text
stringlengths
180
608k
[Question] [ The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa). Example inputs & outputs: ``` Input Output bad bBaAdD Nice NniIcCeE T e S t Tt eE Ss tT s E t sS Ee tT 1!1!1st! 1!1!1sStT! n00b nN00bB (e.g.) (eE.gG.) H3l|@! Hh3lL|@! ``` The input consists of printable ASCII symbols. *You shouldn't duplicate non-latin letters, numbers, special chars.* [Answer] # Python, ~~56~~ 54 bytes ``` lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s) ``` Test it on [Ideone](http://ideone.com/fj1Ge9). [Answer] # JavaScript ES6, ~~70~~ ~~68~~ ~~66~~ 64 bytes *Saved 2 bytes thanks to [@Kevin Lau - not Kenny](https://codegolf.stackexchange.com/users/52194/kevin-lau-not-kenny)* *Saved 2 bytes thanks to [@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)* ``` s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]()) ``` ## Explanation This uses a really hacky: ``` l[`to${l<"a"?"Low":"Upp"}erCase`]() ``` which ungolfed is: ``` l[`to${ l < "a" ? "Low" : "Upp" }erCase`]() ``` Basically `l < "a"` checks if the code point of the letter is less then the code point of `a` (therefore being an uppercase letter). If it is it'll do `to + Low + erCase` which becomed `l['toLowerCase']()` and makes the character lowercase. ``` quotes allow string formatting so essentially you can think of: ``` `to${l < "a" ?"Low" : "Upp"}erCase` ``` as: `"to" + (l<"a" ? "Low" : "Upp") + "erCase"` which generates the function to call (make the string upper or lower case). We put this in square brackets `[ ... ]` which lets us access a property given its name as a string. This returns the appropriate function and then we just call it. [Answer] # Jelly, 5 bytes ``` żŒsQ€ ``` [Try it online!](http://jelly.tryitonline.net/#code=xbzFknNR4oKs&input=&args=J1QgZSBTIHQn) ### How it works ``` żŒsQ€ Main link. Argument: s (string) Œs Yield s with swapped case. ż Zip s with the result. Q€ Unique each; deduplicate each pair of characters. ``` [Answer] # Ruby, ~~37~~ 33 (30 + `-p` flag) bytes `swapcase` to the rescue! Sort of. -4 bytes from @Lynn. ``` gsub(/[a-z]/i){$&+$&.swapcase} ``` [Answer] # C, ~~63~~ 60 bytes ``` f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);} ``` Uses the fact that `'a' XOR 32 == 'A'`, etc. Three bytes saved thanks to FryAmTheEggman. [Answer] ## CJam, 11 bytes ``` l_el_eu.+.| ``` [Test it here.](http://cjam.aditsu.net/#code=l_el_eu.%2B.%7C&input=Ba%20d1!zzz) ### Explanation ``` l e# Read input. _el e# Duplicate, convert to lower case. _eu e# Duplicate, convert to upper case. .+ e# Concatenate the two characters in matching positions from those two e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"]. e# For each character from the original string and the corresponding .| e# string from this list, take the set union (which eliminates duplicates e# and keeps the order the values appear in from left to right, so that e# the original case of each letter comes first). ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` sm{+dr2 ``` [Test suite](http://pyth.herokuapp.com/?code=sm%7B%2Bdr2&test_suite=1&test_suite_input=%22bad%22%0A%22Nice%22%0A%22T+e+S+t%22%0A%22s+E+t%22&debug=0). ``` sm{+dr2 input: Q sm{+dr2dQ implicit arguments Q input m for each character as d: r2d swapcase +d prepend d { deduplicate s join as string ``` [Answer] # Python 3.5, ~~60~~ 56 bytes: ``` for i in input():print(end=i+i.swapcase()[:i.isalpha()]) ``` A full program. Will try to golf more. [Try It Online! (Ideone)](http://ideone.com/5j1h7y) [Answer] # Haskell, 73 bytes ``` l=['a'..'z'] u=['A'..] (>>= \c->c:maybe""pure(lookup c$zip l u++zip u l)) ``` [Answer] # [Cheddar](http://cheddar.vihan.org), ~~118~~ 104 bytes ``` (s)->s.chars.map((i)->{if String.letters has i.lower{if i<"a"{i+i.lower}else{i+i.upper}}else{i}}).join() ``` First real Cheddar answer!!! This is a lot less climactic than I thought it would be... ;\_; Works with release [1.0.0-beta.9](https://github.com/cheddar-lang/Cheddar/releases/tag/v1.0.0-beta.9), non-competing. --- As you can tell I didn't design cheddar to be golfy :/ Ungolfed: ``` (str) -> str.chars.map( (i) -> { if String.letters has i { if i < "a" { // Check char code, meaning it's upper case if true i+i.lower } else { i+i.upper } } else { i } } ).join() ``` Usage: ``` var doThing = <code here>; doThing("input..."); ``` --- **Update:** 7/14/16 I've finished ternaries making this come down to 84 bytes ## Cheddar, 84 bytes ``` (s)->s.chars.map((i)->String.letters has i.lower?i<"a"?i+i.lower:i+i.upper:i).join() ``` works as of version [v1.0.0-beta.14](https://github.com/cheddar-lang/Cheddar/releases/tag/v1.0.0-beta.14) [Answer] # Retina, ~~28~~ ~~27~~ 21 bytes Those are tabs, not spaces. ``` . $& $& T`lL p`Ll_` . ``` [**Try it online**](http://retina.tryitonline.net/#code=LgokJgkkJgpUYGxMCXBgTGxfYAku&input=YmFkCk5pY2UKVCBlIFMgdApzIEUgdAoxITEhMXN0IQpuMDBiIAooZS5nLikKSDNsfEAh) Thanks for the suggestions everyone. [Answer] # C, ~~87~~ 80 Pass a string as input to `f()` and the output is written to STDOUT. The string is not modified. ``` f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;} ``` [Answer] # sed, 30 bytes 29 bytes code + 1 byte parameter `-r` ``` s/([a-z])|([A-Z])/&\u\1\l\2/g ``` Usage: ``` echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\ sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g' ``` [Answer] # J, ~~31~~ 29 bytes ``` [:;]<@~."1@,.tolower,.toupper ``` ## Explanation ``` [:;]<@~."1@,.tolower,.toupper Input: s toupper Convert s to all uppercase tolower Convert s to all lowercase ,. Join them as columns in a 2d array ] Identity function, get s ,. Prepend s as a column to the 2d array ~."1@ Take the unique chars on each row <@ Box them [:; Unbox the list of boxes and join their contents and return ``` [Answer] # Haskell, ~~121, 101, 85,~~ 82 ``` import Data.Char g n|isLower n=toUpper n|1<2=toLower n (>>= \x->x:[g x|isAlpha x]) ``` [Answer] ## Perl, 36 bytes (35 + `-n` flag) ``` s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige ``` (`-p` tag needed) (-2 bytes thanks to @Dom Hasting) Short explanation: `ord` returns the numeric value of a char. `ord(any lower case) >= 97`, and `ord(any upper case) <= 90)`. Run with : ``` perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige' ``` [Answer] # Ruby, ~~31+1=32~~ 30+1=31 bytes With the `-p` flag, run ``` gsub(/(?<=(.))/){$1.swapcase!} ``` Takes advantage of the fact that `swapcase!` will return `nil` on anything but an ASCII letter, which translates to an empty string when returned out of the `gsub` block. @Jordan saved a byte by capturing the previous character in a look-behind. [Answer] # R, 191 187 ~~168~~ ~~156~~ ~~98~~ 99 bytes 99 bytes due to improvements fro [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and [MickyT](https://codegolf.stackexchange.com/users/31347/mickyt). ``` paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="") ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Code: ``` vyyš«Ù? ``` Explanation: ``` v # For each in input. yyš # Push y and y swapcased. «Ù # Concatentate and uniquify. ? # Print without a newline. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=dnl5xaHCq8OZPw&input=TiBpIEMgZQ) [Answer] ## Pyke, ~~8~~ 6 bytes ``` FDl4+} ``` [Try it here!](http://pyke.catbus.co.uk/?code=FDl4%2B%7D&input=%28e.g.%29) [Answer] # [V](https://github.com/DJMcMayhem/V), 21 bytes [Try it online!](http://v.tryitonline.net/#code=w5MuL8Kww7IKw43DoS_CsMKwCsOObGd-bMOOSMOyZ0o&input=SDNsfEAh) Too many bytes... ``` Ó./°ò Íá/°° Îlg~lÎHògJ ``` [Answer] ## Actually, 8 bytes ``` `;Öo╔`MΣ ``` [Try it online!](http://actually.tryitonline.net/#code=YDvDlm_ilZRgTc6j&input=IkgzbHxAISI) Explanation: ``` `;Öo╔`MΣ `;Öo╔`M for each character in input: ; duplicate the character Ö swap case o append to original character ╔ remove duplicated characters Σ concatenate ``` [Answer] # MATL, ~~11~~ 9 bytes ``` tYov"@uv! ``` [**Try it Online**](http://matl.tryitonline.net/#code=dFlvdiJAdXYh&input=J0gzbHxAISc) **Explanation** ``` % Implicitly grab input as string t % Duplicate the input Yo % Swap case of all characters v % Vertically concatenate the original and swap-cased versions " % For each column (letter in the original) @u % Compute the unique values (without sorting) v! % Vertically concatenate with the existing output and transpose % Implicit end of for loop and implicit display ``` [Answer] ## Common Lisp (Lispworks), 262 bytes ``` (defun f(s)(let((b""))(dotimes(i(length s))(if(lower-case-p(elt s i))(progn #1=(setf b(concatenate 'string b(string #2=(elt s i))))(setf b(concatenate 'string b(string(char-upcase #2#)))))(progn #1#(setf b(concatenate 'string b(string(char-downcase #2#)))))))b)) ``` ungolfed: ``` (defun f (s) (let ((b "")) (dotimes (i (length s)) (if (lower-case-p (elt s i)) (progn #1=(setf b (concatenate 'string b (string #2=(elt s i)))) (setf b (concatenate 'string b (string (char-upcase #2#))))) (progn #1# (setf b (concatenate 'string b (string (char-downcase #2#))))))) b)) ``` Usage: ``` CL-USER 1 > (f "abc") "aAbBcC" CL-USER 2 > (f "bad") "bBaAdD" ``` [Answer] ## Perl, ~~28~~ ~~22~~ 21 bytes (20 + `-p` flag) ``` s/[a-z]/$&.$&^$"/ige ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~7~~ 6 bytes Thanks to @recursive for a byte saved! ``` ┤§ÆP♦■ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#c=c%3A~%5C%7Bum&i=%22bad%22%0A%0A%22Nice%22%0A%0A%22T+e+S+t%22%0A%0A%22s+E+t%22%0A%0A%221%211%211st%21%22%0A%0A%22n00b+%22+%0A++%0A%22%28e.g.%29%22%0A%0A%22H3l%7C%40%21%22%0A%0A%22123%22%0A&a=1&m=1) (link is to unpacked version) ### Unpacked (7 bytes): ``` c:~\{um ``` ### Explanation: ``` c:~\{um c Copy the top element of the stack (the input, in this case). :~ Switch case of each letter in the copy. \ Zip. This produces an array of two-character strings. { m Map a block over this array of two-character strings. u Get all unique elements. Implicit concatenate and print. ``` [Answer] ## Python, 59 bytes ``` lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s) ``` Edited to fix repeating non-alphabetic characters [Answer] # Julia, 40 bytes ``` !s=[print(c,isalpha(c)?c$' ':"")for c=s] ``` [Try it online!](http://julia.tryitonline.net/#code=IXM9W3ByaW50KGMsaXNhbHBoYShjKT9jJCcgJzoiIilmb3IgYz1zXQoKZm9yIHMgaW4gKCJiYWQiLCAiTmljZSIsICJUIGUgUyB0IiwgInMgRSB0IiwgIjEhMSExc3QhIiwgIm4wMGIiLCAiKGUuZy4pIiwgIkgzbHxAISIpCiAgICBAcHJpbnRmKCIlLTExcyIscykKICAgICFzCiAgICBwcmludGxuKCkKZW5k&input=) [Answer] # PHP 4.1, 57 bytes This code assumes access through a web server (Apache, for example), using the default configuration. You can pass the string by sending the key `S` by any means (`POST`, `GET`, `COOKIE`, `SESSION`...). ``` <?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':''; ``` [Answer] # C#, ~~82~~ 71 bytes ``` s=>string.Concat(s.Select(c=>c+(char.IsLetter(c)?(char)(c^32)+"":""))); ``` C# lambda where the input and the output are `string`. [Try it online](https://dotnetfiddle.net/Gti6h7). 11 bytes thanks to @Lynn trick. ]
[Question] [ **This is the cops' thread. The robbers' thread goes [here](https://codegolf.stackexchange.com/questions/77420/find-the-program-that-prints-this-integer-sequence-robber-thread).** The last [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") thread was already [4 months ago](https://codegolf.stackexchange.com/questions/67756/printing-ascending-ascii-cops). ## The cop's task * The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer. * **The cop must state it if the program is intolerant towards zero.** * The cop will provide at least **2** sample inputs/outputs. * For example, if I have decided to write the [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number), I would write this in my answer: ``` a(0) returns 0 a(3) returns 2 ``` * The number of examples is up to the cop's discretion. * However, the sequence must actually exist in [the On-Line Encyclopedia of Integer Sequences®](http://oeis.org/), so no pseudo-random number generator for you. `:(` * **The cop can hide as many characters as is so wished.** * For example, if my program is: --- ``` function a(n) if n>2 then return n else return a(n-1) + a(n-2) end end ``` --- * Then I would hide these characters as I want: --- ``` function a(n) if ### then ######## else ###################### end end ``` --- ## The robber's task * is obviously to find the original source code. * **However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.** --- ## Tips for the cops * ~~The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.~~ * Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence. --- Your score is the number of bytes in your code. The winner will be the submission with the lowest score that hasn't been cracked in 7 days. Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win. In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days). Your post should be formatted like this (NN is the number of characters): --- # Lua, 98 bytes Output: ``` a(0) returns 0 a(3) returns 2 ``` Code (`#` marks unrevealed characters): ``` function a(n) if ### then ######## else ###################### end end ``` --- If the code is cracked, insert `[Cracked](link to cracker)` in the header. If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win. [Answer] # Vim, 36 keystrokes -- Safe! ``` i****<esc>:let @q="^*i****$**@***"<cr><n>@qbD ``` (Note: `<n>` is where you type your input) Here is the code unrelated to number generation: ``` :let @q=" "<cr><n>@qbD ``` Meaning I am revealing 5 out of 19 characters. `<n>` is the input. Here are some sample outputs: ``` 1@q: 1 2@q: 3 6@q: 18 ``` # Answer This code prints The Lucas Numbers ([A000032](https://oeis.org/A000032)), which are just like The Fibonnaci Sequence, except that it starts on `2, 1` instead of `1, 1`. Here are the first 15 numbers: ``` 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843 ``` Here's the revealed code: ``` i2 1 <esc>:let @q="^diwwyw$pb@-<c-v><c-a>"<cr><n>@qbD ``` Explanation: ``` i2 1 <esc> "Insert the starting numbers :let @q="....."<cr> "Define the macro 'Q' ``` Explanation of the macro: ``` ^ "Move to the first non-whitespace character on the line. diw "(d)elete (i)nner (w)ord. This is different then 'dw' because it doesn't grab the space. "It also throws people off since 'i' is usually used for inserting text. wyw$ "Move to the next number, yank it then move to the end of the line pb "(p)aste the yanked text and move (b)ack @- <c-a> "@- is the register holding the word we deleted. Increment the current number that many times. <c-v> "Since we're adding <c-a> this from the command line, we need to type it as a literal. ``` Now, we just need to remove the second number, since the first number is the lucas number we want. So we do ``` b "move (b)ack D "(D)elete to the end of the line. ``` Also, if I'm not mistaken, this is the first safe submission! That's kinda cool. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes, safe Last one for today :p. Output: ``` a(0) = 9 a(5) = 4 a(10) = 89 ``` Code: ``` ___m_ ``` Obfuscated characters are indicated with `_`. [Try it online!](http://05ab1e.tryitonline.net/)-link. Uses **CP-1252** encoding. --- ### Solution: ``` žhžm‡ ``` Explanation: ``` žh # Short for [0-9]. žm # Short for [9-0]. ‡ # Translate. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xb5oxb5t4oCh&input=MA) or [Try for all test cases!](http://05ab1e.tryitonline.net/#code=W0nFvUQiYSjDvykgPSAic8W-aMW-beKAocKrLA&input=MAo1CjEw). [Answer] # [Element](https://github.com/PhiNotPi/Element), 7 bytes, [cracked](https://codegolf.stackexchange.com/a/77439/48934) Output: ``` a(3) = 111 a(7) = 1111111 ``` The `#` are hidden characters, and they are all printable ASCII. I think this one is actually reasonably difficult (for only having 5 missing characters). ``` ###,##} ``` For convenience, here's the [Try It Online](http://element.tryitonline.net/) and [Esolang wiki](https://esolangs.org/wiki/element) pages. --- My original program was: > > `_'[,$`}` > > > The trick is that > > `]` and `}` are functionally identical (both translate to `}` in Perl). Also, I used `,$` to produce a `1` as an additional layer of confusion, although it is possible to ignore the `,` completely by doing `,1` instead. > > > [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 5 bytes, [cracked](https://codegolf.stackexchange.com/a/77422/31957) Output: ``` a(2) = 8 a(10) = 4738245926336 ``` All of it is crucial, and I have shown 1 of 5. ``` ####x ``` Original code: ``` mPm$x mP cube m$ catalan number x input ``` [Try it online!](http://conorobrien-foxx.github.io/Jolf/#code=bVBtJHg&input=MTA) [Answer] # JavaScript (ES7), 10 bytes, [Cracked](https://codegolf.stackexchange.com/a/77756/46855) ### Output ``` f(0) -> 1 f(1) -> -1 ``` ### Code ``` t=>~t##**# ``` **Test it in Firefox nightly.** The code is an anonymous function. This will probably be easy since there's only three characters hidden, but at least it's short! :P --- My original code was: > > `t=>~top**t` > > > but after brute-forcing my own code for a solution, I soon realised > > `t=>~t.x**t` (where `x` can be any variable name character) > > > could also be used. This works because > > in the original ES7 exponentiation operator spec, the operator had lower precedence than unary operators (unlike conventional mathematics and most other languages). `~` performs a bitwise NOT on `t.x` (`undefined`) or `top` (`Object`) which casts them to a 32-bit signed integer (uncastables like these become `0`) before doing the NOT (so `0` becomes `-1`). I looked into further into this, and very recently, the spec has changed to disallow ambiguous references like this (not good for future golfing D: ), however most ES7 engines haven't updated to the latest version of the spec yet. > > > [Answer] ## 05AB1E, 4 bytes ([Cracked](https://codegolf.stackexchange.com/a/77447/34388)) Sample output : ``` a(5) = 51 a(8) = 257 ``` And for the code : ``` ###^ ``` I revealed the last one. Should be easy enough though, I had quite a hard time finding a sequence :( All hidden characters are printable. [Answer] # [MATL](http://matl.tryitonline.net), 5 bytes, [cracked](https://codegolf.stackexchange.com/a/77479/36398) Hidden characters are indicated by `%`. ``` %5%*% ``` Output: ``` a(1) = 3 a(2) = 6 a(4) = 12 ``` Input `0` is valid. --- Original code: ``` 35B*s ``` that is, ``` 35 % push number 35 B % convert to binary: array [1 0 0 0 1 1] * % multiply element-wise by implicit input n: gives [n 0 0 0 n n] s % sum of array: gives 3*n ``` [Answer] # SWIFT, 55 bytes, [Cracked](https://codegolf.stackexchange.com/questions/77420/find-the-program-that-prints-this-integer-sequence-robbers-thread/77765#77765) ``` func M(n:Int)->Int{ return(n*****) ?M(**n****):n***; } ``` `*` marks a hidden character Output: ``` M(30) -> 91 M(60) -> 91 M(90) -> 91 M(120)-> 110 M(150)-> 140 ``` Function accepts `0` [Answer] # Ruby, 46 bytes, safe Edit to add disclaimer/apology: This sequence starts with f[0], while the OEIS entry starts with f[1]. The values are the same. Obfuscated code (`#` is any character): ``` ->####or x##1###(#..##0#);x*=3;end;#.###ect:+} ``` Call like ``` ->####or x##1###(#..##0#);x*=3;end;#.###ect:+}[3] (returns 39) ``` Output: ``` f[0] = 0 f[1] = 3 f[2] = 12 f[3] = 39 f[4] = 120 f[5] = 363 f[6] = 1092 f[7] = 3279 f[8] = 9840 f[9] = 29523 ``` Solution: > > `f=->*x{for x[-1]in(0..x[0]);x*=3;end;x.inject:+}` > > > Sequence: > > <http://oeis.org/A029858> > > > Explanation: > > The minor trick here is that we declare the parameter as `*x` rather than `x`. This means that if you pass in `2`, `x` is set to `[2]`...at first. The *major* trick exploits bizarre, and justly obscure, Ruby syntax where you can set the iterator in a for loop to any valid left hand side of an assignment expression, instead of an iterator variable like `i`. So this loops through from 0 to (in this example) 2, assigning each number to `x[-1]`, meaning it overwrites the last value of x. Then the loop body `x*=3`, further mutates x by concatenating it to itself 3 times. So first x becomes `[0]`, then `[0,0,0]`. On the next loop it becomes `[0,0,1]`, then `[0,0,1,0,0,1,0,0,1]`. Finally we pass in 2 and it becomes `[0,0,1,0,0,1,0,0,2]`, then `[0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 2]`. We then sum the result using the `inject` method, which reduces the array by applying `+` (the passed in method) to each element in turn. If we consider how each iteration changes the sum, we see that we effectively add 1 (by overwriting the last element with an element one higher), then multiply by 3. Since `3*(n+1) = 3*n + 3`, this implements Alexandre Wajnberg's recurrence relation for the sequence as described on the page. > > > [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes, [cracked](https://codegolf.stackexchange.com/a/77444/48934) Output: ``` a(9) = 165 a(10) = 220 ``` Hidden code: ``` ##O ``` [Try it online](http://05ab1e.tryitonline.net/#code=IyNP&input=NQ) might come in handy. [Answer] # [Hexagony](http://github.com/mbuettner/hexagony), 7 bytes, [cracked](https://codegolf.stackexchange.com/a/77446/34388) Output: ``` a(1) = 2 a(2) = 4 ``` Hidden code: ``` ?#####@ ``` Or alternatively: ``` ? # # # # # @ ``` [Try it online](http://hexagony.tryitonline.net/) might come in handy. [Answer] # PHP, 41 bytes, [cracked](https://codegolf.stackexchange.com/a/77466/41859) Yeah, finally another Cops and Robbers challenge. Hope I didn't make it to easy. **Output** ``` a(5) = 0 a(15) = 1 a(35) = 0 a(36) = 1 a(45) = 1 ``` **Source** ``` ____________________$argv[1]____________; #################### ############ ``` **Notes** * It's a full program, not a function. * Reads the input from command line (obviously). * [Does not contain any PHP opening tag](http://meta.codegolf.stackexchange.com/questions/7098/is-the-php-opening-tag-mandatory-in-byte-count). --- **Cracked** I obviously made it to easy and provided not enough examples. The sequence I had in mind was [A010054](https://oeis.org/A010054): > > a(n) = 1 if n is a triangular number else 0. > > > Here's my original source code: > > `echo(int)($r=sqrt(8*$argv[1]+1))==$r?1:0;` > > > It tests whether the input is a *triangular number* and outputs `1` or `0` accordingly. [Answer] # Jolf, 11 bytes, [Cracked](https://codegolf.stackexchange.com/questions/77420/find-the-program-that-prints-this-integer-sequence-robbers-thread/77491#77491) , [A011551](https://oeis.org/A011551) ``` c*______x__ c*mf^+91x~P ``` Original code: ``` c*^c"10"x~P ``` Examples: ``` 0 -> 1 12 -> 1618033988749 ``` [Answer] # MATL, 9 bytes, [Cracked](https://codegolf.stackexchange.com/a/77494/42892) Code: ``` 3#2###*## ``` Output: ``` a(1) = 3 a(2) = 6 a(4) = 12 a(12) = 37 ``` `a(0)` is valid. --- ### Cracked Original sequence: [A059563](https://oeis.org/A059563) Original code: ``` 3L2^Ze*sk 3L % Push [1 -1j] from the clipboard 2^ % square Ze % exp * % times input s % sum k % floor ``` [Answer] # Java, 479 bytes, [Cracked](https://codegolf.stackexchange.com/a/77497/41505) Outputs: ``` a(10) = 81 a(20) = 35890 ``` (Inputs are provided via command line arguments) Code (`#` marks hidden characters): ``` import java.util.*; public class A{ public static int######### public boolean########### static A a = new A(); public static void main(String[] args){ int input = Integer.parseInt(args[0]); LinkedList<Integer> l = new LinkedList<>(); l.add(1); l.add(0); l.add(0); for(int ix = 0; ################if(##>##{ ###########d# #######+##p##########+##########(####### } System.out.println(######################### ###(A.#############(#5#####))); } } ``` The program starts at index 0. (Note that SE replaces all of the `\t` indents with 4 spaces, bringing the byte total to 569. Click [here](https://goo.gl/4yS0Ff) to see the program with `\t` indents instead of space indents.) Original code: ``` import java.util.*; public class A{ public static interface B{ public boolean C(int i);} static A a = new A(); public static void main(String[] args){ int input = Integer.parseInt(args[0]); LinkedList<Integer> l = new LinkedList<>(); l.add(1); l.add(0); l.add(0); for(int ix = 0; ix<input; ix++)cif(i-> { return l.add( l.pop()+l.peekFirst()+l.peekLast());});{ } System.out.println(l.get(1));}static boolean cif(A.B b5){return (b5.C((0))); } } ``` (Same code, but formatted normally): ``` import java.util.*; public class A { public static interface B { //functional interface for lambda expression public boolean C(int i); //void would have given it away } static A a = new A(); //distraction public static void main(String[] args) { int input = Integer.parseInt(args[0]);//Input LinkedList<Integer> l = new LinkedList<>(); l.add(1);//Set up list l.add(0); l.add(0); for (int ix = 0; ix < input; ix++) cif(i -> { //Fake if statement is really a lambda expression return l.add(l.pop() + l.peekFirst() + l.peekLast()); }); { //Distraction } System.out.println(l.get(1));//Output } static boolean cif(A.B b5) { //Used to pass in lambda expression. //The A. and b5 were both distractions return (b5.C((0))); } } ``` [Answer] # Octave, 34 bytes, [cracked](https://codegolf.stackexchange.com/a/77532/31516) ``` @(m)(m###m#####m##)&isprime(#)#### ``` Outputs: ``` ans(1) = 0 ans(6) = 5 ans(7) = 10 ans(8) = 15 ``` The sequence starts at `ans(1)` in OEIS. [Answer] # C, 71 bytes [cracked](https://codegolf.stackexchange.com/a/77549/52554) ``` ############ ##### main(){ scanf("%d",##); ###6#; printf("%d",##); } ``` Output: ``` a(1) = 0 a(2) = 0 a(5) = 1 a(6) = 1 a(7) = 1 a(9) = 2 ``` This works with gcc, and is a full program. It accepts 0 as input. [Answer] ## Pyth, 70 bytes, [Cracked](https://codegolf.stackexchange.com/a/77530/34388) ``` DhbI|qb"#"qb"#"R!1Iqb"#"#####+""s####2###;##lY+Q1Ih+""Z#####)=Z+Z1;@YQ ``` `#` are the hidden characters Has been cracked, so here is the versionn without hidden chars : ``` DhbI|qb"4"qb"0"R!1Iqb"1"R!0Rh+""sm^sd2cb1;W<lY+Q1Ih+""Z=Y+YZ)=Z+Z1;@YQ ``` Sample outputs : ``` a(2) -> 10 a(4) -> 19 ``` ~~Good luck to find this on OEIS, I personally failed to find it from those examples (even tho the sequence is quite easy to spot.)~~ [Answer] # Ruby, 38 bytes, [cracked](https://codegolf.stackexchange.com/a/77621/6828) Obfuscated code (`#` can be any character): ``` ->#{(s=#########).sum==#3333&&eval(s)} ``` Output: Multiplies the input by 10 (A008592). Works for any integer, including 0. e.g. ``` ->#{(s=#########).sum==#3333&&eval(s)}[3] => 30 ->#{(s=#########).sum==#3333&&eval(s)}[10] => 100 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes, [cracked](https://codegolf.stackexchange.com/a/77680/34388) Output: ``` a(0) = 0 a(1) = 0 a(2) = 1 a(3) = 1 a(4) = 1 a(5) = 1 a(6) = 1 a(7) = 1 a(8) = 1 a(9) = 1 a(10) = 0 a(11) = 0 ``` Obfuscated code: ``` _____ ``` [Try it online!](http://05ab1e.tryitonline.net/)-link. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes, [cracked](https://codegolf.stackexchange.com/a/77708/34388) Well then, I think I'm addicted to CnR's... Obfuscated code (`_` indicates a wild card): ``` ____ ``` Sequence: ``` a(1) = 2 a(4) = 6720 ``` The sequence in **OEIS** starts at a(1) = 2. [Try it online!](http://05ab1e.tryitonline.net/)-link [Answer] ## Lua, 45 Bytes, [Cracked](https://codegolf.stackexchange.com/a/77763/41019) A small hint: ``` a(0) will make the program crash :) ``` ### Output ``` a(1)=>0 a(2)=>1 ``` ### Code Uses `#` to hide the code :). ``` a=function(n)#####n###### and #or ########end ``` I was using the OEIS [A007814](http://oeis.org/A007814), with the following code: ``` a=function(n)return n%2>0 and 0or 1+a(n/2)end ``` [Answer] ## [Pyke](http://pyke.catbus.co.uk), 15 bytes, SAFE Output ``` a(2) = 21 a(15) = 17 ``` Revealed code: ``` #R#D######+##)# ``` Solution: > > OEIS [A038822](https://oeis.org/A038822) > > > `wR}DSR_Q*L+#P)l` > > > I used a couple of red herrings here by using `wR}` to generate the number 100 and revealing the character `R` which is normally used to rotate the stack. I also used `#P)l` instead of the more simple `mPs` to count the number of primes in the sequence. > > > [Answer] # C, 82 bytes, safe ``` ####=############ main(i){scanf("%d",##); for(i=1;i++/4<#;)##=2; printf("%d",##);} ``` Works with gcc, and it is a full program, which reads its input from stdin and prints its output to stdout. Here the sequence is ~~A004526, floor(n/2)~~. ``` a(0) = 0 a(1) = 0 a(2) = 1 a(3) = 1 a(4) = 2 a(5) = 2 a(6) = 3 a(7) = 3 a(8) = 4 ``` **Solution:** ``` a;*b=(char*)&a+1; main(i){scanf("%d",&a); for(i=1;i++/4<2;)a*=2; printf("%d",*b);} ``` This works only on little endian machines, and only if the size of `char` is 1 byte. And only if the byte higher than the highest order byte of `a` has value 0. I think this is true for gcc since by default uninitialized global variables go into the bss segment, and initialized global variables go into the data segment (see <https://stackoverflow.com/questions/8721475/if-a-global-variable-is-initialized-to-0-will-it-go-to-bss>). So only `a` goes into bss (the only other global variable `b` is initialized and thus goes into the data segment). If `a` is not at the end of bss, then the byte higher than the highest order byte of `a` is also in bss and thus has value 0. [Answer] ## 05AB1E, 1 byte, Cracked ``` _ ``` `_` denotes hidden code. ``` f(1) == 1 f(18) == 6 ``` [Answer] # [Element](https://github.com/PhiNotPi/Element), 10 bytes, [cracked](https://codegolf.stackexchange.com/questions/77420/find-the-program-that-prints-this-integer-sequence-robbers-thread/77433#77433) Output: ``` a(3) = 6561 a(4) = 4294967296 ``` There's probably only a few ways to compute this sequence in Element. I found a 9-char solution, but I figured this 10-char solution is actually more difficult. The `#` are hidden characters. ``` #_####@^#` ``` For convenience, here's the [Try It Online](http://element.tryitonline.net/) and [Esolang wiki](https://esolangs.org/wiki/element) pages. --- The original was ``` 2_3:~2@^^` ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes `#` marks unrevealed characters. ``` L?Jtb##5#m##S#2 #y ``` Outputs (starts from `1`): ``` 1 -> 2 2 -> 3 3 -> 5 4 -> 7 ``` [Online interpreter](http://pyth.herokuapp.com/) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes, [cracked](https://codegolf.stackexchange.com/a/77462) I hope that this submission isn't as easy as my other ones :p. Outputs: ``` a(0) = 0 a(1) = 1 a(2) = 6 a(3) = 24 a(4) = 80 a(5) = 240 ``` Obfuscated code: ``` ####O ``` Contains some non-ASCII characters though, uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/) might come in handy :p. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 11 bytes, [Cracked](https://codegolf.stackexchange.com/a/77460/31541). Output: ``` a(10) = 4 a(20) = 6 a(30) = 8 ``` And the partially hidden code: ``` ####xd###x# ``` Hint: > > When I looked through the sequences in order, I didn't go very far before finding this one. > > > The cracked version isn't quite the same as my original code. I'm not currently at my computer, so I don't have it exactly, but it was something like this: > > `l fzxd!m%xH` > > > (The only part I'm unsure about is the `!m`. It's whatever checks if a variable is zero.) [Answer] ## [Pyke](http://pyke.catbus.co.uk), 6 bytes, [Cracked](https://codegolf.stackexchange.com/a/77478/32686) ``` ###X#s ``` Output: ``` a(2) = 8 a(8) = 80 a(10) = 120 ``` This doesn't work with N<1 Original solution: > > `hSmX$s` > > > ]
[Question] [ As a kid my sister showed me this little love calculation to see how much chance you have of getting in a successful relationship with your crush. All you need is 2 names and a piece of paper. * John * Jane Then, you separate these names with the word **Loves**. You can either write this on one line or on new lines. > > John > > Loves > > Jane > > > Then the calculating begins. You start off by counting how many times a character occurs from left to right and in case you use new lines also from top to bottom. Each character is counted once, So after counting the **J** of John you don't have to count them again when you start with Jane. The result of this example will be as follows: > > J: 2 ([J]ohn | [J]ane) > > O: 2 (J[o]hn | L[o]ves) > > H: 1 (Jo[h]n) > > N: 2 (Joh[n] | Ja[n]e) > > \_\_ > > L: 1 ([L]oves) > > O: **skipped** > > V: 1 (Lo[v]es) > > E: 2 (Lov[e]s | Jan[e]) > > S: 1 (Love[s]) > > \_\_ > > J: **skipped** > > A: 1 (J[a]ne) > > N: **skipped** > > E: **skipped** > > \_\_ > > Final result: 2 2 1 2 1 1 2 1 1 > > > The next step will be adding the digits working from the outside to the middle. > > **2** 2 1 2 1 1 2 1 **1** (2+1=3) > > 2 **2** 1 2 1 1 2 **1** 1 (2+1=3) > > 2 2 **1** 2 1 1 **2** 1 1 (1+2=3) > > 2 2 1 **2** 1 **1** 2 1 1 (2+1=3) > > 2 2 1 2 **1** 1 2 1 1 (1) > > \_\_ > > Result: 3 3 3 3 1 > > > You will keep doing this until you have an integer left less or equal to 100. > > **3** *3* 3 *3* **1** > > **4** *6* **3** > > **76%** > > > It can happen that the sum of 2 digits becomes ≥ 10, in this case the number will be split in 2 on the next row. Example: > > **5** 3 1 2 5 4 1 **8** > > 13 (Will be used as 1 3) > > 1 3 4 5 7 > > 8 8 4 (8+4=12 used as 1 2) > > 1 2 8 > > 92% > > > ### Requirements * Your program should be able to accept any name with reasonable length (100 characters) * [A..Z, a..z] characters are allowed. * Case insensitive so A == a ### Free for you to decide * How to handle special characters (Ö, è, etc.) * Include last names yes or no, spaces will be ignored * Any language is allowed. Winner will be determined by votes on the 28th 14th of February. Happy coding P.s. This is the first time I put something up here, if there is any way to improve it feel free to let me know =3 **Edit:** Changed end date to valentines day, thought that would be more appropriate for this challenge :) [Answer] # [Sclipting](http://esolangs.org/wiki/Sclipting) ``` 글⓵닆뭶뉗밃變充梴⓶壹꺃뭩꾠⓶꺐合合替虛終梴⓷縮⓶終併❶뉀大套鈮⓶充銻⓷加⓶鈮⓶終併❶뉀大終깐 ``` Expects the input as two space-separated words (e.g. `John Jane`). It’s case-insensitive, but supports only characters that are not special regex characters (so don’t use `(` or `*` in your name!). It also expects only two words, so if your love interest is “Mary Jane”, you have to put `MaryJane` in one word; otherwise it will evaluate "YourName loves Mary loves Jane". ## Explanation The hardest part was to handle the case of odd number of digits: you have to leave the middle digit alone instead of adding it with itself. I think my solution is interesting. ``` 글⓵닆뭶뉗밃變 | replace space with "loves" 充 | while non-empty... 梴 | get length of string ⓶壹 | get first character of string (let’s say it’s “c”) 꺃뭩꾠⓶꺐合合 | construct the regex “(?i:c)” 替虛終 | replace all matches with empty string 梴 | get new length of that ⓷縮 | subtract the two to get a number ⓶ | move string to front 終 | end while 併 | Put all the numbers accrued on the stack into a single string ❶뉀大 | > 100 套 | while true... 鈮⓶ | chop off the first digit 充 | while non-empty... (false if that digit was the only one!) 銻⓷加 | chop off last digit and add them ⓶鈮⓶ | chop off the first digit again (returns the empty string if the string is empty!) 終 | end while 併 | Put all the numbers (± an empty string ;-) ) on the stack into a single string ❶뉀大 | > 100 終 | end while 깐 | add "%" ``` When you’re left with something ≤ 100, the loop will just end, the answer will be on the stack and therefore output. [Answer] # Ruby ``` f=IO. read( __FILE__) .gsub(/[^ \s]/x,?#);s= $**'loves';s .upcase!;i=1;a =s.chars.uniq. map{|c|s.count(c)};loop{b=''; b<<"#{a.shift.to_i+a.pop.to_i }"while(a.any?);d=b.to_i;a= b.chars;d<101&&abort(d> 50?f:f.gsub(/^.*/){ |s|i=13+i%3;s[\ i...i]=040. chr*3;s })} V ``` Prints a heart if the chance of a relation is over 50% ``` $ ruby ♥.rb sharon john ##### ##### ######### ######### ############ ############ ############## ############## ############################# ############################# ########################### ####################### ################### ############### ########### ####### ### # ``` And prints a broken heart if chances are below 50% :( ``` $ ruby ♥.rb sharon epidemian ##### ##### ######### ######### ############ ############ ############## ############## ############### ############## ############# ################ ############# ############## ############ ########### ######## ########### ####### ######## ###### ##### ## ##### # ## # ``` Frigging John... Anyways, it's case-insensitive and supports polygamous queries (e.g. `ruby ♥.rb Alice Bob Carol Dave`). [Answer] # [Funciton](http://esolangs.org/wiki/Funciton) This program expects the input separated by a space (e.g. `John Jane`). It is case-insensitive **for characters A-Z/a-z;** for any other Unicode character, it will “confuse” two characters that are equal when or’ed with 32 (e.g. `Ā` and `Ġ`, or `?` and `_`). Furthermore, I have no idea what this program will do if the input contains a NUL (`\0`) character, so don’t use that :) Also, since StackExchange adds too much line spacing, **[here is the raw text on pastebin](http://pastebin.com/raw.php?i=myN7ex8f).** Alternatively, run the following code in your browser’s JavaScript console to fix it right here: `$('pre').css('line-height',1)` ``` ╓───╖ ╓───╖ ╓───╖ ╓───╖ ╓───╖ ╓───╖ ║ Ḷ ║┌╢ Ọ ╟┐║ Ṿ ║ ║ Ẹ ║┌╢ Ṛ ╟┐║ Ṣ ╟┐ ╙─┬─╜│╙───╜│╙─┬─╜ ╙─┬─╜│╙─┬─╜│╙─┬─╜│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └───────────┐ │ │ │ │ │ │ │ │ └─────────────┐│ ┌───────┘ │ │ │ │ │ │ └───────────────┐││ │┌─────────┘ │ │ │ │ └─────────────────┐│││ ││┌──────────────┘ │ │ └───────────────────┐││││ │││ ┌───────────┘ └──────────────────┐ │││││ │││ ┌───┴───┐ ┌─────────────────────────────┴─┐ │││││ │││ │ ╔═══╗ │ │ │ ││││└─────────┐ │││ │ ║ 2 ║ │ │ ┌───┐ ┌───┐ │ │││└─────────┐│ │││ │ ║ 1 ║ │ │ ┌┴┐ │ ┌┴┐ │ │ ││└─────────┐││ │││ │ ║ 1 ║ │ │ └┬┘ │ └┬┘ │ │ │└─────────┐│││ ┌────────────────────────┘││ │ ║ 1 ║ │ │ ┌─┴─╖ │ ┌─┴─╖ │ ┌───╖ │ └─────────┐││││ │┌────────────────────────┘│ │ ║ 0 ║ │ │ │ ♯ ║ │ │ ♯ ║ ├─────┤ ℓ ╟───┴─┐ │││││ ││┌────────────────────────┘ │ ║ 6 ║ │ │ ╘═╤═╝ │ ╘═╤═╝ │ ╘═══╝ ┌─┴─╖ │││││ │││ ┌─────┘ ║ 3 ║ │ │ ┌┴┐ │ ┌┴┐ └─────────────┤ · ╟──────┐│││││ │││┌───────────────────┴┐┌───╖ ║ 3 ║ │ │ └┬┘ │ └┬┘ ╘═╤═╝ ││││││ ││││ ┌┴┤ = ╟─╢ 3 ║ │ │ ┌───┘ └───┴─────┐ ┌───┴───┐ ││││││ ││││ ╔════╗ ┌───╖ │ ╘═╤═╝ ║ 1 ║ │ │ │ ╔═══╗ ┌─┴─╖ │ ╔═══╗ │ ││││││ ││││ ║ 37 ╟─┤ ‼ ╟─┘ ┌─┘ ║ 9 ║ │ │ │ ║ 1 ║ ┌───────┤ · ╟─┐ │ ║ 0 ║ │ ││││││ ││││ ╚════╝ ╘═╤═╝ ┌┴┐ ║ 6 ║ │ │ │ ╚═╤═╝ │ ╘═╤═╝ ├─────┘ ╚═╤═╝ │ ││││││ ││││ ┌───╖ ┌───╖ ┌─┴─╖ └┬┘ ║ 3 ║ │ │ │ ┌─┴─╖ │ ╔═══╗ ┌─┴─╖ │ ╔═══╗ ┌─┴─╖ │ ││││││ │││└─┤ Ẹ ╟─┤ Ṿ ╟─┤ ? ╟───┤ ║ 3 ║ │ │ └─┤ ʃ ╟─┘ ║ 1 ╟─┤ ʃ ╟─┘ ║ 1 ╟─┤ ʃ ╟─┘ ││││││ │││ ╘═══╝ ╘═══╝ ╘═╤═╝ ┌┴┐ ║ 7 ║ │ │ ╘═╤═╝ ╚═══╝ ╘═╤═╝ ╚═══╝ ╘═╤═╝ ││││││ │││ │ └┬┘ ╚═══╝ │ │ │ ┌──────────┘ └──────┐ ││││││ │││ ╔═══╗ ┌─┴─╖ ┌───╖ │ │ │ │ ┌─────────╖ ┌───╖ ┌─────────╖ │ ││││││ │││ ║ 3 ╟─┤ > ╟─┤ ℓ ╟───┘ │ │ └─┤ str→int ╟─┤ + ╟─┤ str→int ╟─┘ ││││││ │││ ╚═══╝ ╘═══╝ ╘═══╝ │ │ ╘═════════╝ ╘═╤═╝ ╘═════════╝ ││││││ ││└───────────────────────────────────┐ │ │ ┌────┴────╖ ││││││ │└───────────────────────────────┐ │ │ │ │ int→str ║ ││││││ │ ╔═══╗ │ │ │ │ ┌───╖ ┌───╖ ╘════╤════╝ ││││││ │ ║ 0 ║ │ │ │ └─┤ Ẹ ╟─┤ ‼ ╟──────┘ ││││││ │ ╚═╤═╝ │ │ │ ╘═══╝ ╘═╤═╝ ┌────────────────────┘│││││ │ ╔═══╗ ┌─┴─╖ │ │ │ ┌─┴─╖ ┌─┴─╖ ╔═══╗ │││││ │ ║ 1 ╟─┤ ʃ ╟─────────────────┴┐ │ └─────────────┤ ? ╟─┤ ≤ ║ ║ 2 ║ │││││ │ ╚═══╝ ╘═╤═╝ │ │ ╘═╤═╝ ╘═╤═╝ ╚═╤═╝ │││││ │ ┌─┴─╖ │ │ │ └─────┘ │││││ │ ┌─┤ Ṣ ╟──────────────────┴┐ │ ╔═══╗ ┌────────────────────────────────┘││││ │ │ ╘═╤═╝ │ │ ║ ║ │ ┌──────────────────────────────┘│││ │ │ ┌─┴─╖ │ │ ╚═╤═╝ │ │ ┌──────────────────────────┘││ │ └─┤ · ╟─────────────┐ │ │ ┌─┴─╖ │┌─┴─╖┌─┴─╖ ││ │ ╘═╤═╝ │ │ │ │ Ḷ ║ └┤ · ╟┤ · ╟┐ ││ │ ┌─────┴───╖ ┌─┴─╖ ┌─┴─╖│ ╘═╤═╝ ╘═╤═╝╘═╤═╝│ ││ │ │ int→str ║ ┌───────┤ · ╟─┤ · ╟┴┐ │ ┌─┴─╖ │ │ ││ │ ╘═════╤═══╝ │ ╘═╤═╝ ╘═╤═╝ │ ┌┤ · ╟──┘ │ ││ │ │ ┌─┴─╖ ┌───╖ │ │ │ ┌─┘╘═╤═╝ ┌─┴─╖ ││ │ │ │ ‼ ╟─┤ Ọ ╟─┘ │ │ │ ┌──┴─────┤ · ╟───────┐ ││ │ │ ╘═╤═╝ ╘═╤═╝ │ │ │ │ ╔════╗ ╘═╤═╝ ╔═══╗ │ ││ │ └─────┘ │ │ │ │ │ ║ 21 ║ │ ║ 2 ║ │ ││ │ ┌───╖ ┌─┴─╖ │ │ ┌──────┘ │ ╚═══╤╝ │ ║ 0 ║ │ ││ │ ┌───┤ Ṿ ╟─┤ ? ╟───────┘ │ │┌───╖ ┌─┴─╖ ┌─┴──╖ │ ║ 9 ║ │ ││ │ │ ╘═══╝ ╘═╤═╝ │ ┌┴┤ ♯ ╟─┤ Ṛ ╟─┤ >> ║ │ ║ 7 ║ │ ││ │ │ │ │ │ ╘═══╝ ╘═╤═╝ ╘══╤═╝ │ ║ 1 ║ │ ││ │ └─────────┐ ┌───────────┘ │ ╔═══╗ ┌─┴─╖ ├───┴─┬─╢ 5 ║ │ ││ └───────────────────┐ └───┘ │ ║ 0 ╟─┤ ? ╟────┘ │ ║ 1 ║ │ ││ ╔════╗ │ │ ╚═══╝ ╘═╤═╝ ┌──────┤ ╚═══╝ │ ││ ║ 21 ║ │ │ ┌─┴─╖ ┌─┴─╖ ╔══╧══╗ │ ││ ╚═╤══╝ │ └───────┤ ? ╟─┤ ≠ ║ ║ −33 ║ │ ││ ┌─┴─╖ ┌────╖ │ ╘═╤═╝ ╘═╤═╝ ╚══╤══╝ ┌┴┐ ││ │ × ╟─┤ >> ╟────────┴────────────┐ │ └──────┤ └┬┘ ││ ╘═╤═╝ ╘═╤══╝ ┌───╖ ╔═════════╗ │ └───────┘ ││ ┌─┴─╖ └────┤ ‼ ╟───╢ 2224424 ║ │ ┌────────────────────────────────────┘│ │ ♯ ║ ╘═╤═╝ ║ 4396520 ║ │ │ ┌────────────────────────────────┘ ╘═╤═╝ ┌─┴─╖ ║ 1237351 ║ │ │ │ ┌─────────────────────┐ └──────────┤ · ╟─┐ ║ 2814700 ║ │ │ ┌─┴─╖ │ ┌─────┐ │ ╘═╤═╝ │ ╚═════════╝ │ ┌─┴──┤ · ╟──┤ │ ┌┴┐ │ ╔═══╗ ┌───╖ ┌─┴─╖ │ ╔════╗ │ ┌─┴─╖ ╘═╤═╝┌─┴─╖ │ └┬┘ │ ║ 0 ╟─┤ Ọ ╟─┤ ‼ ║ │ ║ 32 ║ │ ┌────────┤ · ╟────┴──┤ Ṛ ╟───┤ ┌─┴─╖ │ ╚═══╝ ╘═╤═╝ ╘═╤═╝ │ ╚═╤══╝ │ │ ╘═╤═╝ ╘═╤═╝ │ │ ♯ ║ │ │ ┌─┴─╖ ├─┐ ┌─┴─╖ │ ┌─┴─╖ ┌─┴─╖ ╔═╧═╗ │ ╘═╤═╝ │ ┌─┤ ʃ ╟─┘ └─┤ ʘ ║ │┌┤ · ╟──────┤ · ╟───┐ ║ 1 ║ │ ┌┴┐ │ │ ╘═╤═╝ ╘═╤═╝ ││╘═╤═╝ ╘═╤═╝ │ ╚═══╝ │ └┬┘ │ │ ╔═╧═╗ ├───────┘│ │ ┌──┴─╖ ┌─┴─╖ ┌───╖ ┌─┴─╖ ┌─┴─╖ ╔═══╗ │ │ ║ 0 ║ │ │ │ │ >> ╟─┤ Ṣ ╟─┤ ‼ ╟─┤ · ╟─┤ ʃ ╟─╢ 0 ║ │ │ ╚═══╝ │ │ │ ╘══╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╚═══╝ │ └─────────────┘ │ │ ╔════╗ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┘ ├─────────┘ │ │ ║ 21 ╟─┤ × ╟─┤ · ╟─┤ · ╟─┴─┐ │ │ │ ╚════╝ ╘═══╝ ╘═╤═╝ ╘═╤═╝ │ │ │ └────────────────┘ ┌─┴─╖ │ │ │ ┌───┤ ? ╟───┴┐ │ │ │ ╘═╤═╝ │ │ │ ┌───╖ ┌─┴─╖ │ ┌─┴─╖ │ └───────────┤ ♯ ╟─┤ · ╟─┐ ┌──┤ ? ╟─ │ ╘═══╝ ╘═╤═╝ └───┘ ╘═╤═╝ │ │ ╔═╧═╗ │ │ ║ 0 ║ │ │ ╚═══╝ │ └─────────────────┘ ``` ## Quick explanation * The program just takes STDIN and calls `Ḷ` with it. * `Ḷ` finds the first space in the string, replaces it with `loves` and passes the result to `Ọ`. * `Ọ` repeatedly takes the first character from the input string, calls `Ṣ` with it and concatenates the numbers of occurrences onto a result string. When the input string is empty, it calls `Ṿ` with the result string. * `Ṿ` repeatedly calls `Ẹ` until it gets a result that is either equal to `"100"` or has length less than 3. (`100` can actually occur: consider the input `lovvvv eeeeeess`.) When it does, it adds `"%"` and returns that. * `Ẹ` computes one complete iteration of the love-computation algorithm; i.e., it takes a string of digits and returns the next string of digits. * `Ṛ` takes a *haystack* and a *needle* and finds the index of the first occurrence of *needle* in *haystack* using the faux case-insensitivity criterion (`or 32`). * `Ṣ` takes a *haystack* and a *needle* and repeatedly applies `Ṛ` to remove all instances of the *needle*. It returns the final result after all the removals as well as the number of removals made. [Answer] # APL, 80 ``` {{n←⍎∊⍕¨(⍵[⌈m]/⍨m≠⌊m),⍨+/(⌊m←2÷⍨≢⍵)↑[1]⍵,⍪⌽⍵⋄n≤100:n⋄∇⍎¨⍕n}∪⍦32|⎕UCS⍺,'Loves',⍵} ``` Because ~~love is love~~ [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") (even when it's not) Obligatory ♥︎-shaped version: ``` {f←{m← 2÷⍨≢⍵ n←+/(⌊m)↑[1]⍵,⍪⌽⍵ n←⍎∊⍕¨n,(⍵[⌈m]/⍨m≠⌊m) n≤100:n⋄∇⍎¨⍕n}⋄u←⎕UCS s←u⍺,'Loves',⍵ f∪⍦32|s } ``` The golfed version gives me somewhat erratic behaviour, because of a bug with `∪⍦` that I'm investigating with NARS's developers: ``` 'John'{{n←⍎∊⍕¨(⍵[⌈m]/⍨m≠⌊m),⍨+/(⌊m←2÷⍨≢⍵)↑[1]⍵,⍪⌽⍵⋄n≤100:n⋄∇⍎¨⍕n}∪⍦32|⎕UCS⍺,'Loves',⍵}'Jane' VALUE ERROR ``` But I was able to run it piecewise and get the correct result: ``` 'John'{∪⍦32|⎕UCS⍺,'Loves',⍵}'Jane' 2 2 1 2 1 1 2 1 1 {n←⍎∊⍕¨(⍵[⌈m]/⍨m≠⌊m),⍨+/(⌊m←2÷⍨≢⍵)↑[1]⍵,⍪⌽⍵⋄n≤100:n⋄∇⍎¨⍕n}2 2 1 2 1 1 2 1 1 76 ``` [Answer] # Javascript Probably could be cleaner, but it works. [**Verbose example**](http://jsfiddle.net/Lx7RQ/show/) ``` function z(e) { for (var t = 0, c = '', n = e.length - 1; n >= t; n--, t++) { c += n != t ? +e[t] + (+e[n]) : +e[t]; } return c } for (var s = prompt("Name 1").toLowerCase() + "loves" + prompt("Name 2").toLowerCase(),b = '', r; s.length > 0;) { r = new RegExp(s[0], "g"); b+=s.match(r).length; s = s.replace(r, "") } for (; b.length > 2; b = z(b)) {} console.log("Chances of being in love are: " + b + "%") ``` [Answer] # Python Well, I thought it was a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")... ``` a=filter(str.isalpha,raw_input()+"loves"+raw_input()).lower();a=[x[1]for x in sorted(set(zip(a,map(str.count,[a]*len(a),a))),key=lambda(x,y):a.index(x))] while reduce(lambda x,y:x*10+y,a)>100:a=reduce(list.__add__,map(lambda x: x<10 and[x]or map(int,str(x)),[a[n]+a[-n-1]for n in range(len(a)/2)]+(len(a)%2 and[a[len(a)/2]]or[]))) print str(reduce(lambda x,y:x*10+y,a))+"%" ``` Ungolfed: ``` a = filter(str.isalpha, raw_input() + "loves" + raw_input()).lower() a = [x[1] for x in sorted(set(zip(a, map(str.count, [a] * len(a), a))), key=lambda (x, y): a.index(x))] while reduce(lambda x, y: x * 10 + y, a) > 100: a = reduce(list.__add__, map(lambda x: x < 10 and [x] or map(int, str(x)), [a[n] + a[-n - 1] for n in range(len(a) / 2)] + (len(a) % 2 and [a[len(a) / 2]] or []))) print str(reduce(lambda x, y: x * 10 + y, a)) + "%" ``` [Answer] PHP ``` <?php $name1 = $argv[1]; $name2 = $argv[2]; echo "So you think {$name1} and {$name2} have any chance? Let's see.\nCalculating if \"{$name1} Loves {$name2}\"\n"; //prepare it, clean it, mince it, knead it $chances = implode('', array_count_values(str_split(preg_replace('/[^a-z]/', '', strtolower($name1.'loves'.$name2))))); while(($l = strlen($chances))>2 and $chances !== '100'){ $time = time(); $l2 = intval($l/2); $i =0; $t = ''; while($i<$l2){ $t.=substr($chances, $i, 1) + substr($chances, -$i-1, 1); $i++; } if($l%2){ $t.=$chances[$l2]; } echo '.'; $chances = $t; while(time()==$time){} } echo "\nTheir chances in love are {$chances}%\n"; $chances = intval($chances); if ($chances === 100){ echo "Great!!\n"; }elseif($chances > 50){ echo "Good for you :) !!\n"; }elseif($chances > 10){ echo "Well, it's something.\n"; }else{ echo "Ummm.... sorry.... :(\n"; } ``` sample result ``` $ php loves.php John Jane So you think John and Jane have any chance? Let's see. Calculating if "John Loves Jane" ... Their chances in love are 76% Good for you :) !! ``` [Answer] ## GolfScript Obligatory code golf answer in GolfScript: ``` ' '/'loves'*{65- 32%65+}%''+:x.|{{=}+x\,,}%{''\{)\(@+@\+\.(;}do 0+{+}*+{[]+''+~}%.,((}do{''+}%''+ ``` Accepts input as space-separated names e.g. ``` echo 'John Jane' | ruby golfscript.rb love.gs -> 76 ``` [Answer] ## C# ``` using System; using System.Collections.Generic; using System.Linq; namespace LovesMeWhat { class Program { static void Main(string[] args) { if (args.Length < 2) throw new ArgumentException("Ahem, you're doing it wrong."); Func<IEnumerable<Int32>, String> fn = null; fn = new Func<IEnumerable<Int32>, String> (input => { var q = input.SelectMany(i => i.ToString().Select(c => c - '0')).ToArray(); if (q.Length <= 2) return String.Join("", q); IList<Int32> next = new List<Int32>(); for (int i = 0, j = q.Length - 1; i <= j; ++i, --j) { next.Add(i == j ? q[i] : q[i] + q[j]); } return fn(next); }); Console.Write(fn(String.Concat(args[0], "LOVES", args[1]).ToUpperInvariant().GroupBy(g => g).Select(g => g.Count()))); Console.Write("%"); Console.ReadKey(true); } } } ``` [Answer] # Haskell My version is pretty long, it's because I decided to focus on readability, I thought it would be interesting to formalize your algorithm in code. I aggregate character counts in a *left fold*, it basically snowballs them together and order is in order of their occurrence in the string. I also managed to replace the part of algorithm that would normally require array indexing with list *bending*. It turns out your algorithm basically involves folding list of numbers in half and adding aligned numbers together. There two cases for bending, even lists split in the middle nicely, odd lists bend around a center element and that element doesn't participate in addition. *Fission* is taking the list and splitting up numbers that are no longer single digits, like *>= 10*. I had to write my own *unfoldl*, I'm not sure if it's actually an *unfoldl*, but it seems to do what i need. Enjoy. ``` import qualified Data.Char as Char import qualified System.Environment as Env -- | Takes a seed value and builds a list using a function starting -- from the last element unfoldl :: (t -> Maybe (t, a)) -> t -> [a] unfoldl f b = case f b of Just (new_b, a) -> (unfoldl f new_b) ++ [a] Nothing -> [] -- | Builds a list from integer digits number_to_digits :: Integral a => a -> [a] number_to_digits n = unfoldl (\x -> if x == 0 then Nothing else Just (div x 10, mod x 10)) n -- | Builds a number from a list of digits digits_to_number :: Integral t => [t] -> t digits_to_number ds = number where (number, _) = foldr (\d (n, p) -> (n+d*10^p, p+1)) (0,0) ds -- | Bends a list at n and returns a tuple containing both parts -- aligned at the bend bend_at :: Int -> [a] -> ([a], [a]) bend_at n xs = let (left, right) = splitAt n xs in ((reverse left), right) -- | Takes a list and bends it around a pivot at n, returns a tuple containing -- left fold and right fold aligned at the bend and a pivot element in between bend_pivoted_at :: Int -> [t] -> ([t], t, [t]) bend_pivoted_at n xs | n > 1 = let (left, pivot:right) = splitAt (n-1) xs in ((reverse left), pivot, right) -- | Split elements of a list that satisfy a predicate using a fission function fission_by :: (a -> Bool) -> (a -> [a]) -> [a] -> [a] fission_by _ _ [] = [] fission_by p f (x:xs) | (p x) = (f x) ++ (fission_by p f xs) | otherwise = x : (fission_by p f xs) -- | Bend list in the middle and zip resulting folds with a combining function. -- Automatically uses pivot bend for odd lists and normal bend for even lists -- to align ends precisely one to one fold_in_half :: (b -> b -> b) -> [b] -> [b] fold_in_half f xs | odd l = let middle = (l-1) `div` 2 + 1 (left, pivot, right) = bend_pivoted_at middle xs in pivot:(zipWith f left right) | otherwise = let middle = l `div` 2 (left, right) = bend_at middle xs in zipWith f left right where l = length xs -- | Takes a list of character counts ordered by their first occurrence -- and keeps folding it in half with addition as combining function -- until digits in a list form into any number less or equal to 100 -- and returns that number foldup :: Integral a => [a] -> a foldup xs | n > 100 = foldup $ fission $ reverse $ (fold_in_half (+) xs) | otherwise = n where n = (digits_to_number xs) fission = fission_by (>= 10) number_to_digits -- | Accumulate counts of keys in an associative array count_update :: (Eq a, Integral t) => [(a, t)] -> a -> [(a, t)] count_update [] x = [(x,1)] count_update (p:ps) a | a == b = (b,c+1) : ps | otherwise = p : (count_update ps a) where (b,c) = p -- | Takes a string and produces a list of character counts in order -- of their first occurrence ordered_counts :: Integral b => [Char] -> [b] ordered_counts s = snd $ unzip $ foldl count_any_alpha [] s where count_any_alpha m c | Char.isAlpha c = count_update m (Char.toLower c) | otherwise = m -- | Take two names and perform the calculation love_chances n1 n2 = foldup $ ordered_counts (n1 ++ " loves " ++ n2) main = do args <- Env.getArgs if (null args) || (length args < 2) then do putStrLn "\nUSAGE:\n" putStrLn "Enter two names separated by space\n" else let n1:n2:_ = args in putStrLn $ show (love_chances n1 n2) ++ "%" ``` ## Some Results: "Romeo" "Juliet" 97% - *Empirical testing is important* "Romeo" "Julier" 88% - *Modern abridged version...* "Horst Draper" "Jane" 20% "Horst Draper" "Jane(Horse)" 70% - *There's been a development...* "Bender Bender Rodriguez" "Fenny Wenchworth" 41% - *Bender Says "Folding is for women!"* "Philip Fry" "Turanga Leela" 53% - *Well you can see why it took 7 Seasons for them to marry* **"Maria" "Abraham" - 98% "John" "Jane" 76%** [Answer] # Ruby ``` math = lambda do |arr| result = [] while arr.any? val = arr.shift + (arr.pop || 0) result.push(1) if val >= 10 result.push(val % 10) end result.length > 2 ? math.call(result) : result end puts math.call(ARGV.join("loves").chars.reduce(Hash.new(0)) { |h, c| h[c.downcase] += 1; h }.values).join ``` Minified: ``` l=->{|a|r=[];while a.any?;v=a.shift+(a.pop||0);r.push(1) if v>=10;r.push(v%10) end;r[2]?l[r]:r} puts l[ARGV.join("loves").chars.reduce(Hash.new(0)){|h, c| h[c.downcase]+=1;h}.values].join ``` Call it: ``` $ ruby love.rb "John" "Jane" 76 ``` [Answer] # Python 3 A simple solution that uses no modules. I/O is pretty enough. I used error catching as a backup for when the second iterator is out of bounds; if it catches Python's index error, it assumes 1. Weird, but it works. ``` names = [input("Name 1: ").lower(), "loves", input("Name 2: ").lower()] checkedLetters = [] def mirrorAdd(n): n = [i for i in str(n)] if len(n) % 2: n.insert(int(len(n)/2), 0) return(int(''.join([str(int(n[i]) + int(n[len(n)-i-1])) for i in range(int(len(n)/2))]))) cn = "" positions = [0, 0] for i in [0, 1, 2]: checkAgainst = [0, 1, 2] del checkAgainst[i] positions[0] = 0 while positions[0] < len(names[i]): if not names[i][positions[0]] in checkedLetters: try: if names[i][positions[0]] in [names[checkAgainst[0]][positions[1]], names[checkAgainst[1]][positions[1]]]: positions[1] += 1 cn = int(str(cn) + "2") else: cn = int(str(cn) + "1") except: cn = int(str(cn) + "1") checkedLetters.append(names[i][positions[0]]) positions[0] += 1 print("\n" + str(cn)) while cn > 100: cn = mirrorAdd(cn) print(cn) print("\n" + str(cn) + "%") ``` Here's a sample run: ``` Name 1: John Name 2: Jane 221211211 33331 463 76 76% ``` [Answer] ## Java > > It can happen that the sum of 2 digits becomes greater than 10, in > this case the number will be split in 2 on the next row. > > > What if the number is equal to 10? I just added 1 and 0, is that correct? I decided to ignore case. ``` public class LoveCalculation { public static void main(String[] args) { String chars = args[0].toLowerCase() + "loves" + args[1].toLowerCase(); ArrayList<Integer> charCount = new ArrayList<Integer>(); HashSet<Character> map = new HashSet<Character>(); for(char c: chars.toCharArray()){ if(Pattern.matches("[a-z]", "" + c) && map.add(c)){ int index = -1, count = 0; while((index = chars.indexOf(c, index + 1)) != -1) count++; charCount.add(count); } } while(charCount.size() > 2){ ArrayList<Integer> numbers = new ArrayList<Integer>(); for(int i = 0; i < (charCount.size()/2);i++) addToArray(charCount.get(i) + charCount.get(charCount.size()-1-i), numbers); if(charCount.size() % 2 == 1){ addToArray(charCount.get(charCount.size()/2), numbers); } charCount = new ArrayList<Integer>(numbers); } System.out.println(Arrays.toString(charCount.toArray()).replaceAll("[\\]\\[,\\s]","") + "%"); } public static ArrayList<Integer> addToArray(int number, ArrayList<Integer> numbers){ LinkedList<Integer> stack = new LinkedList<Integer>(); while (number > 0) { stack.push(number % 10); number = number / 10; } while (!stack.isEmpty()) numbers.add(stack.pop()); return numbers; } } ``` input: ``` Maria Abraham ``` output: ``` 98% ``` input: ``` Wasi codegolf.stackexchange.com ``` output: ``` 78% ``` [Answer] # C There might be lots of improvement, but this was fun to code. ``` #include <stdio.h> #include <string.h> int i, j, k, c, d, r, s = 1, l[2][26]; char a[204], *p, *q; main(int y, char **z) { strcat(a, z[1]); strcat(a, "loves"); strcat(a, z[2]); p = a; q = a; for (; *q != '\0'; q++, p = q, i++) { if (*q == 9) { i--; continue; } l[0][i] = 1; while (*++p != '\0') if ((*q | 96) == (*p | 96)&&*p != 9) { (l[0][i])++; *p = 9; } } for (;;) { for (j = 0, k = i - 1; j <= k; j++, k--) { d = j == k ? l[r][k] : l[r][j] + l[r][k]; if (d > 9) { l[s][c++] = d % 10; l[s][c++] = d / 10; } else l[s][c++] = d; if (k - j < 2)break; } i = c; if (c < 3) { printf("%d", l[s][0]*10 + l[s][1]); break; } c = r; r = s; s = c; c = 0; } } ``` And of course, mandatory golfed version: 496 ``` #include <stdio.h> #include <string.h> int i,j,k,c,d,r,s=1,l[2][26];char a[204],*p,*q;main(int y,char **z){strcat(a,z[1]);strcat(a,"loves");strcat(a,z[2]);p=q=a;for(;*q!='\0';q++,p=q,i++){if(*q==9){i--;continue;}l[0][i]=1;while(*++p!='\0')if((*q|96)==(*p|96)&&*p!=9){(l[0][i])++;*p=9;}}for(;;){for(j=0,k=i-1;j<=k;j++,k--){d=j==k?l[r][k]:l[r][j]+l[r][k];if(d>9){l[s][c++]=d%10;l[s][c++]=d/10;}else l[s][c++]=d;if(k-j<2)break;}i=c;if(c<3){printf("%d",l[s][0]*10+l[s][1]);break;}c=r;r=s;s=c;c=0;}} ``` [Answer] **Python 3** This will take two names as input. strip extra spaces and then calculate love. Check out Input output for more details. ``` s=(input()+'Loves'+input()).strip().lower() a,b=[],[] for i in s: if i not in a: a.append(i) b.append(s.count(i)) z=int(''.join(str(i) for i in b)) while z>100: x=len(b) t=[] for i in range(x//2): n=b[-i-1]+b[i] y=n%10 n//=10 if n:t.append(n) t.append(y) if x%2:t.append(b[x//2]) b=t z=int(''.join(str(i) for i in b)) print("%d%%"%z) ``` input: ``` Maria Abraham ``` output: ``` 98% ``` Or, try this one ;) input: ``` Wasi Mohammed Abdullah code golf ``` output: ``` 99% ``` [Answer] # k, 80 ``` {{$[(2=#x)|x~1 0 0;x;[r:((_m:(#x)%2)#x+|x);$[m=_m;r;r,x@_m]]]}/#:'.=x,"loves",y} ``` Here is a run of it: ``` {{$[(2=#x)|x~1 0 0;x;[r:((_m:(#x)%2)#x+|x);$[m=_m;r;r,x@_m]]]}/#:'.=x,"loves",y}["john";"jane"] 7 6 ``` [Answer] ## J Here's a straightforward one in J: ``` r=:({.+{:),$:^:(#>1:)@}:@}. s=:$:^:(101<10#.])@("."0@(#~' '&~:)@":"1)@r c=:10#.s@(+/"1@=)@(32|3&u:@([,'Loves',])) exit echo>c&.>/2}.ARGV ``` It takes the names on the command line, e.g: ``` $ jconsole love.ijs John Jane 76 ``` [Answer] # [Groovy](http://groovy.codehaus.org/) Here's the groovy version, with tests. ``` countChars = { res, str -> str ? call(res+str.count(str[0]), str.replace(str[0],'')) : res } addPairs = { num -> def len = num.length()/2; (1..len).collect { num[it-1].toInteger() + num[-it].toInteger() }.join() + ((len>(int)len) ? num[(int)len] : '') } reduceToPct = { num -> /*println num;*/ num.length() > 2 ? call( addPairs(num) ) : "$num%" } println reduceToPct( countChars('', args.join('loves').toLowerCase()) ) assert countChars('', 'johnlovesjane') == '221211211' assert countChars('', 'asdfasdfateg') == '3222111' assert addPairs('221211211') == '33331' assert addPairs('33331') == '463' assert addPairs('463') == '76' assert addPairs('53125418') == '13457' assert addPairs('13457') == '884' assert addPairs('884') == '128' assert addPairs('128') == '92' assert reduceToPct( countChars('','johnlovesjane') ) == '76%' ``` ### Explanation: * "countChars" simply recurses and removes while build a string of digits * "addPairs" takes one string of digits adding the digits from the outside in \*\* the "collect..join" does the addition of the digits working outside in and rejoins them as a string \*\* the "+ (... c[(int)len])" throws in the middle digit again when c is an odd length * "recudeToPct" calls itself adding pairs until it gets down to less than 3 digits # CodeGolf Groovy, 213 char Seeing this is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") we can inline the closures and get it down to this: ``` println({c->l=c.length()/2;m=(int)l;l>1?call((1..m).collect{(c[it-1]as int)+(c[-it]as int)}.join()+((l>m)?c[m]:'')):"$c%"}({r,s->s?call(r+s.count(s[0]),s.replace(s[0],'')):r}('',args.join('loves').toLowerCase()))) ``` save it as lovecalc.groovy. run "groovy lovecalc john jane" ### Output: ``` $ groovy lovecalc john jane 76% $ groovy lovecalc romeo juliet 97% $ groovy lovecalc mariah abraham 99% $ groovy lovecalc maria abraham 98% $ groovy lovecalc al bev 46% $ groovy lovecalc albert beverly 99% ``` [Answer] ## Java This takes 2 String parameters on start and prints out the count of each character and the result. ``` import java.util.ArrayList; import java.util.LinkedHashMap; public class LUV { public static void main(String[] args) { String str = args[0].toUpperCase() + "LOVES" + args[1].toUpperCase(); LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); for (int i = 0; i < str.length(); i++) { if (!map.containsKey(String.valueOf(str.charAt(i)))) { map.put(String.valueOf(str.charAt(i)), 1); } else { map.put(String.valueOf(str.charAt(i)), map.get(String.valueOf(str.charAt(i))).intValue() + 1); } } System.out.println(map.toString()); System.out.println(addValues(new ArrayList<Integer>(map.values()))+"%"); } private static int addValues(ArrayList<Integer> list) { if ((list.size() < 3) || (Integer.parseInt((String.valueOf(list.get(0)) + String.valueOf(list.get(1))) + String.valueOf(list.get(2))) == 100)) { return Integer.parseInt((String.valueOf(list.get(0)) + String.valueOf(list.get(1)))); } else { ArrayList<Integer> list2 = new ArrayList<Integer>(); int size = list.size(); for (int i = 0; i < size / 2; i++) { int temp = list.get(i) + list.get(list.size() -1); if (temp > 9) { list2.add(temp/10); list2.add(temp%10); } else { list2.add(temp); } list.remove(list.get(list.size()-1)); } if (list.size() > list2.size()) { list2.add(list.get(list.size()-1)); } return addValues(list2); } } } ``` Surely not the shortest one (it's Java), but a clear and readable one. So if you call ``` java -jar LUV.jar JOHN JANE ``` you get the output ``` {J=2, O=2, H=1, N=2, L=1, V=1, E=2, S=1, A=1} 76% ``` [Answer] **R** Not going to win any compactness awards, but I had fun anyway: ``` problove<-function(name1,name2, relation='loves') { sfoo<-tolower( unlist( strsplit(c(name1,relation,name2),'') ) ) startrow <- table(sfoo)[rank(unique(sfoo))] # check for values > 10 . Not worth hacking an arithmetic approach startrow <- as.integer(unlist(strsplit(as.character(startrow),''))) while(length(startrow)>2 ) { tmprow<-vector() # follow by tacking on middle element if length is odd srlen<-length(startrow) halfway<-trunc( (srlen/2)) tmprow[1: halfway] <- startrow[1:halfway] + rev(startrow[(srlen-halfway+1):srlen]) if ( srlen%%2) tmprow[halfway+1]<-startrow[halfway+1] startrow <- as.integer(unlist(strsplit(as.character(tmprow),''))) } as.numeric(paste(startrow,sep='',collapse='')) } ``` Tested: valid for 'john'&'jane' and for 'romeo'&'juliet' . per my comment under the question, ``` Rgames> problove('john','jane','hates') [1] 76 Rgames> problove('romeo','juliet','hates') [1] 61 ``` ]
[Question] [ Each term in the squaring sequence, \$x\_n\$, is created by taking \$x\_{n-1}\$, squaring it, and removing all but the first four digits. The sequence always begins with \$x\_1 = 1111\$. Squaring this yields \$1234321\$, so \$x\_2 = 1234\$ The first few terms are: ``` 1111 1234 1522 2316 5363 ... ``` --- # The Challenge Your task is to, given a non-negative integer \$n\$, calculate \$x\_n\$. You may submit a full program which performs I/O, or a function which takes \$n\$ as a parameter. Your solution can be zero or one indexed, as long as you specify which. Because all the terms in this sequence are shorter than 5 digits, your code should be as short as possible too. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") loopholes apply. May the best golfer win! --- # Test Cases *Note: These are 1-indexed.* ``` 1 -> 1111 8 -> 6840 15 -> 7584 20 -> 1425 80 -> 4717 ``` [Answer] # JavaScript (ES7), ~~44~~ ~~43~~ 36 bytes ``` f=n=>--n?(f(n)**2+f).slice(0,4):1111 ``` This is a great example of abusing type coercion: `**` converts both its arguments to numbers, and `+` converts both its arguments to strings unless they're both numbers. This means that `f(n)**2+f` first converts `f(n)` to a number and squares it, then concatenates the result with the string representation of `f`. We can then use `.slice` to retrieve the first 4 chars of the string. Here are a few alternate approaches that don't use strings: ``` f=(n,x=1111)=>x<1e4?--n?f(n,x*x):x:f(n,x/10|0) f=n=>--n?(x=f(n))*x/(x>3162?1e4:1e3)|0:1111 ``` ### Test snippet ``` let f=n=>--n?(Math.pow(f(n),2)+f).slice(0,4):1111 ``` ``` <input id=I type="number" step="1" min="1" value="1"><button onclick="console.log(f(I.value))">Run</button> ``` Note: this uses `Math.pow` because `**` isn't supported in all browsers. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes Code: ``` $Fn4×4£ ``` Explanation: ``` $ # Push 1 and the input F # Input times do... n # Square the number 4× # Repeat that string 4 times 4£ # Take the first four characters # Output the last computed number ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=JEZuNMOXNMKj&input=ODA) [Answer] # Python 2, ~~51~~ ~~46~~ 44 Bytes ~~~~I'd like to get rid of the clunky `if` if possible, but I think an `exec` could be shorter..~~ Turns out for the moment that `exec` is shorter.~~ Wrong again! The recursive function returns. This is one-indexed. ``` f=lambda n:1111*(n<2)or int(`f(n-1)**2`[:4]) ``` An aleternative 46-byte solution with `exec`: ``` s=1111;exec's=int(`s*s`[:4]);'*input();print s ``` An alternative 49-byte recursive solution: ``` f=lambda n,s=1111:s*0**n or f(n-1,int(`s*2`[:4])) ``` Thanks to Flp.Tkc for saving a byte by reminding me that squaring doesn't need exponentiation :) [Answer] ## Haskell, 40 bytes ``` ((iterate(read.take 4.show.(^2))1111)!!) ``` It's a 0-based sequence. Usage example: `((iterate(read.take 4.show.(^2))1111)!!) 79` -> `4717`. How it works: ``` iterate ( ) 1111 -- repeatedly apply a function starting -- with 1111 and collect the results in a list -- the function is (^2) -- square show -- turn into string take 4 -- take the first 4 chars read -- turn back to number !! -- finally pick the nth element from the list ``` [Answer] ## Perl, 37 bytes 36 bytes of code + `-p` flag. ``` $\=1x4;$\=substr$\*$\,0,4while--$_}{ ``` To run it: ``` perl -pe '$\=1x4;$\=substr$\*$\,0,4while--$_}{' <<< 80 ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 19 bytes ``` 4é1Àñ|C="*" 5|D ``` [Try it online!](http://v.tryitonline.net/#code=NMOpMcOAw7F8QxI9EiIqEiIKGzV8RA&input=&args=Mg) This uses 0-based indexing. Of course, since numbers aren't exactly V's *forte*, this isn't very golfy. However, it does show one nice advantage V has over vim. You can run a macro *0* times, which is not possible in vim since '0' is a command not a count. This contains many unprintable characters, so here is a hexdump: ``` 0000000: 34e9 31c0 f17c 4312 3d12 222a 1222 0a1b 4.1..|C.=."*.".. 0000010: 357c 44 5|D ``` And here is a readable version: ``` 4é1Àñ|C<C-r>=<C-r>"*<C-r>" <esc>5|D ``` Explanation: ``` 4 " 4 times: é1 " Insert a '1' Àñ " Arg1 times: | " Move to the first character on this line C " Delete this whole line and enter insert mode <C-r>= " Insert the following evaluated as vimscript: <C-r>" " Insert what we just deleted * " Times <C-r>" " What we just deleted <esc> " Escape to normal mode 5| " Move to the fifth column on this line D " And delete until the end of this line " The second 'ñ' is added implicitly ``` [Answer] # Mathematica, 48 bytes ``` Nest[⌊10^(3-⌊t=2Log[10,#]⌋+t)⌋&,1111,#]& ``` Unnamed function taking an integer argument; 0-indexed. Uses four three-byte characters `⌊⌊⌋⌋`: Mathematica uses either `Floor[x]` or `⌊x⌋` to round a real number down to an integer, and the latter is generally one fewer byte. The command names in Mathematica for converting integers to strings are too long, so instead we do a mathematical calculation to find the first four digits of x^2: we take the base-10 logarithm of x^2, subtract its integer part, raise 10 back to that power, and multiply by 1000 and round down. tl;dr: logarithms ftw [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~12~~ 9 bytes -3 bytes thanks to Dennis using 1-based indexing and the `ṁ` mold/reshape atom. Golfing suggestions welcome! [Try it online!](http://jelly.tryitonline.net/#code=wrJE4bmBNOG4jAoxw4fCoQ&input=&args=Mg) ``` ²Dṁ4Ḍ 1Ç¡ ``` **Ungolfing** ``` Helper link ² Square. D Integer to decimal (a list of digits). ṁ4 Mold/reshape list_of_digits to be 4 digits long. Ḍ Decimal to integer. Main link: implicit left argument n 1 Start with the nilad 1. Ç¡ Call the helper link n times. ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes -2 (changing the input method) thanks to @Razetime ``` {⍎4⍴⍕⍵*2}⍣⎕⊢1 ``` Explanation: ``` {⍎4⍴⍕⍵*2}⍣⎕⊢1 ⍝ apply the dfn input times 1 ⍝ .. with initial argument 1 ⍵*2 ⍝ current value squared ⍎4⍴⍕ ⍝ take first 4 digits ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97X/1o94@k0e9Wx71Tn3Uu1XLqPZR7@JHfVMfdS0yBCng@p/GZcqVxmVkACQsDAA "APL (Dyalog Extended) – Try It Online") [Answer] ## Powershell, ~~73~~ 55 bytes Huge thanks to TimmyD for shaving off 18 bytes! Code: `for($A=1111;$args[0]---1;$A=-join"$(+$A*$A)"[0..3]){}$A` ~~`$A=1111;1..($n=2)|%{[string]$B=[math]::pow($A,2);$A=$B.substring(0,4)};$A`~~ `$n` is **n** in **xn-1** Explanation and exploded code: ``` $A=1111 #starting number $n=4 #n in formula for($i=0; $i -lt $n;$i++) #loop n times { [string]$B=[math]::pow($A,2) #create a new string $B and set it to $A raised to the power of 2 $A=$B.substring(0,4) #set $A to the first 4 characters of $B } $A #print $A ``` Some notes: * Powershell lets you assign variables in the same statements where you reference them. For example, `1..($n=4)|%` will set $n to 4 and then start a loop that runs $n times. `1` can be changed to any integer and it will loop $n-[your integer]+1 times. * The default data type when using `[math]::` in Powershell is a double. In the code above, we have to explicitly cast `$B` to a string so that we can call `.substring()` on it because there is no `.substring()` function for doubles in Powershell. [Answer] # Python 2, ~~44~~ 41 bytes -3 bytes thanks to xnor (use an integer division to avoid `and`) ``` f=lambda n:int(1/n*1111or`f(n-1)**2`[:4]) ``` **[repl.it](https://repl.it/EenM/1)** 1-based recursive function. When `n>1` the integer division, `1/n`, results in `0`, then `0*1111=0` which is falsey, so the right of the `or` is evaluated, which takes the first four characters of the representation of the square of the `n-1`th result; this is then cast to an `int`. When `n=1` the integer division, `1/n`, results in `1`, then `1*1111=1111`, which is truthy, and the `int` `1111` cast to an `int` is `1111`. [Answer] # Groovy, 49 bytes ``` {x=1111;(it-1).times{x="${x**2}"[0..3] as int};x} ``` [Answer] ## Pyke, 10 bytes ``` 1RVX`4*4<b ``` [Try it here!](http://pyke.catbus.co.uk/?code=1RVX%604%2a4%3Cb&input=5) [Answer] # [MATL](http://github.com/lmendo/MATL), ~~14~~, 13 bytes ``` 1111G:"UV4:)U ``` [Try it online!](http://matl.tryitonline.net/#code=MTExMUc6IlVWNDopVQ&input=Nw) Explanation: ``` 1111 % Push 1111 G % Push input :" % Input times: U % Square the top of the stack V % Convert it to a string 4:) % Take the first four digits U % Convert it back to a number % Implictly display ``` [Answer] # R, ~~58~~ ~~56~~ ~~55~~ 53 bytes ``` x=3334;for(e in N<-scan():1)x=x^2%/%10^(3+(x>3162));x ``` Takes `N` from stdin. 3334 is practically X\_0, which is needed because the for-loop needs to be executed at least once (it would be longer to skip). R really is a terrible language for taking the first four digits of a number, but since the number of cases are limited, we only have to worry about the squares of `x<3163` and `x>3162`, the former yield a 6 digit number, the latter a 7 digit number. The rest is pretty straightforward, `%/%` divides and ignores the remainder. `x` is printed to stdout. Saved 2 bytes thanks to @ETHproductions [Answer] # [Javagony](https://esolangs.org/wiki/Javagony) - 153 bytes Javagony is a restricted version of Java, that doesn't allow any control flow except recursion and `try-catch`, no for loops, while loops, or if's. Coding in it is a pretty fun exercise, but frustrating. Not that regular Java isn't nearly as frustrating by itself. ``` int a(int i){return a(i-1,1111);}int a(int i,int n){try{int x=1/i;return a(i-1,Integer.parseInt((n*n+"").substring(0,4)));}catch(Exception e){return n;}} ``` [Answer] # PHP, ~~55~~ 52 bytes Saved 3 bytes thanks to @user59178 ``` for($i=1111;$argv[1]--;)$i=substr($i**2,0,4);echo$i; ``` Run from command line, zero-indexed. Thanks for not caring about what type my variables are, PHP! Here we simply square the number and trim off everything past the first 4 digits, casually alternating between number and string without a care in the world. [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 14 bytes ``` =1111:(ZZ)[:4] ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/39YQCKw0oqI0o61MYv//BwA "cQuents – Try It Online") 1-indexed. ## Explanation ``` =1111 first term is 1111 : given n, output nth term, otherwise output full sequence each term equals (ZZ) previous term * previous term [:4] [:4] (python slicing) ``` [Answer] # [Pushy](https://github.com/FTcode/Pushy), 20 bytes ``` 1111@:2esL4-:.;Kjk;# ``` [Try it online!](https://tio.run/##Kygtzqj8/98QCBysjFKLfUx0rfSsvbOyrZX///9vbgkA "Pushy – Try It Online") Note this is 1-indexed. ``` % Implicit: N is on stack 1111@ % Push 1111, and then reverse stack to get [1111, n] : % N times do: (this consumes N) 2e % Square last term s % Split into individual digits L4-:.; % Get stack length -4, pop that many times Kj % Join remaining digits (Uses flag "K" for whole stack) k % Set "K" flag to false, so operations only affect last item ; % End loop. # % Output final calculated term ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 18 bytes ``` ,1111:?:{^@[.l4,}i ``` [Try it online!](http://brachylog.tryitonline.net/#code=LDExMTE6Pzp7XkBbLmw0LH1p&input=Nzk&args=Wg) This answer is 0-indexed. ### Explanation ``` ,1111:?:{ }i Iteratively call Input times the predicate in brackets starting with input 1111: ^ Square @[. Output is a prefix of the square .l4, Its length is 4 ``` [Answer] ## Batch, 82 bytes ``` @set n=1111 @for /l %%i in (1,1,%1)do @set/an*=n&call set n=%%n:~0,4%% @echo %n% ``` Like Perl, integers are strings, but unlike Perl I can only take the substring of a variable, and taking substrings inside a loop is somewhat awkward. [Answer] # C, 56 bytes ``` a;s(n){for(a=1111;--n;)a=a*a/(a>3162?1e4:1e3);return a;} ``` One-indexed. [Answer] # Clojure, 76 bytes ``` (defn s[n](if(= n 1)1111(read-string(subs(str(*(s(dec n))(s(dec n))))0 4)))) ``` First Clojure golf (seems like a nice language). This is 1-indexed. Will explain the code later. [Answer] # C#, 64 60 bytes *Saved 4 bytes by following [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire)'s [comment](https://codegolf.stackexchange.com/questions/101961/the-squaring-sequence/101978?noredirect=1#comment247789_101979) on a Java answer!* ``` n=>{int x=1111;for(;n-->1;)for(x*=x;x>1e4;x/=10);return x;}; ``` Previous version (**64 bytes**): ``` n=>{int x=1111;while(n-->1){x*=x;while(x>9999)x/=10;}return x;}; ``` Full program with ungolfed method and test cases: ``` using System; namespace SquaringSequence { class Program { static void Main(string[] args) { Func<int, int> f = n => { int x = 1111; while (n-- > 1) { x *= x; while (x > 9999) x /= 10; } return x; }; // test cases: Console.WriteLine(f(1)); // 1111 Console.WriteLine(f(8)); // 6840 Console.WriteLine(f(15)); // 7584 Console.WriteLine(f(20)); // 1425 Console.WriteLine(f(80)); // 4717 } } } ``` [Answer] # Ruby, 47 bytes First golf! Saves bytes with `-n` option (but still count as 1! :)). ``` a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a ``` 0-indexed. To run it: ``` ruby -ne 'a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a' <<< 80 ``` [Answer] # Pyth, ~~13~~ 12 bytes *Thanks to @Jakube for -1 byte* ``` us<*4`*GG4Q1 ``` A program that takes input of a 1-indexed integer and prints the result. [Test suite](https://pyth.herokuapp.com/?code=us%3C%2a4%60%2aGG4Q1&test_suite=1&test_suite_input=1%0A8%0A15%0A20%0A80&debug=0) This uses a similar approach to [@Adnan's answer](https://codegolf.stackexchange.com/a/101963/55526). **How it works** ``` us<*4`*GG4Q1 Program. Input: Q u Q1 Execute the following Q times, starting at 1, with variable G: *GG Yield G*G ` Convert to string *4 Repeat 4 times < 4 Yield first 4 characters s Convert to integer Implicitly print ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 15 bytes ``` ~1111\{.*`4<~}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v84QCGKq9bQSTGzqarX@/zcAAA "GolfScript – Try It Online") 0-indexed ``` ~ # Parse n to a number 1111 # Push 1111 \{ }* # Execute this block n times .* # Square the number ` # Parse it to a string 4< # Get the first 4 digits ~ # Parse it back to a number ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~6~~ 5 bytes ``` Ṫ(²4Ẏ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaoowrI04bqOIiwiIiwiOCJd), or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmqKMKyNOG6jiIsIiIsIjFcbjhcbjE1XG4yMFxuODAiXQ==). Explanation: ``` Ṫ # Pop, push 1 then the input ( # [Input] times: ² # Square 4Ẏ # Get the first 4 digits ``` [Answer] # TI-Basic, 31 bytes ``` Input N 1111 For(I,2,N int(Ans²/₁₀^(-3+int(log(Ans² End Ans ``` 1-indexed input. `-` represents the negative symbol. [Answer] # Excel VBA, 42 bytes ``` v=1111:For i=2To[A1]:v=Left(v^2,4):Next:?v ``` Input is in cell `A1` of the active sheet. Code is run in the immediate window. Output is to the immediate window. Here's the result for `80` as an input: [![Result](https://i.stack.imgur.com/96mXD.png)](https://i.stack.imgur.com/96mXD.png) ]
[Question] [ Write a short program for [196-algorithm](http://mathworld.wolfram.com/196-Algorithm.html). The algorithm starts from an integer, then adds its reverse to it until a palindrome is reached. e.g. ``` input = 5280 5280 + 0825 = 6105 6105 + 5016 = 11121 11121 + 12111 = 23232 output = 23232 ``` **Input** an integer, which is not a [lyrchrel number](https://en.wikipedia.org/wiki/Lychrel_number) (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely) **Output** the palindrome reached. [Answer] ## APL (22 characters) ``` {a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞ ``` This works in Dyalog APL. Here's an explanation, from right to left: * `{ ... }⍞`: Get input from the user as characters (`⍞`) and feed it to our function (`{ ... }`). * Within the direct function (`⋄` separates statements, so we look at them from left to right): + `a≡⌽a←⍕(⍎⍵)+⍎⌽⍵ : a`: Evaluate (`⍎`) the right argument's (`⍵`) reverse (`⌽`), and add that to the evaluated version of the right argument itself. Then, format the result (`⍕`; i.e., give its character representation), assign (`←`) that to the variable `a`, and finally test if `a`'s reverse is equivalent to `a` (i.e., is `a` a palindrome?). If true, return `a`; otherwise... + `∇a`: Feed `a` back into our function (`∇` is implicit self-reference). Example: ``` {a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞ 412371 585585 ``` [Answer] ## GolfScript, 29 chars ``` ~]{{.`.-1%.@={;0}{~+1}if}do}% ``` --- **Selected commentary** The meat of the program is the `do` loop, of course. So I'll just cover that. 1. `.`` copies the number and stringifies it. 2. `.-1%` copies that string version and reverses it. 3. `.@` copies the reversed version, and brings the original non-reversed version to the front. So, say, the number is 5280. At this stage, the stack is: `5280 "0825" "0825" "5280"`. The stage is set for the comparison. (After the comparison, the stack will be left at `5280 "0825"` no matter what---the items to compare have been popped off.) 1. If the string and the reverse are the same, we don't care about the reversed string, so just pop it off (`;`) and return 0 (to end the `do` loop). 2. If they don't match, then evaluate (`~`) the reversed string (to make it a number), add (`+`) that to the original number, and return 1 (to continue the `do` loop). [Answer] # Python 2, 55 bytes Following JPvdMerwe suggestion: ``` n=input() while`n`!=`n`[::-1]:n+=int(`n`[::-1]) print n ``` **Python 2, 62:** ``` n=raw_input() while n!=n[::-1]:n=`int(n)+int(n[::-1])` print n ``` [Answer] **Ruby — 56 chars** ``` x,r=gets x="#{x.to_i+r.to_i}"until x==r=x.reverse puts x ``` [Answer] Just exercising my Pyth skills, not a serious contender. # Pyth, 16 bytes ``` L?bqb_by`+vbi_bTyz ``` Equivalent to Python 3: ``` y=lambda b:b if b==b[::-1] else y(str(eval(b)+int(b[::-1],10))) print y(input()) ``` [Answer] # J 25 27 31 ``` f=:(+g)^:(~:g=.|.&.":)^:_ e.g. f 5280 23232 ``` [Answer] # CJam, ~~22~~ 21 bytes CJam was created after this question was asked, so technically its an invalid submission. But I found the question interesting, so here goes: ``` r{__W%:X=0{~X~+s1}?}g ``` Explanation: ``` r{ }g "Read the input number as string and enter a while-do loop"; __ "Make 2 copies of the string number"; W%:X "Reverse the second and store it in X"; = "Check if the number is already palindrome"; 0{ }? "Put 0 on stack if it is palindrome, else, run the code block"; ~ "Convert the string to int"; X~ "Put the reverse string on stack and convert it to int too"; +s "Add the two numbers and covert back the result to string"; ``` The core logic is that in each while-do iteration, you first check if palindrome is achieved or not. If not, add the reverse to the number. Pretty much what the algorithm is! [Try it online here](http://cjam.aditsu.net/) [Answer] This is an actual contender, since J has been around for decades. # J (16 bytes) ``` (+^:~:|.&.":)^:_ ``` This is a verb, so it can be assigned to a variable in a J session and used like so: ``` f =. (+^:~:|.&.":)^:_ f 5280 23232 ``` How it works: ``` (+^:~:|.&.":)^:_ +^:~: add if unequal |.&.": reverse under string format +^:~:|.&.": add reverse unless a palindrome ( )^:_ repeat until unchanged ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes Code: ``` [DÂQ#Â+ ``` Explanation: ``` [ # Infinite loop. D # Duplicate and bifurcate (which duplicates it and reverses the duplicate). Q# # If the number and the number reversed are equal, break. Â+ # Add the reversed number to the initial number. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W0TDglEjw4Ir&input=NTI4MA). [Answer] Python: 66 ``` n=input() while 1: r=int(`n`[::-1]) if n==r:break n+=r print n ``` [Answer] Perl, 40 chars ``` $_=<>;$_+=$r while$_!=($r=reverse);print ``` [Answer] # PHP - ~~54~~ 48 characters ``` <?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s; ``` Test: ``` $ php 196.php <<< 5280 23232 ``` [Answer] ### Scala 82 ``` def p(n:Int):Int={val s=n.toString.reverse.toInt if(n==s)n else p(n+s)} p(readInt) ``` [Answer] # [JAGL](http://github.com/globby/jagl) Alpha 1.2 - 19, 21 with stdin ***Not contending***, just getting some experience with my language Expects a number from stdin ``` T~d{DddgCi+dgdC=n}uSP ``` Explanation ``` T~ Get a line of input, and eval to an integer d Duplicate (for first round) {Ddd Drop last and duplicate twice gCi Convert to string, reverse, and convert back to integer +d Add to original and duplicate gdC Convert to string, duplicate, reverse =n} If it isn't a palindrome, keep going uSP Run until palindrome reached, then print output number ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ↔?|↔;?+↰ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFPsaIGFtr/2obcP//6ZGFgb/owA "Brachylog – Try It Online") Somewhat similar to one of the first Brachylog programs I saw and was intrigued by, from the [Brachylog introduction video](https://youtube.com/watch?v=XYVhZ-MFcUs). ``` ?↔?.|↔;?+↰. (initial ? and the .s are implicit) ?↔? % If the input and its reverse are the same, . % then the input is the output |↔;?+↰ % Or, add the input and its reverse, and call this predicate recursively . % The result of that is the output ``` [Answer] ## Bash (64) ``` X=`rev<<<$1|sed s/^0*//`;[ $1 = $X ]&&echo $1||. $0 $(($1+$X)) ``` Call with: bash <filename> <number> [Answer] ## C# - 103 99 chars ``` public int P(int i) { var r = int.Parse(new string(i.ToString().Reverse().ToArray()))); return r == i ? i : P(i + r); } ``` C# never does very well in golf. Elegant, but verbose. [Answer] ## In Q (39 characters) ``` f:{while[x<>g:"I"$reverse -3!x;x+:g];x} ``` Sample Usage: ``` q)f 5280 23232 ``` Edit: Down to 34 now, same usage: ``` {while[x<>g:"I"$(|) -3!x;x+:g];x} 5280 ``` [Answer] ``` r=input() while 1: r=`r` if r==r[::-1]: break else: r=int(r)+int(r[::-1]) print r ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes (non competing) A very simple answer, just for the challenge of coding in and esoteric language. `ṚḌ+µŒḂ¬$¿` ``` ṚḌ : take the argument, reverse (and vectorize) it +µ : add both ŒḂ¬$¿ : while the result isn't a palindrome ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bma4biMK8K1xZLhuILCrCTCv////zUyODA "Jelly – Try It Online") Should this answer be unclear or wrong on any level, feel free to point it out. Thanks to Dennis for helping me out with this first small piece of code. [Answer] # [Java (JDK)](http://jdk.java.net/), ~~78~~ 71 bytes ``` i->{for(int r=0,t;i!=r;)for(t=i+=r,r=0;t>0;t/=10)r=r*10+t%10;return i;} ``` [Try it online!](https://tio.run/##NY6xasNADIZn31OoQ8HXJO45UAgcF5qlkKFTxtJBdeygxDkHnWwowc/uyqUVSKCPn5/vjAOuzsfLVLWYErwjRbib17c@VkJdxHYfpeYGq9pkN6YBpQb6R7DXbJbpD00@X7TeZKM3BnSSoFClmR2EiVbbe9Pxb4qDW4qnh8DezkwCLQIvFXvZ6j6H0lkO/FS6hTyWznMtPUcgP07e3PqvVmv/2oeOjnBV6/wgTPH08QnIp2RVbHY4fCepr0XXS6H2UdqY74omf1lvnFVXgNGM0w8 "Java (JDK) – Try It Online") -7 Thanks to Celingcat! [Answer] Python. 85 characters: ``` s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input()); while rs(n)!=s(n):n+=i(rs(n));print n ``` If you don't want output on each iteration: ``` s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input()); while rs(n)!=s(n):n+=i(rs(n)) print n ``` (one less character) [Answer] ### Windows PowerShell (63) ``` for($a=+"$input";-join"$a"[99..0]-ne$a){$a+=-join"$a"[99..0]}$a ``` I still hate it that there is no easy way to reverse a string. [Answer] **Haskell ~~89~~ 87 chars** ``` r=read.reverse.show main=getLine>>=print.head.filter(\x->x==r x).iterate(\x->x+r x).read ``` Somewhat readable version: ``` myFind p = head . filter p rev = read . reverse . show isPalindrome x = x == rev x next x = x + rev x sequence196 = iterate next palindrome196 = myFind isPalindrome . sequence196 main = getLine >>= print . palindrome196 . read ``` The golfed version was created by manual inlining and renaming the remaining functions to single character names. [Answer] ## befunge, 57 bytes ``` "KCTS"4(&:0\v \T\a*+\:0`jv>:a%\a/ 0:+_v#-TD2$<^\ @.< ``` though the code is places in a 4x19 grid, so might call it 76. * first line is initializeing, and reading input number * second line reverse first number in stack and put it in the second stack position. * and the third line checks if a number is palindrome. [Answer] ## C++ TMP (256 characters) ``` #include<cstdio> #define Y(A,B,C,D)template<int N>struct A<C,D>{enum{v=B};}; #define Z(A)template<int N,int M>struct A{enum{v= #define n 5194 Z(R)R<N/10,M*10+N%10>::v};};Y(R,N,0,N)Z(S)S<N+M,R<N+M,0>::v>::v};};Y(S,N,N,N)main(){printf("%d",S<n+R<n,0>::v,0>::v);} ``` This version could be shortened a bit, but a 256-character answer is hard to pass up. Here's an un-golfed version: ``` #include <iostream> template<size_t N> class Reverse { template<size_t M, size_t R> struct Inner { enum { value = Inner<M/10, R*10 + M%10>::value }; }; template<size_t R> struct Inner<0, R> { enum { value = R }; }; public: enum { value = Inner<N, 0>::value }; }; template<size_t N> class OneNineSix { template<size_t M, size_t R=Reverse<M>::value> struct Inner { enum { value = OneNineSix<M + R>::value }; }; template<size_t M> struct Inner<M, M> { enum { value = M }; }; public: enum { value = Inner<N + Reverse<N>::value>::value }; }; int main() { const size_t N = 4123; std::cout << OneNineSix<N>::value << std::endl; } ``` [Answer] ## Pyke, 13 bytes (noncompeting) ``` D`_b]D$XIsr)h ``` [Try it here!](http://pyke.catbus.co.uk/?code=D%60_b%5DD%24XIsr%29h&input=89&warnings=0) ``` `_b - int(reversed(str(num)) D ] - [num, ^] D - _ = ^ $ - delta(^) XI - if ^: s - num = sum(_) r - goto_start() h - _[0] ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 57 bytes ``` L,BDbRBv D,f,@,1]A+ D,g,@,1]A= D,h,@,{f}A{g}Q{h} L,{h}2/i ``` [Try it online!](https://tio.run/##S0xJKSj4/99Hx8klKcipjMtFJ03HQccw1lEbyEyHMG2BzAwgszqt1rE6vTawOqOWy0cHSBrpZ/5XyUnMTUpJVDCys@fy///f1MjCAAA "Add++ – Try It Online") ## How it works ``` L, ; Create a function 'lambda 1' ; Example argument: [5280] BD ; Digits; STACK = [[5 2 8 0]] bR ; Reverse; STACK = [[0 8 2 5]] Bv ; Undigits; STACK = [825] D,f,@, ; Define a monadic function 'f' ; Example argument: [5280] 1] ; Call 'lambda 1'; STACK = [825] A+ ; Add the argument; STACK = [6105] D,g,@, ; Define a monadic function 'g' ; Example argument: [5280] 1] ; Call 'lambda 1'; STACK = [825] A= ; Equal to argument; STACK = [0] D,h,@, ; Define a monadic function 'h' ; Example argument: [5280] {f} ; Call 'f'; STACK = [6105] A{g} ; If 'g'... Q ; Return {h} ; Else call 'h' L, ; Define a function, 'lambda 2' ; Example argument: [5280] {h} ; Call 'h'; STACK = [46464] 2/i ; Halve; STACK = [23232] ``` [Answer] # C (gcc), 132 bytes ``` t;r(char*s){char*e=s+strlen(s)-1;for(;e>s;*e--=*s,*s++=t)t=*e;}g(o,l,f){for(l=malloc(9);sprintf(l,"%d",o),r(l),f=atoi(l),f-o;)o+=f;} ``` Call with `g(n)` for an `int n`. Try it online [here](https://tio.run/##bYvLCsIwFETX@hWlIOTmAdoqKJf4JW5CTGohTSTJrvTbY1pcllnMwDmjxaB1KRkj0R8VaYJ5ayMTSzk640kCcUEbIkHzTEiNEJImThNjMkOW1OAykMAdtzCvmpOTci5o8gBM3zj6bInj7end8gC8cuBWqhzGbYmAEJi0uJRqNpMaPYFmPh7@z/p7@ZY3A7l19zMA7pC@76/7pOtrVrSUHw). Ungolfed: ``` t; // temporary varaiable fpr swapping characters r(char *s) { // helper function to reverse a string: takes a string argument and modifies it char *e = s + strlen(s) - 1; // find the end of the string for(; e > s; // move the end pointer and the start pointer towards each other until they meet *e-- = *s, *s++ = t) // swap the characters under the start and end pointers ... t = *e; // ... using the temporary variable } g(o, // function for the 196 algorithm: takes an int argument and returns an int l, f) { // abusing the argument list to declare to extra variables: one is a string for reversing the number, the other is an int for(l = malloc(9); // allocate space for the string sprintf(l, "%d", o), // convert the number to a string r(l), // reverse that string f = atoi(l), // convert it back to an int f - o; ) // loop until the two numbers are equal o += f; // add the two numbers } ``` [Answer] # Powershell, ~~63~~ 62 bytes *-1 byte thanks to @AdmBorkBork* ``` param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s ``` Test script: ``` $f = { param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s } &$f 5280 ``` ]
[Question] [ Print or return the following string: ``` zottffssentettffssenttttttttttttttttttttffffffffffffffffffffsssssssssssssssssssseeeeeeeeeennnnnnnnnno ``` This is the first letter of each of the numbers **z**ero, **o**ne, **t**wo, all the way up to **o**ne hundred. Standard I/O rules apply, but the output must be exactly as shown above, optionally with a single trailing newline. No other variation in output is permitted. This is code golf, shortest code in bytes wins. --- Note this has also been cross-posted to [Anarchy Golf](http://golf.shinh.org/p.rb?zottffssentettffssen) (by me) [Answer] # [Python](https://www.python.org), 58 bytes ``` a='ttffssen' print(f"zo{a}te{a+''.join(x*10for x in a)}o") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3rRJt1UtK0tKKi1Pz1LkKijLzSjTSlKryqxNrS1KrE7XV1fWy8jPzNCq0DA3S8osUKhQy8xQSNWvzlTShJuRBNAH1wMwpSYWzsIA0LKAYC0iFgzw4gNsKcz8A) [Answer] # x86-64 machine code, 41 bytes ``` 66 B8 7A 6F 66 AB 48 B8 74 74 66 66 73 73 65 6E 48 AB AA C6 07 65 AE 48 AB 6A 0A 59 F3 AA 48 C1 E8 08 75 F5 B0 6F 66 AB C3 ``` [Try it online!](https://tio.run/##TZFLT8MwEITP8a8Ygqo4EKryFOqDA4gjEqo4gNoeXMdujFI72ClNW/jrBIfwuuxqd0bfjrT8aMF5XTO3BMU4pKS7yM2c5ZBE9oOleQWrEkTbCG@ITDQcXpLAlcatSdCdb0qBXnV2mfh67YUuc1wphGUppXNCh633pW1z8sW7fnq4xf3DGBObqplni8jrnDV667b9oFi5DMe9AQpTwPKKBFYU@Ka4zMI2sfzJZ72FbcEsT5qIv/msKEkcIh6QV6NSSMozZg/g/ILsK83zVSowdGWqTDe7IkTpEkumNI3JjgSNGVa4VV5Ozo9PZgMSSNrOHhAU1tslDTsuTPC3/hOm@o7xTGkBblLRDxu1uVBhhF6CjR9Tg92PHZ3eyaNHbUaUrrRTCy1SfAWOZTypDg9n8eAd60zlAnSDPQ@pbk7/JwHtKDQvcfFUe1Llxfe6/uAyZwtXHy0vznzxjx55v8g/AQ "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI a memory address at which to place the result, as a null-terminated byte string. In assembly: ``` f: mov ax, 'z' | 'o'<<8 # Put these two bytes in AX. stosw # Write them to the string, advancing the pointer. .byte 0x48, 0xB8 # Place the following eight bytes in RAX. .ascii "ttffssen" stosq # Write them to the string, advancing the pointer. stosb # Write the first byte 't' again, advancing the pointer. mov BYTE PTR [rdi], 'e' # Place the byte 'e' at the current output address. scasb # Advance RDI over the 'e' while comparing with AL. stosq # Write "ttffssen" again, advancing the pointer. r: push 10; pop rcx # Set RCX to 10. rep stosb # Write AL to the string 10 times, advancing the pointer. shr rax, 8 # Shift RAX right by 8 bits; AL (its low byte) # will be each of "ttffssen" in order. jnz r # Jump back, to repeat, if the result is nonzero. mov al, 'o' # Set AL to 'o'. stosw # Write 'o' and a null byte, advancing the pointer. ret # Return. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ₁ʀ∆ċvhṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoHKgOKIhsSLdmjhuYUiLCIiLCIiXQ==) ``` ₁ʀ∆ċvhṅ ₁ʀ # Range [0, 100] ∆ċ # Nth cardinal of each vh # First char of each ṅ # Join together ``` # [Vyxal](https://github.com/Vyxal/Vyxal) `sMH`, 4 bytes ``` ƛ∆ċh ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzTUgiLCIiLCLGm+KIhsSLaCIsIiIsIiJd) (thanks to lyxal) sMH, why are there flags for everything ``` H flag # Preset stack to 100 ƛ # Map over 100 M flag # Make that 100 be a range [0, 100] instead of [1, 100] ∆ċ # Convert to cardinal h # Get the first character s flag # Join together ``` [Answer] # [Factor](https://factorcode.org) + `math.text.english`, 39 bytes ``` [ 100 [0,b] [ number>text first ] map ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU2r0GBPP3crhezUorzUHIXi1MLS1Lzk1GKF3MSSDL2S1IoSvdS89JzM4gyISFFiXjpQNjNfwXppaUmarsVN9WgFQwMDhWgDnaRYhWiFvNLcpNQiO5BOhbTMouIShVigzgKFWIjyVcmJOTkK5UWZJakQgQULIDQA) [Answer] # JavaScript (ES6), 57 bytes Builds the output recursively from right to left. ``` f=(k=8)=>k>0?f(k-.1)+`${s}o`[~~k]:`zo${s="ttffssen"}te`+s ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYj29ZC09Yu287APk0jW1fPUFM7QaW6uDY/IbquLjvWKqEqH8i1VSopSUsrLk7NU6otSU3QLv6fk1qikFpRkJpckpqiYKugVJUPU1GSCmdhAWlYQDEWkAoHeXCQr2TNBbK3KLUYaGWahqY1V3J@XnF@TqpeTn66BlBYByJni3CavYL6@x39j@ZMAZLqClYK6o/m9qhrWv8HAA "JavaScript (Node.js) – Try It Online") ### Note Because of floating point errors, we don't reach exactly `k = 0` on the last iteration. That's why we have to use the test `k > 0 ?` instead of just `k ?`. This is still 1 byte shorter than the following integer version: **58 bytes** ``` f=(k=81)=>k--?f(k)+`${s}o`[k/10|0]:`zo${s="ttffssen"}te`+s ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYj29bCUNPWLltX1z5NI1tTO0Glurg2PyE6W9/QoMYg1iqhKh8oYqtUUpKWVlycmqdUW5KaoF38Pye1RCG1oiA1uSQ1RcFWQakqH6aiJBXOwgLSsIBiLCAVDvLgIF/Jmgtkb1FqMdDKNA1Na67k/Lzi/JxUvZz8dA2gsA5EzhbhNHsF9fc7@h/NmQIk1RWsFNQfze1R17T@DwA "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 48 41 bytes ``` IntegerName@#~StringPart~1&~Array~100<>"" ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Zl@98zryQ1PbXILzE31UG5LrikKDMvPSCxqKTOUK3OsagosbLO0MDAxk5J6X8AUKrEIe0/AA "Wolfram Language (Mathematica) – Try It Online") *-1 thanks to Steffan* *-7 thanks to att!* My Wolfram is rusty and was never great, so probably golfable, but it seemed like the right tool. TIO shows an error because it can't connect to the internet, but it's still prints the correct answer. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 145 bytes ``` --[----->+>+>+>+>+>+>+>+<<<<<<<<]++++++++[->++>+>>>++>++>>+<<<<<<<<]>++++.>+.+++++..>.>.>---.>---.>-.>.<<+.->.[<]>------[.>]<[<]>[..........>]<+. ``` [Try it online!](https://tio.run/##VU1RCoBQCDuQuBPILiLvo4Iggj6Czm/6eBVt4JgbOp/TdqzXskeouhYof9pAkwHPSiXskvpVWDko6EWAxbz5jLRmAiU8y/2dOtisrONFbgQRNw "brainfuck – Try It Online") **Commented code** ``` --[----->+>+>+>+>+>+>+>+<<<<<<<<] Set cell 0 to 254 and loop 102 times filling cells 1 to 8 with ascii f ++++++++[->++>+>>>++>++>>+<<<<<<<<] Set cell 0 to 8 and loop 8 times boosting certain cells to give vnffvvfn >++++. Move to cell 1; boost and output z >+.+++++.. Move to cell 2; boost and output ott >.>.>---.>---.>-.>. From cells 3 to 8 output ffssen modifying values as necessary <<+.->. Move to cell 6; temporarily modify to output t; move to cell 7 to output e [<]>------ Move to cell 1 and modify from z to t; cells now contain ttffssen [.>] Move through ttffssen outputing each character once (12 to 19) until empty cell reached <[<]> Move back to cell 1 [..........>] Move through ttffssen outputting each character 10 times (20 to 99) <+. Move to cell 8; modify value to o and output ``` [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` print('zottffssentettffssen'+'t'*20+'f'*20+'s'*20+'e'*10+'n'*10+'o') ``` [Try it online!](https://tio.run/##NcY7DoBACAXA4zzdbfycCaINbOQ1enk0IVYz4@bhtmeO6zROeJxUjRCj/EMH0balQ4soBG39sMIxZ74 "Python 3 – Try It Online") I'm sure this isn't optimal. Idk. [Answer] # [sed](https://www.gnu.org/software/sed/), 59 bytes ``` s/^/ttffssen/ s/./&&&&&&&&&&/g s/.*/zottffssentettffssen&o/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhY3rYv14_RLStLSiotT8_S5ivX19NXgQD8dJKClX5UPU1GSCmOp5etDjICatGAhF4QBAA) [Answer] # [R](https://www.r-project.org/) + [`english`](https://cran.r-project.org/web/packages/english/index.html), 48 50 *Edited per Dominic van Essen's comment* ``` cat(substr(english::as.english(0:100),1,1),sep="") ``` Similar to [chunes' answer](https://codegolf.stackexchange.com/a/252595/87572), this solution uses a library / package to handle integer-to-English mapping, then parses and collapses the resulting vector. [Answer] # [Arturo](https://github.com/arturo-lang/arturo), ~~110~~ ~~65~~ 63 bytes * **-45 bytes**, -2 bytes thanks to Krenium ``` s:"ttffssen"print~{zo|s|te|s||join map split s=>[repeat&10]|o} ``` Readable version: ``` s: "ttffssen" print ~{zo|s|te|s||join map split s => [repeat&10]|o} ``` [Try it Online!](http://arturo-lang.io/playground?pmwgLs) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 29 bytes ``` s["zo"J"ttffssen""te"Js*LTJ\o ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72koLIkY8GCpaUlaboWe4ujlarylbyUSkrS0oqLU_OUlEpSlbyKtXxCvGLyIWqgSmFaAA) A near literal translation of [97.100.97.109](https://codegolf.stackexchange.com/users/113573/97-100-97-109)'s [Python solution](https://codegolf.stackexchange.com/a/252599/78186). [Answer] # [Ruby](https://www.ruby-lang.org/), 54 bytes ``` puts"zo#{a="ttffssen"}te#{a+a.chars.map{|c|c*10}*''}o" ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFipKl@5OtFWqaQkLa24ODVPqbYkFSignaiXnJFYVKyXm1hQXZNck6xlaFCrpa5em6/0/39VPkx1SSqchQWkYQHFWEAqHOTBQT4A "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes Identical to my (and **[@xnor's](https://codegolf.stackexchange.com/users/20260/xnor)**, presumably) Python solution to the **[cross-post](http://golf.shinh.org/p.rb?zottffssentettffssen)** on Anarchy Golf. ``` s='ttffssen' print'zo%ste'%s+s+(('o'+s*10)*8)[-8::-8] ``` [Try it online!](https://tio.run/##bcs9CoAwDEDh3XuU9IeCOpWCJxHHFF2aYrLo5eNkp37TW1575KS6qvIGIqUwY4Wp3VcVeMmwIBgOHKwFgsB@mZ1Pbo8p55gO1Zf@S7DXQBngAexqRx8 "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 40 bytes ``` say+zo,$_=ttffssen,te.$_.s/./$&x10/gre.o ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYK1QnFipoFSVX1KSllZcnJpXkgpnYQFpWEAxFpAKB3lwkK9k/R9omXZVvo5KvC3MFp2SVD2VeL1ifT19FbUKQwP99KJUvfz//wE "Perl 5 – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~106~~ \$\cdots\$ ~~77~~ 75 bytes ``` f(i){for(i=0;i<101;i++)putchar("zottffssentettffssen"[i>99?:i<20?i:i/10]);} ``` [Try it online!](https://tio.run/##bY/dCsIwDIXvfYpQEFrncFO82ObPhfgUzotRWw1qN9aKw7FXt1Y2RWEfBBKSnORwn18ydbRWUmS1zEuKyyDBRRiECXoeK26Gn7KSkkdujJRaC2XEJyM7XEXROsbFNFhjjJMw2LOksagMXDNUlEE9AMdbYgSiKgQ34gBL6JUzPcgedA/ii/qSk6S9nittuh/4SfCzKHd790RN0mo7Tato42JOxvBbz0jTbhelsyMp8TtWQFjbkZT9j6Rq21mMYahT5SQ/nt1kY59cXrKjtv79BQ "C (clang) – Try It Online") *Saved a whopping ~~22~~ ~~28~~ 30 bytes thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)!!!* *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* [Answer] # [Lua](https://www.lua.org/), 68 bytes ``` a='ttffssen'print('zo'..a..'te'..a..a:gsub('.',('%1'):rep(10))..'o') ``` [Try it online!](https://tio.run/##JcoxCoAwDAXQ08hPQIJdCx4mQiuCtKVNFy8fBbc3vHuqu@4wy3mMVND6VYzwVIioCCz90HiOeRAEK2EJ4NhTo7Axf6mC3V8 "Lua – Try It Online") [Answer] # Bash 5.2, ~~45~~ 43 bytes *-2 bytes thanks to Sisyphus* ``` ttffssen echo zo$_\te$_${_//?/&&&&&&&&&&}o ``` Uses the **[brand new](http://git.savannah.gnu.org/cgit/bash.git/tree/NEWS?h=bash-5.2#n86)** (set-by-default) shell option `patsub_replacement`! Look forward to seeing this in many a future Bash golf. ATO is still on 5.1 at the time of writing, so if you want to try it out yourself, the easiest way is with `alpine:edge`: ``` #!/bin/sh podman run --rm -i alpine:edge << 'EOF' apk add bash >/dev/null bash -c 'ttffssen;echo zo$_\te$_${_//?/&&&&&&&&&&}o' EOF ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~29~~ 26 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` `zottffÑA` +h`` +¢®pAÃ+'o ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YHpvdHRmZtFBYAoraGCSYCAroq5wQcMrJ28) Note that there is an unprintable character between the ```` on line 2 ``` `zottffÑA` # U = "zottffssen" # Start building the output with U implicitly h`` # Replace the first 2 characters of U with "te" + # Add that to the output ¢ # Remove the first 2 characters of U ® Ã # For each remaining character pA # Duplicate it 10 times + # Add that to the output +'o # Add "o" to the output # Print implicitly ``` I also tried [another version](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YHR0ZmbRQWAKInpvIitVK2CSYCtVK3BBIPM4IKwrJ28) which does "U repeated 10 times, grouped by index % 8, then joined" for the 20-99 portion, but it didn't golf as well [Answer] # Excel, ~~77~~ 71 bytes Saved 6 bytes thanks to [JvdV](https://codegolf.stackexchange.com/questions/252593/zottffssentettffssen/252739?noredirect=1#comment562329_252739) ``` =LET(a,"ttffssen",CONCAT("zo",a&"te"&a,REPT(MID(a,ROW(1:8),1),10),"o")) ``` This is only slightly more efficient than just typing the 101 characters manually. * `LET(a,"ttffssen"` stores the string `ttffssen` for later repeated use. * `CONCAT("zo",a&"te"&a` combines strings to make the first part. This is only 2 bytes more efficient than hard-coding it. * `MID(a,ROW(1:8),1)` turns the 8 character string into an array of 8 characters. * `REPT(MID(~),10)` repeats each of those characters 10 times. These last two lines are the big byte-saver I missed the first time. Storing the string as `a` is not efficient by itself but it *is* if you later re-use it in the `REPT()` function. * `CONCAT(~,~,~,"o")` add the last letter to the rest of the bits. --- Original 77 byte version: ``` ="zottffssentettffssen"&CONCAT(REPT({"t","f","s","e","n"},5*{4,4,4,2,2}))&"o" ``` --- This **78 byte** alternative looked like it'd be shorter since each character is repeated the same number of times (allowing you to replace an array with a single integer) but it's only a close second: ``` ="zottffssentettffssen"&CONCAT(REPT({"t","f","s"},20))&"eeeeeeeeeennnnnnnnnno" ``` --- This **79 byte** alternative was an attempt at compressing that array of characters but the savings where offset by the bytes required to convert them to strings: ``` ="zottffssentettffssen"&CONCAT(REPT(CHAR(101+{15,1,14,0,9}),5*{4,4,4,2,2}))&"o" ``` [Answer] # [Tcl](http://tcl.tk/), ~~301~~ 57 bytes saved bytes thanks to the comment of @Sisyphus Golfed version provided by me, [try it online!](https://tio.run/##bcsxDoAgDEbhq/whxE0vRBjUFBdCjS0J4fI4GDvxTW95euYx7qqCzkFI0aCakgiVqORbeOiSemDdc8YG37CYyN/pOv@PktVEmpAJMsWwGy8) ``` puts zo[set x ttffssen]te$x[regsub -all . $x &&&&&&&&&&]o ``` Original ungolfed version ``` set a "ttffssen" proc repeat_string {str count} { set result "" for {set i 0} {$i < $count} {incr i} { append result $str } return $result } proc generate_string {a} { set result "" foreach char [split $a ""] { append result [repeat_string $char 10] } return $result } puts "zo${a}te${a}[generate_string $a]o" puts "zottffssentettffssenttttttttttttttttttttffffffffffffffffffffsssssssssssssssssssseeeeeeeeeennnnnnnnnno" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•p≠²δK•ÐST×JŠ"zoÿteÿÿo ``` Port of [*@97.100.97.109*'s Python answer](https://codegolf.stackexchange.com/a/252599/52210), so make sure to upvote him/her as well! [Try it online.](https://tio.run/##yy9OTMpM/f9f71HDooJHnQsObTq3xRvIPjwhOOTwdK@jC5Sq8g/vL0k9vP/w/vz//wE) **Explanation:** ``` .•p≠²δK• # Push compressed string "ttffssen" Ð # Triplicate it S # Convert the top copy to a list of characters T× # Repeat each character 10 times as string J # Join these back together to a single string Š # Triple-swap so the other two strings are on top "zoÿteÿÿo "# Push string "zoÿteÿÿo", where the `ÿ` are automatically filled with # the three strings # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•p≠²δK•` is `"ttffssen"`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 44 bytes ``` zo_te_20$*t20$*f20$*s10$*e10$*no _ ttffssen ``` [Try it online!](https://tio.run/##K0otycxL/P@fqyo/viQ13shARasERKSBiGJDIJEKIvLyueK5SkrS0oqLU/P@/wcA "Retina 0.8.2 – Try It Online") Link is to verbose version of code. Explanation: Mostly run-length compression via `$*`, with a final substitution to save a further 3 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ≔ttffssenθzoθteθFθ×ιχo ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DqaQkLa24ODVPSUehUNOaK6AoM69EQ6kqXwnOQRIuSUUVTssvUgAyFCAiIZm5qcUamToKhgaaCD0gk/7//69blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔ttffssenθ ``` Save the first letters of two/twelve/twenty, three/thirteen/thirty, four(teen)/forty, five/fifteen/fifty, six(teen/ty), seven(teen/ty), eight(een/y) and nine(teen/ty) in a variable. ``` zo ``` Output the first letters of zero and one. ``` θ ``` Output the first letters of two to nine. ``` te ``` Output the first letters of ten and eleven. ``` θ ``` Output the first letters of twelve to nineteen. ``` Fθ ``` Loop over the first letters of twenty to ninety. ``` ×ιχ ``` Output each letter repeated ten times. ``` o ``` Output the first letter of one [hundred]. [Answer] # [simply](https://github.com/ismael-miguel/simply), 64 bytes Just uses the same method as plenty of answers. ``` out"zo"$A="ttffssen""te"$A;each$A as$v;for$_ in0..9out$v;out'o' ``` Outputs the expected string, without any trailing whitespace. # Ungolfed Extremely verbose, almost looking like pseudo-code: ``` Set $initials to the value "ttffssen". Show the values "zo", $initials, "te", $initials. Loop through $initials as $letter. Begin. Loop from 0 to 9 as $i. Begin. Show the contents of $letter. End. End. Show the value "o". ``` More code-y looking: ``` $initials = "ttffssen"; echo "zo", $initials, "te", $initials; each $initials as $letter { for $i in 0..9 { echo $letter; } } echo "o"; ``` All versions do exactly the same. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~19~~ 18 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ╢├╕◄ε╕f♣+∙╢►@♂m*'o ``` [Try it online.](https://tio.run/##y00syUjPz0n7///R1EWPpsx5NHXqo@kt57YC6bRHMxdrP@qYCZKYtsvh0cymXC31/P//AQ) **Explanation:** ``` ╢├ # Push compressed "zo" ╕◄ε # Push compressed "ttff" ╕f♣ # Push compressed "ssen" + # Append the top two together: "ttffssen" ∙ # Triplicate it ╢► # Push compressed "te" @ # Triple-swap the top three values (a,b,c to c,a,b) m # Map over the characters of the top "ttffssen": ♂ * # Repeat the character 10 times 'o '# Push character "o" # (after which the entire stack is joined and output implicitly as result) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 56 bytes ``` "zo$(($a='ttffssen'))te$a$(-join($a|% T*y|%{"$_"*10}))o" ``` [Try it online!](https://tio.run/##bY/BCsIwEETvfsWybElSKOi14kn6B9411C0qpWmbiFrrt0erNSL0nZadYWe2Nhdu7YHL0hNfa84d72EFojPOFYW1XDkO0wTFBHYCDlQBI5ZAecv6nbnz2BmSkvRKfBOFUo5Jk0xO5li9pD6CTXzrozvSFuPF/KGUQY/Z2DwFkuENhTNcf66nMAhj1LDPmrMu/9yQcAM/i38C "PowerShell – Try It Online") ``` "zo " # start s new string with "zo" $( ) # evaluate the subexpression $(...), which ... ($a='ttffssen') # ... sets $a to "ttffssen", and outputs it straight back into the string (because of the additional brackets) te # literal "te" $a # insert $a ("ttffssen") $( ) # insert the results of another subexpression $(...) $a|% T*y # pipe $a to % (alias for ForEach-Object) and call the member ToCharArray() |%{ } # pipe the single characters to % and process them in the scriptblock {...}; loop variable is $_ "$_"*10 # turn the char back into a string, and "multiply" it with 10 -join( ) # join those 10-char-long strings together o # Add the final "one hundred" ``` Output is implicit. [Answer] # [Java (JDK)](http://jdk.java.net/), 92 bytes Interesting challenge! ``` ()->{var s="ottffssente";for(int i=0;i<90;)s+=++i==9?"":s.charAt(i<9?i:i/10%9);return"z"+s;} ``` [Try it online!](https://tio.run/##dZHBToQwEIbv@xSTSUxoyCIeoVbifT15NB4qlN2uLGCnEN0NR28@gr7cvgiWyOKa4H@aTmf@/0u7la1cbrPnvm6eCp1CWkgiuJO6hMNiAaBLq0wuUwUr1wCne2t0uYbcY9ydu2GIrLRudwUFiN5jy5tDKw2QwMraPCdSzgR5XhnP2YEWIdfXUcgZ@cL3tRBRghhTkG6kubWeu0t0rC@vwouIcaNsY0rco0@86/kQN6KOqW2lM9g5YO@H7OERpFkT@4urXmuVWpWBANyfYU3VjPIZ0YzUpHJShfw83ihyyUUwvprrv5FVu6BqbFC7CVuU3gnx/wnn4iOgPxSBemlkQb9bCR4/3zHG49cHstPfdP03 "Java (JDK) – Try It Online") --- I'm really glad that it was possible to beat the trivial solution :') (**95 bytes**) : ``` ()->"zottffssentettffssen"+"t".repeat(20)+"f".repeat(20)+"s".repeat(20)+"eeeeeeeeeennnnnnnnnno" ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` `zo{=`ttffÑA`}{+mpA}o ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YHpvez1gdHRmZtFBYH2SeyttcEF9bw) ``` `zo{=`ttffÑA`}\x92{+mpA}o `zo o :Compressed string, starting with "zo" and ending with "o" { :Interpolate = : Assign to variable U `ttffÑA` : Compressed string "ttffssen" } :End interpolation \x92 :Compressed "te" { } :Interpolate + : Append to U m : Map each character in U p : Repeat A : Ten times ``` [Answer] # Oracle SQL, 97 bytes ``` select 'z'||listagg(substr(to_char(to_date(level,'J'),'jsp'),1,1))from"DUAL"connect by level<=100 ``` Or, a bit more readable: ``` select 'z' || listagg( substr( to_char(to_date(level, 'J'), 'jsp') ,1,1) ) from "DUAL" connect by level<=100; ``` ]
[Question] [ Inspired by [this Stack Overflow post](https://stackoverflow.com/q/70550089/17242583). Given an ascending-sorted array of possibly duplicated integers, your goal is to increment each number by a counter, starting at 0, that resets for each group. Spec: * Any numbers may be negative (but if so, they'll be at the beginning, because the array is sorted), * The array will have at least one element, * There may be any number of integers in one group * The groups of numbers have nothing to do with one another To demonstrate: ``` [1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40] ``` should become this ``` [1, 2, 3, 4, 10, 11, 20, 21, 22, 30, 40, 41, 42, 43] ``` because ``` 1 1 1 1 10 10 20 20 20 30 40 40 40 40 + 0 1 2 3 0 1 0 1 2 0 0 1 2 3 ------- ----- -------- -- ----------- 1 2 3 4 10 11 20 21 22 30 40 41 42 43 ``` ## Test cases ``` input -> output [1, 2, 3] -> [1, 2, 3] [1, 1, 2, 2, 3, 3] -> [1, 2, 2, 3, 3, 4] [0, 0, 0, 0, 0] -> [0, 1, 2, 3, 4] [1, 1, 10, 10, 100, 100, 100, 100] -> [1, 2, 10, 11, 100, 101, 102, 103] [-5, -5, -5, -5, -4, 4, 4, 4, 4, 9, 9] -> [-5, -4, -3, -2, -4, 4, 5, 6, 7, 9, 10] [1, 1, 1, 1, 2, 2] -> [1, 2, 3, 4, 2, 3] ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 3 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Perfect challenge for BQN's *occurence count* builtin. ``` +⟜⊒ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgK+KfnOKKkgoKPuKLiOKfnEbCqCDin6gx4oC/MuKAvzMKMeKAvzHigL8y4oC/MuKAvzPigL8zCjDigL8w4oC/MOKAvzDigL8wCjHigL8x4oC/MTDigL8xMOKAvzEwMOKAvzEwMOKAvzEwMOKAvzEwMArCrzXigL/CrzXigL/CrzXigL/CrzXigL/CrzTigL804oC/NOKAvzTigL804oC/OeKAvzkKMeKAvzHigL8x4oC/MeKAvzLigL8y4p+p) The modifier `⟜` composes two functions. If there is a single argument (as is the case here), the right function is called on that argument, and then the left function is called with that result and the original argument: ``` (f⟜g x) ≡ (x f g x) ``` The builtin `⊒` takes a vector and returns for each element how many times the same value appeared before: ``` (⊒ 1‿1‿1‿10‿10‿100) ≡ 0‿1‿2‿0‿1‿0 ``` The result of `⊒` is then added element-wise to original input by `+`: ``` (1‿1‿1‿10‿10‿100 + 0‿1‿2‿0‿1‿0) ≡ 1‿2‿3‿10‿11‿100 ``` --- Ports of other more interesting answers: * [`⊢+⊒˜-⊐˜`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqiK+KKksucLeKKkMucCgo+4ouI4p+cRsKoIOKfqDHigL8y4oC/Mwox4oC/MeKAvzLigL8y4oC/M+KAvzMKMOKAvzDigL8w4oC/MOKAvzAKMeKAvzHigL8xMOKAvzEw4oC/MTAw4oC/MTAw4oC/MTAw4oC/MTAwCsKvNeKAv8KvNeKAv8KvNeKAv8KvNeKAv8KvNOKAvzTigL804oC/NOKAvzTigL854oC/OQox4oC/MeKAvzHigL8x4oC/MuKAvzLin6k=), [DLosc in Python](https://codegolf.stackexchange.com/a/240425) * [`(⊢+˝=⌜×⊒<⌜⊒)˜`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKKoivLnT3ijJzDl+KKkjzijJziipIpy5wKCj7ii4jin5xGwqgg4p+oMeKAvzLigL8zCjHigL8x4oC/MuKAvzLigL8z4oC/Mwow4oC/MOKAvzDigL8w4oC/MAox4oC/MeKAvzEw4oC/MTDigL8xMDDigL8xMDDigL8xMDDigL8xMDAKwq814oC/wq814oC/wq814oC/wq814oC/wq804oC/NOKAvzTigL804oC/NOKAvznigL85CjHigL8x4oC/MeKAvzHigL8y4oC/MuKfqQ==), [Luis Mendo in MATL](https://codegolf.stackexchange.com/a/240426) [Answer] # [Python 3.8](https://docs.python.org/3/), ~~48~~ 46 bytes *2-byte savings jointly contributed by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748) and [dingledooper](https://codegolf.stackexchange.com/users/88546)* ``` lambda L,j=1:[n-(j:=j-1)-L.index(n)for n in L] ``` [Try it online!](https://tio.run/##XU5BDoIwELz3FRNONNkaKppok/oCfoA9YIAI0UKgB319tRAUTWY2O5PJ7vRPd@1seugHX@uzvxX3S1kgo1ZLlVsRt0q3QnKRbRpbVo/Y8robYNFYZMa7anQjNHKGXBK2hNTQvM8yOIuZEL5YxWSy8H9MIbEn/HBHWOP4xvra57VhhoWyoWToO5VVDP3QWBcHRYjEKSLUk@LcvwA "Python 3.8 (pre-release) – Try It Online") ### Explanation The original 48-byte solution is easier to explain: ``` lambda L:[n+i-L.index(n)for i,n in enumerate(L)] ``` Consider each number \$n\$ in the list together with its index \$i\$. Suppose that we are looking at the \$k^{th}\$ occurrence (0-indexed) of the number \$n\$. We want to add \$k\$ to the number. Since identical numbers are adjacent, the index of the \$0^{th}\$ occurrence of \$n\$ will be at index \$i-k\$. This is the result of `L.index(n)`, meaning \$k\$ is `i-L.index(n)`. Add that value to \$n\$ for each element of the list, and we're done. To get the 46-byte solution, we track the index using a variable instead of `enumerate`, updating it in the list comprehension using Python 3.8's "walrus operator" `:=`. We could track the actual index \$i\$: ``` lambda L,i=-1:[n+(i:=i+1)-L.index(n)for n in L] ``` but it saves a byte to track \$j \equiv -i\$ instead, because we can initialize it to `1` instead of `-1`. [Answer] # [J](http://jsoftware.com/), 9 bytes ``` +i.@#-i.~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tTP1HJR1M/Xq/mty@TnpKURbWds4aIBFNfX16rhSkzPyFdIUDHWQkAEEGyFhYyA2QcH/AQ "J – Try It Online") Basically a port of [DLosc's python answer](https://codegolf.stackexchange.com/a/240425/15469), which fits naturally in the array paradigm. ## how Consider `1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40` * `i.~` Index of each element's first appearance: ``` 0 0 0 0 4 4 6 6 6 9 10 10 10 10 ``` * `i.@#-` Subtract that from `0 1 2 ... n`: ``` 0 1 2 3 0 1 0 1 2 0 0 1 2 3 ``` * `+` Add that to the original input: ``` 1 2 3 4 10 11 20 21 22 30 40 41 42 43 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` t&=XRs+ ``` [Try it online!](https://tio.run/##y00syfn/v0TNNiKoWPv//2hDHQUQMoBhdCIWAA) Or [verify all test cases](https://tio.run/##y00syfmf8L9EzTYiqFj7v0vI/2hDHQUjHQXjWC4QC8IB8ZGFDA1gGJ0AKgEyEIg4LbqmOgoo2ERHARlZAhHCJLirYgE) ### How it works Consider input `[1, 1, 10, 10, 100, 100, 100, 100]` as an example. ``` t % Implicit input. Duplicate % STACK: [1 1 10 10 100 100 100 100], [1 1 10 10 100 100 100 100] &= % Matrix of equality comparisons % STACK: [1 1 10 10 100 100 100 100], [1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1] XR % Upper triangular part, without the diagonal % STACK: [1 1 10 10 100 100 100 100], [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1] s % Sum of each column % STACK: [1 1 10 10 100 100 100 100], [0 1 0 1 0 1 2 3] + % Add, element-wise. Implicit display % STACK: [1 2 10 11 100 101 102 103] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ŒɠḶF+ ``` [Try it online!](https://tio.run/##y0rNyan8///opJMLHu7Y5qb9/3D70UkPd87QjPz/P5or2lBHwUhHwThWB8yE8EACUDEDHQUEQigyNIBhdAKkRtdURwEFm@goICNLIEIyC25tLFcsAA "Jelly – Try It Online") ## How it works ``` ŒɠḶF+ - Main link. Takes a list L on the left Œɠ - Group run lengths Ḷ - Zero based range F - Flatten + - Add elementwise to L ``` For example, take `L = [1, 1, 2, 2, 3, 3]`: * `Œɠ`: `[2, 2, 2]` * `Ḷ`: `[[0, 1], [0, 1], [0, 1]]` * `F`: `[0, 1, 0, 1, 0, 1]` * `+`: `[0, 1, 0, 1, 0, 1] + [1, 1, 2, 2, 3, 3] = [1, 2, 2, 3, 3, 4]` [Answer] # [R](https://www.r-project.org/), ~~40~~ 33 bytes *Edit: -7 bytes thanks to @Giuseppe.* ``` function(a)a+sequence(rle(a)$l)-1 ``` [Try it online!](https://tio.run/##ZZDNCsIwDMfvPkVADw220M6peNAXEQ@jVBiMitM9f43Z2tpaktL@88sHGUNP5xzuk7fv/uFFh9325Z6T89aJcXAkbAZUhjlhhZHQSNghrkFd4Lp8b6scnqWv@sctooQ2JWgJ2SKtY5UCnWsbHb2@yl7MmBTlF8t5WLWXUHhL7X7sRBaLxriikVSTWFIPEo7MGl2PmpZRrYtTeW@I4QM "R – Try It Online") [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 11 bytes ``` gr+>zW(+)nn ``` ## Explanation Most of this is pretty simple * `gr` is "group"; it groups a list into a list of equal segments. * `zW` is "zip with"; it takes a function and uses it to combine two lists pairwise. * `(+)` is "plus"; it adds things. * `nn` is "the natural numbers"; an infinite list of all non-negative numbers in order. * `zW(+)nn` combines the last 3 into a single thing which takes a list and adds every element with its index. The last thing here that links `gr` with `zW(+)nn`. The `+>` operator. This operator has a name it's called "Kleisli composition". Regular composition takes functions `a -> b` and `b -> c` and produces a third function `a -> c`, Kleisli composition does very similar. It takes Kleisli morphisms, which are just a particular kind of function, that maps into a monad. So `a -> m b` where `m` is a monad would be an example of a function from `a` to `m b`, but is a Kleisli morphism from `a` to `b`. So Kleisli composition takes a function `a -> m b` and a function `b -> m c` and produces a function `a -> m c` where `m` is some monad. This is in fact sort of the fundamental essence of a monad, that Kleisli composition forms a category. So how are we using it here? Well we have `gr :: List a -> List (List a)` and `zW(+)nn :: List a -> List a` and the thing we want is `List a -> List a`. A naive way to do it would be to group the whole thing map across each element and the concat everything back up: ``` jn<m(zW(+)nn)<gr ``` However an experienced Haskell golfer will notice that map and then concat is exactly the monad behavior of the `List`. So we could potentially get a bind to do the concat and the map in one go. And now if we look at the types we can see they fit the shape of Kleisli morphisms. So we can actually, compose, map and concat all at once using Kleisli composition. [Answer] # Scala, 43 bytes ``` s=>s.indices.map(i=>s(i)+i-s.indexOf(s(i))) ``` [Try it online!](https://scastie.scala-lang.org/sEZcMudCRjSsj3EGXOuJeQ) A port of [DLosc's great answer](https://codegolf.stackexchange.com/a/240425). Go upvote that! ## My original answer, 48 bytes ``` s=>s.distinct.flatMap(x=>x to x-1+s.count(x.==)) ``` [Try it online!](https://scastie.scala-lang.org/7WxItEEnTQODkMZO1M3iaw) This one gets distinct elements, then for every element `x`, it makes a range from `x` to `x + n`, where `n` is the number of occurrences of `x`. [Answer] # [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~56~~ 54 bytes ``` c;f(int*p,int*q){for(c=0;p-q;*p+=++c)c*=!(*p-*++p-c);} ``` [Try it online!](https://tio.run/##VVDbboMgGL7nKf65bAHBRVfvqHsRZ4wBTEkcUqW7mPHZHbQaLeHj8MN3AJE4IZZF8BZr42LLwnglU9sPWBQpt8mVx5YWlAoi4uIFxzaJKbWJIHxeXrUR3U0qOI9O6v7j8oXQb68l2MHr1J0eHR71n6oddMow8EWQjWvKisCEwLf7xRZHZUT4veCNYeNoKCDlfjoHul9QuvGO3DfJIGIPYV2tOvOTfPVtgsGMUIjw02iDN6VQcGp0tWhGVWZ55U2njMHe0wc@Dzh55E@Y1/j4fRdLKwaHbXbawh2@J8vZbr8eD8rdBuOfjublHw "C (tcc) – Try It Online") * -2 bytes thanks to [pxeger](/users/97857/pxeger) This is a rather straightforward port of my suboptimal [Python answer](https://codegolf.stackexchange.com/a/240429/43394). Takes a pointer to the beginning and end of the array. ## Explanation ``` c; /* int c; (thanks pxeger) */ f( int *p, /* pointer to the first integer */ int *q /* pointer to the last integer */ ) { for ( c=0; /* initialise the increment */ p-q; /* reached the end? (if so, stop) */ /* note: these run out of order */ *p+=++c) c*=!(*p-*++p-c); /* equivalent to: int original_p0 = p[0] - c; // undo increment if (original_p0 != p[1]) { c = 0; // different, so reset counter } p[1] += c; c += 1; p += 1; // move to next p */ } ``` [Answer] # [R](https://www.r-project.org/), 31 bytes ``` function(a)a+seq(!a)-match(a,a) ``` [Try it online!](https://tio.run/##ZZDNDsIgDMfvPkWNFxpLAnNqPOiLGA8N0biDM@p8fsRugCBpCfz760f69F04e395927o7r1i5OXr/FBzRn3jwV0VE6NQyilL0BCsEBegD3CcvqdZDo/SV/3jJpGgTQmGIFukTaxSoGNta6LXV9lLGJui8hI5D6vXBIW3od2P7YLFojGuw0i6SWxQNwRbYa2pR03LqNYlqbI3RP8B "R – Try It Online") Port of [Jonah's J answer](https://codegolf.stackexchange.com/a/240439/67312). Uses 1-based indices but it makes no difference. Test harness taken from [pajonk's answer](https://codegolf.stackexchange.com/a/240433/110034). [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ṁGo→Kg ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY3u@Y/aJnmn////PzraUMdIxzhWB0iDWEA2mGegA4VQGUMDCELBQDldUx0EMtGBQUsdS5hGiLGxsQA "Husk – Try It Online") ``` g # group equal elements ṁ # then map the following onto each group # (concatenating the results): G # scan from left # (arg1=result so far, arg2=next element) o # combination of 2 functions: K # constant function (= arg1) → # incremented ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), ~~26~~ 23 bytes ``` L,dBG€bL€RbFz£+dbL1Xz£_ ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJ8XJ/VHTmiQfIBGU5FZ1aLF2SpKPYQSQEf9fJScxNyklUcHQzp7L////aF1TBQQyUYBBSwXLWAA "Add++ – Try It Online") ## Explained ``` L,dBG€bL€RbFz£+dbL1Xz£_ L, # create a lambda that: d # pushes two copies of the input BG # ... groups the second on consecutive items €bL # ... gets the length of each of those groups €R # ... creates the range [1...n] for each of those lengths (add++ doesn't have a range [0...n) built-in for some reason dang it caird.) bF # ... flattens that list z # and zips it with the original input. This creates a list of items and how much to increment by £+ # now, reduce each item by addition dbL # and push the length of the list, keeping a copy on the stack of the original list 1X # push a list of length(^) 1s z£_ # and subtract that from each item in the other list (this is just to account for the fact that there's no [0...n) built-in) ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~75~~ 66 bytes ``` B+A,[C]-->[A],{C is A+B},B+1+A;[X],{C=X},1+X. _+_-->[]. a-->0+x,!. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30nbUSfaOVZX1y7aMVan2lkhs1jBUdupVsdJ21Db0To6AiRoG1GrY6gdoccVrx0PUhmrx5UIpA20K3QU9f7/T9SINtRRgCMjIIrVcdLUAwA "Prolog (SWI) – Try It Online") This program can be run by calling the grammar `a//0` to parse the input list. The remainder after parsing will be unified with the output list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` +ċṪ$Ƥ ``` A monadic Link accepting a sorted list of integers that yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8/1/7SPfDnatUji35//9/tK6pjgIKNtFRQEaWQBQLAA "Jelly – Try It Online")** ### How? ``` +ċṪ$Ƥ - Link: list of integers, A Ƥ - for prefixes of A: $ - last two links as a monad, f(prefix): Ṫ - pop off the tail from the prefix ċ - count occurrences of that in the remaining prefix + - A add that (vectorises) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~61~~ 60 bytes I wrote this answer to make sure my algorithm was sound, before I [implemented it in C](https://codegolf.stackexchange.com/a/240436/43394). ``` def f(a,b=.5,c=0): for d in a:c*=not d-b;yield d+c;c+=1;b=d ``` [Try it online!](https://tio.run/##VcNLCoAgEADQfaeYpZZF300yJ4kW6SQJoVFuOr0FLSp4bzvD4l0TI80GDJuEwqITGkveJ2D8DgTWwdTrFJ0PQLmSp51XAsq01BlWUiHFbbcusNUegRk2VAJe5bP@bO7t78g5jxc "Python 3 – Try It Online") ## Explanation ``` def f( a, # input list b=.5, # previous value c=0 # consecutive counter ): for d in a: c *= not d-b; # if d and b are different, c = 0 yield d + c; c += 1; b = d # next loop, this'll be the previous value ``` [Answer] # [Perl 5](https://www.perl.org/), 37 bytes ``` s/-?\d+/$&-$f?$i=0:$i++;$i+($f=$&)/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX9c@JkVbX0VNVyXNXiXT1sBKJVNb2xpIaKik2aqoaeqnp/7/b6hgpGDMZagAooEsINtAAQrBooYGEISCuXRNFRDIRAEGLRUsIZogxv3LLyjJzM8r/q@bWAAA "Perl 5 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 38 bytes ``` p=.5 for x;echo $[(c=p-x?0:c+1)+(p=x)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY31Qps9Uy50vKLFCqsU5Mz8hVUojWSbQt0K-wNrJK1DTW1NQpsKzRjIaphmgyiDXQUgEjXFA2b6CggI0swMjSIhWoEAA) I think there might a solution abusing `mv`'s backup functionality like [this answer](https://codegolf.stackexchange.com/a/35950), but I can't work out how. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22 17~~ 10 bytes Saved 7 bytes thanks to ovs! ``` ∊{⊂⍺+⍳≢⍵}⌸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXFyPeucqBOTnVKZl5uQopOUXKZTmZRaWpirkJhZnc4UC1VRXG9pq6z/q3Wp7aL3ho7aJQFbtoRU6MSD6fxpQwaOOrupHXU2PendpP@rd/KhzEUjmUc@O///TFAwVjBSMuUA0iAVkg3kGMAiVMTSAIBQMlDu03hQNmyjAoKWCJUw3xGwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 12 bytes ``` $_+=$h{$_}++ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXttWJaNaJb5WW/v/f11TLgQy4YJBSy7Lf/kFJZn5ecX/dQtyAA "Perl 5 – Try It Online") [Answer] # [Python](https://python.org) + [Pandas](https://pandas.pydata.org/), 40 bytes ``` lambda L:S(L)+S(L).groupby(L).cumcount() ``` The code doesn't run on TIO, since it's `pandas`... But anyway, [here](https://tio.run/##XU7LDoIwELz3KyacaCwGRA@S4Bdw44gcyktJhDZtOfD1SCEomszszkw2uytH8xR9ODVKdJC8r7hG20mhDNJatbXGHKSkie/Ti3dFxZFEqZvQgy3HhxKDLEYry6ErxdAbl06m1kYjRkaQBQwnhjBnq16tTbbQZ/hiNxb4G//LMuRdGH54ZtjjOmO/7XM6JzlphIJ9Em2/dB0RSNXOz1vH4Hg3h6FZHKXTGw) is the code. [Answer] # x86-64 machine code, 15 bytes ``` 3b 06 74 02 31 c9 ad 29 4e fc ff cf e0 f2 c3 ``` [Try it online!](https://tio.run/##VVHLTsMwEDzbX7EYISVpWgpEHFLKj5QcjB@pwXnITquqVX@dsLErWiSPd3Z3xl7ZYl4LMY7cN5BQtqht98ktaEbZR@tUr/hQEtMKUPIQakQ0PSh@yGHjvKli7UuB/zZ9SHRJDp2b9PmfaWqWxHbSy2jgUgb/vKiuKiLVdI@5nNkeIQ4Qc6eQpCu674wEnZh2gDaHKWQcy/c4pN1JBW9@kKZbbN8pnZoNN20Qc1eLHMSWO8gyTPYpPVESOpsK1nB6yuG6lhHPN3hBFP9wXsUDLNq9OapOJzx9vLAwFdGJzSEyfJQwiEH1coXhbg0W42yWQu@woxP2YIChfmOqydLvBp8whvQ8jj9CW177cd68Frjhh63Ro@wv "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the array in RDI and the address of the array of 32-bit integers in RSI. The starting point is after the first 4 bytes. Assembly: ``` .global f repeat: cmp eax, [rsi] # Compare last value and current value je skip # Jump if they are equal f: xor ecx, ecx # (If not equal, or at the start) ECX = 0 skip: lodsd # Put the current value in EAX, and advance the pointer sub [rsi-4], ecx # Subtract ECX from the (same) value dec edi # Count down from the length loopnz repeat # Jump back if not finished, also reducing ECX by 1 ret # Return ``` Here is another solution I found, at 16 bytes, taking the arguments in the opposite order: ``` .global f f: mov eax, edx repeat: cmpxchg [rdi], edx cmovne edx, eax inc edx scasd dec esi jnz repeat ret ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` Ġvẏf+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEoHbhuo9mKyIsIiIsIlsxLDEsMSwxMCwxMCw0LDQsMiwyLDIsMiw1LDYsNiw2XSJd) -1 thanks to lyxal ``` Ġ # Group runs of identical chars vẏf # 0...n each and flatten + # Add to input ``` Port of [caird coinheringaahing's answer](https://codegolf.stackexchange.com/a/240422). [Answer] # JavaScript (ES6), 51 bytes ``` x=>x.map((y,i)=>y+x.reduce((r,z,k)=>r+=z==y&k<i,0)) ``` [Answer] # APL+WIN, 22 bytes Prompts for input vector ``` v+¯1++⌿p×+\p←<⍀v∘.=v←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf5n2ofWG2tqPevYXHJ6uHVMAlLF51NtQ9qhjhp5tGZAHVP8fqJLrfxqXoYKRgjEXiAaxgGwwz0ABCqEyhgYQhIKBcofWmyqgYhMFGLRUsITphpgNAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` IEθ⁺ι№…θκι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyEgp7RYI1NHwTm/FCRTmZyT6pyRD5bK1tRRyNQEAev//6OjDXUUEMgAgo2QsDEQm6Dg2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Does not require the array to be sorted or grouped. Explanation: ``` θ Input array E Map over elements ι Current element ⁺ Plus № Count of ι Current element in …θκ Prefix of input I Cast to string Implicitly print ``` Alternative approach, also 10 bytes, but requires the array to be grouped: ``` IEθ⁺ι⁻κ⌕θι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyEgp7RYI1NHwTczD8jI1lFwy8xLAUlkaoKB9f//0dGGOgoIZADBRkjYGIhNUHBs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over elements ι Current element ⁺ Plus κ Current index ⁻ Minus ⌕ First index of ι Current element in θ Input array I Cast to string Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` r(`(?<=(^|,)(\3,)*)((-)?\d+) #$#2$*1$4$3$* +`1-1 - #(-)?(1*)-? $1$.2 ``` [Try it online!](https://tio.run/##VYzBCsJADETv@Y2NkGwTaXbroaDs0Z8oZQU9ePFQPPrva@tWSpkJ80jITI/383UrB7rmMlGmdL7Q@BGmIQp7JlJOw71hcOgCesMOI3posqmBglvuZJ41ARoeQykmQSKYLDnTzK2s@m2trd4N6Ek2d/JXL319qnVf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` r(` ``` Use right-to-left matching for the whole script, as that allows the matches to be specified slightly more golfily. ``` (?<=(^|,)(\3,)*)((-)?\d+) ``` Match each integer, and count how many times it's been repeated. ``` #$#2$*1$4$3$* ``` Replace each integer with a marker `#`, the repetition count in unary, and the integer in unary. Note that if the integer is positive this already adds the count to the integer. ``` +`1-1 - ``` If the integer was negative then find the difference between it and the count. ``` #(-)?(1*)-? $1$.2 ``` Convert the integer back to decimal, ignoring a trailing `-` sign, which indicates that the count was at least as large as the absolute value of the integer and therefore the result is no longer negative. 28 bytes in [Retina 1](https://github.com/m-ender/retina/wiki/The-Language) if only non-negative integers need to be supported: ``` r`(?<=(\2,)*)(\d+) $.(*_$#1* ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8L8oQcPexlYjxkhHU0tTIyZFW5NLRU9DK15F2VDr/39DHSMdYy5DHRANZAHZBjpQCBY1NIAgFAyRgegBAA "Retina – Try It Online") Link includes test cases. Explanation: ``` r`(?<=(\2,)*)(\d+) ``` From right to left, match each integer, and count how many times it's been repeated. ``` $.(*_$#1* ``` Add the number of repetitions to the integer. [Answer] # [Factor](https://factorcode.org/), 44 bytes ``` [ dup '[ over + swap _ index - ] map-index ] ``` [Try it online!](https://tio.run/##VY/NCsIwEITvfYq5eZBK6x@oDyBevIinUiS0Ww3GNCapWqXPHltrizKzMB/DLmzGEptrt99ttuslzqQlCWS6xIXZEwxdC5IJGRxJkmaCP5nluTRQmqwtlebSYuV5L4QYY4Lqk5rcUMtBr64Ng9b/07T@7MdTdFrU6pe/5yvPRUgLhUGE/EYaQ5g7UziAy5Qe8BHXTyi/pdjNIZlSosTIIBHEtHsD "Factor – Try It Online") Port of @Dlosc's [Python answer](https://codegolf.stackexchange.com/a/240425/97916). `dup '[ ... _ ... ]` slots a copy of the input into the quotation at the `_`. `map-index` is like `map` except it also places the index on the stack in addition to the element. There were a lot of other approaches and attempts; the last three are just longer versions of the above. ``` [ histogram >alist [ first2 over + 1 <range> ] map-concat ] [ [ ] group-by values [ dup length iota v+ ] map-flat ] [ histogram [ over + 1 <range> ] f assoc>map concat ] [ dup '[ _ overd index -rot + - abs ] map-index ] [| l | l [ | n i | n i + l index - ] map-index ] [| l | l [ over + swap l index - ] map-index ] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ü ®í+ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/CCu7Ss&input=WzEsIDEsIDIsIDIsIDMsIDNd) ``` ü - group ® - for each í+ - zip with index then sum ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), ~~66~~ 61 bytes ``` :group_by+:next|:values|:*&(:zip%(:size|:*)|:*&:sum)|:flatten ``` [Try it online!](https://tio.run/##y9ItTar8n2b73yq9KL@0ID6pUtsqL7WipMaqLDGnNLW4xkpLTcOqKrNAVcOqOLMqFcjXBIlZFZfmAhlpOYklJal5/wsU0vQ0og11FBDIAIKNkLAxEJug4FjN/wA "J-uby – Try It Online") ~~Surely there is a way to improve this.~~ Yep, `+` is very useful. [Answer] # [Ruby](https://www.ruby-lang.org/), 37 bytes Requires Ruby version 2.7 or newer. ``` ->a{a.tally.flat_map{[*_1.._1+_2-1]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3VXXtEqsT9UoSc3Iq9dJyEkvicxMLqqO14g319OINteONdA1ja2uhigMLFNKiow11FBDIAIKNkLAxEJug4NhYLiSdRmBkDESxsRCDFyyA0AA) ##### A quick rundown: `->a{X}` is an anonymous lambda function taking a parameter `a` and returning `X`. `tally` returns a hash with each unique number in the input list and the number of times that number appeared in the list. `[*1..4]` returns `[1,2,3,4]`. `flat_map` returns a flattened list from the result of the given `{code block}` being run on each number/count pair returned by `tally`, where `_1` is a placeholder for the number and `_2` is the count. So for example with an array with 5 `2`s, `[*_1.._1+_2-1]` returns `[2,3,4,5,6]`. ]
[Question] [ Your input will be a integer between 1970 and 2090 (inclusive), representing a year. Your program should output the next year on which New Years Day falls on the same day of the week as the input year. **Test Cases:** Below are the sample inputs and outputs ``` 2001 => 2007 2047 => 2058 2014 => 2020 1970 => 1976 1971 => 1982 1977 => 1983 2006 => 2012 ``` **20% Bonus:** Output the day of the week of New Years Day ``` 2001 => 2007 (Mon) 2047 => 2058 (Tue) 2014 => 2020 (Wed) 1970 => 1976 (Thu) 1971 => 1982 (Fri) 1977 => 1983 (Sat) 2006 => 2012 (Sun) ``` **30% Bonus:** Output `Advance Happy New Year, <year>` ``` 2010 => Advance Happy New Year, 2016 ``` **50% Bonus:** Do both above bonuses ``` 2010 => Advance Happy New Year, 2016 (Fri) ``` Write a program which reads input from STDIN or accepts command line arguments, or a function which takes an argument. **Note:** Please add a link to test your code if possible. **Leaderboard:** ``` var QUESTION_ID=66656,OVERRIDE_USER=16196;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/66656/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}#answer-list{padding-right: 100px} ``` ``` <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] ## Mathematica, ~~45~~ ~~37~~ ~~27~~ 24 bytes ``` #+5[6,6,11][[#~Mod~4]]& ``` Improvements thanks to @MartinBüttner (10 bytes), and @ChipHurst (a further 3 bytes). [Answer] # CJam, ~~21~~ ~~12~~ 11 bytes ``` {_9587Cb=+} ``` @martin found a very simple method! Try it [here](http://cjam.aditsu.net/#code=%7B_%5B5%206_B%5D%3D%2B%7D%0A%0A%3AF%3B%0A2001%20FN%0A2047%20FN%0A2014%20FN%0A1970%20FN%0A1971%20FN%0A1977%20FN%0A2006%20FN). EDIT: Thanks, Dennis! [Answer] # gs2, 12 bytes ``` V@¶4☻s%☺♀i50 ``` Translation of my CJam answer. Encoded in CP437 as usual. [Try it online](http://gs2.tryitonline.net/)! [Answer] # JavaScript (ES6), ~~50~~ ~~49~~ 20 bytes (no bonuses) ``` a=>a+[5,6,6,11][a%4] ``` The algorithm by @martin proves to be much smaller, so I went with it. I chose a mathematical approach because JavaScript tends to be verbose. The code is short enough that bonuses only make it longer. Here is my previous answer (49 bytes), and my original answer (50 bytes): `F=(a,b=a)=>((a+--a/4|0)-(b++/4+b|0))%7?F(++a,b):b` `F=(a,b=a)=>(f=c=>(c--+c/4|0)%7)(a)-f(++b)?F(a,b):b` They work by taking the year and calculating a number (0-6) to represent the "starting day of year". Because the date range for this challenge is within the range of years that follow simple leap year rules (no skipping on 2000), it's fairly straightforward to calculate. Then it's just a matter of comparing forward to find years that start with the same value. Recursion proved to be the most concise way to do this. [Answer] # Pyth, ~~14~~ ~~12~~ 11 bytes ``` +QC@"♣♠♠♂"Q ``` The four bytes in the string should be `05 06 06 0B`. EDIT: Thanks, FryAmTheEggman! EDIT: Thanks, Dennis! [Answer] # JavaScript (ES6), 104 bytes - 50% bonus = 52 ``` y=>eval('for(a=0;a!=(b=(new Date(""+y++)+"").slice(0,3));a=a||b)`Advance Happy New Year, ${y} (`')+b+")" ``` ## Explanation ``` y=> eval(` // eval enables for loop without {} or return for( a=0; // a = first day of input year a!= // check if the day of the current year is equal to the first (b=(new Date( // b = day of current year ""+y++)+"") // cast everything as strings! .slice(0,3)); // the first 3 letters of the date string are the day name a=a||b // set a to the day on the first iteration ) // return the string \`Advance Happy New Year, \${y} (\` `)+b+")" ``` ## Test ``` var solution = y=>eval('for(a=0;a!=(b=(new Date(""+y++)+"").slice(0,3));a=a||b)`Advance Happy New Year, ${y} (`')+b+")" ``` ``` <input type="text" id="input" value="2001" /> <button onclick="result.textContent=solution(+input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # Z80 machine code, 12 bytes A Z80 procedure to be stored at `0000h`, called with the input in `HL`, and all other registers clear: ``` .org 0000h ; Bytes ; Explanation ;--------------------------------------------------------------- DEC B ; 05 ; LD B, 6 ; 06 06 ; DEC BC ; 0B ; LD A, 3 ; 3E 03 ; A = 3 AND L ; A5 ; A = input & 3 LD E, A ; 5F ; A = input & 3 DE = input & 3 LD A, (DE) ; 1A ; A = [input & 3] DE = input & 3 LD E, A ; 5F ; A = [input & 3] DE = [input & 3] ADD HL, DE ; 19 ; HL = input + offset RET ; C9 ; ``` The first three instructions are "NOPs", but are indexed as data later in the code. Upon returning, the output is in `HL`. [Answer] # Python 3, ~~140~~ ~~100~~ ~~102~~ ~~84.5~~ 154 \* 0.5 = 77 bytes ~~I could probably write a better solution with Sakamoto's algorithm, but this will do for now~~ I was right. Here's an implementation using Sakamoto's algorithm. ``` def s(y): d=lambda j:(j+j//4)%7 for i in range(y,y+15): if d(i)==d(y-1):return"Advance Happy New Year, %d (%s)"%(-~i,"SMTWTFSuouehranneduit"[d(i)::7]) ``` Explanation: ``` def day_of_the_week(year): return (year + year//4 - 1 + 0 + 1) % 7 # The month code for January is 0, and you add 1 from January *1*. # The -1 is to correct for starting on Saturday # and so that it cancels out the 1 from January 1. def new_years(this_year): # But in Sakamoto's algorithm, if the month is January or February, we must subtract 1. weekdays = "SunMonTueWedThuFriSat" for item in range(this_year, this_year + 15): if day_of_the_week(this_year - 1) == day_of_the_week(item): day = weekdays[day_of_the_week(item)*3 : day_of_the_week(item)*3+3] return "Advance Happy New Year, %d (%s)"%(item + 1, day) # So we subtract from every year we check, including this_year # And add 1 back in at the end # And print the greeting, the year, and the corresponding day of the week ``` [Answer] ## Seriously, ~~35~~ 17 bytes `[5,6,6,11]` trick saves the day. ``` 4,;)%[5,6,6,11]E+ ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=342c3b29255b352c362c362c31315d452b&input=2047) Explanation: ``` 4,;)%[5,6,6,11]E+ 4,;)% push input, input % 4 [5,6,6,11]E push (input % 4)th element of [5,6,6,11] + add to the input ``` Old version: ``` ,;;D`45/*≈7@%`;╝ƒ╗35*r+`╛ƒ╜=`M1@íu+ ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b3b446034352f2af7374025603bbc9fbb33352a722b60be9fbd3d604d3140a1752b&input=2047) Explanation: ``` ,;;D`45/*≈7@%`;╝ƒ╗35*r+`╛ƒ╜=`M1@íu+ ,;; push 3 copies of the input (n) D decrement the top copy of n `45/*≈7@%`;╝ push Sakamoto's algorithm as a function and save a copy in register 1 ƒ╗ call Sakamoto's algorithm function and save result in register 0 35*r+ push [n, n+1, ..., n+14] ` `M map the function: ╛ƒ╜= push Sakamoto's algorithm, call, push 1 if equal to value in register 0 else 0 1@í get the index of the first 1 u+ increment and add n ``` Sakamoto's algorithm: ``` 45/*≈7@% 45/* multiply by 5/4 ≈ floor 7@% mod 7 ``` [Answer] # C, 31 bytes Following the edit to the question that restricts the input range to 1970-2090, this becomes pretty trivial: ``` f(x){return"\5\6\6\13"[x%4]+x;} ``` Without the non-leap century years, there's a simple 5,6,6,11 sequence of intervals for the first repeat of the same day. Complete solution to original problem (not constrained to 2090), 90 bytes: ``` f(x){return(x-1)%100>89&&(x+9)/100%4?"\6\14\5\6\6\6\6\7\14\6"[x%10]+x:"\5\6\6\13"[x%4]+x;} ``` ### Test program: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { while (*++argv) printf("Advance Happy New Year, %d\n", f(atoi(*argv))); return !argc; } ``` # Test run: ``` $ ./66656 2001 2047 2014 1970 1971 1977 2006 Advance Happy New Year, 2007 Advance Happy New Year, 2058 Advance Happy New Year, 2020 Advance Happy New Year, 1976 Advance Happy New Year, 1982 Advance Happy New Year, 1983 Advance Happy New Year, 2012 ``` [Answer] ## R, ~~143~~ 136 \* 0.5 = 68 bytes ``` G=function(y)strftime(paste(y,1,1,sep='-'),'%a') d=seq(y<-scan(),y+14);sprintf("Advance Happy New Year, %i (%s)",d[G(d)==(w=G(y))][2],w) ``` Use `%A` for full day name instead of `%a, depend on desired state. ## R, 120 \* 0.7 = 84 bytes ``` G=function(y)as.POSIXlt(paste(y,1),,"%Y %j")$wday d=seq(y<-scan(),y+14);cat("Advance Happy New Year,",d[G(d)==G(y)][2]) ``` ## R, 90 bytes ``` G=function(y)as.POSIXlt(paste(y,1),,"%Y %j")$wday d=seq(y<-scan(),y+14);d[G(d)==G(y)][2] ``` --- All answers above are derivative work based on @plannapus answer. Using the `;` separator to avoid needing to `source` the file or run it as script on command line. [Answer] # R, 145 bytes -50% -> 72.5 ``` y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x)) ``` Examples: ``` > y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x)) 1: 2006 2: Read 1 item [1] "Advance Happy New Year, 2012 (Sun)" > y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x)) 1: 1977 2: Read 1 item [1] "Advance Happy New Year, 1983 (Sat)" > y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x)) 1: 2014 2: Read 1 item [1] "Advance Happy New Year, 2020 (Wed)" ``` ## R, 97 bytes (without bonus) ``` y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x ``` Indented, with new lines: ``` y = scan() #Takes input from stdin F = function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w") #Year to Weekday x = y+1 while(F(x) != F(y)) x = x+1 x ``` Test cases: ``` > y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x 1: 1977 2: Read 1 item [1] 1983 > y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x 1: 2006 2: Read 1 item [1] 2012 > y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x 1: 2016 2: Read 1 item [1] 2021 ``` [Answer] # VBA, 130 \* 0.50 = 65 Bytes ``` Sub k(y) i=1 Do While Weekday(y+i)<>Weekday(y) i=i+1 Loop MsgBox "Advance Happy New Year," &y+i &WeekdayName(Weekday(y+i)) End Sub ``` VBA makes finding week days so easy.... If only it wasn't so Verbose about it. [Answer] # PHP, 120 ~~139~~ bytes - 50% = 60 bytes A functional approach: ``` $s=strtotime;for($d=date(D,$s(($y=$argv[1]).$_="-1-1"));$d!=date(D,$s(++$y.$_)););echo"Advance Happy New Year, $y ($d)"; ``` Takes one input from command line, like: ``` $ php ahny.php 2001 ``` **The OOP way seems to be longer, as always (143 bytes):** ``` $s=strtotime;for($d=date(D,$s($x=($y=$argv[1])."-1-1"));$d!=date(D,$s(++$y."-1-1")););echo"Advance Happy New Year, $y ($d)"; ``` **Edits** * *Saved* **18 bytes**. Instead of adding one year using the PHP modifier `+1year`, I now simply increment the given year. * *Saved* **1 byte** by storing `-1-1` in a variable. [Answer] # C, score ~~53~~ 52 (104 bytes) ``` f(x){x+="0116"[x%4];printf("Advance Happy New Year, %d (%.3s)",x-43,"MonTueWedThuFriSatSun"+x*5/4%7*3);} ``` Idea borrowed from [Toby Speight](https://codegolf.stackexchange.com/a/66691/25315); added the bonus display of weekday. Shortened the string by shifting the character codes to a more comfortable range. Had to choose the right shifting amount (e.g. 43) to make the short weekday calculation code `x*5/4%7` work. [Answer] ## Jelly, 9 bytes ``` %4*3%7+5+ ``` This is a monadic chain that takes an integer command-line argument as input. It uses my `(x+5+(x%4)**3%7)` algorithm. Try it [here](http://jelly.tryitonline.net/#code=JTQqMyU3KzUr&input=&args=MjAwMQ). Although that's the current version of Jelly, it also works in [this version](https://github.com/DennisMitchell/jelly/tree/c2781762fda4497f099cf62d6a4a548599a0fa0c), which predates the challenge. (Thanks @Dennis!) [Answer] ## Mathematica, 145 \* 50% = ~~74~~ ~~73.5~~ 72.5 bytes ``` d=DateValue;StringForm["Advance Happy New Year, `` (``)",NestWhile[#+1&,(a=#)+1,#!=#2&@@DateObject@{{a},{#}}~d~"DayName"&],{a}~d~"DayNameShort"]& ``` Uses standard date functions. [Answer] ## Pyth, 23 bytes ``` L%+/b4b7.VQIqyby-Q1+1bB ``` Doesn't qualify for any of the bonuses. Try it [here](http://pyth.herokuapp.com/?code=L%25%2B%2Fb4b7.VQIqyby-Q1%2B1bB&input=2006&debug=0). Similar to the pure python answer. ``` - Q = eval(input()) (autoassigned) L - y = lambda b: /b4 - b floordiv 4 + b - + b % 7 - mod 7 .VQ - for b in range(Q, infinate): Iqyby-Q1 - if y(b) == y(Q-1): +1b - print b+1 B - break ``` [Answer] # Java, ~~(1-.2)\*323~~ (1-.5)\*~~350~~ ~~348~~ 339 = ~~258.4~~ ~~175~~ ~~174~~ 169.5 bytes ``` import java.text.*;class D{public static void main(String[]a){long y=new Long(a[0]);int i=0;for(;!s(y).equals(s(y+(++i))););System.out.printf("Advance Happy New Year, %d (%s)",y+i,s(y+i));}static String s(long y){try{return new SimpleDateFormat("E").format(new SimpleDateFormat("d/M/yyyy").parse("1/1/"+y));}catch(Exception e){}return"";}} ``` Ugh. Ungolfed: ``` import java.text.*; class D{ public static void main(String[]a){ long y=new Long(a[0]); int i=0; for(;!s(y).equals(s(y+(++i)));); System.out.printf("Advance Happy New Year, %i (%s)",y+i,s(y+i)); } static String s(long y){ try{ return new SimpleDateFormat("E").format(new SimpleDateFormat("d/M/yyyy").parse("1/1/"+y)); }catch(Exception e){} return""; } } ``` [Try it online!](http://ideone.com/8mltA5) Thanks to @Kenney for pointing out that I could shorten with `new Long` and `printf`! :D [Answer] # GNU coreutils, 52 51 49 bytes (98 bytes program - 50% bonus) ``` seq -f$1-1-1\ %gyear 28|date -f- +'Advance Happy New Year, %Y (%a)'|sed /`date -d$1-1-1 +%a`/!d\;q ``` Input is from command-line argument, and output is to stdout. ### Explanation ``` # generate 28 input years from $1 + 1 onwards (28 is always enough) seq -f '$1-1-1 %g year' 28 | # convert all of these as potential outputs date -f- +'Advance Happy New Year, %Y (%a)' | # Select the first one where the dayname matches that of input year sed "/`date -d$1-1-1 +%a`/!d;q" ``` ### Test run: All locale settings can be `C` or `POSIX`. ``` $ for i in 2001 2047 2014 1970 1971 1977 2006; do ./66656.sh $i; done Advance Happy New Year, 2007 (Mon) Advance Happy New Year, 2058 (Tue) Advance Happy New Year, 2020 (Wed) Advance Happy New Year, 1976 (Thu) Advance Happy New Year, 1982 (Fri) Advance Happy New Year, 1983 (Sat) Advance Happy New Year, 2012 (Sun) ``` Limitation: this only works up to year 2147485519 (though the question is now changed to permit a lower limit). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 28 bytes ``` i0:14+t1tI$YO8H$XO!st1)=f2)) ``` ### Example ``` >> matl i0:14+t1tI$YO8H$XO!st1)=f2)) > 1970 1976 ``` ### Code explained ``` i % input year 0:14+ % vector with that year and the next 14 t1tI$YO % first day of each year 8H$XO % transform into three letters specifying weekday !s % sum those three letters to reduce to unique numbers t1) % get first of those numbers (corresponding to input year) =f2) % find index of second matching ) % index with that to obtain output year ``` [Answer] # [Perl 6](http://perl6.org), ~~70~~ 23 bytes ``` {($^a+1...{[==] ($a,$_).map: {Date.new(:year($_)).day-of-week}})[*-1]} # 70 bytes ``` ``` {($_ X+5,6,6,11)[$_%4]} # 23 bytes ``` usage: ``` for «2001 2047 2014 1970 1971 1977 2006 2010» { printf "%d => %d\n", $_, {($_ X+5,6,6,11)[$_%4]}( $_ ) } ``` ``` 2001 => 2007 2047 => 2058 2014 => 2020 1970 => 1976 1971 => 1982 1977 => 1983 2006 => 2012 2010 => 2016 ``` [Answer] # J, 14 bytes ``` +5 6 6 11{~4&| ``` [Answer] # Japt, 12 bytes ``` U+"♣♠♠♂"cU%4 ``` As with the Pyth answer, the four bytes in the string should be `05 06 06 0B`. [Try it online!](http://ethproductions.github.io/japt?v=master&code=VSsiBQYGCyJjVSU0&input=MjAwMQ==) ``` U+"♣♠♠♂"cU%4 // Implicit: U = input integer "♣♠♠♂" // Take this string. cU%4 // Take the char code at U%4. U+ // Add U. // Implicit: output last expression ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` %4=0,3×-,5S++6 ``` [Try it online!](http://jelly.tryitonline.net/#code=JTQ9MCwzw5ctLDVTKys2&input=&args=MjAwMA) Until today, Jelly had no array indexing, so the above will have to do. Since the latest commit, array indexing has been implemented as `ị`, giving the following solution (**10 bytes**). ``` ị6,6,11,5+ ``` [Try it online!](http://jelly.tryitonline.net/#code=4buLNiw2LDExLDUr&input=&args=MjAwMA) [Answer] # Pyth, 35 bytes ``` Iq%Q4 3=+Q11).?Iq%Q4 0=+Q5).?=+Q6;Q ``` [Try it online.](http://pyth.herokuapp.com/?code=Iq%25Q4+3%3D%2BQ11%29.%3FIq%25Q4+0%3D%2BQ5%29.%3F%3D%2BQ6%3BQ&input=2001&debug=0) [Answer] # C# (6.0) .Net Framework 4.6 173 Bytes - 30% = 121.1 Bytes ``` void n(int y)=>Console.Write($"Advance Happy New Year, {Enumerable.Range(1,15).Select(i=>new DateTime(y+i,1,1)).First(x=>x.DayOfWeek==new DateTime(y,1,1).DayOfWeek).Year}"); ``` [Answer] ## Javascript ES7, 17 bytes ``` a=>a+5+(a%4)**3%7 ``` It's my first time using JS. I found this using a Python script, and I believe it to be optimal. It works because `0**3` is 0 mod 7, `1**3` and `2**3` are both 1, and `3**3` is 6. [Answer] ## Python, 23 bytes ``` lambda a:a+5+(a%4)**3%7 ``` A port of my JavaScript answer. [Answer] # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` ++5%^%Q4 3 7 ``` **[Try it online!](https://pyth.herokuapp.com/?code=%2B%2B5%25%5E%25Q4+3+7&input=2001&test_suite_input=2001%0A2047%0A2014%0A1977&debug=0)** or **[Check out the Test Suite.](https://pyth.herokuapp.com/?code=%2B%2B5%25%5E%25Q4+3+7&input=2001&test_suite=1&test_suite_input=2001%0A2047%0A2014%0A1977&debug=0)** # [Pyth](https://pyth.readthedocs.io), 18 bytes This second approach is mainly a golf of [@wizzwizz4's Pyth answer](https://codegolf.stackexchange.com/a/67510/59487). ``` J%Q4+?q3J11?qJZ5 6 ``` **[Try it online!](https://pyth.herokuapp.com/?code=J%25Q4%2B%3Fq3J11%3FqJZ5+6&input=2001&debug=0)** or **[Check out the Test Suite.](https://pyth.herokuapp.com/?code=J%25Q4%2B%3Fq3J11%3FqJZ5+6&input=2001&test_suite=1&test_suite_input=2001%0A2047%0A2014%0A1977&debug=0)** --- # Explanation ``` ++5%^%Q4 3 7Q - Q means evaluated input and is implicit at the end. %Q4 - Input mod 4. ^ 3 - Cubed. % 7 - Mod 7. +5 - Plus 5 + Q - Plus the input. ``` ]
[Question] [ The goal of this challenge is to print the following tongue twister: ``` She sells seashells by the seashore, The shells she sells are seashells, I'm sure. So if she sells seashells on the seashore, Then I'm sure she sells seashore shells. ``` This is more complicated than just calling your language's `print` equivalent. Since there are a lot of repeated words and phrases, you can greatly decrease the size of your code by using other tactics. **Rules:** * No querying another website which will respond with the full twister * You must include all the punctuation and line breaks in the original text. * You can end with a trailing newline **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!** **Good luck!** [Answer] # [Python 3](https://docs.python.org/3/), ~~166~~ \$\cdots\$ ~~142~~ 135 bytes Saved a whopping ~~13~~ 18 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved 4 bytes thanks to [user253751](https://codegolf.stackexchange.com/users/11600/user253751)!!! Saved a byte thanks to [branboyer](https://codegolf.stackexchange.com/users/94107/branboyer)!!! Saved 7 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! Note: There's lots of unprintables in the following code so please avert your eyes if you're sensitive to such things! :D ``` print("Sh by are,.\nSo if onnore.".translate("| seash|ells|ore,\nThe| sh|e s| I'm sure| the".split("|"))) ``` [Try it online!](https://tio.run/##Hc2xCsMgFIVhtCZ9jYtLIwSXPkXmdMxi4RYFexWvHQK@u7Udz/cPJ5/VJ7r3nkuguujdT1JIeJ5XcVFSTRJcQSHX2R60Jwgv9e@JRqf5N1JBJa22tTji6CouugGjY98wRm6jrwc9PA4dBNxgu72BP2VI9agt5xjGddPGmN6/ "Python 3 – Try It Online") Based on [Netråm](https://codegolf.stackexchange.com/users/87760/netr%c3%a5m)'s [C# answer](https://codegolf.stackexchange.com/a/206623/9481). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~106~~ 103 bytes ``` S230 by41h012 are30,5.¶So if1230 on4n5123ore1h0. 5 I'm1ure 4 the3ore,¶The 3 1eash 2 he10 1 s 0 ells ``` [Try it online!](https://tio.run/##Fcq9DYMwEIbh/pviujQI3flnCGqygCNddEhgSzYpshgDsJiB7pWet@q@5NQ7ZueZPv8gxuIoVfU8xPE85kLLVx4sOeR4V6l6TyMiaHpt8quKANpNHxnO420KD9HUDA6mwhBQA0PXtfV@AQ "Retina 0.8.2 – Try It Online") Explanation: In Retina, a substitution only makes sense if it's long enough `l` for the number `n` of repetitions. The substitution saves `n(l-1)` bytes in the compressed text but costs `l+3` bytes in the replacement stages. This gives the minimum length required to be useful as follows: * 2 repetitions: length > 5 * 3 repetitions: length > 3 * 4 repetitions: length > 3 * 5 repetitions: length > 2 * 6+ repetitions: length > 1 Edit: As @Arnauld pointed out, you can count repetitions from the substitution entries as well. This means that although there were only 5 repetitions of space+s in my previous encoded text, there are also 3 repetitions in the substitutions, thus allowing me to save 3 bytes overall. (@Arnauld himself had only spotted 2 of the 3 repetitions.) [Answer] # JavaScript (ES6), ~~142~~ 141 bytes *Saved 1 byte thanks to @Neil* ``` _=>`246 / I'm5ure/he56/ the4ore, The/5eash/ s/ells`.split`/`.reduce((s,p,i)=>s.split(i).join(p),`S0by35h652 are46,1. So if50on3n1524ore5h6.`) ``` [Try it online!](https://tio.run/##Jc27DsIgGEDhvU/BJiQIvcHW7s51F2z/Cg0CgdbEp0eN8/mSs@mXznOycT/7sEBZh3IbRtX2EnF0OT3FkYAbEJKj3UAfEtDqaoAL0NlwlDk4lxXL0dldccUSLMcMGGcaqSXDmP8JW8K2YD2OhKqpvr87YaRokU7QS9qwagrIrqIOvvONaH@fL2CKlDn4HBwwFx54xYSUDw "JavaScript (Node.js) – Try It Online") ### Compression steps ``` **"ells" -> "6" (9 occurences, saved: 22 bytes)** She s6 seash6 by the seashore, The sh6 she s6 are seash6, I'm sure. So if she s6 seash6 on the seashore, Then I'm sure she s6 seashore sh6. **" s" -> "5" (17 occurences, saved: 14 bytes)** She565eash6 by the5eashore, The5h65he56 are5eash6, I'm5ure. So if5he565eash6 on the5eashore, Then I'm5ure5he565eashore5h6. **"5eash" -> "4" (6 occurences, saved: 18 bytes)** She5646 by the4ore, The5h65he56 are46, I'm5ure. So if5he5646 on the4ore, Then I'm5ure5he564ore5h6. **" the4ore,\nThe" -> "3" (2 occurences, saved: 10 bytes)** She5646 by35h65he56 are46, I'm5ure. So if5he5646 on3n I'm5ure5he564ore5h6. **"he56" -> "2" (4 occurences, saved: 7 bytes)** S246 by35h652 are46, I'm5ure. So if5246 on3n I'm5ure524ore5h6. **" I'm5ure" -> "1" (2 occurences, saved: 5 bytes)** S246 by35h652 are46,1. So if5246 on3n1524ore5h6. **"246 " -> "0" (2 occurences, saved: 1 byte)** S0by35h652 are46,1. So if50on3n1524ore5h6. ``` [Answer] # [///](https://esolangs.org/wiki////), 115 bytes Port of Neil's answer + accepting nph's suggestion. ``` /3/ I'm4ure//2/4eash//1/he40//0/ells//4/ s/S120 by the2ore, The4h041 are20,3. So if4120 on the2ore, Then3412ore4h0. ``` [Try it online!](https://tio.run/##VcoxDoMwDEbhnVN4Y0H8TuJLdKYXAMlVkAKR4jJw@uCOHd/TZ2W1rNY7Eug1HnI1BSJE/QMBWYUBhpZigIAMS4hM203frLE2nYa3o8wSaG0aeUrzsFTaP/Jz9fxzZ/Lr4X7u/QE "/// – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~91~~ 86 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` “SheÌç1€‹€€0, The¬•s‚ÎÌ瀙1,2. So€¬‚ÎÌç1€‰€€0, Then2‚ÎÌç0¬•s.“2Ý…½š¬•s#'í™ì“I'mˆ•“ª1ú: ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcOc4IzUwz2Hlxs@alrzqGEniGxaY6DDFZKReggosKj4UcOsw30gFSCplkWGOkZ6XMH5QA5IGioF0bwBWXOeEVzWAGKQHtAyo8NzHzUsO7T36EKImLL64bVAQw8DOXM81XNPtwEFgcxDqwwP77L6/x8A) **Explanation:** ``` “SheÌç1€‹€€0, The¬•s‚ÎÌ瀙1,2. So€¬‚ÎÌç1€‰€€0, Then2‚ÎÌç0¬•s.“ # Push dictionary string "She sells1 by the0, # The shells she sells are1,2. # So if she sells1 on the0, # Then2 she sells0 shells." 2Ý # Push list [0,1,2] …½š¬•s # Push dictionary string "shore shells" # # Split it on spaces: ["shore","shells"] 'í™ì '# Prepend dictionary string "sea" in front of both: # ["seashore","seashells"] “I'mˆ•“ª '# Append dictionary string "I'm sure" to this list: # ["seashore","seashells","I'm sure"] 1ú # Pad each string with a leading space: # [" seashore"," seashells"," I'm sure"] : # Replace all [0,1,2] with [" seashore"," seashells"," I'm sure"] # (after which the result is output implicitly) ``` [See this 05AB1E tips of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the dictionary strings work. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~79~~ 78 bytes removed trailing newline for -1 byte The text in the tongue twister has many simple patterns. There are enough of them that even "normal" languages can save bytes. However, the *only* thing DEFLATE does is compressing simple patterns with little overhead... ``` 00000000: 0bce 4855 284e cdc9 2906 9289 c519 6056 ..HU(N..).....`V 00000010: 52a5 4209 5018 2c90 5f94 aac3 1502 e441 R.B.P.,._......A 00000020: e58a e1ea 138b 5211 7a74 143c d573 158a ......R.zt.<.s.. 00000030: 4b8b 52f5 b882 f315 32d3 800a 310d cecf K.R.....2...1... 00000040: c334 380f ae13 a105 a602 66ab 1e00 .48.......f... ``` [Try it online!](https://tio.run/##Pc8xSwRBDAXg3l/xSgUJySTZmxEbrQRB5EBbnZmdsdFKr/HPr7O3iw/S5X0k5VTKZ/s4fS0L77kBl9pg0R0hWkOda0JIPCGFmFBdEib2CSB6eLl8IrqiNe@vF5sgw/CQHRY4wVkiQk0M78mQc1WIc0AzE@BI9/RM1/R2NuhuN8IwmseMJi1DNJZBiuCQDwYxrZj9sEJjBVv1SL8/dEvfRLuhw7BybnZHiTGgqzg0zIrInKHCM2qrHXgc/TVhjNC/YcOoqgaN3JGbKLKwI0/jg2nKBdKYsYUsbqdQH7Msfw "Bubblegum – Try It Online") After "writing" this answer, I finally decided to find a way to view the internal representation details of the string (to be specific, information on what characters are printed literally and what substrings are compressed as repetitions via LZ77). I modified `kunzip` (which already had some useful logging capabilities) to log only the information I want to see. This is the result: ``` output 83 S output 104 h output 101 e output 32 output 115 s output 101 e output 108 l output 108 l output 115 s len: 3 dist: 6 ( se) output 97 a output 115 s output 104 h len: 5 dist: 10 (ells ) output 98 b output 121 y output 32 output 116 t len: 3 dist: 23 (he ) len: 5 dist: 17 (seash) output 111 o output 114 r output 101 e output 44 , output 10 output 84 T len: 3 dist: 14 (he ) len: 7 dist: 28 (shells ) output 115 s len: 9 dist: 48 (he sells ) output 97 a output 114 r output 101 e len: 10 dist: 52 ( seashells) output 44 , output 32 output 73 I output 39 ' output 109 m output 32 output 115 s output 117 u output 114 r output 101 e output 46 . output 10 output 83 S output 111 o output 32 output 105 i output 102 f len: 3 dist: 41 ( sh) len: 18 dist: 89 (e sells seashells ) output 111 o output 110 n len: 18 dist: 89 ( the seashore, The) output 110 n len: 9 dist: 58 ( I'm sure) len: 10 dist: 51 ( she sells) len: 8 dist: 34 ( seashor) len: 8 dist: 118 (e shells) output 46 . ``` I think might will be useful for "normal" language answers. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 171 bytes ``` string a=" she sells ",b="shells",c="seashore",d=a+"sea"+b;Write(@$"She{d[4..]} by the {c}, The {b}{a}are sea{b}, I'm sure. So if{d} on the {c}, Then I'm sure{a}{c} {b}.") ``` [Try it online!](https://tio.run/##VYwxC8IwEEb3/orjEFQaM7lJwdW5goM4JOlpA20KuTpIyG@Pl0Vwe@@47zk@OPal8Bp9eIHpEHgkYJomBlS2Q1FhVE6QDI9LJFRDZ9qq2NrTLfqVducN9iOl4X7U@pHBfmCVTnJZNdcKNieTTaxpI6Lgsp2B35F00y/gn2nIsIS/Ufj9yFSONaJxX8oX "C# (Visual C# Interactive Compiler) – Try It Online") The `@` allows for line breaks inside string literals. [Answer] # [Stax](https://github.com/tomtheisen/stax), 83 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÇσGª☺Uë\╠╤↑╡V╦⌐∞┐ü9B@♦1ÖFò╫◄«vâ¬♂ƒQn→↨¥p▬♂♥å↓hb½Z╫Éà½♣µ\╩N>.▄┌bæ¼@3▲¡w8╣▐ù☼ve/h{≈ï░ ``` **[Run and debug it](https://staxlang.xyz/#p=80e547a60155895cccd118b556cba9ecbf813942400431994695d711ae7683aa0b9f516e1a179d70160b0386196862ab5ad79085ab05e65cca4e3e2edcda6291ac40331ead7738b9de970f76652f687bf78bb0&i=&a=1)** ### How? Unpacked: ``` `...`'!/|J `...` - compressed string "She sells..." with '!' where newlines should be '! - a '!' character / - split the compressed string at '!' characters |J - join with newline characters ``` Maybe making a manual compression using the words will be shorter? [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 154 bytes ``` Write(@"S{0}sea{1} by the {2}, The {1} s{0}are sea{1}, I'm sure. So if s{0}sea{1} on the {2}, Then I'm sure s{0}{2} {1}.","he sells ","shells","seashore") ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/vCizJFXDQSm42qC2ODWx2rBWIalSoSQjVaHaqFaHKwTEAIoVA6UTi1IVIEp0FDzVcxWKS4tS9biC8xUy08DyUO35eSja8@BqwYqAwiAD9ZR0lDJAxuXkFCsA2cUZIBaIkZpYnJFflKqk@f8/AA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~108~~ ~~105~~ ~~104~~ ~~96~~ ~~93~~ 92 bytes ``` `S230 by41h012 ‡e30,d. So if1230 4˜123Že1h0.`dd` I'm1¨e`4` e3Že, T”`3`1Á`2`”10`1" s"0`e¥s ``` [Try it online!](https://tio.run/##y0osKPn/PyHYyNhAIanSxDDDwNBI4VB7qrGBTooeV3C@QmaaIUjuUK/JoRlA1qG@VKAavYSUlAQFT/Vcw0MrUhNMEhQOTUgFSelwhRyakmCcYHi4USjBKOHQFEODBEMlhWIlg4TUQ0uL//8HAA "Japt – Try It Online") Port of [the retina answer](https://codegolf.stackexchange.com/a/206622/91267) to [Japt](https://github.com/ETHproductions/japt). ## Explanation ``` S230 by41h012 ‡e30,d. So if1230 4˜123Že1h0. ``` Decompress into the string literal: ``` S230 by41h012 are30,d. So if1230 on4nd123ore1h0. ``` Then we do replacements with: ``` d d` I'm1¨e` // "d" with " I'm1ure" 4` e3Že,\nT”` // "4" with " the3ore,\nThe" 3`1Á` // "3" with "1eash" 2`”10` // "2" with "he10" 1" s" // "1" with " s" 0`e¥s // "0" with "ells" ``` [Answer] # [ink](https://github.com/inkle/ink), ~~129~~ 130 bytes ``` -(i){|The shells|So if|Then I'm sure} {S|s}he sells {|are |}sea{|||shore }shells{& {on|by} the seashore,|{, I'm sure.|.->END}} ->i ``` [Try it online!](https://tio.run/##PYwxDsIwEAR7XnEVASnOE1JBQUOTfMBIh2wRbClHiuj23m5wIlHu7szG9CrFneJZMQYmCTxNgiFTfNYi0a15kywzG@kAscpUhBR@ZoIJewUgIf@i7b4eSXPCYzX6bILf5hba/v86uP56v5gdXB9L@QI "ink – Try It Online") * +1 byte: A period was missing from the end of a line ### Explanation ``` // Thanks to all the new whitespace, this ungolfed code doesn't quite work as is -(i) // A label {|The shells|So if|Then I'm sure} // A sequence - the first time we get here we print nothing, // the second time we print "The shells", // the third time we print "So if", etc {S|s} // Sequences keep outputting their last value once it's been reached he sells // Plain text just gets printed {|are |} sea{|||shore }shells {& {on|by} the seashore,|{, I'm sure.|.->END}} // {& marks a repeating sequence. // Instead of getting stuck on its last value, this it starts over. // On the fourth pass we hit ->END and terminate the program ->i // On the other passes, we get here and go back to the start ``` [Answer] # PowerShell, 158 bytes Because if bash counts then why not... ``` $1="seash" $5="ells" $4="he s$5 " $6=" I'm sure" $2="$1$5" $3="$1`ore" "S$4$2 by the $3,`nThe $5 s$4`are $2,$6.`nSo if s$4$2 on the $3,`nThen$6 s$4$3 $5" ``` [Try it online!](https://tio.run/##VYxNCsIwEIX3nmIYBtwUofnb5QCu2wOkQiRCTSSjiBTPHifduXvve3zvUd6xcorr2hqNHjkunPBA1qMwlmQ8pghMFqQ4j3A@3oFfNUpVHmkkK0n3FEqnOJEhBZcPPEUkPYQ894ckF0yb@S5VsBrInUKeCtyugrtR8p@Rye2D3lVs7Qc "PowerShell – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 110 bytes ``` iS230 by41h012 are30,5. So if1230 on4n5123ore1h0.Í5/ I'm1ure Í4/ the3ore,\rThe Í3/1eash Í2/he10 Í1/ s Í0/ells ``` [Try it online!](https://tio.run/##K/v/PzPYyNhAIanSxDDDwNBIIbEo1dhAx1SPKzhfITPNECSXn2eSZwpk5RelAtXoSR/uNdVX8FTPNSwtSuU63Guir1CSkQqS1YkpCskACRnrG6YmFmcAWUb6GamGBkCGob5CMZAy0E/NySn@/x8A "V (vim) – Try It Online") Port of [@Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [retina answer](https://codegolf.stackexchange.com/a/206622/91267) to [V (vim)](https://github.com/DJMcMayhem/V) [Answer] # PHP, ~~133~~ 126 bytes ``` <?=strtr("S2 s101 by t203,\nT2414e s1 are01,5.\nSo if4e s101 on t203,\nT2n54e s10341.",[" seash",ells,he,ore," sh"," I'm sure"]); ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/75a045e313ee72788372b1a68da5156d0afc8d9a). Use PHP < 7.2 to avoid warnings [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~134~~ ~~133~~ 132 bytes -1 byte thanks @[Titus](https://codegolf.stackexchange.com/users/55735/titus) see similar by [Nail](https://codegolf.stackexchange.com/a/206622/80745) and [Arnauld](https://codegolf.stackexchange.com/a/206652/80745) ``` $d='S0by36h461 are54,2. So if60on3n2615ore6h4.' "154 #he64# I'm6ure# the5ore, The#ells#6eash# s"-split'#'|%{$d=$d-replace$i++,$_} $d ``` [Try it online!](https://tio.run/##ZY/NasMwEITveoolUtEhtokTW4dCINee3Xtx7G1lcCRHqxBC22d31yY/pb1IsDvzzc7gzxjIYt@Po2q3ulrtLxtjC5NDHbAsknUmKg/du1l5t3Frk5c@IAsyLRZ5WYC0aAoJL/pgTgElRIuTIhGvFiVjSRqsyUqgRUpD30Ut9dfTJ2epNg049HWDqlsuE/X2LVQ7ai0EU5DiM6gYTsjZcKhjYyH6ic6f@@BxPHcUMbAnbfC406LiHU2J/NZzJYL9ZbbMg9tVcN3RXc9NH55k6gLEZa7NfwkfYO/@g93d@dfiwy01E3o3/gA "PowerShell – Try It Online") [Answer] # Python, ~~179~~ 176 bytes ``` print"She sells seashells by the seashore,\nThe shells she sells are seashells, I'm sure.\nSo if she sells seashells on the seashore,\nThen I'm sure she sells seashore shells." ``` Trivial algorithm, but nobody’s done it yet. I’m working on a better answer in a different language, but I don’t know if it should be posted in another answer or in this one. Shortening advice accepted, but I’m perfectly fine with just hard-coding it for now. [Answer] # [JavaScript (V8)](https://v8.dev/), 287 bytes Trying a different way of compressing it, in a different language. Feedback is appreciated! ``` function s(){a="kdg by the dj,/nThe g care dg, I'm sure./nSo if cdg on the dj,/nThen I'm sure cdj g.".replace(/c|k/g,function(match){return(match=="c")?"she sells ":"She sells ";});c=a.replace(/d|g/g,function(match){return(match=="d")?"sea":"shells";});return (c.replace(/j/g,"shore"));} ``` [Try it online!](https://tio.run/##hdBNbsIwEAXgfU8x8qa2FJItwrK6Zk0vYCaDSTA22A4SAs4ehp823XXnJ7/5RprenmzG1B3K7DQfx80QsHQxQJbqYo3YtQ7WZyhbgravmvDNDwdoE2dXwfJzD3lIVDdhFaHbAHKfp//2w2@Lf3twtagTHbxFkg1ed42rfpbKvS24VZdEZUjvZIxAob5EZjGT9xnEQqymoG9Ko7ET2V7d/2T7JMmyxTBDT@dVAomT1rPFlZhIKKVv4xHM4zT6A2PI0VPto5NHpcc7 "JavaScript (V8) – Try It Online") [Answer] # Java 8, ~~169~~ 160 bytes ``` v->"".format("S%sells by%s shells she sells are seashells, I'm sure.\nSo if s%1$sells on%2$sn I'm sure s%1$sore shells.","he sells seash"," the seashore,\nThe") ``` Port of [*@IgbyLargeman*'s C# answer](https://codegolf.stackexchange.com/a/206661/52210), so make sure to upvote him as well! -9 bytes thanks to *@branboyer*. [Try it online.](https://tio.run/##PVCxbsMgFNzzFScUq7bkILVr1O4dmsVRlqYDITgmxRDxsKWoyre7YKwscNy7d7rjKkaxuZ5/J2kEEb6Etn8rQNugfCukwi49gSZ4bS@Q5cHpM8ZqG9nHKh4URNASO1i8Yxo3H4zx1vlehJI1BSljCKd7QaBuxvFCZoVPSGS@xudLDxq84kfbOOgWVLyus9LZ4m1N9inJI5fAvMxZzZ62s2UkELrFPwrro913ilXTNmW@DScTMy/Rx9Soj8XLXPL7B6JaWt8pqJ67IfBbHIXSclnawZhq@YDH9A8) (Simply returning as is would be [174 bytes](https://tio.run/##bZDNjsIwDITvPMWIy7YS5AUQ3DnApYjLsgcTAgRSB8VpJbTi2UsK5UeIixWPM7a@OVBNw8Pm2GhHIpiR5f8eYDmasCVtMG9boIjB8g46W3q7QZ2PknrppSKRotWYgzFGUw8n/WJvIMY5SZVkf3utz4g3OQk@mMGKF217H8rTQMG8TANMf0pIFYxaceFht28/X6s9f1nNT@@nx4fHXdVvRi3BqVq7RNCB1C1fmWLI7si/f6C8y@As0ZTKV1Gd0ihmrHTGlXN5F8eluQI).) **Explanation:** ``` v-> // Method with empty unused parameter and String return-type "".format( // Return the following formatted string: "S%sells by%s shells she sells are seashells, I'm sure.\n So if s%1$sells on%2$s n I'm sure s%1$sore shells.", "he sells seash", // Where the first `%s` and all `%1$s` are replaced with "he sells seash" " the seashore,\nThe") // and the second `%s` and all `%2$s` are replaced with " the seashore,\n The" ``` [Answer] # [PicoLisp](https://picolisp.com), ~~160 157 146 142~~ 138 bytes ``` (prin(text"S@1 @2 by the @3, The @5 s@1 are @2,@4. So if s@1 @2 on the @3, Then@4 s@1 @3 @5.""he sells"'seashells'seashore" I'm sure"'shells] ``` Using the template: ``` S1 by the 2, The 5 s1 are 2,4. So if s1 on the 3, Then4 s1 3 5. ``` Where 1 is `"he sells"`, 2 is `"seashells"`, 3 is `"seashore"`, and 4 is `" I'm sure"` [Ideone It!](https://ideone.com/hyfZvI) `{ 14 imaginary interweb points for guessing which syntax highlighting I'm using without peeking }` ### Common Lisp, 160 bytes ``` (format t"S~a~a by the ~a,~%The shells s~3:*~Aare ~a, I'm sure.~%So if s~3:*~A~a on the ~a,~%Then I'm sure s~3:*~a~*~a shells.""he sells ""seashells""seashore") ``` <https://ideone.com/n7zVUm> [Answer] # [Husk](https://github.com/barbuz/Husk), 77 bytes ``` ΓJx'p¨½ΞĿ∫Ẏj5pż¦Sβyεḟ?ṡ,ḣŀḢ¦ṠεΞĿ∫äeŻaŀ`◄,İ'm ṡ→.¶ȮSÏf£2₅Φεḟ?ṡ,ḣnİ'm ṡ→⁸ρΘŀḢ¦. ``` [Try it online!](https://tio.run/##yygtzv7//9xkrwr1gkMrDu09N@/I/kcdqx/u6ssyLTi659Cy4HObKs9tfbhjvv3DnQt1Hu5YfLTh4Y5Fh5Y93Lng3Fao6sNLUo/uTjzakPBoeovOkQ3quQpAtY/aJukd2nZiXfDh/rRDi40eNbWeW4ZiUB6SykeNO843npsBNVvv/38A "Husk – Try It Online") Better than Bubblegum! Husk's string compression is pretty good for this task, a straightforward compressed string would be 82 bytes long. Here, we apply just a single substitution to make it shorter. The compressed string we use here is ``` he sells seashpSpells by the seashore, The shells she sells are seashells, I'm sure. So if spells on the seashore, Then I'm sure spore shells. ``` The structure of the code is: ``` ΓJx'p¨... ¨... The compressed string x'p split on occurrences of the character 'p' ΓJ and joined by interleaving the first substring between the rest ``` What this does in practice is replacing the character 'p' with "he sells seash" everywhere in the rest of the string. This substitution was the one that generated the shortest compressed string among the ones I've tried; multiple substitutions are possible but they didn't seem worth the longer payload. The letter 'p' was chosen because it generates words like "spell" and "spore" in the text that can be compressed very well by Husk. [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), ~~1313~~ 1234 bytes ``` iiissiic{ii}icdddc{{d}iii}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dcdddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}ddsddc{ii}iiic{{d}i}ic{dd}dsdddddc{d}ddcdddc{{d}iii}ic{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dc{i}dddciiic{d}dddc{{ii}}dc{ddd}ddddcdsiiic{ii}cdddc{{d}iii}ic{dd}s{ddd}ic{d}dcdddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}dcdddc{{d}iii}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{{iii}ii}ic{ii}dddc{d}dddc{{d}iii}ic{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dcdddc{i}dddcc{i}dddc{{d}iii}dc{d}ddc{iiii}ic{ddd}ddddc{{i}ddd}c{{d}ii}iiic{dd}s{ddd}iciicdddc{d}dddc{{ii}}ic{{ii}ii}cdsiic{iii}ddc{{d}ii}ic{{iii}iii}dcdddc{{d}iii}c{dd}s{ddd}ic{d}dcdddc{{d}iii}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dcdddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}ds{d}cdc{{d}ii}iic{dd}dsdddddc{d}ddcdddc{{d}iii}ic{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dc{i}dddciiic{d}dddc{{ii}}dc{ddd}ddddcdsiiic{ii}cdddc{i}dc{{d}ii}iic{iiii}ic{ddd}ddddc{{i}ddd}c{{d}ii}iiic{dd}s{ddd}iciicdddc{d}dddc{{d}iii}ic{dd}s{ddd}ic{d}dcdddc{{d}iii}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dc{i}dddciiic{d}dddc{{d}iii}ic{dd}s{ddd}ic{d}dcdddc{i}dddcc{i}dddc{{d}iii}ic ``` [Try it online!](https://tio.run/##xVNBDsMgDHvRHjXFm@YzR5S3M0ICrbZqK2qnHdrQ4sSOCbhdcWd6XEohmRIpmVQKAMkZyvaVAU31hbZWtF1alB5zzTNsfbCJjyRDt3@ypwiQIosmzQSFHNtAlMIOuW/0QdnqYrCrE/ekxHDkC4PMOnLU4OxrZfSEpYkpFzaJMESrw3u9rsyRGlA/mxUbY37WttJjszLGzFVEidESX8w53brTZrNWqc0sJvxvLn0khozDB/Z5zH9r/Vb/c9euo0t5Ag "Deadfish~ – Try It Online") Deadfish, the ungolfing language. [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), ~~1216~~ 1196 bytes ``` iiissiici{ii}cdddci{iii{d}}ciii{dd{i}}cdddd{d}cddd{i}ccddd{i}c{{d{{i}}}}ciii{dd{i}}cdddd{d}cddddcdd{ii}cd{d}cdddcddd{i}ccddd{i}c{{d{{i}}}}c{d{i{i}}}ciii{ii}ci{i{d}}c{iiii{iii}}cdd{d}cdddci{iii{d}}ciii{dd{i}}cdddd{d}cddddcdd{ii}cd{d}cddd{i}ciiicddd{d}cd{{ii}}c{d{{i}}}cdsiiic{ii}cdddci{iii{d}}ciii{dd{i}}cd{d}cdddcddd{i}ccddd{i}c{{d{{i}}}}ciii{dd{i}}cd{d}cdddci{iii{d}}ciii{dd{i}}cdddd{d}cddd{i}ccddd{i}c{{d{{i}}}}ci{ii{iii}}cddd{ii}cddd{d}ci{iii{d}}ciii{dd{i}}cdddd{d}cddddcdd{ii}cd{d}cdddcddd{i}ccddd{i}cd{iii{d}}cdd{d}ci{iiii}c{d{{i}}}c{ddd{i}}cd{dd{ii}}ciii{dd{i}}ciicdddcddd{d}ci{{ii}}c{ii{ii}}cdsiicdd{iii}ci{ii{d}}ciii{ddd{i}}cdddc{iii{d}}ciii{dd{i}}cd{d}cdddci{iii{d}}ciii{dd{i}}cdddd{d}cddd{i}ccddd{i}c{{d{{i}}}}ciii{dd{i}}cdddd{d}cddddcdd{ii}cd{d}cdddcddd{i}ccddd{i}c{{d{{i}}}}cd{dd{i}}cdcii{ii{d}}c{iiii{iii}}cdd{d}cdddci{iii{d}}ciii{dd{i}}cdddd{d}cddddcdd{ii}cd{d}cddd{i}ciiicddd{d}cd{{ii}}c{d{{i}}}cdsiiic{ii}cdddcd{i}cii{ii{d}}ci{iiii}c{d{{i}}}c{ddd{i}}cd{dd{ii}}ciii{dd{i}}ciicdddcddd{d}ci{iii{d}}ciii{dd{i}}cd{d}cdddci{iii{d}}ciii{dd{i}}cdddd{d}cddd{i}ccddd{i}c{{d{{i}}}}ciii{dd{i}}cdddd{d}cddddcdd{ii}cd{d}cddd{i}ciiicddd{d}ci{iii{d}}ciii{dd{i}}cd{d}cdddcddd{i}ccddd{i}ci{iii{d}}c ``` [Try it online!](https://tio.run/##xVNJEsIwDHsRj2KsMuicoydvD7GzToF2CodcateLLCsJtjseDM9bSiRDIIVKRgHgHhUxilsooyeQY2bzvzSrCrX812KIxQy5Bg4Qskd3Hcua8teJGCOn5eAN6Yzo22ybl0ullag6YmMgCJY9EeJ8j0/Vv4qq095ozKzn8vL7KegAEyAnNRRjCRSlplFFxsGmSlkOrkhZGLBuMah2rnIo8LJ7iN4v7NTXXMFa3/X774zWqb1b@9LLGsUpvQA "Deadfish~ – Try It Online") As long as I didn't mess anything up, this should be the shortest possible without `()` and printing in loops. [Answer] # [FEU](https://github.com/TryItOnline/feu), ~~112~~ 111 bytes -1 byte thanks to Neil ``` a/S256 by43h632 are56,1.\nSo if3256 on4n1325ore3h6. m/1/ I'm3ure/2/he36/3/ s/4/ the5ore,\nThe/5/ seash/6/ells/g ``` [Try it online!](https://tio.run/##FYqxDsMgDAX3foW3LlGewOB/6JyOWajk1JUSkKAZ@vWUbKe72/TsPWHxUej1C2zCnlLVKJOb17wU@mx8xZJDdoNK1THNtwMO9LgffFaFhykLGNQQQF/T65vW/DRFHFZTMwh03xvevf8B "FEU – Try It Online") Port of JavaScript answer. [Answer] # [Python 2](https://docs.python.org/2/), ~~175~~ 158 bytes thanks @branboyer for the edit! ``` print"S{0}ells by{1} shells she sells are seashells, I'm sure.\nSo if s{0}ells on{1}n I'm sure s{0}ore shells.".format("he sells seash"," the seashore,\nThe") ``` [Try it online!](https://tio.run/##PY2xDoMwDER/xfJSkKKo7V90hpElSEFBAhvF6YAQ3x6CW5jubN87L2sKTO@clzhSwmZ77n6aBPp1e@0gQYciIOpcPJ377Q18HjPIN3rbUcMwDiAXz1R4ugN64FOVtGgHjrNLFd7VWosGIYX/j5I3HbXBY53zAQ "Python 2 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 155 bytes ``` printf("S%2$s by%1$s shells%3$sare seashells, I'm sure.\nSo if s%2$s on%1$sn I'm sure%3$sshells."," the seashore,\nThe","he sells seashells"," she sells ") ``` [Try it online!](https://tio.run/##RYzBCsIwEER/ZQkNKoSC@gUePXhqj72kdUsidROyERTx22PSSj0NvJk3POhJJ9ffcIhw0ZYAnxHpynDyHt7JB0tx3IpGHiqG/iX3OdjgNLE8VqwDAqNegILz5g78CFh31DiwI/CsOSoarXUxF6UWSkA0vxMXUHXUGsx0Znnxvy9TXrHYpU/6Ag "Scala – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 128 bytes ``` <<Z S${4=${2=he s${1=ells}}${3= seash}$1 }by${5= the$3ore, The} sh$1 s$2 are$3$1,${6= I'm sure}. So if s$4on$5n$6 s$2$3ore sh$1. ``` [Try it online!](https://tio.run/##HYw7DsJADAX7PYULSzRRpM2vig9AHSq6IBkZKWSlNRRg@ezLknbevPmqlDLP17CgDYTWkTAoWiTeNnVH6wmUVxXHCH77oI0EL2HsU@YmXIQdVOqm2MGaK8fYoE0E59MT9J3Z27AkeNyrMaQdxx2nv3wEjmtbyg8 "Zsh – Try It Online") [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 1269 bytes ``` iiissiic{ii}icdddc{ddddddd}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dcdddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}ddsddc{ii}iiic{ddddddddd}ic{dd}dsdddddc{d}ddcdddc{ddddddd}ic{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dc{i}dddciiic{d}dddc{{ii}}dc{ddd}ddddcdsiiic{ii}cdddc{ddddddd}ic{dd}s{ddd}ic{d}dcdddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}dcdddc{ddddddd}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{{iii}ii}ic{ii}dddc{d}dddc{ddddddd}ic{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dcdddc{i}dddcc{i}dddc{ddddddd}dc{d}ddc{iiii}ic{ddd}ddddc{iiiiiii}c{dddddddd}iiic{dd}s{ddd}iciicdddc{d}dddc{{ii}}ic{{ii}ii}cdsiic{iii}ddc{dddddddd}ic{{iii}iii}dcdddc{ddddddd}c{dd}s{ddd}ic{d}dcdddc{ddddddd}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dcdddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}ds{d}cdc{dddddddd}iic{dd}dsdddddc{d}ddcdddc{ddddddd}ic{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dc{i}dddciiic{d}dddc{{ii}}dc{ddd}ddddcdsiiic{ii}cdddc{i}dc{dddddddd}iic{iiii}ic{ddd}ddddc{iiiiiii}c{dddddddd}iiic{dd}s{ddd}iciicdddc{d}dddc{ddddddd}ic{dd}s{ddd}ic{d}dcdddc{ddddddd}ic{dd}s{ddd}ic{d}ddddc{i}dddcc{i}dddc{{iiii}iii}dc{dd}s{ddd}ic{d}ddddcddddc{ii}ddc{d}dc{i}dddciiic{d}dddc{ddddddd}ic{dd}s{ddd}ic{d}dcdddc{i}dddcc{i}dddc{ddddddd}ic ``` [Try it online!](https://tio.run/##xVNbDsMgDDvRDjXhTfM3nxFnZzwSoBpSi8a0ShVpSGLHSfG440n/usVI0nvSCRnoADhBfdJnMoMXswPKNfPp7JSUmFPTi2m8JuXo4nNXigBes0g2Ro1TvoXWwxXSHyQUuFZvHEKFtyRPFeYMwq0K87XQUu1A7QqtjUUhZkhWwgRW5EGa4snOPhubVIOkrdMgL@tZJNWtUyoDbel9HujsV3HbuqYqqaODGH9cVKU1UNkxwLP1//EcJkIs/pA9PMY3 "Deadfish~ – Try It Online") [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 138 bytes ``` O+S=q+=sS=v" shells"4F" se"=tSvT0"sea"F2"S"+" by"+=p" the seashore, The"+v+s+" are"+t+=u" I'm sure. So if"+q+S" onn"3Fp+GuF9+s+Gp 4 9+v"." ``` [Try it online!](https://tio.run/##rVhtc9rGFv4Mv2KtjJEWiUSSuTMtIBgnMR5PHTs1zu0Hm6ayEEYzQlBJOG1j37@ee86@SLuA06YtHxC7e16fPW8i6txH0ZcXSRalm1k8KMpZsnq5GDbVnTS507ai8vd1vEWUJ9m9tlUmS04zi@dJFpM0Jekqu2df1eb1xYd3xKuXk@sr4tfL/x5fkW69HF@8Id/Vy6sPxKuJx@cThfbiw7lC@uHi3fHkB6ugxIKv1v@8/9Dq7HgCSvlRtAjzNq2IVRqwU7IPh9365OLkJzzK4Ah9eYRfg4F@juLZOfx4tNKUwkojeH15ec4o4GsEXvXAFUX31Sk/BNbKuIcw3cSU3mRT2mwys@EG4nAZXBknl2Pry6U9CX61g2ISPBikWMRpWhjdMfyMjaCcPFy7RhGHxtg3JoZtkLvfDTtYG6RcxEARFotVHjvN60Vs2A92AQRhDj9LO9gY5MxckmKTxy@bkxVJ5ob9qz0xyCrLjKPx2j7djL8HjtM16ZLv7QfjpfGFgkFGvwnXvw7zIrYo@dxsJFlJkn6zAbvMFYe055ssgh10hkSwLpdrp1hnN/40@Ow67lO/CWwk4PTwdIH40yJJYwtcB0KLI@AQ47a8zW7ntzn5/HQztWjvhUGZ0kYyJ5YAigQBMV@YlHARcvcAdm8z2LZtvgNKGnFaxOrGk1BMrKSYJfdJKdlBDVroOZWR/Nkmnkts0hYm2jYlHWK6JshCkxJK8rjc5BlPh0fCr5cMBqRLKy@TIl19inMrArFSH3l8JNKGiK0i5thHkwp3kz2uJIHnALpBtb1lBGYdGAGRSoAkm23WFl4GERh1CKyoYOP6bk2zVm6YHG2gAlMr7eTVKwK1AX6DCeuwKHm4lWFeArEAtC0RwpuIUElDWoWl4c@sgm@P8htSvMYocqdgSyR9LTbrNUJJ5f3LHRVYNVIAUEUgypBBt84g4qAyYYwJUzkM1yYZsRrVExtj3MAq1cPqhOEso4QVNu6bhWmApoZpuoqsrut4FD3Cbd0JLvRKAf69WZnAJEs2D9lE8u2z/vjk9Ztffjw4f3upOKFJ8HclHGgiTs8mz/Ee7fJyc0/NyvKzZyzv6rw6yRPWlHyTIWx9VgShaKwKS9YUFoUQX2USEXZ6t5nf@N2pMIKD32I5V2kv1tDHyrkFpODVYZrODJnMwyFko4NCtgVAZFYCeDfh@jW6AfGOdCfRc4yPETHKfBMbEBfVPoYJ7M9DyFc8MLJNmho1BOgnui76AILx8fVqlcLBnQ7As67WXn3Nn/a3O6RaebdtJd5Zucr@VRshEstVmlqqqQ5xHai6f8PkbMdkbFbvjt9fONiyeJzB8uzGc113yjobLOWqSP6IP5YEH/1mHaGKt4gArBz88tn3UeDJzodFB5sfPti3zx9HQDA@Oz9pkznUq36jimyhD0thFK6dNM5Yo1SwskRX4ZhBzj0HxjYjNgLsI/NVDjWTtVzobwOGRR8Ke4KHVTGIluutG2AgJdO6LiBMyRTVFJ@SMlpYbTbTEH2oAYyI@ETYK8xjs0dQCycIEFAciqAw0hZzSogXs5gWsrTPWl5NwYa9Msf2wea9myn9XIcZzBms3HLFV6BYl52H2cyiLfe3OXxqwvdACEI5RPdxmcLgZrXYVbbwgrBLzZKM9pO5ZbHrxOYbLXI0xYEwpZTfcuD295oKD7RL6jvh@lh3YrVA4NGX5iJGom7WVr6u3eH01cmb@gQ5VYQrml@ABoMBwi9Yr9ZxZimKHSM3WLcGq4Il710QjoHvdr9j@6K/W3womIPpM3QKpiKIWAdHJiCH9s1WqANUy@iyYJPYARs7MGGBkgq4QQ7TxaBGCe2A@OrYUMNYe/IjeBL/BiMTJvuOnwfapbPZ/AAL2Q7h@U50gJZUx0Uhf2v2xEy2J46rwif6j3GxWd7BPIIdiMoWhC8e9RC3Uw0l64S9i1mHBTLqubDLDHDCMKLqhUJKjZpUHmB3icNMiH2ugYmOpd6AbOgchcsaBUwMuEIBGr9PDTrSauHpTaeDpFM@ad6y0bYhzTp82S7AHgtWlMhUyxXzN2Uhb7@KCT59cYPsyiBWJqFcYkXG0FKuhw@0Df22@UshUsOMTWQs@fzOcQRlycAvgFHhNmZ5IL306f5QjcJSPsQc6Nk1TFT@RlkU5kOHPUtRI4RfnZ3oVKIdp2XdXs7Urm9nDwrb3XkPDu0dHPi97kNhuce1NqMJVCGMAVqQxSpkYN7CexMS9TsdJk8AxTrm9kVzREst@199FZhX@4E5/CrT4X6mnxmamkN8mGd7vuplX8DOUQ9Ix6tQZrQAvQd51vEgxzyV2P9G6gGUR402CJCU6e3JHVdCzoD2h67A2qdsWmkHDP/mdkKwQ6VLDZj/W7UU80hLtUBPtBFR42mgIousPf4/CjBzghHRRg@26RAlwVCGyzllFfd5aUHagwAKmGLy8J@bPPwXTB5Kkw/22BwIm4XJo@dN5lr3mIzHI6IR@BWFL2vvwT4760XlngxaVUBlXqvOHPRlX1kZqZwiCiv@x7/CL8JXEVPx982eSq1NSNu0QZ2w@vE3j8ByLKpnYKRraHNwlUWMBiVOA41byTDkQArbrti4yT@Be/wvDHVG0bwjatsTbGf6wIekCv/I7x0psJzyaTNQmrOt1q7d6ToTM6tT5cKRNgtNONBbQvvb1dLfVy2PaNVC/Iq7yzb/pJeiYfjEq4iqubHqpGpb9cFD1Gp72F9Zb@Hxzw/Zg1HYIhNA@yyeh5u0BM/kcJJkcJjM2L8PYVTGOTSSyMRxBXcoeeb9B4Wx@VT8l/XE3kCXYZJZFP/SYC8h@Pe65TLF@rD/9OX/ "C (gcc) – Try It Online") Fiiiiiiiine, I'll explain it #### Attempt at explaining it Sorry, the indentation is a little inconsistent... ``` OUTPUT + # substitute " s" with "S" for initial capitalization SUBSTITUTE( = _she_sells_seashells + = _she_sells # inject " se" into "shells" # to get "she sells" SUBSTITUTE( = _shells " shells" 4 0 " se" ) # inject "sea" to get " seashells" = _seashells SUBSTITUTE( _shells 1 0 "sea" ) ) 0 2 "S" ) + " by" + = _the_seashore_the " the seashore,\nThe" + _shells + _she_sells + " are" + _seashells + = _im_sure_so_if " I'm sure.\nSo if" + _she_sells_seashells # shorter to inject than concatenate # to get " on the seashore,\nThen" + SUBSTITUTE( " onn" 3 0 _the_seashore_the ) # Extract "I'm sure" + GET( _im_sure_so_if 0 9 ) + _she_sells # " seashore" + GET( _the_seashore_the 4 9 ) + _shells : "." ``` [Answer] # Bash, 156 bytes ``` i=" I'm sure" h=" she" k=lls l=" seashe"$k s=" seashore" e=" se"$k printf "She$e$l by the$s, The$h$k$h$e are$l,$i. So if$h$e$l on the$s, Then$i$h$e$s$h$k." ``` An expert can probably save some more here. [Answer] # [zlib](https://zlib.net/), 84 bytes Hex dump: ``` 00000000: 78 9c 0b ce 48 55 28 4e cd c9 29 06 92 89 c5 19 x...HU(N..)..... 00000010: 60 56 52 a5 42 09 58 18 28 90 5f 94 aa c3 15 02 `VR.B.X.(._..... 00000020: e2 41 e4 8a e1 ea 13 8b 52 11 7a 74 14 3c d5 73 .A......R.zt.<.s 00000030: 15 8a 4b 8b 52 f5 b8 82 f3 15 32 d3 90 14 22 0c ..K.R.....2...". 00000040: ce cf c3 34 38 0f ae 13 5d 4b 7e 11 cc 56 3d 00 ...48...]K~..V=. 00000050: 3c 70 3a e6 <p:. ``` Raw hex: ``` 789c0bce4855284ecdc929069289c519605652a54209581828905f94aac31502e241e48ae1ea138b52117a74143cd573158a4b8b52f5b882f31532d39014220ccecfc334380fae135d4b7e11cc563d003c703ae6 ``` Or generate this file yourself: ``` openssl zlib < seashells.txt > seashells.zlib ``` You can ~~decompress this file~~ execute this program with: ``` openssl zlib -d < seashells.zlib ``` or, presumably, any of the answers [here](https://unix.stackexchange.com/questions/22834/how-to-uncompress-zlib-data-in-unix). ]
[Question] [ The program must print the alphabet four times: first in the normal alphabetical order, second in the order of a qwerty keyboard, third in the order of a dvorak keyboard, and lastly in reverse alphabetical order. The output should resemble this: ``` abcdefghijklmnopqrstuvwxyz qwertyuiopasdfghjklzxcvbnm pyfgcrlaoeuidhtnsqjkxbmwvz zyxwvutsrqponmlkjihgfedcba ``` The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish. **The catch**: the program must be less than 104 characters, or, in other words, smaller than the length of the alphabet times four. I will accept the answer with the shortest code, unless I see something really clever or interesting that I am more impressed with. EDIT: I will accept the shortest answer on Wednesday, 4/27/2011. EDIT2: **And the winner is** (as usual) [Golfscript](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2234#2234) in 64 chars! [Second place](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2183#2183), which is behind by only three chars, is also in Golfscript, with 67 chars, followed by Bash in [third place](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2197#2197) with 72 chars. But there were a few others I wanted to mention, such as [this one](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2218#2218), which, depending on your definition, only used 52 "characters", and [this one](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2198#2198) where he wrote it in a language he created. There were a [few](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2193#2193) [people](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2284#2284) [who](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times/2190#2190) broke an unwritten rule and did not qualify, but I will mention them just for their way of thinking without the box. [Answer] # Python 2, 97 characters ``` q="qwertyuiopasdfghjklzxcvbnm" a="".join(sorted(q)) print a,q,"pyfgcrlaoeuidhtnsqjkxbmwvz",a[::-1] ``` Sorting QWERTY and converting back from list to string is shorter than the alphabet itself!\* Another option for generating the alphabet in fewer characters than the alphabet itself: ``` print map(chr,range(65,91)) ``` Although this prints a Python list of characters. There's not much to be done here in the way of data compression; jamming the letters into 5 bits only saves 39 characters, which isn't a lot if you then have to un-jam them (and you still have to represent the bytes literally); it looks like zlib (just as an example) saves fewer than 20 bytes; encoding the sequence as a list of deltas to the next letter still takes 5 bits for each delta, because the largest in this sequence is -22: ``` [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, 1, -9, 6, -18, 13, 2, 5, -4, -12, 6, 1, -15, 18, -15, 2, 1, 2, 1, 14, -2, -21, 19, -20, 12, -1, 3, 9, -19, 1, -4, 15, -6, -11, 14, -10, 16, -12, -5, 4, 12, -6, 5, -2, -7, 1, 13, -22, 11, 10, -1, 4, 0, -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, -1, -1] ``` --- \* Although only slightly. [Answer] # PHP, 99 bytes As ISO 8859-1: ``` <?=base64_encode("i·yø!9%z)ª»-ºü1Ë:°z»rº*)jÇ_ä<\½¹æ§'àr¹Z¡ë¢vg²¨äŹ°¿<òÇî¶Êê¦æHâÞuÆÚ"); ``` To reproduce reliably, ``` printf '<?=base64_encode("' >| 4times.php printf abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba | base64 -d >> 4times.php printf '");' >> 4times.php ``` [Answer] ## Ruby 1.9, 88 87 84 80 ``` puts b=[*?a..?z],:qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz,b.reverse ``` [Answer] ## Bash, 82 ``` echo {a..z} echo qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz echo {z..a} ``` [Answer] ## Python, 97 96 "characters" Taking your use of the word "characters" liberally, here's some python that uses 16-bit unicode characters to encode 3 normal characters each. The program is a total of 96 characters, 35 of which are the weirdest unicode characters I've ever seen. ``` for i in range(104):print chr((ord(u'ࠠᒃ⃦ⵉ��割廕��匓�เ᳅ⵉૹ�懬ࣅű傎ᱨ�⤰〷�弙劶��ⶍKᓇࡤ^A'[i/3])>>i%3*5&31)+97), ``` I'm not sure the unicode garbage will come though correctly, so here's a python program to generate the above python program: ``` #!/usr/bin/python import codecs f=codecs.open('alpha.py','w','utf-8') f.write('#!/usr/bin/python\n') f.write('# coding=utf-8\n') f.write('for i in range(104):print chr((ord(u\"') S='''abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcbaa''' for i in xrange(0,104,3): n=32*32*(ord(S[i+2])-97)+32*(ord(S[i+1])-97)+ord(S[i+0])-97 f.write(u'%c'%n) f.write('"[i/3])>>i%3*5&31)+97),\n') ``` [Answer] ### Golfscript, 64 chars ``` "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz".$2%\1$-1% ``` Note: also 64 bytes. Actually, playing with Unicode and base changes seems counterproductive because `base` is too long a keyword. [Answer] ## Bash, 72 ``` echo {a..z} qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz {z..a} ``` EDIT: removed `tr -d`. Credits: Alexander, Roger. [Answer] ## Windows PowerShell, 89 Not particularly good, but at least shorter than the output string: ``` [char[]](65..90) 'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' [char[]](90..65)) ``` Way shorter now that I saw that there is a relaxation on whitespace. And a little shorter still, if I ignore case which I'm allowed to. [Answer] ## Golfscript, ~~76~~, 67 chars ``` 123,97>+."qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"\-1% ``` * changed ruby code to Ventero's [Golfscript alphabet generation](https://codegolf.stackexchange.com/questions/2078/the-alphabet-in-programming-languages/2080#2080). [Answer] ## [CI](https://codegolf.stackexchange.com/questions/585/self-interpreting-interpreter/2163#2163) - 92 chars ``` 'a(1p'z((,0(4d)(.$)<)$)(0c0c.1+2p$.)>)$)qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz ``` CI ("Compiler/Interpreter") is a simple stack-based language I created for the ["Self-Interpreting Interpreter"](https://codegolf.stackexchange.com/q/585/38) challenge ([link to answer](https://codegolf.stackexchange.com/questions/585/self-interpreting-interpreter/2163#2163)). I posted that answer about two hours before this challenge was posted. It's no GolfScript (which I still haven't gotten around to learning), as my goal was to make the interpreter short. This program must be passed to the `ci` interpreter through standard input. The interpreter treats characters after a terminating `)` as input to the program. My language doesn't support string literals, so stdin is taking its place. [Answer] Python 2.7.X - 103 characters ironically... ``` a='abcdefghijklmnopqrstuvwxyz' print a,'qwertyuiopasdfghjklzxcvbnm pyfgcrlaoeuidhtnsqjkxbmwvz',a[::-1] ``` As it turns out, generating the alphabet in python takes more characters than hard-coding it. As does importing the alphabet. Gotta love a readability-centered language sometimes. [Answer] # Lua — 111 characters Beats C and C++! :-) ``` print'abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba' ``` ### "Clever" version in Lua 129 characters ``` q='qwertyuiopasdfghjklzxcvbnm'a={q:byte(1,-1)}table.sort(a)a=q.char(unpack(a))print(a,q,'pyfgcrlaoeuidhtnsqjkxbmwvz',a:reverse()) ``` Whitespaced: ``` q='qwertyuiopasdfghjklzxcvbnm' a={q:byte(1,-1)} table.sort(a) a=q.char(unpack(a)) print(a,q,'pyfgcrlaoeuidhtnsqjkxbmwvz',a:reverse()) ``` [Answer] # C — 133 chars Shortened version from Casey: ``` main(i){char a[105];strcpy(a+26,"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");for(i=0;i<26;)a[i]=a[103-i]=i+++65;puts(a);} ``` Whitespaced: ``` main(i) { char a[105]; strcpy(a+26, "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"); for(i=0;i<26;) a[i]=a[103-i]=i+++65; puts(a); } ``` ### Transposed output Here is a version that does transposed output, for fun. 134 chars. ``` main(i){char*a="qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz";for(i=0;i<26;i++,a++)printf("%c%c%c%c\n",i+65,*a,*(a+25),90-i);} ``` Whitespaced: ``` main(i){ char*a="qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"; for(i=0;i<26;i++,a++) printf("%c%c%c%c\n",i+65,*a,*(a+25),90-i); } ``` Prints: ``` AqmZ BwpY CeyX DrfW EtgV FycU GurT HilS IoaR JpoQ KaeP LsuO MdiN NfdM OghL PhtK QjnJ RksI SlqH TzjG UxkF VcxE WvbD XbmC YnwB ZmvA ``` [Answer] # C - 163 135 chars This doesn't meet the requirements as it clocks in at over 104 characters, but it was fun to make. Maybe someone will have some suggestions. ``` main(i){char a[105];strcpy(&a[26],"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");for(i=0;i<26;)a[i]=a[103-i]=i+++65;puts(a);} ``` This compiles on GCC 4.5.1 (others untested). Yay for omitting #includes, return types, and variable declarations! Hardcoding would've resulted in a shorter program, but that isn't any fun. Whitespaced version: ``` main(i) { char a[105]; strcpy(&a[26], "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"); for(i=0;i<26;) a[i]=a[103-i]=i+++65; puts(a); } ``` ## C - 124 122 lame Here is the lame hardcoded version, and it still doesn't make the cut. ``` main(){puts("abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba");} ``` [Answer] **J** ``` x=:(97+/i.26){a. x 261329910883437428257896643x A.x 247073478763191548160234722x A.x (_1+/-i.26){x ``` My first experience with J. The idea is simply to use the canonical (lexicographic) number of the required permutation; unfortunately this takes more characters than hard-coding it. But if one could find some arithmetic expression (using powers and whatnot) yielding the magic numbers, it could be shortened. [Answer] ## Python, 90 unicode chars ``` #coding:u8 print u"扡摣晥桧橩汫湭灯牱瑳癵硷穹睱牥祴極灯獡晤桧歪穬捸扶浮祰杦牣慬敯極桤湴煳歪扸睭究祺睸當獴煲潰浮歬楪杨敦捤慢".encode("u16")[2:] ``` run at ideone - <http://ideone.com/R2dlI> or codepad - <http://codepad.org/lp77NL9w> [Answer] **Javascript 139 121** new: ``` q='qwertyuiopasdfghjklzxcvbnm' a=q.split('').sort() alert(a.join('')+q+'pyfgcrlaoeuidhtnsqjkxbmwvz'+a.reverse().join('')) ``` old: ``` a=[] a[26]='qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' for(i=0;i<26;i++)a[i]=a[52-i]=String.fromCharCode(i+65) alert(a.join('')) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 26 bytes ``` kak•ṅ« ċ↓U→u°⟇Ȯ≤Ṙ]1biẊ«kzW ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=kak%E2%80%A2%E1%B9%85%C2%AB%0A%C4%8B%E2%86%93U%E2%86%92u%C2%B0%E2%9F%87%C8%AE%E2%89%A4%E1%B9%98%5D1bi%E1%BA%8A%C2%ABkzW&inputs=&header=&footer=) -3 thanks to @A username [Answer] ## PHP 88 bytes ``` <?=$a=join(range(a,z)),~Žˆš‹†Š–žŒ›™˜—•”“…‡œ‰‘’†™˜œ“žšŠ–›—‹‘ŒŽ•”‡’ˆ‰…,strrev($a); ``` [Answer] # J - 69 char ``` 'pyfgcrlaoeuidhtnsqjkxbmwvz'(,~|.)&(,\:~)'mnbvcxzlkjhgfdsapoiuytrewq' ``` Explanation: * `(,\:~) y` - Sort `y` in descending order (`\:~`), and append (`,`) that to `y`. * `x (,~|.) y` - Reverse (`|.`) `y`, and append that to the front of `x`. * `x F&G y` - Execute `(G y) F (G y)`, that is, perform `F` on the results of applying `G` to the arguments. So, all together, we append the alphabet, backwards, to both the Dvorak and reverse-QWERTY strings, then reverse the QWERTY/alphabet one and put that in front of the Dvorak/alphabet one. [Answer] # Bash, 64 I'm very late to the party, but I have a 64 character solution. Program needs to be saved to disk to work ``` echo {a..z} $(sed 1d $0|base64) {z..a};exit ««·+¢¢–¬uø!ŽIsÅËÛžjr~+•ªº'a¶{*ŽL[›ó ``` **How it works:** `{a..z}` and `{z..a}` are pretty self explanatory, but basically that just prints every character in that respective range. `$(sed 1d $0|base64)` outputs the program, ignores the first line, then passes it through a base64 encoder (as some other examples have done). **The reason this is shorter than other similar examples...** ...is because the `{a..z}` ranges are shorter than base64 encodings, so I only need to base64 encode half the string. And because I'm reading the binary data from file rather than storing it in a string, I don't need to escape any character in code. **How to recreate this script:** If the code doesn't copy/paste correctly from Stack Exchange to your text editor then run the following in your command line (shell agnostic): ``` echo 'echo {a..z} $(sed 1d $0|base64) {z..a};exit' > alphabetgolf echo 'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' | base64 -d >> alphabetgolf ``` Then to run: ``` bash alphabetgolf ``` [Answer] # [Deorst](https://github.com/cairdcoinheringaahing/Deorst), 39 bytes ``` EfEuE|'pyfgcrlaoeuidhtnsqjkxbmwvz'EfVE; ``` [Try it online!](https://tio.run/##S0nNLyou@f/fNc211LVGvaAyLT25KCcxP7U0MyWjJK@4MCu7Iim3vKxK3TUtzNX6/38A "Deorst – Try It Online") How on Earth is Deorst beating everything bar Jelly??? ## How it works ``` Ef - Push the lowercase alphabet EuE| - Push 'qwerty…vbnm' '…' - Push that string Ef - Push the alphabet VE; - Reverse and concatenate ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` AžW.•8t”a$äJÚ₁вƒüu¯Cê•AR» ``` [Try it online!](https://tio.run/##ATQAy/9vc2FiaWX//0HFvlcu4oCiOHTigJ1hJMOkSsOa4oKB0LLGksO8dcKvQ8Oq4oCiQVLCu/// "05AB1E – Try It Online") ## Explanation ``` A # Push alphabet žW # Push qwerty string .•8t”a$äJÚ₁вƒüu¯Cê• # Push compressed dvorak string AR # Push reversed alphabet » # Join entire stack with newlines ``` [Answer] ## C++ It's kind of sad when the shortest way to do something in a language is to hard-code it. ``` #include <iostream> int main() { std::cout<<"abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba"; } ``` [Answer] # J (77) ``` (,|.@(26&{.))(,~/:~@(26&{.))'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' ``` Shaved off 3 characters by using a variable: ``` (,|.@a)(,~/:~@(a=.26&{.))'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' ``` Shaved off 2 more characters by using a value-level approach: ``` (|.a),~t,~a=./:~26{.t=.'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' ``` [Answer] # Haskell (95) ``` main=putStr$['a'..'z']++"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"++['z','y'..'a'] ``` # Perl (51) There's no rule that says I can't. ``` use LWP::Simple;print get("http://bit.ly/fGkflf"); ``` [Answer] ## Q (68) ``` .Q.a,"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz",(|:).Q.a ``` Outputs: ``` "abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfg crlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba" ``` Tried to find an improvement on hard-coding the middle two but didn't come up with one. [Answer] # K - 69 char ``` b,a,|b:a@<26#a:"qwertyuiopasdfghjklzxcvbnmpyfgcrlaeouidhtnsqjkxbmwvz" ``` Explanation: * `26#a:` - Assign the two keyboard layouts to `a`, and then take the first 26 characters. * `b:a@<` - Sort `a` and assign that to `b`: `<` provides the permutation for an ascending sort, and `@` lets us index `a` in order to sort it. * `b,a,|` - Append in a row `b`, then `a`, then the reverse (`|`) of `b`. [Answer] # Pyth, 57 ``` G"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"VG ``` Alphabet, string, reversed alphabet. G is the alphabet. Print is implicit. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 60 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⎕A'QWERTYUIOPASDFGHJKLZXCVBNMPYFGCRLAOEUIDHTNSQJKXBMWVZ',⌽⎕A ``` Prints: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ QWERTYUIOPASDFGHJKLZXCVBNMPYFGCRLAOEUIDHTNSQJKXBMWVZ ZYXWVUTSRQPONMLKJIHGFEDCBA ``` Which is permitted as per OP: > > The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish. > > > ]
[Question] [ # Task: **Given an integer number in decimal number system, reduce it to a single decimal digit as follows:** 1. Convert the number to a list of decimal digits. 2. Find the largest digit, D 3. Remove D from the list. If there is more than one occurrence of D, choose the first from the left (at the most significant position), all others should remain intact. 4. Convert the resulting list to a decimal number and multiply it by D. 5. If the number is bigger than 9 (has more than 1 decimal digit), repeat the whole procedure, feeding the result into it. Stop when you get a single-digit result. 6. Display the result. Example: ``` 26364 -> 1. 2 6 3 6 4 2. The largest digit is 6, so D=6 3. There are two occurrences or 6: at positions 1 and 3 (0-based). We remove the left one, at position 1 and get the list 2 3 6 4 4. we convert the list 2 3 6 4 to 2364 and multiply it by D: 2364 * 6 = 14184 5. 14184 is greater than 9 so we repeat the procedure, feeding 14184 into it. ``` We continue by repeating the procedure for 14184 and so on and we go through the following intermediate results, finally reaching 8: ``` 11312 3336 1998 1782 1376 952 468 368 288 224 88 64 24 8 ``` So the result for 26364 is 8. **Input:** An integer / a string representing an integer **Output:** A single digit, the result of the reduction applied to the number. **Test cases:** ``` 9 -> 9 27 -> 4 757 -> 5 1234 -> 8 26364 -> 8 432969 -> 0 1234584 -> 8 91273716 -> 6 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answers in bytes in each language win. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ### Code: ``` [Dg#à* ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f8/2iVd@fACrf//LQ2NzI3NDc0A "05AB1E – Try It Online") ### Explanation ``` [Dg# # While the length of the number is not 1 à # Extract the largest element from the current number * # Multiply it with the leftover number ``` [Answer] # JavaScript (ES6), 49 bytes ``` f=n=>n>9?f(""+n.replace(m=Math.max(...n),"")*m):n ``` Takes input as a string representation of an integer, like `f("26364")`. ## Test Cases ``` f=n=>n>9?f(""+n.replace(m=Math.max(...n),"")*m):n ;["9", "27", "757", "1234", "26364", "432969", "1234584", "91273716"] .forEach(num => console.log(num + " -> " + f(num))) ``` ``` .as-console-wrapper{max-height:100%!important} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` œṡṀẎḌ×ṀD DÇḊ¿ ``` [Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz7c2fBwV9/DHT2HpwOZLlwuh9sf7ug6tP////@WhkbmxuaGZgA "Jelly – Try It Online") -1 thanks to a trick I found in Jonathan Allan's [answer](https://codegolf.stackexchange.com/a/148515/41024). Full program. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` .WtH`*s.-ZKeSZsK ``` Takes input as a String. **[Try it here!](https://pyth.herokuapp.com/?code=.WtH%60%2as.-ZKeSZsK&input=%221234584%22&debug=0)** (Alternative: `.WtH`*s.-ZeSZseS`) # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` .WgHT*s.-`ZKeS`ZsK ``` Takes input as an integer. **[Try it here!](https://pyth.herokuapp.com/?code=.WgHT%2as.-%60ZKeS%60ZsK&input=1234584&debug=0)** ### How it works **16-byter** ``` .WtH`*s.-ZKeSZsK ~ Full program. .W ~ Functional while. While A(value) is truthy, value = B(value). ~ The final value is returned. tH ~ A, condition: Is value[1:] truthy? Is the length ≥ 2? `*s.-ZKeSZsK ~ B, setter. .- ~ Bagwise subtraction, used for removing the highest digit, with... Z ~ The current value Z, and... KeSZ ~ The highest digit of Z (as a String). Also assigns to a variable K. s ~ Casted to an integer. * ~ Multiplied by... sK ~ The highest digit. ` ~ Convert to a String. ``` **18-byter** ``` .WgHT*s.-`ZKeS`ZsK ~ Full program. .W ~ Functional while. While A(value) is truthy, value = B(value). ~ The final value is returned. gHT ~ A, condition: is value (H) ≥ 10? *s.-`ZKeS`ZsK ~ B, setter. .- ~ Bagwise substraction (used for removing first occurrence). `Z ~ The string representation of Z. KeS`Z ~ And the highest (lexicographically) character of Z (highest digit). It also assigns it to a variable called K. s ~ Cast to integer. * ~ Multiply by... sK ~ K casted to int. ``` Being *that close* to Jelly at such type of challenge is very good for Pyth IMO :-) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ ~~13~~ 12 bytes Thanks Zgarb for saving 1 byte. ``` Ω≤9oṠS*od-▲d ``` [Try it online!](https://tio.run/##yygtzv6vcGhb7qOmxv/nVj7qXGKZf2i51qNpm/JTHu5coAtkpPz//z/aUsfIXMfc1FzH0MjYRMfIzNjMRMfE2MjSzBIsYmphomNpaGRubG5oFgsA "Husk – Try It Online") ### Explanation: ``` Ω≤9 Repeat the following function until the result is ≤ 9 d Convert to a list of digits -▲ Remove the largest one od Convert back to an integer oṠS* Multiply by the maximum digit ``` [Answer] # [R](https://www.r-project.org/), ~~99~~ 95 bytes ``` f=function(x)"if"(n<-nchar(x)-1,f(10^(n:1-1)%*%(d=x%/%10^(n:0)%%10)[-(M=which.max(d))]*d[M]),x) ``` [Try it online!](https://tio.run/##JcjtCoIwFIDhexEG58hZuQ@3FnkJXoEYyGQo2BIrWle/pP6977PlHJrwiv453yMkLOZQQLzw6Kdh258LCiCqK8Sz4AJZyWBsEjuyv1XI9sKOQ9u8p9lPh9uQYETsy7Fre6SE@TGs6/IBD46kJVtbElJpkkYZTVpJZ9xP6pMmJ6RVVhikgPkL "R – Try It Online") A recursive function. Adding `f(number)` in the footer can be used to test for other values of `number`. Straightforward implementation, `d` is the list of digits, and `10^(n:2-2)%*%d[-M]` computes the number with the largest digit removed. [Answer] # [Ruby](https://www.ruby-lang.org/), 59 bytes ``` f=->n{m=n.digits.max;n>9?f[n.to_s.sub(m.to_s,"").to_i*m]:n} ``` [Try it online!](https://tio.run/##JYjRDoIgGEZf5R@bWzVkAxSipj0IY00zywuohWw19dkJ6@Y75zuv0H5i7Ku8dpOtHOmG2zB6Ypv30dXq1GtHxsfZEx/ajf0pRmi7yrCz5uCWqBUGJjHIMg1lvEhXcJFQcKaE@sdyn4KiTHJJhSHX5nKHCWYX7AzPMHpAWQd5DVmHIAOdOoZ@hTGwxC8) Recursive lambda function called like `f[26364]`. [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` f=lambda n:`n`*(n<=9)or f(int(`n`.replace(max(`n`),'',1))*int(max(`n`))) ``` **[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qIS9BSyPPxtZSM79IIU0jM69EAyikV5RakJOYnKqRm1gB4mvqqKvrGGpqaoHkYWKamv8LikACaRqWhkbmxuaGZkAhAA "Python 2 – Try It Online")** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` D×Ṁ$œṡṀ$FḌµ>9µ¿ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/l8PSHOxtUjk5@uHMhiOH2cEfPoa12loe2Htr///9/IzNjMxMA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/9/l8PSHOxtUjk5@uHMhiOH2cEfPoa12loe2Htr//3D7o6Y1//9HW@ooGJnrKJibAglDI2MTINfM2AxImRgbWZpZQgRNLYACloZG5sbmhmaxAA "Jelly – Try It Online"). ### How? ``` D×Ṁ$œṡṀ$FḌµ>9µ¿ - Link: number, n ¿ - while: µ - ...condition (monadic): 9 - literal 9 > - loop value greater than (9)? µ - ...do (monadic): e.g. 432969 D - convert to a decimal list [4,3,2,9,6,9] $ - last two links as a monad: Ṁ - maximum 9 × - multiply (vectorises) [36,27,18,81,54,81] $ - last two links as a monad: Ṁ - maximum 81 œṡ - split at first occurrence [[36,27,18],[54,81]] F - flatten [36,27,18,54,81] Ḍ - convert from base 10 389421 (i.e. 360000 + 27000 + 1800 + 540 + 81) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~70~~ ~~67~~ 66 bytes Saved ~~3~~ 4 bytes thanks to nimi! ``` f x|x<10=x|(a,b:c)<-span=<<(>).maximum$show x=f$read[b]*read(a++c) ``` [Try it online!](https://tio.run/##HchLDoIwFADAq3TBopUnsR9ba1pv4AkIMQ@EQKRIQGMX3L1GV5NMj@ujHceUOhK36PjBx40i1OeGuf064@SdoxdWBIxDeIds7Z8fEn2XLS3ey7ra/aSY5w1LAYeJeBJwvt4InZdhehUdI6UFYcAcDXAhFQgttQIlhdX2P8eTAsuFkYbrKn0B "Haskell – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 126 bytes ``` int F(int n){var x=(n+"").ToList();var m=x.Max();x.RemoveAt(x.IndexOf(m));return n>9?F(int.Parse(string.Concat(x))*(m-48)):n;} ``` [Try it online!](https://tio.run/##fY9RS8MwFIWfm19x2VOiNHNt1y6WTUQYCBsOFXwQH0IXR2BNMMlGZey318RO3IP2JeS759xz761sXGkj2p2VagNPn9aJukTnRBdSfZQIVVtuLayM3hhewwFF1nEnK9hruYYllwpbZ3zb6xtws7EEDq1UDuY4vIoc9txAM8XqcjAg9FkvpHWYlKFaTxu65I2nhj6KWu/FrcMNvVdr0Ty845qQ0gi3MwrUjN18B9IVN1acJtI7rSruWwi5wHWcTQi5VuWxjSIvWL0V9MVIJ/wdAs8x83Hobykp/teKcY84StKsJzZP8x45SxOWs/7w8aQngI2SIi1GeXAg7xkOgUE8A9b9kyJA1oE/I9C4oxAdcHJyhkXPuNssFK5@/X6VM8vP7FDKUXREx/YL "C# (.NET Core) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~36~~ ~~35~~ 33 bytes -1 due to updated OP specs. -2 thanks to ngn. Anonymous tacit prefix function. Takes integer as argument. ``` {⍵>9:∇(⌈/×10⊥⊂⌷⍨¨⍳∘≢~⊢⍳⌈/)⍎¨⍕⍵⋄⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71b7SytHnW0azzq6dA/PN3Q4FHX0kddTY96tj/qXXFoxaPezY86ZjzqXFT3qGsRiANUpfmotw8kMxWo@VF3C5CsBZp2aIWlgpG5grmpuYKhkbGJgpGZsZmJgomxkaWZJVjE1MJEwdLQyNzY3NAMAA "APL (Dyalog Unicode) – Try It Online") `{`…`}`a function where `⍵` is the argument:  `⍵>9:` if the argument is greater than 9, then:   `⍕⍵` format (stringify) the argument   `⍎¨` execute (evaluate) each (this gets us the digits as numbers)   `(`…`)` apply the following tacit function on those    `⌈/` the largest digit    `×` times    `10⊥` the base-10 decoding of (collects digits)    `⊂` all the digits    `⌷⍨¨` indexed by each of    `⍳∘≢` the **i**ndices of the number of digits    `≠` differs from    `⊢⍳⌈/` the largest digit's **i**ndex in the entire list of digits   `∇` recurse (i.e. call self) on that  `⋄` else   `⍵` return the argument unmodified [Answer] # [Perl 6](https://perl6.org), ~~45~~ 41 bytes ``` {($_,{$/=.comb.max;S/"$/"//*$/}...10>*).tail} ``` [Test it](https://tio.run/##TY5Pa4QwEMXv8ykGCUVdm6xRoxJceu25PRYWqykI/mONZYv4yXrrF7ObVMqe5s1778fMqC6t2OZJ4aeglYTuCx@qoVZYbItLzsFCWEGroXunXXmVL8whzGHMJ2yllIbHk@9RXTbtut3AJ60mjQW2Ta8m1/v5tqDL3uoDM9tzryWYU6@3noSxLXs8WEjCx3DZ@ccTuqTpx1kHSNR1VJVWtYcLIDYTmt/22LvLA3T@TIP/uw6sW26cHHhqZgxpYkUCIY9iozLgIhK7jCOeC0scbSHJ9iAPeRqloTCb@AU "Perl 6 – Try It Online") ``` {($_,{S/"{.comb.max}"//*$/}...10>*).tail} ``` [Test it](https://tio.run/##TY5PC4JAEMXv8ykGkdCy3Vx1TaTo2rmOQZhuIPiP3KIQP1m3vpi1m0SnefPe@zHTiEvBh2sr8MZJGkP5wElaZwJXQ2eZR6fbUaMjaV2eSJnce4PSqUl7Qoi7WE9tIpO86IcPtJGilbjCIq9Ea9mvp2YseshmVG3bSsagzuw/vRiaIqlwpqEYzvVl5OdrtMy8aq7SQVPcG5FKkdnYAWLeovprjO2/3EHjayr85xrQD5FyImChmj6EgRYBuMzzlVoC4x4fpe@xiGtioQvBcgwil4Ve6HK18Tc "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( # generate the sequence $_, # start the sequence with the input { # generate the rest of the values in the sequence S/ # find and replace (not in-place) "{ .comb.max }" # find the max digit and match against it // # replace it with nothing * # multiply the result with $/ # the digit that was removed } ... # keep generating values until 10 > * # the value is less than 10 ).tail # get the last value from the sequence } ``` [Answer] # [Retina](https://github.com/m-ender/retina), 67 bytes ``` {1`(..+)? 1$&;$& O`\G\d .+((.);.*?)\2 $1 \d+ $* 1(?=.*;(1+))|. $1 1 ``` [Try it online!](https://tio.run/##FckxCoUwEAXA/p0jym4CCxv9BgmS0tILpIighY3Fx07vHnHa@e/Xca61obnUWwuJOE5Q00bTYil5zhvEEQlHsYmzh1HkzcFYKKVJbCR1zI98obWO8AHhF6C@6@GHbuhf "Retina – Try It Online") Link includes the test cases fast enough not to hammer Dennis's server. Explanation: ``` {1`(..+)? 1$&;$& ``` For two digit numbers, this duplicates the number with a `;` separator, prefixing a 1 to the duplicate. For one digit numbers, this prefixes `1;` to the number. ``` O`\G\d ``` Sort the digits of the duplicate. (For one digit numbers, this has no effect.) ``` .+((.);.*?)\2 $1 ``` Find the first occurrence of the largest digit, and delete it, and also the other digits in the duplicate, and the extra 1 that was added earlier. (For one digit numbers, the match fails so this does nothing.) ``` \d+ $* 1(?=.*;(1+))|. $1 1 ``` Multiply the number by the digit. For one digit numbers, this results in the original number, and the loop terminates. Otherwise, the program loops until a single digit is reached. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 123 bytes ``` [Collections.ArrayList]$a=[char[]]"$args" while(9-lt-join$a){$a.remove(($b=($a|sort)[-1]));$a=[char[]]"$(+"$b"*-join$a)"}$a ``` [Try it online!](https://tio.run/##VcyxCsIwEADQ3c8INyRKClGwFOkgrv5ByHAtwUbOnlyCRdRvj5ODH/DenZcoeYpEtfoTE8WxJJ5zcxTB5znlEgB7P04oPgQFKJesVsuUKOrOUrFXTjOgeQE2Em/8iFrD0GvAd2YpxlsXjDn8HXqjYFDrH1UfwFpr57btrnX7Lw "PowerShell – Try It Online") Ooof. PowerShell arrays are immutable, so we need to use the lengthy `[Collections.ArrayList]` casting here so we can call `.remove()` later. Takes input `$args`, converts it to a string, then a `char`-array, then an `ArrayList`. Stores that into `$a`. Then we `while` loop until we're at or below `9`. Each iteration, we're calling `.remove` on the largest element of `$a` (done by `sort` and taking the last element `[-1]`), storing the largest element into `$b` at the same time. This happens to work because the ASCII values sort in the same fashion as the literal digits. Next, we recompute `$a`, again as an `char`-array (and `ArrayList` implicitly), by casting our `$b` (which is currently a `char`) to a string, then an int with `+`, and multiplying that to `$a` `-join`ed into a string (implicitly cast to int). This satisfies the "multiply by D" portion of the challenge. Finally, once we're out of the loop, we put `$a` onto the pipeline and output is implicit. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~177~~ 164 + 18 bytes Saved 13 bytes thanks to @raznagul! ``` int f(int n){string s=n+"",m=s.Max(d=>d)+"";if(n<10)return n;var x=s.ToList();x.RemoveAt(s.IndexOf(m));int y=int.Parse(string.Join("",x))*int.Parse(m);return f(y);} ``` [Try it online!](https://tio.run/##jY/NbsIwEITP@CksTnZbAkkgIXKDVPXUClTUVuqh6sFKHGSJ2KrXoCDEs6c2f701vVizu593ZgsYFNqIdgNSrfDbDqyog7lU3wwVaw6Al0avDK/xHvXAcisLvNWyxAsuFQFr3K/PL8zNCqhDWqksroh/Fd2fxhhyddvv39U5BAvekDKfldQ1mKyIug9H1Ai7MQortuUGN45613MJllDWBK@i1lvxYAkET6oUzUtFakqZN9jl7g2W3IA4BwmetQvlrBpKb36HNWVni4rsKDu0DKHzoY9agV6L4MNIK9zVglQkc/v/mkdpB5BOuogwisddLkmcdDHjOMqS7B9ek2nXqiyM0jgNE48hNBziDA9mOPMqSr0ce@ku83ritd/ri@mR8Wmv1SmXL0cX0iW4ji9evpEg1DugQ/sD "C# (.NET Core) – Try It Online") [Answer] # Java 8, ~~126~~ 104 bytes ``` n->{for(;n>9;n=new Long((n+"").replaceFirst((n=(n+"").chars().max().getAsInt()-48)+"",""))*n);return n;} ``` -22 bytes thanks to *@OlivierGrégoire*. **Explanation:** [Try it here.](https://tio.run/##jZE/T8MwEMX3fopTJxuIpfxp0ihKJRYkJOjSETEY1w0uySWynQKq8tnDtWRFYTnL757v904@ypMM2k7jcf8xqlo6B8/S4HkBYNBre5BKw/ZyBahbrECx64G8IG1YUHFeeqNgCwgljBhszofWsgI3eYEl6k94ogeM4e1yyYXVXU0jH4x1nrRyktW7tI5x0cgvqpX29@4RPeNBsuZkuCMPvyGm1b63CFgMY3Fhd/1bTewpwqk1e2goPtt5a7B6eQXJf7Pvvp3XjWh7Lzpq@RoZCsVyft3jz36UzRiy1ZwjjOJkjpLG6ZwniaM8zf/BWq3nRuVhlMVZmPLpD4fxBw) ``` n->{ // Method with long as both parameter and return-type for(;n>9; // Loop as long as the number contains more than 1 digit n= // Replace the current number with: new Long((n+"").replaceFirst((n=(n+"").chars().max().getAsInt()-48)+"","")) // Remove the first largest digit from the number, *n // and multiply this new number with the removed digit ); // End of loop return n; // Return the result } // End of method ``` [Answer] # C ~~103~~ , ~~95~~ , 90 bytes ``` a,b;t,m;f(n){for(t=m=0,a=b=1e9;a/=10;)if((t=n/a%10)>m)m=t,b=a;n=n>9?f(m*=n/b/10*b+n%b):n;} ``` [Try it online!](https://tio.run/##Hc7NasMwEATgu5/CBAxSvEE/dqyoy7r0OdocJKcqOmhTgm/Gz@7aPQ3MB8NMl59p2rYAEWcomATLJT1fYqZCGgJFMt8egyKjUeYkdmAVGqPlWGShGSIFZOLRvydRzjtGZfQ5ttxE@ca4bhk/Pu@0eLAO3NWBsV0PduiGHvrO@sH/N9dbD95Y1zkzgF6xKiGzkEt1nNkX8h1z28rq95V5TuLUPOrLWDePLz7BoZDEEVJirVRdrdsf) [Answer] # Java 8: 115 bytes -10 bytes thanks to Jo King Unfortunately you can't call a lambda function recursively, so an extra 11 bytes is needed for the method header. I am aware there is a shorter Java answer that loops instead, but I decided to come up with this on my own. ``` long f(long n){int m=(n+"").chars().max().getAsInt()-48;return n>9?f(new Long((n+"").replaceFirst(""+m,""))*m):n;}; ``` [Try it online](https://tio.run/##LU5Na8JAFLz7K5ac3tMm4Ae1NrSlF0HQk0fp4TVu0k13X8Lui7aE/Pa4iJcZmGE@arpQ2rSa6/PvWFgKQR36ICSmUKNtuFIl3ImxNyzKvQHPkgSz4od8AMwc/UWstHyGHQtgunrJvZbOs@L3zUcJrK9qHxvgEfS6tVTorfFBIElm7imqOHX4yvmQj233beP248KlMWflyDAcxRuuTl@KfBWwnxz/g2iXNZ1kbXTEMpSwmS/Wy/X8GTGfDMN4Aw) [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 86 bytes ``` until(.<10;"\(.)"|(./""|max)as$v|index($v)as$x|.[:$x]+.[1+$x:]|tonumber*($v|tonumber)) ``` Expanded ``` until( .<10 # until number is below 10 ; "\(.)" # convert to string | (./""|max) as $v # find largest digit, call it $v | index($v) as $x # find index of digit | .[:$x]+.[1+$x:] # remove digit | tonumber*($v|tonumber) # convert back to number and multiply by $v ) ``` [Try it online!](https://tio.run/##PcvNEoIgFIbhPVfhmAvNIAHFn5puxFzY5MJG0RSMBdcemTru3mfOd15vk56sA7xZKSDxWiGIoy0jgAkN104AYZTtCClJ2fYbLLMo2Y8pJjGNMVvIgDaSi7px0RUHF/vuIs/WLjrbtm5L5ZWjM@maPyvlOtNfSqM8c1Thoxz7jsoKLTou20c1HOfFDs8z5tv1ou74aCDksmlgzXspZgzlB3ZSzPgB "jq – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 41 + 1 (`-p`) = 42 bytes ``` $m=(sort/./g)[-1];s/$m//;($_*=$m)>9&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/18l11ajOL@oRF9PP10zWtcw1rpYXyVXX99aQyVey1YlV9POUk2tKDUl//9/IzNjM5N/@QUlmfl5xf91fU31DAwN/usWAAA "Perl 5 – Try It Online") [Answer] # Lua, ~~137~~ 108 bytes ``` function f(n)while n>9 do b="0"g=b.gsub g(n,".",function(m)b=math.max(m,b)end)n=b*g(n,b,"",1)end print(n)end ``` Thanks to Jonathan S for golfing off 29 bytes. [Try it online!](https://tio.run/##RYxBDoMgFET3PQVhBQ0aAQVZ0LtIFTWRb9Nq2ttT1Dbu3sy8zLQ2MfoV7ss4A/IE6HsYpw7BzaB2Rs7iAvfW5f1rdagnwHCO2d8ngTobmmXIQ/MhgTnaQUvBuutmOoYx41uFHs8RlvSdOHpiKMoyZC6eCL1jmVBXB1eJuZDlHurNUVKdqZTCqOOg@JlVfc6GCy01V3uh4hc) [Answer] # [D](https://dlang.org/), ~~188~~ ~~186~~ 185 bytes ``` import std.conv,std.algorithm;T f(T,U=string)(T u){if(u<10)return u;T[]r;u.text.each!(n=>r~=n.to!T-48);T m=r.maxElement;U s;r.remove(r.maxIndex).each!(n=>s~=n.to!U);return f(m*s.to!T);} ``` [Try it online!](https://tio.run/##TY9BS8NAEIXPza/Y3makLkY9CGO8efC@OYmH0EzaheyszO7GQKl/PcZS0MODBw@@x9cviw@fUbNJubf7KNPut3TjIarPx0DODOB2bZOyejkgOFPw5Acoz/UdKueiYgq59w@lYjPP2XK3P25Bmhf9bsTmuHW3j0@4gkKjNnTz68iBJVNrEqlVDnFiuCxv0vOMf4B0BbRI16cBwk26MJHOyxR9b0LnBdCcqs0/kTU@UrX5WiV4FBigrh/qe0SqzssP "D – Try It Online") I hate lazy evaluation, so much. Any tips are welcome! [Answer] ## Lua, 154 Bytes I should have some ways to golf this down, I'm experimenting right now. ``` n=...z=table while n+0>9 do t={}T={}n=n..''n:gsub(".",function(c)t[#t+1]=c T[#T+1]=c end)z.sort(t)x=t[#t]z.remove(T,n:find(x))n=z.concat(T)*x end print(n) ``` [Try it online!](https://tio.run/##HYtLCoMwFAD3OYXowqTKoz@ECukpshMXGmMN2Jeiz1ZSeva0djEwi5lxaUJACQBeUtOOhr0GO5oIs/31EnWOkXx/1A@UCJCmWN7mpeUxxHm/oCbrkGtBVULZoZY6UlWi/sYMdsLD7CbiJFa5JbWHydzd03CVY9lb7PgqBEoP2qFuiCuxW7eRPSaLxFGEEI7FqTh/AQ "Lua – Try It Online") ### Explanations ``` n=... -- define n as a shorthand for the argument z=table -- define z as a pointer to the object table while n+0>9 -- iterate as long as n is greater than 9 do -- n+0 ensure that we're using a number to do the comparison t={} -- intialise two tables, one is used to find the greatest digit T={} -- the other one is used to remove it from the string n=n..'' -- ensure that n is a string (mandatory after the first loop) n:gsub(".",function(c) -- apply an anonymous function to each character in n t[#t+1]=c -- fill our tables with the digits T[#T+1]=c end) z.sort(t) -- sort t to put the greatest digit in the last index x=t[#t] -- intialise x to the value of the greatest digit z.remove(T,n:find(x)) -- remove the first occurence of x from the table T -- based on its position in the input string n=z.concat(T)*x -- assign the new value to n end -- if it still isn't a single digit, we're looping over again print(n) -- output the answer ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~22~~ 21 bytes ``` Wa>9a:aRAa@?YMXax*:ya ``` Takes input as a command-line argument. Verify all test cases: [Try it online!](https://tio.run/##K8gs@B/NpWDJpWBkzqVgbgokDI2MTYBcM2MzIGVibGRpZgkRNLUAClgaGpkbmxuaccUq@CpU/w9PtLNMtEoMckx0sI/0jUis0LKqTPxf@/@/bh4A "Pip – Try It Online") ### Explanation Ungolfed, with comments: ``` a is 1st cmdline arg W a>9 { While a > 9: Y MXa Yank max(a) into y a RA: a@?y "" Find index of y in a; replace the character at that position with "" a *: y Multiply a by y } a Autoprint a ``` In the golfed version, the loop body is condensed into a single expression: ``` a:aRAa@?YMXax*:y YMXa Yank max(a) a@? Find its index in a aRA x Replace at that index with x (preinitialized to "") *:y Multiply that result by y (using : meta-operator to lower the precedence) a: Assign back to a ``` [Answer] # [Scala](http://www.scala-lang.org/), 121 bytes ``` x=>def g(y:Int):Int={if(y>9){val m=y.toString.max.asDigit;g(y.toString.replaceFirst(m.toString,"").toInt*m)}else y} g(x)} ``` [Try it online!](https://tio.run/##bYzdioMwEEbv8xRDr5KytfUvNl0UCmVhL3rVJ0htlCwxFROKIj67m3ZBZenNDHPOfJ/JueLj/fojcgtnLjWI1gp9M3Cs6x49uILiAN/aQpr9LehhbNPsJgoocXdwjDxH2ssCdxkj/TNTpZ1n7xfbSF16FW89bk6ylPbTRWbRiFrxXHzJxlhcTfxjtSLucKXrigxCGQHdgErckmGs3YNVGheYEQLb7SYDhmYYJC8KDkcLnMQzjxfcD8JoEvtlDw3pexOFAaNsUrt/bfH@fYz5QRImPp0kRWgYfwE "Scala – Try It Online") [Answer] # pure [Bash](https://www.gnu.org/software/bash/), 116 112 bytes, or 101, or even 97? Based on answers from [iBug](https://codegolf.stackexchange.com/a/148738/106907) and [Léa Gris](https://stackoverflow.com/a/68907322/490291) and [tips-for-golfing-in-bash](https://codegolf.stackexchange.com/questions/15279/tips-for-golfing-in-bash) (thanks, @AaronMiller and @BrowncatPrograms!): ``` #!/bin/bash test112() { n=$1;shopt -s extglob;while((n>9));do m=0;for x in ${n//?()/ };{ ((m<x))&&m=$x;};n=$[10#${n/$m/}*m];done;echo $n } for k in 9 27 757 1234 26364 432969 1234584 91273716; do printf '%d -> ' "$k"; test112 "$k"; done ``` [Try it online!](https://tio.run/##LY/BisIwGITvfYpBs5oIUpPWxvBb90GWPWzXuC2aRGzAQumz13bxOMPwzUz109ZjtG2UUnGR9KMvmaS2DveIbQvbxb9bqOhZNzfLuT8ZIegc4ModXcIDHRoP1vs0/eQixUA9OHfHTojVypWso4Em4JfcLecQc@mwcd8TwFuyv3UA8@OQJDPpOpMMlIbea0iV5VBFVuTIM2UK8@/sDzmMVDrTsiBMM@6PxscL1h9nbE9YY8GuC8L7zlvNZeML "Bash – Try It Online") Also there are two shorter variants: ``` #!/bin/bash f()(shopt -s extglob;(($1>9))||exit $1;m=0;for x in ${1//?()/ };{ ((m<x))&&m=$x;};f $[10#${1/$m/}*m]) for k in 9 27 757 1234 26364 432969 1234584 91273716; do printf '%d -> ' "$k"; f "$k"; echo "$?"; done ``` ([Try it online!](https://tio.run/##LYtLDoIwAAWv8oJVWxOCLUhtqngQ48IPFYKlBFg0Qc6OYly9ycvM7doV02Qoo13hmh5hh9z3z5e7aUoJzxRj73fuyx6Ea3vcauNaeJQ1yMCj6ERZhFEPoNQePGOrlT0Sr0dtQM58u5glYqNxYy9smtNqThWEhNxJcBEnEGmcJkhioVL1e3b7BIoLGUueajwcmrase4P18oEwwxoBqQIN89/8XrgvnoLZrfPpAw "Bash – Try It Online")) with 101 bytes and with 97 bytes ([Try it online!](https://tio.run/##NU/LcoIwALzzFTs0FdKOhgCSZoJ4qtd@QKcH5SGMhjiSQ2aUb6fSx213Zx@zh/3QTuXeojiac7MaWuR58P6xC6ahNReL5YDa2ePZHFQYEl5ISu/32nUWhCu9iVRjrnDoepAbZ2wbUoZR3RCGOneULhZ6Q5waFYlAPnn0NLuIZuOL/poeM55XttpUeHX42/fmwtNcKBELiLUAj5MUcZZkKdIklpn8UdZvKSSPRSJ4plAZXK5dbxsEzxWWBQL45OQrrNj/sV9el615wK0/Z/p6@gY "Bash – Try It Online")): ``` shopt -s extglob;(($1>9))||exit $1;m=0;for x in ${1//?()/ };{ ((m<x))&&m=$x;};$0 $[10#${1/$m/}*m] ``` But I am not entirely sure the last two apply to the rules. The latter even uses `$0` (I neither found a rule allowing that nor denying this) to recurse to itself, so it only works if put into a script (like `golf.sh`), made executable and then is called like `golf.sh 91273716; echo $?` Output of the scripts: ``` 9 -> 9 27 -> 4 757 -> 5 1234 -> 8 26364 -> 8 432969 -> 0 1234584 -> 8 91273716 -> 6 ``` Explained first variant (112 bytes): ``` n=$1; # (*) get argument n shopt -s extglob; # enable ${n//?()/ } below while((n>9));do # loop until number is <=9 m=0; # preset maximum to 0 for x in ${n//?()/ };{ # loop over the digits ((m<x))&&m=$x; # find max }; n=$[ # calculate new number 10# # force base 10 as 0N becomes octal ${n/$m/} # remove first occurance of max *m]; # multiply m done; echo $n # output result ``` Notes: * Shebang `#!/bin/bash`+`LF` (12 byte) is not included in the count. + We are in `bash`, so this is already the default * AFAICS passing in the number directly as variable `n` (see marked `(*)` above) is not allowed. Hence these 5 bytes are needed. + Else `./golf.sh 1234` would look like `n=1234 ./golf.sh` + A `read n;` if number is passed in from STDIN is 2 byte longer * `shopt -s extglob;` can be left away, if this option is given on commandline + Like in `n=1234 bash -Oextglob ./golf.sh` + But `extglob` is not set by default, hence AFAICS it must be included in the count * `10#` is needed as `${n/$m/}` can leave a number with a leading `0` + Without the `10#` input `91273716` wrongly returns `8`. Explained shortest variant (97 bytes): ``` shopt -s extglob; # see above (($1>9))||exit $1; # stop if goal reached m=0;for x in ${1//?()/ };{ ((m<x))&&m=$x;}; # max calc, as above $0 $[10#${1/$m/}*m] # recurse to next step ``` Notes: * Actually the last line is a tail recursion, so bash uses `exec` and does not `fork` [Answer] # J, 40 bytes ``` ((]*<^:3@i.{[)>./)&.(10&#.inv)^:(9&<)^:_ ``` [Try it online!](https://tio.run/##Xc3PCgIhEAbwu08xFLgaYf53lTV6j2g7RNJ2qMNCl@jZbVEP0WEYfh/fMPecZogBOCyTCTlthjGow8TeR7pnO4oZERyv2fR40TEQj4dlnTNFKwZdiqGDLXwCpBmh6@X2BA8REvgKXSBdlSlyprEvFFLpX0urbAt4CbSS3vr/E9O3kq3/hHTKCZu/ "J – Try It Online") ## explanation ``` ( iterate )^:(9&<)^:_ NB. keep iterating while the number is > 9 ( stuff )&.(10&#.inv) NB. convert to digits, do stuff, convert back to number ( )>./) NB. stuff is a hook, with max digit >./ on the right (]*<^:3@i.{[) NB. so that in this phrase, ] means "max" and [ means "all digits" ] NB. the max digit... * NB. times... <^:3@ NB. triple box... i. NB. the first index of the max in the list of all digits { NB. "from" -- which because of the triple box means "take all indexes except..." [ NB. from all the digits of the number ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 230 bytes ``` $n="$args";do{$n=$n.ToString();$a=@();0..$n.Length|%{$a+=$n[$_]};$g=[convert]::ToInt32(($a|sort|select -last 1),10);[regex]$p=$g.ToString();[int]$s=$p.replace($n,'',1);if($n.Length-eq1){$n;exit}else{$r=$s*$g}$n=$r}until($r-lt10)$r ``` [Try it online!](https://tio.run/##TY9BSwMxFIT/SilPmuju0rSeGgJeBW/2tiwS1tc0EJL15amF3f3tMV7E0zDDwDczpW@kfMUQSoFotmDJ5a1@T3N1ELtzemXy0QmpwZqnKvuuq/kLRsfX5W4G@1B7PbwNqwZn@jHFLyQeTqdzeo58PAgBdsmJeMkYcORNG2zmjZKN2kvdEzq8DTAZcP9hvY88QDYwdYRTsCMKiM1u1yip/UX8LWjxQ8m6VePN84oh4wxkIN@DW38f0PoZ2QcB1AauQKBSijocH38A "PowerShell – Try It Online") Wasted too much on all the type casting. [Answer] # PHP, ~~82~~ 77+1 bytes ``` for($n=$argn;$n>9;)$n=join("",explode($d=max(str_split($n)),$n,2))*$d;echo$n; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/1b43af319f7f88767c5a4ee06bf34fca64432bb4). ]
[Question] [ *[Rip-off](https://codegolf.stackexchange.com/q/193315/43319) of a [rip-off](https://codegolf.stackexchange.com/questions/193021/i-reverse-the-source-code-you-negate-the-input) of a [rip-off](https://codegolf.stackexchange.com/q/192979/43319) of a [rip-off](https://codegolf.stackexchange.com/q/132558/43319). Go upvote those!* Your task, if you wish to accept it, is to write a program/function that outputs/returns its input/argument¹. The tricky part is that if I transpose your source code², the output/result must be transposed too. 1. You may choose which kind of 2D data your solution can accept. For example a list of lists, a matrix, a list of strings, etc. State which one(s) it handles. You may assume that the input will always be rectangular and will have a length of 1 or more along each dimension. 2. For the purposes of transposing, short lines in your source code will be considered as padded with trailing spaces until it is rectangular, however, these padded trailing spaces do not contribute to your code length. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the target is to optimize the byte count of the original source code (not the transposed version). ## Examples Let's say your solution takes a numeric matrix and your source code is ``` AB DEF ``` and its input/argument is `[[1,2],[3,4],[5,6]]`. If I write ``` AD BE F ``` instead and run it, the output/result must be `[[1,3,5],[2,4,6]]`. Let's say your solution takes a linefeed-separated string and your source code is ``` ABC ``` and its input/argument is `"96\n"`. If I write ``` A B C ``` instead and run it, the output/result must be `"9\n6\n"`. [Answer] # [Python 3](https://docs.python.org/3/) + numpy, 45 bytes ``` lambda\ a:a ma= """ b. " dT" " a " \ """ ``` [Try it online!](https://tio.run/##HYuxCsMwDER3fYXQZENrmnYr@C86elGI0wRqRTjOkK931R4c9@Du9GzLJo8@x9Q/XMaJE/CToXBEIoIxoIlgetE/2Zx@TV@LbrWhHEVP5B1FwV4No1HgyvLObrj5UPO@sGZ3v@B18KB1leZmZ1Pv@xc "Python 3 – Try It Online") *Thanks to @EriktheOutgolfer pointing out a bug of the previous version* ## Transposed: ``` lambda\ a:a.T ma= """ b " d " " a " \ """ ``` [Try it online!](https://tio.run/##HYs7DsMgEET7PcWICqQExU4XiVukpFnL@CMFvMK48OkJ9jRvpDcjZ1m29K6T8/XHcRjZE3/YfgGK7KCUogFXFI1QN/kmyF8WqGuULRekI8oJ3pGE2rfAtWY5c5qD7l7G5rAvLEH3Dzw7Q5LXVPSk29SY@gc "Python 3 – Try It Online") The functions take a numpy matrix as input and output a numpy matrix. The solution does not rely on comments like many other solutions do but instead exploits multi-line strings. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes Input is a list of lists. Thanks to Luis Mendo and Nick Kennedy for improving the answer. ``` ZZ ``` [Try it online!](https://tio.run/##y0rNyan8/z8q6v///9HRhjpGsTrRxjomQNJUxyw2FgA "Jelly – Try It Online") [Try it transposed!](https://tio.run/##y0rNyan8/z@KK@r////R0YY6RrE60cY6JkDSVMcsNhYA "Jelly – Try It Online") The program transposes the input twice, returning the original input. The transposed version ignores the first line and only transposes once. [Answer] # [R](https://www.r-project.org/), ~~5~~ 4 bytes ``` #t I ``` [Try it online!](https://tio.run/##K/qfZvtfuYTL83@6LZeyJ1eJAleaRnJSZl6KRrKGoY6RjrGmTrKGiY6pjpmmpiZXOm65/wA "R – Try It Online") An R function, either the identity function `I` or the transpose function `t` when transposed. Footer on TIO shows output of both. Thanks to @RobinRyder for saving a byte! [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~209~~ ~~205~~ ~~203~~ 201 bytes ## Normal ``` f(n,L,r,c)char**L;{for(c=0;0?L+ c:c<n;c+=puts(""))for(r=0;0?r :L[c][r];r++)putchar(L[ c ][ r ]);}/* \\\ \\ 1 [0][] \ \\\ \ \\ 1 <n \ \\\\\\ r+-c c+-r */ ``` [Try it online!](https://tio.run/##ZY7LTsMwEEXXzVeMLIH8ivIobOpGCGhZ5Q8cL6pRA13UrSZmFeXbQ5wUBMKbmTv3zB1j@o44ji33utakUeDHgaSsTd9eiGOVm/ypVgC4wa03qKrrZ@g4Y0JEn2afYFNbdJacIaXERMQQXltAcBYInDBDJhP4eU3TfDdLLcDmzrrbcPGbP/7W/1qfE5YQUikCqpSiIbPx5AOcDyfPRdInK7z4LkD8Dshw7EIx3aigZ88vr0wD2@3f2GD@Y@UNK8r1w2MEJ363j83dfcbFvJOsWl5qmFOFiWq9qHJSw/gF "C (gcc) – Try It Online") ## Transposed ``` f ( n , L , r , c ) c\ h\ a\ r * * L ; { f\ o\ r ( c = 0 ; 01 ? L[ +0 ] [ c] : c < n ; c +\ = p\ u\ t\ s ( "\ " ) ) f\ o\ r ( r = 0 ; 01 ? r< n : L [ c ] [ r ] ; r +\ + ) p\ u\ t\ c\ h\ a\ r ( L [r + c- c ] [c + r- r ] ) ; } /* */ ``` [Try it online!](https://tio.run/##ZY/NTsMwEITPnadYWQLZSar8FC6kFQJaTrxBnENkNbSHupVjTlGePdhbhECVrNXMevZb2yw/jZnnniAJlpARPrg6roagQtU4aHQ6NhM@IVMTRkKvcea@5PCGUPBVUeI5xBqkBagFNTAtnjiz5kU161THkYvGl4bXGJgjNATvVf/57obv1iAbseE9DQNbFo5FzSKsSBn1u@Xvd@R11oFSmCXIMMFE64J10SpGTYQ8QZLPR@vp1B2tVBixMGc7eDKHzlHi94Mvm5Y2NIqX1zeRkdju3sVU38aqn1hZrR4eYzDkt7so7u5zqXgGi15WGTFV1dGtrq4Kbpq/AQ "C (gcc) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 51 bytes This version is valid, but will not halt when given `[]` as input. ``` f --(:[|,<zabf=]f --abx(y-i$] -- ):x) pf;x[:x y =y ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P41LV1fDKrpGx6YqMSnNNhbET0yq0KjUzVSJBbIVNK0qNBUK0qwroq0quBQqFWwr/@cmZubZFhRl5pWopEVHG@kY6hjH6kQbAGmT2Nj/AA "Haskell – Try It Online") ### Transposed, 75 bytes ``` f--- ---y (a :b)= [x:y |(x ,y) <- zip a$f b]; f x = [ ] : f x ``` [Try it online!](https://tio.run/##HYpBCsIwFET3c4pZdNFCAtW6iuYkn79IwWBoLUVdtNK7x4@bNzzmPdJ7us9zrdl7Dxp2sE1gGLsIyhbMj3YD3d6BN2u@ZQVTk8FRr2CmnZECKsNf6zOVJa6vsnyaLHJ2Jzeok972olp/ "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 51 bytes This version is valid, but crashes with `[]` as input for the transposed version. ``` f --d[(idi)z[.]d!0 -- m!)|,<i0.$ !] -- a! (_-p p=p ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P41LVzclWiMzJVOzKlovNkXRACigkKuoWaNjk2mgp6KgGAsSSFRU0IjXLeBSKLAt@J@bmJlnW1CUmVeikhYdbaRjqGMcqxNtAKRNYmP/AwA "Haskell – Try It Online") [Transposed](https://tio.run/##FYo7CoAwEET7PcUIFgqJxE@pJ1kWCagY/CBqJd49rs3MMO/N/lrGdY1xstYSNA7CAHQE3rzuLEkIIdfzzXSYnpC3aj5BITtCURAkVU74VSdx82HvjjPsdzoxV6Y0tRh22o1I/AA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), ~~75~~ ~~67~~ 57 bytes *At least 7 bytes saved thanks to Ørjan Johansen* This version outputs `[]` when given `[]` as input. ``` f --[[d(i<di)z[.$!0 --]]=!)$|,<i0.d!] -- ;[! >(_-p ] f=f ``` [Try it online!](https://tio.run/##DchLCoAgEADQvadQcFGgYZ9d2kWGIQKThiykWkV3N1cP3rbc@xpjzoFpDeArsp7qFxopTBlEJ2r5KUum8QLL8BEEn6pZJ46MBxfysdDp0kXnIwNAp1rVowJTHBDzDw "Haskell – Try It Online") [Transposed](https://tio.run/##FYvLCsIwFET38xVTyKKFpMTHzsYfuVykUIPBWkp1Jf57vN3MizOP8f28z3OtOYQAmmRQlGnXi@UpCdg2DVg6cHBXm36tNX8Du8E@37IaHMG@V9BN4E5Hra@xLGndyvJxWeToD/6kXqL5WbX@AQ "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` lambda\ a:a mz= ''' bi' ' dp' ' a(' * a \)''' ``` [Try it online!](https://tio.run/##JckxCoNAEAXQfk4x3fwv2ySmCniTbUaMZEE3i6yCXn4TSPWKV876/uS@zUNsi6/j5FH86bJeg5qZjMlU1WQqfx0m2om6RP6@lS3lCnQzXocvSLnsFSQD2YBb0DuDog/6IL8 "Python 3 – Try It Online") Based on [Joel's approach](https://codegolf.stackexchange.com/a/193351/41024). The input is a `tuple` of `tuple`s, and the output is a `zip` (converted to a `tuple` over TIO for better visibility). Transposed: ``` lambda \ a:zip(*a) ma=''' ' b ' d ' ' a ' \ ''' ``` [Try it online!](https://tio.run/##LcoxCsMwEETRfk8x3c4aNYlTBXwTNWtsE4GtiKAE4ssrEPtXr/jlWx/P3LdliG31bZwciOL3PRV2brL5oKqAyogjlQl6yk9BIv4b0Mor5Up2C@ePr0y5vCvNLJg18hJwtQD2ATezHw "Python 3 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~20~~ 11 bytes ``` #& *[ #Z ] ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfWY1LK5pLOYpLIfa/NVdxYqVCmoaGhqGOkaaOhrGOCZA01THT1NS0/g8A "Perl 6 – Try It Online") ### Transposed ``` #*# &[Z] ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfWUtZgUstOir2vzVXcWKlQpqGhoahjpGmjoaxjgmQNNUx09TUtP4PAA "Perl 6 – Try It Online") Both functions work on list of lists. `*[ ]` is a WhateverCode returning the zen slice of its argument, effectively the identity function. `&[Z]` is the zip operator. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 62 bytes ``` //m0()m ] //=](=a ) //>.a>p( ) //mm,m/aa //[ap./=[ p =>p ``` [Try it online!](https://tio.run/##ZY29bsMwDIR3PgVHClCkxP1ZAupFBA1EYhsOzEhwjKBv77JNhha5gbiPOB4vcpfbaZnaurvWc78NvMWoe3KKWCBGLsSC6MymIKnRr1X1GkXMZWkhcgZEbIic2qbrF@d88J1/Kz6/@w//WcoRAEYGOzA9p3LSDPsSVBoQiW/gbBXA2B5bJQmnn2bJDYpz8NBdFlwPPJB9cscHdjw@EYa60NyvOGEdLOdO9Xqrcx/mOtJkgb9s@D/evcRN2zc "JavaScript (Node.js) – Try It Online") Improved with a different layout ``` ///// ///// m=>m[ 0].map ((a,p )=>m. map//= (a=> a[p ])) ``` [Answer] ## Haskell, ~~185~~ 161 bytes ``` t i = i af n m u a e i l p s d lu h=u ( h e a d a ) t h e n [ ] e l s e m a p h e a d a : t ( m a p t a i l a ) ``` [Try it online!](https://tio.run/##ZY1LCsIwFEXndxVn4KBCJn4HQlcSMghYaTENxabrj0lQEJy8d7jcz@jX5xBCzolJ9CrXPyQis9jwDFUPLKzcC2yM/SY6MYpBeBW5vb1IXzUKK1zjINYKqo3Ft@g/e2vZ7teSGtXtT32e/RTpWV5TTOxIWHswR3Nyxp7NxVydy28 "Haskell – Try It Online") Transposed: ``` t a =if null(head a)then[]else map head a:t(map tail a) i u map h es= u id ``` [Try it online!](https://tio.run/##PYqxDsIwEEP3fIUHhiJlgQIDUr4kynBSD@XENarI9ftDoVG92H52pvpm1dYMIIcgL5RVdchME@hsmUtMrJUx04KdPm34FSPR7eIEu1b3t21ynSD3xDUcrN8gU5tJCgKWjxTDCYYYL/7qx@Tjzd/9I6X2BQ "Haskell – Try It Online") No comments, no string literals, just some additional function definitions. Edit: -24 bytes thanks to @Ørjan Johansen. [Answer] # [PHP](https://php.net/) (7.4), ~~114~~ ~~86~~ 70 bytes My first ever experience doing something like this in PHP, there must be a better way I cannot see! Input is an array of arrays like `[[1,2],[3,4],[5,6]]`. ### Normal: ``` fn($a)=>$a/* nu / (l $l a, ). =. >. a$ ra r) a/ y* _ m a p (*/ ``` [Try it online!](https://tio.run/##NcQ9CsMwDAbQ/TtFBw2WETb9XVKnBzEmaDEppEaYdOjp3S59w7PVxv1hqwFU06jNkXKaSaNHex/@ItwG2qACDkgBc4ASuqIzNOLjseAFhcH5OCbA@rPtS3dUXc5HORXJZ7n8vsqtFOZpfAE "PHP – Try It Online") ### Transposed (space padded): ``` fn($a)=>array_map( null,...$a)/* * ( / $ a ) = > $ a / */ ``` [Try it online!](https://tio.run/##jcw7DsMgEEXRflZBQQFoBMq3cXAWgpA1DXIkB42QU2T1hNrT5BavOMXjlfvjySsD6BJ7qUaTjTO1Rt/lTWygfrYNvffDg1MjB0YdCqCPpIAkWUlR0izpv/sgyQnrEwC3V92XZnQxKZ3wnDFd8Dr2hvecrZ36Dw "PHP – Try It Online") [Answer] # [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), ~~382~~ ~~375~~ 337 bytes *No comments!* ``` ( <( <>)<> ><>) ({}) {}{} {( )()<({}<{}<><>>{}<><>{}) ( <>) ({}<><( [ ]({}<{}( )<({}()<{}<><>>){} ><><{}<< ><> ( [ ]( <>)<>)>{}<>>>)){}>)> ( ){ {}[]} <>[]{ (({}({} ( )) <>( ))[( [ ])])({}[ ] [ ]( ) ( ) < ><>{} <>( ){{}()<( )( ({} { [ ]( ) } <>) ( (()) {{}()<{} >} ) ) >} )}[] {} ( ){} ( ){}({}<>)<>([])}<> ``` [Try it online!](https://tio.run/##TVA7DkMhDNt7Co/J2O@EuAhieO3SqlKHroizp3Z4QyVEQmwnDvfv9vo8t8c7AjAUnuqlojLAxnRgzDHBYHDzwlrhIV5XECdVorNgaOiLRYX4VO0KZydGPYsSLPKa6dmQJLL4IOaDw1ufxFsfB1MveSFCX6wqadnDuxNishoCLppCDpJKdBZGGtIyMoyBPwVmLiKlmWaM3T0h1Jkcz4SRzmgvbe53fgA3sdadWUSc4hzHvC9xjdsP "Brain-Flak (BrainHack) – Try It Online") For the input the first two numbers are the dimensions of the matrix and the remainder is the contents of the matrix. Output is given in the same format. ## Transposed # [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 465 bytes ``` ( ( ({ } <( ({ } < > )( < >) ) > < > )< > (( { }) )) [ ( { }[ { }] ) ] ) {( ({ } )[ ( )] < ([ { }] <( { } < >) < > >( { } < >) < >< { }> )< > ({ } < > )< > (( { } < >) <{ ({ } [( ) ]< (( { }) <( { }( ({ } ) <{ ( { }[ ( )] <( { } < >) < > > )} { }< > >) < > <( { } <( <( ) >) < > { ({ } [( ) ]< ({ } < > ) < >> )} > { }) < > >) > )> )} { } > ) >) } ([ ] ) {{ } { }( [ ]) }{ } < >( [ ]) {{ } ( { } < > ) < > ( [ ] ) } < > ``` [Try it online!](https://tio.run/##ZVE5DgMhDOznFZR2mbNCfARtsUmTKFKKtCve7jCGZXNIyPgYPKPh8prvz9t8fZgFQT2yIBTEkSBBhZciaC28ERESRLCgKLROMp/WKjNMRAaPy7pHMwQ61efSMVECk7aaW5N81ZHV4NrEfHB37NLHWUg5xaEs@j0kOLKpbFrkR0CAFracojdXkPDQgdYO/6SbRMbEXanrgK@rrdQZHEVLC/2oXlWr/L3rzZgUZd3X6zbnJ7XERdLoloh/QrO@T81sbwfbeTzayc5v "Brain-Flak (BrainHack) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÕU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1VU&input=W1sxLDIsM10sWzQsNSw2XSxbNyw4LDldXQotUQ) | [Transposed](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1QpV&input=W1sxLDIsM10sWzQsNSw2XSxbNyw4LDldXQotUQ) ``` ÕU :Implicit input of string/array U Õ :Transpose U U :Original U :Implicit output ``` ``` Õ\nU :Implicit input of string/array U Õ :Transpose U \n :Reassign to U U :Newly transposed U :Implicit output ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` A¿⁰« ‖⁰¿ ↗⁰ ¿⁰ ⁰¿ « ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWH9j9q3HBoNdejhmkgxn6uR23TgQwusDgXROjQ6v//o6OjlRydlHQUlFxc3ZRiY2MB "Charcoal – Try It Online") Takes input as an array of strings. Explanation: `A` implicitly prints the explicit input, while `¿⁰` is a conditional, with `0` as the condition, which is therefore always false. `«` then starts a block of meaningless Charcoal code which never gets executed. (It might be possible to remove some of those bytes but in that case I'm not sure whether Charcoal would parse the program correctly.) Transposed, 17 bytes: ``` A‖↗¿⁰« ¿⁰⁰⁰¿ ⁰¿ « ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWPGqY9apt@aP@jxg2HVnOBaQg6tJ8LQh5a/f9/dHS0kqOTko6Ckourm1JsbCwA "Charcoal – Try It Online") Explanation: Much the same as the previous program, except for the addition of the transpose command `‖↗`. I have an alternative solution where both the original and transposed program are 18 bytes: ``` A⊞υ”y ‖υ⁺y ↗⁺ ⊞⁺ υ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWPuuadb33UMLeS61HDNCCrcReQ1TYdSHMBpUDU@db//6Ojo5UcnZR0FJRcXN2UYmNjAQ "Charcoal – Try It Online") Explanation: `A` as above; `⊞υ` pushes a value to the predefined empty list (which doesn't affect the output); `”y` begins an arbitrary string (ends at end of program or matching `”`). Transposed: ``` A‖↗⊞υ ⊞υ⁺⁺ υ⁺ ”y y ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWPGqY9apv@qGve@VYuMPmocRcQcYEZXI8a5lZyVf7/Hx0dreTopKSjoOTi6qYUGxsLAA "Charcoal – Try It Online") Explanation: `A‖↗` as above; `⊞υ` as above; the minor difference here is that I'm pushing concatenations of smaller strings, since I don't want to repeat the `”`. [Answer] # [Haskell](https://www.haskell.org/), ~~153~~ 144 bytes (thanks, [Sriotchilism O'Zaic](https://codegolf.stackexchange.com/users/56656/sriotchilism-ozaic)) ``` f [ ]= [ ]; f( x: l) =( :) x l -- : z $ -- f i f -- [ p -- ] W -- i -- t -- h ``` [Try it online!](https://tio.run/##PcoxDsIwDIXhPad4Q4dWSiVomYJyDgbLQwesRg1VBR0Qlw82EDz4/2R5nh7LNedSxIEcODrAAPDZNqT9BM/wLXL3A2JbhfA/6iey63sE5QuNUZQJYiTlZmDFxWCTKvaKudymtMbtnta9EaLBH/3Ing7aE3N5Aw "Haskell – Try It Online") [Try it transposed!](https://tio.run/##y0gszk7Nyfn/P00BDnQhgEshOhZDSMEWrgzIgauwSoOrBQkrWCMZBxVS0KjAEFKwysEQUtAEWlGVWRCeWZIBE1LQsEJXBVRXoQKzhQshqgAz8X9uYmaebUFRZl6JSlp0tJGOoY5xrE60AZA2iY39DwA "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 35 bytes ``` #-sz## ->hip{ hip } #{f #ht* #..h ``` [Try it online!](https://tio.run/##bY3LDoIwFAX39ysaCvJIKfGdmOCPEBYVacEgNLSYKPDtFatLN2c1Z6YfLk/Di@5apr7vGxyrF8YQn6tajoCWRWgGPHLAlY4AU1qZhQOelg/WIHsEiXiWZWuyIducZDuyJ4c8z0FYq0Wo0n0tqZJNrQM3CemdyXFqpsDx4qNyvCakRcV6NVPds1bJTpUfJFidbl3dhpGbgBy0QlYJ4hsXv7j4Ezdv "Ruby – Try It Online") Hip to be square! (Almost) Accepts ruby matrices as input (arrays of arrays) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ``` {⍵ ⍉ ⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71buR71dgLx1tr/6RCRTojgVoXa/8VFyUCxR20T1UEq1RXUgbJgcmutOhdQkitNAUSmg0gA "APL (Dyalog Unicode) – Try It Online") Transposed: ``` {⍉⍵ ⍵ } ``` Probably a rather boring answer, but anyway here it goes. The inline function definition `{...}` can span multiple lines. In this case, each line is sequentially executed, but any line without an assignment `←` immediately returns its computed value. So the first function returns `⍵` while the second returns `⍉⍵`. Even more boring answer would be the comment abuse: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 bytes ``` ⍝⍉ ⊢ ``` No TIO is necessary, I guess... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` #&(*  *) \ ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lNQ4vrfX@7gpYmV8z/gKLMvBKHNIfqakMdIKzVqTbSAUIgbQzkm9TW/gcA "Wolfram Language (Mathematica) – Try It Online") / [Transposed](https://tio.run/##y00syUjNTSzJTE78n2b7X/l9f3sMlxqXhhaXlub/gKLMvBKHNIfqakMdIKzVqTbSAUIgbQzkm9TW/gcA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 64 bytes ``` //i$ //mp $ p=p //ot //rr //ta // n //Ss //tp //do //Ls //ie //b ``` [Try it online!](https://tio.run/##Jck7CgMhFIXhflZhIdgkuIIpkkwTsLMUiztqguALxymy@dxcSfNxfo5LAQrm6s8UWIZYUMrIFylzWzhra6NZB9E7MYBghdDHzPn6SqiZMRA76gF9sJVxZoy43YW9GPHYhLX4da8E7wOvT4Xbp0CO7h96eBX3Hw "Clean – Try It Online") ``` //$////////// // ////////// import StdLib $p=transpose p ``` [Try it transposed!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3X19fRR8OuPT1FZB4mbkF@UUlCsElKT6ZSVwqBbYlRYl5xQX5xalcCgoF/4NLEoGytgoqCtHR6o5O6rE60erOLuqxsf//JaflJKYX/9f19PnvUpmXmJuZDOFAjAIA "Clean – Try It Online") [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 88 bytes ``` vrlril1-{)?\:',=4*?~r0[ i! '${U [0r/?*7̸0l{$ $ka6 ̹\!$,'/;? = ̹ ' ̸ $ ``` [Try it online!](https://tio.run/##KyrNy0z@/7@sKKcoM8dQt1rTPsZKXcfWRMu@rsggmitTUUFdpTpUIdqgSN9ey/zMDoOcahUulexEM4UzO2MUVXTU9a3tFWwVgDwudQUUcGYHF5fK//@OCsEKLgo6XIEK4QquQDpIIUQhEgA "Runic Enchantments – Try It Online") [Try it transposed!](https://tio.run/##DYxBCsIwAATv84otBIIl0giioEgQ9AGKItJexFMxeAjopeC79A/9UwwMzGkmvZ79Ped3b6wMqXoQdSPZBb0RcRh/YnbumKpiaA0T7wjJ0jUNq7DG1gG3ZDN@C8w9dSSUik@54Wlz3sprJ8dBF@2Ljzrp@gc) Input is *space separated* for each value and *comma separated* for each row (newlines are optional) and supports both strings and (non-zero) numbers. This makes parsing the input easier as input is automatically broken by spaces and newlines. So for example, the input: ``` 1 2 3 , 4 5 6 , 7 8 9 ``` Would be represented in nested array form as `[[1,2,3],[4,5,6],[7,8,9]]`. Minimal support for jagged arrays (only the last one can be short), but as inputs are expected to be rectangular, this satisfies that requirement. Output is represented in the same format (transposed version outputs with newlines, but its zero bytes different to use a space instead). Normal version has a trailing space, transposed version has a trailing comma and newline (due to the difficulty of determining when there is no more data to print). Normal version does have modifier characters in weird places (eg. `7̸0`), but this is due to needing them in the right place when the source is transposed and the normal execution only utilizes the leftmost column of instructions. ### Explanation Explanation of the transposed source will be in a non-transposed form. Arrows will represent IP directionality at the entrance and exit of various blocks. ``` →rlril1-{)?\:',≠4*?~r0[ Initial position. Read and parse input. ↓ Input loop exit and direction ``` The input is read, and when a `,` character is found, a new substack is pushed. This allows each stack to hold each row separately in memory. Enters next section from the top. ``` ↓ .. '${̹L [0r/?*7≠0l{̹$ When no more input: ↑ ↓ ``` `[0` (executed leftwards) sets up a an empty stack to act as a boundary between the first row and the last row and then rotates to the first stack (`{̹`) and starts printing elements and rotating stacks. The `i!` is not executed and `{̹L [0r` is only executed once. When a zero-size stack is found, the loop exits. ``` ↑ ↓ $ka6 \!$,'/;? Row separation formatting ``` When the empty-stack is found, a `,` and newline are printed, and value loop is re-entered. Execution order (mirrored for readability) where `.` is an un-executed command: `\',$!.6ak$?....../`. Changing `ak` to `'<space>` would print spaces instead of newlines. Execution halts when the program attempts to write from an empty stack; this is why only last-row jagginess works correctly and why there is a trailing `,` in the output: the comma has already been printed before the program knows that there's no more data. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øø q ``` [Try it online.](https://tio.run/##yy9OTMpM/f//8I7DO7gK//@PjjbUMYrViTbWMQGSpjpmsbEA) ``` øq ø ``` [Try it transposed.](https://tio.run/##yy9OTMpM/f//8I5CrsM7/v@PjjbUMYrViTbWMQGSpjpmsbEA) **Explanation:** Unlike some of the other languages, newlines are simply ignored in 05AB1E, so I don't think a 2-byter is possible (although I'd love to be proven wrong). ``` ø # Transpose the (implicit) input ø # Transpose it back q # Stop the program (and output the top of the stack implicitly as result) ø # Transpose the (implicit) input q # Stop the program (and output the top of the stack implicitly as result) ø # No-op, since the program has already stopped ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` #∩ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIj4oipIiwiIiwiW1sxLDJdLFszLDRdLFs1LDZdXSJd) or [try it online transposed](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIjXG7iiKkiLCIiLCJbWzEsMl0sWzMsNF0sWzUsNl1dIl0=). Receives a list of lists (a list of strings will work too). *-2 bytes thanks to lyxal* [Answer] # [Python 3](https://docs.python.org/3/), ~~118~~ 95 bytes Input and result are lists of tuples. ``` f=lambda i:i;""" = " l " a m b d a i : [ * z i p ( * i ) ] ; " " """ ``` [Try it online!](https://tio.run/##dVLBbsIwDL37K6xcmqAMCdh2KOoHTOK4G0NVadMR1qZREzbg51mSlg4mmkq15We/55dWn@yuUYtLIUq0baaMboygeVMIFgO64wGdFWkllTDpj7S71OgsF4aGSt/lzwoTrISidXbsMI5f4pS4EmNDUyvsoVW49g3Tan8wlq4Ylk2LvoJShWg2ECZC7mgfL@C3nBpdSRsw2sv0EuRDkem@kYpGURd9173WWWo66XwwgDLNTGpsK9Wn04yi6FImVVZviwxlLJeEEEjw7hCo/hcyqGELhYsgIYY1TODsMg3UZRIYbGAJxD@EXJzGehY/zTZefLj@4m6Pv69ysx8D7YKl5H0YitEZ5viYh6MROoki51IcRX5PlTf6lJZOqryCjygY2NDiG7sJcO4TXNMZxznHBeNInzm@cHxlzlC/4JvSBxv7q@FYDWuXVPo6i/3GtGIDYG8AGwAQtbYnL/SYNMAjxB02Qn4F4Vvk1v0UnRXvYh7eC945GjHTTY0I9@CI8hW9/AI "Python 3 – Try It Online") [Answer] # [Cjam](https://sourceforge.net/p/cjam/), 13 bytes ``` qo ~ z ` ``` [Try it online!](https://tio.run/##S85KzP3/vzCfq46riivh///oaEMFo1iFaGMFk9hYAA "CJam – Try It Online") ## Transposed version: ``` q~z` o ``` [Try it online!](https://tio.run/##S85KzP3/v7CuKoEr////6GhDBaNYhWhjBZPYWAA "CJam – Try It Online") ## Input format The input format is the standard CJam array format: `[[1 2] [3 4]]` # No crash version, 12 bytes The normal version crashes *after* printing the array. A version which doesn't crash would be: ``` qo{ ~ z ` }; ``` [Try it online!](https://tio.run/##S85KzP3/vzC/mquOq4orQaHW@v//6GhDBaNYhWhjBZPYWAA "CJam – Try It Online") or transposed: ``` q~z` o { }; ``` [Try it online!](https://tio.run/##S85KzP3/v7CuKoErn6taQaHW@v//6GhDBaNYhWhjBZPYWAA "CJam – Try It Online") There are probably a few extra bytes that can be saved, i accidentaly worked on the transposed version first, which led to a few extra linebreaks and it's been a long time since i last used CJam. Any improvements welcome. [Answer] # [Zsh](https://www.zsh.org/), 75 bytes ``` <<<${(F)@} fa< o[< r+$ +{ si( ;]F i+) ==a &$} &s r[ ei p+ e1 a] t $ # s ``` TIO: [Normal](https://tio.run/##JY69jsIwEIT7eYq9xCKxfFwELQ6iIS0PEKUIwVFcECOv@REozx4Mt1pNMbOjb588zFv6K4InrSnbH6oM6U9xZV8c7ViY8UbPeEIx1eKVV3I3oW81XK3hlQCpF9jm2DQVrJIoyxYLMWHB8DWMxUXBrNA2CIBACp4jA91wdidSjy8Z@PLdaCjcHYUhOhGXlZ/JgJQuLTPZEJeJ3dV3hjp3Mv@9JP61kx/pZSJyHbxMpnr9u1w1UzK/AQ "Zsh – Try It Online") [Transposed](https://tio.run/##LY2xDoIwGIT3/yl@SyM0FQlxtBgWWX0AwoBaUgapaasSCM9eK/EuueEuuW@yyp9wnzmDQmB8vlQxRJvsZU127YdMDm@crAIrHaajx04btMe@2G6NfMrWIY0sYFtz3je8oLbued6AEILOScXaBUQwhRkSqIBBCQv4wICbeug78nElA6x8PUh0H41OhSZcxMWq@D@TcFmyX3SM0EQ4w8hSH3Zp3izEfwE "Zsh – Try It Online") The garbage below the main print is harmless, it prints an error when encountering a newline after `fa<` and exits. [86 bytes to remove that error.](https://tio.run/##NU5BasMwALvrFVpimgYvC911zuhlu@4BIYfMdYmhs4PttqGjb88S6ITQQUhItzjM73ypnU@BSrH4@PoskD/V5xjqb@tq4y68LSHSTEZzDNYlVieKPY79BN8aBKlBiWhHvHUBVlo0jcNGJGwiEdoKxp4wSsLsBPquRwIEcsR5mYMefvyBcnrcAB53vDNMV880LJ5SqmhWFEDOsY@RNi2MjP4ctKH2B/PfzMTvdl@uciwzsVWrWWb39vW52nX3bP4D "Zsh – Try It Online") The transposed version is here. After printing it errors on seeing `<` at the end of a line and exits. ``` for s;i=&&repeat $#s a[++i]+=$s[i+1] <<<${(F)a} < < $ { ( F ) @ } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` CCQ " Q " ``` [Try it online!](https://tio.run/##K6gsyfj/39k5UEGJK5CLS@n//@hoQx0Fo1gdhWhjHQWT2Nh/@QUlmfl5xf91UwA "Pyth – Try It Online") # Transposed ``` CQ " C Q " ``` [Try it online!](https://tio.run/##K6gsyfj/3zlQQYnLmSuQi0vp///oaEMdBaNYHYVoYx0Fk9hYAA "Pyth – Try It Online") ## Explanation The program transposes the input twice, returning the original input. The transposed version only transposes once. ]
[Question] [ Using the following length-separated lists of words: [https://github.com/Magic Octopus Urn/wordListsByLength](https://github.com/carusocomputing/wordListsByLength) Print 1 word from each list of length `n` from 1 all the way up to 20, here's a valid example: ``` a an and hand hands handle handles abandons abandoned understand outstanding newfoundland understanding characteristic characteristics characterization characterizations characteristically characterologically chemotherapeutically ``` Alternatively (array): ``` ['a', 'an', 'and', 'hand', 'hands', 'handle', 'handles', 'abandons', 'abandoned', 'understand', 'outstanding', 'newfoundland', 'understanding', 'characteristic', 'characteristics', 'characterization', 'characterizations', 'characteristically', 'characterologically', 'chemotherapeutically'] ``` Alternatively (any printable non-alphabetic separator other than `\n`): ``` a:an:and:hand:hands:handle:handles:abandons:abandoned:understand:outstanding:newfoundland:understanding:characteristic:characteristics:characterization:characterizations:characteristically:characterologically:chemotherapeutically ``` --- # Rules * You may choose your own 20 words. * The words must be from the github page provided, more specifically: + 1 from 1.txt, 1 from 2.txt, etc... + Note, files above 20.txt exist, but you do not need any words above 20 characters. * Valid separators are ASCII-printable non-alphabetical characters (even numbers, don't care). * Lowercase or uppercase only, pick one, stick with it; no title-case allowed. * Please don't use a 100% copy of my example 20 words... + You can, but that's no fun. + *They are likely suboptimal anyways...* * If you DON'T want to use the separated files, and need a full list: + Use [unsorted.txt](https://github.com/carusocomputing/wordListsByLength/blob/master/unsorted.txt), this is all `n`.txt files in one, sorted alphabetically. * Note, you CANNOT directly read from the URL, it is a [common loophole](https://codegolf.meta.stackexchange.com/a/1062/53748). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count will be the winner. --- *For reference, the output is 229 bytes, so anything that gets under that beats hardcoding.* --- Possible meta-tag-discussion: [user-driven](/questions/tagged/user-driven "show questions tagged 'user-driven'") where the user gets to customize their outputs from a list of possibilities? [Answer] # [Python 2](https://docs.python.org/2/), 145 bytes ``` print'i am now tiny @ @s##s#ed#act#acts#@#@s#@ed#@ing#arguments#accusation#accusations#advertisings'.replace('#',' counter').replace('@','check') ``` [Try it online!](https://tio.run/##TcpBCgIxDIXhqwSyiAPiwhP0KiUTZoJOWtpUmdPXuNLFg5@PV0/fi93nrE3NSSEfYOUNrnZCgtQRO8qKmf27jgnDUkhS2zC3bRxi4Zl59Oxa7C@D15c01x7nTrcm9ZlZLoR0JeAyzKXR8vMUzrvwg5Y5Pw "Python 2 – Try It Online") Prints these words, separated by spaces: ``` i am now tiny check checks counter counters countered counteract counteracts countercheck counterchecks counterchecked counterchecking counterarguments counteraccusation counteraccusations counteradvertisings ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~49 35 31~~ 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṫ3,⁸Ṗ,$€ẎK “¤ƈȮⱮ⁴⁷ọḤƁŒ|⁾Ė»ḲÇ€K ``` A niladic link returning a list of characters, or a full program printing that list as a string (the words delimited by spaces). **[Try it online!](https://tio.run/##AUsAtP9qZWxsef//4bmrMyzigbjhuZYsJOKCrOG6jksK4oCcwqTGiMiu4rGu4oG04oG34buN4bikxoHFknzigb7ElsK74biyw4figqxL//8 "Jelly – Try It Online")** ### How? ``` ṫ3,⁸Ṗ,$€ẎK - Helper link: list of characters, word e.g. "abreacts" ṫ3 - tail word from index 3 "reacts" ⁸ - chain's left argument, word , - pair ["reacts","abreacts"] $€ - last two links as a monad for €ach of the two words: Ṗ - pop (all but last character) "react" / "abreact" , - pair ["react","reacts"] / ["abreact","abreacts"] Ẏ - tighten ["react","reacts","abreact","abreacts"] K - join with spaces "react reacts abreact abreacts" “¤ƈȮⱮ⁴⁷ọḤƁŒ|⁾Ė»ḲÇ€K - Link: no arguments “¤ƈȮⱮ⁴⁷ọḤƁŒ|⁾Ė» - a compressed string using dictionary indexes: - "agar abreacts acknowledges codeterminations deindustrializations" Ḳ - split at spaces Ç€ - call the last link (Helper) as a monad for €ach K - join with spaces ``` ...which yields: ``` a ar aga agar react reacts abreact abreacts knowledge knowledges acknowledge acknowledges determination determinations codetermination codeterminations industrialization industrializations deindustrialization deindustrializations ``` --- Previous: @35: ``` “¡Ụıƭz Xj]"Ɱ*AJƤʂạ5ƬṚṪð^ƥỤ»ḲṖ,$€K€K ``` Using 10 words and their length-1 prefixes. @49 ``` “ḊAḥTz¹ỴH¡ṛYẈDƤNŀt#ñ²ĿĊḤlṪnð⁻U+ɦỴĊypṆQ0⁴ṄẉṂi⁻d¤&» ``` Simply 20 compressed words. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~166~~ 163 bytes ``` 'a an and' '','s','le','ler','lers'|%{"hand$_"} ($a="character") ($x=-split"s ed ful ized istic istics ization izations istically ologically"|%{"$a$_"}) "un"+$x[8] ``` [Try it online!](https://tio.run/##NY1hCsIwDIX/9xQlVNKBHmFnkWyrthDa0XSIU89e64qQfHnJC7w1PVwW75hrRVIUWy2oEM8ordkdyJ2C79MLfPswV/goa2iE2VOmubgMg7rIyqGAaLfo28Y67E0EKWHulHahElL8T9HGWjONeNjE/MRh0InTvW/wyzN0pMEWm5qg1i8 "PowerShell – Try It Online") Hand-optimized, no algorithms. The two loops `|%{ }` tack on the appropriate ending to the appropriate beginning. I'm searching for a way to get them down into one loop. [Answer] # Python, 169 bytes ``` z='odahs princesses acclimatizers cyanocobalamines aerothermodynamics underrepresentations'.split() print([y[:i+1]for x,y in zip(['']+z,z)for i in range(len(x),len(y))]) ``` Prints a list of the words. [Try it online!](https://tio.run/##FczBCsMgEATQe7/Cm0pDofRW6JeEHKzZNgtmV3YtRH/extPAG2ZyLRvTo/f2sryGTU0WpAiqoCbEmHAPBRuImlgDceR3SGFHGjUIlw1k57XSaVHNj1YQgSygQOVcMqm9aU5YnL@M6@LmOj/xel8@LOaYqkEyDbObrV2ubWp@OA6VQF9wCcgdfhpRvV98738) Words gained by scanning sequences of matching words, by start or end of the word and starting from length 1 upwards or from length 20 downwords. [Here is the script I used to get it.](https://gist.github.com/urielieli/10770ef6ddfcf811505806d28db71017) (the upward-start-matching one) [Answer] # [Python 2](https://docs.python.org/2/), ~~126 120~~ 112 bytes -8 bytes thanks to Anders Kaseorg (I thought I'd migrated this from Python 3, but turns out I'd forgotten!) A port of my Jelly answer works well in Python too... ``` for w in"agar abreacts acknowledges codeterminations deindustrializations".split():print w[2:-1],w[2:],w[:-1],w, ``` **[Try it online!](https://tio.run/##JYhBCsJADAC/EnqyUAV77FfEQ9xNa3BNliSy6OdXSi8zzNRvPFXm3lc1aMAy4IYG@DDCFA6YXqKtUN7IIWmmIHuzYLCKQyaW/PEwxsK/Yw4Xr4XjNC7VWALabV7O1/u0e@cRU@9/ "Python 2 – Try It Online")** Prints: ``` a ar aga agar react reacts abreact abreacts knowledge knowledges acknowledge acknowledges determination determinations codetermination codeterminations industrialization industrializations deindustrialization deindustrializations ``` [Answer] # JavaScript, 159 bytes ``` _='a1an1and}}swwrwrs~~s~ed~ful~ized{{s~|~|s{ally~ologically1misx|s~1x}1hand|ization{~isticxcharacterw}le';for(i of'wx{|}~')with(_.split(i))_=join(pop());f=f=>_ ``` [Try it online!](https://tio.run/##FYu7joMwEAB/JR12cUjUiPsVZPkRNvKxlncTk9jeXyecNMUUMw/zMmQzJP7Z0fnzXJfBTGa/cL1TKblkEiHxTsIzCny8q5WkSaNqYnwLRryD/dfpD@hoJNPRp@36G3wMA@5VgBjsYTeTjWWfS49@mANmBTcMQzlq6zLoArypdaQUgRVovS4PhF0lTErrOSxh@V3POWW0nmgkdvjksWRgr8JVnF8 "JavaScript (Node.js) – Try It Online") Thanks @HyperNeutrino for edit. But, I am reverting back to old post (removing "Node.js" flag) because it has nothing to do with Node.js. It perfectly works in browsers too. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 51 bytes ``` ’¯Óa‚‡’D“€…€¤Þ¨íʃé¢Ã¥£žÜ¶ß´ç…àçî×Ü»‡ÛೌçÓs²® ÿ ÿs ``` [Try it online!](https://tio.run/##DYxbCoJgFIS30hLswR20EQNX4AYO9dajPogXSrtZkAYpvggGM9hCzkb@DgwfzMcwnh9s16FzKhneTAKVXKW2tlEpdfdSuRtx5REPtjz8Yj5x5h43XJaZJUaeMLCxHSs27JianOyDBSv0S2wyifBBt@LXEjn3Bw "05AB1E – Try It Online") Separator: List of words: `a, an, ana, anal, house, houses, amazing, criminal, seriously, apparently, accessories, disciplinary, distributions, discrimination, congratulations, responsibilities, characterizations, telecommunications, representationalist, representationalists` [Answer] # Ruby, 120 bytes ``` j=3 $><<?a " 5 T & } < ".bytes{|i|puts 8.times{|k|$><<%w{dehydro chlori ge n at ion e s}[k]*(j>>7-k&1)} j+=i-31} ``` Prints the following. Each word is built from the 8 strings above, using the binary digits of `j` to select. On each iteration of the loop, `j` is incremented by the ASCII value of the characters in the string in quotes, minus 31. ``` a es ion ions nates nation nations chlorine chlorines chlorinate chlorinates chlorination dehydrogenate dehydrogenates dehydrogenation dehydrogenations dehydrochlorinate dehydrochlorinates dehydrochlorination dehydrochlorinations ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 74 bytes *Psychopathologically adventuresomenesses* ``` .e:"psychopathologicallyadventuresomenesses"b+bhkiR36"GGGGBKMMKKM6K6M0K0K0 ``` [Try it online!](https://pyth.herokuapp.com/?code=.e%3A%22psychopathologicallyadventuresomenesses%22b%2BbhkiR36%22GGGGBKMMKKM6K6M0K0K0&debug=0&input_size=4) It outputs: ``` ['a', 'al', 'all', 'ally', 'logic', 'advent', 'venture', 'ventures', 'adventure', 'adventures', 'venturesome', 'pathological', 'adventuresome', 'pathologically', 'venturesomeness', 'psychopathologic', 'adventuresomeness', 'psychopathological', 'adventuresomenesses', 'psychopathologically'] ``` Which, once formatted yields: ``` a al all ally logic advent venture ventures adventure adventures venturesome pathological adventuresome pathologically venturesomeness psychopathologic adventuresomeness psychopathological adventuresomenesses psychopathologically ``` **Explanation** The key was to choose two words that complement each other. I chose "*psychopathologically*" and "*adventuresomenesses*" thanks to [a little tool I wrote](https://gist.github.com/Jim-Bar/8583ccf50331d2962c4aeec064c2a6f4). Using these two words, for any length we can find substrings which are actual words of the [provided list](https://github.com/carusocomputing/wordListsByLength). All the possible decompositions are demonstrated by: ``` a al all ally logic psycho logical logically pathologic pathological pathologically psychopathologic psychopathological psychopathologically a ad ess ness esses advent venture ventures adventure adventures venturesome adventuresome venturesomeness adventuresomeness adventuresomenesses ``` The next step is just to get the list of the indexes for a given decomposition. For my decomposition, I chose: `16 16 16 16 11 20 22 22 20 20 22 6 20 6 22 0 20 0 20 0`, which are indexes in the concatenated strings: `psychopathologicallyadventuresomenesses`. Finally, write a program which just loops over the indexes and display the substring at each given index with increasing length. For saving bytes, I stored the indexes in a base 36 string. Indeed, `GGGGBKMMKKM6K6M0K0K0` is the list of my indexes in base 36 (because my highest index is 22, I could have used base 23). **Program explanation** ``` .e:"psychopathologicallyadventuresomenesses"b+bhkiR36"GGGGBKMMKKM6K6M0K0K0 iR36"GGGGBKMMKKM6K6M0K0K0 # For each character in the string, convert from base 36 to base 10 .e # Loop over indexes: b are the indexes, h their position :"psychopathologicallyadventuresomenesses"b+bhk # In "psy...ses", select the substring at index b and of length k + 1 ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 66 bytes ``` 00000000: 6d8b 410a 0020 0804 bf6a 4407 a134 5aff m.A.. ...jD..4Z. 00000010: 4fe6 29ac 93ce b0a3 543a ad06 3f6c e769 O.).....T:..?l.i 00000020: 46f3 3ae2 b218 abc4 2cab d389 a805 82aa F.:.....,....... 00000030: fee1 6e43 2444 62df 0f46 4a1e f356 8cf1 ..nC$Db..FJ..V.. 00000040: 73d8 s. ``` Output: ``` o`al`res`alit`reset`preset`present`rational`represent`rationales`annotations`connotations`connotational`representation`representations`representational`misrepresentation`misrepresentations`representationalism`representationalisms ``` [Try it online!](https://tio.run/##jc@9TsNAEEXhnqe4BQ0SGs3ujNdrNwgRpaChQRR0sz8TgRIalOc3DrGoOQ/wSaecSzn2w/m0LLw1I7VcoIENzJHBmRXFk0GVR1gQxWDuwIkeiUBEnzsifaebqxBWQ70nxMkqJqkdhU0wqBiscYJ4quhjmoAXuqNLrzPRw5E@NiNejOQCsR5RYsiwUhWxWkGTPMEyD8jRDNjT/Gvc07XNkNXw3gNSV0FUVaTYHOyaoBY6XIaEXD1gvfh6ut0Vov0z0dufoasxSsv4T9@0LD8 "Bubblegum – Try It Online") The words and separator were selected by simulated annealing: ``` from __future__ import print_function import math import random import zlib wordlists = \ [[chr(x).encode() for x in [9, 10] + list(range(32, 127)) if not chr(x).encode().isalpha()]] + \ [open('wordListsByLength/{}.txt'.format(n), 'rb').read().splitlines() for n in range(1, 21)] words = [random.choice(wordlist) for wordlist in wordlists] temperature = 10. score = 9999 best = score while True: old_score = score n = random.randrange(len(wordlists)) old_word = words[n] words[n] = random.choice(wordlists[n]) z = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, 9) score = len(z.compress(words[0].join(words[1:])) + z.flush()) if score > old_score and random.random() >= math.exp((old_score - score) / temperature): words[n] = old_word score = old_score else: temperature *= .99999 if score < best: best = score print(best, repr(words[0].join(words[1:]))) ``` [Answer] # C#, 259 bytes ``` _=>{var a=new int[7].Select((n,i)=>"abasers".Substring(0,i+1)).ToList();a.Add("abacuses");a.AddRange(new int[12].Select((n,i)=>(i>10?"un":"")+"character"+"|s|ed|ful|ised|istic|istics|isation|isations|istically|ologically|istically|".Split('|')[i]));return a;} ``` Some obvious room for golfing still but I've run out of time now. I know it's longer than hard coding so will fix it when I get some time later on. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~130~~ 68 bytes -62 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) ``` 743222’€Ü†š ƒ´aî³eros €‡a•¿f²Ñns …¿en®íizers ‚ÀÙŠs ‡åØŽ’#‚øε`ηRs£R}˜ ``` [Try it online!](https://tio.run/##JcsxDsIwDIXhu2RjIxJQTsA9XNdtLRG7clIGJG7CzBXYWZG4UiBmfP@nt91DH6nWAGnNZDl8ngHBoGch0za70@txC6MaJBYeyUBajtH7MmvRTJK58PX/jzuXCw@kqPJ7kCDL5HZwMxhYlxksAdJaGOHsemy6ed9r/QI "05AB1E – Try It Online") Takes as many prefixes as needed from each of the following words: ``` amusers carabinero foraminiferans photosensitizers videoconferencings radiopharmaceuticals ``` Prints these words in an array: ``` a am amu amus amuse amuser amusers carabine carabiner carabinero carabineros foraminifera foraminiferan foraminiferans photosensitizer photosensitizers videoconferencing videoconferencings radiopharmaceutical radiopharmaceuticals ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 78 bytes ``` 00000000: 654b c301 4431 10bd a7cb d876 9a5f efe7 eK..D1.....v._.. 00000010: 781e 2080 ee55 0488 ffc8 9f69 e86f a5ff x. ..U.....i.o.. 00000020: ce00 0b98 202e 34ed d701 a464 bf59 35fb .... .4....d.Y5. 00000030: 23d7 9192 b948 7c79 f351 0c8b f4ee 06e4 #....H|y.Q...... 00000040: 8b05 1a33 77c8 1bcf 7f58 7577 e113 ...3w....Xuw.. ``` [Try it online!](https://tio.run/##Pc87TwQxDATgnl8xEr0Vbx5OqCmQqCiQoELrxEZIIKrjIfHfl@wdxzSu5tNYD6qv9nx427bwlyuUnBQ9BkZKkcFBB1bpilGloK3ZYW4C2C3RNdOeD3oiujgJPA2pbFhCDTDLGSHVCvde0bw0WC2O6TjwRSC6Pxov9P5vLNPoFgKCtjqhxRCTDQyZs9ZUEtRzQ8yuwF4Gpf0MesxnI05jiUPQuC3QliqkS4PHzAi9KjyZIRRLwOXevvn5prvjlrORplE1ZPAaI0TmB6zdIZ6nlkVgzBGnzFr83MsPh3m27Rc "Bubblegum – Try It Online") [Answer] # Ruby, 107 bytes ``` p(z=%w{o or for form ultra})+[z[3],c="centrifug",z[4]+c].product(%w{ed ing ally ation ations}).map{|i|i*""} ``` Prints the following array. ``` ["o", "or", "for", "form", "ultra", "formed", "forming", "formally", "formation", "formations", "centrifuged", "centrifuging", "centrifugally", "centrifugation", "centrifugations", "ultracentrifuged", "ultracentrifuging", "ultracentrifugally", "ultracentrifugation", "ultracentrifugations" ``` Changing the `p` for `puts` (with trailing space) gives the following at a cost of an additional 4 bytes. ``` o or for form ultra formed forming formally formation formations centrifuged centrifuging centrifugally centrifugation centrifugations ultracentrifuged ultracentrifuging ultracentrifugally ultracentrifugation ultracentrifugations ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 119 bytes ``` `av„v„dvjvjsvj¤vj¤svfœejvqvqsvq‚vqˆgvqizƒvqÄKcvqÄKcsvqizÂ\nvqizÂ\nsvq‰tkvqologkv·sqizÂ\ns`d'j`Ê@`'k`Åœ§`'q`Ö‹a×` q'v · ``` [Try it online!](https://tio.run/##NYo9CsJAFISv4BHS7TXsvYLFW4wG3wbjY8MUljGCP702KQMeIf17B1uzSGC@GZgZ9uc2JfLQflYJBkewjpmIgw57hkAiRLuZewU5XvQKsX6z@3vMlXXb05L5/GgDpKmbKkCnuAxUOiZ7rskFspsO@iUnZG99efusqBCHQqeUfg "Japt – Try It Online") ## Prints: ``` a an and hand hands handle handles freehand character characters charactered charactering characterizes characteristic characteristics characterization characterizations characteristically characterologically mischaracterizations ``` ]
[Question] [ (Challenge taken from a multiplayer game (clash of code) at [codingame.com](https://www.codingame.com/home)) ## The challenge Find the **n**-th term of the following sequence: `1, 1, 2, 1, 2, 3, 1, 2, 3, 4...` or, to make it more obvious, `{1}, {1,2}, {1,2,3}, {1,2,3,4}...` The sequence is made up from concatenated ranges from **1 to x**, starting from 1, all the way up to infinity. ## Rules / IO Input and output can be in any format, as long as it's distinguishable. Input can be taken from any appropriate source: STDIN, file, etc... The input can be 0- or 1-indexed, and the selected indexing **must be** mentioned in the post. You will have to handle at least up to a result of **255** inclusive (meaning the 0-indexed maximum input is 32640). Anything over that has to be handled, if your language supports it. This is `code-golf` so the shortest byte count wins! ## Test cases (0-based indexing) ``` 0 -> 1 1 -> 1 5 -> 3 10 -> 1 59 -> 5 100 -> 10 1001 -> 12 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~27~~ 26 bytes ``` ([z|k<-[1..],z<-[1..k]]!!) ``` [Try it online!](https://tio.run/nexus/haskell#@59mqxFdVZNtoxttqKcXq1MFYWTHxioqav7PTczMU7BV0CgoLQkuKfLJU1BRKM7ILwdSaQqmCpoKdnbY5HITC4Dy0QZ6epaxmgq6ugopmcUFOYmVxQolGakKpiUZCol5KWB2WmZRcYlCSWqeQlliTmlq8X8A "Haskell – TIO Nexus") Thanks @DanD. for -1 byte! This is an anonymous function, creating the infinite sequence an just returning the `n`-th element thereof: `[[1..k]| k<-[1..]]` produces an infinite list of list: `[[1],[1,2],[1,2,3],[1,2,3,4],...]`. To concatenate these we can write `[z|k<-[1..],z<-[1..k]]` which results in `[1,1,2,1,2,3,1,2,3,4,...]` and finally `(...!!)` accepts the input `n` (pointless notation) and returns the `n`-th term (0-based). [Answer] # JavaScript, ~~29~~ 28 bytes *-1 byte thanks to Arnauld!* ``` f=(n,m)=>n++<m?n:f(n+~m,-~m) ``` Uses the 0-indexed recursive formula found on OEIS. When called with 1 argument as expected, the default value of the second, `m`, will be `undefined`. However, `-~undefined`, returns 1, which allows us to get the recursion rolling without an explicit `m = 1` in the argument list (thanks @Arnauld!) Test snippet: ``` f=(n,m)=>n++<m?n:f(n+~m,-~m) let examples = [0, 1, 5, 10, 15, 1000]; examples.forEach(function log(x) { console.log(x, " => ", f(x)) }); ``` --- Alternatively, for the same byte count, we can have a curried function like so: ``` f=n=>m=>n++<m?n:f(n+~m)(-~m) ``` You can call this with `f(5)()` - it returns a function, which when called, returns the result, as described in [this meta post](http://meta.codegolf.stackexchange.com/a/11317/60919). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes, 1-indexed ``` RRF³ị ``` [Try it online!](https://tio.run/nexus/jelly#@x8U5HZo88Pd3f///zc0AAA "Jelly – TIO Nexus") Explanation: ``` (Assume N = 4 for the examples) R Generate a list of 1 to N [1, 2, 3, 4] R Generate new lists for each item on the previous list, with that item as N [[1], [1,2], ...] F Flatten that list [1, 1, 2, 1, 2, 3 ...] ³ị Use the input number (³) as index (ị) on the list. This is one-based: [1, 1, 2, 1, 2, 3 ...] ^ ``` [Answer] # Octave, 39 bytes ``` @(z)z-(n=ceil((8*z+1)^.5/2-.5))*(n-1)/2 ``` 1- based index Explanation: Consider this sequence: ``` 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 ``` if we count number of element of subsequences we have ``` 1 2 3 4 5 ``` so using [Gauss formula for triangular number](https://en.wikipedia.org/wiki/Triangular_number) we can form a formula for z: ``` z=n*(n+1)/2 ``` that is a quadratic equation if we solve it for n we have ``` n=(sqrt(8*z+1)-1)/2 ``` [Try It Online!](https://tio.run/#n0tRU) [Answer] ## Haskell, ~~25~~ 24 bytes ``` (!!)$[1..]>>= \x->[1..x] ``` Usage example: `((!!)$[1..]>>= \x->[1..x]) 10` -> `1`. [Try it online!](https://tio.run/nexus/haskell#@59mq6GoqKkSbainF2tnZ6sQU6FrB@JUxP7PTczMU7BVKCjKzCtRUFFIUzA0@A8A "Haskell – TIO Nexus"). Maps the anonymous make-a-list-from-1-to-x function `\x->[1..x]` (the built-in `enumFromTo 1` is one byte longer) to the infinite list `[1..]` and concatenates the resulting lists into a single list. `!!` picks the nth element. Thanks to @flawr for one byte. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes The program is 0-indexed, code: ``` ÌLL¹è ``` Explanation: ``` Ì # Double increment the input LL # List of list on the input ¹è # Get nth element ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3@4x8fn0M7DK/7/NwUA "05AB1E – TIO Nexus") [Answer] # [Octave](https://www.gnu.org/software/octave/), 39 bytes ``` @(n){v=1:n,A=triu(v'+0*v),A(A>0)(n)}{3} ``` [Try it online!](https://tio.run/nexus/octave#@@@gkadZXWZraJWn42hbUpRZqlGmrm2gVaap46jhaGegCZSurTau/Z@YV6xhovkfAA "Octave – TIO Nexus") This uses an alternative approach. For e.g. `n=1` this `A=triu(v'+0*v)` creates the matrix ``` 1 1 1 1 0 2 2 2 0 0 3 3 0 0 0 4 ``` When removing all the zero elements and appending the columns by `A(A>0)` we get the sequence: ``` 1 1 2 1 2 3 1 2 3 4 ``` Then it is just a matter of exctracting the `n`-th term of that sequence. [Answer] # [Python](https://docs.python.org/3/), ~~39~~ 36 bytes *-3 bytes thanks to Dennis!* A recursive lambda which uses 1-based indexing. ``` f=lambda n,m=1:n*(n<=m)or f(n-m,m+1) ``` [**Try it online!**](https://tio.run/nexus/python3#JYtBCsIwEEX3PcWnUJroBDoiLoLxIuIiJY0MmKlUF94@Rly9z@O/msMjljlFKJXAXndGz6HYdUM26gqVPdv63ETfpmc3x9eSIJqWj@jdo7ddbldpClcmHAgnArfFP04T33yHfz4OxwR3QcOIAUYoG7HW1i8) We keep track of the current "rise" size using `m`. If `n` is smaller than or equal to `m`, it fits within the current "rise", and so we return it. However, if it's larger than `m`, we take `m` away from it, than add 1 to `m` and call the function recursively (moving on to the next rise). [Answer] ## R, 25 bytes ``` i=scan();sequence(1:i)[i] ``` The index is 1-based. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~6~~ 5 bytes *1 byte saved thanks to [@TheBikingviking!](https://codegolf.stackexchange.com/users/55526/thebikingviking)* ``` @s._S ``` This uses 0-based indexing. [Try it online!](http://pyth.herokuapp.com/?code=%40s._S&input=10&debug=0) ### Explanation ``` @ Index with implicit input into ._ all prefixes of S 1-based range of implicit input s concatenated into an un-nested list ``` [Answer] # Mathematica, ~~27~~ 24 bytes Thanks @MartinEnder for 3 bytes! ``` ((r=Range)@r@#<>1)[[#]]& ``` 1-indexed. This throws errors that are safe to ignore. **Explanation** ``` ((r=Range)@r@#<>1)[[#]]& r=Range (* Store Range function in r *) r@# (* Create list {1..n} *) (r )@ (* For each element, generate {1..n} *) <>1 (* Join the lists and append a 1; throws errors *) ( )[[#]]& (* Take the nth element *) ``` [Answer] # brainf\*ck, 78 bytes ``` ,>+<[>[->>+>+<<<]>>>[-<<<+>>>]<<+[->->+<<]>[<<->>>[-<<+>>]<[-]]>[-]<<<+<-]>>+. ``` Takes input (0-based) and outputs as byte values. You can test it [here.](https://copy.sh/brainfuck/?c=LD4rPFs-Wy0-Pis-Kzw8PF0-Pj5bLTw8PCs-Pj5dPDwrWy0-LT4rPDxdPls8PC0-Pj5bLTw8Kz4-XTxbLV1dPlstXTw8PCs8LV0-Pisu) Input requires a `\` before decimal numbers (e.g. `\10` for 10). If the output is a printable ASCII character, you should see it. Otherwise, hit view memory -> final dump. The value that was printed is in the 3rd cell (cell number 2). **Explanation:** Cell 0 (INPUT): is the input and is decremented my 1 each time through the loop. Cell 1 (RESET): increments by 1 every time it is equal to TERM. To do this, every time through the loop we add 1 and if they are not equal we subtract 1. Cell 2 (TERM): increments by 1 every loop and is set to 0 if it matches RESET. To do this, I only copy the value back from HOLD if this cell was not equal to RESET. Cell 3 (EQUAL): is used to check if RESET and TERM are equal. Cell 4 (HOLD): is used to copy the values of RESET and TERM back after the equals check. ``` ,>+< # get input and put a 1 in RESET [ # for INPUT to 0 >[->>+>+<<<] # copy RESET to EQUAL and HOLD >>>[-<<<+>>>] # copy HOLD back into RESET <<+ # add 1 to TERM [->->+<<] # subtract TERM from EQUAL and copy it to HOLD >[ # if RESET and TERM were not equal <<- # subtract 1 from RESET >>>[-<<+>>] # copy HOLD back to TERM <[-] # zero out EQUAL ] # end if >[-] # zero out HOLD <<<+ # add 1 to RESET (this cancels out the subtraction if # RESET did not equal TERM) <- # subtract 1 from INPUT ]>>+. # end for and add 1 because the sequence resets to 1 not 0 ``` [Answer] ## Pyke, 6 bytes ``` OmSsQ@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=OmSsQ%40&input=0) ``` O - input+2 mS - map(range(1,i+1), range(^)) s - sum(^) Q@ - ^[input] ``` 0-indexed. [Answer] ## R, 43 41 bytes Edit: Found a shorter recursive approach by using [A002262](https://oeis.org/A002262) + 1 (0 indexed): ``` f=function(n,m=1)`if`(n<m,n+1,f(n-m,m+1)) ``` Old version: ``` n=scan();n-choose(floor((1+sqrt(8*n))/2),2) ``` 1-indexed formula from OEIS. [Answer] # [Perl 6](http://perl6.org/), 21 bytes ``` {map(|^*,^∞)[$_]+1} ``` 0-indexed. [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS1Ow/V@dm1igUROnpRP3qGOeZrRKfKy2Ye3/4sRKhTQFA2suCMMQxjCFixhY/wcA "Perl 6 – TIO Nexus") ### How it works: ``` { } # A lambda. ^∞ # Range from 0 to Inf-1. (Same byte count as 0..*, but cooler.) map( ^*, ) # Map each number n to the range 0..(n-1), | # And slip each range into the outer list. [$_] # Index the sequence with the lambda argument. +1 # Add 1. ``` --- # [Perl 6](http://perl6.org/), 21 bytes ``` {[\,](1..*).flat[$_]} ``` 0-indexed. [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS1Ow/V8dHaMTq2Gop6elqZeWk1gSrRIfW/u/OLFSIU3BwJoLwjCEMUzhIgbW/wE "Perl 6 – TIO Nexus") ### How it works: ``` { } # A lambda. 1..* # Range from 1 to infinity. [ ,]( ) # Fold it with the comma operator, \ # and return all intermediate results, e.g. (1), (1,2), (1,2,3)... .flat # Flatten the sequence. [$_] # Index it with the lambda argument. ``` [Answer] Neither of these solutions is as short as [JungHawn Min's](https://codegolf.stackexchange.com/a/107692/56178), but they're alternate approaches, which is something I guess. Both are unnamed functions taking a (1-indexed) positive integer input and returning a positive integer. # Mathematica, 30 bytes ``` -#^2-#&@⌈√(2#)-3/2⌉/2+#& ``` An actual mathematical formula for this function! Made more readable (in part by translating the 3-byte characters `⌈`, `√`, and `⌉`): ``` # - ((#^2 + #) / 2 &)[Ceiling[Sqrt[2 * #] - 3/2]] & ``` `Ceiling[Sqrt[2 * #] - 1/2]` tells us which sublist the input refers to, from which we subtract one to tell us which sublist ends before we get to the input; then `((#^2 + #) / 2 &)` computes how many elements occur in all the sublists before the one we care about, which we subtract from the input `#` to get our answer. (Some will notice the familiar formula `(#^2 + #) / 2` for the `#`th triangular number; `Ceiling[Sqrt[2 * #] - 1/2]` is essentially the inverse function.) # Mathematica, 32 bytes ``` If[#2<=#,#2,#0[#+1,#2-#]]&[1,#]& ``` Recursive solution, basically the same as in [Billywob's answer](https://codegolf.stackexchange.com/a/107678/56178) and others. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 46 bytes Zero indexed ``` (<>()){(({}())[()]){({}[()])<>}{}}<>([{}()]{}) ``` [Try it online!](https://tio.run/nexus/brain-flak#@69hY6ehqVmtoVFdC6SjNTRjgZzqWjDDxq62urYWqCAaJBlbXav5/78lAA "Brain-Flak – TIO Nexus") ### Stack Clean, 48 bytes ``` (<>()){(({}())[()]){({}[()])<>}{}}{}<>([{}()]{}) ``` [Try it online!](https://tio.run/nexus/brain-flak#@69hY6ehqVmtoVFdC6SjNTRjgZzqWjDDxq62uhaIgEqiQdKx1bWa//9bAgA "Brain-Flak – TIO Nexus") ## Explanation This is a modified version of the [modulo function](https://github.com/DJMcMayhem/Brain-Flak/wiki/Basic-Arithmetic-Operations#modulo-positive-only). Instead of using a constant number as the divisor it increments the divisor for each time the divisor is subtracted from it (once per outside loop iteration). ### Annotated Code ``` (<>()) # Switch to the opposite stack and push 1 (the initial divisor) { # (outside loop) While top of stack is not 0... ( # Push... ({}()) # Push the divisor plus 1 [()]) # ...minus one (ie push a copy of the original divisor { # (inner loop) While the top of stack does not equal zero ({}[()]) # Decrement the top of the active stack <> # Switch stacks }{} # (inside loop) End loop and pop zero off the top of stack) } # (outside loop) End loop <> # Switch stacks (to the one with the divisor) ([{}()]{}) # Calculate the result ``` [Answer] # Java 8, ~~85~~ ~~73~~ 55 bytes ``` n->f(n,1)+1int f(int n,int m){return n<m?n:f(n-m,m+1);} ``` 0-indexed recursive approach with the formula provided in the [OEIS](https://oeis.org/A002260): > > `a(n) = 1 + A002262(n)`. > > [*A002262*](https://oeis.org/A002262): `a(n)=f(n,1)` with `f(n,m) = if n<m then n else f(n-m,m+1)`. > > > [Try it here.](https://tio.run/##jY6xboMwEIZ3nuIfbQVIGDK0tM0ThCVj1cFxTOMUnxEcqaKIZ6c26U4k@6w7/ff5u6irynxr6HL6mXSj@h57ZemeAJbYdLXSBlVs5wG0iJVkGSZjuOFUILxjouyjFpQWclUkZUiv16g8o1Udw9fgs8HxxibTfiBOIqV@sNJYnbx3hoeOQG9uR68BlbnUrQpZjhPQDsfGavSsODxXb09wQVMcuLP0/fkFJR@OUR4u@JD5nRsxqwKHW8/G5X7gvA073JBwOeVabORSolhMbJcZy99sX56gbJ7J/AuPyTj9AQ) --- **Old answer (~~85~~ 56 bytes):** ``` n->{int m=~-(int)Math.sqrt(8*n+1)/2;return n-m*-~m/2+1;} ``` Used the other 0-indexed formula provided in the [OEIS](https://oeis.org/A002260): > > n-th term is `n - m*(m+1)/2 + 1`, where `m = floor((sqrt(8*n+1) - 1) / 2)`. > > > [Try it here.](https://tio.run/##hU7BCsIwDL3vK3Jslc5NEJShf@AuHsVDrVWrazbbTBCZvz479SqFJJD3Xl7eRd6lqBuNl8O1V5X0HtbS4DMBMEjaHaXSUA7rBwDFhom8CEgXOpQnSUZBCQhL6FGsnoPELl9i0PK1pHPqb47YfITjnE@mhdPUOgQUdiRedjId50XXF0nwatp9Fbx@lvfaHMCGOGxDzuBpuwPJv1k2D0/apnVLaRMoqpBhqljGP8n@8nmEn8XuYw9mi6hDFlf8YnZJ178B) [Answer] # MATL, 8 bytes ``` :"@:]vG) ``` This solution uses 1-based indexing Try it at [**MATL Online**](https://matl.io/?code=%3A%22%40%3A%5DvG%29&inputs=6&version=19.7.2) **Explanation** ``` Implicitly grab input (N) : Create an array from [1...N] " For each element (A) in this array... @: Create an array from [1....A] ] End for loop v Vertically concatenate everything on the stack G Explicitly grab the input again ) And use it to index into the vertically concatenated array Implicitly display the result ``` [Answer] # [Perl](https://www.perl.org/), 30 bytes 29 bytes of code + `-p` flag. ``` map{$\-=$c++if$c<++$\}0..$_}{ ``` [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdAt@J@bWFCtEqNrq5KsrZ2ZppJso62tElNroKenEl9b/f@/KQA "Perl – TIO Nexus") [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 21 bytes, 1-indexed ``` :[a|[b|~q=a|_Xc\q=q+1 ``` Explanation: ``` : Get 'a' from the cmd line [a| FOR (b = 1; b <= a; b++) This creates an outer loop from 1 to N [b| FOR (c = 1; c <= b; c++) This creates an iteration, yielding the 1, 12, 123 pattern 'q' stores how many terms we've seen. It starts at 1 b default. ~q=a if we are at the desired term (q == a) |_Xc Then quit, and print 'c' (the current number in the sequence) \q=q+1 Else, increase 'q' and run again. ``` Slightly more interesting approach, but 10 bytes longer: ``` :{~b+q>=a|_xa-b|\b=b+q┘q=q+1 ``` This program continuously calculates the total number of numbers in this bracket and all previous ones (`1 at loop 1, 3 at loop 2, 6 at loop 3 ...`). When that counter exceeds the sought-after index N, then return X from the current bracket, where X is N minus the previous amount of the counter. [Answer] ## Ruby, 30 bytes ``` ->n{(0..n).find{|x|0>=n-=x}+n} ``` 1-based indexing [Answer] # R, 37 bytes ``` n=scan();for(i in 2:n)T=c(T,1:i);T[n] ``` Takes input from `n`, and creates the sequence for the first `n` sequences. This makes it somewhat inefficient at higher inputs, but it should be fine. It then returns the `n`-th entry, 1-indexed. Uses a nice little trick by starting off the sequence with `T`, which is `TRUE` or `1` by default. [Answer] # C11, 48 bytes ``` int f(int x){int q=1;while(x>q)x-=q++;return x;} ``` [Try it online!](https://tio.run/nexus/c-gcc#@6@cmZecU5qSqmBTXJKSma@XYcfFlZlXopCmASIrNKtBVKGtoXV5RmZOqkaFXaFmha5toba2dVFqSWlRnkKFdS1ER25iZp6GZjUXJ1ijNRdncXJiXpqGkmqKko5ahSZQoKAIKAUVSdOo0ASK1f7/b2hgCAA) Also works in C++ and Java. --- An alternative for the same byte count: ``` int f(int x){int q=0;while(x>++q)x-=q;return x;} ``` [Answer] # brainfuck, 141 bytes I know I'm too late for the bounty, but I just wanted to see how many bytes the algorithm I thought of would end up being. This program is zero-indexed. ``` ,>+<[[->>+>+<<<]>>[-<<+>>]<[->+>>+<<<]>[-<+>]>>+[[-<->>+<]>[-<+>]<<<<]>>[>>>]>[.[<<<]]<<<<<<<[[-]>>>[-<+<<+>>>]<[->+<]<<<<<]>>>[>>>]<<<]>[.>] ``` [**Try it online**](https://copy.sh/brainfuck/?c=LD4rPFtbLT4-Kz4rPDw8XT4-Wy08PCs-Pl08Wy0-Kz4-Kzw8PF0-Wy08Kz5dPj4rW1stPC0-Pis8XT5bLTwrPl08PDw8XT4-Wz4-Pl0-Wy4KWzw8PF1dPDw8PDw8PFtbLV0-Pj5bLTwrPDwrPj4-XTxbLT4rPF08PDw8PF0-Pj5bPj4-XTw8PF0-Wy4-XQ$$) * Select **Dynamic (infinite) Memory**, or it won't work * To test input values > `255`, change **Cell size (Bits)** to **16** or **32**. * The interpreter explains how to give input. For **decimal input** use `\5` for input of `5`. + The maximum decimal value you can test input with is `\999` + Hex input can go as high the cell-size. --- ### Explanation: This shows the program broken up by step, showing what happens for input of `5`. `#` are placed in the ideal memory dump locations for the interpreter. You will probably want to use checkbox **Dump Memory at char: `#`** if running this version. This will dump the memory upon hitting `#`, allowing you to see the value on the tape in the event that it's an unprintable character, or to see what happens at any step you want. The cell that the pointer is on will be in bold. ``` ,>+< (5) 1 [[->>+>+<<<]>>[-<<+>>] 5 1 (0) 5 <[->+>>+<<<]>[-<+>]>>+ 5 1 0 5 (2) [[-<->>+<]>[-<+>]<<<<] (0) 0 4 1 0 3 2 0 0 >>[>>>] 4 1 0 3 2 0 (0) 0 1 1 0 (0) 2 0 >[.#[<<<]]<<<< 4 1 0 (3) 2 0 0 0 <<<[[-]>>>[-<+<<+>>>]<[->+<]<<<<<]>>> (3) 1 0 3 2 0 0 0 [>>>]<<<]>[.#>] Tape structure: (cell_1 cell_2 temp), (cell_1 cell_2 temp), ... Take Input; If not zero: copy last pair to the right and add one to its cell_2 subtract each cell_2 from each cell_1 (leaving each cell_2 intact) move checking from left to right: If cell_1 is zero and cell_2 isn't: print cell_2 Else: copy last cell_1 back, overwriting each previous cell_1 Else: right one and print result ``` [**Try it online**](https://copy.sh/brainfuck/?c=LD4rPCAgICAgICAgICAgICAgICAgICAgICAgKDUpIDEKW1stPj4rPis8PDxdPj5bLTw8Kz4-XSAgICAgICA1IDEgKDApIDUKPFstPis-Pis8PDxdPlstPCs-XT4-KyAgICAgICA1IDEgMCA1ICgyKQpbWy08LT4-KzxdPlstPCs-XTw8PDxdICgwKSAwIDQgMSAwIDMgMiAwIDAKPj5bPj4-XSAgICAgICAgICAgICAgICAgICAgICA0IDEgMCAzIDIgMCAoMCkgMAogICAgICAgICAgICAgICAgICAgICAgICAgICAgIDEgMSAwICgwKSAyIDAKPlsuI1s8PDxdXTw8PDwgICAgICAgICAgICAgICAgNCAxIDAgKDMpIDIgMCAwIDAKPDw8W1stXT4-PlstPCs8PCs-Pj5dPFstPis8XTw8PDw8XT4-PiAoMykgMSAwIDMgMiAwIDAgMApbPj4-XTw8PF0-Wy4jPl0KClRhcGUgc3RydWN0dXJlOgogICAgKGNlbGxfMSBjZWxsXzIgdGVtcCksIChjZWxsXzEgY2VsbF8yIHRlbXApLCAuLi4KClRha2UgSW5wdXQ7CklmIG5vdCB6ZXJvOgogIGNvcHkgbGFzdCBwYWlyIHRvIHRoZSByaWdodCBhbmQgYWRkIG9uZSB0byBpdHMgY2VsbF8yCiAgc3VidHJhY3QgZWFjaCBjZWxsXzIgZnJvbSBlYWNoIGNlbGxfMSAobGVhdmluZyBlYWNoIGNlbGxfMiBpbnRhY3QpCiAgbW92ZSBjaGVja2luZyBmcm9tIGxlZnQgdG8gcmlnaHQ6IAogICAgSWYgY2VsbF8xIGlzIHplcm8gYW5kIGNlbGxfMiBpc24ndDoKICAgICAgcHJpbnQgY2VsbF8yCiAgICBFbHNlOgogICAgICBjb3B5IGxhc3QgY2VsbF8xIGJhY2ssIG92ZXJ3cml0aW5nIGVhY2ggcHJldmlvdXMgY2VsbF8xCkVsc2U6CiAgcmlnaHQgb25lIGFuZCBwcmludCByZXN1bHQ$) * Select **Dynamic (infinite) Memory**, or it won't work * **Dump Memory at char: `#`** --- Notes: * To run this on another interpreter that doesn't allow moving to the left of the starting cell (that's why I use Dynamic Memory), put in a bunch of `>` at the start. The number required may vary depending on the input value, but is O(1). [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) (repl), 90 bytes (0-indexed) ``` (d r(q((n j x)(i n(i(e j x)(r(s n 1)1(s x(s 0 1)))(r(s n 1)(s j(s 0 1))x))j (q((n)(r n 1 1 ``` Or, non-competing (using a feature that was committed after this challenge was posted), **80 bytes**: ``` (d r(q((n j x)(i n(i(e j x)(r(s n 1)1(a x 1))(r(s n 1)(a j 1)x))j (q((n)(r n 1 1 ``` The first line defines a helper function `r`, and the second line is an unnamed function that takes `n` and returns the nth term of the sequence. I've specified this as a repl submission because the repl autocompletes parentheses at the end of every line, not just at the end of the program. With those caveats, here's a version modified to work at [Try it online](https://tio.run/nexus/tinylisp#RYwxDoAwDAN3XuHR3po/wdAMlShLfh9CEWKIHNsnJ3dMnuSAI8SOwc7jNZMXBkxWGnWtfv1xiX9pSF6dNq6xgh5k8bDWTJk3), and here's an [ungolfed version](https://tio.run/nexus/tinylisp#hY/BCoMwEETvfsUck0OhCp77KWVt1hKIsY3m0K@Pm0YhQqE5bYY3M0xSbiYDZ4dA4aObRhkecQ924UvghdcGUI6mwZBccns85uhXDuKZ7KqLakcofkdyN3hci4iD3H819CPji1TFUEscOolrNVooMqYruAj/HYU/akQoTfntG2tfGSjj9DlQonJbtkz0OlkC@Sej77VOaQM) run against inputs 0 through 54. ### Explanation I'll use the noncompeting version here. The only difference is that the official version has to implement addition as two subtractions. ``` (d r Define r to be: (q( A lambda function (= a list of two elements, quoted to prevent evaluation): (n j x) Arguments n, j (the range counter), and x (the range limit) (i n If n is truthy, i.e. nonzero: (i(e j x) If counter equals limit: (r Call r recursively on: (s n 1) n-1 1 counter reset to 1 (a x 1)) limit increased by 1 (r Else, call r recursively on: (s n 1) n-1 (a j 1) counter increased by 1 x)) same limit j)))) Else, we're done; return the counter value (q( Lambda function: (n) Argument n (r n 1 1))) Call r with n, counter = 1, range limit = 1 ``` [Answer] # C, 54 bytes Not the shortest C solution, but it has the merit of running in constant time (no loops, just math). It uses zero-based indexing: ``` x;f(n){x=floor(sqrt(8*n+1)-1)/2;return 1+n-x*(x+1)/2;} ``` Ungolfed: ``` int f(int n) { int x = floor(sqrt(8*n+1)-1)/2; //calculate the number of the current subsequence (zero based) return 1+n-x*(x+1)/2; //x*(x+1)/2 is the zero based index of the `1` starting the subsequence } ``` Test with: ``` #include <math.h> #include <assert.h> #include <stdio.h> x;f(n){x=floor(sqrt(8*n+1)-1)/2;return 1+n-x*(x+1)/2;} int main(){ int i; for(i = 0; i < 10; i++) printf("%d ", f(i)); printf("\n"); assert(f(0) == 1); assert(f(1) == 1); assert(f(5) == 3); assert(f(10) == 1); assert(f(59) == 5); assert(f(100) == 10); assert(f(1001) == 12); } ``` [Answer] # C, 103 bytes For a begginer it's okay, I think :). ``` int main(){int n,c,i,j;scanf("%d",&n);while(c<n){for(i=1;i<=j;i++){c++;if(c==n)printf("%d",i);}j++;}} ``` or the formatted way ``` #include <stdio.h> int main() { int n,c,i,j; scanf("%d",&n); while(c<n) { for(i=1;i<=j;i++) { c++; if(c==n) printf("%d",i); } j++; } } ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 21 bytes, 0-based indexing ``` ?d8*1+v1-2/d1+*2/-1+p ``` [Try the dc program online!](https://tio.run/nexus/dc#@2@fYqFlqF1mqGukn2KorWWkr2uoXfD/v6GBgSEA "dc – TIO Nexus") Explanation: ``` ? Push input number n. d Duplicate n at the top of the stack. 8*1+ Replace n at the top of the stack with 8n+1. v Replace 8n+1 at the top of the stack with the floor of its square root. 1-2/ Subtract 1, and divide by 2 (ignoring any fractional part). ``` The top of the stack now holds the index k of the greatest triangular number that is <= n. ``` d1+*2/ Compute k(k+1)/2, which is the greatest triangular number <= n. - Subtract n-(the greatest triangular number <= n). The first n is on the stack in position 2, because the input number n was duplicated at the top of the stack at the very beginning of the program, and only one of the values was popped and used (until now). 1+ Add 1 because the desired sequence starts over again at 1 (not 0) at every triangular number. p Print the answer. ``` This dc program can be converted into a competitively-sized bash script: # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 28 bytes, 0-based indexing ``` dc -e"?d8*1+v1-2/d1+*2/-1+p" ``` [Try the bash program online!](https://tio.run/nexus/bash#@5@SrKCbqmSfYqFlqF1mqGukn2KorWWkr2uoXaD0/7@hgYHhfwA "Bash – TIO Nexus") [Answer] # C, ~~81~~ 44 bytes straight iterative method, 0 indexed, and with some gentle massaging; ``` m=1,c=1;f(n){for(;n--;c=c^m?c+1:!!++m);c=c;} ``` [Try it online!](https://tio.run/nexus/c-gcc#FcixCoAgEADQva@4hOAOE3JoqEP6kyAsocErpCbp263e@Ep0tvXOckChHI6ELMawd36Ok9d2rGutI/3BT9nlgrjsggS5AoAzfRNQNatqA/YDEf@dtutOAh1XT@mHFw "C (gcc) – TIO Nexus") ]
[Question] [ A common visual explanation of the Pythagorean theorem is as such: [![3 boxes](https://i.stack.imgur.com/PJFZl.gif)](https://i.stack.imgur.com/PJFZl.gif) The squares are meant to represent the side length's squared, and the areas of `a + b = c`, just like the Pythagorean theorem says. This part is what you have to show. # Your task * You will get two integers as input, meant to represent sides `a` and `b` of a right triangle (ex. `3, 4`). * You will then make squares out of the lengths `a`, `b`, and `c` out of the `#` character. For example here is 3: ``` ### ### ### ``` * You will then format these into a math equation that explains the particular Pythagorean triplet: ``` ##### #### ##### ### #### ##### ### #### ##### ### + #### = ##### ``` * Notice how the `=` and `+` signs have spaces on both sides and how everything is on the bottom. * You will never get values for `a` and `b` that make `c` non-integral. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in **bytes** wins! # Test Cases (more coming once I have time, these are really hard to make by hand) ``` 3, 4 ##### #### ##### ### #### ##### ### #### ##### ### + #### = ##### 6, 8 ########## ########## ######## ########## ######## ########## ###### ######## ########## ###### ######## ########## ###### ######## ########## ###### ######## ########## ###### ######## ########## ###### + ######## = ########## 4, 3 ##### #### ##### #### ### ##### #### ### ##### #### + ### = ##### 5, 12 ############# ############ ############# ############ ############# ############ ############# ############ ############# ############ ############# ############ ############# ############ ############# ##### ############ ############# ##### ############ ############# ##### ############ ############# ##### ############ ############# ##### + ############ = ############# ``` [Answer] # Pyth, 35 32 31 30 bytes ``` j_.ts.i.imm*d\#d+Qs.aQ"+="mk4d ``` [Try it online.](https://pyth.herokuapp.com/?code=j_.ts.imm*d%5C%23d%2BQs.aQm%5Bkdk)%22%2B%3D%22d&test_suite=1&test_suite_input=3%2C+4%0A6%2C+8%0A4%2C+3%0A5%2C+12&debug=0) [Answer] # CJam, 49 bytes ``` " + = "S/3/[q~_2$mh:H]_'#f*:a.*.\:+SH*f.e|zW%N* ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%20%2B%20%20%20%3D%20%22S%2F3%2F%5Bq%7E_2%24mh%3AH%5D_%27%23f*%3Aa.*.%5C%3A%2BSH*f.e%7CzW%25N*&input=3%204). ### How it works ``` " + = "S/3/ e# Split at spaces, then into chunks of length 3. e# This pushes [["" "+" ""] ["" "=" ""]]. [ e# q~ e# Read and interpret all input from STDIN. _2$ e# Copy both integers. mh e# Calculate the hypotenuse of the triangle with those catheti. :H e# Save the result in H. ] e# Collect catheti and hypotenuse in an array. _'#f* e# Copy and replace each length with a string of that many hashes. :a e# Wrap each string in an array. .* e# Vectorized repetition. Turns strings into square arrays. .\ e# Interleave with the string of operators. :+ e# Concatenate to form an array of strings. SH* e# Push a string of spaces of length H. f.e| e# Mapped vectorized logical OR; pads all strings with spaces to e# length H. zW% e# Zip and reverse; rotates the array. N* e# Join the strings, separating by linefeeds. ``` [Answer] # Python 2, ~~134~~ 100 bytes ``` a,b=input() i=c=int(abs(a+b*1j)) while i:print"# "[i>a]*a," +"[i<2],"# "[i>b]*b," ="[i<2],"#"*c;i-=1 ``` [Try it online.](http://ideone.com/Yw7JOz) The program takes input as comma-separated integers, calculates the hypotenuse using Python's built-in complex numbers, then loops down from that value calculating and printing each line as it goes. The main golfing trick is using string indexing in place of conditionals to select `#`/`+`/`=` vs space. *Edit:* The first version was a victim of some serious over-engineering--this one is both simpler and much shorter. [Answer] # JavaScript ES6, ~~155~~ ~~134~~ ~~140~~ 129 bytes ``` (n,m)=>eval("for(o='',q=(b,s)=>' #'[z<b|0].repeat(b)+(z?' ':s),z=i=Math.hypot(n,m);z--;)o+=q(n,' + ')+q(m,' = ')+q(i,'')+`\n`") ``` I've rewritten this with `for`. Lots of golfing still... If something isn't working, let me know. I'll fix it in the morning. **Tested on Safari Nightly** ## Ungolfed: ``` (n,m)=> Array( z=Math.hypot(n,m) ).fill() .map((l,i)=> (q=(j,s)=> (z-i<=j?'#':' ') .repeat(j)+ (z-i-1?' ':s) ) (n,`+`)+ q(m,`=`)+ q(z,'') ).join` ` ``` # Explanation: (Not updated) but still accurate enough. ``` (n,m)=> // Function with two arguments n,m Array( // Create array of length... z=Math.hypot(n,m) // Get sqrt(n^2+m^2) and store in z ).fill() // Fill array so we can loop .map((l,i) => // Loop z times, take l, and i (index) (q=j=>( // Create function q with argument j z-i<=j? // If z-i is less than or equal to j... '#' // Use '#' : // OR ' ' // Use space ).repeat(j) // Repeat the character j times )(n) // Run with n + // Add to string ` ${ // Space (b=z-i-1)? // If this isn't the last line... ' ' // Return ' ' : // Otherwise '+' // Plus } ${ // Space q(m) // run function q with arg m } ${ // Space b? // If b ' ' // Return space : // Otherwise '=' // '=' }` + // Add to... '#'.repeat(z) // Repeat hashtag, z times ).join` // Join the new array with new lines ` ``` # DEMO ES5 version **Input must be valid sets of numbers**: ``` function _taggedTemplateLiteral(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var _templateObject=_taggedTemplateLiteral(["\n"],["\n"]),t=function(e,t){return Array(z=Math.sqrt(e*e+t*t)).fill().map(function(r,n){return(q=function(e,t){return(z-n<=e?"#":" ").repeat(e)+(z-n-1?" ":t)})(e,"+")+q(t,"=")+q(z,"")}).join(_templateObject)}; // Demo document.getElementById('go').onclick=function(){ document.getElementById('output').innerHTML = t(+document.getElementById('input').value, +document.getElementById('input2').value) }; ``` ``` <div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Visually Explaining the Pythagorean Theorem</h2><div><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Number 1" style="resize:none;border:1px solid #DDD;" id="input"><input placeholder="Number 2" style="resize:none;border:1px solid #DDD;" id="input2"><button id='go'>Run!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div> ``` [Answer] # Julia, ~~121~~ ~~114~~ 112 bytes ``` f(a,b)=for i=1:(c=isqrt(a^2+b^2)) g(x,t)=(i>c-x?"#":" ")^x*(i<c?" ":t)" ";println(g(a," +")g(b," =")g(c,""))end ``` Ungolfed: ``` function f(a,b) # Compute the hypotenuse length c = isqrt(a^2 + b^2) # Write the lines in a loop for i = 1:c # Make a function for constructing the blocks g(x,t) = (i <= c - x ? " " : "#")^x * (i < c ? " " : t) " " println(g(a," +") g(b," =") g(c,"")) end end ``` Fixed issue and saved 2 bytes thanks to Glen O. [Answer] # Pyth, ~~51~~ 49 bytes ``` AQJs.aQLj*b]*b\#;j_MCm_.[d\ Jcj[yJb\=byHb\+byG))b ``` Expects input in the form `[3,4]`. [Try it here](http://pyth.herokuapp.com/?code=AQJs.aQLj*b]*b%5C%23%3Bj_MCm_.[d%5C+Jcj[yJb%5C%3DbyHb%5C%2BbyG%29%29b&input=[3%2C+4]) `AQ` - assigns input to `G, H` `Js.a,GH` - calculates hypotenuse as `J` `Lj*b]*b\#;` - defines `y(b)` as making a square of size `b` (elsewhere in the code, `b` means newline) `j_MCm_.[d\ Jcj[yJb\=byHb\+byG))b` - Creates the squares, pads with spaces, and transposes Saved two bytes thanks to Maltysen. [Answer] # C, 176 bytes C is not going to win this, but the fun is worth it. ``` #define A(x,y)for(j=x;j--;)putchar("# "[i+1>x]);printf(i?" ":" "#y" "); i;j;main(a,b,c){for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c;c++);for(i=c;i--;puts("")){A(a,+)A(b,=)A(c,)}} ``` Pretty printed: ``` #define A(x,y)for(j=x;j--;)putchar("# "[i+1>x]);printf(i?" ":" "#y" "); i;j; main(a,b,c) { for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c;c++); for(i=c;i--;puts("")) { A(a,+) A(b,=) A(c,) } } ``` gcc enables us to pass third parameter to main (an array of environment variables), so we take advantage of it to use it for our purpose. The ``` for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c++;); ``` would be equivalent to ``` scanf("%d %d",&a,&b); for(c=2;a*a+b*b>c*c++;); ``` because `scanf` returns the number of successfully scaned parameters. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ⊞θ₂ΣXθ²F =+«←←←ι←G↑←↓⊟θ# ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1BHIbiwNLEoNSg/v0QjuDRXIyC/PLUIJG6kCQTWXGn5RQoaSgq22kqaCtVcnL75ZakaVj6paSVAOTReQFFmXgmEq6OQiUU@P6cyPT9Pwyq0QEcBqszKJb88T0chIL9Ao1BTR0FJWQmosvb//@hoYx0Fk9jY/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of two elements. Explanation: ``` ⊞θ₂ΣXθ² ``` Append the hypotenuse to the inputs. ``` F =+« ``` Loop over the characters that appear to the right of each square in reverse order. ``` ←←←ι← ``` Print that character leftwards with spacing. ``` G↑←↓⊟θ# ``` Pop the last number from the array and print a square of `#`s of that size. [Answer] # Ruby, 134 ``` ->a,b{c=((a**2+b**2)**0.5).round c.times{|i| d=i<c-1?' ':'+=' puts (c-i>a ?' ':?#)*a+" #{d[0]} #{(c-i>b ?' ':?#)*b} #{d[1]} "+?#*c}} ``` simple line by line approach. Below in test program, with symbol changed to @ to help avoid confusting with the syntax `#{....}` ("string interpolation") used to insert expressions into a string. Each input should be given on a different line. ``` f=->a,b{c=((a**2+b**2)**0.5).round c.times{|i| d=i<c-1?' ':'+=' puts (c-i>a ?' ':?@)*a+" #{d[0]} #{(c-i>b ?' ':?@)*b} #{d[1]} "+?@*c}} A=gets.to_i B=gets.to_i f.call(A,B) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~33~~ 29 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") -3 due to my extensions of Dyalog APL. Anonymous prefix lambda: ``` {⊖⍕,' +=',⍪{⍵ ⍵⍴⍕#}¨⍵,√+/⍵*2} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR17RHvVN11BW0bdV1HvWuqn7Uu1UBiB/1bgGKK9ceWgHk6DzqmKWtD2RoGdX@T3vUNuFRb9@jvqme/o@6mg@tN37UNhHICw5yBpIhHp7B/9MUjBVMuNIUzBQsgKSJgjGQNFUwNAIA "APL (Dyalog Extended) – Try It Online") `{`…`}` "dfn"; `⍵` is the argument (side lengths)  `⍵*2` square  `+/` sum  `√` square-root  `⍵,` prepend argument  `{`…`}¨` apply the following anonymous lambda to each   `#` root namespace   `⍕` format as text   `⍵ ⍵⍴` use argument twice to **r**eshape into matrix with those dimensions.  `⍪` make into column  `' ++=',` prepend these three characters to the three rows  `,` ravel (combine rows into list)  `⍕` format as text  `⊖` flip upside-down [Answer] # PHP, ~~178~~ ~~170~~ 168 bytes Input is GET parameters `x` and `y`. Unfortunately I can't seem to golf those repeating strings. ``` <?php for(@$i=$z=hypot($x=$_GET[x],$y=$_GET[y]),@$s=str_repeat;$i;$i--)@print$s($i<=$x?~Ü:~ß,$x).(($l=$i==1)?~ßÔß:~ßßß).$s($i<=$y?~Ü:~ß,$y).($l?~ßÂß:~ßßß).$s(~Ü,$z).~õ; ``` * Saved 8 bytes by inverting all my strings and dropping the quotes. * Saved 2 bytes by replacing the condition `$i>0` with `$i` Not sure why PHP doesn't like `@echo` so I had to sacrifice 1 byte with `@print`. In case SE screws up the encoding, this is meant to be encoded in Windows-1252 (not UTF8). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~139~~ ~~137~~ 135 bytes -2 thanks to ASCII-only -2 thanks to Mazzy ``` param($a,$b)($c=[math]::sqrt($a*$a+$b*$b))..1|%{(($m=" ","#")[$_-le$a]*$a)," +"[$_-eq1],($m[$_-le$b]*$b)," ="[$_-eq1],("#"*$c)-join" "} ``` [Try it online!](https://tio.run/##TYxBCoMwFET3niL8/pYkRkFaShFyEgklSsSKVo1CF9azp9/SRXfDvDczDi/n58Z1XcBar2G03vYcrcJScKx00dulMXk@T36hWqKNsZQERZpm7@PKOfYaGCg4gCjwnnQOrSFNKGAx7I2bMqNI@9HS7HOi@o/SWmIlknZ4POltC1t0wpqd2SUC@MYbu0bhAw "PowerShell – Try It Online") Calculating $c hurt and there's probably a better way to conditionally swap between `#` and . Builds a list of chunks and joins them together while conditionally adding the signs. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `L`, ~~47~~ ~~43~~ 38 bytes (old codepage) ``` λ\#*wnř;:£f⍎÷ð\+ð?¥f⍎÷ð\=ð??Ķĵ∑√I¥f⍎÷W ``` This was *intense*. Also, according to code-golf's statistics, only a small percentage of people who see my answers actually upvote them. So if you enjoy this answer, consider upvoting, it's free, and you can change your mind at any time (given you have ≥2k rep). Enjoy the answer. ## Explained ``` λn\#*wnř;:£f⍎ðJ\+JðJ?¥f⍎JðJ\=JðJ??Ķĵ∑√I¥f⍎J λ # Start a lambda that: n\#* # Repeats the character "#" n times THEN w # Wraps that into a stack AND nř # Repeats the list n times ; # Close lambda :£f # Assign the lambda to variable 'f' leaving an extra copy ⍎ # Apply that lambda to the first input ðJ\+JðJ # Append " ", "+" and " " to the result from above ?¥f⍎ # Apply the lambda to the second input J # Add it to the current list ðJ\=Jð # Append " ", "=" and " " to the result from above ??Ķ # Pair the two inputs into a list ĵ∑ # Square each number and sum the list (a^2 + b^2) √I # Square root that number and convert it to an integer ¥f⍎ # Apply the lambda to that result (c) J # And add it to the big list # The L flag then auto vertical joins the list and outputs it ``` [Answer] # CJam, 78 bytes ``` q~_2f#~+mQ+ee_2=~e>f{\~@1$-S*\'#*+_'#e=\a*_0=,S*@"+= "=1$,(S*\+1$a\a@a+++~}zN* ``` It first computes the hypotenuse (H), then, for each side (S), it builds an array of S lines made of: `H-S` spaces + `S` dashes. Finally, it transposes the matrix. [Demo](http://cjam.aditsu.net/#code=q~_2f%23~%2BmQ%2Bee_2%3D~e%3Ef%7B%5C~%401%24-S*%5C'%23*%2B_'%23e%3D%5Ca*_0%3D%2CS*%40%22%2B%3D%20%22%3D1%24%2C(S*%5C%2B1%24a%5Ca%40a%2B%2B%2B~%7DzN*&input=%5B6%208%5D) [Answer] # Lua5.2, ~~257~~ ~~241~~ ~~227~~ 222 bytes ``` r=io.read a=r"*n"b=r"*n"c=math.sqrt(a^2+b^2)d=a+b w=io.write for i=1,c do for j=0,d+c+5 do w((j>d+5 or(i>c-b and j>a+2 and j<d+3)or(i>c-a and j<a))and"#"or(i==c and(j==a+1 and"+"or(j==d+4 and"="or" "))or" "))end w"\n"end ``` * Edit1: Simplified reading * Edit2: Removed more whitespaces * Edit3: aliases abstraction of `io` functions inspired by [another answer](https://codegolf.stackexchange.com/a/55923/13223) [Answer] # Japt, 28 bytes Takes input as an array of integers. ``` pUx²¬)ËÆDç'# í"+="¬ûR3)c ·z3 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=cFV4sqwpy8ZE5ycjCu0iKz0irPtSMyljILd6Mw==&input=WzMsNF0=) ``` :Implicit input of array U=[a,b] pUx²¬)ËÆDç'# p :Push U ² : Square each element in U x : Reduce by addition ¬ : Square root ) :End push Ë :Map each D Æ : Map the range [0,D) Dç'# : Repeat "#" D times í"+="¬ûR3)c ·z3 í :Interleave "+="¬ : Split the string "+=" to an array of characters û : Centre pad each R3 : With newlines to length 3 ) :End interleave c :Flatten · :Join with newlines z3 :Rotate clockwise 270 degrees ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 99 bytes ``` {$!=sqrt $^a²+$^b²;flip map({map {[' ','#'][$^d>$_]x$d,' =+ '.comb[!$_*++$ ]},$!,$b,$a},^$!)X" "} ``` [Try it online!](https://tio.run/##PcfRCoIwFIDhe5/izA7NtUNQWjeyniMYTmYqBEqmXSRjL@Uj@GIrCLr5@f6hGbtz6GfYtqAgOGRqeo4vQGPXRaKp1iVvu/sAvR0S9w04zYET3/BCo6kvWBZvrImDksD3t0dfaYblTkqEwhMyworQejLIxDWOYh8mO0ObpJSJPPr5RIfjfzJKRR4@ "Perl 6 – Try It Online") Anonymous code block that takes two numbers and returns the full string with a leading newline and three leading spaces and one trailing on each line. If we can use other characters instead of `#`, then I can save a byte by replacing `'#'` with `\*`. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~221~~, 194 bytes This feels way too long. This version just loops to construct the string. EDIT: Ascii-Only with a nice -27 byte golf using the string constructor for serial char additions! Also, ty for pointing out I was using Math.Sqrt not System.Math.Sqrt. This has been adjusted! ``` (a,b)=>{int c=(int)System.Math.Sqrt(a*a+b*b),j=c;var s="";while(j>0)s+=new string(j>a?' ':'#',a)+(j>1?" ":" + ")+new string(j>b?' ':'#',b)+(j-->1?" ":" = ")+new string('#',c)+"\n";return s;} ``` [Try it online!](https://tio.run/##XY5BSwMxEIXv@yuGeNik2S1W8NKY7UHwZEHowYuXSTZtU9KsJtkWKf3ta1aLWBmYYeZ9vHk61roLZuij9RtYfcZk9qLQDmOEl9BtAu5PBcB7r5zVEBOmPA6dbWGJ1lM2igBPvdcP1qcKvltMIbs10IIcKFaKyeaUBdCS5sF@vkyXmLbT1UdIFCfI1USxaie1OGCAKAkRx611hu6aWxa59OZ4sc0XXJRQzsubskLG8z5bkByCzAlwIIxfseqXVSNb139o@Y8eKc04efNEBJP64CGK8yCKS@LHzsfOmelrsMk8W29oS@@r2R1joiiKc65h3dvWRXRr/AI "C# (.NET Core) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` nOtª©Å1'#×ζε®×R„= NĀèð.øý}»R„=+`.; ``` Takes the input as pair of integers (i.e. `[3,4]`). [Try it online](https://tio.run/##yy9OTMpM/f8/z7/k0KpDKw@3GqorH55@btu5rYfWHZ4e9Khhnq2C35GGwysOb9A7vOPw3tpDu8GC2gl61v//RxvrKJjEAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3l4go6Sf2kJhKvzP8@/5NCqQysPtxqqKx@efm7bua2H1h2eHvSoYZ6tgt@RhsMrDm/QO7zj8N7aQ7vBgtoJetb/dQ5ts/8fHW2sYxKroxBtpmMBokx0jEGUqY6hUWwsAA). **Explanation:** ``` n # Take the square of each value in the (implicit) input-list O # Take the sum of that list t # Take the square-root of that sum ª # Append it to the (implicit) input-list # i.e. [3,4] → [3,4,5.0] © # Store it in the register (without popping) Å1 # Change each value to an inner list of that amount of 1s '#× '# And then each 1 to a "#" # → [["#","#","#"],["#","#","#","#"],["#","#","#","#","#"]] ζ # Zip/transpose; swapping rows/columns, with space as default filler # → [["#","#","#"],["#","#","#"],["#","#","#"],[" ","#","#"],[" "," ","#"]] ε # Map the inner lists to: ® # Push the list from the register × # Repeat the characters that many times # i.e. [" ","#","#"] and [3,4,5.0] → [" ","####","#####"] R # Reverse this list „= # Push string "= " NĀ # Push the map-index truthified (0 remains 0; everything else becomes 1) # i.e. 0 → 0 # i.e. 3 → 1 è # Use it to index into the string ð.ø # Surround it with spaces # → "=" → " = " # → " " → " " ý # Join the map-list together with this string as delimiter # → "##### #### " }» # After the map, join everything by newlines # → "##### = #### = ###\n##### #### ###\n##### #### ###\n##### #### \n##### " R # Reverse the string # → " #####\n #### #####\n### #### #####\n### #### #####\n### = #### = #####" „=+`.; # And replace the first "=" with "+" # → " #####\n #### #####\n### #### #####\n### #### #####\n### + #### = #####" # (after which the the result is output implicitly) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 36 bytes ``` ↔T' `+₁√ṁ□¹`+C1" = "JC1" + "m₁ SRR'# ``` [Try it online!](https://tio.run/##yygtzv7//1HblBB1hQTtR02NjzpmPdzZ@GjawkM7E7SdDZUUbBWUvEC0toJSLlCeKzgoSF35////0cY6JrEA "Husk – Try It Online") This can be made shorter if I can find a good way to add the symbols in. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~122~~ 119 bytes -3 thanks to ceilingcat ``` #define P(n);for(i=0;i*i++<n;puts(""))for(j=0;j*j++<n;)putchar(35);puts( i,j;f(a,b){P(a*a)"+")P(b*b)"=")P(a*a+b*b)"");} ``` [Try it online!](https://tio.run/##TYzBDsIgDIbvPEWDlxZmMjWe6t5hrwC4KSSiwe207NmRsYs9tH@/r6k7PpzL@XAfRh8H6DESj@@EvmvZK6/1LfJnnr4oJdEmQhFBhSqoGPc0CS9X2q@EbwKPaBpLS49GGZJaUo9WWZLdlgrTdZPEa/ZxgpfxEQkWIaDURgx0cG3AlnE6c8W17Y//QBqmOUVoWaz5Bw "C (gcc) – Try It Online") ]
[Question] [ Given an integer `n > 9`, for each possible insertion between digits in that integer, insert an addition `+` and evaluate. Then, take the original number modulo those results. Output the sum total of these operations. An example with `n = 47852`: ``` 47852 % (4785+2) = 4769 47852 % (478+52) = 152 47852 % (47+852) = 205 47852 % (4+7852) = 716 ----- 5842 ``` ### Input A single positive integer [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), `n > 9`. ### Output The single integer output following the above construction technique. ### Rules * You don't need to worry about input larger than your language's default type. * 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. ### Examples ``` 47852 -> 5842 13 -> 1 111 -> 6 12345 -> 2097 54321 -> 8331 3729105472 -> 505598476 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes ``` v¹¹N¹‚£O%O ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=dsK5wrlOwrnigJrCo08lTw&input=NDc4NTI) [Answer] # JavaScript, ~~43~~ 47 bytes ``` f= n=>eval(n.replace(/./g,'+'+n+"%($`+ +'$&$'')")) I.oninput=_=>O.value=f(I.value) ``` ``` <input id=I> <input id=O disabled> ``` Takes input as string. --- Edit: **+4 bytes**: Leading zeroes in JavaScript converts the number to octal ): [Answer] # [Brachylog v1](http://github.com/JCumin/Brachylog), 20 bytes ``` :{$@~c#C:@$a+:?r%}f+ ``` [Try it online!](http://brachylog.tryitonline.net/#code=OnskQH5jI0M6QCRhKzo_ciV9Zis&input=MzcyOTEwNTQ3Mg&args=Wg) ### Explanation This implements the formula given. The only thing we have to be careful about is when a `0` is in the middle of the input: in that case Brachylog gets pretty quirky, for example it won't accept that a list of integers starting with a `0` can be concatenated into an integer (which would require ignoring the leading `0` — this is mainly programmed that way to avoid infinite loops). Therefore to circumvent that problem, we convert the input to a string and then convert back all splitted inputs into integers. ``` Example Input: 47852 :{ }f Find all outputs of that predicate: [716,205,152,4769] $@ Integer to String: "47852" ~c#C #C is a list of two strings which when concatenated yield the Input e.g. ["47","852"]. Leave choice points for all possibilities. :@$a Apply String to integer: [47,852] + Sum: 899 :?r% Input modulo that result: 205 + Sum all elements of that list ``` [Answer] # ES6 (Javascript), ~~42~~, 40 bytes EDITS: * Got rid of *s*, -2 bytes **Golfed** ``` M=(m,x=10)=>x<m&&m%(m%x+m/x|0)+M(m,x*10) ``` **Test** ``` M=(m,x=10)=>x<m&&m%(m%x+m/x|0)+M(m,x*10); [47852,13,111,12345,54321,3729105472].map(x=>console.log(M(x))); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖṖLÐṂḌS€⁸%S ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=xZLhuZbhuZZMw5DhuYLhuIxT4oKs4oG4JVM&input=&args=NDc4NTI)** ### How? ``` ŒṖṖLÐṂḌS€⁸%S - Main link: n ŒṖ - partitions (implicitly treats the integer n as a list of digits) Ṗ - pop - remove the last partition (the one with length one) ÐṂ - keep those with minimal... L - length (now we have all partitions of length 2) Ḍ - undecimal (convert each entry back to an integer) S€ - sum each (add the pairs up) ⁸ - left argument, n % - mod (vectorises) S - sum ``` [Answer] ## Python 2, 45 bytes ``` f=lambda n,c=10:n/c and n%(n/c+n%c)+f(n,c*10) ``` Uses arithmetic rather than strings to divide the input `n` into parts `n/c` and `n%c`, which `c` recurses through powers of 10. [Answer] # Perl ~~35 32~~ 27 Bytes Includes +3 for `-p` Saved 8 bytes thanks to Dada ``` $\+=$_%($`+$')while//g}{ ``` [Answer] # C 77 + 4 = 81 bytes ### golfed ``` i,N,t,r,m;f(n){for(r=0,m=n;n;t=n%10,n/=10,N+=t*pow(10,i++),r+=m%(n+N));return r;} ``` ### Ungolfed ``` #include<stdio.h> #include<math.h> i,N,t,r,m; f(n) { m=n; r=0; while(n) { t=n%10; n/=10; N+=t*pow(10,i++); r+=m%(n+N); } return r; } main() { printf("%d",f(47852)); } ``` [Answer] ## Python 2, ~~68~~ ~~64~~ 68 bytes -4 bytes thanks to atlasologist ``` lambda x:sum(int(x)%(int(x[:i])+int(x[i:]))for i in range(1,len(x))) ``` \*Input is a string [Answer] # C, 59 bytes ``` t,s;f(n){s=0;t=10;while(t<n)s+=n%(n/t+n%t),t*=10;return s;} ``` `t` is `10,100,1000,...` and represents the cut in the big number. `n/t` is the right part and `n%t` the left part. If `t` is bigger than the number, it is finished. Ungolfed and usage: ``` t,s; f(n){ s=0; t=10; while(t<n) s += n % (n/t + n%t), t *= 10; return s; } main(){ printf("%d\n",f(47852)); } ``` [Answer] ## [Retina](http://github.com/mbuettner/retina), 38 bytes Byte count assumes ISO 8859-1 encoding. ``` \B ,$';$_¶$` G-2` \d+|, $* (1+);\1* 1 ``` Not exactly efficient... [Try it online!](http://retina.tryitonline.net/#code=JShHYApcQgosJCc7JF_CtiRgCkctMmAKXGQrfCwKJCoKKDErKTtcMSoKCjE&input=MTMKMTExCjEyMzQ1CjQ3ODUyCjU0MzIx) (The first line enables a linefeed-separated test suite.) ### Explanation ``` \B ,$';$_¶$` ``` Between every pair of characters, we insert a comma, everything in front of the match, a semicolon, the entire input, a linefeed, and everything after the match. For input `12345` this gives us: ``` 1,2345;12345 12,345;12345 123,45;12345 1234,5;12345 12345 ``` I.e. every possible splitting of the input along with a pair of the input. We don't need that last line though so: ``` G-2` ``` We discard it. ``` \d+|, $* ``` This replaces each number as well as the comma with its unary representation. Since the comma isn't a number, it's treated as zero and simply removed. This adds the two parts in each splitting. ``` (1+);\1* ``` This computes the modulo by removing all copies of the first number from the second number. ``` 1 ``` That's it, we simply count how many `1`s are left in the string and print that as the result. [Answer] # Pyth, 14 bytes ``` s.e%QssMc`Q]k` ``` A program that takes input of an integer and prints the result. [Test suite](http://pyth.herokuapp.com/?code=s.e%25QssMc%60Q%5Dk%60&test_suite=1&test_suite_input=47852%0A13%0A111%0A12345%0A54321%0A3729105472&debug=0) **How it works** ``` s.e%QssMc`Q]k` Program. Input: Q s.e%QssMc`Q]k`Q Implicit input fill .e `Q Map over str(Q) with k as 0-indexed index: c`Q]k Split str(Q) into two parts at index k sM Convert both elements to integers s Sum %Q Q % that s Sum Implicitly print ``` [Answer] ## Haskell, 62 bytes ``` f x|m<-mod x=sum[m$div x(10^k)+m(10^k)|(k,_)<-zip[0..]$show x] ``` Defines a function `f`. [See it pass all test cases.](http://rextester.com/TDY24542) [Answer] # [Perl 6](https://perl6.org), 33 bytes ``` {sum $_ X%m:ex/^(.+)(.+)$/».sum} ``` ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 sum $_ # the input X% # cross modulus m :exhaustive / # all possible ways to segment the input ^ (.+) (.+) $ /».sum # sum the pairs } ``` [Answer] ## Mathematica, 75 bytes ``` Tr@ReplaceList[IntegerDigits@#,{a__,b__}:>Mod[#,FromDigits/@({a}+{b}+{})]]& ``` This uses pattern matching on the list of digits to extract all partitions of them into two parts. Each such partition into `a` and `b` is then replaced with ``` Mod[#,FromDigits/@({a}+{b}+{})] ``` The notable thing here is that sums of lists of unequal length remain unevaluated, so e.g. if `a` is `1,2` and `b` is `3,4,5` then we first replace this with `{1,2} + {3,4,5} + {}`. The last term is there to ensure that it still remains unevaluated when we evenly split an even number of digits. Now the `Map` operation in Mathematica is sufficiently generalised that it works with any kind of expression, not just lists. So if we map `FromDigits` over this sum, it will turn each of those lists back into a number. At that point, the expression is a sum of integers, which now gets evaluated. This saves a byte over the more conventional solution `Tr[FromDigits/@{{a},{b}}]` which converts the two lists first and then sums up the result. [Answer] # [Actually](https://github.com/Mego/Seriously), ~~16~~ 15 bytes Golfing suggestions welcome! [Try it online!](https://tio.run/nexus/actually#@2/9aOp0lZyihEdTlzyaOidFG0ioJvieW/z/v4m5hakRAA "Actually – TIO Nexus") **Edit:** -1 byte thanks to Teal pelican. ``` ;╗$lr`╤╜d+╜%`MΣ ``` **Ungolfing** ``` Implicit input n. ;╗ Save a copy of n to register 0. $l Yield the number of digits the number has, len_digits. r Yield the range from 0 to len_digits - 1, inclusive. `...`M Map the following function over that range, with variable x. ╤ Yield 10**x. ╜ Push a copy of n from register 0. d Push divmod(n, 10**x). + Add the div to the mod. ╜ Push a copy of n from register 0. % Vectorized modulo n % x, where x is a member of parition_sums. This function will yield a list of modulos. Σ Sum the results together. Implicit return. ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 63 bytes ``` N+C+M:-N>C,N+C*10+T,M is N mod(N//C+N mod C)+T;M=0. N-M:-N+1+M. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30/bWdvXStfPzlkHyNQyNNAO0fFVyCxW8FPIzU/R8NPXd9YGMxWcNbVDrH1tDfS4/HRBOrQNtX31/lvpKpiYW5ga6frqKBQUZeaVaPhq6v0HAA "Prolog (SWI) – Try It Online") -1 thanks to Jo King More interesting: # [Prolog (SWI)](http://www.swi-prolog.org), 104 bytes ``` X/Y:-number_codes(X,Y). N-M:-findall(N mod(A+B),(N/C,append(X,Y,C),X\=[],Y\=[],A/X,B/Y),L),sumlist(L,M). ``` [Try it online!](https://tio.run/##HcpNC8IgHIDxe5/Co9LfCVEUgx3crptnpSJWWgi@oRt9fHu5PIcfT8rRxRctb1urZKqlYfV3k2@PqE3BEhRpNoJOLX3aoGfnsEA@asy3PQEs2ABzSibo3wkDAXnpzldQ/3ImoWeKwEigrN7ZsuARJtLUlqL98XTYIYo4oJRtWDD/@gc "Prolog (SWI) – Try It Online") [Answer] # Ruby, 64 bytes ``` ->s{s.size.times.reduce{|a,i|a+s.to_i%eval(s[0,i]+?++s[i..-1])}} ``` Takes the input as a string [Answer] # Befunge, ~~101~~ 96 bytes ``` &10v `#v_00p:::v>+%\00g1+:9 *v$v+55g00</|_\55+ \<$>>\1-:v ^<^!:-1 +^+^*+55\_$%\00g55 .@>+++++++ ``` [Try it online!](http://befunge.tryitonline.net/#code=JjEwdgpgI3ZfMDBwOjo6dj4rJVwwMGcxKzo5Cip2JHYrNTVnMDA8L3xfXDU1KwpcPCQ-PlwxLTp2IF48XiE6LTEgCiteK14qKzU1XF8kJVwwMGc1NQouQD4rKysrKysr&input=MzcyOTEwNTQ3Mg) **Explanation** ``` & Read n from stdin. 100p Initialise the current digit number to 1. -- The main loop starts here -- ::: Make several duplicates of n for later manipulation. v+55g00< Starting top right, and ending bottom right, this >>\1-:v routine calculates 10 to the power of the ^*+55\_$ current digit number. % The modulo of this number gives us the initial digits. \ Swap another copy of n to the top of the stack. _\55+*v Starting bottom left and ending top left, this ^!:-1\< is another calculation of 10 to the power of 00g55+^ the current digit number. / Dividing by this number gives us the remaining digits. + Add the two sets of digits together. % Calculate n modulo this sum. \ Swap the result down the stack bringing n back to the top. 00g1+ Add 1 to the current digit number. :9`#v_ Test if that is greater than 9. 00p If not, save it and repeat the main loop. -- The main loop ends here -- $$ Clear the digit number and N from the stack. ++++++++ Sum all the values that were calculated. .@ Output the result and exit. ``` [Answer] # APL, 29 bytes ``` {+/⍵|⍨{(⍎⍵↑R)+⍎⍵↓R}¨⍳⍴1↓R←⍕⍵} ``` `⎕IO` must be `1`. Explanation (I'm not good at explaining, any imporvements to this are **very** welcome): ``` {+/⍵|⍨{(⍎⍵↑R)+⍎⍵↓R}¨⍳⍴1↓R←⍕⍵} { } - Function (Monadic - 1 argument) ⍵ - The argument to the function ⍕ - As a string R← - Stored in R 1↓ - All except the first element ⍳⍴ - 1 to the length { } - Another function ⍵↓R - R without ⍵ (argument of inner function) leading digits ⍎ - As a number + - Plus ( ) - Grouping ⍵↑R - The first ⍵ digits of R ⍎ - As a number ¨ - Applied to each argument ⍵|⍨ - That modulo ⍵ (outer function argument) +/ - Sum ``` [Answer] # C#, 67 bytes ``` n=>{long d=n,s=0,p=1;while(d>9)s+=n%((d/=10)+n%(p*=10));return s;}; ``` Full program with ungolfed, explained method and test cases: ``` using System; public class Program { public static void Main() { Func<long,long> f= n=> { long d = n, // stores the initial number r, // remainder, stores the last digits s = 0, // the sum which will be returned p = 1; // used to extract the last digit(s) of the number through a modulo operation while ( d > 9 ) // while the number has more than 1 digit { d /= 10; // divides the current number by 10 to remove its last digit p *= 10; // multiplies this value by 10 r = n % p; // calculates the remainder, thus including the just removed digit s += n % (d + r); // adds the curent modulo to the sum } return s; // we return the sum }; // test cases: Console.WriteLine(f(47852)); //5842 Console.WriteLine(f(13)); // 1 Console.WriteLine(f(111)); // 6 Console.WriteLine(f(12345)); // 2097 Console.WriteLine(f(54321)); // 8331 Console.WriteLine(f(3729105472)); // 505598476 } } ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 48 bytes ``` Sum@{N[_]%Sum@Map[N]=>SplitAt[_,1..#_-1]}@Digits ``` [Try it online!](https://tio.run/##Lci9CsIwFIbhPVdRsG6xmD@qg1Kxq0Wo2yGUUE9qQEswcRKvPf71W96Hz8Ro@gumGq0bEXJLU/u4Vc8GOj3/6mA8NHqzbf3VxV2EjrKimHULpl9V7QYXQyKakAbxHCD3vh80Od7dGE8Y4t4EDGBpBiT7TJYrxemPTExlbAIXUv2ppODTK0q@ZkslS060Tm8 "Attache – Try It Online") ## Explanation ``` Sum@{N[_]%Sum@Map[N]=>SplitAt[_,1..#_-1]}@Digits Digits convert input to digits { }@ call lambda with digits as argument SplitAt[_,1..#_-1] split digits at each partition Map[N]=> Map N to two-deep elements Sum@ Takes the sum of each sub array N[_]% convert digits to int and vector mod Sum@ sum the resultant array ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 15 bytes ``` a%$+(a^@_)MS,#a ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhJSQrKGFeQF8pTVMsI2EiLCIiLCIiLCI0Nzg1MiJd) ### Explanation ``` a%$+(a^@_)MS,#a a Program argument: the input number ,# Range(length) MS Map this function to each of those numbers and sum the results: a^@_ Split the input number at that index $+( ) Sum the two halves a% Take the input number modulo the sum ``` Using range(len) as the list of indices to split on means that in addition to `4785+2`, `478+52`, `47+852`, and `4+7852`, we also have `+47852`. However, a number modulo itself is 0, which doesn't change the sum, so that's no problem. [Answer] **Clojure, ~~91~~ 81 bytes** Edit: this is shorter as it declares an anonymous function `(fn[v](->> ...))` and not using `->>` macro although it was easier to read and call that way. ``` (fn[v](apply +(map #(mod v(+(quot v %)(mod v %)))(take 10(iterate #(* 10 %)1))))) ``` Original: ``` (defn s[v](->> 1(iterate #(* 10 %))(take 10)(map #(mod v(+(quot v %)(mod v %))))(apply +))) ``` Generates a sequence of 1, 10, 100, ... and takes first 10 items (assuming input values are less than 10^11), maps to modulos as specified in specs and calculates the sum. Long function names makes this solution quite long but at least even the golfed version should be quite easy to follow. First I tried juggling strings around but it required tons of boilerplate. [Answer] ## Racket 134 bytes ``` (let((s(number->string n))(h string->number)(g substring))(for/sum((i(range 1(string-length s))))(modulo n(+(h(g s 0 i))(h(g s i)))))) ``` Ungolfed: ``` (define (f n) (let ((s (number->string n)) (h string->number) (g substring)) (for/sum ((i (range 1 (string-length s)))) (modulo n (+ (h (g s 0 i)) (h (g s i))))))) ``` Testing: ``` (f 47852) (f 13) (f 111) (f 12345) (f 54321) (f 3729105472) ``` Output: ``` 5842 1 6 2097 8331 505598476 ``` [Answer] ## Ruby 45 Bytes ``` ->q{t=0;q.times{|x|p=10**x;t+=q%(q/p+q%p)};t} ``` This is a really neat solution. It is technically correct, but it is super inefficient. It would be much more efficient to write q.to\_s.size.times{...}. We use q.times because it saves characters, and the extra number of times it goes through the proc the expression just evaluates to zero. [Answer] # [R](https://www.r-project.org/), 50 bytes ``` function(n)sum(n%%(n%%10^(x=1:nchar(n))+n%/%10^x)) ``` [Try it online!](https://tio.run/##FYpBCsIwEADvvsJLYRdXzGazTSLmK0IJBAWNpbVQXx/bw1xmZmrleDu3stT8fX4qVJyXN9Su22FzhzXxtebHMG0JT7W77HZFbAVY8DAP4/j6QQbng1piIWYmtuKU1IllEm8jG3XeIhVMKYMGt53UkzXRUxBhUqMag/M9tj8 "R – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 92 bytes ``` N =INPUT S N LEN(X) . L REM . R :F(O) S =S + REMDR(N,L + R) X =X + 1 :(S) O OUTPUT =S END ``` [Try it online!](https://tio.run/##FYyxCoAgFEXn51e8USmCypbATYPAnqEGzs1RQ/@PvaZ7OBzuez/nc@lagdCstB9ZJEbvSBaFHXqMbuONMC8yKAEJTcLmtzZKav3PrAuawtjDLJMSAcKR@Ytb4cjWOulx6D8 "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 31 bytes **Solution:** ``` +/(+/+.:''1_(0,'!#$x)_\:$x)!'x: ``` [Try it online!](https://tio.run/##y9bNz/7/X1tfQ1tfW89KXd0wXsNAR11RWaVCMz7GCkgqqldYGZsbWRoamJqYG/3/DwA "K (oK) – Try It Online") **Example:** ``` +/(+/+.:''1_(0,'!#$x)_\:$x)!'x:47852 5842 ``` **Explanation:** Most of the code goes to building up the lists out of the input. Am wondering if there is a trick I'm missing. ``` {.:''1_(0,'!#$x)_\:$x}47852 (4 7852 47 852 478 52 4785 2) ``` Full breakdown: ``` +/(+/+.:''1_(0,'!#$x)_\:$x)!'x: / the solution x: / store input as variable x !' / mod (!) each-both (') ( ) / do this together $x / string x _\: / cut (_) each-left (\:) ( ) / do this together $x / string x # / count length of the string ! / til, range 0..n-1 0,' / prepend 0 to each 1_ / drop the first one .:'' / value (.:) each-each (nested) + / flip rows and columns +/ / sum up the columns +/ / sum up results of the modulo ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, ~~14~~ 11 bytes *-3 bytes thanks to [Lyxal](https://codegolf.stackexchange.com/users/78850/lyxal)* ``` żðvṀṪƛĖ+?$% ``` [Try it online](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixbzDsHbhuYDhuarGm8SWKz8kJSIsIiIsIjQ3ODUyIl0=), or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJzQSIsIiIsIsW8w7B24bmA4bmqxpvElis/JCUiLCIiLCI0Nzg1MlxuMTNcbjExMVxuMTIzNDVcbjU0MzIxXG4zNzI5MTA1NDcyIl0=). Explanation: ``` ż # Range from 1 to the length of the input v # Map each of those to ð # A space Ṁ # Inserted into the input at the nth index (resulting in ["4 7852", "47 852", "478 52", ...]) Ṫ # Remove the last one (which has doesn't space) ƛ # On each string with the inserted space: Ė # Evaluate it as Vyxal code (so push both numbers in the string to the stack) + # Add them ? # Push the input $ # Swap the top two items % # Modulo # Sum with the s flag ``` ]
[Question] [ ## Goal Create a program/function that takes an input `N`, check if `N` random pairs of integers are relatively prime, and returns `sqrt(6 * N / #coprime)`. ## TL;DR These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't [waste ammo](https://medium.com/the-physics-arxiv-blog/how-mathematicians-used-a-pump-action-shotgun-to-estimate-pi-c1eb776193ef#.eld2u7w76)! There are eight more challenges to come. Checkout the [sandbox post](https://codegolf.meta.stackexchange.com/a/10035/43214) to make recommendations. ## Simulation **What are we simulating?** Well, the probability that two random integers are relatively prime (ie coprime or gcd==1) is [`6/Pi/Pi`](https://mathoverflow.net/a/97045), so a natural way to calculate Pi would be to scoop up two buckets (or handfuls) of rocks; count them; see if their [gcd](https://en.wikipedia.org/wiki/Greatest_common_divisor) is 1; repeat. After doing this a ~~couple~~ lot of times, `sqrt(6.0 * total / num_coprimes)` will tend towards `Pi`. If calculating the square-root in post-apocalyptic world makes you nervous, don't worry! There is [Newton's Method](https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number) for that. **How are we simulating this?** * Take input `N` * Do the following `N` times: + Uniformly generate random positive integers, `i` and `j` + With `1 <= i , j <= 10^6` + If `gcd(i , j) == 1`: `result = 1` + Else: `result = 0` * Take the sum of the `N` results, `S` * Return `sqrt(6 * N / S)` [![enter image description here](https://i.stack.imgur.com/xjU5L.jpg)](https://i.stack.imgur.com/xjU5L.jpg) ## Specification * **Input** + Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary) * **Output** + Flexible, give output in any of the standard ways (eg return, print) + White space, trailing and leading white space is acceptable + Accuracy, please provide at least 4 decimal places of accuracy (ie `3.1416`) * **Scoring** + Shortest code wins! ## Test Cases Your output may not line up with these, because of random chance. But on average, you should get about this much accuracy for the given value of `N`. ``` Input -> Output ----- ------ 100 -> 3.???? 10000 -> 3.1??? 1000000 -> 3.14?? ``` [Answer] # APL, 23 bytes ``` {.5*⍨6×⍵÷1+.=∨/?⍵2⍴1e6} ``` Explanation: * `?⍵2⍴1e6`: generate a 2-by-⍵ matrix of random numbers in the range [1..106] * `1+.=∨/`: get the GCD of each pair and see how many are equal to 1. This calculates S. * `.5*⍨6×⍵÷`: (6 × ⍵ ÷ S)0.5 [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20 18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to @Pietu1998 (chain & use count 1s, `ċ1` in place of less than two summed `<2S`) -2 bytes thanks to @Dennis (repeat 1e6 multiple times before sampling to avoid chaining) ``` Ḥȷ6xX€g2/ċ1÷³6÷½ ``` (Extremely slow due to the random function) How? ``` Ḥȷ6xX€g2/ċ1÷³6÷½ - Main link: n ȷ6 - 1e6 x - repeat Ḥ - double, 2n X€ - random integer in [1,1e6] for each 2/ - pairwise reduce with g - gcd ċ1 - count 1s ÷ - divide ³ - first input, n 6 - literal 6 ÷ - divide ½ - square root ``` **[TryItOnline](http://jelly.tryitonline.net/)** [Answer] # Python 2, ~~143~~ ~~140~~ ~~132~~ ~~124~~ ~~122~~ ~~124~~ [122 bytes](https://goo.gl/7RS871) It has been quite some time since I have tried golfing, so I may have missed something here! Will be updating as I shorten this. ``` import random as r,fractions as f n,s=input(),0 k=lambda:r.randrange(1e6)+1 exec's+=f.gcd(k(),k())<2;'*n print(6.*n/s)**.5 ``` Test me [here!](https://repl.it/DnAQ/2) *thanks to Jonathan Allan for the two-byte save :)* [Answer] # Mathematica, ~~49~~ ~~48~~ 51 bytes Saved one byte and fixed one bug thanks to [@LegionMammal978](https://codegolf.stackexchange.com/users/33208/legionmammal978). ``` (6#/Count[GCD@@{1,1*^6}~RandomInteger~{2,#},1])^.5& ``` [Answer] # R, ~~103~~ ~~99~~ ~~95~~ ~~99~~ ~~98~~ 94 bytes Can likely be golfed down a bit. Cut down 4 bytes due to @antoine-sac, and another 4 bytes by defining an alias for `sample`, using `^.5` instead of `sqrt`, and `1e6` instead of `10^6`. Added 4 bytes to ensure that the sampling of `i` and `j` is truly uniform. Removed one byte after I realized that `6*N/sum(x)` is the same as `6/mean(x)`. Used `pryr::f` instead of `function(x,y)` to save 4 bytes. ``` N=scan() s=sample g=pryr::f(ifelse(o<-x%%y,g(y,o),y)) (6/mean(g(s(1e6,N,1),s(1e6,N,1))==1))^.5 ``` Sample output: ``` N=100 -> 3.333333 N=10000 -> 3.137794 N=1000000 -> 3.141709 ``` [Answer] ## Actually, 19 bytes ``` `6╤;Ju@Ju┤`nkΣß6*/√ ``` [Try it online!](http://actually.tryitonline.net/#code=YDbilaQ7SnVASnXilKRgbmvOo8OfNiov4oia&input=MTAw) Explanation: ``` `6╤;Ju@Ju┤`nkΣß6*/√ `6╤;Ju@Ju┤`n do this N times: 6╤; two copies of 10**6 Ju random integer in [0, 10**6), increment @Ju another random integer in [0, 10**6), increment ┤ 1 if coprime else 0 kΣ sum the results ß first input again 6* multiply by 6 / divide by sum √ square root ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 22 bytes ``` 1e6Hi3$YrZ}Zd1=Ym6w/X^ ``` [Try it online!](http://matl.tryitonline.net/#code=MWU2SGkzJFlyWn1aZDE9WW02dy9YXg&input=MTAwMDA) ``` 1e6 % Push 1e6 H % Push 2 i % Push input, N 3$Yr % 2×N matrix of uniformly random integer values between 1 and 1e6 Z} % Split into its two rows. Gives two 1×N arrays Zd % GCD, element-wise. Gives a 1×N array 1= % Compare each entry with 1. Sets 1 to 0, and other values to 0 Ym % Mean of the array 6w/ % 6 divided by that X^ % Square root. Implicitly display ``` [Answer] # Pyth, 21 bytes ``` @*6cQ/iMcmhO^T6yQ2lN2 ``` [Try it online.](http://pyth.herokuapp.com/?code=%40%2a6cQ%2FiMcmhO%5ET6yQ2lN2&input=10000&debug=0) ### Explanation ``` Q input number y twice that m map numbers 0 to n-1: T 10 ^ 6 to the 6th power O random number from 0 to n-1 h add one c 2 split into pairs iM gcd of each pair / lN count ones cQ divide input number by the result *6 multiply by 6 @ 2 square root ``` [Answer] # Scala, ~~149~~ 126 bytes ``` val& =BigInt def f(n: Int)={math.sqrt(6f*n/Seq.fill(n){val i,j=(math.random*99999+1).toInt if(&(i).gcd(&(j))>1)0 else 1}.sum)} ``` Explanation: ``` val& =BigInt //define & as an alias to the object BigInt, because it has a gcd method def f(n:Int)={ //define a method math.sqrt( //take the sqrt of... 6f * n / //6 * n (6f is a floating-point literal to prevent integer division) Seq.fill(n){ //Build a sequence with n elements, where each element is.. val i,j=(math.random*99999+1).toInt //take 2 random integers if(&(i).gcd(&(j))>1)0 else 1 //put 0 or 1 in the list by calling //the apply method of & to convert the numbers to //BigInt and calling its bcd method }.sum //calculate the sum ) } ``` [Answer] ## Racket 92 bytes ``` (λ(N)(sqrt(/(* 6 N)(for/sum((c N))(if(= 1(gcd(random 1 1000000)(random 1 1000000)))1 0))))) ``` Ungolfed: ``` (define f (λ (N) (sqrt(/ (* 6 N) (for/sum ((c N)) (if (= 1 (gcd (random 1 1000000) (random 1 1000000))) 1 0) ))))) ``` Testing: ``` (f 100) (f 1000) (f 100000) ``` Output: ``` 2.970442628930023 3.188964020716403 3.144483068444827 ``` [Answer] # JavaScript (ES7), ~~107~~ ~~95~~ 94 bytes ``` n=>(n*6/(r=_=>Math.random()*1e6+1|0,g=(a,b)=>b?g(b,a%b):a<2,q=n=>n&&g(r(),r())+q(n-1))(n))**.5 ``` The ES6 version is exactly 99 bytes, but the ES7 exponentiation operator `**` saves 5 bytes over `Math.sqrt`. ### Ungolfed ``` function pi(n) { function random() { return Math.floor(Math.random() * 1e6) + 1; } function gcd(a, b) { if (b == 0) return a; return gcd(b, a % b); } function q(n) { if (n == 0) return 0; return (gcd(random(), random()) == 1 ? 1 : 0) + q(n - 1)); } return Math.sqrt(n * 6 / q(n)); } ``` [Answer] # PHP, ~~82~~ ~~77~~ 74 bytes ``` for(;$i++<$argn;)$s+=2>gmp_gcd(rand(1,1e6),rand(1,1e6));echo(6*$i/$s)**.5; ``` Run like this: ``` echo 10000 | php -R 'for(;$i++<$argn;)$s+=2>gmp_gcd(rand(1,1e6),rand(1,1e6));echo(6*$i/$s)**.5;' 2>/dev/null;echo ``` # Explanation Does what it says on the tin. Requires PHP\_GMP for `gcd`. # Tweaks * Saved 3 bytes by using `$argn` [Answer] # Perl, 64 bytes ``` sub r{1+~~rand 9x6}$_=sqrt$_*6/grep{2>gcd r,r}1..$_ ``` Requires the command line option `-pMntheory=gcd`, counted as 13. Input is taken from stdin. **Sample Usage** ``` $ echo 1000 | perl -pMntheory=gcd pi-rock.pl 3.14140431218772 ``` [Answer] # R, 94 bytes ``` N=scan();a=replicate(N,{x=sample(1e6,2);q=1:x[1];max(q[!x[1]%%q&!x[2]%%q])<2});(6*N/sum(a))^.5 ``` Relatively slow but still works. Replicate N times a function that takes 2 random numbers (from 1 to 1e6) and checks if their gcd is less than 2 (using an [old gcd function of mine](https://codegolf.stackexchange.com/a/48845/6741)). [Answer] ## PowerShell v2+, ~~118~~ 114 bytes ``` param($n)for(;$k-le$n;$k++){$i,$j=0,1|%{Random -mi 1};while($j){$i,$j=$j,($i%$j)}$o+=!($i-1)}[math]::Sqrt(6*$n/$o) ``` Takes input `$n`, starts a `for` loop until `$k` equals `$n` (implicit `$k=0` upon first entering the loop). Each iteration, get new `Random` numbers `$i` and `$j` (the `-mi`nimum `1` flag ensure we're `>=1` and no maximum flag allows up to `[int]::MaxValue`, which is allowed by the OP since it's larger than `10e6`). We then go into a [GCD `while` loop](https://codegolf.stackexchange.com/a/83562/42963). Then, so long as the GCD is `1`, `$o` gets incremented. At the end of the `for` loop, we do a simple `[math]::Sqrt()` call, which gets left on the pipeline and output is implicit. Takes about 15 minutes to run with input `10000` on my ~1 year old Core i5 laptop. ### Examples ``` PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 100 3.11085508419128 PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 1000 3.17820863081864 PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 10000 3.16756133579975 ``` [Answer] # Java 8, ~~164~~ 151 bytes ``` n->{int c=n,t=0,x,y;while(c-->0){x=1+(int)(Math.random()*10e6);y=1+(int)(Math.random()*10e6);while(y>0)y=x%(x=y);if(x<2)t++;}return Math.sqrt(6f*n/t);} ``` ## Explanation ``` n->{ int c=n,t=0,x,y; while(c-->0){ // Repeat n times x=1+(int)(Math.random()*10e6); // Random x y=1+(int)(Math.random()*10e6); // Random y while(y>0)y=x%(x=y); // GCD if(x<2)t++; // Coprime? } return Math.sqrt(6f*n/t); // Pi } ``` ### Test Harness ``` class Main { public static interface F{ double f(int n); } public static void g(F s){ System.out.println(s.f(100)); System.out.println(s.f(1000)); System.out.println(s.f(10000)); } public static void main(String[] args) { g( n->{int c=n,t=0,y,x;while(c-->0){x=1+(int)(Math.random()*10e6);y=1+(int)(Math.random()*10e6);while(y>0)y=x%(x=y);if(x<2)t++;}return Math.sqrt(6f*n/t);} ); } } ``` **Update** * **-13** [16-10-05] Thanks to [*@TNT*](https://codegolf.stackexchange.com/users/32515/tnt) and added test harness [Answer] # [Pyt](https://github.com/mudkip201/pyt), 24 bytes ``` Đ0⇹`⇹ɽɽǤ⁻?ŕ:ŕ⁺;⇹⁻łŕᵮ/6*√ ``` [Try it online!](https://tio.run/##K6gs@f//yASDR@07E4D45N6Te48vedS42/7oVKujUx817rIGigL5R5uOTn24dZ2@mdajjln//xsaAAEA "Pyt – Try It Online") ``` Đ implicit input; Đuplicate on stack (N, i) where i is a counter 0 push 0 (S) ⇹ swap top two items on stack ` ł do... while top of stack is not 0 ⇹ swap top two items on stack ɽɽ get two ɽandom 32-bit integers Ǥ⁻? if the ǤCD of the two random integers is >1: ŕ ŕemove the GCD :ŕ⁺ otherwise ŕemove the GCD and increment S ;⇹⁻ either way, swap and decrement N ŕ ŕemove i (which is now 0) ᵮ cast S to a ᵮloat / N/S 6*√ sqrt(6*N/S); implicit print ``` [Answer] # [Perl 6](https://perl6.org), ~~56~~ 53 bytes ``` {sqrt 6*$_/(1..10⁶).roll(*).map(*gcd*==1)[^$_].sum} ``` [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLU7D9X11cWFSiYKalEq@vYainZ2jwqHGbpl5Rfk6OhpamXm5igYZWenKKlq2toWZ0nEp8rF5xaW7t/@LESoU0BUMDay4Yy8DA@j8A "Perl 6 – TIO Nexus") [Answer] # Frink, ~~84~~ 89 ``` r[]:=random[10^6]+1 g=n=eval[input[1]] for a=1to n g=g-1%gcd[r[],r[]] println[(6*n/g)^.5] ``` I got lucky: **g=n=...** saves a byte over **g=0 n=...**; and **1%gcd()** gives (0,1) vs (1,0) so I can subtract. And unlucky: **n** is preassigned and **a** used because loop variables and their bounds are local and undefined outside the loop. ## Verbose ``` r[] := random[10^6] + 1 // function. Frink parses Unicode superscript! g = n = eval[input[""]] // input number, [1] works too for a = 1 to n // repeat n times g = g - 1%gcd[r[], r[]] // subtract 1 if gcd(i, j) > 1 println[(6*n/g)^.5] // ^.5 is shorter than sqrt[x], but no super ".", no ½ ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 109 bytes ``` func G(p,q){return(q?G(q,p%q):p)}{for(;i++<$0;)x+=G(int(1e6*rand()+1),int(1e6*rand()+1))==1;$0=sqrt(6*$0/x)}1 ``` [Try it online!](https://tio.run/##ZcixCoMwEADQX@mQwp0JmFscjKFjvkOsghRi7owoiN@egqtvfP3@K2Xa4vAKkAzjKWPeJAJ/ArBJb8Y24XVOi4Cbte6UdXhoH2COGWhsKunjF1ATmseg9@SU9StLhqZStj7wolLI3v4 "AWK – Try It Online") I'm surprised that it runs in a reasonable amount of time for 1000000. [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~37~~ 35 bytes ``` ←Đ0⇹`25*⁶⁺Đ1⇹ɾ⇹1⇹ɾǤ1=⇹3Ș+⇹⁻łŕ⇹6*⇹/√ ``` Explanation: ``` ←Đ Push input onto stack twice 0 Push 0 ⇹ Swap top two elements of stack ` ł Repeat until top of stack is 0 25*⁶⁺Đ1⇹ɾ⇹1⇹ɾ Randomly generate two integers in the range [1,10^6] Ǥ1= Is their GCD 1? ⇹3Ș Reposition top three elements of stack + Add the top 2 on the stack ⇹⁻ Swap the top two and subtract one from the new top of the stack ŕ Remove the counter from the stack ⇹ Swap the top two on the stack 6* Multiply top by 6 ⇹ Swap top two / Divide the second on the stack by the first √ Get the square root ``` [Answer] # J, 27 Bytes ``` 3 :'%:6*y%+/(1:=?+.?)y#1e6' ``` ### Explanation: ``` 3 :' ' | Explicit verb definition y#1e6 | List of y copies of 1e6 = 1000000 (1:=?+.?) | for each item, generate i and j, and test whether their gcd is 1 +/ | Sum the resulting list 6*y% | Divide y by it and multiply by six %: | Square root ``` Got pretty lucky with a `3.14157` for `N = 10000000`, which took `2.44` seconds. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~23~~ 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` *6/UÆ2ÆÒL³öÃrjÃx)¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KjYvVcYyxtJMs/bDcmrDeCms&input=MTAwMDA) ]
[Question] [ You have a coin that produces `0` or `1`. But you suspect the coin may be *biased*, meaning that the probability of `0` (or `1`) is not necessarily 1/2. A [well known](https://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coin) procedure to "transform" a biased coin into a *fair coin* (i.e. to obtain equally likely results), as proposed by von Neumann, is as follows. Produce (non-overlapping) blocks of two coin tosses until the two values of a block differ; and output the first value in that block (the second value would also do, but for the purposes of this challenge we choose the first). Intuitively, `1` may be more likely than `0`, but `01` and `10` will be equally likely. For example, the input `1110...` would discard the first block, then produce a `1` from the second block, ... This procedure is *expensive*, because several coin tosses are consumed to generate a single result. ### The challenge Take a finite sequence of zeros and ones, representing tosses of the original coin, and produce the *maximum number of results* according to the above procedure, until all the input is consumed. The last block may be incomplete, if the number of input values is odd. For example, the input sequence `11111` would produce no result (the first two blocks have equal values, and the third block is incomplete). ### Rules The input can have any non-negative number of values, not necessarily positive or even. The input format may be: * an array of zeros and ones; * a string of zeros and ones with an optional separator. Output format may be: * a string of zeros and ones, with or without separators; * an array of zeros and ones; * strings containing a single zero or one, separated by newlines; * any similar, reasonable format that suits your language. Code golf. Fewest bytes wins. ### Test cases Input and output are here assumed to be strings. ``` Input --> Output '1110' --> '1' '11000110' --> '01' '1100011' --> '0' '00' --> '' '1' --> '' '' --> '' '1101001' --> '0' '1011101010' --> '1111' ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~16~~ 14 bytes ``` (.)\1|(.)?. $2 ``` [Try it online!](http://retina.tryitonline.net/#code=KC4pXDF8KC4pPy4KJDI&input=MTAxMTEwMTAxMDE) ### Explanation This is fairly simple. The code defines a single regex substitution replacing all (non-overlapping) matches of `(.)\1|(.)?.` with whatever the second group captured. This combines three different cases into one: ``` (.)\1 --> <empty> ``` If two repeated digits are equal, we remove them from the string (because group 2 is unused). ``` (.). --> $2 ``` Otherwise, if we can match two characters, remove the second one, by replacing both of them with the first. If that's not the case the `?` will omit the group: ``` . --> <empty> ``` This only happens if there is an unpaired trailing character, which is also removed. [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), ~~21~~ 12 bytes ``` "(. : ""*$,@ ``` ~~A rare example of a compact Labyrinth program that also has no no-ops.~~ The `|` in the previous version was completely unnecessary, and removing it massively reduced the size of the program. In fact, Lab's beating Retina! [Try it online!](http://labyrinth.tryitonline.net/#code=IiguIDoKIiIqJCxA&input=MDExMTAwMTAwMTEwMDAwMDAwMTA) The bottom-left `"` can also be a space, but having it there greatly simplifies the explanation. ## Explanation This one's a little trickier, so it's accompanied by images. But first, a quick primer: * Labyrinth is a stack-based 2D language. Memory consists of a main stack and an auxiliary stack. * Labyrinth's stacks are bottomless and filled with zeroes, so performing operations on an empty stack is not an error. * At each junction, where there are two or more paths for the instruction pointer to go, the top of the main stack is checked to figure out where to go next. Negative is turn left, zero is straight ahead and positive is turn right. If a turn fails, the pointer tries to turn in the other direction. ### Setup [![enter image description here](https://i.stack.imgur.com/VrV1K.png)](https://i.stack.imgur.com/VrV1K.png) The program starts at the top-left `"`, which is a no-op. Then we perform: ``` ( Decrement a bottom zero to -1. Since -1 is negative we try to turn left at this junction, fail, and turn right instead. " No-op junction, turn left * Multiply top of stack (-1) with a 0 at bottom of stack, giving 0. This makes us go straight ahead at this junction. $ Bitwise xor (of 0 and 0) ``` This leaves the stack with a single 0 on it, which is as good as empty for the purposes of Labyrinth. ### Reading input and termination [![enter image description here](https://i.stack.imgur.com/7uz88.png)](https://i.stack.imgur.com/7uz88.png) `,` reads a char from input, returning 48 or 49 for `0` or `1` respectively, and -1 on EOF. Since this is nonzero, either way we turn into the `:`, which duplicates the top of the stack. The `:` is at a dead-end, so we turn around and execute `,` once more. Now if the last input was EOF, then we turn left and terminate with `@`, else we turn right, with the stack looking like `[a a b]` (where `a`, `b` are the two chars). ### Interpreting the coin toss [![enter image description here](https://i.stack.imgur.com/5c5Rl.png)](https://i.stack.imgur.com/5c5Rl.png) If we didn't terminate, our next move is to execute `$` (bitwise xor) again. This yields 0 if the input chars were the same, 1 otherwise. We then multiply `a` with this result, giving either 0 or `a`. Since the `*` is at a junction, this top stack value determines what happens next. In the 0 case, we go straight ahead and execute three `"` no-ops, before perform a `(` decrement. Like the setup, this makes us turn and execute `"*$`, leaving us ready to read more chars. [![enter image description here](https://i.stack.imgur.com/tIdrY.png)](https://i.stack.imgur.com/tIdrY.png) Otherwise, in the `a` case, we turn right at the junction since `a` is positive (48 or 49). `.` outputs the char, leaving the stack empty, and `(` decrements the top of the stack, turning a 0 to -1. Once again, this makes us turn left, executing `"*$` like in the setup, also leaving us ready to read more input. [Answer] ## CJam, ~~10~~ 8 bytes ``` l2/{)-}% ``` [Test it here.](http://cjam.aditsu.net/#code=l2%2F%7B)-%7D%25&input=1011101010) ### Explanation This is a very simple solution: in each pair, remove all instances of the last character. Repeated digits and unpaired trailing digits will be removed, as will be the second digit in any pair of unequal digits: ``` "0" --> "" "1" --> "" "00" --> "" "01" --> "0" "10" --> "1" "11" --> "" ``` This leaves only the digits we're looking for. Here's how the code computes this: ``` l e# Read input. 2/ e# Split into pairs. Odd inputs will yield a single-character string at the end. { e# Map this block over the pairs... ) e# Pull the last character off the string. - e# Remove all occurrences of that character from the remainder (which is either e# an empty string to begin with or a single-digit string). }% ``` When the list is auto-printed at the end of the program, the empty strings are simply omitted. [Answer] # Jelly, 6 bytes ``` s2Q€Ṗ€ ``` [Try it online!](http://jelly.tryitonline.net/#code=czJR4oKs4bmW4oKs&input=&args=JzExMDAwMTEwJw) ### How it works ``` s2Q€Ṗ€ Main link. Argument: S (string) s2 Split the string into pairs of characters. Q€ Deduplicate each pair. This removes the second character iff it is equal to the first. Ṗ€ Pop each; remove the last character of each pair/singleton. ``` [Answer] # Perl, ~~19~~ ~~18~~ 17 bytes @Martin Büttner Retina solution inspired a 2 byte gain Includes +1 for `-p` Run with the input on STDIN, e.g. `perl -p fair.pl <<< 11000110` `fair.pl`: ``` s/(.)\1|.?\K.//g ``` Not much to explain here since it is an (indirect) translation of the specification: * `(.)\1` If the first 2 digits are the same, drop them * `.\K.` Otherwise the first two digits are different. Keep (`\K`) the first one * `.?\K.` Except that the first `.` is optional. This allows for a single match at the end of the string which then gets discarded since the kept part is empty [Answer] ## Haskell, ~~71~~ ~~44~~ 29 bytes ``` p(a:b:r)=[a|a/=b]++p r p _=[] ``` Extreme golfing by [nimi](https://codegolf.stackexchange.com/users/34531/nimi). [Answer] # Mathematica, 36 ~~38~~ bytes -2 after stealing @LegionMammal978's function for determining if a 2-element list is {0,1} or {1,0} ``` #&@@@Select[#~Partition~2,Tr@#==1&]& ``` Argument is expected to be a list of integers. [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), ~~23~~ 21 bytes ``` ,){,/;(_\/'%<\{)/>~$> ``` Unfolded: ``` , ) { , / ; ( _ \ / ' % < \ { ) / > ~ $ > . . . . . . . . . . . . . . . . ``` This terminates with an error, but the error message goes to STDERR. [Try it online!](http://hexagony.tryitonline.net/#code=LCl7LC87KF9cLyclPFx7KS8-fiQ-&input=MDExMTEwMTAwMDExMA) Judging by the number of mirrors it might be just about possible to fit it into side-length 3 but I've had no luck so far. ### Explanation Here's the usual diagram, generated with Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer): [![enter image description here](https://i.stack.imgur.com/PxJ48.png)](https://i.stack.imgur.com/PxJ48.png) The program uses only three memory edges, labelled **A**, **B**, and **C** here (diagram courtesy of Timwi's [EsotericIDE](https://github.com/Timwi/EsotericIDE)): [![enter image description here](https://i.stack.imgur.com/WSfxF.png)](https://i.stack.imgur.com/WSfxF.png) Execution starts on blue path. The `/` are just mirrors that redirect the instruction pointer (IP), the actual code is: ``` , Read character from STDIN into memory edge A. ) Increment. { Move to memory edge B. , Read character from STDIN into memory edge B. ) Increment. ' Move to memory edge C. % Compute A mod B in memory edge C. ``` The `,` will set the edge to `-1` instead of the character code if we've hit EOF. Since we're incrementing both inputs that doesn't change whether they are equal or not, but it turns EOF into `0`. We use modulo to check for equality, because it's either `1` or `49` (positive) for unequal characters and `0` for equal characters. It also serves as the end of the program, because when we have the `0` from EOF, the attempted division by zero will cause an error. Now the `<` distinguishes zeroes from positive results. The simple one first: if the characters are equal, the IP takes the red path. `_` is a mirror, `\` is also a mirror but gets ignored, and `>` deflects the IP such that it wraps around the edges and starts from the top again. However, on this iteration, the roles of **A**, **B** and **C** are swapped cyclically (**C** now takes the role of **A** and so on). If the characters are different, the green path is taken instead. This one's a bit messier. It first jumps over a no-op with `$`, then wraps around to the `/` on the left edge, then traverses the second-to-last row from right to left and finally re-enters the interesting part of the source code at the `{`. There's an essentially linear bit of code, that I'll explain in a second, before the `$` makes the IP jump over the `>` to merge the two paths again. Here is that linear piece of code: ``` { Move to memory edge A. ( Decrement to recover the actual character we read. ; Print the character back to STDOUT. ' Move to memory edge B. ~ Multiply the value there by -1, making it negative. This is necessary to ensure that the path correctly wraps back to the top. ``` Note that in this case, the roles of the edges for the next iteration are also swapped cyclically, but with **B** taking the role of **A** and so on. [Answer] ## [><>](https://esolangs.org/wiki/Fish), 11 bytes ``` i:i:0(?;-?o ``` ><> is pretty well suited to read-a-char-at-a-time challenges like this :) [Try it online!](http://fish.tryitonline.net/#code=aTppOjAoPzstP28&input=MTExMDAxMDAwMDEw) ``` i: Read char and duplicate i Read char :0(?; Halt if last char was EOF - Subtract ?o Output first char if the subtraction was non-zero (i.e. not equal) ``` This all happens in a loop since the instruction pointer wraps around once it reaches the end of a line. [Answer] ## Python, 42 bytes ``` f=lambda L:L[1:]and L[:L[0]^L[1]]+f(L[2:]) ``` Fun with recursion and bitwise xor. Takes a list of 1s and 0s as input. [Answer] # JavaScript (ES6), 33 bytes ``` s=>s.filter((c,i)=>++i%2&c!=s[i]) ``` ### How it works ``` s=>s // Take the input array. .filter((c,i)=> ) // Filter to only the chars that are both: ++i%2& // on an even index, and c!=s[i] // not equal to the one after them. ``` [Answer] ## [Prelude](http://esolangs.org/wiki/Prelude), 12 bytes ``` 11(-(#!)?^?) ``` This assumes an interpreter that reads and prints characters. [You can sort of try it online.](http://prelude.tryitonline.net/#code=MTEoLSgjISk_Xj8p&input=MTAxMTEwMTAxMA) But that interpreter prints integers, so for each `0` you'll get `48` and for each `1` you'll get `49` instead (and a linefeed). ### Explanation It's very rare that you can write a non-trivial program on a single line in Prelude (because Prelude needs more than one line to be Turing-complete). ``` 11 Push two 1s. We need something non-zero on the stack to enter the loop, and by pushing the same value twice, we make sure that the loop doesn't print anything on the first iteration. ( Main loop... - Subtract the last two values. This will be zero for equal values, and non-zero otherwise... ( This "loop" is simply used as a conditional: if the last two values were were equal, skip the code inside... # Discard the conditional. ! Print the value below. ) The loop is exited because the value below is always zero. ? Read the first character of the next pair from STDIN. ^ Duplicate it, so the lower copy can be printed. ? Read the second character of the pair. This returns 0 at EOF, which terminates the loop. ) ``` [Answer] ## Perl, ~~27~~ 21 bytes ``` say grep$_-chop,/../g ``` Byte added for the `-n` flag. ``` /../g match groups of two chars grep , select/filter on... chop remove the last character, mutating the string $_- is it different than the remaining char? (subtract it, empty string is falsy) say output if so ``` Test: ``` llama@llama:~$ perl -nE 'say grep$_-chop,/../g' 1110 1 11000110 01 1100011 0 00 1 1101001 0 1011101010 1111 ``` Thanks to [@TonHospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for 6 bytes! [Answer] ## [Befunge 93](https://esolangs.org/wiki/Befunge), 16 bytes ``` ~:~:0`!#@_->#,_$ ``` A one-liner for compactness. Tested using [this online interpreter](http://www.quirkster.com/iano/js/befunge.html). ``` ~: Read input char a and dup ~ Read input char b (-1 on EOF) :0`! Push 1 if b <= 0, 0 otherwise #@_ Halt if b <= 0 (i.e. EOF) - Subtract to check whether a != b >#,_$ Output a if so ``` The last part makes use of the fact that [popping from an empty Befunge-93 stack yields 0](http://catseye.tc/view/befunge-93/doc/Befunge-93.markdown). If `a != b`, we perform ``` > Move rightward # Bridge: skip next _ Horizontal if - go right if 0, else left. But a != b, so we go left , Output a # Bridge: skip next - Subtract (0 - 0 = 0) _ If: go right since 0 is popped ># Go right and skip next _ If: go right since 0 is popped $ Pop top of stack, stack is now empty ``` Otherwise, if `a == b`, we perform: ``` > Move rightward # Bridge: skip next _ If: go right since a == b (i.e. a-b is 0) $ Pop top of stack and discard, keeping stack empty ``` [Answer] # brainfuck, 33 bytes ``` ,>,[<[->->+<<]>[[-]>.<]>[-]<<,>,] ``` Compared to Java, this is very compact, however, I'm afraid of brainfuck-golfer answerer. And feel free to mention if there's a bug. Assuming EOF is 0, input doesn't contain invalid input, the cell is initially zero, and the cell value range is finite and cyclic. No other assumption is present. Explanation: Memory Cell Map ``` +---------+---------+-----------------+ |1st input|2nd input|copy of 1st input| +---------+---------+-----------------+ ``` Instruction ``` ,>, read two instruction at once | first to first cell | second to second cell [ Until the input is EOF < look at first cell [->->+<<] move the first cell to additional cells while subtracting the second cell with this at same time >[ if the second cell is nonzero (it means that first cell and the second cell is the same) [-]>.< Print the copied first input ] >[-] clear the first input to prevent it polluting next input <<,>, continue with next two input ] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ḟ2/ḟ ``` [Try it online!](https://tio.run/##y0rNyan8///hjvlG@kDi/@H2R01rIv//Vzc0NDRQ1wFSBgYGKEwgywDMBWKIKFAcxAEywBygYgA "Jelly – Try It Online") Full program, but the link still runs all test cases, since they still get the smash-print treatment. ``` 2/ Split the input into slices of length 2, then reduce each slice by ḟ remove elements of right from left. This produces a list of empty lists and singleton lists, except if the length of the input is odd the last element is entirely unaffected. ḟ Remove elements of the input from that result. This removes the odd element if there is one, and nothing else, since it is necessarily an element of the input, and everything else is a list. ``` [Answer] ## Pyth, ~~10~~ 9 bytes ``` jkPM{Mcz2 ``` Algorithm shamelessly stolen from [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/74873/3808). ``` z input c 2 chunks of 2 {M dedup each chunk PM all-but-last element of each chunk jk join on empty string; can't use `s' because that gives `0' for [] ``` [Answer] ## Python 2, 48 bytes ``` lambda n:[s for s,t in zip(*[iter(n)]*2)if s!=t] ``` [Try it online](http://ideone.com/fork/Z0IvyV) Thanks to Dennis and vaultah for pointing out stuff that I missed [Answer] # Mathematica, ~~41~~ 39 bytes ``` Select[#~Partition~2,Tr@#==1&][[1]]& ``` Less complicated and shorter than the other answer. The box is a transpose character. [Answer] ## JavaScript (ES6), 33 bytes ``` s=>s.replace(/(.)\1|(.)?./g,"$2") ``` Boring port of the Retina answer. [Answer] ## sed, ~~34~~ 33 bytes ``` s/../& /g;s/00\|11//g;s/.\b\| //g ``` Test: ``` llama@llama:~$ sed 's/../& /g;s/00\|11//g;s/.\b\| //g' 1110 1 11000110 01 1100011 0 00 1 1101001 0 1011101010 1111 ``` [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 31 bytes Not as short and neat as Sp3000's solution, but I thought I'd post this anyway as a different approach: ``` "" @ ,, :{" ) { $; *"})";. "" ``` ### Explanation The first loop is simply ``` "" ,, ``` which reads in two characters at a time (the `"` are no-ops). After EOF, `,` will return `-1`, but only check for EOF at every second character. That means in any case the top of the stack will then be `-1` and the value below is either `-1` or some character code that we don't care about, because it's an unpaired coin toss. Then `)*` turns the `-1` and the value below into a single `0` which we need a) to get rid of those two values and b) to enter the next loop correctly. That next loop is simply ``` "} "" ``` Which shifts all the values over to the auxiliary stack. This is necessary because we want to start processing the pairs that we read first. Now the final loop: ``` :{" { $; )";. ``` The `)` just increments some dummy value to ensure that it's positive and the instruction pointer turns north. `{` pulls over the first digit of the next pair and `:` duplicates it. Now when we're done processing, this will have been a `0` from the bottom of the auxiliary stack. Otherwise it's either `48` or `49`. In case of a zero, we exit the loop and terminate on `@`, otherwise, the IP turns east. `{` pulls over the other digit of the current pair. `$` takes the XOR between them. If that is 0, i.e. the two are equal, the IP just continues moving south, `;` discards the zero, and the IP turns west into the next iteration. If the XOR was `1`, i.e. they were different, the IP turns west, discards the `1` with `;` and prints the first digit with `.`. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~11~~ ~~9~~ 8 bytes ``` `-?6MD]T ``` Input and output are numbers separated by newlines. Ends with an error (allowed by default) when all inputs have been consumed. [**Try it online!**](http://matl.tryitonline.net/#code=YC0_Nk1EXVQ&input=MQowCjEKMQoxCjAKMQowCjEKMAo) ``` ` % do...while loop - % take two inputs implicitly. Compute difference ? % if nonzero 6M % push first of the two most recent inputs again D % display (and remove from stack) ] % end if T % true. Used as loop condition, so the loop is infinite % end loop implicitly ``` ## Old approach, 11 bytes ``` 2YCd9L)Xz0< ``` Input is a string. Output is numbers separated by newlines. [Try it online!](http://matl.tryitonline.net/#code=MllDZDlMKVh6MDw&input=JzEwMTExMDEwMTAnCg) ``` 2YC % implicitly take input as a string. Generate 2D array of length-2 % overlapping blocks as columns, padding with a zero if needed. d % difference of the two values in each column of that array 9L % predefined literal [1 2 0]. This corresponds to "1:2:end" indexing ) % keep only values at indices 1, 3, 5, ... This reduces the set of blocks % to non-overlapping, and discards the last (padded) block if the input had % odd length Xz % keep only nonzero entries, corresponding to blocks that had different values 0< % 1 if negative, 0 if possitive. Implicitly display ``` [Answer] # [str](https://github.com/ConorOBrien-Foxx/str), 11 bytes ``` gd0H=N~e>*x ``` [Try it online!](https://tio.run/##Ky4p@v8/PcXAw9avLtVOq@L/f0NDA0MDA0MA "str – Try It Online") Alternative 11 byte solution: `dgdb=Nue>*x` If we didn't have to handle the edge case of an unpaired toss (i.e., the input was always even), then the solution would be 5 bytes: `dg=Nx`. ## Explanation str iterates implicitly over each character of the input. However, since it does not consume all the input at once, we can iterate over *pairs* of characters by manually taking the second character as input with `g`. Let `c1` be the first character and `c2` be the second. ``` gd0H=N~e>*x stack: [c1] g stack: [c1, c2] d stack: [c1, c2, c2] - duplicate 0H stack: [c1, c2, c2, c1] - get the first member of the stack = stack: [c1, c2, (c2==c1)] - equality N stack: [c1, c2, (c2!=c1)] - negate (inequality) ~ stack: [c1, (c2!=c1), c2] - swap top 2 e stack: [c1, (c2!=c1), c2, ``] - push empty string > stack: [c1, (c2!=c1), c2>``] - test for end of input * stack: [c1, Q] - Q is, if the two characters don't match AND we didn't read past the input x stack: [c1 x Q] - c1 repeated once if Q, zero times if not ``` [Answer] # Mathematica, 41 bytes ``` Cases[#~Partition~2,a_/;Tr@a==1:>a[[1]]]& ``` Anonymous function that inputs and outputs lists of zeros and ones. [Answer] # Pyth, 10 bytes ``` hMf!qFTcz2 ``` [Test suite](https://pyth.herokuapp.com/?code=hMf%21qFTcz2&input=1110%0A11000110%0A1100011%0A00%0A1%0A%0A1101001%0A1011101010&test_suite=1&test_suite_input=1110%0A11000110%0A1100011%0A00%0A1%0A%0A1101001%0A1011101010&debug=0) [Answer] # C, 66 bytes ``` main(char*p,char**x){for(p=x[1];*p&p[1];p+=2)write(1,p,*p^p[1]);} ``` Assuming `sizeof(int) == sizeof(char *)` # "clever" solution - ~~84~~ 81 bytes ``` main(int c,short**x){while(!((c=*x[1]++-12336)&~511))c>>8^c&1&&putchar(48|c&1);} ``` Works on little-endian machine assuming `short` is 2 bytes. Input is passed as argument. The program iterates over pairs of characters and prints 0 for 0x3130 and 1 for 0x3031. On big-endian the result will be reversed (replace `48|c&1` with `49^c&1` to fix this). [Answer] # C, 57 bytes ``` f(char*p,char*r){for(;*p*p[1];)*r=*p++,r+=*r!=*p++;*r=0;} ``` We tentatively copy a character from input `p` to result `r`, but only advance the `r` pointer if it differs from the next character. If not, then we'll overwrite it at the next unmatched pair, or with `NUL` at the end. ## Test program: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { while (*++argv) { char *result = malloc(1+strlen(*argv)); f(*argv, result); printf("%s => %s\n", *argv, result); free(result); } return EXIT_SUCCESS; } ``` ## Test output: ``` $ ./74864 1110 11000110 1100011 00 1 "" 1101001 1011101010 1110 => 1 11000110 => 01 1100011 => 0 00 => 1 => => 1101001 => 0 1011101010 => 1111 ``` [Answer] # [Befunge-93](https://esolangs.org/wiki/Befunge), 40 bytes ``` v ,-1< | -< >~1+:~1+:| ^ < @ ``` You can [try it here](http://www.quirkster.com/iano/js/befunge.html). Paste code in the space under the "show" button, press "show", define input, press "run". Our use the "step" button to see how the program works. [Answer] # Ruby, 46 bytes This separates `l[0]`, `l[1]` and `l[2..{end}]` as `a`, `b` and `c`. Then it creates a string with `a` if `a!=b` or `''` otherwise and `f[c]` if `c[0]` exists or `''` otherwise. ``` f=->l{a,b,*c=l;"#{a!=b ?a:''}#{c[0]?f[c]:''}"} ``` **Ungolfed:** ``` def f(l) a = l[0] b = l[1] c = l[2..l.length] s = '' if a!=b s += a.to_s end if c[0] # equivalent to !c.empty? s += f[c] # no .to_s because the output will be a string end puts s end ``` ]
[Question] [ ## Input A integer *n* ( ≥ 1) and a digit *d* (an integer such that 0 ≤ *d* ≤ 9). In either order; from stdin or parameters or whatever; to a program or function; etc. ## Output The integers from 1 to *n* inclusive (in order) whose decimal representations contain an **even** number of *d*s. (That is, the integers in the list are the integers that have, respectively, an even number of *d*s.) In any standard format, etc. In particular, the output need not be represented in decimal. If output as a single string, the integers must be separated somehow (spaces, commas, newlines, null bytes, whatever). ## Examples ``` in(d,n) ↦ out 1,12 ↦ 2 3 4 5 6 7 8 9 11 0,111 ↦ 1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,21,22,23,24,25,26,27,28,29,31,32,33,34,35,36,37,38,39,41,42,43,44,45,46,47,48,49,51,52,53,54,55,56,57,58,59,61,62,63,64,65,66,67,68,69,71,72,73,74,75,76,77,78,79,81,82,83,84,85,86,87,88,89,91,92,93,94,95,96,97,98,99,100,111 ``` ## Thanks To [quintopia](/users/47050/quintopia) for the title. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes Code: ``` \>GN¹¢ÈiN, ``` Explanation: ``` \ # Pop input, which saves the first input into ¹ > # Increment on second input G # For N in range(1, input + 1) N # Push N ¹ # Push the first input from the input register ¢ # Count the number of occurences of the digit in N È # Is even? iN, # If true, print N with a newline ``` [Try it online](http://05ab1e.tryitonline.net/#code=XD5HTsK5wqLDiGlOLA&input=MAoxMTE) Uses **CP-1252** encoding. [Answer] # Haskell, ~~69~~ ~~63~~ ~~52~~ 50 bytes ``` d#n=[i|i<-[1..n],even$sum[1|x<-show i,read[x]==d]] ``` Straightforwared solution for my first ever post here. It uses `show` to count the number of `d`'s. I explicitly did not use `Char` as input for `d`, which would have saved ~~12~~ 6 (after Damien's edit) bytes. EDIT: 11 bytes less thanks to Damien! EDIT 2: another 2 bytes less thanks to nimi! [Answer] ## Befunge, ~~1080~~ 945 bytes ``` vd>"000">" "v &0 ^ p21-1+*68< 62 > v 8 >-| >12g68*-:| * >11g1+11p^ $ + v < 5 |%2g11< 5 v.:< + v < 0 >268*+12p68*11p"000"40p50p60pv p v -1< v-g01p06+1g06< >& >:>:10g1-` | >:0`| v < @ v-+55p05+1g05< >:54+` | v p04+g04< ^ < < < >60g68*-0`| >50g68*-0`| >" "60p^ >" "50p^ ``` The score is given that we count the entire square, including newlines, which makes sense. You can copy paste the code into [the interpeter](http://www.quirkster.com/iano/js/befunge.html). Provide two inputs, first *d* and then *n*. This solution does not work for values larger than *n* > 999. This will obviously not be a contender for the grand prize, but I've been wanting to implement a codegolf in Befunge for a while now, so I decided to just do it. I figure this will not be even close to an optimal Befunge solution, as it is the first actual thing I've done in Befunge. So, hints are welcome, if you need clarification or more information, please let me know in the comments. ## Attempt at explanation: In the first column downward we read an integer from the input, add 48 (6\*8, you'll see this more often) to it to convert it to the corresponding ASCII value and puts it to `(10, 0)`. `&` - read input `68*+` - add 48 `55+0p` - put the value at `(10, 0)` Note that the `d` at `(1, 0)` is just an easy way to get the number 100 on the stack. After that, we go east and read another integer and head in to what I call the ASCIIfier. This turns the current number into a series of ASCII characters. The ASCIIfier is the rectangular piece from `(13, 12)` to `(26, 17)`. It consists of two loops, first counting the hunderds and than the tens and putting them into the three digits at `(6, 0)` and `(5, 0)`. After that the last digit is put into `(4, 0)`. So the numbers is actually in reverse. ``` v-g01p06+1g06< - increment the "hunderds counter" located at (0, 6) and decrease current value by 100 >:10g1-` | - ASCIIfier entry; check if the current value is > 99, if so, go up, else go down v < - go to start of "tens counter" v-+55p05+1g05< - increment the "tens counter" located at (0, 5) and decrease current value by 10 >:54+` | - check if current value is > 9, if so, go up, else go down p04+g04< - put the final value into the "singles counter" located at (0, 4) ``` After putting the current integer into a series of ASCII characters, we go a bit more south to remove prepended zeroes. Thus, afterwards, what are initially the three zeroes at the top, will be the current number, without prepended zeroes. Then we go back up, all the way to the North, where we put the three digits on the stack. We iterate over the three digits in the top loop, each time incrementing the counter located at `(1, 1)` if the current digit corresponds with the input *d* When that is done we go and check to see if the counter that located at `(1, 1)` is odd or even. If it is even, we output the current number and move on to the big outer loop to decrement the current value and start over again. [Answer] ## Python 2, 50 bytes ``` f=lambda d,n:n*[0]and f(d,n-1)+~`n`.count(d)%2*[n] ``` A recursive function that takes the digit `d` as a string and the upper bound `n` as a number. The count of digits `d`'s in `n` is tested to be even by taking it's bit complement modulo 2, which gives `1` for even and `0` for odd. This many `n`'s are appending to the list, and the function recurse down to `n-1`, stopping via logical short-circuit on the empty list when `n==0`. If the output may be given in decreasing order, one byte can be saved, for 49 bytes: ``` f=lambda d,n:n*[0]and~`n`.count(d)%2*[n]+f(d,n-1) ``` --- **Old 51-byte solution:** ``` lambda d,n:[x+1for x in range(n)if~`~x`.count(d)&1] ``` An anonymous function that takes the digit `d` as a string and the upper bound `n` as a number. Two tricks are used: * Python's `range` is zero-indexed `0...n-1`, so we add one to each potential value `x`. Then, to count `d`'s in `x+1`, it saves a character to use its negation `~x` instead. * To filter for even values, we do `~_%2`, which first bit-flips to switch parity, then takes the last bit with `&1` (same as `%2` here), producing a truthy value only if the original was even. [Answer] # Pyth, 10 bytes ``` f!%/`Tz2SE ``` [Try it online.](https://pyth.herokuapp.com/?code=f!%25%2F%60Tz2SE&input=1%0A12&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=f!%25%2F%60Tz2SE&input=1%0A12&test_suite=1&test_suite_input=1%0A12%0A0%0A111&debug=0&input_size=2) [Answer] ## Lua, 86 Bytes If using inconsistent separator is allowed, I could replace `io.write` by `print`, meaning numbers would be separated by one or multiple newlines. This is a full program, which have to be called like this: `lua file.lua d n`. It removes all non-`d` character from the current number and uses the size of the resulting string to decide weither or not it should be outputed. ``` for i=1,0+arg[2]do io.write(#(i..''):gsub("[^"..arg[1].."]","")%2<1 and i.." "or"")end ``` [Answer] # JavaScript (ES6) 64 An anonymous function with output to console. Straightforward implementation using `split` to count the digits. ``` (d,n)=>{for(i=0;i++<n;)(i+'').split(d).length&1&&console.log(i)} ``` Output using `alert` would be 6 byte less, but I really don't like it (and I'm not going to beat the toy languages anyway) [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~12~~ 10 bytes ``` :!V!=s2\~f ``` First input is *n*, second is *d* as a string. For example: ``` 12 '1' ``` [**Try it online!**](http://matl.tryitonline.net/#code=OiFWIT1zMlx-Zg&input=MTExCicwJw) ``` : % implicitly take input n (number). Generate row vector [1,2,...,n] ! % transpose into column vector V % convert each number to string. Gives 2D char array padded with spaces ! % transpose = % implicitly take input d (string). Compare with each element of the array s % sum of each column: number of coincidences with d 2\~ % true for even values f % find indices of true values. Implicitly display ``` [Answer] # Ruby, ~~47~~ 42 bytes ``` ?1.upto $*[1]{|s|s.count($*[0])%2<1&&p(s)} ``` Run with *d* and *n* as command-line parameters, e.g. ``` ruby golf.rb 1 12 ``` [Answer] # PowerShell, ~~62~~ 55 ``` param($1,$2);1..$2|?{!(([char[]]"$_"-match$1).Count%2)} ``` edit: using a param block in this case is shorter. removed some redundant space --- Not a golfing language but its the only one I really know. This would work saved as a script and called like this `M:\Scripts\cgNeverTellMeTheOdds.ps1 1 12`. First argument is the digit *d* and the second is integer *n*. Create an array of number 1 to *n*. For each of those convert that into a character array. 10 would be 1,0. Using `-match` as an array operator return all the elements that match the digit *d*. Count the amount of elements returned and mod 2 the result. Result will be 0 for even and 1 for odd. 0 as a boolean is false so we use `!` for the loop to evaluate the odd results to false and even results to true. Output is a newline delimited on console. [Answer] # Jelly, 7 bytes ``` RDċ€Ḃ¬T ``` [Try it online!](http://jelly.tryitonline.net/#code=UkTEi-KCrOG4gsKsVA&input=&args=MTI+MQ) ### How it works ``` RDċ€Ḃ¬T Main link. Arguments: n, d R Range; yield [1, ..., n]. D Convert each integer in the range to base 10. ċ€ Count the occurrences of d in each array of decimal digits. Ḃ Compute the parities. ¬ Negate, so even amounts evaluate to 1, odds to 0. T Find all indices of truthy elements. ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~99~~ 105 bytes Note the trailing spaces. `<empty>` represents an empty line. ``` \d+$ $* +`^(. )(1*)1\b $1$2 1$2 1+ $.0 +`^(.)(.*) ((?!\1)\d)*\1((?!\1)\d|(\1)((?!\1)\d)*\1)*\b $1$2 ^. <empty> ``` Takes input like `1 12`. Output is space separated in decreasing order. I modified [`0*1(0|10*1)*`](https://stackoverflow.com/a/20498401/2415524) to match an odd number of `\1` in a number. I changed `0` to `(?!\1)\d`, and `1` to `\1` to create the long regex line you see above. Understanding how the linked regex works is crucial. [**Try it online**](http://retina.tryitonline.net/#code=XGQrJAokKgorYF4oLiApKDEqKTFcYgokMSQyIDEkMgoxKwokLjAKK2BeKC4pKC4qKSAoKD8hXDEpXGQpKlwxKCg_IVwxKVxkfChcMSkoKD8hXDEpXGQpKlwxKSpcYgokMSQyCl4uICAK&input=MSAxMg) ### Commented explanation of old version [If descending order were okay](http://retina.tryitonline.net/#code=XGQrJAokKgorYDEoMSopJAokMCAkMQogKDEpKwogJCMxCitgXiguKSguKikgKCg_IVwxKVxkKSpcMSgoPyFcMSlcZHwoXDEpKCg_IVwxKVxkKSpcMSkqIAokMSQyIApeLiAK&input=MSAxMg) ``` \d+$ Convert last number N to unary $* +`1(1*)$ Create list N N-1 ... 1 in unary $0 $1 (1)+ Convert back to decimal $#1 +`^(.)(.*) ((?!\1)\d)*\1((?!\1)\d|(\1)((?!\1)\d)*\1)* Remove numbers w/ odd num of D's $1$2 ^. Remove first parameter <empty> ``` [Answer] # Bash + GNU utilities, 37 * 1 byte saved thanks to @Ruud. ``` seq $1|egrep "^[^$2]*($2[^$2]*){2}*$" ``` [Answer] # Python 3.4, 92 85 79 85 bytes *Saved 7 bytes thanks to Mego* *Saved another 6 bytes thanks to mbomb007* *Regained those 6 bytes because Python 3.x* This is my first shot at code golf, so here goes nothing! ``` lambda n,d:[i for i in range(n+1)if len([j for j in list(str(i))if j==str(d)])%2is 0] ``` [Answer] # Perl 6, 38 bytes ``` {(1..$^n).grep(*.comb.Bag{~$^d} %% 2)} ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 32 bytes ``` :1reIlL,"":Ic:.xl-L=%2=0,Iw,@Sw\ ``` Expects N as input and the digit as output, e.g. `brachylog_main(12,1).` ### Explanation ``` :1reI § I is a number between 1 and Input lL, § L is the length of I "":Ic § Convert I to a string :.x § Remove all occurences of Output in that string l-L=%2=0, § Check that the length of that new string - L mod 2 is 0 Iw,@Sw § Write I, then write a space \ § Backtrack (i.e. try a new value of I) ``` [Answer] # Mathematica, 54 bytes ``` Position[Count[#2]/@IntegerDigits/@Range@#,x_/;2∣x]& ``` [Answer] # Perl, 28 ~~29~~ ~~31~~ bytes Includes +2 for `-an` Run with the specification digit and count on consecutive lines on STDIN: ``` echo -e "0\n111" | perl -anE'map s/@F/$&/g%2||say,1..<>' ``` [Answer] # Oracle SQL 11.2, ~~111~~ 82 bytes ``` SELECT LEVEL FROM DUAL WHERE MOD(REGEXP_COUNT(LEVEL,:d),2)=0 CONNECT BY LEVEL<=:n; ``` [Answer] ## Kotlin, 136 bytes ``` fun main(a:Array<String>)=print({n:String,d:String->IntRange(1,n.toInt()).filter{"$it".count{"$it"==d}%2==0}.joinToString()}(a[0],a[1])) ``` Fully functional program, takes arguments as: n d [Try it online!](http://try.kotlinlang.org/#/UserProjects/p93emhf4kmdc8i9n0gh049u5is/lealr85qeb1iv9htbtuqutsulu) [Answer] # Java 8, 84 bytes This is a lambda expression for a `BiConsumer< Integer, Integer>`: ``` (d,n)->for(int x=0;x++<n;)if((""+x).split(""+d,-1).length%2>0)System.out.println(x); ``` Explanation: for each number between 1 and n, convert the number to a string and split it using d as the delimiter. If it was split into an odd number of sections, then print out the number followed by a new line. [Answer] # Retina, ~~72~~ ~~71~~ 55 ``` \d+$ $* \B ¶$` 1+ $.0 G`(.),((?>.*?\1){2})*(?!.*\1) ., <empty> ``` Great thanks to Martin, who totally by accident reminded me of atomic matching groups! [Try it online!](http://retina.tryitonline.net/#code=XGQrJAokKgpcQgrCtiRgCjErCiQuMApHYCguKSwoKD8-Lio_XDEpezJ9KSooPyEuKlwxKQouLAo&input=MSwxMTI) ### Explanation: ``` \d+$ $* ``` Replace the number, but not the digit, with its unary equivalent. ``` \B ¶$` ``` `\B` matches each position (zero-width) that is not a word boundary. Note that this will not match any of the following: the beginning of the string, the end of the string, or any position around the comma character. Each of these non-boundaries is then replaced with a newline and then the string that comes before the match (`$``). This gives a list like: ``` d,1 d,11 d,111 ``` Where `d` is any single decimal digit. ``` 1+ $.0 ``` This converts all lists of `1`s into the decimal representation of their lengths. This conveniently won't affect the `1` that could be before the comma, as it's length it always `1` as well. ``` G`(.),((?>.*?\1){2})*(?!.*\1) ``` Here, the `G` turns on grep mode, which means that lines that match the regex are kept, and other lines are discarded. This regex is complicated, but it essentially matches groups of 2 of the leading digit (stored in capture group 1, so we can reference it with `\1`). The key here, is that if it failed when using the non-greedy match up to the two earliest appearances of the digits, it would then just roll back and try again, with `.` matching over the digit. This would make numbers like 111 match when our digit is 1. Therefore, we use `?>` to make the match atomic, essentially preventing the regex from backtracking to before it matched this value. An atomic match works kind of like [possesive](https://stackoverflow.com/a/5319978) matching would in certain flavours. Since the `*` meta-character is followed by a `?` the `.` will match characters up until it is able to match what we stored in `\1`. Then once we do this twice, the regular expression's "memory" is destroyed, preventing the behaviour that would normally occur, where it goes back and has the `.` match an additional character, our `\1` digit, which would created invalid matches. Then, we check that from the final position, after matching repeated groups of two of the input digit, that we cannot match another input digit. ``` ., <empty> ``` Here we are just removing the digit and comma from each of the strings, so we just get our nice answer. [Answer] # Python 2, ~~57~~ 54 bytes ``` lambda d,n:[i for i in range(1,n+1)if`i`.count(d)%2<1] ``` --- ### Usage ``` >>> (lambda d,n:[i for i in range(1,n+1)if`i`.count(d)%2<1])('1', 12) [2, 3, 4, 5, 6, 7, 8, 9, 11] ``` [Answer] # Julia, 44 bytes ``` f(n,d)=filter(i->sum(d.==digits(i))%2<1,1:n) ``` This is a function that accepts two integers and returns an array. We start with the set of integers from 1 to `n`, inclusive. For each integer `i`, we determine which of its decimal digits are equal to `d`, which yields a Boolean array. We `sum` this to get the number of occurrences of `d` as a digit in `i`, and `filter` the original range based on the parity of the sum. [Try it here](http://goo.gl/YJuytp) [Answer] ## Seriously, 17 bytes ``` ╩╜R;`$╛@c2@%Y`M@░ ``` Takes inputs as `n\n'd'` (integer, newline, string). [Try it online!](http://seriously.tryitonline.net/#code=4pWp4pWcUjtgJOKVm0BjMkAlWWBNQOKWkQ&input=MTIKJzEn) Explanation: ``` ╩╜R;`$╛@c2@%Y`M@░ ╩ push all inputs to registers ╜R; push two copies of range(1, n+1) ` `M map: $╛@c count the number of d's 2@%Y modulo 2, logical not (1 if even, 0 if odd) @░ filter: take only the values of range(1, n+1) where the count is even ``` [Answer] # Mathematica, 45 bytes ``` Select[a=#2;Range@#,2∣DigitCount[#,10,a]&]& ``` Uses the built-in `DigitCount`. [Answer] # Japt, ~~13~~ 12 bytes ``` Uò1 f_s èV v ``` Input is *n*, then *d* wrapped in quotes. [**Test it online!**](http://ethproductions.github.io/japt?v=master&code=VfIxIGZfcyDoVnMpdg==&input=MTExICIwIg==) ### How it works ``` // Implicit: U = input integer, V = input string Uò1 // Create the inclusive range [1..U]. f_ // Filter to only the items Z that return truthily to this function: s èV // Take Z.toString(), then count the number of matches of V. v // Return 1 (truthy) if even, 0 (falsy) otherwise. // Implicit output, array separated by commas ``` [Answer] # CJam, 38 bytes ``` r:P;r~1+,0-_{s{s}%Pe=2%!}%]z{~{}{;}?}% ``` --- ### Explanation ``` r:P; e# set input d to variable P r~1+,0- e# create a range(1, n+1) _{s{s}%Pe=2%!}% e# determine which numbers are needed ]z{~{}{;}?}% e# remove extra numbers ``` [Answer] # Scala, 66 bytes ``` (d:Int,n:Int)=>(1 to n).map(""+).filter(_.count((""+d)(0)==)%2==0) ``` [Answer] # R, 145 bytes (I am sure there are ways to shorten this further) :) ``` g<-sapply(sprintf("%s",seq(1:111)),function(z){if(sapply(regmatches(z,gregexpr("0",z)),length)%%2==0){z}else{NULL}}) names(g[!sapply(g,is.null)]) ``` ]
[Question] [ A [self number](https://en.wikipedia.org/wiki/Self_number) (also called a Colombian or Devlali number) is a natural number, `x`, where the equation `n + <digit sum of n> = x` has no solutions for any natural number `n`. For example, **21** is not a self number, as `n = 15` results in `15 + 1 + 5 = 21`. On the other hand, **20** *is* a self number, as no `n` can be found which satisfies such an equality. As this definition references the digit sum, it is base dependent. For the purposes of this challenge, we will only be considering base 10 self numbers, which are sequence [A003052](https://oeis.org/A003052) in the OEIS. Binary ([A010061](https://oeis.org/A010061)) and base 100 ([A283002](https://oeis.org/A283002)) self numbers have also been calalogued. ## The Challenge Given a positive integer `x` as input, output a truthy value if `x` is a self number in base 10, and a falsey value otherwise. For clarification of truthy and falsey values, refer to [this meta post on the subject](https://codegolf.meta.stackexchange.com/a/2194/41020). You may write a full program or function, and input and output may be provided on any of the usual channels. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are, of course, banned. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shorter your answer (in bytes) the better! ## Test cases Truthy: ``` 1 3 5 7 9 20 31 86 154 525 ``` Falsey: ``` 2 4 6 8 10 15 21 50 100 500 ``` [Sandbox link](https://codegolf.meta.stackexchange.com/a/16052/41020) ## 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=159881,OVERRIDE_USER=41020;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] # [Octave](https://www.gnu.org/software/octave/), 37 bytes ``` @(n)sum(dec2base(t=1:n,10)'-48,1)+t-n ``` Port of my MATL answer. [Try it online!](https://tio.run/##TY1BCoMwFET3nmJ2RqohPxqbFoTeo3RhNaGCxmJioadPU@iii2GG9xazDqF/mWg7znm8MFf4fWGjGeS994aFjs6uJFHkVaNLKg6hctGuGxw6XAk1FI44QQrUBN2CVAMlFSQatNAgkRAkQaUhRCpxy4DJwqavtIBx8k@Wh20Pj3f@RWb25s/YfvY/4cYsJX4A "Octave – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 84 bytes ``` i->{for(int n=i;i-->1;)i|=((""+i).chars().map(x->x-48).sum()+i^n)-1>>-1;return~i<0;} ``` [Try it online!](https://tio.run/##PVDLTsMwELz3K1aRKtnUdpPSQiEkdw5ISD0ikEwerUviRPamalXCrwc7hVqyd9cz4531Xh4k3@dfg6rbxiDsXS06VJUoO52harS4iSdZJa2FF6k0nCcAbfdZqQwsSnTh0KgcaoeRDRqlt2/vIM3W0pEK8Kzx1RS5yiQWUEIyKJ6ey8YQpRF0omLFeRrFVH0nhATBTFGR7aSxhIpatuTI0yNfrqmwXU3oTH1oyqM05VFsCuyM/lFPYdwP8djLPem6Y2HRQvLX36@IwS2DFYN7Bg8MFqGr3d36jkG0Wjpk4bD5HNB0uDtdZQsGDnSkteOFnuu0TrfyeRj6JPSyUlb2X9XHkzFzE8I4onfzePFEr5Y2J4tFLZoORev@DEsSTHPgKUztVAdspDMohY/EH5ReJuwnfvfDLw "Java (JDK 10) – Try It Online") ## Explanation ``` i->{ // IntPredicate for(int n=i;i-->1;) // for each number below n i|=( // keep the sign of (""+i).chars().map(x->x-48).sum() // sum of digits +i // plus the number ^n // xor n (hoping for a zero) )-1>>-1; // changing that into a negative number if equals to zero return~i<0; // return i>=0 } ``` ## Credits * -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) * -1 byte thanks to [Nevay](https://codegolf.stackexchange.com/users/69142/nevay) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` LD€SO+ÊW ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx@VR05pgf@3DXeH//xuamgAA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVln538flUdOaYH/tw13h/yuVDu9X0LVTOLxfSUcz5r8hlzGXKZc5lyWXkQGXsSGXhRmXoakJl6mRKZcRlwmXGZcFl6EBUIjLyJDLFMgwMABSBgA) **Explanation** ``` L # push range [1 ... input] D # duplicate €S # split each number into a list of digits O # sum digit lists + # add (n + digitSum(n)) Ê # check for inequality with input W # min ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` ¬{⟦∋Iẹ+;I+?} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9Ca6kfzlz3q6PZ8uGuntrWntn3t//9GBv8B "Brachylog – Try It Online") ### Explanation ``` ¬{ } Fails if succeeds, suceeds if fails: ⟦∋I I ∈ [0, ..., Input] Iẹ+ The sum of the elements (i.e. digits) of I... ;I+? ... with I itself results in the Input ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~49~~ ~~47~~ 44 bytes ``` @(x)arrayfun(@(k)k+sum(num2str(k)-48)-x,1:x) ``` [Try it online!](https://tio.run/##JYxBCsIwFET3PcVspAm2wYqCFAo9iJuo@fCpTctPIvH0MeBi4D14zPaM9uMKTcaYMqusrYj9UvJqVotejiGtyqf1HKJU7y833eduGLMutAmYMWEYr6cGYAIpZl0R2IV9JNUeGBxgEdybUH8eTu6@7f6Z86@mrvwA "Octave – Try It Online") **Explanation:** Trying to do the operation on a range is cumbersome and long, since `num2str` returns a string with spaces as separators if there are more than input number. Subtracting 48 would therefore give something like: `1 -16 -16 2 -16 -16 3 -16 -16 4` for an input range **1 ... 4**. Getting rid of all the `-16` takes a lot of bytes. Therefore, we'll do this with a loop using `arrayfun`. For each of the numbers **k = 1 .. x**, where **x** is the input, we add `k` and its digit sum, and subtract `x`. This will return an array of with the result of that operation for each of the numbers in **k**. If any of the numbers in the array is a zero, the number is not a self number. For inputs `20` and `21`, the outputs are: ``` 20: -18, -16, -14, -12, -10, -8, -6, -4, -2, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9, 2 21: -19, -17, -15, -13, -11, -9, -7, -5, -3, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 1, 3 ``` There are only non-zero elements for input `20`, and at least one non-zero element for input `21`. That means that `20` is a self number, and `21` is not. Octave treats an array with at least one zero as false, as can be seen in the TIO-link. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~70~~ ~~67~~ 65 bytes ``` i,r,d,j;f(n){for(r=i=n;d=j=--i;r*=d!=n)for(;j;j/=10)d+=j%10;i=r;} ``` [Try it online!](https://tio.run/##NY1BbsIwEEXX@BRupEh2sVUnkBZqzbYn6DIbFDepLTpUJiAhlLOnpB6v3mjm/fmdHrpunr2Kyqlge4Hy3p@iiOABrYMAWnsbn8E9AcrlYoMNL1AZ6dYQyspYD9FO8/XkHR@Ex5GjZHe2@o2PuRdFuXG8dC0WiqPiS4G0bGJsMX8OHkWyL@NZFJ/xMn7f3lvUWhcPbTWIKmGT0CS8JewTakMOubtXijZbStX/udzS4sfheP6inlxUJ1CEXuzok8kfyaWmJu@NyYtlmOY/ "C (gcc) – Try It Online") To shave off another 2 bytes, the truthy value returned is no longer 1, but the number itself. [Answer] # [J](http://jsoftware.com/), 28, 24, 22 21 bytes -1 byte thanks to Conor O'Brien -2 byts thanks to ngn ``` $@-.(+1#.,.&.":)"+@i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/VRx09TS0DZX1dPTU9JSsNJW0HTL1/mtycaUmZ@QrpCkYwhjGMIYpjGEOY1jCGEYGcNVwfRZmcKNMTeBmGJnCbTCCMeCycB0WcK0GCEPg@uBWmCJkDQwQggb/AQ "J – Try It Online") ## Explanation: `i.` a list 0 .. n-1 `( )"+` for each item in the list `.,.&.":` convert it to a list of digits, `1#` find their sum `+` and add it to the item `$@-.` exclude the list from the argument and find the shape [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` t:tFYA!Xs+- ``` The output is a non-empty array, which is truthy if all its entries are non-zero, and falsy if it contains one or more zeros. [Try it online!](https://tio.run/##y00syfn/v8SqxC3SUTGiWFv3/39DUwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##bc69CsIwFAXg/TxFHKSDWJK0qdVFhCq4OTjoIFhoawMxLU2KdPDZYzsoGbzL/eGDe565Ve5OvjUnWROG4auWqnR2Yw/X3exiFku39cixQmC73tZDMK2n3tTE1tIQYzupH3h7dq9MSQiCKldm4v/8zfe6QObHkaZV@YCz/19XUktbkuKXlaimaR1DBIEV1uAUEUOagIkYggtwxEiQgtHxBM4gxoHSsdEP), including truthiness/falsihood test. ### Explanation Consider input `n = 10` as an example. ``` t % Implicit input, n. Duplicate % STACK: 10, 10 : % Range % STACK: 10, [1 2 3 4 5 6 7 8 9 10] t % Duplicate % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 10] FYA! % Convert to base 10 digits and transpose % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [0 0 0 0 0 0 0 0 0 1 1 2 3 4 5 6 7 8 9 0] Xs % Sum of each column % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 1] + % Add, element-wise % STACK: 10, [2 4 6 8 10 12 14 16 18 11] - % Subtract, element-wise % STACK: [8 6 4 2 0 -2 -4 -6 -8 -1] % Implicit display ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes ``` ~⊢∊⍳+(+/⍎¨∘⍕)¨∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24S6R12LHnV0PerdrK2hrf@ot@/QikcdMx71TtWEMjb//29Q96h3hQaQaWKgeXh6GlACxAQA "APL (Dyalog Unicode) – Try It Online") **How?** ``` ⍳ range ( ⍎¨∘⍕) digits (+/ ) digit sums ⍳+ vectorized addition with the range ⊢∊ is the input included? ~ negate ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ḟDS+Ɗ€ ``` For input **n**, this returns **[n]** if **n** is a self number, **[]** if not. [Try it online!](https://tio.run/##y0rNyan8///hjvkuwdrHuh41rfl/uB1IRv7/b6ijYKyjYKqjYK6jYKmjYGQA5APFLMx0FAxNTYAyRkA5Ix0FIBMoZAEUNQDJAMWAqkxBbAMDEMMAAA "Jelly – Try It Online") ### How it works ``` ḟDS+Ɗ€ Main link. Argument: n € Call the link to the left for each k in [1, ..., n]. Ɗ Drei; combine the three links to the left into a monadic chain. D Decimal; map k to the array of its digits in base 10. S Take the sum. + Add k to the sum of the k's digits. ḟ Filterfalse; promote n to [n], then remove all elements that appear in the array to the right. This returns [n] if the array doesn't contain n, [] if it does. ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes ``` n->!sum(i=1,n,i+sumdigits(i)==n) ``` [Try it online!](https://tio.run/##FcjLCoMwEIXhV0ldZegJZKLxsogvUroQijLQDkHtok8f09X5zp@XXdyWy2pSUTffju/HSmIo5F79kk3OwwqlpFSWnN8/q8bNJu@iZ2XzP41ZrRLBPBgtIgZMCB4tY@zBsUMMEQEdeoxgXxMCI1Z4X8c/qVw "Pari/GP – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 46 bytes ``` f x=and[x/=n+sum[read[d]|d<-show n]|n<-[1..x]] ``` [Try it online!](https://tio.run/##bY6xboNADIb3PsUf1CERDuVISNMqDB3SqZ2aDaHqyBkRFQ56d6gMeXcKiZQu9eJftj5/LqX94qoahgJ9IrVK@4dE@7arU8NSpSo7q93Sls0PdHbWu2UqgqDPsqGWJ40EqrnDWBU7SGvZuP03JPJxcyogkySHK1nDsOuMni/AlWWwMY3BPbz9FGbY9y0fHatneL5/cUnf9/BydJ2s/ob5RVXL9v0T85vtYDpGgGKBVNCKYnqkJ4pCWgnabkjEa4qjOPsXfZXTN1c2ojVtaEsiHBmKBMVjCMOxhVe47dyHM28a3oGts2inM2rmDb8 "Haskell – Try It Online") [Answer] # Scala, ~~44~~ 42 bytes ``` x=>0 to x forall(n=>x!=(n/:s"$n")(_+_-48)) ``` [Try it online](https://scastie.scala-lang.org/O9mJjklnT3ODlUIPhYgM7w) [Answer] # [Perl 5](https://www.perl.org/) `-a`, 34 bytes ``` #!/usr/bin/perl -a say!grep{s/./$_+=$&/reg;/@F/}1..$_ ``` [Try it online!](https://tio.run/##FcqxCsIwFAXQ/f6FEFykSW7aNA1FcHLzG0qHUASxIeki4q/3qWc@OZWHF6nz67CUlN/VaKOm01kdTUnLaC5X86HWahIhHFp08OgRMCCCFiTowBbsQA/2YAAHMMJZOCIGxN/9Z4t9zdt9fVZpZmluXtNq@wU "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes ``` ->x{(1..x).all?{|n|n+n.digits.sum!=x}} ``` [Try it online!](https://tio.run/##DchLDsIgFEbhuavQmcbfGy4ttQ7QhTQd1Ee1SSVGIMEAa8eOzpfz9ddfGXU5nEPcMlHY0TDPl5hMMntD9@k5OUvWvzc65Fyc7hgVFI44QQpUjLYBqxpKKkjUaNCCxbIgGWqBEEtEv3L0GG6vmEL6eGfXYxf6XP4 "Ruby – Try It Online") [Answer] # Python 2, ~~70~~ 66 Bytes ``` lambda x:[i for i in range(x)if i+sum([int(j)for j in`i`])==x]==[] ``` EDIT: -4 thanks to @user56656 [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` !/m+sjdT ``` [Test suite.](https://pyth.herokuapp.com/?code=%21%2Fm%2BsjdT&input=154&test_suite=1&test_suite_input=1%0A3%0A5%0A7%0A9%0A20%0A31%0A86%0A154%0A525%0A2%0A4%0A6%0A8%0A10%0A15%0A21%0A50%0A100%0A500&debug=0) If swapping truthy / falsy values is allowed, then we can drop the `!` and get 7 bytes instead. One of [Sok](https://codegolf.stackexchange.com/users/41020/sok)'s suggestions helped me golf 2 bytes. ## Explanation ``` !/m+sjdT – Full program. Takes an input Q from STDIN, outputs either True or False. m – Map over the range [0 ... Q) with a variable d. jdT – Convert d to base 10. s – Sum. + – And add the sum to d itself. / – Count the occurrences of Q in the result. ! – Negate. Implicitly output the result. ``` [Answer] # [Perl 6](https://perl6.org/), ~~39~~ 33 bytes ``` {!grep $_,map {$_+[+] .comb},^$_} ``` [Try it out!](https://tio.run/##K0gtyjH7n1upoJamYPu/WjG9KLVAQSVeJzexQKFaJV47WjtWQS85PzepVidOJb72f3FipUKahqGCgqY1F4RtjMQ2RWKbI7EtkdhGBkh6DRFsCzME29DUBGGmkSlCL5I5JkhsMyS2BRLb0ADZTCQ3INlriqzGwABJHMj@DwA) A bare block with implicit single parameter, called thus: ``` say {!grep $_,map {$_+[+] .comb},^$_}(500); > False say {!grep $_,map {$_+[+] .comb},^$_}(525); > True ``` Since `n + digits(n) >= n`, we can just calculate the Colombian number for all the numbers up to our query value and see if any of them match. So this calculates the Colombian number for a given input: ``` {$_ + [+] .comb} ``` Which we apply to all the values up to our target: ``` (^$_).map({$_+[+] .comb}) ``` But we only care whether any of them match, not what those values are, so as pointed out by @nwellenhof, we can grep: ``` grep $_, map {$_+[+] .comb}, ^$_ ``` The rest is just coercion to bool and wrapping in a block. ## 39 bytes ``` {!((^$_).map({$_+[+] .comb}).any==$_)} ``` [TIO test link provided by @Emigna](https://tio.run/##Tc5NCoMwEAXgvacYQUqCEBJrUkVyEmklLboyrdRVEM8eBRd5u4/5eTPL@J9N9IFuE9m45Yy9ioEL7xa2FUPZl08Sn59/71y4b7D2bO5xdYEmpoh4l12@gzX4AW7BlYRdldyYZKXrlFnptAs5NdiAG7CSmAk/wF2NM1JC/XQ8AA) @nwellenhof pointed out that using grep would save 6 bytes! [Answer] # [Python 3](https://docs.python.org/3/), 60, 56, 55, 54 bytes ``` lambda x:{x}-{n+sum(map(int,str(n)))for n in range(x)} ``` [Try it online!](https://tio.run/##Lc3RCoIwGAXg@55iN@I/OoGbTU3oSaqLiVkD3WQaGOKzrwmdmwMfB874nd/O5qG73kOvh6bVbKnXZTut9jh9Bhr0SMbOmGZPlnPeOc8sM5Z5bV9PWvgWdjI73QQkcpyhUKBEhQtEBqEgM0iBXKAqouwUN7GVVI/6wP4ZfTyiNGnrZEoTMmic66kjE295@AE "Python 3 – Try It Online") -4 using all inverse instead of any -1 by changing != to ^ by @jonathan-allan -1 by using sets by @ovs [Answer] # [J](http://jsoftware.com/), 20 bytes ``` #@-.i.+1#.10#.inv i. ``` [Try it online!](https://tio.run/##RY0xDoAwDAP3viJSR0SUFgplQOIviIoywMb3w0Lc7RT7nEu1rEx@67lyFzwH8VzvlyrrsZ8PFQruh8EgGcwGi0EUtOHlySikERsxOUgGSGFkqNJG4OFFaqlIO4p@ "J – Try It Online") ``` i. Range [0,n-1] 10#.inv To base 10 1#. Sum the digits i.+ Plus the corresponding number -. Remove from the input, leaves an empty list if it was a self number. #@ An empty list is truthy, so return the length instead. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-d!`](https://codegolf.meta.stackexchange.com/a/14339/), 6 bytes ``` N¥U+ìx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWQh&code=TqVVK%2bx4&input=MjE) --- ## Original, 8 bytes Returns the input number for truthy or `0` for falsey. If only the empty array were falsey in JavaScript, this could be 7 bytes. ``` ÂNkUÇ+ìx ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=wk5rVccr7Hg=&input=ODg=) --- ### Explanation ``` :Implicit input of integer U UÇ :Generate the range [0,U) and pass each Z through a function ì : Digits of Z x : Reduce by addition + : Add to Z k :Remove the elements in that array N :From the array of inputs  :Bitwise NOT NOT (~~), casts an empty array to 0 or a single element array to an integer ``` --- ### Alternative ``` Ç+ìxÃe¦U ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=xyvseMNlplU=&input=ODg=) ``` :Implicit input of integer U Ç :Generate the range [0,U) and pass each Z through a function ì : Digits of Z x : Reduce by addition + : Add to Z à :End function e :Every ¦U : Does not equal U ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), ~~27~~ 18 bytes ``` L,RFBDB+B]ARz€b+Ae ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJ8jNycVJ2ynWMajqUdOaJG3H1P8lVtGGCsYKpgrmCpYKRgYKxoYKFmYKhqYmCqZGprFcaVbRRgomCmYKFgqGBkBhBSNDBVMgw8AASBnEcnG5luhwcaZkggglXTslIK2Sk5iblJKoYGgHEvXn4vJXUgKqSyOg7r@RAQA "Add++ – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-apl -MList::Util=sum,all`, 28 bytes ``` $_=all{"@F"-sum/./g,$_}1..$_ ``` [Try it online!](https://tio.run/##Fc27CsIwAAXQ/X5G6dikuekjTaHg5KSjc@ggEog2mDiJv26s@4ETr88wlFK7ZQ3hXR2OlUiveyvbW1O7D6WsXSmERoceA0YYTLCgAglqsAN7cABH0IATaKEVNGEN7G7/WOG7xey3RyrifPIpz/Ml@7DsVbO/Rawx/AA "Perl 5 – Try It Online") [Answer] # [Lua](https://www.lua.org/), 81 bytes ``` for i=1,...do a=i+0(i..''):gsub('.',load'a=a+...')b=b or a==0+...end print(not b) ``` [Try it online!](https://tio.run/##FctBCoAgEEDRq8xuFGWwwE0whxmxQhANs/NPtf28Xx9RPfqAwosnotxBuLhgChGi3c77SQYJfe2SUVjch9AmTvBNwhz@sLcM1yhtmtYnJKuqcY0v "Lua – Try It Online") ``` for i=1,...do a=i+0 -- +0 is needed to avoid an error (i..''):gsub('.',load'a=a+...') -- Sums up all the digits of i b=b or a==0+... -- Sets b to true if a equals the input end print(not b) ``` [Answer] # [FunStack](https://github.com/dloscutoff/funstack) alpha, 46 bytes ``` All? Minus Plus foldl ToBase 10 hook map From0 ``` Try it at [Replit](https://replit.com/@dloscutoff/funstack)! ### Explanation First, we construct a function that adds a number to its base-10 digit sum: ``` Plus foldl Left-fold second argument on addition, with first argument as starting value hook Take a single argument; pass it to the above function twice: first, unchanged, and second, passed through the following function: ToBase 10 Convert to list of base-10 digits ``` This is a bit shorter than the alternatives: ``` Plus Sum ToBase 10 over hook Sum Pair ToBase 10 compose3 ``` Then: ``` From0 Range of integers from 0 up to input-1 ... map Map the above function to each Minus Subtract each from the input All? Are all results truthy (non-zero)? ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~18~~ 12 bytes ``` aNI:_+$+_M,a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgUXTsgqWlJWm6FmsS_Tyt4rVVtON9dRIhQlCZJdFGBjBVAA) *-6 thanks to @DLosc* #### Explanation ``` aNI:_+$+_M,a ; Full program. Input (a) on command line M,a ; Map over the range from 0 to a (_) $+_ ; Sum _ _+ ; And add this to _ aNI: ; Is a not in this list? ; Implicit output ``` Old: ``` $*Y{\a!=a+$+a}M\,a ; Full program. Input (n) on command line. \,a ; Range from 1 to n { }M ; Map over this list (a): $+a ; Sum the digits of a a+ ; Add to a \a!= ; And check if it's not equal to n $*Y ; Get the product of this list ; Implicit output ``` [Answer] # [Arturo](https://arturo-lang.io), ~~36~~ 34 bytes ``` $->x[every? x'n->x<>+∑digits<=n] ``` [Try it](http://arturo-lang.io/playground?F6U5Kl) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 55 bytes ``` .+ * Lv`_+ _+ $&$.& ^_+ $&¶$& \d * Cms`^(_+)\b.*¶\1\b 0 ``` [Try it online!](https://tio.run/##HYlBDoIwFAX3c47aIE2a/wtFXLtw4xEaQKILF7hQ49E4ABerjckkb/Lmdf88nlfNu@o8Ze@ouXyn0VEw1njL8LdtNZZ0K/m0vKehGt0@zb7e1qRpRnJWGiIHjgShUfoOjS0xRAItHT0q5SIosYhIGfkB "Retina – Try It Online") Link includes test cases. Explanation: ``` .+ * ``` Convert input `x` to unary. ``` Lv`_+ ``` Create a range from `x` down to `1`. ``` _+ $&$.& ``` Suffix the decimal value of each `n` to its unary value. ``` ^_+ $&¶$& ``` Make a copy of `x`. ``` \d * ``` Convert each decimal digit of `n` to unary, thus adding the digits to the existing copy of `n`. ``` Cms`^(_+)\b.*¶\1\b ``` Check whether `x` appears in any of the results. ``` 0 ``` Invert the result. [Answer] # JavaScript (ES6), ~~52~~ 51 bytes *Saved 1 byte thanks to @l4m2* Returns **0** or **1**. ``` n=>(g=k=>k?eval([...k+'k'].join`+`)-n&&g(k-1):1)(n) ``` [Try it online!](https://tio.run/##bctBDoMgEEDRfU/hSiCOBFCsbYI9iDGRWCWKHUxtvD5126Sr/zdvsYfdh/e8fXIMzzFOJqJpqDPeNP4xHnalLefcZ8STji9hxj7rWY5p6qjPJbtLRpHFIeAe1pGvwdFWQgEarnADJaCQUFcgdQla6Y6/7EYxMU0yUcwIYYxdfqyCEiqoQYrTgJKgzxHijPiH4xc "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~63~~ 58 bytes ``` s 0=0 s x=x`mod`10+s(x`div`10) f n=all(\x->x+s x/=n)[1..n] ``` [Try it online!](https://tio.run/##dZAxb8IwEIV3/4rXqAMIldopoTC4Q4cuoDK0G63kSHGUCONUOEHm1wcPDEjVu8n6Pt/d0zVlOFjnxjFAaikCoo7m2FVGyVmYRFO15/Scihpel85NfuLTW5ylb8/aT/dqPve/Y4QJTTe46t0aXKDxN/Rf/Wnr8Yi2RoTWCfeN9ch2mwzWBYvss@ux2zxkQhzL1qeuqhNIVUPdz/s@DfbGXwgvCH8lfE14Ltlilmi1JEIVCxY2Z3Hze/5RpiPdxIKJJRMrJpSkpmAmV8wUfJqUvOm/Gq8 "Haskell – Try It Online") ]
[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 7 years ago. [Improve this question](/posts/1798/edit) Write a program to test if a string is palindromic, with the added condition that the program be palindromic itself. [Answer] ## Ruby ``` z=gets;puts *z.reverse==z&&1||0||1&&z==esrever.z* stup;steg=z ``` Prints 1 if the input is a palindrome, 0 if it isn't. Input without linebreak. Doesn't use any comments, instead it uses 2 tricks: * Short-circuiting: `0` is true-ish in Ruby (only `nil` and `false` evaluate to false), so `1&&z==esrever.z* stup` isn't evaluated and thus can't raise a runtime exception * The splat/multiplication operator (`*`): To avoid a syntax error in `z=esrever.z stup`, we force the parser to parse this as `z=esrever.z()*stup` by adding a `*`. On the other side, the `*` is parsed as a splat operator, which in a function call splits an array in a series of parameters. If there's only one element instead of an array, it basically does nothing, so `puts *foo` is equivalent to `puts foo`. Obvious solution using comments (prints true/false): ``` puts gets.reverse==$_#_$==esrever.steg stup ``` [Answer] **Python without comment** ``` "a\";w=]1-::[w trinp;)(tupni_war=w;";w=raw_input();print w[::-1]==w;"\a" ``` I'm surprised that no one found that trick yet, it should work in most languages! [Answer] ## Perl `perl -nle "$s=$_ eq+reverse;print$s;s$tnirp;esrever+qe _$=s$"` no comment tricks, just cleverly abusing the substitution operator (hey, perl variables start with a $ too, so what?) [Answer] # Python 2.7 ``` s=raw_input();print'YNEOS'[s!=s[::-1]::2]#]2::]1-::[s=!s['SOENY'tnirp;)(tupni_war=s ``` [Answer] ## C ``` #include <stdio.h> // #include <string.h> // int main() { // char str[1024]; // fgets(str, sizeof(str), stdin); // int i = 0, j = strlen(str) - 2; // for (; i < j; i++, j--) // if (str[i] != str[j]) { // printf("no\n"); // return 0; // } // printf("yes\n"); // } // // } // ;)"n\sey"(ftnirp // } // ;0 nruter // ;)"n\on"(ftnirp // { )]j[rts =! ]i[rts( fi // )--j ,++i ;j < i ;( rof // ;2 - )rts(nelrts = j ,0 = i tni // ;)nidts ,)rts(foezis ,rts(stegf // ;]4201[rts rahc // { )(niam tni // >h.gnirts< edulcni# // >h.oidts< edulcni# ``` Running example: ``` $ gcc -std=c99 c.c && ./a.out blahalb yes ``` [Answer] # Golfscript ``` .-1%=#=%1-. ``` * just with comment trick * input without \n at the end * perform matching char by char (even for punctuation) * returns 1 for success, 0 for failure [Answer] # PHP ``` echo strrev($z)==$z;#;z$==)z$(verrts ohce ``` Facts: * `$z` string, the input string to check * `$t` boolean, TRUE if the input string `$z` is palindrome, FALSE otherwise * Using comments to help me make the code palindrome. * Outputs `$t` * Source itself is a palindrome The reason why it will not be possible to implement palindromic palindrome checker in PHP it's because PHP variables are named starting with a `$`. You cannot end an identifier name with `$` in PHP. [Answer] # PHP ``` <?php eval/*/*/(';{$i=fgets(STDIN,2e9);};{$a="strrev";}{var_dump("{$i}"=="{$a($i)}");}/*}{*\{;("{(tupni$)a$}"=="{putni$}")ohce}{;"verrts"==a$};{;(9e2,NIDTS)stegf=i$);');/*\*\eval php?> ``` Uses some odd tricks to avoid the `$` issue, technically isnt a palindrome as I had to sneak a `;` in at the end. ``` <?php $i = fgets(STDIN,2e9); echo $i == strrev($i);/*\;(i$)verrts == i$ ohce ;(9e2, NIDTS)stegf = $i php?> ``` This is a working one that uses PHP's `/* */` comments and the fact that you don't need the end for them. [Answer] # [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 17 bytes ``` ^Cz.=i_;@;_i=.zC^ ``` Not exactly sure how the win is defined, but I put the byte count up top. `^` gets the input and pushes it to the first stack. `C` copies the first stack to the second. `z` reverse the top of the stack, so "as" becomes "sa". `.` shifts the active stack, so the active stack has the input, and the inactive one has the reversed input. `=` checks for equality, returning `0` for equality. `i` inverts the ToS, so `0` becomes `1`, and anything else pretty much becomes `False`. `_` pops and sets the temp variable which the `;` then prints. `@` ends the program manually, so it doesn't hit the reversed part. This makes the palindrome. [Answer] ## CoffeeScript I actually struggled with the reverse spellings of 'split', 'reverse' and 'join' :\ ``` p=(s)->s.split('').reverse().join('')==s#s==)''(nioj.)(esrever.)''(tilps.s>-)s(=p ``` [Answer] ## Groovy ``` print args[0]==args[0].reverse()?1:0//0:1?)(esrever.]0[sgra==]0[sgra tnirp ``` [Answer] # Python 3, 55 bytes Uses a comment, but is shorter than the other Python one that uses comments. ``` s=input();print(s==s[::-1])#)]1-::[s==s(tnirp;)(tupni=s ``` [Answer] # Javascript ``` function a(b){return b==b.split('').reverse().join('')}//})''(nioj.)(esrever.)''(tilps.b==b nruter{)b(a noitcnuf ``` Hard to do it without comments... ]
[Question] [ # Aligning Lines! Given a character and a multiline string, your job is to pad each line of the string so they line up among the given delimiter. ## Examples **Input:** ``` , Programming, Puzzles And, Code golf ``` **Output:** ``` Programming, Puzzles And, Code golf ``` # Input The input will be a multiline string and a character (which you will align among), you may take these in any order / format you wish. The character will appear exactly once per line. Each line of the input may be different in length. Input can be through function arguments or STDIN. # Output The output should be the same string centered. You are allowed one trailing newline and no trailing whitespace. The output should be padded with the *minimum* amount of spaces. You may not remove any leading whitespace in the input (if it exists). Output can be from function return or STDOUT. [Answer] # APL (37) APL just isn't very good at string processing (or I'm not good at golfing, of course). ``` {⌽∊R,¨' '/⍨¨(⌈/-+)⍺⍳⍨¨⌽¨R←S⊂⍨S=⊃S←⌽⍵} ``` This takes the character as its left argument, and the multiline string as its right argument. It is assumed that the multiline string ends in a linefeed (e.g. `A\nB\nC\n` rather than `A\nB\nC`.) Since I can use "any format [I] wish", and this is also the conventional format for text files, I think this is reasonable. Explanation: * `S←⌽⍵`: reverse the string, and store it in `S`. * `R←S⊂⍨S=⊃S`: split `S` on its first character, and store the array of strings in `R`. * `⍺⍳¨⌽¨R`: reverse each string in `R`, and then find the index of ⍺ (the character) in each string. * `(⌈/-+)`: subtract each of the indices from the largest index, giving the amount of spaces needed * `' '/⍨¨`: for each of those values, generate that many spaces * `R,¨`: add the spaces to each string in `R`. * `∊`: join all the strings together * `⌽`: reverse it (to get the original order back) Example: ``` NL←⎕UCS 10 ⍝ newline test←'Programming, Puzzles',NL,'And, Code golf',NL test ⍝ test string Programming, Puzzles And, Code golf ⍝ run the function +X←','{⌽∊R,¨' '/⍨¨(⌈/-+)⍺⍳⍨¨⌽¨R←S⊂⍨S=⊃S←⌽⍵}test Programming, Puzzles And, Code golf ⍴X ⍝ result is really a string with newlines, not a matrix 44 ``` [Answer] # CJam, ~~23~~ ~~22~~ 20 bytes *Thanks to Dennis for saving 2 bytes.* ``` ea_rf#_:e>\fm.{S*\N} ``` This reads the lines from command-line arguments and the character from STDIN. The online interpreter doesn't support command-line arguments, but you can [test an equivalent version here.](http://cjam.aditsu.net/#code=lqN%2F_%40f%23_%3Ae%3E%5Cfm.%7BS*%5CN%7D&input=%2C%0AProgramming%2C%20Puzzles%0AAnd%2C%20Code%20golf) ## Explanation ``` ea e# Get the lines from ARGV. _rf# e# Duplicate input, read the character and find index of character in each line. _:e> e# Duplicate indices and find maximum. \fm e# Subtract each index from the maximum index. .{ e# Apply this block to each pair of line and (max_index - index). S* e# Get a string with the right amount of spaces. \N e# Swap spaces with line and push a line feed. } ``` [Answer] # [Pip](http://github.com/dloscutoff/pip), ~~22~~ ~~20~~ 18 + 1 = 19 bytes ``` Y_@?qMgsX(MXy)-y.g ``` Takes strings as command-line arguments and delimiter from STDIN (*idea borrowed from Martin's CJam answer*). Uses `-n` flag to print output values on separate lines. ``` g is list of cmdline args; s is space (implicit) q Read the delimiter from stdin _@? Construct a lambda function that takes a string and returns the index of the delimiter in it Mg Map that function to each remaining item in g Y Yank the resulting list of indices into the variable y (MXy)-y Take the max of y minus each element in y sX Space, repeated that many times... .g ... concatenated to each item in g Print, newline-separated (implicit, -n flag) ``` And an example run: ``` C:\Users\dlosc> pip.py -ne Y_@?qMgsX(MXy)-y.g "Programming, Puzzles" "And, Code golf" , Programming, Puzzles And, Code golf ``` [Answer] # JavaScript ES 2015, 113 bytes ``` f=(c,s)=>s.split` `.map((e,_,a)=>' '.repeat(a.map(j=>j.indexOf(c)).reduce((g,h)=>g>h?g:h)-e.indexOf(c))+e).join` ` ``` Not quite as short as the golfing languages posted so far. Takes input as two function arguments, e.g. `f(',','Programming, Puzzles\nAnd, Code golf')`. The snippet below is ungolfed and includes an easy method to test. ``` f=function(c,s){ return s .split('\n') .map(function(e,_,a){ return ' '.repeat( a.map(function(f){ return f.indexOf(c) }).reduce(function(g,h){ return g>h?g:h })-e.indexOf(c) )+e }) .join('\n') } run=function(){document.getElementById('output').innerHTML=f(document.getElementById('char').value,document.getElementById('string').value)};document.getElementById('run').onclick=run;run() ``` ``` <label>Character: <input type="text" id="char" value="," maxlength="1" /></label> <textarea id="string" rows="4" cols="30" style="display:block"> Programming, Puzzles And, Code Golf</textarea><button id="run">Run</button><br /> <pre id="output"></pre> ``` [Answer] # Pyth, ~~27~~ 24 bytes ``` V.z+.[deSmxdz.z<NJxNz>NJ ``` Updated for the [latest Pyth](https://github.com/isaacg1/pyth/commit/d814c9e3de3cba5170a5391dc8b42a810fa29b74). [Live demo.](https://pyth.herokuapp.com/?code=V.z%2B.%5BdeSmxdz.z%3CNJxNz%3ENJ&input=%2C%0AProgramming%2C+puzzles%0AAnd%2C+code+golf&debug=1) ## 27-byte version ``` jbm+.[eSmxkz.z<dJxdz\ >dJ.z ``` [Live demo.](https://pyth.herokuapp.com/?code=jbm%2B.%5BeSmxkz.z%3CdJxdz%5C+%3EdJ.z&input=%2C%0AProgramming%2C+puzzles%0AAnd%2C+code+golf&debug=1) [Answer] # Pyth, 18 bytes ``` V.z+*d-eSxRz.zxNzN ``` [Answer] # [Dyalog APL](https://dyalog.com/), ~~22~~ ~~20~~ 16 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) -4 thanks to ngn. APL is actually not so bad at string processing, if allowed to work with arrays. In this challenge, we may chose the most appropriate format, which for APL means a vector of text vectors as left argument, and the delimiter as a scalar right argument. This even handles multiple delimiters per line, and aligns the first one of each line. ``` ⊣,¨⍨' '⍴¨⍨⌈.⍳-⍳¨ ``` `⊣,¨⍨` prepend each line with `' '⍴¨⍨` as many spaces as `⌈.⍳` the rightmost index of the character among the lines `-` minus `⍳¨` the index of the character in each line [Try APL online!](http://tryapl.org/?a=f%u2190%u22A3%2C%u2368%A8%27%20%27/%u2368%A8%28%28%u2308/-%u22A2%29%u2373%A8%29%20%u22C4%20%u2191%27Programming%2C%20Puzzles%27%20%27And%2C%20Code%20golf%27%20f%20%27%2C%27&run) (`↑` added to print output vertically) **Bonus?** [Works](http://tryapl.org/?a=f%u2190%u22A3%2C%u2368%A8%27%20%27/%u2368%A8%28%28%u2308/-%u22A2%29%u2373%A8%29%20%u22C4%20%u2191%27Programming%2C%20Puzzles%27%20%27Do%2C%20I%2C%20get%2C%20a%2C%20bonus%3F%27%20f%20%27%2C%27&run) for any number of strings, and delimiters (aligns by left-most). [Answer] # Julia, 117 bytes ``` f(c,t)=(s=[split(l,c)for l=split(t,"\n")];join(map(i->lpad(i[1],maximum(map(i->length(i[1]),s))," ")*c*i[2],s),"\n")) ``` Ungolfed: ``` function f(c::String, t::String) # Create an array of arrays by splitting on newlines and # then on the given delimiter s = [split(l, c) for l in split(t, "\n")] # Find the maximum length on the left side of the delimiter m = maximum(map(i -> length(i[1]), s)) # Rejoin on the delimiter and pad each line with spaces, # and rejoin this with newlines join(map(i -> lpad(i[1], m, " ") * d * i[2], s), "\n") end ``` [Answer] ## Python 3, 85 (IDLE 3.2.2, Windows) ``` c,*s=input().split('\n') for x in s:print(' '*(max(z.find(c)for z in s)-x.find(c))+x) ``` Pretty straightforward. This finds the position of the character in the string twice: once to find the max (well, once per line), and once to find the offset. I tried combining these but it was longer. Python 3 is used for the input unpacking. MY IDLE seems to take multiline strings as input. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ỵ©w€µạṀ⁶ẋż®Y ``` **[Try it online!](https://tio.run/##y0rNyan8///h7i2HVpY/alpzaOvDXQsf7mx41Ljt4a7uo3sOrYv8//9/QFF@elFibm5mXrqOQkBpVVVOajGXY16KjoJzfkqqQnp@ThpXqo6Ca2ioK1dyYmYRUCI5PzMvI7UIqCMxMQNIcrmk5uVlFisAUUlGqkJSanGJDlhjapFCZh5YrDy/KCflvw4A "Jelly – Try It Online")** Done and golfed with [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) in [**J**elly **H**yper **T**raining (JHT)](https://chat.stackexchange.com/rooms/57815/jelly-hypertraining), our Jelly practice chat room. ### How it works The third command line argument (first input) should be the multi-line string, and the character should be the fourth command line argument (second input). ``` Ỵ©w€µạṀ⁶ẋż®Y ~ Full program. Ỵ ~ Split the string by newlines. © ~ Copy the result to the register. w€ ~ Get the index of the first occurrence of the character on each line. Ṁ ~ Take the maximum. µạ ~ And subtract it from each index, taking the absolute value. ⁶ẋ ~ Repeat a space that many times (vectorizes). ż® ~ Interleave with what was stored in the register. Y ~ Join by newlines and print implicitly. ``` I am not sure whether taking input as a list of lines is allowed, so this takes a multiline string as input. If it were allowed: ### 10 bytes ``` w€µạṀ⁶ẋż³Y ``` [Try it online!](https://tio.run/##y0rNyan8/7/8UdOaQ1sf7lr4cGfDo8ZtD3d1H91zaHPk////o5UCivLTixJzczPz0nUUAkqrqnJSi5V0lBzzUnQUnPNTUhXS83PSgAKpOgquoaGuQFZyYmYRUDI5PzMvI7UIqC8xMQNIAmVcUvPyMosVgKgkI1UhKbW4RAesPbVIITMPLFaeX5STohT7XwcA "Jelly – Try It Online") [Answer] # Kakoune, 9 bytes ``` s\Q<c-r>"<ret><a-h><a-;>& ``` (`<c-x>` means CTRL+x, `<a-x>` is alt) [![asciicast](https://asciinema.org/a/OkI9DDXNTVRuVaTU5N6LDX6r3.svg)](https://asciinema.org/a/OkI9DDXNTVRuVaTU5N6LDX6r3) Expects the delimited in the "-register, the input in the default buffer and the cursor spanning the entire buffer. Explanation: ``` s <ret> Match the contents of the current selection on the following regex, select every part that matches \Q Quote, everything after this only matches itself literally (avoiding problems with . etc) <c-r>" Dump the contents of the "-register (containing the char to align on) <a-h> Select to the beginning of the line for each selection <a-;> "flip" each selection, so that the anchor is at the end. & Align everything ``` This might be stretching the allowed input format a bit, so here's a solution which takes the input exactly like the challenge example, in the default buffer, with the cursor at (0, 0): # Kakoune, 13 bytes ``` xd%s\Q<c-r>"<backspace><ret><a-h><a-;>& ``` This is basically the same solution, with a prelude deleting the delimiter and putting it into the "-register. Note that the newline is also put into the register, which the `<backspace>` deletes. [Answer] # C# 4.0, ~~329~~ ~~320~~ 307 bytes ``` using System;class P{static void Main(){Func<char,dynamic>f=(d)=>Console.ReadLine().Split(d);var c=f(' ')[0][0];var m=0;var l=new string[9999][];var z=0;for (l[z]=f(c);l[z].Length==2;l[z]=f(c)){m=Math.Max(l[z][0].Length,m);z++;}for(var i=0;i<z;i++){Console.WriteLine("{0,"+m+"}"+c+"{1}",l[i][0],l[i][1]);}}} ``` Ungolfed version : ``` using System; class P { static void Main() { // lamba to to read a line and split on a char, returns an array of Func<char,dynamic>f=(d)=>Console.ReadLine().Split(d); // read the separator char by taking the first char of the first string // in the array // use our lambda var c=f(' ')[0][0]; var m=0; // max position where char is found var l=new string[9999][]; // hold all input var z=0; // count valid entries in l // loop until the input doesn't contain an // array with 2 elements // here we use our lambda agian, twice for (l[z]= f(c);l[z].Length==2;l[z] = f(c)) { // calculate max, based on length // of first element from the string array m=Math.Max(l[z][0].Length,m); z++; // increase valid items } // loop over all valid items for(var i=0;i<z;i++) { // use composite formatting with the padding option // use the max to create a format string, when max =4 // and seperator char is , this will give // "{0,4},{1}" Console.WriteLine("{0,"+ m +"}"+c+"{1}",l[i][0],l[i][1]); } } } ``` It does accept a maximum of 9999 lines ... [Answer] # Common Lisp, 101 bytes ``` (lambda(c l)(dolist(x l)(format t"~,,v@a~%"(-(apply'max(mapcar(lambda(x)#1=(position c x))l))#1#)x))) ``` The first parameter is the character, the second is a list of string to be aligned. [Try it online!](https://tio.run/##NYtBCsIwEAC/sqRIdyEefICg@AEf4GVN2hLYdEMaJfbQr9d48DYMM07CknbcUTg@PaMDIfTabMH641Fz5ALFbNa@L7wdDB6RU5JPH7li5OQ4/@9K3emMSZdQgs7goBIJNdlRI9q7h4UezT3rlDnGME8W7q91lWExYK6zt3BTP8CkMprWfwE) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 (or 5?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` U|XδkZαú» ``` [Try it online.](https://tio.run/##yy9OTMpM/f8/tCbi3JbsqHMbD@86tPv/fx2ugKL89KLE3NzMvHQdhYDSqqqc1GIux7wUHQXn/JRUBff8nDQuIAss7ZyRmJOTmpcOVKGGJA8A) If the I/O of the multi-line string could be a list of lines, this would be **5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` δkZαú ``` [Try it online.](https://tio.run/##yy9OTMpM/f//3JbsqHMbD@/6/1@HK1opoCg/vSgxNzczL11HIaC0qiontVhJR8kxL0VHwTk/JVXBPT8nDSgAZIOVOGck5uSk5qWDVakhq4kFAA) **Explanation:** ``` U # Store the first input-character in variable `X` | # Take the other input-lines as a list of strings δ # For each string: X k # Get the 0-based index of character `X` in this string Z # Push the maximum index (without popping the list itself) α # Take the absolute difference of this maximum with the integer-list ú # Pad each string of the (implicit) input-list (because we've used `|`) with # that many leading spaces » # And join the list by newlines # (after which it is output implicitly as result) δ # For each string in the second (implicit) input-list k # Get the 0-based index of the first (implicit) input-character Zαú # Same as above # (after which the list of strings it output implicitly as result) ``` [Answer] ## Matlab / Octave, 106 bytes Function that uses three separate arguments for character, string, string; and gives result in stdout: ``` function f(c,s,t) p=find(s==c)-find(t==c);disp([repmat(32,1,max(-p,0)) s]),disp([repmat(32,1,max(p,0)) t]) ``` Example in Matlab: ``` >> f(',', 'Programming, Puzzles', 'And, Code golf') Programming, Puzzles And, Code golf ``` Or [try it online](http://ideone.com/oaR4ow) with Octave interpreter. [Answer] # Julia, 80 bytes ``` f(c,s)=(t=split(s,' ');u=[search(i,c)for i=t];join([" "].^(maxabs(u)-u).*t,' ')) ``` Ungolfed: ``` function f(c,s) # converts multiline string to array of single-line strings t=split(s,'\n') # creates array of positions of delimiter u=[search(i,c)for i=t] # Appends appropriate number of spaces to each line # (uses elementwise operations to achieve this result) v=[" "].^(maxabs(u)-u).*t # Recombines array of strings to multiline string and returns return join(v,'\n') end ``` [Answer] # JavaScript (ES6), 105 Using template strings, the 2 newlines are significant and counted. Test running the snippet in any EcmaScript 6 compatible browser (that is FireFox. Chrome does not support default parameters) ``` f=(s,c,p=(s=s.split` `).map(r=>m<(v=r.indexOf(c))?m=v:v,m=0))=>s.map((r,i)=>' '.repeat(m-p[i])+r).join` ` // Ungolfed f=(s,c)=>{ s=s.split('\n') p=s.map(r=>r.indexOf(c)) m=Math.max(...p) s=s.map((r,i)=>' '.repeat(m-p[i])+r) return s.join('\n') } // TEST out=x=>O.innerHTML+=x+'\n' out(f(`Programming, Puzzles And, Code golf`,',')) ``` ``` <pre id=O></pre> ``` [Answer] # Python 2, 93 bytes ``` def f(x,y,z): p=y.index(x)-z.index(x) if p<0:y=" "*abs(p)+y else:z=" "*p+z print y+'\n'+z ``` Called like so: ``` f(',','Programming, Puzzles','And, Code Golf') ``` [Answer] # Ruby, 74 bytes ``` l=lambda{|d,s|s.each{|e|puts ' '*(s.map{|f|f.index(d)}.max-e.index(d))+e}} ``` and call it like ``` l.call ',',['Programming, Puzzles','And, Code golf'] ``` [Answer] ## R, 68 bytes ``` function(c,x,y,r=regexpr)cat(x,"\n",rep(" ",r(c,x)-r(c,y)),y,sep="") ``` Unnamed function that takes `3` inputs; `c` which is the character to align, `x` is the first string and `y` the second string. In R, the function `regexpr` returns the position of a given pattern in a string. The solution works by applying `regexpr` on both strings and repeating white spaces amounting to the difference and subsequently just print both inputs separated by a newline. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ·mqV Õvù ÕmqV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=t21xViDVdvkg1W1xVg&input=IlByb2dyYW1taW5nLCBQdXp6bGVzCkFuZCwgQ29kZSBnb2xmIgoiLCI) ``` ·mqV Õvù ÕmqV :Implicit input of string U & delimiter V · :Split U on newlines m :Map qV : Split on V Õ :Transpose v :Modify first element ù : Left pad with spaces to the length of the longest Õ :Transpose m :Map qV : Join with V :Implicit output joined with newlines ``` [Answer] # C#, 191 As a function. Roughly a porting of my JS answer. ``` using System.Linq;string f(string s,char c){var q=s.Split('\n');int m=0,v;Array.ForEach(q,x=>m=m<(v=x.IndexOf(c))?v:m);return String.Join("\n",q.Select(x=>new String(' ',m-x.IndexOf(c))+x));} ``` [Answer] # Python 2, ~~67~~ 66 bytes ``` def a(d,l): i=l[0].index(d) for e in l:print' '*(i-e.index(d))+e ``` Called with: ``` a(',', ['Programming, Puzzles', 'And, Code golf']) ``` [Answer] ## Moonscript, 138 bytes ``` (n)=> i=0 @=' '..@ l=[b-a for a,b in @gmatch " ().-()"..n] m=math.max unpack l (@gsub ' ',(a)-> i=i+1 a..(' ')\rep m-l[i])\sub(2) ``` This returns a function which takes 2 arguments. The first is the string, the second is the character to align on. These arguments are the implicit argument @, and n. First, I append a new line to the string, to make processing easier. ``` @=' '..@ ``` Now, I generate a list of the positions of every alignment character, using `gmatch`. Next, I replace the newline before every line with the correct number of spaces, then trim the newline I added at the beginning. [Answer] # Lua, 169 bytes ``` function a(d,t)m={}for k,v in pairs(t)do m[#m+1]=string.find(v,d)end o=math.max(unpack(m))for k,v in pairs(t)do print(string.rep(" ",o-(string.find(v,d)or 0))..v)end end ``` Not as short as other answers but this is my first one :D [Answer] # [Retina](https://github.com/m-ender/retina), 71 bytes ``` +`^((.)(.*¶)*)((.)*\2.*¶)((?<-5>.)*(?(5)\2|(.)\2).*) $1$#7$* $4$#5$* $6 ``` [Try it online!](https://tio.run/##K0otycxL/P9fOyFOQ0NPU0NP69A2TS1NEFsrxgjM09Cwt9E1tQMKaNhrmGrGGNUAJWOMNPW0NLlUDFWUzVW0FFRMVJRNQbTZ//86XAFF@elFibm5mXnpOgoBpVVVOanFXI55KToKzvkpqQrp@TlpAA "Retina – Try It Online") Note: This leaves the alignment character in the output; it can be deleted at a cost of 4 bytes. If only two strings need to be aligned, then for 52 bytes: ``` ^(.)¶((.)*\1.*¶)((?<-3>.)*(.)*\1.*) $#5$* $2$#3$* $4 ``` Explanation: ``` ^(.)¶ ``` This matches the alignment character. ``` ((.)*\1.*¶) ``` This matches the first line and also keeps track of how many characters there were before the alignment character. (.NET keeps a match stack for each variable, in this case, `$3`.) ``` ((?<-3>.)*(.)*\1.*) ``` This matches the second line, trying to account for as many characters as we found on the first line. `?<-3>` causes the match to pop the stack for each character, until it is empty, at which point the match fails, and the `(.)*` then matches the remaining characters before the alignment character. At this point we have the following variables: * `$1` contains the alignment character * `$2` contains the first line * `$3` contains a stack whose length is the first line prefix minus the second line prefix * `$4` contains the second line * `$5` contains a stack whose length is the second line prefix minus the first line prefix `$#5$*` then prefixes the necessary number of spaces to make the first line align with the second, and vice versa for `$#3$*`. Similar logic applies to the main answer, except here we have to find two lines which don't align so that we can align them (this is where the `?(5)` comes in) and then repeat the alignment over all the lines until they are all equally aligned. [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=max`, ~~69~~ 64 bytes ``` $l=max map{/$d/xg;pos}($d,@a)=<>;say map{/$d/x;$"x($l-pos).$_}@a ``` [Try it online!](https://tio.run/##RY6xDoIwFEV3vqIxHSBpAQcWEMW4asKgs2lSaJq88hpaE8Tw61Z0cbrJOWe4thuhCIFCbcREjLCvjMpsUpVFt8RUskYk9W5fOfH824puppgCX5skpfelESGw6DhIRk4oO6IQ@qgdUY3CGD0oRtrHPEPnoisiAfwSj3h4o/UaBxf4pUjzbb7uWTtfljevf4cChw8 "Perl 5 – Try It Online") ]
[Question] [ You are given three parameters: start(int), end(int) and list(of int); Make a function that returns the amount of times all the numbers between **start** and **end** are multiples of the elements in the **list**. example: ``` start = 15; end = 18; list = [2, 4, 3]; 15 => 1 (is multiple of 3) 16 => 2 (is multiple of 2 and 4) 17 => 0 18 => 2 (is multiple of 2 and 3) result = 5 ``` The function should accept two positive integer numbers and an array of integers as parameters, returning the total integer number. Assume that start is less <= end. examples: ``` Multiple(1, 10, [1, 2]); => 15 Multiple(1, 800, [7, 8]); => 214 Multiple(301, 5000,[13, 5]); => 1301 ``` The shortest solution is the victor!!! May he odds be ever in your favor... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ŸÑ˜åO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6I7DE0/PObzU//9/YwNDLlMDAwOuaENjHdNYAA "05AB1E – Try It Online") --- ### Explanation ``` Ÿ - the numbers between start and end Ñ - get their divisors ˜ - deep flatten this list å - find the instances of the elements in the list in these divisors O - Sum this ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` (a#b)x=sum[1|0<-mod<$>[a..b]<*>x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNROUmzwra4NDfasMbARjc3P8VGxS46UU8vKdZGy64i9n9uYmaegq1CQVFmXomCioKGoamyoYVmtJGOiY5x7H8A "Haskell – Try It Online") Explanation: ``` (a#b)x --take two values a and b and the list x [a..b] --generate the range a, a+1, ... , b mod<$>[a..b] --partially apply "mod" to each entry of the list mod<$>[a..b]<*>x --apply the partially applied functions to all values of the list x [1|0<-mod<$>[a..b]<*>x] --generate a new list with a one for every zero in the previously computed list (a#b)x=sum[1|0<-mod<$>[a..b]<*>x] --sum it all up ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 44 bytes ``` (a,x,y)=>a.map(n=>t+=y/n-(~-x/n|0)|0,t=0)&&t ``` [Try it online!](https://tio.run/##XcxBCoMwFATQfU/xV5LQH/OjDXUTL1K6CFZLiyZSQ1GQXj1NEbpwNgPDY572bafm9RiDcP7Wxs5EZnHGhZva5oMdmTN1OJpFOsE@YpZuJb4SBkM8y0JsvJt83@a9v7OOXRRCcUVIpYhz2CIlKH3YyTNCtcmK/jTJQp32VJUIOtmSkta08d9pGuIX "JavaScript (Node.js) – Try It Online") --- # [Python 2](https://docs.python.org/2/), 38 bytes ``` lambda a,x,y:sum(y/i-~-x/i for i in a) ``` [Try it online!](https://tio.run/##RcxBCoMwFATQfU8x4CaBLyaxoVLwJG0XKSU0UKOoBbPx6umHgJ3NMPCYKa3vMZrs@3v@uOH5cnC0Ubou30GkJtR7vTUBfpwRECKczNMc4iq8uGmCeRC4tJISJRW0PR3kQugK6dRhKhh9/hvdEiyjVjGzqji@4Z1/ "Python 2 – Try It Online") \$ \sum \_{i \in list} \lfloor \frac{end}{i} \rfloor - \lfloor \frac{start-1}{i} \rfloor \$ The answer seems trivial and naive. So am I misunderstand something? [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 21 bytes ``` {sum $^a..$^b X%%@^c} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0V0ElLlFPTyUuSSFCVdUhLrn2vzVXcWKlQpqGoY6hgU60oY5RrCZCyMIAKGauY4EQMzYw1FEwNQCJGxrrmAIl/gMA "Perl 6 – Try It Online") ### Explanation ``` { } # Anonymous codeblock returning sum # The sum of $^a..$^b # How many numbers in the range a to b X%% # Are divisible by any of @^c # The third parameter ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` :i\~z ``` Inputs are a cell array containing the `start` and `end` values, and then a column vector defining `list`. [Try it online!](https://tio.run/##y00syfn/3yozpq7q//9qQ1MFQ4tarmgjawUTawXjWAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfn/3yozpq7q//9qQ1MdBUOLWq5oI2sFE2sF41gA). ### Explanation ``` : % Range, with implicit input: cell array {start, end}. This gives the range % from start to end i % Input: list of numbers in the form of a column vector \ % Modulo, with boradcast. This gives a matrix with each number in the range % modulo each number in the list ~ % Logical negation z % Number of nonzero entries. Implicit display ``` [Answer] # Python 3, 54 bytes ``` lambda s,e,L:sum(n%l<1for n in range(s,e+1)for l in L) ``` [Try It Online!](https://tio.run/##VclBDsIgEIXhfU/BxgTixDDFRmL0Br1B46IqVRIYGqCLnh7pxuhL3ub75zW/A6li/RxiZmlNTf0hmRzNY4nJBnLW28xR1okyXd3o78@RJTDQn9PiOe3cBacQGTFLLI70MrzWPYoN3Ya9KHO0lPnEsQPUMLRwBHUTovk6oIQBof1HLaueQP@qkgid3AIq6GopHw) [Answer] # APL+WIN, ~~20~~ 15 bytes 5 bytes saved thanks to Adam. Prompts for end integer, start integer and then list: ``` +/,0=⎕∘.|⎕↓0,⍳⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7a@joEtUOxRxwy9GhDdNtlA51HvZiDzP1DB/zQuQwsuQ1MuIwUTBWMuIM@Ay5DLUMEIyLQwALHNFSyAbFMDIMfYAChlrGAKAA "APL (Dyalog Classic) – Try It Online") Could be reduced to 9 bytes if we could enter two lists and not have to generate the first: ``` +/,0=⎕∘.|⎕ ``` [Answer] # [R](https://www.r-project.org/), 35 bytes ``` function(a,b,l)sum(b%/%l-(a-1)%/%l) ``` [Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9PI1EnSSdHs7g0VyNJVV81R1cjUddQE8TS/J@mYaijYGgAxFZGmlxgnoUBkGtuZQHiGhsABUwNQCLJGobGQLam5n8A "R – Try It Online") Implementation of [tsh's method](https://codegolf.stackexchange.com/a/196599/67312) by [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe). 3 bytes shorter than the previous version: # [R](https://www.r-project.org/), ~~45~~ 38 bytes -7 bytes thanks to Nick Kennedy and Xi'an. ``` function(a,b,l)sum(!outer(a:b,l,`%%`)) ``` [Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9PI1EnSSdHs7g0V0Mxv7QktUgj0QoooJOgqpqgqfk/TcNQR8HQAIitjDS5wDwLAyDX3MoCxDU2AAqYGoBEkjUMjYFsoB4A "R – Try It Online") Boils down to summing the values of `!(x %% y)` for `x` in `a:b` and `y` in `l` (`%%` is \$mod\$ in R, so `x %% y == 0` iff `x` is a multiple of `y`). [Answer] # [C++ (clang)](http://clang.llvm.org/), ~~113~~ ~~110~~ ~~109~~ ~~108~~ ~~106~~ ~~100~~ ~~93~~ ~~99~~ ~~91~~ 89 bytes ``` using I=int;I s;void f(I a,I b,I*l,I z,I&s){for(s=0;a<=b;++a)for(I i=z;i--;)s+=a%l[i]<1;} ``` [Try it online!](https://tio.run/##lc9Ba4MwGMbxu5/igbGhM0LUyqQxu@czSA@p2hJIYzG6Q8XP7pIquw22S0L@h9/7prnfk0ZLc13XySpzheDKjEzAsq9etbiEApIInIl41@5@EPFmo/nSD6HllMmKn1kcy8gHAcUfTCUJi2zM5auu1alK2bK@KNPoqe1Qqd6OQydvn4GbgptUJowwB/AvXZ845ozgQJAvLHCz04IgLQm0KwQ2ctGO7fHY9NOIqoJ9Hr50ptUs2KG0PsFRKUG2O46hjvHlH062OR8E5Y9TUg9lf4Q2J9/3cX8oNiinjiro08p/s/weQzdOgwFlwbJ@Aw "C++ (clang) – Try It Online") Saved 3 bytes thanks to @AZTECCO!!! Saved ~~6~~ 13 bytes thanks to @bznein!!! ~~Added 6~~ Saved 8 bytes thanks to @AZTECCO (and now it's playing by the rules)!!! [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` ->a,e,l{l.sum{|x|(a..e).count{|r|r%x<1}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ1UnpzpHr7g0t7qmokYjUU8vVVMvOb80r6S6pqimSLXCxrC2tvZ/gUJatKGOoYEOkDSKjf0PAA "Ruby – Try It Online") [Answer] # JavaScript (ES6), 47 bytes Takes input as `(list, start)(end)`. ``` (a,x,s=0)=>g=y=>y<x?s:g(y-1,a.map(c=>y%c||s++)) ``` [Try it online!](https://tio.run/##XczRCoIwGIbh865iJ8GGv7pfG0k0u5DoYCwdhjlpEQ6897UYdOB3@PLwPdRHOf0a5nc@2XsXehmoggWc5Ey2RnrZ@vNycSdDfY6giqeaqY5xr9fVZRljQdvJ2bErRmtoT68IpLoBQUaRM0bSypKg2G3kEUiTZMP/NMoKD1uKNRARbc2jFjzx32kM4Qs "JavaScript (Node.js) – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 16 bytes ``` {+//~z!\:x_!1+y} ``` [Try it online!](https://tio.run/##Hcc7DoAgEAXAqyyVEKLsA4mEvYqJHQ2FrZ/o1ZHYzdRxr62VfFvn3kut@dgU7Pm0Mg1aIwqSeJopGNEQsID8z8QsC6XuwJDIvQgUjWkf "K (oK) – Try It Online") ## Explanation: ``` {+//~z!\:x_!1+y} - function with 3 arguments [x;y;z] <- (start; end; list) !1+y - a list 0 to end (inclusive) x_ - drop the first start numbers z!\: - find the modulo of each number in the range start..end with each of list ~ - negate (0 becomes 1, non-zero becomes 0) +// - reduce by addition and converge (repeat until result stops changing) ``` # [J](http://jsoftware.com/), 22 bytes ``` 1#.1#.0=[|/(}.i.,])/@] ``` [Try it online!](https://tio.run/##LcixCsIwFEDRPV9x0aEWyut7xmAoBPofpZMY1MWha/vtMUjgTOdT8pYEZUKLnaXStOzj5ZC3DGs/zmvp3UnocpKOgWMib849H68vXLnhyVjAYjurWwfTFnfiP6K2MU@o49UIqlp@ "J – Try It Online") ## Explanation: The verbs (functions) in [J](http://jsoftware.com/) can take one (right) or two (left and right) arguments. The left argument is the `list`, the right one - a list of the `start` and `end` numbers. ``` ( )/@ insert the verb in () between the elements of ] the right argument (start and end) , append i. a list 0..end-1 ] to the right argument (end) }. drop start elements |/ insert modulo verb between the above list and [ the left argument (the list) 0= compare each with 0 1#. sum by base 1 conversion 1#. sum by base 1 conversion (we do it twice, because the result of |/ is a table) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 [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") Full program, prompting for **end**, **start**, **list**, from stdin. ``` ≢⍸=⎕|\⎕…⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jzkWPenfYPuqbWhMDJB41LAOSIKn/CmBQwGVowWVoymWkYKJgzAUX4zI04DJUMEISsDAw4DJXsICLGBsYcpkaAAUNjRVMAQ "APL (Dyalog Extended) – Try It Online") `⎕` prompt for **end** `⎕…` prompt for **start** and generate progression vector `⎕|\` prompt for \*\*list\* and make division remainder table `=` Boolean mask indicating where equal to zero `⍸` get the indices of the Trues `≢` tally them [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` f=lambda n,m,l:m/n and sum(n%i<1for i in l)+f(n+1,m,l) ``` [Try it online!](https://tio.run/##VcpBDoIwEIXhvaeYjUkbJtoBicToSQgLFBonoVPSlgWnr7Ax@pJ/8@XNa3p7KTO72YcEcY2HrVMcUxhfS4jsZWLHSZHZprN9TL17Dj0IOpxu7izQywBxcUqOfCfrAzCwwKQLq6Sg/abzHFgSWEU1UoNtiResOn34MpLBlrD8s8ZseMXmBytDWJvdqcK60/kD "Python 2 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 40 bytes ``` eval set !\$[{$1..$2}%{$3}]+;echo $[$*0] ``` [Try it online!](https://tio.run/##S0oszvj/P7UsMUehOLVEQTFGJbpaxVBPT8WoVrVaxbg2Vts6NTkjX0ElWkXLIPb////GBob/TQ0MDP4bGuuYAgA "Bash – Try It Online") [Answer] # APL(NARS), chars 13, bytes 26 ``` {+/∊0=⍺∣../⍵} ``` ⍺ it is the list of divisors, ⍵ it is the range. Test: ``` 1 2{+/∊0=⍺∣../⍵}1 10 15 7 8{+/∊0=⍺∣../⍵}1 800 214 13 5{+/∊0=⍺∣../⍵}301 5000 1301 13 5 3 11{+/∊0=⍺∣../⍵}301 5000 3294 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` r/ḍ@€FS ``` [Try it online!](https://tio.run/##y0rNyan8/79I/@GOXodHTWvcgv///29oqmNo8d9Ix0THGAA "Jelly – Try It Online") A dyadic link taking a list of `[start, end]` as the left argument and the list of possible divisors as the right argument. Returns an integer indicating the total number of possible divisions. [Answer] # Java (JDK), ~~115~~ 67 bytes ``` (s,e,d)->{int t=0;for(;s<=e;s++)for(int j:d)t+=s%j<1?1:0;return t;} ``` *48 bytes saved thanks to Olivier* [Try it online!](https://tio.run/##hY7BasMwDIbvfQpdBjZxg7OsrNRN@wQ59Th28BKnOEucYisdI@TZMzsYxgZjFwn90ie@Vt7ltq3fl9v41ukKqk46B6XUBqYNgEOJPtUGlW1kpaBcYwgJNCRUx9ZBre3lFWoq/MX8DZfQQwELcUyxmm5PUzjHgotmsES4Y6GESxIaprBpDzXFpHAP7TE7ZwcurMLRGkAxL@FzFI3P74Ouofe65IJWm6sXkPbqaNS8fDpUfTqMmN78GjtD@rQh2Y5Btmdg1Ee0nh4ZPDHIZ7rq/00y2HP@g3z20X9Yzj2447/ILPdhROfNvHwB "Java (JDK) – Try It Online") First time golfing in Java, so this is a new experience for me. [Answer] # [Icon](https://github.com/gtownsend/icon), 59 bytes ``` procedure f(a,b,l) n:=0 (a to b)%!l<1&n+:=1&\z return n end ``` [Try it online!](https://tio.run/##Zc5BCsMgEIXhvaewiwals3BipRKak6RdmMSAkIxFDIVePo27kr7tx4M/DJG27ZXi4Mc1eT4JBz3MklHTKiYcz5H38nya71jRpWmxenxY8nlNxIl5Gn@@iwskJOP73ilkLyaBBtBCV8MV9FMeDFBBh1D/g1W73MAeRSsEowqiBm4Kl4Qv "Icon – Try It Online") [Answer] # Python 54 bytes ``` lambda K,M,H:sum(n%l<1for n in range(K,M+1)for l in H) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` rõ ïvV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=cvUg73ZW&input=WzE1LDE4XQpbMiw0LDNd) ``` rõ ïvV :Implicit input of arrays U=[start,end] and V=list > e.g., U=[15,18] V=[2,4,3] r :Reduce U by õ : Inclusive range > [15,16,17,18] ï V :Cartesian product with V > [[15,2],[15,4],[15,3],[16,2],[16,4],[16,3],[17,2],[17,4],[17,3],[18,2],[18,4],[18,3]] v :Reduce each pair by testing the divisibility of the first by the second > [0,0,1,1,1,0,0,0,0,1,0,1] :Implicit output of sum of resulting array > 5 ``` [Answer] # [Kotlin](https://kotlinlang.org), 69 bytes ``` {s:Int,e:Int,l:List<Int>->(s..e).toList().sumBy{v->l.count{v%it==0}}} ``` [Try it online!](https://tio.run/##lVbbbttGEH3XV6yFFCVRhrbsyEnlyEWSJmiABHlIXgrDD2tpJW1DclnuUrYg6NvdMzNLWrKDFjUEmuQezuXM9bsLha3uj4/Vx6puw0RVLqxstVQL1yjXNmpuFrotggrGBzXT3vgBwDgMq8YY5Ws9w9XUutHBzNXCmmLuc/VtZXDf@EBo65VWja6WQAbdBGWrYJamEZg3M1fNGURgwRl6Iyho0oGOC93ExwoXQ2AWJ2JgdiNS1MyVpX4wioCFhflu0cn07B@EqNp5b28KWKtnwTU@HxD8XWPEHUZB6MzNjVq6YqFmK10UBjZOCLgKofaT42M6p@McFs2@mzugAMlhyfHfx6Nfz8fnY4L/4W5VqauNCrY0PlO6IcPNRpXg2NaF8b8pNuBP1/Lh0q5NFbkmd0oTYP1EHE/gTZoRHHTxg9LgjXxNxNf0gk4/6@8GtCzaahasq4TQxoS2qTyToEvXVsQPodk0BSf5qGrLG@LrxoRbA1MkgKQGOglOVvbWE8X0lSlMaargYQM/k0k5G3qnSwAnffDUVI3GFxxv3L26kEhN1dVppl5k6uyaPRiN1fRSjVSCUHTKSNdZyqfndHr65PSU7XwhmJeEOYGKf8OKvMZ4SvmpGnMsOJc77vzKtcVc6dnM1KiKW0cZZAPCxJkeU7ZjjWQiW3XT6M1@@jFxfi@iWYwHlR4RFlzQRQcntEjM1Rvv29JICGMxoTKM9@r1lFjcZ9kzzZ@jl8koU6OTTF3h/@l1esGMjh8jXp0Q5CVuIuR09OIAc3YC1PgEsKvRGe46SXjfswWSGm4Y3hUt02Yl0daWiuzo6EjScqPwzs3nlF7KrEEc8mVDbWeh167Jc6nG93c1iKRy7KJwa8OKy5yTTJKOy1yXN3OtWg9wcKR@bWIBd2XLBL1zFbQFtkkazqJxZSQUH8b24zhOkr3qa1uqtu7TGUooWNyzAmR49IpSS305tTQifK2L1qAffnAcRaNnq644MjhAVXdQL3AF7kuLtUtbIQlYGcd7btd2zkRVxaa3j4@igHwAilTduBkyImF3Jujs0AWP5G6g8EcyJ59weY1Xl6ma8lv5IM@BTfPg6DxJc@Tb243aiivq@SVDOyG5@BBPf7KomimqbKd2HLkPfctxsN7XBUJO/loaNlIerg24Z4@ld0gMxZP4zf/wZDvAawj7JJnw0MC7@GMuGOE8ZpXg@9TSNw45Q991@ZUDAfdUzTQBe/6rutkgv@@3fkKGGL4WD2Y8v0w8aHxM4nb9/LIQxrZrcDWdnux2u3uW@fsTdpAfXRMWSjLiSyzY51K6FVtZN0iKokqGyTNmLFPPwFamhr8M9kL2l7PVN/c1ALxMhjjF74ou18O0Aw5TKupn2zqJglgOfZ7uhulgt2fEQGoZldtz@JR1CWcJVIIpjgH2hlriazFiL2zfmg0c0vOuD6KSm5/94zVDsN1M73YOHnOhWzyoNwvuycw/mGFdyTGUe0Gu/muhOFB/IF56V9wkGPZOwwcaAlgKMDKIHvyi4oUtTIadqzqwNKP9ylbIOTvvTPoCw5tb600m0FjjygbSE0DblkO35rGB/MH4IiI/2cok6dFRjljZkAwR2R7XDWDGX51cI12RvckDQKayHI@eHsdRLeen152KbJjmpa6jQfQHI@O36Av8YqESEo6ZxUakEYpFBxvSR@TMUhdvmmVLBfi@Iy7pBQ7f6rlsrEfRn4NOsZ@uMbG@7AWAOi/mI6UsJUFHZZ8FD7tun1S0f5G4PokEydo8q/NcnjH4gpW2z8D9xi9LkfNRYtYZEJVTOycLKK47mBFmq8Q0jWsmSEvQo7GtppHcvuCJDwm7jKW4tvujH4SbtH5ZJKMx9gH@YXQ/jnmHeSU7A28FNPSfBD8C47@4tKXZwZAgQdg50qx7ovXiBxhaJ1LRQCxjo52bO2JL5hIeLXjqcuUg4leMveZIdPe9fNEQX6dMKw/tjfQx6kr3/wA "Kotlin – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` #0×`%… ``` [Try it online!](https://tio.run/##yygtzv6fm18enJp/bnfxo6bGIkXDQzuLFI1AhLFm@aFt/5UNDk9PUH3UsOz///@GpgqGFgrRRjomOsaxXIYKhgYK0YY6RiCmhQGQba5jEctlbGCoYGoA4hoa65jGAgA "Husk – Try It Online") Nothing very special. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `d`, ~~5~~ 4 bytes ``` ṡ$vḊ ``` *-1 byte thanks to @lyxal* [Try it online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwi4bmhJHbhuIoiLCIiLCIxXG44MDBcbls3LDhdIl0=) Explanation: ``` ṡ # Range from a to b $ # Swap (last input is now on top) vḊ # For each in the range, test for divisibility with the last input # Deep flatten and sum with the d flag ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` I⁻Σ÷ηζΣ÷⊖θζ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYI7g0V8Mzr8QlsywzJVUjQ0ehSlNTRwFV1CU1uSg1NzWvJDVFo1ATrAQIrP//jzY2MNRRMDUwMNBRiDY0BjJjY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` η Second input (End) ζ Third input (List) ÷ Vectorised integer division Σ Sum θ First input (Start) ⊖ Decremented ζ Third input (List) ÷ Vectorised integer division Σ Sum ⁻ Subtract I Cast to string Implicitly print ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` /.nm%LdeQ}.*PQ0 ``` [Try it online!](https://tio.run/##K6gsyfj/X18vL1fVJyU1sFZPKyDQ4P9/Q1MdQwudaCMdEx3jWAA "Pyth – Try It Online") Takes input as `start, end, list` Explanation: ``` } # Inclusive range .* # Splat (list becomes list of arguments) PQ # All but the last element of the input # --> inclusive range from start to end m # map each number of that L eQ # to a map of each member of Q[-1] = list % d # remainder modulo member (2, 4, 3 in example) # --> List of lists of remainders .n # flatten / 0 # count zeroes ``` [Answer] # [Perl 5](https://www.perl.org/) (`-ap`), 33 bytes ``` for$i(<>..<>){$i%$_||$\++for@F}}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8PGTk/Pxk6zWiVTVSW@pkYlRlsbKOHgVltb/f@/obGCKZexgSGXqYGBwb/8gpLM/Lzi/7qJBQA "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 54 bytes ``` (a,b,l)=>l.Where(x=>a%x<1).Count()+(++a>b?0:f(a,b,l)); ``` [Try it online!](https://tio.run/##ZcxLC4JAFAXgvb/iboIRbzKjSZKPFlEQtHcRLVRGEmwCHzAq/XabqRZii3MXh@@evFnnTTmdOpGHpWhR53wU3YPXaVZx3cUI@kIB0URSzLAyo7iykzuvOZFRnK5kyEz78OxES0yLWFYaZ3u6K37YDCb1f72BhAhgZAjOKzCSumz5pRScFERVjKJU0jC@tFd0dBA2CO4Se0r72M/0oPUWwf/f9SlFGOb2g5mL3gK7VHGPKj9oP70B "C# (Visual C# Interactive Compiler) – Try It Online") Recursive approach [Answer] # SimpleTemplate, 86 bytes Yeah, kinda long, but it works! Receives 2 numbers (in any order) and an array/string of 1-digit numbers (e.g.: `"243"`), passed to the `render()` method of the compiler. ``` {@fori fromargv.0 toargv.1}{@eachargv.2}{@ifi is multiple_}{@incR}{@/}{@/}{@/}{@echoR} ``` Displays the result or nothing, if none is --- **Ungolfed** ``` {@set count 0} {@for i from argv.0 to argv.1} {@each argv.2 as number} {@if i is multiple of number} {@inc by 1 count} {@/} {@/} {@/} {@echo count} ``` Should be mostly straightforward. --- You can try it on <http://sandbox.onlinephpfunctions.com/code/b26cd7f75e0c4676038573c4274180891a890895> Change line 986 to test the golfed and ungolfed versions, and line 988 to get the input. [Answer] ## Mathematica, 52 bytes ``` f[s_,e_,l_]:=(q=Quotient;Total[q[e,#]-q[s-1,#]&/@l]) ``` This uses the simplification formula from @tsh A less clever solution at 66 bytes but more directly following the OP: ``` f[s_,e_,l_]:=Total[Length@Intersection[Divisors@#,l]&/@Range[s,e]] ``` ]
[Question] [ This is a byte sized challenge where you have to convert an input temperature in one of the three units (Celsius, Kelvin and Fahrenheit) to the other two. # Input You would be provided with a temperature as a number followed by a unit (separated by space). The temperature can be an integer or a floating point number (23 vs 23.0 or 23.678). You can submit a function or a full program that reads the space separated string from STDIN/ARGV/function argument or the closest equivalent and prints the output to STDOUT or closest equivalent. # Output Your output should be the temperature converted to the other two formats, separated by a newline and followed by the corresponding unit character on each line (optionally separated by a space). The order of the two units does not matter. **Output precision** * The converted number should be accurate to at least 4 decimal places without rounding. * Trailing zeroes or decimal places are optional as long as first 4 decimal places (without rounding) are precise. You can also skip the 4 zeroes and/or the decimal point in case the actual answer has 4 zeroes after the decimal point. * There should not be any leading zeroes * Any number format is acceptable as long as it fulfills the above three requirements. # Unit representation Unit of temperature can only be one of the following: * `C` for Celsius * `K` for Kelvin * `F` for Fahrenheit # Examples Input: ``` 23 C ``` Output: ``` 73.4 F 296.15 K ``` Input: ``` 86.987 F ``` Output: ``` 303.6983 K 30.5483 C ``` Input: ``` 56.99999999 K ``` Output: ``` -216.1500 C -357.0700 F ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest entry in bytes wins! Happy Golfing! # Leaderboard ``` <script>site = 'meta.codegolf',postID = 5314,isAnswer = true,QUESTION_ID = 50740</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] # Python 3, ~~118~~ 116 bytes ``` I=input() t=eval(I[:-1]) u=ord(I[-1])%7 exec("u=-~u%3;t=[t*1.8-459.67,(t-32)/1.8,t+273.15][u];print(t,'FCK'[u]);"*2) ``` Performs the conversions in a rotary order `K -> F -> C -> K` twice. [Answer] # CJam, ~~77~~ ~~65~~ ~~60~~ ~~59~~ ~~55~~ ~~54~~ 52 bytes ``` l~2|"459.67+1.8/'K 273.15-'C 1.8*32+'F"S/m<{~N2$}%6< ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l~2%7C%22459.67%2B1.8%2F'K%20273.15-'C%201.8*32%2B'F%22S%2Fm%3C%7B~N2%24%7D%256%3C&input=23%20C). ### How it works ``` l~ e# Read and evaluate the input: F, K, C -> 15, 20, 12 2| e# Bitwise OR with 2: F, K, C -> 15, 22, 14 = 0, 1, 2 (mod 3) "459.67+1.8/'K 273.15-'C 1.8*32+'F"S/ e# Push ["459.67+1.8/K" "273.15-C" "1.8*32+F"]. e# These commands convert from F to K, K to C and C to F. m< e# Rotate the array of commands by 15, 22 or 14 units to the left. { e# For each command: ~ e# Execute it. N e# Push a linefeed. 2$ e# Copy the temperature for the next iteration. }% e# Collect all results in an array. 6< e# Keep only the first 8 elements. ``` [Answer] # JavaScript (*ES6*), 127 ~~130 132~~ bytes Waiting for some amazing esolanguage answer, I did not find much to golf here. Using template string, the 3 newlines are significant and counted. Run snippet in Firefox to test. ``` F=x=>([t,u]=x.split(' '),z=273.15,y=9/5,u<'F'?`${t*y+32} F ${+t+z} K`:u<'K'?`${t=(t-32)/y} C ${t+z} K`:`${t-=z} C ${t*y+32} F`) // Predefined tests ;['23 C','86.987 F','56.99999999 K'] .forEach(v=>O.innerHTML += v+' ->\n'+F(v)+'\n\n') ``` ``` <input id=I><button onclick='O.innerHTML=F(I.value)'>-></button><br> <pre id=O></pre> ``` [Answer] # Pip, ~~58~~ 57 bytes ``` Ft"CFK"RMbP(a-(o:[32i273.15]Ab%7))*$/95@A[tb]+(oAt%7).s.t ``` Takes input from command-line arguments. Formatted and slightly ungolfed: ``` o:[32 0 273.15] F t ("CFK" RM b) P (a - o@(Ab % 7)) * "95"@At / "95"@Ab + o@(At%7) . s . t ``` **Explanation:** The general conversion formula between unit 1 and unit 2 is `temp2 = (temp1 - offset1) * mult2 / mult1 + offset2`. The offsets could be to absolute zero or to any other convenient temperature; let's use 0 °C. ``` Unit Mult Offset C 5 0 K 5 273.15 F 9 32 ``` We'll build lists of these values and index into them based on which unit we're dealing with. Pip doesn't have associative arrays/hashes/dictionaries, so we need to convert the characters into integer indices. Maybe there will be helpful patterns with the ASCII values. ``` Unit Asc A%2 Mult A%7 A%7%3 Offset C 67 1 5 4 1 0 K 75 1 5 5 2 273.15 F 70 0 9 0 0 32 ``` This looks promising. One more useful fact: indices in Pip wrap around. So we don't actually need the `%3` as long as we're indexing into something of length 3. Defining `o:[32 0 273.15]` and using `(o (Ab)%7)` will do the trick. (`A` gets the ASCII value of a character. The `(l i)` syntax is used for indexing into iterables, as well as for function calls.) For the multipliers, we only need the two numbers 9 and 5. Since numbers are the same as strings in Pip, and thus are indexable, getting the multiplier is as simple as `95@Ab` (using the other method of indexing, the `@` operator). Using Pip's array-programming features, we can save a character over the naive method: ``` 95@At/95@Ab $/95@A[tb] Make a list of t and b, apply 95@A(...) to each item, and fold on / ``` Finally, add the offset for the new unit, concatenate a space and the new unit's symbol onto the end, and print. We do this for each `t` in `"CFK" RM b`, thus converting to each unit except the original. **Sample invocation:** ``` C:\Golf> pip.py tempConv.pip 86.987 F 30.548333333333332 C 303.6983333333333 K ``` (For more on Pip, see [the repository](http://github.com/dloscutoff/pip).) [Answer] # dc, 102 bytes I'm pretty sure this can be golfed more, but here's a start: ``` 4k[9*5/32+dn[ F ]n]sf[459.67+5*9/dn[ K ]n]sk[273.15-1/dn[ C ]n]sc[rlfxlkxq]sC[lkxlcxq]sF?dC=CF=Flcxlfx ``` dc barely makes the grade on this one. Specifically dc string handling isn't really up to the job. But all we need to do is differentiate between "C", "F" and "K". Fortunately dc parses "C" and "F" as hex numerals 12 and 15. And fo "K" it just leaves 0 on the stack. ### Output: ``` $ dc -f tempconv.dc <<< "23 C" 73.4000 F 296.1500 K $ dc -f tempconv.dc <<< "86.987 F" 303.6983 K 30.5483 C $ dc -f tempconv.dc <<< "56.99999999 K" -216.1500 C -357.0700 F $ ``` [Answer] ## C, 160 bytes ``` float v,f[]={1,1.8,1},d[]={0,32,273.15};u,t,j;main(){scanf("%f %c",&v,&u);for(u=u/5-13,v=(v-d[u])/f[u];j<2;)t=(++j+u)%3,printf("%f %c\n",f[t]*v+d[t],"CFK"[t]);} ``` This reads from stdin. No output precision is specified, so it prints whatever `printf()` feels like printing, which is mostly more than 4 digits. Ungolfed version: ``` #include <stdio.h> float v, f[] = {1.0f, 1.8f, 1.0f}, d[] = {0.0f, 32.0f, 273.15f}; char u; int t, j; int main() { scanf("%f %c", &v, &u); u = u / 5 - 13; v = (v - d[u]) / f[u]; for( ; j < 2; ) { t = (++j + u) % 3; printf("%f %c\n", f[t] * v + d[t], "CFK"[t]); } return 0; } ``` Some explanations/remarks: * This is based on lookup tables `f` and `d` that contains the multiplication factors and offsets to convert Celsius to any other unit (including Celsius itself, to avoid special cases). * If `u` is the input unit, `u / 5 - 13` maps `C` to 0, `F` to 1, and `K` to 2. * Input is always converted to Celsius. * Loop iterates over the two units that are not the input, and converts the Celsius value to that unit. * The golfed version uses an `int` variable instead of a `char` variable to receive the `scanf()` input. This is a type mismatch, which will only produce correct results on little endian machines (which is almost all of them these days). [Answer] # Python 2, 168 Bytes I saw the Python 3 solution just as I was about to post this, but whatever, I'm just practicing golfing. ``` s=raw_input().split();v=eval(s[0]);c,t=(v-32)/1.8,v-273.15 print[["%fC\n%fF"%(t,t*1.8+32),"%fK\n%fC"%(c+273.15,c)][s[1]=="F"],"%fK\n%fF"%(v+273.15,v*1.8+32)][s[1]=="C"] ``` Ungolfed: ``` def conv(s): s = s.split() v = float(s[0]) if s[1]=="C": print "%f K\n%f F"%(v+273.15,v*1.8+32) elif s[1]=="F": v = (v-32)/1.8 print "%f K\n%f C"%(v+274.15,v) else: c = v-273.15 print "%f C\n%f F"%(c,c*1.8+32) ``` [Answer] # Perl, ~~85 80~~ 76 ``` #!perl -nl print$_=/C/?$_+273.15." K":/K/?$_*9/5-459.67." F":5/9*($_-32)." C"for$_,$_ ``` Test [me](http://ideone.com/40j1HI). [Answer] # PHP, ~~161~~ 153 ``` function f($i){list($v,$u)=split(" ",$i);$u==C||print($v=$u==K?$v-273.15:($v-32)*5/9)."C\n";$u!=K&&print $v+273.15 ."K\n";$u!=F&&print $v*9/5+32 ."F\n";} ``` <http://3v4l.org/CpvG7> ~~Would be nice to golf out two more characters to get in the top ten...~~ [Answer] # Python 2, 167 ``` s=raw_input();i=eval(s.split()[0]);d={"C":"%f K\n%f F"%(i+273,32+i*1.8),"K":"%f C\n%f F"%(i-273,i*1.8-459.4),"F":"%f C\n%f K"%(i/1.8-17.78,i/1.8+255.2)};print d[s[-1]]` ``` This is my first try on CodeGolf. [Answer] # Pyth, 126 bytes ``` AYZczdJvY=Y*JK1.8 ?%"%f F\n%f K",+32Y+J273.15qZ"C"?%"%f F\n%f C",-Y459.67-J273.15qZ"K"?%"%f C\n%f K",c-J32K*+J459.67c5 9qZ"F" ``` This feels really long to me...oh well. [Answer] # R, ~~150~~ ~~144~~ 141 bytes ``` a=scan(,"");U=c("C","K","F");i=which(U==a[2]);Z=273.15;x=scan(t=a[1]);cat(paste(c(C<-c(x,x-Z,5*(x-32)/9)[i],C+Z,32+C*9/5)[-i],U[-i]),sep="\n") ``` Indented, with new lines: ``` a=scan(,"") U=c("C","K","F") i=which(U==a[2]) Z=273.15 x=as.double(a[1]) cat(paste(c(C<-c(x,x-Z,5*(x-32)/9)[i],C+Z,32+C*9/5)[-i], U[-i]), sep="\n") ``` Usage: ``` > a=scan(,"");U=c("C","K","F");i=which(U==a[2]);Z=273.15;x=scan(t=a[1]);cat(paste(c(C<-c(x,x-Z,5*(x-32)/9)[i],C+Z,32+C*9/5)[-i],U[-i]),sep="\n") 1: 23 C 3: Read 2 items Read 1 item 296.15 K 73.4 F > a=scan(,"");U=c("C","K","F");i=which(U==a[2]);Z=273.15;x=scan(t=a[1]);cat(paste(c(C<-c(x,x-Z,5*(x-32)/9)[i],C+Z,32+C*9/5)[-i],U[-i]),sep="\n") 1: 56.9999999 K 3: Read 2 items Read 1 item -216.1500001 C -357.07000018 F > a=scan(,"");U=c("C","K","F");i=which(U==a[2]);Z=273.15;x=scan(t=a[1]);cat(paste(c(C<-c(x,x-Z,5*(x-32)/9)[i],C+Z,32+C*9/5)[-i],U[-i]),sep="\n") 1: 86.987 F 3: Read 2 items Read 1 item 30.5483333333333 C 303.698333333333 K ``` Thanks to @AlexA. & @MickyT. ! [Answer] # Javascript, ~~206~~ ~~193~~ ~~187~~ ~~175~~ ~~162~~ ~~159~~ 156 ``` e=273.15,a=prompt(f=1.8).split(" "),b=+a[0],X=b-32,c=a[1];alert(c=="F"&&(X/f+"C\n"+(X/f+e+"K"))||(c=="C"?b*f+32+"‌​F\n"+(b+e+"K"):b*f-459.67+"F\n"+(b-e+"C"))) ``` Thanks goes to Optimizer and Ismael Miguel for helping me golf it a little further. [Answer] ## Mathematica, 66 Hopefully correct this time. ``` Print[1##]&@@@Reduce[F==1.8K-459.67&&C==K-273.15&&#==#2,,#2];&@@#& ``` Example ``` %[37 C] (* % represents the function above *) ``` > > 310.15 K > > > 98.6 F > > > [Answer] # Excel, 239 bytes ``` =IF(RIGHT(A1,1)="C",LEFT(A1,LEN(A1)-2)+273.15&"K "&9*LEFT(A1,LEN(A1)-2)/5+32&"F",IF(RIGHT(A1,1)="K",LEFT(A1,LEN(A1)-2)-273.15&"C "&(LEFT(A1,LEN(A1)-2)*9/5-459.67&"F",(LEFT(A1,LEN(A1)-2)+459.67)*5/9&"K "&(LEFT(A1,LEN(A1)-2)-32)*5/9&"C")) ``` 112 bytes of which are used to seperate Value and Unit. Anybody know a better solution? ]
[Question] [ Your task is to translate a [103-smooth number](https://en.wikipedia.org/wiki/Smooth_number) into an English word, using the method described below. ## How? 1. Generate the list of prime factors (with repetition) of the input number. 2. Sort the list: * If **2** is not one of the prime factors, sort the list in ascending order. * If **2** is one of the prime factors, remove it from the list and sort the remaining factors in descending order. 3. Translate each factor into a letter, using the following table: ``` 3 = S 13 = L 29 = X 43 = O 61 = Z 79 = H 101 = K 5 = P 17 = Q 31 = N 47 = R 67 = T 83 = V 103 = Y 7 = M 19 = U 37 = C 53 = A 71 = E 89 = D 11 = F 23 = I 41 = W 59 = G 73 = J 97 = B ``` ***Note**: This table was built empirically to maximize the number of possible words. For the curious, [here is a list of 2,187 words](https://pastebin.com/7dBFbt5b) that can be encoded that way (may include rude language). It's definitely not guaranteed to be optimal, but it's good enough for this challenge.* ## Examples **Example 1: 579085261** (ascending order) 1. The prime factors are **[ 37, 47, 53, 61, 103 ]**. 2. **2** is not a prime factor, so we keep the list sorted in ascending order. 3. 37 = C, 47 = R, etc. The output is "CRAZY". **Example 2: 725582** (descending order) 1. The prime factors are **[ 2, 11, 13, 43, 59 ]**. 2. **2** is a prime factor, so we remove it and sort the list in descending order, which gives: **[ 59, 43, 13, 11 ]**. 3. 59 = G, 43 = O, etc. The output is "GOLF". **Example 3: 10757494** (with a repeated factor) 1. The prime factors are **[ 2, 11, 71, 71, 97 ]**. 2. **2** is a prime factor, so we remove it and sort the list in descending order, which gives: **[ 97, 71, 71, 11 ]**. 3. 97 = B, 71 = E, 11 = F. The output is "BEEF". ## Clarifications and rules * The input number is guaranteed to be 103-smooth and divisible by 2 at most once. * By definition, a smooth-number is a *positive integer*. * Input and output can be handled in any reasonable format. The output can be in lowercase or uppercase. Trailing whitespace is acceptable. Leading whitespace is not. * If your program/function can't support large inputs, please specify it in your answer. * This is code golf, so the shortest answer in bytes wins. ## Test cases ``` 34874 --> ARM 483254 --> BAR 353722 --> EAR 494302 --> EGG 39061 --> FAT 6479 --> FUN 60421 --> ICE 54166 --> JAM 48911474 --> BETA 2510942 --> BOOM 2303854 --> DOOM 844261 --> FIRE 1606801 --> MAZE 1110085 --> PAGE 5212974 --> BALLS 67892046 --> BEANS 885396199 --> CREEK 67401037 --> FUNKY 27762173 --> QUICK 1238440506 --> ARROWS 33045832681 --> CRAGGY 1362714005 --> PIRATE 137302698 --> TROLLS 358310128062 --> BEGGARS 40255151586 --> DETAILS 164633248153 --> FIXATED 621172442227 --> UNRATED 2467812606 --> VACUUMS 86385078330 --> GROWNUPS 26607531423091 --> UNWORTHY ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 27 bytes ``` ÆEµØA“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?xḊṚḢ}¡ ``` *Thanks to @JonathanAllan for golfing off 1 byte!* [Try it online!](https://tio.run/nexus/jelly#FU89SgNREL5KelPM/8yrxMJDeBMbIQgqpLGwScRmra0EYRPEYoMBj/H2IusMD@aHN9/fcnq8nr5Ou6t58zYN3MeHPn5e9MPP3/c09OPzed@P2/Nu3ux/Xy5v@7jth9c@vt9Nw3J6mu8/bpaFJVzWKwkmzc7KTpR7E4bs3MBwvTLxlhWEclFBs4I0RCkwKUKTvCYGjqIJESocGlhADYgAoQkmpFYg82gEkkQRys2wlYILILAnlbsROieUOOlAIU@ZQTStWhQnGzkKgNbs6ddaVIRgBKQAqyBAqpgvrOyIMZMEahInPzqlU6ISlHSEZCUTljHAI@XywwxcGSXTNfwH "Jelly – TIO Nexus") ### Background ``` “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’ ``` is a numeric literal. The characters between the quotes are replaced with their 1-based indices in the [Jelly code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), and the resulting array is interpreted as a base-250 number. This yields the integer **c := 288824892868083015619552399**. ### How it works ``` ÆEµØA“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?xḊṚḢ}¡ Main link. Argument: n ÆE Yield the exponents of n's prime factorization, with. zeroes. This yields an array A. µ Begin a new monadic chain with argument A. ØA Set the return value to “ABC...XYZ”. “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ? Select the c-th permutation of the alphabet, yielding s := “SPMFLQUIXNCWORAGZTEJHVDBKY”. Ḋ Dequeue; yield A without its first element, stripping the exponent of 2. x Repeat the k-th letter of s r times, where r is the exponent of the k-th odd prime number. ¡ Combine the two links to the left into a quicklink: Ḣ} - Apply head to the right argument (A), yielding the exponent of 2. Since n is at most divisible by the first power of 2, this yields 1 for even numbers and 0 for odd ones. Call the link to the left that many times on the previous return value. Ṛ - Reverse the string to the left. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes ``` “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA1;;⁶ ×107ÆE¢×UḢ¡t⁶ ``` [Try it online!](https://tio.run/nexus/jelly#AWkAlv//4oCcwqEz4biF4biyK@G5vsm8wqHhuo/GmeG6isaY4oCZxZM/w5hBMTs74oG2CsOXMTA3w4ZFwqLDl1XhuKLCoXTigbb/w4figqxL//9bNTc5MDg1MjYxLDcyNTU4MiwxMDc1NzQ5NF0 "Jelly – TIO Nexus") ## Explanation **Helper constant `1£`** (produces `“SPMFLQUIXNCWORAGZTEJHVDBKY ”` with a 1 prepended) ``` “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA1;;⁶ “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’ 288824892868083015619552399 (compressed representation) œ?ØA th permutation of the alphabet 1; prepend 1 ;⁶ append a space ``` **Main program** ``` ×107ÆE¢×UḢ¡t⁶ ×107 Multiply {the input} by 107 ÆE Convert to a list of frequencies for each factor ¢× {Vectorized} multiply by the return value of 1£ UḢ¡ Delete the first value, reverse the list that many times t⁶ Delete trailing/leading space ``` I have a feeling that my compression of the list easily beats the other Jelly answer, but that my algorithm for using it could be a lot more efficient. Maybe I'll try to combine them. # [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes, inspired by @Leakynun's answer ``` “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA⁷; ÆfÆCị¢U⁸¡U ``` [Try it online!](https://tio.run/nexus/jelly#AWgAl///4oCcwqEz4biF4biyK@G5vsm8wqHhuo/GmeG6isaY4oCZxZM/w5hB4oG3OwrDhmbDhkPhu4vColXigbjhuILCpMKhVf/Dh@KCrEv//1s1NzkwODUyNjEsNzI1NTgyLDEwNzU3NDk0XQ "Jelly – TIO Nexus") (slightly modified to run a lot faster) Is inconsistent in whether it prints a trailing newline (but PPCG normally allows answers either with or without a trailing newline, so I guess this works too?). Is *very* slow (O(*n*) where *n* is the input, and those numbers aren't exactly small…) ## Explanation **Helper constant `1£`** (produces `“¶SPMFLQUIXNCWORAGZTEJHVDBKY”`, where `¶` is newline) ``` “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA⁷; “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’ 288824892868083015619552399 (compressed representation) œ?ØA th permutation of the alphabet ⁷; prepend newline ``` **Main program** ``` ÆfÆCị¢U⁸¡U Æf Produce list of prime factors (repeating repeated factors) ÆC Map the nth prime to n ị¢ Index into the output of 1£ U Reverse ¡ a number of times ⁸ equal to the input U Reverse again ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ 38 bytes ``` ÒW<iR¨}26LØR•6Ê2"£´õþÕàçŸôëÂÛ*™•36BS:J ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#AUUAuv//w5JXPGlSwqh9MjZMw5hS4oCiNsOKMiLCo8K0w7XDvsOVw6DDp8W4w7TDq8OCw5sq4oSi4oCiMzZCUzpK//83MjU1ODI "05AB1E – TIO Nexus") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~139~~ ~~138~~ ~~134~~ ~~125~~ ~~120~~ 115+7 = ~~146~~ ~~145~~ ~~141~~ ~~132~~ ~~127~~ 122 bytes Uses the `-rprime` flag for +7 bytes. -1 byte from @daniero. -4 bytes by remembering that I can just do a regular divisibility check instead of checking the prime division for the existence of `2`. -9 bytes from @mbomb007's Python solution reminding me of a shorter way to retrieve the matching letter. -5 bytes because trailing whitespace is now allowed. -5 bytes from discovering `Enumerable#find_index` ``` ->n{x=Prime.prime_division n;x.reverse!if n%2<1;x.map{|i,c|" SPMFLQUIXNCWORAGZTEJHVDBKY"[Prime.find_index i]*c}*''} ``` [Try it online! (all test cases)](https://tio.run/nexus/ruby#JY9tT1QxEIW/z6@4vBiQuJt563QaxURFAUVEUVDRbHC5mzSBy@YukCXAb19HSdO0OT1zztOVpf76z20z6Kd9vWibQQcw2fy1GLzs7uabB/@04f@X0Vm9qbN62TXd8/mwb2/aftYu1UnTPeEXFNLF6fTuvj4b3y83hwcf3@19/rb7ff/N8acvr7Z/fn37fudo6/WHH8snj5GT2p2NYrfzpv7eGD9srK09LKbXV7NmMhyfnp@vr46GV5ej@nQh6llBXTgpSJLMDFpUkMFQmSApmYEUNALTXMJbiDSGOBEWZWBB8Zh2VQ4TGZpjnESIniAxcQm7ZS@MauCepBiVEpIioWTgnI0pCxBLxGDCqBTUFFzmkSXGmRQxxTUHnBUPWhdCYkcLZuSUKJZbEKiJsDolgcilzIHGHD0aFMRBCG4BjdmjBtgMcxLS@Eqhvw "Ruby – TIO Nexus") ### Explanation ``` ->n{ # Anonymous procedure with one argument n x=Prime.prime_division n; # Get prime factorization of n, sorted # p0^e0 * p1^e1 ... -> [[p0,e0],[p1,e1],...] x.reverse!if n%2<1; # Reverse if divisible by 2 x.map{|i,c| # For each prime/exponent pair: " SPMFLQUIXNCWORAGZTEJHVDBKY"[ # Get corresponding character by obtaining: Prime.find_index i] # Determine index of the current prime *c # Repeat the letter by the supplied exponent }*''} # Join all letter sequences together ``` [Answer] # Bash + GNU utilities + bsd-games package, 170 Seems pretty non-optimal, but it works: ``` p='printf %03d\n' a=(`factor $1`) x=$[a[1]<3] $p `primes 3 104`|paste - <(fold -1<<<SPMFLQUIXNCWORAGZTEJHVDBKY)|join -o1.2 - <($p ${a[@]:x+1})|(((x))&&tac||cat)|tr -d \\n ``` [Try it online](https://tio.run/nexus/bash#RZHbjhMxDIbv@xTWqrvbERrkU5wEWsT5fD5DW6mj6VS7CDpVZy4qMTx7MSsQyUWi2P/vz86m3UPfdH1ddQ1cbkE0RQVNwkFBgkRm0KyCDJLRCExjBkNlgqBk5rmZSF3EgTArAwtKcnVSZReQoSX0kwgxBQhMnD3dYsqMapBSkGyU3TYqEkoEjtGYogCxuA0GNBBBDc5lyb3EOJIiBr9Gh7OcnDYJIXFCc2bkEMh3MidQE2FNFATclyI7GrPXUacgdkJI5tAYk5cBNsMYhNRbyXQT1u0IfHVND2UJ43/zunrc7S@3/QZOTjsob8HJ/@hxNzv/GzxFWS@256NqNlltqrr3mY9pVYwOs/G8mtNyKsvReAcrT//RdOBto66GXdX1DZQwnWza72soaTqdvnv94uHzNx@efH5579Ort3cefX3/4Onjj/fvPvtSDN9a/7@ypet8JXLD8c9qfnt543CNfhXDZDI5FMXZWV/Vw1BXfTH0eyjXsFhsj38aaeqLdrRut83xNw). [Answer] # Python 2, ~~220~~ 217 bytes ``` n=input() i=1 L=[] exec'i+=1;c=0\nwhile n%i<1:c+=1;n/=i\nif c:L+=[i]*c\n'*n T='SPMFLQUIXNCWORAGZTEJHVDBKY' print''.join(T[[p for p in range(3,104)if all(p%k for k in range(2,p))].index(q)]for q in[L,L[:0:-1]][L[0]<3]) ``` [**Try it online**](https://tio.run/nexus/python2#RczLTgIxFIDhfZ@iG9IWBpwCwTjQhaCiWLzAcNFOF6QWPTI5lAlE3n4EN27/L/lLVIDhsOeCgJJEK2OJP3rHoKZk16k4w58vyD3FCvRk4s4VLxRkCGvqEl1TBmzVZciqSFLFpi/jO/06e1g@DRbPk@vhe3o7up/f9B/fGAkF4J6xxvcWkKfGBLreFjRQQFqs8NPzViTjtjiNV3nOQ2Xz55t/b0ZBCNsA/PBHvhP2zLsTGx1pk8RJXVprtIltr2VFWXbal1e/) - *only runs the smallest test case without running out of memory* ### Ungolfed: This version doesn't use `exec`, so you can actually test all of the test cases without running out of memory. ``` n=input() i=1 L=[] while~-n: i+=1;c=0 while n%i<1:c+=1;n/=i if c:L+=[i]*c if L[0]<3:L=L[:0:-1] T='SPMFLQUIXNCWORAGZTEJHVDBKY' print''.join(T[[p for p in range(3,104)if all(p%k for k in range(2,p))].index(q)]for q in L) ``` [**Try it online**](https://tio.run/nexus/python2#RcxLU8IwFAXgfX5FNkwTeZi0CGPkLlR8oFFR6zOTBVMLXulcQgdGV/712rJxec535lQESGG7EZIhaGbBefb9iUX@2yXDOLZBH2WgGN@VnFo40iZrWtoHrAdznhnbBod@L2N1sk75UWIsWGeU6WrPUogepzfn9v5p8np7@nL3cHzxnp5dXT6PT67fIhZKpE0U9b5WSCJ1LvD5quSBI/FyRotcJB2t@rK@nhWFCK3lzpf/HneClL6H9JH/iLX0Da8btrKq4sFADQ8S3Y8Tdaj/AA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆfÆCUṖ$¹e@?1’ị“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA¤ ``` **[Try it online!](https://tio.run/nexus/jelly#AU0Asv//w4Zmw4ZDVeG5liTCuWVAPzHigJnhu4vigJzCoTPhuIXhuLIr4bm@ybzCoeG6j8aZ4bqKxpjigJnFkz/DmEHCpP///zg4NTM5NjE5OQ)** [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~51~~ 50 bytes 49 bytes of code, +1 for the `-P` flag. ``` %2?Uk :Uk Åw)£`yspmflquixncÙgz’jhvdbk`g#ho fj bX ``` [Try it online!](https://tio.run/nexus/japt#@69qZB@arWAFxIdbyzUPLU6oLC7ITcspLM2syEs@PFM4verQpKyMspSk7IR05Yx8hbQshaSI//@NzMwMzE2NDU2MjA0sDRV0AwA "Japt – TIO Nexus") This could be way shorter if only Japt had a couple more features... ### Explanation ``yspmflquixncÙgz’jhvdbk`` is just the same string everyone else is using compressed as much as Japt can compress it (3 bytes shorter than the original!). Japt's only built-in compression tool at the moment replaces common pairs of lowercase letter with a single-byte char. So let's examine the actual code: ``` %2?Uk :Uk Å w) %2?Uk :Uk s1 w) %2? // If the input mod 2 is non-zero, Uk // take the prime factors of the input (U). :Uk // Otherwise, take the prime factors of the input, s1 w // slice off the first one (2), and reverse. ``` Then `£` is used to replace each item `X` in the result like this: ``` "string"g#h o fj bX "string"g104o fj bX 104o // Create the range [0...104). fj // Filter to only items Z where Z.j() is truthy (Z is prime). // This results in the list of prime numbers from 2 to 103. bX // Take the index of X in this list. "string"g // Get the char in the compressed string at that index. // For `y`, the index is 26, but since the string is only 26 chars // long, Japt wraps around and grabs the first char in the string. ``` The result is an array of characters at this point, so the `-P` flag joins it into a single string, and the result is implicitly sent to output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes ``` Æfḟ2ÆCṚ⁸Ḃ¤¡Ṛị“YSPMFLQUIXNCWORAGZTEJHVDBK ``` [Try it online!](https://tio.run/nexus/jelly#@3@4Le3hjvlGh9ucH@6c9ahxx8MdTYeWHFoI5Dzc3f2oYU5kcICvm09gqGeEn3O4f5Cje1SIq5dHmIuT9////82NTE0tjAA "Jelly – TIO Nexus") [Verify all testcases at once!](https://tio.run/nexus/jelly#DY85TgNhDIV7zuLCu/2XEPZ9CUtAtJwjpAgFN0AghETJAQbRJSeZuchgubAtvef3eVwvn/ruk9fLSf/7Njx3fbdYfa@@aun/Xof5@@zq/GT3@OL64O50cnt2ubl3P9053L/Z3joa5h8b65dh8TMbx/FBNENBU9gUxCSYQZsKMkhDJ3CNBo7KVKpGpCVnI2zKwIKS5UtVLik5emJ1IsQ0MCZuJffIxqgOmSbNqdXBUCSUAGIpNxo6iKBagXjWCXEOUkSrMYrGWxZeCiFxohckshlVpVewughrkgk4EwUXEXMAa4UTFxikFytGVgywO4YJaX3Q6PEf "Jelly – TIO Nexus") (slightly modified) [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~54~~ 47 bytes 7 bytes thanks to isaacg ``` s__W%Q2@L."AZ❤O❤❤❤❤❤❤Q❤9❤❤×❤❤"xL_MP#r_3_103-PQ2 ``` (`❤` represents an unprintable character) Pyth doesn't have many prime built-ins... Hexdump: ``` 0000000: 73 5f 5f 57 25 51 32 40 4c 2e 22 41 5a 03 4f f3 s__W%Q2@L."AZ.O. 0000010: 14 af 15 ed f5 51 90 39 d5 18 d7 20 a8 22 78 4c .....Q.9... ."xL 0000020: 5f 4d 50 23 72 5f 33 5f 31 30 33 2d 50 51 32 _MP#r_3_103-PQ2 ``` [Try it online!](https://pyth.herokuapp.com/?code=s__W%25Q2%40L.%22AZ%03O%C3%B3%14%C2%AF%15%C3%AD%C3%B5Q%C2%909%C3%95%18%C3%97%C2%A0%C2%A8%22xL_MP%23r_3_103-PQ2&test_suite=1&test_suite_input=34874%0A483254%0A353722%0A494302%0A39061%0A6479%0A60421%0A48911474%0A2510942%0A2303854%0A844261%0A1606801%0A1110085%0A5212974%0A67892046%0A885396199%0A67401037%0A1238440506%0A33045832681%0A1362714005%0A137302698%0A358310128062%0A40255151586%0A164633248153%0A621172442227%0A2467812606%0A86385078330%0A26607531423091&debug=0) [Answer] # [J](http://jsoftware.com/), 59 bytes ``` 'SPMFLQUIXNCWORAGZTEJHVDBKY'{~(p:>:i.26)i.[:|.@}.^:(2={.)q: ``` [Try it online!](https://tio.run/nexus/j#JZDJakJRDIb3PkXoRi/IbaaTk3OKpfM8zwMUiii6aovdqX11G5AskkD@P1@y0fa640Ht9pcVoQI2q@79zeXRxe3j6cvV/vP13e7x28Ph2cnTwd75a3f@1/uu23XasjXT9r0u2p1l@1F7PJi3zU9dNZ3f0ex3BoMKiwr9ClubIOpZQV04KUiSzAxaVJBBChqBaS5gqEyQlMxithBpiDgRFmVgQfFQuyqHgAzNMTIRoidITFxi3LIXRjVwT1KMSthmRULJwDkbUxYglrDBhAYiqCm4zMNLjDMpYooyB5wVD1oXQmJHC2bklCjCLQjURFidkkD4UuZAY449GhTEQQhuAY3ZYw2wGeYkpHFKoc5oOPmC9av6LYxh9DmcrPvVPw "J – TIO Nexus") Quite simple... ``` 'SPMFLQUIXNCWORAGZTEJHVDBKY'{~(p:>:i.26)i.[:|.@}.^:(2={.)q: (p:>:i.26) first 26 primes after 2 i. for which the indices is q: prime factors |.@}. remove first and reverse ^: if (2={.) the first entry is 2 {~ reverse index '..........................' hardcoded string ``` [Answer] # PHP, 173 Bytes ``` for($i=2;1<$n=&$argn;$n%$i?++$i:$r[]=$i.!$n/=$i)for($t=$i;$i>2&!$w[$i]&&$i%--$t;$t>2?:$w[$i]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++]);$r[0]>2?:rsort($r);foreach($r as$s)echo$w[$s]; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/5bd12c1943f66d4a93056d55eabb1c0e497da3d3) Expanded ``` for($i=2;1<$n=&$argn; # loop till input is 1 $n%$i?++$i:$r[]=$i.!$n/=$i) #after loop add value to result if input is divisible and divide input for($t=$i;$i>2&!$w[$i]&&$i%--$t; # loop if number is gt 2 and not in letter array till number is divisible $t>2?:$w[$i]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++]) # if is prime add to letter array ; # make nothing in the loop $r[0]>2?:rsort($r); # reverse result array if 2 is in result array foreach($r as$s) # loop result array echo$w[$s]; # Output ``` # PHP, 178 Bytes ``` for($z=2;$p<26;$t>1?:$w[$z]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++])for($t=++$z;$z%--$t;);for($i=2;1<$n=&$argn;)$n%$i?++$i:$r[]=$i.!$n/=$i;$r[0]>2?:rsort($r);foreach($r as$s)echo$w[$s]; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/f50b5f6f427a7228178d0f3e00d3d77ae50585d0) Expanded ``` for($z=2;$p<26; $t>1?:$w[$z]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++]) # after loop if is prime add to letter array for($t=++$z;$z%--$t;); for($i=2;1<$n=&$argn;) # loop till input is 1 $n%$i?++$i:$r[]=$i.!$n/=$i; #add value to result if input is divisible and divide input $r[0]>2?:rsort($r); # reverse result array if 2 is in result array foreach($r as$s) # loop result array echo$w[$s]; # Output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 27 bytes ``` ∆Ǐḣ« ‹ṀnΠ⌈≈Ǐ¶¨≤½꘍Qr←«f*∑$ßṘ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwi4oiGx4/huKPCq1xu4oC54bmAbs6g4oyI4omIx4/CtsKo4omkwr3qmI1RcuKGkMKrZiriiJEkw5/huZgiLCIiLCIyNjYwNzUzMTQyMzA5MVxuMzU4MzEwMTI4MDYyXG4xNjA2ODAxIl0=) Port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/117830/100664). ``` ∆Ǐ # Exponents of prime factors ḣ # Remove the first item and leave it on the stack «...«f # Compressed string "spmflquixncworagztejhvdbky", as a char list *∑ # Repeat each character by its corresponding exponent, and concatenate $ß # If the popped item is nonzero (i.e. factor of 2) Ṙ # Then reverse the string ``` [Answer] # Python, 1420 bytes ``` lambda x:(lambda a,b,e,k,l,m,q,p:len.__name__[:a].join(dict(zip((lambda n:(lambda n,f,g:f(n,e,[],f,g))(n,lambda n,i,r,f,g:g(n,i+b,r,f,g)if i<n else r,lambda n,i,r,f,g:f(n,i,[r,r+[i]][all(i%x!=a for x in[e]+r)],f,g)))(l*e*(k*l+b)),(lambda n,o,t:(lambda n,f,g:f(n, len.__name__[:a],f,g))(n,lambda n,s,f,g:g(n,s,f,g)if n>o else s,lambda n,s,f,g:f(n//t,s+chr(n%t),f,g)))((((((k<<e)-b)<<m)+m)<<((k<<q)+(k<<b)))+(((((k<<e)-b)<<e)+b)<<((k<<q)-(b<<b)))+((((((b<<k)+b))<<l)+b)<<((((k<<e)-b)<<l)+(b<<b)))+(((((k<<e)-b)<<l)-k)<<((m<<m)+p))-(((p<<m)-b)<<((m<<m)-(b<<b)))+(((m<<k)+b)<<((((m<<e)-b)<<k)-(b<<b)))+(((((k<<e)-b)<<l)-m)<<((((b<<l)+b)<<k)+k))-(((((b<<l)-b)<<l)-p)<<((b<<p)+(b<<b)))-(((p<<k)-b)<<((((b<<l)-b)<<k)+k))-(((k<<q)-b)<<((p<<l)))+(((m<<m)+m)<<((((k<<e)+b)<<k)-b))-(((k<<m)+b)<<((k<<m)-b))-(((m<<m)+k)<<((((k<<e)-b)<<k)-(b<<b)))+(((((k<<e)+b)<<e)+b)<<((m<<l)-(b<<e)))-(((((k<<e)+b)<<e)+b)<<((((b<<l)+b)<<e)-b))+((((((b<<k)+b))<<k)+b)<<((p<<k)))+(((((k<<e)-b)<<k)-k)<<((k<<l)))+(((m<<l)+b)<<((m<<k)))+(((m<<e)-b)<<((b<<m)+(b<<b)))+((((((b<<k)+b))<<e)-b)<<((k<<k)+b))+(((m<<k)-b)<<((b<<l)+b))-((((k<<e)-b))<<((k<<e)))+(((m<<e)+b)<<e)-b,b,b<<l*e)))[i]for i in(lambda x: [x.remove(e), x[::-b]][b] if e in x else x)((lambda x:(lambda x,g,h:g(x,b,[],g,h))(x,lambda x,n,r,g,h:h(x,n+b,r,g,h)if x>b else r,lambda x,n,r,g,h:h(x//n,n,r+[n],g,h)if x%n==a else g(x,n,r,g,h)))(x))))(*[x for x in range(True<<len(len.__name__))]) ``` This could definitely by shorted some, but it's my attempt at solving it with no numbers or string literals. I realize this is a code-golf problem and this isn't *exactly* short but wanted to share anyway, not sure if this breaks any rules or not. Was a lot of fun to make, I used the algorithm on [this blog post](https://benkurtovic.com/2014/06/01/obfuscating-hello-world.html) to reduce the ASCII numerical representation of "SPMFLQUIXNCWORAGZTEJHVDBKY" in to the bit-shift expression I use. I also generally took a lot of inspiration from this blog, I wanted to try it out myself and this seemed like a good challenge to do it with. [Here](https://gist.github.com/anonymous/b02774144c02ff410e7c4cf21b6ca5a6) is a slightly more readable version, with some more sensible variable names too ]
[Question] [ ### Backstory Disclaimer: May contain made up information about kangaroos. Kangaroos traverse several stages of development. As they grow older and stronger, they can jump higher and longer, and they can jump more times before they get hungry. In stage **1**, the kangaroo is very little and cannot jump at all. Despite this, is constantly requires nourishment. We can represent a stage **1** kangaroo's activity pattern like this. ``` o ``` In stage **2**, the kangaroo can make small jumps, but not more than **2** before it gets hungry. We can represent a stage **2** kangaroo's activity pattern like this. ``` o o o o o ``` After stage **2** the kangaroo improves quickly. In each subsequent stage, the kangaroo can jump a bit higher (1 unit in the graphical representation) and twice as many times. For example, a stage **3** kangaroo's activity pattern looks like this. ``` o o o o o o o o o o o o o o o o o ``` For stage **n**, the activity pattern consists of **2n-1** V-shaped jumps of height **n**. For example, for stage **4**, there are **8** jumps of height **4**. ``` 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 ``` ### Task Write a full program or a function that takes a positive integer **n** as input and prints or returns the ASCII art representation of a stage **n** kangaroo's activity pattern. Surrounding whitespace and ANSI escape codes are allowed, as long as the pattern looks exactly as depicted above. If you choose a function that returns the output, it must return a single string or character array that displays the proper output when printed. Returning an array of strings is not allowed. You can use any printable, non-whitespace character instead of `o`, as long as it is consistent within the activity pattern and across all patterns in your answer. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); may the shortest answer in bytes win! [Answer] # MATLAB, ~~92 90 86~~ 84 bytes ``` n=input('');p=eye(n)+32;A=repmat([fliplr(p),p,''],1,2^n/2);A(:,n+1:n:end)=[];disp(A) ``` [Try it online!](https://tio.run/nexus/octave#BcFBCoAgEADA57iLC6F1Ujz4DikINBBsWcwOvd5mJofK8g5QCr2E8hVg1Kv1MfQi9zkgXa1K6yBIQkrtZMgevFj0ERyxNo5d4Ywh7T7XRyDinNsP "Octave – TIO Nexus") `eye` creates an identity matrix. If we flip it and concatenate the original i.e. `[fliplr(p),p]` we get (for `n=3`): ``` 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 ``` With `repmat(...,1,2^n/2)` we repeat this `2^(n-1)` times and get ``` 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 ... 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 ``` From this we just delete the unnecessary columns, with `A(:,n+1:n:end)=[];` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` NλP^×λoF⁻λ¹‖O→ ``` [Try it online!](https://tio.run/nexus/charcoal#ASUA2v//77yuzrvvvLBew5fOu2/vvKbigbvOu8K54oCW77yv4oaS//80 "Charcoal – TIO Nexus") ### Explanation `Nλ` inputs an integer into `λ`. `P^` is a multidirectional print (SE and SW) of `×λo` (string multiplication of `λ` with `o`). Then `F⁻λ¹` runs a for loop `λ - 1` times, in which `‖O→` reflects the whole thing to the right with overlap. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes ``` Îj¹FÐvû},À ``` Explanation: ``` Î # Push zero and input j # Prepend input - 1 spaces ¹F # Input times do.. Ð # Triplicate the string v } # Length times do.. û # Palindromize , # Pop and print with a newline À # Rotate the string on to the right ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3@4L@vQTrfDE8oO767VOdzw/78JAA "05AB1E – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 87 bytes ``` n=input() for i in range(n):print''.join(' o'[abs(j%(2*n)-n)==i]for j in range(1,n<<n)) ``` [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqiocmVll@kkKmQmadQlJiXnqqRp2lVUJSZV6KurpeVn5mnoa6Qrx6dmFSskaWqYaSVp6mbp2lrmxkL0pWF0GWok2djk6ep@f@/CQA "Python 2 – TIO Nexus") Uses a formula for the coordinates `(i,j)` that contain a circle, then joins and prints the grid. There's a lot of golf smell here -- `''.join`, two nested ranges, `for` over `exec`, so there's likely to be improvements. [Answer] # Python 2, ~~83~~ 81 bytes ``` n=input() i=0 exec"s=' '*n+'o'+' '*i;i+=1;print(s[i:-1]+s[:i:-1])*2**~-n+s[i];"*n ``` [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqiocmVaWvAlVqRmqxUbKuuoK6Vp62er64NYmVaZ2rbGloXFGXmlWgUR2da6RrGahdHW4EZmlpGWlp1unlAgcxYayWtvP//TQA) [Answer] # Befunge, ~~98~~ 91 bytes This uses a `,` in place of the `o`, since that enables us to save a couple of bytes. ``` &::1>\1-:v +\:v^*2\<_$\1-2*::!+00p*1 :-1_@v0\-g01:%g00:-1<:\p01 ,:^ >0g10g--*!3g,:#^_$\55+ ``` [Try it online!](http://befunge.tryitonline.net/#code=Jjo6MT5cMS06dgorXDp2XioyXDxfJFwxLTIqOjohKzAwcCoxCjotMV9AdjBcLWcwMTolZzAwOi0xPDpccDAxCiAsOl4gPjBnMTBnLS0qITNnLDojXl8kXDU1Kw&input=NA) **Explanation** Given the stage number, *n*, we start by calculating the following three parameters of the pattern: ``` jump_count = 2 ^ (n - 1) jump_len = (n - 1) * 2 width = (jump_len * jump_count) + 1 ``` The *jump\_len* is normalised to avoid it being zero for a stage 1 kangaroo with: ``` jump_len += !jumplen ``` We can then output the jump pattern by iterating over the *x* and *y* coordinates of the output area, and calculating the appropriate charater to output for each location. The *y* coordinate counts down from *n* - 1 to 0, and the *x* coordinate counts down from *width* - 1 to 0. We determine whether a dot needs to be shown with the following formula: ``` jump_off = x % jump_len show_dot = (jump_off == y) or (jump_off == (jump_len-y)) ``` The *show\_dot* boolean is used as a table index to determine actual character to output at each location. To save on space, we use the start of the last line of source as that table, which is why our `o` character ends up being a `,`. [Answer] # [J](http://jsoftware.com/), ~~28~~ 25 bytes ``` ' o'{~]_&(](|.,}.)"1)=@i. ``` Saved 3 bytes thanks to @[Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien). This is based on the palindrome trick from @muddyfish's [solution](https://codegolf.stackexchange.com/a/107617/6710). [Try it online!](https://tio.run/nexus/j#@5@mYGuloK6Qr15dFxuvphGrUaOnU6unqWSoaeuQqcfFlZqcka@QpmDy/z8A "J – TIO Nexus") ## Explanation ``` ' o'{~]_&(](|.,}.)"1)=@i. Input: integer n i. Form the range [0, 1, ..., n-1] =@ Equality table with itself. Creates an identity matrix of order n ] Get n _&( ) Repeat n times on x = identity matrix ( )"1 For each row |. Make a reversed copy }. Get a copy with the head removed , Append them ] Use that as the new value of x ' o'{~ Index into the char array ``` [Answer] ## Pyke, 11 bytes ``` XFd*\o+Q^Vs ``` [Try it here!](http://pyke.catbus.co.uk/?code=XFd%2a%5Co%2BQ%5EVs&input=4&warnings=0) ``` F - for i in range(input) d*\o+ - " "*i+"o" Q^ - ^.lpad(input) Vs - repeat len(^): palindromise() X - print(reversed(^)) ``` [Answer] # [Haskell](https://www.haskell.org/), 100 bytes ``` k 1="o" k n|n<-n-1,m<-n*2=unlines[[last$' ':['o'|mod c m`elem`[m-r,r]]|c<-[0..m*2^n]]|r<-[n,n-1..0]] ``` [Try it online!](https://tio.run/nexus/haskell#Dcw9CsQgEEDhfk8xhIAQVPLTLfEUWw4uCYlF0BkXYzrv7lo9vuZVD5PpYvfywIVXxWqS1DLM5uFwsbsRw37nXoB4o4iiUDzhANpccLQhqSSTteVYFY5a0zB/uTE1smwzrUdrK@0Xg4Hfkz85QQ8elvoH "Haskell – TIO Nexus") Usage: `k 3`. Explanation: Given a row `r`, a column `c` and `m = 2(n-1)` an `o` is set if `c mod m` equals `r` or `m-r`. The outermost list comprehension sets the range of `r` from `n-1` to `0`, the next one sets the range of `c` from `0` to `m*2^(n-1)` and the innermost acts as conditional returning `'o'` if the above formula is fulfilled and `' '` otherwise. This yields a list of strings which is turned into a single newline separated string by `unlines`. For `n=1` the function produces a division-by-zero error, so this case is handled explicitly in the first line. [Answer] ## C#, 180, 173 171 bytes Wont win this, posting for other C# contestants as something they can beat. ``` n=>{var s=new string[n];for(int a=-1,j=0,i,m=n-1,x=m;j<=m*(Math.Pow(2,n)*n+1);){i=j++%n;s[i]+=x==i?"o":"_";if(i==m&n>1){x+=a;a*=x%m==0?-1:1;}}return string.Join("\n",s);}; ``` complete program: ``` using System; public class P { public static void Main() { Func<int, string> _ = n => { var s = new string[n]; for (int a = -1, j = 0, i, m = n - 1, x = m; j <= m * (Math.Pow(2, n) * n + 1);) { i = j++ % n; s[i] += x‌​ == i ? "o" : "_"; if (i == m & n > 1) { x += a; a *= x % m == 0 ? -1 : 1; } } return string.Join("\n", s); }; Console.Write(_(4)); Console.ReadKey(); } } ``` --- **edit:** -7 bytes thanks to @KevinCruijssen **edit:** -2 bytes, simplified if [Answer] # [Pyth](https://github.com/isaacg1/pyth), 30 bytes ``` jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^ ``` A program that takes input of an integer and prints the result. Uses a quote mark `"` instead of `o`. [Try it online!](https://tio.run/nexus/pyth#@5/lrGcTphWrrZVSEuiXoVUSGGcUqKXtFRpYEhDvFff/vwkA "Pyth – TIO Nexus") **How it works** ``` jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^ Program. Input: Q jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^QQ Implicit input fill ] Yield a one-element list, A *dtQ cotaining Q-1 spaces + N appended with a quote mark. h*tQ^2Q Yield 1+(Q-1)*2^Q * Repeat A that many times, giving B UQ Yield [0, 1, 2, ..., Q-1] J (Store that in J) + tP_J Append the reverse of J, discarding the first and last elements * ^QQ Repeat the above Q^Q times, giving C V Vectorised map. For each pair [a,b] from B and C: .< Cyclically rotate a left by b characters C Transpose j Join on newlines Implicitly print ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~115~~ ~~113~~ ~~108~~ 98 bytes ``` lambda n:'\n'.join(map(''.join,zip(*[' '*abs(i)+'o'+~-n*' 'for i in range(-n+1,n-1)*2**~-n])))+'o' ``` [Try it online!](https://tio.run/nexus/python2#JcpNCsIwEEDhq8xuftIUKrgRPIl1MUUjI3YS0rpx4dXTorvH40vnsb10nm4KfsLRsX9mc5q1EP67@1ghuSCg6LSQccCM4Rtd9pVyBQNzqOqPO0UPQ@dxYDmI7OTK/OOtVPMVEpmX90rM7bgB "Python 2 – TIO Nexus") Using `range(-n+1,n-1)` to create the absolute number of spaces between the bottom and the `o` to generate ``` o o o o ``` and then appending more copies, rotating 90º everything and appending the last `o` at bottom right [Answer] # [J](http://jsoftware.com/), ~~58~~ 47 bytes ``` ' o'{&:>~[:(,.}."1)&.>/(2^<:)#<@(|.,.}."1)@=@i. ``` Saved 11 bytes using the identity matrix idea from @flawr's [solution](https://codegolf.stackexchange.com/a/107611/6710). [Try it online!](https://tio.run/nexus/j#@5@mYGuloK6Qr16tZmVXF22loaNXq6dkqKmmZ6evYRRnY6WpbOOgUaMHFXawdcjU4@JKTc7IV0hTMPn/HwA "J – TIO Nexus") A straightforward application of the definition. ## Explanation For `n = 3`, creates the identity matrix of order *n*. ``` 1 0 0 0 1 0 0 0 1 ``` Then mirror it to make ``` 0 0 1 0 0 0 1 0 1 0 1 0 0 0 1 ``` Repeat that 2*n*-1 times and drop the head of each row on the duplicates ``` 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 ``` Use those values as indices into the char array `[' ', 'o']` to output a 2d char array ``` o o o o o o o o o o o o o o o o o ``` [Answer] ## JavaScript (ES6), 83 bytes ``` f= n=>` `.repeat(n).replace(/ /g,"$'o$`-$`o$'-".repeat(1<<n-1)+` `).replace(/-.?/g,``) ``` ``` <input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒḄ¡ḶUz1Ṛa⁶Y ``` **[TryItOnline!](https://tio.run/nexus/jelly#ARoA5f//xZLhuITCoeG4tlV6MeG5mmHigbZZ////Mw)** ### How? The printable character used is `0`. Builds upon the method of [Dennis's answer](https://codegolf.stackexchange.com/a/98545/53748) to his previous question on the subject of kangaroos. ``` ŒḄ¡ḶUz1Ṛa⁶Y - Main link: n e.g. 3 ŒḄ - bounce, initial implicit range(n) e.g. [1,2,3,2,1] ¡ - repeat n times e.g. [1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1] i.e. [1,2,3,2,1] bounced to [1,2,3,2,1,2,3,2,1] bounced to [1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1] Ḷ - lowered range (vectorises) e.g. [[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0]] U - upend (vectorises) e.g. [[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0]] z1 - transpose with filler 1 Ṛ - ...and reverse e.g. [[1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1], [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1], [0,1,2,1,0,1,2,1,0,1,2,1,0,1,2,1,0]] a⁶ - logical and with space character (all non-zeros become spaces) Y - join with line feeds e.g. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` [Answer] # MATL, 27 bytes ``` XyPt3LZ)2&Pht4LZ)lGqX"h48*c ``` Try it out at [**MATL Online**](https://matl.io/?code=XyPt3LZ%292%26Pht4LZ%29lGqX%22h48%2ac&inputs=3&version=19.7.2) [Answer] # [Python 3](https://docs.python.org/3/), 177 bytes ``` n=5;f=n-1;w='' for i in range(n): s='';a=0;d='\n' if i==f:w='';a=-1;d='' for _ in range(2**f): s+=' '*(f-i)+'o'+' '*(2*i-1)+w+' '*(n-i-2+a) print(s,end=d);w='o' print('o') ``` [Try it online!](https://tio.run/nexus/python3#Rc5NCgMhDAXgvafILv5U6AjtYiQ3KRTBsWSTKVqY41vtLLrLe48P0oVusZD4JR6EqMpegYEFapLXpsWsCtoYYqJrzIQPQQVcgInKepzDsHlamPj5x8HaMj00RwhodfFsHO7ofilY9otxx5nEsw8uGQXvyvLR7bJJpmzmWzuqsxyX6f3@BQ "Python 3 – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), ~~104~~ ~~93~~ 88 bytes ``` ->\n{my @a;@a[$_;$++]="o" for [...] |(n-1,0,n-1)xx 2**n/2;say .join for @a».&{$_//" "}} ``` Inserts `o`'s into a 2D array, and then prints it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` L<¹Fû}ð×'o«.BøR» ``` [Try it online!](https://tio.run/nexus/05ab1e#ARsA5P//TDzCuUbDu33DsMOXJ2/Cqy5Cw7hSwrv//zE "05AB1E – TIO Nexus") Why and how? ``` # Example input of n=2. L< # [0,1] (Push [1..a], decrement). ¹Fû} # [0,1,0,1,0] (Palindromize n times). ð×'o« # ['o',' o','o',' o','o'] (Push n spaces, append o's). .Bø # ['o ',' o','o ',' o','o '] (Pad with spaces into 2D array, transpose). R» # Reverse, join and print. ``` [Answer] # Java 8, 254 bytes Golfed: ``` n->{if(n==1)return"o";int k,x,y,m=n+n-2;char[][]p=new char[n][m];for(y=0;y<n;++y)for(x=0;x<m;)p[y][x++]=' ';for(k=0;k<m;++k)p[k<n?n-k-1:k-n+1][k]='o';String s="";for(y=0;y<n;++y){for(k=0;k<1<<(n-1);++k)for(x=0;x<m;)s+=p[y][x++];if(y==n-1)s+='o';s+='\n';} ``` Ungolfed: ``` import java.util.function.*; public class LeapingKangaroos { public static void main(final String[] args) { for (int i = 1; i <= 4; ++i) { System.out.println(toString(n -> { if (n == 1) { return "o"; } int k, x, y, m = (n + n) - 2; char[][] p = new char[n][m]; for (y = 0; y < n; ++y) { for (x = 0; x < m;) { p[y][x++] = ' '; } } for (k = 0; k < m; ++k) { p[k < n ? n - k - 1 : (k - n) + 1][k] = 'o'; } String s = ""; for (y = 0; y < n; ++y) { for (k = 0; k < (1 << (n - 1)); ++k) { for (x = 0; x < m;) { s += p[y][x++]; } } if (y == (n - 1)) { s += 'o'; } s += '\n'; } return s; } , i)); System.out.println(); System.out.println(); } } private static String toString(final IntFunction<String> func, final int level) { return func.apply(level); } } ``` Program output: ``` 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 o o o o o o o o o o o o ``` [Answer] ## PHP, 157 bytes ``` for($i=$n=$argv[1],$r=str_repeat;$i>0;)echo$r($r(' ',$i-1).'o'.$r(' ',2*$n-2*$i-1).($i==$n|$i==1?'':'o').$r(' ',$i-2),2**($n-1)).($i--==1&$n!=1?'o':'')."\n"; ``` Ungolfed: ``` for($i=$n=$argv[1];$i>0;) { // Spacing from beginning of pattern to first 'o' $o = str_repeat(' ',$i-1); // First 'o' for the ascent $o .= 'o'; // Spacing between ascent and descent $o .= str_repeat(' ',2*$n-2*$i-1); // Second 'o' for the descent, unless we are at the apex or the bottom $o .= ($i==$n|$i==1?'':'o'); // Spacing to the end of the pattern $o .= str_repeat(' ',$i-2); // Repeat the pattern 2^(n-1) times echo str_repeat($o, 2**($n-1)); // Output final 'o' if we are at the bottom in the last pattern echo $i--==1&$n!=1?'o':''; // End of line echo "\n"; } ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` o×/L[│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=byVENyV1RkYwRiV1RkYyQyV1RkYzQiV1MjUwMg__,i=NA__,v=8) ## Explanation ``` o×/L[| o× repeat o input times / make an antidiagonal using it L get width without popping [| palindromize width times ``` ]
[Question] [ # Stock Time Machine You've gained access to a dataset, `tomorrowStocks`, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time. ``` // Assume the stock market opens at 9:30AM EDT // tomorrowStocks[] contains the prices of your target stock. // If the stock is $22 @ 10:30AM EDT tomorrowStocks[60] == 22 ``` # Output Your task is to determine the best possible outcome of `1 purchase` and `1 sale` of `1 stock` from the given dataset. **Gotchas** * You must buy and sell exactly 1 stock. * You may not buy *and* sell in the same time slot. * You must buy *before* you sell. # Test Data ``` [1,2,3,4,5] # 4 [1,99,2,105] # 104 [99,1,99,100] # 99 [99,1,1,2,1,3] # 2 [5,4,3,3,1] # 0 [5,4,3,1] # -1 [5,2,1] # -1 [5,4,1] # -1 [55,45,20,1] # -10 [5,1] # -4 [10,7,5,1] # -2 [7] # Invalid input -- assume size >= 2 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); submit the shortest answer in your favorite language! [Answer] # Python 2, 46 bytes ``` f=lambda x:-min(x.pop(0)-max(x),x[1:]and-f(x)) ``` Test it on [Ideone](http://ideone.com/rjdtsx). ### How it works This is a recursive approach that takes advantage of Python 2's beautifully perverse mixed-type comparisons. The best possible outcome is either the difference of the maximum of the list with its first element removed and that first element, or another difference that does not involve the first element. After extracting the first element with `x.pop(0)` (which permanently removes it from **x**), we compute `x.pop(0)-max(x)`. Note that this difference has the "wrong" sign. If the updated list **x** still contains at least two elements, `x[1:]` yields a non-empty list, and `and` replaces it with the negative of a recursive call, computed as `-f(x)`. Once there are too few elements to continue, `x[1:]and-f(x)` evaluates to an empty list. To select the maximal outcome, we take the *minimum* of the difference and the negative of the recursive call (or `[]`). Since all integers are strictly less than `[]`, `min` will simply return its left argument if the right one is `[]`. Finally, the unary minus `-` corrects the sign of the computed outcome. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 4 bytes Using [FryAmTheEggman's approach](https://codegolf.stackexchange.com/a/85474/34388). Code: ``` ¥ŒOà ``` Explanation: ``` ¥ # Calculate the increments of the array. Œ # Get all substring of the array. O # Sum the arrays in the array. à # Get the largest sum and implicitly print that. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wqXFkk_DoA&input=WzEsIDk5LCAyLCAxMDVd). [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` 2XN!dX> ``` [Try it online!](http://matl.tryitonline.net/#code=MlhOIWRYPg&input=WzEsOTksMiwxMDVd) Or [verify all test cases](http://matl.tryitonline.net/#code=YAoyWE4hZFg-CkRU&input=WzEsMiwzLDQsNV0KWzEsOTksMiwxMDVdCls5OSwxLDk5LDEwMF0KWzk5LDEsMSwyLDEsM10KWzUsNCwzLDMsMV0KWzUsNCwzLDFdCls1LDIsMV0KWzUsNCwxXQ). ``` 2XN % Take input implicitly. Two-column 2D array with all combinations of 2 elements. % Each combination is a row. Elements in each row are in increasing order ! % Transpose d % Difference of the two numbers in each column X> % Maximum value. Display implicitly ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œcḅ-Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZJj4biFLeG5gA&input=&args=WzEsMiwzLDQsNV0) or [verify all test cases](http://jelly.tryitonline.net/#code=xZJj4biFLeG5gArDh-KCrEc&input=&args=WzEsMiwzLDQsNV0sIFsxLDk5LDIsMTA1XSwgWzk5LDEsOTksMTAwXSwgWzk5LDEsMSwyLDEsM10sIFs1LDQsMywzLDFdLCBbNSw0LDMsMV0sIFs1LDIsMV0sIFs1LDQsMV0sIFs1NSw0NSwyMCwxXSwgWzUsMV0sIFsxMCw3LDUsMV0). ### How it works ``` Œcḅ-Ṁ Main link. Argument: A (integer array) Œc Generate all combinations of two elements of A, in order. ḅ- Convert each pair from base -1 to integer. This maps [a, b] to b - a. Ṁ Take the maximum of all computed differences. ``` [Answer] ## Pyth, 9 ``` eSsM.:-Vt ``` [Try it here](http://pyth.herokuapp.com/?code=eSsM.%3A-Vt&input=%5B99%2C1%2C1%2C2%2C1%2C3%5D&debug=0) or run a [Test Suite](http://pyth.herokuapp.com/?code=eSsM.%3A-Vt&input=%5B99%2C1%2C1%2C2%2C1%2C3%5D&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C4%2C5%5D%0A%5B1%2C99%2C2%2C105%5D%0A%5B99%2C1%2C99%2C100%5D%0A%5B99%2C1%2C1%2C2%2C1%2C3%5D%0A%5B5%2C4%2C3%2C3%2C1%5D%0A%5B5%2C4%2C3%2C1%5D%0A%5B5%2C2%2C1%5D%0A%5B5%2C4%2C1%5D%0A%5B55%2C45%2C20%2C1%5D%0A%5B10%2C7%2C5%2C1%5D&debug=0). Finds the consecutive differences between each element, then finds each substring of that array. Finally, sum the elements and return the maximal one. ### Explanation: ``` eSsM.:-Vt eSsM.:-VtQQ ## Auto-fill variables -VtQQ ## Splat subtraction on each element of zip(Q[1:], Q) .: ## Get all substrings sM ## Sum each list eS ## Take the largest number ``` It was mentioned to me that that this algorithm works isn't entirely intuitive. Hopefully this example will illustrate why this algorithm works: ``` [a, b, c, d] difference between each element (reversed because of how Pyth does this) [b-a, c-b, d-c] "substrings" or each continuous slice [b-a], [c-b], [d-c], [b-a, c-b], [c-b, d-c], [b-a, c-b, d-c] sum each [b-a], [c-b], [d-c], [b-a+c-b], [c-b+d-c], [b-a+c-b+d-c] simplify [b-a], [c-b], [d-c], [c-a], [d-b], [d-a] ``` [Answer] # Pyth, 9 ``` _hS-M.cQ2 ``` Yay pfns! ``` _hS-M.cQ2 .cQ2 # generate all 2-elements combinations of Q (argument) -M # map-splat with -: for each combination, substract the elements together S # tort h # take the first _ # absolute value ``` [Answer] ## PowerShell v2+, 58 bytes ``` param($n)($n|%{($n[++$i..$n.count]|sort)[-1]-$_}|sort)[-1] ``` Takes input `$n`, pipes each element into a loop `|%{...}`. Each iteration, we slice `$n` based on pre-incremented `++$i` to the end of the input array, `|sort` that, and take the maximal `[-1]`, then subtract the current element `$_`. We then `|sort` all of those differences, and again take the maximal `[-1]`. Tosses out a verbose array-index error, because we try to slice past the end of the array. But, since [STDERR is ignored by default](http://meta.codegolf.stackexchange.com/q/4780/42963), we don't care. [Answer] ## JavaScript (ES6), ~~57~~ 54 bytes ``` a=>(m=Math.max)(...a.map((x,i)=>m(...a.slice(i+1))-x)) ``` In JavaScript it's easier to take the max of the remainder of the array and subtract the current element. (In the case of the last element the result will still be -Infinity.) Edit: Saved 3 bytes thanks to @CharlieWynn. [Answer] # J, 21 bytes ``` [:>./@;i.@#<@{."_1-/~ ``` Takes an array of values as an argument and returns the result. ## Explanation ``` [:>./@;i.@#<@{."_1-/~ Input: p -/~ Make a table of all differences between every pair # Get the count of values in p i.@ Create a range [0, 1, ..., len(p)-1] {."_1 Take that many values from each row of the table <@ Box each row of selected values [: ; Unbox and concatenate them >./@ Reduce it by the max and return ``` [Answer] # Java, 141 bytes ``` a->java.util.stream.IntStream.range(0,a.size()-1).map(i->a.subList(i+1,a.size()).stream().reduce(Math::max).get()-a.get(i)).max().getAsInt(); ``` The lambda accepts an ArrayList and returns an Integer. Ungolfed code with test cases: ``` import java.util.ArrayList; import java.util.Arrays; import java.util.function.Function; import java.util.stream.IntStream; class Test { public static void main(String[] args) { Function<ArrayList<Integer>, Integer> f = a -> IntStream .range(0, a.size()-1) .map(i -> a.subList(i+1, a.size()).stream().reduce(Math::max).get() - a.get(i)) .max() .getAsInt(); System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,2,3,4,5)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,99,2,105)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,99,100)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,1,2,1,3)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,3,1)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,1)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,2,1)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,1)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(55,45,20,1)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,1)))); System.out.println(f.apply(new ArrayList<>(Arrays.asList(10,7,5,1)))); } } ``` As far as I know, Java doesn't have a way to look forward in a stream, and manipulating the method from which the stream is generated produces strange results. So doing `a.remove(0)` inside a map horribly breaks the stream. [Answer] ## VBA, 154 Takes in the input in column A starting in A1, outputs in C1. Must be run with the last cell in A selected. Note that Excel auto-adds the spaces between terms in VBA, otherwise this could be golfed further. ``` Sub s i = Selection.Row r = "B1:B" + i-1 Range(r).FormulaArray = "MAX(A2:A$" + i + "-A1)" Range(r).FillDown Range("C1").Formula = "MAX(" + r + ")" End Sub ``` [Answer] # Java, 116 Another java solution, i used this one to prove that, streams might looks nice, but not always useful for golfing. ``` int a(int[]a){int t,d=a[1]-a[0],i,j,l=a.length;for(i=0;i<l;i++)for(j=i+1;j<l;j++){t=a[j]-a[i];d=d<t?t:d;}return d;} ``` there is lot of space for improvements in this solution [Answer] # Clojure, 99 bytes ``` (fn[x](apply max(map #(-(apply max(% 1))(apply min(% 0)))(map #(split-at % x)(range 1(count x)))))) ``` Splits input list at first position then second and so on, so we get a list which looks like this: `[[[n1][n2 ... nk]][[n1 n2][n3 ... nk]]...[[n1...n(k-1)][nk]]]` then for each pair subtracts minimum of the first elements from max of the second element and then find max from them. Would be shorter if Clojure's `min` `max` were taking sequences rather than any number of arguments. See it online: <https://ideone.com/b2nllT> [Answer] # ruby, 52 bytes ``` ->a{b=[];(x=a.pop;b+=a.map{|v|x-v})while a[0];b.max} ``` pops possible sell prices and look at all of the previous to find profit. Then gets max profit. [Answer] **C, 101 99 Bytes** ``` int i,j,m,h;int f(int*a){m=1<<31;for(;a[i];i++){for(j=i+1;a[j];h=a[j++]-a[i],m=h<m?m:h);}return m;} ``` Input: null terminated array. E.g. {1,2,3,4,5,0} Output: returns the best outcome You can save 8 bytes (93 91 total) if you never want to lose money: ``` int i,j,m,h;int f(int*a){for(;a[i];i++){for(j=i+1;a[j];h=a[j++]-a[i],m=h<m?m:h);}return m;} ``` [Answer] # R, 58 44 bytes ``` max(unlist(sapply(seq(y<-scan()),diff,x=y))) ``` ungolfed ``` y=scan() #input s=1:length(y) #sequence of same length from 1 l = sapply(s,diff,x=y) #applies the function diff to each 'lag' in sequence s #and differencing on y max(unlist(l)) #reforms as vector and finds maximum ``` **EDIT:** changed function. original below. ``` f=function(x)max(max(x[-1]-x[1]),if(length(x)-2)f(x[-1])) ``` or, if you're willing to put up with a bunch of warning messages, get rid of the -2 after length, for 56 bytes. ``` f=function(x)max(max(x[-1]-x[1]),if(length(x))f(x[-1])) ``` And if you feel like not trading and losing money when that's the only possibility, you can get down to 52 ``` f=function(x)max(max(x-x[1]),if(length(x))f(x[-1])) ``` ]
[Question] [ Your challenge is to write a code-golf HTTP server that accepts GET requests. It obviously doesn't have to be fully featured, but it must serve files from a directory. Rules: * The HTTP server must listen on TCP port 36895 (0x901F) * It must serve files from `/var/www` on \*NIX systems (e.g. Linux), or `C:\hgolf` on Windows. * You may ignore all incoming HTTP headers except the `GET` itself. * If the HTTP method is not GET, you must send back a status code of "405 Not Supported" and a body of "405 Not Supported". * If the file does not exist, you must send back a status code of "404 File Not Found" and a body of "404 File Not Found". * If the file exists but could not be read for some reason, you must send back a status code of "500 Server Error" and a body of "500 Server Error". * If the user requests `/` or any other existing directory root (e.g. `/foo/` where a directory `foo` exists in `/var/www/`), respond with a blank page. * Your response must contain at least the minimum headers to allow the content to be displayed on Firefox 8.0 and Internet Explorer 8.0 * You must respond with the `Content-Type` header set, but you only have to support extensions `html => text/html` and `txt => text/plain`. For any other file extension, Send `application/octet-stream` as the content type. * Your code must be able to transfer both ASCII and binary data, though you do not explicitly have to distinguish between the two. * You may not use 3rd party libraries. * You may not use in-built classes or features designed to process HTTP requests (e.g. `HttpListener` in C#) * If your code will only work on a specific OS due to the socket APIs you've used, please state this. Solutions must include an image showing it serving a HTML page to a browser. If you've got any questions, please feel free to ask! :) [Answer] # Bash+netcat: 354 characters * Two script files are used. * No URL decoding, thus file names with spaces and special characters not supported. * Single threaded, so concurrent requests may fail. * Tested on Linux, works nicely with Firefox and Opera. **webserver.sh** (33 characters): ``` while :;do nc -lp36895 -e./w;done ``` **w** (321 characters): ``` read m p v p=/var/www$p t=text/plain [[ -r $p ]]||s='500 Server Error' [[ -e $p ]]||s='404 Not Found' [[ $m != GET ]]&&s='405 Not Supported' [[ $s||-d $p ]]||case ${p##*.} in txt);;html)t=text/html;;*)t=application/octet-stream;;esac echo "$v ${s-200 Ok} Content-Type:$t " [[ $s ]]&&echo $s||{ [[ -d $p ]]&&echo||cat $p;} ``` Sample run: ``` bash-4.2$ ./webserver.sh ``` Sample visit (Firefox 19.0): ![enter image description here](https://i.stack.imgur.com/M7MCK.png) [Answer] ### Ruby, 383 characters ``` require 'socket' v=TCPServer.new 36895 while c=v.accept h="200 OK";m="";t="" (c.gets=~/GET (\S*)/)?File.directory?(s='C:/hgolf'+$1)?0:File.exist?(s)?(h+="\r\nContent-Type: "+(s=~/\.txt$/?"text/plain":s=~/\.html$/?"text/html":"application/octet-stream");t="IO.copy_stream(s,c)"):(h=m="404 File Not Found"):(h=m="405 Not Supported") c.puts "HTTP/1.1 #{h}\r\n\r\n"+m eval(t) c.close end ``` The restructuring of the code to pack the essential logic into one line which makes the code shorter. Nevertheless, I hope this version can be golfed a little bit further. ![enter image description here](https://i.stack.imgur.com/3anmo.png) Note: I didn't yet implement the "500 Server Error" because I couldn't find an appropriate structure (maybe packaging everything into begin/rescue/end but reading the file is done after the header was sent). [Answer] # Haskell, 636 ``` import Data.List;import Network;import System.Directory;import System.IO main=listenOn(PortNumber 36895)>>=l;l s=(n s`catch`\_->u())>>l s n s=do(h,_,_)<-accept s;z h>>=q.words>>=hPutStr h;hClose h q("GET":p:_)=d$"/var/www"++p;q _=c"405 Not Supported" d p=doesFileExist p>>=f p;e x|x=u$s""""|1<3=c"404 File Not Found" f p x|x=t p`catch`\_e->c"500 Server Error"|1<3=doesDirectoryExist p>>=e t p=fmap(s$"\nContent-Type: "++g p)$z=<<openBinaryFile p ReadMode r s h b=["HTTP/1.0 ",s,h,"\n\n",b]>>=id g p|b".html"p="text/html"|b".txt"p="text/plain"|1<3="application/octet-stream" s=r"200 OK";c s=u$r s[]s;u=return;b=isSuffixOf;z=hGetContents ``` Files are streamed lazily, so serving large files does not use much memory, but this also means that only errors at the start of transmission (e.g. permission errors) result in a `500 Server Error`. ![Serving a HTML page](https://i.stack.imgur.com/NzJxw.png) Tested on Ubuntu 10.10. Can be ported to Windows by changing the `/var/www` to `C:/hgolf` and changing `main=` to `main=withSocketsDo$`, since the sockets library on Windows requires explicit initialization. **Ungolfed version:** ``` import Data.List import Network import System.Directory import System.IO root = "/var/www" main = do s <- listenOn (PortNumber 36895) loop s loop s = (next s `catch` \e -> return ()) >> loop s next s = do (h, _, _) <- accept s hGetContents h >>= serve >>= hPutStr h hClose h serve req = case words req of ("GET" : path : _) -> deliver (root ++ path) _ -> complain "405 Not Supported" deliver path = do isFile <- doesFileExist path if isFile then transfer path `catch` (\e -> complain "500 Server Error") else do isDir <- doesDirectoryExist path if isDir then return $ response "200 OK" [] "" else complain "404 File Not Found" transfer path = do body <- hGetContents =<< openBinaryFile path ReadMode return $ response "200 OK" ["Content-Type: " ++ guessType path] body response status headers body = concat [unlines $ ("HTTP/1.0 " ++ status) : headers, "\n", body] complain status = return $ response status [] status guessType path | ".html" `isSuffixOf` path = "text/html" | ".txt" `isSuffixOf` path = "text/plain" | otherwise = "application/octet-stream" ``` [Answer] ## Python 2, 525 510 493 (bending the rules 483) chars ``` from socket import* from os.path import* a=socket(2,1) a.bind(("",80)) a.listen(5) while 1: c,_=a.accept();i=c.recv(512).split("\n")[0].split();z=i[1][1:];m=i[2]+(i[0]!="GET"and"405 Not Supported\n\n"*2or exists(z)-1and"404 File Not Found\n\n"*2or"200 OK\n") if(len(m)>16)+isdir(z)<1: try:f=open(z,"rb");m+="Content-Type: "+{".txt":"text/plain","html":"text/html"}.get(z[-4:],"application/octet-stream")+"\n\n"+f.read() except:m=i[2]+"500 Server Error\n\n"*2 c.send(m);c.close() ``` I stated that I only need 483 chars if I bend the rules because the last `;c.close()` could be omitted. This is because the moment the next client gets accepted, the socket gets closed anyway. This will of course increase waiting time somewhat (Firefox will only display the page when the next client connects, Chrome will display it before, but will continue to load), but the rules do not require me to respond to the request *immediately*, only to do so *at some point*. I am not certain whether this will work on Unixes because I used send instead of sendall and send does not guarantee to actually send everything it is fed. It does work on Windows. ![The screenshot that doesn't proof anything because there is no way to tell whether I used Apache or my own server to create it](https://i.stack.imgur.com/hly3p.png) [Answer] # Groovy, ~~507~~ ~~500~~ ~~489~~ 485 ``` for(ServerSocket s=new ServerSocket(36895);;){t=s.accept() o=t.outputStream o<<"HTTP/1.1 " e='\r\n'*2 d={o<<"$it$e$it"} p=t.inputStream.newReader().readLine().split() if(p[0]!='GET')d'405 Not Supported'else{f=new File('/var/www/',p[1]) if(!f.exists())d'404 File Not Found'else if(f.isFile()){x=f.name=~/\.(.*)/ o<<"200 OK\r\nContent-Type: ${[html:'text/html',txt:'text/plain'][!x?:x[0][1]]?:'application/octet-stream'}$e" try{o.bytes=f.bytes}catch(t){d"500 Server Error"}}} o.close()} ``` ![enter image description here](https://i.stack.imgur.com/YxRjE.png) Added the image download to show binary files are working properly - had a few issues with them to begin with. Can anyone suggest a shorter way to read the input? [Answer] ## Erlang (escript) 575 Very dirty Erlang escript. There have to be one blank line at beginning of file to work well: ``` $ cat hgolf.erl main(_)->{ok,L}=gen_tcp:listen(36895,[]),s(L). s(L)->{ok,S}=gen_tcp:accept(L),receive{tcp,S,"GET "++R}->[F|_]=string:tokens("/var/www"++R," "),case case file:read_file_info(F)of{ok,{_,_,regular,read,_,_,_,_,_,_,_,_,_,_}}->a;{ok,_}->"500 Server Error";_->"404 File Not Found"end of a->h(S,"200 OK\r\nContent-Type: "++case lists:reverse(F)of"lmth."++_->"text/html";"txt."++_->"text/plain";_->"application/octet-stream"end,[]),file:sendfile(F,S);E->h(S,E,E)end;_->E="405 Not Supported",h(S,E,E)end,gen_tcp:close(S),s(L). h(S,H,B)->gen_tcp:send(S,["HTTP/1.1 ",H,"\r\n\r\n",B]). ``` How to run ``` $ escript hgolf.erl ``` ![Screenshot](https://i.stack.imgur.com/rvGSR.png) **Edit:** I have squeezed out 20 chars. `case` is surprisingly shorter than function with even one argument and three clauses. [Answer] # VB.NET, 7203 ![Picture of server running](https://i.stack.imgur.com/27LXi.png) You can define any port and any base directory using `--port` and `--base`, respectively. No, this isn't really a golfing solution. But being VB.NET, there's really no point anyway. On the plus side, this one has lots more features. ``` Imports System.IO Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Text.RegularExpressions Public Module Server Private Const READ_BUFFER_SIZE As Integer = 1024 #Region "Content-Type Identification" Private ReadOnly ContentTypes As New Dictionary(Of String, String) From { {".htm", "text/html"}, {".html", "text/html"}, {".js", "text/javascript"}, {".css", "text/css"}, {".png", "image/png"}, {".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".gif", "image/gif"} } 'Feel free to add more. ''' <summary> ''' Retrieves the Content-Type of the specified file. ''' </summary> ''' <param name="filepath">The file for which to retrieve the Content-Type.</param> Private Function GetContentType(ByVal filepath As String) As String Dim ext As String = IO.Path.GetExtension(filepath) If ContentTypes.ContainsKey(ext) Then _ Return ContentTypes(ext) Return "text/plain" End Function #End Region #Region "Server Main()" Public Sub Main(ByVal args() As String) Try 'Get a dictionary of options passed: Dim options As New Dictionary(Of String, String) From { {"--port", "8080"}, {"--address", "127.0.0.1"}, {"--base", String.Empty} } For i As Integer = 0 To args.Length - 2 If args(i).StartsWith("-") AndAlso options.ContainsKey(args(i)) Then _ options(args(i)) = args(i + 1) Next 'Get the base directory: Dim basedir As String = Path.Combine(My.Computer.FileSystem.CurrentDirectory, options("--base")) 'Start listening: Dim s As New TcpListener(IPAddress.Parse(options("--address")), Integer.Parse(options("--port"))) 'Can be changed. Dim client As TcpClient s.Start() Do 'Wait for the next TCP client, and accept the connection: client = s.AcceptTcpClient() 'Read the data being sent to the server: Dim ns As NetworkStream = client.GetStream() Dim sendingData As New Text.StringBuilder() Dim rdata(READ_BUFFER_SIZE - 1) As Byte Dim read As Integer Do read = ns.Read(rdata, 0, READ_BUFFER_SIZE) sendingData.Append(Encoding.UTF8.GetString(rdata, 0, read)) Loop While read = READ_BUFFER_SIZE 'Get the method and requested file: #If Not Debug Then Try #End If If sendingData.Length > 0 Then Dim data As String = sendingData.ToString() Dim headers() As String = data.Split({ControlChars.Cr, ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries) Dim basicRequestInfo() As String = headers(0).Split(" "c) Dim method As String = basicRequestInfo(0) Dim filepath As String = basicRequestInfo(1).Substring(1) Dim actualFilepath As String = Path.Combine(basedir, Uri.UnescapeDataString(Regex.Replace(filepath, "\?.*$", "")).TrimStart("/"c).Replace("/"c, "\"c)) Dim httpVersion As String = basicRequestInfo(2) 'Set up the response: Dim responseHeaders As New Dictionary(Of String, String) Dim statusCode As String = "200" Dim statusReason As String = "OK" Dim responseContent() As Byte = {} 'Check the HTTP version - we only support HTTP/1.0 and HTTP/1.1: If httpVersion <> "HTTP/1.0" AndAlso httpVersion <> "HTTP/1.1" Then statusCode = "505" statusReason = "HTTP Version Not Supported" responseContent = Encoding.UTF8.GetBytes("505 HTTP Version Not Supported") Else 'Attempt to check if the requested path is a directory; if so, we'll add index.html to it: Try If filepath = String.Empty OrElse filepath = "/" Then actualFilepath = Path.Combine(basedir, "index.html") filepath = "/" ElseIf Directory.Exists(actualFilepath) Then actualFilepath = Path.Combine(actualFilepath, "index.html") End If Catch 'Ignore the error; it will appear once again when we try to read the file. End Try 'Check the method - we only support GET and HEAD: If method = "GET" Then 'Make sure nobody's trying to hack the system by requesting ../whatever or an absolute path: If filepath.Contains("..") Then statusCode = "403" statusReason = "Forbidden" responseContent = Encoding.UTF8.GetBytes("403 Forbidden") Console.WriteLine("Access to {0} was forbidden.", filepath) ElseIf Not File.Exists(actualFilepath) Then statusCode = "404" statusReason = "Not Found" responseContent = Encoding.UTF8.GetBytes("404 Not Found") Console.WriteLine("A request for file {0} resulted in a 404 Not Found. The actual path was {1}.", filepath, actualFilepath) Else Try 'Read the requested file: responseContent = File.ReadAllBytes(actualFilepath) 'Get the requested file's length: responseHeaders.Add("Content-Length", responseContent.Length.ToString()) 'And get its content type too: responseHeaders.Add("Content-Type", GetContentType(actualFilepath)) Catch 'Couldn't get the file's information - assume forbidden. statusCode = "403" statusReason = "Forbidden" responseContent = Encoding.UTF8.GetBytes("403 Forbidden") End Try End If ElseIf method = "HEAD" Then 'Make sure nobody's trying to hack the system by requesting ../whatever or an absolute path: If filepath.Contains("..") Then statusCode = "403" statusReason = "Forbidden" responseContent = Encoding.UTF8.GetBytes("403 Forbidden") Console.WriteLine("Access to {0} was forbidden.", filepath) ElseIf Not File.Exists(actualFilepath) Then statusCode = "404" statusReason = "Not Found" responseContent = Encoding.UTF8.GetBytes("404 Not Found") Console.WriteLine("A request for file {0} resulted in a 404 Not Found.", filepath) Else Try 'Get the requested file's length: responseHeaders.Add("Content-Length", New FileInfo(actualFilepath).Length.ToString()) 'And get its content type too: responseHeaders.Add("Content-Type", GetContentType(actualFilepath)) Catch 'Couldn't get the file's information - assume forbidden. statusCode = "403" statusReason = "Forbidden" responseContent = Encoding.UTF8.GetBytes("403 Forbidden") End Try End If Else 'Unknown method: statusCode = "405" statusReason = "Method Not Allowed" End If 'Prepare the response: Dim response As New List(Of Byte) 'Prepare the response's HTTP version and status: response.AddRange(Encoding.UTF8.GetBytes("HTTP/1.1 " & statusCode & statusReason & ControlChars.CrLf)) 'Prepare the response's headers: Dim combinedResponseHeaders As New List(Of String) For Each header As KeyValuePair(Of String, String) In responseHeaders combinedResponseHeaders.Add(header.Key & ": " & header.Value) Next response.AddRange(Encoding.UTF8.GetBytes(String.Join(ControlChars.CrLf, combinedResponseHeaders.ToArray()))) 'Prepare the response's content: response.Add(13) response.Add(10) response.Add(13) response.Add(10) response.AddRange(responseContent) 'Finally, write the response: ns.Write(response.ToArray(), 0, response.Count) End If End If #If Not Debug Then Catch ex As Exception Console.WriteLine("Serious error while processing request:") Console.WriteLine(ex.ToString()) Dim errorResponse() As Byte = Encoding.UTF8.GetBytes("HTTP/1.1 500 Internal Server Error" & ControlChars.CrLf & ControlChars.CrLf & "500 Internal Server Error") ns.Write(errorResponse, 0, errorResponse.Length) End Try #End If 'And at last, close the connection: client.Close() Loop Catch ex As SocketException Console.WriteLine("SocketException occurred. Is the socket already in use?") Console.ReadKey(True) End Try End Sub #End Region End Module ``` I even decided to put it on GitHub :) <https://github.com/minitech/DevServ> [Answer] # C# (869) ![It worked](https://i.stack.imgur.com/DQPRL.png) ``` using E=System.Text.Encoding;using System.IO;class C{static void Main(){var l=new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(16777343,36895));l.Start();while(0<1){using(var c=l.AcceptTcpClient()){try{string v="200 OK",r="",t="text/plain",p;var s=c.GetStream();var b=new byte[c.ReceiveBufferSize];s.Read(b,0,b.Length);var h=E.UTF8.GetString(b).Split();b=null;try{if(h[0]=="GET"){p="/var/www"+h[1];if(File.Exists(p)){b=File.ReadAllBytes(p);t=p.EndsWith(".txt")?t:p.EndsWith(".html")?"text/html":"application/octet-stream";}else if(!Directory.Exists(p)){v=r="404 Not Found";}}else{v=r="405 Not Supported";}}catch(IOException){v=r="500 Server Error";}b=b??E.UTF8.GetBytes(r);var m=E.UTF8.GetBytes("HTTP/1.1 "+v+"\r\nContent-Type:"+t+";charset=utf-8\r\nContent-Length:"+b.Length+"\r\n\r\n");s.Write(m,0,m.Length);s.Write(b,0,b.Length);}catch(IOException){}}}}} ``` Ungolfed ``` using System.Text; using System.IO; class C { static void Main() { var listener = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(16777343,36895)); listener.Start(); while (true){ using (var client = listener.AcceptTcpClient()) { try { string responseCode = "200 OK", responseBody = "", contentType = "text/plain", path; var stream = client.GetStream(); var bytes = new byte[client.ReceiveBufferSize]; stream.Read(bytes,0,bytes.Length); var requestHeaders = Encoding.UTF8.GetString(bytes).Split(); bytes = null; try{ if(requestHeaders[0] == "GET"){ path = "/var/www" + requestHeaders[1]; if (File.Exists(path)) { bytes = File.ReadAllBytes(path); contentType = path.EndsWith(".txt") ? contentType : path.EndsWith(".html") ? "text/html" : "application/octet-stream"; } else if (!Directory.Exists(path)){ responseCode = responseBody = "404 Not Found"; } } else { responseCode = responseBody = "405 Not Supported"; } } catch(IOException) { responseCode = responseBody = "500 Server Error"; } bytes = bytes ?? Encoding.UTF8.GetBytes(responseBody); var responseHeader=Encoding.UTF8.GetBytes("HTTP/1.1 " + responseCode + "\r\nContent-Type:" + contentType + ";charset=utf-8\r\nContent-Length:" + bytes.Length + "\r\n\r\n"); stream.Write(responseHeader, 0, responseHeader.Length); stream.Write(bytes, 0, bytes.Length); } catch(IOException) { // If a client disconnects in the middle of a request (e.g. by refreshing the browser) an IOException is thrown. } } } } } ``` [Answer] # Node.js - 636 Only tested on Linux, won't work on Windows. ``` a=require b=a('fs') function c(){g+=o+h+i+j+f+f+o+f} a('net').createServer(function(d){d.on('data',function(e){f='\r\n' g='HTTP/1.1 ' h=f+'Content-Type: ' i='text/' j='plain' if(k=/^GET (\S+)/.exec((e+'').split(f)[0])){k=k[1] l=k.slice(k.lastIndexOf('.')+1) m='www'+k if(b.existsSync(m)){if(b.lstatSync(m).isDirectory()){g+='200 OK'+h+i+j+f}else{try{n=b.readFileSync(m) g+='200 OK'+h if(l=='txt')g+=i+j else if(l=='html')g+=i+l else g+='application/octet-stream' g+=f+f+n}catch(_){o='500 Server Error' c()}}}else{o='404 File Not Found' c()}}else{o='405 Not Supported' c()} d.write(g) d.end()}) d.on('error',function(){})}).listen(36895) ``` ![Screenshot](https://i.stack.imgur.com/BrIbO.png) [Answer] # Python 3 - 655 ``` from socket import* import re import threading def x(c): u=str(c.recv(1024)) if not'GET'in u:conn.sendall(t("HTTP/1.1 405 Not Supported")) u=re.search('GET [^\s]+ HTTP/1.1',u).group(0).split(" ")[1];u="/index.html" if u == "/" else u;e=u.split(".")[1] try:c.sendall(t("HTTP/1.1 200 OK\nContent-Type: "+({'txt':'text/plain','html':'text/html'}[e]if e in'txthtml'else'application/octet-stream')+"\n\n")+open("."+u,'rb').read()) except:c.sendall(t("HTTP/1.1 404 File Not Found\n\n404 File Not Found")) t=lambda s: bytes(s,'utf8') s=socket(AF_INET,SOCK_STREAM) s.bind(('',36895)) s.listen(10) while 1:threading.Thread(target=x,args=[s.accept()[0]]).run() ``` ![enter image description here](https://i.stack.imgur.com/oQ0Yv.jpg) [Answer] ## Scala, 653 characters ``` import java.net._ import java.io._ object I extends App{val l=new ServerSocket(36895) while(true){var (s,e,c,b)=(l.accept,"200 OK","text/html","") var h=io.Source.fromInputStream(s.getInputStream).getLines.next.split(" ") if(h(0)!="GET"){e="405 Not Supported" b=e}else{var f=new File("/var/www"+h(1)) if(!f.isDirectory){if(f.exists){var q=h(1).split("\\.").last if(q=="txt")c="text/plain"else if(q!="html")c="application/octet-stream" try b=io.Source.fromFile(f).mkString catch{case _=>e="500 Server Error";b=e}}else{e="404 File Not Found" b=e}}} var o=new PrintWriter(s.getOutputStream) o.print("HTTP/1.1 "+e+"\nContent-Encoding:"+c+"\n\n"+b) o.close}} ``` A screenshot of it running on my MacBook: ![Screenshot](https://i.stack.imgur.com/mFYiM.jpg) Not great, but I'll have a go at squashing it a bit when I've got some time later. [Answer] # VB.Net (3504 characters): ``` Imports System.IO:Imports System.Net:Imports System.Net.Sockets:Imports System.Text:Imports System.Text.RegularExpressions:Module x:Dim s=1024,ct As New Dictionary(Of String,String)From{{".htm","text/html"},{".html","text/html"},{".js","text/javascript"},{".css","text/css"},{".png","image/png"},{".jpg","image/jpeg"},{".jpeg","image/jpeg"},{".gif","image/gif"}}:Function b$(f$):Dim ext$=Path.GetExtension(f$):Return If(ct.ContainsKey(ext$),ct(ext$),"text/plain"):End Function:Sub Main(a$()):Try:Dim z As New Dictionary(Of String,String)From{{"--port","8080"},{"--address","127.0.0.1"},{"--base",""}}:For i As Integer=0 To a.Length-2:If a$(i).StartsWith("-")AndAlso z.ContainsKey(a$(i))Then:z(a$(i))=a$(i+1):Next:Dim b$=Path.Combine(My.Computer.FileSystem.CurrentDirectory,z("--base")),s As New TcpListener(IPAddress.Parse(z("--address")),Integer.Parse(z("--port"))),c As TcpServer:s.Start():Do:c=s.AcceptTcpServer():Dim ns As NetworkStream=c.GetStream():Dim sd As New Text.StringBuilder(),rd(s-1)As Byte,r As Integer:Do:r=ns.Read(rd,0,s):sd.Append(Encoding.UTF8.GetString(rd,0,r)):Loop While r=s:Try:If sd.Length>0 Then:Dim dd$=sd.ToString(),h$()=dd$.Split({ControlChars.Cr,ControlChars.Lf},StringSplitOptions.RemoveEmptyEntries),br$()=h$(0).Split(" "c),mt$=br$(0),f$=br$(1).Substring(1),af$=Path.Combine(b$,Uri.UnescapeDataString(Regex.Replace(f$,"\?.*$","")).TrimStart("/"c).Replace("/"c,"\"c)),hv$=br$(2),rh As New Dictionary(Of String,String),sc$="200",sr$="OK",rc()As Byte={}:If hv$<>"HTTP/1.0"AndAlso hv$<>"HTTP/1.1"Then:sc$="505":sr$="HTTP Version Not Supported":rc=Encoding.UTF8.GetBytes("505"&sr$):Else:Try:If f$=String.Empty OrElse f$="/"Then:af$=Path.Combine(b$,"index.html"):f$="/":ElseIf Directory.Exists(af$)Then:af$=Path.Combine(af$,"index.html"):End If:Catch:End Try:If mt$="GET"Then:If f$.Contains("..")Then:sc$="403":sr$="Forbidden":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("{0} forbidden.",f$):ElseIf Not File.Exists(af$)Then:sc$="404":sr$="Not Found":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("{0} resulted in 404 Not Found. Path {1}.",f$,af$):Else:Try:rc=File.ReadAllBytes(af$):rh.Add("Content-Length",rc.Length&""):rh.Add("Content-Type",b$(af$)):Catch:sc$="403":sr$="Forbidden":rc = Encoding.UTF8.GetBytes(sc$&" "&sr$):End Try:End If:ElseIf mt$="HEAD"Then:If f$.Contains("..")Then:sc$="403":sr$="Forbidden":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("{0} forbidden.",f$):ElseIf Not File.Exists(af$)Then:sc$="404":sr$="Not Found":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("404 Not Found: {0}",f$):Else:Try:rh.Add("Content-Length",New FileInfo(af$).Length&""):rh.Add("Content-Type",b$(af$)):Catch:sc$="403":sr$="Forbidden":rc = Encoding.UTF8.GetBytes(sc$&" "&sr$):End Try:End If:Else:sc$="405":sr$="Method Not Allowed":End If:Dim rr As New List(Of Byte):rr.AddRange(Encoding.UTF8.GetBytes("HTTP/1.1 "&sc$&sr$&ControlChars.CrLf)):Dim cr As New List(Of String):For Each h As KeyValuePair(Of String,String)In rh:cr.Add(h.Key&": "&h.Value):Next:rr.AddRange(Encoding.UTF8.GetBytes(String.Join(ControlChars.CrLf,cr.ToArray()))):rr.Add(13):rr.Add(10):rr.Add(13):rr.Add(10):rr.AddRange(rc):ns.Write(rr.ToArray(),0,rr.Count):End If:End If:Catch ex As Exception:Console.WriteLine("Error:"):Console.WriteLine(ex.ToString()):Dim e()As Byte=Encoding.UTF8.GetBytes("HTTP/1.1 500 Internal x Error"&ControlChars.CrLf &ControlChars.CrLf &"500 Internal x Error"):ns.Write(e,0,e.Length):End Try:c.Close():Loop:Catch:End Try:End Sub:End Module ``` Golfed from @minitech's answer. [Answer] # Lua 5.1 in ~~435~~ 434 bytes ``` s=require'socket'.bind('*',36895)while{}do c=s:accept()u=c:receive'*l':match'GET (.*) HTTP'f,_,e=io.open('/var/www'..u,'rb')d=z x=z if f then d,_,x=f:read'*a'end h=u and(x==21 and''or(e==2 and'404 File Not Found'or d and('200 OK\r\nContent-Type:'..(({txt='text/plain',html='text/html'})[u:match'%.(.-)$']or'application/octet-stream'))or'500 Server Error'))or'405 Not Supported'c:send('HTTP/1.1 '..h..'\r\n\r\n'..(d or h))c:close()end ``` ...and the proof... ![](https://i.stack.imgur.com/v6WDs.png) ]
[Question] [ I hope this picture looks familiar to you. [![enter image description here](https://i.stack.imgur.com/Egmke.png)](https://i.stack.imgur.com/Egmke.png) It's one of [Pacman](https://www.google.com/logos/2010/pacman10-i.html)'s ghosts in his ["vulnerable" state](http://pacman.wikia.com/wiki/Vulnerable_Ghost), after Pacman has eaten a power pill. ## The challenge Picture our ghost in a little frame, using ASCII art. At normal scale (more about this later), each square in the above image should correspond to one character, and the frame should have a one-character separation up and down, and a two-character separation to the left and right of the ghost: ``` #################### # # # #### # # ######## # # ########## # # ############ # # ############ # # ### ## ### # # #### ## #### # # ############## # # ############## # # ## ## ## ## # # # ## ## ## # # # ############## # # ## ### ### ## # # # ## ## # # # # #################### ``` But this doesn't look very pretty. `#` may not be the best choice for the active pixels. Besides, character cells are not square, which makes our friend look more ghostly than he already is. So, to have more flexibility, the picture will change according to three input parameters: * Character to be used for active pixels; * Horizontal scale factor; * Vertical scale factor. For example, with `%`, `4`, `2` the ouput would be the better looking picture ``` %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%% %%%% %%%% %%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%% %%%%%%%% %%%%%%%% %%%%%%%% %%%% %%%% %%%%%%%% %%%%%%%% %%%%%%%% %%%%%%%% %%%% %%%% %%%% %%%%%%%% %%%%%%%% %%%%%%%% %%%% %%%% %%%% %%%% %%%%%%%% %%%%%%%% %%%%%%%% %%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%%%%%% %%%%%%%%%%%% %%%%%%%%%%%% %%%%%%%% %%%% %%%% %%%%%%%% %%%%%%%%%%%% %%%%%%%%%%%% %%%%%%%% %%%% %%%% %%%% %%%%%%%% %%%%%%%% %%%% %%%% %%%% %%%% %%%%%%%% %%%%%%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ``` ### Rules All builtins allowed. Inputs are taken in any reasonable format and any order. The first input above (character for active pixels) is guaranteed to be a printable ASCII character (codes 32 to 126). Trailing space after each line or trailing newlines after last line are acceptable. Code golf, fewest bytes wins. [Answer] # CJam, ~~53~~ ~~51~~ 49 bytes ``` q~"ǟ #/?Y__Fy_Nf ǟ"f{'Ƞ^2b_W%+S@+f=}fe*e*N* ``` Note that three of the characters are unprintable. [Try it online!](http://cjam.tryitonline.net/#code=cX4ix58gIy8_Hx8ZWV9fRnlfTmYgx58iZnsnyKBeMmJfVyUrU0ArZj19ZmUqZSpOKg&input=MiA0ICcl) ### Background The right half of the unscaled output is identical to the left one, so it suffices to encode one of them. If we replace spaces with zeroes and non-spaces with ones, we get ``` 1111111111 1000000000 1000000011 1000001111 1000011111 1000111111 1000111111 1000111001 1001111001 1001111111 1001111111 1001100110 1001011001 1001111111 1001101110 1001000110 1000000000 1111111111 ``` where each line can be interpreted as a binary number. This yields ``` 1023 512 515 527 543 575 575 569 633 639 639 614 601 639 622 582 512 1023 ``` The easiest way to encode this information is to replace each integer with the Unicode character at that code point, but they would all require two bytes to be encoded with UTF-8. By XORing the integers with 544, we keep all but two integers below 128 and avoid null bytes. The result is ``` 479 32 35 47 63 31 31 25 89 95 95 70 121 95 78 102 32 479 ``` as integers or ``` ǟ #/?\x1f\x1f\x19Y__Fy_Nf ǟ ``` as an escaped string. ### How it works ``` q~ e# Read and evaluate all input. This pushes the vscale factor V, e# the hscale factor H, and the character C. "ǟ #/?Y__Fy_Nf ǟ" e# Push that string. f{ e# For each character, push C and the character; then: 'Ƞ^ e# XOR the character with '\u0220' (544), casting to integer. 2b e# Convert from integer to base 2. _W% e# Push a reversed copy of the binary digits. + e# Concatenate. S@+ e# Append C to " ". f= e# Replace each binary digit with ' ' or C. } e# fe* e# Repeat each character in each string H times. e* e# Repeat each string V times. N e# Join the strings, separating by linefeeds. ``` [Answer] # Perl, ~~113~~ ~~105~~ ~~104~~ ~~100~~ ~~97~~ 96 Added +2 for `-ap` Suggestions by dev-null save 9 bytes Fixed wrong count as noticed by Dennis Run using `echo "2 4 %" | perl -ap pacman.pl` `pacman.pl`: ``` }for(map+(unpack(aXBXB8Xb8XBXa),$/)x"@F","\xff\x00\x03\x0f\x1f\x3f\x3f\x39\x79\x7f\x7f\x66\x59\x7f\x6e\x46\x00\xff"=~/./g){s%%($&?$F[2]:$")x$F[1]%ge ``` except that the string `"\xff\x00\x03\x0f\x1f\x3f\x3f\x39\x79\x7f\x7f\x66\x59\x7f\x6e\x46\x00\xff"` should be written in binary form with single quotes Space as replacement character becomes the empty string and leads to short lines. But it will all look blank anyways [Answer] # Dyalog APL, 64 bytes ``` {/∘⍉/⍺,⊂' '⍵[1+,∘⌽⍨1⍪⍨1⍪1,0⍪⍨0⍪0,0,⍉(7/2)⊤⎕AV⍳'Äâ\⊥⊥∘)⍞⍞┬#⍞`⍒']} ``` This takes the scale factor as its left argument and the character as its right argument, i.e: ``` 2 1{/∘⍉/⍺,⊂' '⍵[1+,∘⌽⍨1⍪⍨1⍪1,0⍪⍨0⍪0,0,⍉(7/2)⊤⎕AV⍳'Äâ\⊥⊥∘)⍞⍞┬#⍞`⍒']}'%' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% %% %% %%%%%%%% %% %% %%%%%%%%%%%%%%%% %% %% %%%%%%%%%%%%%%%%%%%% %% %% %%%%%%%%%%%%%%%%%%%%%%%% %% %% %%%%%%%%%%%%%%%%%%%%%%%% %% %% %%%%%% %%%% %%%%%% %% %% %%%%%%%% %%%% %%%%%%%% %% %% %%%%%%%%%%%%%%%%%%%%%%%%%%%% %% %% %%%%%%%%%%%%%%%%%%%%%%%%%%%% %% %% %%%% %%%% %%%% %%%% %% %% %% %%%% %%%% %%%% %% %% %% %%%%%%%%%%%%%%%%%%%%%%%%%%%% %% %% %%%% %%%%%% %%%%%% %%%% %% %% %% %%%% %%%% %% %% %% %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ``` Explanation: * `⍉(7/2)⊤⎕AV⍳'Äâ\⊥⊥∘)⍞⍞┬#⍞`⍒'`: The left half of the ghost, without the border. (It is symmetric.) Each character has its high bit set, to prevent selecting non-printing characters from `⎕AV`, but only the first 7 bytes are used. * `0,⍪⍨0⍪0,0,`: add a border of blanks on the left, top, and bottom * `1⍪⍨1⍪1,`: add the frame on the left, top, and bottom * `,∘⌽⍨`: join it with its vertical mirror * `1+`: add 1, because arrays are 1-indexed by default * `' '⍵[`...`]`: use that matrix as an index into the string `' '⍵`, so each 0 gets mapped to a blank and each 1 gets mapped to `⍵`. * `⍺,⊂`: enclose the matrix and join it to the scale factors * `/`: right fold with the following function: * `/∘⍉`: transpose and scale horizontally [Answer] # [MATL](https://esolangs.org/wiki/MATL), 71 bytes ``` 32hO511-3-12-16-32O6-64-6O25 13-38 17 40 70-511Nq$hYs10H$Bt!P!hi1$lX*Q) ``` [**Try it online!**](http://matl.tryitonline.net/#code=MzJoTzUxMS0zLTEyLTE2LTMyTzYtNjQtNk8yNSAxMy0zOCAxNyA0MCA3MC01MTFOcSRoWXMxMEgkQnQhUCFoaTEkbFgqUSk&input=JygnClsyIDNd) ### Explanation The image is horizontally symmetric, so only the left half needs to be coded. Each 10-pixel row is binary coded as a number between 0 and 1023. Active pixels are coded as 0 rather than 1, so the first row is number 0 rather than 1023. Since consecutive rows differ by a few pixels only, the numbers are further encoded differentially. So each row will be decoded as the cumulative sum of all numbers up to that row, followed by conversion to binary. The needed numbers are then ``` 0 511 -3 -12 -16 -32 0 6 -64 -6 0 25 13 -38 17 40 70 -511 ``` 0 is introduced in MATL using the `O` function, which avoids a separator with neighbouring numbers. Also, negative signs do not imply extra bytes as they serve as separators. Once the array has been created, it is cumulatively summed, binary-decoded, and horizontally mirrored. The resulting 2D array is used to index a two-char string to produce the result. This string is of the form `'% '`, where `'%'` is an input char. As noted by @Conor, the code also works with two chars as input. In this case the final string indexed into will be of the form `'%_ '`, where the input is a two-char string `'%_'`. The space will simply be ignored, because the indexing array only addresses the first two chars. ``` 32 % space (ASCII) h % concat horizontally with 1st input: char O511-3-12-16-32O6-64-6O25 13-38 17 40 70-511 % push these numbers Nq$h % concat all those numbers Ys % cumulative sum 10H$B % convert to 10-digit binary numbers % gives 2D array, each number in one row t % duplicate !P! % flip horizontally h % concat horizontally i % take 2nd input: array [V H] 1$l % matrix oh V×H ones X* % Kronecker product to increase vertical % and horizontal scales by V and H resp. Q % add 1. Converts array of 0,1 into 1,2 ) % uses those 1,2 as indices into string ``` [Answer] # BBC BASIC, ~~239~~ ~~236~~ ~~232~~ 214 bytes ``` 0DEFPROCM(A,B,C)C=C-32:FORU=0TO18*A-1:FORV=0TO20*B-1:Y=U DIVA:X=V DIVB:V.32-C*FNC((X<10)*-X-(X>9)*(19-X),Y):N.:P.:N.:E. 1DEFFNC(X,Y)Z=Y*10+X:=((ASCMI."#Cb^2aC*[#1CF<;)C$;I9I$;EYLb&#",Z/6+1)-35)AND(2^(Z MOD6)))=0 ``` Calling `PROCM(1,1,35)` produces the ghost made of # symbols. The arguments to PROCM are: horizontal scale, vertical scale, ASCII value of character. This program will work both for Brandy Basic, and BASIC 2 on an original Model B. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~199~~ 197 bytes -2 bytes thanks to @JonathanFrech ``` n,j;f(c,h,v){for(char t[20],i=18;i--;){for(n=10;n--;)t[n]=t[19-n]=((("\xff\0""1;\x7fM3\x7f\x7fON~~|x`\0\xff"[i]<<3)|(i&&i^17?1:7))>>n)&1?c:32;for(j=v;j--;puts(""))for(n=20*h;n--;)putchar(t[n/h]);}} ``` [Try it online!](https://tio.run/##NY5hTsMwDIV/s1NUQbQ2SkXcIhXmdTsBcIC2iClSaCoR0AhTpa27ekmo@GFbz8/y93T@rvU8OzmwAS17ecST@TyA7veHxDeF6qSt6YFtnvPiuJoUuyh947raN/SYhwkAoh2NaZUQxO1Ymacy9lgvz5fLeXxrVTwQje02mxLPYNPUvlK1o3WFuN06TGmn12XBETPURx4C5evHf4MQiAu7ULf9Qg9GDAkhxV3fIU/TbJ1PPvbWAa5OqysD2XUmSRJy8v@F/9Y3mbyXRRDT/As "C (gcc) – Try It Online") # 188 bytes (unprintables) Courtesy of @JonathanFrech. ``` n,j;f(c,h,v){for(char t[20],i=18;i--;){for(n=10;n--;)t[n]=t[19-n]=((("\xff\0001;M3ON~~|x`\0\xff"[i]<<3)|(i&&i^17?1:7))>>n)&1?c:32;for(j=v;j--;puts(""))for(n=20*h;n--;)putchar(t[n/h]);}} ``` [Try it online!](https://tio.run/##NY7RasJAEEWf9StCislM2eBOUrB1jH6B@gFJSmVhmw10W@xWBI359Lgx9Gm498I5o5JPpfreioY1KFGLE1709xFUfTgGrkhlJUxOr2yShMfF5iTZDtEVtspdQW@JvwAQlmetSyklcbfNum6/u92u549SDn1YmGq1yvAKJorMOy02tFwgrtcWI9qoZZbyQG/yEzce/vPnfiEMEUdlKp/rUeqH4Tfw8nldIbdtb6wLvg7GAk4v04mG@CkWJAg5@Kfwo57F4kWkPrT9HQ "C (gcc) – Try It Online") Nothing spectacular going on. Like others noticed, the ghost is highly symmetrical. The image itself is 20 units wide, but except for the top and bottom rows, the three right-most columns are identical. This allows us to store half of the image as characters instead of having to use integers: ``` ####### 127 \x7f 0 \0 ## 96 ` #### 120 x ##### 124 | ###### 126 ~ ###### 126 ~ # ### 78 N # #### 79 O ####### 127 \x7f ####### 127 \x7f ## ## 51 3 # ## # 77 M ####### 127 \x7f ### ## 59 ; ## # 49 1 0 \0 ####### 127 \x7f ``` The resulting string was reversed to eke out a few bytes on having a descending for loop (also solving an annoying issue with hexadecimal escapes). Other loops could be flipped without issue thanks to symmetry. Each character is shifted left and given a border (with special care on first and last rows). Then it's just a matter of outputting the string correctly scaled. All the for loops makes me feel there is a better way. # [C (gcc)](https://gcc.gnu.org/), 175 bytes (non-ASCII) Another version, this time courtesy of ceilingcat. Uses some funky non-ASCII characters. ``` n,j;f(c,h,v){for(char t[20],i=18;i--;){for(n=10;n--;)t[n]=t[19-n]=(L"ǿĀ1;ſM3ſſON~~|x`\0ǿ"[i]*8|(i&&i^17?1:7))>>n&1?c:32;for(j=v;j--;puts(""))for(n=20*h;n--;)putchar(t[n/h]);}} ``` [Try it online!](https://tio.run/##NY5dCoJAFIWfaxVipDMxkteCfi7WBvpZgBnFgDlCU9QUQRntbF6SlmVj0tPlnAPfd7m347wsJcswIZyl7ErvyeFEeLo9WSoK/JiJEIYoPA/rRYbgo6yiimQcqghGnrlkZn/0@wVY6Hmv0IVeLp7Px22z8j/ajkTcGT6IcByxhsEUxgNKJxPpwJSPewFW2Cy8Ymaox4s6E9umtHYFfietbWaoniLG2k1jinleCqms/VZIQpv3ZiMhbstlwICi9afgr267rM8CE/LyCw "C (gcc) – Try It Online") [Answer] ## Seriously, 116 bytes ``` ╩' "3ff 200 203 20f 21f 23f 23f 239 279 27f 27f 266 259 27f 26e 246 200 3ff"s`24╙(¿¡╜'1(Æ' '0(Æ"╛*"£M;R@+εj2└@n`M' j ``` That newline is important. Hexdump: ``` 00000000: ca27 2022 3366 6620 3230 3020 3230 3320 .' "3ff 200 203 00000010: 3230 6620 3231 6620 3233 6620 3233 6620 20f 21f 23f 23f 00000020: 3233 3920 3237 3920 3237 6620 3237 6620 239 279 27f 27f 00000030: 3236 3620 3235 3920 3237 6620 3236 6520 266 259 27f 26e 00000040: 3234 3620 3230 3020 3366 6622 7360 3234 246 200 3ff"s`24 00000050: d328 a8ad bd27 3128 9227 2027 3028 9222 .(...'1(.' '0(." 00000060: be2a 229c 4d3b 5240 2bee 6a32 c040 6e60 .*".M;R@+.j2.@n` 00000070: 4d27 0d0a 6a M'..j ``` Same strategy as Dennis's [CJam answer](https://codegolf.stackexchange.com/a/73992/45941), but the values are encoded in hex, rather than XORed with 544, and string manipulation is a lot harder in Seriously. [Try it online!](http://seriously.tryitonline.net/#code=4pWpJyAiM2ZmIDIwMCAyMDMgMjBmIDIxZiAyM2YgMjNmIDIzOSAyNzkgMjdmIDI3ZiAyNjYgMjU5IDI3ZiAyNmUgMjQ2IDIwMCAzZmYic2AyNOKVmSjCv8Kh4pWcJzEow4YnICcwKMOGIuKVmyoiwqNNO1JAK861ajLilJRAbmBNJwpq&input=JyUnCjQKMg) [Answer] ## Batch, ~~740~~ ~~722~~ 720 bytes ``` @echo off setlocal enabledelayedexpansion set h=%3 set w= set s= for /l %%a in (1,1,%2)do set w=%1!w!&set s= !s! call:l #################### call:l # # call:l # #### # call:l # ######## # call:l # ########## # call:l # ############ # call:l # ############ # call:l # ### ## ### # call:l # #### ## #### # call:l # ############## # call:l # ############## # call:l # ## ## ## ## # call:l # # ## ## ## # # call:l # ############## # call:l # ## ### ### ## # call:l # # ## ## # # call:l # # call:l #################### exit/b :l set l=%* set l=!l: =%s%! for /l %%a in (1,1,%h%)do echo !l:#=%w%! ``` Edit: Saved ~~18~~ 20 bytes by removing unnecessary spaces. [Answer] # [Stax](https://github.com/tomtheisen/stax), 45 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` àÄÅ╣>u°↨2ö|dτÅbn╦─▀:ΣFúÇz?⌂É\!n▄§V0Ncó╤½8|δò_ ``` [Run and debug it](https://staxlang.xyz/#p=858e8fb93e75f81732947c64e78f626ecbc4df3ae446a3807a3f7f905c216edc1556304e63a2d1ab387ceb955f&i=%22%23%22+1+1%0A%22%25%22+4+2%0A%22%E2%96%88%22+3+2&a=1&m=2) Explanation: ``` "<long string>"!E' x+:BA/s|*mn|*:m Full program, implicit input. "<long string>"!E Push 1531747987795407832964332490922049710271411270772589567 ' x+ Push a space plus the given character :B Interpret the number in binary, replacing 0 with ' ' and 1 with the given char A/ Group into pieces of length 10. Gives the first half of each line. s|* Repeat each line <vertical scale factor> times m For each line: n|* Repeat each character <horizontal scale factor> times :m Mirror Implicit output with newline ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 42 bytes ``` »∆nµOḢrċ:f=¢×⁽Ti∴%β‡zwøÞ»ð?+τ18/ƛƛ⁰*;ṅm¹(… ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%BB%E2%88%86n%C2%B5O%E1%B8%A2r%C4%8B%3Af%3D%C2%A2%C3%97%E2%81%BDTi%E2%88%B4%25%CE%B2%E2%80%A1zw%C3%B8%C3%9E%C2%BB%C3%B0%3F%2B%CF%8418%2F%C6%9B%C6%9B%E2%81%B0*%3B%E1%B9%85m%C2%B9%28%E2%80%A6&inputs=%25%0A2%0A4&header=&footer=) ``` »...» # Compressed integer representation τ # Decompress using... ð?+ # Space and input char 18/ # Divide into 18 pieces ƛ # Foreach... ƛ ; # Foreach character ⁰* # Repeat as necesarry ṅ # Join m # Palindromise ¹(… # Print (input) times ``` [Answer] ## JavaScript (ES6), 167 bytes ``` (s,w,h)=>[...`NJ56:* \fLJJSlJ[s5NJ`].map(c=>`${t=(c.charCodeAt()^565).toString(2)}${[...t].reverse().join``} `.replace(/./g,b=>` ${s}`[b].repeat(w)).repeat(h)).join`` ``` Based on @Dennis's answer. I guess you could shave off another byte by using a literal FF instead of `\f`, but I doubt I can paste one in here. When trying this out you may also want to use `\u01CA` instead of the `NJ` character. Sadly prepending a space to the character argument costs a whole 6 bytes. [Answer] ## Python 2, ~~838~~ ~~828~~ 618 bytes Saved 210 bytes by using a string instead of an array, thanks to Dennis for that suggestion, I know I can make even better, but for now its a good improvement. ~~This is the best I can do, I'm not very good with graphics in command line.~~ I took the small ghost as base. I'm using the ascii 219 by default, because with that char, the ghost looks pretty awesome!!! ### Golfed ``` def g(c,s,w,h,l=""): x="c-20,c-1,s-18,c-1,c-1,s-7,c-4,s-7,c-1,c-1,s-5,c-8,s-5,c-1,c-1,s-4,c-10,s-4,c-1,c-1,s-3,c-12,s-3,c-1,c-1,s-3,c-12,s-3,c-1,c-1,s-3,c-3,s-2,c-2,s-2,c-3,s-3,c-1,c-1,s-2,c-4,s-2,c-2,s-2,c-4,s-2,c-1,c-1,s-2,c-14,s-2,c-1,c-1,s-2,c-14,s-2,c-1,c-1,s-2,c-2,s-2,c-2,s-2,c-2,s-2,c-2,s-2,c-1,c-1,s-2,c-1,s-1,c-2,s-2,c-2,s-2,c-2,s-1,c-1,s-2,c-1,c-1,s-2,c-14,s-2,c-1,c-1,s-2,c-2,s-1,c-3,s-2,c-3,s-1,c-2,s-2,c-1,c-1,s-2,c-1,s-3,c-2,s-2,c-2,s-3,c-1,s-2,c-1,c-1,s-18,c-1,c-20" for r in x.split(","): d=r.split("-");l+=d[0].replace("s",s).replace("c",c)*int(d[1])*w if len(l)==20*w:print(l+"\n")*h,;l="" ``` ### Try it on [repl.it](https://repl.it/BqbO/2) ### Ungolfed ``` def pacmanGhost(char = "█", sep = " ", width = 1, height = 1): coords = [[[char, 20]], [[char, 1], [sep, 18], [char, 1]],[[char, 1], [sep, 7], [char, 4], [sep, 7], [char, 1]], [[char, 1], [sep, 5], [char, 8], [sep, 5], [char, 1]], [[char, 1], [sep, 4], [char, 10], [sep, 4], [char, 1]], [[char, 1], [sep, 3], [char, 12], [sep, 3], [char, 1]], [[char, 1], [sep, 3], [char, 12], [sep, 3], [char, 1]], [[char, 1], [sep, 3], [char, 3], [sep, 2], [char, 2], [sep, 2], [char, 3], [sep, 3], [char, 1]], [[char, 1], [sep, 2], [char, 4], [sep, 2], [char, 2], [sep, 2], [char, 4], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 14], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 14], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 2], [sep, 2], [char, 2], [sep, 2], [char, 2], [sep, 2], [char, 2], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 1], [sep, 1], [char, 2], [sep, 2], [char, 2], [sep, 2], [char, 2], [sep, 1], [char, 1], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 14], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 2], [sep, 1], [char, 3], [sep, 2], [char, 3], [sep, 1], [char, 2], [sep, 2], [char, 1]], [[char, 1], [sep, 2], [char, 1], [sep, 3], [char, 2], [sep, 2], [char, 2], [sep, 3], [char, 1], [sep, 2], [char, 1]], [[char, 1], [sep, 18], [char, 1]], [[char, 20]]] for coord in coords: line = "" for element in coord: line = "{}{}".format(line, element[0] * element[1] * width) for i in range(height): print(line) return ``` ### Test [![enter image description here](https://i.stack.imgur.com/hNO30.png)](https://i.stack.imgur.com/hNO30.png) [Answer] # Python 2, 244 bytes ``` p,w,h=raw_input().split() for i in range(18): mystr=''.join([(p if i=='1'else' ')*int(w)for i in str(10+(i%17==0))+format(ord('\xff\x00\x03\x0f\x1f??9y\x7f\x7ffY\x7fnF\x00\xff'[i]),'08b')]);print'\n'.join([mystr+mystr[::-1]for j in[1]*int(h)]) ``` [Answer] # Python 2, 169 bytes ``` def a(s,x,y): z=[] for c in u'\u01df #/?\x1f\x1f\x19Y__Fy_Nf \u01df': b="".join((s if d=="1"else" ")*x for d in bin(ord(c)^544)[2:]);z+=[b+b[::-1]]*y print"\n".join(z) ``` [Try it online!](https://tio.run/##LczPC4IwHAXws/4VXyaxrdaPiR1ajG4du8dc4pojI2aogfrPr6IODx68x@c59rfGpyHYykFJOjawkYo4mqTSceSaFq5Qe3jh/LXh1kGyPuQDd//szkVxHIuTg9@MhZEIre5N7QnpoHZgpUQcVY@uQoDofIAvab@k@Xya1pIrvWyzjKpUaLqfFlKZhVFCLLnW8zGOnm3te5T7vzrRUBKcYMYZp/GnzjDLWEpDeAM "Python 2 – Try It Online") ## Explanation: ``` u'\u01df #/?\x1f\x1f\x19Y__Fy_Nf \u01df' ``` As in [Dennis](https://codegolf.stackexchange.com/a/73992/73368)'s answer, each character in this string represents the binary representation of one line of the left half of the "image", XOR 544. ``` for c in <unicode string>: ``` For each character in the string, do the following: ``` bin(ord(c)^544) ``` Transform the character into its integer representation, then perform a binary XOR with 544. Then transform this integer into a character string of its binary representation, like '0xb1111111111'. ``` for d in <string>[2:] ``` For each character in the sting, starting at position 2 (which skips the 0b at the beginning), do the following: ``` (s if d=="1"else" ")*x ``` If the character == "1", replace it with the supplied character, otherwise replace it with a space. Then copy this character x times. (x=0 will result in an empty string.) ``` b="".join(<previously generated list of strings>) ``` Concatenate all strings into one long string, separated by an empty string "". ``` z+=[b+b[::-1]]*y ``` make a string of b + the reverse of b, then create an array containing y instances of this string (y=0 will produce an empty list []), then append this list to the list z. ``` print"\n".join(z) ``` Finally, print to screen each of the produced strings, separated by line breaks. [Answer] Added some text color using [ASCII Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code) to match the original image. # C (msvc), 468 bytes ``` #include <stdio.h> main(){char*i[]={"2B14B2B","2B5B4C5B2B","2B3B8C3B2B","2B2B10C2B2B","2B1B12C1B2B","2B1B12C1B2B","2B1B3C2W2C2W3C1B2B","2B4C2W2C2W4C2B","2B14C2B","2B14C2B","2B2C2W2C2W2C2W2C2B","2B1C1W2C2W2C2W2C1W1C2B","2B14C2B","2B2C1B3C2B3C1B2C2B","2B1C3B2C2B2C3B1C2B","2B14B2B"};for(int y=0;y<16;y++,puts("\x1b[0m")){for(char*p=i[y];*p;){int n=strtol(p,&p,10);char c=*p++;char*color=(c=='B')?"\x1b[40m":(c=='C')?"\x1b[44m":(c=='W')?"\x1b[47m":"\x1b[0m";printf("%s%*s",color,n*2,"");}}} ``` [Try it online!](https://godbolt.org/z/6be79Kv53) # Output Windows Command Prompt: [![enter image description here](https://i.stack.imgur.com/Yb9Z7.png)](https://i.stack.imgur.com/Yb9Z7.png) ]
[Question] [ Sometimes I make bad jokes... And a bad joke I like to make involves interpreting exclamation marks in sentences as the factorial sign. # Task Your task is to write a program that receives a sentence and applies the factorial joke to the sentence. The "factorial joke" consists of looking for exclamation marks "!" and doing the factorial of whatever is to the left of it. If the thing to the left is an integer, then the usual factorial is used. If the thing to the left is a word (a sequence of characters in `[a-zA-Z]`, delimited by spaces), then we want to concatenate all of the subsequent prefixes of the word. E.g. if the word was `abcd` then `abcd! = abcdabcaba`. **However**, there is an exception, which is when the sentence contains a "1!" or "2!", because `1! = 1` and `2! = 2` and the joke doesn't really work. In these cases, your program can do whatever it wants EXCEPT applying the factorial joke or returning the same sentence. # Input A sentence with characters in the range `[a-zA-Z0-9 !]` with the restriction that only one exclamation mark "!" is present and to the right of an integer or a "word". This means you don't have to worry with things as `"abc4!"` as a word here is defined as a sequence of *alphabetical* characters delimited by spaces. # Output The same sentence, but with the factorial joke applied to the word or integer on the left of the exclamation mark. # Test cases You can find a [Python reference implementation](https://tio.run/##hVNNj5swEL3zKx5cFpQPhaRSq0jZWw8rVb20ag8IbRwYgrPERrZZkq72t6fjkKRRVamCA543896b8dAeXa3V4lNrTie5b7Vx2AtXB0FJFXb6hWKbLANAlgesYKdSlXSIozBKOGidMM4@C8cQJ3Ckr2VDsNkNyRGuEPEjVHmX/7jCzNPec0xWSAPP4YX@MGCEdMnsOUP8OnMcCqUXVS7uk2A4VxySCnE6xjwZcgBDrjMKUce@K6mojIbsShTete912hpdxplCpQ2UpzBCbcnzyFGa5ElwR2Sz5c3ZKM3ZnHUm9myJ/87Y6Chd5l6EDgW1Dj9E09FnY7QZPCnqLSs/PEx3Wqq4z5Yq/1u6IQaS8Ww8SZP/yJ/p7pRPjqzzAhnXRT8JjbYOribfa1FjAacxC6Oxh7UR2OhG2Mt5K185j/Dhcn5CL5SjEvMQV2w@QF/IobPYdLIpIWCV7vdCXepYVhiWFo6woUJ0liAdpEUr2E368cavVXNELZhaK/pHNL3GVGGolJuGQjwNkKJXMrBEipeL11iqLRr54pUuLmreHsHoXvzyYKFLwlY3FYpaNDzjLfFg2JS89v9N85TUEX6GKISlK/C9Jjv0xDfdcfERu853cvX3VfOopAv9pM2QmS6igBehNX5Lo/V6zf@Mv@czOV/1@aL8TgwZVfTmI@@YPOLt/Of5Y/LOVfcUp98) here ``` We lost the match 3 to 0! -> We lost the match 3 to 1 ora bolas! -> ora bolasbolabolbob give me 4! -> give me 24 I wanted 2! give me 2 -> undefined Let us build a snowman! -> Let us build a snowmansnowmasnowmsnowsnosns We are late because it is past 17! -> We are late because it is past 355687428096000 I only have one! -> I only have oneono I only have 1! -> undefined Incredible! I have never seen anything like it -> IncredibleIncrediblIncredibIncrediIncredIncreIncrIncInI I have never seen anything like it What an amazing code golf challenge this is! -> What an amazing code golf challenge this isi So many test cases! -> So many test casescasecascac These are actually just 11! -> These are actually just 39916800 No wait! there are 13 -> No waitwaiwaw there are 13 ``` --- 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] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ ~~22~~ ~~26~~ ~~25~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ð¡εD'!åi¨ÐaiηRJë2Lså+!]ðý ``` +4 bytes for two bug-fixes (+1 in case the input is without spaces; +3 for `0!`) -5 bytes thanks to *@Grimmy*. Outputs `2`/`3` for `1!`/`2!` respectively. [Try it online](https://tio.run/##ATwAw/9vc2FiaWX//8OwwqHOtUQnIcOlacKoRCFzPs63UkpNXcOww73//0kgd2FudGVkIDAhIGdpdmUgbWUgMiE) or [verify all test cases](https://tio.run/##XY89TsNAFISvMt6GxkL5QaIjTRojaABBgVI82w/vwmYXedeJzAE4ADegQKJMg6ho4j6H4CJm11Eayvnez8xYR7niftXOBH5f3yBm7Vz03Wb7vvuaHyXdh9p@zhN3tvu@Or9cdJvupxfHt2l/L@4Y2joPLxlL8oXEFN5ilIhU2JqQW00uikqtwgbjJIoMazKeS0wSHAaTwC/Yo3HIG6VLEJyx6yWZeBF8qA5e5BmZh3J4pmA7Pt2/s0a3kBQ@WcP/0XgApqi5VLnmBNmeG15xDcdsQKb1UpkKWj0xlI@OknzgoCW9xElhS0Zl9QMKSVqzqTi0DkHU0O/ahv6mhecQqyDHA72R7PbJqfBNOGvx2MTcQ6a4m2AqUojRQYvFHw). **Explanation:** ``` ð¡ # Split the (implicit) input-string on spaces # (NOTE: `#` cannot be used here if the input doesn't contain spaces) ε # Map each part to: D # Duplicate it '!åi '# If it contains a "!": ¨ # Remove the last character (the "!") D # Duplicate it ! # Take the factorial of it (strings remain the same) s # Swap to get the duplicate value again > # Increase it by 1 (strings remain the same) η # Get the prefixes of this string/integer R # Reverse it J # And join them together to a single string M # And then push the largest value on the stack # (which is either the factorial-integer; # or the integer+1 if it was 0, 1, or 2; # otherwise it's the longest string, which is the joined prefixes) ] # Close both the map and if-statement ðý # And join everything with space delimiter again # (after which the result is output implicitly) ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~222~~ \$\cdots\$ ~~178~~ 176 bytes Saved 2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!! Added ~~2~~ 3 bytes to fix bugs. Saved 5 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` lambda j:(g:=re.match(r"(.*)\b(\w+)!(.*)",j).group)(1)+(str(math.perm(int(f)))*-~(f in'1 2')if(f:=g(2))[0]<':'else''.join(f[:i]for i in range(len(f),0,-1)))+g(3) import math,re ``` [Try it online!](https://tio.run/##lVPBbtswDL3nKxhfLLVuYCdpmxrzLgMGBNhtBXZIepAd2lbmSIYkt8iC7tcz2mqyDW2B7SCK4iOfRIps967WarZozbHM1sdG7PKNgG3KqjQzONkJV9TMBGxywdc5Wz9d8nGvB9GWTyqju5azhF8y6wwj33rSotkxqRwrOecXVz9ZCVKFCUxDLktWplnFppyv4ocPYRpiYzEMJ1stFStXqXwotQFJAWCEqpA1SHYexdFVQmyXFZvxkdy12jjoL4sMHk12uDcdpl2w7qa3ySyI4LMg2hfD/FPwPHJonYUM2IgF3xAabR24GmFIDmbgNMRjCnwPTAIeUag2AnLdCDv4nk@9oJXr3LtV8pGiEeaD2@k0nXt0CU9COdzAdAxnrHf8DUz/AIaYL@igs5B3stmAAKv0006ogf5tyG@D7AUtq6znohSFoTSFwwikA2mhFZRycnuqwJvw7Pr6ZnE7ny7iu5s4jk@5aNXsoRb0Wq1w7NP4y6aVfu2bvPJMXkq8VIXBjcwbHMPSQwof0YBFVCAUNatUFTTyO9LrBpZzxFk7KS@73wbZC1pLtfwXdl@vWjiCQOzEjx4s9Aah0k0JRS0aatAKqV2oTNK3xX/4S3/DV029pvbQdykUwqInem3uBa1CFD7wvkbrv0sUriPyPWy7/it9fd@DZ3d3yc3C/yEf9RPnIuxnbhiTdARgs5I5TkprhkkOg4N7DuDqIwQHS8rBrGyW4cNzyI@/AA "Python 3.8 (pre-release) – Try It Online") Replaces `1!` with `11` and `2!` with `22`. ### Ungolfed: ``` import math,re def f(j): m=re.match(r"(.*)\b(\w+)!(.*)" ,j) f=m.group(2) if f in ('1','2'):f='' if re.match(r"\d+",f): f=str(math.factorial(int(f))) else: f=''.join(f[:i] for i in range(len(f),0,-1)) return m.group(1)+f+m.group(3) ``` [Answer] # JavaScript (ES6), ~~86 85~~ 80 bytes Replaces `1!` and `2!` with `0` ... ¯\\_(ツ)\_/¯ ``` s=>s.replace(/\w+!/,g=s=>(s=s.slice(0,-1))?1/s?'1006'[s]||s*g(s-1+'#'):s+g(s):s) ``` [Try it online!](https://tio.run/##jVNNj9pADD23v8LZHkjKVwIsC5XonpF6a6Uetj04E5PMdphB8QREtf@ddaCwbNitiGQ78bxnx87LI66RValXvmtdRrvFbMezr9wraWVQUdj/tWkH/U4@k2zIM@6x0ZKOO90kiu6TPt@3kjgetx7499MTf85D7ibt1qdW9IXb8iAh2iln2RnqGZeHi/DGlQipM8jBTRR92F/9PpyytRNLXfqxQcz1mmBJMHpFPGYHoyZ@Dhu0njIYBC@oI1WYlc1ooS1lTeI38lAxpJU2GSCwdZsl2mNXYb4NOIS9r50YW27W/kmAJYFBTx3QHjTDCtlDcndW/z3Q8PZ2PLkbDSbxdBzH8eXAzpotFCizOkvB2ayNI2fd/8hJcM2a5laVlOnUUCD190RLayqBiSyg3fpC2xyM/kMyRF2xfpET6XR3vPkXD2Hvayc2t/MrGlxsukAvIMAl/q1hSvQNuTMLUAUaQzYnkAIs2z2MWy/@eo5u9vvuQESwBU/ypRQy8fkWL09rJ6ZQNSv9KIgPCkDlK@m7hceq1khyppH3QMPpNBlPLsUhmjJOzn0hPwJ6VcAQvIP4tezegiS7Zw "JavaScript (Node.js) – Try It Online") ### How? Because the callback function of `replace()` is recursive, it's better to feed it with a single variable \$s\$ to keep the recursive calls short. That's why the `!` is captured along with the word preceding it. The same `slice(0,-1)` is used to remove the `!` on the first iteration and to build the prefixes in case of a string. In order to make the factorial computation compatible with that method, we just have to pad the recursive argument with a random character which is immediately removed by the next iteration. To deal with the weird edge cases \$1!\$ and \$2!\$, we use the small lookup string `'1006'` to stop the recursion whenever the value is less than or equal to \$3\$. This way, we have \$0!=1\$, \$3!=6\$ and \$n! = 6\cdot\prod\_{k=4}^{n}k\$ for \$n>3\$, but \$1!=2!=0\$ (sic). ### Commented *NB: alternate slash symbols used in the regular expression to prevent the syntax highlighting from being broken* ``` s => // s = input string s.replace( // find in s ⁄\w+!⁄, // a word followed by a '!' g = s => // g is a recursive function computing the replacement (s = s.slice(0, -1)) // remove the last character from s // (for the 1st iteration, it removes the '!') ? // if the resulting string is not empty: 1 / s ? // if this is a numeric value: '1006'[s] // 0 -> 1, 1 -> 0, 2 -> 0, 3 -> 6 || s * // for all other values, multiply s by g(s - 1 + '#') // the result of a recursive call with s - 1, // padded with a '#' for the next slice() : // else (s is a string): s + // append s g(s) // append the result of a recursive call : // else (s is empty): s // stop recursion ) // end of replace() ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~157~~ 155 bytes Thanks to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) for -2 bytes. ``` (*s,w),b=map(str.split,input().split('!')) w*=1+(w in'1 2') if'A'>w: i=int(w);w=1 while i:w*=i;i-=1 else: d=w[:-1] while d:w+=d;d=d[:-1] print(*s,w,*b) ``` [Try it online!](https://tio.run/##VZFBa9wwEIXv@hXPe7G9cUq9KRR2caGHFAKFHhrIofQwtidrNVrJSHJU989vRzU59CTm0@jNe5p5jZOzd9fBjYwOu93uWu1Dk@qm7y40VyH6d2E2Ojbazkus6q2qyqKsa5X2XXtTJWhbtjiUtdLP5efyUzoq6E7bWKX6lLpWIU3aMPRRHuiTvhXEJrC0jV36cbxtf761jMd0042nsRs3PPsskx01@76@ij@lts5Hv2QBRL/mA@DfPFQ5R61yMfAccf/ty733zm8dvWd6uT4xjAsRcWJcKA4T7hAd3hfKeULvDIVCnfWr3DI@FOoBiWzkEYcCb/igvnLEEtAv2owgBOvShWyhRJ28TKDIDXSEDphJprUfs5KzZsVEIuIs/w9aKe3gedS94QIPG7X8yh6B2YKs7ErbM4x@kb@M6mmiKBR0oT@Z/9vh2ZlnDBMZw/bMElIMaAn03UlYuyKymBkosLDHicNml4a4yJMVv5bstS3@Ag "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 173 bytes ``` StringRiffle[""<>If[Last@#=="!",If[NumberQ[n=ToExpression[""<>#]],If[n>0&&n<3&&First@#!="0","",ToString@n],Rest@NestList[Most,#,Length@#-1]],#]&/@Characters/@StringSplit@#]& ``` [Try it online!](https://tio.run/##bY09a8MwEIb3/gr7BJpU4jRrFASlhYIb2iSb0KCEsyywpSBdS/@9qjRDFy8H73Pvx2xpxNmSv9jiZDlS8sEd/DBMqAG2u7dB9zaTYlJCC6LK/dd8xvSpgzzFl59rwpx9DH9mZszNEXYd52G74fzVp1u2ldCBABCneB9QwYgD1te@nt5n0u8xk2Cix@BoVOxxXauY4Sv1PNpkL4Qpr9Q9fLxOvpYaXj6qpEY5DTHZ5hwnm1swD//Y@W9sZmy6Zbxexk/LeFNxKb8 "Wolfram Language (Mathematica) – Try It Online") *-2 bytes from @Kevin Cruijssen* [Answer] # [Perl 5](https://www.perl.org/) `-p -MList::Util=product`, 93 bytes ``` s/(\d+)!/$1?$1>2?product 1..$1:'':1/e;s%(\w+)!%join'',map{substr$1,0,$_}reverse 1..length$1%e ``` [Try it online!](https://tio.run/##dY8xT8MwEIX3/IqL5ChFJE0dyhJEOyPBiFgqIbs@EiPXtuxLOyD@OiapgE4M93Tv3veG8xjMbUqxWezU9VXeML5lfNNufXBq3BPw5ZLxriw73uBdLBa700QV707bsqwOwn/EUUYKjFerir1@BjxiiDjXDNqeBsYLTOkFwbhIQAPCQdB@gBsgB6sc6g38E/LMBQHSGRHP2J@bZRrpZNbr49RBWJ@JX9euswc4CUuooM0v55kZrcI3bVF9OU/a2ZjqJ6l7bWlaHnWkrnsmbe5//k@1N98 "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 21 bytes ``` ;”ḟV$¹ƤṖṚƊfØD$?ċ¡€”!K ``` [Try it online!](https://tio.run/##VY8xSwNBEIX7@xVvIa1gomAR0MYmaKcYLOfuxruNm1253Us4K7EJaC8iigiWVmKRYJdI/sflj8Q5goXlfPPmzXsDNqZar7urm5d6@nrWms@W7/XsoZ49Le8uFo@HrYOf@/nb6vZDBOqo0T1jax8ydevp52LSiurvr8VEBOfrdZ9hnA8IOWNIIcmxg@CwrSJXEGJnyKso0yPZMnZV1MOYbOAUHYU/3ImOOaD0iEttUhC8deMhWRWJOxXygQIj5oRKz9AB2uOK5Gl7rzF01lTISbyc5f@gLaNNCk51bFiht6GWR1zAM1uQrUKubQajLxvrqJ9TEAoa0nXDE5cyMmcukORkDNuMpasE0NLrxElnWyGwhEnIs7DTnP0mNSWhlJMKg7LJ2la/ "Jelly – Try It Online") A full program taking a list of words and printing a string. For the 1 and 2 cases the 1 and 2 are dropped from the output. Saved a byte now that a list of words is permitted input. ## Explanation ``` Ḳ | Split at spaces ċ¡€”! | For each word, if it contains a ! then do the following: fØD$? | - If any characters are left after restricting to digits: $ | - Then: ;”ḟ | - Append ḟ (which will filter out 1 and 2 at the next step because x! == x) V | - Evaluate (i.e. calculate the factorial and then filter out the input number) Ɗ | - Else: ¹Ƥ | - Prefixes Ṗ | - Remove last Ṛ | - Reverse K | Finally, join with spaces ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 70 bytes ``` ' %/!$/&/^[012]!$/(`.. $.(*__ /\D./(^`. $` .+ * _ $.>`$* ~`^ ^.$*¶$$.( ``` [Try it online!](https://tio.run/##jVFLbttADN3PKWhAaQy31cdxHHuTVYFCQHcNkEVaW5TEWNOOOYVmlMBZ5Fg9QC/mcKTGRZIGyIKPnMdHiiJb8pox2x@NPxf7YzhKRlHyLlldpdn0u4TjIo5VFI8n67VKvn2Kk/GqEKJQ8Xs1UWtJnRfRRN0XK7WKo8mf35GI93vbIpTWoBvBx3M4vAKIlbZUG31DsCWY9YrH13SmcrhF9lTDdPSPDpqOa7rWTLX6Qh46B2WnTQ0Iju3tFrlv9P/U4HoMIObYqUsCbAkMevoA2oN28Audh@ysb/Va@uT0dL44m00X6XKepqkMbNnsoEGZ1TL1tc84y/aJLBs9/aGcq5ZqXRqpzgcJ0w214IgYkHe@0bwBo39SmCR84FBxiB6Dv35wPQYQyzl/Q3d12aAXFnCLd4GvbE2wseYaqgaNId4QSIWThQx7erteq68W5B478CSbrNDR0OMlHUCswkpdNOSGW2DlO2m5gx9duNOwxtfSJ8tlNl@k6QM "Retina – Try It Online") Link includes test cases. Explanation: ``` ' % ``` Split the input into words. ``` /!$/& ``` Only process words that end in `!`. ``` /^[012]!$/(` ``` If this is `0!`, `1!` or `2!`... ``` .. $.(*__ ``` ... then return the incremented digit. (Approach shamelessly stolen from @Arnauld.) ``` /\D./( ``` If the word contains a non-digit (excluding the trailing `!`)... ``` ^`. $` ``` ... then replace it with all of its prefixes in reverse order. (Note that these are exclusive prefixes so that the empty prefix is included but the string including the `!` is excluded.) ``` .+ * _ $.>`$* ~`^ ^.$*$n$$.( ``` Otherwise compute the factorial. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 206 bytes ``` D =84 ** 9 INPUT ARB . L SPAN(&UCASE &LCASE D) . W '!' REM . R W SPAN(D) :F(S) N =W + 1 LT(W,3) :S(O) N =W F W =W - 1 GT(W,1) :F(O) N =N * W :(F) S N =N W W ARB . W RPOS(1) :S(S) O OUTPUT =L N R END ``` [Try it online!](https://tio.run/##LY65DoMwEETr9VcMDdjkkBAUCRIFZxSJ2MgGuU8dhSL/L7Ic1R5vZ2d@3/k9f7JloQbFLUMc4y7oqYdpRGkrXNHDDaWW4VSXrkXYb6VRTDyiIIJtX9xbQX4/ZER5J50SpFF4nJBQP0p/ThXlTppjLzoWML4wfqw4UavswBoxPOWyU8Lts18N9kQedjBOJts/9jFkpnENXPTQnKTVzbKUFdIAdfMH "SNOBOL4 (CSNOBOL4) – Try It Online") `84 ** 9 = 208215748530929664` which has all the digits from 0-9. ``` D =84 ** 9 ;* D contains every decimal digit. INPUT ARB . L SPAN(&UCASE &LCASE D) . W '!' REM . R ;* split the input into an ARBitrary Left part, the Word followed by a '!' and the REMainder to the Right part. W SPAN(D) :F(S) ;* if W has digits, goto S N =W + 1 LT(W,3) :S(O) ;* if W < 3, then N = W + 1 and goto O N =W ;* set N = W F W =W - 1 GT(W,1) :F(O) ;* decrement W, and goto O if W == 0 N =N * W :(F) ;* N = N * W, goto F S N =N W ;* W is a string, so set N = N W W ARB . W RPOS(1) :S(S) ;* set W to W excluding its final character and if W had any characters, goto S O OUTPUT =L N R ;* output Left, the New middle, and the Right string. END ``` [Answer] # [Red](http://www.red-lang.org), ~~242~~ ~~225~~ 204 bytes ``` func[s][c: charset[#"0"-#"z"]parse s[any[change[copy t any c"!"]( case[find"12"t[0]t <"A"[t: to 1 t p: 1 while[t > 1][p: p * t t: t - 1]p]t >":"[p: copy t until[take/last p append t p p =""]t]])| skip]]s] ``` [Try it online!](https://tio.run/##RVBNT8MwDL33V7x5F0CaWAenCiZxROIESByiHLLWXcu6JGpcpiH@e3G1DRJFkd6H/eyeq/GVK2OzuhjrwZcmWVMWKBvXJxYzpyUt5vRNNk4AknH@aJT1WzZliEcIFEFJM7JXWekSm7r1FeUrErO0ggd6IiMFJCBXcSz0OzRtx0awRm6NIhE3kGwSYaFQVNuaCpqoc4/BS9sZcTu@7VzSMnAxsq@minofiaxYe/2DtGujtcmOdejZlQ0STAY99MHoglqlYeydKHU3hVrO6MSH3mETtPoF2LZfqmTcX4BnHJwXrrCa4UKuztwLa8iEzdB2FRySD4e98//O4LsjGqem4PkCvwVNotsT1lzT7v56vzes23a9vlIG16n5c1BRnqvCniaKfevF6Jx7HZIWa0KNZDM7/gI "Red – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~205~~ ~~201~~ ~~194~~ 189 bytes ``` s=scan(,'');l=grepl('\\w!',s);w=s[l];n=nchar;k=function(m,x)substr(x,1,n(x)-m);w=k(1,w);b=as.numeric(w);o=`if`(is.na(b),Reduce(paste0,sapply(0:n(w)-1,k,w)),gamma(b+1));s[l]=o;if(o!=w)cat(s) ``` [Try it online!](https://tio.run/##FY5LbsMwDESvYq9MokwRbyvoBl112xQIrcipYH0MUYLc07vKcgbvDSafp2gxHIGmCZXXz2x3D9Pt1saJBFXT8u1/VNTR/HJWm15rNMWlCIEOlLpIyXDQTBEOvISXsMFMDdWiWd5jDTY7Az0nfXfrHVwvGRakL/uoxsLOUuyVhPfd/8H1I3b2MtPWJ5CeHEKH32ZE9fqhk3IrpFE3NFxA8Py0ZagyLNX5x8CDxNQCx/H8Bw "R – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~88 85~~ 83 bytes ``` ->s{s.sub(/\S+!/){|z|z<?1?1:z>?9?z.chars.map{z=z.chop}*'':eval([6,*4..z.to_i]*?*)}} ``` [Try it online!](https://tio.run/##ZcjNDoIgAADge0@BXlQqjHJtuZSH6GiuQcNy08Eg3QJ5dvq5cvw@NbG37yq/rbXVSE8sza@XdZRndjGLORNMcGlqciIG3Z9UaTRSaU31k5AOJknJZzqkzXEDC4QMeolb30ICM@e8BF0TC0UBEwPVUdyu/vPoZw5GDopgcDD7YA7B7L7jPw "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḲṖVN!Ƒ¡!ƲṖƤṚ$<”AẠ$?¹ċ?€”!K ``` A full program accepting a string which prints the result. **[Try it online!](https://tio.run/##y0rNyan8///hjk0Pd04L81M8NvHQQsVjIM6xJQ93zlKxedQw1/HhrgUq9od2Hum2f9S0Biig6P3//39PhfLEvJLUFAUjRYX0zLJUhdxUBSMA "Jelly – Try It Online")** Kind of a tough one for Jelly. ### How? ``` ḲṖVN!Ƒ¡!ƲṖƤṚ$<”AẠ$?¹ċ?€”!K - Link: list of characters, s Ḳ - split at space characters -> words ”! - literal '!' character € - for each word: ? - if... ċ - ...condition: count (i.e. contains?) ? - ...then: if... $ - ...condition: last two links as a monad: < - less than: ”A - literal 'A' character Ạ - all? Ʋ - ...then: last four links as a monad: Ṗ - pop (remove the '!') V - evaluate as Jelly code (get an integer) ¡ - repeat... Ƒ - ...number of times: is invariant under?: ! - factorial N - ...action: negate (i.e. 1;2;X -> -1;-2;X) ! - factorial (-1! = -2! = inf) $ - ...else: last two links as a monad: Ƥ - for prefixes: Ṗ - pop (remove the `!` from each prefix) Ṛ - reverse ¹ - ...else: no-op K - join with spaces - implicit, smashing print ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 23 bytes ``` wm??öΣ↔ḣhȯs§Y→ΠiV√I€'!w ``` [Try it online!](https://tio.run/##VY8xTsNAEEV7n@JvRUsCEmVqS3QgIsqxPXiXrHeRdx3LdKSIqBEVFVIKGiS6iDo0VLkDvogZK6KgnDeaN//rJiyGql897LZDW81mX9v9pl8//3xu9PdH2L1d9@un/au56h9f0n71fqTaYRjmDOtDRNSMimKucYLocawSXxMybymopDRL2TJOVZKiJRe5wFThD0@Tc45oArLG2AKE4HxbkVOJ2KmWDxQZGefUBIaJMAF3JE8nZ6PQO9tBk7i84/9gIqPLay5MZlkhPVDHS64RmB3IdVEbV8KaxahO5pqiUFBF9yPPfcEovb1BrsladiVLVwlgpNeFl86uQ2QJk1NgYZeawyE15bGRkw63zZh1on4B "Husk – Try It Online") Maps 1 to 2 and 2 to 3. On my phone, so writing an explanation is not too easy, but I'll try. Code with parentheses for "clarity": ``` wm(?(?(Σ↔ḣh)(s§Y→Πi)(V√))(I)(€'!))w ``` The main part of the code is built by conditionals, they may be a bit easier to read once you know that in Husk `?abc` means `if c then a else b`. Also, most of the time `fg` is the composition of functions `f` and `g`, so we are actually applying `g` before `f` (to oversimplify it, you should read the code backwards) A pseudocode for this could be: ``` Split input into words, map the following function to each word and then join them again. If word contains '!': if any character of the word is a letter: get the head of the word (drop final '!') get the list of prefixes (heads) reverse it join prefixes in a single word else: convert word to integer get the maximum between: successor factorial convert it back to string else apply Identity function (do nothing) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` ≔⌕θ!η≔⊟⌕A⁺ …θη ζ…θζ≔✂θζη¹ε≡ε2¹1¹0¦1¿ΣεIΠ…·¹Iε⭆ε…ε⁻Lεκ✂θ⊕η ``` [Try it online!](https://tio.run/##bVBLasMwEN37FBOtxuBC3GWyCoZCIQETn0CVJ5aoLCeWlNCUnt0df0hbqDaD3m94o7TsVSftMOy8N43DF@NqvGQgViLNQKfbZCHK7jyRO2uxtNGjAJFB8aEsFZq5y6hmC8PjuLOz7I0L@EdyT38SK2sUTSBbM8jZRcz6mwlKA1IKn4mSnkA8iw3MYTkLZiz/B1s/MKYZrekkow0bMCfAKracmS6CQvqAZd/VUQV8dYobmSsdpWsIc@410qzmtwWyHD7bqsCjOcgz0u/y/DkYx0fZk2uCZmcG75M5@VrO8GjLy3pqyQWqUY@SYdhTgOjhLRpbgwTvulsr3SoZnq72Gw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⌕θ!η ``` Find the position of the `!`. ``` ≔⊟⌕A⁺ …θη ζ ``` Find the position of the start of the word ending in `!`. ``` …θζ ``` Print the prefix of the input before the word. ``` ≔✂θζη¹ε≡ε ``` Extract the word and switch on it. ``` 2¹1¹0¦1 ``` If it's `2` or `1` then output a `-`, otherwise if it's a `0` then outputs `1`, otherwise... ``` ¿ΣεIΠ…·¹Iε ``` ... if it's an integer then output its factorial, otherwise... ``` ⭆ε…ε⁻Lεκ ``` ... output its prefixes in reverse order. (These are inclusive prefixes, so they include the word itself but not the empty string.) ``` ✂θ⊕η ``` Print the suffix of the input after the `!`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Well, this is just god-awful but I've spent far too long on it to *not* post it. Kids, let this be a warning against trying to golf without your full faculties about you! ``` r"(%w+)!"Ï<3?°Y:Yn ʪYå+ Ôq ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIoJXcrKSEizzwzP7BZOlluIMqqWeUrINRx&input=WyJhYmNkISIsIldlIGxvc3QgdGhlIG1hdGNoIDMgdG8gMCEiLCJvcmEgYm9sYXMhIiwiZ2l2ZSBtZSA0ISIsIkkgd2FudGVkIDIhIGdpdmUgbWUgMiIsIkxldCB1cyBidWlsZCBhIHNub3dtYW4hIiwiV2UgYXJlIGxhdGUgSXQgaXMgcGFzdCAxNyEiLCJJIG9ubHkgaGF2ZSBvbmUhIiwiSSBvbmx5IGhhdmUgMSEiLCJJbmNyZWRpYmxlISBJIGhhdmUgbmV2ZXIgc2VlbiBhbnl0aGluZyBsaWtlIGl0IiwiV2hhdCBhbiBhbWF6aW5nIGNvZGUgZ29sZiBjaGFsbGVuZ2UgdGhpcyBpcyEiLCJTbyBtYW55IHRlc3QgY2FzZXMhIiwiVGhlc2UgYXJlIGFjdHVhbGx5IGp1c3QgMTEhIiwidGVzdCEgMyIsICIwISIsInRlc3QiXQotbVI) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ ~~22~~ 26 bytes ``` ð¡εD'!¢i¨D.ïiÐ!Ês!*ëηRJ]ðý ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8IZDC89tdVFXPLQo89AKF73D6zMPT1A83FWsqHV49bntQV6xhzcc3vv/f0lqcYmiAogEAA "05AB1E – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 227 bytes ``` s=>{var w=s.Split("!")[0].Split(" ").Last();if(!int.TryParse(w,out int n))for(;(w=w.Substring(1)).Length!=0;)s=s.Replace("!",w+"!");else{for(int i=n;--i>0;n=n*i);s=s.Replace(w+"!",""+(n<1?1:n>4?n:0));}return s.Replace("!","");} ``` [Try it online!](https://tio.run/##bVLBbtswDL3nK2ifpDUJ4rbAgLpObwMKBMOwFOih6EFRmFibQgUSHSML8u0ZXcfDBuwkkI@Pj3yUTROb3OVLQ/YxcXS0HUP/zmFTXVI1Px1MhLZK0@XeO1Z5luu32fsQQa6nC5NY6dJtVOaIpy/x@M3EhKodh4ZBUkBab0JUpWqrdrpsVr2CKrSQkbZcZ9Ws1ElEvuPeG4udzLi96cRK9AlPHb3r5CoqJxM3n5VU0Seny79JH4Rxnt8oeiyeigea3z/Rw0zr8hyRm0jwr0Au3c@XctRtyFABYfv2fspfEXxIDFwj7AzbGu6AA8yEMQLIQzSwCt6ka7x1B6lDuL/Gz9AaYlzDbQYDdttDC2RoEqwa59dgIFFod4auPJE1UaQNI6zQmiYhONk4wV4MhuLzn/6B/BFqI60D4X@yxZAjG3HtVh4zeO4hwgNGSIgEho5cyxnAu5@d0nWK2rBAYHbmVwfasEbYBr8BWxvv5VooxshQbth/GcQlOgKjTGlNwgF4qTH1OxnLjZCP8KPpNhnm@xrEKsdZ53TsK4u7/FyO5NpobK26w8gf2n98I2AtpNfoGBeOUG1UD8l5L78B "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # C (GCC), 236 bytes ``` i,j;char*a,*b,*c,*d;f(char*s){a=strchr(s,33);for(b=a;b>s&!isspace(b[-1]);--b);for(d=s;d-b;)putchar(*d++);*a=0;if(*b&64)for(c=a;*b;*--c=0)printf("%s",b);else{for(i=j=1;j-atoi(b);)i*=++j;printf("%d",i);}printf("%s",a+1);j>0&j<3&&puts(b);} ``` [Try It Online!](https://tio.run/##Tc5NTsMwEAXgdXMKJxKR7dhVnAKbwV1zAHalC/8k1CEkVSbAourZg0Ohqhe2NP7e0zj55tw8B9GCO5iRG8Gt4E5wDw39nSA7GY3T6A4jRbHZMGiGkVptwG4xTwPi0bia2p1UewZS2gvwGsFLC@z4OS09lPuiYMCNLiE0lNv88Z4t0MUmboFL6XTJjmPop4Zmd5iJ2FR3WJ8WFXSrFbTSTEOg8YMFrouihav3mQgMzrd5UygG7bbM26dNnsc9cEme5yjIhwk9/RqCZ8kpWS0LEtztiSbZc911Q0peapzIer1@7TNIVg1FFp9/qS70IY23qsqrUbeouiCVkoDkPfSeDA35rsPol96YIH8nBqsYPM8/) Explanation: ``` i,j; char*a,*b,*c,*d; f(char*s) { // a is the first '!' in s a=strchr(s,33); // b is the first character after the first whitespace before a, or s if there is no whitespace there for(b=a;b>s&!isspace(b[-1]);--b); // Print each character from s to b for(d=s;d-b;)putchar(*d++); // Null-terminate s at a *a=0; // If b is alphabetic if(*b&64) // While there's anything left of b, print b and shorten it by adding an earlier null terminator for(c=a;*b;*--c=0) printf("%s",b); else { // If b is not alphabetic, it's assumed to be a number. // i is the product of all j-s between 1, and b as a number for(i=j=1;j-atoi(b);)i*=++j; printf("%d",i); } // Print everything after the exclamation mark printf("%s",a+1); // Print the number twice if it's 1 or 2 j>0&j<3&&puts(b); } ``` [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)'s 226 byte version: ``` i,j;char*a,*b,*c,*d;f(char*s){for(b=a=index(s,33);b>s&!isspace(b[-1]);--b);for(d=s;*a=d-b;)putchar(*d++);if(*b&64)for(c=a;*b;*--c=0)printf(b);else{for(i=j=1;j-atoi(b);)i*=++j;printf("%d",i);}printf("%s",a+1);j>0&j<3&&puts(b);} ``` [Try It Online](https://tio.run/##TZDLTsMwEEXX7Vc4kYg8jl3VLbAZ3DUfwK504VfAoSRVHB5S1W8PdgsVXszInnPvHdmKF2unKfAW7asemObMcGY5c9jQ80uEY9MP1CitQuf8N418vQY0m1gVIcaDtp6arZA7QCEMYIadisi0csIgHD7G7EOZq2vA0FBmqvtbyJhVGplBJoRVSzgMoRsbmiz8PvpzaFCtktgKPfYhDyAwVdct/qLljSt5ADxd77HkupaA7WZZtQ/rqkrpMStPUyLIuw4d/eyDg/lxPstrkbjdEUXKR7/f9wV58nEki8XiuStxPmtohNT@SHlB74pU5Wp5ZeR/aHWBZEFCJG/px0jfkC8fBpd9k4L8niRcJeFp@gE) ]
[Question] [ Challenge inspiration was this that I saw somewhere: > > The word "nun" is just the letter **n** doing a cartwheel > > > Your challenge is to take a string and determine if it is the first letter doing a cartwheel. # Rules A string is a letter doing a cartwheel if: * The first letter is the same as the last letter. (The letter can't land on its head.) * The string alternates between cartwheeling letters every one character. The cartwheeling letters are `n` and `u`, `m` and `w`, `b` and `q`. Note that `n` and `w` together are *not* cartwheeling letters, and neither are `w` and `b`. * You will take a string using any of our standard input methods. * You will output a truthy value if the string is a cartwheeling letter, and a falsy value if it is not. Output can be done using any standard output methods. Additional rules: * Only lowercase cartwheel letters `n`/`u`/`m`/`w`/`b`/`q` need to be handled. * You may assume that input is never empty. * A one-character string is not a valid cartwheel. # Test cases ``` Input -> Output nun -> truthy nunun -> truthy nunununu -> falsy wmw -> truthy wmwun -> falsy bqbqbqbqbqb -> truthy v^v^v -> falsy AVAVA -> falsy OOO -> falsy ununununu -> truthy nunwmwnun -> falsy nun unun -> falsy nunwmw -> falsy nnuunnuunnuu -> falsy nwnwnwnwn -> falsy m -> falsy nunuuunun -> falsy ``` # Winner As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code (in each language) wins! [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 30 + 1 `-r` = ~~43~~ 31 bytes *Saved 12 bytes thanks to @Neil by shortening the first line* ``` /nu|wm|qb/!d /^((.).)\1*\2$/!d ``` [Try it online!](https://tio.run/##K05N@f9fP6@0pjy3JqlQXzGFSz9OQ0NPU08zxlArxkgFKPL/v2MYEHL5@/tz5ZXmKZQCCRADDEGM8txyKAWWKYdCrrI4IOQq5wJKgMTBgCupEA654AZxlcLNAyr@l19QkpmfV/xftwgA "sed 4.2.2 – Try It Online") Deletes input if falsey, otherwise does nothing to the input. ### Explanation With the `-r` flag, we do not need to use `\(` and `\)` for capturing groups and this saves bytes. ``` /nu|wm|qb/! # On every line that does not match this regex d # Delete /^((.).)\1*\2$/! # On every line that does not math ^((.).) # the first two characters at the beginning of the line \1* # repeated \2$ # with the first character at the end of the line d # Delete ``` [Answer] ## JavaScript (ES6), ~~82~~ ~~78~~ 77 bytes *Saved 1 byte by using two falsy values, as suggested by ThePirateBay and MD XF.* ``` ([c,...s],S='bqwmun')=>s.reduceRight((r,a)=>r&a==S[S.search(c)^++k&1],k=s>'') ``` ### Test cases ``` let f = ([c,...s],S='bqwmun')=>s.reduceRight((r,a)=>r&a==S[S.search(c)^++k&1],k=s>'') console.log('Truthy ...') console.log(f("nun" )) // -> truthy console.log(f("nunun" )) // -> truthy console.log(f("wmw" )) // -> truthy console.log(f("bqbqbqbqbqb" )) // -> truthy console.log(f("ununununu" )) // -> truthy console.log('Falsy ...') console.log(f("nunununu" )) // -> falsy console.log(f("wmwun" )) // -> falsy console.log(f("v^v^v" )) // -> falsy console.log(f("AVAVA" )) // -> falsy console.log(f("OOO" )) // -> falsy console.log(f("nunwmwnun" )) // -> falsy console.log(f("nun unun" )) // -> falsy console.log(f("nunwmw" )) // -> falsy console.log(f("nnuunnuunnuu")) // -> falsy console.log(f("m" )) // -> falsy ``` [Answer] # [Python 3](https://docs.python.org/3/), 111 bytes *-2 bytes thanks to Mr. Xcoder.* ``` lambda s:s[0]==s[-1]and any(any({*s[::2]}=={i[j]}and{*s[1::2]}=={i[j<1]}for j in[0,1])for i in['nu','mw','bq']) ``` [Try it online!](https://tio.run/##TU1dC4MwDHz3V@Stdjiw25usv6TLoOJklVk/Wici/vbO6DbGkdxdLiTt5B@NPYdSXsNT13mhwWVOpSilU0eB2hag7RRTzQensuyEi5SzURUua0gz8Te8CFzKpocKjFVpIpCTM@SYHVjC6nFteceQB3933oEESixLgGgXI21ttPu8@4Hs67aCxGA/YBhF30ew3c2g7Y31cRkbzsMb "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes ``` lambda s:s[:3]in'ununqbqbwmwm'and s==s[:2]*max(len(s)/2,1)+s[0] ``` [Try it online!](https://tio.run/##dY5NC4JAEIbP7a8YvKyWUtlN8CBRp05ZJ5VYU0lwp9Z1sX69uREWfcx7eZnheZjLrTmd0e0KP@4qxtOMgfRk5C2SEqlChSIVactbThlmIH2/v7nJmLOrWeVoSmvq2nNrIqNZ0jW1yg9HJnMJPkQE@jF6g2GDoU1Kl1Q8oitvhxgkIaRglfzi1UCrT4fQHUWfB36pS2yAOg7stvsVLINwFYLjUFKca9BWKBFeL3pk9CTihtpQmHprvWvWwSb853n79beouwM) [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes ``` lambda n:''.join(sorted({*n[1::2]}|{*n[::2]}))in"nu,mw,bq"*(n==n[::-1]) ``` [Try it online!](https://tio.run/##TY7dCoJAEIXvfYrBm92VNbDuFjboCbzrxgwUlTZy/NtNonp22zUjOQznG4Y5M@1DXxrcTZU8TbeszosMUBCyuTYK6dD0uizoM8AkEmKbvl8OZ2JMoY@G1yPPOz@gKKWbhFHKJl0OegAJCUGDhIOzFVg5Hutxse8s7xa55n62cnA4WjmI49iZWUdYt@v/bFjdWeIRjfkVST3Pq5oeFCiE@UsBba9QU8VJuCe8ooqx6QM "Python 3 – Try It Online") *-1 thanks to @HyperNeutrino and **-13** thanks to @ovs* If the above is found to fail for any test case, there is an alternative: ``` lambda n:(sorted(list({*n[1::2]}.union({*n[::2]})))in[[*'nu'],[*'mw'],[*'bq']])*n[0]==n[-1] ``` [Try it online!](https://tio.run/##TY7LCoMwEEX3fsXskoiW2u4EC/0Cd92kKSgqDdTxlVRK6bfbifYhl3DuPLiT9mGuDe6nKjlPt6zOiwww5kPTm7LgNz0Y/vRRRnG8U6@NRd3g3JhrIYRGKX2GlqmAWI8L844pJWhtq5IEZRipyZSDGSABScvIAnBYGZLzIyUsWGZ595Mr7xeSM8cTyZk0TR3sOoRIAf90WF36HEC09vuY8jyvanrQoBHmf8bQ9hoN1wELDyyouBZiegM "Python 3 – Try It Online") --- # Explanation * `''.join(sorted(list({*n[1::2]}).union({*n[::2]}))))` - Gets the characters at odd indexes and the characters at even indexes, de-duplicates them and sorts the list formed by their union. * `in'nu,mw,bq'` - Checks if they are valid cart-letter combinations. * `n[0]==n[-1]` - Checks if the first character is the same as the last one. [Answer] # JavaScript (ES6), 40 bytes ``` s=>/^(nu|un|bq|qb|wm|mw)+$/.test(s+s[1]) ``` Checks to see if the input string concatenated with the second character of the input string is a repeating string of the same pair of cartwheel characters. Tests: ``` [ "nun", "nunun", "nunununu", "wmw", "wmwun", "bqbqbqbqbqb", "v^v^v", "AVAVA", "OOO", "ununununu", "nunwmwnun", "nun unun", "nunwmw", "nnuunnuunnuu", "nwnwnwnwn", "m", "nunuuunun" ].forEach( x=>console.log( x, (s=>/^(nu|un|bq|qb|wm|mw)+$/.test(s+s[1]))(x) ) ) ``` [Answer] # Clojure, 156 bytes ``` (fn[w](let[s["nu""wm""bq"]c #(= 1(count(set %)))e #(take-nth 2 %)r #(and(c(e %))(c(e(drop 1 %))))](and(=(first w)(last w))(r w)(some #(=(set w)(set %))s)))) ``` This was deceptively difficult! I ended up having to break it down into 3 sub problems: * Is the first letter the same as the last? * Do the letters repeat? * Are all the letters a part of one of the valid sets? I certainly didn't win, but this was a good morning exercise! Full explanation below: ``` (defn cartwheel? [word] (let [; Valid Character Sets cs ["nu" "wm" "bq"] ; Is the list composed of only a single character? count-1? #(= 1 (count (set %))) ; Grabs every other element of the list every-other #(take-nth 2 %) ; Do the characters repeat? Works by checking if every other element is the same, then drops the first letter ; to check all the odd indexed characters repeating? #(and (count-1? (every-other %)) (count-1? (every-other (drop 1 %))))] ; Do all the predicates hold? (and (= (first word) (last word)) (repeating? word) ; Is the set of letters in the word part of some set of the valid characters? (some #(= (set word) (set %)) cs)))) ``` [Answer] ## Haskell, ~~80~~ 78 bytes ``` f s|l<-length s=odd l&&l>1&&any((==s).take l.cycle)(words"un nu mw wm bq qb") ``` [Try it online!](https://tio.run/##PYzLCoMwEEV/5RJK0EWF7ptCv8Bdly1RYxWT8RHTIPTf0yhaDjMDw72nkbZTWodQw3719awVvecGVvRVBc25vl04l7QkiRA2zWbZKeisXEqt0sT3U2WZI5CD8fAGxYixYCmCkS1BYJhamnGCkQPqeLcGGG2d/47E8irw8VWMO/g8I7g/IsjzHO6fjiuGd8HrMK0OIueOAfkdGBZ@ "Haskell – Try It Online") How it works: ``` l<-length s -- let l be the length of the input string f s = -- return True, if odd l -- l is odd and l > 1 -- l is greater than 1 and any -- any of the following is also True ( )(words " ... ") -- apply the function to each of the words "un", "nu" ... "qb" cycle -- infinitely repeat the word take l -- take the first l characters (==s) -- and compare to s ``` [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` lambda s:s[2:]+s[1:3]==s>s[:2]in'bqbunuwmw' ``` [Try it online!](https://tio.run/##bZDLboMwEEXX8BUjb0IUWil0Z8mR@gVIXbQLSiOT8rBkDPWjiFU@nZo64ZHEV174zNXMHbe9rhoRDQX5HDits28KCqskwulOJXv8khKiDirBUcrEJvvJzkaYc1d3m6GrGM9hj32PM5EDAUm7IxOt0cHW92iYhScyVp5Vy9k/01SWubbOEyFIS6OrHvmezJXhI82ahgdFQLfW2komNCToQzaixCgE9MbKSmOUJs5PiOuWhkBDhwZhBEzn6QBuhG/xXLjBVldcUK563672qIfFqx7ObP/jqqX598vqzvz6bnVH4zhezXPULMOtItsgl20ms30fpxWXdN5lpsKY613Q7qKVtwZ4EG1MZcxNhj8 "Python 2 – Try It Online") The spaces in the string are `DEL` characters. [Answer] # [Retina](https://github.com/m-ender/retina), 24 bytes ``` G`nu|mw|bq ^((.).)\1*\2$ ``` Outputs 1 for truthy, 0 for falsy. Port of Cows quack's answer. [Try it online!](https://tio.run/##K0otycxL/P/fPSGvtCa3vCapkCtOQ0NPU08zxlArxkjl//@80rzy3HIgCQA "Retina – Try It Online") [Answer] ## [Grime](https://github.com/iatorm/grime), 28 bytes ``` e`..-#!"nu\|bq\|mw"oTv&..v+. ``` [Try it online!](https://tio.run/##Sy/KzE39/z81QU9PV1lRKa80piapMKYmt1wpP6RMTU@vTFvv///SPCAEAA "Grime – Try It Online") Prints `1` for truthy inputs and `0` for falsy ones. ## Explanation Grime syntax resembles regular expressions, and a Grime program specifies a pattern that may or may not match a rectangle of characters. ``` e`..-#!"nu\|bq\|mw"oTv&..v+. e` Match input against pattern: ! Does not # contain .. a 2-character substring - which is not "nu\|bq\|mw" any of these strings oT potentially reversed, v& AND .. two characters v+ one or more times . then one more character. ``` Some features of Grime that helped shorten this: * Normally a character literal must be escaped with a backslash, but `""` changes this: syntax elements are escaped but literals are not. Without the quotes, the part that enumerates the character pairs would be `(\n\u|\b\p|\m\w)oT`. * Unary operators that follow a binary operator (here `-`) act on its result: `..-#!"…"oT` is equivalent to `(..-"…"oT)#!`. * The `v`s lower the precedence of the syntax elements that follow them. A lone `&` has higher precedence than `-`, but `v&` has lower. Similarly, `..+` is parsed as `.(.+)`, but `..v+` is equivalent to `(..)+`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *This took more work than one might think!* ``` “nmbuwq”iЀo⁵IAs2⁼€3,3Ȧ ``` A monadic link taking a list of characters and returning `1` (truthy) or `0` (falsey). **[Try it online!](https://tio.run/##y0rNyan8//9Rw5y83KTS8sJHDXMzD0941LQm/1HjVk/HYqNHjXuAPGMd4xPL/v//n1eaBwA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##y0rNyan8//9Rw5y83KTS8sJHDXMzD0941LQm/1HjVk/HYqNHjXuAPGMd4xPL/h9uBzIf7u4Gqi4pKi3JqAQy0hJzioH03HCgFBeIOLrncHsWkAbK6dqBJA4tcf//P1oprzRPSQdEImggBDLLc8shJFgiqRAOgbyyOCAE0o5hQAik/f39gWQpkm4gBdQKN1QBYT7E3Ly80lIYBnHLoRDIzlWKBQA "Jelly – Try It Online"). ### How? Finds the index of each character of the input in the 1-indexed list of characters `nmbuwq`. This string is arranged such that the indexes of pairs are three apart, as such the incremental difference of the indexes for valid cartwheels will be repetitions of one of `[-3,3]` or `[3,-3]`. When an item is not found in a list by the "index of" atom, `i`, it returns `0`, which would pair unfound characters with `b`, making input like `bxbxb` truthy. So `0`s are replaced by `10` a value more than three away from any other value prior to checking for validity. ``` “nmbuwq”iЀo⁵IAs2⁼€3,3Ȧ - Link: list of characters, s Ѐ - map across c in s: i - first index of c in (1-indexed; 0 if not present) “nmbuwq” - literal "nmbuwq" ⁵ - literal 10 o - logical or (vectorises - replace any 0s with 10s) I - incremental differences (i.e. deltas) A - absolute value (vectorises) s2 - split into chunks of 2 (possibly with a single remainder) 3,3 - pair three with three = [3,3] ⁼€ - equals? for €ach (1 if so, otherwise 0 - including a single 3) Ȧ - any and all? (0 if any 0s or if empty, 1 otherwise) ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` lambda x:any([x in p*len(x)for p in'nu','mw','bq'])*len(x)%2*len(x)>2 ``` [Try it online!](https://tio.run/##bVCxCoMwFNz7FVlKtKSLo6DQpatL6WItKI1UiM9okqpfbxNNqynlSHh37/JeOD7KZwPBVEa3ieV18cjREOYweumAKkD8wCh4g182HeJawKAwwXWvr6LFmW/b@8AWcTBJKqSI0lRbARN06RTNCJrpH0GZgeicM7GIvZm9ejSdH62GorXY2l53Dcd2umo4SpIkDleb/ds/6ZXws1NzpP6Iy2c3Eij1OW6jt3DU@suynQnYJEc6KhSTJvs5yJB3FcilhY8xJqVnan96Aw "Python 2 – Try It Online") [Answer] # [Pyth](http://pyth.readthedocs.io), 27 bytes ``` &qeQhQ/"nu,mw,bq"S+{%2tQ{%2 ``` [Test Suite.](http://pyth.herokuapp.com/?code=%26qeQhQ%2F%22nu%2Cmw%2Cbq%22S%2B%7B%252tQ%7B%252&input=%22MWNUNU%22&test_suite=1&test_suite_input=%27nun%27%0A%27nunun%27%0A%27nunununu%27%0A%27wmw%27%0A%27wmwun%27%0A%27bqbqbqbqb%27%0A%27v%5Ev%5Ev%27%0A%27AVAVA%27%0A%27OOO%27%0A%27ununununu%27%0A%27nunwmwnun%27%0A%27nun+unun%27%0A%27nunwmw%27%0A%27nnuunnuunnuu%27&debug=0) Outputs `1` for truthy and `False` or `0` for falsy, as the OP allowed in chat. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` Ḋm2Qµ³m2Q;Ṣe“nu“mw“bq”ȧ³⁼U¤ ``` [Try it online!](https://tio.run/##y0rNyan8///hjq5co8BDWw9tBlLWD3cuSn3UMCevFEjklgOJpMJHDXNPLD@0@VHjntBDS/7//6@UVwqGSgA "Jelly – Try It Online") # How it works ``` Ḋm2Qµ³m2Q;µṢe“nu“mw“bq”ȧ³⁼U¤ Main link; z is the argument Ḋ z[1:] m2 z[1::2] Q deduplicate(z[1::2]) µ New Chain ³ z m2 z[::2] Q deduplicate(z[::2]) ; deduplicate(z[1::2]) + deduplicate(z[::2]) Ṣ Sort the result e Is it an element of the following? “nu“mw“bq” ["nu", "mw", "bq"] ȧ It has the correct characters and: ³ ¤ Nilad followed by links as nilad ³ z ⁼ == U z[::-1] ¤ [End chain] ``` [Answer] # [Python 2](https://docs.python.org/2/), 103 bytes ``` lambda x:len(x)>1and{x[0],x[1]}in[{i,j}for i,j in zip('ubw','nqm')]and x==(-~len(x)/2*(x[0]+x[1]))[:-1] ``` [Try it online!](https://tio.run/##PY3PDoIwDIfve4rduin@gSMJJj4BNy@ICQSJM6yiMpkafHXsFOiXX5c07bf62ZwuGPRltO@rTOdFxm1YHVFYufEzLN42WaeeTfy0U5i8lXfuysuN08sV8peqBZi8BQ/wqkGmdMFtFInF5@9YBTPhDHNnkDIJF37a/wTuHADQIKOMnWCtbl1olF8n2ONAsO2OYHEcMzPtU6P1QcFHl7MgGjOG6XaAafp3ea8r1QjYI8iwvilsRCmUlHyq/gs "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 47 bytes ``` g ¦U¬o ª`q¿nwm`ò má c aU¯2)<0?0:UÅë ä¥ ©Uë ä¥ e ``` [Try it online!](https://tio.run/##y0osKPn/P13h0LLQQ2vyFQ6tSig8tD@vPDfh8CaF3MMLFZIVEkMPrTfStDGwN7AKPdx6eLXC4SWHliocWhkKY6b@/6@UW56rBAA "Japt – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 88 bytes ``` lambda x:[len(x)%2,x[:2]in'nu,un,bq,qb,mw,wm',len(set(x[::2])),len(set(x[1::2]))]==[1]*4 ``` `len(x)%2`: an even-length string can't end on the first character `x[:2] in`: check for any of the 6 valid beginning pairs `len(set())`: get the length of the sets of characters at 0,2,4... and 1,3,5... Returns `True` if the list of evaluations is equal to [1,1,1,1], else `False`. [Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUaHCKjonNU@jQlPVyM5ApyLayig2M089r1SnNE8nqVCnMEknt1ynPFddB6SqOLVEA6gEqEZTE0nAECISa2sbbRirZfL/f14pGAIA "Python 3 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 55 + 1 (-p) = 56 bytes ``` $c={"nuunmwwmbppb"=~/./g}->{$l=chop};$_=/^($l$c)+$/&&$c ``` [Try it online!](https://tio.run/##K0gtyjH9/18l2bZaKa@0NC@3vDw3qaAgScm2Tl9PP71W165aJcc2OSO/oNZaJd5WP05DJUclWVNbRV9NTSX5///ccijkMrI0BEIuIyDgyisFw3/5BSWZ@XnF/3V9TfUMDA3@6xbkAAA "Perl 5 – Try It Online") Prints the "upside down" version of the first character for true, nothing for false. [Answer] # PHP, 59+1 bytes ``` <?=preg_match('#^(nu|un|mw|wm|bq|qb)\1+$#',$argn.$argn[1]); ``` Run as pipe with `-F`. partly regex solution, 101+1 bytes: ``` for($s=$argn;$c=$s[$i++];$p=$c)$c!=$p||die;echo$i%2<1&&preg_match("#^(nu|mw|bq)#",count_chars($s,3)); ``` Empty output for falsy. Run as pipe with `-nR`. [Answer] # Java 8, 57 bytes ``` s->s.matches("(nu)+n|(un)+u|(mw)+m|(wm)+w|(bq)+b|(qb)+q") ``` [Try it here.](https://tio.run/##jZJBbsMgEEX3OcXIKxCKLxClUg/QeBEpm6qRgNDWqRnbgTGqap/dpY1TdRXQhwWap88fhrMc5LrtDJ5PH7NupHPwJGv8WgHU6M3lVWoDu58jgGrbxkgEzfb@UuMbOL6JhSnuuJyXvtawA4QtzG794EorvX43jhUMiQscGSEXNDIbuLAjC5aLMDLVc6FG1isu@oLPm6tdR6qJdovr0NYnsDHYcvXzC0h@TbX/dN7YsiVfdrHkG2RYalYgYcF/A95lMqhgQ5JR/Z@SLOGie2SspKMnPG7pM3ocjlFJ6vEQlaSqqsp5@Rgsc0ZAmWDOpBCJbjsNh0VJ0mZ9NvrXybSa5m8) Simple regex to match all six cases. Note that Java's [`String#matches`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) automatically matches the entire String, so there is no need for `^...$`. [Answer] # [MATL](https://github.com/lmendo/MATL), 25 bytes ``` 'nuwmbq'&mq2&\d~wdts~Gnqv ``` The ouput is a non-empty numeric column vector, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398) if all its entries are nonzero, and [falsy](https://codegolf.stackexchange.com/a/95057/36398) otherwise. [**Try it online!**](https://tio.run/##y00syfn/Xz2vtDw3qVBdLbfQSC0mpa48paS4zj2vsAwslacOAA "MATL – Try It Online") To [**verify all test cases**](https://tio.run/##XVBNT8MwDL3nV/jCAhLqgT@AEEWICWkcEOIAiLZpqKXUSZtkpQf214fbbmshT/HzR54ju86C2X@@ruFwziC1SZJ0FZoygVvresDaGSwwAJKLAYKFwqDLbdYqWMM5kg9lpsBquL/YS4pdnTdyVTdXqze161TwuzU12/01wPzJgxYytDFUvRzjp@gr8KFF@oJjQfwsFXfGl0LqzPhR8l8zFcT7HwkpQC3SZS5F70zWi@dl8tFaB4UlhQEtgbYtz6qRMJSgTusAw88uh/lda4vSe6Dy@7CVYW6SYrAzM9jt6m6yYyFvTuBo@8FgvnlhMG82G7ZxoWZi6akpzP2nvkQxHu8QdgewX8tf), an `if` branch is added in the footer that replaces any truthy value by the string `'truthy'`, or any falsy value by the string `'falsy'`, and then displays the string. ### Explanation ``` 'nuwmbq' % Push this string &m % Implicit input. For each char, push index of membership in the above % string, or 0 if not member q % Subtract 1 2 % Push 2 &\ % Divmod. Pushes remainders, then quotients d~ % Consecutive differences negated. Gives an array of ones iff all % quotients were equal w % Swap. Moves remainders to top d % Consecutive differences. Gives nonzeros iff no consecutive % remainders were equal ts~ % Duplicate, sum, negate. Gives true iff sum was 0. For unequal % consecutive differences of remainders, this corresponds to an odd % number of remainders Gnq % Push input, length, subtract 1. True iff input longer than 1 v % Concatenate into column vector. Truthy iff all entries are nonzero ``` [Answer] # [Python 2](https://docs.python.org/2/), 74 bytes ``` import re re.compile('(n(un)+|u(nu)+|m(wm)+|w(mw)+|b(pb)+|p(bp)+)$').match ``` [Try it online!](https://tio.run/##pYxNCsMgEEb3cwoXhYwUsugykEVPkE3psiUGQ4RqVLSTQu9uJyHkAvWBb5ifz3/SNLtLKcb6OSYRNURdD7P15qWxQofZyfM3o8ssi2RZhJZYCoNiBVRBnuWpkrXt0zCVsf03AmjiW3GLWTcgljb29DTO54QShBnFiItsfDQuiaVc7wx0XQcuO5H5W4uNtSBLu7YJ7cD7wQABD9b@9kCFAziCIB95vPwD "Python 2 – Try It Online") This take on the problem is surprisingly competitive. [Answer] # Clojure, 115 bytes ``` (apply some-fn(map(fn[r]#(re-matches r %))(map(fn[[x y]](re-pattern(str x"("y x")+")))["nu""un""mw""wm""bq""qb"]))) ``` Build a regex out of each letter pair and see if the input matches one. Lots of more elegant ways to do all of these parts, but they're all more verbose. Such is life with Clojure golfing. [Answer] # Perl 5, 68 + 1 = 69 bytes ``` if(/../&&$&=~/nu|un|bq|qb|mw|wm/){s/^($&)*//;$&=~/./;print if/^$&$/} ``` Run with `-n`. Explanation: ``` # Match the first two characters, and if they exist, then... if (/../ && # Make sure they are a pair of compatible cartwheel characters. $&=~/nu|un|bq|qb|mw|wm/) { # If that's true, then eliminate as many of that pair of characters # from the beginning of the string as possible. s/^($&)*//; # Then get the first character out of the match (the first character # of the original string). $&=~/./; # Print the text (which is truthy since it's nonempty) if the original # first character matches exactly the remaining string. print if/^$&$/ # Otherwise, print nothing (the empty string in Perl is falsy). } ``` [Answer] ## [TXR Lisp](http://nongnu.org/txr), 50 bytes ``` (f^$ #/n(un)+|u(nu)+|m(wm)+|w(mw+)|b(qb)+|q(bq)+/) ``` Run: ``` 1> (f^$ #/n(un)+|u(nu)+|m(wm)+|w(mw+)|b(qb)+|q(bq)+/) #<intrinsic fun: 1 param> 2> [*1 "nun"] "nun" 3> [*1 "nuns"] nil 4> [*1 "mwm"] "mwm" 5> [*1 "wmw"] "wmw" 6> [*1 "abc"] nil ``` `f^$` is a combinator which takes a regex object and returns a function which matches that regex in an anchored way. (By itself, a regex object is function-callable object which takes a string and searches for itself through it.) [Answer] # [Python 3](https://docs.python.org/3/), 66 bytes ``` lambda x:x==len(x)//2*x[:2]+x[0]and{*x}in[{*'nu'},{*'mw'},{*'bq'}] ``` [Try it online!](https://tio.run/##bZDBa4MwFMbv@ytyS3UpHe4mWNhlVy9llywDRaVCfG1NMjPEv929RdcmpXyE5Pu9L3mPnH/08QSvc5N9zrLoyqogNrVZJmvY2Gi3S2LL00Q8W/4iCqjG2E4t8DGmYOjEcO@GZS8vdBKzrpVWGedYBsrIoTe1YMTZBwCF7L2QaoEDPuZl0LpLt0B5WeXHvr9QQeztAxWQPM8Db7z@/kzYEu56oifmAVyG9RAY87/CwrAqoN3Viafm1JO/n2N9rYzUpAVnVXruW9AbV6LbPWWNO0fR/As "Python 3 – Try It Online") [Answer] ## [TXR](http://nongnu.org/txr): ~~78~~ 74 bytes ``` @{x 2}@(rep :gap 0)@x@(end)@y @(bind(x y)(#"nu un mw wm bq qb"@[x 0..1])) ``` Run, from system prompt. Number in prompt is termination status: 0 = success, 1 = failure: ``` 0:$ ./txr cart.txr nun 0:$ ./txr cart.txr abc 1:$ ./txr cart.txr bab 1:$ ./txr cart.txr mwm 1:$ ./txr cart.txr nununununun 0:$ ``` Explanation: * `@{x 2}`: match two characters, bind to `x` variable. * `@(rep :gap 0)@x@(end)`: repeated match with no skipped gaps: zero or more occurrences of `x`, the previously matched digraph. * `@y`: remainder of line matched, captured into `y`. * `@(bind(x y)(foo bar))`: bind `x` to `foo`, y to `bar`. Since `x` and `y` are already bound, they have to match `foo` and `bar`, or else there is a failure. * `foo` is `#"nu un mw wm bq qb"`, a word list literal, syntactic sugar for the Lisp list `("nu" "un" ... "qb")`. A `bind` match between a variable and a list means that the variable must match an element. * `bar` is `@[x 0..1]`: the one-character substring of `x` from its beginning. The `bind` match between `y` and this forces the last letter of the line to match the first. [Answer] ## C++, 268 bytes ``` #include<map> #include<string> std::map<char,char>c{{'n','u'},{'m','w'},{98,'q'},{'w','m'},{'u','n'},{'q',98}}; int w(std::string s){if(s[0]!=s[s.size()-1]||c.find(s[0])==c.end()||s.size()<3)return 0;for(int i=0;i<s.size()-1;i+=2)if(s[i+1]!=c[s[i]])return 0;return 1;} ``` [Answer] # JavaScript (ES6), 63 bytes ``` s=>/bq|wm|un/.test(s)&s.replace(RegExp(s[0]+s[1],'g'),'')==s[0] ``` Returns `1` or `0`. **Explanation** All cartwheel strings will have one or more of **bq**, **wm**, or **un**. We test for that with: ``` /bq|wm|un/.test(s) ``` If you replace all instances of the first two letters of a cartwheel string with nothing, you're left with the first letter of the string. We test for that with: ``` s.replace(RegExp(s[0]+s[1],'g'),'')==s[0] ``` ``` let f= s=>/bq|wm|un/.test(s)&s.replace(RegExp(s[0]+s[1],'g'),'')==s[0] console.log(f('nun')) // truthy console.log(f('nunun')) // truthy console.log(f('nunununu')) // falsy console.log(f('wmw')) // truthy console.log(f('wmwun')) // falsy console.log(f('bqbqbqbqbqb')) // truthy console.log(f('v^v^v')) // falsy console.log(f('AVAVA')) // falsy console.log(f('OOO')) // falsy console.log(f('ununununu')) // truthy console.log(f('nunwmwnun')) // falsy console.log(f('nun unun')) // falsy console.log(f('nunwmw')) // falsy console.log(f('nnuunnuunnuu')) // falsy console.log(f('nwnwnwnwn')) // falsy console.log(f('m')) // falsy ``` ]
[Question] [ I have a challenge for you: * Print "Hello World" using any language. * Each character must be printed from its own, unique thread That's it. Obviously, as there's no guarantee that the threads will operate in the order you start them, you have to make your program thread safe to ensure the output is printed in the right order. And, because this is code golf, the shortest program wins. **Update:** The winner is [Marinus' APL entry](https://codegolf.stackexchange.com/a/5886/4139), at 34 characters. It also wins the prize for the least readable entry. [Answer] ## C, 61 62 chars ``` i;main(){write(1,"Hello World\n"+i++,1);i>13||fork()||main();} ``` The pthread library functions all have loooooong names, so instead I fired up an entire separate process for each character. `fork()` is so much shorter. It was necessary to use `write()` instead of `putchar()` because the stdio buffering functions are not thread-safe. **Edited**: Back up to 62 chars. In my zeal, dropping down to 61 chars also dropped the thread-safety. [Answer] ## APL (Dyalog) (~~44~~ ~~43~~ ~~39~~ 34) ``` {⍞←⍺⊣⎕DL⍵}&⌿2 11⍴'Hello World',⍳11 ``` Explanation: * `2 11⍴'Hello World',⍳11` creates a matrix: (H,1), (e,2), ... * `&⌿` means: for each column of the matrix, do on a separate thread: * In a thread, `⍺` is now the character and `⍵` is now the time * `⎕DL⊃⍵` waits for `⍵` seconds. * Then, `⍞←⍺` outputs the character. [Answer] ### Ruby, 46 characters ``` "Hello World".chars{|c|Thread.new{$><<c}.join} ``` It is synchronized due to the fact that the program waits for the thread to end before starting the next thread and continuing with the next char. [Answer] # Pythonect (35 chars) <http://www.pythonect.org> ``` "Hello World"|list|_.split()->print ``` [Answer] ## Python (~~101~~ ~~93~~ 98) This is Peter Taylor's solution. It works by delaying printing the N-th character by N seconds. See comments. ``` import sys.threading as t for x in range(11):t.Timer(x,sys.stdout.write,"Hello World"[x]).start() ``` This is the original one: ``` import sys,threading as t for x in "Hello World":t.Thread(None,sys.stdout.write,x,x).start() ``` It worked because the time it takes to print a single character is less than the time it takes Python to initialize a new thread, therefore the N-th thread would finish before the N+1-th thread was created. Apparently it is against the rules to rely on this. [Answer] # C# 73 ``` "hello world".ToList().ForEach(c=>Task.Run(()=>Console.Write(c)).Wait()); ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 [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") Full program. Prints to stderr. Inspired by [marinus' solution](https://codegolf.stackexchange.com/a/5886/43319). ``` 'Hello World'{⍞←⍺⊣⎕DL⍵}&¨⍳11 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@6R2pOTr5CeH5RTop69aPeeY/aJjzq3fWoa/GjvqkuPo96t9aqHVrxqHezoSFIw38FMCjggtBgNQqGRgqPeucqpKTmJFaCOMWpyfl5KcUKaflFCiUZqQqJSfllqQol@QppmXmZxRkA "APL (Dyalog Unicode) – Try It Online") `⍳11` first 11 integers `'Hello World'{`…`}&¨` for each integer as right argument (`⍵`), spawn the following function with the corresponding character as left argument (`⍺`):  `⎕DL⍵` **d**e**l**ay right-argument seconds  `⍺⊣` discard that (the effective delay) in favour of the left-argument character  `⍞←` print that to stdout without trailing line break [Answer] ## Java (160 chars) ``` class A{static int i;public static void main(String...a){new Thread(){public void run(){System.out.print("Hello World".charAt(i++));if(i<11)main();}}.start();}} ``` Yeah, I know this is the wrong language for code golf, I do it for fun. [Answer] ## Bash (64) ``` :(){ [ "$1" ]&&(echo -n "${1:0:1}"&: "${1:1}")};: "Hello World" ``` [Answer] ## Haskell (~~120~~ 118) ``` import Control.Concurrent t=threadDelay.(*3^8) main=(\(x,y)->forkIO$t x>>putChar y)`mapM_`zip[0..]"Hello World">>t 99 ``` I'm not all that sure about multiplying by 9999 - I have a 2Ghz Xeon on which it'll work fine even if you don't, but I also have a Pentium 4 that needs it (999 gave garbled output and 99 didn't do anything at all.) [Answer] ### scala(~~81~~ 79 chars) ``` def?(l:String){if(l.size!=0)new Thread{print(l(0));?(l.tail)}} ?("Hello World") ``` [Answer] # Groovy, 51 characters ``` "Hello World".each{a->Thread.start{print a}.join()} ``` [Answer] ## D (135 chars) ``` import std.concurrency,std.stdio; void main(){ p("Hello World"); } void p(string h){ write(h[0]); if(h.length>1)spawn(&p,h[1..$]); } ``` I only start the next thread when I have already printed the current char edit +2 chars for better bound check [Answer] ### Scala 74 ``` "Hello World".zipWithIndex.par.map(x=>{Thread.sleep(x._2*99);print(x._1)}) ``` * zipWithIndex produces ((H, 0), (e, 1), (l, 2) ...). * par makes it a parallel collection. Tests: ``` (1 to 10).foreach {_ => "Hello World".zipWithIndex.par.map(x=>{Thread.sleep(x._2*99);print(x._1)});println()} Hello World Hello World Hello World ... Hello World ``` [Answer] ## Javascript (72) ``` (function f(){console.log("Hello world"[i++]);i<11&&setTimeout(f)})(i=0) ``` [Answer] ### scala(45) Thread#join based solution ``` "Hello World"map{x=>new Thread{print(x)}join} ``` or ``` for(x<-"Hello World")new Thread{print(x)}join ``` [Answer] This is my F# attempt. My first serious F# program. Please be kind. ``` let myprint c = async { printfn "%c"c } "Hello World"|>Seq.map myprint|>Async.Parallel|>Async.RunSynchronously|>ignore ``` [Answer] ## [Go](http://golang.org/) ``` package main import"fmt" func main(){o:=make(chan int) for _,c:=range"Hello World"{go func(c rune){fmt.Printf("%c",c) o<-0}(c)} for i:=0;i<11;i++{<-o}} ``` [Answer] # Erlang (90) ``` -module(h). r()->r("Hello World"). r([])->'';r([H|T])->spawn(h,r,[T]),io:format("~c",[H]). ``` Compile `erlc +export_all h.erl` [Answer] ## Nimrod, 121 ``` proc p(c:char){.thread.}=write(stdout,c) for c in "Hello World": var t:TThread[char] createThread(t,p,c) joinThread(t) ``` [Answer] ## Python: too many characters, but it works. ``` # Ok. First we patch Threading.start to test wether our solution actually works import threading import random, time original_run = threading.Thread.run def myRun(self): tosleep = random.randint(0,200)/1000.0 time.sleep(tosleep) original_run(self) threading.Thread.run = myRun # And now the real code: import time, sys, threading string_to_write = "Hello World\n" current_char_index = 0 # This integer represents the index of the next char to be written # It will act as a semaphore: threads will wait until it reaches # the index of the single char that particular thread is due to output class Writer(threading.Thread): def __init__(self, char_to_write, index_to_write): self.char_to_write, self.index_to_write = char_to_write, index_to_write super(Writer, self).__init__() def run(self): ch = globals()['current_char_index'] while not self.index_to_write == ch: time.sleep(0.005) sys.stdout.write(self.char_to_write) # This will be atomic because no other thread will touch it while it has "our" index globals()['current_char_index'] += 1 for i, char in enumerate(string_to_write): Writer(char, i).start() ``` [Answer] ### C# ~~90~~ 84 ``` foreach(var c in"Hello World"){var t=new Thread(Console.Write);t.Start(c);t.Join();} ``` Running version: <http://ideone.com/0dXNw> [Answer] **Objective-C (183 characters)** ``` -(void) thread {[self performSelectorInBackground:@selector(printC) withObject:nil];} -(void) printC {char *c = "Hello World"; for(int i = 0; c[i] != '\0'; i++) {printf("%c", c[i]);}} ``` [Answer] ## Haskell 99 Characters ``` import Control.Concurrent f[]=return() f(x:xs)=(putChar x)>>(forkIO$f xs)>>f[] main=f"Hello World" ``` How it works is each thread starts the next after having displayed its character, so they actually useful stuff can not happen out of sequence. [Answer] # [Bash](https://www.gnu.org/software/bash/), 43 bytes ``` xargs -n1 printf<<<'H e l l o \ W o r l d' ``` [Try it online!](https://tio.run/##S0oszvj/vyKxKL1YQTfPUKGgKDOvJM3GxkbdQyFVIQcI8xViFBTCgVQRkJOi/v8/AA "Bash – Try It Online") `xargs` forks a separate `printf` process for each character (and waits for it to exit). # [Bash](https://www.gnu.org/software/bash/), 45 bytes, no external utilities ``` eval \(printf\ {H,e,l,l,o,\\\ ,W,o,r,l,d}\)\; ``` [Try it online!](https://tio.run/##S0oszvj/P7UsMUchRqOgKDOvJC1GodpDJ1UnBwjzdWJiYhR0woGMIiA3pTZGM8b6/38A "Bash – Try It Online") Expands to `(printf H); (printf e); (printf l); (printf l); (printf o); (printf \ ); (printf W); (printf o); (printf r); (printf l); (printf d);` before evaluation. The parentheses make Bash fork a subshell for each letter (and wait for it to exit), but this time `printf` is the Bash builtin. ]
[Question] [ # Introduction Humans are a remarkable species, but we can be very awkward to understand sometimes—especially for computers. In particular, we seem to like writing polynomials in a very convoluted fashion with seemingly arbitrary rules. What is the shortest program you can write to format a polynomial correctly using these rules? # Challenge Input > > A list of integers between -1000 and 1000 (inclusive), representing the coefficients of a polynomial, with the last entry being the coefficient of x^0 (the constant), the second last being the coefficient of x^1, etc. > > > Output > > A string representing this polynomial in the correctly formatted mathematical notation of humans. > > > ## Rules: * The sign on the leading coefficient is only shown if it is negative. `Right: -x^2+3` `Wrong: +x^2+3` * Components with coefficient of 0 are not printed (except for the corner case where all coefficients are 0\*). `Right: x^5-x^2+3` `Wrong: x^5+0x^4+0x^3-x^2+0x+3` * Coefficients `-1` and `+1` are to be displayed without the 1, unless they are the constant. `Right: x^5-x^2+1` `Wrong: 1x^5-1x^2+1` * The exponent is only shown if it is greater than 1 and the variable is only shown if the exponent is greater than 0. `Right: 3x^3-7x^2+2x+1` `Wrong: 3x^3-7x^2+2x^1+1x^0` * \*Corner case: while zero values usually result in not printing that component, if all coefficients are zero the constant 0 should be printed. `Right: 0` `Wrong: 0x+0` `Wrong: (nothing)` * This is code-golf so the winner will be the program with the fewest bytes. # Example Input and Output ``` Input: Output: [0] 0 [0,0] 0 [0,-1,35,0] -x^2+35x [5,1,7,-9] 5x^3+x^2+7x-9 [100,0,0,-1] 100x^3-1 [931,21,-11,1] 931x^3+21x^2-11x+1 ``` I look forward to seeing your solutions. Have fun! # EDIT: * You can surround operations by whitespace if you wish. So `3x+5` and `3x + 5` are both fine. `3x+ 5` and `3x +5` are not. * If you want to produce actual exponent characters (say in Tex) that is allowed as it is even closer to how humans write. * Coefficients must appear without any decimals e.g. `9x^2` is correct, `9.0x^2` is not. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes ``` (?=( \S+)+) x^$#1 \b0x.\d+ \b1x x x.1 x 0 - - + ``` [Try it online!](https://tio.run/##FYkxCoAwEAT7fcWCCpGQcIeIWIilD7ANoqKFjYVY5PcxMgwMzHO@172lykxrMuNgGGZb2xpxKQtF2CX6cFgip0ZkvBKRoAB0cCBsSgLhr1M2vs3ZUtnR9VDJh/@BKuUD "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` (?=( \S+)+) x^$#1 ``` Insert all of the powers of `x`, including `x^1` but not `x^0`. ``` \b0x.\d+ ``` Delete all powers of `x` with zero coefficients, but not a trailing `0` (yet). ``` \b1x x ``` Delete a multiplier of `1` (but not a constant `1`). ``` x.1 x ``` Delete the `^1` of `x^1`. ``` 0 ``` Delete a constant 0 unless it is the only thing left. ``` - - ``` Delete the space before a `-`. ``` + ``` Change any remaining spaces to `+`s. [Answer] # JavaScript (ES6), ~~107~~ 106 bytes ``` a=>a.map(c=>c?s+=(c>0&&s?'+':_)+(!--e|c*c-1?c:c<0?'-':_)+(e?e-1?'x^'+e:'x':_):e--,e=a.length,_=s='')&&s||0 ``` [Try it online!](https://tio.run/##dc3PjoIwEAbwu0@BF1u2HWyXECPZ0gcxYJpx/BcEszWbHnh3tkTXA8nO8ZvffHN1P87j9@X@gK4/0Hg0ozOVy27uztFUaL0wHCu1WnnLBCv3qeBLABrwA0FbLPFLWQbPBVmKGQsNE1SyMIUlAUgyLmupOz3Ocm@8YSyNdcOgRuw737eUtf2JH/lO1cnfpGmyXieJWsyJfKP/CWiZFxN8EgjNp8iLMIeF1HIjYVu/u4rQ5GLSmwDbOdcqPpdTe/3iMYkHoMdf "JavaScript (Node.js) – Try It Online") ### How? The output is built by applying the following formulas to each coefficient **c** of the input array **a[ ]** while keeping track of the current exponent **e**. **1st formula: plus sign** If the coefficient is strictly positive and this is not the first term in the output expression, we append a `+`. Otherwise, we append nothing. ``` c > 0 && s ? '+' : _ ``` **2nd formula: minus sign and coefficient** If the exponent is zero or the absolute value of the coefficient is not equal to 1, we append the coefficient (which may include a leading `-`). Otherwise, we append either a `-` (if the coefficient is negative) or nothing. ``` !--e | c * c - 1 ? c : c < 0 ? '-' : _ ``` **3rd formula: variable and exponent** If the exponent is 0, we append nothing. If the exponent is 1, we append `x`. Otherwise, we append `x^` followed by the exponent. ``` e ? e - 1 ? 'x^' + e : 'x' : _ ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 37 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┴₧↕ê♦•Vªâÿσ9s╘dσ■à@@ⁿ■o─╦ñºº┌x╡ER▓ δ¿ ``` [Run and debug it online](https://staxlang.xyz/#p=c19e1288040756a68398e53973d464e5fe854040fcfe6fc4cba4a7a7da78b54552b220eba8&i=[0]%0A[0,0]%0A[0,-1,35,0]%0A[5,1,7,-9]%0A[100,0,0,-1]&a=1&m=2) Here's the unpacked, ungolfed version. ``` r{ reverse the input and map using block ... |c skip this coefficient if it's falsy (zero) 0<.+-@ sign char; e.g. '+' _|aYv i!+ abs(coeff)!=1 || i>0 y$ str(abs(coeff)); e.g. '7' z "" ?+ if-then-else, concatenate; e.g. '+7' "x^`i" string template e.g. 'x^3' or 'x^0' iJ(T+ truncate string at i*i and trim. e.g. 'x^3' or '' mr$ re-reverse mapped array, and flatten to string c43=t if it starts with '+', drop the first character c0? if the result is blank, use 0 instead ``` [Run this one](https://staxlang.xyz/#c=r%7B+++++++++%09reverse+the+input+and+map+using+block+...%0A++%7Cc+++++++%09skip+this+coefficient+if+it%27s+falsy+%28zero%29%0A++0%3C.%2B-%40+++%09sign+char%3B+e.g.+%27%2B%27%0A++_%7CaYv+i%21%2B%09abs%28coeff%29%21%3D1+%7C%7C+i%3E0%0A++++y%24+++++%09str%28abs%28coeff%29%29%3B+e.g.+%277%27%0A++++z++++++%09%22%22%0A++%3F%2B+++++++%09if-then-else,+concatenate%3B+e.g.+%27%2B7%27%0A++%22x%5E%60i%22+++%09string+template+e.g.+%27x%5E3%27+or+%27x%5E0%27%0A++iJ%28T%2B++++%09truncate+string+at+i*i+and+trim.+e.g.+%27x%5E3%27+or+%27%27%0Amr%24++++++++%09re-reverse+mapped+array,+and+flatten+to+string%0Ac43%3Dt++++++%09if+it+starts+with+%27%2B%27,+drop+the+first+character%0Ac0%3F++++++++%09if+the+result+is+blank,+use+0+instead&i=[0]%0A[0,0]%0A[0,-1,35,0]%0A[5,1,7,-9]%0A[100,0,0,-1]%0A[-1000,-1000,-1000]&a=1&m=2) [Answer] # Python 3, ~~279~~ ~~277~~ ~~258~~ 251 bytes ``` k=str.replace def f(x): z=len(x) y='--'*(['-1']==[c for c in x if'0'!=c][:1]) for i,v in enumerate(x): p=str(z+~i) if v in'-1'and~i+z:y+='+x^'+p elif'0'!=v:y+='+'+v+'x^'+p return y and k(k(k(k(y[1:],'+-','-'),'^1',''),'x^0',''),'-+','-')or 0 ``` Takes input as a list of strings. This solution is not highly golfed yet. This basically works by replacing things to suit the output format, which highly increases the byte count. [Try It Online!](https://tio.run/##XY/RioMwEEXf/YrZp9FNUgxlWVbIl4iC2MiG2lSyVtSH/ro701goJQ@5mXPnzmRYxt@rP6r2cW/b2fyN4RDs0DetTU62gy6dsyKB1fTWk0xgMagUfqYlKo2VMWUL3TVAC87DDK7DHD9MW5WFrsjNyMmJofW3iw3NaGMiDDwrXcXdkY8agV0c2vjT3Ym1WIRBMdcoBuK236OnWEcxCdxhsOMteFiAOuGcxrOUuqgkCoUSFWYSa02KxVznu1IiQloy34bg/Jh29DHGOVZZlrzW3t@Sd5V4PHw97fDCFVeZf7Px561b53EGWXQMIr79Aw) *Special thanks to ovs and NK1406*. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 41 bytes ``` p->concat([c|c<-Vec(Str(Pol(p))),c!="*"]) ``` [Try it online!](https://tio.run/##LYzBCsIwEER/Zc1pI7uQIEUE228QBC8hh7BYKZR2CbkI/ntM0MvMPGYYTXnhl9YZxqo8yb5JKhjkI1d@PAXvJeNtX1GttSSH0RxNtDWprm9U4Ak0L1tBJTCdDMx9ShCCi00d/Y09nYYfDOTpTHzp2bu2oF7HdvsF "Pari/GP – Try It Online") --- If an `*` between the coefficient and the variable is allowed: # [Pari/GP](http://pari.math.u-bordeaux.fr/), 3 bytes ``` Pol ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7PyA/539iQUFOpUaBgq6dQkFRZl6JRoGOghKIp6SQplGgqamjEB1tEAskDXSglK6hjrEphGOqY6hjrqNrCWIbGgBV6ICkY2M1/wMA "Pari/GP – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~114~~ ~~113~~ ~~109~~ ~~107~~ 106 bytes ``` {{⍵≡'':⍕0⋄⍵↓⍨'+'=⊃⍵}∊⍵{{'1x'≡2↑1↓⍵:¯1⌽1↓1⌽⍵⋄⍵}('-0+'[1+×⍺]~⍕0),∊(U/⍕|⍺),(U←⍺≠0)/(⍵>⍳2)/¨'x'('^',⍕⍵)}¨⌽⍳⍴⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/uvpR79ZHnQvV1a0e9U41eNTdAuK3TX7Uu0JdW932UVczkF/7qKMLSFVXqxtWqAMVGz1qm2gIVrTV6tB6w0c9e0E8EA3SDDaiVkNd10BbPdpQ@/D0R727YutApmvqAA3SCNUHsmuAgpo6GqGP2iYAWY86Fxho6msA9dk96t1spKl/aIV6hbqGepy6DlAtUFiz9tAKsPGbH/VuARn//1HfVE9/oG4DLjcgOVS9wQX0BlCvm4KOAZxpgMIGOkzH2BRJyFTHUMccKGwJFzE0AGrRASv9DwA "APL (Dyalog Classic) – Try It Online") -4 bytes thanks to @dzaima! This can definitely be golfed down further. This requires `⎕IO←0` [Answer] # [Pip](https://github.com/dloscutoff/pip), 78 bytes ``` (RV(B."x^"._MERVg)J'+)R[`\b0[^+]+``x.0|\^1|^\++|\++$``\b1x``\++-?`][xx'x_@v]|0 ``` Takes the coefficients as command-line arguments. [Try it online!](https://tio.run/##K8gs@P9fIyhMw0lPqSJOSS/e1zUoLF3TS11bMyg6ISbJIDpOO1Y7IaFCz6AmJs6wJi5GW7sGiFUSgJKGFUBSW1vXPiE2uqJCvSLeoSy2xuD///8G/3UN/xub/jcAAA "Pip – Try It Online") Uses `ME` (map-enumerate) and `J` (join) to generate something of the form `0x^3+-1x^2+35x^1+0x^0`, and then a bunch of regex replacements to transform this into the proper format. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~79~~ 76 bytes ``` {'^$' '\b1x' '\+?¯' '^\+'⎕r('0x-',⊂⍬)∊⍕¨(0≠⍵)⌿'+',⍵,⊖⍪((⊢↓⍨2≤⊢)↑'x^',⍕)¨⍳≢⍵} ``` [Try it online!](https://tio.run/##NY2xSsRAEIb7fYothEnYLOwmhCM2vsgRiHdEgoFILsWKXCMSTHRFkVjLYRFEuEKusTnIo8yLxFnBZub/5/t/Jrsq5fo6K6sLuSqzzaZYzfg0FBW2z2rOad5AegIclufauCXOpj3tdCmAcrUHykgIsL9F@@XjfY92mEZPYfeO9uDj4xEEYXugyBvaT8/DfoftK9oxxO6DjI/tC5jUhQZ/GtF@Y7ejwnaeG/eeJB1qkjnan9M15FlRAkkCNT7cQXUJW@YFym8CUMAUV/9i2msexeRBmjQUUWyAxVzzBZGkgdikkXBgYWQCTCuq8r9WA2SISg0siTQPtbtqToCsq4U0Q6m1ERp@AQ "APL (Dyalog Classic) – Try It Online") [Answer] # Python 3, 161 162 bytes *Fixed a bug thanks to ovs.* ``` l=len lambda p:''.join(['+'*(i>0)*(c>0)+(str(c)[:-1],str(c))[abs(c)!=1or i==l(p)-1]+'x'*(i!=l(p)-1)+('^%d'%(l(p)+~i))*(i<l(p)-2)for i,c in enumerate(p)if c])or'0' ``` Expanded: ``` l=len # Alias the len function since we use it a lot lambda p: ''.join([ # Join a list of strings '+'*(i>0)*(c>0) # Prepend a + if this isn't the first term and the coefficient is positive + (str(c)[:-1], str(c))[abs(c) != 1 or i == l(p) - 1] # If the coefficient is 1 and this isn't the last term, delete the '1' from the string representation, otherwise just use the string representation + 'x' * (i != l(p) - 1) # If this isn't the last term, append an x + ('^%d' % (l(p) + ~i)) * (i < l(p) - 2) # If this isn't one of the last two terms, append the exponent for i, c in enumerate(p) if c]) # Iterating over each coefficient with its index, discarding the term if the coefficient is zero or '0' # If all of the above resulted in an empty string, replace it with '0' ``` [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), 237 bytes ``` c=>{var b=1>0;var r="";int l=c.Length;var p=!b;for(int i=0;i<l;i++){int n=c[i];int e=l-1-i;var o=p&&i>0&&n>0?"+":n==-1&&e!=0?"-":"";p=n!=0?b:p;r+=n==0?"":o+(e==0?$"{n}":e==1?$"{n}x":n==1||n==-1?$"x^{e}":$"{n}x^{e}");}return r==""?"0":r;} ``` [Answer] # [Clean](https://clean.cs.ru.nl), 172 bytes ``` import StdEnv,Text r=reverse @""="0" @a|a.[size a-1]<'0'=a+"1"=a ? -1="-" ?1="" ?a=a<+"" $l=join"-"(split"+-"(join"+"(r[?v+e\\v<-r l&e<-["","x":map((<+)"x^")[1..]]|v<>0]))) ``` [Try it online!](https://tio.run/##RYlNS8QwFEX3@RXhOTgtaUqLO0lsF7oQXAjjrtOBRyeVSD5KmilV5rcbiy7c3HvuuYNR6JL154tR1KJ2SdvJh0gP8fzkluJNrZEEGdSiwqxICyChAtLiFctu1l@KIq97sa/2EhnUIJE0lNcSOJBmqy1RomAb7Iz88NptTzZPRkdgG/0aBlnomoWp43ERPFBzqwTvAApY4d7ilGWC5bCeIO/qsuz76yIeqj7P83SIGCK5oePFDVF7RyVt/Y7If0G7u6LqKaXpexgNvs@JP7@kx0@HVg9/49VgHH2wPw "Clean – Try It Online") [Answer] # Wolfram Language/Mathematica, 39 bytes ``` TraditionalForm@Expand@FromDigits[#,x]& ``` [Try it online!](https://www.wolframcloud.com/objects/bbe24a71-2110-459a-b9a4-f297c2911db3) Turns out there is a built-in to get in in the right order. Previous solution: ## Wolfram Language/Mathematica, 93 bytes ``` StringReplace[StringRiffle[ToString/@InputForm/@MonomialList@FromDigits[#,x],"+"],"+-"->"-"]& ``` ~~At least to me, this is suprisingly long for a language designed for mathematical manipulation. It seems like `Expand@FromDigits[#,x]&` should work, but the default ordering for polynomials is the reverse of what the question requires, so some extra finagling is required.~~ ### Explanation ``` FromDigits[#,x] converts input list to polynomial (technically converts to a number in base x) MonomialList@ gets list of terms of polynomial InputForm/@ converts each term to the form a*x^n ToString/@ then to a string version of that StringRiffle[...,"+"] joins using +'s StringReplace[...,"+-"->"-"]& replaces +-'s with -'s ``` [Answer] Python3: ~~150~~ 146 bytes ``` f=lambda l:''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1]for i,a in zip(range(len(l)-1,-1,-1),l)if a).lstrip('+')or '0' ``` (previous implementations): ``` f=lambda l: ''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1] for i,a in zip(range(len(l)-1,-1,-1),l) if a).lstrip('+') or '0' ``` You can [*try it online*](https://tio.run/##hY/BboQgEIbv@xQ0PcAU2IDEbDTdvojRhG3XLQ1F43qgTd/dgibLag8lBGaY7/@Z6b/G984p/jrf09Qerf48vWlkS4z3H51xBFOOK/0sanodB6IhxmX@RIg@XUP6cJTwQ@SLAagp9g2uSrOgBkLIZd12AzJMI@PQt@nJoN3lTOzZEQtcsnkDs2BapGFvgzJAmGIIMizw1A/GjaQllWCiBtilfJ1FJzUjKL3ynEl2YLxYsVIELybjz38c0f16vEVit@njfyr2kyf2RnHfZFTlPrF3TW4dc98oGgUHz4vtBGIZYK0IpaDhMsGFkiyLw0q24AkOpfhBFs4s1D2V0y8) Kudos to: @Benjamin [Answer] # [Perl 5](https://www.perl.org/) `-a`, 94 bytes ``` ($_=shift@F)&&push@a,@a*!/-/>0&&'+',@F?s/\b1\b//r:$_,@F>0&&'x',@F>1&&'^'.@F while@F;say@a?@a:0 ``` [Try it online!](https://tio.run/##HYndCoIwGEBfZYFs/Ti3rxDCSL@r3fUGknyCsYHkcEb18q0V5@Zwjh/msYxxnXXnYN1tQbPh3D@CRcqRtislVa05FzuRo2mCantoe6XmKutS@K/Xb9WQ7CoKNOxp3TigOQV6IzVIlY5RsyMDYJrtgUk4JE3AZ/KLm@4hyktZaNBR0hc "Perl 5 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 113 bytes ``` \w+ a$'b$& a( [^b ]*)*?b(\d+) $2x^$#1 (\^1|x\^0)(?!\d) (?<= |-|^)(1(?=x)|0[^ -]*) ([ -])* $1 [ -]$|^ ^$ 0 + ``` [Try it online!](https://tio.run/##FYuxDsIwEEP3@wojAlxanZQrlFKJqiMf0RDRqgwsDAiJDvn3kMqDbT378/y@3mPa8e2R/K@k0Rwms6eRMYQJ98IW/cR@Li2Zaglmq8Q@aFx8cJb7jZ8tEffXDlFisKzcd4uNbgiQfM5syMEWZJTWZGIAUTDkCFSmVEPRQFpS57BKlLJlLKrQ3FtcIA3OkBonyBFV3sD9AQ "Retina 0.8.2 – Try It Online") I'm sure there is a lot to golf here... [Answer] # [Haskell](https://www.haskell.org/), ~~166~~ 163 bytes ``` g s|l<-length s,v:w:r<-id=<<["- +"!!(1+signum m):(id=<<[show$abs m|abs m>1||e==0]++["x"|e>0]++['^':show e|e>1])|(e,m)<-zip[l-1,l-2..]s,m/=0]=[v|v>'+']++w:r|1<3="0" ``` [Try it online!](https://tio.run/##dY7RaoMwFIbv9xSnYaCSxJmKlEriE2xXuxQFy4LKEieNtTLy7i46OtbSnouQk3wf/99U5lMqNc81GKs4VbKrhwYMGdNzeuS0/RCc54gCRpuNz7Bp6@6kQQep//tlmq/zc3UwoO16ZsxaKURUYJyjCVmZrVev9NIFBeleWBFYXxIdcPrd9rmijCi6DcPCEP3iVJGPdsw87DnTtbCMxwJFaNZV24EAXfVv4Pen4X04vnYQQh1A/gTr5FFB4M5Q@n@L/mhyl39Iu6Zxcutc0XQqtzhOpouTEEZ2hO5vYq4TkqmM8SLuJrq/mCxy7ciSWRQPTQc5l7L5Bw "Haskell – Try It Online") Example usage: `g [0,-1,35,0]` yields `"-x^2+35x"`. --- Previous 166 byte solution, which is slightly better readable: ``` 0#n=show n m#n=id=<<[show n|n>1]++"x":['^':show m|m>1] m%0="" m%n|n<0='-':m#(-n)|1<3='+':m#n g s|l<-length s,v:m:r<-id=<<zipWith(%)[l-1,l-2..]s=[v|v>'+']++m:r|1<3="0" ``` [Try it online!](https://tio.run/##dY5Ra4MwEMff/RRHSlExJ0lFSiXpJ9ie9rCHoCCsqCzJpDonw@/uoqNjLe29JHf8fve/uuzeT1rPM9tY2dUfX2A9477NmxRC/Q4me@R5FJGRZMov/Gydmsm4qWe2TBLiHkcJJn30M7MJ0IYTF4n0o6W1XgXdpAXqk636Gjo6ZCY7C1xDvpv2tenrYBsqjZxq3MVx3kk1TMPR@S7Yses2wshsysaCBFO2zxC0n/1Lf36yEEMVgvJgLcVyCncK8X/H/mh6l39IuxuT9Na5onEsdlGSjhcnpZzuKR5uYq4T0rFIokXcj3i4mJy56@iSmecPTQc5F/n8Aw "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 111 bytes ``` ->a{i=a.size;s=a.map{|x|i-=1;"%+d"%x+[?x,"x^#{i}",""][i<=>1]if x!=0}*'';s[0]?s.gsub(/(?<!\d)1(?=x)|^\+/,""):?0} ``` [Try it online!](https://tio.run/##ddDdaoMwFMDx@z6FjZTqcmI9ihRnUx/ERrAfbrkYlEXhbOqzuyPsZuuWixD4/3ICee/PH3OrZ3VsBqubyNnPW@H48Nbch5FGqzQWYiOvYkOyKgkE1f5gJwFCmMoe9BGNbT1a63h62m4LV8WmdNGL68/BLigP69M1xKDUFI71Se74VvhcxtPc6WrlsQXvz@XHS4V/@ndVCGn2aHxFdSLTjBhlgLAHlT/M8TOqU7nAPamcJcb8HCxDf1mfC1uFjPIUIUE2CGh@IC7LwIT3hDNJXJlVF92ay@vyjfe@c15bkZnmLw "Ruby – Try It Online") Solving this in Ruby turned out to be a bit frustrating, mainly due to the fact that unlike most languages, in Ruby (almost) everything is truthy, including 0-s and empty strings, so that even a simple check for zero becomes nowhere near as short as `x?`. I played with various methods of constructing the string, and ultimately settled on a mix of several approaches: * Terms with 0 coefficients are dropped using a simple conditional * `+` and `-` signs are produced by formatting syntax with forced sign: `%+d` * The correct form or `x^i` is selected using rocket operator indexing `[...][i<=>1]` * Leading + and unnecessary 1-s are removed by regex replacements [Answer] # [Husk](https://github.com/barbuz/Husk), ~~44 43 41~~ 40 bytes ``` |s0Ψf¤|□ṁ`:'+f¹zμ+↓s²_&ε²¹↑□¹+"x^"s)¹m←ṡ ``` [Try it online!](https://tio.run/##AVoApf9odXNr//98czDOqGbCpHzilqHhuYFgOicrZsK5es68K@KGk3PCsl8mzrXCssK54oaR4pahwrkrInheInMpwrlt4oaQ4bmh////WzEsLTMzLDQsMCwtMSwtMl0 "Husk – Try It Online") This feels a bit clunky; Husk is not optimized for string manipulation. I borrowed some ideas from the [Stax answer](https://codegolf.stackexchange.com/a/158271/32014). ## Explanation ``` Implicit input, say L = [2,-3,0,-1]. First we compute the exponents. ṡ Reversed indices: [4,3,2,1] m← Decrement each: [3,2,1,0] Then we format the individual terms of the polynomial. zμ...)¹ Zip with L using two-argument lambda: Arguments are coefficient and index, say C = -3 and I = 2. +"x^"s Convert I to string and concatenate to "x^": "x^2" ↑□¹ Take first I*I characters (relevant when I = 0 or I = 1): "x^2" _&ε²¹ Check if abs(C) <= 1 and I != 0, negate; returns -1 if true, 0 if false. ↓s² Convert C to string and drop that many elements (from the end, since negative). Result: "-3" The drop is relevant if C = 1 or C = -1. + Concatenate: "-3x^2" Result of zipping is ["2x^3","-3x^2","x","-1"] f¹ Keep those where the corresponding element of L is nonzero: ["2x^3","-3x^2","-1"] Next we join the terms with + and remove extraneous +s. ṁ Map and concatenate `:'+ appending '+': "2x^3+-3x^2+-1+" Ψf Adjacent filter: keep those chars A with right neighbor B ¤|□ where at least one of A or B is alphanumeric: "2x^3-3x^2-1" |s0 Finally, if the result is empty, return "0" instead. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 97 bytes ``` {$!=+$_;.map({('+'x?($_&&$++&$_>0)~.substr(--$!&&2>.abs)~(<<''x>>[$!]//'x^'~$!))x?$_}).join||'0'} ``` [Try it online!](https://tio.run/##NY3ZCoJQFEWf8yu8cLgDHs2rWIjTh4iJQkKRKVpgOPy6qdnL3izYQ31tHqe5/Ki0UAN17oEEGqSeUWY17znTWBdxSCkFTaOQhqaYjPadt6@G6zoQSq3QyPJWTNz3GevCMAaSHI@su7AJiBBdBOkojHt1ew4DM9k4e0qbrW/LqlCLqlEOsZngqvh3XaLt7OSgxDPq7gbSXEK4BjZ0bYmWXEii3Ks/l0t5/gI "Perl 6 – Try It Online") Explanation: ``` $!=+$_; ``` `$!` keeps track of the current exponent. ``` '+'x?($_&&$++&$_>0) ``` Add `+` before positive coefficients, except if it's the first non-zero one. The `$_&&` short circuit makes sure that the anonymous state variable `$` is only incremented for non-zero coefficients. The `&` junction is collapsed when coerced to Bool with `?`. ``` .substr(--$!&&2>.abs) ``` Decrement `$!`. Chop 1 or -1 coefficient unless it's constant. ``` <<''x>>[$!]//'x^'~$! ``` Special-case linear and constant terms. Using the quote-protecting `<< >>` construct is one byte shorter than the equivalent `('','x')` or `2>$!??'x'x$!!!'x^'~$!`. ``` x?$_ ``` Hide zero terms, but always evaluate the preceding expression for the `--$!` side effect. ``` ||'0' ``` Return `0` if all coefficients are zero. [Answer] # Java 8, ~~202~~ ~~176~~ ~~174~~ 173 bytes ``` a->{String r="";int j=a.length;for(int i:a)r+=i==0*j--?"":"+"+i+(j<1?"":j<2?"x":"x^"+j);return r.isEmpty()?"0":r.substring(1).replace("+-","-").replaceAll("(\\D)1x","$1x");} ``` * 26 bytes thanks to *@Nevay*. **Explanation:** [Try it online.](https://tio.run/##lVBNT8IwGL7zK940HlrXLusAEcYkJnqUi0fApIyBnaMsXUEI2W/Hd4DeTFjSNnk/nj4fmdopsSlSky2@TkmuyhLelDbHFoA2LrVLlaQwrkuAd2e1WUFCcTKZgWIRtiu8eEqnnE5gDAZiOCnxdLxu25iQCAGQxcrPU7Nyn9FyY@s/QA8Us16s4zi4z4QYETIgHvG0R7OhrKtsGI7IHrv7D@JlLLKp21oD1tfl67pwB8pGJCAD65fbeXnmo5L5Ni1ylE2JJwgngvx1nvOcEjqdvjC5x8kdviyqTtHFQrGd52jh6mS30QtYYxT0YmQyU@waw6F06drfbJ1f4MTlhho/oSb9hnMwx6Bi52huWeWNloXk7W4TSJdL3uOifztCBqiJ11S3Y/ptyUOJEMkboEJkCZuYuUgTnYbqMLSQizbvcNHlD1z0@CMmwuXF56/bf3auNFWrOv0A) ``` a->{ // Method with String-array parameter and String return-type String r=""; // Result-String, starting empty int j=a.length; // Power-integer, starting at the size of the input-array for(int i:a) // Loop over the array r+=i==0 // If the current item is 0 *j--? // (And decrease `j` by 1 at the same time) "" // Append the result with nothing : // Else: "+" // Append the result with a "+", +i // and the current item, +(j<1? // +If `j` is 0: "" // Append nothing more :j<2? // Else-if `j` is 1: "x" // Append "x" : // Else: "x^"+j); // Append "x^" and `j` return r.isEmpty()? // If `r` is still empty "0" // Return "0" : // Else: r.substring(1) // Return the result minus the leading "+", .replace("+-","-") // and change all occurrences of "+-" to "-", .replaceAll("(\\D)1x","$1x");} // and all occurrences of "1x" to "x" ``` [Answer] # Python, 165 bytes ``` lambda a:"".join([("+"if c>0 and i+1<len(a)else"")+(str(c)if i==0 or abs(c)!=1 else "")+{0:"",1:"x"}.get(i,"x^"+str(i))for i,c in enumerate(a[::-1])if c][::-1])or"0" ``` [Answer] ## PHP, 213 Bytes ``` $p=0;for($i=count($a=array_reverse(explode(',',trim($argv[1],'[]'))))-1;$i>=0;$i--)if(($b=(float)$a[$i])||(!$i&&!$p)){$k=abs($b);echo ($b<0?'-':($p?'+':'')).((($k!=1)||!$i)?$k:'').($i>1?'x^'.$i:($i?'x':''));$p=1;} ``` Command line argument as requested by OP (single argument with brackets and commas). Pretty print and some explanation: ``` $p = false; /* No part of the polynomial has yet been printed. */ for ($i = count($a = array_reverse(explode(',',trim($argv[1],'[]')))) - 1; $i >= 0; $i--) { $b = (float)$a[$i]; /* Cast to float to avoid -0 and numbers like 1.0 */ if (($b != 0) or (($i == 0) and !$p)) /* Print, if $b != 0 or the constant if there is no part until here. */ { $k = abs($b); echo ($b < 0 ? '-' : ( $p ? '+' : '')); /* Sign. The first sign is suppressed (if $p is false) if $b positive. */ echo ((($k != 1) || ($i == 0)) ? $k : ''); /* Coefficient */ echo ($i > 1 ? 'x^' . $i : (($i != 0) ? 'x' : '')); /* x^3, x^2, x, constant with empty string. */ $p = true; /* Part of the polynomial has been printed. */ } } ``` [Answer] # PowerShell, 295 bytes ``` $c=$args[0] $p=$c.length-1 $i=0 $q="" while($p -ge 0){$t="";$e="";$d=$c[$i];switch($p){0{$t=""}1{$t="x"}Default{$t="x^";$e=$p}}if($d-eq 0){$t=""}elseif($d-eq 1){$t="+$t$e"}elseif($d-eq-1){$t="-$t$e"}elseif($d-lt 0 -or$i -eq 0){$t="$d$t$e"}else{$t="+$d$t$e"}$q+=$t;$i++;$p--}if($q -eq""){$q=0} $q ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/471/edit). Closed 4 years ago. [Improve this question](/posts/471/edit) This is based on a talk on compilers I listened to a while back, but I, unfortunately, can't remember when or where. Create the shortest compiler in any language that can compile itself. Target any reasonable ISA (68K, x86, MIPS, ARM, SPARC, IBM BAL, etc.) that doesn't have a "compile-program" instruction (this may exclude some versions of VAX). Read source programs from `stdin` and print generated code to `stdout`. You may use the standard C library for I/O and string processing (e.g., `_printf`). You don't need to compile the whole language, *just any subset that contains the compiler (i.e., just printing an assembly language quine, while impressive, does not count as a solution.)* [Answer] ## Haskell subset → C - 18926 characters This compiles a small subset of Haskell to C. Features it supports: * Pattern matching and guards * Data declarations * Select infix operators * Lazy evaluation The biggest missing features are nested variables (meaning no lambda/let/where/case), type checking, and type classes. Resulting programs leak memory, and self-compilation takes about 200 megabytes on my system (the [Boehm garbage collector](http://www.hpl.hp.com/personal/Hans_Boehm/gc/#contacts) helps a lot, but only if the compiler optimizes tail recursion well). To bootstrap, uncomment the first three lines (not counted in the score) and compile with GHC. The compiler takes Haskell-subset code on stdin and produces C code on stdout. It's long not because the language is complex, but because I'm lazy. However, it's currently the shortest solution Not anymore. Guess I won't be bored this weekend. ``` -- import Prelude hiding (fmap, lookup, snd, zip);import Data.Char -- import Data.List hiding (lookup, zip);data P a b = P a b;data B = B -- add=(+);sub=(-);showInt=show;append[]ys=ys;append(x:xs)ys=x:append xs ys data Program = Program [[Constructor]] [Function] data Toplevel = TD [Constructor] | TE Equation | TO data Constructor = Constructor String Int data Function = Function String Int [Equation] data Equation = Equation String [Pattern] (Maybe Expression) Expression data Pattern = PVar String | PCon String [Pattern] data Expression = Var String | Con String | Int String | Char String | String String | Ap Expression Expression data Environment = Environment [P String Int] [P String VarInfo] data VarInfo = VBox String | VArg Int | VItem VarInfo Int main = interact (compile . parse) constructorName (Constructor name _) = name functionName (Function name _ _) = name equationName (Equation name _ _ _) = name sortToplevels [] = (P [] []) sortToplevels (TD x : xs) = applyFst ((:) x) (sortToplevels xs) sortToplevels (TE x : xs) = applySnd ((:) x) (sortToplevels xs) sortToplevels (TO : xs) = sortToplevels xs pcons x xs = PCon "Cons" [x, xs];pnil = PCon "Nil" [] ebinary op a b = Ap (Ap (Var op) a) b;ebinaryE op a b = Ap (Ap op a) b econs x xs = Ap (Ap (Con "Cons") x) xs enil = Con "Nil" listEq eq [] [] = True listEq eq (x:xs) (y:ys) | eq x y = listEq eq xs ys listEq _ _ _ = False snd (P a b) = b zip = zipWith P lookup q (P k v : _) | listEq (==) q k = Just v lookup q (_ : xs) = lookup q xs lookup q _ = Nothing compose2 f g x y = f (g x y) applyFst f (P x y) = P (f x) y applySnd f (P x y) = P x (f y) fMaybe f Nothing = Nothing fMaybe f (Just x) = Just (f x) cond f t False = f cond f t True = t condList f t [] = f condList f t xs = t xs countFrom n = n : countFrom (add n 1) range l h | l > h = [] range l h = l : range (add l 1) h parse = makeProgram . sortToplevels . concatMap parse_p . ((:) prelude) . preprocess parse_p (P lineno line) = maybe (parse_err lineno line) snd (parseLine line) parse_err lineno line = error (concat ["Parse error on line ", showInt lineno, ": `", line, "`"]) preprocess = filter (not . isCommentOrEmpty . snd) . zip (countFrom 1) . map (dropWhile isBlank) . lines isCommentOrEmpty = parserSucceeds (pro (ignore (pro (parseS "--") (parseS "import "))) parseEof) liftA2 f a b = ap (fmap f a) b parserSucceeds p s = maybe False (const True) (p s) fmap f p = fMaybe (applySnd f) . p pure x s = Just (P s x) ap1 b (P s x) = maybe Nothing (ap2 x) (b s) ap2 x (P s y) = Just (P s (x y)) empty = (const Nothing) pro a b s = maybe (b s) Just (a s) ap a b = maybe Nothing (ap1 b) . a prc = liftA2 (:) pra = liftA2 append prl = liftA2 const prr = liftA2 (const id) many p = pro (some p) (pure []) some p = prc p (many p) optional p = pro (fmap Just p) (pure Nothing) choice = foldr pro (const Nothing) parseEof = parseEof_1 parseEof_1 [] = Just (P "" B) parseEof_1 _ = Nothing parsePred pred = parsePred_1 pred parsePred_1 pred (x:xs) | pred x = Just (P xs x) parsePred_1 _ _ = Nothing manyParsePred = justFlipSplit justFlipSplit pred xs = Just (P (dropWhile pred xs) (takeWhile pred xs)) someParsePred pred = prc (parsePred pred) (manyParsePred pred) parseC = parsePred . (==) parseS = foldr (prc . parseC) (pure []) wrapC = wrapSpace . parseC wrapS = wrapSpace . parseS skipPred pred = prr (parsePred pred) (pure B) manySkipPred pred = prr (manyParsePred pred) (pure B) preSep p sep = many (prr sep p) sepBy1 p sep = prc p (many (prr sep p)) sepByChar p c = pro (sepByChar1 p c) (pure []) sepByChar1 p c = sepBy1 p (wrapSpace (parseC c)) wrapSpace p = prl (prr skipSpace p) skipSpace ignore = fmap (const B) isBlank c | c == ' ' || c == '\t' = True isBlank _ = False isDigit1 c = c >= '1' && c <= '9' parseBetween l r p = prl (prr (parseC l) (wrapSpace p)) (parseC r) skipSpace = manySkipPred isBlank chainl1 f sep p = fmap (foldl1 f) (sepBy1 p sep) chainr1 f sep p = fmap (foldr1 f) (sepBy1 p sep) chainl f z sep p = pro (fmap (foldl f z) (sepBy1 p sep)) (pure z) chainr f z sep p = pro (fmap (foldr f z) (sepBy1 p sep)) (pure z) parseNonassoc ops term = liftA2 (flip ($)) term (pro (liftA2 flip (choice ops) term) (pure id)) parseVar = prc (parsePred (orUnderscore isLower)) (many (parsePred (orUnderscore isAlphaNum))) orUnderscore p c | p c || c == '_' = True orUnderscore _ _ = False parseCon = prc (parsePred isUpper) (many (parsePred (orUnderscore isAlphaNum))) parseInt = pro (parseS "0") (prc (parsePred isDigit1) (many (parsePred isDigit))) parseEscape q (c:x:xs) | c == '\\' = Just (P xs (c:x:[])) parseEscape q [c] | c == '\\' = Just (P [] [c]) parseEscape q (c:xs) | c /= q = Just (P xs [c]) parseEscape q _ = Nothing parseStringLiteral q = pra (parseS [q]) (pra (fmap concat (many (parseEscape q))) (parseS [q])) parsePattern = chainr1 pcons (wrapC ':') (pro (liftA2 PCon parseCon (preSep parsePatternPrimary skipSpace)) parsePatternPrimary) parsePatternPrimary = choice [fmap PVar parseVar, fmap (flip PCon []) parseCon, parseBetween '(' ')' parsePattern, parseBetween '[' ']' (fmap (foldr pcons pnil) (sepByChar parsePattern ','))] relops f = relops_1 (ops_c f) otherops f = f ":" (Con "Cons") : otherops_1 (ops_c f) ops_c f x y = f x (Var y) relops_1 f = [f "<=" "_le", f "<" "_lt", f "==" "_eq", f ">=" "_ge", f ">" "_gt", f "/=" "_ne"] otherops_1 f = [f "$" "_apply", f "||" "_or", f "&&" "_and", f "." "_compose"] parseRelops = parseNonassoc (relops parseRelops_f) parseRelops_f op func = prr (wrapS op) (pure (ebinaryE func)) parseExpression = chainr1 (ebinary "_apply") (wrapC '$') $ chainr1 (ebinary "_or") (wrapS "||") $ chainr1 (ebinary "_and") (wrapS "&&") $ parseRelops $ chainr1 econs (wrapC ':') $ chainr1 (ebinary "_compose") (wrapC '.') $ chainl1 Ap skipSpace $ choice [fmap Var parseVar, fmap Con parseCon, fmap Int parseInt, fmap Char (parseStringLiteral '\''), fmap String (parseStringLiteral '"'), parseBetween '(' ')' (pro parseSection parseExpression), parseBetween '[' ']' (chainr econs enil (wrapC ',') parseExpression)] parseSection = choice (append (relops parseSection_f) (otherops parseSection_f)) parseSection_f op func = prr (wrapS op) (pure func) parseEquation = ap (ap (ap (fmap Equation parseVar) (many (prr skipSpace parsePatternPrimary))) (optional (prr (wrapC '|') parseExpression))) (prr (wrapC '=') parseExpression) skipType = ignore (sepBy1 (sepBy1 skipTypePrimary skipSpace) (wrapS "->")) skipTypePrimary = choice [ignore parseVar, ignore parseCon, parseBetween '(' ')' skipType, parseBetween '[' ']' skipType] parseDataDecl = prr (parseS "data") (prr skipSpace (prr parseCon (prr (preSep parseVar skipSpace) (prr (wrapC '=') (sepByChar1 (liftA2 Constructor parseCon (fmap length (preSep skipTypePrimary skipSpace))) '|'))))) skipTypeSignature = prr parseVar (prr (wrapS "::") skipType) skipTypeAlias = prr (parseS "type") (prr skipSpace (prr parseCon (prr (preSep parseVar skipSpace) (prr (wrapC '=') skipType)))) parseToplevel = choice [fmap (const TO) (pro skipTypeSignature skipTypeAlias), fmap TD parseDataDecl, fmap TE parseEquation] parseLine = prl (prl (sepByChar1 parseToplevel ';') skipSpace) parseEof patternCount (Equation _ ps _ _) = length ps makeProgram (P ds es) = Program ds (makeFunctions es) makeFunctions = map makeFunctions_f . groupBy makeFunctions_g makeFunctions_f [] = error "Internal error: No equations in binding group" makeFunctions_f (x:xs) = cond (error (concat ["Equations for ", equationName x, " have different numbers of arguments"])) (Function (equationName x) (patternCount x) (x:xs)) (all (((==) (patternCount x)) . patternCount) xs) makeFunctions_g (Equation name_a _ _ _) (Equation name_b _ _ _) = listEq (==) name_a name_b lookupCon name (Environment c _) = lookup name c lookupVar name (Environment _ v) = lookup name v walkPatterns f = walkPatterns_items f VArg walkPatterns_items f base = concat . zipWith (walkPatterns_f2 f) (map base (countFrom 0)) walkPatterns_f2 f v (PCon name ps) = append (f v (PCon name ps)) (walkPatterns_items f (VItem v) ps) walkPatterns_f2 f v p = f v p compile (Program decls funcs) = concat [header, declareConstructors decls, declareFunctions funcs, boxConstructors decls, boxFunctions funcs, compileConstructors decls, compileFunctions (globalEnv decls funcs) funcs] globalEnv decls funcs = Environment (append (globalEnv_constructorTags decls) (globalEnv_builtinConstructors)) (append (map (globalEnv_f . functionName) funcs) globalEnv_builtinFunctions) globalEnv_f name = (P name (VBox name)) globalEnv_constructorTags = concatMap (flip zip (countFrom 0) . map constructorName) globalEnv_builtinConstructors = [P "Nil" 0, P "Cons" 1, P "P" 0] globalEnv_builtinFunctions = map globalEnv_f ["add", "sub", "_lt", "_le", "_eq", "_ge", "_gt", "_ne", "_and", "_or", "divMod", "negate", "not", "error"] localEnv ps (Environment t v) = Environment t (append (walkPatterns localEnv_f ps) v) localEnv_f v (PVar name) = [P name v] localEnv_f _ (PCon _ _) = [] declareFunctions_f [] = "" declareFunctions_f xs = concat ["static Function ", intercalate ", " xs, ";\n"] declareConstructors = declareFunctions_f . map ((append "f_") . constructorName) . concat declareFunctions = declareFunctions_f . map ((append "f_") . functionName) boxConstructors = concatMap boxConstructors_f . concat boxConstructors_f (Constructor name n) = boxThing name n boxFunctions = concatMap boxFunctions_f boxFunctions_f (Function name n _) = boxThing name n boxThing name n | n == 0 = concat ["static Box b_", name, " = {0, f_", name, ", NULL};\n"] boxThing name n = concat ["static Partial p_", name, " = {", showInt n, ", 0, f_", name, "};\n", "static Box b_", name, " = {1, NULL, &p_", name, "};\n"] compileConstructors = concatMap (concat . zipWith compileConstructors_f (countFrom 0)) compileConstructors_f tag (Constructor name n) = concat ["static void *f_", name, "(Box **args)\n", "{\n", allocate n, "\tv->tag = ", showInt tag, ";\n", concatMap initialize (range 0 (sub n 1)), "\treturn v;\n", "}\n"] allocate n | n == 0 = "\tValue *v = malloc(sizeof(Value));\n\t(void) args;\n" allocate n = concat ["\tValue *v = malloc(sizeof(Value) + ", showInt n, " * sizeof(Box*));\n"] initialize i = concat ["\tv->items[", showInt i, "] = args[", showInt i, "];\n"] compileFunctions env = concatMap (compileFunction env) compileFunction env (Function name argc equations) = concat ["static void *f_", name, "(Box **args)\n", "{\n", concatMap (compileEquation env) equations, "\tNO_MATCH(", name, ");\n", "}\n"] compileEquation genv (Equation _ patterns guard expr) = compileEquation_a (localEnv patterns genv) patterns guard expr compileEquation_a env patterns guard expr = compileEquation_b (concat ["\treturn ", compileExpressionStrict env expr, ";\n"]) (append (compilePatterns env patterns) (compileGuard env guard)) compileEquation_b returnExpr preds = condList returnExpr (compileEquation_f returnExpr) preds compileEquation_f returnExpr xs = concat ["\tif (", intercalate " && " xs, ")\n\t", returnExpr] compilePatterns env = walkPatterns (compilePatterns_f env) compilePatterns_f _ _ (PVar name) = [] compilePatterns_f env v (PCon name ps) = compilePatterns_h v name (lookupCon name env) compilePatterns_h v name (Just n) = [concat ["match(", compileVarInfo v, ",", showInt n, ")"]] compilePatterns_h v name Nothing = error (append "Not in scope: data constructor " name) compileGuard env Nothing = [] compileGuard env (Just expr) = [concat ["isTrue(", compileExpressionStrict env expr, ")"]] compileExpressionStrict env (Var name) = concat ["force(", compileVar (lookupVar name env) name, ")"] compileExpressionStrict _ (Con name) = concat ["force(&b_", name, ")"] compileExpressionStrict _ (Int s) = concat ["mkInt(", s, ")"] compileExpressionStrict _ (Char s) = concat ["mkInt(", s, ")"] compileExpressionStrict _ (String s) = concat ["mkString(", s, ")"] compileExpressionStrict env (Ap f x) = concat ["apply(", compileExpressionStrict env f, ",", compileExpressionLazy env x, ")"] compileExpressionLazy env (Var name) = compileVar (lookupVar name env) name compileExpressionLazy _ (Con name) = concat ["&b_", name, ""] compileExpressionLazy _ (Int s) = concat ["box(mkInt(", s, "))"] compileExpressionLazy _ (Char s) = concat ["box(mkInt(", s, "))"] compileExpressionLazy _ (String s) = concat ["box(mkString(", s, "))"] compileExpressionLazy env (Ap f x) = concat ["deferApply(", compileExpressionLazy env f, ",", compileExpressionLazy env x, ")"] compileVar (Just v) _ = compileVarInfo v compileVar Nothing name = error (append "Not in scope: " name) compileVarInfo (VBox name) = append "&b_" name compileVarInfo (VArg n) = concat ["args[", showInt n, "]"] compileVarInfo (VItem v n) = concat ["item(", compileVarInfo v, ",", showInt n, ")"] header="#include <assert.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\ntypedef struct Box Box;\ntypedef struct Value Value;\ntypedef struct Partial Partial;\ntypedef void *Function(Box**);\nstruct Box{int state;Function *func;void*vc;Box*fx[];};\nstruct Value{int tag;Box *items[];};\nstruct Partial{int remaining;int applied;Function *func;Box *args[];};\n#define copy(...)memdup(&(__VA_ARGS__), sizeof(__VA_ARGS__))\n#define countof(...)(sizeof(__VA_ARGS__) / sizeof(*(__VA_ARGS__)))\n#define match(box, expectedTag)(((Value*)force(box))->tag == (expectedTag))\n#define item(box, n)(((Value*)(box)->vc)->items[n])\n#define isTrue(value)(!!*(int*)(value))\n#define NO_MATCH(func)fatal(\"Non-exhaustive patterns in function \" #func)\nstatic void fatal(const char *str){fprintf(stderr,\"*** Exception: %s\\n\", str);exit(EXIT_FAILURE);}\nstatic void *memdup(void *ptr, size_t size){void*ret=malloc(size);memcpy(ret,ptr,size);return ret;}\nstatic void *force(Box *box){switch(box->state){\ncase 0:box->state=2;box->vc=box->func(box->vc);box->state=1;\ncase 1:return box->vc;\ndefault:fatal(\"infinite loop\");}}\nstatic void *apply(Partial*f,Box*x){Partial*f2=malloc(sizeof(Partial)+(f->applied+1)*sizeof(Box*));\nmemcpy(f2->args,f->args,f->applied*sizeof(Box*));f2->args[f->applied]=x;\nif(f->remaining>1){f2->remaining=f->remaining-1;f2->applied=f->applied+1;f2->func=f->func;return f2;\n}else return f->func(f2->args);}\nstatic void*deferApply_cb(Box**a){return apply(force(a[0]),a[1]);}\nstatic Box*deferApply(Box*f,Box*x){\nBox*ret=malloc(sizeof(Box)+2*sizeof(Box*));\nret->state=0;\nret->func=deferApply_cb;\nret->vc=ret->fx;\nret->fx[0]=f;\nret->fx[1]=x;\nreturn ret;}\n\nstatic Box*defer(Function*func,void*ctx){\nBox*ret=malloc(sizeof(Box));\nret->state=0;\nret->func=func;\nret->vc=ctx;\nreturn ret;}\n\nstatic Box *box(void *value)\n{\n\tBox *ret = malloc(sizeof(Box));\n\tret->state = 1;\n\tret->func = NULL;\n\tret->vc = value;\n\treturn ret;\n}\n\nstatic int *mkInt(int n)\n{\n\tint *ret = malloc(sizeof(*ret));\n\t*ret = n;\n\treturn ret;\n}\n\nstatic Function f_Nil, f_Cons, f_P;\nstatic Box b_Nil, b_Cons, b_P, b_main;\n\n#define FUNCTION(name, argc) \\\n\tstatic Function f_##name; \\\n\tstatic Partial p_##name = {argc, 0, f_##name}; \\\n\tstatic Box b_##name = {1, NULL, &p_##name}; \\\n\tstatic void *f_##name(Box **args)\n\n#define intop(name, expr) \\\n\tFUNCTION(name, 2) \\\n\t{ \\\n\t\tint a = *(int*)force(args[0]); \\\n\t\tint b = *(int*)force(args[1]); \\\n\t\treturn mkInt(expr); \\\n\t}\n\n#define intop1(name, expr) \\\n\tFUNCTION(name, 1) \\\n\t{ \\\n\t\tint a = *(int*)force(args[0]); \\\n\t\treturn mkInt(expr); \\\n\t}\n\nintop(add, a + b)\nintop(sub, a - b)\n\nintop(_lt, a < b)\nintop(_le, a <= b)\nintop(_eq, a == b)\nintop(_ge, a >= b)\nintop(_gt, a > b)\nintop(_ne, a != b)\nintop(_and, a && b)\nintop(_or, a || b)\n\nintop1(negate, -a)\nintop1(not, !a)\n\nFUNCTION(divMod, 2)\n{\n\tint n = *(int*)force(args[0]);\n\tint d = *(int*)force(args[1]);\n\tint div = n / d;\n\tint mod = n % d;\n\t\n\tif ((mod < 0 && d > 0) || (mod > 0 && d < 0)) {\n\t\tdiv--;\n\t\tmod += d;\n\t}\n\t\n\tBox *pair[2] = {box(mkInt(div)), box(mkInt(mod))};\n\treturn f_P(pair);\n}\n\nstatic void *mkString(const char *str)\n{\n\tif (*str != '\\0') {\n\t\tBox *cons[2] =\n\t\t\t{box(mkInt(*str)), defer((Function*) mkString, (void*)(str + 1))};\n\t\treturn f_Cons(cons);\n\t} else {\n\t\treturn force(&b_Nil);\n\t}\n}\n\nstatic void putStr(Value *v, FILE *f)\n{\n\tif (v->tag == 1) {\n\t\tint c = *(int*)force(v->items[0]);\n\t\tputc(c, f);\n\t\tputStr(force(v->items[1]), f);\n\t}\n}\n\nFUNCTION(error, 1)\n{\n\tfflush(stdout);\n\tfputs(\"*** Exception: \", stderr);\n\tputStr(force(args[0]), stderr);\n\tputc('\\n', stderr);\n\texit(EXIT_FAILURE);\n}\n\nstruct mkStringFromFile\n{\n\tFILE *f;\n\tconst char *name;\n};\n\nstatic void *mkStringFromFile(struct mkStringFromFile *ctx)\n{\n\tint c = fgetc(ctx->f);\n\t\n\tif (c == EOF) {\n\t\tif (ferror(ctx->f))\n\t\t\tperror(ctx->name);\n\t\treturn force(&b_Nil);\n\t}\n\t\n\tBox *cons[2] = {box(mkInt(c)), defer((Function*) mkStringFromFile, ctx)};\n\treturn f_Cons(cons);\n}\n\nint main(void)\n{\n\tstruct mkStringFromFile c_in = {stdin, \"<stdin>\"};\n\tBox *b_in = defer((Function*) mkStringFromFile, copy(c_in));\n\tputStr(apply(force(&b_main), b_in), stdout);\n\treturn 0;\n}\n" prelude = P 0 "_apply f x=f x;_compose f g x=f(g x);data List a=Nil|Cons a(List a);data P a b=P a b;data B=B;data Maybe a=Nothing|Just a;data Bool=False|True;id x=x;const x _=x;flip f x y=f y x;foldl f z[]=z;foldl f z(x:xs)=foldl f(f z x)xs;foldl1 f(x:xs)=foldl f x xs;foldl1 _[]=error\"foldl1: empty list\";foldr f z[]=z;foldr f z(x:xs)=f x(foldr f z xs);foldr1 f[x]=x;foldr1 f(x:xs)=f x(foldr1 f xs);foldr1 _[]=error\"foldr1: empty list\";map f[]=[];map f(x:xs)=f x:map f xs;filter p[]=[];filter p(x:xs)|p x=x:filter p xs;filter p(x:xs)=filter p xs;zipWith f(x:xs)(y:ys)=f x y:zipWith f xs ys;zipWith f _ _=[];append[]ys=ys;append(x:xs)ys=x:append xs ys;concat=foldr append[];concatMap f=concat.map f;length[]=0;length(_:l)=add 1(length l);take n _|n<=0=[];take _[]=[];take n(x:xs)=x:take(sub n 1)xs;takeWhile p[]=[];takeWhile p(x:xs)|p x=x:takeWhile p xs;takeWhile _ _=[];dropWhile p[]=[];dropWhile p(x:xs)|p x=dropWhile p xs;dropWhile p xs=xs;span p[]=P[][];span p(x:xs)|p x=span_1 x(span p xs);span p xs=P[]xs;span_1 x(P ys zs)=P(x:ys)zs;break p=span(not.p);reverse=foldl(flip(:))[];groupBy _[]=[];groupBy eq(x:xs)=groupBy_1 x eq(span(eq x)xs);groupBy_1 x eq(P ys zs)=(x:ys):groupBy eq zs;maybe n f Nothing=n;maybe n f(Just x)=f x;all p=foldr(&&)True.map p;intersperse _[]=[];intersperse _[x]=[x];intersperse sep(x:xs)=x:sep:intersperse sep xs;intercalate xs xss=concat(intersperse xs xss);isDigit c=c>='0'&&c<='9';isAlphaNum c=c>='0'&&c<='9'||c>='A'&&c<='Z'||c>='a'&&c<='z';isUpper c=c>='A'&&c<='Z';isLower c=c>='a'&&c<='z';showInt n|n<0='-':showInt(negate n);showInt n|n==0=\"0\";showInt n|n>0=reverse(map(add 48)(showInt_1 n));showInt_1 n|n==0=[];showInt_1 n=showInt_2(divMod n 10);showInt_2(P div mod)=mod:showInt_1 div;lines []=[];lines s=lines_1(break((==)'\\n')s);lines_1(P l[])=[l];lines_1(P l(_:s))=l:lines s;interact=id" ``` [Answer] # Custom Language → C - (7979) Since the question doesn't preclude creating my own language, I thought I'd give that a try. ## The Environment The language has access to two stacks, The Call Stack, and The Data Stack. The Call Stack is used for the jumping instructions `{` and `}`, while The Data Stack is used by most other instructions. The Call Stack is opaque to applications. The Data Stack can hold three different types of values: integer, text, and empty. Integers are of type intptr\_t, while text is stored as C-style strings. The `^` instruction has access to The Array. The Array is a constant array of length 17 of text items. You should probably see the source for the indexing scheme since it's a little wonky. ## The Language ``` # - Begin number - Marks the beginning of a number, for example: #42. . - End number - Marks the end of a number and pushes it to the data stack. ^ - Translate - Pops a number, and pushes the corresponding text from The Array. < - Write - Pops a value, and prints it to stdout. > - Read - Reads a character from stdin and pushes it as a number. If EOF, exit. { - Start Loop - Pushes the current location in the program to the call stack. } - End Loop - Go to the position specified by the top of the call stack. + - Add - Pop two numbers from the data stack, add them, push the result. - - Subtract - Pop into A, pop into B, push B - A. Both B & A must be numbers. ! - Duplicate - Pop from The Data Stack, push that value twice. _ - Discard - Pop from The Data Stack. = - Skip if Equal - Pop two values, if they are equal skip the next instruction and pop one item from the call stack. ? - Loop - Pop one number, subtract one, if it's less than one, pop one item from the call stack and skip the next instruction. @ - Array Separator - Marks the end of an array item. $ - Program End - Marks the end of the program. ``` ## The Compiler This is the compiler. It isn't golfed, and I expect it could be cut down considerably. It should be possible to use machine code directly and output a dos COM file, but I haven't gotten around to that yet. I know this looks like a C program, but the actual compiler implementation is down at the end. Currently the compiler generates a lot of debugging information on stderr. ``` #include <string.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <setjmp.h> #include <stdbool.h> const char* position; const char* array[] = {"@"}; void die(const char* reason) { fprintf(stderr, "%s\n", reason); exit(1); } // // Stack Functions // #define T_EMPTY (0) #define T_NUMBER (1) #define T_TEXT (2) typedef struct { unsigned char type; union { const char* text; intptr_t number; }; } stack_entry; #define STACK_MAX (1024) stack_entry stack[STACK_MAX]; size_t stack_position = 0; stack_entry* _push() { if (stack_position >= STACK_MAX) { die("out of stack space"); } return &stack[stack_position++]; } void push(stack_entry v) { if (v.type == T_EMPTY) { fprintf(stderr, "\tpushed: None\n"); } else if (v.type == T_TEXT) { fprintf(stderr, "\tpushed: %s\n", v.text); } else { fprintf(stderr, "\tpushed: %d\n", v.number); } stack_entry* entry = _push(); *entry = v; } void push_empty() { fprintf(stderr, "\tpushed: None\n"); stack_entry* entry = _push(); entry->type = T_EMPTY; entry->number = 0; } void push_number(intptr_t number) { fprintf(stderr, "\tpushed: %d\n", number); stack_entry* entry = _push(); entry->type = T_NUMBER; entry->number = number; } void push_text(const char* text) { fprintf(stderr, "\tpushed: %s\n", text); stack_entry* entry = _push(); entry->type = T_TEXT; entry->text = text; } // Polymorphic Push (for literals) #define PUSH0() do { fprintf(stderr, "literal:\n"); push_empty(); } while (0) #define PUSH1(a) do { fprintf(stderr, "literal:\n"); push_number(a); } while (0) #define GET_MACRO(_0, _1, NAME, ...) NAME #define PUSH(...) GET_MACRO(_0, ##__VA_ARGS__, PUSH1, PUSH0)(__VA_ARGS__) stack_entry pop() { if (stack_position <= 0) { fprintf(stderr, "\tpopped: None\n"); return (stack_entry) {.type = T_EMPTY, .number = 0}; } stack_entry v = stack[--stack_position]; if (v.type == T_EMPTY) { fprintf(stderr, "\tpopped: None\n"); } else if (v.type == T_TEXT) { fprintf(stderr, "\tpopped: %s\n", v.text); } else { fprintf(stderr, "\tpopped: %d\n", v.number); } return v; } stack_entry peek() { if (stack_position <= 0) { return (stack_entry) {.type = T_EMPTY, .number = 0}; } return stack[stack_position-1]; } // // Jump Functions // #define JUMP_MAX (1024) jmp_buf jump[JUMP_MAX]; size_t jump_position = 0; #define start() \ do { \ if (jump_position >= JUMP_MAX) { \ die("out of jump space"); \ } \ fprintf(stderr, "start: %d\n", jump_position); \ setjmp(jump[jump_position++]); \ } while (0) void pop_jump() { if (jump_position <= 0) { die("empty jump stack"); } jump_position -= 1; } #define end() \ do { \ if (jump_position <= 0) { \ die("empty jump stack"); \ } \ fprintf(stderr, "end: %d\n", jump_position-1); \ longjmp(jump[jump_position-1],1); \ } while (0) // // Program functions // void translate() { fprintf(stderr, "translate:\n"); stack_entry entry = pop(); if (entry.type == T_TEXT) { die("translating text"); } else if (entry.type == T_EMPTY) { push_empty(); } else { switch (entry.number) { case 0: case 1: push_text(array[entry.number]); break; case 64: push_text(array[2]); break; case 94: push_text(array[3]); break; case 45: push_text(array[4]); break; case 43: push_text(array[5]); break; case 62: push_text(array[6]); break; case 60: push_text(array[7]); break; case 33: push_text(array[8]); break; case 95: push_text(array[9]); break; case 61: push_text(array[10]); break; case 63: push_text(array[11]); break; case 123: push_text(array[12]); break; case 125: push_text(array[13]); break; case 35: push_text(array[14]); break; case 46: push_text(array[15]); break; case 36: push_text(array[16]); break; default: push_empty(); break; } } } void subtract() { fprintf(stderr, "subtract:\n"); stack_entry v1 = pop(); stack_entry v2 = pop(); if (v1.type != T_NUMBER || v2.type != T_NUMBER) { die("not a number"); } push_number(v2.number - v1.number); } void add() { fprintf(stderr, "add:\n"); stack_entry v1 = pop(); stack_entry v2 = pop(); if (v1.type != T_NUMBER || v2.type != T_NUMBER) { die("not a number"); } push_number(v2.number + v1.number); } void read() { fprintf(stderr, "read:\n"); int in = getchar(); if (in >= 0) { push_number(in); } else { die("end of input"); } } void write() { fprintf(stderr, "write:\n"); stack_entry v = pop(); if (v.type == T_NUMBER) { putchar(v.number); } else if (v.type == T_TEXT) { const char* x = v.text; char y; while (0 != (y=*(x++))) { y -= 128; putchar(y); } } } void duplicate() { fprintf(stderr, "duplicate:\n"); stack_entry v = pop(); push(v); push(v); } void discard() { fprintf(stderr, "discard:\n"); pop(); } bool equals() { fprintf(stderr, "equals:\n"); stack_entry x = pop(); stack_entry y = pop(); bool skip; if (x.type != y.type) { skip = false; } else if (x.type == T_EMPTY) { skip = true; } else if (x.type == T_NUMBER) { skip = x.number == y.number; } else { skip = strcmp(x.text, y.text) == 0; } if (skip) { pop_jump(); } return !skip; } bool question() { fprintf(stderr, "question:\n"); stack_entry x = pop(); intptr_t value; if (x.type == T_EMPTY) { value = 0; } else if (x.type == T_NUMBER) { value = x.number; } else { die("it is bad form to question text"); } value -= 1; if (value < 1) { pop_jump(); return false; } else { push_number(value); return true; } } int main() { @","@translate();@subtract();@add();@read();@write();@duplicate();@discard();@if(equals())@if(question())@start();@end();@PUSH(@);@return 0;}@ #0.^< Emit the preface #17.{ Loop for as many array slots exist #.{<>#128.+!#192.=} Copy characters, adding 128 until reaching an at sign #128.- ^< Emit the code between array items ?} Return to start #1.^< Emit the prologue {{ >!^< Read character, translate it, and print it !#35.=} Check if we have a literal #.{<>!#46.=}^< If so, verbatim copy characters until a period } Continue executing $ ``` To compile the generated C code: ``` gcc -finput-charset=CP437 -fexec-charset=CP437 -std=gnu11 ``` The charset is required because the compiler escapes special characters by adding 128. ## The Bootstrap To compile the first compiler, I wrote a python interpreter for the language. ``` import sys from collections import defaultdict KEYS = [0,1] + map(ord, ['@','^','-','+','>','<','!','_','=','?','{','}','#','.','$']) # Read the source file with file(sys.argv[1]) as f: data = f.read() pos = 0 # Initialize the environment array = defaultdict(str) jmp = [] stk = [] def log(x): sys.stderr.write(x + '\n') def read(): global pos,data pos += 1 return data[pos-1] def pop(): global stk try: x = stk.pop() except IndexError: x = None log('\tpopped ' + repr(x)) return x def push(value): global stk log('\tpushing ' + repr(value)) stk.append(value) # Read the array initialization section for key in KEYS: while True: c = read() if c == '@': break array[key] += c # Execute the program while pos < len(data): c = read() if c == '^': log('translate:') push(array.get(pop(), None)) elif c == '-': log('subtract:') x = pop() y = pop() push(y - x) elif c == '+': log('add:') x = pop() y = pop() push(y + x) elif c == '>': log('read:') push(ord(sys.stdin.read(1))) elif c == '<': log('write:') v = pop() if isinstance(v, int): sys.stdout.write(chr(v)) elif v is not None: sys.stdout.write(v) elif c == '!': log('duplicate:') x = pop() push(x) push(x) elif c == '_': log('discard:') pop() elif c == '=': log('skip if equal:') x,y = pop(),pop() if x == y: pos += 1 jmp.pop() elif c == '?': log('loop:') x = pop() x -= 1 if x < 1: pos += 1 jmp.pop() else: push(x) elif c == '{': log('start: ' + repr(pos)) jmp.append(pos) elif c == '}': log('end:') pos = jmp[-1] elif c == '#': literal = '' while True: c = read() if c == '.': log('literal: ' + repr(literal)) if literal == '': push(None) else: push(int(literal)) break else: literal += c ``` ## Putting It All Together Assuming you've saved the compiler as `compiler.cmp` and the bootstrap as `bootstrap.py`, here's how to build the compiler, and then use it to compile itself: ``` $ cat compiler.cmp | python bootstrap.py compiler.cmp 2> trace-bootstrap | gcc -finput-charset=CP437 -fexec-charset=CP437 -std=gnu11 -o result -xc - $ cat compiler.cmp | ./result 2> trace-final ``` So I'm not much of a C programmer, nor am I much of a language designer, so any suggestions on improving this are quite welcome! ## Example Programs ### Hello, World! ``` Hello, World!@@@@@@@@@@@@@@@@@#0.^<$ ``` [Answer] # [Extended Brainfuck](http://sylwester.no/ebf/) v0.9: 618 bytes (not counting the uneccesary linefeeds) ``` :c:n:z:g:i:t:w:a:p++++++++[->++++++++<]>[->>>>>>>[>>>>>>>>]+[<<<<<<<<]>]>>>>>>>[->>>>>>>>]@i $i,[[-$t+$w+$i]$t[-$i+$t]+$a+++[-$w-----------$a]$w---[$a++[-$w-----------$a]$w[--[--[--[$i. $t+++++++[-$w++++++++$t]$w[-]]$t[-$p[-]$i.$n,.[-<[<<]+[>>]<]@n$c[<<]>[-<<<+>>>>[>>]@z$p+$c[< <]>]<<<[->>>+<<<]>>>>[->>]@z$t]$w]$t[-$i.$p+$t]$w]$t[-$i.$p-$t]$w]$t[$i.$n,.[-<[<<]+[>>]<]@n $g[-$t+$c[<<]>+>[>>]@z>]$c[<<]>>[->>]@z$t[-$g+$t]$t]$w]$t[-$i.[-]$n,.[-<[<<]+[>>]<]@n$c[<<]> [-<<<+>>>>[>>]@z$i+$a+$c[<<]>]<<<[->>>+<<<]>>>>[->>]@z<++++++[->++++++++++<]$w+$p[$a[-$w-]<[ @w-$p[-$z.$p]+$t]$w+$p-]$z++$w-$a[-$z.$a]$z[-]$i[-$p+$i]$t]$w$i,] ``` This is a golfed version of my [very first version of EBF](https://github.com/westerp/ebf-compiler/blob/34c378c8347aafa5dbf37f4973461d42c8120ea4/ebf.ebf) with removed support for comments and dead code to support removing of variables. So basically it's [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck) with variables. `:x` creates variables x. The compiler knows where you are so `$y` will produce <'s and >'s to get to that position. Sometimes you need asymmetric loops and then you need to tell the compiler where you are with `@x`. As current EBF it compiles to Brainfuck. This first version had only one char variable names, but I have used this version to compile the next version and so on until the current version that has an impressive feature set. When compiling from github source it actually downloads the handcompiled binary to bootstrap 6 intermediate ebf versions in order to create the current version. To bootstrap it you may use this [first and only binary](https://github.com/westerp/ebf-compiler/blob/34c378c8347aafa5dbf37f4973461d42c8120ea4/ebf-handcompiled.bf) in the EBF git repository which was compiled by hand successfully after a couple of tries. ``` wget -nv https://raw.githubusercontent.com/westerp/ebf-compiler/34c378c8347aafa5dbf37f4973461d42c8120ea4/ebf-handcompiled.bf beef ebf-handcompiled.bf < ebf09.ebf > ebf09a.bf beef ebf09a.bf < ebf09.ebf > ebf09b.bf diff -s ebf09a.bf ebf09b.bf # Files ebf09a.bf and ebf09b.bf are identical ``` Brainfuck has a few hardware implementations, eg. [this](http://vonkonow.com/wordpress/2013/09/my-first-brainfuck-computer/), [this](http://gergo.erdi.hu/blog/2013-01-19-a_brainfuck_cpu_in_fpga/) and [this](http://grapsus.net/74/) to mention a few. But mostly it's so easy to implement you can practically implement an interpreter on any system at all. I use to joke that [Zozotez LISP](http://sylwester.no/zozotez/), which is written in EBF, probably is the most portable LISP ever. [Answer] ## Hex, 550 bytes This specifically targets x86\_64 systems running Linux. ``` 7f454c4602010100000000000000000002003e0001000000780040000000000040000000000000000000000000000000000000004000380001004000000000000100000005000000000000000000000000004000000000000000400000000000130100000000000013010000000000000000200000000000e81700000085c07c0b31ff01c7e879000000ebec31c089c7b03c0f05e84c0000004885c07c203c2178f2741b89c7e825000000c0e00450e83100000089c7e8150000005900c8c3e8210000003c0d7ff774ca3c0a75f1ebc489f831c93c400f9cc148ffc980e12780c13028c8c36a004889e631c089c2fec289c70f0531c985c0580f95c148ffc94809c8c3574889e631c0fec089c289c70f0558c3 ``` In this language, source code consists of bytes represented as two lowercase hexadecimal digits, `[0-9a-f][0-9a-f]`. These bytes may have any amount of surrounding whitespace, but nothing may occur between the digits that form a single byte. Further, `'!'` is a line-comment character: it is ignored, as well as everything between it and the next `'\n'` character. If you understand x86 assembly, here's a much more readable version of the source code: ``` ! ELF Header !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 7f 45 4c 46 !e_ident[EI_MAG0] (0x7F "ELF") 02 !e_ident[EI_CLASS] (64-bit) 01 !e_ident[EI_DATA] (little-endian) 01 !e_ident[EI_VERSION] (ELF v1) 00 !e_ident[EI_OSABI] (System V ABI) 00 !e_ident[EI_ABIVERSION] (version 0) 00 00 00 00 00 00 00 !e_ident [EI_PAD] 02 00 !e_type (executable) 3e 00 !e_machine (x86_64) 01 00 00 00 !e_version (ELF v1) 78 00 40 00 00 00 00 00 !e_entry (0x40078) 40 00 00 00 00 00 00 00 !e_phoff (0x 40) 00 00 00 00 00 00 00 00 !e_shoff (0x 0) 00 00 00 00 !e_flags 40 00 !e_ehsize (ELF header size = 64 bytes) 38 00 !e_phentsize (Program headers = 56 bytes) 01 00 !e_phnum (1 program header) 40 00 !e_shentsize (Section headers = 64 bytes) 00 00 !e_shnum (no section headers) 00 00 !e_shstrndx (section names, not useful here) ! Program Headers !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 01 00 00 00 !p_type (LOAD) 05 00 00 00 !p_flags (R+E) 00 00 00 00 00 00 00 00 !p_offset (file-loc 0) 00 00 40 00 00 00 00 00 !p_vaddr (vmem-loc 0x40000) 00 00 40 00 00 00 00 00 !p_paddr (pmem-loc 0x40000) 13 01 00 00 00 00 00 00 !p_filesz (length 0x113 bytes) 13 01 00 00 00 00 00 00 !p_memsz (allocate 0x113 bytes) 00 00 20 00 00 00 00 00 !p_align (align pages in 0x20000 increments) ! Program Code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! _start: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! e8 17 00 00 00 ! callq _gethx 85 c0 ! test %eax,%eax 7c 0b ! jl .+11 31 ff ! xor %edi,%edi 01 c7 ! add %eax,%eax e8 79 00 00 00 ! callq _putch eb ec ! jmp .-20 31 c0 ! xor %eax,%eax 89 c7 ! mov %eax,%edi b0 3c ! mov $0x3c,%al 0f 05 ! syscall !! _gethx: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! e8 4c 00 00 00 ! callq _getch 48 85 c0 ! test %rax,%rax 7c 20 ! jl _gethx+42 3c 21 ! cmp $0x21,al 78 f2 ! js _gethx 74 1b ! je _gethx+43 89 c7 ! mov %eax,%edi e8 25 00 00 00 ! callq _h2d c0 e0 04 ! sal $4,%al 50 ! push %rax e8 31 00 00 00 ! callq _getch 89 c7 ! mov %eax,%edi e8 15 00 00 00 ! callq _h2d 59 ! pop %rcx 00 c8 ! add %cl,%al c3 ! retq e8 21 00 00 00 ! callq _getch 3c 0d ! cmp $0xd,%al 7f f7 ! jg _gethx+43 74 ca ! je _gethx 3c 0a ! cmp $0xa,%al 75 f1 ! jne _gethx+43 eb c4 ! jmp _gethx !! _h2d: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 89 f8 ! mov %edi,%eax 31 c9 ! xor %ecx,%ecx 3c 40 ! cmp $0x40,%al 0f 9c c1 ! setl %cl 48 ff c9 ! dec %rcx 80 e1 27 ! and $0x27,%cl 80 c1 30 ! add $0x30,%cl 28 c8 ! sub %cl,%al c3 ! retq !! _getch: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 6a 00 ! push $0 48 89 e6 ! mov %rsp,%rsi 31 c0 ! xor %eax,%eax 89 c2 ! mov %eax,%edx fe c2 ! inc %dl 89 c7 ! mov %eax,%edi 0f 05 ! syscall 31 c9 ! xor %ecx,%ecx 85 c0 ! test %eax,%eax 58 ! pop %rax 0f 95 c1 ! setne %cl 48 ff c9 ! dec %rcx 48 09 c8 ! or %rcx,%rax c3 ! retq !! _putch: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 57 ! push %rdi 48 89 e6 ! mov %rsp,%rsi 31 c0 ! xor %eax,%eax fe c0 ! inc %al 89 c2 ! mov %eax,%edx 89 c7 ! mov %eax,%edi 0f 05 ! syscall 58 ! pop %rax c3 ! retq ``` If you extract the assembly language from the comments below `! Program Code`, you can assemble and run the Hex compiler. Input and output use stdin and stdout. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes (possibly non-competing) ``` .V ``` [Try it online!](http://05ab1e.tryitonline.net/#code=LlY&input=KwoxNwo4) Code on the first line of input, inputs on subsequent lines. [Answer] # [Nil](http://esolangs.org/wiki/Nil), 0 bytes > > Incredibly, despite not being Turing-complete, the Nil language is expressive enough to implement an interpreter for itself, much more concisely than many 'proper' languages can. The example presented here is a simple implementation, but using advanced compression techniques Nil developers have been able to produce working interpreters in as little as 0 lines of code. > > > [Answer] ## [Lumber](https://github.com/UnrelatedString/lumber), 0 bytes Lumber is a complete esoteric programming language invented by [Unrelated String](https://github.com/UnrelatedString) written in just 10 lines of Prolog code. Can't believe it? These programs had comments removed and makes the interpreter source more concise. lumber\_corefuncs.pl: ``` :- use_module(lumber_types). ``` lumber\_types.pl ``` :- module(lumber_types, []). ``` lumber\_corefuncs.pl takes in the library lumber\_types; and in turn, this library defines a module with nothing in it. Therefore, Lumber does nothing on arbitary inputs, which is in turn a self-compiler. ]
[Question] [ I know, the title cracks you up --- Given an amount of money, output the fewest number of **coins** that make up that amount. ## Examples ``` 0.1 1 dime 0.01 1 penny 0.28 1 quarter 3 penny 0.56 2 quarter 1 nickel 1 penny 1.43 5 quarter 1 dime 1 nickel 3 penny ``` ## Spec * 100 cents in a dollar. * The values of each type of coin is: + `penny` 1 cent + `nickel` 5 cents + `dime` 10 cents + `quarter` 25 cents Built-ins which trivialize this task are not allowed. ## I/O Input is a decimal representing the dollar value of the total * No need to pluralize * Order: `quarter` -> `penny` * Output should be `<#_of_coins> <coin type>` * Separators: `,` or `,` (comma and a space) or The only trailing whitespace allowed is a single trailing newline/space. --- **If there is zero of a coin type, that coin type should not be shown**. E.g. `0.25` -> `1 quarter` **not** `1 quarter 0 dime 0 nickel 0 penny` [Answer] # JavaScript ES6, 107 bytes ``` n=>((n*=100)/25|0)+` quarter ${(n%=25)/10|0} dime ${n%10/5|0} nickel ${n%5|0} penny`.replace(/ ?0 \S+/g,"") ``` Simple maths. [Answer] ## Python 2, 120 bytes ``` n=int(round(input()*100)) a=25 for b in"quarter","dime","nickel","penny": if n>=a:print"%d "%(n/a)+b, n%=a;a=40/a+5^12 ``` Just to be safe, changed to something that definitely works to fix @Ogaday's comment, for now at least. I'm uncertain whether or not I need the `int()` as well, but I'm having trouble convincing myself that I don't. ``` print`n/a`+" "+b, ``` is an extra byte off, but prints an extra `L` for large inputs (although this code doesn't work for extremely large inputs anyway, due to float precision). [Answer] # dc, 104 Newlines added for *"readability"*: ``` [dn[ quarter ]n]sq [dn[ dime ]n]sd [dn[ nickel ]n]sn [d1/n[ penny ]n]sp ?A0* 25~rd0<qst A~rd0<dst 5~rd0<nst d0<p ``` [Answer] # CJam, 60 ``` q~e2i[25A5]{md}/]" quarterx dimex nickelx penny"'x/.+{0#},S* ``` This script seems to have alot of room for improvement but this is shorter than any so far. This makes use of the built in "md" command which returns both the integer result of a division and the remainder. It does the following: * reads input (if it were a function I guess you can remove q~ for two less characters) * multiples the input by 100 and converts it to an integer * performs "md" using [25 10 5] which results in the remainders on the stack * combines the numbers and coin names * removes the number and coin name if the former is 0 * adds pre-number zeros Try it [here](http://cjam.tryitonline.net/#code=cX5lMmlbMjVBNV17bWR9L10iIHF1YXJ0ZXJ4IGRpbWV4IG5pY2tlbHggcGVubnkiJ3gvLit7MCN9LFMq&input=MS4zOA) prior versions: ``` q~e2i[25A5]{md}/]_:!:!" quarter x dime x nickel x penny"'x/.*.+e_0- q~e2i[25A5]{md}/]_:!:!\" quarter x dime x nickel x penny"'x/.+.* ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 97 Thanks (as always) to @randomra - saved 1 byte. Assumes input is either in the form `xxx.yy` or `xxx.y`. ``` \..$ $&0 \. .+ $0$*: (:{25})+ $#1 quarter (:{10})+ $#1 dime (:{5})+ $#1 nickel (:)+ $#1 penny ``` [Try it online.](http://retina.tryitonline.net/#code=bWBcLi4kCiQmMApcLgoKLisKJDAkKjoKKDp7MjV9KSsKJCMxIHF1YXJ0ZXIgCig6ezEwfSkrCiQjMSBkaW1lIAooOns1fSkrCiQjMSBuaWNrZWwgCig6KSsKJCMxIHBlbm55&input=MC4xCjAuMDEKMC4yOAowLjU2CjEuNDM&args=) [Answer] # Vitsy, ~~110~~ ~~100~~ 97 bytes Yeah, hold on, I'm still methodizing this. ``` aa**Dv52^1m([N' retrauq 'Z]v52^MDva1m([N' emid 'Z]vDvaM51m([N' lekcin 'Z]v5MD([N'ynnep 'Z] /D1M-D ``` Explanation in soon-to-come verbose mode: ``` push a; push a; multiply top two; multiply top two; duplicate top item; save top as temporary variable; push 5; push 2; push second to top to the power of top; push 1; goto top method; if (int) top is 0; begin recursive area; output top as number; push " quarter "; output stack as chars; end recursive area; save top as temporary variable; push 5; push 2; push second to top to the power of top; modulo top two; duplicate top item; save top as temporary variable; push a; push 1; goto top method; if (int) top is 0; begin recursive area; output top as number; push " dime "; output stack as chars; end recursive area; save top as temporary variable; duplicate top item; save top as temporary variable; push a; modulo top two; push 5; push 1; goto top method; if (int) top is 0; begin recursive area; output top as number; push " nickel "; output stack as chars; end recursive area; save top as temporary variable; push 5; modulo top two; duplicate top item; if (int) top is 0; begin recursive area; output top as number; push " penny"; output stack as chars; end recursive area; : divide top two; duplicate top item; push 1; modulo top two; subtract top two; duplicate top item; ``` [Try it online!](http://vitsy.tryitonline.net/#code=YWEqKkR2NTJeMW0oW04nIHJldHJhdXEgJ1pddjUyXk1EdmExbShbTicgZW1pZCAnWl12RHZhTTUxbShbTicgbGVrY2luICdaXXY1TUQoW04neW5uZXAgJ1pdCi9EMU0tRA&input=&args=MS40Mw&debug=on) [Answer] # LabVIEW, 62 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) I created 2 arrays for the names and values and iterate through them from the top (index array with i) using a modulo operator (the R IQ thing). The remaining coins are passed into the shift register. If the value is bigger than 0 I convert the number to string and concatenate the passed down string, the number and the name of the coin and put it back into the shift register. I just realized my gif doesn´t show the false case but there is nothing to see anyway, it just passes through the string that came in. [![](https://i.stack.imgur.com/EgWqo.gif)](https://i.stack.imgur.com/EgWqo.gif) [Answer] # Java 8 lambda, 165 bytes Expects input `y` as either double or float. ``` y->{int c,d=(int)(y*100);return(((c=d/25)>0)?c+" quarter ":"")+(((c=(d=d%25)/10)>0)?c+" dime ":"")+(((c=(d=d%10)/5)>0)?c+" nickel ":"")+(((d=d%5)>0)?d+" penny":"");} ``` So much ternary. ;-; [Answer] # JavaScript ES6, ~~202~~ 200 bytes I hope this can be golfed... ``` r=>eval('i=[.25,.1,.05,.01];v=[0,0,0,0];for(k=0;k<4;k++)for(;r>=i[k];v[k]++,r-=i[k],r=((r*100+.01)|0)/100);v.map((x,i)=>x?x+" "+"quarter0dime0nickel0penny".split(0)[i]:"").join` `.replace(/ +/g," ")') ``` Ungolfed code: ``` function m(r){ i=[.25,.1,.05,.01] v=[0,0,0,0] for(k=0;k<4;k++)for(;r>=i[k];v[k]++,r-=i[k],r=((r*100+.01)|0)/100); return v.map((x,i)=>x?x+" "+"quarter0dime0nickel0penny".split(0)[i]:"").join(" ").replace(/ +/g," "); } ``` [Answer] # Japt, 77 bytes ``` ` {U*=L /25|0} quÂòr {U%=25 /A|0} ÜX {U%A/5|0} Íõel {U%5|0} p¿ny` r" 0 %S+" x ``` Thankfully, all four coin names are compressable. The `¿` should be the literal byte 0x81. [Test it online!](http://ethproductions.github.io/japt?v=master&code=YCB7VSo9TCAvMjV8MH0gcXXC8nIge1UlPTI1IC9BfDB9INxYIHtVJUEvNXwwfSDN9WVsIHtVJTV8MH0gcIFueWAgciIgMCAlUysiIHg=&input=LjM4) [Answer] ## C, ~~147~~ ~~144~~ ~~142~~ 140 bytes ``` a[]={25,10,5,1},m,i=0;f(float n){for(m=n*100;i<4;m%=a[i++])m/a[i]&&printf("%d %s ",m/a[i],(char*[]){"quarter","dime","nickel","penny"}[i]);} ``` Ungolfed with tests: ``` #include <stdio.h> a[]={25,10,5,1},m,i=0; f(float n) { for(m=n*100;i<4;m%=a[i++]) if(m/a[i]) printf("%d %s ",m/a[i],(char*[]){"quarter","dime","nickel","penny"}[i]); } int main() { float test[] = {.1, .01, .28, .56, 1.43}; for(int j = 0; j < 5; i = 0) { f(test[j++]); printf("\n"); } } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` т*ò25‰`T‰`5‰`)“œ¤æáeàë×ä“#øʒнĀ}˜ðý ``` Outputs with spaces like the examples. [Try it online](https://tio.run/##yy9OTMpM/f//YpPW4U1Gpo8aNiSEgAgwS/NRw5yjkw8tObzs8MLUwwsOrz48/fASoJjy4R2nJl3Ye6Sh9vScwxsO7/3/39BCz9gYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/i01ahzcZmT5q2JAQAiLALM1HDXOOTj605PCywwtTDy84vPrw9MNLgGLKh3ecmnRh75GG2tNzDm84vPe/zv9oAz1DHQUDPQMwaWQBIk3NdBQM9UyMgaSFnrFxLAA). **Explanation:** ``` т* # Multiply the (implicit) input-decimal by 100 ò # Bankers-round this to the nearest integer (to both prevent floating point # inaccuracies, as well as removing the ".0" from the ouput-numbers) 25‰ # Take the divmod-25 ` # Push both values separated to the stack T‰ # Take the divmod 10 on the top value ` # Push both values separated to the stack 5‰ # Take the divmod 5 on the top value ` # Push both values separated to the stack ) # Wrap all values on the stack into a list “œ¤æáeàë×ä“ # Push dictionary string "quarter dime nickel penny" # # Split it on spaces ø # Zip/transpose, creating pairs with the earlier integer list ʒ # Filter this list by: н # Where the first item (the integer) Ā # Is not 0 }˜ # After the filter: flatten the list of pairs ðý # And join this list with a space delimiter # (after which this is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“œ¤æáeàë×ä“` is `"quarter dime nickel penny"`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~185~~ 176 bytes ``` {' '∘(1↓,(/⍨)1(⊢∨⌽)0,≠)⍕,⍉(z[1;]≠0)/z←'quarter' 'dime' 'nickel' 'penny',[0.5]⍨{(⌊(⍵÷25)),(⌊(25|⍵)÷10),(⌊(10|25|⍵)÷5),⌊5|⍵}⍵×100} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqdQX1Rx0zNAwftU3W0dB/1LtC01DjUdeiRx0rHvXs1TTQedS5QPNR71SdR72dGlXRhtaxQAEDTf0qoF71wtLEopLUIqARKZm5qUAqLzM5OzUHyChIzcurVNeJNtAzjQWaWa3xqKdL41Hv1sPbjUw1NXXAXCPTGqCI5uHthgZQEUODGrigqaYOUAjMqwVpnG5oYFALdLOCgZ4hF4g0gFBGFmDK1AxIGeqZGHMBAA "APL (Dyalog Unicode) – Try It Online") The decomposition is in two parts: Computation, and Formatting Computation: ``` {(⌊(⍵÷25)),(⌊(25|⍵)÷10),(⌊(10|25|⍵)÷5),⌊5|⍵}⍵×100 { } A dfn that takes... ⍵×100 ...the input argument of the entire function, and multiplies by 100 to convert from dollars-and-cents to cents, then generates a vector, consisting of ... (⌊(⍵÷25)), ...the number of quarters, computed as the the round-down-to-integer of the number of cents divided by 25, followed by... (⌊(25|⍵)÷10), ...the number of dimes, computed as the round-down-to-integer of the remainder of the number of cents divided by 25, divided by 10, followed by... (⌊(10|25|⍵)÷5), ...the number of nickels, computed as the round-down-to-integer of the remainder from dividing (the remainder of the number of cents divided by 25) by ten, divided by five, followed by... ⌊5|⍵ ...the number of pennies, computed as the round-down-to-integer of the remainder from dividing the number of cents by five. ``` Computation is complete, and gives a vector of coin counts; the remainder is formatting: ``` ' '∘(1↓,(/⍨)1(⊢∨⌽)0,≠)⍕,⍉(z[1;]≠0)/z←'quarter' 'dime' 'nickel' 'penny',[0.5]⍨ Append the result of the computation to this expression 'quarter' 'dime' 'nickel' 'penny' Take a vector of coin names, and... ⍨ ...swap it with the computation result, then... ,[0.5] ...append the two along a 'side-by-side' axis. This gives a matrix which, if printed out, would have the coin counts above the coin name. Then... z← ...assign it to a temporary variable, and... (z[1;]≠0) ...generate a vector of 1s and 0s such that the 0s in this vector are in the same position as any 0s in the computation, then... / ...use that vector to compress out the columns in the matrix where the coin count is zero, then... ⍉ ...transpose the matrix along its main diagonal. This converts it to two columns; left is coin counts, right is coin names. Then... , ..."unravel" the matrix into a linear vector; the result now has the coin count followed by the coin name - but there will be too many spaces, so... ⍕ ...convert to a character representation instead of a vector of mixed objects, then... ' ' 0,≠ ...this is a fork, with left argument being the space all the way at the beginning (S), and right argument being the formatted string (F). It is interpreted as S 0 F , S ≠ F. S ≠ F generates a vector C of 0s and 1s, where the 0s are at the same positions as the spaces. S 0 F is a constant 0. 0 , C prepends a 0 to the vector C (C2). Then... 1(⊢∨⌽) ...we "go up a level" and see a new fork, 1 (⊢∨⌽) C2. This is interpreted as S 1 F (which is constant 1) (⊢∨⌽) S C2 F (which is constant C2). The central (⊢∨⌽) is itself a fork with arguments 1 and C2, so is interpreted as (1⊢C2)∨(1⌽C2). Dyadic ⊢ is right-identity, or C2, and 1⌽C2 takes the zero at the beginning of C2 and moves it to the end (C3). ∨ is logical OR, so C2 OR C3 gives a vector C4 of 1s and 0s where the 0s are positioned to correspond with the first space of a pair of consecutive spaces. This... ,(/⍨) ...becomes the right argument to /⍨ with the left argument being S , F. S , F is the formatted string with a space prepended (SF), so we now have SF /⍨ C4. ⍨ is an operator saying "swap the arguments of (in this case) /" so that we're really computing C4 / SF. Dyadic / with a left argument of 1s and 0s is "compression"; it returns those elements of its right argument that corresponds to 1s in the left argument. So, where C4 has a 0, the corresponding character in SF is omitted. Since C4 only had 0s where there was a space immediately before another space, the result is the compression of all multi-space substrings to single spaces. Then... 1↓ ...we drop the first character (a space) of the result. This gives us a string which contains no leading or trailing spaces, and no sequence of more than one space within the string. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 82 ~~106~~ ~~107~~ ``` '%i quarter %i dime %i nickel %i penny'i[.25 .1 .05]"@2#\w]100*Yo5$YD'0 \S+ ?'[]YX ``` Try it at [**MATL Online!**](https://matl.io/?code=%27%25i+quarter+%25i+dime+%25i+nickel+%25i+penny%27i%5B.25+.1+.05%5D%22%402%23%5Cw%5D100%2aYo5%24YD%270+%5CS%2B+%3F%27%5B%5DYX&inputs=0.28&version=12.0.1) [Answer] # JavaScript, ~~156~~ ~~145~~ 144 bytes No match to ETHproduction's formula answer, but anyway... ``` function c(t){n=['quarter','dime','nickel','penny'];v=[.25,.1,.05,.01];s='';for(i in v){c=t/v[i]|0;if(c>0)s+=c+' '+n[i]+' ';t-=c*v[i];}return s} ``` This is one of my first rounds of golfs, so any improvements are highly appreciated! I already stole ETH's "xor trunc" -- sorry man, it was just too smart :-) More readable: ``` function c(t) { n = ['quarter', 'dime', 'nickel', 'penny']; v = [.25, .1, .05, .01]; s = ''; for(i in v) { c = t/v[i]|0; if(c>0) s += c+' '+n[i]+' '; t -= c*v[i]; } return s } ``` Note: While testing I realised that JavaScript (at least on my machine?) divides `1.13 / 0.01` to `1.12999...`, making my (and probably all other JS submissions) not work 100% properly... [Answer] # [Kotlin](https://kotlinlang.org), 147 bytes ``` {listOf("quarter" to 25,"dime" to 10,"nickel" to 5,"penny" to 1).fold((it*100).toInt()){d,(n,a)->val z=d/a if(z>0){print("$z $n ") d-(z*a)}else d}} ``` ## Beautified ``` { listOf( "quarter" to 25, "dime" to 10, "nickel" to 5, "penny" to 1).fold((it * 100).toInt()) { d, (n, a) -> val z = d / a if (z > 0) { print("$z $n ") d - (z * a) } else d } } ``` ## Test ``` import java.io.ByteArrayOutputStream import java.io.PrintStream var f:(Double)->Unit = {listOf("quarter" to 25,"dime" to 10,"nickel" to 5,"penny" to 1).fold((it*100).toInt()){d,(n,a)->val z=d/a if(z>0){print("$z $n ") d-(z*a)}else d}} val TEST = listOf( 0.1 to "1 dime", 0.01 to "1 penny", 0.28 to "1 quarter 3 penny", 0.56 to "2 quarter 1 nickel 1 penny", 1.43 to "5 quarter 1 dime 1 nickel 3 penny" ) fun main(args: Array<String>) { val temp = ByteArrayOutputStream() System.setOut(PrintStream(temp)) for ((input, output) in TEST) { temp.reset() f(input) println() val text = temp.toString().trim() if (text != output) { throw AssertionError("$input '$output' != '$text'") } } } ``` ## TIO [TryItOnline](https://tio.run/##bVJLbtswEN3zFFPBgMlAUSWnLoqgNpCiWXSVAk4PwEZUykYi1dHIrW3o7A4/ciw04UIA+T7zRjNPlmptjkw3rUWC33IrM22zLztSN4hyd9dT29OGUMnmf9J31OYEsa1EqK75V9v/rJW4XP8wmmB1PNS6o7uKJ396iaQwAbKwWKZJqRsVLkWeJkY/PKk6XB3UKmN2ERNZZeuSc00XRZ6LjOw3Q1yIQ5lyk0pXZytr2K/K95Lpiu/XuTi0PhZPZnuYGUgEKy/5/kKKQdWdgnIYjsxr7m8397CCMR6D8eRZ4QsnBYSA6QTIT0jMN4UWn0Zo7BKu3iAtPwbS4oVUQOwbXlsW2YerwF5O2D7RWXQqwQRjVW+gkdpwiY/dNYTJfXaT0eZxLeAQbH3TpJrWNf3mdLkItM2uc6ysU+RAPhkx92IRSZVFcEMxTpyCDSYCtAk/9VTPHy/JUDmz0T2Io/D8EAZWmwklZv3nFihakI3NcLcBqJsJU1fAA/Pd6iXIuX7I8AvtX7jpOoWkrblFtOi2I2SA+SyK5l4/n3mneXJ2H1j8Dsdn) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~120~~ ~~118~~ 115 bytes *Inspired by [Veskah](https://codegolf.stackexchange.com/a/200798/80745)* ``` $n=100*"$args" ''+(25,10,5,1|%{for($i=0;($n-=$_)-ge0){++$i}$n+=$_ $i;(echo quarter dime nickel penny)[$p++]}|?{$i}) ``` [Try it online!](https://tio.run/##ZZDRToMwFIbv@xQn5ExaC0thYowL0fcwxizssBFZYQWiBnh2bKqwRXvRi@//v9OT1tUHmeZIZTlhnvYT6jRS6tbDnTk0HvN9yeMkiFRgr2HV55XhWKRqy1GHKb6J8EBK9FJiMaKWljAstpyyYwXnbmdaMrAvTgS6yN6phJq0/hIvWEv5Og5PvdXENDL2zBnYE3C1jgLwIyf5YoHqhzr9CscPDs8vbf4VkntbiJdCNO/xd1S0vtvYZnLVdGsvwmU0EzDACnpn4u5UdboNAOmzpqylPaRgP8FlhpqubC24wXxuusRD/huGdF5M8TgrHhunbw "PowerShell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~133~~ ~~131~~ ~~130~~ ~~123~~ 110 bytes -8 bytes by snagging several tricks from [mazzy's answer](https://codegolf.stackexchange.com/a/200802/78849) -13 bytes thanks directly to mazzy ``` $n=100*"$args" ''+(25,10,5,1|%{($y=$n/$_-replace'\..*');(echo quarter dime nickel penny)[$i++];$n%=$_}|?{+$y}) ``` [Try it online!](https://tio.run/##PcbdCoIwGADQe59ixGdTZ2uzjEBGD1IhYp8prWmzCFGf3YJ@bg6nqZ9o2xK1nqBQ/QRGSSGCGWT23M4cSpkXxaEU4ZvB7T3oFJglpAuLjc5ypAfOA@onHuZlTW6PzN7RklN1RWKq/IKaNGhM5@@hYuyYgHEVpOOw6xl0oz@NzhwKIrh0vhH/Rdvf4s1nkq9X0ws "PowerShell – Try It Online") Each iteration (i.e. `25,10,5,1`) generates two lines of output through the pipeline: the number and the coin size. `|?{+$y}` is a where clause that filters out both generations if `$y` is 0, which is the truncated result of `$n/$coin_size`. [Answer] # T-SQL, 181 bytes I added some linebreaks to make it readable ``` DECLARE @2 decimal(10,2)=1.43 DECLARE @ INT=@2*100 SELECT string_agg(left(nullif(c,0),99) +' '+trim(substring('quarterdime nickle penny',b*8,8)),' ') FROM(values(0,@/25),(1,@%25/10),(2,@%25%10/5),(3,@%5))p(b,c) ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1210991/this-challenge-makes-cents)** [Answer] # [Julia](https://julialang.org), ~~128~~ 127 bytes * -1 byte: @MarcMush readable version: ``` !s=( x=floor(Int,100s); join("$v $w "^(v>0) for (v,w)=zip( [25,10,5,1].|>u->(t=x÷u;x=x%u;t),"quarter dime nickel penny"|>split ) ) ) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=vZLRasIwFIbZbZ_iGB0kEKWpU2QlHd4MhF0MvHQOyowQ16Zdk2o3hD3IYHjjM_gAe4rtaRZbFd3Y7W5OyPnP-fMlJ2_rWR7JcPV19l6PQ61FZnBBeAFXkGZSmUhhdCdGzG978W1_OEQELn8qLL7uD24Qcf4y-N24a3AmoQn5yAFwW4wHiMFExgIQLTNulUqFUs_7nNcrc095mBmRQftU7XSt6h1UBko-PIoITkxY66JtyzpHZeWph-oj07FTB-b1bKxpjgs-UAZPoyTJMHNdTYg_S6S9TmMOjQWgezwPXALTJAM8pwvCX2SKR16HMpfaMG4tg7wZYMOLj03uF7w4z31DKNqDlBg7iBIBLQOdRtIQQta5mTZ7n68VR8VgaWjJ8e8Y3dJc00xowrdDtO9ar-llsJuw3e4_gwXm2zJHqEnVvVpV6zc) [Answer] # Perl 5 - ~~128~~ 124 bytes I guess this can be re-written to be much shorter but I really can't see it. ``` $s=<>*100;@v=($s/25,$s%2.5,$s%25%10/5,$s%250%5);map{$l=int($_);print$l.$".qw(quarter dime nickel penny)[$i].$"if$l>0;$i++}@v ``` EDIT: Just a math trick to save 4 chars. [Answer] # [Perl 6](http://perl6.org), 96 bytes ``` $/=get;put map {$_=Int($//$^a);$/%=$a;"$_ $^b" if $_},<.25 quarter .1 dime .05 nickel .01 penny> ``` ``` $/ = get; # set $/ to the input # print the following list with spaces between # and a newline at the end put map { # the parameters to this block are $a, and $b # which are declared as placeholder parameters $^a, and $^b $_ = Int( $/ / $^a ); # set $_ to the count of the current coin $/ %= $a; # set $/ to the modulus of itself and the current coin "$_ $^b" if $_ # return a string if $_, otherwise return Empty }, < .25 quarter .1 dime .05 nickel .01 penny > ``` ### Usage: ``` for amount in 0.1 0.01 0.28 0.56 1.43; do echo $amount | perl6 -e'…'; done ``` ``` 1 dime 1 penny 1 quarter 3 penny 2 quarter 1 nickel 1 penny 5 quarter 1 dime 1 nickel 3 penny ``` [Answer] ## Python 2, ~~167~~ 161 bytes *Update 1:* Stole Sp3000's idea to use input() and make my code a script instead of a function. ``` a=input()*100;k={25:0,10:0,5:0,1:0} for i in k:k[i]=a//i;a%=i print' '.join(['%d %s'%(k[x],{25:'quarter',10:'dime',5:'nickel',1:'penny'}[x]) for x in k if k[x]]) ``` [Answer] # C, 162 bytes Unfortunately, doesn't work without the `#include`. ``` #include <stdlib.h> i,a[]={25,10,5,1};main(c,v)char**v;{for(c=atof(v[1])/.01;c;c%=a[i++])c/a[i]?printf("%d %s ",c/a[i],"quarter\0dime\0 nickel\0 penny"+8*i):0;} ``` ## Ungolfed ``` #include <stdlib.h> i,a[]={25,10,5,1}; /* loop index, coin values */ main(c,v) char**v; { /* Get dollar amount from command line, convert to pennies */ for (c=atof(v[1])/.01;c;c%=a[i++]) /* loop while still change... */ { c/a[i] /* if there are coins at this index... */ ? printf("%d %s ", c/a[i], "quarter\0dime\0 nickel\0 penny"+8*i) /* print out how many */ : 0; } } ``` [Answer] # Lua 5.3, 141 139 132 131 bytes Sort of based on Sp3000's Python answer, but with my own magic formula. ``` n=.5+100*io.read'n'a=25 for s in("quarter dime nickle penny "):gmatch".- "do _=n<a or io.write(s,~~(n//a)," ")n=n%a a=35%a|#s%2 end ``` Edit -- improved the `a` formula. Previously it was `a=a*3%13~#s%4`. Edit 2 -- previously I was using `math.ceil` to round and convert to integer. Now I am reusing `//` to round and adding `~~` to convert to integer. Edit 3 -- shaved a character by changing the pattern from `"%w+ "` to `".- "`. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~95~~ 78 bytes **Solution:** ``` {" "/,/`quarter`dime`nickel`penny{("";$y,x)y>0}'(-c,1)!'{y!x}\x,c:25 10 5}100* ``` [Try it online!](https://tio.run/##y9bNz/7/v1pJQUlfRz@hsDSxqCS1KCElMzc1IS8zOTs1J6EgNS@vslpDSclapVKnQrPSzqBWXUM3WcdQU1G9ulKxojamQifZyshUwdBAwbTW0MBAy1DPxPj/fwA "K (oK) – Try It Online") **Example:** ``` {" "/,/`quarter`dime`nickel`penny{("";$y,x)y>0}'(-c,1)!'{y!x}\x,c:25 10 5}100*0.92 "3 quarter 1 dime 1 nickel 2 penny" {" "/,/`quarter`dime`nickel`penny{("";$y,x)y>0}'(-c,1)!'{y!x}\x,c:25 10 5}100*0.95 "3 quarter 2 dime" ``` **Explanation:** Modulo the input by each coin, then divide coins by the result. Feed each result along with the name of the coin into a function, returning the string value of both if number of coins is non-zero. Flatten everything down and join together with whitespace. [Answer] # Swift, 164 bytes Assuming input is `i` ``` let m=[("quarter",25),("dime",10),("nickel",5),("penny",1)] var b=Int(i*100) print(m.reduce(""){o,t in let(n,v)=t, x=Int(b/v) b-=x*v return x==0 ?o:o+"\(x) \(n) "}) ``` [Try it](https://repl.it/repls/CloseEnragedQuery) [Answer] # Mathematica 30 bytes This submission may not qualify, as it makes use of a readily available built-in! But some may find it useful for understanding the connection to Frobenius equations. The task can be understood as a search for all solutions to the Frobenius equation, `25q+10d+5n+p=t`, where q, d, n, p, and t, represent *quarters*, *dimes*, *nickels*, *pennies*, and *total*, respectively. ``` FrobeniusSolve[{25,10,5,1},#]& ``` The [Frobenius equation](https://www.wolframalpha.com/input/?i=Frobenius%20equation&wal=header) `25q+10d+5n+p=100` represents all cases that sum to 100 cents. The first solution, below, represents 100 pennies; the second solution represents 1 nickel and 95 pennies. And so on... ``` FrobeniusSolve[{25,10,5,1},100] {{0, 0, 0, 100}, {0, 0, 1, 95}, {0, 0, 2, 90}, {0, 0, 3, 85}, {0, 0, 4, 80}, {0, 0, 5, 75}, {0, 0, 6, 70}, {0, 0, 7, 65}, {0, 0, 8, 60}, {0, 0, 9, 55}, {0, 0, 10, 50}, {0, 0, 11, 45}, {0, 0, 12, 40}, {0, 0, 13, 35}, {0, 0, 14, 30}, {0, 0, 15, 25}, {0, 0, 16, 20}, {0, 0, 17, 15}, {0, 0, 18, 10}, {0, 0, 19, 5}, {0, 0, 20, 0}, {0, 1, 0, 90}, {0, 1, 1, 85}, {0, 1, 2, 80}, {0, 1, 3, 75}, {0, 1, 4, 70}, {0, 1, 5, 65}, {0, 1, 6, 60}, {0, 1, 7, 55}, {0, 1, 8, 50}, {0, 1, 9, 45}, {0, 1, 10, 40}, {0, 1, 11, 35}, {0, 1, 12, 30}, {0, 1, 13, 25}, {0, 1, 14, 20}, {0, 1, 15, 15}, {0, 1, 16, 10}, {0, 1, 17, 5}, {0, 1, 18, 0}, {0, 2, 0, 80}, {0, 2, 1, 75}, {0,2, 2, 70}, {0, 2, 3, 65}, {0, 2, 4, 60}, {0, 2, 5, 55}, {0, 2, 6, 50}, {0, 2, 7, 45}, {0, 2, 8, 40}, {0, 2, 9, 35}, {0, 2, 10, 30}, {0, 2, 11, 25}, {0, 2, 12, 20}, {0, 2, 13, 15}, {0, 2, 14, 10}, {0, 2, 15, 5}, {0, 2, 16, 0}, {0, 3, 0, 70}, {0, 3, 1, 65}, {0, 3, 2, 60}, {0, 3, 3, 55}, {0, 3, 4, 50}, {0, 3, 5, 45}, {0, 3, 6, 40}, {0, 3, 7, 35}, {0, 3, 8, 30}, {0, 3, 9, 25}, {0, 3, 10, 20}, {0, 3, 11, 15}, {0, 3, 12, 10}, {0, 3, 13, 5}, {0, 3, 14, 0}, {0, 4, 0, 60}, {0, 4, 1, 55}, {0, 4, 2, 50}, {0, 4, 3, 45}, {0, 4, 4, 40}, {0, 4, 5, 35}, {0, 4, 6, 30}, {0, 4, 7, 25}, {0, 4, 8, 20}, {0, 4, 9, 15}, {0, 4, 10, 10}, {0, 4, 11, 5}, {0, 4, 12, 0}, {0, 5, 0, 50}, {0, 5, 1, 45}, {0, 5, 2, 40}, {0, 5, 3, 35}, {0, 5, 4, 30}, {0, 5, 5, 25}, {0, 5, 6, 20}, {0, 5, 7, 15}, {0, 5, 8, 10}, {0, 5, 9, 5}, {0, 5, 10, 0}, {0, 6, 0, 40}, {0, 6, 1, 35}, {0, 6, 2, 30}, {0, 6, 3, 25}, {0, 6, 4, 20}, {0, 6, 5, 15}, {0, 6, 6, 10}, {0, 6, 7, 5}, {0, 6, 8, 0}, {0, 7, 0, 30}, {0, 7, 1, 25}, {0, 7, 2, 20}, {0, 7, 3, 15}, {0, 7, 4, 10}, {0, 7, 5, 5}, {0, 7, 6, 0}, {0, 8, 0, 20}, {0, 8, 1, 15}, {0, 8, 2, 10}, {0, 8, 3, 5}, {0, 8, 4, 0}, {0, 9, 0, 10}, {0, 9, 1, 5}, {0, 9, 2, 0}, {0, 10, 0, 0}, {1, 0, 0, 75}, {1, 0, 1, 70}, {1, 0, 2, 65}, {1, 0, 3, 60}, {1, 0, 4, 55}, {1, 0, 5, 50}, {1, 0, 6, 45}, {1, 0, 7, 40}, {1, 0, 8, 35}, {1, 0, 9, 30}, {1, 0, 10, 25}, {1, 0, 11, 20}, {1, 0, 12, 15}, {1, 0, 13, 10}, {1, 0, 14, 5}, {1, 0, 15, 0}, {1, 1, 0, 65}, {1, 1, 1, 60}, {1, 1, 2, 55}, {1, 1, 3, 50}, {1, 1, 4, 45}, {1, 1, 5, 40}, {1, 1, 6, 35}, {1, 1, 7, 30}, {1, 1, 8, 25}, {1, 1, 9, 20}, {1, 1, 10, 15}, {1, 1, 11, 10}, {1, 1, 12, 5}, {1, 1, 13, 0}, {1, 2, 0, 55}, {1, 2, 1, 50}, {1, 2, 2, 45}, {1, 2, 3, 40}, {1, 2, 4, 35}, {1, 2, 5, 30}, {1, 2, 6, 25}, {1, 2, 7, 20}, {1, 2, 8, 15}, {1, 2, 9, 10}, {1, 2, 10, 5}, {1, 2, 11, 0}, {1, 3, 0, 45}, {1, 3, 1, 40}, {1, 3, 2, 35}, {1, 3, 3, 30}, {1, 3, 4, 25}, {1, 3, 5, 20}, {1, 3, 6, 15}, {1, 3, 7, 10}, {1, 3, 8, 5}, {1, 3, 9, 0}, {1, 4, 0, 35}, {1, 4, 1, 30}, {1, 4, 2, 25}, {1, 4, 3, 20}, {1, 4, 4, 15}, {1, 4, 5, 10}, {1, 4, 6, 5}, {1, 4, 7, 0}, {1, 5, 0, 25}, {1, 5, 1, 20}, {1, 5, 2, 15}, {1, 5, 3, 10}, {1, 5, 4, 5}, {1, 5, 5, 0}, {1, 6, 0, 15}, {1, 6, 1, 10}, {1, 6, 2, 5}, {1, 6, 3, 0}, {1, 7, 0, 5}, {1, 7, 1, 0}, {2, 0, 0, 50}, {2, 0, 1, 45}, {2, 0, 2, 40}, {2, 0, 3, 35}, {2, 0, 4, 30}, {2, 0, 5, 25}, {2, 0, 6, 20}, {2, 0, 7, 15}, {2, 0, 8, 10}, {2, 0, 9, 5}, {2, 0, 10, 0}, {2, 1, 0, 40}, {2, 1, 1, 35}, {2, 1, 2, 30}, {2, 1, 3, 25}, {2, 1, 4, 20}, {2, 1, 5, 15}, {2, 1, 6, 10}, {2, 1, 7, 5}, {2, 1, 8, 0}, {2, 2, 0, 30}, {2, 2, 1, 25}, {2, 2, 2, 20}, {2, 2, 3, 15}, {2, 2, 4, 10}, {2, 2, 5, 5}, {2, 2, 6, 0}, {2, 3, 0, 20}, {2, 3, 1, 15}, {2, 3, 2, 10}, {2, 3, 3, 5}, {2, 3, 4, 0}, {2, 4, 0, 10}, {2, 4, 1, 5}, {2, 4, 2, 0}, {2, 5, 0, 0}, {3, 0, 0, 25}, {3, 0, 1, 20}, {3, 0, 2, 15}, {3, 0, 3, 10}, {3, 0, 4, 5}, {3, 0, 5, 0}, {3, 1, 0, 15}, {3, 1, 1, 10}, {3, 1, 2, 5}, {3, 1, 3, 0}, {3, 2, 0, 5}, {3, 2, 1, 0}, {4, 0, 0, 0}} ``` [Answer] # [Pxem](https://esolangs.org/wiki/Pxen) (`ABORT_ILLEGAL_INTEGER=0`), 139 bytes (filename only). Backslash followed by four-digit of octet character means a character with the codepoint. Also this uses a implementation-defined feature that "pushes zero for non-integer input for `._`", which is adopted from nk.'s pxemi.7z (though the implementation is terrible). ``` ._\0012.!.i.s.i0.-.+\0012.!._.+.c\0030.x.c\0031.$.n\0031.%.t quarter .p.mBB.a.c\0011.x.c\0012.$.n\0012.%.t dime .p.mBB.a.c\0004.x.c\0005.$.n\0005.$.t nickel .p.mBB.a.c.w.n penny.p.d.a ``` ## Usage * Full program. * stdin/stdout. * Input shall be a line and shall match this POSIX ERE: `^[0-9]+\.[0-9][0-9]?$` [Try it online!](https://tio.run/##pTp7X9u4sv/7UwgTSNzEdgK0UILpBhpoTnkdCLfdQ6h/xlbAkNhZy4HwyP3qe2ck@Qnt7tmbXdJY89BoXpqR9eiwmz8XF8wrPzDZjaIsksmMjo3xXUzHE4OOr4xJyPyZz8YG8QPdDT1KTgADHmIaTSIK34ayCHR71ImnEWXwRHSyG44nTuxfjSh58OMbEtwZVcaJAo96hE3o0B/6LqCEASfYeYypPg38mLg3TuS4wJePH4WEjUBIEoQRCaajERnCj6E/ooEzphzlLI6oM9bDyKfA3yM985hL9C3yY5iPXD0apD9x6J7z8EQDlG/PD5wRmU48J6YGWWmutIzmurHaIuf93fpHxDjwXRowAO4C79i/p7iicRgw8h8aheQeCAzU1jWNycnxWe/76JGwKSjEZ3REGSM0uPejMBiDSAoDJJ1OlenYYXek2VxfJ4uwnhh@rqy0icP4moTOFTqbhFFMDnbtzsGBtavEjxOK07hhMCTbpkfvTa6Gle3lFlleFnAXhHMC7y245HfS6X@x1EotwdQnKVMEAXpKqlWecai@ORc/9LmacDk/6n23z/qfrZVmcxUWgXJ/OdHPv6fToC4Ofrd3j09Pu7t9qyWR9o/O/1wkJ@d98vvx@Sk5@d49JGfwa7dLvnRPu8pe76B71DnsWlXDHjSbrRVjwfANZvhNQzfqyYht1A0XHlabxkz8aBkVIxA/loyY/DF1IvAcYkyM8c6O4XCkVktiAw@BDT8Q2/PHtIjaXJOozfcSlf@ISeC7d3SUQzYejIBMaBA8wphnOFVl9/io3z3qWwr@2uvtW1Vlp7vfO3pWCCHnZ117Z9dqtvFh57Tb@WofHB@f2N@@dI/s3tHZ@d5eb7eH5AKls3N82rd3To@/AhwxrVZuvHdw0N3vHABhv7vfPUWaeRX0695Q984PrrP48IdIBW4ZxEOyxAaDgKiVRNkqeUHodUQnRP@D6F0ywGf4VGs/Xi5@DAaX2mBQa7408X/@19RqFz@a@sblS0WrEiW@oQGSUPcmJEfodmn0QrCnYpDW9vIKx5tBgLeUoa/8c8nMl7xw79dfmvgHXznRtGpRtDOeQv5CItBfOA1ikCm8jpyxgn47Q6K8XGpF2lnNDadjbeKF@WVdAdIMFkMeXKK7YlIvDKgiwlaE/KuofXkh3GkEuKbV5Np5HtmVD54fxeMJhPRz//Dkc@90E8NUgFyHUZhYYKi4glq1qklgRmrClxxst2vmGwhGBn73GgxTi19LZjp1u02Z48oHnqm5tkGESrKKWsbIH5ILokeEr38aQV4Kx@QSshYOu6XhNklMmn5CyGMdEhAdYnmN6EcEvu4LZBk6HTFaIK5NGFLrIZn4XoPGkAwaE3cybdyzJ7AjbA2a8MK3ppvymYrgOALrMALZZXXt/Yf1jY@kejEI3l1WS3jcq40yseOPiB6QtZUSgMGOVmXmD@PdoGYMnjcG84FWMQcts8zWebhDmRxLX2mtra9trH5Y2yDVAsqzU7cqzfa8e/T5mbsoceY5DAgC8SNbODKtPmcoDNVaqzS1do4MTQy@aanOlevR4fWNf3s3Ggfh5I@IxdP7h9njU2dn93N3b/9L719fDw6Pjk/@fXrWP/@fb99//0@mLlvNMT2wIFCv45tawr0wYxjVfMiI/pbVarb9el17LqwT4bcAvwX4WvsW4AVwFqBsesXiKJ2jAYM1vkLt3YHWaOXnTIiImhdzLn@matSSFCA@m2Q7jUSzwudRcVcuC5IkwF9gQq01jQLSTOIf04h0bUxxqsgWm2QIngQ@E4ewwQc0Aj8mDkFQGDnRI8@Aapr@Mr4tfNSUuaK4I@oENojBhagJ3fLco5PKcwsSDal8UrjDOxNSrZLu916ffDk/IbAfkX@fw8NJ76RLOgenh6TfPT1E3GhM9CEsMGGrpgz0v0XP83SlBfIlHLCaEWvWVFlloLcyN/InscJZF1fy1/MoqTVEnoddXN3ezgutQP00AQ1KreTzfEtuWvks0UqzxKvkgPYu5Id8WlgkYXTtBP4TJSMfNlOoVsFPYWcXwIi64TWH3jsjH219B9WqkiWBz8d9a@2DiP6sCIHPiAGVrDFwpxh7F63WyqWFPzaal5Y6UYuwloCtfwRYWII1JWwDYEER1nwvYasA8wuwjwBS7eLQR4H9YR1AbmkWyWkDObESbEPCPgDsviSBXNU6rmpYgslVfcBV0RLPNckT6NWoBJNybqCcD0XYitTGBmpjVoLJ@TZwvscSTMr5EeV8KqplXYqJGnNKonyQLEFcNS4tT4q5jmKOSzAp5gcU0yvA1lDD9eIQzqwXhlYRa6E4hOqvFIdw6qV0SPgjf@IZM3FHaCDv/XDKLOnlF9w/LxOyZLReF@O4eSlJ6VBLiS1gv7xcaWKZAZPnNwPcCTitbq20@Q/xreva69Q@VJNgW/IGgdp4W6h0I8B1Vprp@DxdHW6vWQlU@@m8f3fSeTXJCg83vntDwiHBPRW2AMogt4@dGAaxzf4ksKhxbZAHMpvNMPOHyc8HAYWiyxGk2IJy4gYvrQgzHbNjEmwP/WvotykZTiOARIKQhaQDKvawbQfqqwizDnFyaSegLB7dW02ReMwfFyjmZcVMtMEnQ0HBogI3b1KujnZAZ3HmKOYPJyMHm8sZrGbeyJxQ7ahtvkk0CwbJk22/phqqzpKLas9EE7i6njd4KlTBzq12ahjH88jIuYIikz@Lwd5hr9/p9472yf5x/5icwUP3ENqEM/KtBy333vHBwfE3BHe@fSVnR72Tk25/U5Byv2kLcRfFGjh7C3LLbKZqz/A9T4BY2v4awzCMPDKHwVM/8mWlEOJ3ACXFzGcxdpCcl6CZ55bkB37sO6PRI5RBYgTcAwoM@LsJH4BPHOpALlfBvRTd6ZrGnCsEKPgTGYUhFCrMrJgNs4TJHQ9RMzzCMX@TmM6DM3t4dAS2GwbAd1rEZ2bjt3cZayRwEoKriDp3r9lzgmSGziYqAzf6EY0pLNXzh0NYJYS8rLkWyfFO/1sSAYINLh00@ID6SEIit/8K26jqnB/9CPWCW1E8DRMnWlArk4kTxcKz3g4g4Zv1euKLUL/WIPM28D/OUisEE1HFPKqYrxBWb7PW9QJr1Avw/u3vc08jAlSB9V3ARliBymMnhpp1JtBhAwccB4UyJelyhGSCaSoXM8152cHNFFYxwdOTx6vc@pKkmuczmbKbWp5We00JndakYkKehRpvAWrL@LGmaZNpjOcatUkI3bggArywYoJMf4EUvELCQ9BrWsbzK0I8PJRDLhnEziAJaQZ0y@wBMS4wZiUMBCaw@4oJeyiNGM3GhhUz115hgIHj23wHw0aLzyBHL/zLlIxWTPCYKMT15bhFb8iXa7KEDlLsxCfR1BBUNszj1dRlVdPecHTuFOl46qIJL2dQE@ywXS4yHLQSjtK/32Jadv2Eb6diylj@pLZl/qEJMC4uNw5vqDMpWXrMcThAKmQYhWP5nCB5FZOnqlQz9YXKki5Ug7aoadvWiuZEsGGNwS9criWOnAYgcPTAtDztDcMQwoFHWi09FKvy4kjmJdxschEGUcXDEbb6DJ9LlAbjqyNKzbkKo9hGRQs@muiKeVP5nJt2Grh47g/lgB9IzGcWO@7dhe9ZUJ82xdSi08qfvmU85imTnNdxVg2WbvLMEqpqC@b1uu8BcyV/htAEJ2fcsXOFAdokkUdvNcDLSwIlx32ZPOlUHsVNg9hoTyTXL/@7@ep8PlDcnJQ6z0U0Rr6DbvOmWFFgu4LcLU4N0zNLaMurN74xmdEq6RjwHwmJ8fB0y0Lj1pgZT8aD4RBjRoxH4tzR0PBgwDOo4STnF@JQoTJTi0ufpYsWB5l4XgBiFWQlW1vVvfOj3X7v@OisqqSm4v5RG7PrXPNM4PFFRRZ4JCEaBnEm20beUHVKxVwSnxFUcm4MVEVuHEYg149ZgzSh9PDojHoJCnhY4E@mI/GaKZVDhuezPPlIZ4Cycp5hCYO@QsphcMPZfua8jRSrXr@0bD@PizmgzKyh6ylFnnH8JnKKqrfyyEkGt/2GfSs0i75mo7PZ4G0JlbkCj7mjMvvWSlnbflrt5sest@bW30IuwS37VhYb3IYYDPDPeApuKgPkARsOsUL@wgJSYC6Us9WJvJjowvfQt3lw5TSQ5c8ELwm/olI5DtorBXMbgWR@CF@3KB7jLxN5rcrLORh3RtD5cODVI0jO6B9TGrhUQq@m2EQ9XlHxStRx@dtCIMa3DVN8JZp3GLG5owy54yN1AJ@lENsQ21cKDpZu@WhdV1BB7gW7Zr1MwnXtvdbGNg1K6MTE/jtLb2VlH/cLF3Z2291KzldBFnjM@UXCTp6N8okbLa2@tsHZO4xNuX46Z7u9XmLkVOSkfrGjVFjel9vTAEBX02Hmf5GVDl5kbXSSQN8AJcaNshUBeyyMRuAzMK5tQWNYRJbLz5HmhOVzpBbJT1kMXp@xieNSjiU51T5uAc7yso1n0GvaywvEm7W6Muf@ch3yjZkwPHWE/CTsXFOXPLWxDPoGpILGUiOj7Rqo8SgL5DaGclYWLoBFl5dzErWTFfOFchaWPKPmnmJZa6tCPHCQXCstRxKK7JQnP11B07DWtY2Xl/frW4kDi/E3X0rmNjiR91XD3uRHDk5A5ILhX/A2NW0reG@a0S0SbxpAs@QPwX7XkMYjbB8yo2nc13mBE9@ASzKCdwTCOM/h@GvndwIexYqAguXbrw/ZXzf7iwTfEPFezfOv/ZgXU@jDKEM7NdbaRuYX79fbBdPlPT@CBprA5DqGVTrJa7EKjstfUQaej37jjEoba77wSkIvKec@qYk5Els4m2QMToSBbDw0oBKAv8cGKtB4kgbJvTFLqFRijxwW8zqaqDkWDtLkIiartvl3w@b9bcNmFB@FfBkri3@nLsuH8IA172RJTf3KVgu/ep1eSh18F16Q599zpeRyaW29tfIPpxHLtPg06ZhYc3Ewt8yZqqVW5uRbkuIN3Mcy7vbPcZ/KuAtWHlluzQ83j8Qnzhj2MHku4uOZYmLITX42dQMhNqKMjPyxjzdsoHu7pngMKeOYNYATZRPqirMhyPd7EaU7Z5/bpDlb3xMfLODw2GXszAhvsAG20RQfhMGuosiTFZzU54cFYmoC9eGIgruQg@OjfR721Mtml@eiQLFtkdUVcgXhibd4Dju/73Rho/qK9y9Oz0j/mHzu7vY@dwlYsP@le4ojACI7u7lgypoqO5zwbHzbsO/SmBJXObJg9qVloZ56ZWJ/KynJJPIdJAdMClAfAb59Vz6rBBBLdgtegS@xgbrkwh8jL/gSaTBYGAwq8M87EwauXJULiHLeZh53a8HUAE53xruCVLdv5GaI7HCCIZ0tX75JzNKzqHfvtJ9GD7Cw8BWCRtJGn6ukLvv8dhl14RXqu5@h6mrh8LZApJeIBB2voreapYP@4mx6K6OaF6b8X/WisnRZmPSnpk6s/Q4AVmnCVwp@olGoe/69z8Db1Fc8Sh7zK6fJyZxfmdBXRf1k@6Z9u2n7S8BSK@1ocyXt0H7SwfWOev2qcnRqWa3n7LW/DeWxZ8sDIKgk8WR8Dljb1gpsenlgEi8mDTzX1LJ3AND0a/mj@rnoMMWRUr2eP3LirwfE4ftcQYGw262GVzEwISycRi60t7zxrW1iA7mq5S@yydfnpbaZ4wHRG9ePnpuLi@/MOVndxiMHTD9yquRNuidfL8sX6DyDDvEy4ehRqcm3JOJoC9oE6EP/X3dcSrdb7sUFl/Ltltwu/d/caPnpXZa/flH9@grLG5dX3rq2Ury18sv7KuKmyuuLKuKKinjbbwzLr@DTq1n/8EV8eu6BLisnEtZNLoWJivUfctcwJUvN8U4qZTL2r2@gvaTX4Gv8viyv7hWuosKtCU4IDs3jB5wP2mWQB9UxdmK8dYeKET0sNrVSx4d4VyK57tk53bcPO98LgQIhxNe91vz4QVNJcnPx0LRW2oe6tYFvLUS/iLu@KnUODasiu0hGIDlsH0pjsTbDVx3KM7MQMFcyOzL@hmDmRFCt6z3ylNjv6c@m0fo/ "yash – Try It Online") ]
[Question] [ According to me, a tornado looks like this: ``` ######## ####### ###### ##### #### ### ## # ``` This tornado starts out with width `n`, and on each next line, a character is removed from either the left or the right, depending on the input. # Input The input will be a list of some sort of any two unique values (a string of two unique characters works too), and an optional positive integer to indicate the starting width. If the optional integer is not taken, then the starting width is 1 greater than the length of the list. Let the starting width be `n`. # How to make a tornado In my example, I choose my list to contain `1`s and `0`s, though you may choose any two distinct constant values, or a string of any two distinct constant characters. The first row will consist of `n` non-whitespace characters (you may choose any consistent character; I choose `#` for my example). Then, for each number in the list, if the number is `0`, remove the left character and create a new row; if it's a `1`, remove the right character and create a new row. Thus, the above tornado is the output for `8, [1, 0, 0, 0, 1, 0, 0]`. # Output The output can be a list of strings, a list of lists of characters, or a multiline string. Trailing whitespace on each line is allowed, and a trailing newline at the end is allowed. # Test Cases These testcases include the starting width and use lists of `1, 0`. ``` 5, [1,0,0,1] ##### #### ### ## # 10, [1,0,0,1,0,1,0,0,1] ########## ######### ######## ####### ###### ##### #### ### ## # 7, [1,1,1,1,1,1] ####### ###### ##### #### ### ## # ``` # Rules * Standard loopholes apply * Shortest code in bytes wins! [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") * Background doesn't have to be a space (I forgot to specify this earlier). * Your language only has to support numbers (widths) that it can handle, but if your interpreter were rewritten with a larger number size, it has to theoretically work. # [Reference Implementation](https://tio.run/##nY5NDsIgEIXX5RQvcQGobWzc1fQkTRcYR0UrJRSjPX0FUhe6MTHMT2C@9wY7@nNvttOknFMjajTaeEEd3ch4iWPvMF@gTQh790IWg@106C1z/SNq@IK3WEJ0ZEQyklihlOxLnkYVy6yLSzgvLr02InhIyTJ9fKOByKJSmwM9o84pc6JkHlnkKNfIU8rIRmkYNIlvUdcI/6k@nsDBd9g7UleWUTfQjx1/@E5TiU045ZyhvgA) [Answer] # [Python 2](https://docs.python.org/2/), ~~66~~ 59 bytes -7 bytes thanks to Arnold Palmer ``` x,z=input() for i in range(x):print' '*sum(z[:i])+'#'*(x-i) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v0KnyjYzr6C0REOTKy2/SCFTITNPoSgxLz1Vo0LTqqAoM69EXUFdq7g0V6Mq2iozVlNbXVldS6NCN1Pz/39DA51oAx1DIDSAYiAZCwA "Python 2 – Try It Online") `0` to remove from the right, `1` to remove from the left [Answer] # [V](https://github.com/DJMcMayhem/V), ~~15~~, 12 bytes ``` ïÀé#òÙxHxG@" ``` [Try it online!](https://tio.run/##K/v///D6ww2HVyof3nR4ZoVHhbuD0v//OXZ2Of9NAQ "V – Try It Online") `l` for right, (makes perfect sense, doesn't it?) and `>` for left. [Answer] # vim, 85 82 bytes ``` o"cp:s/#/ <C-v><CR>0"cy$<ESC>"ayy7hR$/<ESC>"bdd:s/[][, ]\+/<C-v><CR>@/g<CR>ggAa#<C-v><ESC><ESC>^D@"^"cy$:2,$:norm D@" ``` `<ESC>` is 0x1B, `<CR>` is `0x0D`, `<C-v>` is 0x16. And `<ESC>OH` is a multibyte sequence representing the HOME key. The input uses `a` as the "remove left" value and `b` as the "remove right" value. ``` " @a will remove from the left; @b will remove from the right. o"cp:s/#/ <C-v><CR>0"cy$<ESC>"ayy 7hR$/<ESC>"bdd " split the input into digestible chunks :s/[][, ]\+/<C-v><CR>@/g<CR> gg " Create the first line Aa#<C-v><ESC><ESC> ^D @"^"cy$ " Create tornado :2,$:norm D@" ``` No TIO link, unfortunately. I couldn't get it working under V. Test by copying code into tornado.vim (replacing `<ESC>`, etc with their actual bytes) and running as follows: ``` $ echo '8, [b, a, a, a, b, a, a]' > a.txt $ { cat tornado.vim; echo ':wq'; } | vim a.txt $ cat a.txt ``` -3 bytes due to Neil's suggestion. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes -2 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) ``` 0×=²v¨yú= ``` Remove from left: `1` Remove from right: `0` [Try it online!](https://tio.run/##MzBNTDJM/f/f4PB020Obyg6tqDy8y/b/f0MDrmgDHUMgNIBiIBkLAA "05AB1E – Try It Online") ``` 0× # Make a string of n 0s = # Print without popping ²v # For each character in input (call it y): ¨ # Remove the last character of the current string yú # Pad with y spaces = # Print without popping ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~30~~ 28 bytes ``` .? $`#$&$'¶ T`d`#`#.* T`d` _ ``` [Try it online!](https://tio.run/##K0otycxL/P9fz55LJUFZRU1F/dA2rpCElATlBGU9LTBLIf7/fwNDQwNDEAEA "Retina – Try It Online") Takes just a string of 0s and 1s and calculates the width based on the string. Explanation: The first stage takes the input string and duplicates it once for each boundary point, inserting a `#` at that point. The second stage then changes all the digits after the `#` to more `#`s, creating the triangle. The third stange then deletes all the remaining ones and changes the zeros to spaces which results in the torndao's "wobble". [Answer] # Python 2, ~~58~~ 57 bytes edit: saved 1 byte thanks to xnor ``` l,a=input() s="#"*l for i in a+[0]:print s;s=" "*i+s[:-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P0cn0TYzr6C0REOTq9hWSVlJK4crLb9IIVMhM08hUTvaINaqoCgzr0Sh2BooraCklaldHG2laxj7/7@pjkK0gY4hEBrEAgA "Python 2 – Try It Online") 1 to remove from the left, 0 to remove from the right. [Answer] ## Perl, 43 bytes **42 bytes code + 1 for `-l`.** ``` $_="#"x<>;do{print}while<>|0?s/#$//:s/#/ / ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZJWanCxs46Jb@6oCgzr6S2PCMzJ9XGrsbAvlhfWUVf3wpI6Svo//9vaMBlyGXABSGhrH/5BSWZ@XnF/3VzAA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~85~~ 82 bytes 3 bytes saved thanks to Giuseppe ``` function(n,l)for(k in 1:n)cat(rep(" ",sum(c(0,l)[1:k])),rep("%",n-k+1)," ",sep="") ``` [Try it online!](https://tio.run/##NYoxCoAwDAB3XxECQoIR7CaCqy9wEwcpFqQapdb3VxGFGw7uQnJtcpfauOxKKiu7PZCHRcE0ynaKFOaDEFDOayNL1bMMpvEjs7wlR9HSF4YFs2eajxaRk6NawFIn0P98zpxu "R – Try It Online") Explanation: ``` function(n,l){ for(k in 1:n){ # Proceed line by line cat( # Concatenate... rep(" ",sum(c(0,l)[1:k])), # ...required number of leading spaces,... rep("%",n-k+1), # ...required number of tornado characters... "\n", # ...and a new line. sep="" # Join without spaces ) } } ``` [Answer] ## Haskell, 50 bytes ``` h n=scanl(\s i->[(' ':),id]!!i$init s)$'#'<$[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0Mhz7Y4OTEvRyOmWCFT1y5aQ11B3UpTJzMlVlExUyUzL7NEoVhTRV1Z3UYl2lBPLy/2f25iZp6CrUJKPpeCQkFpSXBJkU@egopCaV5OZl5qMZCVoWCqoBBtqGMAhIaxuFUZGsBVQTFI/X8A "Haskell – Try It Online") If the input list can be a list of function names, we can save a byte ### Haskell, 49 bytes ``` f=id g=(' ':) h n=scanl(flip id.init)$'#'<$[1..n] ``` Usage example: `h 5 [g,f,f,g]`. [Try it online!](https://tio.run/##y0gszk7Nyfn/P902M4UrzVZDXUHdSpMrQyHPtjg5MS9HIy0ns0AhM0UvMy@zRFNFXVndRiXaUE8vL/Z/bmJmnoKtQko@l4JCQWlJcEmRT56CikJpXk5mXmoxkJWhYKqgEJ2ukwaE6bG4VRkawFVBMUj9fwA "Haskell – Try It Online") How it works: ``` '#'<$[1..n] -- build the first line of the tornado, i.e. n times '#' scanl( ) -- repeatedly apply the given function to the starting -- value and the next element of the input list and -- return a list of the intermediate results \s i-> -- the function takes a string s and a number i init s -- and first drops the last element of s [ ]!!i -- and then picks and apply a funtion from the list (' ':) -- i = 0: prepend a space id -- i = 1: do nothing ``` [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 3132 bytes ArnoldC doesn't have string concatenations, so this builds a tornado out of `8`s and uses `1`s to space it out. ArnoldC also only supports up to 16-bit integers, so it overflows with input longer than 7 digits. (So it will only make mini-tornadoes) `1` is left, any other digit is right (although I wouldn't recommend `0`, since you can't start with that.) Input: `1221122` Output: ``` 88888888 18888888 18888881 18888811 11888811 11188811 11188111 11181111 ``` Golfed code: ``` IT'S SHOWTIME HEY CHRISTMAS TREE d YOU SET US UP 0 HEY CHRISTMAS TREE e YOU SET US UP 0 HEY CHRISTMAS TREE m YOU SET US UP 0 GET YOUR ASS TO MARS m DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY HEY CHRISTMAS TREE l YOU SET US UP 0 GET YOUR ASS TO MARS l DO IT NOW g m DO IT NOW h l m YOU HAVE BEEN TERMINATED LISTEN TO ME VERY CAREFULLY g I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE m GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE i YOU SET US UP 2 HEY CHRISTMAS TREE n YOU SET US UP m STICK AROUND n GET TO THE CHOPPER n HERE IS MY INVITATION n HE HAD TO SPLIT 10 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE n GET TO THE CHOPPER i HERE IS MY INVITATION i GET UP 1 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC CHILL I'LL BE BACK i HASTA LA VISTA, BABY LISTEN TO ME VERY CAREFULLY h I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE l I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE m GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE o YOU SET US UP -2 GET TO THE CHOPPER o HERE IS MY INVITATION o GET UP l ENOUGH TALK HEY CHRISTMAS TREE k YOU SET US UP 1 STICK AROUND o GET TO THE CHOPPER k HERE IS MY INVITATION k YOU'RE FIRED 10 ENOUGH TALK GET TO THE CHOPPER o HERE IS MY INVITATION o GET DOWN 1 ENOUGH TALK CHILL HEY CHRISTMAS TREE p YOU SET US UP 0 HEY CHRISTMAS TREE f YOU SET US UP 0 HEY CHRISTMAS TREE i YOU SET US UP 0 HEY CHRISTMAS TREE q YOU SET US UP l HEY CHRISTMAS TREE d YOU SET US UP 0 HEY CHRISTMAS TREE e YOU SET US UP 1 HEY CHRISTMAS TREE a YOU SET US UP 0 HEY CHRISTMAS TREE b YOU SET US UP 0 HEY CHRISTMAS TREE c YOU SET US UP l STICK AROUND q GET TO THE CHOPPER i HERE IS MY INVITATION 0 ENOUGH TALK GET TO THE CHOPPER a HERE IS MY INVITATION d ENOUGH TALK GET TO THE CHOPPER b HERE IS MY INVITATION e ENOUGH TALK GET TO THE CHOPPER c HERE IS MY INVITATION l ENOUGH TALK STICK AROUND c BECAUSE I'M GOING TO SAY PLEASE a GET TO THE CHOPPER i HERE IS MY INVITATION i GET UP 1 YOU'RE FIRED 10 ENOUGH TALK GET TO THE CHOPPER a HERE IS MY INVITATION a GET DOWN 1 ENOUGH TALK BULLSHIT GET TO THE CHOPPER f HERE IS MY INVITATION b LET OFF SOME STEAM BENNET c ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE f GET TO THE CHOPPER i HERE IS MY INVITATION i GET UP 1 YOU'RE FIRED 10 ENOUGH TALK BULLSHIT GET TO THE CHOPPER i HERE IS MY INVITATION i GET UP 8 YOU'RE FIRED 10 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC YOU HAVE NO RESPECT FOR LOGIC GET TO THE CHOPPER c HERE IS MY INVITATION c GET DOWN 1 ENOUGH TALK CHILL GET TO THE CHOPPER i HERE IS MY INVITATION i HE HAD TO SPLIT 10 ENOUGH TALK TALK TO THE HAND i GET TO THE CHOPPER q HERE IS MY INVITATION q GET DOWN 1 ENOUGH TALK GET TO THE CHOPPER p HERE IS MY INVITATION m HE HAD TO SPLIT k I LET HIM GO 10 ENOUGH TALK GET TO THE CHOPPER k HERE IS MY INVITATION k HE HAD TO SPLIT 10 ENOUGH TALK GET TO THE CHOPPER f HERE IS MY INVITATION p YOU ARE NOT YOU YOU ARE ME 1 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE f GET TO THE CHOPPER d HERE IS MY INVITATION d GET UP 1 ENOUGH TALK BULLSHIT GET TO THE CHOPPER e HERE IS MY INVITATION e GET UP 1 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC CHILL I'LL BE BACK i HASTA LA VISTA, BABY ``` [Try it online!](https://tio.run/##tVZLc9owEL77V@yNSzsTc@pVNgvWRJZcSYbxkWfCxAmh/3@Grk1pipH8SMoBD1p92v32oV0tf70dys36dOJ2ZMAkamF5ikGCBcSJ5samzIDViLAJCpWDQQu5gTyDBxdo2wf0egOa0X@SaWCGMApSpg3BJgq4BakWAYcFk7baYuaxggKDKJdxAmoKP3M0litpgMkJfEATNkewCaYkNwvUSJtpihPOLIrCxazsx6z8YAZP//KEZyj/uFcbjxAlWNQpl2RzEggyVklID8IcNRFgGqe5EAU8kZMSiWNtLhaKmJvzIlLKnp2rl6mySsdFLKpQzvjZSYOQocpIxrh2@bZv@DZ2gd4aoNeAIhs/AtMqJ/NvdTyIPhmkoyrLUJMwodgCN5AWwOWcW1Zlo5ZTGCYV3mSCIhQ@BChVPkvAMvEYRBiznHjzUQozxeWsRrICyAtm0G1t77G2r8FEObyy8TcVUoFGk2FsYao0CDXjcRAnXIiAj4SgVEHEyFPSz4xlIBjMKTLsG4mjojVzz5/JXHnndB8amfw@dkXz4Inm4RLN8iqaDjsvDTvhdcUcXFZfPFZrXSPamfLqsjbKZTD9iVrIRjmcE@5w471P49r1Ae37gI4NUPnfOm7oAi37aFr1Aa1viF@l@zjkynamd@k5uOk6uPIc3HYdXHsOXl@DK5fXnX1s@ck@NvAy@KK19F2GiLqXSbh1Kdt5lK0CQWA1nYJR1AmpKbKUeqeUJF0P6u67O0SlzaNO1T9aVbcPkvbdAYW2bu9cg/zqGL/V56IsqabN3qX@6FF/9BF16Hj36Hi9ofhCU7EqsIRXRdOj6P2jpMP7ATV/ng007im79WsQLmu6AeHXi37jbXPOJ01bkW@9je@er6PTKRyPQ/r9Bg "ArnoldC – Try It Online") Ungolfed code (5178 bytes): ``` IT'S SHOWTIME HEY CHRISTMAS TREE left YOU SET US UP 0 HEY CHRISTMAS TREE right YOU SET US UP 0 HEY CHRISTMAS TREE input YOU SET US UP 0 GET YOUR ASS TO MARS input DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY HEY CHRISTMAS TREE width YOU SET US UP 0 GET YOUR ASS TO MARS width DO IT NOW calcwidth input DO IT NOW buildline width input YOU HAVE BEEN TERMINATED LISTEN TO ME VERY CAREFULLY calcwidth I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE input GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE result YOU SET US UP 2 HEY CHRISTMAS TREE calc YOU SET US UP input STICK AROUND calc GET TO THE CHOPPER calc HERE IS MY INVITATION calc HE HAD TO SPLIT 10 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE calc GET TO THE CHOPPER result HERE IS MY INVITATION result GET UP 1 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC CHILL I'LL BE BACK result HASTA LA VISTA, BABY LISTEN TO ME VERY CAREFULLY buildline I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE width I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE input GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE ctr YOU SET US UP -2 GET TO THE CHOPPER ctr HERE IS MY INVITATION ctr GET UP width ENOUGH TALK HEY CHRISTMAS TREE mask YOU SET US UP 1 STICK AROUND ctr GET TO THE CHOPPER mask HERE IS MY INVITATION mask YOU'RE FIRED 10 ENOUGH TALK GET TO THE CHOPPER ctr HERE IS MY INVITATION ctr GET DOWN 1 ENOUGH TALK CHILL HEY CHRISTMAS TREE digit YOU SET US UP 0 HEY CHRISTMAS TREE decider YOU SET US UP 0 HEY CHRISTMAS TREE result YOU SET US UP 0 HEY CHRISTMAS TREE lines YOU SET US UP width HEY CHRISTMAS TREE left YOU SET US UP 0 HEY CHRISTMAS TREE right YOU SET US UP 1 HEY CHRISTMAS TREE leftcounter YOU SET US UP 0 HEY CHRISTMAS TREE rightcounter YOU SET US UP 0 HEY CHRISTMAS TREE widthcounter YOU SET US UP width STICK AROUND lines GET TO THE CHOPPER result HERE IS MY INVITATION 0 ENOUGH TALK GET TO THE CHOPPER leftcounter HERE IS MY INVITATION left ENOUGH TALK GET TO THE CHOPPER rightcounter HERE IS MY INVITATION right ENOUGH TALK GET TO THE CHOPPER widthcounter HERE IS MY INVITATION width ENOUGH TALK STICK AROUND widthcounter BECAUSE I'M GOING TO SAY PLEASE leftcounter GET TO THE CHOPPER result HERE IS MY INVITATION result GET UP 1 YOU'RE FIRED 10 ENOUGH TALK GET TO THE CHOPPER leftcounter HERE IS MY INVITATION leftcounter GET DOWN 1 ENOUGH TALK BULLSHIT GET TO THE CHOPPER decider HERE IS MY INVITATION rightcounter LET OFF SOME STEAM BENNET widthcounter ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE decider GET TO THE CHOPPER result HERE IS MY INVITATION result GET UP 1 YOU'RE FIRED 10 ENOUGH TALK BULLSHIT GET TO THE CHOPPER result HERE IS MY INVITATION result GET UP 8 YOU'RE FIRED 10 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC YOU HAVE NO RESPECT FOR LOGIC GET TO THE CHOPPER widthcounter HERE IS MY INVITATION widthcounter GET DOWN 1 ENOUGH TALK CHILL GET TO THE CHOPPER result HERE IS MY INVITATION result HE HAD TO SPLIT 10 ENOUGH TALK TALK TO THE HAND result GET TO THE CHOPPER lines HERE IS MY INVITATION lines GET DOWN 1 ENOUGH TALK GET TO THE CHOPPER digit HERE IS MY INVITATION input HE HAD TO SPLIT mask I LET HIM GO 10 ENOUGH TALK GET TO THE CHOPPER mask HERE IS MY INVITATION mask HE HAD TO SPLIT 10 ENOUGH TALK GET TO THE CHOPPER decider HERE IS MY INVITATION digit YOU ARE NOT YOU YOU ARE ME 1 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE decider GET TO THE CHOPPER left HERE IS MY INVITATION left GET UP 1 ENOUGH TALK BULLSHIT GET TO THE CHOPPER right HERE IS MY INVITATION right GET UP 1 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC CHILL I'LL BE BACK result HASTA LA VISTA, BABY ``` [Answer] # C, ~~68~~ ~~63~~ 62 bytes ``` s;f(w,i)int*i;{for(;w;s+=*i++)printf("%*s%0*d\n",s,"",w--,0);} ``` This makes use of the dynamic field width specification in a `printf()` format string. The function is called like this: ``` #include <stdio.h> s;f(w,i)int*i;{for(;w;s+=*i++)printf("%*s%0*d\n",s,"",w--,0);} int main() { f(8, (int[]){0, 1, 1, 1, 0, 1, 1}); } ``` As suggested by @EasyasPi, this swaps the meaning of zero and one in the control string to save a negation in the loop increment expression. Which is fine by the "you may choose any two distinct constant values" rule. [Answer] # [J](http://jsoftware.com/), 32 19 bytes ``` ' #'#~0(,.#\.)@,+/\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RWU1ZXrDDR09JRj9DQddLT1Y/5rcqUmZ@QrpAGVGQKhwX8A "J – Try It Online") -13 thanks to miles Very belated update... [Answer] # [R](https://www.r-project.org/), ~~116~~ ~~109~~ 102 bytes *-5 bytes thanks to user2390246* (and another 2 I saved myself) [Outgolfed by user2390246](https://codegolf.stackexchange.com/a/133720/67312) ``` function(n,l){k=cumsum m=matrix(' ',n,n) for(i in 1:n)m[k(c(1,!l))[i]:k(c(n,-l))[i],i]='#' write(m,'',n,,'')} ``` [Try it online!](https://tio.run/##FYzBCoMwEAXvfkVKD9lHV2gOvQTyJeKhiIFFd4U00kLpt6fKwNxmSsup5d2mKpuR8YqvJn3WIh/yzrOxoctbIXFiLkSDDrSk1640UeDLiiFEGYFIy816AcuY/NV37yJ1JmV/Pg7j1zI9@IzuBwFofw) Returns an anonymous function that takes `n` and a vector `l` with `0` for removing from the left and `1` for removing from the right, and prints the result to console with the right formatting. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes *-1 byte thanks to @ETH* ``` å+ uP £X+QpV´ ``` Input is the array, then the size. Array values are `""` or `" "`, which represent removing from the right or left, respectively. Uses `"` instead of `#` and returns as an array of strings. The idea here was to first create an array of the left padding for each line, hence the input strings. Then, each line gets the `"`s added, using the fact that the amount of `"`s decreases by 1 each time. ## Try it online! These all use the `-R` flag to format the output by joining it with newlines. * [Test Case 1: 5 tall](http://ethproductions.github.io/japt/?v=1.4.5&code=5SsgdVAgo1grUXBWtA==&input=WyIiLCIgIiwiICIsIiJdCjUKLVI=) * [Test Case 2: 10 tall](http://ethproductions.github.io/japt/?v=1.4.5&code=5SsgdVAgo1grUXBWtA==&input=WyIiLCIgIiwiICIsIiIsIiAiLCIiLCIgIiwiICIsIiJdCjEwCi1S) * [Test Case 3: 7 tall](http://ethproductions.github.io/japt/?v=1.4.5&code=5SsgdVAgo1grUXBWtA==&input=WyIiLCIiLCIiLCIiLCIiLCIiXQo3Ci1S) * [Test Case 4: 100 tall](http://ethproductions.github.io/japt/?v=1.4.5&code=5SsgdVAgo1grUXBWtA==&input=WyIiLCAiICIsICIgIiwgIiAiLCAiICIsICIiLCAiICIsICIgIiwgIiAiLCAiIiwgIiIsICIgIiwgIiIsICIgIiwgIiAiLCAiIiwgIiAiLCAiICIsICIiLCAiICIsICIgIiwgIiIsICIiLCAiICIsICIiLCAiIiwgIiIsICIiLCAiICIsICIiLCAiICIsICIiLCAiIiwgIiAiLCAiICIsICIiLCAiICIsICIiLCAiIiwgIiAiLCAiICIsICIiLCAiIiwgIiIsICIgIiwgIiAiLCAiIiwgIiIsICIiLCAiIiwgIiIsICIgIiwgIiAiLCAiICIsICIiLCAiIiwgIiAiLCAiIiwgIiAiLCAiICIsICIiLCAiIiwgIiIsICIiLCAiIiwgIiIsICIiLCAiIiwgIiIsICIiLCAiICIsICIiLCAiIiwgIiAiLCAiICIsICIgIiwgIiAiLCAiIiwgIiAiLCAiICIsICIgIiwgIiAiLCAiIiwgIiIsICIiLCAiIiwgIiAiLCAiIiwgIiAiLCAiIiwgIiAiLCAiICIsICIiLCAiIiwgIiAiLCAiICIsICIgIiwgIiAiLCAiIl0KMTAwCi1S) ## Explanation ``` å+ uP £X+QpYnV ``` Implicit: `U` = input array, `V` = input number. ``` å+ uP ``` Cumulatively reduce the input array (`å`) with string concatenation (`+`). This results in the array of each intermediate value of the reduction. Then, prepend (`u`) an empty string (`P`) to the array. ``` £X+ ``` Map `£` each value to itself (`X`) concatenated with... ``` QpV´ ``` The quote character (`Q`) repeated (`p`) `V--` (`V´`) times. This also decrements `V` each time. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~22~~ 19 bytes ``` {(-x,x-\y)$|,\x#$0} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rW0K3QqdCNqdRUqdGJqVBWMajl4kpQMLBKiza1NlQwAELDWKiAoQFMBIqR5MyBUnAYy6UP0wHTYgDXYgBWAzcAhTSEkggVhgrIViLUIbMMcZiMCQ2Q1BqgsFDtNEBXGQsAF2E1tw==) Takes two args: the starting width (x), and the list of values (y). Returns a list of strings, with `"0"` in place of `"#"`. * `x#$0` initialize a string with `x` copies of `"0"`, e.g. `"00000"` * `|,\` get the reversed prefixes of that string, e.g. `("00000";"0000";"000";"00";,"0")` * `(-x,x-\y)` determine how long each line of the output should be (with no trailing spaces) and negate it, e.g. `-5 -4 -4 -4 -3` * `(...)$...` left-pad each line (with spaces) to its proper length [Answer] # [Haskell](https://www.haskell.org/), ~~67~~ 64 bytes The input is flipped: `0` means remove right, and `1` remove left: ``` f n=zipWith(\x y->(' '<$[1..y])++('#'<$[1..n-x]))[0..].scanl(+)0 ``` [Try it online!](https://tio.run/##XY9BC4JAEIXv@ysGDZzFdVkPEUR56VqnDh1siTUMJduk3Uj786ZmFvGYw3zv8YbJlDmnRdE0J9DLZ17ucpvhvoI6iNADbzGJQ85rSX0fPXdYdVBJSmPBueTmqHSBPhWNTY1dKZMaWAIBiAGnDGLBwlZC0hYxwFCwDxrmx5x13qieSkK6XkDFEtoWl3e7tTdAk10fb0ghiga81uDM99rpyEWVm8OXo3KTv6RDyEXlui19Z/s74xPNCw "Haskell – Try It Online") ### "Ungolfed" ``` f n = zipWith (\x y-> replicate y ' ' ++ replicate (n-x) '#') [0..] . scanl (+) 0 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~138~~ 133 bytes ``` a->n->{char[]s=new char[n];int i=n,v,k[]={0,--n};for(;i-->0;s[i]=35);for(;i++<n;s[k[v=a[i%n]]]=32,k[v]-=v-1|v)System.out.println(s);} ``` [Try it online!](https://tio.run/##dZDbboMwDIav16fwzSRQCUo2TZuU0TfobnqJcpFR2qWlpiI068R4dmYOPdBqWIqs359/bG@00yzfp7hZbpv94TMzCSSZthbm2iBUE6DPYJkWK52k8AEVzOHokRKGIWhfQn2DzAlxuVn2FOAZsaUuyX1lUGdkhBA1ms2QzarkSxexshGm39DlqGTbayIMXLCNVVTxgDGs5SovPGkYm3FpY6Oi5xd/0KbTdyRtG7tIx@YRlaLqEzU7xSLHxK/zFz@2THdhfijDfUH@GXrWl3Uju/GG5Ycpuw12dAJvURK7jhXoYm19usgDhkdPBJxC@JTSCCftHK3@etF5T7dvW3kbV8Sp1vcJftt4KvPO/AyPXjG8F0IE1/YX7joT/zjfB79i@Sgb/5Pfkv1K7U7tletJ3fwB "Java (OpenJDK 8) – Try It Online") [Answer] # JavaScript (ES6), 64 bytes Anonymous function taking parameters in currying syntax (a)(b). In the b array an empty string represents removing from right and a space represents removing from left. ``` a=>b=>b.reduce((t,v)=>t+'\n'+(a.pop(),p+=v)+a,a=Array(a+1),p='') ``` Using 1 and 0 like in the examples the score is 70 ``` a=>b=>b.reduce((t,v)=>t+'\n'+(a.pop(),v?p:p+=' ')+a,a=Array(a+1),p='') ``` **Test** ``` F= a=>b=>b.reduce((t,v)=>t+'\n'+(a.pop(),p+=v)+a,a=Array(a+1),p='') function update() { var b=B.value.match(/\d/g) if (b) { b=b.map(v=>+v?'':' ') O.textContent = F(b.length+1)(b) } else O.textContent = 'invalid input' } update() ``` ``` Input B (0 and 1) <input id=B value='1001' oninput='update()'> <pre id=O></pre> ``` [Answer] # Scala, ~~41~~ 39 bytes ``` n=>_.scanLeft("#"*n)(" "+_.init drop _) ``` [Try it online!](https://scastie.scala-lang.org/OeeTo9yjTpGZm2JDWuERuQ) Uses 1 for dropping a hash on the right, 0 for dropping a hash on the left. Accepts `(n)(list)`. Outputs a list of strings. ## Input and output reversed, 35 bytes ``` n=>_.scanRight("#"*n)(" "*_+_.init) ``` [Try it online!](https://scastie.scala-lang.org/bKIqRustSA2MYfXi2rh4rA) Help! The sky's falling down! ``` # ## ### #### ##### ###### ####### ######## ######### ########## ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ×*…?(Ṫn$꘍… ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDlyrigKY/KOG5qm4k6piN4oCmIiwiIiwiMTBcblswLDEsMSwwLDEsMCwxLDEsMF0iXQ==) ## How? ``` ×*…?(Ṫn$꘍… ×* # Repeat an asterisk the first (implicit) input amount of times … # Print without popping ?( # Loop through the second input Ṫ # Remove the last character of the current string n$꘍ # Prepend the current item amount of spaces … # Print without popping ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 53 bytes ``` param($a,$b)"#"*$a;0..$a|%{" "*($i+=$b[$_])+"#"*--$a} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJU0lZSUsl0dpAT08lsUa1WklBSUtDJVPbViUpWiU@VlMbJK@rq5JY@///f4v/DhoGOgqGMARlawIA "PowerShell – Try It Online") Takes input `$a` as the optional integer and `$b` as the array of `1` and `0`s. (Note that my array of `1` and `0` is flip-flopped from the challenge's.) Constructs the initial line of `#` and leaves that on the pipeline. Then loops from `0` to `$a`. Each iteration, we output a possibly-incremented number of spaces, followed by a pre-decremented number of `#`. Yes, this will spit out a blank trailing newline at the end, since we're looping up to `$a` rather than the number of items in the list. All the individual strings are left on the pipeline and output with a newline separator between them is implicit at program completion. [Answer] # C#, 181 bytes ``` n=>a=>{var r=new string[n];r[0]=new string('#',n);for(int i=1,p;i<n;++i){r[i]=r[i-1];p=a[i-1]?r[i].LastIndexOf('#'):r[i].IndexOf('#');r[i]=r[i].Remove(p,1).Insert(p," ");}return r;} ``` [Try it online!](https://tio.run/##dZDBTsMwDIbvfQqrHJZoWcUOXMhSDkhIoCHQOHAoOYQ2RZFaZ0qyAar67CXtNG0g4UNsff79K3bpF61FO5SN8h6eky6BGD6oYErYW1PBozJI6IQPzTFevn3QbXa3w3JlMLBf4N3appAsujiDH4XMc6hBwIAiVyLv9sqBE6g/jwKU3BWX8gyR2cWMIeW1dSTagxFLtuVmhXw@N7RzhZEiPoul5FuhpuJmhNla@XCPlf56qkcPej3Rc8KPwzLb6NbuNdmyJY0Sr12IdQop5b3TYecQHO8Hnvzd@tait43OXp0Jem1Qk8OvswcbT5W@YcqgJleUxIUKCR0Et9MRqcaf0sigp5T@77/Rqprso2Zs90k//AA "C# (Mono) – Try It Online") Full/Formatted Version: ``` class P { static void Main() { System.Func<int, System.Func<bool[], string[]>> f = n => a => { var r=new string[n]; r[0]=new string('#',n); for (int i = 1, p; i < n; ++i) { r[i] = r[i - 1]; p = a[i - 1] ? r[i].LastIndexOf('#') : r[i].IndexOf('#'); r[i] = r[i].Remove(p, 1).Insert(p, " "); } return r; }; System.Console.WriteLine(string.Join("\n", f(5)(new[] { true, false, false, true }))); System.Console.ReadLine(); } } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` FN«P×#⁺¹ι¿I§⮌ηι↑↖ ``` [Try it online!](https://tio.run/##TUzLCsJADDzbrwj1koUWdq96Ek8FKyL6AbWmdGH7YB9FEL99bbe1GJKZZJhMWRe67ArlfdVpwKztnT275kEaGYN3tMmdsrLXsrV4kw0ZjLdxAhflDIoEJGNsH21kBXgsjMWDzdonvfBKA2lDWLPZA3k3EO7uPQNShtbzRJUdAz7eC86jcTifQIiJlh53EQQRhIALiD/zWsEx56yf/Cf6dPCpUV8 "Charcoal – Try It Online") Link is to nearest verbose version of code. Explanation: ``` FN« ``` The first input gives the number of loop iterations. ``` P×#⁺¹ι ``` Since loop indices default to zero-indexed, we add one here to get the correct number of `#`s. ``` ¿I§⮌ηι ``` Starting from the bottom of the tornado and working up saves a byte, but we then need to reverse the second input so that we can index the current digit. ``` ↑ ``` If the current digit is a `1`, move up. This makes the previous row have an extra `#` at the end. ``` ↖ ``` If the current digit is a `0`, move up and left. This makes the previous row have an extra `#` at the start. [Answer] # [C#](http://www.mono-project.com/), 159 bytes ``` using System.Linq;n=>a=>new[]{new string('#',n)}.Concat(a.Select((_,i)=>{var s=a.Take(i+1).Count(j=>j==0);var h=n-i-1;return new string('#',h).PadLeft(s+h);})) ``` **Explanation** ``` new[] { new string('#', n) } //start with n number of hashes .Concat( //append... a.Select((_, i) => // map each element of array { var s = a.Take(i + 1).Count(j => j == 0); // count the number of 0's up to, and including, this point var h = n - i - 1; // number of hashes for this step return new string('#', h).PadLeft(s + h); // number of hashes padded left with number of 0s })); ``` [Try it online!](https://tio.run/##pVDBTsMwDL33K6xxWKJ1UXtAHLrkggCBhjQxpB3GhELnsYzOFU06hKp@e0m3HrZJXMC2rMh23nt2aofbnPKmtIbeYfptHW7FdZ5lmDqTkxV3SFiYNAlOJsaGPpMgzbS1MAmqALxZp51JYZebJTxqQ4zvy4dma93f25LSkSEXnhfmixDub6jcYqHfMhxZV3hKpRSsQEJDUmmpCL/mi8pnOLRZ/6IfEq@9aEq1Y1pMsRXP2GtouFTVThdgpRbP@gOZGcTcT5bk2EaqjZQRT9qBtaShGcZJga4sCM7g11xM9HKMK8fsYM2TmvMmCc738gJsnqGYFcahPxCyA4R4yP0xei/UC2HFLjnbrwAVxGHkPQYPx5O/oV0do/no/D@QcXSCGe0jPsrtoyP4jeEJ/blagk5EHdTNDw "C# (Mono) – Try It Online") [Answer] ## PHP, 136 bytes ``` $b=explode(',',end($argv));$a=$argc==3?$argv[1]:count($b)+1;$c=0;for(;$a;--$a){printf("% {$c}s%'#{$a}s\n",'','');$c+=!array_shift($b);} ``` Save in a php file and test with `php file.php 8 '1,0,0,0,1,0,0'`. Output: ``` ######## ####### ###### ##### #### ### ## # ``` Alas, getting the input ready is half of the job. Another version (158 bytes) using `str_repeat` instead of `printf` and...`goto` of all things: ``` $b=explode(',',end($argv));$a=$argc==3?$argv[1]:count($b)+1;$c=0;z: echo str_repeat(' ',$c).str_repeat('#',$a)."\n";while(--$a){$c+=!array_shift($b);goto z;} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ŻµJṚżÄUØṖxⱮ ``` [Try it online!](https://tio.run/##y0rNyan8///o7kNbvR7unHV0z@GW0MMzHu6cVvFo47r/h9Ycbo9UedS0JvL//2hDHQMgNIzVgbGgGCYGh7EA "Jelly – Try It Online") Uses `0` for `1` and `1` for `0`, and outputs a list of rows with `!` for `#`. (Note the convenience testing footer `¬ÇY$€Y`: negate, join each output on newlines, join the outputs on newlines.) ``` Żµ Consider the input with 0 prepended. ż Zip J [1 .. length] Ṛ reversed Ä with the cumulative sums, U and reverse each pair. Ɱ For each pair, x vectorizing repeat ØṖ printable ASCII. ``` Since dyadic zipwith-vectorization pads with 0 when the shapes of the arguments don't match, every character in the list of printable ASCII characters is repeated 0 times except for space and `!`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://github.com/abrudz/SBCS) Takes 1's and 0's swapped. ``` (0,-+\⎕)⌽⊖↑,\⎕/'#' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@GgY6udsyjvqmaj3r2Puqa9qhtog6Iq6@urA5S8T@Ny5SrzlDBAAgNuR71ruFK4zI0gItAMULOHCQFhwA "APL (Dyalog Unicode) – Try It Online") `⎕/'#'` create a string of length `n`. `,\` get all prefixes of the string. I think there might be a way to get a list of all column heights and use this to get the output with `⍉↑'#'/⍨¨`, but I couldn't figure it out. [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éPQ─\▐┐·è ``` [Run and debug it](https://staxlang.xyz/#p=825051c45cdebffa8a&i=%5B0,-1,-1,0%5D,5%0A%5B0,+-1,+-1,+0,+-1,+0,+-1,+-1,+0%5D,+10%0A%5B0,+0,+0,+0,+0,+0%5D,+7%0A%5B0,+-1,+-1,+-1,+-1,+0,+-1,+-1,+-1,+0,+0,+-1,+0,+-1,+-1,+0,+-1,+-1,+0,+-1,+-1,+0,+0,+-1,+0,+0,+0,+0,+-1,+0,+-1,+0,+0,+-1,+-1,+0,+-1,+0,+0,+-1,+-1,+0,+0,+0,+-1,+-1,+0,+0,+0,+0,+0,+-1,+-1,+-1,+0,+0,+-1,+0,+-1,+-1,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+-1,+0,+0,+-1,+-1,+-1,+-1,+0,+-1,+-1,+-1,+-1,+0,+0,+0,+0,+-1,+0,+-1,+0,+-1,+-1,+0,+0,+-1,+-1,+-1,+-1,+0%5D,+100%0A&m=2) takes `0` as `-1` and `1` as `0`. ]
[Question] [ Imagine a very simple language. It has just 2 syntax features: `()` indicates a block scope, and any word consisting only of 1 or more lower case ASCII letters, which indicates a identifier. There are no keywords. In this language, the value of identifiers is not important except when they appear multiple times. Thus for golfing purposes it makes sense to give them names that are as short as possible. A variable is "declared" when it is first used. The goal of this challenge is to take a program, either as a string or as a ragged list, and make the identifiers as short as possible. The first identifier (and all its references) should be re-named to `a`, the next `b` then so on. There will never be more than 26 identifiers. Each set of `()` encloses a scope. Scopes can access variables created in the parent scope defined before but not those created in child or sibling scopes. Thus if we have the program `(bad (cab) (face))` the minimum size is `(a (b) (b))`. A variable belongs to the scope when it is first used. When that scope ends the variable is deleted. ## In summary: 1. If a variable name has appeared in the scope or enclosing scopes before, re-use the letter 2. Else create a new letter inside the current scope 3. At the end of a scope delete all variables created inside the scope. ## Test cases ``` { "(rudolf)": "(a)", "(mousetail mousetail)": "(a a)", "(cart fish)": "(a b)", "(no and no)": "(a b a)", "(burger (and fries))": "(a (b c))", "(burger (or burger))": "(a (b a))", "(let (bob and) (bob let))": "(a (b c) (b a))", "(let (a (fish (let))))": "(a (b (c (a))))", "(kor (kor kor) (kor kor))": "(a (a a) (a a))", "((kor) kor)": "((a) a)", "(aa (ab ac ad) (ad ad) ad)": "(a (b c d) (b b) b)", "(aa not (ab ac ad) (ad ad))":"(a b (c d e) (c c))", "(((((do) re) mi) fa) so)": "(((((a) a) a) a) a)", "(do (re (mi (fa (so)))))": "(a (b (c (d (e)))))", "((mark sam) sam)": "((a b) a)", } ``` ## IO 1. You can take input as either a string or ragged array. 2. You can give output either as a string or ragged array. 3. However, you must use the same format for input and output. Specifically, you need to produce output in such a way that it would also be a valid input. Applying the function or program more than once always has the same result as applying it once. Neither scopes nor variable names may be empty. Applying your program to its result again should be a no-op. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 149 bytes ``` (load library (d G(q((L N)(i(c()(h L))(i L(c(G(h L)N)(G(t L)N))L)(i(contains? N(h L))(c(last-index N(h L))(G(t L)N))(G L(insert-end(h L)N (q((L)(G L( ``` The last line is an anonymous function that takes a nested list and returns a nested list. The returned list uses nonnegative integers instead of letters, which seems to be allowed by [this comment](https://codegolf.stackexchange.com/questions/251864/re-name-all-identifiers-to-a-single-letter#comment560861_251864). [Try it online!](https://tio.run/##VY07EsMgDER7n2JLqfAZ0oWG8R34JSZDcGwo4tMTwBlP0mj2aVer7OMefHqVQmFRFsHrTW37QBaCViKJicmTIaYZkquGrCQ6VUtQ7oJljy0xKx/TBdM3biiolEcfrXufy/OIRG2rebfl0UV7lLbf1/778Evl7FI2KjnQCgougx7@iSb0ormNvw0UNAwsHG64Y4bnZjHzQNezrMMvc/kA "tinylisp – Try It Online") Or, [verify all test cases](https://tio.run/##bVPLcsMgDLznK3SUDp1pHvfekkum/4ANbphiSIDMNF@fCmHjPswYkMVqvSw4W/9wNl2fT3RBaXC2iyo@aIMaTnhDPMM7ocUeCS9wJo7hzG8neeOlE2YJ6Cyw4LOyPr3B@wTv0amUX6zX5qslWxGemI3xJuYX4/VEWluRcBQJFSbJJ2ozQDYp9yqZtAG8bQAQMd51cAPBSsNXJiszjuGeDAt00CJqIGiwXsUMg00XWuGC7QzzAZTX4MM6bOHr7vHDRMCCHqI1iegHELewo7/QEKGGf6GvDepMBuxCV0RQjTgl@Jl1pUABlp0BCnZmrwW4E69awSerkIE7LdH0hWrZZNxUgYKU4Z8lTL1YoliHYuk9qCKeb16ZS5/Fw17kb2kxnIt8yCuFVA1n/Xs4UJkXR0vTfETREIyWYFAEqR6ZrImq9kxFOgBGAzhatoulcsFs1mLVHvBAP@zCUcVPSGqkOvzefNnJZC4Dr3xznRo7zeTlJhcKNLe7cm9CdgS8GN6crFX@i1zcmuBM@wfo@Q0). ### Ungolfed ``` (load library) (def _rename (lambda (expr names) (if (type? (head expr) List) (if expr (cons (_rename (head expr) names) (_rename (tail expr) names)) nil) (if (contains? names (head expr)) (cons (last-index names (head expr)) (_rename (tail expr) names)) (_rename expr (insert-end (head expr) names)))))) (lambda (expr) (_rename expr nil)) ``` --- Here's a **167-byte** version that uses letters instead of numbers: ``` (load library (d G(q((L N)(i(c()(h L))(i L(c(G(h L)N)(G(t L)N))L)(i(contains? N(h L))(c(single-char(a(last-index N(h L))97))(G(t L)N))(G L(insert-end(h L)N (q((L)(G L( ``` [Try it online!](https://tio.run/##VY6xUsMwEET7fMWWe4Vn7BAIqejixpN/kCURi1FkYqkgX@9ICjDQ3Oze7ry75MLNu/i5rvSzMvBuXNRy29Cg55UccBI6agonDJI1huz66nLUM1UhQ63NISkX4htO33XN6MLZ20ZPaqGiVzE1Lhj79VM57OUPhn3mZ4JdUmODeZwp3xzrN498zT7ZmLSKFryC3ibww11QxDiPUsa/DRRGaBhYvOOMCU5KJCIbHn9h1RRgC3ZosRV04DarDk/Y4Rkv2OMVB3R51QnaDFjv) [Answer] # [Python](https://www.python.org), 79 bytes ``` f=lambda _,**s:[i==[*i]and f(i,**s)or s.setdefault(i,chr(97+len(s)))for i in _] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZJNbsMgEIWlLnsK5JVx0277I_kMOYCForGBGgVDBHjRs2STTXqn9jSFoVZiqkj1gueZ-WbmCfv4efgIozWn03kO8vHlaytbDVPPgew2TePfOtW2XaMYGE5krVKOWkf8kxeBCwmzDjE7jK5-fX7QwtSeUiojoYgyZMfy2O-74eCUCbWsu8rN3GpZMUrvL8nJznEiKF1tyFWwhgZwIdWl8mNRMjYVosskMVhX-9m9CxdL3YJIp4Sv2E3MJlkSBaZFQKa3_bKUXcWpfKMD8ET76SWTBbu32UFWFFbGq45uYbKuhkHeCNnogOevW-CXCOVvY7zI8I_-tZv4VNziVCdQJoUiAcWXH4db3BHhJBHGO8rGE1zeUGTA7dNyD1MemZTS_K8tv_IP) Thanks to @loopy walt. ## [Whython](https://github.com/pxeger/whython), 66 bytes ``` f=lambda _,**s:[s.setdefault(i,chr(97+len(s)))?f(i,**s)for i in _] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZLNSsQwEMfBo09RcmrW6tUPWARfo5Rl2iQ2bJpIPhCfxctexGfSpzGZWHYTWbCH_DMzv_lgmvfP1_nNz0YfDh_Bi-u7ryexVbCMDJpdt9m4h97dOO4ZFxCUb2U3zba9v71SXLeOUvoooi9yVBjbyEbqZjfkSt8X04uV2rei7YkNzChBBkovj87FhFgapCJdc2KU0ATWp7iQbq5C2qQAaJYkGmV0DPaZ2xjqV0RYyR0ZzmImyeqoMMU9MqMZ16bDiZ3CZzIATxw_XTJZsXuTJ8iKMtR2kdGvTNaiGOSOkAed8PydFtjRQvmbGBfp_5FfThM_wgxWtRxlkSgCUFz9c5jBHhFOEmHcUR48wfWGIgN2n5o7WHLJpJTmt7a-3h8) Port of the above. ## [Whython](https://github.com/pxeger/whython), 72 bytes ``` f=lambda a,s={}:s.setdefault(a,chr(97+len(S:={**s})))?[f(i,S)for i in a] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZKxTsMwEIYlRp4iymSXwApUiljZO0YZLrFNrDo2sh0hVPVJWLogngmeBvtM1MaoUjP49_m-u_vl-OPrbXj3g9GHw-fkxe3D97OoFYwdgwIqV-_2a3fnuGdcwKQ8gaofLHm8v1Fck8263q1Wbk8pfWoEkdWGCmMLWUhdQJv6_Vz1r1ZqTwRpSjsxo0TZUnp9PBzNFAaAVGVVnARLqAfrY15IN2QpbWICNIsSgmW2m-wLtyHVzIiwkruyPYuZKPNBhinukelMNw9tT-KYPlMBuKL9uElkxm5NcpAUpc3jRUUzM0kXzSBNhGS0x_XPLbBjhPK_MFykv6B-6SZ8JTPY1XKUUaIIQHH5z2EGZwQ4SoDxjpLxCOc3FBiw2zjcwZhaRqU0vbX5Df8C) My original solution [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~81~~ 70 bytes ``` \X,[I]-->[H],{copy_term(X,Z),\(Z,H,I);nth1(I,X,H)},(\X;[]). a--> \_,!. ``` [Try it online!](https://tio.run/##bZBLT8MwEITv@RXhlkjTSuVxQiD1nfR5rXBXldukJaKJkZMKIcRvL2s7lICIZGd3Pnt2kletjurQKt@y83m9goip1XoUEeFjp17fN1Wq82CFpxDr4AkR4vC@qJ47QYwVovATwXp1Lyhse5Kv@esNrtrnswyEPiXquCd0Q3jc5upUppXMjrhUhJ5jO6kr7LPymdB3SqEgiwSFIgycsj3pQ6ohjLzXWVoSYfgbKQ1XMho5dEwriK3aGjdyFUvMxw0uIcxwCIsYRg6@sKHdeNFPRfwLLBdWt9vEKZKtJA/bQZpxMrFvs6aXA4Wq/jlEmNWm/CT82Tol5BlhLwkl93OHEwWhU4g849A8jZGNvKhv51K/oJQ5uW3JcrfrP/iiQ/B6PVvBN02/XzfX3AwG342Dw2HdCxZu2N8bjRpKxyjj8a8zDRJFDSJuYKabkF4cfwMXon4zmUwMMSnt/Om06Q3/trbnrDbvbPaT1wy4hX9HrrRp53NrJy6OzeUtFn/z8X1x5/6kt1y6KG5ah9pf "Prolog (SWI) – Try It Online") Instead of using predicates, I use definite clause grammar (DCG) notation. DCG notation is syntactic sugar in Prolog that allows for more writing more concise code for sequence processing. The basic way my program operates is that it iterates through the input and output list using DCG notation to bind the first item of the remainder of the input list to `NextItem` and the first item of the remainder of the output list to `ProcessedItem`. Then the program handles each potential case for `NextItem` and binds `ProcessedItem` to the appropriate value. Finally, the program attempts to process the following items, or, if none are found, terminates. I stumbled onto an 11 byte golf of my program when I realized my original code was broken. The issue was that when parsing a sublist, the inner scope would leak into the outer scope since `InScopeVars` was having new variables placed into it by `nth1/3`, instead of by the intended `append/3`. I found a way to exploit this behavior though with the `copy_term/2` predicate, which unifies the second argument with a copy of the first argument but with fresh variables (e.g. `copy_term(X,Z)` where `X=[aa|SomeVar]` unifies `Z` with `[aa|SomeNewVar]`). This allows us to create a copy of the scope to use when handling a sublist where its uninitialized tail can be used without the inner scope leaking, thereby allowing us to use `nth1/3` for both appending and finding the index. ## Ungolfed Code ``` rename_item(InScopeVars), [ProcessedItem] --> [NextItem], { % Case 1: NextItem is a sublist % This predicate sets InScopeVarsCopy to a copy of InScopeVars, % but replaces all Prolog variables in it with newly instantiated ones. % This means any unifications that occur in the following rename_item call % will not affect InScopeVars copy_term(InScopeVars, InScopeVarsCopy), % DCGs are syntactic sugar for predicates with an additional two arguments: % the input sequence and the output sequence. % This fails if NextItem is not a list, in which case we'll % do Case 2 instead. rename_item(InScopeVarsCopy, NextItem, ProcessedItem) ; % Case 2: NextItem is a variable % We unify ProcessedItem with the index of NextItem in the list InScopeVars. % Note that since InScopeVars initially uninitialized, % it gets unified with [NextItem|UninitializedVariable]. % On later calls, if NextItem appears in InScopeVars then ProcessedItem is % unified with the index of NextItem. % Otherwise the head of the uninitialized tail of InScopeVars is set to % NextItem, and NextItem's new index in InScopeVars is unified with % ProcessedItem. nth1(ProcessedItem, InScopeVars, NextItem) }, ( % Attempt to rename the next remaining item in the list rename_item(InScopeVars) ; % If that fails then we are done! [] ). rename --> % Due to the way the nth1/3 predicate works, passing in an % uninitialized variable for the initial scope is in essence passing in an % infinite list of uninitialized variables. % As we encounter new (not Prolog) variables in the input program they will be % unified with the first uninitialized (Prolog) variable in the scope. rename_item(_), % Once we get the first solution, we use the cut to prevent backtracking !. ``` Before I realized that it was permitted to output numbers instead of letters I wrote the following program, which I've modified to use some of the golfs I later found: ## 92 bytes ``` \X,[I]-->[H],{copy_term(X,Z),\(Z,H,I);nth1(N,X,H),C is 96+N,name(I,[C])},(\X;[]). a--> \_,!. ``` [Try it online!](https://tio.run/##bZDda9swFMXf/Vd4bzY7CfSlMMoGifNh58N5DVUuRbGV1jS2iuwwxtjfnl1JbuqOGSTde37yucd@M/qsn0ftz@p6PewhMhqNfoiU8LvQb7@eOmXqaI/HGIfoESmy@KHpXu6iHHukMZKwasNv919zNLJWUQaRUPwH0WH/ICgeB5LNwsMTvoyvVxkJcyn1@USYxAi4rfWlVZ2szrhVhKlnhTQdTlX7Qki80mjIpkSjCTOvHC/mWRkIK59MpVoizD8jbeBLRguPzqqDOOqjdSNfscR8OeASwg6HcIhh6uErG7qNF31UxD/GceF0t628ItlK8rAC0o6TpTvtWt8uNLr7zyXCpjflp@TPNopQV4STJLTcbz0uNYRREHXFoXkaIxc579@upXlFK2vy247lyST8Hgq2CaZTVyG0TZL0zZGb2ey98XA@73vBQsH@wWIxUKRVlstPdwYkTQdEFLDTbcggy96BD9GfTFYrS2xKN3@9HnojLHt7zurybjYfee2AEqEiX7q0262zEzfH4Qry/N98/L5Q/k8Gu52P4qdJGv8F "Prolog (SWI) – Try It Online") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 101 bytes This version uses 1-26 instead of a-z (alternative version for a-z below). Had to (re)learn about Prolog dictionaries for this one, I like them! ``` [H|T]+[I|U]+A/N:-(H@>[],H+I+A/N;I=A.get(H)),T+U+A/N;I is N+1,T+U+A.put(H,I)/I. A+A+_. A+B:-A+B+_{}/0. ``` [Try it online!](https://tio.run/##dVJda8IwFH3WX3ERhi2JdXt1KHN7sS8@bApCCJK2qQbbRpIWB3O/3d00tBsbK@Tk5pz7lZuejS70YWIv6nZjq@uGExZft5wsp@vZJFg9LRinKxK782M8X0YHWQerMKQbsvUcKAtr8uCJ6NygTONwGkfDJVmSvdueZxMEsv/4nN5Ht9kELkbVsqiC8UbaWlWHKIrGIR0CQCnOhbJ1wHZ8sQh25FXapqgpDAcD8HZP3cHLUaYnUDnkwXsIc9ycEcJRF5ltQ7pCPgbbBlcEGEtERlkqEk5ZLlLJOfWCaTJd5N2p1I2VtVAFhd7stFQYbCJX9tgxlaYgqoxCpTsqacxBGgqs5XOjpOV/NI3gD71WSMzNEp20GXlnI/3LReByPdCW4LyXTy6rRwT@0@5cmBda9Ixw6YQrmuJq6@KcvOXg26vS9X@ufXr8MpwEGIlQKoRcINh@OhkOjBmJUCp3D1cd1R@3YKUwJwwRJffI/W/SvevorUlTaUdhdPsC "Prolog (SWI) – Try It Online") (The `H@>[]` part is a bit hacky, it's a list check (`is_list(H)`) that works on TIO, but there's probably a way to get rid of it, as neither are necessary in my ungolfed solution. Please correct me!) ### Ungolfed, commented ``` f([H|T],[NewH|NewT],Dict,N):- % Case 1) No dict update needed ( f(H,NewH,Dict,N); % First element is a list (matches f([H|T]... or f([]...) NewH=Dict.get(H)), % First element is an atom f(T,NewT,Dict,N); % Case 2) If first part failed, need to update the dictionary NewH is N+1, NewDict = Dict.put(H,NewH), f(T,NewT,NewDict,NewH). f([],[],_,_). % Wrapper predicate for recursive predicate A+B:-f(A,B,_{},0). ``` ### a-z solution, 114 bytes ``` [H|T]+[I|U]+A/N:-(H@>[],H+I+A/N;I=A.get(H)),T+U+A/N;Z is N+1,name(I,[Z]),T+U+A.put(H,I)/Z. A+A+_. A+B:-A+B+_{}/96. ``` [Try it online!](https://tio.run/##dVJdS8MwFH12v@IiyFqSdfgiONlw@rK@7EEnyEIYaZtuYW0zkpYJzt8@bxpbRbGQk3vPuR/JTQ9GF3o7skd1PrPFacUJi08vnMzHy8koWNzPGKcLEjv/Lp7Oo62sg0UY0hV5abk1KAtLck0rUcogpmzNv8To0GAojcPxOhrMyZxs3PYwGSGQzfvH@PYmOk9GcDSqlkUVDFfS1qraRlE0DOkAAEpxKJStA/bKZ7PglTxJ2xQ1hcHFBXi7p67gcSfTPagc8uAthCluzghhp4vMtildI5@DdwDXBBhLREZZKhJOWS5SyTn1gmkyXeSdV@rGylqogkJvdloqDB4iV3bXMZWmIKqMQqU7KmnMVhoKrOVzo6TlfzSN4J1eKyTWZolO2oq8s5H@FSJwuTPQluC8l/euqkcE/tPuQpgXWvSMcOWEa5riavvinLzl4Duq0vV/oX15/DKcBBiJUCqEXCDYfjoZDowZiVAqdw/XHdUft2ClMHtMESX3yP1v0r3r5XOTptJehtH5Ew "Prolog (SWI) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 208 bytes ``` a[26];b[26];c;d;e;f;g;h;i(*j){for(;f=*j;j++)if(f/47)c=c?:j;else{if(c){for(*j=g=d=0;a[d]*!g;wcscmp(a[d],c)?d++:g++);g||(a[d]=c,b[e=d]=h);putchar(d+97);}for(c=!putchar(f);f==41&b[e]==h;a[e--]=0);h+=f%17-47%f;}} ``` [Try it online!](https://tio.run/##dVPbbuIwEH3nK6ZIrGwCWlqhRYtl9Qf2DyAPji9JaC7ISdQVNL@@7NhpQoDWSsbjmXPGc5HlUmaiiC8XsXv5FbLIS8kU08ywmCUsJfMDPZvSEmb4/MAOQUBTQ8zP9YZKLl@3B6azSp/RJjvc/MBjrviKiZ0K508xe5eVzI/EHReSvqog2MYYhcUfH97I5SLaaY5KQtmxqWUiLFHB7w1lrQso@VNvNRSz4OvnH0gIOU/wDr1chnxFWRJwM3veLNebmWFte0mLGnKRFoTCeQK40DCHWlf1LgT@aXPrz5TYRpWZodOFOwjcx868bCpdizSDQeuRcI@VwtZg0ioZENEdoihBFAqK8op4iBI1NtYWiAMam@qKDmASgaTfwEsLnXoDF/fwTNdoLyOXB@00NN1d8T0TAa5AIJ50QyMS3Z1tTHvDxLzAn161K9P1sZN3TOIZTnRYjP7QLOECYLIShCtHKL/jP64HfKU4jId5IL0o6y9CjOaDdSnQ1O0PzXdLlRQs@vOUgsEUq364bvmUh@@WrEogVgPJU2wqZorEL1qqgGj62FaSC/sGlcipF32HXJE396wWsPKHlvnNuHG413HCZ7Bi3ZM4hQxOAX@ho4dxtIgyZDrLqn0BWGHVZPUW8KJPCmUDNiX4ylVzJL1r5Ovj7Av996hlrdUWfMx9McSCAJ77eO2knVz@SZOJuLos3/8D "C (clang) – Try It Online") -1 byte thanks to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9)! -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)! -1 byte thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)! [Answer] # [Ruby](https://www.ruby-lang.org/), ~~69 65~~ 60 bytes ``` f=->l,*r{l.map{|x|x*0==[]?f[x,*r]:""<<97+(r|=[x]).index(x)}} ``` [Try it online!](https://tio.run/##jVLNbsMgDH6VilPbZdVu06amexDEgRTYUJNQmURiavLsmW2C1vW0HPjy/WDsBBib72Vx9fOprfZwaw@dvt6mNKX9S11L9eFkQl29C3E8vr0@bWGqZVK7g@@NTdu0m@dFSgGjCa0TqpKiC2O0g/atqDZ3hKyzhoFU5@MXC30gqntDgIS0ZoRPCyjIYjjwNgr1YAaCIrDZ2oGdJjSlrLrjZP/JaV65GXrJPicuIZ@RkUE9cszJ4qyIJXNNnRs487p2oc0vy7DGcfDhH7voPHyECVwBLEPnGZxmiPkTmsD1MEKAEZ4zt0aRPCU6Gi5UPuoubydU5QZcN/jv1bz8AA "Ruby – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~65~~ 54 bytes ``` {$[x~*x;`s$`c$97+(s::?s,x)?x;[t:s;r:o'x;s::t;r]]};s:!0 ``` [Try it online!](https://ngn.codeberg.page/k#eJx9kt1qwzAMhe/7FB0UFm+52N1YdNEHKQE5ib2FNjHYLqSM9tl3lPQvaTqDZSH5y5EU2+x3telObx1xWHG5+vp8T0KWrUPaqXVHm5gF8pl77QjRSD7Pj/BePhaLKOTh5DO7BOy2lLDV9Y46OpBX+XERNyn7feV2djmzKGU9F8/BceP2wUR87eZdOdazYM+V2ke2dfiZ0QNXPONax7qtcDzhZhSFS7jY+2/jqaetr01QVy5hTSBL9R/n/Nl94PQstzMRSVeI4OAgokZ6E/jGyYWknw5mL5hSFw4FYZfyT4bohds6FAkzcu709NlM9NLr/UkXwqU9M00MelpSqL9kjf50dT7UXX8sjaNeLtSYa118gNWFIwHZyFHeOKyUK0fsjSJuahirYYJTNCT7Uu/3oAcmAQTT1P3Dx+gAYY3miYtIGIkPXKP9loNuSIwaz0Ue2uNg8j8UqPek) [Answer] # Rust, 277 bytes ``` enum N{A(String),B(Vec<N>)};fn f(a:&[N],b:&mut Vec<String>)->Vec<N>{a.iter().map(|j|match j{N::A(j)=>N::A(('a'..='z').map(|i|i.to_string()).nth(b.iter().position(|a|a==j).unwrap_or_else(||{b.push(j.clone());b.len()-1})).unwrap()),N::B(j)=>N::B(f(j,&mut b.clone()))}).collect()} ``` [Playground Link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a3966f982bd29bd1b9546c075f5f8139) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 109 bytes ``` s=>s.replace(/\w+|\S/g,m=>m>')'?v[m]=v[m]||Buffer([v[0]++]):(v=m<')'?S.push(v)&&{...v}:S.pop(),m),S=[v=[97]]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVPNjtMwED5w61OMKrSx1Wx2hUALLe5KSJw59JhGWjdx2rBxHNlJQGr7JFyqFTwJTwFPw9hu06y2WM146vm--fks__hZqUwcnnL2q23y6_d_pGFzE2lRlzwV5Gb5bbJbLm7WoWRzOQ9ocN_FMmHW7Haf2jwXmsRdfJtMJgmdko7Jjxa0iOrWbEhHr662URR1-ymeqJrQUNJwweKOxR_ukoT6on9f_Z6NRl9WX0XaRKJqdCEM2Y4A15joNlNlTsdTeLnGhNNxeARK1RrR8KKE3utZCIQBNOW6gbwwmwtpLXR1hlYKeJVBpf4HHeZdtXotNBDLyO0U9MyyYLKClL6EKw3efQnnA3gpGjxSK9sQ9R4eeU6f_SIJY3ZaIA7fVzmSSIoId3wiPWJHzuBHz965klXT2zOJOLA1l5TCCkOluE2CnabA7Sw8czt-yD3NAm5KvIzhfSCxUs0FMjL9feA4GQhq96HYdmWKgsaQLCjk2JA53qqPug77X0_MFBAtgMgCVcTOkNRrOFAwAyLoMxWJ5PoRDJfUmWeqWEHsZK7Onka50p95uiEkLqq6bUIQ32t8DQkFNgf7FFJVmQZU22AUGOTE4eisD9XcGAycEIwdU5wQqhRRqdbE4e4hWLZv7m7fBTD17ts0COFYO7ie4x-fKYQTwUIfiE8qMni99e6ePmAXezrzb_lw8Ps_) ## Ungolfed and Explained ``` str => str.replace( /\w+|\S/g, // replace each variable name or bracket m => m > ')' ? // if match is a variable v[m] = v[m] || Buffer([v[0]++]) : // lookup the new var name, otherwise assign new ( v = m < ')' ? // otherwise, if match is opening bracket S.push(v) && {...v} : // push current var dict to stack S.pop(), // otherwise pop var dict m // return matched bracket (no-op) ), S = [ // initialise stack v = [ // initialise var dict 97 // v[0] = char code of next var name ] ] ) ``` [Answer] # [Raku](https://raku.org/), 76 bytes ``` sub f($x,%h?){$x~~Str??(%h{$x}//=chr 97+%h)!!$x.map:{f $^a,$_}with %h.clone} ``` [Try it online!](https://tio.run/##TYzdCoMwDEZfJUIllRW929jA@RC7n9Q/KqiV1jGH6Ku7xN0sN4fvy0nG2nXnffevAhopZhWaLFrEvG2PyWWZDA2FNUnS0ji4Xk6hiYJAzHGvx9vSgHhqJfL13U4GQhOXnR3qdff6AyJXgJDeARWQl0NjHUiJXT1RI7GwBRH1UGH0l3kdccGDlUVFAV3NEvbtgUYf8PZ3yRKBHAY5DHIYnh8cs38B "Perl 6 – Try It Online") [Answer] # Perl, ~~63~~ ~~60~~ 29 bytes (+1 for `-p`) ``` s/\w+/$a{$&}||=chr$i+++97/ge ``` Run like: ``` $ perl -pe 's/\w+/$a{$&}||=chr$i+++97/ge' <<<"(rudolf)" ``` or even ``` $ perl -pe 's/\w+/$a{$&}||=chr$i+++97/ge' file ``` ### Ungolfed and explained This is a simple replacement using the powerful `/e` modifier, which instructs perl to **e**valuate the replacement as code. It finds each identifier and checks it against a hash. If the hash is empty, it populates the next available letter, starting with ASCII code 97 (`a`): ``` s/ # substitute (\w+) # match: 1+ word characters / $letter{$1} ||= # use existing letter or else assign … chr($i++ + 97) # … a char w/ value of $i + 97, then increment $i /gex; # match globally and eval the replacement as code # (this explanation uses /x for comments & spacing) ``` Running through the examples on a file containing each test case on its own line: ``` $ while IFS= read line; do printf "%-30s %s\n" "$line" \ "$(perl -pe 's/\w+/$a{$&}||=chr$i+++97/eg' <<<"$line")" done < test-cases (rudolf) (a) (mousetail mousetail) (a a) (cart fish) (a b) (no and no) (a b a) (burger (and fries)) (a (b c)) (burger (or burger)) (a (b a)) (let (bob and) (bob let)) (a (b c) (b a)) (let (a (fish (let)))) (a (b (c (a)))) (kor (kor kor) (kor kor)) (a (a a) (a a)) ((kor) kor) ((a) a) (aa (ab ac ad) (ad ad) ad) (a (b c d) (d d) d) (aa not (ab ac ad) (ad ad)) (a b (c d e) (e e)) (((((do) re) mi) fa) so) (((((a) b) c) d) e) (do (re (mi (fa (so))))) (a (b (c (d (e))))) ((mark sam) sam) ((a b) b) ``` This prints the input in a 30-char column before printing the answer. ]
[Question] [ We can read `13576870234289` digit-by-digit in English, and it makes a haiku: > > *one three five seven* > > *six eight seven zero two* > > *three four two eight nine* > > > We say it's a "digit haiku", because when read out like this, it's 5+7+5 syllables long, **and** no word is broken across a line. For example, `111171111101111` is **not** a digit haiku, even though it has 17 syllables: > > *one one one one **se-*** > > ***-ven** one one one one one **ze-*** > > ***-ro** one one one one* > > > Two-syllable digits (`0` "zero" and `7` "seven") are not allowed to span the 5th-and-6th syllable positions, or the 12th-and-13th syllable positions. (Other than that, any 17-syllable digit string makes a digit haiku.) All other digits beside 0 and 7 are one syllable long in English. ## Task Given a non-empty string of digits (or list of numbers) `0` through `9`, decide whether it forms a digit haiku. * You can assume the string does not start with `0`, and thus you're also permitted to take input as a number. * You can assume the input is at most 17 digits long. However, it may be more than 17 *syllables*. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): aim to write the shortest answer, measured in bytes. ## Test cases ``` 7767677677 -> True 13576870234289 -> True 123456789012345 -> True 11111111111111111 -> True 9 -> False 9876543210 -> False 11171111101111 -> False 111171111101111 -> False 998765432101234 -> False 77777777777777777 -> False ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes ``` 0|7 _# ^.{5}\w.{6}\w.{4}$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w36DGnCtemStOr9q0NqZcr9oMTJrUqvz/b25uBoQgxGVobGpuZmFuYGRsYmRhyWUIpE3NzC0sDcAsLkN0wGXJZWlhbmZqYmxkaACSNgcLG0DkEFIg7Vzm6AAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` 0|7 _# ``` Expand `0` and `7` into two syllables. ``` ^.{5}\w.{6}\w.{4}$ ``` Check that neither the 6th nor the 13th syllable is the second such syllable. [Answer] # JavaScript (ES6), ~~48~~ 41 bytes Expects a list of digits. Returns a Boolean value. ``` a=>a.map(d=>i-=d%7?1:i%7-6?2:.1,i=17)&&!i ``` [Try it online!](https://tio.run/##hU/LDoIwELz7Fx54JYUAAgWSws0v8IYcGh5ag0AATfz6uiIaDI1k00l2d2Y6e6F32mcdawe9bvKCl4RTElHjSls1JxHTSS7h2AqZhHUvtkPDQoxYWJPlLeNZU/dNVRhVc1KV5NDdhvMjVbTNfF6qCUYYedObMNUWLAvtkDvufUAT2dA7gD4KhOz33h39gAOK70zIX6mX5kekHOtkT6tedJEoUTDm9iCRAyls8DT/5MCzv815hoWrwPdzqYCP0UqBhj8B "JavaScript (Node.js) – Try It Online") ### How? We use a syllable counter \$i\$ initialized to \$17\$, subtract either \$1\$ or \$2\$ from \$i\$ after each digit and check whether we end up with \$i=0\$. The haiku is supposed to look like that: ``` 17 16 15 14 **13** 12 11 10 09 08 07 **06** 05 04 03 02 01 ``` When the digit is either \$0\$ or \$7\$ and \$i\equiv 6\pmod 7\$, we have an invalid hyphenation and subtract \$1/10\$ from \$i\$ instead of \$2\$. Because this test can only be triggered once, \$i\$ remains a non-integer value whatever happens next. [Answer] # [J](http://jsoftware.com/), 32 30 bytes ``` 4=5 12 17+/@e.~[:+/\0,~1+0=7|] ``` *-2 thanks to xash* [Try it online!](https://tio.run/##bY1NCsIwEIX3PcWjmyDVdNI2mTQQEARXrtxWV9JW3HgB6dVjWgVpcH5g5n28mUfIpRjgHQS2ILjYO4nD@XQMjddQFRQX5b6XU@eK8kLbSRXk@XUNm2z0snMYkMucsqy/3Z9Q8BghmE3MucRKV7VmY5mquqlsm7AoasO2pWVKYBpfTB/cJqtlo5u6UrTWo48XN/058TPN/9eQ0xDhDQ "J – Try It Online") ## original explanation ``` [:(5&e.*12&e.*17={:)[:+/\1+0=7|] ``` [Try it online!](https://tio.run/##bY1BDsIgEEX3PcWki6K20oG2TEtCYjRxZVy4ra5MW@PGA@jdkaKJgTgDBP77f7jblLMRjAYGBSBot9ccdqfD3vZ60WQDXwnpTzJPvex1Xp5FjoZeF7tMjlsOlZmN4F15uSkC48AzhsSSZDK81zBCylNMhuvtARMwUTWkWkJZ1bLtnMsDAWaGRMr1vFigx6GAObFR1HbobxGM64vxg7vo2ZJq6koKDHWXI5/GPyN@ofn/EFJczL4B "J – Try It Online") Straightforward: * Take list of digits * `7|]` mod 7 * `0=` equals 0 (returns 1-0 list) * `1+` add 1 (now list of 1-2) * `[:+/\` scan sum * `[:(5&e.*12&e.*17={:)` is 5 an elm and is 12 an elm and is 17 the last? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 7ḍ‘ŒṖ§Ḍ575e ``` [Try it online!](https://tio.run/##y0rNyan8/9/84Y7eRw0zjk56uHPaoeUPd/SYmpum/nd51LTmcDuQACowNwNCENJRMDQ2NTezMDcwMjYxsrAE8oEMUzNzC0sDMEtHAShmaWFuZmpibGRoAJQ3NDQ3BAEDEAGUQ0iCNAAA "Jelly – Try It Online") # Explanation ``` 7ḍ‘ŒṖ§Ḍ575e Main Link // convert to syllables 7ḍ Divisibility by 7 (1 for 0 and 7, 0 otherwise) ‘ Increment (2 for 0 and 7, 1 otherwise; this gives the syllables) // all ways to divide the digits into lines, and total syllable counts ŒṖ Partitions (all divisions of a list) § Sum each sublist for each partition // check if any of them are [5, 7, 5] Ḍ Convert the lines' syllable sizes into a decimal integer; this can cause collisions but not if the total number of syllables is maximum 34 575e Is 5-7-5 a possible partition? ``` Takes a long time on some test cases so I didn't include them. -1 byte thanks to Jonathan Allan [Answer] # [JavaScript (Node.js)](https://nodejs.org), 46 bytes ``` s=>/^.{9},.{13},.{9}$/.test(s.map(c=>c%7||.1)) ``` [Try it online!](https://tio.run/##XU/NboMwDL7zFDmsItGoy08hoCrctifYrWvVKIMuEyOIsAmJ8uyMoNFIdSzL/n4c@Yv/ci1a2XTbWn0UU8kmzfLdGYZs9GAIIlOz8WkHXaE7rOGbN1iwXGzo7QYBIZPBBdcFYuhCaTI/k2ibo7f2p3CCKKZJSv0w2odpZuF5jhOaZv7SWfwx7szifeWVntuUJvE@CgPfYrOULgZ/df1rrdj8ZAn6GHfqArqpZIfd99oly8E9YjnqV9gIXUIOzno6lKp94eIT46P0kDoRIx8coWqtqgIqdcUlPgKAPNl1zz0hnvLkvGckh@kP "JavaScript (Node.js) – Try It Online") Take input as array of digits. Output truthy vs. falsy. * `s.map(c=>c%7||.1)` mapping each digits to a number. Digits 0 or 7 which has 2 syllables are mapped into `0.1` while others are mapped into an 1 digit number. * `RegExp.prototype.test` converts its parameter into `string`. The mapping result is an array. When try to convert array into a string, each elements are converted into string and connected by a comma (`,`). So, basically, each digits in the string is 1 syllable. And commas between theme mean you can break line here, while dots mean you cannot break line here. * Finally, `/^.{9},.{13},.{9}$/` test if the string has a 5-7-5 syllables pattern. [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` t=17 for d in input():t-=0<d%7or 2+t%7/6*t print t==0 ``` [Try it online!](https://tio.run/##hU3bCoMwDH33K4og7JKx2qlRWb9EfJodCqIiGdu@voudEx8GkvbAuSXDm@q@U/ZZN60RYW5e5ub7viUdonfvR1GJpuM3PGi3z@mk5bUKkHV1pADPyYG8YWw6EqS1tFOzQEBI5j9j6RUhXCB2PGWUoJhHjClkzv3y2OVZ48SiOX9jODPtydz2hPdE3FXsyKWNq7xc9@BP63edfYSNKT8 "Python 2 – Try It Online") Based on [Arnauld's solution](https://codegolf.stackexchange.com/a/213869/20260). I use `True/False` output here and in the answers below since I'm not sure what [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") output is allowed. **55 bytes** ``` t=4 for d in input():t-=1+~d%7/6+t%47/46*40 print-t==93 ``` [Try it online!](https://tio.run/##hU1LCoMwEN17iiAIbR0xakxUyEnEVbUoiIpMabvp1dMxteKiIJM8ePM@M72wHYfYPNqub1hUNM/m6rquQS2c2zizmnUDvemOp3OBgY78d@2pUProCRUKeRHcmeZuwAC1zhOzZEsFCuT6V6ycMoIEUsszQg4xcUGYQW7VL0@tn3bk2HZWPxjyLD25bZfUIygbk8K3tNr5@T4Hf1K/66QrOJjqAw "Python 2 – Try It Online") **58 bytes** ``` t=1 for d in input():t=t<<1+~d%7/6|1 print-3967&t>>5==4225 ``` [Try it online!](https://tio.run/##hU3bCoJAEH33K0QoiiZyV3dXxfVHxKc0XAgVmagg@nUbNxMfApndA2fOZbon1m3Dh3ttrpXLkupRnT3PG1Az59L2bumahl53w90@QY1pyg7vcqNO8sWcrjcNHoNYqi1mmdA65FwMYzxXoEBOf8LCyRkEICyPCH3gxEPCCGKrfrmwftqRY95ZfWXIM/bEtl1ST0hZToo/p9XC7y9z8Cf1u066gpUpPg "Python 2 – Try It Online") **58 bytes** ``` s=t=0 for d in input():s+=1+~d%7/6;t+=s%7==5 print s*t==34 ``` [Try it online!](https://tio.run/##hU1LCoMwEN17iiAIbR1ojJ@oZU4irqpFQVRMSttNr56OqRUXBZnkwZv3mfGlm6EX5tG0Xc2CvH7WV9d1jUKN3LkNE6tY29Mb7/pwzJWPgf@uPHlOLtpH5UnE2BmnttdMnTRiGJk5XkiQkCx/wdIpAgghtjwl5CCIR4QpZFb98tj6aUeOdWf1nSHP3JPZ9oR6IsoKUvialhs/3@bgT@p3nXQJO1N@AA "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~72~~ ~~66~~ ~~65~~ 63 bytes *Edit: -6 bytes thanks to Robin Ryder, and -2 bytes thanks to Giuseppe* ``` max(s<-cumsum(1+!utf8ToInt(scan(,''))%%7-6))==17&5%in%s&12%in%s ``` [Try it online!](https://tio.run/##jc9dS8MwFAbg@/yK40bXBC30Y81JxXopeL9LQULsXFibQpOg/752Bd1WNHgSSCAP5z0ZxrGTn9Q@JMp31nc0u73xbi92/bNx1Cpp6F0cMxZFmHDG6jrDTRlpE9lNls/niMinddqErOFj0K4BaWHvjXK6N@B6cI11INsWlLSNvSdv@l2714PUR19/O2oYCYxiAiMQoqSj8YuJ2WVrujqPtmKwhuQRdoNvrk1WlMgFpnmxzUUVcBMoOYoqnW8BuKy/6U/ck2zt8k0gL7dFnqUBNHXHOSO9DPod/lNW5@DTRwMSl3VtyfgF "R – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~96~~ \$\cdots\$ ~~92~~ 91 bytes Added 14 bytes to fix a bug kindly pointed out by [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino). Saved 2 bytes thanks to [rtpax](https://codegolf.stackexchange.com/users/85545/rtpax)!!! Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` p;h;s;c;f(long n){for(h=5,p=s=c=0;n;c=c/h?p|=c!=h,h^=2,!++s:c,n/=10)c+=n%10%7?1:2;h=p|s<3;} ``` [Try it online!](https://tio.run/##XVBtb4IwEP7urzhJSEBqLCAUrN0@LPsV0y2mFCFxlQAfyJTfzkrt2Mb1Lrk@99wrX585H4aKFrShnObO5SrPIN1bfq2dgkWoYg3jDFNJOeOb4rm6M75kBSreWYCWntfsOJIb5mOXe0zaPrbJs78LaMGqe7MPaT@UsoXPUykdd3FbgBLdohVN@yHfjsDgRkis3qgI/DAicUJwEG6DJFV/5UQxSVKsPQXMBYGipQmJo20Y@FgziI5gE/4NjjUQkLmMkE@0@QbqqZ51HF50leCtyB7DqoKT4pmaJF6c6hXUD7516F6DQ5e@KIssBH//oWUyxmuPrUqZiU5lYWrcPTTll7jmzs8Q7sYAqwmh4Hma7cLjwNORpSplDq0JRzrFx26tCueOdP@jQqHTyvO0qlaU3LHsSwbrJ7AzsJuDVGtJBC1SOy8FY@3RlOwX/fAN "C (gcc) – Try It Online") Returns \$0\$ if the input integer is a digit haiku or \$1\$ otherwise. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` ≔⭆S∨﹪Iι⁷χθ›⁼¹⁷Lθ№﹪⌕Aθ0⁷¦⁵ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0TDOb8UyPLNTynNyddwy8xLcczJ0QguAcqn@yYWaHjmFZSWQLgamjoK/kUwpc6JxSUamUAhcyA2NNAEkkoGSlC@qaampvX//5aWFuZmpibGRoYGhkbGJv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` for haiku, nothing if not. Works like my Retina answer, except it replaces `0` and `7` with `10` and checks that neither the 6th nor the 13th syllable is `0`. Explanation: ``` ≔⭆S∨﹪Iι⁷χθ ``` Reduce all of the digits modulo 7, then change all `0`s to `10`, so that `0` represents a second syllable. ``` ›⁼¹⁷Lθ ``` Check that there are 17 syllables, but not that... ``` №﹪⌕Aθ0⁷¦⁵ ``` any second syllables are at position equivalent to 5 (modulo 7). [Answer] # [Perl 5](https://www.perl.org/) (`-p`), ~~38~~, 34 bytes ``` s/0|7/ /g;$_=/^.{5}\V.{5}\H.{5}$/ ``` [Try it online!](https://tio.run/##K0gtyjH9X6yvoGunp6Wvbw1kGtSY6ytw66dbq8Tb6sfpVZvWxoSBSQ8QqaL//7@5uRkQghBQm0JIUWkql6GxqbmZhbmBkbGJkYUlQhjINzUzt7A0ALMQ4ugALgPW65aYUwxkWpibmZoYGxkaIMSASs3BGgxguqBqEYpBNiEkzNEBXOpffkFJZn5e8X/dnAIA "Perl 5 – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 60 bytes ``` 5-in($l=$args|%{($s+=1+($_-in48,55))})-and12-in$l-and$s-eq17 ``` *-42 bytes thanks to mazzy* [Try it online!](https://tio.run/##bZDLCoMwEEX3@YpBxqKoYNSYuBD8E5HWtkLQ1hS6UL89jY8@kE6yuPfmzBDm1j3rXl1rKYNj19caz5DDoFnQtA7KHKv@okZ7cFB5OfUcLM1DInzGXHdyg6o90cgkKGeJKqjvlOuJkMIBi8aMp4KHUZxEIrOID2Bxnpoz39X/Y6gxLOUiCxe1hfta460lEzxlSRzR8EPzhQp/0C80z33/Z1cWcWEEGwYCgOrRN@3FLARLYw9mN8UWAZm0fgE "PowerShell Core – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~[62](https://codegolf.stackexchange.com/revisions/214094/1)~~ ~~[58](https://codegolf.stackexchange.com/revisions/214094/2)~~ 56 bytes *Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) for helping me reduce this* ``` g q|r<-do x<-q;1:[0|7*x==x*x]=length r==17&&r!!5*r!!12>0 ``` [Try it online!](https://tio.run/##DcdLCoAgFADAqxhEC3mB9tM@r4tEi6CwyKyshYvubm4GZp2efdHae0Xuz3bpfBLXpXfLm4F9gjpER92IejHqXYlF5CJJbBSVNMCznvlj2gxedjNvrAYOOZQgoAIZZJCFF0EJ9eh/ "Haskell – Try It Online") The first thing we do is convert the input to a sort of syllable map. That is a list of integers, one for each syllables with the following meaning: 0. Second syllable of a word 1. First syllable of a word So with this we check that the length of is 17, that is there are 17 syllables all in all. Then we index the syllable codes at the beginning of the second and third lines. We multiply these together. If either of them is the second syllable of a word this product is zero because zero times any number is zero. And if both of them are 1 then it is not zero. So we check that this is not zero. That is to say that no line starts with the second syllable of a word. And that's it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 7Ö>.œO575S.å ``` Input as a list of digits. [Try it online](https://tio.run/##yy9OTMpM/f/f/PA0O72jk/1NzU2D9Q4v/f8/2lDHWMdUx1zHTMcCSBroGAH5JkDSQscyFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXwf/PD0@z0jk72NzU3DdY7vPS/zv9oc3MzIAQhHUNjU3MzC3MDI2MTIwtLHUMgbWpmbmFpAGbpGKIDHUsdSwtzM1MTYyNDA5C0OVjYACKHkAJp1zFHB7EA). **Explanation:** ``` 7Ö # Check for each digit of the (implicit) input-list whether it's divisible # by 7 > # Increase these checks by 1 (2 for 0 and 7; 1 otherwise) .œ # Check all partitions of this list O # Sum each inner-most list 575S # Push [5,7,5] .å # Check that this list is in the list of lists # (after which the result is output implicitly) ``` [Answer] # JavaScript, 53 bytes `BigInt` input. ``` n=>!(f=s=>n?f(s-=n%10n%7n?1:s%7-6?2:18,n/=10n):s)(17) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` §&o=17→§&€5€12∫mȯ→¬%7d ``` [Try it online!](https://tio.run/##yygtzv7//9BytXxbQ/NHbZOArEdNa0yB2NDoUcfq3BPrQYJrVM1T/v//b2hsam5mYW5gZGxiZGEJAA "Husk – Try It Online") Port of [my R answer](https://codegolf.stackexchange.com/a/213885/95126) so probably not the golfiest approach in [Husk](https://github.com/barbuz/Husk)... ``` §&o=17→§&€5€12∫mȯ→¬%7d §& # fork &: are both of the following true? o=17→ # last element equals 17? §& # fork &: are both of the following true? €5 # contains 5? €12 # contains 12? # ...when applied to: ∫ # cumulative sum of m d # this function applied to digits of input: ȯ # combine 3 functions: %7 # MOD 7 ¬ # NOT → # +1 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~70~~ 67 bytes Thanks to ceilingcat for the -3. Returns `0` if a valid haiku and non-zero if not. As the syllable count can only increase by either 1 or 2, I check for 5, 12 and greater than 16 and increase the state when I see those values (this also accounts for strings that would be valid except for continuing past 17.) If the state ends at 3 by the end of the input, then it's correct. ``` c,d;f(char*s){for(c=d=0;*s;d+=c==5|c==12|c>16)c-=~!(~*s++%7);d-=3;} ``` [Try it online!](https://tio.run/##bVDbboMwDH3nKzwmpFxg4lIIKAtfUO1tT@seqmSskTaYSLaXlv46C2yDqppjRT7H9rFlGb1KOY4yVLxB8rDvicHHpuuRFErEnBiuqJBC5Cf3JelJ1kmBZSTON@hMDKUBw1xFIuPDeKtb@fapXuDeWKW7u0Ptebq18L7XLfrqtMJw9ACmIUDM07OYIYDPWOHe5H74wyRZzoqSxWm2SctqYR3MC1ZW8Rwt9LX9JVbdhVq0qpIV@SZLk/hChs3t8aVG8j9drf3TLuvEK/tNPDxuty4YQiDECsM9B6YjcyCWY/jo3Z0a5AcGRA2B2rW@q7SUhtAgYjHm3jB@Aw "C (gcc) – Try It Online") [Answer] # [K (ngn/k)](https://git.sr.ht/%7Engn/k), ~~31~~ 30 bytes ``` {(17=*|o)>/^(o:+\1+~7!x)?5 12} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxdjEsKAjEQRPc5RQtCEgOazq+SiHoREbKZ7WwFP2d3ko2Q6l5UdT16qS/FuBzeq76eHmqt5s7mi91T3yKx+wjR6rFKuVdA2qYvsY9IGdb54HLZMB9iQi52OOJZVKhkpBi8Y9trjLMdHU+5/NH+jjBLC6MW2c5N/wAyUCeA) A straightforward translation of @jonah's `J` answer. * `(o:+\1+~7!x)` convert input to number of syllables in each digit, storing in `o` (literally, `sums 1 + not 7 mod x`) * `^(...)?5 12` check whether 5 and 12 are in that list * `(17=*|o)` check whether or not the list ends up with syllable 17 * `(...)>/...` use greater-than-fold, seeded with `(17=*|o)` ]
[Question] [ Write a program or function that takes an array of non-negative integers as input and outputs a set of vectors/arrays with the elements of the input array in order, split so that each vector sums up to 15. If the sum of the first N elements doesn't "hit 15", then the number that made it pass 15 must be cut off, and the remainder will be the first element of the next vector. This goes on until you reach the end of the input array. If the sum of the final vector is less than 15, then a number must be added at the end to make the sum go up. I think the rules are more easily understood by looking at the examples: ``` Input: 3 7 5 10 Output: 3 7 5 <- Sum is 15 10 5 <- 5 is added to make the sum 15 Input: 2 4 5 9 2 3 5 0 2 4 5 0 3 Output: 2 4 5 4 <- Sum 15. 9 is split in two. 5 2 3 5 <- The first 5 is the remainder of 9 0 2 4 5 0 3 1 <- The last number is added to make the sum 15 Input: 1 1 1 Output: 1 1 1 12 <- The number 12 is added to make the sum 15 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Output: 1 2 3 4 5 6 7 2 <- 2 is the first part of 8 6 9 <- 6 is the remainder of 8 10 5 <- 5 is first part of 11 6 9 <- 6 is remainder of 11. 9 is first part of 12 3 12 <- 3 is remainder of 12. 12 is first part of 13 1 14 <- 1 is remainder of 13. 14 is 14 15 15 <- 15 is first part of 16 1 14 <- 1 is remainder of 16. 14 is first part of 17 3 12 <- 3 is remainder of 17. 12 is added to make the sum 15 Input: 20 20 Output: 15 5 10 <- 5 is remainder from the first 20 10 5 <- 10 is remainder from second 20. 5 is added to make the sum = 15. Input: 100 Output 15 15 15 15 15 15 10 5 ``` Both the input and the output format is optional. Whatever is best in your language. **The shortest code 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=65577,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] ## Java - 229 200 192 181 172 170 168 bytes Had already begun, not for the win but for the fun :) Any suggestion is welcome. **Saved 8 bytes thanks to @ThomasKwa** **Saved 20 bytes thanks to @corsiKa** **Saved 2 bytes thanks to @Ypnypn** **Saved 2 bytes thanks to @user902383** ``` String p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j-->0;)if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+" ";}return s+(15-c);} ``` **170 bytes** ``` String p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j-->0;){if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}return s+(15-c);} ``` **172 bytes** ``` String p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j>0;){j--;if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}return s+(15-c);} ``` **181 bytes** ``` void p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j>0;){j--;if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}System.out.print(s+(15-c));} ``` **192 bytes** ``` void p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j>0;){j--;c++;if(c==15){s+=(i-j)+"\n";c=0;if(j>=15)continue;if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+" ";}System.out.print(s+(15-c));} ``` **200 bytes** ``` void p(int[]a){int c=0,j;String s="";f:for(int i:a){j=i;while(j>0){j--;c++;if(c==15){s+=(i-j)+"\n";c=0;if(j>=15)continue;else{if(j!=0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}System.out.print(s+(15-c));} ``` **229 bytes** ``` void p(int[]a){int c=0,j;f:for(int i:a){j=i;while(j>0){j--;c++;if(c==15){System.out.print(i-j+"\n");c=0;if(j>=15){continue;}else{if(j!=0)System.out.print(j+" ");c+=j;continue f;}}}System.out.print(i+" ");}System.out.print(15-c);} ``` --- ``` String p(int[] a) { int c = 0, j; String s = ""; f: for (int i: a) { for (j = i; j-- > 0;) if (++c > 14) { s += (i - j) + "\n"; c = 0; if (j < 15) { if (j > 0) s += j + " "; c += j; continue f; } } s += i + " "; } return s + (15 - c); } ``` [Answer] ## Pyth, 37 bytes ``` K15VQ=+ZNIgZK=-ZK-NZbIZZ)).?N;I>KZ-KZ ``` ## Explained This is an implementation of Noah's equation in Pyth ``` K15 Store 15 in K (the max) (K is Autoinitializing, no = needed here) VQ For N in the evaluated input =+ZN Set Z(Which in pyth defaults to 0) to Z+N IgZK If Z(row total) is greater than or equal to K (row max) =-ZK Set Z to Z-K (How much the max was exceeded) -NZ Implicitly print N-Z b Implicitly print b (in pyth defaults to a newline) IZ If Z > 0 (There was excess to carry to the next row) Z Implicitly print Z (the excess) .?N Else(the current row count is < the max(15)) output the current number ; Use infinite )'s in place of )) (to save 1 character) I>KZ If K > Z (The max is greater than the current row count) -KZ Implicitly print K-Z (The amount needed for the row to equal 15) ``` This was my first pyth, so feel free to suggest improvements. ## Example: Input ``` [1, 3, 4, 5, 9, 8] ``` Output ``` 1 3 4 5 2 7 8 ``` **Note:** Much thanks to Isaacg for several bytes of size reduction advice and creating pyth in the first place! Please upvote his comments below :) [Answer] ## Python 3 - 1̶7̶7̶ 1̶3̶8̶ 1̶6̶6̶ 1̶3̶3̶ 113 ``` s=0 i=15 p=print for e in eval(input()): if s>=i:p() s=s%i+e if s>i:s-=i;p(e-s);p();e=s p(e) if s!=i:p(i-s%i) ``` **Edit 5** Truly golfed thanks to @poke \*removed line breaks etc **Edit 4** Aliased print, and replaced a = with a -= to save a byte. Thanks to @poke and @elzell. Also moved input eval into for loop to save 2 bytes from assignment **Edit 3** Found savings in different OO inside second if **Edit 2** Fixed bug **Edit 1** Changed the input to be in the form '[1,2,3,4,5...]', and implemented first two comments, big thanks to @Morgan Thrapp First time poster here. Input is command line with entries separated by spaces, output is entry per line, with a newline between groupings. [Answer] ## Haskell, ~~126~~ ~~107~~ ~~102~~ 100 bytes ``` []#c=[] (h:t)#c|s<0=t#u|s<1=u:t#[]|1<2=(c++[h-s]):(s:t)#[]where s=sum c+h-15;u=c++[h] (#[]).(++[14]) ``` Usage example: `(#[]).(++[14]) $ [1..17]` -> `[[1,2,3,4,5],[6,7,2],[6,9],[10,5],[6,9],[3,12],[1,14],[15],[15],[1,14],[3,12]]` Edit: @Stewie Griffin helped me saving 19 bytes. Thanks! [Answer] ## CJam, 39 bytes ``` q~0af*Sf*N*30/{S-N/:,F1$:+-+0+e`W<e~p}/ ``` [Test it here.](http://cjam.aditsu.net/#code=q~0af*Sf*N*30%2F%7BS-N%2F%3A%2CF1%24%3A%2B-%2B0%2Be%60W%3Ce~p%7D%2F&input=%5B1%202%203%204%205%206%207%208%209%2010%2011%2012%2013%2014%2015%2016%2017%5D) This feels very suboptimal, but so far all my attempts at a shorter solution have been foiled by the presence of zeros in the input. [Answer] # Python2*powered by RegEx*: ~~158~~ *155* bytes Made in python with love and almost no math. Or Regex Math if you will, unary math. 'Real' math used only to 'fix' the last requirement: > > If the sum of the final vector is less than 15, then a number must be added at the end to make the sum go up. > > > ### Codegolfed: ``` import re def f(i):o=[map(len,p.split())for p in re.findall('((?:x *){15}|.+)',' '.join(['x'*c for c in i]))];l=sum(o[-1]);o[-1]+=([],[15-l])[l<15];print o ``` The way this works is by converting each number N into a string of length N (**x** chosen as the char to fill up the string) and joining them all into a space separated `string`. Resulting string is split via ***RegEx BLACK MAGIC*** into something like: ``` ['x xx xxx xxxx xxxxx ', 'xxxxxx xxxxxxx xx', 'xxxxxx xxxxxxxxx', 'x'] ``` for an input like: `f([1, 2, 3, 4, 5, 6, 7, 8, 10])` That's then split again, and the length of consecutive `x`es is used to create the numbers again, everything packed nicely in a list comprehension. ### Ungolfed: ``` import re o = [map(len, p.split()) for p in re.findall('((?:x *){15}|.+)', ' '.join(['x'*c for c in i]))] l = sum(o[-1]) o[-1] += ([], [15-l])[l<15] print o ``` Output: ``` >>> f([30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16]) [[15], [15], [1, 2, 3, 4, 5], [6, 7, 2], [6, 9], [15], [1, 14]] ``` *Note: there wasn't enough magic for the 0s so this entry disqualifies* > > zeros must be included. See the second example > > > [Answer] ## Seriously, 88 bytes ``` ,`'!*'0`M' j0╗`;;;'|ε35*('!=╜+;╗%(' =|('0=|I)`Mεj'|@s`ôl`╝`ö'0@s╛M`Md;Σ35*-;`X``@q`Iƒ@q. ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c6027212a2730604d27206a30bb603b3b3b277cee33352a2827213dbd2b3bbb252827203d7c2827303d7c4929604dee6a277c407360936c60bc609427304073be4d604d643be433352a2d3b60586060407160499f40712e&input=[2,4,5,9,2,3,5,0,2,4,5,0,3]) It's my first Seriously answer! Now I'm intimately familiar with all the language's shortcomings! Hex Dump: ``` 2c6027212a2730604d27206a30bb603b3b3b277cee33352a2827213dbd2b3bbb252827203d7c2827303d7c49 29604dee6a277c407360936c60bc609427304073be4d604d643be433352a2d3b60586060407160499f40712e ``` Explanation: ``` ,`'!*'0`M' j Replace all the numbers by "0"+"!"*n, separated by " " 0╗ Initialize an accumulator in register 0 ` ... `M Map the string with the following function: ;;;'|ε Put three extra copies of the character, a pipe, an empty string 35* and a 15 on the stack. ('!= Move one copy of the character to the top and push 1 if it's a ! ╜+ Load the accumulator, add the 1 or 0 from the preceding test ;╗ Make a copy, and save it back to register 0 % Modulo the sum by 15 (' =| Or the result with whether the dug-up character is " " ('0=| Or the result with whether the dug-up character is "0" I If we're at " " or "0" or the current sum is not divisible by 15, push empty string, else push "|" ) Bury the new character under the original character. εj Join the list that resulted from the map into a single string. '|@s Resplit the string on occurrences of "|" (after every 15 "!"s) `ôl`╝ Store a function in register 1 which trims whitespace and returns the length of the remaining string ` ... `M Map the list with the following function: ö Trim leading spaces. '0@s Split the string on occurrence of "0" ╛M Map the resulting list with the function stored in register 1 d; Push the last sublist from the resulting list and make a copy. Σ Find the sum of the list. 35*- Subtract it from 15 ;`X``@q`Iƒ Duplicate it, drop it if it's zero, put it in the list otherwise. @q. Put the list back in the big list and print it. ``` [Answer] # Javascript, ~~138~~ 128 bytes ``` i=>eval("for(o=z=n='',m=15,t=q=0;q<i.length;q++)(t+=c=+i[q])>=m?(t-=m,z+=c-t,o+=z+`\n`,z=t>0?t+' ':n):z+=c+' ';t<m?o+z+(m-t):o") ``` With whitespace: ``` i => eval(" for(o=z=n='', m=15, t=q=0; q < i.length; q++) (t+=c=+i[q])>=m ?( t-=m, z+=c-t, o+=z+`\n`, z=t>0?t+' ':n) : z+=c+' ' ; t<m ? o+z+(m-t) : o ") ``` ### Example: Assign the function to a variable ``` sumFifteen=i=>eval("for(o=z=n='',m=15,t=q=0;q<i.length;q++)(t+=c=+i[q])>=m?(t-=m,z+=c-t,o+=z+`\n`,z=t>0?t+' ':n):z+=c+' ';t<m?o+z+(m-t):o") ``` Then evaluate like so: ``` console.log(sumFifteen([1,4,11,4,5])) 1 4 10 1 4 5 5 ``` **Revision history:** 12/3/2015 00:02 - Thanks to user81655(+1 him in the comments) for 10 byte improvement 12/2/2015 21:44 - Switched to use functional style in-order to reduce size. [Answer] ### Python 3: 139 bytes Slightly different approach than the other answer. Produces the actual output from the question because I initially assumed that was a requirement. ``` def f(l): m=15;r,s=sum(l)%m,0 if r:l+=[m-r] while l: x=l.pop(0) if s+x>m:y=m-s;l[0:0]=[x-y];x=y s+=x;print(x,end=' \n'[s==m]);s%=m ``` Example usage: ``` >>> f([2, 4, 5, 9, 2, 3, 5, 0, 2, 4, 5, 0, 3]) 2 4 5 4 5 2 3 5 0 2 4 5 0 3 1 ``` [Answer] # Perl, 86 bytes ``` #!perl -p s|\d+( ?)|($i+=$&)<15?$&:($a=$&-($i%=15)).$/.($&>$a&&$&-$a.$1)|ge;$\=$".(15-$i)if$i ``` Counting the shebang as three, input is taken from stdin, space separated. --- **Sample Usage** ``` $ echo -n 2 4 5 9 2 3 5 0 2 4 5 0 3 | perl sum15.pl 2 4 5 4 5 2 3 5 0 2 4 5 0 3 1 ``` [Answer] # R, 155 bytes ``` n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}} ``` With indents and linebreaks: ``` n=scan() while(S<-sum(n)){ C=cumsum(n) if(S>14){ w=which(C>14)[1] N=n[1:w] n=n[-(1:w)] r=C[w]-15 N[w]=N[w]-r if(r) n=c(r,n) cat(N,"\n") }else{ cat(n,15-S) n=0 } } ``` Usage: ``` > n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}} 1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18: Read 17 items 1 2 3 4 5 6 7 2 6 9 10 5 6 9 3 12 1 14 15 15 1 14 3 12 > n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}} 1: 20 20 3: Read 2 items 15 5 10 10 5 > n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}} 1: 10 5 3: Read 2 items 10 5 > n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}} 1: 2 4 5 9 2 3 5 0 2 4 5 0 3 14: Read 13 items 2 4 5 4 5 2 3 5 0 2 4 5 0 3 1 ``` [Answer] # Python 2, 117 bytes ``` i=input() while i: s=15;r=[] while s>0:n=i.pop(0)if i else s;s-=n;r+=[n]if s>=0 else[n+s] if s<0:i=[-s]+i print r ``` Takes input as list: ``` >>[2,4,5,9,2,3,5,0,2,4,5,0,3] [2, 4, 5, 4] [5, 2, 3, 5] [0, 2, 4, 5, 0, 3, 1] ``` [Answer] ## Perl, 76 bytes Includes +3 for `-p` (normally +1, but +3 to play fair with the other perl solution) Run with the input on STDIN (final newline on input is optional, but ***MUST*** be absent for the empty input) ``` sum15.pl <<< "1 2 3" ``` `sum15.pl`: ``` #!/usr/bin/perl -p s/$/ 15/;s/\d+/1x$&/eg;s/( *1){15}\K ?/ /g;s/ 1* *$//;s/1+|\B/length$&/eg ``` Look ma, no calculations whatsoever... [Answer] # Java - 158 155 bytes Lambda version of <https://codegolf.stackexchange.com/a/65590/46866> by [yassin-hajaj](https://codegolf.stackexchange.com/users/46087/yassin-hajaj), Not sure if a valid submission, but dont have enough rep to add a comment on the linked answer. Counted using <http://meta.codegolf.stackexchange.com/questions/4944/byte-counter-snippet> ``` a->{int c=0,j;String s="";f:for(int i:a){for(j=i;j-->0;)if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+" ";}return s+(15-c);} ``` 158 Bytes ``` a->{int c=0,j;String s="";f:for(int i:a){for (j=i;j-->0;)if(++c>14){s+=(i-j)+ "\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+ " ";}return s+(15-c);} ``` Ungolfed ``` a -> { int c=0, j; String s = ""; f: for (int i : a) { for (j = i; j-- > 0; ) if (++c > 14) { s += (i - j) + "\n"; c = 0; if (j < 15) { if (j > 0) s += j + " "; c += j; continue f; } } s += i + " "; } return s + (15 - c); } ``` can be used like ``` Function<int[], String> func =a->{int c=0,j;String s="";f:for(int i:a){for (j=i;j-->0;)if(++c>14){s+=(i-j)+ "\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+ " ";}return s+(15-c);}; System.out.println(func.apply(new int[]{2, 4, 5, 9, 2, 3, 5, 0, 2, 4, 5 ,0 ,3})); ``` ]
[Question] [ This is a challenge in which two people, 1 and 2, are running for office. People deterministically vote in certain ways in the world of 1 and 2, which can allow for the candidates to figure out the results before the election. NOTE: this is not meant to refer to any outside elections or other political events. Two people are running for office. We'll call these people 1 and 2. Because they both want to know if they will win the election, they decide to use their knowledge of people and some code to figure out what the result will be. Due to the want to minimize government spending, the code needs to be a short as possible. **Your task:** Given a string of people based on how they are voting, output who wins the election. There are five kinds of people in the fun and exciting world of 1 and 2: * `A`: people who will definitely vote for 1. * `B`: people who will definitely vote for 2. * `X`: people who will vote for whoever the person to their left will vote for. If there is no person to their left, then they vote for whoever the person at their right will vote for. If it is not clear who the person to their right is voting for, then they do not vote. * `Y`: people will vote the opposite of the person to their left. If there is no person to their left, then they vote opposite of whoever is at their right. If it is not clear who the person to their right is voting for, then they do not vote. * `N`: people who do not vote. This is evaluated from left to right. **Example:** Whoever is being "evaluated" is in lowercase, for clarity. ``` Input: `XXAYAN` xX Votes for whoever their friend is voting for. Their friend has not decided yet, so it is unclear, so they do not vote. Xx Person to left is voting "none" so votes "none." a Votes for 1 Ay Since person on left is voting for 1, votes for 2. a Votes for 1 n Does not vote ``` Final poll: * 2 people voted for 1 * 1 people voted for 2 * 3 people did not vote 1 has the most votes, so 1 wins! **Test cases:** You may use other characters or values as input and output, as long as they are distinct. (For example: numbers instead of letters, different letters, lowercase letters, truthy/falsy or positive/negative (for output), etc.) ``` Input -> Output "AAAA" -> 1 "BBBB" -> 2 "BBAXY" -> 2 "BAXYBNXBAYXBN" -> 2 "XXAYAN" -> 1 "AAAABXXXX" -> 2 "AXNXXXXAYB" -> 1 "NANNY" -> 1 "XA" -> 1 "YAB" -> 2 "XY" -> anything (do not need to handle test cases with no victor) "AB" -> anything (do not need to handle test cases with no victor) ``` [Answer] # Java 8, ~~153~~ ~~141~~ ~~135~~ ~~131~~ 129 bytes ``` a->{int l=a.length,t,r=0,i=-1;for(;++i<l;r+=(t=a[i]=a[i]>4?t<3?t^3:3:a[i]>3?t:a[i])>2?0:3-t*2)t=a[i>0?i-1:i<l-1?i+1:i];return r;} ``` Uses an integer array as input with `A=1, B=2, N=3, X=4, Y=5` and outputs a positive integer (`>= 1`) if A wins, a negative integer (`<= -1`) if B wins, or `0` if it's a draw. -18 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##nVbLbptAFN37K668wjF@AEatTLA1s@ui00rZgNJUmhiSTErAgiFWFHnbD@gn9kfcy/CInRiTdEaCGbDP4Z5z79Xc80c@ug9@7VYRzzL4ykX83AMQsQzTG74KgRVb9QBWGl4vr4APHHy27eElk1yKFTCIwYUdHy2eix9GLh9HYXwr73Spp@5UF@7IcG6SVHOGQ3EeOenQ1aTLL8WVuixmS3luLeVPa27N1QPcqMVgYS6nc2skz8yB@sNiuhQjY44gI2Mphri6ctJQ5mkMqbPdOb3JWe9LvM7lHIhr6EBdUwfmWjp47kwH37V733JZvZdpHhY/ueFRFvbOJhjQOr@OMKAqrsdEBPCAmmgXMhXxrQq@FOTiKZPhwzjJ5XiNr2QUa/3vafIogjAAGWYoF8/CbN5XYoF6pMXhBpSGz4au5nbgwJExmUCf4OjDaFGvNIIBUBQTsgQIbEScDY4hm7qaJ5ApjhK5XCHyFJFnCpmeRjb0mW4fxS6RiefX0ISU2CZiW93YChkZLLwXO1vdLcWlsBGaMo8S36Os4kAKypAJw2CKy0Kuz11cM0Qu8I0K/W0cnkd8UpEwRihhTSRGl/6Vs/jts3IecNTOUg/Hi720caLw2O6KoNDKqvFVLPt@Kw6PFQzEpzUJKwapWAqdzK5IrEIhnO1@M0St/C6WpUrG0Sw9Vi8/4ovkIQQeBEKKJObRuwrHVIliKAGKna3uL4mC2qJ5HqG@V3tIimxURpLKyk9NUpJTiWLr7cmiEsU/TJWPJoutjKzTXa1eGel7rEh5vDQcVGU9aVi6C7elGewVblVQTTMw3mCeMPA6ifNszzvY3InVHYRxAPkavwE4BCnftFla9ZWTHYt4L22lCbzM4BK8zcAToZcG1rI2oU@7UA3d7EAlddXRpiKMLlSrVYGm2ryPf6vVqQD7PwX0sjhs1SEOda6L0PMZq/VVFUhZ3SOspvxOsrT3uIrlVZM76HHvyhCrszTq2m5VZ/8gpA4MiqI@KrWeFu7x5DXOpYjGJE35UzaWSXnI0Phg2Ie/v/9AfxiPV7itzlvb3T8) **Explanation:** ``` a->{ // Method with int-array parameter and boolean return-type int l=a.length, // Length of the input-array t, // Temp integer, uninitialized r=0, // Result-integer, starting at 0 i=-1;for(;++i<l // Loop `i` in the range [0, l): ; // After every iteration: r+= // Increase the result by: (t=a[i]= // Change `i`'th item in the array to: a[i]>4? // If the `i`'th item is a 5: t<3? // If `t` is 1 or 2: t^3 // Use `t` Bitwise-XOR 3 to invert it // (1 becomes 2; 2 becomes 1) : // Else (`t` is 3, 4, or 5 instead): 3 // Set it to 3 :a[i]>3? // Else-if the `i`'th item is a 4: t // Set it to `t` : // Else (the `i`'th item is a 1, 2 or 3): a[i]) // Leave it unchanged )>2? // And if this new `i`'th value is 3, 4, or 5: 0 // Leave the result the same by increasing it with 0 : // Else (it's 1 or 2 instead): 3-t*2; // Increase it by 3 minus two times the `i`'th value // (which is 1 for 1; and -1 for 2) t= // Set `t` to: a[i>0? // If `i` is not the first item: i-1 // Set `t` to the previous (`i-1`'th) value :i<l-1? // Else-if `i` is not the last item: i+1 // Set `t` to the next (`i+1`'th) value : // Else (`i` is the first or last item): i]; // Set `t` to the current item itself return r;} // Return the result // (positive if A wins; negative if B wins; 0 if it's draw) ``` [Answer] ## Haskell, ~~60~~ ~~50~~ ~~48~~ 59 bytes ``` l#(v:o)|v<2=v+v#o|n<-(3-v)*l=n+n#o _#_=0 f x=rem(x!!1)2#x>0 ``` Uses `1` for `A`, `-1` for `B`, `0` for `N`, `2` for `X` and `4` for `Y`. Returns `True` if `A` wins, else `False`. [Try it online!](https://tio.run/##TY5BDoMgEEX3nmIaNlqhAeqqkd6gJzDGkKqpKaJRQ1x4d6ujts1n8d9n@MNL9@/CmHk2xHe3JphcLJULHWkmGzP/ylxwNsqGljReRjLFvRJG1RW1P55OIpBkvPO51pUFBbVuHxn4bVfZAS5QBpB4kAiKSunimaDH@WNBJY0ORlhTvhjkaDMcJ@QCa3Tw3r4OyE17LLFgk8BGvODry0W4jzHQeV4NVWO1gaHoB3jqvuhxz/eT0c@KNJ0/ "Haskell – Try It Online") On the recursive way down the input list we add `1` for every vote for `A`, `-1` for every vote for `B` and `0` for "no vote". `l` is the last vote, `v` the next. If `v=1`, `-1` or `0` (or `v<2`) we just add it to the sum. If `v` is "vote same" (`X` in the challenge, `2` for my solution) we keep and add `l` (`(3-2)*l` = `l`). If `v` is "vote opposite" (`Y` in the challenge, `4` for my solution) we first negate `l` (`(3-4)*l` = `-l`) and then add it. Base case is the empty list which starts the sum with `0`. Recursion is started with `l` set to `rem s 2` where `s` is the second element of the input list (`x!!1`). `rem s 2` maps `1` and `-1` to itself, all other values to `0`. Fix votes ignore `l` anyway [\*] and `X` or `Y` get the right neighbor if it's a fix vote. If the overall sum is positive, `A` wins. [\*] this makes singleton lists with fix votes like `[1]` work, because due to Haskell's laziness access to the second element is never evaluated. Inputs like `[2]` fail with error, but don't have to be considered. [Answer] # Perl 5, ~~56~~ ~~80~~ ~~72~~ ~~65~~ 53 bytes +26 bytes to handle the case X or Y in first position and A or B in second. output is `1` if 1 wins empty (false value in perl) otherwise. ``` s/^X(.)/$1$1/,s/A\KX|B\KY|^Y(?=B)/A/|s/B\KX|A\KY|^Y(?=A)/B/&&redo;$_=y/A//>y/B// ``` [TIO](https://tio.run/##PYsxC4NADIX3/A4RD9oGh07FlmQVMicgdqlDQXriuQj@9l5zSz/IC3y8t0zrfM054ajNJWDVVi2eEtLQ68FDb8dozaPjgIRHQi6a/poCMtb1Or3irXp2u5fwvrvDnMkBdjxIDUqwKJMpC6iSkUApsTpAKuWTMQiJGPiEGMzPN9@4bO/4Sfm8zD8) using `P` and `S` instead of `X` and `Y` allowing to use xor operation on characters, would save some more bytes ``` s/(?|^(P|S)(?=(A|B))|(A|B)\K(P|S))/P^$1^$2/e&&redo;$_=y/A//>y/B// ``` uses a branch reset group `(?|`..`|`..`)`, so that `$1` `$2` refering to corresponding group in branch. Using `\0` and `\3` instead of `X` and `Y` ``` $_=s/^\W(?=(\w))|(\w)\K\W/$1.$2^$&/e?redo:y/A//>y/B// ``` [72 bytes](https://tio.run/##NYvBCsJADETv@YqCS6mgBgueSoXkKiwLvSQg9eIehGJL66XQb3dNCz6YCWRmhjh2l7TLpA6Z1g3MKIqhwSpN2BZhafYFLbzH0Lpz68qTKzEeJtye99tW@GcY83yMz75yj3pGQrzOyIgpkQFsmJEorMZemFTYgwgpeVhLLAaQ@PWSMnjyXsEmxKAm23z74fPq31M6Dt0P) [65 bytes](https://tio.run/##HYuxCoNAEET7/QohIndFWBJIJRfZbQPHgc0uBNPEIiAqmka4b8/l9MHMwDAz98twS6dCXCjUtbChKIYW67SiaWJnQmytaZyhyNbGI56Po7UYuvLSlVfsq2rp31NdvtyGhHjfkBFTogxwJhuJwm7shUmFPYiQkod9xJIBEr8nKYMn7xXyhRg0K39@0/z9TOOazvPwBw) [53 bytes](https://tio.run/##FYtBC4JAEIXv8zuW0IONFl4Kk5lrNFdnYLFLHgJJ0SCEfnvb7gfve5f35mEZ67ChGvrSH/Ec3L1Zsfdd1jaZ/@T5N9lffYeu2rtD73Y4tMvwmE4bEuJlQ0YMgSLAkShSgyQWZTJlAVUyEkgj1giQSmoyBiERg3ghBk1hAottTL9pfj@n1xqKeQzFrd6X1R8) [Answer] # JavaScript (ES6), ~~78 75~~ 73 bytes Takes input as an array of integers with: \$0\$ = N, \$1\$ = A, \$2\$ = B, \$4\$ = Y, \$8\$ = X. Returns \$false\$ if the first candidate wins or \$true\$ if the 2nd candidate wins. ``` a=>a.reduce((v,x,i)=>v+~~[,1,-1][p=x?x&3||~-x%7^(p&3||a[i+1]&3):0],p=0)<0 ``` [Try it online!](https://tio.run/##dY7RSsMwGIXv9xQh4EhYmjXuQhBTSR4g3iaUWkKaSmW2ZamlF6OvXhtRLzb3Xf3wcc5/3u1ogzs1/ZC0XeWXmi@WZ5aefPXpPEIjmUiDeTbu5jknjCSsyHs@PU/bw/k8J9Pdwyvq423zZseK7QE/pgXpeYqf0mXwYQAcBMAz4Lo2dEdPj90bqlFOKQ0F/bA9ctFCJWRpyrLUkDZt5aeXGjm8stnEEgTFCgS/YLDfgyQD7MfKlWt7/2eFNvCmXaVUWgqjpYKXVmthhII3/sZVUq/A/5qFVtEJ873tMquEUter2PIF "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ ~~33~~ ~~32~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gFÐNè©[[email protected]](/cdn-cgi/l/email-protection)èDÄ2‹*D(‚®èNǝ]O ``` Uses an integer-array as input with `A=-1, B=1, N=0, X=2, Y=3` and outputs a negative integer (`<= -1`) if A wins, a positive integer (`>= 1`) if B wins, or `0` if it's a draw. [Try it online](https://tio.run/##yy9OTMpM/a/kmVdQWqJQlphTmlqsUFqcmmLFpeBoq2vIpeBkCyT8bA24FCJsjbgUIm2Nubj8S0uAyoFK/FLTE0syy1IVbBUcFcoz84q5FALyizOhQk5QIQMgO6UosVwp5n@62@EJfodXHFpp5JDpV2GoF6x7eIXL4RajRw07tVw0HjXMOrTu8Aq/43Nj/f//jzbSMdYxAkJdQyADSBjEAgA) or [verify all test cases](https://tio.run/##bU@/S8NAFN7vr3hkaStJSe6cxFATgqBDKri0xA6RhnIgrZim1SGQoThXR7GDW0tBcBInITf4f@QfiZe7i1SUdz@@99177/tuEoeXNCq1k/F1MoVZeJVEMSRxNDxA4NiGhcC1@eHbJoKejRH0bYJQN5nycl7iR6NwSmcR2ODAnI5jBGeTmCrKVZTJ8fAmnGsXCM3u2NLr7LPVoeb4bq@vFdnLqQZN9tmC4v4RtE45OmZLn63zDT6i/q3VPjfY2mMLXGQfe16zyJ7yV7b2v1Zp2i29jtfO3zzacNmWLWjDYdtGvmGLNC2y52pq/s4eWhzrZRAYll6vgQ6BpYuoIeexTmQmMSdNfouUCGBWz5hDwRiK2JmrV40i1AMWI2SIJqFnil4eRJVJPUMKipxIoBSJ/keViNk/5iQU9nd/pNqlaO1WecC/xKttCv3a1L/OB4Nv). **Explanation:** ``` g # Take the length of the (implicit) input-list # i.e. [3,1,3,3,2,0,1] → 7 F # Loop `N` in the range [0, length): Ð # Triplicate the list at the top of the stack # (which is the implicit input-list in the first iteration) Nè # Get the `N`'th item of the list # i.e. [3,1,3,3,2,0,1] and `N`=0 → 3 # i.e. [-1,1,-1,3,2,0,1] and `N`=3 → 3 © # Store it in the register (without popping) 2@i # If it's larger than or equal to 2 (so either 2 or 3): Nx # Push `N` and `N` doubled both to the stack # i.e. `N`=0 → 0 and 0 # i.e. `N`=3 → 3 and 6 1.S # Compare the double integer with 1 (-1 if N*2<1; 0 if N*2==1; 1 if N*2>1) # (So this will be -1 in the first iteration, otherwise it will be 1) # i.e. 0 → -1 # i.e. 6 → 1 -è # Subtract that from the index, and index it into the list # i.e. `N`=0 and -1 → 1 (first item, so get the next index) # → [3,1,3,3,2,0,1] and 1 → 1 # i.e. `N`=3 and 1 → 2 (fourth item, so get the previous index) # → [-1,1,-1,3,2,0,1] and 2 → -1 D # Duplicate that value Ä2‹ # Check if that value is -1, 0, or 1 (abs(i) < 2) (truthy=1; falsey=0) * # And multiply that with the value # (remains the same if truthy; or becomes 0 if falsey) D(‚ # Pair it with its negative (-1 becomes [-1,1]; 1 becomes [1,-1]) ®è # And index the `N`'th value (from the register) into it (with wraparound) # (if it was a 2, it uses the unchanged (first) value of the pair; # if it was a 3, it uses the negative (second) value of the pair) # i.e. [1,-1] and 3 → -1 # i.e. [-1,1] and 3 → 1 Nǝ # And replace the `N`'th value with this # i.e. [3,1,3,3,2,0,1], `N`=0 and -1 → [-1,1,3,3,2,0,1] # i.e. [-1,1,-1,3,2,0,1], `N`=3 and 1 → [-1,1,-1,1,2,0,1] ] # Close both the if-statement and loop O # Sum the modified list (which now only contains -1, 0, or 1) # i.e. [-1,1,-1,1,1,0,1] → 2 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` s=>s.map(c=>x+=l=c%2|l*c/2,l=s[x=1]%2)|x>1 ``` [Try it online!](https://tio.run/##dc/RasMgGAXg@zyFCAWzGTO9FH5BH8BrJeQiuHRsuKbUUALrnj013drBmp7bD89//OiOXQqH9/1Y7YbXft7CnEAl9tntSQA1PUOEsBGn@BRqQSOkZgLebkR5mhSfxz6NCFBCoFAYdmmIPYvDG9mShjGW2p@aRcmXlhWnRnJq5Qt1UlAvK/HdhLbMKYqlimCdg9E1JaprVCnEf9Xk3Ku4qXYeP9SMxjqjvTMW/1fntNcWP7i7rDIuB681a2cX0/6y7e7t3@C1H62qKOYz "JavaScript (Node.js) – Try It Online") Save 1 bytes, thanks to Shaggy. --- * Input as integer array where N = 0, A = -1, B = 1, X = 2, Y = -2; * Output 1 = Falsy, 2 = Truthy [Answer] # [Python 2](https://docs.python.org/2/), ~~95~~ 73 bytes ``` lambda(v):sum([l for l in[2*int(v[1]/2)]for i in v for l in[i*l**(i%2)]]) ``` [Try it online!](https://tio.run/##VVBNi8MgEL37K4bAEk2TLsmx0AU99OjZkM0h21h2IJqgtrS/PqvpfrAPZsSZN@85Lo/wOdtmPcER3tdpMB/jQG/s4K@GdhNcZgcToO2aAm2gt67uXxvWpzLGMtz@GFhMRUHxJbZ7to76AucG6XkeNTsQiAjahwl9iE5dzvMyb2PIGCqGyPuNlOSW2WPA2ZaAQZtko@3VaDcETX9EvjUT8PLkHY@Q3P4aCU6Hq7O/klBBs/X1HQNlhKBZZhfAPzzZNkGrk2G8730Y0e6dHsZU9fRpucxLWmDbjT3fe04TiRNHHC6UwbbL4tKX/WvsMqjeINtlddVkXb0zw50atPREoywra1ZWNesZWXkEERExcdWSlIRUgrdKSKIUb7kkiSRUBOFKppO3gkguZUsUJy0XJE5y8QU "Python 2 – Try It Online") --- * Input as integer array where N = 0, A = -2, B = 2, X = 1, Y = -1; * Output negative = A, 0 = draw, positive = B * If first input is X or Y, then 2\*int(v[1]/2) maps second to itself or 0 Bug fix was required that added extra bytes, but converting to lambda thanks to @Stephen reduced it back to 95 [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 70 bytes ``` AY AB BY BA }`(A|B)X $1$1 ^X(A|B)|^Y[AB] $1$1 +`N|X|Y|AB|BA .+|(?<=B) ``` [Try it online!](https://tio.run/##JY6xCgJBDET7@Y4T9jgQrldkprFLnSAea2FhYyGW8dvXXX1FwgyPkNf9/Xje2q6Uc20MUFBAxKcWpmbHtE4rNv@l3OJCXf/dUi09I6nsPvZLltPhqLk1dqBOH/RxzkPmYrgM7gwahiTvgG5jMwSjWcDHH18 "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for a tie. Explanation: ``` AY AB BY BA ``` Handle `Y` voters to the right of people with decided votes. ``` }`(A|B)X $1$1 ``` Handle `X` voters to the right of people with decided votes, and then loop back until all possible `Y` and `X` votes can be decided. ``` ^X(A|B)|^Y[AB] $1$1 ``` Handle an initial `X` voter next to a decided vote, and also an initial `Y` voter next to a decided vote. As this voter will vote opposite to the decided vote, we can just delete both votes in this case. ``` +`N|X|Y|AB|BA ``` Delete any remaining no vote or undecided votes, and cancel out all pairs of opposing decided votes. Repeat until all possible votes are cancelled. In the case of a tie, nothing will be left, otherwise the remaining votes will all be of the same type. ``` .+|(?<=B) ``` Output `1` if there are any votes, but `2` if they are `B` votes. [Answer] # [Python](https://www.python.org) 3.8+, 55 bytes ``` lambda v:[l:=v[1]&~1]and sum((l:=i*l**(i%2))for i in v) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDLasMwEKRXfcUSaC2ldsC-tARcKh1yKj7LpD64sUwXbNnYckgI6Y_0EijtP7VfU8lOHwO7Qrszs1q9frR789zo09sqfnwfTBncft5Uef1U5LBdrqtlvF2H2dVLmOW6gH6oKbU1nFfzOcXLiLGy6QABNWzZJP-6uC9UCZsI6aYpFFsSsDCqNxX2BmJYe9zzvdRGYkPaEF42kpxX2_RosNE-oFG1M1Z6qFWXG0V_TM6eDlhOvDgGN-2v4dApM3T61xICiMa-2qGhjBCs26Yz0O974kZXqJUbaO-L3hSoF53KC1ft6Xlk27Rug3E5Nr534xSOYyUdtpTBtEvboTa09A7_e0cI7uAwC4Notg6v63xHa9R0Ra0t80PmByHLjt75I0-fD9yCCAubuEyJSyKRgqdSJERKnvKEOJKQFoTLxJ08FSThSZISyUnKBbFKLibTbw) Port of [ABridgeTooFar's Python 2 solution](https://codegolf.stackexchange.com/a/179704/85334), since we took the time [in TNB](https://chat.stackexchange.com/transcript/message/60745317#60745317) to figure out why and how that list comprehension does anything at all. [Answer] ## Python ~~3~~ 2, ~~125~~ ~~121~~ 117 bytes (Thanks to Jonathan Frech) ``` def f(x): for i,v in enumerate(x):n=x[i-(i>0)];x[i]=(v>3)*n+abs(n-1)*(v<0)+x[i]*(0<v<4) print x.count(1)>x.count(0) ``` Using tab indentation Input: list of `int`s where 'A'=1, 'B'=0, 'X'=4, 'N'=3, 'Y'=-1, so "AAAA" is `[1, 1, 1, 1]` and "XXAYAN" is `[4, 4, 1, -1, 1, 3]`. `[{'A': 1, 'B': 0, 'X': 4, 'N': 3, 'Y': -1}[c] for c in s]` will convert the strings to the needed input format. You can [Try it online!](https://tio.run/##XY5Na4NAEEDP@iuGXNw1pmi0HxgV1oPHPfWwIh6sUSoka/ALS@lvtyNpTOxc3sLbYd7lq/us5X6ajkUJJRmpqypl3UBlDFBJKGR/LpqsK65Gkf6YVDtSBSZND/hMfTIENtXllsi6A0l1Mngm3c5KJ6Y3eA5VlUtTyQ7Gp7zuZUcsGtyeJp0i8OGUnT@OGbQuFiTfGtNcsAzQQqSJFEgHyZE2MkburJ8kT2FOzefQNqXq9Qxuvjd9YRwgIhuGs7mZvQFRdmr/VIizKPufYiJenLN2qEIuQhaLkC9/nh@PCsFidncvq/25KBQ4i39dBQs@Sxbf294ePWecY9r0Cw "Python 2 – Try It Online") (Thanks to Jonathan Frech for the suggestion) [Answer] # Python 3, ~~187~~ 156 bytes Really not that competitive with the other python answers on this, but I had some good ideas for using dicts to make an answer that actually takes string inputs, and it didn't turn out horribly long. ``` def E(s): r,g,*v=range(len(s)),lambda**d:d.get(s[i],0),*s for i in r:v[i]=g(A=1,B=-1) for i in r:v[i]=g(X=1,Y=-1)*v[(i-1,i+1)[i<1]]or v[i] return sum(v) ``` [Try it online!](https://tio.run/##bY4xa8MwEIV3/wqRSVLlEtGlmHo4QVbNJ4wHFyuOIJGN7Bjy651zhoJC3/h9d7w3PZbLGL@@p7RtvT@zE59FVbCkBiXXOnVx8PzqI1Ghrt3tt@@k7Kv@c/ALn5vQqqNQci7YeUwssBBZqlbC9cCh1srUpRb/SSTpdinXhodSq/ChRRN@dNvS7X5EG/xyT5HN9xtfxTalEBd@4gegHIQo/oChvAFAlxMCxqIBh8ZmBhEc5GgvMEjJKdqdgcu7LFibd2G@zkH@8LbsZbcn) Edit -21 bytes: Some beautifully horrific abuse of python by @Unrelated String Loops through the input twice to fill out an output list containing the vote of each person (`1` for `A`, `-1` for `B`, `0` for no vote), and filling out the `X`s and `Y`s on the second loop. I thought I could do it with one loop, but irritatingly that fails on an `X` or `Y` at the beginning of the string, as it hasn't processed the following vote yet. The return value is positive if candidate 1 wins, and negative if candidate 2 wins. (The absolute value of it also happens to be the margin of victory) [Answer] # Perl 5, 54 bytes ``` s/^\W(?=(\w))|(\w)\K\W/$1^$2^$&/e&&redo;$_=y/A//>y/B// ``` [Try it online!](https://tio.run/##FYs9C8MwDER3/Q4TkqGoH3QKaZHWgtZIYNKlGQqhNkmhGPrb69oP7t1yF@d1OeeEauj3/oR93nDyY3sdWv/pum@1v/kR3WFyx8k1ODfNOj9C7@5DQkK8JGTEnKkAXCgiNahiUSZTFlAlI4E6Yi0AqdQmYxASMSgXYtAaJrDSxvQL8f0Mry3v4vIH "Perl 5 – Try It Online") Uses `A` for `A`, `B` for `B`, `N` for `N`, `\0` for `X` and `\3` for Y (the last two being literal control chars). The trick is that `A` bitwise-xor `\3` equals `B`, and vice-versa. [Answer] # Javascript (ES6) - 133 bytes ``` a=>(i=($=_=>'AB'.search(_)+1)(a[1],o=0),[...a].map(v=>(r=['NAB','NBA']['XY'.search(x)],p=r?r[i]:v,i=$(p),o+='NA'.search(p))),o>0?1:2) ``` Takes in a string with the format given in the OP and returns *1* if candidate 1 won and *2* otherwise (I'll admit it, I'm even-biased). ]
[Question] [ Write a program or function that takes in a rectangular grid of text where every cell is either an `A` or a `B`. All the `A` cells will form a [simply-connected](https://en.wikipedia.org/wiki/Simply_connected_space) shape, i.e. they will all be orthogonally [connected](https://en.wikipedia.org/wiki/Connected_space) with no holes (diagonally neighboring letters do not count as connected). Likewise, all the `B` cells will form another simply-connected shape. The grid will always contain at least one `A` and at least one `B`. Imagine the grid is actually two blocky-shaped pieces of thin plastic, represented by the `A` and `B` portions. If it were placed flat on a table, could the two pieces be slid apart while keeping both completely flat on the table? Print or return a [truthy](https://codegolf.meta.stackexchange.com/a/2194/26997) value if the two `A` and `B` shapes could be separated like this by simply pulling them apart. If not, print or return a [falsy](https://codegolf.meta.stackexchange.com/a/2194/26997) value. For example, the input ``` AAA ABB AAA ``` is truthy because the `BB` section can be slid to the right, separating it from the `A`'s: ``` AAA A BB AAA ``` However, the input ``` AAAA ABBA ABAA ``` is falsy because there's no way to slide the `A` and `B` portions apart without having them overlap. The shortest code in bytes wins. If desired, you may use any two distict [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `A` and `B`. **Truthy Examples (separated by empty lines)** ``` BBB BAA BBB BA A B AB AB AAA BBB AAAAB ABBBB ABBA ABBA AAAA AAAAAABBBBBBBBB AABBBBBBBBBBBBB AAAAAAAAAABBBBB AABBBBBBBBBBBBB AAAAAAAAAAAAAAB AAAAAAAAAAAA ABABABABABAB BBBBBBBBBBBB BAAAAABB BBAAABBB BBBABBBB BBBABBBB BBBABBBB BBBBBBBB BBBBBBBB AAA BAA AAA ``` **Falsy Examples** ``` BBBB BAAB BABB BBBB BAAB AABB BBBBBBB BBBBBAB AAAAAAB BBBBBBB BAAA BABA BBBA AABA AAAA AAAAAAA ABBBBBA AAAAABA BBBBBBA BAAAAABB BBAAABBB BBBABBBB BBBABBBB BBBAABBB BBBBBBBB BBBBBBBB AAA ABA BBA ABA AAA ``` [Answer] # CJam, ~~33~~ ~~32~~ ~~20~~ ~~19~~ 17 bytes Revised version, with massive support from @Sp3000 and @MartinBüttner: ``` qN/_z]{:e`z,3<}/| ``` [Try it online](http://cjam.aditsu.net/#code=qN%2F_z%5D%7B%3Ae%60%3A.%7C%2C3%3C%7D%2F%7C&input=AAAAAAAAAAAA%0AABABABABABAB%0ABBBBBBBBBBBB) ### Contributions * @Sp3000 suggested a critical simplification to my original algorithm. * @MartinBüttner applied his mad golfing skills to the revised approach, which almost certainly resulted in shorter code than I would have come up with even after considering the simplification. ### Algorithm and Proof The following explains the criteria for the puzzle sliding apart horizontally. The vertical case can be determined by looking at columns instead of rows, or transposing the character matrix and looking at the rows again. I'll use the term "stretch" for a maximum sequence of the same letters. For example, the following rows have 1, 2, and 3 stretches respectively: ``` AAAAAAAA BBBAAAAA AABBBAAA ``` I'll also use the term "interlocked" for a row/puzzle that cannot slide apart. The key observation is that **the puzzle can slide apart if and only if all rows have at most 2 stretches**. Or reversed, it is **interlocked if and only if there is any row with more than 2 stretches**. The following might not qualify as a strict mathematical proof, but I believe that it makes for a convincing explanation why this has to be the case. It is easy to see that the puzzle is interlocked if it has rows of more than 2 stretches. Looking at a row with 3 stretches: ``` BBBAAB ``` it is clear that it prevents the puzzle from sliding apart because the `A` stretch is locked between the `B` stretches. This means that the row is interlocked, which in turn makes the whole puzzle interlocked. The opposite direction of the proof is not quite as obvious. We need to show that there are no interlocked puzzles where all rows have only 1 or 2 stretches. Starting with a couple of observations: * Rows with only 1 stretch do not contribute to a puzzle being interlocked, since they can slide in either direction without any collisions. * If all rows with 2 stretches have the same order of `A` and `B`, the puzzle is clearly not interlocked. In this case, all `A` cells are left of all `B` cells, or vice versa, and there are no collisions when sliding the two pieces apart. The only tricky case would be puzzles where we have rows with 2 stretches of different order. I'm going to show that such puzzles **do not exist** under the given specifications. To show this, let's look at a partial puzzle that does have this configuration, where `.` are wildcards: ``` ....... AAABBBB ....... BBAAAAA ....... ``` Now, the specification says that both the `A` and `B` cells are simply connected in all valid puzzles. To make the `A` cells connected in the partial puzzle above, we have two options: 1. We loop around one of the stretches of `B`, for example: ``` ..AAAAAA AAABBBBA .......A BBAAAAAA ........ ``` To do this, we unavoidably extend one of the rows to have 3 stretches, so this will never give us a valid puzzle where all rows have at most 2 stretches. 2. We connect them on a direct path: ``` ....... AAABBBB ..A.... BBAAAAA ....... ``` The `A` cells are now simply connected, and there are still no rows with more than 2 stretches. However, the `B` cells also need to be simply connected. The direct path is now blocked by the connected `A` cells, and the only way to connect the `B` cells is to loop around one of the stretches of `A` cells. This leads back to case 1, where we can't do that without creating rows of 3 stretches. To count the stretches, the implementation uses the CJam RLE operator. ### Explanation of Code ``` qN/ Get input and split at newlines. _z Make a transposed copy. ] Wrap the original and transposed puzzle in an array so that we can loop over the two. { Start of loop over original and transposed puzzle. :e` Apply RLE to all rows. z, Transpose the matrix with the RLE rows, and take the element count of the result. Or in other words, take the column count. This will be the length of the longest row after RLE. 3< Check the length for less than 3. }/ End of loop over original and transposed puzzle. | Or the results of the two. ``` [Answer] # Snails, 14 ``` o(t\B+~)+!(t\B ``` If the puzzle can be slid apart, it prints the area of the input. Otherwise, it prints 0. It's a bit slow for the larger examples, as it takes time factorial in the area of the grid. ``` ,, the program will print the number of starting cells matching this pattern o ,, pick a cardinal direction ( t ,, teleport to any cell on the grid \B+ ,, match "B" 1 or more times, moving in the direction set by 'o'. ,, when a cell is matched, it gets slimed and can't be matched again. ~ ,, match an out-of-bounds cell )+ ,, do parenthesized instructions 1 or more times !( ,, the following must not match: t\B ,, teleport to some cell and match 'B' ``` [Answer] # JavaScript (ES6), ~~108~~ ~~107~~ ~~98~~ ~~91~~ 82 bytes ``` a=>!(T=[],R=/AB+A|BA+B/).test([...a].map((c,i)=>T[i%-~a.search` `]+=c))|!R.test(a) ``` [Live demo](http://jsfiddle.net/intrepidcoder/vdzwnca8/). Tested in Firefox. Takes input as a newline-delimited string. Edits: * Saved 1 byte by changing `\n` to a literal newline. * Saved 9 bytes by doing the RegExp test directly on the multi-line string instead of converting to an array. * Eliminated another 9 bytes by using array comprehensions to split string, moving ! into `g` function and calling RegExp directly on array instead of using `find`. * Continued the arthmetic sequence by saving another 9 bytes. Did a modulus on the index instead of splitting the array by newlines before taking the transpose. ### How it works Previous version: ``` a=>(T=[],a.split` `.map(s=>s.split``.map((c,i)=>T[i]+=c)),!T.find(g=s=>/AB+A|BA+B/.test(s)))|!g(a) ``` 1. Take the input `a` and split it by newlines into an array of strings. 2. Transpose `a` and store it in `T`. Use `map` to iterate over each element of `a`, split the string into a character array, and use `map` again to append the `i`th character in the line to the `i`th line of `T`. Since each element of `T` is uninitialized, it will end up looking something like `"undefinedAAABBA"`, but this won't matter. 3. Create a RegExp based testing function `g` that matches the pattern `/AB+A|BA+B/`. If it matches, the pieces are locked in the given direction because then there are a set of `B`s sandwiched between two or more `A`s or vice-versa. 4. Use the testing function `g` to test all elements of the block `a` and its transpose `T` for a match using `find`. If both match, then the pieces are locked in both directions, so output a falsy value, otherwise a truthy one. [Answer] # Javascript (ES6), 118 ``` slidey= // code a=>!a.match(R=/AB+A|BA+B/)||!(a=a.split` `.map(b=>b.split``))[0].map((_,c)=>a.map(d=>d[c])).some(e=>e.join``.match(R)) // IO var S =document.getElementById('S'); S.onkeyup = _=> document.getElementById('P').innerText = slidey(S.value); document.getElementById('P').innerText = slidey(S.value); ``` ``` <textarea id='S'>BAAAAABB BBAAABBB BBBABBBB BBBABBBB BBBABBBB BBBBBBBB BBBBBBBB</textarea> <p id='P'></p> ``` Explanation: ``` a=> !/* check string horizontally */ || !/* check string vertically by transposing it and running the same horizontal check */ a=> !a.match(R=/AB+A|BA+B/) || !/* ... */ // check for lines containing something like BAAAAAB or ABBBBBBBA // this is the only way something can get blocked horizontally // eg AAAAAAA // AAABAAA <<< note the B in the middle of As here // AAABBBB <<< blocked from being pulled out horizontally // AAAAAAA a=> /* ... */ ||!( a = a.split('\n').map(b=> b.split('')) ) // split a into 2D array [0].map((_,c)=>a.map(d=>d[c])) // transpose it .some(e=>e.join``.match(R)) // run the check again using `some` to go line by line // which is shorter than .join().match() outside a=> !/* returns null if no horizontal obstacles and an array if there are */ || !/* same thing */ // negate both to cast to a boolean (false if obstacles, true if not) // an input can only be unslidable if both directions are blocked // so (no obstacles vertically? || no obstacles horizontally?) gives the answer ``` [Answer] # JavaScript (ES6) 72 ~~74~~ **Edit** 2 bytes saved thx @NotthatCharles I have the intuitive understanding that if one piece can slide just a fraction of step, then it's free. The current test cases confirm this. So I check just one step in each direction. Characters used: 1 and 0 2 bytes more to use any 2 printable characters like A and B Test running the snippet below in an EcmaScript 6 compliant browser (supporting the spread operator - IE Firefox) ``` f=s=>[w=~s.search` `,-w,-1,1].some(o=>![...s].some((x,p)=>x+s[p+o]==10)) // 4 bytes more- for any symbol, not just 1 and 0 (for instance A and B): g=s=>[w=~s.search` `,-w,-1,1].some(o=>![...s].some((x,p)=>x+s[p+o]=='AB')) //TEST console.log=x=>O.innerHTML+=x+'\n' testOk = [ '111\n100\n111', '10', '0\n1', '01\n01', '000\n111', '00001\n01111', '0110\n0110\n0000', '000000111111111\n001111111111111\n000000000011111\n001111111111111\n000000000000001', '000000000000\n010101010101\n111111111111', '10000011\n11000111\n11101111\n11101111\n11101111\n11111111\n11111111', '000\n100\n000' ] testKo = [ '1111\n1001\n1011', '1111\n1001\n0011', '1111111\n1111101\n0000001\n1111111', '1000\n1010\n1110\n0010\n0000', '0000000\n0111110\n0000010\n1111110', '10000011\n11000111\n11101111\n11101111\n11100111\n11111111\n11111111', '000\n010\n110\n010\n000' ] console.log('Expecting true') testOk.forEach(t=>console.log(t+'\n'+f(t)+'\n')) console.log('Expecting false') testKo.forEach(t=>console.log(t+'\n'+f(t)+'\n')) ``` ``` <pre id=O></pre> ``` [Answer] # Mathematica ~~100~~ 69 bytes With a massive 31 bytes saved, thanks to @Martin Buttner, ``` g=Max[Length/@Split/@#]<3&;g[c=Characters@StringSplit@#]||g@Thread@c& ``` Formats the input as a matrix of characters; it also makes a transpose of the matrix. If either the matrix or its transpose has no more than 2 runs per row then the puzzle is can slide. `{a,a,b,b,b}` has 2 runs of letters. `{a,a,b,a,a}` has 3 runs of letters. `{a,a,b,a,a,a,b,b,b,b,b,b,b,b}` has 4 runs of letters. [Answer] ## Dyalog APL, 22 bytes ``` (∨/{∧/2>+/2≠/⍵}¨)⊂∘⍉,⊂ ``` [Try it here.](http://tryapl.org/) This is a function that takes in a 2D array of characters, and returns `1` for sliding instances and `0` for non-sliding ones. The algorithm is similar to most other answers: check for the matrix and its transpose that no row contains more than one adjacent pair of different letters. For the 4x3 input matrix ``` AAAA ABBB AAAB ``` the function can be invoked as ``` f ← (∨/{∧/2>+/2≠/⍵}¨)⊂∘⍉,⊂ f 4 3 ⍴ 'AAAAABBBAAAB' ``` which results in `1`. ## Explanation ``` ⊂∘⍉,⊂ The matrix and its transpose. {...}¨ For each of them: 2≠/⍵ On each row, replace each adjacent pair with 1 if they differ, with 0 otherwise 2>+/ Take the sum on each row and check that it's less than 2 ∧/ AND over all rows ∨/ OR over the resulting two values ``` [Answer] # JavaScript (ES6), 94 bytes ``` x=>!(y=/AB+A|BA+B/).test(x)|(z=[],x.split` `.map(b=>b.split``.map((c,i)=>z[i]+=c)),!y.test(z)) ``` Same-size alternate method: ``` x=>(t=s=>!/AB+A|BA+B/.test(s),z=[],x.split` `.map(b=>b.split``.map((c,i)=>z[i]+=c)),t(x)|t(z)) ``` This returns `1` for a truthy input and `0` for falsy. I started work on this before any other answers had been posted. I also originally tried using ES7's array comprehensions, but that ended up about 10 chars longer than this method. Try it out: ``` a=x=>!(y=/AB+A|BA+B/).test(x)|(z=[],x.split` `.map(b=>b.split``.map((c,i)=>z[i]+=c)),!y.test(z)) P.onclick=_=>Q.innerHTML='Result: '+a(O.value) ``` ``` <textarea id=O cols="20" rows="8">AAAAAABBBBBBBBB AABBBBBBBBBBBBB AAAAAAAAAABBBBB AABBBBBBBBBBBBB AAAAAAAAAAAAAAB</textarea> <button id=P>Test</button> <p id=Q>Result: </p> ``` Suggestions welcome! ]
[Question] [ Your goal is to determine whether a given number `n` is prime in the fewest bytes. But, your code must be a single [Python 2](https://docs.python.org/2/) expression on numbers consisting of only * operators * the input variable `n` * integer constants * parentheses No loops, no assignments, no built-in functions, only what's listed above. Yes, it's possible. **Operators** Here's a list of [all operators in Python 2](https://docs.python.org/2/reference/lexical_analysis.html#operators), which include arithmetic, bitwise, and logical operators: ``` + adddition - minus or unary negation * multiplication ** exponentiation, only with non-negative exponent / floor division % modulo << bit shift left >> bit shift right & bitwise and | bitwise or ^ bitwise xor ~ bitwise not < less than > greater than <= less than or equals >= greater than or equals == equals != does not equal ``` All intermediate values are integers (or False/True, which implicitly equals 0 and 1). Exponentiation may not be used with negative exponents, as this may produce floats. Note that `/` does floor-division, unlike Python 3, so `//` is not needed. Even if you're not familiar with Python, the operators should be pretty intuitive. See [this table for operator precedence](https://docs.python.org/2/reference/expressions.html#operator-precedence) and [this section and below](https://docs.python.org/2/reference/expressions.html#the-power-operator) for a detailed specification of the grammar. You can [run Python 2 on TIO](https://tio.run/#python2). **I/O** **Input:** A positive integer `n` that's at least 2. **Output:** 1 if `n` is prime, and 0 otherwise. `True` and `False` may also be used. Fewest bytes wins. Since your code is an expression, it will be a snippet, expecting the input value stored as `n`, and evaluating to the output desired. Your code must work for `n` arbitrarily large, system limits aside. Since Python's whole-number type is unbounded, there are no limits on the operators. Your code may take however long to run. [Answer] # 43 bytes ``` (4**n+1)**n%4**n**2/n&2**(2*n*n+n)/-~2**n<1 ``` [Try it online!](https://tio.run/##TY0xDsMgEARreMU1juAcyz7kygo/SUNhEiRrbWGaNPk6wV2a1U6xs8envHe4GvdMoATKAa/VuDvJNNlFqyjk6VnNzIxebMvuqsxuxM0xG9cAPew4fBviIVVF1zZh2wy6RJc5/ZsxiLVahfNcc6Eo3sd2B61SbLTQkRMKof4A "Python 2 – Try It Online") The method is similar to Dennis' second (deleted) answer, but this answer is easier to be proved correct. # Proof ### Short form The most significant digit of `(4**n+1)**n%4**n**2` in base \$2^n\$ that is not divisible by \$n\$ will make the next (less significant) digit in `(4**n+1)**n%4**n**2/n` nonzero (if that "next digit" is not in the fractional part), then a `&` with the bitmask `2**(2*n*n+n)/-~2**n` is executed to check if any digit at odd position is nonzero. ### Long form Let \$[a\_n,\dots,a\_1,a\_0]\_b\$ be the number having that base \$b\$ representation, i.e., \$a\_nb^n+\dots+a\_1b^1+a\_0b^0\$, and \$a\_i\$ be the digit at "position" \$i\$ in base \$b\$ representation. * \$\texttt{2\*\*(2\*n\*n+n)/-~2\*\*n} =\lfloor{2^{(2n+1)n}\over1+2^n}\rfloor =\lfloor{4^{n^2}\times 2^n\over1+2^n}\rfloor =\lfloor{{(4^{n^2}-1)\times 2^n\over1+2^n} +{2^n\over1+2^n}}\rfloor \$. Because \$2^n\times{4^{n^2}-1\over1+2^n} =2^n(2^n-1)\times{(4^n)^n-1\over4^n-1} =[2^n-1,0,2^n-1,0,2^n-1,0]\_{2^n}\$ (with \$n\$ \$2^n-1\$s) is an integer, and \$\lfloor{2^n\over1+2^n}\rfloor=0\$, `2**(2*n*n+n)/-~2**n` = \$[2^n-1,0,2^n-1,0,2^n-1,0]\_{2^n}\$. Next, consider $$\begin{align} \texttt{(4\*\*n+1)\*\*n} &=(4^n+1)^n \\ &=\binom n04^{0n}+\binom n14^{1n}+\dots+\binom nn4^{n^2} \\ &=\left[\binom nn,0,\dots,0,\binom n1,0,\binom n0\right]\_{2^n} \end{align}$$ \$4^{n^2}=(2^n)^{2n}\$, so `%4**n**2` will truncate the number to \$2n\$ last digits - that excludes the \$\binom nn\$ (which is 1) but include all other binomial coefficients. About `/n`: * If \$n\$ is a prime, the result will be \$\left[\binom n{n-1}/n,0,\dots,0,\binom n1/n,0,0\right]\_{2^n}\$. All digits at odd position are zero. * If \$n\$ is not a prime: Let \$a\$ be the largest integer such that \$n\nmid\binom na\$ (\$n>a>0\$). Rewrite the dividend as \$\left[\binom n{n-1},0,\binom n{n-2},0,\dots,\binom n{a+1}, 0,0,0,\dots,0,0,0\right]\_{2^n} + \left[\binom na,0,\binom n{a-1},0,\dots,\binom n0\right]\_{2^n}\$ The first summand has all digits divisible by \$n\$, and the digit at position \$2a-1\$ zero. The second summand has its most significant digit (at position \$2a\$) not divisible by \$n\$ and (the base) \$2^n>n\$, so the quotient when dividing that by \$n\$ would have the digit at position \$2a-1\$ nonzero. Therefore, the final result (`(4**n+1)**n%4**n**2/n`) should have the digit (base \$2^n\$, of course) at position \$2a+1\$ nonzero. Finally, the bitwise AND (`&`) performs a vectorized bitwise AND on the digits in base \$2^n\$ (because the base is a power of 2), and because \$a\texttt &0=0,a\texttt&(2^n-1)=a\$ for all \$0\le a<2^n\$, `(4**n+1)**n%4**n**2/n&2**(2*n*n+n)/-~2**n` is zero iff `(4**n+1)**n%4**n**2/n` has all digits in first \$n\$ odd positions zero - which is equivalent to \$n\$ being prime. [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` n**(n*n-n)/(((2**n**n+1)**n**n>>n**n*~-n)%2**n**n)%n>n-2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfWRxfUJSZm2qbk5iblJKokGcV8z9PS0sjTytPN09TX0NDw0hLCyiQp22oCWHY2YFIrTqgtCpUTlM1zy5P1@h/Wn6RQp5CZp5CtJGOgrGOgomOgmmsFRcn0Ia8EoU8HQWYbRp5mv8B "Python 2 – Try It Online") This is a proof-of-concept that this challenge is doable with only arithmetic operators, in particular without bitwise `|`, `&`, or `^`. The code uses bitwise and comparison operators only for golfing, and they can easily be replaced with arithmetic equivalents. However, the solution is extremely slow, and I haven't been able to run \$n=6\$`, thanks to two-level exponents like \$2^{n^n}\$. The main idea is to make an expression for the factorial \$n!\$, which lets us do a [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) primality test \$(n-1)! \mathbin{\%} n > n-2 \$ where \$ \mathbin{\%}\$ is the modulo operator. We can make an expression for the [binomial coefficient](https://codegolf.stackexchange.com/a/169115/20260), which is made of factorials $$\binom{m}{n} \ = \frac{m!}{n!(m-n)!}$$ But it's not clear how to extract just one of these factorials. The trick is to hammer apart \$n!\$ by making \$m\$ really huge. $$\binom{m}{n} \ = \frac{m(m-1)\cdots(m-n+1)}{n!}= \frac{m^n}{n!}\cdot \left(1-\frac{1}{m}\right)\left(1-\frac{2}{m}\right)\cdots \left(1-\frac{n-1}{m}\right)$$ So, if we let \$c \$ be the product \$ \left(1-\frac{1}{m}\right)\left(1-\frac{2}{m}\right)\cdots \left(1-\frac{n-1}{m}\right)\$, we have $$n! = \frac{m^n}{\binom{m}{n}} \cdot c$$ If we could just ignore \$c\$, we'd be done. The rest of this post is looking how large we need to make \$m\$ to be able to do this. Note that \$c\$ approaches \$1\$ from below as \$ m \to \infty \$. We just need to make \$m\$ huge enough that omitting \$c\$ gives us a value with integer part \$n!\$ so that we may compute $$n! = \left\lfloor \frac{m^n}{\binom{m}{n}} \right\rfloor $$ For this, it suffices to have \$1 - c < 1/n!\$ to avoid the ratio passing the next integer \$n!+1\$. Observe that \$c\$ is a product of \$n\$ terms of which the smallest is \$ \left(1-\frac{n-1}{m}\right)\$. So, we have $$c > \left(1-\frac{n-1}{m}\right)^n > 1 - \frac{n-1}{m} n > 1-\frac{n^2}{m},$$ which means \$1 - c < \frac{n^2}{m}\$. Since we're looking to have \$1 - c < 1/n!\$, it suffices to take \$m \geq n! \cdot n^2\$. In the code, we use \$m=n^n\$. Since Wilson's Theorem uses \$(n-1)!\$, we actually only need \$m \geq (n-1)! \cdot (n-1)^2\$. It's easy to see that \$m=n^n\$ satisfies the bound for the small values and quickly outgrows the right hand side asymptotically, say with [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation). [Answer] This answer doesn't use any number-theoretic cleverness. It spams Python's bitwise operators to create a manual "for loop", checking all pairs \$1 \leq i,j < n\$ to see whether \$i \times j = n\$. # Python 2, way too many bytes (278 thanks to Jo King in the comments!) ``` ((((((2**(n*n)/(2**n-1)**2)*(2**((n**2)*n)/(2**(n**2)-1)**2))^((n*((2**(n*n-n)/(2**n-1))*(2**((n**2)*(n-1))/(2**n**2-1))))))-((2**(n*n-n)/(2**n-1))*(2**((n**2)*(n-1))/(2**(n**2)-1))))&(((2**(n*(n-1))/(2**n-1))*(2**((n**2)*(n-1))/(2**(n**2)-1)))*(2**(n-1)))==0))|((1<n<6)&(n!=4)) ``` [Try it online!](https://tio.run/##lY69DsIwDIR3nsIsyLYa0UaIATVvgpAY@OlyraIuSLx7yE8VlQ1usu/82Z5e83OEDffRE2gA@SseN7aNbeW0ockPmAnNOXCWVWUoZJ8qmE5UrWi2o5/qJSvdMiCXlFbarPhvmLNVwmikJsn8h9bbUbv69Hr3j3QZyZE414q8mbse/TGuxdYdREL4AA "Python 2 – Try It Online") This is a lot more bytes than the other answers, so I'm leaving it ungolfed for now. The code snippet below contains functions and variable assignment for clarity, but substitution turns isPrime(n) into a single Python expression. ``` def count(k, spacing): return 2**(spacing*(k+1))/(2**spacing - 1)**2 def ones(k, spacing): return 2**(spacing*k)/(2**spacing - 1) def isPrime(n): x = count(n-1, n) y = count(n-1, n**2) onebits = ones(n-1, n) * ones(n-1, n**2) comparison = n*onebits difference = (x*y) ^ (comparison) differenceMinusOne = difference - onebits checkbits = onebits*(2**(n-1)) return (differenceMinusOne & checkbits == 0 and n>1)or 1<n<6 and n!=4 ``` # Why does it work? I'll do the same algorithm here in base 10 instead of binary. Look at this neat fraction: $$ \frac{1.0}{999^2} = 1.002003004005\dots $$ If we put a large power of 10 in the numerator and use Python's floor division, this gives an enumeration of numbers. For example, \$ 10^{15}/(999^2) = 1002003004 \$ with floor division, enumerating the numbers \$ 1,2,3,4 \$. Let's say we multiply two numbers like this, with different spacings of zeroes. I'll place commas suggestively in the product. $$ 1002003004 \times 1000000000002000000000003000000000004 = $$ $$ 1002003004,002004006008,003006009012,004008012016 $$ The product enumerates, in three-digit sequences, the multiplication table up to 4 times 4. If we want to check whether the number 5 is prime, we just have to check whether \$ 005 \$ appears anywhere in that product. To do that, we XOR the above product by the number \$ 005005005\dots005 \$, and then subtract the number \$ 001001001\dots001 \$. Call the result \$d\$. If \$ 005 \$ appeared in the multiplication table enumeration, it will cause the subtraction to carry over and put \$ 999 \$ in the corresponding place in \$d\$. To test for this overflow, we compute an AND of \$d\$ and the number \$ 900900900\dots900 \$. The result is zero if and only if 5 is prime. ]
[Question] [ xkcd is everyone's favorite webcomic, and you will be writing a program that will bring a little bit more humor to us all. Your objective in this challenge is to write a program which will take a number as input and display that xkcd and its title-text (mousover text). ## Input Your program will take a positive integer as input (not necessarily one for which there exists a valid comic) and display that xkcd: for example, an input of 1500 should display the comic "Upside-Down Map" at xkcd.com/1500, and then either print its title-text to the console or display it with the image. [![Due to their proximity across the channel, there's long been tension between North Korea and the United Kingdom of Great Britain and Southern Ireland.](https://i.stack.imgur.com/LpNQf.png)](https://i.stack.imgur.com/LpNQf.png) `Due to their proximity across the channel, there's long been tension between North Korea and the United Kingdom of Great Britain and Southern Ireland.` Test case 2, for n=859: [![Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text."](https://i.stack.imgur.com/ItL7a.png)](https://i.stack.imgur.com/ItL7a.png) `Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text."` Your program should also be able to function without any input, and perform the same task for the most recent xkcd found at xkcd.com, and it should always display the most recent one even when a new one goes up. You do not have to get the image directly from xkcd.com, you can use another database as long as it is up-to-date and already existed before this challenge went up. URL shortners, that is, urls with no purpose other than redirecting to somewhere else, are not allowed. You may display the image in any way you chose, including in a browser. You may ***not***, however, directly display part of another page in an iframe or similar. CLARIFICATION: **you cannot open a preexisting webpage, if you wish to use the browser you have to create a new page**. You must also actually display an image - outputting an image file is not allowed. You can handle the case that there isn't an image for a particular comic (e.g. it is interactive or the program was passed a number greater than the amount of comics that have been released) in any reasonable way you wish, including throwing an exception, or printing out an at least single-character string, as long as it somehow signifies to the user that there isn't an image for that input. You can only display an image and output its title-text, or output an error message for an invalid comic. Other output is not allowed. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the fewest bytes wins. [Answer] # Perl + curl + feh, ~~86~~ ~~84~~ 75 bytes ``` `curl xkcd.com/$_/`=~/<img src="(.*)" title="(.*?)"/;$_=$2;`feh "http:$1"` ``` Requires the `-p` switch. I have accounted for this in the byte count. [Answer] ## PowerShell v3+ ~~110~~ ~~99~~ ~~107~~ 103 Bytes ``` iwr($x=((iwr "xkcd.com/$args").images|?{$_.title})).src.Trim("/") -outf x.jpg;if($x){ii x.jpg;$x.title} ``` Thanks to Timmy for helping save some bytes by using inline assignments. If no arguments are passed then `$args` is null and it will just get the current comic. Download the picture, by matching the one with alt text, into a file in the current running directory of the script. Then display it with the default viewer of jpg's. The alt text is then displayed to console. `iwr` is an alias for `Invoke-WebRequest` If the number passed (or any invalid input for that matter) does not match the process fails with at least a 404 error. ``` iwr( # Request the comic image from XKCD $x=((iwr "xkcd.com/$args").images| # Primary search to locate either the current image # or one matching an argument passed ?{$_.title})) # Find the image with alt text .src.Trim("/") # Using the images associated link and strip the leading slashes -outf x.jpg # Output the image to the directory local to where the script was run if($x){ # Test if the image acquisition was successful ii x.jpg # Open the picture in with the default jpg viewer $x.title # Display alt text to console } # I'm a closing bracket. ``` [Answer] ## [AutoIt](http://autoitscript.com), 440 bytes Yes, it's long, but it's stable. ``` #include<IE.au3> #include<GDIPlus.au3> Func _($0='') _GDIPlus_Startup() $1=_IECreate('xkcd.com/'&$0) For $3 In $1.document.images ExitLoop $3.title<>'' Next $4=_GDIPlus_BitmapCreateFromMemory(InetRead($3.src),1) $6=_GDIPlus_ImageGetDimension(_GDIPlus_BitmapCreateFromHBITMAP($4)) GUICreate(ToolTip($3.title),$6[0],$6[1]) GUICtrlSendMsg(GUICtrlCreatePic('',0,0,$6[0],$6[1]),370,0,$4) _IEQuit($1) GUISetState() Do Until GUIGetMsg()=-3 EndFunc ``` First of all, this doesn't use RegEx to scrape the site (because I have no time to test this on all comics), but rather uses the Internet Explorer API to iterate through the DOM's `img` tags until it finds one with a title text. The binary stream is read from the image URL and rendered into a bitmap using GDIPlus. This is then displayed in a nice, auto-sized GUI with an actual tooltip to make it behave almost exactly like the website. Here's a test case (`_(859)`): ![](https://i.stack.imgur.com/IRgTc.png) ) [Answer] ## Powershell, 93 Bytes 93 Byte version to use local image viewer. ``` $n=(iwr xkcd.com/$args).images|?{$_.title};$n.title;iwr ("http:"+$n.src) -OutF x.jpg;ii x.* ``` Saved 2 bytes by removing needless doublequotes, then another lot by using `("http:"+$n.src)` instead of `"https://"+$n.src.trim("/")` - since the `img` src comes with `//` already on it, and xkcd doesn't require https. ``` $n=(iwr xkcd.com/$args).images|?{$_.title};$n.title;saps ("http:"+$n.src) ``` `$n=(iwr "xkcd.com/$args").images|?{$_.title};$n.title;saps ("https://"+$n.src.trim("/"))` extremely similar to Matts powershell answer, (should probably be a comment but low reputation) Instead this opens a new tab/window in the default browser, and other things, saving some bytes. `iwr` is an alias for `Invoke-WebRequest` `saps` is an alias for `Start-Process` which opens 'it' in the default context. [Answer] # R, ~~358~~ ~~328~~ ~~310~~ 298 bytes ``` f=function(x){H="http:";p=paste0;library(XML);a=xpathSApply(htmlParse(p(H,'//xkcd.com/',x)),'//div/img',xmlAttrs)[[1]];download.file(p(H,a[1]),'a');I=`if`(grepl('png',a[1]),png::readPNG,jpeg::readJPEG)('a');d=dim(I)/100;quartz(,d[2],d[1]);par(mar=rep(0,4));frame();rasterImage(I,0,0,1,1);cat(a[2])} ``` With new lines and comments: ``` f=function(x){ H="http:" p=paste0 library(XML) #Needed for xpathSApply, htmlParse and xmlAttrs # The following line find the first img element and extract its attributes a=xpathSApply(htmlParse(p(H,'//xkcd.com/',x)),'//div/img',xmlAttrs)[[1]] download.file(p(H,a[1]),'a') #Download to a file called 'a' I=`if`(grepl('png',a[1]),png::readPNG,jpeg::readJPEG)('a') #Check if png or jpeg and load the file accordingly d=dim(I)/100 #convert dimension from pixel to inches (100 ppi). quartz(,d[2],d[1]) #open a window of the correct dimension par(mar=rep(0,4)) #Get rid of margins frame() #Create empty plot rasterImage(I,0,0,1,1) #Add png/jpeg to the plot cat(a[2]) #Print title text to stdout } ``` Screenshots of test cases: for x=1500: [![for x=1500 (png)](https://i.stack.imgur.com/FK5Qj.png)](https://i.stack.imgur.com/FK5Qj.png) for x empty: [![for x=''](https://i.stack.imgur.com/JXYwL.png)](https://i.stack.imgur.com/JXYwL.png) case when picture is a jpeg: [![for x=10 (jpeg)](https://i.stack.imgur.com/XjgcE.png)](https://i.stack.imgur.com/XjgcE.png) x=859: [![x=859](https://i.stack.imgur.com/f6V2Z.png)](https://i.stack.imgur.com/f6V2Z.png) [Answer] ## PHP, 95 bytes ``` <?php echo str_replace("title=\"","/>",file_get_contents("https://xkcd.com/".$_GET["id"])); ?> ``` Save as main.php, run server ``` php -S localhost:8123 ``` Open <http://localhost:8123/main.php?id=1500> [Answer] ## Python 2.7, ~~309~~ ~~299~~ ~~295~~ 274 bytes Full program. Definitely more golfable, but having read xkcd comics for so long I couldn't let this pass (who knows if this will be helpful in a future for easily browsing xkcd). If no input is passed, gets current comic. If a valid comic number is passed as input then gets that comic. If an invalid input (not a number comic in the valid range) is passed, throws an error. Any suggestions on how to reduce byte count are welcome! Will revisit (and add explanation) when I have more time. -10 bytes thanks to @Dopapp -21 bytes thanks to @Shebang ``` import urllib as u,re from PIL import Image h='http://';x='xkcd.com/' o=u.URLopener() t=u.urlopen(h+x+raw_input()).read() c=sum([re.findall(r,t)for r in[h+'imgs.'+x+'c.*s/.*\.\w{1,3}','\.\w{1,3}" t.*e="(.*)" a']],[]) Image.open(o.retrieve(c[0],'1.png')[0]).show();print c[1] ``` [Answer] # PHP, 42 bytes ``` <?=@file('http://xkcd.com/'.$_GET[i])[59]; ``` Save to a file and fire it up in your web server of choice [Answer] # [Wolfram Language](http://reference.wolfram.com/language/) 45 bytes ( Mathematica ) ``` Import["https://xkcd.com/"<>#,"Images"][[2]]& ``` Usage with number: ``` %@"1500" ``` Usage without number: ``` %@"" ``` [Answer] # JavaScript + HTML, 124 + 18 = 142 bytes ``` i=>fetch(`//crossorigin.me/http://xkcd.com/${i||""}/info.0.json`).then(r=>r.json()).then(d=>(A.innerHTML=d.alt,B.src=d.img)) ``` ``` <img id=B><p id=A> ``` Cross-origin solution thanks to [Kaiido's answer here](https://codegolf.stackexchange.com/questions/125715/lazy-click-and-drag/125759#125759). 17 bytes (`//crossorigin.me/`) can be saved if the proxy required to connect to xkcd.com can be subtracted ([meta post about this](https://codegolf.meta.stackexchange.com/questions/12846/should-proxy-usage-be-included-in-byte-counts/)). ## Test Snippet ``` f= i=>fetch(`//crossorigin.me/http://xkcd.com/${i||""}/info.0.json`).then(r=>r.json()).then(d=>(A.innerHTML=d.alt,B.src=d.img)) ``` ``` <style>img{width:50%}</style><input id=I> <button onclick="f(I.value)">Run</button><br> <img id=B><p id=A> ``` [Answer] # Python 3 + Requests + PIL, ~~192~~ 186 bytes ``` from requests import* import PIL.Image as f from io import* r=get("https://xkcd.com/%s/info.0.json"%input()).json() f.open(BytesIO(get(r["img"],stream=1).content)).show() print(r["alt"]) ``` Opens up an image viewer (whichever is default on the system it's being run on) containing the comic, and posts the title text to the console. ]
[Question] [ Because of this, you need a better way of working out if a phrase is an acronym of a word. You also think it would be worthwhile to see if the phrase and word in question are recursive acronyms. ## Your task: Given a word and then a phrase separated by a line, output if the phrase is an acronym and then if it is [a recursive acronym](https://en.wikipedia.org/wiki/Acronym#Recursive_acronyms). (The phrase contains what it stands for) * The input will compose of alphabetical characters as well as spaces. * Your program shouldn't be case sensitive. ## Example Input/Output: Case 1: Input: ``` Acronyms Acronyms can really obviously narrow your message sensors ``` Output: ``` True True ``` Case 2: Input: ``` FAQ frequently asked questions ``` Output: ``` True False ``` Case 3: Input: ``` foo bar baz ``` Output: ``` False False ``` Case 4: Input: ``` GNU GNU is not Unix ``` Output: ``` False False ``` Case 5: Input: ``` Aha A huge Aha ``` Output: ``` True True ``` [Answer] # Python 3, 89 Saved a bunch of bytes thanks to SOPython. ``` a=input().lower() d=input().lower().split() h=tuple(a)==next(zip(*d)) print(h,h&(a in d)) ``` The most complicated part of this solution is `h=tuple(a)==next(zip(*d))`. This unpacks the list `d` into zip and then calls `next` to return a tuple of the first element of each iterable passed into `zip` which is then compared against a tuple of each letter in a (`tuple(a)`). [Answer] # Pyth, ~~19~~ 18 ``` &pqJrz0hCKcrw0)}JK ``` This prints the result in a rather odd format, like: `TrueFalse`. You can [try it online](http://pyth.herokuapp.com/?code=%26pqJrz0hCKcrw0%29%7DJK&input=Aha%0AA+huge+Aha&debug=0) or [run the Test Suite](http://pyth.herokuapp.com/?code=%26pqJrz0hCKcrw0%29%7DJK&input=FAQ%0Afrequently+asked+questions&test_suite=1&test_suite_input=Acronyms%0AAcronyms+can+really+obviously+narrow+your+message+sensors%0AFAQ%0Afrequently+asked+questions%0Afoo%0Abar+baz%0AGNU%0AGNU+is+not+Unix%0AAha%0AA+huge+aha&debug=0&input_size=2). ### Explanation: ``` &pqJrz0hCKcrw0)}JK : rz0 rw0 : read two lines of input, and convert each to lower case c ) : chop the second input on whitespace J K : store the first line in J and the chopped second line in K q hC : zip K and take the first element, check if it is the same as J p : print and return this value & }JK : and the value with whether J is in K, implicit print ``` [Answer] # CJam, ~~21~~ 20 bytes ``` qeuN/)S/_:c2$s=_p*&, ``` Try [this fiddle](http://cjam.aditsu.net/#code=qeuN%2F)S%2F_%3Ac2%24s%3D_p*%26%2C&input=Aha%0AA%20huge%20Aha) in the CJam interpreter or [verify all test cases at once.](http://cjam.aditsu.net/#code=qN2*%2F%7B%0A%20%20QeuN%2F)S%2F_%3Ac2%24s%3D_p*%26%2C%0ApNo%7DfQ&input=Acronyms%0AAcronyms%20can%20really%20obviously%20narrow%20your%20message%20sensors%0A%0AFAQ%0Afrequently%20asked%20questions%0A%0Afoo%0Abar%20baz%0A%0AGNU%0AGNU%20is%20not%20Unix%0A%0AAha%0AA%20huge%20Aha) ### How it works ``` qeu e# Read from STDIN and convert to uppercase. N/ e# Split at linenfeeds. )S/ e# Pop the second line form the array. S/ e# Split it at spaces. _:c e# Push a copy and keep on the initial of each word. 2$s e# Push a copy of the line array and flatten it. e# This pushes the first line. = e# Check for equality. _p e# Print a copy of the resulting Boolean. * e# Repeat the word array 1 or 0 times. & e# Intersect the result with the line array. , e# Push the length of the result (1 or 0). ``` [Answer] # Haskell, ~~81~~ 80 bytes ``` import Data.Char f[a,b]|c<-words b=(a==map(!!0)c,elem a c) p=f.lines.map toLower ``` The output format is not strictly defined, so I return a pair of booleans, e.g. `p "Aha\na huge arm"` -> `(True,False)`. [Answer] # Scala, 135 110 108 bytes ``` val Array(x,y)=args.map(_.toLowerCase) val z=y.split(" ").map(_(0)).mkString print(z==x,z==x&&y.contains(z)) ``` Saved a few bytes by using command line arguments (thanks to J Atkin for the hint), putting the booleans out as a tupel, using `mkString` instead of `new String` and print instead of println. EDIT: Misinterpreted the question, and had to reimplement the solution [Answer] # Python 3, 106 bytes Well, at least it beat Scala ;) ``` x=input().lower() y=input().lower().split() g=all(x[i]==y[i][0]for i in range(len(y))) print(g,g&(x in y)) ``` [Answer] # AppleScript, ~~302~~ ~~301~~ ~~297~~ 293 Bytes Aw, hell yeah. Not even bothered that I lose, this is competitive for AppleScript. ``` set x to(display dialog""default answer"")'s text returned set y to(display dialog""default answer"")'s text returned's words set n to y's items's number repeat n try if not y's item n's character 1=(x as text)'s character n then return{false,false} end set n to n-1 end return{true,x is in y} ``` Outputs as: ``` {true, false} ``` Or whatever the answer happens to be. [Answer] # PHP, 120 bytes Not being case sensitive is a lot of weight (26 bytes). Passed all test cases: ``` foreach($c=explode(' ',strtolower($argv[2]))as$l)$m.=$l[0];var_dump($x=$m==$a=strtolower($argv[1]),$x&&in_array($a,$c)); ``` Outputs two bool values in this form: ``` bool(true) bool(false) ``` Reads two arguments from the command line, like: ``` a.php Acronyms "Acronym can really obviously narrow your message sensors" ``` **Ungolfed** ``` $acronym = strtolower($argv[1]); $words = strtolower($argv[2]); $words = explode(' ', $words); foreach($words as $word) { $letters .= $word[0]; } $isAcronym = $letters == $acronym; var_dump( $isAcronym, $isAcronym && in_array($acronym, $words) ); ``` [Answer] # Ruby, ~~77~~ 74 bytes ``` b=gets.chop.upcase a=gets.upcase p c=a.scan(/\b\w/)*''==b,c&&a.include?(b) ``` [Answer] # Ruby, 52 bytes ``` p !!gets[/^#{x=gets.scan(/\b\w/)*""}$/i],!! ~/#{x}/i ``` Example: ``` $ echo "Aha A huge AHA" | ruby acronym.rb true true ``` [Answer] ## Matlab, 90 bytes ``` function z=f(r,s) z=[sum(regexpi(s(regexpi(s,'(?<=(\s|^))\S')),r))>0 nnz(regexpi(s,r))>0]; ``` Example (note that Matlab displays `true`/ `false` as `1`/ `0`): ``` >> f('Aha', 'A huge Aha') ans = 1 1 ``` [Answer] # JavaScript ES6, ~~95~~ 92 bytes ``` (a,b)=>[(r=eval(`/^${a}$/i`)).test((s=b.split` `).map(c=>c[0]).join``),s.some(c=>r.test(c))] ``` Input both strings as parameters. Outputs an array with two values: one for each boolean. [Answer] # GNU sed, 118 bytes Requires `-r` flag, included in score as +1. Note that I'm using `\b` for a word-boundary match, even though I can't find this documented in GNU sed. It *Works For Me*... ``` N h s/^(.*)\n.*\b\1\b.*/True/i /\n/s/.*/False/ x : s/(.)(.*\n)\1[^ ]* ?/\2/i t /../s/.*/False/ /F/h /F/!s/.*/True/ G ``` ### Expanded: ``` #!/bin/sed -rf N h # Is it recursive? s/^(.*)\n.*\b\1\b.*/True/i # If no replacement, there's still a newline => false /\n/s/.*/False/ x # Is it an acronym? # Repeatedly consume one letter and corresponding word : s/(.)(.*\n)\1[^ ]* ?/\2/i t # If more than just \n remain, then false /../s/.*/False/ # And falsify recursive, too /F/h # !False => true /F/!s/.*/True/ G ``` [Answer] # Groovy, 91 bytes ``` a=args*.toLowerCase() println([a[1].split()*.charAt(0).join("")==a[0],a[1].contains(a[0])]) ``` Output format is `[bool, bool]`.This takes it's input from the command line args. [Answer] # Lua 5.3, 182 bytes ``` a=""b=io.read c=a.lower d=a.reverse e=d(c(b()))f=~e:len()h=a.sub g=d(c(b()))for m in g:gmatch"[^ ]+"do f=-~f if h(e,f,f)~=h(m,~0)then break end k=k or m==e end f=f>~1print(f,f and k) ``` [Answer] # R, 93 bytes ``` a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w="")) ``` Usage: ``` > a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w="")) Aha A huge Aha Read 3 items TRUE TRUE > a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w="")) Acronyms Acronyms can really obviously narrow your message sensors Read 8 items TRUE TRUE > a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w="")) FAQ frequently asked questions Read 3 items TRUE FALSE > a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w="")) foo bar baz Read 2 items FALSE FALSE ``` [Answer] # `awk` 137 bytes ``` awk 'BEGIN{T="True";F="False"}NR*NF<2{a=tolower($1)}END{for(i=1;i<=NF;i++)b=b substr(tolower($i),1,1);print(a==b?T:F)"\n"(a==tolower($1)?T:F)}' ``` * Initialize `T="True";F="False"` to simplify output. * `NR*NF<2{a=tolower($1)}`: set `a` only if the first line only has one field. * `END{...}`: assuming only two lines... + `for(i=1;i<=NF;i++)b=b substr(tolower($i),1,1)`: construct recursive acronym. + `print(a==b?T:F)"\n"(a==tolower($1)?T:F)`: print the output of both comparisons, `a==b` and `a==tolower($1)`. If anyone knows how to optimize the recursive acronym construction, feel free to suggest. [Answer] # SpecBAS - 144 bytes ``` 1 INPUT a$,b$: LET a$=UP$(a$),b$=UP$(b$),d$="": DIM c$(SPLIT b$,NOT " ") 2 FOR EACH w$ IN c$(): LET d$=d$+w$(1): NEXT w$ 3 TEXT d$=a$'POS(a$,b$)>0 ``` Converting the 2 x inputs to uppercase saves characters vs. lowercase conversion. Can now have multiple assignments done in one `LET` statement, which also helps. And `TEXT` saves one character over `PRINT`. Uses 1/0 to show true/false (the apostrophe just moves output to the next line). [Answer] # Perl5, 90 bytes ``` ($a,$b)=map{chomp;lc}<>;print((join"",map{substr($_,0,1)}split/ /,$b)ne $a?0:($b=~$a?2:1)) ``` cheating a bit: 0 = all false, 1 = one true, 2 = both true. I'm not a golfer, but am upset perl is missing while browsing! ``` ($a,$b)=map{chomp;lc}<>; # get the two lines as lowercase print(( # join"",map{substr($_,0,1)}split/ /,$b # collapse first letters of secondline ) ne $a ? 0 : ( $b=~$a ? 2 : 1))# 0 nothing, 1 not recursive, or 2 ``` [Answer] # JavaScript (ES6) 93 ``` (w,s)=>s[L='toLowerCase'](w=w[L](z=y='')).replace(/\w+/g,v=>y+=v[z=z||v==w,0])&&[y=y==w,y&&z] ``` Test running the snippet below in any EcmaScript 6 compliant browser ``` f=(w,s)=>s[L='toLowerCase'](w=w[L](z=y='')).replace(/\w+/g,v=>y+=v[z=z||v==w,0])&&[y=y==w,y&&z] // TEST out=x=>O.innerHTML+=x+'\n'; ;[ ['Acronyms', 'Acronyms can really obviously narrow your message sensors', true, true] ,['FAQ', 'frequently asked questions', true, false] ,['foo', 'bar baz', false, false] ,['GNU', 'GNU is not Unix', false, false] ,['Aha', 'A huge Aha', true, true] ,['Lolcat', 'Laughing over lolcat captions and tearing.', true, true] ,['ABCDE', 'Another basic clearly defined example.', true, false] ,['GNU', 'Gnus nettle unicorns', true, false] ,['PHP', 'PHP Hypertext Preprocessor', true, true] ].forEach(([a,b,c,d]) => ( [r,s]=f(a,b), out(((r==c && s==d)?'OK ':'KO ') + a + ',' + b + ' -> ' + f(a,b)) )) ``` ``` <pre id=O></pre> ``` [Answer] # JavaScript (ES6), ~~89~~ ~~96~~ 95 bytes ``` (a,b)=>[p=(a=a[l='toLowerCase']())==(c=b[l]().split` `).map(x=>x[0]).join``,p&&c.some(x=>x==a)] ``` Shucks...I thought I had it all sorted out, but apparently I was wrong. This defines an anonymous function which takes input as two strings, and returns and array of two boolean items. The first item is calculated by comparing the the first string in all lowercase with the first char of each word in the second string. The second item is calculated simply by checking if the second string contains the first. Here's another solution for the second item; 2 bytes shorter, but very few browsers support it: ``` p&&c.includes(a) ``` [Answer] ## Pyke (was untitled when posted), (noncompetitive), 20 bytes ``` l1c"jFh)J"iQl1qDji{& ``` You can find the source code [here](https://github.com/muddyfish/PYKE), language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 8) ### Or 18 bytes (stableish) ``` l1idcmhsRl1jqDji{& ``` [Try it here!](http://pyke.catbus.co.uk/?code=l1idcmhsRl1jqDji%7B%26&input=Acronyms+can+really+obviously+narrow+your+message+sensors%0AAcronyms&warnings=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ŒlḲḢ€⁼ɗ,wɗ/«\ ``` [Try it online!](https://tio.run/##PY@/TgMxDMb3PIUfAIlnOP4WqUJFagckFvfq9gJpfDi5tofEAAt7lzKzwoQYiuhE1aGPcX2Rw9cByYqd5PPPn2/JubKuN3NXLT@r5dvu@WP3tNouDqbbxeHv@01d/XxtVno8rl/0bzOvvl81X9d1kgr7chwgRQ9CqBzg/sRyEbTyKMJTKLkQGFMIOCII5ANLMEOh@4J8VBmGOxqA3kK07IPpo0AfH8z5ZQ9sAM8Ret7OTAJZoYQkQ5PoY0aNLNgUUkcoChrQ0HpF0QzHuSMTM23XQIgWo2ljMcqsHwFPtNWxSzGq8Xw/FdAPICpHBabT6kCrzEkizSJ0hHLhVBdg@d/YnCVXZsjcuDR7S0fHJ6eme5F0TXuPbih/ "Jelly – Try It Online") Takes input as a pair `[phrase, word]`. [+2 bytes](https://tio.run/##y0rNyan8///opJyHu7c83LHp4Y5Fj5rWPGrcc3K6TvnJ6Q76////d0wuys@rzC3mgjEUkhPzFIpSE4FaFfKTyjLzS4uBrLzEoqL8coXK/NIihdzU4uLE9FSF4tS84vyiYgA) to input as a newline separated pair with the word first If the inputs were always in a single case, then [this](https://tio.run/##PY@/TgMxDMZ3P4UfAIlnOP4WqUJFagckFvfq9gJpfCS5tofEAAt7F5hZGGBCDEV0anUDj3F9kcPtgGTFTvL558/XbG3ZNPXis168bh4/Ng/L3@e96er9qqnmdv22D/XPV7XU4379pP/VvP5@0XzZNEnqxZXjgCk59EwKQulPjBRBK0feyxRLKTyOOQQaMQZ2QXyAoefbgl1UGYUbHqDeQjTiAvTJY5/u4PS8hyagk4g9Z2aQYFYoIckIEn3MeCsLJsXUMnkFDXhonKJ4RuPcMsRM2zUIo6EIbSpGmXEjlIm2WrEpRTWe76YiuQFG5agAOq0OtsqcfeRZxI7n3EuqC4j/3xhOkgsYimxdws7SweHRMXTPki60d@gt5Q8) much more elegant program would work for 9 bytes. This outputs the pair `[a, b]`, where `a` and `b` are truthy values (`1`) or falsey values (`0`). The Footer in the TIO link runs the code over each test case. ## How it works ``` ŒlḲḢ€⁼ɗ,wɗ/«\ - Main link. Takes [phrase, word] on the left Œl - Convert both to lowercase ɗ - Group the previous 3 links into a dyad, f(phrase, word): ɗ - Group the previous 3 links into a dyad, g(phrase, word): Ḳ - Split the phrase on spaces Ḣ€ - Take the first characters of each word ⁼ - Does this equal the word? w - Index of word as a sublist of phrase, or 0 if not found , - Pair; Yield [g(phrase, word), index] / - Reduce [phrase, word] by f, yielding f(phrase, word) «\ - Scan by minimum ``` It is possible for `word` to be a sublist of `phrase`, but not an acronym (for example, `[GNU is not Unix, GNU]`. In this case, `f` returns `[0, 1]` which isn't a valid output. Additionally, `w` returns a non-zero integer, rather than `1/0`, any we want to turn this into `1`. Therefore, we scan `f`'s return by `«` (minimum), which transforms it: ``` [g(phrase, word), index] «\ = [g(phrase, word), min(g(phrase, word), index)] ``` This zeros out any trailing `1`s, and converts `[1, x]` (where `x > 0`) into `[1, 1]` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 107 bytes ``` $0=tolower($0){a="True"}b{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);$0=(b==f?a:c)"\n"(e?a:c)}!b{b=$1}f ``` [Try it online!](https://tio.run/##HYyxCsMgEED3fkV6OChmiGvl6NYv6NjlLnpLQwVNCFT8divdHjzeo/Pdu1pwT1s6Y9ZqMZUQnvmI0LhKynpFeNBWInhlbfDRIiOqYARlKgeXfVRhdrMzfoz0kHKn22rg9QEd/9iuXBmVa9K7pHRhyhPT9wc "AWK – Try It Online") Here's a different take using GAWK... The code defines four conditions with associated code blocks. The order they are evaluated when each line is read in matters in this case, to save a couple of characters. The first condition, ``` $0=tolower($0) ``` is always true given the possible inputs. The check is really unimportant here, the side effect of translating the input line to lowercase it what we care about. The code run just sets variable `a` to the string `True` to shorten the code. ``` {a="True"} ``` The second condition, ``` b ``` is true only for the second input line, since `b` isn't set until the first line is processes. So it's essentially a shortcut for `NR>1`. ``` {for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);e=e?a:c;$0=(b==f?a:c)"\n"e} ``` The code block is two statement, first a `for` loop that processes each word in the input stream. The top of loop statement, ``` c="False" ``` is just setting up `c` as a shortcut for `False` to save characters. Putting here saves a character, since the `;` is already there. The "should I iterate" test, ``` $++d ``` sets `d` to the current word and stops when we run off the end of the line. And the bottom of the loop statement, ``` e+=b==$d ``` increments `e` everytime the current word matches the acronym from the first line (which is in `b`). Finally, the body of the loop appends the first character of the current word to `f`, which will end up being the acronym associated with the line. ``` f=f substr($d,1,1) ``` Once the loop is done, the output `$0` is set by concatenating two ternary. ``` $0=(b==f?a:c)"\n"(e?a:c) ``` The `(b==f?a:c)` part is `True` or `False` depending on whether or not the provided and constructed acronyms match. And the second part, ``` (e?a:c) ``` is `True` or `False` based on how many words in the second line matched the acronym from the first line. The third condition applied to each line just sets `b` to the value of the first line, setting `b` only if is hasn't been set already. ``` !b{b=$1} ``` And the last condition is true only after the second line has been processed. ``` f ``` It uses the default action for unspecified code block. So it's a shortcut for `NR>1{print$0}`. One caveat: I'm not 100% clear on the rules of the contest. If the second condition depends on the first, meaning only valid acronyms can be recursive acronyms, this slightly longer version is necessary. ``` $0=tolower($0){a="True"}b{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);$0=(g?a:c)"\n"(e&&(g=b==f)?a:c)}!b{b=$1}f ``` ]
[Question] [ ### Introduction [![code golf explanation](https://i.stack.imgur.com/5kSwA.png)](https://i.stack.imgur.com/5kSwA.png) Imagine that line of chars is in fact two rows. **Upper row - dots - represents hours** (24 hour system), while **lower - commas - represents minutes**. One character can represent hour, minute or **both** - whenever it's possible. At first probably you'd have to convert minutes since midnight to *hours and minutes*. The result is the string showing current time in "dot format". The dot count (**apostrophe counts here as a dot and will be called so!**) is the hour count since midnight and comma count is minutes count. I'll show a few examples to make it clear. * (Remark) hh:mm - `result` * (Only hours) 05:00 - `'''''` * (Only minutes) 00:08 - `,,,,,,,,` * (hours < minutes) 03:07 - `;;;,,,,` * (hours > minutes) 08:02 - `;;''''''` * (hours = minutes) 07:07 - `;;;;;;;` * (the start of the day) 00:00 - (*empty result*) Notice that *"both" character* can be used max 23 times - for 23:xx, where xx is 23 or more. ### Symbols If character **have to** (see rule 5.) be escaped in your language, you could changed it to one of alternatives. If said alternatives aren't enough, you may use other symbols - but keep it reasonable. I just don't want escaping to be a barrier. * `;` (semicolon) - marker for both hours and minutes (alt: `:`) * `'` (apostrophe) - marker for hours (alt: `'``°`) * `,` (comma) - marker for minutes (alt: `.`) ### Additional rules 1. The code with the least amount of bytes wins! 2. You have to use *both symbol* whenever it's possible. For 02:04 the result can't be `'',,,,`, nor `;',,,`. It have to be `;;,,` 3. Input - can be script/app parameter, user input (like readline) or variable inside code 3.1. If the variable inside code is used, then its lenght have to be the longest possible. It's `1439` (23:59), so it would look like `t=1439` 4. The common part which is symbolized by *"both" character* (12 in 12:05, 3 in 03:10) must be placed on the beginning of the string 5. Symbols can be replaced to alternatives only if they would have to be escaped in your code. 6. Input is given in minutes after **00:00**. You can assume that this is a non-negative integer. ### Test cases ``` Input: 300 Output: ''''' Input: 8 Output: ,,,,,,,, Input: 187 Output: ;;;,,,, Input: 482 Output: ;;'''''' Input: 427 Output: ;;;;;;; Input: 0 Output: (empty) ``` [Answer] # Pyth, 19 bytes ``` :.iF*V.DQ60J"',"J\; ``` [Test suite](https://pyth.herokuapp.com/?code=%3A.iF%2aV.DQ60J%22%27%2C%22J%5C%3B&input=300&test_suite=1&test_suite_input=300%0A8%0A187%0A482%0A427%0A0&debug=0) ``` :.iF*V.DQ60J"',"J\; .DQ60 Divmod the input by 60, giving [hours, minutes]. J"'," Set J equal to the string "',". *V Perform vectorized multiplication, giving H "'" and M ','. .iF Interleave the two lists into a single string. : J\; Perform a substitution, replacing J with ';'. ``` [Answer] ## CJam, ~~22~~ ~~20~~ 19 bytes Takes input from STDIN: ``` ri60md]',`.*:.{;K+} ``` [Test it here.](http://cjam.aditsu.net/#code=ri60md%5D'%2C%60.*%3A.%7B%3BK%2B%7D&input=252) ### Explanation ``` ri e# Read input and convert to integer. 60md e# Divmod 60, pushes hours H and minutes M on the stack. ] e# Wrap in an array. ',` e# Push the string representation of the comma character which is "',". .* e# Repeat apostrophe H times and comma M times. :.{ e# Apply this block between every pair of characters. This will only applied to e# first N characters where N = min(hours,minutes). The others will remain e# untouched. So we want the block to turn that pair into a semicolon... ; e# Discard the comma. K+ e# Add 20 to the apostrophe to turn it into a semicolon. } ``` It was really lucky how well things worked together here, in particular the assignment of hours to `'` and minutes to `,` such that the order of hours and minutes on the stack matched up with the string representation of the character. This is the only 3-byte block I've found so far. There were tons of 4-character solutions though: ``` {;;';} {';\?} {^'0+} {^'F-} {-'@+} {-'6-} ... ``` [Answer] # GNU Sed, 37 Score includes +1 for `-E` option to sed. I wasn't particularly impressed with the golfiness of my [bash answer](https://codegolf.stackexchange.com/a/67453/11259), so I thought I'd try with sed for the fun. Input is in unary, as per [this meta-answer](https://codegolf.meta.stackexchange.com/a/5349/11259). ``` y/1/,/ # Convert unary 1's to commas (minutes) s/,{60}/'/g # divmod by 60. "'" are hours : # unnamed label s/(.*)',/;\1/ # replace an apostrophe and comma with a semicolon t # jump back to unnamed label until no more replacements ``` [Try it online](https://ideone.com/qzbE3f) [Answer] ## Python 2, 56 bytes ``` def g(t):d=t%60-t/60;print(t/60*";")[:t%60]+","*d+"'"*-d ``` A function that prints (one char shorter than `t=input();`). The method is similar to [Loovjo's](https://codegolf.stackexchange.com/a/67462/20260). The number of `,` is the different between minutes and hours, with an implicit minimim of 0. For `'`, it's the negation. For `;`, computes the `min` implicitly by taking as many `;` as hours, then truncating to the number of minutes. It saves chars to save `d`, but not the number of hours and minutes here. The analogue with lambda was two chars longer (58), so the variable assignments are worth it. ``` lambda t:(t%60*";")[:t/60]+","*(t%60-t/60)+"'"*(t/60-t%60) ``` Processing the input directly didn't save chars either (58): ``` h,m=divmod(input(),60);d=m-h;print(";"*m)[:h]+","*d+"'"*-d ``` Another strategy with slicing, much longer (64): ``` def g(t):m=t%60;h=t/60;return(";"*m)[:h]+(","*m)[h:]+("'"*h)[m:] ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 24 Trivial port of [my sed answer](https://codegolf.stackexchange.com/a/67455/11259). Input is in unary, as per [this meta-answer](http://meta.codegolf.stackexchange.com/a/5349/11259). ``` 1 , ,{60} ' +`(.*)', ;$1 ``` [Try it online.](http://retina.tryitonline.net/#code=MQosCix7NjB9CicKK2AoLiopJywKOyQx&input=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE) [Answer] # Pure Bash (no external utilities), 103 ``` p()(printf -vt %$2s;printf "${t// /$1}") p \; $[h=$1/60,m=$1%60,m>h?c=m-h,h:m] p , $c p \' $[m<h?h-m:0] ``` Thanks to @F.Hauri for saving 2 bytes. [Answer] # C, 119 bytes ``` #define p(a,b) while(a--)putchar(b); main(h,m,n){scanf("%d",&m);h=m/60;m%=60;n=h<m?h:m;h-=n;m-=n;p(n,59)p(h,39)p(m,44)} ``` Detailed ``` // macro: print b, a times #define p(a,b) while(a--)putchar(b) int main(void) { int h,m,n; scanf("%d",&m); // read input h=m/60;m%=60; // get hours:minutes n=h<m?h:m; // get common count h-=n;m-=n; // get remaining hours:minutes p(n,59); // print common p(h,39); // print remaining hours p(m,44); // print remaining minutes return 0; } ``` [Answer] # Haskell, ~~68~~ 66 Bytes ``` g(h,m)=id=<<zipWith replicate[min h m,h-m,m-h]";'," g.(`divMod`60) ``` Usage example: ``` (g.(`divMod`60)) 482 ``` The clever bit here is that `replicate` will return the empty string if the length given is negative or zero so I can apply it to both differences and only the positive one will show up. The first part is easy, since the number of semicolons is just the minimum of the two. Then `zipWith` applies the function to the corresponding items. EDIT: Realized I was using the wrong char for minutes EDIT 2: Saved 2 bytes thanks to @Laikoni [Answer] # JavaScript (ES6) 69 ``` m=>";".repeat((h=m/60|0)>(m%=60)?m:h)+",'"[h>m|0].repeat(h>m?h-m:m-h) ``` [Answer] # Powershell, ~~99~~ 85 bytes `param($n)";"*(($m=$n%60),($h=$n/60))[($b=$m-gt$h)]+"'"*(($h-$m)*!$b)+","*(($m-$h)*$b)` Using [Loovjo's](https://codegolf.stackexchange.com/a/67462/20260) method, this is my powershell implementation. ungolfed ``` param($n) # set the number of minutes and hours, and a boolean which one is bigger # and also output the correct number of ;s ";"*(($m=$n%60),($h=$n/60))[($b=$m-gt$h)]+ # add the difference between h and m as 's but only if h > m "'"*(($h-$m)*!$b)+ # add the difference between m and h as ,s but only if m > h ","*(($m-$h)*$b) ``` Saved 14 bytes thanks to AdmBorkBork [Answer] # Python 3, 98 bytes ``` d=int(input());m=d%60;h=int((d-m)/60) if m>=h:print(";"*h+","*(m-h)) else:print(";"*(m)+"'"*(h-m)) ``` Probably not the best answer, but it was a lot of fun! [Answer] # Python 2, 61 bytes ``` t=input();m,h=t%60,t/60 print";"*min(h,m)+","*(m-h)+"'"*(h-m) ``` Explaination: ``` t=input(); # Read input m, t%60, # Do a divmod, h = div, m = mod h= t/60 print";"*min(h,m)+ # Print the minimum of the h and m, but in ";"s ","*(m-h)+ # Print (m-h) ","s (if m-h is negative, print nothing) "'"*(h-m) # Print (h-m) "'"s (if h-m is negative, print nothing) ``` [Answer] # PHP, 81 bytes I went for the variable input as it is shorter than reading from `STDIN` or taking command line arguments. ``` for($_=1439;$i<max($h=0|$_/60,$m=$_%60);++$i)echo$i<$h?$i<min($h,$m)?';':"'":","; ``` [Answer] # JavaScript (ES6), ~~77~~ 71 bytes ``` x=>';'[r='repeat'](y=Math.min(h=x/60|0,m=x%60))+"'"[r](h-y)+','[r](m-y) ``` [Answer] # Perl 6, ~~103~~ ~~101~~ ~~98~~ ~~97~~ 69 bytes ``` $_=get;say ";"x min($!=($_-$_%60)/60,$_=$_%60)~"'"x $!-$_~","x $_-$!; ``` ~~Outputs several arrays, but fuck it,~~ enjoy. As usual, any golfing oppertunities are appericated. Edit: -2 bytes: got brave and removed some casts. Edit2: -3 bytes by removing the arrays. Edit3: -1 byte to print in right format, using "lambdas" and removing parantheses. Edit4: (sorry guys) abusing that hours - minutes should return 0 and the opposite. Removed if statements. Then removing brackets, then realising i didnt need the lambda at all. -28 bytes :) Woah im getting better at this. [Answer] # C, 141 bytes ``` main(h,m){scanf("%d",&m);h=(m/60)%24;m%=60;while(h||m){if(h&&m){printf(";");h--;m--;}else if(h&&!m){printf("'");h--;}else{printf(",");m--;}}} ``` [Answer] # Gema, 119 characters ``` <D>=@set{h;@div{$0;60}}@set{m;@mod{$0;60}}@repeat{@cmpn{$h;$m;$h;$h;$m};\;}@repeat{@sub{$h;$m};'}@repeat{@sub{$m;$h};,} ``` Sample run: ``` bash-4.3$ gema '<D>=@set{h;@div{$0;60}}@set{m;@mod{$0;60}}@repeat{@cmpn{$h;$m;$h;$h;$m};\;}@repeat{@sub{$h;$m};`}@repeat{@sub{$m;$h};,}' <<< '252' ;;;;,,,,,,,, ``` [Answer] ## Matlab: 89 bytes ``` i=input('');m=mod(i,60);h=(i-m)/60;[repmat(';',1,min(h,m)),repmat(39+5*(m>h),1,abs(h-m))] ``` Test: ``` 310 ans = ;;;;;,,,,, ``` [Answer] # SmileBASIC, 59 bytes ``` INPUT M H%=M/60M=M-H%*60?";"*MIN(H%,M);",'"[M<H%]*ABS(H%-M) ``` Explained: ``` INPUT MINUTES 'input HOURS=MINUTES DIV 60 'separate the hours and minutes MINUTES=MINUTES MOD 60 PRINT ";"*MIN(HOURS,MINUTES); 'print ;s for all positions with both PRINT ",'"[MINUTES<HOURS]*ABS(HOURS-MINUTES) 'print extra ' or , ``` It looks pretty terrible, since the bottom part of `;` is not even the same as `,` in [SmileBASIC's font](http://12Me21.github.io/syntax/linkc#;,%27) [Answer] # PHP, 81 bytes some more solutions: ``` echo($r=str_repeat)(";",min($h=$argn/60,$m=$argn%60)),$r(",`"[$h>$m],abs($h-$m)); // or echo($p=str_pad)($p("",min($h=$argn/60,$m=$argn%60),";"),max($h,$m),",`"[$h>$m]); ``` Run with `echo <time> | php -R '<code>'`. ``` <?=($r=str_repeat)(";",min($h=($_=1439)/60,$m=$_%60)),$r(",`"[$h>$m],abs($h-$m)); // or <?=($r=str_repeat)(";",min($h=.1/6*$_=1439,$m=$_%60)),$r(",`"[$h>$m],abs($h-$m)); // or <?=str_pad(str_pad("",min($h=($_=1439)/60,$m=$_%60),";"),max($h,$m),",`"[$h>$m]); ``` Replace `1439` with input, save to file, run. [Answer] # Ruby, 50 characters ``` ->t{(?;*h=t/60)[0,m=t%60]+",',"[0<=>m-=h]*m.abs} ``` Thanks to: * [G B](https://codegolf.stackexchange.com/users/18535/g-b) for + reminding me that I can't take more characters from a string than it has (-1 character) + reorganizing my calculation (-1 character) Waited so long to use `Numeric.divmod`, just to realize that its horribly long. Sample run: ``` 2.1.5 :001 > puts ->t{(?;*h=t/60)[0,m=t%60]+",',"[0<=>m-=h]*m.abs}[252] ;;;;,,,,,,,, ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` 60‰vy„'.Nè×}‚.BøJ„'.';:ðK ``` [Try it online!](https://tio.run/nexus/05ab1e#@29m8KhhQ1nlo4Z56np@h1ccnl77qGGWntPhHV5gIXVrq8MbvP//NzQxMAQA "05AB1E – TIO Nexus") `60‰vy„'.Nè×}` can definitely be shortened, I just couldn't figure it out, and doubt I'll be able to shave off 7 bytes to win with this approach unless there's a vectored version of `×`. --- Example (With input equal to 63): ``` 60‰ # Divmod by 60. # STACK: [[1,3]] vy } # For each element (probably don't need the loop)... # STACK: [] „'.Nè× # Push n apostrophe's for hours, periods for minutes. # STACK: ["'","..."] ‚ # Group a and b. # STACK: [["'","..."]] .B # Boxify. # STACK: [["' ","..."]] ø # Zip it (Transpose). # STACK: [["'."," ."," ."] J # Join stack. # STACK: ["'. . ."] „'.';: # Replace runs of "'." with ";". # STACK: ["; . ."] ðK # Remove all spaces. # OUTPUT: ;.. ``` --- `D60÷''×s60%'.ׂ.BøJ„'.';:ðK` was my original version, but that's even MORE costly than divmod. `60‰WDµ';ˆ¼}-¬0Qi'.ë''}ZׯìJ` yet another method I tried... [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 95 bytes ``` [60~sdsp39sj]sd[60~spsd44sj]se?ddd60~<d60~!<e[59Plp1-spld1-dsd0<y]syld0<y[ljPlp1-dsp0<y]sylp0<y ``` [Try it online!](https://tio.run/nexus/dc#@x9tZlBXnFJcYGxZnBVbnALmFhSnmJiAuKn2KSkpQBEbEKFokxptahmQU2CoW1yQk2Kom1KcYmBTGVtcmQOio3OywHJAs6CiIPr/fxMLo695@brJickZqQA "dc – TIO Nexus") [Answer] # Java 8, ~~101~~ ~~99~~ 86 bytes ``` n->{String r="";for(int m=n%60,h=n/60;h>0|m>0;r+=h--*m-->0?";":h<0?",":"'");return r;} ``` **Explanation:** [Try it here.](https://tio.run/##hZBNTsMwEIX3PcXIUkVM6@D@qIQahxPQDcuKhXFd4hJPIsephErOHtySLcrGI897M9/TnNRZsao2eDp89bpUTQOvyuJlAmAxGH9U2sDu@gV4C97iJ@gkKoBUxGY3iU8TVLAadoAgoUeWXwanl4SIY@VvA07idMPnhcSHDRdFzn9czoWfyYKxe8dYzl@IINviOdY52ZI7QoU3ofUIXnS9uJLq9qOMpAF4ruwBXEyb/PH274oOSb@bYFxatSGtoxJKTDDVyYpzeov9ryMb0RfZ44hjnS3HHMuxHWMpF@vVEx3u3/W/) ``` n->{ // Method with integer parameter and String return-type String r=""; // Result-String (starting empty) for(int m=n%60,h=n/60; // Get the minutes and hours from the input integer h>0|m>0; // Loop as long as either the hours or minutes is above 0 r+= // Append the result-String with: h--*m-->0? // If both hours and minutes are above 0 // (and decrease both after this check): ";" // Use ";" :h<0? // Else-if only minutes is above 0 (hours is below 0) "," // Use "," : // Else: "'" // Use "'" ); // End loop return r; // Return the result } // End of method ``` [Answer] # [///](https://esolangs.org/wiki////), 49 bytes ``` /x/1111111111//xxxxxx/o//oo1/o1o//o1/;//o/'//1/,/ ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X79C3xAO9PUrwEA/X18/P99QP98QxDDUtwaS@ur6@ob6Ovr//wMA "/// – Try It Online") The first two substitutions, `/x/1111111111//xxxxxx/o/`, replace sequences of 60 `1`s with an `o`. `/oo1/o1o/` interweaves the `1`s into the `o`s, which are next to each other. Ex. `oooooo1111111111 -> o1o1o1o1o1o11111` This pairs each o, which is one hour, with one 1, which is minute. This also pushes the `1`s to the left, so whichever one is greater is left at the right. `o1/;/` replaces each pair with a ; `/o/'/ /1/1/` and this converts the leftovers to `:`s or `'`s [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` d60ؽẋ"Sị“',; ``` [Try it online!](https://tio.run/##AT4Awf9qZWxsef//ZDYww5jCveG6iyJT4buL4oCcJyw7/@KAnQrDh@KCrFn//1szMDAsOCwxODcsNDgyLDQyNywwXQ "Jelly – Try It Online") ## Explanation ``` d60ؽẋ"Sị“',; Main monadic link d60 Divmod by 60 " Zipmap ؽ [1, 2] with that ẋ using the “repeat n times” operator S Sum ị Index into “',; "',;" ``` ]
[Question] [ Write a program or function which receives as input a string representing a Welsh word (UTF-8 unless otherwise specified by you). The following are all *single letters* in Welsh: > > a, b, c, ch, d, dd, e, f, ff, g, ng, h, i, j, l, ll, m, n, o, p, ph, r, rh, s, t, th, u, w, y > > > To quote [Wikipedia](https://en.wikipedia.org/wiki/Welsh_orthography), > > While the digraphs *ch*, *dd*, *ff*, *ng*, *ll*, *ph*, *rh*, *th* are each written with two symbols, they are all considered to be single letters. This means, for example that Llanelli (a town in South Wales) is considered to have only six letters in Welsh, compared to eight letters in English. > > > These letters also exist in Welsh, though they are restricted to technical vocabulary borrowed from other languages: > > k, q, v, x, z > > > Letters with diacritics are not regarded as separate letters, but your function must accept them and be able to count them. Possible such letters are: > > â, ê, î, ô, û, ŷ, ŵ, á, é, í, ó, ú, ý, ẃ, ä, ë, ï, ö, ü, ÿ, ẅ, à, è, ì, ò, ù, ẁ > > > (This means that ASCII is not an acceptable input encoding, as it cannot encode these characters.) ### Notes: * This is code golf. * You do not have to account for words like *llongyfarch*, in which the *ng* is not a digraph, but two separate letters. This word has nine letters, but you can miscount it as eight. (If you *can* account for such words, that's kind of awesome, but outside the scope of this challenge.) * The input is guaranteed to have no whitespace (unless you prefer it with a single trailing newline (or something more esoteric), in which case that can be provided). There will certainly be no internal whitespace. ### Test cases: * Llandudno, 8 * Llanelli, 6 * Rhyl, 3 * Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch, 50 (really 51, but we'll count 50) * Tŷr, 3 * Cymru, 5 * Glyndŵr, 7 [Answer] # [Retina](http://github.com/mbuettner/retina), 23 bytes ``` i`[cprt]h|dd|ff|ng|ll|. ``` [Try it online!](http://retina.tryitonline.net/#code=aWBbY3BydF1ofGRkfGZmfG5nfGxsfC4&input=TmVzYQ) Even moar regex. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~24~~ ~~23~~ 21 bytes Code: ``` u•éÓœ°D¥M™ù>•30B2ô0:g ``` Explanation: ``` u # Convert the input to uppercase. •éÓœ°D¥M™ù>•30B # Compressed version of CHDDFFNGLLPHRHTH. It convert the text between the •'s from base 214 to base 10 and converts that to base 30. 2ô # Split into pieces of 2. 0: # Replace each element that also occurs in the input by 0. g # Get the length of the processed input. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=deKAosOpw5PFk8KwRMKlTeKEosO5PuKAojMwQjLDtDA6Zw&input=Umh5bA) [Answer] # JavaScript (ES6), 44 bytes ``` x=>x.match(/[cprt]h|dd|ff|ng|ll|./gi).length ``` The trivial answer may be the shortest. [Answer] # BASH 52 50 (sed + wc) 41 -9 thanks to Jordan ``` sed -r 's,dd|ff|ng|ll|[cprt]h,1,gi'|wc -m ``` If uppercase letter are required this needs an `i` at the end of the sed command. (I left it out because all of the "single letters" in the question are lowercase even though some examples aren't). [Answer] ## [Straw](https://github.com/tuxcrafting/straw), ~~30~~ ~~58~~ ~~35~~ 33 bytes ``` <((?i:[cprt]h|dd|ff|ng|ll|.))0/$> ``` Replace each occurence of the regex by `0`, and convert from unary to decimal. ~~Sadly, Straw can't pass flags to regexs.~~ I forget about the `?flags:` construct [Try it online!](http://straw.tryitonline.net/#code=KDwoKD9pOltjcHJ0XWh8ZGR8ZmZ8bmd8bGx8LikpMC8kPgo-KTcjKigmKTcjKiY&input=TGxhbmR1ZG5vCkxsYW5lbGxpClJoeWwKTGxhbmZhaXJwd2xsZ3d5bmd5bGxnb2dlcnljaHd5cm5kcm9id2xsbGxhbnR5c2lsaW9nb2dvZ29jaApUxbdyCkN5bXJ1CkdseW5kxbVy) (The added code is to verify all test cases) [Answer] # Python 3, 64 bytes ``` import re print(len(re.findall("[cprt]h|dd|ff|ng|ll|.",input()))) ``` Uses regex again [**Ideone it!**](https://ideone.com/NANtPk) [Answer] ## PowerShell v2+, ~~52~~ ~~50~~ 48 bytes ``` ($args[0]-replace'dd|ff|ng|ll|[prtc]h',0).length ``` Does a `-replace` on all the two-symbol-single-letter letters, changes 'em to `0` (done because changing to a non-numeral would require quotes), then gets the `.length` of the resultant string. ### Test cases ``` PS C:\Tools\Scripts\golfing> 'Llandudno','Llanelli','Rhyl','Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch','Tŷr','Cymru','Glyndŵr'|%{"$_ --> "+(.\how-long-is-a-welsh-word.ps1 $_)} Llandudno --> 8 Llanelli --> 6 Rhyl --> 3 Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch --> 50 Tŷr --> 3 Cymru --> 5 Glyndŵr --> 7 ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 31 bytes ``` Íã[cprt]hüddüffüngüllü./ Dé0@" ``` [Try it online](http://v.tryitonline.net/#code=w43Do1tjcHJ0XWjDvGRkw7xmZsO8bmfDvGxsw7wuLwEKRMOpMEAi&input=TGxhbmZhaXJwd2xsZ3d5bmd5bGxnb2dlcnljaHd5cm5kcm9id2xsbGxhbnR5c2lsaW9nb2dvZ29jaA), or [Verify all test cases!](http://v.tryitonline.net/#code=w43Do1tjcHJ0XWjDvGRkw7xmZsO8bmfDvGxsw7wuLwEKw45Ew6kwQCI&input=TGxhbmR1ZG5vCkxsYW5lbGxpClJoeWwKTGxhbmZhaXJwd2xsZ3d5bmd5bGxnb2dlcnljaHd5cm5kcm9id2xsbGxhbnR5c2lsaW9nb2dvZ29jaApUxbdyCkN5bXJ1CkdseW5kxbVy) This contains some unprintable characters, so here is a hexdump: ``` 0000000: cde3 5b63 7072 745d 68fc 6464 fc66 66fc ..[cprt]h.dd.ff. 0000010: 6e67 fc6c 6cfc 2e2f 010a 44e9 3040 22 ng.ll../..D.0@" ``` [Answer] # PHP , 56 Bytes ``` <?=preg_match_all("#[cprt]h|dd|ff|ll|ng|.#iu",$argv[1]); ``` [Answer] # Java 7, ~~156~~ 73 bytes Loads of bytes saved thanks to *@OlivierGrégoire*. ``` int c(String s){return s.replaceAll("[cprt]h|dd|ff|ng|ll","*").length();} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/wxWzFF) ``` class M{ static int c(String s){ return s.replaceAll("[cprt]h|dd|ff|ng|ll", "*").length(); } public static void main(String[] a){ System.out.println(c("llandudno")); System.out.println(c("llanelli")); System.out.println(c("rhyl")); System.out.println(c("llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch")); System.out.println(c("tŷr")); System.out.println(c("cymru")); System.out.println(c("glyndŵr")); } } ``` **Output:** ``` 8 6 3 50 3 5 7 ``` [Answer] ## R, 54 bytes Very similar to the other answers. Matches any of the two character letters and replaces them with `@` and subsequently counts the number of characters. Reads input from stdin. Uses the option `ignore.case = TRUE` (third argument to `gsub`) to match both upper and lowercase characters. ``` nchar(gsub("ch|dd|ff|ng|ll|ph|rh|th","@",scan(,""),T)) ``` **Bonus** Both `gsub` and `nchar` are vectorized which means that this also works on a character vector, e.g.: ``` v=c("Llandudno","Llanelli","Rhyl","Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch","Tŷr","Cymru","Glyndŵr") nchar(gsub("ch|dd|ff|ng|ll|ph|rh|th","@",v,T)) ``` produces: ``` [1] 8 6 3 50 3 5 7 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 36 bytes ``` +*.comb(/:i.|<[cprt]>h|dd|ff|ng|ll/) ``` [Try it online!](https://tio.run/##HYrNCoJAFIXX@RSXiNAC27VIa9OiTatoFyHmOD9wnZGrIRenx4qewOcyi7M43@E7dUm4HSuGpYT9uF7Fhase4WZnYp/eipra@0F7IbyU3iqPuInGJJCOID1jbsVTWAc/KhENXDTjf8ncUN0hqo6t4qmdKokL3TFZQe4xKZxuLTcGjVP/FBquw4fgyBU94YRsxfCmA/TBrMkZ5osMehkusug1T4LX@AU "Perl 6 – Try It Online") [Answer] # XQuery, 77 bytes ``` declare variable$s external;count(tokenize($s,'[cprt]h|ff|dd|ll|ng|.','i'))-1 ``` [Answer] # tcl, 71 ``` proc L s {string le [regsub -all -nocase ch|dd|ff|ng|ll|ph|rh|th $s @]} ``` # [demo](http://rextester.com/APD41427) [Answer] # [Perl 5](https://www.perl.org/), 35 + 1 (`-p`) = 36 bytes ``` s/[cprt]h|dd|ff|ng|ll/a/gi;$_=y///c ``` [Try it online!](https://tio.run/##HYpBCgMhDAA/02vJqafSH/QHpRSrawyERKIgAd9eV8oc5jBTD@PbWg1esVp/l5nSzHkKTmYIgHS/fB4OAHGtJwfJgawOZhwu6NuKh3ksw02S6Xcn3lv3RkyKf2L5ae2k0ta1ng "Perl 5 – Try It Online") ]
[Question] [ ![cantor normal form](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Omega-exp-omega-labeled.svg/500px-Omega-exp-omega-labeled.svg.png "Round and round it goes, and this is only the beginning") The [ordinal number system](http://en.wikipedia.org/wiki/Ordinal_number) is a system with infinite numbers. A lot of infinite numbers. So many infinite numbers that it literally does not have an infinity to represent its own infiniteness. The image above gives a little idea of how they work. An ordinal number ([Von Neumann construction](http://en.wikipedia.org/wiki/Ordinal_number)) is a set of previous ordinals. For example, 0 is the empty set, 1 is the set {0}, 2 is the set {0, 1} and etc. Then we get to ω, which is {0, 1, 2, 3 ...}. ω+1 is {0, 1, 2, 3 ... ω}, ω times two is {0, 1, 2 ... ω, ω + 1, ω + 2...} and you just keep going like that. Your program will output a set of ordinals, such {0, 1, 4}. Your **score** will then be the least ordinal more than all the ordinal in your set. For {0, 1, 4} the score would be 5. For {0, 1, 2 ...}, the score would be ω. How do you output your ordinals you ask. Code of course. Namely, your program will output a potentially infinite list of other programs, in quotes, one on each line (use the literal string "\n" to represent new lines). A program corresponds to its score as indicated above. For example, if you output ``` "A" "B" "C" ``` where A, B, and C are themselves valid answers and have scores {0, 1, 4}, the score of your program would be 5. Note that A, B, and C, have to be full programs, not fragments. Based on the above rules, a program that outputs nothing has a score of 0 (the least ordinal greater than all {} is 0). Also, remember a set cannot contain itself, via the [axiom of foundation](http://en.wikipedia.org/wiki/Axiom_of_regularity). Namely, every set (and therefore ordinal) has a path down to zero. This means the a full-quine would be invalid as its not a set. Also, no program is allowed to access outside resources (its own file, the internet etc...). Also, when you list your score, put the [cantor normal form](http://en.wikipedia.org/wiki/Ordinal_arithmetic#Cantor_normal_form) of the score alongside it if it isn't in cantor normal form already, if you can (if not, someone else can). After taking all the above into account, the actual answer you post must be under 1,000,000 bytes (not counting comments). (This upper bound will likely only come into play for automatically generated code). Also, you get to increment your score for each byte you don't use (since we are dealing with infinities, this will probably only come into account when ordinals are very close or the same). Again, this paragraph only applies to the posted answer, not the generated ones, or the ones the generated ones generate, and so on. This has the quine tag, because it may be helpful to generate at least part of the sources own code, for use in making large ordinals. It is by no means required though (for example, a submission with score 5 would probably not need its own source code). For a worked out and annotated example, see [here](https://codegolf.stackexchange.com/a/48932/16842). [Answer] ## Haskell: ψ(ΩΩω) + 999672 points ``` main=print$f++shows f"$iterate(Z:@)Z";f="data N=Z|N:@N deriving Show;r=repeat;s Z=[];s(a:@Z)=r a;s(Z:@b)=($u b)<$>h b;s(a:@b)=do(f,c)<-h b`zip`s a;f<$>[c:@b,a]\nh=scanl(flip(.))id.t;t(Z:@Z)=r(:@Z);t(Z:@b)=((Z:@).)<$>t b;t(a:@b)=flip(:@).(:@b)<$>s a;u Z=Z;u(Z:@b)=u b;u(a:@_)=a;g f=mapM_$print.((f++shows f\"$s$\")++).show;main=g" ``` 329 bytes of code with ordinal [ψ(ΩΩω)](https://en.wikipedia.org/wiki/Small_Veblen_ordinal) + 1. Uses a [tree-based representation](http://www.madore.org/~david/math/ordtrees.pdf) of ordinals discovered by [Jervell (2005)](https://dx.doi.org/10.1007%2F11494645_26). The tree with children *α*, *β*, …, *γ* is denoted `α :@ (β :@ (… :@ (γ :@ Z)…))`. This left-to-right order agrees with Jervell, although note that Madore flips it right-to-left. ## Haskell: Γ0 + 999777 points ``` main=print$f++shows f"$iterate((:[]).T)[]";f="data T=T[T]deriving(Eq,Ord,Show);r=reverse;s[]=[];s(T b:c)=(++c)<$>scanl(++)[](b>>cycle[fst(span(>=T b)c)++[T$r d]|d<-s$r b]);g f=mapM_$print.((f++shows f\"$s$\")++).show;main=g" ``` 224 bytes of code with ordinal [Γ0](https://en.wikipedia.org/wiki/Feferman%E2%80%93Sch%C3%BCtte_ordinal) + 1. This is based on a generalization of Beklemishev’s Worm to ordinal-valued elements, which are themselves recursively represented by worms. ## Haskell: ε0 + 999853 points ``` main=print$f++shows f"$map(:[])[0..]";f="s[]=[];s(0:a)=[a];s(a:b)=b:s(a:fst(span(>=a)b)++a-1:b);g f=mapM_$print.((f++shows f\"$s$\")++).show;main=g" ``` 148 bytes of code with ordinal [ε0](https://en.wikipedia.org/wiki/Epsilon_numbers_(mathematics)) + 1. This is based on [Beklemishev’s Worm](http://www.mi.ras.ru/~bekl/Problems/gpa5.html). The list ``` map(+1)α ++ [0] ++ map(+1)β ++ [0] ++ ⋯ ++ [0] ++ map(+1)γ ``` represents the ordinal (ω*γ* + ⋯ + ω*β* + ω*α*) − 1. So the second-level outputs `[0]`, `[1]`, `[2]`, `[3]`, … represent 1, ω, ωω, ωωω, …, the first-level output represents ε0, and the initial program represents ε0 + 1. ## Haskell: ε0 + 999807 points ``` main=print$f++shows f"$iterate(:@Z)Z";f="data N=Z|N:@N deriving Show;s Z=[];s(Z:@b)=repeat b;s(a:@Z)=scanl(flip(:@))Z$s a;s(a:@b)=(a:@)<$>s b;g f=mapM_$print.((f++shows f\"$s$\")++).show;main=g" ``` 194 bytes of code with ordinal ε0 + 1. `Z` represents 0, and we can prove by transfinite induction on *α*, then on *β*, that `α :@ β` ≥ ω*α* + *β*. So there are second-level outputs at least as big as any tower ωω⋰ω, which means the first-level output is at least ε0 and the initial program is at least ε0 + 1. [Answer] # Ruby, ψ0(ψX(ψM+1(ΩM+1ΩM+1))(0)) + 999663 points Assuming I understand my program properly, my score is ψ0(ψX(ψM+1(ΩM+1ΩM+1))(0)) + 999663 points where **ψ** is an ordinal collapsing function, **X** is the chi function (Mahlo collapsing function), and **M** is the first Mahlo 'ordinal'. This program is an extension of the one I wrote on [Golf a number bigger than TREE(3)](https://codegolf.stackexchange.com/a/145882/58880) and ***utterly trumps*** all of the other solutions here for now. ``` z=->x,k{f=->a,n,b=a,q=n{c,d,e=a;!c ?q:a==c ?a-1:e==0||e&&d==0?c:e ?[[c,d,f[e,n,b,q]],f[d,n,b,q],c]:n<1?9:!d ?[f[b,n-1],c]:c==0?n:[t=[f[c,n],d],n,d==0?n:[f[d,n,b,t]]]};x==0??p:(w="\\"*k+"\"";y="";(0..1.0/0).map{|g|y+="x=#{f[x,g]};puts x==0??p:"+w+"#{z[f[x,g],k*2+1]}"+w+";"};y)};h=-1;(0..1.0/0).map{|i|puts "puts \"#{z[[i,h=[h,h,h]],1]}\""} ``` [Try it online!](https://tio.run/##ZY/RboMwDEV/pU2lqi2Gkb4tmceHhDyEBEqFFsFGVSjw7cyw9mmyZF9d@x4l37esn@cHhp8dVENB04CHDA006AcLDnI0cms3SSMMIk0TcpEjxuOY7/eORGJFvkmUWo4LlS9xaLQm7Z4arBb@gyfvYuvoslAZ@JCvtl0AXqgWybbgNThNKfe0X4xWaz3JbnGTWhzuyNKUnaqApYzJHqkd4ijiUfwWH6MvUw/jZewDZB3uhkJ1cKF0fWt/Ni8EC@4B2w0P9beF6nQOuJ5WW7JJ9sdJlhjyf9zruHLY2tMVoa5QoiqBir5NFHrUNM@/) # Ruby, ψ0(ψI(II)) + 999674 points ``` z=->x,k{f=->a,n,b=a{c,d,e,q=a;a==c ?a-1:e==0||d==0?(q ?[c]:c):e ?[[c,d,f[e,n,b],q],f[d,n,b],c,q]:[n<1?9:d&&c==0?[d]:d ?[f[c,n],d]:[f[b,n-1],f[c,n,b]],n,n]};x==0??p:(w="\\"*k+"\"";y="";(0..1.0/0).map{|g|y+="x=#{f[x,g]};puts(x==0??p:"+w+"#{z[f[x,g],k*2+1]}"+w+");"};y)};h=0;(0..1.0/0).map{|i|puts("puts(\"#{z[h=[h,h,h,0],1]}\")")} ``` [Try it online!](https://tio.run/##ZYxBboMwEEWvEjlShMNATXexO@UgxgtjQ6hQEbSNAgHOTsdEXVWWvv/Y897XrZy27YHJ@wjtXNNtoYMS7ezAQwUDWmUR3SG3SSYrRLEsnjKPhkOunZGOy4qaDuu1rgJsYDDU/bM7mqTu3rL8Iv3p5AKsvZGeqJqwzgBNVEvokiyAbgcNZWdWNQYg72V0R1YU7NzGrGBMTUgRiTTNUvEiePpp@3m5LlOMbMTjXOsRrkT3t5/v6E/B4nvMjvNDP3@hPb/GmVn3Z67Yqia@qgbFP@/HsnvYnsWuaFA3EI4wQI6CccbXbfsF) (warning: it won't do much, since clearly `(0..1.0/0).map{...}` cannot terminate. It's how I print infinitely many programs as well.) # Ruby, ψ0(ψI(0)) + 999697 points ``` z=->x,k{f=->a,n,b=a{c,d,e=a;a==c ?a-1:e==0||d==0?c:e ?[[c,d,f[e,n,b]],d-1,c]:[n<1?9:d&&c==0?[d]:d ?[f[c,n-1],d]:[f[b,n-=1],f[c,n,b]],n,n]};x==0??p:(w="\\"*k+"\"";y="";(0..1.0/0).map{|g|y+="x=#{f[x,g]};puts(x==0??p:"+w+"#{z[f[x,g],k*2+1]}"+w+");"};y)};h=0;(0..1.0/0).map{|i|h=[h];puts|i|puts("puts(\"#{z[hz[h=[h],1]}\")")} ``` [Try it online!](https://tio.run/##ZYzRboMwDEV/pXKlCophZG9L6vEhIQ@BQJnQEFpXFUr4dmYy7Wkv17J9zv26V/O2PSl9n7BfWp4WB6zILjU6bMgqS1QfCpsK2RDl3jvOopbNodB6Z1rd7IYx6FKBtZF6uIjiTbrTqd5R7Yx0DLdMD6lgjJFWV7wQb@Ec9AEHs6ppd4pRRg@CsoRzn0AJoGbiiPIsE1n@ksfZpx0Xf/VzQjDRcWn1hFe2x/v3LfqrgOSRwHF56t8v9ufXRJg1nGMFq5rjVXWU/@v98KEHQpahoiPdGWS7hBjiddt@AA) A more reasonable test program that implements `(0..5).map{...}` instead: ``` z=->x,k{f=->a,n,b=a{c,d,e=a;a==c ?a-1:e==0||d==0?c:e ?[[c,d,f[e,n,b]],d-1,c]:[n<1?9:d&&c==0?[d]:d ?[f[c,n-1],d]:[f[b,n-=1],f[c,n,b]],n,n]};x==0??p:(w="\\"*k+"\"";y="";(0..5).map{|g|y+="x=#{f[x,g]};puts(x==0??p:"+w+"#{z[f[x,g],k*2+1]}"+w+");"};y)};h=0;(0..5).map{|i|h=[h];puts("puts(\"#{z[h,1]}\")")} ``` [Try it online!](https://tio.run/##VYzRboMwDEV/pXKlCopBZNIemszjQ5I8BAJlQovQtqpQ4NuZodrDXq5l@5z7dSvHdX1Q@j5gNzU8HQYsyU0VeqzJKUdUHQqXClkT5fPsOYtK1odC641pdL0Z1qJPBVZW6vAmiov0p1O1odpb6RlumA6pYIyRRpe8EG/7edcDBruoYXOKXkZ3AmPg3CVgANRIHFGeZa9x9un6ab7OY0Iw0HFq9IBXNvvbz3f0p0NyT@A4PfTzi935JRF22c@xgkWN8aJayv91fswt6dY@m2BPs5e0yK6BGOJlXX8B) Unfortunately, even with `(1..1).map{...}`, you will find this program to be *extremely* memory intensive. I mean, the length of the output exceeds things like SCG(13). By using the simpler program, we may consider a few values: ``` a = value you want to enter in. z=->x,k{f=->a,n,b=a{c,d,e=a;a==c ?a-1:e==0||d==0?c:e ?[[c,d,f[e,n,b]],d-1,c]:[n<1?9:d&&c==0?[d]:d ?[f[c,n-1],d]:[f[b,n-=1],f[c,n,b]],n,n]};x==0??p:(w="\\"*k+"\"";y="x=#{f[x,k]};puts(x==0??p:"+w+"#{z[f[x,k],k*2+1]}"+w+");";y)};puts("puts(\"#{z[a,1]}\")") ``` [Try it online!](https://tio.run/##Nc7NCsIwDAfwu08hEcS5DKzgwc7YB2l76Nr1MijiB06nzz6zqpeEJL8/5HxrHuPoaDd7UnXssRsid4cJG3KDx4AtudoR@blylZAt0eb1ClyVl@1caT2ZqNspYS2GSqC3UqeDUHsZlks/UR2sDIwj61QJZkyibnggnvI6xxMm@677KaNOcnUnMAbWXQkGoH4Q9LQYouY3WZ1u18vqT6G8l7AYnvp7xW69LYV953VRc7b4BSBXk61DJgYKKMbxAw) It basically prints the same program repeatedly, in the format of: ``` x=...;puts(x==0??p:"..."); ``` where the initialized `x` records the ordinal the program is related to, and the `"..."` holds the programs after `x` has been reduced. If `x==0`, then it prints ``` p ``` which is a program that prints nothing with a score of zero, hence ``` x=0;puts(x==0??p:"p"); ``` has a score of 1, and ``` x=1;puts(x==0??p:"x=0;puts(x==0??p:\"p\");"); ``` has a score of 2, and ``` x=2;puts(x==0??p:"x=1;puts(x==0??p:\"x=0;puts(x==0??p:\\\"p\\\");\");"); ``` has a score of 3, etc., and my original program prints these programs in the format ``` puts("...") ``` where `...` are the programs listed above. My actual program actually prints these programs in the format ``` x=0;puts(x==0??p:"p;p;p;p;p;..."); ``` Infinitely many times, and for values such as `ω`, it does something akin to ``` x=ω;puts(x==0??p:"(x=0 program); (x=1 program); (x=2 program); ...") ``` And thus, the score of the program ``` x=(some_ordinal);puts(x==0??p:"...") ``` is `1+some_ordinal`, and the score of ``` puts("x=(some_ordinal);puts(x==0??p:\"...\")") ``` is `1+some_ordinal+1`, and the score of ``` z=->x,k{f=->a,n,b=a{c,d,e=a;a==c ?a-1:e==0||d==0?c:e ?[[c,d,f[e,n,b]],d-1,c]:[n<1?9:d&&c==0?[d]:d ?[f[c,n-1],d]:[f[b,n-=1],f[c,n,b]],n,n]};x==0??p:(w="\\"*k+"\"";y="";(0..1.0/0).map{|g|y+="x=#{f[x,g]};puts(x==0??p:"+w+"#{z[f[x,g],k*2+1]}"+w+");"};y)};puts("puts(\"#{z[some_ordinal,1]}\")") ``` is `1+some_ordinal+2`. --- # Explanation of ordinals: `f[a,n,b]` reduces an ordinal `a`. Every natural number reduces to the natural number below it. ``` f[k,n,b] = k-1 ``` `[c,0,e]` is the successor of `c`, and it always reduces down to `c`. ``` f[[c,0,e],n,b] = c ``` `[c,d,e]` is a backwards associative hyperoperation, are reduces as follows: ``` f[[c,d,0],n,b] = c f[[c,d,e],n,b] = [[c,d,f[e,n,b]],f[d,n,b],c] ``` `[0]` is the first infinite ordinal (equivalent to ω) and reduces as follows: ``` f[[0],0,b] = [9,0,0] f[[0],n,b] = [n,n,n] ``` `[c]` is the cth omega ordinal and reduces as follows: ``` f[[c],0,b] = [9,0,0] f[[c],n,b] = [[f[b,n-1,b],f[c,n,b]],n,n] Note the two-argument array here. ``` `[c,d]` is ψd(c) and reduces as follows: ``` f[[c,d],0,b] = [9,0,0] f[[0,d],n,b] = [[d],n,n] f[[c,d],n,b] = [[f[c,n,c],d],n,n] ``` `[c,d,e,0]` is basically the same as `[c,d,e]`, except it enumerates over the operation `[c]` instead of the successor operation. ``` f[[c,0,e,0],n,b] = [c] f[[c,d,0,0],n,b] = [c] f[[c,d,e,0],n,b] = [[c,d,f[e,n,b],0],f[d,n,b],c,0] ``` [Answer] # Java + Brainf\*\*\*, ω+999180 points A java program that produces infinitely many Brainf\*\*\* programs, of which each produces the last as output. Why? Because I can. Any improvements to the Brainf\*\*\* generation part are definitely welcome. ``` import java.io.*;import java.util.*;import static java.lang.System.*; class O{ static String F(String s){ String t="++++++++++++++++++++"; List<Character> c=Arrays.asList('+','-','.','<','>','[',']'); t+="[->++>++>++>+++>+++>++++>++++<<<<<<<]>+++>+++++>++++++>>++>+++++++++++>+++++++++++++"; for(int x=0,i=6;x<s.length();x++){ int d=c.indexOf(s.charAt(x)),k=d; while(d>i){d--;t+=">";} while(d<i){d++;t+="<";} t+=".";i=k; }return t; }; static void p(String a){ int i=48;while(i<a.length()){out.println(a.substring(i-48,i));i+=48;} out.println(a.substring(i-48));out.println(); } public static void main(String[]a) throws Exception{setOut(new PrintStream("o.txt"));String b="";while(true)p(b=F(b));} } ``` [Answer] ## Literate Haskell (GHC 7.10): ω² + 999686 points. This will serve as an example answer. Since its an example, it only makes sense to use [literate programming](http://en.wikipedia.org/wiki/Literate_programming). It won't score well though. The birdies will decrease my score, but oh well. First, let's make a helper function s. If x is an ordinal, s x = x+1, but we find unexpected uses of s. ``` > s x="main=putStrLn "++show x ``` The show function luckily does all the string sanitization for us. Its also worth making 0. Zero is not the successor of anything, but s"" will equal "main=putStrLn """, which equals 0. ``` > z=s"" ``` Now we will make a function that takes n, and returns ω\*n. ``` > o 0=z > o n=q++"\nmain=putStrLn$unlines$map show$iterate s$o "++show(n-1) ``` It works by making ω\*n by {ω\*(n-1), ω\*(n-1)+1, ω\*(n-1)+2, ...}. What is this q? Why, its the reason we have a [quine](/questions/tagged/quine "show questions tagged 'quine'") tag. q is the above helper functions so far. ``` > h x = x ++ show x > q = h "s x=\"main=putStrLn \"++show x\nz=s\"\"\no 0=z\no n=q++\"\\nmain=putStrLn$unlines$map show$iterate s$o \"++show(n-1)\nh x = x ++ show x\nq = h " ``` Note that only o n needs q, not any of its successors (s(o(n)), s(s(o(n)))), since they don't need the helper functions (except indirectly from o n.) Now we only have to output all of ω\*n for finite n. ``` > main=mapM(print.o)[0..] ``` There we go. ω^2 Having used only 314 code character, I claim a final bonus of 999686, giving me a final score of ω^2 + 999686, which is already in cantor's normal form. First four lines of output (0, ω, ω\*2, ω\*3): ``` "main=putStrLn \"\"" "s x=\"main=putStrLn \"++show x\nz=s\"\"\no 0=z\no n=q++\"\\nmain=putStrLn$unlines$map show$iterate s$o \"++show(n-1)\nh x = x ++ show x\nq = h \"s x=\\\"main=putStrLn \\\"++show x\\nz=s\\\"\\\"\\no 0=z\\no n=q++\\\"\\\\nmain=putStrLn$unlines$map show$iterate s$o \\\"++show(n-1)\\nh x = x ++ show x\\nq = h \"\nmain=putStrLn$unlines$map show$iterate s$o 0" "s x=\"main=putStrLn \"++show x\nz=s\"\"\no 0=z\no n=q++\"\\nmain=putStrLn$unlines$map show$iterate s$o \"++show(n-1)\nh x = x ++ show x\nq = h \"s x=\\\"main=putStrLn \\\"++show x\\nz=s\\\"\\\"\\no 0=z\\no n=q++\\\"\\\\nmain=putStrLn$unlines$map show$iterate s$o \\\"++show(n-1)\\nh x = x ++ show x\\nq = h \"\nmain=putStrLn$unlines$map show$iterate s$o 1" "s x=\"main=putStrLn \"++show x\nz=s\"\"\no 0=z\no n=q++\"\\nmain=putStrLn$unlines$map show$iterate s$o \"++show(n-1)\nh x = x ++ show x\nq = h \"s x=\\\"main=putStrLn \\\"++show x\\nz=s\\\"\\\"\\no 0=z\\no n=q++\\\"\\\\nmain=putStrLn$unlines$map show$iterate s$o \\\"++show(n-1)\\nh x = x ++ show x\\nq = h \"\nmain=putStrLn$unlines$map show$iterate s$o 2" ``` [Answer] # GolfScript, ε₀+1 + 999537 points ``` {{ {"{"lib`+"}:lib~~"@++"~"+p}:output; {{}}:nothing; {{1{).2$`+output 1}do}}:list; {{\.(`2$`+" iter"+@`if output}}:iter; {{1${@`@(2$`{rep~}+++\}{;;}if~}}:rep; {\`\+}:combine; {{\@@~}}:swap; {{1${1$(1$`{rangemap~}+[+@@[\\]]{~}/+}{;;}if}}:rangemap; {`{}+}:wrap; }}:lib~~ nothing {iter combine list~} {rep combine} {~swap combine combine} rep combine swap combine combine {~list~} combine rangemap {~~} combine combine swap combine combine swap combine combine list~ ``` It can probably be better, but I became too lazy to debug and prove larger ordinals. ### Smaller ordinals ``` #ω^ω^ω #nothing {iter combine list~} {rep combine swap combine combine list~} {rep combine swap combine combine swap combine combine list~} rep combine swap combine combine swap combine combine swap combine combine list~ #ω^ω^2 #nothing {iter combine list~} { {rep combine swap combine combine list~} rep combine swap combine combine swap combine combine list~} rep combine swap combine combine swap combine combine list~ #ω^nω #nothing {iter combine list~} 2 { {rep combine swap combine combine list~} rep combine swap combine combine swap combine combine list~} rep~ #ω^ω #nothing {iter combine list~} {rep combine swap combine combine list~} rep combine swap combine combine swap combine combine list~ #ω^n #nothing {iter combine list~} 3 {rep combine swap combine combine list~} rep~ #ω^3 #nothing {{iter combine list~} rep combine swap combine combine list~} rep combine swap combine combine list~ #ω^2 #nothing {iter combine list~} rep combine swap combine combine list~ #nω #nothing 3 {iter combine list~} rep~ #2ω #nothing iter combine list combine iter combine list~ #ω #nothing iter combine list~ #finite #2 nothing iter~ ``` [Answer] # Javascript (Nashorn), ω2+999807 points **Nashorn** is the Javascript engine which comes built into Java. This may also work in Rhino, but I haven't tested it in that yet. ``` c="(b=function(a){print(a?\"(b=\"+b+\")(\"+(a-1)+\")\":\"c=\\\"(b=function(a){print(a?'(b='+b+')'+'('+(a-1)+')':'')})(\\\";a=0;while(++a)print(c+a+\\\")\\\")\")})(";a=0;while(++a)print(c+a+")") ``` ]
[Question] [ Nichomachus's Theorem relates the square of a sum to the sum of cubes: ![Nichomachus's Theorem](https://i.stack.imgur.com/58XhI.png) and has a beautiful geometric visualization: ![Visualization](https://i.stack.imgur.com/r0HLx.png) ## Challenge: Create the 2d part of this visualization in ascii. You will need to ensure that all visual demarcations are upheld by your diagram. This is simplest to do with four "colors," though it's possible to achieve with only three (see last example below for how). With four colors, you use two to distinguish between regions within a "strip" (ie, the different parts that make up a single cube), and two to distinguish between adjacent strips. You may also use more than four colors if you like. If any of this is confusing, the example output below should clarify. ## Input / Output Input is a single integer greater than 0. Output is an ascii grid similar to the examples below, corresponding to the flattened grid for that input number in the image above. Leading and trailing whitespace are ok. This is code golf, with standard rules. ## Sample outputs N = 1 ``` # ``` N = 2 ``` #oo o@@ o@@ ``` N = 3 ``` #oo+++ o@@+++ o@@+++ +++### +++### +++### ``` N = 4 ``` #oo+++oooo o@@+++oooo o@@+++@@@@ +++###@@@@ +++###@@@@ +++###@@@@ oo@@@@oooo oo@@@@oooo oo@@@@oooo oo@@@@oooo ``` N = 5 ``` #oo+++oooo+++++ o@@+++oooo+++++ o@@+++@@@@+++++ +++###@@@@+++++ +++###@@@@+++++ +++###@@@@##### oo@@@@oooo##### oo@@@@oooo##### oo@@@@oooo##### oo@@@@oooo##### +++++#####+++++ +++++#####+++++ +++++#####+++++ +++++#####+++++ +++++#####+++++ ``` Three color version for N = 4, thanks to @BruceForte: ``` #oo+++oooo o##+++oooo o##+++#### +++ooo#### +++ooo#### +++ooo#### oo####++++ oo####++++ oo####++++ oo####++++ ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~30~~ ~~28~~ 27 bytes ``` t:P"@:s:@/Xk&+@+8MPt&(]30+c ``` [Try it online!](https://tio.run/##y00syfn/vyzTKkDJwarYykE/IltN20HbwjegRE0j1thAO/n/fzMA) Bonus features: * For **26 bytes**, the following modified version produces **graphical output**: ``` t:P"@:s:@/Xk&+@+8MPt&(]1YG ``` Try it at [MATL Online!](https://matl.io/?code=t%3AP%22%40%3As%3A%40%2FXk%26%2B%40%2B8MPt%26%28%5D1YG&inputs=6&version=20.4.1) * The image is begging for some **colour**, and it only costs 7 bytes: ``` t:P"@:s:@/Xk&+@+8MPt&(]1YG59Y02ZG ``` Try it at [MATL Online!](https://matl.io/?code=t%3AP%22%40%3As%3A%40%2FXk%26%2B%40%2B8MPt%26%28%5D1YG59Y02ZG&inputs=8&version=20.4.1) * Or use a longer version (37 bytes) to see how the character matrix is **gradually built**: ``` t:P"@:s:@/Xk&+@+8MPt&(t30+cD9&Xx]30+c ``` Try it at [MATL Online!](https://matl.io/?code=t%3AP%22%40%3As%3A%40%2FXk%26%2B%40%2B8MPt%26%28t30%2BcD9%26Xx%5D30%2Bc&inputs=6&version=20.4.1) ## Example outputs For input is `8`, the following shows the basic version, graphical output, and colour graphical output. [![enter image description here](https://i.stack.imgur.com/CmO38.png)](https://i.stack.imgur.com/CmO38.png) [![enter image description here](https://i.stack.imgur.com/MW4PQ.png)](https://i.stack.imgur.com/MW4PQ.png) [![enter image description here](https://i.stack.imgur.com/RZGCT.png)](https://i.stack.imgur.com/RZGCT.png) ## Explanation ### General procedure A numeric matrix is built from outer to inner layers in `N` steps, where `N` is the input. Each step overwrittes an inner (upper-left) part of the previous matrix. At the end, the numbers in the obtained matrix are changed to characters. ### Example For input `4` the first matrix is ``` 10 10 9 9 9 9 8 8 8 8 10 10 9 9 9 9 8 8 8 8 9 9 8 8 8 8 7 7 7 7 9 9 8 8 8 8 7 7 7 7 9 9 8 8 8 8 7 7 7 7 9 9 8 8 8 8 7 7 7 7 8 8 7 7 7 7 6 6 6 6 8 8 7 7 7 7 6 6 6 6 8 8 7 7 7 7 6 6 6 6 8 8 7 7 7 7 6 6 6 6 ``` As a second step, the matrix ``` 7 7 7 6 6 6 7 7 7 6 6 6 7 7 7 6 6 6 6 6 6 5 5 5 6 6 6 5 5 5 6 6 6 5 5 5 ``` is overwritten into the upper half of the latter. Then the same is done with ``` 6 5 5 5 4 4 5 4 4 ``` and finally with ``` 3 ``` The resulting matrix is ``` 3 5 5 6 6 6 8 8 8 8 5 4 4 6 6 6 8 8 8 8 5 4 4 6 6 6 7 7 7 7 6 6 6 5 5 5 7 7 7 7 6 6 6 5 5 5 7 7 7 7 6 6 6 5 5 5 7 7 7 7 8 8 7 7 7 7 6 6 6 6 8 8 7 7 7 7 6 6 6 6 8 8 7 7 7 7 6 6 6 6 8 8 7 7 7 7 6 6 6 6 ``` Lastly, `30` is added to each entry and the resulting numbers are interpreted as codepoints and converted to characters (thus starting at `33`, corresponding to `!`). ### Construction of the intermediate matrices For input `N`, consider decreasing values of `k` from `N` to `1`. For each `k`, a vector of integers from `1` to `k*(k+1)` is generated, and then each entry is divided by `k` and rounded up. As an example, for `k=4` this gives (all blocks have size `k` except the last): ``` 1 1 1 1 2 2 2 2 3 3 ``` whereas for `k=3` the result would be (all blocks have size `k`): ``` 1 1 1 2 2 2 ``` This vector is added, element-wise with broadcast, to a transposed copy of itself; and then `k` is added to each entry. For `k=4` this gives ``` 6 6 6 6 7 7 7 7 8 8 6 6 6 6 7 7 7 7 8 8 6 6 6 6 7 7 7 7 8 8 6 6 6 6 7 7 7 7 8 8 7 7 7 7 8 8 8 8 9 9 7 7 7 7 8 8 8 8 9 9 7 7 7 7 8 8 8 8 9 9 7 7 7 7 8 8 8 8 9 9 8 8 8 8 9 9 9 9 10 10 8 8 8 8 9 9 9 9 10 10 ``` This is one of the intermediate matrices shown above, except that it is flipped horizontally and vertically. So all that remains is to flip this matrix and write it into the upper-left corner of the "accumulated" matrix so far, initiallized to an empty matrix for the first (`k=N`) step. ### Code ``` t % Implicitly input N. Duplicate. The first copy of N serves as the % initial state of the "accumulated" matrix (size 1×1). This will be % extended to size N*(N+1)/2 × N*(N+1)/2 in the first iteration :P % Range and flip: generates vector [N, N-1, ..., 1] " % For each k in that vector @: % Push vector [1, 2, ..., k] s % Sum of this vector. This gives 1+2+···+k = k*(k+1)/2 : % Range: gives vector [1, 2, ..., k*(k+1)/2] @/ % Divide each entry by k Xk % Round up &+ % Add vector to itself transposed, element-wise with broadcast. Gives % a square matrix of size k*(k+1)/2 × k*(k+1)/2 @+ % Add k to each entry of the this matrix. This is the flipped % intermediate matrix 8M % Push vector [1, 2, ..., k*(k+1)/2] again Pt % Flip and duplicate. The two resulting, equal vectors are the row and % column indices where the generated matrix will be written. Note that % flipping the indices has the same effect as flipping the matrix % horizontally and vertically (but it's shorter) &( % Write the (flipped) intermediate matrix into the upper-left % corner of the accumulated matrix, as given by the two (flipped) % index vectors ] % End 30+ % Add 30 to each entry of the final accumulated matrix c % Convert to char. Implicitly display ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~187~~ ~~178~~ ~~164~~ ~~162~~ 152 bytes -8 bytes thanks to Mr.Xcoder -1 byte thanks to Stephen -10 bytes thanks to Jonathan Frech ``` g=lambda y:y>1and[l+y*f(y,i)for i,l in enumerate(g(y-1))]+y*[''.join(f(y,i)for i in range(y*-~y/2))]or['#'] f=lambda y,i:'0@+#'[(y*~-y/2%y+i)/y%2+y%2*2] ``` [Try it online!](https://tio.run/##Tc2xCsIwFEDR3a8IlJKkaa1mEQqK/xE7RJrGJ@1LCXV4S389RhBxuNuBu9D6CKhT8ufJzvfBMurocrQ4mElRNQqqQY4hMqgnBsgcvmYX7eqEF9QcpeyzMpzvnwFQ/PEPjha9E1Q1G7U60xANL3i/G3@vGjp@uKqCm8y2JrOSFMiWSq1yle7TEgFXxm/4fXhxkjK9AQ "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ 46 bytes ``` F⮌…·¹N«≔⊘×ι⊕ιθF⊕⊘ι«F§#+@⁺ικ«UO⁻θ×ικθλUOθ⁻θ×ικλ ``` [Try it online!](https://tio.run/##dY7NDoIwEITP8BRNPLDGcvDgyYvc5OBPiC8AZcWGUqSFxsTw7LX8SLy42dPMtzPLHqlidSqsvdeKQIIGlUaIJROd5gaTVBYIW0pi@ezac1dlqGDthrx9L9KaFxKOqTCYw41XqIEPKFNYoWydyB1KSbPe@95Y8OvNd3xOm4CojWWOLwhWm0NAydW9MWSWX8i7ZKKWBZy4dE5DyVJbjk2UiKFs4ZzwB5243nfbW7uzobGhFh8 "Charcoal – Try It Online") Link is to verbose version of code. Previous 50-byte version with explanation: [Try it online!](https://tio.run/##S85ILErOT8z5///9nmWP1vU8alh2aPuhne/3rDu0@lHnlMPbD08/t/NR465DO8/tPLTp3A6QKhDv8HYQ/9BqIP/QcmVtB6DguZ3ndoEEtr7fs/5R4@5zO0Baz@06t@PcbojguR3Iwrv//zcFAA "Charcoal – Try It Online") ``` F⮌…·¹N«≔÷×ι⁺¹ι²θF⁺¹÷鲫F§#+@⁺ικ«UO⁻θ×ικθλUOθ⁻θ×ικλ F « Loop over …·¹ Inclusive range from 1 to N Input as a number ⮌ Reversed ι⁺¹ Add 1 to current index × ι Multiply by current index ÷ ² Divide by 2 ≔ θ Assign to q F « Loop over Implicit range from 0 to ÷ι² Half the current index ⁺¹ Plus 1 F « Loop over #+@ Literal string § Circularly indexed by ⁺ικ Sum of outer and inner index ×ικ Multiply outer and inner index ⁻θ Subtract from q UO θλ Draw an oblong (q-ik, q) using that character UOθ⁻θ×ικλ Draw an oblong (q, q-ik) using that character ``` Note: I loop over the character rather than trying to assign the character directly to `l` because you can't directly assign the result of indexing a string to a variable as it's an ambiguous construct in Charcoal. Fortunately the byte count is the same. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~135~~ ~~128~~ 120 bytes ``` f(n,m,i,x,y,k){for(m=n*-~n/2,i=m*m;i--;printf("\n%d"+!!(~i%m),(x/k+y/k+k)%3))for(x=i%m,y=i/m,k=n;x>=k&y>=k;x-=k--)y-=k;} ``` [Try it online!](https://tio.run/##RY7BDoIwDIbP8BQDg9mkE8XjrE/ixYBoM1cNYrLF4Kvj8OKh/5f2T/@20ZemmaZOMjgg8BDAqnd376VDXukPVzUQupUzpLV59MRDJ/MjF21eZpn8UOEUSF/ZMsSyqtgpNW97jA4EpMqBRTb@gHYZohiv0WqtQoQZpwVxc3u1Z7F/Di3d19dDGk8IdyKWSrzTJIYJOY8It0bQHrd1RFn@zKSTpEzk/7F87sc06c/Dq2exMek4fQE "C (gcc) – Try It Online") Uses only three colors. Conceptually, works on a grid rotated by 180 degrees: ``` 000111 000111 000111 111220 111220 111001 ``` And computes colors according to the formula: ``` c(x,y,n) = c(x-n,y-n,n-1) if x >= n and y >= n = (x div n + y div n + n) mod 3 otherwise ``` [Answer] # [R](https://www.r-project.org/), ~~131~~ ~~126~~ 123 bytes *3 bytes saved thanks to @Giuseppe* ``` function(n){l=w=sum(1:n) m=matrix(,l,l) for(i in n:1){m[l:1,l:1]=outer(x<-(1:l-1)%/%i,x,`+`)+i l=l-i} write(m%%4,"",w,,"")} ``` [Try it online!](https://tio.run/##DctBCsMgEEDRvacIAWGGTChCuwn1JKWQUiIMjApWUQg5u3Xx3@6n7mx3JXwzxwABT7HV/ooHswVU3vpPTtyAhASViwl44jCFzeDpX7IZGr1tLPlI0J7r2GQ1qG@aqdG@7LiwEisrX6omzgd4re80z1RpiFd38MD@Bw "R – Try It Online") This uses the same algorithm as @LuisMendo 's [MATL answer](https://codegolf.stackexchange.com/a/143234/66252). The only difference is that rather than converting to characters, the matrix is output with all of the values mod4 to ensure that each element is a single ascii character. [Answer] # [Python 2](https://docs.python.org/2/), ~~176~~ 175 bytes ``` n=input() R,J=range,''.join;r=[] for i in R(n+1): S=sum(R(i));c='AxBo'[i%2::2] for j in R(S):r[~j]+=c[j/i%2]*i r+=[J(c[-j/i%2]for j in R(S+i,0,-1))]*i for l in r:print J(l) ``` [Try it online!](https://tio.run/##Tcq7DsIgFIDhnadgMXCEemmcaBh07NiOpINpvBxSDw22iS6@Okq6uP7/N76ne6AyJbJI4zxJYI2ubTzT7aKF2PiAVEXrOnYNkSNH4o0ktQfDeGuf80M2EgGq3orj6xSEw1VpTNkxnr1ffAsmuo/vlO2d3/5Et0bGo7Kulr0rlvTvFeqdLvYAGeYx5BHNGJEmXssBUjp8AQ "Python 2 – Try It Online") ]
[Question] [ Because we can't get enough of esoteric language golfs, can we? ///—pronounced *slashes*—is a fun little language based on the `s///` regex-replacement function of Perl fame. It contains only two special characters, slash `/` and backslash `\`. You can find a full article on it at the [esolangs wiki](http://esolangs.org/wiki////), but I will reproduce a description of the language below, as well as some examples. In short, it works by identifying `/pattern/repl/rest` in the program and making the substitution as many times as possible. No characters are special except `/` and `\`: `/` demarcates patterns and replacements in the program, while `\` allows you to insert literal `/` or `\` characters into your code. Notably, these are not regular expressions, just plain string substitutions. *Your challenge* is to produce an interpreter for the /// language, as either a program reading STDIN or a function taking a string argument, in as few characters as possible. You may use any language except for /// itself. You may not use any libraries that interpret ///; you may, however, use regexes, regex libraries, or string-matching libraries. --- ## Execution There are four states, *print*, *pattern*, *replacement*, and *substitution*. In every state except *substitution*: * If the program is empty, execution halts. * Else, if the first character is `\`, do something with the next character (if present) and remove both from the program. * Else, if the first character is `/`, remove it, and change to the next state. * Else, do something with the first character and remove it from the program. * Repeat. The states cycle through *print*, *pattern*, *replacement*, and *substitution* in order. * In *print* mode, 'do something' means output the character. * In *pattern* mode, 'do something' means add the character to the current Pattern. * In *replacement* mode, 'do something' means add the character to the current Replacement. In *substitution* mode, you follow a different set of rules. Repeatedly substitute the first occurrence of the current Pattern with the current Replacement in the program, until no more substitutions are possible. At that point, clear the Pattern and Replacement and return to *print* mode. In the program `/foo/foobar/foo foo foo`, the following happens: ``` /foo/foobar/foo foo foo foo foo foo foobar foo foo foobarbar foo foo foobarbarbar foo foo ... ``` This loops forever and never exits *substitution* mode. Similarly, if the Pattern is empty, then the first occurrence of the empty string—at the beginning of the program—always matches, so *substitution* mode loops forever, never halting. --- ## Examples ``` no ``` Output: `no`. ``` / world! world!/Hello,/ world! world! world! ``` Output: `Hello, world!`. ``` /foo/Hello, world!//B\/\\R/foo/B/\R ``` Output: `Hello, world!`. ``` a/ab/bbaa/abb ``` Output: `a`. Program does not halt. ``` // ``` Output: none. ``` /// ``` Output: none. Program does not halt. ``` /\\/good/\/ ``` Output: `good`. There is also a quine [on the wiki](http://esolangs.org/wiki////#Quine) you can try. [Answer] # J - ~~181~~ ~~190~~ 170 char This was a nightmare. I rewrote it from scratch, twice, because it just kept bugging me. This is a function taking a single string argument, outputting to STDOUT. ``` (0&$`((2{.{:@>&.>)((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i 5;@}.&,'/';"0;&.>)@.(2<#)@}.[4:1!:2~{:@>@p=.>@{.@[)@((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)i=. ::](^:_) ``` To explain, I will break it up into subexpressions. ``` i =. ::](^:_)) parse =: ((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,) print =: 4:1!:2~{:@>@p=.>@{.@[ eval =: 0&$`((2{.{:@>&.>)sub 5;@}.&,'/';"0;&.>)@.(2<#)@}. sub =: ((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i interp =: (eval [ print) @ parse i ``` * `i` (short for *iterate*) is an adverb. It takes a verb argument on the left and returns a verb `(f)i`, which when applied to an argument, applies `f` repeatedly to the argument until one of two things happens: it finds a fixed point (`y = f y`), or it throws an error. The fixed-point behaviour is inherent to `^:_`, and `::]` does the error handling. * `parse` tokenizes the input into what I call *half-parsed* form, and then cuts it up at the unescaped '/'. It binds escaping backslashes to their characters, but doesn't get rid of the backslashes—so we can either revert it or finish it depending on which we want. The bulk of the interesting work occurs in `;:`. This is a sequential-machine interpreter primitive, taking a description of the machine (`(0;(0,:~1 0,.2);'\';&<1 0)`) on the left and something to parse on the right. This does the tokenizing. I will note that this specific machine actually treats the first character unspecial, even if it's a `\` and should bind. I do this for a few reasons: (1) the state table is simpler, so it can be golfed further; (2) we can easily just add a dummy character to the front to dodge the problem; and (3) that dummy-character gets half-parsed at no extra cost, so I can use it to set up for the cutting phase, next. We also use `<;._1` to cut the tokenized result on unescaped `/` (which is what I choose to be the first char). This is handy for pulling out the output, pattern, and replacement from `out/patt/repl/rest` all in one step, but unfortunately also cuts up the rest of the program, where we need those `/` to stay untouched. I splice these back in during `eval`, because making `<;._1` leave them alone ends up costing a lot more. * The fork `(eval [ print)` executes `print` on the result from `parse` for its side-effects, and then runs `eval`. `print` is a simple verb that opens up the first box (the one we know for sure is output), finishes parsing it, and sends it to STDOUT. However, we also take the chance to define a utility verb `p`. `p` is defined as `>@{.@[`, so it takes its left arg (acts like the identity if given only one arg), takes the first item of that (identity when given a scalar), and unboxes it (identity if already unboxed). This will come in very handy in `sub`. * `eval` evaluates the remainder of the processed program. If we don't have a full pattern or a full replacement, `eval` throws it out and just returns an empty list, which terminates evaluation by making `;:` (from `parse`) error out on the next iteration. Else, `eval` fully parses the pattern and replacement, corrects the remainder of the source, and then passes both to `sub`. By explosion: ``` @}. NB. throw out printed part @.(2<#) NB. if we have a pattern and repl: 2{. NB. take the first two cuts: &.> NB. in each cut: {:@> NB. drop escaping \ from chars ( ) NB. (these are pattern and repl) &.> NB. in each cut: ; NB. revert to source form '/';"0 NB. attach a / to each cut &, NB. linearize (/ before each cut) 5 }. NB. drop '/pattern/repl/' ;@ NB. splice together ( sub ) NB. feed these into sub ` NB. else: 0&$ NB. truncate to an empty list ``` * `sub` is where one (possibly infinite) round of substitutions happens. Because of the way we set up `eval`, the source is the right argument, and the pattern and replacement are bundled together in the left. Since the arguments are ordered like this and we know the pattern and replacement don't change within a round of substitutions, we can use another feature of `i`—the fact that it modifies only the right argument and keeps passing in the same left—to delegate to J the need to worry about keeping track of the state. There are two spots of trouble, though. The first is that J verbs can have at most two arguments, so we don't have an easy way to access any that are bundled together, like pattern and replacement, here. Through clever use of the `p` utility we defined, this isn't that big of a problem. In fact, we can access the pattern in one character, just by using `p`, because of its `>@{.@[` definition: the Unbox of the First item of the Left arg. Getting the replacement is tricker, but the shortest way would be `p&|.`, 2 chars shorter than manually getting it out. The second problem is that `i` exits on fixed points instead of looping forever, and if the pattern and replacement are equal and you make a substitution, that looks like a fixed point to J. We handle this by entering an infinite loop of negating 1 over and over if we detect they are equal: this is the `-i@=`p@.~:~/` portion, replacing `p&|.`. ``` p E.] NB. string search, patt in src I.@ NB. indices of matches 0{ NB. take the first (error if none) j=. NB. assign to j for later use #@p+ NB. add length of pattern ]}.~ NB. drop that many chars from src /@[ NB. between patt and repl: ~ NB. patt as right arg, repl as left @.~: NB. if equal: -i@= NB. loop forever `p NB. else: return repl (j{.]) NB. first j chars of src , , NB. append all together ( )i NB. iterate ``` * This cycle repeats due to the use of `i`, until something outside of `sub` errors out. As far as I'm aware, this can only happen when we are out of characters, of when we throw out an incomplete set of pattern-and-replacement. Fun facts about this golf: * For once, using `;:` is shorter than manually iterating through the string. * `0{` should have a chance to error out before `sub` goes into an infinite loop, so this it should work fine if the pattern matches the replacement but never shows up in the remainder of the source. However, this may or may not be unspecified behaviour, since I can't find a citation either way in the docs. Whoopsie. * Keyboard interrupts are processed as spontaneous errors inside running functions. However, due to the nature of `i`, those errors get trapped too. Depending on when you hit Ctrl+C, you might: + Exit out of the negate-forever loop, error out of the `sub` loop by trying to concatenate a number to a string, and then go on interpreting /// as if you finished substituting a string with itself an infinite number of times. + Leave `sub` halfway through and go on interpreting a half-subbed /// expression. + Break out of the interpreter and return an unevaluated /// program to the REPL (not STDOUT, though). Example usage: ``` f=:(0&$`((2{.{:@>&.>)((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i 5;@}.&,'/';"0;&.>)@.(2<#)@}.[4:1!:2~{:@>@p=.>@{.@[)@((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)i=. ::](^:_) f 'no' no f '/ world! world!/Hello,/ world! world! world!' Hello, world! f '/foo/Hello, world!//B\/\\R/foo/B/\R' Hello, world! f '//' NB. empty string f '/\\/good/\/' good ``` [Answer] ## APL (133) ``` {T←''∘{(0=≢⍵)∨'/'=⊃⍵:(⊂⍺),⊂⍵⋄(⍺,N⌷⍵)∇⍵↓⍨N←1+'\'=⊃⍵}⋄⍞N←T⍵⋄p N←T 1↓N⋄r N←T 1↓N⋄''≡N:→⋄∇{⍵≡p:∇r⋄∨/Z←p⍷⍵:∇(r,⍵↓⍨N+≢p),⍨⍵↑⍨N←1-⍨Z⍳1⋄⍵}1↓N} ``` This is a function that takes the `///` code as its right argument. Ungolfed, with explanation: ``` slashes←{ ⍝ a function to split the input string into 'current' and 'next' parts, ⍝ and unescape the 'current' bit split←''∘{ ⍝ if the string is empty, or '/' is reached, ⍝ return both strings (⍺=accumulator ⍵=unprocessed) (0=≢⍵)∨'/'=⊃⍵:(⊂⍺),⊂⍵ ⍝ otherwise, add current character to accumulator, ⍝ skipping over '\'s. (so if '\/' is reached, it skips '\', ⍝ adds '/' and then processes the character *after* that.) idx←1+'\'=⊃⍵ (⍺,idx⌷⍵)∇idx↓⍵ } ⍞ next ← split ⍵ ⍝ output stage pat next ← split 1↓next ⍝ pattern stage, and eat the '/' rpl next ← split 1↓next ⍝ replacement stage, and eat the '/' ⍝ if there are no characters left, halt. ''≡next:⍬ ⍝ otherwise, replace and continue. ∇{ ⍝ if the input string equals the pattern, return the replacement and loop ⍵≡pat:∇rpl ⍝ otherwise, find occurences, if there are, replace the first and loop ∨/occ←pat⍷⍵:∇(rpl, (idx+≢pat)↓⍵),⍨ (idx←(occ⍳1)-1)↑⍵ ⍝ if no occurences, return string ⍵ }1↓next } ``` [Answer] # [Pip](http://github.com/dloscutoff/pip), ~~100~~ 102 bytes I hadn't ever proven Pip to be Turing-complete (though it's pretty obviously so), and instead of going the usual route of BF I thought /// would be interesting. Once I had the solution, I figured I'd golf it and post it here. 101 bytes of code, +1 for `-r` flag: ``` i:gJnf:{a:xW#i&'/NE YPOia.:yQ'\?POiya}W#iI'\Q YPOiOPOiEIyQ'/{p:VfY0s:VfIyQ'/WpNi&YviR:Xp{++y?ps}}E Oy ``` Here's my ungolfed version with copious comments: ``` ; Use the -r flag to read the /// program from stdin ; Stdin is read into g as a list of lines; join them on newline and assign to c for code c : gJn ; Loop while c is nonempty W #c { ; Pop the first character of c and yank into y Y POc ; If y equals "\" I yQ'\ ; Pop c again and output O POc ; Else if y equals "/" EI yQ'/ { ; Build up pattern p from empty string p : "" ; Pop c, yank into y, loop while that is not equal to "/" and c is nonempty W #c & '/ NE Y POc { ; If y equals "\" I yQ'\ ; Pop c again and add that character to p p .: POc ; Else, add y to p E p .: y } ; Yank 0 so we can reliably tell whether the /// construct was completed or not Y0 ; Build up substitution s from empty string s : "" ; Pop c, yank into y, loop while that is not equal to "/" and c is nonempty W #c & '/ NE Y POc { ; If y equals "\" I yQ'\ ; Pop c again and add that character to s s .: POc ; Else, add y to s E s .: y } ; If the last value yanked was "/", then we have a complete substitution ; If not, the code must have run out; skip this branch, and then the outer loop ; will terminate I yQ'/ { ; While pattern is found in code: W pNc { ; Set flag so only one replacement gets done i : 0 ; Convert p to a regex; replace it using a callback function: if ++i is 1, ; replace with s; otherwise, leave unchanged c R: Xp {++i=1 ? s p} } } } ; Else, output y E Oy } ``` [Try it online!](https://tio.run/##NYwxC8IwFIR3f0VFaMHYXrIGxKlDHaw6qIVbulSySLAgltLfHl@qPvKOu/se8c6H4Ox9/@js2Nr3deXSDIcyaY61aws7nDLuxA7tJKjKeJpJLVtWAjF6e@ka3YvO@eoPLm1e7mxvflRq2Pl@msqkHkLAAsASREFqYkNudBTDb2d@XYzRxFKsIhWxJbfxJicW3/QnWM6DQn5XVKI5SOmhYSBvDaUKE/LnBw "Pip - Try It Online") (Note that TIO doesn't give any output when the program is non-terminating, and it also has a time limit. For larger examples and infinite loops, running Pip from the command line is recommended.) [Answer] # Perl - 190 ``` $|=1;$/=undef;$_=<>;while($_){($d,$_)=/(.)(.*)/;eval(!$e&&({'/','$a++','\\','$e=1'}->{$d})||('print$d','$b.=$d','$c.=$d')[$a].';$e=0');if($a==3){while($b?s/\Q$b/$c/:s/^/$c/){}$a=0;$b=$c=''}} ``` Reads `///` program from stdin until EOF. [Answer] # C++ 347 **Edits:** * **Thanks to @algorithmshark for lots of help making the original shorter** * **Thanks to @Adalynn for a good suggestion to save bytes** * **Thanks to @ceilingcat for many, many very nice pieces of golfing - now even shorter** Here is the code: ``` #import<bits/stdc++.h> #define N(x)o[i]);else if(n<x)o[i]==92? #define O (o[++i]):o[i]==47?n++: char p[198],*q=p,*s=p+99;int i,t;main(int n,char**m){for(std::string o=m[1];i<=o.size();++i){if(!N(3)putchar O putchar(N(4)*q++=O(*q++=N(5)*s++=O(*s++=o[i]);if(n>4){for(n=2;~(t=o.find(p,i+1));o=o.substr(0,t)+s+&o[t+strlen(p)])s=p+99;bzero(q=p,198);}}} ``` [Try it online!](https://tio.run/##PY/BbsIwEETv/QojpGodu6RQqjYxBolTT0HimuQAiQOWEtvERq1A9NdTh6Cedmd3pJlXGPNyKIquG8vG6NYt9tLZ0LqyIGRyXD6NS1FJJVACP1inMsdM1FYgWYFaDBfOo9nq37dBoFNCvDEenvOPlSIkfiqOuxaZdBp95jQ4cUMDyw2JIiaVQ5I61uykgl4o2nuDoMHXSrfgu8Sxda1UB6R5k05zJhdcT6y8CMDMZ@GrrzNK4A2bs7vnbNBjgwTmODgRwjdwHwm848AOuh8DU4@znA95is/YLzif4IFKMFSSKcZM95HnvS8Cr9RhYsmzTh3xuhYKDM7xg2d/Ea2GntCzYna73bquCyutwy9R15qib93W5SgM11mYZdv7Zx1m2z8 "C++ (gcc) – Try It Online") [Answer] # Python 2 (236), Python 3 (198?) ``` from __future__ import print_function def d(i): t=0;p=['']*3+[1] while i: if'/'==i[0]:t+=1 else: if'\\'==i[0]:i=i[1:] p[t]+=i[0] i=i[1:] print(end=p[0]);p[0]='' if t>2: while p[1]in i:i=i.replace(*p[1:]) d(i);i=0 ``` Called as `d(r"""/foo/Hello, world!//B\/\\R/foo/B/\R""")`. The triple quotes are only needed if the `///` program contains newlines: otherwise simple quotes are ok. EDIT: This interpreter now prints stuff as expected (previously it only printed at the very end, cf. comments). For Python 3, remove the first line (but I don't have Python 3 on my ancient install, so cannot be sure there is no other change). [Answer] # Cobra - 226 ``` sig Z as String def f(l='') m=Z(do=[l[:1],l=l[1:]][0]) n as Z=do if'/'<>(a=m())>'',return if(a=='\\',m(),a)+n() else,return'' print n()stop p,s=n(),n() if''<l while p in l,l=l[:l.indexOf(p)+1]+s+l[p.length:] .f(l) ``` [Answer] # **[BaCon](http://www.basic-converter.org), ~~391~~ ~~387~~ 395 bytes** From the contributions on this page I only got the Python program to work. The others work for some /// samples, or do not work at all. Therefore, I decided to add my version, which is an implementation in BASIC. To compete in a CodeGolf contest with BASIC is not easy, as BASIC uses long words as statements. The only abbreviation commonly found in BASIC is the '?' sign, which means PRINT. So the below program may never win, but at least it works with all demonstration code on this Codegolf page and on the [Esolangs Wiki](http://esolangs.org/wiki////). Including all versions of the "99 bottles of beer". ``` p$="" r$="" INPUT i$ WHILE LEN(i$) t$=LEFT$(i$,1) i$=MID$(i$,2) IF NOT(e) THEN IF t$="\\" THEN e=1 CONTINUE ELIF t$="/" THEN o=IIF(o<2,o+1,0) IF o>0 THEN CONTINUE FI FI IF o=1 THEN p$=p$&t$ ELIF o=2 THEN r$=r$&t$ ELIF o=0 THEN IF LEN(p$) THEN i$=REPLACE$(i$,p$,r$) IF NOT(INSTR(t$&i$,"/")) THEN ?t$; BREAK ELSE ?LEFT$(i$,INSTR(i$,"/")-1); i$=MID$(i$,INSTR(i$,"/")) FI p$="" r$="" FI e=0 WEND ?i$ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~119~~ 110 bytes Terminates with exception ``` r=->s,o=$>{s[k=s[0]]='';k==?/?o==$>?s.gsub!([r[s,''],e=r[s,'']][0]){e}:t=o:o<<(k==?\\?s[0]+s[0]='':k);t||redo} ``` [Try it online!](https://tio.run/##fZBPb@IwEMXv/hSDbCutGnAIf4eSckaqelpxSaMqgCkRIWZjZ1EFfHZ2AuS00h6ePT/7zfPIZbX8uV7LqP1mfROJt5ONd5GNgySJPO91F0UzNTMRXcxs59tWy9ZTXMbW97zE19GjSsj@fNKXiYvMxEynT3Xb5@esjnmpF4qa7J5f3flc6rW5XDm4bWYhzXNztLAxJeyr3GV5VmjIikPlGL/vQC6X7nQBm9Lswbp1VoAzkP4x2Rqq7/wHtF2lBw1W/650sdKW3Rsj8Dwmph2drrZft@DTOTs/UqdTyC6Mc8bK@HaSXFXCYqUUV7A0zuXagtnAUusSDL241XCkaX2mVOsfB/tFE5JNw9ocCx8OqbWQOUhLUxVrXymhWtQo/xvdYWT5eFfsNshcIXJEgWOJY45jgSOJI44jgUOJQ45DgQOJA44DgX2JfY59gT2JPY49gaHEkGMosCuxy7ErMJAYcAxat/QFPYQo5zXM6wNC0lgt7jAmjRoYkYYNDEmDBgakfgN9Uq@BHilsICR1G@iS2upeUxXwNs1040B9GNibUj9u2/VvkJpPq5sftVr8BQ "Ruby – Try It Online") Terminates cleanly (116 bytes) ``` r=->s,o=$>{s[k=s[0]||exit]='';k==?/?o==$>?s.gsub!([r[s,''],e=r[s,'']][0]){e}:t=o:o<<(k==?\\?s[0]+s[0]='':k);t||redo} ``` [Try it online!](https://tio.run/##fZBPb@IwEMXv/hSDbCutNuDwn6GknJFWPa24pFEVwJSIELOxs2xF@OzsBMhppR6ePT973vPIRbn6ul6LsP1qfROK17ON9qGNgriq9N/UxaHnvezDcK7mJqTrue182nLVeoqKyPqeF/s6fFQxmZ7P@jJ1oZma2eyptr2/z@uwH/VCUdP984urqkJvzOXKwe1SC0mWmZOFrSngUGYuzdJcQ5ofS8f4fQfqcsle57AtzAGs26Q5OAPJH5NuoPzMvkDbdXLUYPXvUudrbdndGILnMTHr6GS9@7gFn6u0eqTOZpBeGOeMFdHtJL6qmEVKKa5gZZzLtAWzhZXWBRh6cafhRNP6TKnWfx3sF01IbRo25pT7cEyshdRBUpgy3/hKCdUio/w2usOo5e2nYrdBFgqRIwqcSJxwnAgcSxxzHAscSRxxHAkcShxyHAocSBxwHAjsS@xz7AvsSexx7AnsSuxy7AoMJAYcg9YtfUkPIcpFDYv6gJA0Ucs7TEjjBsakUQMj0rCBIWnQwIDUb6BP6jXQI3Ub6JLa6l5TFfA2zXTjQL0ZOJhCP27b9W@Qmk@rzY9aLf8B "Ruby – Try It Online") [Answer] # Python 2/3 (211 bytes) The following code, based on [Bruno Le Floch's answer](https://codegolf.stackexchange.com/a/37093), is Python 2 and Python 3 compatible. Moreover, being iterative rather than recursive it does not risk hitting the maximum recursion depth of Python. ``` def S(c): while c: B=["","",1] for m in 0,1,2: while c: if"/"==c[0]:c=c[1:];break if"\\"==c[0]:c=c[1:] if m:B[m-1]+=c[0] else:yield c[0] c=c[1:] while c and B[0]in c:c=c.replace(*B) ``` ]
[Question] [ ### Statement You are given a still of a series of balls falling in a 2D grid. This grid is surrounded by immutable and unbreakable walls so all the action is contained within them. Your task is to determine what the state of the scenario will be after gravity does all it's work. ### Elements inside grid * `-` Floor, doesn't alter the direction of falling balls. * `\` Right slide, alters the path of the ball one (1) position right. * `/` Left slide, alters the path of the ball one (1) position left. * `o` A ball. ### Rules * Balls fall. * Floors and slides **don't fall**. * If the ball hits a slide that would make it go through a wall (`\#`or`#/`), or cross through a floor the slide will act as a floor. * When a ball hits another ball the will become one ball, but increase their power to the sum of both balls. * New balls (joined) will continue to behave as usual. * When a ball can't move anymore, it's replaced by its power. * The power of a ball will always be at most 9. ### Input The grid will be given in a string variable with whatever name is shortest in your language of choice. By default we will use `a` as the input. A sample of an input, exactly as received: ``` ##########\n# \ #\n#o #\n# - -\o #\n#/- \ #\n# \oo-/\#\n#-/ \ /#\n# \ \ #\n# /#\n########## ``` For random grids generated use <https://repl.it/B1j3/2>. Use [my generated page](http://bohem.io/wadus/index.php) instead (no ads, no crap, just the input and the output) **Note** line breaks are `\n`. Printing the input to screen (not required for the challenge) would show things like this. Although I've put four puzzles alongside to safe space. ``` ########## ########## ########## ########## # \ # # o -/# # o# #-o / # #o # # \ # # o -# #-- \ /\ # # - -\o # #- \ # # - \o# # - -- o-# #/- \ # # # #o /\ # #/ \ # # \oo-/\# #o -o- # # / -o# #/ /o oo/# #-/ \ /# # -/- # # - o -# #o/ # # \ \ # # \\ # # \o /# #o-o o# # /# # \o\ /\# # \o # # -\o o /# ########## ########## ########## ########## ``` ### Output The same grid, printed to screen with the final result of ball power. A valid answer would be one (1) of the following puzzles, each one corresponds to the input at the same position, of course if the input is different you should adjust the output. Not limit it to those four! ``` ########## ########## ########## ########## # \ # # -/# # 1# #-1 / # # # # \ # # -# #-- \ /\ # #1 - -\ # #- \ # # - \ # # - -- -# #/- \1# # # # /\ # #/ \ # # \ -/\# # -1- # # / -2# #/ / /# #-/ \ /# # -/- # # - -# # / # # \ \ # # \\ # # \ /# # - # # 2 /# #1\2\ /\# #2 2\1 # #2-\3 23/# ########## ########## ########## ########## ``` ### Score Languages will compete against themselves so feel free to use nongolf languages. To validate a solution I must be able to test it somewhere to see it works!. Score is number of bytes. In the event of a tie, the first answer to reach the tied score wins. ### Warnings * If unsure of how a ball should react, ask me and I'll clarify, I've been as clear as I could but I'm sure there are cases that are confusing. * Slides are only ridden **if you can exit them**, think about it like a real slide. There's a guy at the top that doesn't let you through the ball unless it will exit through the other side. ### Clarifying examples of ball movement ``` ###### ###### #-o- # BALL WOULD GO RD #- - # # \ # # \o # ###### ###### ###### ###### #-o- # BALL WOULD STAY #-o- # # \\ # # \\ # ###### ###### ###### ###### # -o# BALL WOULD STAY # -o# # \# # \# ###### ###### ###### ###### # o # BALL WOULD STAY # o # # \/# # \/# ###### ###### ###### ###### #-o- # BALL WOULD GO LD #- - # # /\ # #o/\ # ###### ###### ``` ### How can I test if my answer is valid? I've set up [a simple page](http://bohem.io/wadus/index.php) in one of my sites that will give you a random puzzle, and its answer. Take the input and check it against the output. My solution, without worrying too much about golfing is `389b` `355b` in python (generator, and page also python) ### Leaderboard ``` var QUESTION_ID=64359,OVERRIDE_USER=8478;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] # Marbelous, 19561 bytes (Not that I tried to optimize the size.) This claims the final bounty [here](https://codegolf.meta.stackexchange.com/a/8219/96393). This expects a trailing newline in the input. It works for boards up to 15x15 (including the edges) but I feel like this is reasonable as that is a direct result of the num size limit being 255. Please use my [interpreter](https://replit.com/@DanielJames5/MarbelousInterpreter) as I can make no guarantees about other interpreters. It is based on the one [here](https://codegolf.stackexchange.com/a/40808/96393) but with a few bug fixes and an added debugger. To solve the boards in the example takes about 330000 ticks. That is mostly due to the difficulty of arbitrary data storage. Marbelous is not turning complete so I have to use a big rotating tape to store the board. The code is divided into roughly three sections. (Separated by those four big lines of %%). 1. This gets the full input and converts it to the encoding expected by the rest of the code. It also populates the initial fields of the main processing loop. 2. This function takes a t of values (ie one square and the three below it) and figures out the state after one tick. It then outputs all the values that need to be sent to the memory tape or terminates the program if we are complete. 3. This is the memory tape. It is possible to read or write to it by sending values to the appropriate portals. Overall this is an interesting language that could be fun if it is made turning complete. I do feel that the coding can get a bit repetitive (it is mostly just lots of `&0`s) but it is still fun. ``` # ENCODING: # 0 = empty square # 1-9 = that many marbles # A = wall # B = right ramp # C = left ramp # D = reset count # E = nothing .. @B .. .. .. .. .. .. .. @C .. .. .. .. .. .. .. .. .. .. .. .. 00 00 // // // // // // // .. .. .. .. .. .. .. .. .. .. .. .. ge t_ in pu t_ +_ in it .. .. .. .. .. .. .. .. .. .. .. .. .. @B @C .. .. &A .. .. @K .. .. .. .. .. .. .. .. .. .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% .. .. .. .. .. .. .. \\ \\ \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. // .. .. \\ \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ \\ %% @4 %% @9 %% .. .. .. .. .. .. .. .. .. .. .. .. .. \\ %% @3 \\ .. .. &4 .. .. .. .. .. .. .. .. .. .. .. .. .. .. @2 \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% @1 \\ \\ .. .. .. .. // .. @A .. .. .. .. .. .. .. .. 0A @0 \\ \\ \\ .. 01 .. .. .. .. // // .. .. .. .. .. .. .. .. \\ \\ \\ \\ ti ck _r et ur n_ pr in t_ an d_ te rm in at e_ pg # ys: v0 v3 .. .. .. .. @0 @1 @2 @3 @4 .. &0 &1 &2 .. &0 &1 &2 &3 &4 &3 &4 # xs: v1 v2 l0 w sl .. .. .. .. .. .. .. .. .. \\ \\ \\ @5 \\ \\ \\ @6 \\ @7 \\ @8 # @5 = write loc .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # @6 = write val .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # @7 = read loc .. .. .. .. .. .. .. .. .. .. .. .. \/ .. .. .. \/ .. \/ .. \/ # @8 = read ret loc %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% @D @E 01 .. %% # Acts as a switchboard .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% &5 &5 // .. %% # to activate the right .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% pl us .. .. %% # gate when a write is .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% =1 =2 =3 =4 %% # complete .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% &0 &1 &2 &3 %% .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% ++ ++ ++ eo %% .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% \\ \\ \\ @E %% .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% %% %% %% %% %% .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. @G @K .. .. .. .. @P 0E .. .. @O 0E .. .. @N 0E .. .. @M 0E .. \\ .. .. .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 .. .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. .. \\ &9 0E .. \\ &9 .. .. \\ &9 .. .. \\ &9 .. .. \\ &9 .. .. .. 0E &9 // .. .. @P .. .. .. @O .. .. .. @N .. .. .. @M .. .. .. \\ &9 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. &A .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. // // .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. // // .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. // // .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. 01 .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. ng .. .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. &A .. @5 .. @7 .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. .. .. du pe du pe .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. .. .. ez @L ez .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. .. .. +2 .. +3 .. .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. .. @H .. .. .. .. .. .. .. .. .. .. .. .. .. 0E &9 // .. .. .. .. // // // // .. .. .. .. .. .. .. .. .. .. \\ &9 0E .. .. .. .. .. @I .. .. .. @L .. .. .. .. .. .. .. .. 0E &9 // .. .. .. .. .. // // // // // .. .. .. .. .. .. .. .. \\ &9 0E .. .. @F .. .. .. @J @8 @6 .. .. .. .. .. .. .. .. .. .. &9 // .. .. 00 01 00 00 // // // .. .. .. .. .. .. .. .. .. .. \\ \\ \\ lo op er lo op er lo op .. .. .. .. .. .. .. .. .. .. .. .. .. @G @F @H @I @J @D @9 @A .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # value, position, mode, w/r-location, input, wrote, read1, read2 # # mode 0 = waiting # mode 1 = inputing # mode 2 = writing # mode 3 = reading :looper # &6 = reset # &5 = not reset # # &7 = writing and match # &8 = writing and no match # # &9 = reading and match # &A = reading and no match # # mode 1: output nothing # mode 2: }2 .. %% }0 .. %% 00 01 00 00 00 .. .. .. .. .. .. >0 &0 %% =D &5 %% &1 &1 &1 &1 &1 .. .. .. .. .. .. .. \/ %% &6 \/ %% {1 {2 {3 {4 \\ !! .. .. .. .. .. >1 &1 %% \/ .. %% %% %% %% %% %% %% %% %% %% %% %% .. \/ %% .. .. %% }1 }3 .. }4 }1 00 00 00 00 .. .. >2 &2 %% %% %% %% &2 &2 .. .. ++ .. .. .. .. .. .. .. \/ %% .. .. %% mi nu .. &7 &7 &7 &7 &7 &7 .. .. >3 &3 %% .. .. %% =0 &8 .. {0 {1 {5 {3 {4 \\ !! .. &4 \/ %% .. .. %% &7 .. .. .. .. .. .. .. .. .. .. \/ .. %% .. .. %% .. .. }0 }0 }1 .. .. .. .. .. .. .. .. %% .. .. %% .. .. .. ne wl 02 }3 }4 00 .. .. .. .. %% .. .. %% .. .. &8 &8 .. &8 &8 &8 &8 .. .. .. .. %% .. .. %% .. .. {0 {1 .. {2 {3 {4 \\ !! .. .. .. %% .. .. %% %% %% %% %% %% %% %% %% %% %% %% .. .. %% .. .. %% }1 }3 .. }0 }1 00 00 }4 }0 00 .. .. .. %% .. .. %% &3 &3 .. .. ++ .. .. &9 &9 .. .. .. .. %% .. .. %% mi nu .. &9 &9 &9 &9 se nd &9 .. .. .. %% .. .. %% =0 &A .. {0 {1 {3 {4 {6 {7 \\ !! .. .. %% .. .. %% &9 .. .. .. .. .. .. .. .. .. .. .. .. %% .. .. %% .. .. }0 }0 }1 .. .. .. .. .. .. .. .. %% .. .. %% .. .. .. ne wl 03 }3 }4 00 .. .. .. .. %% .. .. %% .. .. &A &A .. &A &A &A &A .. .. .. .. %% .. .. %% .. .. {0 {1 .. {2 {3 {4 \\ !! .. .. .. %% .. .. %% .. .. .. .. .. .. .. .. .. .. .. .. .. %% .. .. %% .. .. .. .. .. .. .. .. .. .. .. :newl # }0 = 0 -> same # }0 = D -> 0 # else -> }1 + 1 }0 .. .. =E =D .. &0 &1 &2 \/ \/ \/ }1 00 }1 .. .. ++ &0 &1 &2 {0 {0 {0 # Tik, Return, Print, and Terminate Program # # 0,1,9-C, # :tick_return_print_and_terminate_pg %% %% %% %% %% %% %% %% %% %% %% %% %% %% }2 }3 }4 00 01 }2 }2 }2 }2 }2 }2 %% # Echo values that should be echoed %% ++ .. .. .. .. ++ +2 .. -- .. ++ %% %% .. .. .. .. .. .. }3 .. }3 }3 }3 %% %% &0 &0 &0 &0 &0 &0 &0 &0 &0 &0 &0 %% %% {2 {3 {4 {F {G {D {E {5 {6 {7 {8 %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% .. .. .. .. %% .. }5 }0 }1 }6 .. %% # (left) prints the cell %% .. .. .. .. %% .. so lv ev ls .. %% # (right) solve the position %% .. .. .. .. %% // // .. .. .. .. %% %% .. }3 }2 .. /\ \\ .. .. .. .. .. %% %% .. pr in tc %% .. &0 &0 &0 &0 .. %% %% .. .. .. .. %% .. {9 {A .. du pe %% %% .. .. .. .. %% .. .. .. // {C {1 %% %% .. .. .. .. %% .. .. du pe .. .. %% %% .. .. .. .. %% .. .. {B {0 .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% .. }4 }2 .. .. .. .. .. .. .. 00 %% # Check if the program should terminate %% .. mi nu .. .. .. .. }3 .. .. &1 %% %% .. \\ \\ \\ =0 &0 .. &1 .. .. .. %% %% .. .. .. .. &1 \/ .. pb .. .. .. %% %% .. .. .. .. \/ .. .. .. .. .. !! %% %% %% %% %% %% %% %% %% %% %% %% %% %% # Get Input and Initlize # # gets the full board input :get_input_+_init # 1) }1 = 0 then print char }0++ # 2) }1 = 0 & char = \n then }1 = }0, }0 := 0 # 3) }1 != 0 & char != \n then }1++ # 4) eof then output stop # 5) }0 = 1 or w-1 or w or w+1 & }1 != 0 output v # 6) }1 != 0 output encoding .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 00 .. .. .. .. .. .. .. .. .. .. .. .. .. }0 }1 .. .. ]] &1 .. .. .. .. .. .. .. .. .. .. .. .. mi nu .. .. .. \/ .. .. }0 }1 .. .. .. .. .. .. .. .. -2 .. 0D .. \\ \\ \\ c+ ge t_ in pu t_ +_ in .. .. .. &1 .. &1 .. .. .. .. // .. .. .. .. .. .. .. .. .. .. /\ {4 {7 .. .. .. /\ {0 {1 {2 {3 {4 {5 {6 {7 .. .. !! .. .. .. .. .. !! .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # Char + Get Input and Initlize # # gets the full board input :c+get_input_+_init # &0 = no width # &1 = width # &2+&9 = newline # &3+&8 = not newline # &4 = no width & newline # &5 = no width & !newline # &6 = width & newline # &7 = width & !newline # &A/B/B = release v0/2/3 .. .. .. .. %% 00 00 %% .. .. .. .. .. .. .. .. .. .. .. .. .. }2 .. .. .. %% &0 &0 %% }0 .. }1 00 .. 00 }1 }1 .. }0 }1 }2 .. =0 &1 .. .. %% &2 &3 %% &0 .. &5 &5 .. &4 &4 &4 .. ec ++ .. .. &0 \/ .. .. %% &4 &5 %% [[ .. ++ .. .. {0 {1 {3 .. &7 &7 &7 .. \/ .. .. .. %% \/ \/ %% .. .. {0 {1 .. .. .. .. .. {7 {0 {1 .. %% %% %% %% %% %% %% %% .. .. .. .. .. .. .. .. .. .. .. .. .. }0 .. .. .. %% 00 00 %% }1 }2 .. }0 }0 }0 .. 23 .. .. .. .. .. =A \\ du pe %% &1 &1 %% &6 &6 .. ec ec ec .. &4 .. .. .. .. .. du pe &3 &8 %% &9 &8 %% {0 {1 .. &A &B &C .. [[ .. .. .. .. .. &2 &9 \/ \/ %% &6 &7 %% .. .. .. {5 {2 {6 .. .. .. .. .. .. .. \/ \/ .. .. %% \/ \/ %% .. .. .. .. .. .. .. .. .. .. .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% }1 .. .. }1 .. .. }1 .. .. .. .. .. .. .. .. .. .. .. .. .. .. &7 .. .. &7 }2 .. &7 }2 .. .. .. .. .. .. .. .. .. .. .. .. .. =1 \/ .. mi nu .. mi nu .. .. .. .. .. .. .. .. .. .. .. .. .. &A .. .. =1 \/ .. =2 \/ .. .. .. .. .. .. .. .. .. .. .. .. .. \/ .. .. &B .. .. &C .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \/ .. .. \/ .. .. .. .. .. .. .. .. .. .. .. .. .. .. 00 .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ !! # Encoding # # convert the char code to the encoding :ec }0 .. .. .. .. .. ++ .. .. .. .. .. >> .. .. .. .. .. >> .. .. .. .. .. =S =B =C =N =9 .. &0 &1 &2 &3 &4 &5 \/ \/ \/ \/ \/ \/ 01 0A 0C 0B 0A 00 &0 &1 &2 &3 &4 &5 \\ \\ \\ {0 // // # Print Bottom # # prints #\n then # repeated }0 times :pb 0A .. @0 .. @1 .. 23 .. &0 .. &0 .. [[ 23 /\ [[ -- .. .. @0 .. }0 >0 \/ .. .. .. \\ @1 .. # Print Cell # # }0 = the width of the board # }1 = the position of the cell to print # }2 = the cell to print # # prints the cell and a newline if needed :printc %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% }0 }1 %% .. %% }2 .. .. .. .. %% .. .. .. .. }2 %% }1 }0 %% .. %% %% is bd %% 23 %% &0 .. .. .. .. %% 20 2D 5C 2F tn %% ++ .. %% 0A %% %% =1 &0 %% &1 %% =0 =A =B =C <A %% &2 &3 &4 &5 &6 %% di vb %% &7 %% %% &1 \/ %% [[ %% &2 &3 &4 &5 &6 %% [[ [[ [[ [[ [[ %% =1 \/ %% [[ %% %% \/ .. %% .. %% \/ \/ \/ \/ \/ %% .. .. .. .. .. %% &7 .. %% .. %% %% .. .. %% .. %% .. .. .. .. .. %% .. .. .. .. .. %% \/ .. %% .. %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% # Is Border # # }0 = board width # }1 = position # # {0 = 1 if on border else 0 :isbd }1 }0 }1 }0 .. .. ++ .. di vb di vb \\ {0 // .. # Solve Values # # takes input in a t: # takes 4 cells in a t shape: # x or 1 # xxx 234 # and returns their values # after 1 tick :solvevls # &0) center is space # &1) center is wall # &2) left slide & left is space # &3) left slide & left isn't space # &4) right slide & right is space # &5) right slide & right isn't space # &7) no ball %% %% %% %% %% %% %% %% %% %% %% %% }0 .. .. .. .. .. .. .. .. %% # Top Center %% du pe 6x 6x 6x 6x .. .. .. %% %% <A <A <A <A <A <A &7 .. .. %% %% &0 &1 &2 &3 &4 &5 \/ .. .. %% %% \/ \/ \/ \/ \/ \/ .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% }1 .. .. .. .. .. .. .. .. %% # Bottom Left %% du pe 6x 6x 6x 6x .. .. .. %% %% .. .. <A >9 .. .. \/ .. .. %% %% .. .. &2 &3 .. .. .. .. .. %% %% \/ \/ \/ \/ \/ \/ .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% }2 .. .. .. .. .. .. .. .. %% # Bottom Center %% du pe 6x 6x 6x 6x .. .. .. %% %% <A =A =C =C =B =B \/ .. .. %% %% &0 &1 &2 &3 &4 &5 .. .. .. %% %% \/ \/ \/ \/ \/ \/ .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% }3 .. .. .. .. .. .. .. .. %% # Bottom Right %% du pe 6x 6x 6x 6x .. .. .. %% %% .. .. .. .. <A >9 \/ .. .. %% %% .. .. .. .. &4 &5 .. .. .. %% %% \/ \/ \/ \/ \/ \/ .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% %% .. .. }0 .. %% .. .. .. .. %% %% 00 }1 }2 }3 %% }0 }1 }2 }3 %% %% &0 &0 &0 &0 %% &1 &1 &1 &1 %% %% {0 {1 {2 {3 %% {0 {1 {2 {3 %% %% %% %% %% %% %% %% %% %% %% %% %% .. }0 .. .. %% .. .. .. .. %% %% 00 }1 }2 }3 %% }0 }1 }2 }3 %% %% &2 &2 &2 &2 %% &3 &3 &3 &3 %% %% {0 {1 {2 {3 %% {0 {1 {2 {3 %% %% %% %% %% %% %% %% %% %% %% %% %% .. .. .. }0 %% .. .. .. .. %% %% 00 }1 }2 }3 %% }0 }1 }2 }3 %% %% &4 &4 &4 &4 %% &5 &5 &5 &5 %% %% {0 {1 {2 {3 %% {0 {1 {2 {3 %% %% %% %% %% %% %% %% %% %% %% %% %% .. .. .. .. %% .. .. .. .. %% %% }0 }1 }2 }3 %% .. .. .. .. %% %% &7 &7 &7 &7 %% .. .. .. .. %% %% {0 {1 {2 {3 %% .. .. .. .. %% %% %% %% %% %% %% %% %% %% %% %% # @0 set tape to position # @7 gets zero once complete # @1 send current marble to location + advance one # @2 write to current marble + advance one # &0 = marble tape # &1 = counter # @3 counter loop # @4, @5, @6 # .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # .. .. .. 08 @5 .. .. .. .. .. .. .. .. .. .. # .. 07 &0 // // .. .. .. .. .. .. .. .. .. .. # .. \\ &0 06 .. .. .. .. .. .. .. .. .. .. .. # .. 05 &0 // .. .. .. .. .. .. .. .. .. .. .. # .. \\ &0 04 .. .. .. .. .. .. .. .. .. .. .. # .. 03 &0 // .. .. .. .. .. .. .. .. .. .. .. # .. \\ &0 02 .. .. .. .. .. .. .. .. .. .. .. # .. 01 &0 // .. .. .. .. .. .. .. .. .. .. .. # .. \\ &0 00 .. .. .. .. .. .. .. .. .. .. .. # .. 00 &0 // .. .. .. .. .. .. .. .. .. .. .. # .. \\ &0 00 .. .. .. .. .. .. .. .. .. .. .. # .. 00 &0 // .. .. .. .. .. .. .. .. .. .. .. # .. \\ &0 .. .. .. .. .. .. .. .. .. .. .. .. # .. .. /\ @5 .. .. .. .. 00 .. .. .. .. .. .. # .. >0 @8 .. .. .. .. .. .. .. .. .. .. .. .. # .. &1 .. .. .. .. .. .. .. .. .. .. .. .. .. # .. .. .. .. .. .. .. @8 .. @9 .. .. .. .. .. # .. .. .. .. .. .. .. \\ &0 // .. .. .. .. .. # .. .. .. .. .. .. .. .. \/ .. .. .. .. .. .. # .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # .. .. .. .. .. .. .. .. @3 00 .. .. .. .. .. # .. .. .. .. .. .. .. .. &1 // .. .. .. .. .. # .. .. .. .. .. .. .. .. ++ .. .. .. .. .. .. # .. .. .. .. .. .. .. @3 /\ .. .. .. .. .. .. # .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # .. .. .. .. .. .. 05 @0 @4 .. .. .. .. .. .. # .. .. .. .. .. .. \\ \\ te st .. .. .. .. .. # .. .. .. .. .. .. .. .. @4 .. =0 \\ .. .. .. # .. .. .. .. .. .. .. .. .. .. @9 .. .. .. .. # .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # .. .. .. .. .. .. .. .. .. .. .. .. \/ .. .. # Test Equality # # if }0 == }1 sends 00 to {0 and 01 to {> # else sends }0 to {0 and 00 to {> :test }0 }1 .. .. .. .. .. mi nu .. .. }0 .. .. =0 \\ \\ &0 &0 .. .. du pe 3x \/ du pe 3x ez eo .. .. .. .. ez {0 {> !! .. !! {0 {> ### SIMPLE HELPERS ### # Send # # sends }1 to {0 if }0 = 0 else {1 :send }0 .. 00 =0 &1 .. &0 \/ .. \/ .. .. }1 }1 .. &0 &1 .. {0 {1 !! # Marker # # does nothing :%% }0 {0 ## EQUALS ## # Equals Max # # sends FF to {0 :em }0 FF .. {0 # Equal One # # sends 01 to {0 :eo }0 01 .. {0 # Equal Zero # # sends 00 to {0 :ez }0 00 .. {0 ## DUPLICATE ## # Duplicate 2 times # # sends }0 to {0 and {1 :dupe .. }0 .. {0 /\ {1 # Duplicate 3 times # # sends }0 to {0, {1, and {2 :dupe3x .. }0 .. .. .. /\ .. .. .. .. /\ .. .. .. .. // {0 {1 {2 .. # Duplicate 4 times # # sends }0 to {0, {1, {2, and {3 :dupe4x4x .. }0 .. .. .. .. /\ .. .. .. .. .. /\ .. .. .. .. .. /\ .. .. .. .. .. // {0 {1 {2 {3 .. # Duplicate 6 times # # sends }0 to {0, {1, {2, {3, {4 and {5 :dupe6x6x6x6x .. }0 .. .. .. .. .. .. /\ .. .. .. .. .. .. .. /\ .. .. .. .. .. .. .. /\ .. .. .. .. .. .. .. /\ .. .. .. .. .. .. .. /\ .. .. .. .. .. .. .. // {0 {1 {2 {3 {4 {5 .. ### MATH ### # Divisible By # # returns }0 % }1 == 0 :divb }0 }1 mo du =0 &1 &0 .. 01 00 &0 &1 {0 {0 # Modulo # # sends }0 % }1 to {0 # # if }0 > }1 return modu }0 - }1 else }0 :modu }0 }1 Gt eq # interpreter includes this =1 &0 &1 \/ \/ .. }0 .. &0 .. {0 .. .. .. }0 }1 mi nu &1 }1 mo du {0 .. # To Number Char # # converts number 0-9 to a number character :tn }0 +F +F +F +3 {0 # Plus # # sends }0 + }1 to {0 :plus }0 .. }1 \\ {0 // # Minus # # sends }0 - }1 to {0 :minu .. }1 }0 ng \\ {0 # Negative # # sends -}0 to {0 :ng }0 ~~ ++ {0 ``` [Answer] # JavaScript (ES6), 157 ~~196~~ **Edit** char by char instead of row by row, much better result ``` g=>(s=~g.search` `,g=[...g]).map((c,i)=>c<' '?0:g[[0,1,-1].map(d=>!d|'\\ /'[d+1]==g[d+=i]&&+g[d+=s]?g[v+=+g[d],d+v-v]=' ':0,v=c>'a'?1:+c),i]=v?v:c)&&g.join`` ``` Note: does not handle ball values > 9. But it could, with a 18 bytes cost. See basic code below. **TEST snippet** (better full page) ``` F=g=>(s=~g.search` `,g=[...g]).map((c,i)=>c<' '?0:g[[0,1,-1].map(d=>!d|'\\ /'[d+1]==g[d+=i]&&+g[d+=s]?g[v+=+g[d],d+v-v]=' ':0,v=c=='o'?1:+c),i]=v?v:c)&&g.join`` // Basic code, starting point before golfing B=g=>{ s = ~g.search('\n'); (g=[...g]).map((c,i)=>{ v = c == 'o' ? 1 : +c if (c>=' ' // skip newlines && !isNaN(v)) // digit or space { if (w=+g[i+s]) v += w, g[i+s]=' ' if (g[i-1]=='\\' && (w=+g[i+s-1])) v += w, g[i+s-1]=' ' if (g[i+1]=='/' && (w=+g[i+s+1])) v += w, g[i+s+1]=' ' if (v) g[i] = v } }) // return g.join`` // To handle values > 9 ... return g.map(v=>+v?v%10:v).join`` } function test() { O.textContent = F(I.value) } test() ``` ``` textarea,pre { width: 15em; height: 15em; display: block; margin: 0; } iframe { height: 25em; width: 15em} td { vertical-align: top } ``` ``` <table> <tr> <th>Test cases</th> <th>Input</th> <td></td> <th>Output</th> </tr><tr> <td> Copy/paste test cases from here <br>(courtesy of OP) <button onclick="T.src='http://bohem.io/wadus/index.php'">reload</button><br> <iframe id=T src="http://bohem.io/wadus/index.php"></iframe> </td> <td><textarea id=I>########## # o o o# # o\o o # #oo o/ # # o# # /o # #\o o # # o /- # # o - # ##########</textarea></td> <td><button onclick='test()'>Test</button></td> <td><pre id=O></pre></td> </tr> </table> ``` [Answer] # Javascript (ES6), ~~453~~ ~~426~~ ~~409~~ ~~306~~ ~~290~~ 286 bytes The first and most obvious solution that came to my mind is one that looks around the slides and then merges or replaces. ``` a=>{a=a.split` `.map(b=>[...b.replace(/o/g,'1')]);for(r=1;r<a.length-1;r++){d=a[r];for(c=1;c<d.length-1;c++){e=a[r+1];f=e[c]=='\\'?c+1:e[c]=='/'?c-1:!isNaN(+e[c])?c:null;(''+d[c]).match(/[0-9]/g)&&f!=null&&!isNaN(+e[f])?(e[f]=+e[f]+ +d[c],d[c]=' '):0}}return a.map(b=>b.join``).join` `} ``` Ungolfed: ``` func = state => { state = state.split ` `.map(line => [...line.replace(/o/g, '1')]); for (r = 1; r < state.length - 1; r++) { thisState = state[r]; for (c = 1; c < thisState.length - 1; c++) { nextState = state[r + 1]; nc = nextState[c] == '\\' ? c + 1 : nextState[c] == '/' ? c - 1 : !isNaN(+nextState[c]) ? c : null; ('' + thisState[c]).match(/[0-9]/g) && nc != null && !isNaN(+nextState[nc]) ? ( nextState[nc] = +nextState[nc] + +thisState[c], thisState[c] = ' ' ) : 0; } } return state.map(line => line.join ``).join ` `; } ``` Test like: ``` func(`########## # -- o - # # \\\\\\ - # #- # # o o # #o \\\\ /-\\# # \\ # #/- // # # /- o # ##########`) ``` *Thanks to: [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)* [Answer] ## Java, ~~Too Many~~ ~~1102~~ 987 bytes [Because, Java.](http://meta.codegolf.stackexchange.com/a/5829) \o/ It's under 1000! ``` class G{class T{char s;int p=0;T(char c){s=c;}}T A=new T(' ');T[][]o;boolean i(){for(int i=1;i<o.length;i++)for(int j=1;j<o[i].length;j++)if(o[i][j].p>0){if(m(i,j,i+1,j)||o[i+1][j].s=='/'&&m(i,j,i+1,j-1)||o[i+1][j].s=='\\'&&m(i,j,i+1,j+1))return 1>0;int w=o[i][j].p;o[i][j]=new T(Integer.toString(w).charAt(0)){{p=w;}};}return 1<0;}boolean m(int a,int b,int c,int d){if(o[c][d]==A||o[c][d].p>0){o[a][b].p+=o[c][d].p;o[c][d]=o[a][b];o[a][b]=A;return 1>0;}return 1<0;}String s(){String s="";for(T[]r:o){for(T t:r)s+=t.s;s+="\n";}return s;}void f(String s){String[]r=s.split("\\\\n");o=new T[r.length][r[0].length()];for(int i=0;i<o.length;i++)for(int j=0;j<o[i].length;j++)switch(r[i].charAt(j)){case'-':o[i][j]=new T('-');break;case'\\':o[i][j]=new T('\\');break;case'/':o[i][j]=new T('/');break;case'o':o[i][j]=new T('o'){{p=1;}};break;case'#':o[i][j]=new T('#');break;default:o[i][j]=A;}}public static void main(String[]a){G g=new G();g.f(a[0]);while(g.i());System.out.println(g.s());}} ``` A side goal was being able to print every iteration of the board: just remove the middle `;` in `while(g.i())` `;` `System.out.print(g.s());` (Though this does disable the last print which has the 0->power conversion). Unfortunately, in this version, gravity works in strangely. Each pass I take the first non-stuck ball and move it. Short circuiting `iterate()` there is less bytes than going over the whole board then returning if anything changed. This is a complete main class, compile and run on the command line with argument: ``` java -jar G.jar "##########\n# o-/ #\n#- / -/ #\n# oo o #\n# / \o #\n# o o \#\n# o #\n# -\o #\n#\ \\ o/#\n##########" ``` "Readable" version: ``` class GravitySimulator { class Token { char symbol; int power = 0; Token(char c) { symbol = c; } } Token A = new Token(' '); Token[][] board; boolean iterate() { for (int i=1; i<board.length; i++) for (int j=1; j<board[i].length; j++) if (board[i][j].power>0) { if (move(i,j,i+1,j) || board[i+1][j].symbol=='/' && move(i,j,i+1,j-1) || board[i+1][j].symbol=='\\' && move(i,j,i+1,j+1)) return true; int pow = board[i][j].power; board[i][j] = new Token(Integer.toString(pow).charAt(0)){{power=pow;}}; } return false; } boolean move(int x1, int y1, int x2, int y2) { if (board[x2][y2] == A || board[x2][y2].power>0) { board[x1][y1].power += board[x2][y2].power; board[x2][y2] = board[x1][y1]; board[x1][y1] = A; return true; } return false; } String string() { String s = ""; for (Token[] row : board) { for (Token token : row) s+=token.symbol; s+="\n"; } return s; } void fromString(String s) { String[] rows = s.split("\\\\n"); board = new Token[rows.length][rows[0].length()]; for (int i=0; i<board.length; i++) for (int j=0; j<board[i].length; j++) switch(rows[i].charAt(j)) { case '-': board[i][j]=new Token('-');break; case '\\':board[i][j]=new Token('\\');break; case '/': board[i][j]=new Token('/');break; case 'o': board[i][j]=new Token('o'){{power=1;}};break; case '#': board[i][j]=new Token('#');break; default: board[i][j]=A; } } public static void main(String[] args) { GravitySimulator g = new GravitySimulator(); g.fromString(args[0]); while(g.iterate()); System.out.println(g.string()); } } ``` [Answer] ## Python3, 355b ``` g=g.replace("o","1").split("\n") r=1 while r: r=0 for y in range(len(g)): for x in range(len(g[y])): if g[y][x].isdigit(): h=g[y+1] m={"/":-1,"\\":1} j=x+m[h[x]]if h[x]in m else x if("0"+h[j].strip()).isdigit(): r=1 g[y+1]=h[:j]+str(int(g[y][x])+int("0"+h[j]))+h[j+1:] g[y]=g[y][:x]+' '+g[y][x+1:] print("\n".join(g)) ``` [Test here](https://repl.it/Bb4Y/1) [Answer] # PHP, ~~228 204 197~~ 194 bytes ``` for($a=strtr($a,o,1);$c=$a[$i];$i++)$c>0&&(($d=$a[$t=$i+strpos($a," ")+1])>" "?$d!="/"?$d!="\\"?$d>0:$a[++$t]<"!"||$a[$t]>0:$a[--$t]<"!"||$a[$t]>0:1)&&$a[$t]=min($a[$t]+$c,9).!$a[$i]=" ";echo$a; ``` yields warnings in PHP 7.1. Insert `(int)` before `$a[$t]+$c` to fix. Run with `php -nr '$a="<string>";<code>'` or [try it online](http://sandbox.onlinephpfunctions.com/code/58766c66396d99f43599ce05d60a35800071d099). **breakdown** ``` for($a=strtr($a,o,1); # replace "o" with "1" $c=$a[$i];$i++) # loop through string $c>0 # if character is numeric &&(($d=$a[ # and ... $t=$i+ # 3: target position = current position + 1 line strpos($a,"\n")+1 # 2: width = (0-indexed) position of first newline +1 ])>" " # if target char is not space ?$d!="/" # and not left slide ?$d!="\\" # and not right slide ?$d>0 # but numeric: go :$a[++$t]<"!"||$a[$t]>0 # right slide: if target+1 is space or ball, then go :$a[--$t]<"!"||$a[$t]>0 # left slide: if target-1 is space or ball, then go :1 # space: go )&& # if go: $a[$t]=min($a[$t]+$c,9) # move ball/merge balls .!$a[$i]=" " # clear source position ; echo$a; # print string ``` ]
[Question] [ You are given as input a greyscale image. Your task is to find a static or looping pattern in Conway's [Game of Life](http://en.wikipedia.org/wiki/Conway's_Game_of_Life) that resembles the input image as closely as possible. Your output can be *either* a still image or a looping animation in some format that can be converted to gif. The output image dimensions should be the same as the input, and it must contain only black and white pixels. If the output is an animation, each frame must be generated from the previous one according to the Game of Life rules, with one cell per pixel. The animation must loop, with the first frame being generated from the last frame by the same rules. If the output is a still image, applying the game-of-life rules to it must produce the same image. This means that no 'alive' cell may have more than three or less than two 'alive' neighbours, and no 'dead' cell may have exactly three 'alive' neighbours. (Note that this is basically the same as an animation as described above, but with only one frame.) Extra rules and clarifications: * You (or your program) may choose whether 'alive' cells are represented as white and 'dead' as black, or vice versa. That is, you can either hard-code this or your program can choose it based on the input image. (But it must be the same for every frame of the animation.) * The boundary conditions should be periodic, meaning that cells on the rightmost column have neighbours on the leftmost column, etc. * For animations, the frame rate is up to you (or your program); I imagine fast frame rates will work well for approximating grey pixels. * Please post at least two results embedded in your answer. If you can post results from all of the input images below, it's preferable. * It is acceptable to scale down the test images if this is necessary in order to achieve gifs with small enough file sizes. If you want to link to larger files as well, that's fine. If you want to show off, feel free to find some higher-resolution source files. * Please try to avoid having too many controllable parameters in your code - it's best if your program's only input is the image. The exception is if you want to have a parameter for controlling the number of animation frames, since that will affect the file size. * You may use external programs to change the format of the input and output files, and/or compile output frames into an animation if you want. (This is not a file-format-handling challenge.) * This is [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most votes wins. Here is a selection of test images, mostly taken from other questions on this site. (It's possible that I will add additional "bonus" input images later.) ![enter image description here](https://i.stack.imgur.com/k2caC.png) ![enter image description here](https://i.stack.imgur.com/B2DBy.jpg) ![enter image description here](https://i.stack.imgur.com/T5ajB.png) ![enter image description here](https://i.stack.imgur.com/vIZ8x.png) ![enter image description here](https://i.stack.imgur.com/mNnzM.png) Just to get things started, here's a very dumb reference attempt in Python 2, which takes advantage of the fact that a block of four squares is a stable structure in the Game of Life. It just rescales the input image by a factor of 4, then draws a block if the corresponding pixel is darker than 0.5. ``` from skimage import io from skimage import transform import sys img = io.imread(sys.argv[1],as_grey=True) source = transform.resize(img, [i/4 for i in img.shape]) img[:]=1 for x in xrange(source.shape[0]): for y in xrange(source.shape[1]): if source[x,y]<0.5: img[x*4, y*4] = 0 img[x*4+1, y*4] = 0 img[x*4, y*4+1] = 0 img[x*4+1, y*4+1] = 0 io.imsave(sys.argv[2], img) ``` Here are some outputs from the example code. I'm sure that *much* better results are possible. ![enter image description here](https://i.stack.imgur.com/rpuP9.png) ![enter image description here](https://i.stack.imgur.com/aTJgu.png) [Answer] # Python ``` import sys, random, itertools from PIL import Image filename, cutoff = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 128 # load command-line arg as image src = Image.open(sys.argv[1]).convert("L") # grayscale (w, h), src = src.size, src.load() # flatten src = bytearray(src[x, y] for y in range(h) for x in range(w)) size = len(src) neighbour_offsets = (-w-1,-w,-w+1,-1,1,w-1,w,w+1) shapes = set() max_shape_x, max_shape_y = 0, 0 for shape in (((1, 1), (1, 1), "b"), # block ((0,1,1,0),(1,0,0,1),(0,1,1,0), "h"), # hive ((0,0,1,0),(0,1,0,1),(1,0,0,1),(0,1,1,0), "l"), # loaf ((0,1,0),(1,0,1),(0,1,0), "t"), # tub ((1,1,0),(1,0,1),(0,1,0), "B"), # boat ((1,1,0),(1,0,1),(0,1,1), "s"), # ship ((1,1,0,1,1),(0,1,0,1,0),(0,1,0,1,0),(1,1,0,1,1), "I"), # II ((0,0,0,1,1),(0,0,0,0,1),(0,0,0,1,0),(1,0,1,0,0),(1,1,0,0,0), "c"), # canoe sinking ((1,1,0,0),(1,0,0,1),(0,0,1,1), "a"), # aircraft carrier ((0,1,1,0,0),(1,0,0,1,0),(0,1,0,0,1),(0,0,1,1,0), "m"), # mango ((0,1,1,0),(1,0,0,1),(1,0,0,1),(0,1,1,0), "p"), # pond ((0,0,0,1,1),(0,0,1,0,1),(0,0,1,0,0),(1,0,1,0,0),(1,1,0,0,0), "i"), # integral ((1,1,0,1),(1,0,1,1), "S"), # snake ((1,1,0,0),(1,0,1,0),(0,0,1,0),(0,0,1,1), "f"), # fish hook ): X, Y = len(shape[0]), len(shape)-1 max_shape_x, max_shape_y = max(X, max_shape_x), max(Y, max_shape_y) shapes.add(((X, Y), tuple(y*w+x for y in range(Y) for x in range(X) if shape[y][x]), shape[:-1], shape[-1])) shapes.add(((X, Y), tuple(y*w+x for y in range(Y) for x in range(X-1,-1,-1) if shape[y][x]), shape[:-1], shape[-1])) shapes.add(((X, Y), tuple(y*w+x for y in range(Y-1,-1,-1) for x in range(X) if shape[y][x]), shape[:-1], shape[-1])) shapes.add(((X, Y), tuple(y*w+x for y in range(Y-1,-1,-1) for x in range(X-1,-1,-1) if shape[y][x]), shape[:-1], shape[-1])) def torus(i, *indices): if len(indices) == 1: return (i + indices[0]) % size return [(i + n) % size for n in indices] def iter_neighbours(i): return torus(i, *neighbour_offsets) def conway(src, dest): for i in range(size): alive = count_alive(src, i) dest[i] = (alive == 2 or alive == 3) if src[i] else (alive == 3) def calc_score(i, set): return 255-src[i] if not set else src[i] def count_alive(board, i, *also): alive = 0 for j in iter_neighbours(i): if board[j] or (j in also): alive += 1 return alive def count_dead(board, i, *also): dead = 0 for j in iter_neighbours(i): if (not board[j]) and (j not in also): dead += 1 return dead def iter_alive(board, i, *also): for j in iter_neighbours(i): if board[j] or (j in also): yield j def iter_dead(board, i, *also): for j in iter_neighbours(i): if (not board[j]) and (j not in also): yield j def check(board): for i in range(size): alive = count_alive(board, i) if board[i]: assert alive == 2 or alive == 3, "alive %d has %d neighbours %s" % (i, alive, list(iter_alive(board, i))) else: assert alive != 3, "dead %d has 3 neighbours %s" % (i, list(iter_alive(board, i))) dest = bytearray(size) if False: # turn into contrast for i in range(size): mx = max(src[i], max(src[j] for j in iter_neighbours(i))) mn = min(src[i], min(src[j] for j in iter_neighbours(i))) dest[i] = int((0.5 * src[i]) + (128 * (1 - float(src[i] - mn) / max(1, mx - mn)))) src, dest = dest, bytearray(size) try: checked, bad, score_cache = set(), set(), {} next = sorted((calc_score(i, True), i) for i in range(size)) while next: best, best_score = None, sys.maxint current, next = next, [] for at, (score, i) in enumerate(current): if score > cutoff: break if best and best_score < score: break if not dest[i] and not count_alive(dest, i): do_nothing_score = calc_score(i, False) clean = True for y in range(-max_shape_y-1, max_shape_y+2): for x in range(-max_shape_x-1, max_shape_x+2): if dest[torus(i, y*w+x)]: clean = False break if not clean: break any_ok = False for (X, Y), shape, mask, label in shapes: for y in range(Y): for x in range(X): if mask[y][x]: pos, ok = torus(i, -y*w-x), True if (pos, label) in bad: continue if clean and (pos, label) in score_cache: score = score_cache[pos, label] else: paint = torus(pos, *shape) for j in paint: for k in iter_alive(dest, j, *paint): if count_alive(dest, k, *paint) not in (2, 3): ok = False break if not ok: break for k in iter_dead(dest, j, *paint): if count_alive(dest, k, *paint) == 3: ok = False break if not ok: break if ok: score = 0 any_ok = True for x in range(X): for y in range(Y): score += calc_score(torus(pos, y*w+x), mask[y][x]) score /= Y*X if clean: score_cache[pos, label] = score else: bad.add((pos, label)) if ok and best_score > score and do_nothing_score > score: best, best_score = (pos, shape, label), score if any_ok: next.append((score, i)) if best: pos, shape, label = best shape = torus(pos, *shape) sys.stdout.write(label) sys.stdout.flush() for j in shape: dest[j] = True check(dest) next += current[at+1:] else: break except KeyboardInterrupt: pass print if True: check(dest) anim = False while dest != src: if anim: raise Exception("animation!") else: anim = True sys.stdout.write("x"); sys.stdout.flush() conway(dest, src) dest, src = src, dest check(dest) # canvas out = Image.new("1", (w, h)) out.putdata([not i for i in dest]) # tk UI Tkinter = None try: import Tkinter from PIL import ImageTk root = Tkinter.Tk() root.bind("<Button>", lambda event: event.widget.quit()) root.geometry("%dx%d" % (w, h)) show = ImageTk.PhotoImage(out) label = Tkinter.Label(root, image=show) label.pack() root.loop() except Exception as e: print "(no Tkinter)", e Tkinter = False if len(sys.argv) > 3: out.save(sys.argv[3]) if not Tkinter: out.show() ``` ## Please squint: ![enter image description here](https://i.stack.imgur.com/3S0v2.png) ![enter image description here](https://i.stack.imgur.com/Wqx63.png) ![enter image description here](https://i.stack.imgur.com/AsCX0.png) ![enter image description here](https://i.stack.imgur.com/nPK5K.png) ![enter image description here](https://i.stack.imgur.com/cBcGi.png) ![enter image description here](https://i.stack.imgur.com/3raFK.png) The code stamps on the whitest pixels with the best-fitting [standard still life](http://en.wikipedia.org/wiki/Still_life_(cellular_automaton)). There's a cut-off argument so you get to decide were the rounding to black-white threshold goes. I've experimented with living-is-white and the outcome is much the same. [Answer] # Java An edge-detection-based approach. Requires [this text file](https://gist.githubusercontent.com/SuperJedi224/16eb4790df7d52439257/raw/4f491cabb27d0390d4b1774bc11b7d5f55635e45/lib.txt) in the running directory. ``` import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.*; import javax.imageio.ImageIO; public class StillLifer{ private static List<boolean[][]>patterns=new ArrayList<>(); private static boolean[][] copy(boolean[][]b,int x,int y){ boolean[][]r=new boolean[6][6]; for(int i=0;i<6;i++){ for(int j=0;j<6;j++){ r[i][j]=b[y+i][x+j]; } } return r; } private static void paste(boolean[][]from,boolean[][]to,int x,int y){ for(int i=0;i<from.length;i++)for(int j=0;j<from[0].length;j++){ to[y+i][x+j]=from[i][j]; } } private static boolean[][]findClosest(boolean[][]b){ boolean[][]c=null; int d=999999; for(boolean[][]k:patterns){ int d2=editDistance(b,k); if(d2<d){ c=k; d=d2; } } return c; } private static boolean[][]decode(String s){ char[]a=s.toCharArray(); boolean[][]r=new boolean[6][6]; int k=0; for(int i=0;i<6;i++){ for(int j=0;j<6;j++){ r[i][j]=a[k++]=='1'; } } return r; } private static class EdgeDetectEntry{ int l; int x; int y; public EdgeDetectEntry(int m,int x,int y){ this.l=m; this.x=x; this.y=y; } } private static Random rand; private static int w,h; private static BufferedImage img; private static boolean[][]grid; private static File file; private static int editDistance(boolean[][]from,boolean[][]to){ int w=from.length; int h=from[0].length; int k=0; for(int x=0;x<w;x++){ for(int y=0;y<h;y++){ k+=from[y][x]^to[y][x]?1:0; } } return k; } private static int colorDistance(Color from,Color to){ return from.getRed()-to.getRed(); } private static int edgeDetectWeight(int x,int y){ int k=0; Color c=new Color(img.getRGB(x, y)); for(int x2=Math.max(0,x-1);x2<Math.min(w,x+2);x2++){ for(int y2=Math.max(0,y-1);y2<Math.min(h,y+2);y2++){ int l=colorDistance(c,new Color(img.getRGB(x2, y2))); k+=l*l; } } return k; } private static void save() throws Exception{ int bk=Color.BLACK.getRGB(); int wt=Color.WHITE.getRGB(); for(int x=0;x<w;x++){ for(int y=0;y<h;y++){ img.setRGB(x,y,grid[y][x]?wt:bk); } } String k=file.getName().split("\\.")[0]; ImageIO.write(img,"png",new File(k="out_"+k+".png")); } private static String rle(boolean[][]grid){ StringBuilder st=new StringBuilder(); for(boolean[]row:grid){ for(int j=0;j<row.length;j++){ int k=1; for(;j<row.length-1&&row[j]==row[j+1];j++)k++; if(k!=1)st.append(Integer.toString(k,36)); st.append(row[j]?'@':'-'); } } return st.toString(); } private static int getVal(boolean[][]grid,int x,int y){ if(x<0)x+=w; if(y<0)y+=h; if(x==w)x=0; if(y==h)y=0; return grid[y][x]?1:0; } private static boolean newState(boolean[][]grid,int x,int y,String rule){ String[]r=rule.split("/"); int k=0; for(int a=-1;a<=1;a++)for(int b=-1;a<=1;a++)k+=(a|b)==0?0:getVal(grid,x+a,y+b); String s=Integer.toString(k); return grid[y][x]?r[1].contains(s):r[0].contains(s); } private static boolean[][] next(boolean[][]grid,String rule){ boolean[][]r=new boolean[h][w]; for(int x=0;x<w;x++){ for(int y=0;y<h;y++){ r[y][x]=newState(grid,x,y,rule); } } return r; } private static void loadPatterns() throws Exception{ Scanner reader=new Scanner(new File("lib.txt")); while(reader.hasNext()){ String line=reader.nextLine(); if(line.startsWith("--"))continue; patterns.add(decode(line)); } reader.close(); } public static void main(String[]a) throws Exception{ loadPatterns(); Scanner in=new Scanner(System.in); img=ImageIO.read(file=new File(in.nextLine())); in.close(); w=img.getWidth(); h=img.getHeight(); grid=new boolean[h][w]; final int npix=w*h; rand=new Random(npix*(long)img.hashCode()); List<EdgeDetectEntry> list=new ArrayList<>(); for(int x=0;x<w;x++){ for(int y=0;y<h;y++){ list.add(new EdgeDetectEntry(edgeDetectWeight(x,y),x,y)); } } list.sort((one,two)->{int k=two.l-one.l;if(k>0)return 1;if(k<0)return -1;return 0;}); for(int i=Math.max(Math.min(3,npix),npix/5);i>0;i--){ EdgeDetectEntry e=list.get(i); grid[e.y][e.x]=rand.nextDouble()<0.9; } grid=next(grid,"/2345678"); boolean[][]d=new boolean[h][w]; for(int i=0;i<w/6;i++){ for(int j=0;j<h/6;j++){ paste(findClosest(copy(grid,i*6,j*6)),d,i*6,j*6); } } grid=d; assert(rle(next(grid,"3/23")).equals(rle(grid))); save(); } } ``` Some results: ![enter image description here](https://i.stack.imgur.com/taa0J.png) ![enter image description here](https://i.stack.imgur.com/XjOhT.png) ![enter image description here](https://i.stack.imgur.com/H27Ct.png) ![enter image description here](https://i.stack.imgur.com/N5yKy.png) ![enter image description here](https://i.stack.imgur.com/NP8Vr.png) [Answer] # C++ Straightforward pixelation approach using the average of each 8x8 grid to select an 8x8 output grid (a "color texture"). Each 8x8 output grid has a 2 cell separator at the top and right. Grids were designed ranging from 4 cell still lifes to 18 cell still lifes within the remaining 6x6 pixels. The program acts as a filter from binary PGM to binary PBM. By default, images are "dark"; black is death and white is life; `-i` inverts this. `-g [value]` adds a gamma, which is used to pre-weight averages before selecting the color textures. ``` #include <iostream> #include <vector> #include <string> #include <sstream> #include <cmath> // colors 4 through 18 have 4 through 18 live cells // colors 1-3 are repetitions of 0 or 4 used // as artificially weighted bins unsigned char gol_colors[]={ 0, 0, 0, 0, 0, 0, 0, 0 // Color 0 , 0, 0, 0, 0, 0, 0, 0, 0 // Color 1 , 0, 0, 0, 16, 40, 16, 0, 0 // Color 2 , 0, 0, 0, 16, 40, 16, 0, 0 // Color 3 , 0, 0, 0, 16, 40, 16, 0, 0 // Color 4 , 0, 0, 0, 24, 40, 16, 0, 0 // Color 5 , 0, 0, 0, 16, 40, 80, 32, 0 // Color 6 , 0, 0, 0, 48, 72, 40, 16, 0 // Color 7 , 0, 0, 8, 20, 8, 64,160, 64 // Color 8 , 0, 0, 8, 20, 8, 64,160, 96 // Color 9 , 0, 0, 12, 20, 8, 64,160, 96 // Color 10 , 0, 0, 12, 20, 8,192,160, 96 // Color 11 , 0, 0,204,204, 0, 0, 48, 48 // Color 12 , 0, 0,204,204, 0,192,160, 64 // Color 13 , 0, 0, 0,108,168,168,108, 0 // Color 14 , 0, 0, 96,144,104, 40,172,192 // Color 15 , 0, 0,204,204, 0, 0,204,204 // Color 16 , 0, 0,216,216, 0,216,212, 8 // Color 17 , 0, 0,204,164, 40, 80,148,204 // Color 18 }; enum { gol_bins = sizeof(gol_colors)/(sizeof(*gol_colors))/8 }; bool inverted=false; bool applygamma=false; double gammasetting=0.0; unsigned int corrected(unsigned int i, unsigned int r) { return static_cast<unsigned int>(r*std::pow(i/static_cast<double>(r), gammasetting)); } int main(int argc, char** argv) { std::vector<unsigned short> pgm_data; unsigned pgm_width; unsigned pgm_height; unsigned pgm_vpp; std::vector<unsigned char> pbm_data; unsigned pbm_width; unsigned pbm_height; unsigned int doublings=0; std::vector<std::string> args(argv+1, argv+argc); for (unsigned int i=0, e=args.size(); i<e; ++i) { if (args[i]=="-i") { inverted=true; continue; } if (args[i]=="-g") { if (i+1==e) continue; std::stringstream ss; ss << args[++i]; if (ss >> gammasetting) applygamma = true; continue; } } std::string line; std::getline(std::cin, line); if (line!="P5") return 1; enum { nothing, have_w, have_h, have_bpp } readstate = nothing; while (std::cin) { std::getline(std::cin, line); if (line.empty()) continue; if (line[0]=='#') continue; std::stringstream ss; ss << line; for(;;) { switch (readstate) { case nothing: if (ss >> pgm_width) readstate = have_w; break; case have_w: if (ss >> pgm_height) readstate = have_h; break; case have_h: if (ss >> pgm_vpp) readstate = have_bpp; break; } if (readstate==have_bpp) break; if (ss) continue; break; } if (readstate==have_bpp) break; } if (readstate!=have_bpp) return 1; // Fill pgm data pgm_data.resize(pgm_width*pgm_height); for (unsigned i=0, e=pgm_width*pgm_height; i<e; ++i) { int v = std::cin.get(); if (v==std::char_traits<char>::eof()) return 1; pgm_data[i] = static_cast<unsigned int>(std::char_traits<char>::to_char_type(v))&0xFFU; } pbm_width = pgm_width/8*8; pbm_height = pgm_height/8*8; pbm_data.resize(pbm_width*pbm_height/8); for (unsigned x=0, xe=pbm_width/8; x<xe; ++x) { for (unsigned y=0, ye=pbm_height/8; y<ye; ++y) { // Calculate the average of this 8x8 area unsigned int total=0; for (unsigned int xd=0; xd<8; ++xd) { for (unsigned int yd=0; yd<8; ++yd) { unsigned int c = x+xd+(y+yd)*pgm_width; unsigned int pv = pgm_data[x*8+xd+(y*8+yd)*pgm_width]; // Apply gamma prior to averaging if (applygamma) pv=corrected(pv, pgm_vpp); total += pv; } } total /= 64; // Invert average if inverting colors (white on black) if (inverted) total=pgm_vpp-total; total *= gol_bins; total /= (pgm_vpp+1); // Fill 8x8 areas with gol color texture for (unsigned int yd=0; yd<8; ++yd) { pbm_data[x+(y*8+yd)*pbm_width/8] = gol_colors[total*8+yd]; } } } // Now, write a pbm std::cout << "P4\n" << "# generated by pgm2gol\n" << pbm_width << " " << pbm_height << "\n"; for (unsigned i=0, e=pbm_data.size(); i<e; ++i) { unsigned char data=pbm_data[i]; if (!inverted) { data=pbm_data[i]^0xFF; } std::cout.put(data); } } ``` Selected results (note: all pbm's were converted to png's using a third party program for upload): Escher, gamma 2.2 [![Escher](https://i.stack.imgur.com/YeNxb.png)](https://i.stack.imgur.com/YeNxb.png) Mona Lisa, gamma 2.2 [![Mona](https://i.stack.imgur.com/U8Z5R.png)](https://i.stack.imgur.com/U8Z5R.png) Ocean, gamma 2.2 inverted [![Ocean](https://i.stack.imgur.com/LK5fP.png)](https://i.stack.imgur.com/LK5fP.png) Puppy, gamma 2.2 [![Puppy](https://i.stack.imgur.com/RSuso.png)](https://i.stack.imgur.com/RSuso.png) Treachery of Images, gamma 2.2 inverted [![Treachery](https://i.stack.imgur.com/BuTRk.png)](https://i.stack.imgur.com/BuTRk.png) Mona Lisa gamma 2.2, inverted, for comparison [![Mona](https://i.stack.imgur.com/jqC46.png)](https://i.stack.imgur.com/jqC46.png) ]
[Question] [ # Challenge Given a list of integers, show how gravity sort would be done. # Gravity Sort In gravity sort, imagine the numbers as rows of asterisks. Then, everything falls, and the new rows will be obviously sorted. Let's look at an example: `[2, 7, 4, 6]`: ``` ** ******* **** ****** ------- ** **** ******* ****** ------- ** | 2 **** | 4 ****** | 6 ******* | 7 ``` Notice that this is pretty much just parallelized bubble sort. # Exact Specs On each iteration, starting from the top row, take every asterisk from the row that doesn't have an asterisk below it, and move it down a row. Keep doing that until the list is sorted. # Input Input will be a list of strictly positive integers. # Output For the output, you must output each step. You can choose any two non-whitespace printable ASCII characters, one to be the "asterisks", and one to be the separating "dashes". The rows of asterisks must be separated with a standard newline of some sort (e.g. `\n` or `\r\f`). The row of dashes must be at least the width of the widest row (otherwise your asterisks are going to fall too far down!). A row of dashes at the very bottom is optional. A trailing newline at the end is permitted. Trailing spaces on each line are permitted. # Test Cases input will be represented as a list, then output will be listed immediately below. Test cases are separated by a double-newline. ``` [4, 3, 2, 1] **** *** ** * ---- *** ** * * * ** ---- ** * * ** * *** ---- * ** *** **** [6, 4, 2, 5, 3, 1] ****** **** ** ***** *** * ------ **** ** ** **** *** * ** *** ------ ** **** *** ** * * *** ***** ------ ** *** * * *** ** **** ***** ------ ** * *** **** ****** ***** ------ * ** *** **** ***** ****** [8, 4, 2, 1] ******** **** ** * -------- **** ** **** * ** ** -------- ** * ** ** **** **** -------- * ** **** ******** [2, 7, 4, 6] ** ******* **** ****** ------- ** **** ******* ****** ------- ** **** ****** ******* ``` Please feel free to correct my test cases if they're wrong, I made them by hand :) Note: Do not output the sorted list at the end. :) # Scoring All of your programs will be written on top of each other. You wouldn't want pieces of your program to fall down, so make sure you have the shortest code! [Answer] # [Pyth](https://github.com/isaacg1/pyth), 27 bytes ``` jsCM.u:R"v "" v"N+R\-.t*L\v ``` [Try it online!](http://pyth.herokuapp.com/?code=jsCM.u%3AR%22v+%22%22+v%22N%2BR%5C-.t%2aL%5Cv&input=%5B6%2C+4%2C+2%2C+5%2C+3%2C+1%5D&debug=0) [Answer] # [Perl 5](https://www.perl.org/), 118 bytes 115 bytes of code + `-pla` flags. ``` \@X[$_]for@F;s%\d+ ?%Y x$&.$"x($#X-$&).$/%ge;while(/Y.{$#X} /s){print$_,_ x$#X;1while s/Y(.{$#X}) /X$1b/s;y/bX/Y /} ``` [Try it online!](https://tio.run/nexus/perl5#JctNCsIwEEDhvacY7aQ0aDPEv00WduUZEqyEFqsWgoZGsFJ69lh0@/heMvdN5yD3roploU9oz9dnVxxVYOVlCQdmoMdU4KLPMNE5plwgsVuj3vfWNRkZMUx9BAp88F37eKFd2WlJtJI/AoFM9kccSKOsKagP1ZoM0BjjHrawhh1sQM6@ "Perl 5 – TIO Nexus") It seems a bit too long. But again, dealing with multiline strings with regex is usually not easy. I'm using `Y` instead of `*` and `_` instead of `-`. [Answer] # Octave, 104 bytes ``` b=(1:max(L=input("")))<=L;do;disp(" *-"([b;max(b)+1]+1))until b==(b=imerode(b,k=[1;1])|imdilate(b,k)~=b) ``` \*Requires image package. [Try it online!](https://tio.run/nexus/octave#HcoxDsIwDADAr3iLTWEwYkAY/6A/iDLUSgeLpq1oKjEgvh4E6@maKfKtDC/s1ed1rxgCEd21l7xI9m3FAIdTwGjyW0Ydp46J9rn6BKaKpl7G55JHtONDIwsnenvJPg31b/RRo9biVeAicBbg9AU "Octave – TIO Nexus") Explanation: ``` input = [8 ;4 ;2 ;1] L = input(''); %input list b=(1:max(L))<=L; % generate matrix of 0s and 1s as indexes of asterisks b = 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 do; disp(' *-'([b;max(b)+1]+1)) %display asterisks and dashes E = imerode(b,k=[1;1]); %morphological erosion E = 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 D = imdilate(b,k); %morphological dilation D = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 b_temp = E | (D~=b) %intermediate result b_temp = 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 until b==(b=b_temp) %loop until no change ``` [Answer] # Python, ~~203~~ 199 bytes ``` def k(x): m,j=max(x),''.join;d=[*map(lambda i:('*'*i).ljust(m),x)];f=sorted(d);print(*d,sep='\n') while d!=f:d=[*map(j,zip(*[x.replace('* ',' *')for x in map(j,zip(*d))]))];print('-'*m,*d,sep='\n') ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~69~~ 62 bytes *-7 bytes thanks to @Shaggy* ``` ®ç'x +SpZnUrwÃpQpUrw¹· V l o ®V=z d" x""x " z3ÃuW X¯XbXgJ)Ä · ``` Learning Japt and wanted to try out a more complicated challenge. Outputs with `x`s and `"`s instead of asterisks and dashes; takes input as an array of numbers. Assumes sorting will be complete within `input.length` steps; correct me if that is ever not the case. [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=Cq7nJ3ggK1NwWm5VcnfDcFFwVXJ3ubcKVgpsIG8grlY9eiBkIiB4IiJ4ICIgejPDdVcKWK9YYlhnSinEILc=&input=WzIsIDEsIDQsIDYsIDEsIDhd) ## Explanation ``` // implicit: U = input array ® ç'x +SpZnUrwà pQpUrw¹ · // implicit: V = this line UmZ{Zç'x +SpZnUrw} pQpUrw) qR // ungolfed UmZ{ } // U mapped by the function: Zç'x // "x" times this item +SpZnUrw // plus " " times the max of the input array (Urw) minus this value (Z) pQpUrw) // push " (Q) times the max qR // join with newlines V // implicit: W = this line l o ® V=z d" x""x " z3à uW // implicit: X = this line Ul o mZ{ZV=z d" x""x " z3} uW // ungolfed Ul o // the array of the range [0, U.length) mZ{Z } // mapped by the no-arg function: V=z // set V to itself rotated 90deg d" x""x " // replace all " x" with "x " to "fall" z3 // rotate back to normal uW // add W(the original) to the start X¯XbXgJ)Ä · // implicit: return this line Xs0,XbXgJ)+1 qR // ungolfed Xs0, // get the substring of X from 0 to... XbXgJ)+1 // the first index of the last item, plus one qR // join with newlines ``` [Answer] # [R](https://www.r-project.org/), ~~210~~ 205 bytes ``` l=scan();w=max(l);h=sum(l|1);a=1:h;p=h+1;m=matrix(' ',w,p);m[,p]='+';for(x in a)m[l[x]:1,x]='*';f=function()write(m,'',w,sep='');f();while(any(i<-m[,a]>m[,a+1])){s=which(i);m[,a][s]=' ';m[,a][s+w]='*';f()} ``` [Try it online!](https://tio.run/##NY3BCsIwEAV/JbfsmniIeJDG9UdCDqG0JJDU0rQ0on57TUUvDx4DM9O2RcqtGwD1SskViKg95SVBfCnUjlTj9UheKJ0qn6dQgDMuVzmiTkaOlrjgur9PUFgYmMNkoim2UbJUdKiI@mVo53CvjXUKcwdJ8l2Qu5E4R93vbR9iB254QLgeq9bZ275CWcRnpopbD@FbdNbkamb8f8T6CwG@tws7sxNT2wc "R – Try It Online") reads in the list from stdin; separated by `+` characters instead of `-`. It's a lot longer than I would have thought it would be. Takes advantage of the fact that the comparison `'*'>'+'` evaluates to `FALSE` but `'*'>' '` is `TRUE`, at least on TIO (on my machine I used `'='` which looked a little better). Managed to golf 5 bytes down from all the techniques I've learned since writing the original answer. [Try it online!](https://tio.run/nexus/r#NY7BbsMgEETv/Qpuu9ibA2lPJtsfQUhBll2QwLFsKhNF/XYXDrmMdjSjeXtG3ke3oNQHJ1cwSu05TstP9u12rAavV/a90qkW8hYKggBa6ZA6mZUsQw/6Pj@2OxZylEwhNURTrL1doAOpZ55/lzGHR6UcW8gTZkySAOigfVoZWqc94EOc0C1PDLdLMo7sd9VekZXytXONR4@hUWtk9goW8Da9qraDtvN3folPcRXq4/wH) [Answer] # [Japt](https://github.com/ETHproductions/japt) ~~[`-R`](https://codegolf.meta.stackexchange.com/a/14339/)~~, ~~32~~ ~~31~~ ~~30~~ ~~32~~ ~~31~~ 30 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Really enjoyed this one but not *entirely* happy with the final result, especially after having to add 2 bytes to fix a bug. Still determined to get it down under 30 bytes, though. Uses `n` instead of `*`. ``` ¡P=yÈrSùÍSúÍê¡Xçn÷úÃâ qR² ú- ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=oVA9echyU/nNU/rNw6qhWOduw7f6w%2bIgcVKyIPot&footer=ZCJuKiI&input=WzIgNyA0IDZd) (footer replaces `n`s with `*`s) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=oVA9echyU/nNU/rNw6qhWOduw7f6w%2bIgcVKyIPot&footer=UD0iIlJpVWQibioiKWlSaVBpUmlXZ1YguCn6LQ&input=WwpbMiA3IDQgNl0KWzQgMyAyIDFdCls2IDQgMiA1IDMgMV0KWzggNCAyIDFdCl0tbVI) ``` ¡P=yÈrSùÍSúÍê¡Xçn÷úÃâ qR² ú- :Implicit input of array U ¡ :Map P= : Reassign to P (initially the empty string) y : Transpose P È : Pass through the following function and transpose back r : Replace S : Space ù : Left padded with Í : "n" to length 2 SúÍ : With a space right padded with "n" to length 2 à : End function ª : Logical OR ('cause it'll still be the empty string on the first iteration) ¡ : Map each X in U Xçn : "n" repeated X times à : End map · : Join with newlines ú : Right pad each with spaces to the length of the longest à :End map â :Deduplicate q :Join with R : Newline ² : Repeated twice ú- :Right pad each line with "-" to the length of the longest ``` [Answer] # [Haskell](https://www.haskell.org/), 213 211 208 bytes ``` import Data.List (?)=replicate p=transpose s l|w<-length l,i<-[n?'*'++w?' '|n<-l]=intercalate[w?'-']$i:(p<$>unfoldr f(p i)) f i|i==n=mempty|2>1=Just(n,n)where n=t<$>i t(a:b:y)|a>b=" *"++t y|2>1=a:t(b:y);t k=k ``` [Try it online!](https://tio.run/##JcuxboMwEIDhnac4RUiYYCIlTTtQDEunKltHxOCkppwwh2UfQpF4d0rV9f/19ToMxtptw9FNnuFDsz7dMHAk6lR54yw@NJvIKfaagpuCiQLYdSlza@iHe7ASy7yhOjkmWbbUCSQr7bNVSGz8Q9udN3vPkzbGQrgyrmbqJvvtoRMOME2jDnBFpUiNZnT8XC/VWX3OgQVJSpfeeAOkeIcYsdDFvXimq67u6gDHQ5Yx/AtdsPhb7wyDGrZRI4ECN/MX@xvBCWaySCZADAGaN3mVF/kqX@S53X4B "Haskell – Try It Online") [Answer] # Javascript, 274 bytes ``` a=>(r="",m=Math.max(...a),b=a.map(n=>Array(m).fill(0).map((_,i)=>i<n)),(k=_=>(b.map(c=>r+=c.map(v=>v?"*":" ").join``.trim()+` `),r+="-".repeat(m)+` `,n=0,b.map((r,i)=>(s=b[i+1])&&r.map((c,j)=>s[j]||(n|=s[j]=-(c>0),c>0&&(r[j]=0)))),b=b.map(c=>c.map(n=>n<0?1:n)),n&&k()))(),r) ``` Example code snippet: ``` f = a=>(r="",m=Math.max(...a),b=a.map(n=>Array(m).fill(0).map((_,i)=>i<n)),(k=_=>(b.map(c=>r+=c.map(v=>v?"*":" ").join``.trim()+` `),r+="-".repeat(m)+` `,n=0,b.map((r,i)=>(s=b[i+1])&&r.map((c,j)=>s[j]||(n|=s[j]=-(c>0),c>0&&(r[j]=0)))),b=b.map(c=>c.map(n=>n<0?1:n)),n&&k()))(),r) o.innerText = f([6,4,2,5,3,1]) ``` ``` <pre id=o> ``` [Answer] # [J](http://jsoftware.com/), 49 45 bytes ``` ' *-'{~2,/@,.~[:((]+[-1|.])]<_1|.!.0])^:a:#&1 ``` [Try it online!](https://tio.run/##bc5BC4JAEAXgu7/iWdBqjpO7muGQEAWdpENX2SIiiS79gMK/vi0iHaLD8OC97zAPV4WibRlKpVQwYdWhFigQMoi/lLE7NnunME/Vqze02BD3rUSRTdpUv9nGdn32GXJm45NcZDrTLg4OW8aoehmYrhNJfmVwu96f6EBcIIfBWPhXvkNJKAiGsCTk9E/4bTWg0n0A "J – Try It Online") Takes input as a column vector. About a third of the bytes are just to conform to the output specs. * `#&1` Convert to rows of ones, with 0 fill. * `[:(...)^:a:` Do `...` until a fixed point is reached, keeping track of intermediate results. * `]<_1|.!.0]` Rotate the rows down, then ask: "where is that less than the original input?" This will pick out just the valid falling pieces, in their "next" position. Call these the "rain". * `(]+[-1|.])` Add the rain to this step's input minus the rain rotated up. That is, rewind the "rain" one step, remove this rewinded-rain from the input, and then add the not-rewinded rain. This is precisely the rain plus the static pieces, which is what we want for the next iteration. * `' *-'{~2,/@,.~` Conform to output spec. ]
[Question] [ # Description We consider a slightly simplified version of Tetris where each move consists of: * rotating the piece clockwise, 0 to 3 times * positioning the piece at a given column * fast drop The goal is to determine the number of completed lines, given a list of such Tetris moves. Completed rows are removed as pieces are dropped, following standard Tetris rules. **Playfield** The playfield is 10-column wide. There's no *Game Over* and it is assumed that there's always enough space and time to perform the above actions, no matter the configuration of the playfield. The height of the playfield doesn't really matter here, but you can use the standard 22 rows as an upper limit. **Shapes of Tetrominoes** [![shapes](https://i.stack.imgur.com/4pQum.png)](https://i.stack.imgur.com/4pQum.png) ## Input / Output **Input** A comma separated list of Tetris moves encoded with 3 characters. The first two character describe the Tetromino shape to use and the last one describes the position where it's dropped. 1. Tetromino: `I`, `O`, `T`, `L`, `J`, `Z` or `S`, in the same order as above. 2. Number of clockwise rotations: `0` to `3` 3. Column: `0` to `9`. This is the column in which the top-left corner of the piece (marked with an `x` on the above picture) is located after the rotation 1 It is assumed that all moves in the provided list are valid. There's no need to check for invalid entries such as `I07` (horizontal `I` shape put too far on the right). 1 *You are free to either implement a real rotation algorithm or to hardcode all the different shapes, as long as the `x` is located in the column given by the third character of the move.* **Output** Number of completed lines. ## Example [![example](https://i.stack.imgur.com/vDnqP.png)](https://i.stack.imgur.com/vDnqP.png) `O00,T24` will generate the first position and `O00,T24,S02,T01,L00,Z03,O07,L06,I05` will generate the second position. Therefore, the following sequence will generate a Tetris and should return `4`: ``` O00,T24,S02,T01,L00,Z03,O07,L06,I05,I19 ``` ## Test cases ``` 1) "O00,T24,S02,T01,L00,Z03,O07,L06,I05,I19" -> 4 2) "S00,J03,L27,Z16,Z18,I10,T22,I01,I05,O01,L27,O05,S13" -> 5 3) "I01,T30,J18,L15,J37,I01,S15,L07,O03,O03,L00,Z00,T38,T01,S06,L18,L14" -> 4 4) "S14,T00,I13,I06,I05,I19,L20,J26,O07,Z14,Z10,Z12,O01,L27,L04,I03,S07,I01,T25,J23,J27,O01, I10,I10" -> 8 5) "O00,T24,L32,T16,L04,Z11,O06,L03,I18,J30,L23,Z07,I19,T05,T18,L30,I01,I01,I05,T02" -> 8 ``` ## Test page You can use **[this JSFiddle](https://jsfiddle.net/02vkdv99/1/)** to test a move list. [Answer] # C, ~~401~~ ~~392~~ ~~383~~ ~~378~~ ~~374~~ ~~351~~ ~~335~~ ~~324~~ ~~320~~ ~~318~~ ~~316~~ 305 bytes ``` d[99]={'3Z3Z',983177049,513351321,1016270793,970073931,~0},*L=d+5,V,s;char c;main(x){B:for(c=0;c[++L]|V;V>>=4)c-=(L[c]=*L|(V&15)<<x)>1022;s-=c;if(scanf("%c%1d%d,",&c,&V,&x)>2)for(V=c^79?d[c/4%5]>>24-V*8:27,V=c^73?V/64%4<<8|V/8%8<<4|V%8:V&32?15:4369;;--L)for(c=4;c--;)if(L[c]>>x&V>>c*4&15)goto B;return s;} ``` Takes comma-separated input on stdin, returns the score in the exit status. Requires `char` to be signed (which is the default for GCC) and requires `'3Z3Z'` to be interpreted as 861549402 (which is the case for GCC on little endian machines, at least). --- ### Usage example: ``` echo "O00,T24,S02,T01,L00,Z03,O07,L06,I05,I19" | ./tetris; echo "$?"; ``` --- ### High-level explanation: All shapes except the line can fit in a 3x3 grid with one corner missing: ``` 6 7 - 3 4 5 0 1 2 ``` That means it's easy to store them in a byte each. For example: ``` - - - 0 0 - - # - --> 0 1 0 --> 0b00010111 # # # 1 1 1 ``` (we align each piece to the bottom-left of the box to make dropping it easier) Since we get at least 4 bytes to an int, this means we can store all 4 rotations of each piece in a single integer, with a special case for the line. We can also fit each row of the game grid into an int (only needs 10 bits), and the currently falling piece into a long (4 lines = 40 bits). --- ### Breakdown: ``` d[99]={ // General memory '3Z3Z', // Shape of "S" piece (multi-char literal, value = 861549402) 983177049, // Shape of "T" piece 513351321, // Shape of "Z" piece 1016270793, // Shape of "J" piece 970073931, // Shape of "L" piece ~0 // Bottom of game grid (solid row) }, // Rest of array stores lines in the game *L=d+5, // Working line pointer (start >= base of grid) V, // Current piece after expansion (also stores rotation) s; // Current score (global to initialise as 0) char c; // Input shape identifier (also counts deleted lines) main(x){ // "x" used to store x location B: // Loop label; jumps here when piece hits floor for(c=0;c[++L]|V;V>>=4) // Paint latest piece & delete completed lines c-=(L[c]=*L|(V&15)<<x)>1022; s-=c; // Increment score if(scanf("%c%1d%d,",&c,&V,&x)>2) // Load next command for(V=c^79? // Identify piece & rotation d[c/4%5]>>24-V*8 // Not "O": load from data :27, // Else "O": always 27 V=c^73? // If not "I" (line): V/64%4<<8|V/8%8<<4|V%8 // expand shape to 16-bits : // Else we are a line: V&32? // "I" coincides with "J"; use this to check 15:4369; // horizontal/vertical ;--L) // Loop from top-to-bottom of grid for(c=4;c--;) // Loop through rows of piece if(L[c]>>x&V>>c*4&15) // If collides with existing piece: goto B; // Exit loops return s; // Return score in exit status } ``` --- -4, -1 thanks to @Titus, and -23, -11 with inspiration from their answer [Answer] # PHP, ~~405~~ ~~399~~ ~~378~~ ~~372~~ ~~368~~ ~~360~~ ~~354~~ ~~347~~ ~~331~~ ~~330~~ ~~328~~ ~~319~~ ~~309~~ 300 bytes (with [Dave´s block mapping](https://codegolf.stackexchange.com/questions/90255/given-a-list-of-tetris-moves-return-the-number-of-completed-lines/90357#90357)) ``` <?$f=[~0];L:for($y=0;$f[++$d+$y]|$s;$s>>=4)$y-=1022<$f[$d+$y]=$f[$d]|$s%16<<$x;$c-=$y;if(list($p,$r,$x)=$argv[++$z])for($s=I==$p?$r&1?4369:15:hexdec(decoct(O==$p?27:ord(base64_decode('M1ozWjqaF1kemR6ZPJMPyTnSJ0s')[ord($p)/4%5*4+$r])));;$d--)for($y=4;$y--;)if ($f[$d+$y]>>$x&$s>>$y*4&15)goto L;echo$c; ``` program, takes moves as separate arguments, prints result **breakdown to function:** takes moves as array, returns result ``` function t($a) { $f=[~$z=0]; // init field $f (no need to init $z in golfed version) L: // jump label // A: paint previous piece at line $d+1: # if($s)paint($f,$s,$d+1,$x); for($y=0; // $y = working line offset and temporary score $f[++$d-$y]|$s;$s>>=4)// next field line; while field or piece have pixels ... $s>>=4) // next piece line $y+=1022< // 3: decrease temp counter if updated line is full $f[$d-$y]=$f[$d] // 2: use $y to copy over dropped lines |$s%16<<$x; // 1: set pixels in working line $c+=$y; // add temp score to global score # paint($f);var_dump($c); if(list($p,$r,$x)=$a[$z++])// B: next piece: $p=name; $r=rotation, $x=column # {echo"<b>$z:$p$r-$x</b><br>"; for( // C: create base 16 value: $s=I==$p ? $r&1?4369:15 // I shape (rotated:0x1111, not rotated:0xf) : hexdec(decoct( // 5: convert from base 8 to base 16 O==$p ? 27 // O shape (rotation irrelevant: 033) : ord( // 4: cast char to byte // 0: 4 bytes for each remaining tetromino base64_decode('M1ozWjqaF1kemR6ZPJMPyTnSJ0s')[ ord($p)/4%5 // 1: map STZJL to 01234 *4 // 2: tetromino offset +$r] // 3: rotation offset )));;$d-- ) for($y=4;$y--;) // D: loop $y through piece lines if ($f[$d+$y]>>$x & $s>>$y*4 & 15) // if collision ... goto L; // goto Label: paint piece, tetris, next piece # } return$c; // return score } ``` for reference: the old mapping ``` hexdec(decoct( // 3. map from base 8 to base 16 // 0. dword values - from high to low: rotation 3,2,1,0 [0x991e991e,0xc90f933c,0x4b27d239,0x1b1b1b1b,0,0x5a335a33,0x59179a3a] [ord($m[0])/2%9] // 1. map ZJLO.ST to 0123.56 -> fetch wanted tetromino >>8*$m[1]&255 // 2. the $m[1]th byte -> rotated piece )) ``` **testing** see [my other PHP answer](https://codegolf.stackexchange.com/questions/90255/given-a-list-of-tetris-moves-return-the-number-of-completed-lines/90929#90929) **want to watch?** remove the `#` from the function source and add this: ``` function paint($f,$s=0,$d=0,$x=0){echo'<pre>';for($y=count($f)+5;$y--;$g=0)if(($t=(($z=$y-$d)==$z&3)*($s>>4*$z&15)<<$x)|$r=$f[$y]|0){$z=$t?" $r|$t=<b".(1022<($z=$t|$r)?' style=color:green':'').">$z":" <b>$r";for($b=1;$b<513;$b*=2)$z=($t&$b?'<b>'.($r&$b?2:1).'</b>':($r&$b?1:'.')).$z;printf("%02d $z</b>\n",$y);}echo'</pre>';} ``` **some golfing steps** Rev. 5: A big leap (399-**21**=378) came by simply moving the column shift from a separate loop to the two existing loops. Rev. 8: Switching from array to base 16 for the piece ($s) did not give much, but made way for some more golfing. Rev. 17: crunched the values with `base64_encode(pack('V*',<values>))` and used byte indexing instead of `unpack` to save **16** bytes Rev. 25 to 29: inspired by Dave´s code: new hashing (-2), new loop design (-9), goto (-10) no pre-shift though; that would cost 17 bytes. **more potential** With `/2%9`, I could save 15 bytes (only 14 bytes with `/4%5`) by putting binary data into a file `b` and then indexing `file(b)[0]`. Do I want that? UTF-8 characters would cost a lot for the transformation. **on the hashing** I used `ZJLO.ST /2%9 -> 0123.56`; but `T.ZJLOS /3%7 -> 0.23456` is as good. one byte longer: `O.STJLZ %13/2 -> 0.23456` and three more: `OSTZJ.L %17%12%9 -> 01234.6` I could not find a short hash (max. 5 bytes) that leaves no gap; but Dave found `STZJL /4%5 -> 01234`, dropping the O from the list. wtg! btw: `TIJSL.ZO (%12%8) -> 01234.67` leaves room for the `I` shape (and a fictional `A`, `M` or `Y` shape). `%28%8` and `%84%8`, do the same (but with `E` instead of `A`). [Answer] # Ruby, ~~474~~ ~~443~~ ~~428~~ 379 + 48 = 427 bytes -1 thanks to @Titus This can definitely be golfed more. Reads a binary dictionary of pieces (see below) from STDIN or a filename and takes a move list as an argument, e.g. `$ cat pieces | ruby script.rb O00,T24,S02,...`. ``` q=$*.pop z=$<.read.unpack('S*') b=c=g=i=0 x=10 u=1023 r=->n{n&2**x-1>0?n:r[n>>x]} y=->n{n>0?[n&u]+y[n>>x]:[]} l=->c,n{z.find{|m|m>>x==c<<2|n.to_i}||l[c,n-2]} q.scan(/(\w)(\d)(\d)/){n=l["IOTLJSZ".index($1),$2.to_i] v=(n&1|(n&6)<<9|(n&56)<<17|(n&960)<<24)<<$3.to_i (y[b].size+1).times{t=b<<40 t&v>0&&break g=t|v v<<=x} b=0 a=y[r[g]] a.grep_v(u){|o|b|=o<<x*i i+=1} c+=a.count u} p c ``` Binary piece data (xxd format) ``` 0000000: c003 4b04 d810 d814 b820 9c24 d029 5a2c ..K...... .$.)Z, 0000010: 7830 9634 e039 ca3c 3841 d444 c849 4e4c x0.4.9.<8A.D.INL 0000020: 9861 9869 5c64 5c6c f050 f058 9a54 9a5c .a.i\d\l.P.X.T.\ ``` See it on repl.it (with hard-coded arguments, dictionary): <https://repl.it/Cqft/2> ## Ungolfed & explanation ``` # Move list from ARGV q = $*.pop # Read piece dictionary; pieces are 16-bit integers: 3 for letter, # 2 for rotation, 10 for shape (and 1 wasted) z = $<.read.unpack('S*') # Empty board and various counters b = c = g = i = 0 x = 10 # Magic numbers u = 1023 # A function to remove empty lines r = ->n{ n & 2**x - 1 > 0 ? n : r[n >> x] } # A function to split the board into lines y = ->n{ n > 0 ? [n & u] + y[n >> x] : [] } # A function to lookup a piece by letter and rotation index l = ->c,n{ z.find {|m| m >> x == c << 2 | n.to_i } || l[c, n-2] } # Read the move list q.scan(/(\w)(\d)(\d)/) { # Look up the piece n = l["IOTLJSZ".index($1), $2.to_i] # Convert the 10-bit piece to a 40-bit piece (4 rows of 10 columns) v = (n & 1 | (n & 6) << 9 | (n & 56) << 17 | (n & 960) << 24 ) << $3.to_i # Shift by the appropriate number of columns # Drop the piece onto the board (y[b].size + 1).times { t = b << 40 t & v > 0 && break g = t | v v <<= x } # Clear completed rows b = 0 a = y[r[g]] a.grep_v(u) {|o| b |= o << x * i i += 1 } c += a.count u # Count cleared rows } p c ``` [Answer] # PHP, ~~454~~ ~~435~~ ~~427~~ ~~420~~ 414 bytes bit fields for pieces and map; but no special case for the `I` shape as Dave´s golfing. ``` <?$t=[I=>[15,4369],O=>[51],T=>[114,562,39,305],L=>[113,802,71,275],J=>[116,547,23,785],Z=>[54,561],S=>[99,306]];foreach($argv as$z=>$m)if($z){$s=$t[$m[0]][$m[1]%count($t[$m[0]])];for($d=$i=0;$i<4;$i++)for($k=0;$k<4;$k++)if($s>>4*$k&1<<$i){for($y=0;$y++<count($f);)if($f[$y-1]&1<<$m[2]+$i)$d=max($d,$y-$k);$k=3;}for($k=$d;$s;$k++,$s>>=4)if(1022<$f[$k]|=$s%16<<$m[2]){$c++;unset($f[$k]);}$f=array_values($f);}echo$c; ``` takes arguments from command line, prints result **ungolfed as function** takes arguments as array, returns result ``` function t($a) { // bitwise description of the stones and rotations $t=[I=>[15,4369],O=>[51],T=>[114,562,39,305],L=>[113,802,71,275],J=>[116,547,23,785],Z=>[54,561],S=>[99,306]]; foreach($a as$m) { $s=$t[$m[0]][$m[1]%count($t[$m[0]])]; // $s=stone // find dropping space for($d=$i=0;$i<4;$i++) // a) lowest pixel of stone in column i for($k=0;$k<4;$k++) if($s>>4*$k&1<<$i) { // b) top pixel of field in column x+i for($y=0;$y++<count($f);) if($f[$y-1]&1<<$m[2]+$i)$d=max($d,$y-$k); $k=3; // one byte shorter than `break;` } // do drop for($k=$d;$s;$k++,$s>>=4) if(1022<$f[$k]|=$s%16<<$m[2]) // add block pixels to line pixels ... if full, {$c++;unset($f[$k]);} // tetris $f=array_values($f); } return$c; } ``` **tests** (on function) ``` $data=[ "O00,T24,S02,T01,L00,Z03,O07,L06,I05,I19"=>4, "S00,J03,L27,Z16,Z18,I10,T22,I01,I05,O01,L27,O05,S13" => 5, "I01,T30,J18,L15,J37,I01,S15,L07,O03,O03,L00,Z00,T38,T01,S06,L18,L14" => 4, "S14,T00,I13,I06,I05,I19,L20,J26,O07,Z14,Z10,Z12,O01,L27,L04,I03,S07,I01,T25,J23,J27,O01,I10,I10" => 8, // additional example for the two last tetrominoes: 'O00,T24,L32,T16,L04,Z11,O06,L03,I18,J30,L23,Z07,I19,T05,T18,L30,I01,I01,I05,T02' => 8, ]; function out($a){if(is_object($a)){foreach($a as$v)$r[]=$v;return'{'.implode(',',$r).'}';}if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';} function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);} 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='';} foreach($data as $v=>$e) { $x=explode(',',$v); test($x,$e,t($x)); } ``` ]
[Question] [ In the 1990s, COBOL computer engineers worked out a way to extend six-digit date fields by converting them to `YYYDDD` where `YYY` is the `year - 1900` and `DDD` is the day of the year `[001 to 366]`. This scheme could extend the maximum date to `2899-12-31`. In the year 2898, the engineers started panicking because their 900 year old code bases were going to fail. Being from the year 2898, they just used their time machine to send a lone Codeinator to the year 1998 with this algorithm and the task of getting it implemented as widely as possible: > > Use a scheme `PPQQRR` where if `01 ≤ QQ ≤ 12` then it's a standard `YYMMDD` date in the 1900s, but if `QQ > 12` then it represents the days after `2000-01-01` in base 100 for `PP` and `RR` but base 87 for `QQ - 13`. > > > This scheme extends far beyond year 2899 and is also backwards compatible with standard dates, so no modifications of existing archives are required. Some examples: ``` PPQQRR YYYY-MM-DD 000101 1900-01-01 -- minimum conventional date suggested by J. Allen 010101 1901-01-01 -- edge case suggested by J. Allen 681231 1968-12-31 -- as above 991231 1999-12-31 -- maximum conventional date 001300 2000-01-01 -- zero days after 2000-01-01 008059 2018-07-04 -- current date 378118 2899-12-31 -- maximum date using YYYDDD scheme 999999 4381-12-23 -- maximum date using PPQQRR scheme ``` Your challenge is to write a program or function to accept input as `PPQQRR` and output as an ISO date `YYYY-MM-DD`. Input method can be parameter, console or command line, whatever is easiest. For your amusement, here is a noncompeting solution in COBOL-85: ``` IDENTIFICATION DIVISION. PROGRAM-ID. DATE-CONVERSION. DATA DIVISION. WORKING-STORAGE SECTION. 01 T PIC 9(8). 01 U PIC 9(8). 01 D VALUE '999999'. 05 P PIC 9(2). 05 Q PIC 9(2). 05 R PIC 9(2). 01 F. 05 Y PIC 9(4). 05 M PIC 9(2). 05 D PIC 9(2). PROCEDURE DIVISION. IF Q OF D > 12 THEN MOVE FUNCTION INTEGER-OF-DATE(20000101) TO T COMPUTE U = R OF D + 100 * ((Q OF D - 13) + 87 * P OF D) + T MOVE FUNCTION DATE-OF-INTEGER(U) TO F DISPLAY "Date: " Y OF F "-" M OF F "-" D OF F ELSE DISPLAY "Date: 19" P OF D "-" Q OF D "-" R OF D END-IF. STOP RUN. ``` [Answer] # T-SQL, ~~99~~ 98 bytes ``` SELECT CONVERT(DATE,IIF(ISDATE(i)=1,'19'+i, DATEADD(d,8700*LEFT(i,2)+RIGHT(i,4)-935,'1999')))FROM t ``` Line break is for readability only. Thank goodness for implicit casting. Input is via a pre-existing table **t** with `CHAR` column **i**, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Goes through the following steps: 1. Initial check is via the SQL function `ISDATE()`. (The behavior of this function changes based on language settings, it works as expected on my `english-us` server). Note this this is just a check for validity, if we tried to parse it directly, it would map `250101` as 2025-01-01, not 1925-01-01. 2. If the string parses correctly as a date, tack `19` on the front (rather than change the server-level year cutoff setting). Final date conversion will come at the end. 3. If the string does *not* parse as a date, convert it to a number instead. The shortest math I could find was `8700*PP + QQRR - 1300`, which avoids the (very long) SQL `SUBSTRING()` function. This math checks out for the provided samples, I'm pretty sure it is right. 4. Use `DATEADD` to add that many days to `2000-01-01`, which can be shorted to `2000`. 5. Take that final result (either a string from step 2, or a DATETIME from step 4), and `CONVERT()` it to a pure `DATE`. I thought at one point that I found a problematic date: `000229`. This is the only date which parses *differently* for 19xx vs 20xx (since 2000 was a leap year, but 1900 was not, due to [weird leap-year exceptions](https://en.wikipedia.org/wiki/Leap_year#Algorithm)). Because of that, though, `000229` isn't even a valid input (since, as mentioned, 1900 was not a leap year), so doesn't have to be accounted for. [Answer] # [R](https://www.r-project.org/), 126 bytes ``` function(x,a=x%/%100^(2:0)%%100,d=as.Date)'if'(a[2]<13,d(paste(19e6+x),'%Y%m%d'),d(a[3]+100*((a[2]-13)+87*a[1]),'2000-01-01')) ``` [Try it online!](https://tio.run/##bc7NasMwDADg@54iMIztJt4kq03k0tz2EiNkYBobeugPbQp5@9QJ7Id0QgcJfUK6jrEe4/207w/nkxoKXw/iXSDAl7Jb0GIqi672t7cP3wctD1Eq39h2h1R06uJvfVDoQpkPupDiUxxFJ3Wa@IbaPO2u1MwNks65WvkG2wQtABjAlFLrMarUIqDOXrMwXMK@D122zdB9o5eoSkZLz6Jkg9bQJJz7Vzj3I9IRAliI31dmwbBxTwLZQGVgnQRVjMhLwX@uuDkWYk2Mk7A0PgA "R – Try It Online") * -5 bytes thanks to @Giuseppe suggestion to take a numeric input instead of string [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 103 bytes ``` s=>new Date(...([a,b,c]=s.match(/../g),b>12?[2e3,0,(b-13+a*87)*100-~c]:[a,b-1,c])).toJSON().split`T`[0] ``` [Try it online!](https://tio.run/##Pc4xT4QwGMbx3U/RjfYs770vjTnQFBddHHTQjZBcqeVEOUpoo7j41fHwEp/pt/yT5918mmCnboxpGLtXNx398OG@l1YvQZeD@2J3JjoOALwyspG21gGOJto3vgXYHoRsSspuq8wpiZI3KalLs8l3YkOI6Y@tr9cspVMoBET/8Pz0yAWEse/i/mVfYb1EF6I1wQWmWZUUBWWKEskSRFKIZ@V4VaxSu5woX1X8LalvLv57aP10b07PZqZLZv0QfO@g9wc@S9byWQix/AI "JavaScript (SpiderMonkey) – Try It Online") --- `.toJSON` will failed on a UTC+X timezone. This code works, but longer (+11bytes): ``` s=>Intl.DateTimeFormat`ii`.format(new Date(...([a,b,c]=s.match(/../g),b>12?[2e3,0,(b-13+a*87)*100-~c]:[a,b-1,c]))) ``` [Answer] # [Python 2](https://docs.python.org/2/), 159 bytes ``` from datetime import* def f(s):D=datetime;p,q,r=map(int,(s[:2],s[2:4],s[4:]));return str(q>12and D(2000,1,1)+timedelta(100*(q-13+87*p)+r)or D(1900+p,q,r))[:10] ``` [Try it online!](https://tio.run/##VdDBjoMgEADQ8/YruAkKyQy4FWy6p/6F8WCipiarIrKHfr0Ltpu1hIQJbzKTGfvw93mS29a7eSRt4zs/jB0ZRjs7n57aric9XVl5u/7ZxfKFu@vYWDpMntO1KmXN10qWeXzysmbs4jr/4yayekeXL5TN1JIblQDAkSPLYp22@/YNRYCULgJVpovUssyx2YVUNADZ3oixqkSotz7828Xxx9iSYSJVlYRqCJhwksRsARhuUnMSBA@CRzlrlOolZy1QCvUSY/7FmKOENgogShzgrQ9o@DRPQS2gEJA/RRUaUe@i36uZ/UTJlcYoUiV1XZ4@rAv73GckYUge9h5itv0C "Python 2 – Try It Online") [Answer] ## ABAP, ~~173~~ 171 bytes Saved 2 bytes by further optimizing the output According to the legends, an SAP customer in the early 21st century once said: > > After a nuclear war of total destruction, the one thing remaining will be SAPGUI. > > > He was right. Today, in 2980, there is no more C++, no more COBOL. After the war everyone had to rewrite their code in SAP ABAP. To provide backwards compatibility to the leftovers of the 2800's COBOL programs, our scientists rebuilt it as a subroutine in ABAP. ``` FORM x USING s.DATA d TYPE d.IF s+2 < 1300.d ='19'&& s.ELSE.d ='20000101'.d = d + s+4 + 100 * ( ( s+2(2) - 13 ) + 87 * s(2) ).ENDIF.WRITE:d(4),d+4,9 d+6,8'-',5'-'.ENDFORM. ``` It can be called by a program like this: ``` REPORT z. PARAMETERS date(6) TYPE c. "Text input parameter PERFORM x USING date. "Calls the subroutine ``` --- Explanation of my code: ``` FORM x USING s. "Subroutine with input s DATA d TYPE d. "Declare a date variable (internal format: YYYYMMDD) IF s+2 < 1300. "If substring s from index 2 to end is less than 1300 d ='19'&& s. "the date is 19YYMMDD ELSE. "a date past 2000 d ='20000101'. "Initial d = 2000 01 01 (yyyy mm dd) "The true magic. Uses ABAPs implicit chars to number cast "and the ability to add days to a date by simple addition. "Using PPQQRR as input: " s+4 = RR, s+2(2) = QQ, s(2) = PP d = d + s+4 + 100 * ( ( s+2(2) - 13 ) + 87 * s(2) ). ENDIF. "Make it an ISO date by splitting, concatenating and positioning the substrings of our date. WRITE: "Explanation: d(4), "d(4) = YYYY portion. WRITE adds a space after each parameter, so... 5 '-' && d+4, "place dash at absolute position 5. Concatenate '-' with MMDD... 8 '-' && d+6. "place dash at absolute position 8, overwriting DD. Concatenate with DD again. ENDFORM. ``` ABAP's Date type has the odd property to be formatted as DDMMYYYY when using `WRITE` - might be locale dependent even - despite the internal format being YYYYMMDD. But when we use a substring selector like `d(4)` it selects the first 4 characters of the *internal* format, hence giving us YYYY. **Update**: The output formatting in the explanation is now outdated, I optimized it by 2 bytes in the golfed version: ``` WRITE: "Write to screen, example for 2000-10-29 d(4), "YYYY[space] => 2000 d+4, "MMDD[space] => 2000 1029 9 d+6, "Overwrites at position 9 => 2000 10229 8'-', "Place dash at position 8 => 2000 10-29 5'-'. "Place dash at position 5 => 2000-10-29 ``` [Answer] # [Kotlin](https://kotlinlang.org), 222 bytes Hard coded Calendar field names constants to save 49 bytes. ``` {d:Int->val p=d/10000 val q=d/100%100 val r=d%100 if(q<13)"19%02d-%02d-%02d".format(p,q,r) else{val c=Calendar.getInstance() c.set(2000,0,1) c.add(5,(p*87+q-13)*100+r) "%4d-%02d-%02d".format(c.get(1),c.get(2)+1,c.get(5))}} ``` [Try it online!](https://tio.run/##lVf/UiJJEv6fp8ghwhhwaKTxFxjDRDiCLrsqiDgbxsX9UXYX2CvdjdWNyho@wL7HPdm9yNyXWUXjzOpdHGFId1VlVuaXX/7gLs1nUfJ9a5OOjFa5DqnRaDVaTZqkhvLbKKMgDTVN09mEgls1m@lkqg9Kt3k@zw62tniT9@pZroI7/YQj2K8Habx1v9BZHqVJtuXv7bf3mqVSP4FGTX673chqdDT4OjiF9ni@yLUh6I0SrU1Gj6m5gx3pIidFj2pJeUr6KddJSFn05IXRNMophK00ifQszOhmCTXJgzZ5lEz5iphFrq@vu90uPd5qo/mF4Atfv9TKkAcrGg1S0MmH3FaIy9LJ@tQ/Gg2fVW3v7f2zTmNGIwugXuO@xSxcWcXnY/UUxYvY2gWRZqvd9vymt@3XC8dFJzZaNXldewzwDEM/V0kU3LETNzpQi0zzucgQmyrCKS6VeNyoTAMpdm2aitcpTVQ0q9NXza8Tk8Zv3LmkPxZZTtAcOtV5FLPxwS1MYSUZO6RoluL1CDdFicqZCelaG@LXoscov7X8ULNpavAWC5p8KlfZHeM41blEBOGK4vkMuCXspYLhUahnS36ap1kW3cxAqRLhcwWf1Qrk4fDiYjRyEYwmhGD8@69/0cWFfPlNviyB9o8Zy@S4XpkQoT47Q0glENGKcQ1m3A0YBTWQ//JKmoyeGw2/84IE0DdhTjYbjYbX8PHHmhhz8hEKTo3hUNyFeaxVtlr7sgP1YNc2wv6aMJYqGYJkENxlCtlVaNqiSZDMUqgK7h7hRyapoXIGx6JdeMiuwR0cTlKK0zCaRIGSVGPU9VOUCezKIKoPoIkCfEbfLyKjQ5h1mYo9ikOSAXcHM@fItXd25nW7Jfjtw2kBzgFAnkdxlAjJJdsSvlHNLNDZYjpFuiO6SMZf63TIhaLESpwa/5UaHU6RQQzZ22J7Lb@5LWJ7LZtDIga2qJv0QZfa7dX@KsesdS4F/2Yd3PG3EbfX8WSBP7VJ3w53iYvgbpsl/JbX2PcaOyIRLIyBaqt1e7/l@y16leo/mCG4LDKOhCtFlgownz9EO9stn@Wa2@/Jucg4udJ1ujDrIixFK6VH5B7nzNykU6NiAgMniyRg93lbBYGeg/bJnMtptlLJjEOBdYsqof7lwN68ZkGd@iIV6/w2Rd3BqRuNGoVbNOCqMdBZCnbiSnA1Zp3oJbqGjIUm1GM2UassQojBu2OcW7ILKkYB4mJQI5vanL9JmjDhtVAXahfiAdJO@oTX2gVT@93e@bh/3D86HPcH59Ttf@tf4qEupWM4GpyMDs@8PgzvHo573tHg/FtvZA9g4fCn878PRr/1z0@8y/FgdHjSo8ve0bjYBEPGNOwfUbvSqhZLV39f6tK3w9OrHn20Uf1YJ9mR3V0aOoGmE3DLF28vj35ahvrjHw5cuwM7P8qdva2u@2oZ4Bz1ulej3k8g9I9hzOAYZ6Ukjn/pnRcqzgbfenR8dS6wUP983DvpjbzBscfoVjhZOLurNB7QuBA6GpwNr8Y9QNWBP6L5kxTNTapU3FVcHqtYRsHcBES8xq/jd26WYOJaZ0HlSq48Lk53@5fD08NrKnfBugMqAyaoPKayVwY0xWNXHkWqd3rZe0/cb5edTSJ1sX507lgN512vj@CAPEMaXQHNza0SmlxqcvpDPag66DurHylkKkp2qbS1RT3pACh1SIyMuY1aPVPxTajqJWRskbWVUOzoJ3kVGD5zX4T0V0xnd64/SWNzHXleo/uapLNx4xDSdmJl7jmzUOO5ryF5/e3aKwUZLZdxHIbcs2KVWwm0FDvBSelA@mHB7sPuLDfITebNAwrrHMaxpi2fieAW718tbvjFsnHLbgk9uHJPn5kFAmbZb280mqFX/CvX7aUV652pOhAGMN88Rpn@0RGp2yilXIhcb81SK@FmKFpFgoKZyqRuYjiRnSBFSQ@c/6yxTr9ruuU@K5MWnxFgpdyhBfOY4LRn6kHTThvNCw35oLikft07HHX82nrhbHA@/qXTrFkxjlaxxezu7NbpBPYw4nJHAA8zLETOLtj7q0oWyiwJauEv/qvQTlvpZMJHwSZuZcIFKxTIQC9n3omjngGeZ4kBhylAmAq7gE/f2VKxYQrquEfyvkb481erMKSyW6PKfLO1/@neQ1Q3EedPxgV3Y@etyAZ8QcWvoovIU7P6ya8VOWnXdqus4oV9iSalF5jBeTRGN6HQRNxf7I8UvW6KNpViFSUVZaaIyaExavn5Ulz@Ui3S6VQSb90p31BkMZlQx0o0m00b5@/P4QGS0/siWdAJXQII/e2b0Fx43wnlOZpU7j8Dl/9G9PsaAOOAPEsoOu8E4lUQGjWf3y38b6D/v5B/BXyB98vLd/F2DKaBPqH7QWVTzU4KKD16CuyZxRg6AtQXi1CUM2g5JNeUErmOqDrFaFCpfvhQz1PA5zg1R1zyWVIpbzT2ZAbeyApDWbZGE/muVosakGB25ZkGYavJjDxDtMWaVbKHeqIWszyrC3swGge3VNHGpOYAP@JM@qgwU1edlYUFX1Vox6Sam75Waj6Uq4U/iD/yv4M5J8sHk0rZ9sByjcp21uUnO76W12wu24FVTskkap94wuQnO0f@eJ4/5Wo9VnN6Bq4Oshc5wlytFD9v2KCqE/1/0HSJhXCV5IFz5vt/AA "Kotlin – Try It Online") ]
[Question] [ Given an input of an ASCII art picture, output the ASCII art italicized. To italicize the ASCII art: 1. Insert zero spaces before the last line, one space before the second-last line, two spaces before the third-last line, etc. 2. Remove any extra leading whitespace that may have been created. That is, if each line has at least `n` spaces preceding it, remove `n` spaces from the beginning of each line. 3. Replace all `\`s with `|`, all `|`s with `/`, and all `/`s with `_`. Keep existing `_`s the same. The input is guaranteed to contain only the characters `\|/_` and space. For example, the input ``` /\/\/\ /\/\/\ /\/\/\ /\/\/\ /\ /\ /\ /\ /\ /\ /\/\/\ /\/\/\ /\ /\ /\/\ /\ /\ /\ /\ /\ /\ /\ /\/\/\ /\/\/\ ``` must output ``` _|_|_| _|_|_| _|_|_| _|_|_| _| _| _| _| _| _| _|_|_| _|_|_| _| _| _|_| _| _| _| _| _| _| _| _|_|_| _|_|_| ``` which in turn, provided as input, outputs ``` _/_/_/ _/_/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/_/_/ _/_/_/ ``` which would output ``` ______ ______ ______ ______ __ __ __ __ __ __ ______ ______ __ __ ____ __ __ __ __ __ __ __ ______ ______ ``` Input and output may be either a single string (with optional trailing newline) or an array of lines. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Extra test cases: ``` ||||| ///// \\\\\ _____ ``` ``` ///// _____ ||||| _____ ``` ``` ________ ``` ``` ________ ``` (that is, input of empty string results in output of empty string) [Answer] ## CJam, ~~43~~ 38 bytes ``` qN/W%eeSf.*:sW%z_{S-}#>zN*"\|/__"_(+er ``` Requires the input to be padded to a rectangle. [Try it online!](http://cjam.tryitonline.net/#code=cU4vVyVlZVNmLio6c1clel97Uy19Iz56TioiXHwvX18iXygrZXI&input=L1wvXC9cICAgIC9cL1wvXCAgICAgIC9cL1wvXCAgICAvXC9cL1wgICAgCiAvXCAgICAvXCAgL1wgICAgL1wgIC9cICAgICAgICAvXCAgICAgICAgIAogIC9cL1wvXCAgICAvXC9cL1wgICAgL1wgICAgICAgIC9cICAvXC9cICAKICAgL1wgICAgICAgIC9cICAgICAgICAvXCAgICAgICAgL1wgICAgL1wgCiAgICAvXCAgICAgICAgL1wgICAgICAgICAgL1wvXC9cICAgIC9cL1wvXA) ### Explanation ``` qN/ e# Read input, split into lines. W% e# Reverse lines. ee e# Enumerate them (pairing each line with its index starting from 0). Sf.* e# Turn each index i into i spaces. :s e# Flatten each pair into a single string, prepending the spaces. W% e# Reverse the lines again. z_ e# Transpose the character grid, duplicate it. {S-}# e# Find the first row index that contains non-spaces. > e# Discard that many rows. zN* e# Transpose back and join with linefeeds. "\|/__" e# Push this string. _(+ e# Make a copy that's rotated one character to the left, i.e. "|/__\". er e# Perform character transliteration mapping from the first string to the second. ``` [Answer] # Pyth, 32 ``` jCf|Z=Z-Td.t_.e+*kd.rb"\|/__"_Qd ``` [Try it here](http://pyth.herokuapp.com/?code=jCf%7CZ%3DZ-Td.t_.e%2B%2akd.rb%22%5C%7C%2F__%22_.zd&input=%5B%27%7C%7C%7C%7C%7C%27%2C+%27++%2F%2F%2F%2F%2F%27%2C+%27+%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%27%2C+%27+++_____%27%5D&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=jCf%7CZ%3DZ-Td.t_.e%2B%2akd.rb%22%5C%7C%2F__%22_Qd&input=%7C%7C%7C%7C%7C%0A++%2F%2F%2F%2F%2F%0A+%5C%5C%5C%5C%5C%0A+++_____&test_suite=1&test_suite_input=%5B%27______%27%5D%0A%5B%27%27%5D%0A%5B%27%2F%5C%5C%2F%5C%5C%2F%5C%5C++++%2F%5C%5C%2F%5C%5C%2F%5C%5C++++++%2F%5C%5C%2F%5C%5C%2F%5C%5C++++%2F%5C%5C%2F%5C%5C%2F%5C%5C%27%2C+%27+%2F%5C%5C++++%2F%5C%5C++%2F%5C%5C++++%2F%5C%5C++%2F%5C%5C++++++++%2F%5C%5C%27%2C+%27++%2F%5C%5C%2F%5C%5C%2F%5C%5C++++%2F%5C%5C%2F%5C%5C%2F%5C%5C++++%2F%5C%5C++++++++%2F%5C%5C++%2F%5C%5C%2F%5C%5C%27%2C+%27+++%2F%5C%5C++++++++%2F%5C%5C++++++++%2F%5C%5C++++++++%2F%5C%5C++++%2F%5C%5C%27%2C+%27++++%2F%5C%5C++++++++%2F%5C%5C++++++++++%2F%5C%5C%2F%5C%5C%2F%5C%5C++++%2F%5C%5C%2F%5C%5C%2F%5C%5C%27%5D%0A%5B%27_%7C_%7C_%7C++++_%7C_%7C_%7C++++++_%7C_%7C_%7C++++_%7C_%7C_%7C%27%2C+%27_%7C++++_%7C++_%7C++++_%7C++_%7C++++++++_%7C%27%2C+%27_%7C_%7C_%7C++++_%7C_%7C_%7C++++_%7C++++++++_%7C++_%7C_%7C%27%2C+%27_%7C++++++++_%7C++++++++_%7C++++++++_%7C++++_%7C%27%2C+%27_%7C++++++++_%7C++++++++++_%7C_%7C_%7C++++_%7C_%7C_%7C%27%5D%0A%5B%27++++_%2F_%2F_%2F++++_%2F_%2F_%2F++++++_%2F_%2F_%2F++++_%2F_%2F_%2F%27%2C+%27+++_%2F++++_%2F++_%2F++++_%2F++_%2F++++++++_%2F%27%2C+%27++_%2F_%2F_%2F++++_%2F_%2F_%2F++++_%2F++++++++_%2F++_%2F_%2F%27%2C+%27+_%2F++++++++_%2F++++++++_%2F++++++++_%2F++++_%2F%27%2C+%27_%2F++++++++_%2F++++++++++_%2F_%2F_%2F++++_%2F_%2F_%2F%27%5D&debug=0) Each line has several trailing spaces. This works by applying `.r` which is the rotation built-in to each line of the string. The rotation takes each character in the string that matches one in the other argument `"\|/__"` and replaces it with the next character. The double underscore nicely prevents underscores from becoming backslashes. The strings are also padded based on their index. Once that is done, the lines are zipped together, then we filter out each column that only contains spaces, until one of them doesn't. Then we unzip and join on newlines. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~38~~ ~~33~~ 29 bytes ``` P"NZ"@Y:'\|/' '|/_'XEh]XhPcYv ``` Output lines have trailing spaces to match the longest line (this is allowed by the challenge). Input is a cell array (list) of strings. The array uses curly braces, and strings use single quotes, as follows (click each link to *Try it online!*). * [First example](http://matl.tryitonline.net/#code=UCJOWiJAWTonXHwvJyAnfC9fJ1hFaF1YaFBjWXY&input=eycvXC9cL1wgICAgL1wvXC9cICAgICAgL1wvXC9cICAgIC9cL1wvXCcgICcgL1wgICAgL1wgIC9cICAgIC9cICAvXCAgICAgICAgL1wnICAnICAvXC9cL1wgICAgL1wvXC9cICAgIC9cICAgICAgICAvXCAgL1wvXCcgJyAgIC9cICAgICAgICAvXCAgICAgICAgL1wgICAgICAgIC9cICAgIC9cJyAnICAgIC9cICAgICAgICAvXCAgICAgICAgICAvXC9cL1wgICAgL1wvXC9cJ30K): ``` {'/\/\/\ /\/\/\ /\/\/\ /\/\/\' ' /\ /\ /\ /\ /\ /\' ' /\/\/\ /\/\/\ /\ /\ /\/\' ' /\ /\ /\ /\ /\' ' /\ /\ /\/\/\ /\/\/\'} ``` * [Second example](http://matl.tryitonline.net/#code=UCJOWiJAWTonXHwvJyAnfC9fJ1hFaF1YaFBjWXY&input=eydffF98X3wgICAgX3xffF98ICAgICAgX3xffF98ICAgIF98X3xffCcgJ198ICAgIF98ICBffCAgICBffCAgX3wgICAgICAgIF98ICAgICAgJyAnX3xffF98ICAgIF98X3xffCAgICBffCAgICAgICAgX3wgIF98X3wnICdffCAgICAgICAgX3wgICAgICAgIF98ICAgICAgICBffCAgICBffCcgJ198ICAgICAgICBffCAgICAgICAgICBffF98X3wgICAgX3xffF98J30K): ``` {'_|_|_| _|_|_| _|_|_| _|_|_|' '_| _| _| _| _| _| ' '_|_|_| _|_|_| _| _| _|_|' '_| _| _| _| _|' '_| _| _|_|_| _|_|_|'} ``` * [Third example](http://matl.tryitonline.net/#code=UCJOWiJAWTonXHwvJyAnfC9fJ1hFaF1YaFBjWXY&input=eycgICAgXy9fL18vICAgIF8vXy9fLyAgICAgIF8vXy9fLyAgICBfL18vXy8nICcgICBfLyAgICBfLyAgXy8gICAgXy8gIF8vICAgICAgICBfLyAgICAgICAnICcgIF8vXy9fLyAgICBfL18vXy8gICAgXy8gICAgICAgIF8vICBfL18vICAnICcgXy8gICAgICAgIF8vICAgICAgICBfLyAgICAgICAgXy8gICAgXy8gICAnICdfLyAgICAgICAgXy8gICAgICAgICAgXy9fL18vICAgIF8vXy9fLyAgICAnfQo): ``` {' _/_/_/ _/_/_/ _/_/_/ _/_/_/' ' _/ _/ _/ _/ _/ _/ ' ' _/_/_/ _/_/_/ _/ _/ _/_/ ' ' _/ _/ _/ _/ _/ ' '_/ _/ _/_/_/ _/_/_/ '} ``` ### Explanation The array is initially flipped. Each string is processed in a loop and the modified string is pushed onto the stack. Processing consists in replacing the characters and appending a number of spaces. The number of spaces equals the current number of elements in the stack (thanks to the fact that the array has been flipped). After the loop the strings are collected in an array, which is flipped back, converted to a 2D char array, and disposed of unwanted leading spaces: leading spaces that are present in all rows of the 2D char array. ``` P % implicitly input cell array of strings. Flip it (reverse order) " % for each NZ" % string with as many spaces as elements there are on the stack @Y: % push current input string '\|/' % push string: origin for replacement '|/_' % push string: target for replacement XE % replace h % concatenate string with spaces and modified-character string ] % end for each Xh % collect all processed strings in a cell array P % flip back to restore original order c % convert to 2D char array Yv % remove trailing spaces common to all rows. Implicitly display ``` [Answer] ## JavaScript (ES6), ~~171~~ ~~149~~ 148 bytes ``` a=>a.map(s=>(t=' '.repeat(--i)+s,l=t.match` *`[0].length,n=l<n?l:n,t),n=i=a.length).map(s=>s.slice(n).replace(/./g,c=>"|/__ "["\\|/_ ".indexOf(c)])) ``` Accepts and returns lines as an array of strings. Edit: Saved 22 bytes thanks to @user81655. Saved 1 byte by realising that the input is limited to the 5 characters `\|/_` and space. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM) (older versions), ~~23~~ 48 bytes Adjusting whitespace is expensive: ``` {{⍵↓⍨0,⌊/+/∧\' '=⍵}(⍳≢⍵)⌽'|/ _'['\| '⍳(∊,⊢,∊)⍵]} ``` This requires `⎕ML←0`, which [was default until recently](http://help.dyalog.com/14.0/Content/Language/System%20Functions/ml.htm). [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `a` ~~39~~ 37 bytes -2 thanks to @Aaron Miller ``` ṘėṘƛt`\|/``|/_`Ŀnh$꘍;:ƛ`^ *`$et;g£ƛ¥ȯ ``` Really bad answer, id like to fix it; the program takes in the string, breaks it into chunks, transliterates to the correct characters, and then spends most of the chars trying to fix the spacing. [Try it Online!](http://lyxal.pythonanywhere.com?flags=a&code=%E1%B9%98%C4%97%E1%B9%98%C6%9Bt%60%5C%7C%2F%60%60%7C%2F_%60%C4%BFnh%24%EA%98%8D%3B%3A%C6%9B%60%5E%20*%60%24et%3Bg%C2%A3%C6%9B%C2%A5%C8%AF&inputs=%20%2F%5C%2F%5C%2F%5C%20%20%20%20%2F%5C%2F%5C%2F%5C%0A%2F%5C%20%20%20%20%20%20%20%20%2F%5C%0A%20%2F%5C%20%20%20%20%20%20%20%20%2F%5C%20%20%2F%5C%2F%5C%0A%20%20%2F%5C%20%20%20%20%20%20%20%20%2F%5C%20%20%20%20%2F%5C%0A%20%20%20%20%20%2F%5C%2F%5C%2F%5C%20%20%20%20%2F%5C%2F%5C%2F%5C&header=&footer=%2C) [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rl`, ~~39~~ ~~38~~ ~~37~~ 36 bytes *How do you golf an elephant? One byte at a time...* ``` YsXRV,#g.:gWw~=@ZyY@>*yyTR"\|/""|/_" ``` [Try it online!](https://tio.run/##K8gs@P8/sjgiKExHOV3PKj28vM7WIaoy0sFOq7IyJEgppkZfSalGP17p/3/9GBBUAAIEC5mNYHEpwEQUMFgwHhRwYTcBVS1ElEsBuxnoLCDJhUsFpm3/dYtyAA "Pip – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` JU⁶ẋ$;¥"µEƤS$€Ṃ$‘ṫ€@µ“\|/“|/_”yⱮ ``` [Try it online!](https://tio.run/##y0rNyan8/98r9FHjtoe7ulWsDy1VOrTV9diSYJVHTWse7mxSedQw4@HO1UCOw6GtjxrmxNToA8ka/fhHDXMrH21c9//h7i2H2yMf7mw5tPXY5EMLH@6cDZQHSv43/q8fA4IKQIBgIbMhLC4FGE8BgwXhcWFqgimDKYGIc2GIYmdBVGJVgGkVAA "Jelly – Try It Online") The number in STDIN just indicates how many times italicization will be run (for easier testing). Set it to 1 for normal execution. [Answer] # [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╦'Fi╘◘¥╘τ9jq'∟w7#ù╢→↨↨─╟ ``` [Run and debug it](https://staxlang.xyz/#p=cb274669d4089dd4e7396a71271c77372397b61a1717c4c7&i=%5B%5B47,+92,+47,+92,+47,+92,+32,+32,+32,+32,+47,+92,+47,+92,+47,+92,+32,+32,+32,+32,+32,+32,+47,+92,+47,+92,+47,+92,+32,+32,+32,+32,+47,+92,+47,+92,+47,+92%5D,+%5B32,+47,+92,+32,+32,+32,+32,+47,+92,+32,+32,+47,+92,+32,+32,+32,+32,+47,+92,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92%5D,+%5B32,+32,+47,+92,+47,+92,+47,+92,+32,+32,+32,+32,+47,+92,+47,+92,+47,+92,+32,+32,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92,+32,+32,+47,+92,+47,+92%5D,+%5B32,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92,+32,+32,+32,+32,+47,+92%5D,+%5B32,+32,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92,+32,+32,+32,+32,+32,+32,+32,+32,+32,+32,+47,+92,+47,+92,+47,+92,+32,+32,+32,+32,+47,+92,+47,+92,+47,+92%5D%5D%0A%5B%5B95,+124,+95,+124,+95,+124,+32,+32,+32,+32,+95,+124,+95,+124,+95,+124,+32,+32,+32,+32,+32,+32,+95,+124,+95,+124,+95,+124,+32,+32,+32,+32,+95,+124,+95,+124,+95,+124%5D,+%5B95,+124,+32,+32,+32,+32,+95,+124,+32,+32,+95,+124,+32,+32,+32,+32,+95,+124,+32,+32,+95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124%5D,+%5B95,+124,+95,+124,+95,+124,+32,+32,+32,+32,+95,+124,+95,+124,+95,+124,+32,+32,+32,+32,+95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124,+32,+32,+95,+124,+95,+124%5D,+%5B95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124,+32,+32,+32,+32,+95,+124%5D,+%5B95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124,+32,+32,+32,+32,+32,+32,+32,+32,+32,+32,+95,+124,+95,+124,+95,+124,+32,+32,+32,+32,+95,+124,+95,+124,+95,+124%5D%5D%0A%5B%5B32,+32,+32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32,+32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32,+95,+47,+95,+47,+95,+47%5D,+%5B32,+32,+32,+95,+47,+32,+32,+32,+32,+95,+47,+32,+32,+95,+47,+32,+32,+32,+32,+95,+47,+32,+32,+95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+32,+32,+32,+32,+32,+32,+32%5D,+%5B32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32,+95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+32,+32,+95,+47,+95,+47,+32,+32%5D,+%5B32,+95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+32,+32,+32,+32,+95,+47,+32,+32,+32%5D,+%5B95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+32,+32,+32,+32,+32,+32,+32,+32,+32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32,+95,+47,+95,+47,+95,+47,+32,+32,+32,+32%5D%5D%0A%5B%5B124,+124,+124,+124,+124%5D,+%5B32,+32,+47,+47,+47,+47,+47%5D,+%5B32,+92,+92,+92,+92,+92%5D,+%5B32,+32,+32,+95,+95,+95,+95,+95%5D%5D%0A%5B%22________%22%5D%0A%5B%22%22%5D&m=2) Takes a list of lines as input. They are formatted as ascii codepoints for convenience, but you can still pass a list of strings directly. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 84 bytes ``` def f(s): i=len(s) for x in s:print(' '*i+x.translate({92:124,124:47,47:95}));i-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfYxutHl8DggpAgGAhsyEsdR11GBeCkVkQHlgJplnISiDicLMwpZFZOBVicV3s/5TUNIU0jWJNKy6FTNuc1Dwgk0shLb9IoUIhM0@h2KqgKDOvRENdQV0rU7tCr6QoMa84J7EkVaPa0sjK0MhEB4itTMx1TMytLE1rNTWtM3VtDf@naeRo/gcA "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ A lot of PPCG users helped with the creation of this challenge, both in chat and the Sandbox, specifically [Martin Ender](https://chat.stackexchange.com/transcript/240?m=43488434#43488434), [AdmBorkBork](https://chat.stackexchange.com/transcript/240?m=43717719#43717719), [Emigna](https://chat.stackexchange.com/transcript/message/43814604#43814604) and [user202729](https://chat.stackexchange.com/transcript/240?m=43915697#43915697) Our community has found it necessary to create a set of languages designed specifically for golfing, "golfing languages" as we call them. Such languages have evolved from the once brilliant, now clunky [GolfScript](http://www.golfscript.com/golfscript/) to the sleek concise languages such as [Jelly](https://github.com/DennisMitchell/jelly) and [Husk](https://github.com/barbuz/Husk). As we can see, these languages are continually getting shorter and shorter for a set of tasks. So, as the obvious experts around here regarding golfing languages, we should design a language together to beat every other language that dares to compete. Introducing Bugle! > > Bugle: From the acronym BuGoL: *Bu*ilt *Go*lfing *L*anguage. > > > ## How this challenge will work In case you didn't get what I'm alluding to in the introduction, this challenge is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge where we each contribute something to the interpreter of a new golfing language, improving its ability to compete on PPCG with each answer. I will post the first answer consisting of the basis of the language spec/interpreter, and all other answers will continue from that. New submissions will provide the following things: * A change to the language's spec * An up-to-date interpreter, meeting *exactly* what is laid out in the changes * The language's updated score (more details in a bit) You may change the spec in one of three ways: * You may add a single command * You may add two new commands * You may edit the behaviour of one existing command Regarding the new interpreter, you *must* use the latest version, written in Python. It does not have to be golfed. Every previously added command must be testable with the latest interpreter, as well as the newest command(s) (the one you add). You must also not use offensive language at any point when updating the interpreter, such as in comments or string literals etc. **The added command(s) may do anything you wish**. The only requirements are: * It doesn't produce offensive output * It isn't the same as another command * It doesn't prevent one of the sample challenges from being completed Aside from these, it can be as specific or as general as you want. It can also be any *character* you want. If you aren't sure if your addition constitutes a 'new command', feel free to ask in the comments. ## The language's score You may have noticed that you have to include the language's score in all new submissions. Its score is what prevents this challenge going forever, and is defined as follows: > > The current score is the sum of the byte counts it takes for the language to complete the below 20 tasks > > > For each of the tasks, [Standard I/O rules apply](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), as do the [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). ### The 20 tasks: 1. ["Hello, World!"](https://codegolf.stackexchange.com/questions/55422/hello-world) – Output the string `Hello, World!` 2. [1, 2, Fizz, 4, Buzz](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz) – Output each integer from 1 to 100 (inclusive) on a separate line, with multiples of 3 being replaced by `Fizz`, multiples of 5 being replaced by `Buzz` and multiples of both by `FizzBuzz` 3. [Produce the number 2014 without any numbers in your source code](https://codegolf.stackexchange.com/questions/17005/produce-the-number-2014-without-any-numbers-in-your-source-code) – Output the number **2014** without using any of the characters `0123456789` in the source code, without accessing external variables or random seeds 4. [Obfuscated Hello World](https://codegolf.stackexchange.com/questions/307/obfuscated-hello-world) – Output the string `Hello, World!`, without using any of characters in at least two of the following sets: `hlwd`, `eor01` and `27` (case-insensitive) 5. [Sing Happy Birthday to your favourite programming language](https://codegolf.stackexchange.com/questions/39752/sing-happy-birthday-to-your-favourite-programming-language) – In a language of your choice, output the following: ``` Happy Birthday to You Happy Birthday to You Happy Birthday Dear [the name of your favourite programming language] Happy Birthday to You ``` 6. [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) – Output the full [lyrics of "Never Gonna Give You Up"](https://pastebin.com/wwvdjvEj) 7. [Output the sign](https://codegolf.stackexchange.com/questions/103822/output-the-sign) – Given a number, print **-1** if it is negative, **0** if it is **0** or **1** if it is positive 8. [Collatz Conjecture (OEIS A006577)](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture-oeis-a006577) – Starting from an integer, divide it by 2 if it's even, or multiply it by 3 and add 1 if it's odd, and repeat the process until you reach 1. The output should be the number of iterations it takes you to reach 1. 9. [An Array of Challenges #1: Alternating Arrays](https://codegolf.stackexchange.com/questions/103571/an-array-of-challenges-1-alternating-arrays) – Given an array of integers, check whether all even-indexed items are equal, and all odd-indexed items are equal, and output a truthy or falsy value accordingly 10. [Am I an insignificant array?](https://codegolf.stackexchange.com/questions/143278/am-i-an-insignificant-array) – Given an array of integers, check whether the absolute differences between consecutive elements are all smaller than or equal to 1, and output a truthy or falsy value accordingly 11. [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime) – Given a positive integer, write a full program to check whether it is prime, and output a truthy or falsy value accordingly 12. [I'm a palindrome. Are you?](https://codegolf.stackexchange.com/questions/110582/im-a-palindrome-are-you) – Given a string, check whether it is palindrome, while your program / function is palindrome too, and output two distinct and consistent values accordingly 13. [Sum the numbers on standard in](https://codegolf.stackexchange.com/questions/113674/sum-the-numbers-on-standard-in) - Take a series of numbers in from STDIN and output their sum. 14. [Find the Factorial](https://codegolf.stackexchange.com/questions/607/find-the-factorial) - Given an integer `n`, output the product of all integers between `1` and `n` inclusive. 15. [Shortest code to produce infinite output](https://codegolf.stackexchange.com/q/13152/66833) - Without any input, produce infinite output, that will, theoretically, never stop outputting. 16. [Bake a slice of Pi](https://codegolf.stackexchange.com/questions/93615/bake-a-slice-of-pi) - Output this exact text: ``` ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` 17. [Find the smallest number that doesn't divide N](https://codegolf.stackexchange.com/questions/105412/find-the-smallest-number-that-doesnt-divide-n) - Given a positive integer N, output the smallest positive integer that does not divide N. 18. [Is this even or odd?](https://codegolf.stackexchange.com/questions/113448/is-this-even-or-odd) - Given an integer N, output its parity as truthy/falsy values. 19. [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code) - Write the shortest code whose output has the same length as the code, where the output is not the same as the code. 20. [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good) - Write the shortest [quine](https://en.wikipedia.org/wiki/Quine_(computing)) in your language. In order to be valid, a new submission must have golfed submissions for at least **2** of the problems, by at least **1 byte** for each. You may increase the lengths of other submissions, but the total score must decrease by **at least 2** per answer. Also, please consider including a link to the updated programs. The updated solutions *must not work* when run with a previous version of the interpreter. ## How to get cookies I have a list of 5 challenges, which aren't compulsory to attempt, and have no bearing on your score, but are simply additional challenges to test if Bugle is capable enough. Feel free to include a solution to any number of these in your answer: 1. [Create a Self interpreter](https://codegolf.stackexchange.com/q/585/66833) 2. [Create a payload capable quine](https://codegolf.meta.stackexchange.com/a/4924/66833) 3. [Covfefify a string](https://codegolf.stackexchange.com/questions/123685/covfefify-a-string) 4. [Hyperprogramming: N+N, N×N, N^N all in one](https://codegolf.stackexchange.com/questions/92944/hyperprogramming-nn-n%C3%97n-nn-all-in-one) 5. ["KNOT" or "NOT"?](https://codegolf.stackexchange.com/questions/30292/knot-or-not) Descriptions not included as they aren't required for everyone to be able to compete in the challenge. ## How to win Once the minimum score ([we believe](https://chat.stackexchange.com/transcript/message/43717558#43717558) to be 16, although any attempts to golf that down are much welcomed) has been reached, obviously the chain has ended as solutions cannot get a better score. Once 16 has been reached, the challenge stays alive for **1 month** afterwards, to give anyone a chance to golf the solutions any more. After this month has passed, the challenge is over. Once the challenge is over, I will be migrating the interpreter onto a GitHub repository, and going through the usual machinations of releasing a stable language. You may also begin to post solutions to challenges on PPCG at this time, using the said language, but please try not to flood the front page with answers. Instead, spread them out over a period of time. ## Formatting In order to make information easier to find in your answer, please format it as follows: ``` # [N]. [Score] [New command + description] [Interpreter/link to interpreter] [Link to programs] ``` Where `[N]` is your answer number (1 for the first, 2 for the second etc.) ## Rules * You must wait 3 hours between posting answers * You may not post twice in a row, unless no answer has been posted for 10 days (exactly 240 hours) * You may not remove previous commands. * Your interpreter doesn't have to be golfed, and its byte count is completely irrelevant here. * If someone suggests a golf to the programs while your answer is the latest, you *must* edit in the golfs, and update your score. + You may also do this when your answer is in the middle of the chain, so long as your score doesn't become lower than any later answers. * Please refrain from answering any existing PPCG challenges using this language, at least until the challenge is over * The interpreter is written in Python 3, and should continue that way throughout the entire chain. Changing the language is forbidden. * Again, in order to be valid, a new submission must have golfed submissions for at least **2** of the problems, by at least **1** byte for each. Let's get started! [Answer] # 2. Score: ~~2938~~ 2583 The modified interpreter is [here on TIO](https://tio.run/##7Txpc9tGlh@3ir8CuRakTTFSjtlZJsocuTa7k3jWTvYYhcOBSEhCTAIcELTFeL0l0hd95LLj@Ep8JD4Sx3Fsx4ckH6kSSCXOBwj6CcQfyb6@gMZFgfaktmprVWWT6O539HuvX7/X/cBa05jR1Kd/Vqo1TTcESZ@uSXpdTtHnklapyCVD0dQ6a9Jqsi4Zmu4@uz31pvu1oSolrSyXJUNKpR4TxsfHhRcBhyGpRh0/PZZKKeqUMC5MVTTJSIvwIGZSqqR6TfAATSmEp1iTpmUBukRRNOfMltk2d5q7zR3mru5cd@fbxttqd3f3gLmn@775odkx95r7zP3dg91Puse7R80D5nvm@@YH3Yvdy92F7l1AweFcj3EKjzz62ONP/L2Yzqxbnx3JPTk69tTTzzz7q3/49T/mn3t@/IXf/PZ3v3/xpZdfefWfXvvnf/nD629s@OO/btz05lv/9u//8Z9/mni78OfiX6TJUlmemp5R3tlcqapa7a963Whs2TrbfHfbf23/76WbUUR7rd6O3h7zo94@86B5yPzY/KR30DxsHu0d6H3cO9o73jvdO9s7bx4zj5snzE97l3sXe9fNz3o3e/O9hd7d3m3ztHnG/Nw8a543vzDPdVvdXd093ffMC90PzCvml@ZX5kXz6@6h7pHuie4x85L5jXnZ/Lb7dffb7mL3Xq/d29nrmFd7@81r5nfmdfNm75A533vPvNE73Dtmnuqd6J3pnetdMBfMRfO2eaf3be/r3g3zbu@W@X1vsXevd8c5si9qUtZH1m7roHXI@tg6bHWsT6wj1l7rqHXM2mcdt05Yn1qfWSetU9YB67R1xvrCOmuds963zlsXrC@tr6wP/g6hDOO8al2yrlnfWdetG9Y31k3rlnXZmrcWrG@tD61F67Z1x7pr3bO@XzmwMreyY6W9snNl18p71pWV3St7Vjore1fej@L0h@v9@Sv9@Xv9hY/7i@0fbvTnr/bnv@8vHO4v7ujPt/vzJ7un@/Of9xfmfrzcX/ikv3C6v3Cxv7ivPw/dp7pn@vNf9BdaP37bXzjSXzjTX/i6v7h/6UK33T3ZvdR7v3epe727o3uq@03vg9433RtLF5cWnbkFZ24xipfl1vKe5X3LHy0fWj7qXL28/Nny2eVLy9d@PHv/0HLn/pHlg/dP3z@/fOz@1fvXls/9dPr@nZ/ay9/8tP/Hc0tfLV3uXv3xVhRSe6@9zz5sn7Y/t4/YX9hH7ZP2KftL@0P7jP2xfdY@ZJ@zO/Zx@4R9wd5v77I/sM/bB@2P7M/sT@22/cnqsdXj9o3VudW2fWt1hz1v37O/X@3YV1Zb9vXVnfZ3q7tWj9qL9u3VPasnVg@vnlrdbV@zr9p37TurB@2b5knzXhRPztxpp9N2OrudvR1nL3w/7nQ6Tmev0zngdPY7na@czsWlS07ngtP50tl3eOms0767dG7pi6XPnfYlp/2VM3dl6fulM05rj9PqOHN3nNZeZ@6uM3/UmTu/dMWZ@9yZ@8yZ@9SZO@nMHXPmjjp7zy59vXRr6baz91z/@h6nc3LpvHnEaV1ZWli6tvSd07rutG44rZtO65bTmndaC05r0WnddlqA@a7TumfectpzTrvltNtOe4fT3um0dznt3U57j9PuOO29Tnuf097vtA847fecNrYz6u5el6ua3hSqIICK6/JKFaleF15HbfmUAH/gNASlXjSkmpyuy5WpDGlGf7psNHQVehXsN0tkQFZ4E8aCW@Sgobu0OSn4JjTYDz@tK@Wk4K/CWD@0Lk8rdUPWk2LYSMf7sZTlvzYSi@AlNJiDLzV0XVaN4hapEoFEUuqy8IZmvFatVeQqjJPLL@s6bGAufFXaLBdVpSKVKQGMKBkOolIs1TRWbMbTbLGoqIpRLFKs6zDaOocXteew@mBvq4BY0nSIO8LFVWvUZ2LxTGk64VlQVPKl7nX6CeWkWk1Wy4QQJ8OaVqPoFbUszwI/I2McBUNv@jFS3XCIEQYM63Evz5bkmhEJOMqRluXND0d7gsA9IVRkNe01ZwpDcjLYkDiqaK6ZIQyIACEVBuW@VVcMGZawrqjTPHA9EpqpPsXZmC7XdGpjYW5FYpnbtmfEHFhJFQIrTj48GmAhFgv0xYEB9/FwCvMLEYDTsgHdVXd1ENOJFjen5IKP5ygcMdLncYCF4THeMiPLGPnWtVZxXXlXBngIWLOgPKkG39/UI8iRYejD30Fh0Ie/A20C0DExWvC3szUx6jYrU4SLRzAbESvdQyWsIyysaS8Ip8d3BGJmUFhGEwJsuEIhI/odFfZFiipVUKhOBoo@J6Vg5SAvJauNKkokyDLDHGf8BLdgNMj04FvG1wXMKohJTz5@UI8PFHZsE4X1GNt6Qdwu@gbC3iwPAAWgVDROQUyFG3l5UHHhzjWX2ZrChwGua4sQFfaSMuxNIE8keqKebduJlsSYCaKILNw1pJYSaGsYrQ2lvcFaXFObA7Ua0COTLnOiGGYiPzJWCM81gYWxxTQR1FB4uKurCT9zD6KoNZSUVEGJlROvmIFKiVUIkwX@zKFNE7ZhRLuw9sJLuFEZXnj925qODjuMphcfyJXKoLAAAU940isEt3kXPmaPCsK7@9RQ4QK2DG4n9NsHGZ7llBwwlK0zSkWmkdgL40G/4zHKIsnRTPQGNBE3h6q2RS7qyvSMEZQlt9@B9sei/eMj0f7R3VzDBsehfWLcwzRg0REZcHBhQURTCQjGP@eKPDVoyiMPPGVBUss8pueF0YFS4IQgjHBEiTAAs6oZQ2InKdJraADJjGK9YljabCprMY@FC7kgrMn0aFYYzQye44ME9miFDhvXc2ubRfcknETJ8lrh5CyYFQsnm9z3WS62hJ4BkSbFgD78HRRdM9TBcM@Gg1BGqBnumg0HogQkph0dK6AgNBDO1jRFRa6YuCZXS9QO8GRizL0Z18ecXhF5Ol1Sp@U0GhsTqbjMsXVKwmREOZNg604EHmnjvyD/SRgPUBgbHU4@Y6MJsk4usAx5MmKnAzxZM26APwzCIRP8e1sVnP2X8b9C8qg@NuitKCreKd3p59cMFiHyQLEUgswIb8cGoPgvBwKrSCU5LWbFLPAwBMDEsAAFCgCBERHUgAxgAs2CRLNjKJwNRFPxzjqhthD6tIiUJIIRwdJPu/soEjKyXWh/5slnM5jfSF7/z2onXjPuFIaQ3f@vguHlvPYKCMUvQ2X2kq5LTXa4W5Vq6YpUnSxLgpT3mgAwK0iZTNaTesZz6FVptqhrWyF4VKeNGUAFDQSTrGYJ/kwm4hjGSwIA2p8CEKCoiBfZFwzPQBDmpxsR8Glb2QYhjor@DQgT8OJ/GJryMVeTyu5E@MmAHSO@JcQuYRKUMZYaYLtoOJ0fBsiHcmSZHNjjjU/bmo/IUUn/OPuW099pgGaAx0z84qRjY06HeHvjzQWZ1vMvoIMZ/L//SHaWqosLqoY9acUJ8VRFMgzeT2RQqPzAOS32NBxPhQmO26Ez3MHYfvF8d3aYhDfEK8t@Qx2DUuHwjAfPlcbHkXliMHaOSlkGJ9ezA7Lr2AAt8aTjo4XZAZn5rD81x4lMwsR5dkDmzE3Hy2BnY3LMmCnGJptxGdEACbiUOW7WlgonFEjVpck67ywy4cw9ipabzQ9JD/levyLK2lY1UhHNAXbVXCvwnx2UGMWkIy7gg@ZsSay2OUBeTb/VNsNW26gNEtXIGqLyrKSZzGZnE9lscxibbUbYbAKZcCLhbbY50GabMTY7JD2fzf7vHPuwCgdy9INuJY348x/myt/Q1BAF1hfYJ9a68nXph259g5fPCW99g2CJxRo8@E0k18CsiUxxyQcTKFeVmMOFIz7xxgkHHWvVGxD8pDM5d1Rm4tl8ISRBTA2lBTAq5SvDWENiYfS/QikFEQG6wQceQtxTp5RQvgOrIUhdgr/ogTuUXav@IZmCYipIkoZqaxeq@AolcIFQGcShGM00zw9ln5oJGgZOV69oiHl0118sVVGWwWCzAjo@DjUi/xlsTAXu6shyCoFi5YVapUqFtnFL2it1UlWwkCp3Jkz9LQNT6tj1IdhIbdFxFEU471OmSM1Zzi0My0SbCxNRIky4QC0aEZNqIjy41CwaD1NEIjxu0Vk0Ll5lsfjoWFeLbCBvXFhdrKTvlYZKli0r50MKnYS8Tm8WWVU0Mb2soNUoZ7Q2Clk0qrByK6VQtu89oPQMiJA6MuFFrVqFPRDoMCpSmRo1xRpLlTznYDxdOvXGpKFLJWMocACi4NVGxVBqleZQ4ABEwcvKFlgZQwEbekMGMEZfKzcq2nDUNXfuW6Wa77CDnEuMPFXIsq9jKA9zv2e9EQSDLoNLqfsnAHY4I9Uhx9aZOlH9GuhTZDm6yHtMT/@cvifyXumAP/wig1hNIPdEQAhbkMSXG6BTfm6GZuDDERJUBk4@AmcjZOw6/zEGW8@oj5BhJwk8GdTm3eqALIxmjZ0oocgVnWoFUnNDrsadzyBk68ddQmholFBQP9t2CCmeY9RLFY4PQPAIcPe6UmVM04MjyrVvFwqwBTMiXZCPIAwCjMXgEVUZUTshO/CjBSJYZwEWfnEe@CMn3mx0UK3hN2bJNTIvdJiMaCtFtHGmLUFQlhUmqRdDlV/Ck/j6M8KXKWpJx1ZHYme8f@BjKmrH7JkPsL1G9IiCfOZg5IdGNuIim5aN0ozkbiogRjTrZh0WYFlRc7oMocVYhhk@dIcCQPjgNVCa0XEVAEWuqLWGwbD74jjcY8g4kiCDUlFVqyw@Fb2gwoeG9stgDGmGciAmNohtcRuoE/Vtcfh8rFjRQPGonp8LtkkPF9NkhUZdLnPuj5ytkX3bH9YGdm48BE8fXGgN2MO0sgKPNhU6j6fT4PigNjaFgh8DW0aQaegbxHG9VlFAJDrwosqzRhGnmJQZyKnF7dxZN6DCAX1ZnsgzuIIvr3b7WTeXbbgBzZCCAaoxcgln8mFozFVCuTJRee9w4cUsgC1sbtRcI6midx0UGa3xbcQDiY@JeQEdQeC3FUhALT5O28grCLTxVdqIXyygbS/RNlLnTxs3ocYx7v2BLCVlzqGep/y0zBYdTu9bUKlLntT3oq/@0l0XqJ0M6BUJZJhxGfjhOgJ7xp1DansqNeXFiq5M1sMwN0XxZz1cvgKhmz8B4dOMUCef0/j8qn8Yn@XEDHOnM5KITRZXxvMaPYJj2O@7YxmOG@Yy/EQihkkkGc9usN9Fn0@EnpkMaspHRH04RszEk6fwuCkv8OcCafyAwtNMBHfPJeJuE9u64xnAiy08hNMXZRG15PH//KY6molVIIXDt8lCcDMejZrU87GT4thB6zLnXg/EUkeLMmqYS2z8b6JfFBXh2lkuqUvAEzpQj@DpheEEgO97ElALjHPJ/ebhROCFNg9m4LHwSY1P0zESErxlHtASY5G4YvrDw4kJXyx6Cd0DCgthIYeeUSxuiGXRO5eiyHEEkIdcEhWWAGZaGR4ZkkTS2phIHDSFjoD/099u4b0gRPqRP8dSiFwejVoEjpkEEsUyjIDVHkobKHtIrg09mTZwCjic4dG0scw2iHQk/XqysGGrNGAP8ve6qJ258w9nKuuivbIXQh5JFkLQw7AH8y/42XeDH8nKrUSskIO1wS7fV0/gJwURqualem6EOgG0vWyPRsXboJHPpwg4Tb7BPNOTTUMmx/5uloV//MGr1ClpKnh4UDMaygJoL4flCjjwAF/9Rgg7TZ18OP1JTzy54IjIU2YCNS6Mzk5NDUaMsgffANy@flzwmKavpq4XcGHZWCr@HodJbT3JGPFr8xMI0RpvseLC@7fID268hHHgu560@Ja6WYXwgjCFDS7PFx2hZlo5lvKdh2M2iIa5DJhMB59a60ZWQNskVQj6AY2N9PBwRhbqVXBuMHt6hqVNCfS1YMgISjMwRDLo8RGWD8aXpzUxSl2YlCroVe8yvgVO80IsIKVgusQyUbki3lKxceBLa0SAUStrcl0VDRAa5Is5QWQ1ye6dMSJM7bWGK@tGOb6KyPOGTZWvFXreRx6zSzABYzwS95FN45FxXnzswj04U/FRMXA35mMMX5B7Lb5660Bf@HLfRwuWm@sMcpvlZj0dURlOZuar74h83y1yJgUxDiGuguCOwUJFJKEjCTSEnoKjX6rhT3cMbbOMM252Ou0rdShpVVro5@k0Ttek3cMUo3uONqYASmXnPXx5HPNYuHtoxQakO1C3nhRYuEjNM1w/wc0w5a/GiENOOhhi10fl6AkZsuhMABdqzCl18CkKeAUI1GAtuGIoBsSAGRfI2vDKeIuojHckUGAaYyhramiApiJehkSiDs4guh46oqTHty3osrQ5WlHY3QONVDTK0BT92sVPEXebrvDXXtzklDt01OluW1m0fDMDeHDRTyCChbQnVAQu5BGFQiZKf@PueXn04aWfDjawVKTjCcjqMRpGE/iM/3YLNbGLiMBRM/nJFnJxT45G/bf4rn/hPA/ZiZAIJiu@kAAUgDHAlua/zKd4vRs0Sjc00OXHLejhCro4kv7wBqFnIiMYMv5Iy9iMvCidTN7voWDnRkjTMCZgJtBC0bFDY7@xcT/SAkOz@B4weJKNwXO@OhFEKICJ8icO/uUdMcQeOeVOcz89lsNBpFLCVDIRvAAImssEgiY/HoKnVkjFvLhIuAs6NIQeFSUipkdEHAiglrF8AY1UphV0sBEpCq7eBt/ZhPmMFA07b49cz5KOy1BgTBFdzaK0hQ5H04yZmk8kDDS9boLyGcg/g6@SYZKZwEtoUXYYtZcxQw47VrpQsIbG8mEPHbXqBsrNPZSngsOqiqbvDsVCC08g7KzclIJ3NwSOuBt5Vi41DOQ2wO@oBi5JNwBkus4XCeFySNKco6bMBRgUFGdWuXcgs0tjp4sVwtw9G5Sj6ZnYMKZGfi1mBG5LcDfvyBoEjgzFwVo4V8J7z3AnN4vgCyTEN5PNmQJmhSkF65Fetso6@nkoBZXbqVJVLhZJvFCsSopaRGEDvWonP1ao4xIO8j33O326gcK8P@Ie9iM96JpbrMMmJRdRfQl3f4pO/Ejc5aJD1TPFasNogDdsFiHnqjTqyhZ0Zaw12N03BcNDJUoyLY5M4WBlBM0Gvs3IFXRdJG6qgbuYQhdkKPnBwhcmZQHdJwtTulYF9iiEhI0OMTOQTImQgVzf/YJevxqGJMrUSuw6j8DyxP0CDtJvELLUPjmyb0Eqis0NEnjoQhHmFC5egIQwYnqxBCqEADEdDv@GhlFrGJh5@j4UpJfoCduPoQmb3nzp5Y0bh5lMTdemdakqDuYIvm0BrCp84tW3TqRomZn7DAh/IOg6M0B@QSBeuRtyBc2ihl86oQMoS@SSFlHTJ2H5SnXBDxlYqqiT1ChQmrS2miIFG4lc4fioIoI2cxupCAdBX/bf4B40YDcM4p@CSIw6OtyEzYOhiPd/qZ/hb6Tx80jl55HSz4@PTYytH6vnn64/sW37o@@@q7zyqAZ/9edG64X8s7Sx8Xuvsb4tv2F7YWxUy4@Njo4U/gc "Python 3 – Try It Online"). String literal is the most obvious addition to the language, mainly to combat [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges. ## Solutions ### 1. ["Hello, World!"](https://codegolf.stackexchange.com/questions/55422/hello-world) - 20 bytes (-28) ``` #"Hello, World!"[o>] ``` Any [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge can be completed using the structure `#"<string>"[o>]` which outputs the given string until the 0 after the string is reached. ### 2. [1, 2, Fizz, 4, Buzz](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz) - ~~419~~ 64 bytes (-1332) ``` $1[1+1s:3s%{}"zziF"oooos;0s]:5s%{}"zzuB"oooos;0s]s{:O}]10o:100-] ``` Thanks to @user202729 for awesome golfing on this. ### 3. [Produce the number 2014 without any numbers in your source code](https://codegolf.stackexchange.com/questions/17005/produce-the-number-2014-without-any-numbers-in-your-source-code) - 9 bytes (-4) ``` #"ĒĎ"[O>] ``` Uses the two chars 20 and 14 in Bugle codepoints. ### 4. [Obfuscated Hello World](https://codegolf.stackexchange.com/questions/307/obfuscated-hello-world) - 19 bytes (-153) ``` #"Ifmmp!Xpsme"[-o>] ``` Meets rules #1 (no `HLWDhlwd`) and #3 (no `27`). ### 5. [Sing Happy Birthday to your favourite programming language](https://codegolf.stackexchange.com/questions/39752/sing-happy-birthday-to-your-favourite-programming-language) - 98 bytes (-230) ``` #"Happy Birthday to You Happy Birthday to You Happy Birthday Dear Bugle Happy Birthday to You"[o>] ``` ### 6. [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) - 1887 bytes (-5006) ``` #"We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it And if you ask me how I'm feeling Don't tell me you're too blind to see Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you (Ooh, give you up) (Ooh, give you up) (Ooh) Never gonna give, never gonna give (Give you up) (Ooh) Never gonna give, never gonna give (Give you up) We've know each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you"[o>] ``` ### 16. [Bake a slice of Pi](https://codegolf.stackexchange.com/questions/93615/bake-a-slice-of-pi) - 149 bytes (-290) ``` #"()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\|"[o>] ``` ### 20. [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good) - 62 bytes (-12) ``` #"[>]<o-o+[<]>[o>]<-o;<[<]>[o>]#"[>]<o-o+[<]>[o>]<-o;<[<]>[o>] ``` --- ## Added Language Feature * `"..."`: String literal. + Stack / Deque: Push the Bugle codepoints of each char to the top / front of the stack / deque. + Tape / Grid: Write the Bugle codepoints of each char onto the tape / grid to the right, starting from the current cell. Does not move the cursor. + `\n` is handled just like other chars. + There is no escaped character for now, so you can't write `"` (34) to the memory using this command. It's not too big of a problem, at least for now, since all of the [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges listed here don't have `"` in the output. --- Any further golfing is always welcome, especially for "Never gonna give you up" and the quine. Specifically, the above quine is very first nontrivial quine I ever made, so I strongly believe someone can come up with a shorter one. [Answer] # 3. Score: ~~2938~~ ~~2583~~ 2532 (-51) The new interpreter is [here](https://tio.run/##7Txpc9tGlh@3ir8CuRakTTFSrp3lRJmZzbXZnSSzdrLHKBouRIISYhLkgKBNjtdbIn1RtnPZcXwlPhIfieM4tuNDko9UEaQS5wME/QTij2RfX0DjokB7Ulu1taqyCXb3O/q916/f635gtanPVdSnf1bK1YqmC5I2W5W0mpyg3/OVUknO60pFrbGmSlXWJL2iOd@dnlrTeayrSr5SkAuSLiUSjwmTk5PCi4BDl1S9hr89lkgoalGYFIqliqQnRfgiphKqpLpN8AWaEghPrirNygJ0iaJozBsto23sMvYYO43dvfnernf0d9Tent4BY2/vfeNDo2MsGPuM/b2DvU96x3tHjQPGe8b7xge9i73LvaXeXUDB4dyIcQqPPPrY40/8rZhMbdiYHss8OT7x1NPPPPvc3/3q77O/fn7yhd/89nf/8OJLL7/y6j@@9k///PvX33jzD/@yafNbb//rv/37f/xx6p3pP@X@U5rJF@Ti7Jzy7pZSWa1U/6zV9PrWbY3mX7b/147/7t4MI9pv9Xf29xof9fcZB41DxsfGJ/2DxmHjaP9A/@P@0f7x/un@2f5545hx3DhhfNq/3L/Yv2581r/ZX@wv9e/2bxunjTPG58ZZ47zxhXGu1@rt7u3tvWdc6H1gXDG@NL4yLhpf9w71jvRO9I4Zl4xvjMvGt72ve9/2lnv3@u3@rn7HuNrfb1wzvjOuGzf7h4zF/nvGjf7h/jHjVP9E/0z/XP@CsWQsG7eNO/1v@1/3bxh3@7eM7/vL/Xv9O/aRfWGTMj8y95gHzUPmx@Zhs2N@Yh4xF8yj5jFzn3ncPGF@an5mnjRPmQfM0@YZ8wvzrHnOfN88b14wvzS/Mj/4G4QyiPOqecm8Zn5nXjdvmN@YN81b5mVz0VwyvzU/NJfN2@Yd8655z/x@9cDq/OrO1fbqrtXdq@@ZV1b3rO5d7awurL4fxukP1weLVwaL9wZLHw@W2z/cGCxeHSx@P1g6PFjeOVhsDxZP9k4PFj8fLM3/eHmw9Mlg6fRg6eJged9gEbpP9c4MFr8YLLV@/HawdGSwdGaw9PVgeX/3Qq/dO9m71H@/f6l3vbezd6r3Tf@D/je9G92L3WV7fsmeXw7jZaW1sndl38pHK4dWjtpXL698tnJ25dLKtR/P3j@00rl/ZOXg/dP3z68cu3/1/rWVcz@dvn/np/bKNz/t//Fc96vu5d7VH2@FIbUWrH3WYeu09bl1xPrCOmqdtE5ZX1ofWmesj62z1iHrnNWxjlsnrAvWfmu39YF13jpofWR9Zn1qta1P1o6tHbdurM2vta1bazutReue9f1ax7qy1rKur@2yvlvbvXbUWrZur@1dO7F2eO3U2h7rmnXVumvdWTto3TROGvfCeLLnT9udtt3ZYy907AV4Pm53OnZnwe4csDv77c5Xdudi95LduWB3vrT3He6etdt3u@e6X3Q/t9uX7PZX9vyV7vfdM3Zrr93q2PN37NaCPX/XXjxqz5/vXrHnP7fnP7PnP7XnT9rzx@z5o/bC2e7X3Vvd2/bCucH1vXbnZPe8ccRuXekuda91v7Nb1@3WDbt1027dsluLdmvJbi3brdt2CzDftVv3jFt2e95ut@x2227vtNu77PZuu73Hbu@12x27vWC399nt/Xb7gN1@z25jO6Pu7nW5XNGaQhkEUHJcXr4k1WrC66gtmxDgD5yGoNRyulSVkzW5VEyRZvSnyXpdU6FXwX4zTwakhbdgLLhFDhq681vigm9Gg73ws5pSiAv@Koz1QmvyrFLTZS0uhk10vBdLQf5zPbYIXkKDOfh8XdNkVc9tlUohSCSlJgtvVPTXytWSXIZxcuFlTYMNzIEvS1vknKqUpAIlgBHFw0FUiqWaxIpNuZrN5RRV0XM5inUDRlvj8KL2DFYf7G0lEEuSDnFGOLiq9dpcJJ5iRSM8C4pKHmpup5dQRqpWZbVACHEyrFaqFL2iFuQG8DM2wVHQtaYXI9UNhxhhwLAu93IjL1f1UMBxjrQsb3k42lME7gmhJKtJtzk1PSInww2Jo4rmmhrBgAgQUqFf7ts0RZdhCWuKOssD10KhmeoTnI1pclWjNhbkViSWuX1HSsyAlZQhsOLkw6MBFiKxQF8UGHAfDacwvxACOCvr0F12VgcxnXBxc0qe9vAchiNC@jwOsDA8xl1mZBkj37reKq4pf5EBHgLWNChPqsLzW1oIOTIMfXg7KAz68HagTQA6psanve1sTYw7zUqRcPEIZiNkpbuohA2EhXXtBeF0@Q5BzAwKy2hKgA1XmE6JXkeFfZGiSiUUqpOBosdJKVg5yEvJar2MEgmyzDDHKS/BrRgNMj14Snm6gFkFMenKxwvq8oHCju2isBFj2yiIO0TPQNib5SGgAJQIxymIiWAjLw8qLty57jJbV/gwwHFtIaLCXlKGvQnkiURP1LN9B9GSGDFBFJEFu0bUUgxtjaK1kbQ3XIvranOoVn16ZNJlThTDTGXHJqaDc41hYWwxTfk1FBzu6GrKy9yDKGodJcVVUGzlRCtmqFIiFcJkgT8zaNOEbRjRnl5/4cXcqHQ3vP5tVUOHHXrTjQ/kUmlYWICAp1zpTfu3eQc@Yo/ywzv71EjhArYMbif02gcZnuaU7DOUbXNKSaaR2AuTfr/jMsoiyfFU@AY0FTWHcmWrnNOU2TndL0tuvwPtT4T7x0fC/aOzuQYNjkP7xKSLaciiIzLg4IKCCKfiE4x3ziW5OGzKYw88ZUFSCzym54XxoVLghCCMcUSJMACzWtFHxE5SpNfQAJIZRXrFoLTZVNZjHgsXckFYk8nxtDCeGj7HBwns0QodNa7n1jaL7kk4iZLl9cLJBpgVCyeb3HODiy2hZ0ikSTGgD28HRdcMdDDcjWAQygg1g12NYCBKQCLa0bECCkJ94Wy1oqjIFRPX5GiJ2gGeTIS5N6P6mNPLIU@nSeqsnERjIyIVhzm2TkmYjCinYmzdscBDbfwX5D8O4z4KE@OjyWdiPEbWyQWWAU9G7HSIJ2tGDfCGQThkgn/vqIK9/zL@Nx0/qo8MekuKindKZ/rZdYNFiDxQLIUgU8I7kQEo/suAwEpSXk6KaTENPIwAMDUqwDQFgMCICGpIBjCFZkGi2QkUzvqiqWhnHVNbCH1SREoSwYhg6SedfRQJGdkutD/z5LMpzG8or/9ntROtGWcKI8ju/1fB6HJefwUE4peRMntJ06QmO9wtS9VkSSrPFCRByrpNAJgWpFQq7Uo95Tr0stTIaZVtEDyqs/ocoIIGgklW0wR/KhVyDOMmAQDtTQEIUFjEi@wLhqcgCPPSDQn4KtvYBiGOi94NCBNw438YmvAwV5UKzkT4yYAdI74lxC5hEpQxkRhiu2g4nR8GyAZyZJkc2OONr7ItG5Kjkv5J9pTR3q2DZoDHVPTipGMjTod4e@PNBZnW8y@ggxn8v/dItkHVxQVVo5604oS4WJJ0nfcTKRQqP3BOiz0Nx9P0FMftyBnucGy/eL7bGCXhDfDKst9Ax7BUODjj4XOl8XFonuiPncNSluHJdWNIdh0ZoMWedHS00BiSmTe8qTlOZGImzo0hmTM3HTeDbUTkmBFTjEw2ozKiIRJwKHPcrC8VTiiQqkszNd5ZpIKZexgtJ5sfkR7yvV5FFCrb1FBFNIfYVXO9wL8xLDGKSEccwAfN2eJYbXOIvJpeq20GrbZeHSaqsXVE5VpJM57NNmLZbHMUm22G2GwMmXAi4W22OdRmmxE2OyI9j83@7xz7sAoHcvSDbiX16PMf5srfqKgBCqzPt0@sd@Xr0A/c@vovn2Pe@vrBYovVf/AbS66@WROZ4pIPJlCuKjGDC0c84o0SDjrWqtUh@EmmMs6o1NSz2emABDE1lBbAqISnDGMdiQXRP4dSCiICdIMPPAS4p04ppnyHVkOQugRv0QN3KLte/UM8BUVUkMQN1dYvVPEUSuACoQKIQ9GbSZ4fyj41EzQMnK5WqiDm0V1/Ll9GWQaDTQvo@DjQiPynvzHhu6sjyykAipUXaJVKJdrGLWm31ElVwULK3Jkw9bcMTKlh14dgQ7VFx1EUwbxPKZKas4xTGJYKNxcmoliYcIFaOCIm1Vh4cKlZOB6miFh4nKKzcFy8yiLx0bGOFtlA3riwulhJ3yt1lSxbVs6HFDoDeZ3WzLGqaGJ6aaFSpZzR2ihk0ajCyqmUQtm@@wWlZ0CE1JEJL1bKZdgDgQ6jIhWoUVOskVTJ9wyMp0unVp/RNSmvjwQOQBS8XC/pSrXUHAkcgCh4QdkKK2MkYF2rywDG6FcK9VJlNOoVZ@7bpKrnsIOcS4w9NZ1mjxMoD3Oe0@4IgkGTwaXUvBMAO5yTapBja0ydqH4N9CmyHF3kPaarf07fU1m3dMAbfpFBrCaQ@0ZACFuQxBfqoFN@bnpFx4cjJKj0nXz4zkbI2A3eYwy2nlEfIcNOEngyqM291QFZ6M0qO1FCkSs61fKl5rpcjjqfQcg2TjqE0NAwoaB@tu0QUjzHqJcqHB@A4BHg7jWlzJimB0eUa88u5GMLZkS6IB9BGAQYi8FDqjLCdkJ24EcLRLDOfCz84jzwR0682WigWt1rzJJjZG7oMBPSlg9p40xbgqAsLTCnUahXS0reT4ruOJVq02/YrlaYrbhjQ1cSsRPsMVGVmfAkvmoN8ZuKmtewhZM4He9V@EiMrhn2nQ/m3Ub0FSUUbFryQyMbc5DNynp@TnI2MFAZkkqzBjIpKGpGkyGMmUixRQbdgWATPnht5@c0XHFAkStqta4z7J6YEffoMo5ayKBEWIUsi4VFN4DxoKH9MhhekqEciokNYtvpm9Rhe7ZTfBaXK1XAyNC7A1xgT3q4@Ckt1GtygXO15ByPxAjeENoXJeAhePrgrqvAHqaVFni0icDZP50Gxwe1sSIKtHRsGX6moW8YxzVYJyASDXhR5Yaew@ksZQbyd3EHd64OqHDyUJCnsgxu2pPDO/2sm8tsnOBpRMEA1Qi5BE8NgtCYq5hyZaJy3xfDi1kAW9hSrzpGUkbvVSgyWuPbibcTHxOzAjruwG9GkOBdfJy2kdcdaOOrtBG/xEDbXqJt5J0C2rgZNU5w7yqkKSljHvU85aVltOhwereDymqypJYYPXrLhB2gdjygVySQYcph4IfrCOwZZw6JHYlE0Y1LHZlshGFOOuTNsLjcCMJEb7LDpzSBTj5/8vhV7zA@o4oY5kxnLBabLIaN5jV8BMew13dHMhw1zGH4iVgMk6g1ml1/v4M@Gws9MxnUlA2JMHE8moomT@FxU1bgzyCS@AsKhVMh3P06FnebWZgQzQBebMEhnL4oi6gli//nN9XxVKQCKRy@uRb8m/F42KSej5wUxw5alxnnKiKSOlqUYcMcYpN/Ff2iCAzX6XIJZAye0OF9CE8vjCYAfLcUg5pvnEPuNw8nAje0eTADj4SPa3wVDSMhwVvqAS0xEokjpt8/nJjwJaYbYz@gsBAWcsAaxuKbkSy6Z2AUOY4AspC3oiIWwEyr0ENDklBam2KJg6brIfB//OstvBeEUD/yp0gKocujXg3BMRdDoliGIbCVh9IGyh7ia0OLpw2cbo5meDRFLbANIhlKvxYvbNgmDdmDvL0Oanv@/MOZyoZwr@yGkEfihRD04O3B/Av@7qkWCGXlVixWyCHecJfvqV3wkMKUCjGM0zk1CEBLD2Xajz6aeRf4Sk4hG2@QCqMGOmTAY6e54qkUiqYrblrqRNNTwICbmVKutkMjn/uRYJweFADq5ExTl8l1iJMR4h/FcCuY8hUVdiMwSTSUBftuvs0VtuABnrqWAHaa5nlwehO0aHL@EaGn7wRqUhhvFIvDEaNMxzMAt2@cFFym6Su7GwVccDeRiL7fYlLbSLJb/HMCUwjROm/34hcS3iY/RPISxoHvwJLi2@oWFUIhwhReHFm@GAs1U6NIeO4JMBtEw1y2TqaDT/M1PS2gLZ0qBP2wyCZ6qDonC7UyWCvMnp7tVYoCfV0aspf8HAyRdHpOhuWD8WVprZBSE2akEnoFvoBvx5O8EKeRUjBdYpmojBNv/9g48GU@IsCoFSpyTRV1EBrkthlBZLXazl06IkzttYorDsc5vnJo1QRNla@het5DHrNLMAFjPBLnK5vGI5O8@Fghgn@m4qOi787QwxguHHBbPHXovr5g0YOHFiw3xxlktsjNWjKkYp7MzFP3EvoeYOhMpsUohLg6hDuyCxTXBI5P0BB6O4B@wYc/idIrW2R8OsBO7T0lIPlKmRZAujqN0jVpdzFF6J6jjSmAUtnZFF82yDwW7h5ZsT7pDtWtKwUW2lLzDNaVcDNMeKtUopCTDobY8VEZepqHLDrlw4UaM0oNfIoCXgGCSlgLjhhyPjFgxgWyNtzy5hwqbx7zFd5GGMq6GhqiqZCXRJGo/TMIrxMPKXXybAuaLG0JVxR290AjEY4yMEWvdvG3kDtfR/jrL25yIh84lnW2rTRavqkhPDjopxDB6aQrVAQuZBEFPvrgVyY72w8/aPXSwQaWCHU8Plk9RuMiAp/y3vqhJnZp4jsWJz9lQwoayDGut7rB8S@c5yE7ERLBTMkTEoACMAbY0rxFDhSve7NI6QYGOvw4hU5coRtH0hveIPRMZARDyhtp6VuQF6WTyXo9FOzcCGkSxvjMBFooOnbA7TU27sdrYGga34/6T90xeMZTP4MI@TBR/sThv0gkBtgjJ/JJ7ifZMjiIVPKYSiqEFwBBc5lC0ORHVfDUphMRL3QS7vwODaFHxZqI6TERBwKoZSI7jUYqswo6hAkVBVeHhO@XgnyGiobdDYSuZ0nD5TkwJoeurFGKRYejaUZMzSMSBprcMEX59OXK/lfsMMmU7@W8MDsM28uYIQcdK10oWEMT2aCHDlt1Q@XmXCBQwWFVhdN3hmKhBScQdFZOSsG7GwJH3I3ckPN1HbkN8Duqjkv1dQCZrfHFU7hMlDRnqClzAQYFxZmVk@2Bly@yfRVmyQZlaHom1vXi2K/ElMBtCc7mHVqbwZGhOFgL50p47xns5Gbhf7GG@GayOVPAtFBUsB7pxbCsoZ/NUlAZoiqV5VyOxAu5sqSoORQ20BIE8iOOGi5tIc@Z32mzdRTm/QH3sB8vQtf/Yg02KTmH6m64u150OkniLgcdqirKlet6HbxhMwc5V6leU7ai6@1KndUEUDA8VKIkk@JYEQcrY2g28DQnl9DVlri5Cu6iiC7zUPKDhS/MyAK6@xaKWqUM7FEICRsdYmYomTwhky8XnAf0WtooJFGmlmdXjwSWJ@4VsJ9@nZCl9smRfRtSUWxukMBDF4owi7ioAxLCkOlFEigRAsR0OPxv1vVqXcfM0/fEIL1E37D96BVh81svvbxp0yiTqWqVWU0qi8M5gqetgFWFT7z6NogULTNzjwHhDwRdYwbILwjEK3ebr6BZVPHLOHQAZYlcKCNq2gwsX6kmeCF9SxV1knoKSpPWnFOkYCOhKxwfVYTQZm4jEeIg6I8gvOkcNGA3DOIvQiRGHR1uwubBUET7v8TP8DdW/3ms9PNY/ufHH9309DObCpuefm6TxD3@Dw "Python 3 – Try It Online"). Mainly for the purposes of golfing the quine and making output easier, I've added the ability to duplicate the stack/deque and also to output the entire model in rendered text form instead of as integers. ## Solutions ### 1. ["Hello, World!"](https://codegolf.stackexchange.com/questions/55422/hello-world) - 17 bytes (-3) ``` #"Hello, World!"a ``` ### 5. [Sing Happy Birthday to your favourite programming language](https://codegolf.stackexchange.com/questions/39752/sing-happy-birthday-to-your-favourite-programming-language) - 95 bytes (-3) ``` #"Happy Birthday to You Happy Birthday to You Happy Birthday Dear Bugle Happy Birthday to You"a ``` ### 6. [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) - 1884 bytes (-3) ``` #"We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it And if you ask me how I'm feeling Don't tell me you're too blind to see Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you (Ooh, give you up) (Ooh, give you up) (Ooh) Never gonna give, never gonna give (Give you up) (Ooh) Never gonna give, never gonna give (Give you up) We've know each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you"a ``` ### 16. [Bake a slice of Pi](https://codegolf.stackexchange.com/questions/93615/bake-a-slice-of-pi) - 149 bytes (-3) ``` #"()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\|"a ``` ### 20. [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good) - 23 bytes (-39) ``` $"R34RdR36Ra"R34RdR36Ra ``` --- ## Added Language Features * `a` + All: Print the entire model as text, e.g. `#"Hello, World!"a` prints `Hello, World!` * `d` + Stack/Deque: Push the stack on top of itself. [Answer] # 1. Score: 9638 The base interpreter can be found [here](https://github.com/cairdcoinheringaahing/bugle/blob/master/bugle.py), and the submissions [here](https://github.com/cairdcoinheringaahing/bugle/tree/master/submissions). It's rather long, so I've included it on GitHub, rather than take up most of the post. ## Solutions All of these solutions are the Unicode programs, run with the `-u` command line flag, but the scores are counted as though encoded with Bugle's code page. ### 1. ["Hello, World!"](https://codegolf.stackexchange.com/questions/55422/hello-world) - 48 bytes ``` $72o101o108o108o111o44o32o87o111o114o108o100o33o ``` Simply push then output the character code of each character in the string. ### 2. [1, 2, Fizz, 4, Buzz](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz) - 1396 bytes ``` $49o10o50o10o70o105o122o122o10o52o10o66o117o122o122o10o70o105o122o122o10o55o10o56o10o70o105o122o122o10o66o117o122o122o10o49o49o10o70o105o122o122o10o49o51o10o49o52o10o70o105o122o122o66o117o122o122o10o49o54o10o49o55o10o70o105o122o122o10o49o57o10o66o117o122o122o10o70o105o122o122o10o50o50o10o50o51o10o70o105o122o122o10o66o117o122o122o10o50o54o10o70o105o122o122o10o50o56o10o50o57o10o70o105o122o122o66o117o122o122o10o51o49o10o51o50o10o70o105o122o122o10o51o52o10o66o117o122o122o10o70o105o122o122o10o51o55o10o51o56o10o70o105o122o122o10o66o117o122o122o10o52o49o10o70o105o122o122o10o52o51o10o52o52o10o70o105o122o122o66o117o122o122o10o52o54o10o52o55o10o70o105o122o122o10o52o57o10o66o117o122o122o10o70o105o122o122o10o53o50o10o53o51o10o70o105o122o122o10o66o117o122o122o10o53o54o10o70o105o122o122o10o53o56o10o53o57o10o70o105o122o122o66o117o122o122o10o54o49o10o54o50o10o70o105o122o122o10o54o52o10o66o117o122o122o10o70o105o122o122o10o54o55o10o54o56o10o70o105o122o122o10o66o117o122o122o10o55o49o10o70o105o122o122o10o55o51o10o55o52o10o70o105o122o122o66o117o122o122o10o55o54o10o55o55o10o70o105o122o122o10o55o57o10o66o117o122o122o10o70o105o122o122o10o56o50o10o56o51o10o70o105o122o122o10o66o117o122o122o10o56o54o10o70o105o122o122o10o56o56o10o56o57o10o70o105o122o122o66o117o122o122o10o57o49o10o57o50o10o70o105o122o122o10o57o52o10o66o117o122o122o10o70o105o122o122o10o57o55o10o57o56o10o70o105o122o122o10o66o117o122o122o ``` Same technique as the Hello, World! example ### 3. [Produce the number 2014 without any numbers in your source code](https://codegolf.stackexchange.com/questions/17005/produce-the-number-2014-without-any-numbers-in-your-source-code) - 13 bytes ``` #++O--O+O+++O ``` `#` uses the tape, `+` increments the cell, `O` outputs as an integer and `-` decrements ### 4. [Obfuscated Hello World](https://codegolf.stackexchange.com/questions/307/obfuscated-hello-world) - 172 bytes ``` #+++++++++[>++++++++<-]>o<++++[>+++++++<-]>+o+++++++oo+++o>++++[>+++++++++++<-]>o------------o[-]++++++++[>+++++++++++<-]>-o<<<o+++o------o--------o[-]+++[>+++++++++++<-]>o ``` Uses its inherent similarity to brainfuck. Meets rules #1 and #3 ### 5. [Sing Happy Birthday to your favourite programming language](https://codegolf.stackexchange.com/questions/39752/sing-happy-birthday-to-your-favourite-programming-language) - 328 bytes ``` $72o97o112o112o121o32o66o105o114o116o104o100o97o121o32o116o111o32o89o111o117o10o72o97o112o112o121o32o66o105o114o116o104o100o97o121o32o116o111o32o89o111o117o10o72o97o112o112o121o32o66o105o114o116o104o100o97o121o32o68o101o97o114o32o66o117o103o108o101o10o72o97o112o112o121o32o66o105o114o116o104o100o97o121o32o116o111o32o89o111o117o ``` All the [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges have this kind of structure, at the moment. ### 6. [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) - 6893 bytes ``` $87o101o39o114o101o32o110o111o32o115o116o114o97o110o103o101o114o115o32o116o111o32o108o111o118o101o10o89o111o117o32o107o110o111o119o32o116o104o101o32o114o117o108o101o115o32o97o110o100o32o115o111o32o100o111o32o73o10o65o32o102o117o108o108o32o99o111o109o109o105o116o109o101o110o116o39o115o32o119o104o97o116o32o73o39o109o32o116o104o105o110o107o105o110o103o32o111o102o10o89o111o117o32o119o111o117o108o100o110o39o116o32o103o101o116o32o116o104o105o115o32o102o114o111o109o32o97o110o121o32o111o116o104o101o114o32o103o117o121o10o73o32o106o117o115o116o32o119o97o110o110o97o32o116o101o108o108o32o121o111o117o32o104o111o119o32o73o39o109o32o102o101o101o108o105o110o103o10o71o111o116o116o97o32o109o97o107o101o32o121o111o117o32o117o110o100o101o114o115o116o97o110o100o10o32o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o32o121o111o117o32o117o112o10o78o101o118o101o114o32o103o111o110o110o97o32o108o101o116o32o121o111o117o32o100o111o119o110o10o78o101o118o101o114o32o103o111o110o110o97o32o114o117o110o32o97o114o111o117o110o100o32o97o110o100o32o100o101o115o101o114o116o32o121o111o117o10o78o101o118o101o114o32o103o111o110o110o97o32o109o97o107o101o32o121o111o117o32o99o114o121o10o78o101o118o101o114o32o103o111o110o110o97o32o115o97o121o32o103o111o111o100o98o121o101o10o78o101o118o101o114o32o103o111o110o110o97o32o116o101o108o108o32o97o32o108o105o101o32o97o110o100o32o104o117o114o116o32o121o111o117o10o32o10o87o101o39o118o101o32o107o110o111o119o110o32o101o97o99o104o32o111o116o104o101o114o32o102o111o114o32o115o111o32o108o111o110o103o10o89o111o117o114o32o104o101o97o114o116o39o115o32o98o101o101o110o32o97o99o104o105o110o103o32o98o117o116o10o89o111o117o39o114o101o32o116o111o111o32o115o104o121o32o116o111o32o115o97o121o32o105o116o10o73o110o115o105o100o101o32o119o101o32o98o111o116o104o32o107o110o111o119o32o119o104o97o116o39o115o32o98o101o101o110o32o103o111o105o110o103o32o111o110o10o87o101o32o107o110o111o119o32o116o104o101o32o103o97o109o101o32o97o110o100o32o119o101o39o114o101o32o103o111o110o110o97o32o112o108o97o121o32o105o116o10o65o110o100o32o105o102o32o121o111o117o32o97o115o107o32o109o101o32o104o111o119o32o73o39o109o32o102o101o101o108o105o110o103o10o68o111o110o39o116o32o116o101o108o108o32o109o101o32o121o111o117o39o114o101o32o116o111o111o32o98o108o105o110o100o32o116o111o32o115o101o101o10o32o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o32o121o111o117o32o117o112o10o78o101o118o101o114o32o103o111o110o110o97o32o108o101o116o32o121o111o117o32o100o111o119o110o10o78o101o118o101o114o32o103o111o110o110o97o32o114o117o110o32o97o114o111o117o110o100o32o97o110o100o32o100o101o115o101o114o116o32o121o111o117o10o78o101o118o101o114o32o103o111o110o110o97o32o109o97o107o101o32o121o111o117o32o99o114o121o10o78o101o118o101o114o32o103o111o110o110o97o32o115o97o121o32o103o111o111o100o98o121o101o10o78o101o118o101o114o32o103o111o110o110o97o32o116o101o108o108o32o97o32o108o105o101o32o97o110o100o32o104o117o114o116o32o121o111o117o10o32o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o32o121o111o117o32o117o112o10o78o101o118o101o114o32o103o111o110o110o97o32o108o101o116o32o121o111o117o32o100o111o119o110o10o78o101o118o101o114o32o103o111o110o110o97o32o114o117o110o32o97o114o111o117o110o100o32o97o110o100o32o100o101o115o101o114o116o32o121o111o117o10o78o101o118o101o114o32o103o111o110o110o97o32o109o97o107o101o32o121o111o117o32o99o114o121o10o78o101o118o101o114o32o103o111o110o110o97o32o115o97o121o32o103o111o111o100o98o121o101o10o78o101o118o101o114o32o103o111o110o110o97o32o116o101o108o108o32o97o32o108o105o101o32o97o110o100o32o104o117o114o116o32o121o111o117o10o32o10o40o79o111o104o44o32o103o105o118o101o32o121o111o117o32o117o112o41o10o40o79o111o104o44o32o103o105o118o101o32o121o111o117o32o117o112o41o10o40o79o111o104o41o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o44o32o110o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o10o40o71o105o118o101o32o121o111o117o32o117o112o41o10o40o79o111o104o41o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o44o32o110o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o10o40o71o105o118o101o32o121o111o117o32o117o112o41o10o32o10o87o101o39o118o101o32o107o110o111o119o32o101o97o99o104o32o111o116o104o101o114o32o102o111o114o32o115o111o32o108o111o110o103o10o89o111o117o114o32o104o101o97o114o116o39o115o32o98o101o101o110o32o97o99o104o105o110o103o32o98o117o116o10o89o111o117o39o114o101o32o116o111o111o32o115o104o121o32o116o111o32o115o97o121o32o105o116o10o73o110o115o105o100o101o32o119o101o32o98o111o116o104o32o107o110o111o119o32o119o104o97o116o39o115o32o98o101o101o110o32o103o111o105o110o103o32o111o110o10o87o101o32o107o110o111o119o32o116o104o101o32o103o97o109o101o32o97o110o100o32o119o101o39o114o101o32o103o111o110o110o97o32o112o108o97o121o32o105o116o10o32o10o73o32o106o117o115o116o32o119o97o110o110o97o32o116o101o108o108o32o121o111o117o32o104o111o119o32o73o39o109o32o102o101o101o108o105o110o103o10o71o111o116o116o97o32o109o97o107o101o32o121o111o117o32o117o110o100o101o114o115o116o97o110o100o10o32o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o32o121o111o117o32o117o112o10o78o101o118o101o114o32o103o111o110o110o97o32o108o101o116o32o121o111o117o32o100o111o119o110o10o78o101o118o101o114o32o103o111o110o110o97o32o114o117o110o32o97o114o111o117o110o100o32o97o110o100o32o100o101o115o101o114o116o32o121o111o117o10o78o101o118o101o114o32o103o111o110o110o97o32o109o97o107o101o32o121o111o117o32o99o114o121o10o78o101o118o101o114o32o103o111o110o110o97o32o115o97o121o32o103o111o111o100o98o121o101o10o78o101o118o101o114o32o103o111o110o110o97o32o116o101o108o108o32o97o32o108o105o101o32o97o110o100o32o104o117o114o116o32o121o111o117o10o32o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o32o121o111o117o32o117o112o10o78o101o118o101o114o32o103o111o110o110o97o32o108o101o116o32o121o111o117o32o100o111o119o110o10o78o101o118o101o114o32o103o111o110o110o97o32o114o117o110o32o97o114o111o117o110o100o32o97o110o100o32o100o101o115o101o114o116o32o121o111o117o10o78o101o118o101o114o32o103o111o110o110o97o32o109o97o107o101o32o121o111o117o32o99o114o121o10o78o101o118o101o114o32o103o111o110o110o97o32o115o97o121o32o103o111o111o100o98o121o101o10o78o101o118o101o114o32o103o111o110o110o97o32o116o101o108o108o32o97o32o108o105o101o32o97o110o100o32o104o117o114o116o32o121o111o117o10o32o10o78o101o118o101o114o32o103o111o110o110o97o32o103o105o118o101o32o121o111o117o32o117o112o10o78o101o118o101o114o32o103o111o110o110o97o32o108o101o116o32o121o111o117o32o100o111o119o110o10o78o101o118o101o114o32o103o111o110o110o97o32o114o117o110o32o97o114o111o117o110o100o32o97o110o100o32o100o101o115o101o114o116o32o121o111o117o10o78o101o118o101o114o32o103o111o110o110o97o32o109o97o107o101o32o121o111o117o32o99o114o121o10o78o101o118o101o114o32o103o111o110o110o97o32o115o97o121o32o103o111o111o100o98o121o101o10o78o101o118o101o114o32o103o111o110o110o97o32o116o101o108o108o32o97o32o108o105o101o32o97o110o100o32o104o117o114o116o32o121o111o117o ``` ### 7. [Output the sign](https://codegolf.stackexchange.com/questions/103822/output-the-sign) - 18 bytes ``` $?:Zs0=0s-s:1s-++O ``` Checks if the input is greater than zero, less than zero (changed to yield `-1` instead of `1`) and equal to zero, before taking their sum. ### 8. [Collatz Conjecture (OEIS A006577)](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture-oeis-a006577) - 36 bytes ``` #$?:1-[:2s%{3×1+}2s÷]:1s-₀+₁]₀O ``` This performs the looping on the stack, but switches over to the tape to increment the count each iteration. ### 9. [An Array of Challenges #1: Alternating Arrays](https://codegolf.stackexchange.com/questions/103571/an-array-of-challenges-1-alternating-arrays) - 35 bytes ``` #?>?>+>?[[<+<<->>>-]+<[-<<]>[>]?]<O ``` This is a slight modification of [Mitch Schwartz](https://codegolf.stackexchange.com/a/103582/66833)'s answer to the existing challenge, go upvote that! ### 10. [Am I an insignificant array?](https://codegolf.stackexchange.com/questions/143278/am-i-an-insignificant-array) - 46 bytes ``` $1 0-?…1[s:sr-:Z1s-2×1+×1s-Z1-L2s-×]1+Z1-O ``` All credit goes to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for [making](https://chat.stackexchange.com/transcript/message/43814604#43814604) this ### 11. [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime) - 31 bytes ``` $?:1s-:[:1s-:];L1s[×L2s-]:×%O ``` Uses Wilson's Theorem and calculates `(n-1)!² % n` ### 12. [I'm a palindrome. Are you?](https://codegolf.stackexchange.com/questions/110582/im-a-palindrome-are-you) - 13 bytes ``` $?:R=:O:=R:?$ ``` The first half of the program, up to `O`, sets the stack up as `[x, x]` where `x` is either `True` or `False`. `O` pops the top value and outputs it. The rest of the program just makes sure that no errors are produced. Luckily, when `?` encounters the end of the file, it just pushes `''` (the empty string). ### 13. [Sum the numbers on standard in](https://codegolf.stackexchange.com/questions/113674/sum-the-numbers-on-standard-in) - 19 bytes ``` $?:[?:];L0s[+L1s-]O ``` This can be split into two parts: `?:[?:];` and `L0s[+L1s-]`. The first part collects all input to the stack. The second part pushes the sum of the top two elements, while the length is greater than 1. ### 14. [Find the Factorial](https://codegolf.stackexchange.com/questions/607/find-the-factorial) - 25 bytes ``` $?:[:1s-:];L1s-Z[×L1s-]O ``` This has a similar structure to the sum program, but instead of pushing ltiple inputs, the `[:1s-:];` pushes the range from `1 .. n` to the stack, and `[×L1s-]` takes the product. ### 15. [Shortest code to produce infinite output](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output) - 5 bytes ``` #+[O] ``` Use a while loop, with the `1` continually under the pointer. Outputs `1` forever. ### 16. [Bake a slice of Pi](https://codegolf.stackexchange.com/questions/93615/bake-a-slice-of-pi) - 439 bytes ``` $40o41o40o41o40o41o40o41o40o41o40o41o10o124o92o51o46o49o52o49o53o57o50o54o124o10o124o58o92o53o51o53o56o57o55o57o51o124o10o92o58o58o92o50o51o56o52o54o50o54o124o10o32o92o58o58o92o52o51o51o56o51o50o124o10o32o32o92o58o58o92o55o57o53o48o50o124o10o32o32o32o92o58o58o92o56o56o52o49o124o10o32o32o32o32o92o58o58o92o57o55o49o124o10o32o32o32o32o32o92o58o58o92o54o57o124o10o32o32o32o32o32o32o92o58o58o92o51o124o10o32o32o32o32o32o32o32o92o95o95o92o124o ``` ### 17. [Find the smallest number that doesn't divide N](https://codegolf.stackexchange.com/questions/105412/find-the-smallest-number-that-doesnt-divide-n) ``` $?:1:[:rs%0=s1+srr:Rs]1s-O ``` This uses trial division, terminating when the result of the modulo does not equal `0`. ### 18. [Is this even or odd?](https://codegolf.stackexchange.com/questions/113448/is-this-even-or-odd) - 5 bytes ``` $2?%O ``` Simple modulo by 2 ### 19. [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code) - 16 bytes ``` $16:[32+:o33s-:] ``` Outputs the first 16 printable ASCII characters in reverse: `0/.-,+*)('&%$#"!` ### 20. [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good) ``` $1[93, 76, 111, 91, 49, 59, 104, 48, 79, 49, 111, 54, 51, 0] 36o1O0h;1[oL] ``` Credit goes to [user202729](https://codegolf.stackexchange.com/users/69850/user202729) for [making this](https://chat.stackexchange.com/transcript/240?m=43915697#43915697) --- ## Language specification ### Calling `bugle.py` currently takes a series of flags, then the file name / code to be executed. As of yet, it has 4 command line flags: * `-f`/`--file` specifies that code is to be read from a file * `-c`/`--cmd`/`--cmdline` specifies that code is supplied via the command line. `-c` and `-f` cannot be used in the same call * `-u`/`--unicode` tells the interpreter to read the code with the Unicode encoding. The default is to use Bugle's encoding below * `-l`/`--length` outputs the length of the file, in bytes, to STDERR after execution The following call was used to test the above submissions ``` $ python bugle.py -f -u [file] ``` ### Code page Bugle uses 512 characters in its code page. **The `0xFF` character is not to be used for a command**, as its used to indicate that the next hex value in to index into the second half of the code page. The characters used are: ``` ÀÁÂÄÆÃÅĀĄ\t\nĆČÇĎÐ ÈÉÊËĒĖĚĘÌÍÎÏĪĮĹĽ !"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ `abcdefghijklmno pqrstuvwxyz{|}~¶ ŁŃŇÑŊÒÓÔÖŒÕØŌŔŘŚ ŠŤŦÙÚÛÜŮŪŴÝŶŸŹŽŻ àáâäæãåāąćčçďðèé êëēėěęìíîïīįĺľłń ňñŋòóôöœøōõŕřßśš ťŧùúûüůūŵýŷÿźžż◊ ΑΆΒΓΔΕΈΖΗΉΘΙΊΚΛΜ ΝΞΟΌΠΡΣΤΥΎΦΧΨΩΏ αάβγδεέζηήθιίΐκλ μνξοόπσςτυύΰφχψω ώǴḰḾṔẂǵḱḿṕẃḂḞĠḢṀ ȮṖṠṪẊḃḟġḣṁȯṗṡṫẋ§ ĂĞĬŎŬĴăğĭŏŭĵªº‹› ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒ ɠɦƙɱɲƥʠɼʂƭʋȥ©®ıȷ ЉЊЕРТЗУИОПШАСДФГ ХЈКЛЧЋЅЏЦВБНМЂЖљ њертзуиопшасдфгх јклчћѕџцвбнмђжÞþ †∂∆≈≠√∈∉∌∋∩∪¬∧∨⊕ ¤₽¥£¢€₩‰¿¡⁇⁈‼⁉‽⸘ …°•”“„’‘≤«·»≥ᴇ∞¦ ×⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ ÷₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ ``` Or see it in [table format](https://github.com/cairdcoinheringaahing/bugle/wiki/Code-Page). Note that `\t` and `\n` represent tab and newline respectively. Also take note that the 16th line ends with an unprintable character: ``, and may not be displayed on all browsers. ### Memory The interpreter currently has 5 memory models built in to it. Each memory model requires a character to tell the interpreter to begin using that model: * Stack (`$`): a standard stack, which supports values being pushed, popped etc. * Infinite tape (`#`): A tape, à la brainfuck, which initially is only `0`s. * Infinite grid (`G`): A 2d grid, infinite in both directions, containing only `0`s * Deque (`D`): A [deque](https://en.wikipedia.org/wiki/Double-ended_queue), as implemented by the [`collections`](https://docs.python.org/3.5/library/collections.html#collections.deque) module. * Register (`S`): A single value, which can be used to store *one* value. The grid also has a single value saved in its pointer that can be written to, or write to cells. In addition, tape and grid sizes and wrapping behaviour can be modified, by using a different invoke command. These different commands take a given number of values from the current memory model as customisation parameters: * Tape (`À`): Takes two values - size (`int`) and wrapping (`bool`) * Tape (`Á`): Takes one value - size (`int`). Wraps at end of the tape * Tape (`Â`): Takes one value - size (`int`). Doesn't wrap at the end * Grid (`Ǵ`): Takes 4 values - x size (`int`), y size (`int`), x wrap (`bool`) and y wrap (`bool`) The memory type being used can change during a program by the use of `₀₁₂₃₄₅₆₇₈₉`, which access the 0-indexed `n`th used memory type (`₀` is the first, `₁` is the second etc.), but, currently, values cannot be swapped between different memory types. ### Branching So far Bugle has two branching commands, both terminated with a `]` character: * While (`[`): brainfuck-style while loops. These pop a value from the stack/deque if being used, or access the cell under the pointer in tape/grid. Example: `#?[-O]` counts from the input down to `0` * If/else (`{` and `}`). Single execution while loops. If the value popped is false, then the if clause is skipped, going to the else clause, separated by `}`. They behave the same way as while loops regarding memory access. Example: `{0}1]` is a logical NOT gate ### Builtin functions Runs of digits are interpreted as integers, and are just pushed/written to the current memory model as is. Obviously, I've equipped Bugle with some basic builtin functions, as few as I could, to allow others to add more as the chain progresses. The base commands are as follows: * `+` + Stack/Deque: Add the top two values + Tape/Grid: Increment the current cell * `-` + Stack/Deque: Subtract the top two values + Tape/Grid: Decrement the current cell * `%` + Stack/Deque: Modulo the top two values * `:` + Stack/Deque: Duplicate the top value * `;` + Stack/Deque: Pop the top value + Tape/Grid: Zero the current cell * `<` + Tape/Grid: Move left one cell * `=` + Stack: Are the top two values equal? + Grid: Move down one cell * `>` + Tape/Grid: Move right one cell * `?` + Stack/Deque: Evaluate a line of input + Tape/Grid: Take a character of input * `L` + Stack/Deque: Push the length of the stack/deque * `O` + All: Output the current value * `R` + Stack: Reverse the top element if possible, else reverse the stack * `Z` + Stack: Top element is positive? * `^` + Grid: Move up one cell * `h` + All: Print the full memory model * `o` + All: Print the current value as a character * `r` + Stack: Rotate the top 3 values + Deque: Rotate the deque `n` times, where `n` is the top value * `s` + Stack/Deque: Swap the top two values * `…` + Stack: Splat the top value * `×` + Stack: Multiply the top two values + Grid: Write the pointer value to the current cell * `÷` + Stack: Divide the top two values + Grid: Write the current cell to the pointer value ]
[Question] [ ## Background In France, and probably in the rest of the European Union, any food available for sale [must](https://www.legifrance.gouv.fr/affichCodeArticle.do?idArticle=LEGIARTI000006292795&cidTexte=LEGITEXT000006069565&dateTexte=20110531) list the ingredients that compose it on its packaging, in **weight percentage descending order**. However, the **exact percentage** doesn't have to be indicated, [unless](https://www.legifrance.gouv.fr/affichCodeArticle.do?idArticle=LEGIARTI000006292806&cidTexte=LEGITEXT000006069565&dateTexte=20110531) the ingredient is highlighted by the text or an image on the covering. For example, my basil tomato sauce, showing only some big red tomatoes and beautiful basil leaves on its packaging, has the following indications: > > *Ingredients:* Tomatoes 80%, onions in pieces, basil 1.4%, sea salt, mashed garlic, raw cane sugar, extra virgin olive oil, black pepper. > > > It sounds savoury, but… **how much onions will I eat**, exactly? ## Challenge Given a list of weight percentages in descending order, eventually incomplete, output a **complete** list of the **minimal** and **maximal** weight percentages that can possibly be found in the recipe. * You can write either a function, or a full program. * The *input* can be in any reasonable form (array of numbers or list of strings, for instance). Fractional values should be supported at least to one decimal place. A missing weight percentage can be represented in any consistent and unambiguous way (`0`, `'?'` or `null`, for instance). You can assume that the input will always be associated to a valid recipe (`[70]` and `[∅, ∅, 50]` are invalid, for instance). * The *output* can be in any reasonable form (one array for both of the minimal and maximal weight percentages, or a single list of doublets, for instance). The minimal and maximal percentages can be in any order (`[min, max]` and `[max, min]` are both acceptable). Exact weight percentages don't need to be processed differently than other percentages and may be represented by equal minimal and maximal values. Standard rules for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply: while you're typing your code, my pasta dish is cooling down, so the shortest submission wins. ## Examples Since this problem is harder than it may look at first glance, here is a step-by-step resolution of a few cases. ### `[40, ∅, ∅]` Let's call respectively `x` and `y` the two missing percentages. * Because it comes after the first ingredient at 40%, `x` can't be higher than 40 % itself. `[40, [?, 40], [?, ?]]` * The sum of the two missing percentages is always 60%. Consequently : + If `x` takes its *maximal* value, then `y` takes its *minimal* value, which is therefore 60% - 40% = 20%. `[40, [?, 40], [20, ?]]` + If `x` takes its *minimal* value, then `y` takes its *maximal* value. But `x` can't be lower than `y`, so in this case, `x` = `y` = 60% / 2 = 30%. `[40, [30, 40], [20, 30]]` ### `[70, ∅, ∅, 5, ∅]` Let's call respectively `x`, `y` and `z` the three missing percentages. * The minimal and maximal percentages for `z` are necessarily between 0% and 5%. Let's assume `z` = 0% for a moment. The sum of the two missing percentages is always 25%. Consequently : `[70, [?, ?], [?, ?], 5, [0, 5]]` + If `y` takes its *minimal* value, 5%, then `x` takes its *maximal* value, which is therefore 25% - 5% = 20%. `[70, [?, 20], [5, ?], 5, [0, 5]]` + If `y` takes its *maximal* value, then `x` takes its *minimal* value. But `x` can't be lower than `y`, so in this case, `x` = `y` = 25% / 2 = 12.5%. `[70, [12.5, 20], [5, 12.5], 5, [0, 5]]` * Let's verify that everything is fine if we assume now that `z` = 5%. The sum of the two missing percentages is always 20%. Consequently : + If `y` takes its *minimal* value, 5%, then `x` takes its *maximal* value, which is therefore 20% - 5% = 15%. This case is already included in the previously calculated ranges. + If `y` takes its *maximal* value, then `x` takes its *minimal* value. But `x` can't be lower than `y`, so in this case, `x` = `y` = 20% / 2 = 10%. This case is already included in the previously calculated range for `y`, but not for `x`. `[70, [10, 20], [5, 12.5], 5, [0, 5]]` ## Test cases ``` Input: [∅] Output: [100] Input: [70, 30] Output: [70, 30] Input: [70, ∅, ∅] Output: [70, [15, 30], [0, 15]] Input: [40, ∅, ∅] Output: [40, [30, 40], [20, 30]] Input: [∅, ∅, 10] Output: [[45, 80], [10, 45], 10] Input: [70, ∅, ∅, ∅] Output: [70, [10, 30], [0, 15], [0, 10]] Input: [70, ∅, ∅, 5, ∅] Output: [70, [10, 20], [5, 12.5], 5, [0, 5]] Input: [30, ∅, ∅, ∅, 10, ∅, ∅, 5, ∅, ∅] Output: [30, [10, 25], [10, 17.5], [10, 15], 10, [5, 10], [5, 10], 5, [0, 5], [0, 5]] ``` [Answer] # JavaScript (ES6), 252 bytes Expects `0` for missing percentages. Returns a pair of minimum and maximum values for all entries. ``` a=>(g=a=>(h=(M,I,J=I^1)=>a.some((x,i)=>a.map((y,j)=>s-=j-i?M(j,i)-i?y[I]:M(w=y[I],z=x[J])-z||w==z?w:++k&&z:y[J],s=100,k=1,X=x)&&(I?-s:s)<0)?X[J]=M(X[I],X[J]+s/k):0)(Math.max,0)+h(Math.min,1)?g(a):a)(a.map((n,i)=>[n?p=n:a.find(n=>i--<0&&n)||0,p],p=100)) ``` [Try it online!](https://tio.run/##jZJdj6IwFIbv51dwRdpYsAWJGzKVi7lyNtybEDbpakVwLMQy40f8725bUXRVZghpzoGe5317egr2xeR0nVe1I8oZP87pkdERyKheFxTEaIze6fgPgXTEXFmuOABblJtsxSoAdqhQiXRo4eRRDAr1TwW7ZJyGMdhQHaA93SbvKXT2h8OG0n20CXu9pW3vw536jCQlGKMlJWhCt9C2wThyZCjhK4bRRG2gMZhoio57sr@EIYYgZvVCGdgiDHuLJssFIjDKAIMhg6DxJ4zZREQVFSFz57mYAUFHueO8YtsW8HDAqEpRpU1AeOz3rRXLhVVzWVtTJrl8mZZClh/c/SgzMAcJTiG0Oh/FSBQt/b9yiJHld5brymbXo2L9Pi8/FyckMAQVqYwE6R1r8COW3pX4ahkYlnfydQc7scg3sGSgTP0yIKKRQWpqnp3yubn2lPj2lE3wwGELDZ5wb6CegaqtxHM1NjiRH/TRb91q5WuVRkiD/Qs4OB@fDN02PrWikbxo42vl1sGLIpb1gq@vJtSSn1mmMj6z/u6s3/xLze/b@jMvpOTi8XV13b65Ls94OLc3OAe@7/p@E3sdk9XdajNZWmFwGQhv@E2vjeB1o@8ELr7NcOmg7fpNf1uR4z8 "JavaScript (Node.js) – Try It Online") ## How? ### Initialization We first replace each value in the input array **a[ ]** with the largest possible range. ``` a.map((n, i) => // for each value n at position i in a[]: [ // generate a [min, max] array: n ? // if n is not 0: p = n // use n as the minimum and save it in p : // else: a.find(n => // find the first value n i-- < 0 && // which is beyond the current value n // and is not equal to 0 ) || 0, // or use 0 as a default value p // use p as the maximum ], // end of array declaration p = 100 // start with p = 100 ) // end of map() ``` Examples: ``` [ 0 ] --> [ [ 0, 100 ] ] [ 30, 0, 5, 0 ] --> [ [ 30, 30 ], [ 5, 30 ], [ 5, 5 ], [ 0, 5 ] ] ``` ### Main function The main function is **h()**. It looks for the first entry that appears to be inconsistent when we try to either minimize or maximize it. If it finds one, it updates it to a value which is at least temporarily acceptable, given the other ranges. It takes as input either **M = Math.max** / **I = 0** or **M = Math.min** / **I = 1** and defines **J** as **I XOR 1**. Because **h()** was written to support both the minimizing and maximizing passes, the code is a bit tricky to comment. That's why we will focus on the maximizing pass only, for which we have **M = Math.max**, **I = 0** and **J = 1**. With these parameters, the code reads as follows: ``` a.some((x, i) => // for each range x at position i in a[] (tested range): a.map((y, j) => // for each range y at position j in a[] (reference range): s -= // update s: j - i ? // if i is not equal to j: Math.max(j, i) - i ? // if j > i: y[0] // the reference range is beyond the tested range // so we just use the minimum value of the y range : // else: Math.max( // take the maximum of: w = y[0], // w = minimum value of the y range z = x[1] // z = maximum value of the x range ) - z || // if it's not equal to z w == z ? // or they are equal (i.e. if w <= z): w // use w : // else: ++k && z // increment the counter k and use z : // else: y[1], // use the maximum value of the y range s = 100, // start with s = 100 k = 1, // start with k = 1 X = x // save the range x in X ) && // end of map() (0 ? -s : s) < 0 // abort if s < 0 (i.e. if we've subtracted more than 100) ) ? // end of some(); if truthy: X[1] = Math.max( // update the maximum value of the faulty range to: X[0], // either the minimum value X[1] + s / k // or the maximum value, less the correction ) // whichever is greater : // else: 0 // do nothing ``` ### Recursion The recursive function **g()** keeps calling **h()** until neither the minimizing or the maximizing pass leads to a new correction, and eventually returns the final result. ``` g = a => h(Math.max, 0) + h(Math.min, 1) ? g(a) : a ``` ]
[Question] [ **The Challenge** Given an integer input `x` where `1 <= x <= 255`, return the results of powers of two that when summed give `x`. **Examples** Given the input: ``` 86 ``` Your program should output: ``` 64 16 4 2 ``` Input: ``` 240 ``` Output: ``` 128 64 32 16 ``` Input: ``` 1 ``` Output: ``` 1 ``` Input: ``` 64 ``` Output: ``` 64 ``` The output may contain zeros if the certain power of two is not present in the sum. For example, input `65` may output `0 64 0 0 0 0 0 1`. **Scoring** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. [Answer] # JavaScript (ES6), 28 bytes ``` f=n=>n?[...f(n&~-n),n&-n]:[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PPlpPTy9NI0@tTjdPUydPTTcv1io69n9yfl5xfk6qXk5@ukaahoWZpiYXqpCRiQGGmCGGiJmJpuZ/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 since we may output zeros in place of unused powers of 2 :) ``` Ḷ2*& ``` **[Try it online!](https://tio.run/##y0rNyan8///hjm1GWmr///@3MAMA "Jelly – Try It Online")** ### How? ``` Ḷ2*& - Link: integer, n e.g. 10 Ḷ - lowered range of n [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2* - two to the power of [ 1, 2, 4, 8, 16, 32, 64,128,256,512] & - bit-wise and [ 0, 2, 0, 8, 0, 0, 0, 0, 0, 0] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` BUT’2* ``` [Try it online!](https://tio.run/##y0rNyan8/98pNORRw0wjrf@H2x81rXH//9/CTEfByMRAR8FQR8HMBAA "Jelly – Try It Online") ### Explanation BUT here is an explanation (note: I had assumed that we may only output the powers of 2 themselves and nothing else): ``` BUT’2* – Monadic link. Takes a number N as input. Example: 86 B – Convert N to binary. [1, 0, 1, 0, 1, 1, 0] U – Reverse. [0, 1, 1, 0, 1, 0, 1] T – Truthy indices. [2, 3, 5, 7] ’ – Decrement. [1, 2, 4, 6] 2* – Raise 2 to that power. [2, 4, 16, 64] ``` **"Proof" that it works correctly.** The standard representation of an integer \$ X\$ in base 2 is a list \$\{x\_1, x\_2, x\_3,\cdots, x\_n\}\$, where \$x\_i\in\{0,1\},\:\forall\:\: i\in\overline{1,n}\$, such that: $$X=\sum\_{i=1}^n x\_i\cdot 2^{n-i}$$ The indices \$i\$ such that \$x\_i=0\$ obviously have no contribution so we're only interested in finding those such that \$x\_i=1\$. Since subtracting \$i\$ from \$n\$ is not convenient (the powers of two all have exponents of the form \$n-i\$, where \$i\$ is any index of a \$1\$), instead of finding the truthy indices in this list we reverse it and then find them "backwards" with `UT`. Now that we've found the correct indices all we have to do is raise \$2\$ to those powers. [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 20 ``` echo $[2**{7..0}&$1] ``` [Try it online!](https://tio.run/##TYvBCkBAGAbvnuJLy0Gt0IZSXkQO2F9cdrW7N3n2n5Qyx5lmnvzGq3UI5MMyecJu0CpUqkCJWnXQNsLD4XYTVsSJhuwRQ3zDWz0FSPmTTMtmIYYqy84mz4srFeXI2hpivgE "Bash – Try It Online") ### Explanation ``` {7..0} # Brace expansion: 7 6 5 4 3 2 1 0 2**{7..0} # Brace expansion: 128 64 32 16 8 4 2 1 2**{7..0}&$1 # Brace expansion: 128&n 64&n 32&n 16&n 8&n 4&n 2&n 1&n (Bitwise AND) $[2**{7..0}&$1] # Arithmetic expansion echo $[2**{7..0}&$1] # and output ``` [Answer] # [Python](https://docs.python.org/), 35 bytes ``` lambda n:[n&2**i for i in range(8)] ``` Little-endian with zeros at unused powers of 2. **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjpPzUhLK1MhLb9IIVMhM0@hKDEvPVXDQjP2P0ioJLW4BCSqYWGmo2BkYqCjYKijYGaiacWloFBQlJlXogFSoaOgrmunrqOQBuZpArkxeeqa/wE "Python 3 – Try It Online")** [Answer] # [Sledgehammer](https://github.com/tkwa/Sledgehammer) 0.2, 3 bytes ``` ⡔⡸⢣ ``` Decompresses into `{intLiteral[2],call[NumberExpand,2]}`. Sledgehammer is a compressor for Wolfram Language code using Braille as a code page. The actual size of the above is 2.75 bytes, but due to current rules on meta, padding to the nearest byte is counted in code size. [Answer] # [Catholicon](https://github.com/okx-code/Catholicon/), 3 bytes ``` ṫĊŻ ``` [Try it online!](https://tio.run/##S04sycjPyUzOz/v//@HO1Ue6ju7@/9/MFAA "Catholicon – Try It Online") Explanation: ``` ṫ Decompose into the largest values where: Ċ the input Ż the bit count is truthy (equal to one) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. Requires 0-based indexing (`⎕IO←0`). ``` 2*⍸⍢⌽⍤⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/420HvXueNS76FHP3ke9Sx51LfmfBhR/1NsHUdLVfGi98aO2iUBecJAzkAzx8Az@n6ZgYQYA "APL (Dyalog Extended) – Try It Online") `2` two `*` raised to the power of `⍸` the **ɩ**ndices where true `⍢` while `⌽` reversed `⍤` of `⊤` the binary representation [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ýo& ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/179178/52210), so make sure to upvote him! Contains zeros (including -loads of- trailing zeros). [Try it online](https://tio.run/##yy9OTMpM/f//8Nx8tf//DU0B) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCgpK9v8Pz81X@6/zP9pQR8FIR8HQFIjNdBTMTIAYyLYAso1MDGIB). **Explanation:** ``` Ý # Create a list in the range [0, (implicit) input] # i.e. 15 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # i.e. 16 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] o # Take 2 to the power of each value # → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768] # → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536] & # Bitwise-AND each value with the (implicit) input # 15 → [1,2,4,8,0,0,0,0,0,0,0,0,0,0,0,0] # 16 → [0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0] # (and output the result implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 17 bytes ``` #~NumberExpand~2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOrzQ3KbXItaIgMS@lzkjtf0BRZl5JdJqDiVHsfwA "Wolfram Language (Mathematica) – Try It Online") Mathematica strikes again. [Answer] # [R](https://www.r-project.org/), ~~27~~ 23 bytes ``` bitwAnd(scan(),2^(7:0)) ``` [Try it online!](https://tio.run/##PYxNCsIwEIX3PcWAmxnQUEutIrrwIkJaEw3YSWmmtFJ69tgsdPM93g@vjxsYe91BaDSDY/GgwQ7ciPMMq3uZdwdigjh@AgbdGqg/YqDxAwtl9vob40RzOrns/olSiuZpibWT8cYPTDXStrjj8ZwTxSWzWB3WEzxViUWZJ9knVCXFLw "R – Try It Online") ### Unrolled code and explanation : ``` A = scan() # get input number A from stdin # e.g. A = 65 bitwAnd( A , 2^(7:0)) # bitwise AND between all powers of 2 : 2^7 ... 2^0 and A # and implicitly print the result # e.g. B = bitwAnd(65, c(128,64,32,16,8,4,2,1)) = c(0,64,0,0,0,0,0,1) ``` * 4 bytes thanks to @Kirill L. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 29 bytes Contains 5 unprintable characters. ``` n=>"€@ ".Select(a=>a&n) ``` # Explanation ``` //Lambda taking one parameter 'n' n=> //String with ASCII characters 128, 64, 32, 16, 8, 4, 2, and 1 "€@ " //Iterate through all the chars of the above string and transform them to .Select(a=> //A bitwise AND operation between the integer value of the current char and the input value a&n) ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXouPpmleam1qUmJSTCuLb2SXZ/s@ztVM61OCgIMDBwsSopBecmpOaXKKRaGuXqJan@d@aKy2/SAOoViHT1sA6U1vbxsjU1FqTK7wosyTVJzMvVUOp2qDWSqG6WqHasFahtlZJRyFTR6G4pCgzL13PKz8zTwMooqSTpJGpqalpzfUfAA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 39 bytes ``` f(n){for(;n;n&=n-1)printf("%d ",n&-n);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOi2/SMM6zzpPzTZP11CzoCgzryRNQ0k1RUFJJ09NN0/TuvZ/WX5mikKJBlBGIU9ToZqLE0mVrR1QIVDYmosTZJw1QjImTwnIreUC685NzMzTAOst0bAwAykr0TAyMYAwDCGUmQmEBonW/gcA "C (gcc) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 38 bytes ``` x=>{for(int y=8;y-->0;Print(x&1<<y));} ``` [Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2eTmVdip5CmYPu/wtauOi2/SAMooFBpa2FdqatrZ2AdUATka1SoGdrYVGpqWtf@t@ZK0zAyNNa0/g8A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~16~~ 12 bytes *-4 bytes thanks to Jonathan Allan* ``` *+&2**all ^8 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0tbzUhLKzEnRyHO4r81V3FpkkJZYk5parGGb6mCSpamQjWXAhAA1TuUWYOZunYKjnmVCirFCtVAMb2C0uIMKxCvVgOoHKIEpLSWiystv0jBwkzHyMRAx1DHzARsVHFipYKeWpqeGsQWoLr/AA "Perl 6 – Try It Online") Returns an All Junction with 8 elements. This is a rather non-standard way of returning, but generally, Junctions can act as ordered (at least until autothreading is implemented) lists and it is possible to extract the values from one. ### Explanation: ``` *+& # Bitwise AND the input with 2** # 2 raised to the power of all ^8 # All of the range 0 to 7 ``` [Answer] # 05AB1E, 7 bytes ``` 2вRƶ<oò ``` explanation: ``` 2в convert input to binary array R reverse array ƶ< multiply each item by it's index and subtract 1 oò 2^item then round down ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f6MKmoGPbbPIPb/r/39AUAA "05AB1E (legacy) – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 13 bytes ``` n->n&2.^(0:7) ``` [Try it online!](https://tio.run/##yyrNyUw0@59m@z9P1y5PzUgvTsPAylzzf25igQZQpKAoM68kJ08jTSNPU1Mn2sJMR8HIxEBHwVBHwcwkVvM/AA "Julia 0.6 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` (mapM(\n->[0,2^n])[7,6..0]!!) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyM3scBXIyZP1y7aQMcoLi9WM9pcx0xPzyBWUVHzf25iZp6CrUJBUWZeiYKKQpqChdn/f8lpOYnpxf91kwsKAA "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` ->n{8.times{|i|p n&2**i}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2kKvJDM3tbi6JrOmQCFPzUhLK7O29n@0hZmOgpGJgY6CIZA2M4nVS01MzlCorqmoUSgoLSlWUFKurqi1UrJWSIuuiLUGi9X@BwA "Ruby – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 133 110 63 58 bytes *58-byte solution thanks to @ceilingcat*. ``` x=256;main(y){for(scanf("%d",&y);x/=2;)printf("%d ",y&x);} ``` [Try it online!](https://tio.run/##S9ZNzknMS///v8LWyNTMOjcxM0@jUrM6Lb9Iozg5MS9NQ0k1RUlHrVLTukLf1shas6AoM68ELKqgpFOpVqFpXfv/v5GJIQA "C (clang) – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 6 bytes ``` 2*⍸⌽⊤⎕ ``` 2 to the `*` power of the `⍸` indices of the true bits of the `⌽` reversed `⊤` binary encoding of the `⎕` input [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862hXS/htpPerd8ahn76OuJUCp/0DB/2kKXBZmAA "APL (Dyalog Extended) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` BPfqW ``` [Try it online!](https://tio.run/##y00syfn/3ykgrTD8/38LMwA "MATL – Try It Online") # Explanation Consider input `86` as an example. ``` B % Implicit input. Convert to binary (highest to lowest digits) % STACK: [1 0 1 0 1 1 0] P % Flip % STACK: [0 1 1 0 1 0 1] f % Find: indices of nonzeros (1-based) % STACK: [2 3 5 7] q % Subtract 1, element-wise % STACK: [1 2 4 6] W % Exponential with base 2, element-wise. Implicit display % STACK: [2 4 16 64] ``` [Answer] # Japt, ~~8~~ 5 bytes ``` Æ&2pX ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xiYycFg=&input=ODY=) ``` Æ&2pX :Implicit input of integer U Æ :Map each X in the range [0,U) & : Bitwise AND of U with 2pX : 2 to the power of X ``` --- ## Alternative Suggested by [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) to avoid the `0`s in the output using the `-mf` flag. ``` N&2pU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=TiYycFU=&input=ODYKLW1m) ``` N&2pU :Implicitly map each U in the range [0,input) N :The (singleton) array of inputs & :Bitwise AND with 2pX :2 to the power of U :Implicitly filter and output ``` [Answer] # APL(NARS) 18 chars, 36 bytes ``` {(⍵⊤⍨8⍴2)/⌽1,2*⍳7} ``` test: ``` f←{(⍵⊤⍨8⍴2)/⌽1,2*⍳7} f 86 64 16 4 2 f 240 128 64 32 16 f 1 1 f 64 64 f 3 2 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` Ýoʒ›}æʒOQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Nz8U5MeNeyqPbzs1CT/wP//DU0B "05AB1E – Try It Online") --- This is also correct for 6-bytes, but it doesn't complete in time on TIO for 86: # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ÝoæʒOQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fJ//wslOT/AP//7cwAwA "05AB1E – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` {:T{2\#T&}%} ``` [Try it online!](https://tio.run/##S85KzP1fWPe/2iqk2ihGOUStVrX2f12w1n9DAwA "CJam – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ 16 bytes -3 bytes thanks to ngn! ``` {*/x#2}'&|(8#2)\ ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWku/QtmoVl2tRsNC2Ugz5n@agoXZfwA "K (oK) – Try It Online") oK does not have `power` operator, that's why I need a helper function `{*/x#2}` (copy 2 `x` times and reduce the resulting list by multiplication) [Answer] # [Alchemist](https://github.com/bforte/Alchemist), 125 bytes ``` _->In_x+128a+m m+x+a->m+b m+0x+a->n+a m+0a->o+Out_b+Out_" " n+b->n+x+c n+0b+a->n+c n+0a->p o+b->o+c o+0b->p p+2c->p+a p+0c->m ``` [Try it online!](https://tio.run/##JcwxCsMwDAXQ3acoWT8GN3TolL1Tj2Bsp9BAZRnigE8fRXYX6fG/UPil74e2vYp4u7yyb7jPzwAyhIZgF0JUuuGM0K1ivI/q45jTbTIZsdcNSeni/3hYVQz3mjVgLXtQMCfd@q/AqUjkcXKpG@dd7HoB "Alchemist – Try It Online") or [Test every input!](https://tio.run/##jY9Ba4MwFMfPzad4iK6V4NSMwtg67zt1h/Y2kJikUzAvmdohbPvs7mmh9LhL8uP/z/vxUsm@npQcdru1Qb2GApTT5l51OJVJ8YrlyHPxKLlllo9cJoXlFWG2MHI5M5Hj@/NQVssZQMCQV3M9ckWYVZfHCxN55ubaUeConAPPhaKbfJ5nRHaibRg7uQ4QGoRw05tPyCHM42fQjq32x8Pb8fASboyqHYQIP5A6P6SyVbWxTX9D1x/FbOW7BocTBNGDBogSIXqI@ncMZkMQfl@sTwn8UvIfdaKvdhDFXQ5Fqs1Xiue2pbGPznhIHGgzmM42SBONipl2aKZJbLd/ "Alchemist – Try It Online") ### Explanation ``` _->In_x+128a+m # Initialize universe with input, 128a (value to compare to) and m (state) m+x+a->m+b # If c has been halved, subtract min(a, x) from a and x and put its value into b m+0x+a->n+a # If x < a, continue to state n m+0a->o+Out_b+Out_" " # Else print and continue to state o n+b->n+x+c # Add min(a, x) (i.e. x) back to x, and add it to c (we're collecting a back into c) n+0b+a->n+c # Then, add the rest of a to c n+0a->p # Then, go to state p o+b->o+c # Add min(a, x) (i.e. a) to c - x _is_ greater than a and so contains it in its binary representation, so we're not adding back to x o+0b->p # Then, go to state p p+2c->p+a # Halve c into a p+0c->m # Then go to state m ``` [Answer] # [PHP](https://php.net/), ~~41~~ 39 bytes ``` for($c=256;$c>>=1;)echo$argv[1]&$c,' '; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFSSbY1MzaxVku3sbA2tNVOTM/JVEovSy6INY9VUknXUFdSt////b2EGAA "PHP – Try It Online") Or **38** with no fun `>>=` operator and PHP 5.6+: ``` for($x=8;$x--;)echo$argv[1]&2**$x,' '; ``` Or **36** with little-endian ("0 2 4 0 16 0 64 0") output: ``` while($x<8)echo$argv[1]&2**$x++,' '; ``` Really I just wanted to use the `>>=` operator, so I'm sticking with the **39**. Tests: ``` $php pow2.php 86 0 64 0 16 0 4 2 0 $php pow2.php 240 128 64 32 16 0 0 0 0 $php pow2.php 1 0 0 0 0 0 0 0 1 $php pow2.php 64 0 64 0 0 0 0 0 0 $php pow2.php 65 0 64 0 0 0 0 0 1 ``` [Answer] # TSQL, ~~43~~ 39 bytes Can't find a shorter fancy solution, so here is a standard loop. -4 bytes thanks to MickyT and KirillL ``` DECLARE @y int=255 ,@ int=128s:PRINT @y&@ SET @/=2IF @>0GOTO s ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/973160/sum-of-powers-of-2)** ]
[Question] [ ## Introduction and Credit Today without a fancy prelude: Please implement `takewhile`. A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly). ## Specification ### Input The input will be a list (or your language's equivalent concept) of positive integers. ### Output The output should be a list (or your language's equivalent concept) of positive integers. ### What to do? Your task is to implement `takewhile` (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile). So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (`takewhile`). ### Potential corner cases The order of the output list compared to the input list may not be changed, e.g. `[14,42,2]` may not become `[42,14]`. The empty list is a valid in- and output. ### Who wins? This is code-golf so the shortest answer in bytes wins! Standard rules apply of course. ## Test Vectors ``` [14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372] [42, 14, 42, 2324] -> [42, 14, 42, 2324] [7,14,42] -> [] [] -> [] [171480372, 13, 14, 42] -> [171480372] [42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42] ``` ### Step-by-Step Example ``` Example Input: [42, 14, 42, 43, 41, 4080622, 171480372] Consider first element: 42 42 is even (21*2) Put 42 into output list, output list is now [42] Consider second element: 14 14 is even (7*2) Put 14 into output list, output list is now [42,14] Consider third element: 42 42 is even (21*2) Put 42 into output list, output list is now [42,14,42] Consider fourth element: 43 43 is not even (2*21+1) Drop 43 and return the current output list return [42,14,42] ``` [Answer] ## Mathematica, 18 bytes ``` #~TakeWhile~EvenQ& ``` Another glorious built-in that is beaten by a factor of 3 by golfing languages without the built-in... [Answer] ## Haskell, 13 bytes ``` fst.span even ``` `span` splits the input list into a pair of lists just before the first element where the predicate (-> `even`) is false. `fst` takes the first element of the pair. Alternative version, 13 bytes: ``` fst.break odd ``` `break` is the opposite of `span`, i.e. it splits the list at the first element where the predicate is true. Of course there's also ``` takeWhile even ``` but that's 14 bytes. [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` toYs~) ``` [**Try it online!**](http://matl.tryitonline.net/#code=dG9Zc34p&input=WzQyLCAxNCwgNDIsIDQzLCA0MSwgNDA4MDYyMiwgMTcxNDgwMzcyXQ) ### Explanation ``` t % Input array implicitly. Duplicate o % Parity of each entry. Gives 0 for even entries, 1 for odd Ys % Cumulative sum ~ % Logical negate. Gives true for the first run of even entries, and then false ) % Use this as logical index into the original array. Implicitly display ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 19 ``` 2.}<@>%?<{>$"/\M!8; ``` Readable: ``` 2 . } < @ > % ? < { > $ " / \ M ! 8 ; ``` [Try it online!](http://hexagony.tryitonline.net/#code=ICAyIC4gfQogPCBAID4gJQo_IDwgeyA-ICQKICIgLyBcIE0KICAhIDggOw&input=MjQgMiA4IDE3IDI) This can probably be golfed by a byte or two, but that might require some truly ingenious layout, that might be more easily found via brute force (even if it might take rather long to find it). ### High level explanation The program mostly follows this pseudocode: ``` while (read number is not zero) { if (number is even) print number; } ``` Which abuses how Hexagony tries to read a number once STDIN is empty (it returns a zero). Big thanks to Martin for help with coming up with this approach. ### Full Explanation I still haven't fiddled around with Mono to get Timwi's [fantastic esoteric IDE](https://github.com/Timwi/EsotericIDE/) running, so I've leant on Martin to provide me with some helpful pretty pictures! First, a little primer on basic control flow in Hexagony. The first instruction pointer (IP), which is the only one used in this program, starts at the top left of the hexagonal source code, and begins moving towards the right. Whenever the IP leaves the edge of the hexagon, it moves `side_length - 1` rows towards the middle of the hexagon. Since this program uses a side length three hexagon, the IP will always be moving two rows when this happens. The only exception is if it moves off of the middle row, where it conditionally moves towards the top or bottom of the hexagon, depending on the value of the current memory edge. Now a bit about conditionals. The only conditionals in Hexagony for control flow are `>`, `<` and the middle edge of the hexagon. These all follow a constant rule: if the value on the current memory edge is zero or negative control flow moves left and if is positive the control flows right. The greater than and less than brackets redirect the IP at sixty degree angles, while the edge of the hexagon controls to which row the IP jumps. Hexagony also has a special memory model, where all data is stored on the edges of an infinite hexagonal grid. This program only uses three edges: one to store a two, one for the currently read number, and one for the number modulo two. It looks something like: ``` Mod \ / Input | 2 ``` I'm not going to carefully explain where we are in memory at each point during the explanation of the program, so come back here if you get confused by where we are in memory. With all of that out of the way, the actual explanation can begin. First, we populate the "2" edge in memory with a 2, then we execute a no-op and move the memory pointer to the right (`2.}`). Next, we begin the main program loop. We read the first number from STDIN and then we hit a conditional (`?<`). If there are no numbers left in STDIN, this reads a zero into the current memory edge, so we turn left onto the `@`, which ends the program. Otherwise, we bounce off a mirror, move the memory pointer backwards and to the left, wrap around the hexagon to calculate the remainder of dividing the input by 2 and then hit another conditional (`/"%>`). [![Odd Path](https://i.stack.imgur.com/AUWOs.png)](https://i.stack.imgur.com/AUWOs.png) If the remainder was one (i.e. the number was odd), we turn right following the blue path above starting by executing the no-op again, then we wrap around to the bottom of the hexagon, multiply the current edge by 10 and then add eight, bounce off a couple mirrors, do the same multiplication and addition again, getting 188 on the current edge, wrapping back around to the top of the hexagon, executing the no-op again, and finally ending the program (`.8/\8.@`). This convoluted result was a happy accident, I originally had written a much simpler bit of logic, but noticed that I could remove it in favour of the no-op, which I thought was more in the spirit of Hexagony. [![Even Path](https://i.stack.imgur.com/zHmfI.png)](https://i.stack.imgur.com/zHmfI.png) If the remainder was zero we instead turn left following the red path, above. This causes us to move the memory pointer to the left, and then print the value there (the input value) as a number. The mirror we encounter acts as a no-op because of the direction we are moving (`{/!`). Then we hit the edge of the hexagon which acts a conditional with only one outcome, as the input value from before was already tested to be positive, so we always move towards the right (if you imagine yourself facing in the direction of the IP). We then multiple the input by 10 and add two, only to change direction, wrap around and overwite the new value with the ascii value of the capital letter M, 77. Then we hit some mirrors, and exit over the edge of the middle of the hexagon with a trampoline (`2<M\>$`). Since 77 is positive, we move right towards the bottom of the hexagon and because of the trampoline skip the first instruction (`!`). We then multiply the current memory edge by 10 and add 8, getting 778. We then output this value mod 256 (10) as an ASCII character, which happens to be newline. Finally we exit the hexagon and wrap back around to the first `?` which overrides the 778 with the next input value. [Answer] ## ed, 13 ``` /[13579]$/,$d ``` Because [*real* programmers](https://xkcd.com/378/) use [The Standard Text Editor](http://c2.com/cgi/wiki?EdIsTheStandardTextEditor). Takes input as one integer on each line; outputs in the same format. This simply finds the first odd number (number ending in an odd digit) and deletes from that line until the end of the file. [Answer] # Pyth, ~~13~~ ~~9~~ 7 bytes ``` uPWs%R2 ``` Credits to @FryAmTheEggman for 2 (quite tricky) bytes! Explanation: ``` u Q keep applying to input until invariant: PW drop last element if... s%R2G ...any one is odd, G is the argument originally given the value of input ``` [Test it here](http://pyth.herokuapp.com/?code=uPWs%25R2&test_suite=1&test_suite_input=%5B14%2C%2042%2C%202324%2C%2097090%2C%204080622%2C%20171480372%5D%0A%5B42%2C%2014%2C%2042%2C%202324%5D%0A%5B7%2C14%2C42%5D%0A%5B%5D%0A%5B171480372%2C%2013%2C%2014%2C%2042%5D%0A%5B42%2C%2014%2C%2042%2C%2043%2C%2041%2C%204080622%2C%20171480372%5D&debug=0). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḃœp⁸Ḣ ``` [Try it online!](http://jelly.tryitonline.net/#code=4biCxZNw4oG44bii&input=&args=WzQyLCAxNCwgNDIsIDQzLCA0MSwgNDA4MDYyMiwgMTcxNDgwMzcyXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4biCxZNw4oG44biiCsOH4oKsRw&input=&args=WzE0LCA0MiwgMjMyNCwgOTcwOTAsIDQwODA2MjIsIDE3MTQ4MDM3Ml0sIFs0MiwgMTQsIDQyLCAyMzI0XSwgWzcsMTQsNDJdLCBbXSwgWzE3MTQ4MDM3MiwgMTMsIDE0LCA0Ml0sIFs0MiwgMTQsIDQyLCA0MywgNDEsIDQwODA2MjIsIDE3MTQ4MDM3Ml0). ### How it works ``` Ḃœp⁸Ḣ Main link. Argument: A (array) Ḃ Bit; yield 1 for odd integers, 0 for even ones. ⁸ Yield A. œp Partition A, splitting at 1's in the bit array. This yields a 2D array of runs of even integers. Ḣ Head; extract the first chunk. ``` [Answer] # Python 2, ~~43~~ 42 bytes ``` def f(x): while"1'"in`map(bin,x)`:x.pop() ``` The function [modifies its argument in place](http://meta.codegolf.stackexchange.com/a/4942). *Thanks to @xnor for golfing off a byte in a really clever way!* Test it on [Ideone](http://ideone.com/7xXEI9). [Answer] ## Clojure, 21 bytes ``` #(take-while even? %) ``` Clojure is kinda nearly competing at last! (thanks to the task being a built-in) See it online <https://ideone.com/BEKmez> [Answer] # Python, ~~45~~ 44 bytes ``` f=lambda x:x and~x[0]%2*x and x[:1]+f(x[1:]) ``` Test it on [Ideone](http://ideone.com/6pRtWR). [Answer] # Brainf\*\*\*, 263 bytes I took a little snippet from [here](https://stackoverflow.com/a/35243393) ``` >>>>>>,[>>>>>>,]>++++[<++++++++>-]>>>>>+>>>>>>>++++[<++++++++>-]<<<<<<<[<<<<<<]>>>>>>[[>>>>>>>++++[<-------->-]<]<<<<<<[->>>+<<<]>>>[-<+<<+>>>]<>>+>+<<<[-[->]<]+>>>[>]<[-<]<[-]<-[<[<<<<<<]>>>>>>.>>>>>>[>[-]++++[<++++++++>-]<.>>>>>>]>++++[-<++++++++>]<.[-]]>>>>>>] ``` I'd give an explanation but even I don't have a clue how this works anymore. Expects input as space-seperated numbers (eg `2 432 1`) [Answer] ## R, 25 bytes ``` x=scan() x[!cumsum(x%%2)] ``` Or equivalently ``` (y=scan())[!cumsum(y%%2)] ``` [Answer] ## 05AB1E, ~~8~~ 7 bytes ``` [DÉO_#¨ ``` **Explanation** ``` [ # infinite loop start DÉO # count odd numbers _ # push negative bool (turning 0->1, X->0) # # if true (no odd numbers exist), break out of loop and implicitly print ¨ # else, remove last element from list ``` [Try it online](http://05ab1e.tryitonline.net/#code=W0TDiU9fI8Ko&input=WzQyLCAxNCwgNDIsIDQzLCA0MSwgNDA4MDYyMiwgMTcxNDgwMzcyXQ) **Previous 8 byte solution** ``` vyÈiyˆëq ``` **Explanation** ``` v # for each y in input yÈi # if y is even yˆ # push y to global array ëq # else terminate program # implicitly print global array ``` [Try it online](http://05ab1e.tryitonline.net/#code=dnnDiGl5y4bDq3E&input=WzQyLCAxNCwgNDIsIDQzLCA0MSwgNDA4MDYyMiwgMTcxNDgwMzcyXQ) [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 14 bytes ``` ?: "`# "@% \!; ``` Input and output are linefeed-separated lists (although in principle, the input could use any non-digit separator). [Try it online!](http://labyrinth.tryitonline.net/#code=PzoKImAjCiJAJQpcITs&input=Mgo0CjYKOAoxMAoyNAoyMwo2CjgKODg) This is probably the most compact Labyrinth program I've ever written. Interestingly, `takewhile(odd)` is lot simpler: ``` ?:# " % \!/ ``` ### Explanation The usual Labyrinth primer: * The memory model is a stack (there's actually two, but we'll only need one for this program), which holds arbitrary-precision integers and initially holds an (implicit) infinite number of zeros. * There are no control flow instructions. Instead, the movement of the instruction pointer (IP) is determinated by the layout of the code (spaces are considered "walls" and cannot be traversed by the IP). *Normally*, the code is supposed to resemble a maze, where the IP follows straight corridors and bends, but whenever it reaches a junction, this acts as a conditional where the IP's new direction is determined based on the current state. The rules for choosing a direction boil down to this: if the top of the stack is zero, the IP keeps moving forward; if the top is positive, the IP turns right; if the top is negative the IP turns left. If one of these directions is blocked by a wall, the IP takes the opposite direction instead. This means that programs *without* clear corridors are usually incredibly tough to work with, because every single command would act as a junction. The fact that this worked out in this case is a bit of a miracle. * The IP starts at the first non-space character in reading order (`?` in this case), moving east. The main flow through the program is a single loop around the perimeter: ``` >v ^>v ^@v ^<< ``` As it happens, we know that the top of the stack is zero after `!` and `"` so that the IP is guaranteed not to turn towards the centre. ``` and `%` on the other hand are used as conditionals where the IP might move towards the centre such that `@` terminates the program, or it might keep moving around the perimeter. Let's look at the code in the loop: ``` ? Read decimal integer N from STDIN, or 0 at EOF. : Duplicate. Since this is just a corner, the IP always turns south. ` Negate the copy of the input (i.e. multiply by 1). At EOF, the result is still zero and the IP keeps moving south into the @. Otherwise, the top of the stack is now negative, and the IP turns east. # Push the stack depth (i.e. 2). Again, this is a corner, and the IP is forced to turn south. % Computer (-N % 2), which is identical to (N % 2) to determine the parity of the input. If input was odd, this gives 1, and the IP turns west into the @. Otherwise, the result is 0 and the IP keeps moving south, continuing the loop. ; Discard the 0. This is a corner, so the IP is forced to turn west. ! Print (and discard) N. The top of the stack is now one of the implicit zeros at the bottom, so the IP keeps moving west. \ Print a linefeed. The IP is forced to turn north in the corner. "" Two no-ops. The top of the stack is still zero, so the IP keeps moving north. ``` And then the loop starts over. That raises the question why `takewhile(odd)` is so much simpler. There's two reasons: * Since EOF is returned as `0` (which is even), we don't need a separate EOF check. The list would be cut off at that point anyway. * Now we want to terminate when `N % 2` is `0` (as opposed to `1`), which means instead of conditional control flow we can simply divide the other copy `N` by `N % 2`: if the input is odd, that just leaves `N` and we even got rid of the `N % 2` (so we don't need `;`), but if the input is even, that simply terminates the program with a (silent) division-by-zero error. Hence, the other code is a simple loop that doesn't allow for any branching at all. [Answer] ## Pyth, 7 bytes ``` <x%R2Q1 ``` [Try it here!](http://pyth.herokuapp.com/?code=%3Cx%25R2Q1&input=%5B42%2C+14%2C+42%2C+2324%5D&test_suite=1&test_suite_input=%5B14%2C+42%2C+2324%2C+97090%2C+4080622%2C+171480372%5D%0A%5B42%2C+14%2C+42%2C+2324%5D%0A%5B7%2C14%2C42%5D%0A%5B%5D%0A%5B171480372%2C+13%2C+14%2C+42%5D%0A%5B42%2C+14%2C+42%2C+43%2C+41%2C+4080622%2C+171480372%5D&debug=0) What I attempted to do in Pyke but index is broken in that atm [Answer] # Racket, 22 bytes ``` (λ(n)(takef n even?)) ``` The `λ` character is counted as 2 bytes. I haven't seen Racket used before in any of the code golfing answers I've seen, so I had to do it at least once! [Answer] # Perl 5 + [Perligata](//metacpan.org/pod/Lingua::Romana::Perligata), 173 bytes 145 bytes, plus 28 for `-MLingua::Romana::Perligata` Use as `perl -MLingua::Romana::Perligata foo.pl`; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata, released two days ago; I don't know whether it works with Perligata version 0.50. ``` huic vestibulo perlegementum da.his _ scindementa da.per in his fac sic si recidementum hoc tum II fac sic I exi cis hoc tum _ egresso scribe cis ``` --- Obviously this is clear as a bell. In case it's not, run it with `-MLingua::Romana::Perligata=converte` instead of `-MLingua::Romana::Perligata`, and `perl` will, instead of running the script, output a translation into regular Perl: ``` $_ = Lingua::Romana::Perligata::getline (*STDIN ); @_ = split ( '_'); for $_ (@_) {if ( ($_ % 2)) {exit ( 1)} ; print (STDOUT $_, '_')} ``` For a token-by-token analysis, use `-MLingua::Romana::Perligata=discribe`. --- Golfing notes: * It seems from the documentation that `ultimus si recidementum hoc tum II fac.` would work instead of `si recidementum hoc tum II fac sic ultimus cis`, saving 7 bytes. But it doesn't (it gives a "iussa absentia" error). * Undocumented (but unsurprising), you don't need a space after `.`. * (Also unsurprising,) `scinde` doesn't need a second argument, and uses `hoc`. Alas, `exi` needs an argument. * Instead of `huic vestibulo perlegementum da`, I tried `-pMLingua::Romana::Perligata`, but couldn't get it to work. --- Just for kicks (although this whole answer was just for kicks): * After cleaning it up to `Huic vestibulo perlegementum da. His lacunam scindementa da. Per in his fac sic si recidementum hoc tum II fac sic I exi cis. Hoc tum lacunam egresso scribe cis.`, Google Translate gives `This court perlegementum grant. His gap scindementa grant. 2 By that time, do so in the following 1, Go out and do so if recidementum on this side. This was the gap as soon as write on this side.`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 14 bytes ``` {|$_,1...^*%2} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7pGJV7HUE9PL05L1aj2f3FipUKaRrShiY6CiZGOgpGxEZBlaW5gaQAUMLAwMDMCihqaG5pYGBibG8VqWnNBdYBUI@tCkjLXAUqYICtGYsLNAmo3hhmBw1wToAITQxwO@Q8A "Perl 6 – Try It Online") Finally, a use for a neat trick I found involving `...`. This is an anonymous code block that basically filters the list until it reaches an element that succeeds in the condition `*%2` i.e. odd. Then we return the list excluding the last element. Since an element has to pass the condition at some point, otherwise it attempts to extrapolate off the end of the list, we append a `1` to the input list. Note this isn't the intended use for the sequence operator `...`, which is usually used to create sequences based off several parameters. We're using the behaviour that the end condition is checked against the starting elements as well, and will stop even before any new elements are generated. ### Explanation: ``` { } # Anonymous code block |$_,1 # Using the input list appended with 1 ... # Take up to *%2 # The element that is odd ^ # And exclude the last element ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 11 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` {⍵/⍨∧\~2|⍵} ``` `2|` division remainder from dividing with 2 `~` negate `∧\` AND-scan (turns off from first 0) `/⍨` select where [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~19~~ 16 bytes ``` ~~hH:2%0,?b&~b.hH;[].~~ s.:Mc?,.:{:2%0}a ``` ### Explanation ``` s. Output is an ordered subset of Input :Mc?, The concatenation of Output with a list M is Input .:{:2%0}a All elements of Output are even ``` Today I learnt a neat trick (which was used in the 19 bytes answer): `~b.hH` is shorter than `:[H]rc.` to append an element at the beginning of a list. The first one means *"Output is the result with an extra item at the beginning, and the first item of the Output is `H`"*, whereas the other one is straightforwardly *"Output is the concatenation of `[[H], Result]`".* [Answer] # J, 10 bytes ``` {.~2&|i.1: ``` ## Explanation ``` {.~2&|i.1: Input: s 2&| Take each value in s mod 2 i.1: Find the index of the first 1 {.~ Take that many values from s and return ``` [Answer] ## Python, 41 bytes ``` lambda l:l[:[x%2for x in l+[1]].index(1)] ``` Truncates `l` up to the index of the first occurrence of an odd number. The index is found by looking for a `1` in the values modulo `2`. To guard against no odd number being found, a `1` is put on the end. [Answer] ## C#, 50 bytes ``` int[]f(int[]a)=>(a.TakeWhile(x=>x%2<1).ToArray()); ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 11 bytes *Thanks to @Dennis for two corrections and one byte off!* ``` {1+_2f%1#<} ``` This is a code block (equivalent to a function; allowed by default) that expects the input array on the stack, and leaves the output array on the stack. [**Try it online!**](http://cjam.tryitonline.net/#code=cX4gICAgICAgICAgICBlIyB0YWtlIGlucHV0IGZyb20gc3RkaW4KezErXzJmJTEjPH0gICBlIyBhY3R1YWwgY29kZSBhcyBhIGJsb2NrCn4gICAgICAgICAgICAgZSMgZXhlY3V0ZSBibG9jawpgICAgICAgICAgICAgIGUjIHN0cmluZyByZXByZXNlbnRhdGlvbg&input=WzQyIDE0IDQyIDQzIDQxIDQwODA2MjIgMTcxNDgwMzcyXQ) ### Explanation ``` { } e# define code block 1+ e# attach 1 at the end of the array _ e# duplicate 2f% e# modulo 2 of each entry 1# e# find index of first occurrence of 1 < e# slice before ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 17 bytes ``` ?\d*[13579]\b.* ``` The trailing linefeed is significant. Input and output are space-separated lists. [Try it online!](http://retina.tryitonline.net/#code=ID9cZCpbMTM1NzldXGIuKgo&input=MiA0IDYgOCAxMCAyNCAyMyA2IDggODg) This is a simple regex substitution, it matches the first odd number (i.e. a number ending in an odd digit), and if possible the space preceding it as well as everything after it and replaces it with an empty string, i.e. all elements from there onward are removed from the input. As Leaky Nun points out, taking the list in binary, we can save 6 bytes, but it seems a bit cheaty, so I'll probably continue counting the decimal version: ``` ?\d*1\b.* ``` [Answer] # JavaScript, ~~27~~ 25 bytes ``` a=>a.filter(v=>a=a&&~v%2) ``` The filer expression repeatedly assigns to `a` and uses the value of `a` as a filter predicate. `a` holds either the initial array value (always truthy) or the boolean of whether only even values have been seen. When `a` turns `false` (i.e., an odd number appears), then subsequent runs of the `a = a && ...` logical AND operation short cirucits, and we use `false` for the rest of the run. The bitwise NOT `~v` turns even numbers to odd and vice versa, so `~v%2` returns a truthy value for even input and falsy values for odd input. [Answer] # [SML](https://en.wikipedia.org/wiki/Standard_ML), 44 bytes > > an assignment at my university functional programming course > > > Yay, functional programming! So as an assignment solution, this would probably look like this: ``` (* 'a takeWhile : ('a -> bool) -> 'a list -> 'a list *) fun takeWhile p nil = nil | takeWhile p (x::xr) = if p x then x :: takeWhile p xr else nil (* takeWhileEven : int list -> int list *) val takeWhileEven = takeWhile (fn x => x mod 2 = 0) ``` which can be golfed to ``` fun t[]=[]|t($ :: &)=if$mod 2=0then$ ::t&else[] ``` However using `foldr` is 3 bytes shorter: ``` foldr(fn($,r)=>if$mod 2=0then$ ::r else[])[] ``` [Answer] ## JavaScript (Firefox 30-57), 30 bytes ``` a=>[for(x of a)if(!(a|=x&1))x] ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 13 bytes ``` íä*[13579]¾.* ``` [Try it online!](http://v.tryitonline.net/#code=w63DpCpbMTM1Nzldwr4uKg&input=MTQgNDIgMjMyNCA5NzA5MCA0MDgwNjIyIDE3MTQ4MDM3Mgo0MiAxNCA0MiAyMzI0CjcgMTQgNDIKCjE3MTQ4MDM3MiAxMyAxNCA0Mgo0MiAxNCA0MiA0MyA0MSA0MDgwNjIyIDE3MTQ4MDM3Mg) Explanation: ``` í "search for, on every line ä* "Any number of digits [13579] "Followed by an odd digit ¾ "Then the end of a word, .* "Followed by anything "(implicit) and replace it with nothing. ``` Conveniently, the same code works to verify all test-cases simultaneously. [Answer] # Ruby, 25 bytes ``` ->a{a.take_while &:even?} ``` I think I lose... ]
[Question] [ **The Challenge** Your task is to create a program or function that outputs the following with no input: ``` a bb ccc dddd eeeee ffffff ggggggg hhhhhhhh iiiiiiiii jjjjjjjjjj kkkkkkkkkkk llllllllllll mmmmmmmmmmmmm nnnnnnnnnnnnnn ooooooooooooooo pppppppppppppppp qqqqqqqqqqqqqqqqq rrrrrrrrrrrrrrrrrr sssssssssssssssssss tttttttttttttttttttt uuuuuuuuuuuuuuuuuuuuu vvvvvvvvvvvvvvvvvvvvvv wwwwwwwwwwwwwwwwwwwwwww xxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyy zzzzzzzzzzzzzzzzzzzzzzzzzz ``` You may use the uppercase alphabet instead of lowercase if you prefer. Trailing/leading newlines or spaces are allowed. **Scoring** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` i=1 exec'print chr(i+96)*i;i+=1;'*26 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWkCu1IjVZvaAoM69EITmjSCNT29JMUyvTOlPb1tBaXcvI7P9/AA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` Aƶ ``` **[Try it online!](https://tio.run/##MzBNTDJM/f/f8di2/4d2/wcA "05AB1E – Try It Online")** Note that this outputs as a list of lines, as the OP explicitly allowed. The link uses a version with pretty-print (joined by newlines). ## How it works * `A` yields the lowercase alphabet. * `ƶ` lifts the alphabet (multiplies each element by its index). * `»` joins by newlines. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~12~~ ~~8~~ 5 bytes [SBCS](https://github.com/abrudz/SBCS) *3 bytes saved thanks to @ngn* *4 bytes saved thanks to @Adám* ``` ⍴⍨⌸⎕A ``` OP [clarified](https://codegolf.stackexchange.com/questions/147469/alphabet-staircase#comment360851_147469) uppercase letters are valid, as well as output as an array of strings. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEx61TXzUu@VR74pHPTuAIo7//wMA) **How?** `⌸` gives us every letter in the **`⎕A`** lphabet with its indexes in it, handed into the function `⍴⍨` with the letter as left argument and the index~~es~~ as right argument. `⍴⍨` resha **⍴** es its right argument to the length supplied by its left one. `⍨` switches the left and right (therefore the symbol of it, looking like the face of someone reading this explanation). [Answer] # [Haskell](https://www.haskell.org/), 27 bytes ``` [c<$['a'..c]|c<-['a'..'z']] ``` [Try it online!](https://tio.run/##y0gszk7NyflfbBvzPzrZRiVaPVFdTy85tibZRhfCVq9Sj439n5uYmadgq5CbWOCrUFBaElxS5JOnUPz/X3JaTmJ68X/d5IICAA "Haskell – Try It Online") Returns a list of lines. (Thanks to @totallyhuman for pointing out that this is now allowed) **Explanation:** ``` c<-['a'..'z'] -- for each character c from 'a' to 'z' [ |c<-['a'..'z']] -- build the list of [ ['a'..c]|c<-['a'..'z']] -- the lists from 'a' to c, e.g. "abcd" for c='d' [c<$['a'..c]|c<-['a'..'z']] -- with each element replaced by c itself, e.g. "dddd" ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~32~~ 30 bytes -2 bytes thanks to @EricDuminil. ``` 27.times{|n|puts (n+96).chr*n} ``` [Try it online!](https://tio.run/##KypNqvz/38hcryQzN7W4uiavpqC0pFhBI0/b0kxTLzmjSCuv9v9/AA "Ruby – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 74 bytes ``` ++++++++[>+>+++>++++++++++++<<<-]>++>++>+>+<<[->>[->+<<.>]>[-<+>]<+<+<<.>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwqi7bTtgJSdNhKwsbHRjbUDC4JkbWyide3sgBjI0rOLBbJstO1ibbRtIPz//wE "brainfuck – Try It Online") ## Explanation ``` ++++++++[>+>+++>++++++++++++<<<-]>++>++>+>+ TAPE: 000 010 C_NEWLINE 026 V_ITERCOUNT 097 V_ALPHA >001< V_PRINTCOUNT 000 T_PRINTCOUNT V_ITERCOUNT TIMES: <<[- V_PRINTCOUNT TIMES: >>[- INC T_PRINTCOUNT >+ OUTPUT V_ALPHA <<. >] RESTORE V_PRINTCOUNT >[-<+>] INC V_PRINTCOUNT <+ INC V_ALPHA <+ OUTPUT C_NEWLINE <<. >] ``` [Try it online!](https://tio.run/##jVBBCsIwELznFXsPlehBUZaFUgIGNC11q4dSRAVBBA@C76/ZWksrCs6hm84sM5Mc74fL7fw4XetatyhJUxike0DEqKKGFFVxnNmFAjDGyHdsACDZe7tbOW@FmUwDs907tnmSFp6Fm88aLl5ly1gBGTNG@c9y57lbMmLFfVL1bIDd2m4W0ACxjMJQaujS3yEqIyUH55OBK7QId5GRFpwV/C4HHRBHCn6CKsnO7YbT3A47iFpGqMPKK3z7JRx1J37kvsW2V/e0//Siqq6f "brainfuck – Try It Online") [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 27 bytes ``` 1+:0\::'`j'@+\k:$$>:#,_$a, ``` where `` is a substitution character (ASCII 26) [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/31DbyiDGykpdKiFL3UE7JttKRcXOSlknXiVR5/9/AA "Befunge-98 (FBBI) – Try It Online") Uses uppercase letters, and has a trailing newline. ### Explanation The code works by storing a counter (0 initially), and on every loop: * `1+` - Increments it by 1 * `:0\::` - Pushes things so that the stack looks like this: `bottom [N, 0, N, N, N] top` * `'`j'@` - Checks if the counter is greater than 26 + `j'@` - If it is, we jump over the `'` and exit using `@` + `j'@` - If it isn't, we execute the `'`, which pushes the ASCII value of `@` to the stack Now the stack looks like this: `bottom [N, 0, N, N, 64] top` * `+\` - Adds, then switches the top 2: `bottom [N, 0, (N+64), N] top` The first time through, this is ASCII 65, or `A` * `k:` - Duplicates the second from the top `(N+1)` times - now there are `(N+2)` values of `(N+64)` on the stack (plus the `N` and `0` from earlier) * `$$` - Throw away the top 2 values - now there are only `N` values of `(N+64)` * `>:#,_` - Prints each top value until it gets to a `0` - this means `N` copies of `(N+64)` get printed * `$` - Throws away the `0` - Now the stack is just `N` * `a,` - Prints an enter And it repeats --- I like how I used the `@` both for ending the program and for adding to the counter. [Answer] # JavaScript (ES6), 54 bytes ``` f=(n=9)=>++n<36?n.toString(36).repeat(n-9)+` `+f(n):'' O.innerText = f() ``` ``` <pre id=O></pre> ``` [Answer] **Excel VBA, 38 bytes** Using Immediate Window. :) ``` [A1:A26]="=REPT(CHAR(96+ROW()),ROW())" ``` [Answer] ## BASH, ~~59 54~~ 40 bytes ``` for l in {a..z};{ a+=a echo ${a//a/$l} } ``` [Try it online!](https://tio.run/##S0oszvj/Py2/SCFHITNPoTpRT6@q1rqaK1HbNpErNTkjX0GlOlFfP1FfJaeWq/b/fwA) thx. 5 bytes to @Justin Mariner [Answer] # Ruby, 38 bytes Returns an Array of strings ``` ->{(a=*?a..?z).map{|x|x*-~a.index(x)}} ``` *-5 bytes thanks to totallyhuman* \*-11 bytes thanks to some excellent golfing by Jordan. [Answer] # [V](https://github.com/DJMcMayhem/V), 9 bytes ``` ¬az\ÓÎÛäl ``` [Try it online!](https://tio.run/##K/v//9CaxKqYw5MP9x2efXhJzv//AA "V – Try It Online") Hexdump: ``` 00000000: ac61 7a5c d3ce dbe4 6c .az\....l ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` 2Y2"@X@Y" ``` [**Try it online!**](https://tio.run/##y00syfn/3yjSSMkhwiFS6f9/AA "MATL – Try It Online") ### Explanation ``` 2Y2 % Push string 'abc...z' " % For char in that string each @ % Push current char X@ % Push iteration index (1-based) Y" % Run-length decoding: repeat char that many times % Implicit end. Implicit display ``` [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` for k in range(27):print(chr(k+96)*k) ``` Prints a leading newline (which is allowed). [**Try it online!**](https://tio.run/##K6gsycjPM/7/Py2/SCFbITNPoSgxLz1Vw8hc06qgKDOvRCM5o0gjW9vSTFMrW/P/fwA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly) sneaky Python implementation abuse -1 byte thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) (outputting a list of lines has been allowed; as, now, has writing a function rather than a program) ``` Øa×J ``` A niladic link that returns a list of strings, the lines (to print it with the newlines as a full program [just add `Y` back in](https://tio.run/##y0rNyan8///wjMTD070i//8HAA "Jelly – Try It Online")). **[Try it online!](https://tio.run/##ARYA6f9qZWxsef//w5hhw5dK/8KixZLhuZj/ "Jelly – Try It Online")** (the footer calls the link as a nilad (`¢`) and gets the Python representation of the result (`ŒṘ`) for clarity as the default full-program behaviour would smash the result together like `abbccc...`) ### How? ``` Øa×J - main link: no arguments Øa - yield the alphabet = ['a','b','c',...,'z'] J - range of length = [1,2,3,...,26] × - multiplication = ["a","bb","ccc",...,"zzzzzzzzzzzzzzzzzzzzzzzzzz"] - (Python multiplication lengthens chars to strings - not usually a Jelly thing) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` 2Y2t!g*!YRc ``` [Try it online!](https://tio.run/##y00syfn/3yjSqEQxXUsxMij5v6pjTnG@gqGhQlJlSWoxFxdQTrGkTlEbKAdm5xiZRShFBv0HAA "MATL – Try It Online") Uses broadcast multiplication with ones to get a big square 26x26 matrix of the desired letters. Next, the lower triangular part is taken, and implicitly printed. Also 11 bytes: ``` 2Y2!t~!+YRc % Using broadcast addition with zeroes 2Y2!l26X"YR % Using 'repmat' ``` [Answer] # Javascript, ~~87 bytes~~, 72 bytes (A lot of thank to @steenbergh) My first answer too: ``` for(i=1,j=97;j<123;){console.log(String.fromCharCode(j++).repeat(i++))}; ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~9~~ 7 bytes Outputs an array of lines ``` ;C¬Ëp°E ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=O0Osy3CwRQ==&input=LVI=) --- ## Explanation Split (`¬`) the lowercase alphabet (`;C`) to an array of characters, map over the array (`Ë`) and repeat (`p`) the current element by the current index (`E`) incremented (`°`) times. [Answer] # [Pip](https://github.com/dloscutoff/pip), 9 bytes ``` FczPcX++i ``` [Try it online!](https://tio.run/##K8gs@P/fLbkqIDlCWzvz/38A "Pip – Try It Online") In pseudocode, this is ``` For-each c in z Print (c string-multiply ++i) ``` where `z` is preset to the lowercase alphabet and `i` is preset to 0. --- Map-based solutions take one extra byte because they need the `-n` flag to display on multiple lines: ``` {aX++i}Mz B X_+1MEz ``` [Answer] # [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 66 bytes ``` Count i while 26-i { Count j while i+1-j { Write 97+i } Write 10 } ``` [Try it online!](https://tio.run/##S0xOTkr6/985vzSvRCFToTwjMydVwchMN1OhmgsimAUVzNQ21M0CioYXZZakKliaa2dy1UI5hgZctf//AwA "Acc!! – Try It Online") ### With comments ``` # Loop i from 0 to 25 Count i while 26-i { # Loop j from 0 to i (inclusive) Count j while i+1-j { # Print a letter Write 97+i } # Print a newline Write 10 } ``` [Answer] # [Haskell](https://www.haskell.org/), 31 bytes *-12 bytes thanks to nimi.* ``` zipWith replicate[1..26]['a'..] ``` [Try it online!](https://tio.run/##BcExDoAgDADAr3QwYZJEBzde4eCgDg0BbaykkbL4eOvdifVKzJbDZi/JQnrCk4QpoqZ18H6c9tWh8363G6lAAGk66wMdtMJUUoVsX8yMR7U@ivw "Haskell – Try It Online") This is not a snippet, it is a *nullary function* (one that takes no arguments) that outputs a list of lines which is allowed because of [this meta consensus](https://codegolf.meta.stackexchange.com/a/12945/68615). [Answer] # [R](https://www.r-project.org/), 38 bytes A relatively uninteresting answer. Iterate for `i` from 1 to 26, print the `i`th letter of the alphabet `i` times (with an implicit line break). ``` for(i in 1:26)print(rep(letters[i],i)) ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdDKyEyzoCgzr0SjKLVAIye1pCS1qDg6M1YnU1Pz/38A "R – Try It Online") A more interesting approach might be to use something like the following: ``` cat(letters[(1:351*2)^.5+.5]) ``` This gives us all the letters in the right amount, but no linebreaks. Perhaps someone smarter than me can figure out a way to use that to make a golfier answer. [Answer] # [Perl 5](https://www.perl.org/), 19 bytes ``` say$_ x++$"for a..z ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIlXqFCW1tFKS2/SCFRT6/q//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 82 bytes ``` ||for i in 1..27u8{println!("{}",((i+96) as char).to_string().repeat(i as usize))} ``` I had hoped that it would've been a lot shorter, but explicitly converting/casting between types takes a lot of bytes :( [Try it online!](https://tio.run/##Lc3LCsIwEEbhfZ/it6sZlIAuvFB8Fgkl1YGYlkmyMc2zxwquz4FPc0xtCnhbCcQoHeBdwujnmNXhjrau06wQSMDRmNMlX8uiEpIPO@pL7Q9Esr@dGTZifFllk@ZHTNvyJDbqFmcTya/mKB/HXBswbM7fIB662r4 "Rust – Try It Online") [Answer] # PHP, ~~47~~ 46 bytes ``` for($c=a;$i<26;)echo" ",str_pad($c,++$i,$c++); ``` or ``` for($c=a;$i<26;)echo str_pad(" ",++$i+1,$c++); ``` Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/31a9cb0fc1a67c88d9942b25365a5a78a9564535). [Answer] # [J](http://jsoftware.com/), 18 17 bytes ``` a.{~(#"0+&96)i.27 ``` Explanation: ``` i.27 - list of integers 0 - 26 ( +&96) - adds 96 to the above list (starting offset of 'a') #"0 - copies the right argument left argument times {~ - select items from a list (arguments reversed) a. - the whole alphabet #"0 +&96 is a hook, which means that at first +96 is applied to the list i.27, resulting in a list 96, 97, 98... 122, then #"0 is applied to this result. So it is evaluated as ((i.27)#"0(96+i.27)){a: ``` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/xP1qus0lJUMtNUszTQz9YzM/2tyKekpqKfZWqkr6CjUWimkFXOlJmfkK6T9BwA "J – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~24~~ 23 bytes ``` .say for 'a'..'z'Zx 1..* ``` [Try it](https://tio.run/##K0gtyjH7/1@vOLFSIS2/SEE9UV1PT71KPapCwVBPT@v/fwA "Perl 6 – Try It Online") ``` .say for 'a'..*Zx 1..26 ``` [Try it](https://tio.run/##K0gtyjH7/1@vOLFSIS2/SEE9UV1PTyuqQsFQT88IKAEA "Perl 6 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~25~~ 24 bytes ``` ['',tril((x=65:90)'+~x)] ``` [Try it online!](https://tio.run/##y08uSSxL/f8/Wl1dp6QoM0dDo8LWzNTK0kBTXbuuQjP2/38A "Octave – Try It Online") Saved one byte thanks to Giuseppe who informed me that OP allows upper case letters. ### Explanation: Create a vector `x` with the ASCII-values of the upper case alphabet, and transpose it. Add the negated `x` (thus 26 zeros, in a row vector, in order to create a grid with (the ASCII-values of): ``` AAAA BBBB CCCC ``` Take the lower triangular matrix and convert to characters by concatenating with the empty string. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~48 bytes~~ 50 bytes Re-runnable version, as per cleblanc and Steadybox in the comments below. ``` s[9];main(i){for(;i<27;)puts(memset(s,i+95,i++));} ``` [Try it online!](https://tio.run/##S9ZNT07@/7842jLWOjcxM08jU7M6Lb9IwzrTxsjcWrOgtKRYIzc1tzi1RKNYJ1Pb0hRIaGtqWtf@/w8A "C (gcc) – Try It Online") [Answer] # Japt, ~~17~~ ~~16~~ 11 bytes -5 bytes thanks to Oliver In ISO-8859-1 ``` ;26ÆCgX pXÄ ``` Not the best score, but I'm still a novice. Any suggestions are very welcome. Outputs list of lines, as OP allowed. Link contains 3 bytes more for newlines. [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=OzI2xkNnWCBwWMR9ILc=&input=) ``` ; - Use string variables 26 - Literal 26 Æ - For range 0..26 C - Alphabet gX - . character at index X pXÄ - Duplicate X+1 times - End function (implicit) ``` ]
[Question] [ Input a non-empty array with \$n\$ positive integers. Test if the input array contains every integer in \$1\cdots n\$. In case you prefer 0-indexed numbers, you may choose to input an array of non-negative integers, and test if the input array contains every integer in \$0\cdots (n-1)\$ instead. All testcases and formula listed below use 1-index. You may need to adjust them if you choose this option. ## Input / Output Input is an array \$A\$ with \$n\$ positive integers: $$ A = \left[A\_1,\dots,A\_n\right] $$ $$ \forall i \in \left[1,\dots,n\right]: A\_i>0 $$ Output if input \$A\$ satisfies: $$ \forall i \in \left[1,\dots,n\right]: i \in A $$ Output would be two distinct values, or truthy vs falsy values (swap meaning of truthy / falsy is allowed). ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins. And since this is code-golf, don't worry about time / memory complexity of your code. You may even timeout on TIO as long as your program works when giving it more time to run. ## Testcases ### Truthy ``` 1 1,2 2,1 1,3,2 3,1,2 1,2,3,4,5,6,7,8,9,10,11,12 12,11,10,9,8,7,6,5,4,3,2,1 6,3,8,12,1,10,4,2,7,9,5,11 16,37,14,15,23,8,29,35,21,6,5,34,38,9,36,26,24,32,28,7,20,33,39,12,30,27,40,22,11,41,42,1,10,19,2,25,17,13,3,18,31,4 ``` ### Falsy ``` 2 12 1,1 1,3 2,3 3,3 2,1,3,2 1,4,3,1 4,1,2,4 1,2,2,5,5 1,3,3,3,5 8,7,5,3,4,1,6 5,7,1,4,6,1,8,3 6,3,5,4,7,1,8,1,2 6,5,3,8,2,7,9,4 1,1,1,1,1,1,1,1 1,5,9,13,11,7,3 14,6,12,4,10,8,16,2 34,33,38,17,35,11,36,31,28,14,6,15,18,2,19,40,29,41,9,1,27,23,20,32,26,25,37,8,13,30,39,7,5,3,21,4,11,16,10,22,12,24 38,27,20,23,31,6,2,24,21,31,33,7,26,12,14,17,3,2,28,31,5,23,28,27,37,32,7,39,22,6,35,42,19,3,35,17,35,40,22,13,27,7 ``` [Answer] # [Risky](https://github.com/Radvylf/risky), ~~7 bytes~~ 7 bytes and a palindrome ``` 1_??!0:0!??_1 ``` [Try it online!](https://radvylf.github.io/risky?p=WyIxXz8_ITA6MCE_P18xIiwiW1s2LDMsOCwwLDEsMTAsNCwyLDcsOSw1LDExXV0iLDBd) ## Explanation ``` 1 sort _ ? input ? filter by ! factorial 0 0 : = 0 range ! length ? input ? find first number such that _ 1 1 ``` [Answer] # [J](http://jsoftware.com/), 7 bytes ``` -:/:@/: ``` [Try it online!](https://tio.run/##VVHLasNADLznK0wvoSAnXmkf9tJCoNBTT/2IBPr/d2dm1jmUOItWK81oRn/722U636fPPp1tWqaO/3yZvn5/vve5X/vt2vf304Pv91v/6PtjsoR7MsfpRxy6hY0sTmSyFavWbLXN0mIpWdKjK1yQXfFaUZXZL6SKaDWWsCIj21BX0MFOvDZL2VIxZ51vFgiTQAIopIpqjg83NyeDLxZhsRE2FvNmGaemyPgOrrSBzMEEBlRbWi3weprnGdSSdcz/kiz5IdkjftmQJIhVmYYAZFjimLIg5lBFBmFy3Avu7Kk4V2HRBtrSlBmmSiNFy5KB@e@nTKHZQW1NSEmwTq6FUHUsKsuSlWqD7tI1yIVfo6FQv9MUerXRqI1zNBpPQ10mFy5klWELHR66nGK440pSOo1qDgxC1z4AEtwa8yzHBfM0YnL3WXOZ9hfURFL1gi5oALiAWzl81pghHVJzbDdY354 "J – Try It Online") Ninja'd by hyper-neutrino :( Takes zero-based input. Applying Grade Up twice to a vector gives a "ranking" of each element, so that 0 is the smallest, 1 is the next smallest, ... up to n-1, breaking ties by giving a smaller number to the one appearing first. A vector is a permutation if and only if the ranking is identical to itself. # [J](http://jsoftware.com/), 7 bytes ``` 2|C.!.2 ``` [Try it online!](https://tio.run/##VVHLasRADLv3K9JeloITMva8ElooLPTUUz9iF/oN/fdU0mQPZbODx2NLlvxzvCzT5Ta979PFpnXa8Z@X6fr99Xn473V5Xvx4fbrz/faxv@3HfbKEezLH6WccuoWNLE5kshWr1qzbZmm1lCzp0RWuyHa8VlRl9gupIurGElZkZBvqCjrYiddmKVsq5qzzzQJhEkgAhVRRzfHh5uZk8NUiLDbCxmreLOPUFBnfyZU2kDmYwIBqS90Cr0/zPINass75H5IlPyR7xA8bkgSxKtMQgAxLHFMWxByqyCBMjnvBnT0VZxcWbaAtTZlhqjRStCwZmP9@yhSaHdTWhJQE6@RaCVXHorIs6VQbdJeuQS78Gg2F@p2m0KuNRm2co9F4GuoyuXAhXYatdHjocorhjitJ6TSqOTAIXfsASHBrzLMcF8zTiMndZ81l2l9QE0nVC7qgAeACbuXwWWOGdEjNud1gffsD "J – Try It Online") Takes zero-based input. `C.!.2` is a built-in for "cycle parity". It gives 1 if a permutation has even number of swaps, -1 if odd, and 0 if not a valid permutation. I take it modulo 2 to convert all nonzero results to 1 (the only truthy value in J). ~~Even if [error/non-error output](https://codegolf.meta.stackexchange.com/a/11908/78410) were allowed, it is too bad that permutation-related built-ins `A.` and `C.` don't error on all possible non-permutations.~~ # [J](http://jsoftware.com/), 7 bytes ``` #\-:/:~ ``` [Try it online!](https://tio.run/##VVG7bgMxDNvzFUY7BAV0qS35cXdApwKdOnXunAD9iP76laSTocjFkGWJFKmf4@mSztf0tqezpZx2/JdLev/6/Diev5f9df89Xk43vl@PW7KCuJjj9HscuoXNLE5kqjXrNmy1zUq2Uqzo0RVmZFe8dlRV9gupI1qNJayoyA7UNXSwE6/DSrXSzFnnmwXCIpAACqmim@PDzc3J4NkiLDbCRjYfVnFqiorvzlU2kDmYwIBqK6sFXk/LsoBasu7zPyRLfkj2jB82FAliVaUhAJmWOKZsiDlUk0GYHPeGO3s6zlVYtIG2DGWmqdJI0bJkYv77KdNodlDbEFIRrJMrE6rPRVVZslJt0F26BrnwazY06neaQq82GrVxjkHjaajL5MaFrDIs0@GpyymGO@4kpdOo5sAgdO0DIMGtMc9yXDDPICZ3XzWXaX9BTSRVL@iCBoALuJ3DV40Z0iE19@0G68cf "J – Try It Online") Takes one-based input. `#\` is a golfing trick for getting 1..n, which is compared to the sorted array `/:~` of the original. --- If output by erroring/non-erroring is allowed: # [J](http://jsoftware.com/), 3 bytes ``` C.~ ``` [Try it online!](https://tio.run/##VVHLasNADLznK0wvoSAbr7QvmxYKgZ566kck0I/or7szs86hxFm0WmlGM/o5Xpbpep/e9@lq0zrt@M/LdPv@@jxuy@/xennw7f6xv@3HY7KEezLH6WccuoWNLE5kshWr1qzbZmm1lCzp0RWuyHa8VlRl9gupIurGElZkZBvqCjrYiddmKVsq5qzzzQJhEkgAhVRRzfHh5uZk8NUiLDbCxmreLOPUFBnfyZU2kDmYwIBqS90Cr5d5nkEtWef8T8mSH5I94qcNSYJYlWkIQIYljikLYg5VZBAmx73gzp6KswuLNtCWpswwVRopWpYMzH8/ZQrNDmprQkqCdXKthKpjUVmWdKoNukvXIBd@jYZC/U5T6NVGozbO0Wg8DXWZXLiQLsNWOjx0OcVwx5WkdBrVHBiErn0AJLg15lmOC@ZpxOTus@Yy7S@oiaTqBV3QAHABt3L4rDFDOqTm3G6wvv0B "J – Try It Online") Takes zero-based input. Abuses dyadic form of `C.`, whose left argument must strictly be a permutation. It throws an `index error` otherwise. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 bytes ``` ⊢≡⍋∘⍋ ``` [Try it online!](https://tio.run/##VZJNSgNBEIX3OUVdQJiu6r9Zu9Gt8QIBiZuAbl0LQRMSdCG41Qu48QQepS8yvlc9ESRDU11df@@rrO43ZzcPq83d7TS13Wd7/miHfXt6xzmt2/alHY5t9/jzZW372o5vy6tznNcXl8tpLUHa4VvCgpbi1Nk2v9nsxQk7SpIsRaqMEgYJQYI/qpsDvBWvGVGR@V4pw6oewogIb0FcQgYz8VokRAlJlHE6isEMXsRQha0si@LDTUXZQQcxExtZ1gbRIhGnTxHxzb3CiGaKTuhgVFLF8Lo4adY/q6s4CXcI5uK7fYIRXBajogOJMxjFrAk2R0uOCfPjnnBnTsZZvRZhEE5xT0frSindwfSa/37uSURuVFi8UvCyyl4DS@W@ruhgKjUbGZMdRINaT0ikoERDYiNxjZyjED@xqqNOXEt1bAM5d11KMdx0ZlPyRjQHRkP1raCIcXf0MxwXzFNYk/@A6HOJb9GoiU09F@2MANALdTOHjz6muQ5XM@/YGF9@AQ "APL (Dyalog Unicode) – Try It Online") -4 bytes thanks to Bubbler by turning this into a train and via using `⍵≡` to match the whole array instead of `∧/⍵=` to match element-wise and then reduce by AND. ``` ⊢≡⍋∘⍋ Train ≡ Check equality between ⊢ (Right argument ⍵) and ⍋∘⍋ Composed function {⍋⍋⍵}; grade up twice ``` Grading up twice gives the minimum permutation of length X that has the same (non-strict) ordering as the original - so, if the permutation of the right order is the same as the original, then the original was that permutation and thus a permutation. [Answer] # [Haskell](https://www.haskell.org/) (1 indexed), 29 bytes *Courtesy of AZTECCO* ``` g l=all(`elem`l)[1..length l] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P10hxzYxJ0cjITUnNTchRzPaUE8vJzUvvSRDISf2fxpQNl0lN7FAI6ZC165C21Azhys3MTPPNiWfS0GhoCgzr0QlLdowFpmjY4DMNdAx0jHWMdExRBU0BEKgBLpKDHUm2ASNsQlDrDGN/Q8A "Haskell – Try It Online") # Haskell (0 indexed), ~~42~~ ~~32~~ 31 bytes *Lynn saved one byte with the pointfree solution.* ``` all.(.fst).flip elem<*>zip[0..] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802MSdHT0MvrbhEUy8tJ7NAITUnNddGy64qsyDaQE8v9n9uYmaebUo@l4JCQVFmXolKWrRBLBLHUAeFa6BjpGOsY6JjiCpoCIRACXSVGOpMsAkaYxOGWGMa@x8A "Haskell – Try It Online") I tried a bunch of creative stuff with scans, folds and zips, but the boring solution ended up being the shortest. Both of these check that every integer in the available range is in the list. The first is `1` to the length of the list, the second is `0` to 1 less than the length of the list. [Answer] # [Python 3](https://docs.python.org/3/), 31 bytes Input is \$ 0 \$-indexed. ``` lambda a:{*a}=={*range(len(a))} ``` [Try it online!](https://tio.run/##VVFBbtswELzzFbxFCraFlkuKUgC/JO1BRe1GgKIIjoomCPJ2d2adHALLJJcczuwMt9f94Wm1y@nw47JMj79@T3G6e7ud3g@Ht9vztP45Nstxbaa2fb/8e5iXY9S7EOd1i4e4zM978zhtzbzuwr2/e9N@f96WeW9u5KZt20/k/Uv8FjWens7xBVvc/RnidsbF5oTrW9teNKikkISzYWXCGn9UWYr0UmWQUbQTVVEcJV902Btw1gOTeRMMPeZBCOB5xl4FqgAfFGdVNIsWSUSlUQxLdQIDA0Wsl4QPVZJE9tSJmdhIUuskVckYvYOM70NJR0gl6EABaNFBDKeBzcKKW4NFgznOV6PqbWvINAwwx4ReSqBwcfvoLhRUxPYYwesmabl6zbDcAS25XTJ9@aEuDNDYdQWDOlkif0eKnrFnNzrQgzExZgETSOEKL3SVaJUJjLQ/Ur0yTsaUPLrCmAePoWNuVyeJBvhqPSWZH9A5QC55xqAwvgR3CUaBbioZ@ZrZuxJ/E6MbSvpdiBltQwmsPVvP3qS5C/fy8WJGfP0P "Python 3 – Try It Online") This is the most obvious implementation I could think of. It compares the set of \$ a \$ to the set of numbers from `0` to `len(a)-1`. # [Python 3](https://docs.python.org/3/), 30 bytes As [@ovs](https://codegolf.stackexchange.com/users/64121/ovs) suggested, we can save a byte by switching the definition of truthy and falsey. A valid permutation returns a falsey value, and truthy otherwise. ``` lambda a:{*a}^{*range(len(a))} ``` [Try it online!](https://tio.run/##VVHRTtwwEHz3V/iNBC0o67XjBIkvaamUqnclUgjREVQqxLcfM3v0obqc7bXHMzvj7e/@@Lza@Xj//bxMTz9/TXG6e7@ePn68X5@m9fehWQ5rM7Xtx/nP47wcot6FOK9bvI/L/LI3T9PWzOsu3Hvdm/b2ZVvmvbmSq7Zt/yG/vcWbqPH4fIpv2OLuQ4jbCRebI65vbXvWoJJCEs6GlQlr/FFlKdJLlUFG0U5URXGUfNFhb8BZD0zmTTD0mAchgOcZexWoAnxQnFXRLFokEZVGMSzVCQwMFLFeEj5USRLZUydmYiNJrZNUJWP0DjK@LyUdIZWgAwWgRQcxnAY2CytuDRYN5jhfjKq3rSHTMMAcE3opgcLF7aO7UFAR22MEr5uk5eo1w3IHtOR2yfTfD3VhgMauKxjUyRL5O1L0jD270YEejIkxC5hAChd4oatEq0xgpP2R6pVxMqbk0RXGPHgMHXO7OEk0wFfrKcn8gM4BcskzBoXxJbhLMAp0U8nI18zelfibGN1Q0u9CzGgbSmDt2Xr2Js1duJevFzPi6yc "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 30 bytes Expects 0-indexed values. Returns a Boolean value. ``` a=>a.every(x=>(a[~x]^=1)/a[x]) ``` [Try it online!](https://tio.run/##VVHLbtswELzzK4RcJAIbVXzp0cLuqf2BHNMUEBw5VeFKruQGDor2192ZtS@FJFJLDmd2ht/7137dLePxdD/Nz8Nlv7n0m21fDq/D8lacN9uif/x7fvq6cfZd/3h@spdl@PlrXIYi36@5LZehf/48HoaHt2lXVLY8zQ@nZZxeCluux8N4Ku6@THe23M/Lp373rVizzTb7bbJsN0/rfBjKw/yCxY/ZvlhvB3IB7Y/@WEzETtl95qzN3md5bj@YP/bijBNvvHAO@AvCGh@qKElqaaSVTlwlzonDltefCmst9mpgIk@CocbcCgHcj1hrgErAG4e9RlwUl8QT5TsJ@HVKEMBAkVCLx4vKiye7ryQECR1JQyW@kYhRO4h4b0qug5SHDhSAFtdKwK4x7BZe1Bs8BrjjfHXqtG9nIh0DzdGjmaRJ8EmGPSRNAo2ahIqnaoyQUL9032jN3NQM3alzcv73oE7MMtBAAwanZJ78FSlq3kBUzy3tBIbHWOAHgVzhiQY9XTOMjkl0VG@YLBPzmmJi4q0mUjHCqxNPA7zAmpKMEuhoIOc1blAEXgpXCUaBbhoy8mKjdiV6PYFuKKlnIRZoG0pgrdl61CaDulAvt8sLxDf/AA "JavaScript (Node.js) – Try It Online") ### Commented We test whether all values are less than the length \$N\$ of the input array and make sure that there is no duplicate. Both conditions are satisfied iff the array consists of all values from \$0\$ to \$N-1\$. ``` a => // a[] = input array a.every(x => // For each value x in a[]: (a[~x] ^= 1) // ~x is -x - 1, which is guaranteed to be negative // Therefore, a[~x] is a property (such as '-1') of // the underlying object of a[], which can be safely // used to store values that were already encountered // If a[~x] XOR 1 is not equal to 1, we have a // duplicate value / a[x] // We also make sure that a[x] is defined, which // means that x < a.length // The possible cases are: // 1 / n, n > 0 is a truthy number \__ success // 1 / 0 is +Infinity (also truthy) / // 1 / undefined is NaN (falsy) \ // 0 / n, n > 0 is 0 (falsy) |_ failed // 0 / 0 is NaN (falsy) | // 0 / undefined is NaN (falsy) / ) // End of every() ``` [Answer] # Julia 1.5, 6 bytes This is a built-in, so it's quite easy for Julia ``` isperm ``` Use it like this: `isperm([6,3,8,12,1,10,4,2,7,9,5,11])` [Answer] # [Zsh](https://www.zsh.org/), ~~18~~ ~~12~~ 11 bytes ``` >$@<{1..$#} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhar7VQcbKoN9fRUlGshIkttbGxU7CHsm-rRZjoKxjoKFjoKhkZADEQGOgomOgpAjrmOgqWOgilQyDAWahoA) Outputs via exit code: 0 for a permutation and 1 for not a permutation Explanation: * `>`: create files called + `$@`: each command-line argument * `{1..$#}`: range from 1 to the number of command-line arguments * `<`: try to read from each of those numbers as a file If any command fails, then that means one of the files in the range didn't exist, so it's not a valid permutation, and zsh will exit with status 1. [Answer] # [R](https://www.r-project.org/), ~~26~~ 24 bytes -2 bytes thanks to pajonk. ``` all(seq(x<-scan())%in%x) ``` [Try it online!](https://tio.run/##VVLRSsNAEHzvVxRByMEKud27XAL66hf42JdSLAoloq1QEb@9zmzSi9KQ5nbndnZn9uOyXz@s95/j7vT6Njbn8H3cbceHGgjr82V7ODTH5/fmfH/HZBPC7et4ew6Xn9Vqtz01N08fn6eXr814E1b7ZtfEMP@Lzl8qS8xq1GRB4AuZJFk6KdLLILGVGCVWgPqxRaYHogMysVat3OHUC2FEJWQKsBm3rhWAKBKTxCxKrA5i@IxezFCNtNaJ4sFJRcmkrZiJDSxtrWiRhLd3k/DMfHEAoYINDEBL7MWQBfUk0WbcjI/bw/F5kmlSpY5WRfgjU5XOqlxL7K@M0YW43kwU1Ymvsiqmy/OZA2UXGlPPsYwYa3R495WDclLi4tHFKNeK4rm8C8@/X41mGmnUqtTK0amUPbQs3S0LkVzqnioanaMbkBE@TJcydVWKTQ8GGjCwt0JDaZS6eZlG925ES@emmZVDcoc6EtNBoK8DgFTdaxQybgRzvIIDeiqsy91K3pv4bhjnI7HfBaVRFPChdscBkrdqPotPNG@OEV9CuPwC "R – Try It Online") If input is of length at least 2, `seq(x)` outputs the integers from 1 to `length(x)`; if input is of length 1, it outputs the integers from 1 to `x`. Return `TRUE` iff all those integers are elements of `x`. [Answer] # [Ruby](https://www.ruby-lang.org/), 21 bytes ``` ->a{a|[*1..a.max]==a} ``` [Try it online!](https://tio.run/##XZDBDoIwEETvfAWJNzMSdrdAOeCPEA41gZMmRiXRqN@Os3Az2TTtdrpvprf59Fqmbjkc0zt9@r0URSou6Tl0Xfou13zqe4HCUCEMQ77LH7d5zLZ@DWsgAVJBDRHawrgV1FRbgEWwU0NZPCk0ooGWMIO1EI4toQ0CV4UIAosbSAlpSdUKQgLVkAjjbfbnwSnmIOrI5gzyKCSJxmq3xpfq45zSOoJkp9KyW9HVXuVR4ooq3VvjCTxK8JlMKptHqrdvmNL5PmbLDw "Ruby – Try It Online") -1 byte thanks to ovs! -3 bytes thanks to Razetime! [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, ~~24~~ 23 bytes ``` [ dup length iota ⊃ ] ``` [Try it online!](https://tio.run/##VVJBTsMwELz3FfsCVO/aTgIPQFy4IE6IQ1UCVEBaSnpAiBM3nslHyswGEqeNImc9nt2Z8f1q3W/3x@uri8vzU3lq9137LC@r/vHk0G3W27tW3trXQ9ut2zfZ7du@f9/tN10vZ4vFx0Lw@5ClfI6rMK7DrK7Fjs5wXKuYREmSpZJaGgkoFkyBhQY7FRAJSHO@iT/huyKOMMNWBjjy1MiRxLIE7EVRgrUWw3I58JkYOxuI8OALM7FZAB2Gq8mtjWgWw9vniXiGhqGmBLQDXjlZJbbEGJMThZJJ9tyeCayFUTqzU2e2mRv5/21upM1sDZAWxwr1RLeaov@rEVVyJbyroh8tpdHZ62VgyVmqP5dtpqj8T/UIHJyBablUxKaBMzdkS0UL5qGMBJaa54hk4CkyGU5FmhzoPPOoGUZNgzLDZWjBg4wMvfJUGqY4GKDUyyuWZAgzMPKxd0UacIDJ6JTv8sySQ2US80Yah2Mi6nH7tVI/i55Gc9AQ7IkKos@qLsYl/V0jJT6j9@fxRu4OO3luu4f@UTbbfiU/319ye3xZ7eTk@As "Factor – Try It Online") 0-indexed to save a byte. Is the input a superset of \$[0..|input|)\$? [Answer] # [Python 3](https://docs.python.org/3/), 33 bytes ``` lambda x:max(*x,len(x))^len({*x}) ``` 1. Check uniqueness: len(x) = len(set(x)) 2. For unique set: max(x) == len(x) iff x = 1...n [Try it online!](https://tio.run/##VVHRasMwEHv3V@RtSTlGfGfHyaB/MgYtW2kgbcOWsYyxb@@ka19GUzvnU6STPH8vx8vZroft83Xanfavu2p9Ou3WerPK9Hau16Z54f6zWX@b69dxnN6q@BSq8TxX22oaP5b6tJvr8bwIzz6Xunn8mKdxqR/koWmaUM3vaNb7y2WqD8DNOLzGEEWDCnfDmwlr/FElydJJkV4Gia3EKBEt9ZcWZz16HTCJX4Khw94LAewnnBWgMvAholckJolZlCgdxPAancDAQBHrRPGgUlGyaytmYgNJrRUtkrD6BAnPXSkOkFLoQAFoib0YuoHDwopbg0WDOe43o9HHjiHRMMBcFbPkQOHs9jFdyKiI7bCC103ScvGaYbkDWnK7ZPr3Q50ZoHHqAoboZEr@lhQdY09utKcHY2LMAiaQwg2e6UpplQkMtD9QvTBOxqQeXWbMvcfQMrebE6UB3lpHSeYHdAqQU88YFMab4CnBKDBNISNvM/lU4ndidENJ/xZiRttQAmvH0ZMPae7CvdxvzIgvfw "Python 3 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 13 bytes ``` : >$@<{1..$#} ``` [Try it online!](https://tio.run/##BcFNCoAgEAbQq3yQhAZKY/85WJcR2rTJVolnn9778iXaFP3c6EJOL2ySHVGdXMg51VQxPrY2MLM6KmYMWEEeBOoxwmPBhglE8gM "Zsh – Try It Online") ``` : noop command to prevent hanging while waiting for input >$@ create a file for every argument <{1..$#} read every file between 1 and the number of arguments ``` Since the redirects are handled left-to-right, we create the files before trying to read them. If we encounter a number for which no file exists (for example on `zsh x.zsh 4 1 2`), we get the following error: `no such file or directory: 3` and receive exit code 1. If it was indeed a permutation, we exit cleanly with code 0. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` Ṣ⁼J ``` [Try it online!](https://tio.run/##VVK7VQQxEMtdxj5CBZ4Z/7YFCqADEt41QAgJfRATkvAgo5K7RhZp7hLe7dkeWyuN5H16PJ2ej@P89X55@bk/zt@fD79vd5fXj@PYts2KwYtDc3AVUM0/q4aOgYmFHVZhBuOR56Jyb/FsENP0JhkG5wUBdN64N4nqxBfj2YQ1WIcL5TuCS0uCIINEYsD5sHK42L0iArGLNCp8onHMDhqfm5LtlHLqUIFo2ELwtKhZWklrtBg0p/lq1LJtK02GCdbo7KUXCfe0z@5KZyXs4EjeNCnLM2uFlQ5kKe2K6d@PdVeAoa4nGSzJXPxVFEOxtzS65CGUmLKgCaZwhXe5cllVArvs71KfilMxeUbXFfPKGKpyuzpxGdCtDUkqP6JboZxnxqQI3YR2BWbBbqYYdZstu0LeSciNJPNdioVsU4msQ623bDLSRXq53VgIP/nF/QE "Jelly – Try It Online") ``` Ṣ⁼J Monadic Link Ṣ 1-chain: sort the input ⁼J 2,1-chain: is (the input sorted) equal to (range on the length of the input)? ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` o~⟦ ``` [Try it online!](https://tio.run/##bVJLSgNBEL1KM@uJTFd3z2ejBwlZRPGzCASiEiRGMILozhu4060Iblx6k8xFxqp61TELYYburu@r9@p4MT25uJnNz2kY9Zv77dfLz@dqWbjRoSuWR6v@8aPfPPRP78XV4vr0oLiV69l0dsn39fb7ec0Jw/yuf30bhvHYT0o39qUjOal0@R3MxGf2yqmOWLpUurp0Tena0nUcUvHPfo9AslelzlYDa02KqGx9an21kqdtJCGqu9HMJHW0okSyzbPXs5WQRhwT5Olz/SANgCmwheQXE5ck4CDuETg9dGgb@E1sj3Ia8Cj/HyTfKSYSOAIiKGzP9YIEKnOY22jakWikBmMyv/f49ZkTzYlg24riSjpYEgMmSFkEmVrMSc2oVOultV4gGLw32ZP1rHOpdo/y3PifzzwJigdQ1Vgnb70JyCp0qvMWRSO9BYUhIVs0Eg5Fm1whgVoC7ypLB0k6YG@gvwpJpnHCfrSmTgV9d2QRyNGlrAFPtZZ0nViAkW2HFA/YKML6SLpYZIQGHXVjo02DQNsHW0@yigIrgF6BJG1rEBBtxGB8GC@7RQwo0Ewmvw "Brachylog – Try It Online") 0-indexed. Succeeds or fails. ``` o The input sorted ~⟦ is the range from 0 to something inclusive. ``` Note that this can not be golfed to `⟦p` with reversed input, as it fails to terminate for cases it should reject: ``` ⟦ Choose an integer. Is the range from 0 to it inclusive p a permutation of the input? ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` UIS ``` [Try it online!](http://pythtemp.herokuapp.com/?code=UIS&test_suite=1&test_suite_input=%5B0%5D%0A%0A%5B0%2C+1%5D%0A%0A%5B1%2C+0%5D%0A%0A%5B0%2C+2%2C+1%5D%0A%0A%5B2%2C+0%2C+1%5D%0A%0A%5B0%2C+1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%5D%0A%0A%5B11%2C+10%2C+9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%2C+0%5D%0A%0A%5B5%2C+2%2C+7%2C+11%2C+0%2C+9%2C+3%2C+1%2C+6%2C+8%2C+4%2C+10%5D%0A%0A%5B15%2C+36%2C+13%2C+14%2C+22%2C+7%2C+28%2C+34%2C+20%2C+5%2C+4%2C+33%2C+37%2C+8%2C+35%2C+25%2C+23%2C+31%2C+27%2C+6%2C+19%2C+32%2C+38%2C+11%2C+29%2C+26%2C+39%2C+21%2C+10%2C+40%2C+41%2C+0%2C+9%2C+18%2C+1%2C+24%2C+16%2C+12%2C+2%2C+17%2C+30%2C+3%5D%0A%0A%5B1%5D%0A%0A%5B11%5D%0A%0A%5B0%2C+0%5D%0A%0A%5B0%2C+2%5D%0A%0A%5B1%2C+2%5D%0A%0A%5B2%2C+2%5D%0A%0A%5B1%2C+0%2C+2%2C+1%5D%0A%0A%5B0%2C+3%2C+2%2C+0%5D%0A%0A%5B3%2C+0%2C+1%2C+3%5D%0A%0A%5B0%2C+1%2C+1%2C+4%2C+4%5D%0A%0A%5B0%2C+2%2C+2%2C+2%2C+4%5D%0A%0A%5B7%2C+6%2C+4%2C+2%2C+3%2C+0%2C+5%5D%0A%0A%5B4%2C+6%2C+0%2C+3%2C+5%2C+0%2C+7%2C+2%5D%0A%0A%5B5%2C+2%2C+4%2C+3%2C+6%2C+0%2C+7%2C+0%2C+1%5D%0A%0A%5B5%2C+4%2C+2%2C+7%2C+1%2C+6%2C+8%2C+3%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%0A%5B0%2C+4%2C+8%2C+12%2C+10%2C+6%2C+2%5D%0A%0A%5B13%2C+5%2C+11%2C+3%2C+9%2C+7%2C+15%2C+1%5D%0A%0A%5B33%2C+32%2C+37%2C+16%2C+34%2C+10%2C+35%2C+30%2C+27%2C+13%2C+5%2C+14%2C+17%2C+1%2C+18%2C+39%2C+28%2C+40%2C+8%2C+0%2C+26%2C+22%2C+19%2C+31%2C+25%2C+24%2C+36%2C+7%2C+12%2C+29%2C+38%2C+6%2C+4%2C+2%2C+20%2C+3%2C+10%2C+15%2C+9%2C+21%2C+11%2C+23%5D%0A%0A%5B37%2C+26%2C+19%2C+22%2C+30%2C+5%2C+1%2C+23%2C+20%2C+30%2C+32%2C+6%2C+25%2C+11%2C+13%2C+16%2C+2%2C+1%2C+27%2C+30%2C+4%2C+22%2C+27%2C+26%2C+36%2C+31%2C+6%2C+38%2C+21%2C+5%2C+34%2C+41%2C+18%2C+2%2C+34%2C+16%2C+34%2C+39%2C+21%2C+12%2C+26%2C+6%5D%0A&debug=0&input_size=2) [Answer] # [R](https://www.r-project.org/), 27 bytes ``` any(rank(x<-scan(),,'f')-x) ``` [Try it online!](https://tio.run/##VVNNb5tAEL37V6zSQ0AaS@wXC1UuvVQ99NSmh0q9IGSiqClEmCquqv52970JXhyDMDs7897Oe8N8fmde5u75@TCbYZrNse/GohTTPT1NL4/jg1kmsxyOi/k1zQfTd8fDcTeYu70Zfo/98jiNxan8uzNa9yZcns7d@KeYu/Fncbrbr7hyO9yW@1N5/rfru6W42eN3/@Xb/afv73@MN@VuKPrCluu/uPXNyRbzOeply8AbdoJEqSVJI63YSqwVmxOcLivsNMiokRmIlZFrrBphGrMCdhJyI6ouCMhIYoPYKI65rhWPV6tgHmik9bU43Fg5cWRylXgvviW0r8QlCXjqaQLulc@2IHRgAwOyxTbisQvqTaePHz5/vZJp6yxrcKVSVs5ntbbYtYpWdbhUBmqqvBdVHZqL65r9RNUZTa@xiBgxajybzEE1qXDS6OaTSkXtVN2N582Vo5E@ekqVMrJVKsczVISut3kIqnRDET2NoxlQETa8FkXK6qg1LWipf8uzJfpJn5x6F@lzoz5UNO61Z8cmOUI1iWkgsi8NgNSp1QDyHAjusQQLnCkRl6MV9Gyio@HZH4m1FpSeooAP2DUbCHpUr71oR@vgeOanqw@CFy06/wc "R – Try It Online") Returns FALSE for Truthy, TRUE for FALSY (just to shave one byte) **Explanation:** If the array containing the rank of each value is equal to the input array, then it's a permutation of `1..n` **Note:** 5 bytes are wasted because in `rank` function the default handling strategy in case of ties is "average their ranks" instead of any of the other possibilities... argh! [Answer] # [Perl 5](https://www.perl.org/), 38 bytes ``` sub{!grep!{map+($_,1),@_}->{$_},1..@_} ``` [Try it online!](https://tio.run/##dVNda9tAEHzPr1AOUWyyDbovnWST1k99KTQveUuLSSBu06a2UZyHYvLb3Zm1rFMotYy4292buZ1ZbR@6p3goV1eH55f7/fn37mF7vv99t72YlEuxU1ksX99/2JfLV7GXl9gc5meLXfey@/HnanJW4Hdrv0m/EHdaOhlFfY57GRVhiVyQKLUkaaQVW4m1YnOF032FVIOSGqWBcBm9xrYR1rEsIJVQHHFswEBJEhvERnEsdq14LK3CeeCR2dfi8MfOiSOXq8R78S2xfSUuScBb7xPw7wltC0YHOjCgWmwjHtmeewqtVndPz4NUo8ayCGOlsn4@SzaKvhHTqhjD8UBtB25V16HDODaCzxBgm1EdgBanYESQwDXeTaamzhQ/aXhkoopIVVX4EfubJ4cjbfaUMWV0q3yON6kIX48mJqgPDSX29JVWQWOYdDwVKbqjEzSopTstL5joNl106mzkFDTqUkVbj607tsoRq8lMe1E9NAFWp5MAJM95YZJnsMGlEoE5ekEvJzo5ni2SWc@C01MZEAK8ZgdB7@q1GW2pnyvP@pQnZ9s9rneFudFvbfZ1bebFMfSuXE0W5XL60Wx@FWZmvlzfFNefCyM/N4/riREjzIrBkWK16fqvdQD8xIE84v0DeIKaKfT/AHWk54e/ "Perl 5 – Try It Online") [Answer] # [Red](http://www.red-lang.org), 46 bytes ``` func[a][i: 0 until[alter a i: 1 + i]single? a] ``` [Try it online!](https://tio.run/##bVJBbttAELv7FUSuvWhndrWSgaJ/6FXQQW2U1oDrBq5z6OtdcpIi1aqwIFiznCF3yOv6eP@8Pk7z4Xm9/jjen14uX6dlnk5HdHi53E7naTnf1isWsJTwAac54SPO6@Xb7fsnLPP9@frzywq1Y0qc8@8nbFsw7BDeYhy7NhaIyyjoUTFgROqQElKLs6h2BAwE9mzIImhZexYHCC1wJqCypbC5mUdgRcpIBaYWG@H8m2K0c7a0eA/jwy@Didc6uMNHMXgHq8h8h7bM5402jeQ1kpKBaKQBztO/Ch6elvOv38eH7f7a@7Z72q@3NcDbbe8Q//EkxR6b4VlGvQt@t8q4nLItay0lPOTutkeFR5rf8z20auSUTKxxuAtG2CBfwsCdlM2vPSyKkcuU2rKmUGNS24m232U0h8ODzHPlRiGge7T/tbfITpPHsn6U76PkV@VI@bDITFG@hvC/U2Bel2Rah4Lci1/BIbq5HLktksZ5rjwKok5@UFrVeAU8h0REMl2XFn/0ktm1N9KSotc9cij2uFJc7C23LnydD4f7Hw "Red – Try It Online") increments a counter as long as the counter is found in the list, and then checks it against the length. `1 = length?` is used as a polyfill for `single?` in the latest Red version. -5 bytes from tsh. -5 bytes from Galen Ivanov. [Answer] # [Java (JDK)](http://jdk.java.net/), 43 bytes ``` a->a.sorted().reduce(1,(x,y)->y==x?x+1:0)>0 ``` [Try it online!](https://tio.run/##bVFdb9MwFH3Pr7AqTUrgNortfLQdLQKJhz0gEOMN8eC1zshokypxyia0317uuQ0SSFM@7Pvhc@45fnAnN3/Y/Tw3h2PXB/XAcdp06avr6N/MGJr9i7l6bLeh6doXi0PovTugFG33bhjUR9e06nek1HG82zdbNQQXeDl1zU4duBbfhr5p7799V66/HxJpVepz73fN1gX/5qYNt4K5UbVan91849KBOf0uTlLuGrc@1hQ/0lMy3zyt149vH1/rVZZssvO1QLX@l3o/1rXn5i/e7XwfI3XTHscJecrePg3BH9KmTZJ037R@YIK66z@47Y8YsZpvpumUOrleBT8EtVbv@t49DZNwaUyH474J8YxmjHRwx68di4j58/e@X61Obj/6T3WShk7Oxsn1hDpN0I0hPbIpoY5nV8NKXd1dtTP6SxS6i2Mx@BNSdYpN/P8YUksm4GdZn6Pns440mcgQVss7S4j54yingkqqaEFL0hlpTZpLRjYZ5xZcK7knx0lGKHldEBpQzzlXcVfB/ZHmWkU6J12QQZdZkuWtFgDLCCCxJRl@OTJkgG4yspbsEqA2I1NRzn@ZIOd3YtJLpjLMwwzcTXpBlqsRhmUpIo0lWhaH9SJUy9g6yiGYm/E3PEshRuApIoxQiBE8Z1RwhFMl/5lB5EJ8JTFsEy0QJ8KB@d/DcQErLeavGEELmAF@BogSF5CL5AXUWHgHV1gO@3FpL6DPQDS8WMKIJdgrGAvDjJhYwPCFGJLBwYsSAwG4vxKUcJK784jpjLjNEBZ3giyaOeBpKiDiXnOZiuR2LNSAUs4ymYVsZmLUEqPnMqQVFaJlujuL/uoP "Java (JDK) – Try It Online") ## Explanations This answer is a `Predicate<IntStream>` and requires that the input contains no `0`. First this code sorts the input stream. The reduce method then makes sure that each consecutive number is encountered, and return the last encountered number. `x` always contains the next expected number, or `0` if we got an unexpected number. `1` is the first parameter of the `reduce` method as it's the first expected number. Given that `0`, or any negative number, is not allowed in the `IntStream`, when `0` is returned for the first time, it will always be returned for the remaining of the process. [Answer] # TypeScript's Type System, 450 442 bytes ``` type A<T extends any[]>=T extends{length:infer L}?(L extends number?L:never):never type B<L extends number,T extends 0[]=[]>=T extends{length:L}?T:B<L,[...T,0]> type C<N extends number,T extends number=1,R extends any[] = []> = R['length']extends N?R:C<N,A<[...B<T>,0]>,[...R,T]> type D<T extends any[],U extends any[]>=T extends[]?true:T extends[infer H,...infer R]?H extends U[number]?D<R,U>:false:never type F<T extends any[]>=D<T,C<A<T>>> ``` [TypeScript Playground Link](https://www.typescriptlang.org/play?#code/PTAECUFMDNIJ0gOwMaQM4C5QAsAuuAHTEAS10UgA9cA6Ege2BIFsCAbSZpXExAcwC0AQzhlsXHsgEB3MbwG4AngXTJRBXGgXLIAtIrS5OwgIwwTAFgAMQgGzR7AKCUrQAQQA8AFVBUjiABM0UCFERQBtAF0APgBeHz8kIIBvDn5cbAxeWDhQABkAXwB%20AAo832ok4MQAV2YAI3givIwKADd4AEpWyA64Zx1QACEPcsTA6rrGuAAaBMqJ0Cso2Ki4%20f8UtL4MjEKirwwRvJnwmnOvGasYgdcAYQ8AOQrNyYb4OZeq0Fr3uFiTDNwF9FqEIpFQLFQGtIRBwgBybYZeGRcZBUCPIrgDAPR4zTxnc4jLzRK4xU7nGjgOY3FyQUAAEW8IPRNUQAGtEPRpIgojMAKos4Jsznc3kxeJCqJFXBwGqQDAbKrhbLwUAACRmlNVuXAkSK6qFoH54V%20031TOp-OiGGgQjYaAV7Xgt3pADFmWjgmC1rEmZcHp4SdFoo5XaAvOhcCZYQ8TFZQyBQMmAHpFMN0iNRgBMsI94UBoGzM1AAGYSxYS7YSwBWG5J1Pp8ORwylvMeAsl4tlisl%20O1%20tgRsZwYt3AWdtrRwN0BpkeuMc1yeF7vl0CV0A1qslgDsJYAHIPk7OikA) ## Explanation ``` // This allows getting the Length of any tuple via inferring its L property type A<T extends any[]>=T extends{length:infer L}?(L extends number?L:never):never // This creates a tuple of arbitrary length L (we need to use this later for arithmetic) type B<L extends number,T extends 0[]=[]>=T extends{length:L}?T:B<L,[...T,0]> // We can use this to generate an incrementing tuple of length L (e.g. [1, 2, 3, 4]). We use this to compare against the final array. type C<N extends number,T extends number=1,R extends any[] = []> = R['length']extends N?R:C<N,A<[...B<T>,0]>,[...R,T]> // This checks if two arrays have the same elements inside them type D<T extends unknown[],U extends unknown[]>=T extends[]?true:T extends[infer H,...infer R]?H extends U[number]?D<R,U>:false:never // Finally, we can use this to compare the chosen array T vs the increasing tuple N type F<T extends any[]>=D<T,C<A<T>>> ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~22~~ 20 bytes ``` Sort@#==Range@Max@#& ``` -2 bytes, thanks to @ZaMoC: [Try it online!](https://tio.run/##VZJNasNADIX3uUagK0E80vx5YfAFCqU9gSkhzSIpBC8KIWd339NMCsXG9mg070mffFnWr@NlWc@fy3aato/v2zrvp@l9uZ6O8@vyM@9ftrfb@boe5tNhvu/u4SF4iPKl0lfW1iZ9Ay/EoiTJUqTKKGGQECS0XfXvAeGK7Yy0SImmlvFZhTlMiQgXJCYc8bPYLhKihCTKRB3F8BlcxqBDN8uiuLFSUXroIGZiI3VtEC0S8fQ6Iu5uFka4KazggGwJVQy78EWvrfLW3bPtBsFa7331RyN4V54aCcaFHI2i1PQkx8sXrDM5NjTDQEKAIhnP2uQJh7SKhzpt75wonFR3@Xe1UOIcjD2XphZcW@k4UC73MUaHVcnBCJ48AQIk24lEMkpcpDgS4chiCkdC1Or4E0dVHeVA9q09ZUucf6YrZ4BsLxqO6qOCinGg3GA@FiioUJT/RfTCxEdrbIuufhZ@Rgowg3Bm9dHrNG/E2@mDN@aXx@6xbb8) [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` c%R|} ``` [Run and debug it](https://staxlang.xyz/#c=c%25R%7C%7D&i=%5B1%5D%0A%5B1,2%5D%0A%5B2,1%5D%0A%5B1,3,2%5D%0A%5B3,1,2%5D%0A%5B1,2,3,4,5,6,7,8,9,10,11,12%5D%0A%5B12,11,10,9,8,7,6,5,4,3,2,1%5D%0A%5B6,3,8,12,1,10,4,2,7,9,5,11%5D%0A%5B16,37,14,15,23,8,29,35,21,6,5,34,38,9,36,26,24,32,28,7,20,33,39,12,30,27,40,22,11,41,42,1,10,19,2,25,17,13,3,18,31,4%5D%0A%5B2%5D%0A%5B12%5D%0A%5B1,1%5D%0A%5B1,3%5D%0A%5B2,3%5D%0A%5B3,3%5D%0A%5B2,1,3,2%5D%0A%5B1,4,3,1%5D%0A%5B4,1,2,4%5D%0A%5B1,2,2,5,5%5D%0A%5B1,3,3,3,5%5D%0A%5B8,7,5,3,4,1,6%5D%0A%5B5,7,1,4,6,1,8,3%5D%0A%5B6,3,5,4,7,1,8,1,2%5D%0A%5B6,5,3,8,2,7,9,4%5D%0A%5B1,1,1,1,1,1,1,1%5D%0A%5B1,5,9,13,11,7,3%5D%0A%5B14,6,12,4,10,8,16,2%5D%0A%5B34,33,38,17,35,11,36,31,28,14,6,15,18,2,19,40,29,41,9,1,27,23,20,32,26,25,37,8,13,30,39,7,5,3,21,4,11,16,10,22,12,24%5D%0A%5B38,27,20,23,31,6,2,24,21,31,33,7,26,12,14,17,3,2,28,31,5,23,28,27,37,32,7,39,22,6,35,42,19,3,35,17,35,40,22,13,27,7%5D&m=2) Explanation: ``` ; Implicit input onto top of stack c ; Copy top of stack % ; Length of top of stack R ; Make range [1 .. n] |} ; Compare top two elements of stack. Arrays are different orderings of same elements? ; Implicit output of truthy/falsy ``` Could probably save a byte somewhere. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 1.5 bytes (3 nibbles) ``` -,, ``` Returns an empty list (falsy) if input is a permutation of 1..n, or a non-empty list (truthy) if it is not. ``` - # remove , # sequence of 1.. , # length of # (implicitly) input # from # (implicitly) input ``` [![enter image description here](https://i.stack.imgur.com/UJwUg.png)](https://i.stack.imgur.com/UJwUg.png) [Answer] # Python, ~~43~~ 39 Bytes ``` lambda x:sorted(x)==list(range(len(x))) ``` 0-indexed. Uses `sorted()`, `range()` and `list()`. Surprisingly gives correct answer for empty list. [Test on TIO.](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqji/qCQ1RaNC09Y2J7O4RKMoMS89VSMnNQ8opKn5v6AoM69EI00j2kDHUMdIx1jHJFZTkwsuaggVNUURNQGJ6FjomKOJglQa6higiAI5/wE) [Answer] # Python, 39 Bytes ``` lambda x:sorted(x)==list(range(len(x))) ``` I am an account owned by PlaceReporter99. I am trying to get 20 rep so that I can access the chat rooms. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` ¬⁻Eθκθ ``` [Try it online!](https://tio.run/##BcFLCoAgFAXQrThUuIH2j9ZgNBcH4iRJLM3a/uscf7jiLxeJ9hJS5dtVuQ7pfbh2N89gpwDLQoiVyJgBLSYoBYkFHRRGzOihpLXUfPEH "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Outputs a Charcoal boolean, i.e. `-` for permutation, nothing if not. Explanation: ``` θ Input array E Map over elements κ Current index ⁻ Remove values found in θ Input array ¬ Check that nothing is left Implicitly print ``` (Mapping over the input indices is golfier than creating a range.) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~40~~ 38 bytes ``` s=>s.sort((a,b)=>a-b).some((x,i)=>x^i) ``` [Try it online!](https://tio.run/##DchbCoAgEADA6@zCJr3/7CJRoKVhWBtuRLe35nN28xhZUrju4uTVZa@z6EGUcLoBDFnUgyks/nE4gJfCH@8cMC98CkenIm/gYSypopo6aqmnZkLMHw "JavaScript (Node.js) – Try It Online") Returns true for invalid and false for valid. Put a `!` before the `s.sort` for the otherway round. Takes input 0-indexed. [Answer] # [jq](https://stedolan.github.io/jq/), ~~20~~ ~~49~~ 36 bytes ``` length==max and max==(unique|length) ``` [Try it online!](https://tio.run/##yyr8/z8nNS@9JMPWNjexQiExL0UBSNvaapTmZRaWptZAJDX//4821DHVsdQxNNYxNNQx1zGOBQA "jq – Try It Online") *Thanks to `tsh` and `xigoi` for catching mistakes in the previous attempts...* Third time is the charm perhaps? Since the rules limit the numbers to "positive integers", there's no need to test the minimum. Making sure the largest number in the list, the size of the original list and the size of a de-dup'd list are all the same is sufficient. So that's what this version does. [Answer] # [Raku](http://raku.org/), 14 bytes ``` {$_∖bag ^$_} ``` 0-based. [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiX@Uce0pMR0hTiV@Nr/xYmVCkoq8Qq2dgrVimkKQCElhbT8IoVoAx0jHcNYnWggqWMApA2gpCFQ3FjHVMdMx1zHItb6PwA "Perl 6 – Try It Online") * `$_` is the list argument to the function. * `^$_` is a list of numbers from 0 to one less than the size of the input list. * `bag ^$_` is a bag (a set with multiplicity) of that list of those sequential numbers. * `∖` is the set difference operator. The left argument, the input list, is coerced to a bag because the right argument is a bag, from which one instance of each of the sequential numbers is removed. The result will be an empty bag only if the input list contained exactly one number from zero up to one less than its size. An empty bag is falsey in a boolean context, and a non-empty bag is truthy. ]
[Question] [ A set is sum-free if no two (not necessarily distinct) elements when added together are part of the set itself. For example, `{1, 5, 7}` is sum-free, because all members are odd, and two odd numbers when added together are always even. On the other hand, `{2, 4, 9, 13}` is not sum-free, as either `2 + 2 = 4` or `4 + 9 = 13` add together to a member of the set. Write a program or function that takes a set as input, and outputs a Truthy value if the set is sum-free, and Falsy otherwise. Examples: ``` Sum-free: {} {4} {1, 5, 7} {16, 1, 4, 9} Not sum-free: {0} {1, 4, 5, 7} {3, 0} {16, 1, 4, 8} ``` [Answer] # Python 2, 41 bytes ``` lambda s:s==s-{a+b for a in s for b in s} ``` `s` should be a Python set. Fun fact: `sum-free` is an anagram of my name. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṗ3ḅ-P ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmXM-G4hS1Q&input=&args=WzIsIDQsIDksIDEzXQ&debug=on) ### How it works ``` ṗ3ḅ-P Main link. Argument: A (array) ṗ3 Take the third Cartesian power of A, i.e., generate all triplets that consist of elements of A. ḅ- Convert each triplet from base -1 to integer. This maps [a, b, c] to a - b + c = (a + c) - b. If (a + c) belong to A, this will yield 0 for some b. P Take the product of all resulting integers. ``` [Answer] # Pyth - ~~8~~ 5 bytes *Thanks to @FryAmTheEggman for saving me 3 bytes.* ``` !@sM* ``` [Test Suite](http://pyth.herokuapp.com/?code=%21%40sM%2a&test_suite=1&test_suite_input=1%2C+5%2C+7%0A2%2C+4%2C+9%2C+13&debug=0). ``` ! Logical not. This makes the empty intersection true and vice versa. @ Q Setwise intersection with input (implictly). sM Map sum to all the pairs. *QQ Get all pairs by doing cartesian product with input*input (implicit). ``` [Answer] # JavaScript, ~~86~~ ~~42~~ 41 bytes ``` n=>!n.some(m=>n.some(o=>n.includes(m+o))) ``` Thanks Cᴏɴᴏʀ O'Bʀɪᴇɴ for saving me a ton of bytes off parentheses/curly brackets. Also thanks Neil for pointing out that the function was returning the opposite boolean value than it should have. I tried to cut down on bytes by redefining `n.some` but that doesn't work because it's a prototype function unfortunately. There might be a better solution with `Array.prototype.map` in JS but the some function is really fun. I'm now wondering if there's a shorter way than `.includes` using something such as .indexOf and adding 1 (which would give it a truthy value if it contains the number). --- Testing: ``` > (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7]); true > (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7,12]); false ``` [Answer] # MATL, 5 bytes ``` t&+m~ ``` This outputs an array which is truthy if all entries are `1` and falsey otherwise. [Here is a demo to show various truthy/falsey values in MATL](http://matl.tryitonline.net/#code=YGkgICAgICAgJSBGb3IgYWxsIGlucHV0cwo_ICAgICAgICAlIElmIHRydWUKJ3RydWUnCn0gICAgICAgICUgZWxzZSBmYWxzZQonZmFsc2UnCl1EVA&input=MQowClsxIDEgMV0KWzAgMCAwXQpbMSAwIDFd). [**Try it Online**](http://matl.tryitonline.net/#code=dCYrbX4&input=WzEgNSA3XQ) **Explanation** ``` % Implicitly grab input t % Duplicate &+ % Compute sum of each element with every other element (2D Matrix) m % Check which members of the input are present in this matrix of sums ~ % Negate the result to yield a truthy value for sum-free sets % Implicitly display truthy/falsey value ``` [Answer] # Mathematica, 23 Bytes ``` {}==#⋂Tr/@#~Tuples~2& ``` [Answer] # Haskell, ~~32~~, 30 bytes Simple solution: ``` f x=and[a+b/=c|a<-x,b<-x,c<-x] ``` Two bytes saved by @Lynn [Answer] # J, ~~18~~ ~~10~~ 8 bytes 8 bytes saved thanks to miles, and 2 thanks to FrownyFrog! ``` -:]-.+/~ ``` Matches the original list with the set difference of tabulated sums. This is equivalent to: ``` (-: (] -. +/~)) y ``` for input `y`. This translates to: ``` y -: (] -. +/~) y y -: (y -. +/~ y) ``` `+/~` returns a table of sums using `y`. For `y =: 16 1 4 9`, this gives: ``` +/~ 16 1 4 9 32 17 20 25 17 2 5 10 20 5 8 13 25 10 13 18 ``` Then, we use `-.`, which produces a list consisting of all elements in `y` not in this table. If the list is sum-free, this will produce the same list. Then, `-:` checks for equality of lists, which produces the desired output. ## Old, 18 bytes ``` [:-.[:>./^:_+/~e.] ``` `+/~` creates a table of the values of the set added to itself, and `e.` checks if those members are in the original set. The rest of that is negating the maximal element. [Answer] # Julia, 18 bytes ``` !x=x∩(x'.+x)==[] ``` [Try it online!](http://julia.tryitonline.net/#code=IXg9eOKIqSh4Jy4reCk9PVtdCgohWzEsIDUsIDddICAgICB8PiBwcmludGxuCiFbMiwgNCwgOSwgMTNdIHw-IHByaW50bG4&input=) [Answer] ## [Retina](https://github.com/m-ender/retina), ~~45~~ 44 bytes ``` \d+ <$&$*1> $ $`$` M`(<1*)>.*<(1*>).*\1\2 ^0 ``` Input is a decimal list of comma-separated numbers. Output is `0` (falsy) or `1` (truthy). [Try it online!](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoxPgokCiRgJGAKTWBcYigxKj4pLipcYigxKik-LipcYlwyXDEKXjA&input=MSw1LDcKCjEKMiw0CjQsOSwxMwoyLDQsOSwxMwow) (The first line enables a linefeed-separated test suite.) ### Explanation **Stage 1: Substitution** ``` \d+ <$&$*1> ``` This converts all elements of the input to unary and wraps them in `<...>`. The purpose of the angle brackets is to distinguish a list containing only `0` from an empty list (since the unary representation of `0` is empty itself). **Stage 2: Substitution** ``` $ $`$` ``` We repeat the string 3 times by append it twice at the end. **Stage 3: Match** ``` M`(<1*)>.*<(1*>).*\1\2 ``` We now try to find three numbers in the result such that the first two add up to the third. Those matches are counted (this doesn't actually count all such tuples, because matches cannot overlap, but if such a tuple exists it will be found). Hence, we get `0` for sum-free sets and something positive otherwise. **Stage 4: Match** ``` ^0 ``` Since the previous stage gave the opposite of what we want, we negate the result by counting the matches of `^0` which is `1` for input `0` and `0` for everything else. [Answer] # Octave, ~~29~~ ~~21~~ 25 bytes ``` @(s)~[ismember(s,s+s') 0] ``` Thanks to [Suever](https://codegolf.stackexchange.com/users/51939/suever)! It returns an array. I added `0` at the end to make `[]` become sum-free. To verify truthy and falsey in Octave, you can do this: ``` > f=@(s)~[ismember(s,s+s') 0] > if f([]) "sum-free" else "not sum-free" end ans = sum-free > if f([0]) "sum-free" else "not sum-free" end ans = not sum-free > if f([4]) "sum-free" else "not sum-free" end ans = sum-free > if f([1 3]) "sum-free" else "not sum-free" end ans = sum-free > if f([2 4]) "sum-free" else "not sum-free" end ans = not sum-free ``` An alternative that returns 0 or 1 is: ``` @(s)~numel(intersect(s+s',s)) ``` [Answer] # Clojure, ~~47~~ 37 bytes ``` #(=(for[a % b % :when(%(+ a b))]a)[]) ``` quite plain solution. uses list comprehension to find all elements which sum is equal to another element. 38 bytes variant: ``` #(every? nil?(for[a % b %](%(+ a b)))) ``` [Answer] # Ruby, 36 bytes Constructs a cartesian product of the set against itself and finds the sum of all elements, then checks for intersection with the original set. Input is arrays, but in Ruby they have enough set operations to make it work out nicely anyways. -1 byte over my original solution (used `&` instead of `-` and compared with `[]`) because of inspiration from @feersum [Try it here!](https://repl.it/C94f/1) ``` ->s{s-s.product(s).map{|x,y|x+y}==s} ``` [Answer] # [Perl 6](http://perl6.org), ~~24 21 20~~ 19 bytes ``` ~~{not any (@\_ X+@\_)X==@\_} {so all (@\_ X+@\_)X!==@\_} {not @\_ (&)(@\_ X+@\_)} {not @\_∩(@\_ X+@\_)}~~ {!(@_∩(@_ X+@_))} ``` Input is any [Positional](https://docs.perl6.org/type/Positional) value like a [List](https://docs.perl6.org/type/). ( a [Set](https://docs.perl6.org/type/Set) is an [Associative](https://docs.perl6.org/type/Associative) so you would have to call [`.keys`](https://docs.perl6.org/routine/keys) on it. ) ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my @sum-free = ( (), (4,), (1, 5, 7), (16, 1, 4, 9), ); my @not-sum-free = ( (0,), (1, 4, 5, 7), (3, 0), (16, 1, 4, 8), ); my @tests = ( |(@sum-free X=> True), |(@not-sum-free X=> False) ); plan +@tests; # store the lambda in lexical namespace for clarity my &sum-free-set = {!(@_∩(@_ X+@_))} for @tests -> $_ ( :key(@list), :value($expected) ) { is sum-free-set(@list), $expected, .gist } ``` ``` 1..8 ok 1 - () => True ok 2 - (4) => True ok 3 - (1 5 7) => True ok 4 - (16 1 4 9) => True ok 5 - (0) => False ok 6 - (1 4 5 7) => False ok 7 - (3 0) => False ok 8 - (16 1 4 8) => False ``` [Answer] # Mathematica ~~63 62~~ 42 bytes This shorter version benefitted from A Simmons' submission. No element needs to be removed from the list before `IntegerPartitions` is applied. If an element cannot be partitioned into two integers (each from the list), then `IntegerPartitions[#,{2},#]=={}` holds. `And` checks whether this holds for every element in the list. If so, the list is sum-free. ``` And@@(IntegerPartitions[#,{2},#]=={}&/@#)& ``` --- ## Examples ``` And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{2, 4, 9, 13} ``` False --- ``` And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{1, 5, 7} ``` True --- There is a 2, but no odd numbers that differ by 2. ``` And@@(IntegerPartitions[#,{2},#]=={}&/@#)&@{2, 3, 7, 11, 17, 23, 29, 37, 41, 47, 53, 59, 67, 71} ``` True [Answer] # R, ~~39~~ 36 bytes ``` w<-function(s)!any(outer(s,s,'+')%in%s) ``` Call as `w(s)`, where `s` is the set (actually vector) of values. Here is the output for some test cases: ``` > w(numeric(0)) # The empty set [1] TRUE > w(0) [1] FALSE > w(1) [1] TRUE > w(c(1, 5, 7)) [1] TRUE > w(c(2, 4, 9, 13)) [1] FALSE ``` Where `c()` is the concatenation function that takes a bunch of values and makes it a vector. EDIT: Making it an anonymous function to save 3 bytes, thanks to @MickyT. ``` function(s)!any(outer(s,s,'+')%in%s) ``` [Answer] # Python, 40 bytes ``` lambda s:s^{a+b for a in s for b in s}>s ``` `^` = symmetric difference, new set with elements in either sets but not both `>` True if the left set is a superset of the right set. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` '(p:?+L:?x'L) ``` ### Explanation ``` '( ) True if what's in the parentheses is impossible, false otherwise p Get a permutation of Input :?+L L is the list of element-wise sums of the permutation with Input :?x'L There is at least one element of Input in L ``` [Answer] # Racket, 58 bytes ``` (λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l)) ``` Explanation: ``` (λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l)) (λ(l) ) # Define a lambda function that takes in one parameter (andmap(λ(m) )l) # If for all m in l (andmap(λ(n) )l) # If for all n in l (not(memq(+ n m)l)) # n + m is not in l ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 5 bytes Saved 4 bytes thanks to *Magic Octopus Urn* ``` ãOå_P ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8GL/w0vjA/7/jzbUMdUxjwUA "05AB1E – Try It Online") **Explanation** ``` ã # cartesian product O # sum å # check each if it exists in input _ # logical negation P # product ``` [Answer] # APL, 8 bytes ``` ⊢≡⊢~∘.+⍨ ``` Explanation: ``` ⊢ argument ≡ equals ⊢ argument ~ without ∘.+⍨ sums of its elements ``` Test: ``` ( ⊢≡⊢~∘.+⍨ ) ¨ (1 5 7)(2 4 9 13) 1 0 ``` [Answer] ## Haskell, 30 bytes ``` f s=and[x+y/=z|x<-s,y<-s,z<-s] ``` I think there exists a shorter solution that's more interesting, but I haven't found it. These are 33 and 34 bytes: ``` f s=and$((/=)<$>s<*>)$(+)<$>s<*>s f s|q<-((-)<$>s<*>)=all(/=0)$q$q$s ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes ``` ;;∙♂Σ∩Y ``` [Try it online!](http://actually.tryitonline.net/#code=OzviiJnimYLOo-KIqVk&input=WzEsNSw3XQ) ``` ;;∙♂Σ∩Y Stack: [1,5,7] ; duplicate [1,5,7] [1,5,7] ; duplicate [1,5,7] [1,5,7] [1,5,7] ∙ cartesian product [1,5,7] [[1,1],[1,5],[1,7],[5,1],[5,5],[5,7],[7,1],[7,5],[7,7]] ♂Σ sum each [1,5,7] [2,6,8,6,10,12,8,12,14] ∩ intersect [] Y negate 1 ``` [Answer] ## Java, 67 bytes ``` s->!s.stream().anyMatch(p->s.stream().anyMatch(q->s.contains(p+q))) ``` Input is a `Set<Integer>`. Tests: ``` import java.util.Arrays; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; public class SumFree { public static void main(String[] args) { sumFree(s->!s.stream() .anyMatch(p->s.stream() .anyMatch(q->s.contains(p+q)))); // formatted to avoid wrapping } public static void sumFree(Function<Set<Integer>, Boolean> func) { test(func); test(func, 4); test(func, 1, 5, 7); test(func, 16, 1, 4, 9); test(func, 1, 4, 5, 7); test(func, 0); test(func, 3, 0); test(func, 16, 1, 4, 8); } public static void test(Function<Set<Integer>, Boolean> func, Integer... vals) { Set<Integer> set = Arrays.stream(vals).collect(Collectors.toSet()); System.out.format("%b %s%n", func.apply(set), set); } } ``` Output: ``` true [] true [4] true [1, 5, 7] true [16, 1, 4, 9] false [0] false [1, 4, 5, 7] false [0, 3] false [16, 1, 4, 8] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 30 bits1, 3.75 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` ẊṠ↔¬ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBPSIsIiIsIuG6iuG5oOKGlMKsIiwiIiwiW11cbls0XVxuWzEsIDUsIDddXG5bMTYsIDEsIDQsIDldXG5bMF1cblsxLCA0LCA1LCA3XVxuWzMsIDBdXG5bMTYsIDEsIDQsIDhdIl0=) ``` Ẋ # cartesian product with itself Ṡ # vectorized sums ↔ # intersection of this with the input ¬ # logical NOT ``` If inverted truthiness is allowed, the `¬` can be removed for [2.875 bytes](https://vyxal.pythonanywhere.com/?v=1#WyJBPSIsIiIsIuG6iuG5oOKGlCIsIiIsIltdXG5bNF1cblsxLCA1LCA3XVxuWzE2LCAxLCA0LCA5XVxuWzBdXG5bMSwgNCwgNSwgN11cblszLCAwXVxuWzE2LCAxLCA0LCA4XSJd), but the challenge specifically states "*outputs a Truthy value if the set is sum-free, and Falsy otherwise.*" [Answer] # TSQL, 47 bytes ``` CREATE table T(a int) INSERT T values(1),(5),(7),(12) SELECT min(iif(a.a+b.a<>T.a,1,0))FROM T a,T b,T ``` Note: This will only run once, then the table needs to be deleted or dropped to run again. The fiddle editor doesn't allow creation of tables. Therefore the fiddle included in my answer uses 2 extra bytes to compensate for this - the fiddle version doesn't require cleanup. **[Fiddle](https://data.stackexchange.com/stackoverflow/query/508914/is-it-a-sum-free-set)** [Answer] # Perl, 46 bytes 45 bytes code + 1 byte command line (-p) ``` $_="$_ $_ $_"!~/(\b\d++.*)((?1))(??{$1+$2})/ ``` Uses a single regex match with Perl's support for 'code expressions' inside the regex to allow for evaluation within a match. To get around the requirement that the input is unsorted, we repeat the input string three times. This guarantees that the result is after the two operands, and allows the same digit to be matched again (e.g. in the case of input `2 4`). Usage example: ``` echo "3 5 6 8" | perl -p entry.pl ``` [Answer] # Factor, 47 bytes ``` [ dup dup 2array [ Σ ] product-map ∩ { } = ] ``` * `∩ { } =` is equivalent to but shorter than `intersects?`. * `Σ` is shorter than but equivalent to `sum`. Thanks, [math.unicode](https://codegolf.stackexchange.com/questions/75610/tips-for-golfing-in-factor)! testing code: ``` USING: arrays kernel math.unicode sequences sequences.product ; IN: sum-free : sum-free? ( seq -- ? ) dup dup 2array [ Σ ] product-map ∩ { } = ; USING: tools.test sum-free ; IN: sum-free.tests { t } [ { 5 7 9 } sum-free? ] unit-test { f } [ { 2 4 9 13 } sum-free? ] unit-test { t } [ { } sum-free? ] unit-test { f } [ { 0 } sum-free? ] unit-test { t } [ { 1 } sum-free? ] unit-test { f } [ { 0 1 } sum-free? ] unit-test ``` I'm only confident the first two are correct. It's unclear from the question what the rest should be, so I think it's fine for now. [Answer] # PHP, 73 bytes +8 to turn the snippet into a program, -8 on obsolete variables thanks to insertusernamehere ``` <?foreach($argv as$p)foreach($argv as$q)if(in_array($p+$q,$argv))die;echo 1; ``` prints `1` for `true`, empty output for `false` usage: `php <filename> <value1> <value2> ...` qualified function for testing (~~94~~ 86): returns `1` or nothing ``` function f($a){foreach($a as$p)foreach($a as$q)if(in_array($p+$q,$a))return;return 1;} ``` **tests** ``` function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';} function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);} 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='';} $samples = [ [], 1, [0], false, [1], 1, [0,1], false, [2, 4, 9, 13], false, [1,5,7], 1 ]; while($samples) { $a=array_shift($samples); $e=array_shift($samples); test($a,$e,f($a)); } ``` [Answer] ## Clojure, 34 bytes ``` #(not-any? %(for[i % j %](+ i j))) ``` I wrote this before noticing the earlier Clojure solution. Anyway, this one is more compact as it uses the input set as a `pred` function for `not-any?`. ]
[Question] [ The sequence of Fibonacci numbers is defined as follows: \$ F\_0 = 0 \\ F\_1 = 1 \\ F\_n = F\_{n-1} + F\_{n-2} \$ Given a Fibonacci number, return the previous Fibonacci number in the sequence. You do not need to handle the inputs \$ 0 \$ or \$ 1 \$, nor any non-Fibonacci numbers. Errors as a result of floating point inaccuracies are permitted. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` kg/ṙ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrZy/huZkiLCIiLCIyIl0=) Port of Unmitigated's JavaScript answer ``` / # Divide by... kg # Phi ṙ # Round ``` [Answer] # JavaScript, ~~21~~ 17 bytes ``` n=>n*5**.5-n+1>>1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9YuT8tUS0vPVDdP29DOzvB/QVFmXolGmoaRpiYXjG2MxDZFYlsgsQ2RFRkZIus2QdaOot8S2QAToLr/AA) -4 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203). [Answer] # [R](https://www.r-project.org), ~~23~~ ~~22~~ 20 bytes *Edit: -1 byte thanks to pajonk, then -2 bytes thanks to att* ``` \(x)(x*5^.5-x+1)%/%2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHqgqLUsvi0zCQFG92lpSVpuhZbYjQqNDUqtEzj9Ex1K7QNNVX1VY0gUjc1YKo1kjWMdIx1THUsdAyNdYwMdYxNdEyBPEsdQxMTTU0uiPoFCyA0AA) The ratio between consecutive fibonacci numbers famously converges towards [the golden ratio phi](https://en.wikipedia.org/wiki/Golden_ratio), equal to `(1+5^.5)/2`. This is sufficiently accurate that rounding produces the correct value for all fibonacci numbers, including even the second `1` at the start which we don't need to handle here. (Edit after reading some other answers: this was independently-derived, but is also the approach taken by [Luis Mendo](https://codegolf.stackexchange.com/a/247844/95126) and [unmitigated](https://codegolf.stackexchange.com/a/247840/95126)) [Answer] # [R](https://www.r-project.org), 27 bytes ``` \(x){while(x>T)T=F+(F=T);F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHqgqLUsvi0zCQFG92lpSVpuha7YzQqNKvLMzJzUjUq7EI0Q2zdtDXcbEM0rd1qISrWwvRoGBprckHEFiyA0AA) Similar to [this answer](https://codegolf.stackexchange.com/a/247836/67312), iterates through the Fibonacci sequence until `T==x` and returns `F`. [Answer] # x86-64 assembly, ~~13~~ 12 bytes ``` 6a 01 58 99 92 01 c2 39 fa 75 f9 c3 ``` In assembly: ``` previous: push 1 pop rax cdq # zeroes rdx previous_loop: xchg eax,edx add edx,eax cmp edx,edi jne previous_loop ret ``` [Try it online!](https://tio.run/##bVHRbtswDHw2v4JoMOwlMeqkW9sA3cuA/cQ2GIxFO@pkyZPkxP76jLaStClmwDZF3h1PJIXA7c6Mq6aqTgtKJw543FPkA3vUAbXF704xBq6idhbJKnR97PqIw6Cwdr6lCAvlONjPEY/O/0FdYzVxhG7INyIU92Sx0x3jrq9r9rDYiYAICmGinRUFFrHtq720GY80Qq5tZFOG0UYa0LrOc60HyBVFghDJx/Jse9yepHjQrg9bQHm6PuyxSKHr0NMwx5X6CxdgaZzrEnqo9g0yDUtWCUdKocRLvvDaLp2Vns@vlvFGZ856jie26s0UXKLSsH15X1rd2gcIFdm6DNFr22why1OEd5/6X/ZOPMso/l/Gl2@YQNLjioCatOk9ly2HQA1v4Ur5IRVW@cT4AJpdYo4r/FAAyCMPUX6NcTsy2JK2MH3ES@h36EO3fJoT56lmrTtIVi@lAplhQq/08uf7W/6GrCJjcM5BFjnEtAOZefZqGGVeSYcnqghdGJfJQ3azuIQNV@y168303kSmpHSS1V6Ng/QU89P605WyaacFrGFdwOYBigd5nzZfN0XxfL9BWD8/Fuviy/3j5h8 "Assembly (gcc, x64, Linux) – Try It Online") Uses the usual calling convention of taking the first argument in `rdi` and returning in `rax`. It's also valid x86-32, just with `edi` and `eax` instead. It's pretty simple- it just explicitly computes Fibonacci numbers and returns if the new number is equal to the input. At the end of a loop, `rdx` contains the next Fibonacci number and `rax` contains the previous. If `rdx` is equal to the input `rdi`, then the loop terminates (and thus `rax`, the previous number, is returned). Otherwise the two are swapped, and the loop begins again. This uses 32-bit registers to save a few bytes, so it only works up to the 47th Fibonacci number, `2971215073`. It can be expanded to work with 64-bit numbers by changing all the registers to 64-bit, at the cost of 2 bytes: ``` 6a 01 58 99 48 0f c1 c2 48 39 fa 75 f7 c3 ``` The added bytes are the REX.W (`0x48`) prefix that swaps the operand size to 64-bit. `xchg rax,rdx; add rdx,rax` is also replaced with `xadd rdx,rax`, which is shorter because it uses one fewer REX.W prefix. -1 byte thanks to [@PeterCordes](https://codegolf.stackexchange.com/users/30206/peter-cordes). [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, ~~21~~ ~~19~~ ~~18~~ 14 bytes ``` [ φ / round ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVBQlFpSUllQlJlXopCdWpSXmgMW10vOzysuScwrKYZwS/Myk/NTUiGctNK85JJMoAIFay4uE0MLQ67/0Qrn2xT0FYryS/NSFGL/Jyfm5Cjo/QcA "Factor – Try It Online") -4 thanks to @DominicvanEssen! Divide the input by the golden ratio and round the result. [Answer] # [C(gcc)](https://gcc.gnu.org/c99status.html), ~~57,55,53,50,45~~, 36 bytes ``` x;y;f(a){for(x=y=1;y-a-x;y+=x=y-x);} ``` Naive approach based on calculating all previous Fibonacci numbers, breaking when we reach the input. [Try it here](https://tio.run/##dczBCgIhGATgu08hG4GyGbkRBH/2JF1E1xJKw3VDWfbZzUu3nNvMB6PYXalSEmQwRNLF@ECSyIJDZpLVuRe1skRhLRvr1HPW42WK2vr944qsi/glrSMfbzVdEK55h7oa0m31zXU7QwZK4S8cW3BqwbkFvPk18J@EMc7B4QOgtXwB) Edit: Thanks for Neil, golfing ~~2~~ 5 bytes. Edit2: Thanks Dominic van Essen for golfing an other 5 bytes. Edit3: Thanks att for golfing 9 bytes. [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes ``` f=lambda n,a=0,b=1:n-b and f(n,b,a+b)or a ``` [Try it online!](https://tio.run/##xVBBboQwDLzzCt8A1SvhBBKyUvqRtocAQYvaZhGkUlvE26mD2jc0h2Q89owdz1/xdg/yOEb75t67wUFAZyvsLF3DpQMXBhiLgB26h668L@CO6Ne4goVCIEiEBqFFIEaCmKiZSZRhruZASM5IrREUVQimZUSN4Vs0LedralmmtGIRVaZW/GhNzIlWNVxWK6m4gW4qkUoEScOOZBQr2Zl0S1Rm/nP2ffRDmitp/320Mutvvn/1S5oof/4Quu5zhBORzMts5GVG9DAF@J7m4twqwt8/ymsGfNKexyKWZzAvU4jFmG9xh8sjbOsO22@TJ2/t@rKz7fED "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~29~~ ~~28~~ ~~27~~ 24 bytes *The footer uses [@Noodle9's checker code](https://codegolf.stackexchange.com/a/247843/36398)*. *1 byte saved thanks to [@Chris](https://codegolf.stackexchange.com/users/58834/chris)!* *3 more bytes off thanks to [Albert.Lang](https://codegolf.stackexchange.com/users/101374/albert-lang)!* Function that returns an integer-valued `float`. It fails for large inputs due to floating-point inaccuracies. ``` lambda n:~n*(1-5**.5)//2 ``` [Try it online!](https://tio.run/##ZY1BDoIwEEXXcorZ0WJRWzQmJPUiyAJhEKLWhtYEJXh1rFVXzupN5s9/@m6bq0qmWu6nc3E5VAWo9KkiwuNNFC02dLkUk0VjjcwES/IAe42lxUpmnIk8qK8d9NAq6Ap1RCIYX61oGsx@sUWhNaqK@Ios5jkNZp7/DvMvCRcpGyxP2IEEEu5vYrsuQwaeeBJSL7UM39pHqz8VDH5Kpwc3xn3XxFK/6K5VltThYEeIdzCYEYavJEMpTT662ukF) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 17 bytes ``` Round[2#/++√5]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyi/NC8l2khZX1v7Uccs01i1/4GlmaklDgFFmXkl0cq6dmkOyrFqDlpumUn5eYnJyZl1wcmJeXVBiXnpqdHGOkYGsf8B "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 31 bytes ``` [int]("$args"/1.61803398874989) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PzozryRWQ0klsSi9WEnfUM/M0MLA2NjSwsLcxNLCUvP///9GxsYA "PowerShell – Try It Online") The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is divided by ((1 + sqrt(5)) / 2) and then rounded, the resultant number will be the previous Fibonacci number... at least according to [this article.](https://www.geeksforgeeks.org/find-the-previous-fibonacci-number/#:%7E:text=Approach%3A%20The%20ratio%20of%20two,be%20the%20previous%20Fibonacci%20number.) -16 thanks [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy) [Answer] # [Haskell](https://www.haskell.org/), ~~38~~ 37 bytes This works for an aribrary size of inputs. We iterate through the Fibonacci sequence until we find some number `x`, that is larger than half the input `n`. This is works because the previous fibonacci number is roughly `0.618*n`. The Fibonacci list `f` was borrowed from [R. Martinho Fernandes](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence#comment110_89). ``` g n=[x|x<-f,2*x>=n]!!0 f=0:scanl(+)1f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P10hzza6oqbCRjdNx0irws42L1ZR0YArzdbAqjg5MS9HQ1vTMO1/bmJmnoKtQkFRZl6JgopCbmKBQrpCtJGOsY6pjoWOoXHsfwA "Haskell – Try It Online") [Answer] # JavaScript, Node.js, 32 bytes *-1 thanks to Arnauld* ``` n=>(y=1,f=x=>y-n?f(y,y+=x):x)(0) ``` **Explanation:** This is a recursive solution, based off one of the two most common recursive fibonacci algorithms, which involves a function `f(x, y) = f(y, x + y)` that stops at some point. With this function, `x` is always a fibonacci number, and `y` is always the fibonacci number after it, so once `y` is the fibonacci number we were given as input, we know `x` is the one before it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅF¨θ ``` [Try it online](https://tio.run/##yy9OTMpM/f//cKvboRXndvz/b2gAAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R/ic7jncGtaWaW9ksKjtkkKSvaV/w@3uh1acW7Hf53/AA). `¨θ` could be a lot of different alternatives, like `Á¤` or ``\`. **Explanation:** ``` ÅF # Push a list of Fibonacci numbers lower than or equal to the (implicit) input ¨ # Remove the last one (the input) θ # Keep the next last one # (after which it is output implicitly as result) ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~6~~ 4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` )φ/i ``` -2 bytes porting [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/247842/52210), which is in turn a port of [*@Unmitigated*'s JavaScript answer](https://codegolf.stackexchange.com/a/247840/52210). [Try it online.](https://tio.run/##y00syUjPz0n7/1/zfJt@5v//RlzGXKZcFlyGxlxGhlzGJlymQJ4ll6GJCQA) **Original 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) answer:** ``` ╒fg<┤Þ ``` [Try it online.](https://tio.run/##y00syUjPz0n7///R1Elp6TaPpiw5PO//fyMuYy5TLgsuQ2MuI0MuYxMuUyDPksvQxAQA) `g<` could alternatively also be `á>`: [try it online](https://tio.run/##y00syUjPz0n7///R1ElphxfaPZqy5PC8//@NuIy5TLksuAyNuYwMuYxNuEyBPEsuQxMTAA). **Explanation:** ``` ) # Increase the (implicit) input-integer by 1 φ/ # Divide it by the golden ratio 1.618033988749895 i # Truncate it to an integer # (the +1 and truncate act as a round builtin here, which MathGolf lacks) # (after which the entire stack is output implicitly as result) ``` ``` ╒ # Push a list in the range [1, (implicit) input-integer] f # Get the 0-based n'th Fibonacci number for each value in this list g # Filter it by: < # Where it's smaller than the (implicit) input-integer ┤ # Extract the trailing value Þ # Discard the list from the stack, keeping just that value # (after which the entire stack is output implicitly) ``` [Answer] ### [Python 3](https://docs.python.org/3/), ~~50 bytes~~ 48 bytes ``` def f(n,a=0,b=1): while b<n:a,b=b,a+b return a ``` [Try it online!](https://tio.run/##ZY1NbsMgEEb3nGJ2xgqJDLZUKSq9iOsFtofaakUQECWN5bMTTNNsMqtv/t6zv2E6mTrGETVoapiSFeslL48ELtP8g9C/m6NKo56pXU/AYTg7AyoG9MHLVrC6I3i1OAQcZcuZ6Ig@ObjCbMAp84VUMF5VG/D/7KCsRTPSjGj3vCsJ5Pyy2D2SSCfDhMM3OpBAi8@zeGuGgkFOvC7KLA0MN@1ttn8I9lRu@lQ@fWsaytxYN5tAdbGEFfYfsPgVloekRSl9tyZs5E0T7w "Python 3 – Try It Online") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 35 bytes ``` 1+0. N+M:-nth1(M,_,_),X is N-M,M+X. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/31DbQI/LT9vXSjevJMNQw1cnXideUydCIbNYwU/XV8dXO0Lvv5WugrGJtq@OQkFRZl6Jhq@m3n8A "Prolog (SWI) – Try It Online") -9 bytes thanks to Jo King Of course, it's shorter to just use floating point: # [Prolog (SWI)](http://www.swi-prolog.org), 31 bytes ``` N/M:-M is round(2*N/(1+5^0.5)). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30/f10rXVyGzWKEovzQvRcNIy09fw1DbNM5Az1RTU@@/la6CsYm@r45CQVFmXomGL1AIAA "Prolog (SWI) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes ``` .+ $* (\2?(\1)|1)+1 $1$2 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSyPGyF4jxlCzxlBT25BLxVDFiMvw/38LLmMTLkMTEwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Loosely based on @MartinEnder's Retina answer to [Am I a Fibonacci Number?](https://codegolf.stackexchange.com/q/126373). ``` .+ $* ``` Convert to unary. ``` (\2?(\1)|1)+1 ``` Match as many Fibonacci numbers as possible. The first iteration only matches the leading `1` while subsequent iterations match iteration of the loop matches the penultimate Fibonacci number (if any), then the previous Fibonacci number, while saving it as the next penultimate Fibonacci number. The match actually sums the Fibonacci sequence, resulting in a sequence one less than the Fibonacci sequence, so a final `1` needs to be matched. ``` $1$2 ``` Because the match is summing the sequence, the final capture of the sequence `$1` is actually the Fibonacci number before the one we want, so we need to add on the penultimate matched Fibonacci number `$2`. ``` 1 ``` Convert to decimal. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 16 bytes ``` n->n*2\/(1+5^.5) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWG_J07fK0jGL0NQy1TeP0TDUhwjfN0_KLNDIVbBWMdBQMDQx0FPKA7LTMpPy8xOTkTI1MTWuFgqLMvBKNPAUlBV07IJGmkaepCdW-YAGEBgA) Port of [Unmitigated's JavaScript answer](https://codegolf.stackexchange.com/a/247840/9288). `a\/b` is a short way to write `round(a/b)`. PARI/GP's floating point number is 128-bit by default. This gives the correct result until the 184th Fibonacci number (`127127879743834334146972278486287885163`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ‘:Øp ``` Add 1 to the input and integer-divide by the golden ratio. [Try it online!](https://tio.run/##y0rNyan8//9RwwyrwzMK/v//b2wCAA "Jelly – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` →←xİf ``` [Try it online!](https://tio.run/##yygtzv7//1HbpEdtEyqObEj7//@/kSEA "Husk – Try It Online") Makes use of the built-in list of Fibonacci numbers. ### Explanation ``` →←xİf İf Take the list of Fibonacci numbers x Split it on occurrences of the input ← Get the first sub-list → Get the last element of that ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Çâ'Ç,¼)í"─ ``` [Run and debug it](https://staxlang.xyz/#p=808327802cac29a122c4&i=2%0A3%0A5%0A8%0A19134702400093278081449423917&a=1&m=2) ### Approach * Start with an infinite Fibonacci generator * Keep values while they are less than the input, resulting in array e.g. `[1, 1, 2, 3, 5]`. * Extract last element. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~12~~ 11 bytes ``` --2!(1-%5)* ``` [Try it online!](https://ngn.codeberg.page/k/#eJxNjU1OwzAYRPc+xYegUgK4xn+xYx+DZVXR1Nht1NYucYJSoXJ2LLHJavRGTzPBYMweKopXsn5GaDQ/T5vb72ACAMx2l0622oWuP9vZ3uxQb+8o9Pt3/zX56LxhwEGCBsqBUeACZKEWqBDAOAeuFDT0DVqtgMpWAZNagKCaQqMaWe42izVLXzH9WBRbhF6qpRBgQTVCBB3H8ZoNIS59+kM6h3UeO3fyszt28eDXLl1IsfPYp5gJE0pzSa6D/+7TlHEZS7Fzrsdxuuz9UAQtVPP4H+gPmTxTfA==) Applies @Albert.Lang's approach from [this comment](https://codegolf.stackexchange.com/questions/247835/previous-fibonacci-number?answertab=scoredesc#comment554398_247844). * `(1-%5)*` calculate 1 minus the square root of 5 (i.e. `-1.2360679774997898`) and multiply it by the (implicit) input * `-2!` integer divide by 2 (rounding towards 0, e.g. `-8!-7` returns `-1`) * `-` negate (and implicitly return) [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 17 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⌊.5+⍵÷.5×1+5*.5} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U06Vnqv2od@vh7Xqmh6cbaptq6ZnWAgA&f=e9Q39VHbhDQFQwtjM2NDQ0sDY65HUCELSwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) 5 [Answer] # [Pip](https://github.com/dloscutoff/pip), 10 bytes ``` Ua*DRT5//2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWq0ITtVyCQkz19Y0gAlDxm2rRStGGCkYKxgqmChYKhsYKRoYKxiYKpkCepYKhiYmCkbFxLNwYAA) [Answer] # [Fig](https://github.com/Seggan/Fig), \$5\log\_{256}(96)\approx\$ 4.116 bytes ``` _\mG} ``` [Try it online!](https://fig.fly.dev/#WyJfXFxtR30iLCI0MTgxIl0=) No round builtins, so I use the old increment and floor trick. ``` _\mG} } # The input number incremented \ # Divided by mG # The golden ratio _ # Floor ``` [Answer] # [Go](https://go.dev), 59 bytes ``` import."math" func f(n float64)float64{return Round(n/Phi)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9JDsIwDEX3OYXVVSOFoRNtQdwBsUUIhSEQ0ToopKuqR-AEbCokDsFRuA0ulI39_azv4f44mvZ1kbuzPB6glBqZLi_GuqGnSuc9K6cG2Xv2Z6V0J4-pCnegfARVGOkmMe9zbQ-usghLU-Hex9HipHnTj7h9Td0Cn9dM6e0VpnNYrf_WUEAkIBGQCQhIhQGBmEiHcmIxFWFEnShNBUyCsYA8IxUkOcUwyeKGKWNhI3A6txLpnW5LzRZWoyvQR9HdzDlrWH9U2_7yBw) wow built-in constants ### Calculated version, 72 bytes ``` import."math" func f(n float64)float64{return Round(2*n/(1+Pow(5,0.5)))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BTsMwEEX3PsUoKxuGUjtxm1TqnmXVLULIlLpENOPKOGIR5QicgE1UiUNwFG7DBNLNzJ830v8zn-dDGL5PbvfqDntoXE2ibk4hplnmm5R9tcnflD93F9a49JIJ39IOvCTwx-DSolBT7-I-tZFgG1p6luaKbqW-3oR3aXE-s0qpfvL7-HMY06TqhK-f3mC1hvuHi49ByBEsQomgWRnNoGAyoopZwYPJeZMvlwgLPUeoSlbaVlyNLYte-BDhEWm1jo74tzGlE5tYUzqSJBwfUEr0YjpqGP77Lw) [Answer] # m68k assembly (GNU), 16 bytes ``` 70 00 72 01 d0 81 c1 41 b2 af 00 04 66 f6 4e 75 ``` Or in assembly: ``` begin: moveq.l #0, %d0; moveq.l #1, %d1; loop: add.l %d1, %d0; exg.l %d0, %d1; cmp.l 4(%sp), %d1; bne loop; rts; ``` Works with both the Linux and the SysV calling conventions (parameters on stack, return in %d0, %d0-%d1 are scratch registers). The c function definition is: ``` unsigned long prev_fibonacci(unsigned long num); ``` All calculations are done in 32 bit mode. 16bit is the same size, only faster. Code execution takes 22 cycles plus 46 cycles per loop iteration. (On a 68000 w/ a 16bit bus and no waitstates) [Answer] # x86-64 machine code, 10 bytes Expects input in `edx` and outputs to `eax`. ``` b8 dd bc 1b cf f7 f0 d1 e8 c3 ``` [Try it online!](https://tio.run/##ZVJhb5swEP3OrzgxIUHibLBVWtWUTdHGh0ptEtF23bROCAwkSNggIGmiLn999I6QEDIUXex3z@/d@cxHC87r@l0ieboKI7guqzCR1fvlF6WPZf9BaRKcY0UiF2fYtvwghC8JVVaofOlVUPgvXh7HXrCtovK3Zf4BG17NTXDJwNyEIcWAU7QCijymGH9uotlwLIpRw@efdmNFWWdJCAMURe28KlBw@nh7iwm0BIR1@pcGvCqAH22KqFr7KTII8EuhNwv6VJGtIQo3DDQLniWoXYb7aQraxzOU@BoWFvmbfuYKVLsQKuh7M@M00eDSYO3qWHqPhIoqMrCYvajR1ot6q0Iee9jt@xR@InW6iUOfp/eBU8h1uhQGFtY6d2cPnutMvsPf/frJvXlwDhvnp/ONwd1k7s3dmx@TJkG7yXQ2/XU3e7zHm8cflkM2IhI833YtsP6EyfBQOJW5TBZLLMhix07T7KUPVCJvD8RZAc3wEtscQ3J9cYFxODx02JLxNGqMzwTJqMMa26F9ot0dphdCeaOj5/iYq1hXKaWFxhVoIdACtPJZ4lCIzug4IzcGeuPZyBvwFVSV5jcYgOO6MBiorfKuNz8TR1fX/3ic@ouyHj3h66pHAh@jjd5R@gY) ## Explanation Disassembly: ``` b8 dd bc 1b cf mov eax,0xcf1bbcdd f7 f0 div eax d1 e8 shr eax,1 c3 ret ``` The function approximates \$\operatorname{round}(\frac{n}{\phi})=\lfloor\frac{n+\frac{\phi}{2}}{\phi}\rfloor=\lfloor\frac{1}{2}\cdot\frac{2^{32}n+2^{31}\phi}{2^{31}\phi}\rfloor\$, where \$\phi=\frac{1+\sqrt{5}}{2}\$. \$2^{31}\phi\approx3474701533\$, which fits nicely into a 32-bit integer as `0xcf1bbcdd`. Since `div r32` works on `edx:eax`, `n` can be loaded into `edx` and `0xcf1bbcdd` can be loaded into `eax` to create the numerator of the fraction, while also having `eax` as the denominator of the fraction after `div eax`. Afterwards, all that is left is to divide by two, which is handled by `shr eax, 1`. [Answer] # [rSNBATWPL](https://github.com/Radvylf/rSNBATWPL), 32 bytes ``` x~for{t=1;x>t;f=b}{b=t;t=f+t}$-1 ``` [Try It Online!](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCJnPXh+Zm9ye3Q9MTt4PnQ7Zj1ifXtiPXQ7dD1mK3R9JC0xOyIsImckMTMiLCIiLCIiXQ==) Port of R answer. ]
[Question] [ The task is simple: print `The quick brown fox jumps over the lazy dog` using as few *distinct* characters in your source code as possible. `print "The quick brown fox jumps over the lazy dog"` has a score of 29 characters, as all 26 lowercase letters appear at least once, as well as an uppercase T, spaces, and quote characters. I'm sure you can get more creative than that, though! In the event of a tie, the shorter answer will be accepted. **Validity criterion:** your language's syntax must be composed of more than 8 semantically meaningful characters. (For example, Whitespace would be disallowed for only having 3 such characters.) [Answer] ## Lua, 8 distinct characters ``` load"load\"load\\\"load\\\\\\\"load\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\5\50\\5\55\\\\0 \\5\50\\05\55\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\5\55\\5\50\\\\\\\\\\\\0\\5\ 50\\05\05505\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\05\0550\\\\\\\\\\\\\\5\50\\5\55 \\\\\\5\50\\5\55\\\\5\\5\50\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\ \\\05\\\\05\\5\50\\5\50\\\\\\\\\\\\0\\5\50\\05\0550\\5\50\\\\\\\\\\\\0\\5\50\\05 \0550\\\\\\5\50\\5\55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\\ \\\\\\\\\\5\50\\5\55\\\\\\5\50\\5\55\\\\\\\\5\\\\\\5\50\\5\55\\\\\\\\\\\\\\5\50\ \5\55\\\\0\\5\50\\05\55\55\\\\\\\\\\\\0\\5\50\\05\05505\\\\\\5\55\\5\55\\\\\\\\\ \\\0\\5\50\\05\0550\55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\ \\\\\\\5\55\\\\\\\\5\\\\5\\5\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\5\55\\5\50o\ \\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\5\55\\5\55\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\5 0\\05\0550\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\\0\\5\50\\05 \0550\50o\\\\\\\\\\\\0\\5\50\\05\55\0500\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\0 5\55\50\\\\\\\\\\\\0\\5\50\\05\0550\\\\5\\5\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\5 0\\05\55\55\\\\\\\\\\\\0\\5\50\\05\0550\\5\55\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50 \\05\55\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\05\0555\\\\\\\\\\\\\\\\\\\\\\\\05 \\\\0\\5\50\\05\55\50o\\\\\\\\\\\\\\\\\\\\\\5\50\\5\55\\\\\\5\50\\5\55\\\\\\\\5\ \\\5\\5\50\\\\\\\\\\\\0\\5\50\\05\0550\\\\\\5\50\\5\55\\\\\\\\\\\\\\5\50\\5\55\\ \\0\\5\50\\5\55\\5\50\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\\ \\5\50\\5\55\\\\\\5\50\\5\55\\\\5\\5\50\\\\\\\\\\\\0\\5\50\\05\0550\\5\50\\\\\\\ \\\\\0\\5\50\\05\0550\\\\\\5\50\\5\55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\5 5\50la\\\\\\\\\\\\0\\5\50\\05\55\50\50\\\\\\\\\\\\0\\5\50\\05\55\50\\\\\\5\50\\5 \55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50do\\\\\\\\\\\\\\\\\\\\0\\5\50\ \05\0550\\\\\\\\5\\\\\\5\50\\5\55\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\ "\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\"\\\"\\\"\"\"\"""" ``` All newline characters must be removed from this code to get single line of length 1998. Lua 5.2 required --- **How arbitrary Lua program could be written using only 8 characters `load"\05`** Having chars `05\`, it is possible to write string literal for any string consisting of chars `0257\`. Indeed, `"\\"` means backslash, `"2" == "\50"` and `"7" == "\55"` (`"\ddd"` in Lua means char with decimal code `ddd`). Having chars `0257\`, it is possible to write string literal for any string consisting of chars `024579\` (as `"4" == "\52"` and `"9" == "\57"`) On the next step chars `01245679\` will become available. One more step is required to get all decimal digits. Lua has function `load` which treats a string as Lua code and converts it to a function. E.g., `load("print\"Hello\"")()` prints `Hello`. It could be written without parentheses: `load"print\"Hello\""""` (last two quotes mean empty string which is passed as optional parameter to the function). Any Lua program could be converted to reduced alphabet within at most 5 steps. *Example:* If our program consists of single digit `9`, then only two steps are required: step 0: `9` step 1: `load"\57"""` step 2: `load"load\"\\5\55\"\"\""""` [Answer] # 64-bit Intel machine code for Linux in binary: 2 distinct characters ``` 01111111010001010100110001000110000000100000000100000001000000000000000000000000 00000000000000000000000000000000000000000000000000000010000000000011111000000000 00000001000000000000000000000000011110000000000001000000000000000000000000000000 00000000000000000100000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000100000000000000001110000000000000000001000000000000000000000000 00000000000000000000000000000000000000010000000000000000000000000000010100000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000000000000000000011001011000000000000000000000000 00000000000000000000000000000000110010110000000000000000000000000000000000000000 00000000000000000000000000000000001000000000000000000000000000000000000000000000 10111000000000010000000000000000000000001011111100000001000000000000000000000000 01001000101111101001111100000000010000000000000000000000000000000000000000000000 10111010001011000000000000000000000000000000111100000101101110000011110000000000 00000000000000001011111100000000000000000000000000000000000011110000010101010100 01101000011001010010000001110001011101010110100101100011011010110010000001100010 01110010011011110111011101101110001000000110011001101111011110000010000001101010 01110101011011010111000001110011001000000110111101110110011001010111001000100000 01110100011010000110010100100000011011000110000101111010011110010010000001100100 011011110110011100001010 ``` I refuse to rewrite it in unary. [Answer] # Python, 9 Using [this idea](https://codegolf.stackexchange.com/a/6984/7409). (The line breaks are there for readability and can be removed.) ``` exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11 +11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11 +11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1)+chr(11+11+11+ 11+11+11+11+11+11+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1+1)+chr(111+1+1+1 +1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+ 11)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+ 1)+chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1+1+1)+chr(111)+chr( 111+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(11+11+1+1+1+1+1+1+1+ 1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1)+chr(111)+chr(111+1+1+1+1+1+1+1+1+1) +chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+chr (111+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1 )+chr(111+1+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1+1+1+1+1 )+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(111+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1 +1)+chr(111+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1)+chr(11+11+11+11 +11+11+11+11+11+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+ 11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111+11) +chr(111+1+1+1+1+1+1+1+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+ 11+11+11+11+1)+chr(111)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1)+chr(11+11+11+1)) ``` This builds the string `'print"The quick brown fox jumps over the lazy dog"'` and executes it. [Answer] # dc: 4 distinct chars (384 375 363 361 360 350 chars in total) A short answer (but far from the shortest possible, I'm still working on it) using only 4 distinct characters and 384 375 363 361 360 350 characters in total, I hope you will find it entirely self-explanatory: ``` 11d1+ddd++d++dP+1+1+ddd1+ddddd1+dd1+1+ddd1+1+1+PP1d+d+d+d+d+P11+1+dP1d+d++P1d+d++PP1d+d+d++P1d+d+d+d+d+PP111dd1+1+1+PP1d+d+d++P11+1+P1d+d+d+d+d+P1d+d++P111P1d+d+d++ddd11+1+1+1+P1d+d+d+d+d+PP11+P1+1+1+dP1+1+1+dP1+1+1+dP1d+d+d+d+d+P111P1+1+1+P1+1+1+dddP11+1+1+dP1d+d+d+d+d+P1+1+P1+1+1+PP1d+d+d+d+d+P11+PP11dd+dd+d+++d1+PP1d+d+d+d+d+P1+1+1+dP111P1+1+1+P ``` The earlier answer that is slightly more verbose (it contains 13916 1's): ``` 1111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111 11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P111P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111 11/P11111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111 11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P1111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/11/P111 11/P ``` Ah, you just gotta love the ole' trusty desk calculator! [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) (GNU), 2 distinct characters (`z`, `P`), 134660653084537 bytes The behavior of `P` on number is a GNU extension. (can't post code) Anyway, this is the generator program: [Try it online!](https://tio.run/##jVRJj9owFD6TX@H6MjYESqYqGiE86iCNqkpdUDs9tBFCIThgCHbGdlhG/e/02Qlbe5nDC/Zbvve9xRR7u1Dy3V2hD4bhpwVHz6VIV2iq1VaiTO3QslwXBqkN18iCOU9e9mim5rjDZapmnNyUdzf0kGm1RuvELpBYF0pbJMyztkF9cYbj2ZTTQquUGxP4ILsvhJwfwz4LY0P0VBY5D9FPKZQ8xmWlTK1SuQkKLaQlNEiM4S6TtB2HNJnuLTdkih@GOER4KuaYMkZ67weDuz@9Hg0@nCA6uS4naZIuOFknOyNeOPuqJKfBjGdok@QlJ6LvgEO09L@0fQ/fPtLcllr@m9LEor8cH3O@Ns9W6dX/aXzpsa889pYsV4kFcNcZpxmP@0HjWPqALQcs55IYGjQ2rKYOcHAVGVqy2nhiTjatKETxZgwOU26gpFckZMQNsCNkBqEuMlMarYAw0omcc7J0mFWiVkSBXmP7I1UaJrh1IMxXugzRCkIdrcr6hh1RUSJnaNOOBsz7x11XYsPzY2shiTuEiFTGdjRuuVz@Rpu3vppWdQP8uk4XErhPTcQdz1y6IerSeo/wd27K3LodhL2c62TtSpnbRR9XYR6BBtNcpSt4I0O0EkP0BeQjyBPICOQR5DfILzHEHVPkwi2oYN1guxA5R6IVDRzpCoT6gk/Y9@y22SRRt0nAjcKsRItFR3bsksXb2lFQUHqoWMA8oKUnlwG4RD3on98FIAAdcfUxjKu57dzc1klB3BJPJvAcJ5Nzf@KoPz7f/Cyr@BbDL7hJdsDwUjfCp2V09VV6eHYXrScXhquONuoSR1Xb@/ikqr1hh@VGrfjsW2mL0rLzX0dHl5IAjxjPUvfY2xy@VdQY1CEydqauI0afRo@0U@lPqR9SWyY5Uh7fDfwqIT0/tCsezASHw18 "Python 3.8 (pre-release) – Try It Online") You can verify manually that for some smaller text (such as `abca`) it produces the correct output. It will only actually try to construct the program if the resulting program size does not exceed \$2^{16}\$ (configurable in the program) Assuming that the actual [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) implementation doesn't have any problem with having about that many numbers on the stack. I came up with the idea when someone [mentioned in chat](https://chat.stackexchange.com/transcript/message/56978380#56978380) that it's possible to solve the challenge with 2 distinct bytes. --- ### Explanation: To print out the string in dc, obviously a character printing command is required (I use `P`), and something to push to the stack is required. As far as I can see, the only commands that push something to the stack while the stack is empty are `0-9A-F` (pushes the corresponding digit/sequence of number interpreted in base 10), `.` (pushes `0.0` = 0), `_` (pushes `-0` = 0) `I/ll/O/K` (pushes 0/0/10/10 by default), `z` (push the number of values currently in the stack). Of those only `z` have the potential to produce *any* values. Therefore, with only `z` and `P`, at any time the stack is `[0, 1, 2, ..., n]`, and `P` will print the value corresponding to `n` and pop `n`. > > the integer portion of its absolute value is printed out as a "base (UCHAR\_MAX+1)" byte stream > > > So the program \$\text{‘z'}^{a\_1} + \text{‘P'} + \text{‘z'}^{a\_2} + \text{‘P'} + \text{‘z'}^{a\_3} + \ldots + \text{‘P'} + \text{‘z'}^{a\_n} + \text{‘P'}\$ will call `P` on \$a\_1-1, a\_1+a\_2-2, \ldots, (a\_1+\ldots+a\_n-n)\$. [Answer] # dc - 5 distinct characters (2,i,1,0,P) ``` 2i01010100011010000110010100100000011100010111010101101001011000110110101100100000011000100111001001101111011101110110111000100000011001100110111101111000001000000110101001110101011011010111000001110011001000000110111101110110011001010111001000100000011101000110100001100101001000000110110001100001011110100111100100100000011001000110111101100111P ``` [Answer] ## GolfScript (4 distinct chars, 441 chars total) ``` 11(11+11+11+11+11+11+11+(((111(((((((111((((((((((11(11+11+111(1+1+1+111(11+((((111((((((111((((((((((((111((((11(11+11+111(((((((((((((111(1+1+1+1+111(1+111(11+((111(11(11+11+111(((((((((111(1+111(11+(11(11+11+111(((((111(11+((((111((111(1+1+111(11+((((((11(11+11+111(1+111(11+(((111((((((((((111(1+1+1+1+11(11+11+111(11+(((((111(((((((111((((((((((11(11+11+111(((111((((((((((((((111(11+1+111(11+11(11+11+111(((((((((((111(1+111((((((((](+ ``` Chars used: `]1(+` Explanation: in GolfScript, adding a string to an array of integers converts the array into a string with the integers as codepoints and then concatenates the two strings. If nothing is supplied on stdin, the stack starts with an empty string. So we can build an array of integers with the right codepoints and then concatenate to that empty string. We'll need `+` for the concatenation, `]` at minimum to create the array (and either `[` to prevent the empty string from being included in it or some way of extracting it afterwards), and some way of separating the integers. So I use the decrement operator `(` to separate the integers, which requires some extra additions to compensate in some cases but gives a quick way of getting e.g. 110; and that operator is also the operator to extract the first element from an array, so it serves to retrieve the empty string for concatenation. [Answer] # Tcl 10 different chars. ``` \160\165\164\163 \124\150\145\40\161\165\151\143\153\40\142\162\157\167\156\40\146\157\170\40\152\165\155\160\163\40\157\166\145\162\40\164\150\145\40\154\141\172\171\40\144\157\147 ``` Characters used: , `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `\` It's just each part of the command encoded as \ooo sequence. For Tcl, it does not matter if you do such funny things in the command name or in his arguments, in fact the `$object configure` is very common in Tcl/Tk. With this technique and `eval` you could even write every program in Tcl with 10 different bytes :) Test program: ``` set code [read stdin] puts "Characters used: `[join [set ch [lsort -unique [split $code {}]]] {`, `}]` puts "Number of different characters: [llength $ch]" ``` [Answer] ## J, 6 distinct chars 6 distinct char version (`u:10 +`) using some idea [flornquake](https://codegolf.stackexchange.com/a/11342/7311) used. The method is adding vectors of `0` `1` `11` and `111` together to add up to the desired `84 104 101 32 113 117 ...` vector: ``` u:11 11 11 11 111 111 11 11 11 11 11 111 111 111 11 11 11 111 111 11 11 111 11 111 111 11 111 111 11 111 11 111 11 11 11 11 11 111 111 11 11 111 11 + 11 11 11 11 1 1 11 11 11 11 11 1 0 1 11 11 11 0 1 11 11 1 11 1 1 11 0 1 11 1 11 1 11 11 11 11 11 11 1 11 11 0 11 + 11 11 11 1 1 1 11 11 11 1 11 1 0 1 11 1 11 0 1 1 11 1 11 0 1 1 0 1 11 1 1 1 11 11 1 11 11 0 1 1 11 0 11 + 11 11 11 1 0 1 11 11 11 1 11 1 0 1 11 1 11 0 1 1 11 1 11 0 1 1 0 1 11 1 1 1 11 11 1 11 11 0 1 1 11 0 11 + 11 11 11 1 0 1 11 11 11 1 11 0 0 1 11 1 11 0 1 1 11 1 11 0 1 1 0 1 11 0 1 1 11 11 1 11 11 0 1 1 11 0 11 + 11 11 11 1 0 1 11 11 11 1 11 0 0 1 11 1 11 0 1 1 11 1 11 0 0 1 0 1 11 0 1 1 11 11 1 11 11 0 1 1 11 0 11 + 11 11 11 1 0 1 11 11 11 1 11 0 0 1 11 1 11 0 1 1 11 1 11 0 0 1 0 1 11 0 1 0 11 11 1 11 11 0 1 1 11 0 11 + 1 11 11 1 0 0 11 11 11 1 11 0 0 1 11 1 11 0 1 1 11 0 11 0 0 1 0 1 11 0 1 0 11 11 1 11 11 0 1 1 11 0 11 + 1 11 11 1 0 0 11 11 11 1 1 0 0 1 11 1 11 0 1 1 11 0 11 0 0 1 0 0 11 0 1 0 11 11 1 11 1 0 1 1 11 0 11 + 1 1 1 1 0 0 1 0 1 1 1 0 0 0 11 1 1 0 1 1 1 0 1 0 0 1 0 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 1 + 1 1 1 1 0 0 1 0 1 1 1 0 0 0 0 1 1 0 0 1 1 0 1 0 0 1 0 0 1 0 1 0 1 1 1 1 1 0 1 1 0 0 1 + 1 1 0 1 0 0 1 0 1 1 1 0 0 0 0 1 1 0 0 1 1 0 1 0 0 1 0 0 0 0 1 0 1 0 1 1 1 0 0 1 0 0 1 + 1 1 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 1 + 1 1 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 + 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The quick brown fox jumps over the lazy dog ``` **Edit**: `1+:1` is `0` so maybe there is a 5 char solution here... (Also `+:` as double could be used to shorten the solution.) 13 distinct char version: ``` u: 84 104 101 32 113 117 105 99 107 32 98 114 111 119 110 32 102 111 120 32 106 117 109 112 115 32 111 118 101 114 32 116 104 101 32 108 97 122 121 32 100 111 103 The quick brown fox jumps over the lazy dog ``` Anonymous user's (DirkL) improvement: shorter solution but still using 6 characters (`u:23 |`) is possible. Using `|` as residue operator for decimals e.g. `223 | 2333333 = 84`. ``` u:223|2333333 232333323 3223 32 23223333 23222222 323232 322 32333323 32 322333 232333333 3233 2323333 3232 32 2332 3233 32232 32 323233 23222222 2323323 23223332 3223333322 32 3233 2323332 3223 232333333 32 32333332 232333323 3223 32 2323322 322332 32332223 32233 32 323 3233 2333 The quick brown fox jumps over the lazy dog ``` [Answer] ## C, 15 distinct chars Some inspiration from Fors's answer (which I beat by a character) and ecatmur's comment to that answer. Spaces and newlines are only for clarity, and are not counted. How it works? 1. Each group of 3 characters is represented in a number. A pointer to this number, treated as a character pointer, is a pointer to a string of these 3 characters, plus a terminating null. Assumes little-endian. 2. The function `a` helps get the address of a literal number, without defining a variable. ``` a(i){if(printf(&i)){}} main(){ if(a(1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+1111+111+111+11+11+11+11+11+11+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1+1+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+11111+11111+11111+1111+1111+1111+1111+11+11+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+11+11+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+111+111+111+111+111+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+11+1+1+1+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+1111+111+111+11+11+11+11+11)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+1111+1111+1111+1111+111+111+111+111+111+11+11+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+11+11+11+11+11+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+11111+11111+111+111+111+111+111+111+111+111+111+11+11+1+1+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+1+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)){} if(a(1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+111+11+1+1+1+1+1+1+1+1)){} if(a(1111+1111+111+111+111+11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)){} } ``` [Answer] # Befunge-98, 4 distinct characters (1047 characters in total) ``` "@@@,,,,,,,,,,,,,,,"+++++++++++++++++,",,,,,,,,,,,,,,"+++++++++++++,"+++,,,,,,,,,,,"+++++++++++++,"@@@,,,,,,,,"++++++++++,"@+++,,,,"+++++++,"@@@+++,,,,,,,"++++++++++++,"@@+++,,,,,,,,,,,,,,"++++++++++++++++++,"@@+,,,,,,,,,,"++++++++++++,"@+"+,"@@@,,,,,,,,"++++++++++,"@@++,,,,,,,,,"++++++++++++,"@++,,,,,"+++++++,"@@@+,,,"++++++,"@@@+,,,,,,,,,"++++++++++++,"@@@++,,"++++++,"@@@,,,,,,,,"++++++++++,"++,,,,,,,,,,,,"+++++++++++++,"@@@+,,,"++++++,"@@@,,,,,,,,,,"++++++++++++,"@@@,,,,,,,,"++++++++++,"@@++,,,,,,,,,,,,,,,"++++++++++++++++++,"@@@+++,,,,,,,"++++++++++++,"@@@+++,"++++++,"@@@,,,,"++++++,"@+,,,,,,"+++++++,"@@@,,,,,,,,"++++++++++,"@@@+,,,"++++++,"@@@++,,,,,,,,"++++++++++++,"+++,,,,,,,,,,,"+++++++++++++,"@++,,,,,"+++++++,"@@@,,,,,,,,"++++++++++,"@,,,,,,,"+++++++,",,,,,,,,,,,,,,"+++++++++++++,"+++,,,,,,,,,,,"+++++++++++++,"@@@,,,,,,,,"++++++++++,"@,"+,"@@+++,,,,,,,,"++++++++++++,"@++,,,,,,,,,,,"+++++++++++++,"@+++,,,,,,,,,,"+++++++++++++,"@@@,,,,,,,,"++++++++++,"@@,,,,,,,,,,,"++++++++++++,"@@@+,,,"++++++,"+,,,,,,,,,,,,,"+++++++++++++,@ ``` If non-terminating answers are allowed, then this can be done in 3 distinct characters: ``` "++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"++++++++++++++++++++++++++++++++++++,",,,,,,,,,,,,,,"+++++++++++++,"+++,,,,,,,,,,,"+++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"+++++++,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,"+++,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,"+++++++,,,,,,,,,,,,,"+++++++++++++++++++,"+++++,,,,,,,,,"+++++++++++++,"+++++,,,,,,,,,,,,,,,"+++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"++++++,,,,,,,,"+++++++++++++,"++++++,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,"+,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++,"+,,,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,"++,,,,,,,,,,,,,,,,,,"+++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"++,,,,,,,,,,,,"+++++++++++++,"+,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"++++++,,,,,,,,,,,,,,"+++++++++++++++++++,"+++,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,"+++,,,,,,,,,,,,,,,,,"+++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++,"+++++,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"+,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++,"++,,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,"+++,,,,,,,,,,,"+++++++++++++,"++++++,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"++++,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++,",,,,,,,,,,,,,,"+++++++++++++,"+++,,,,,,,,,,,"+++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"++++,,,,,,,,,,,,,,,,"+++++++++++++++++++,"+++++++,,,,,,,"+++++++++++++,"++++++,,,,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++++++++,"+++++++,,,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++++++++++,",,,,,,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++++++,"++++,,,,,,,,,,"+++++++++++++,"+,,,,,,,,,,,,,,,,,,,"+++++++++++++++++++,"+,,,,,,,,,,,,,"+++++++++++++,"+++,,,,,,,,,"+++++++++++, ``` Uses [this](http://mearie.org/projects/pyfunge/) Befunge-98 interpreter. At first, I joined the 4-character competition with an `@` at the end to terminate . This program repeatedly outputs `The quick brown fox jumps over the lazy dog\r`, where the terminating `\r` deletes the previous sentence. Therefore, the sentence is written once. [Answer] # Ruby: 7 distinct characters (With thanks to [randomra](https://codegolf.stackexchange.com/users/7311/randomra) for his [comment](https://codegolf.stackexchange.com/questions/11336/print-a-string-in-as-few-distinct-characters-as-possible/11353#comment21538_11342).) ``` $>.<<""<<11+11+11+11+11+11+11+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<111+1+1<<111+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1<<111+1+1+1<<111<<111+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+11<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1<<111<<111+1+1+1+1+1+1+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1<<111+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1<<111+1<<111+1+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<111<<111+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1<<111+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<111+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<111+11<<111+1+1+1+1+1+1+1+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1<<111<<11+11+11+11+11+11+11+11+11+1+1+1+1 ``` Sample run: ``` bash-4.2$ ruby distinctchar.rb The quick brown fox jumps over the lazy dog ``` Counting: ``` bash-4.2$ sed 's/./&\n/g' distinctchar.rb | sort -u | wc -l 7 bash-4.2$ sed 's/./&\n/g' distinctchar.rb | sort | uniq -c 88 < 1 > 1 . 2 " 1 $ 384 + 637 1 ``` [Answer] # Java: 18 distinct characters ``` \u0063\u006C\u0061\u0073\u0073\u0020\u0054\u007B\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0020\u0061\u0029\u007B\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0054\u0068\u0065\u0020\u0071\u0075\u0069\u0063\u006B\u0020\u0062\u0072\u006F\u0077\u006E\u0020\u0066\u006F\u0078\u0020\u006A\u0075\u006D\u0070\u0073\u0020\u006F\u0076\u0065\u0072\u0020\u0074\u0068\u0065\u0020\u006C\u0061\u007A\u0079\u0020\u0064\u006F\u0067\u0022\u0029\u003B\u007D\u007D ``` A Java program can be written in UNC notation... But it remains verbose! [Answer] # JavaScript (in Chrome Console) 17 I had the same idea as flornquake but he beat me too it. So I went for the ugly way to do this! ``` [constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+"q"+[constructor+[]][+![]][+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]]+"k"+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][+![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]]+"x"+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+"z"+"y"+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]]+[constructor+[]][+![]][!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]] ``` [Answer] ## vba (16 8 distinct characters) (using ideas from matatwork and AutomatedChaos) ``` ?Chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1)Chr(11+11+1+1+1+1+1+1+1+1+1+1)Chr(111+1+1)Chr(111+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1)Chr(11+11+1+1+1+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)Chr(111+1+1+1)Chr(111)Chr(111+1+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+11)Chr(11+11+1+1+1+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1+1)Chr(111)Chr(111+1+1+1+1+1+1+1+1+1)Chr(11+11+1+1+1+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)Chr(111+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)Chr(111+1)Chr(111+1+1+1+1)Chr(11+11+1+1+1+1+1+1+1+1+1+1)Chr(111)Chr(111+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)Chr(111+11)Chr(111+1+1+1+1+1+1+1+1+1+1)Chr(11+11+1+1+1+1+1+1+1+1+1+1)Chr(11+11+11+11+11+11+11+11+11+1)Chr(111)Chr(11+11+11+11+11+11+11+11+11+1+1+1+1) ``` note that if you want to put this in, you would have to break the line into 2, as it's too long for the VBA editor > > Code: 40 '(' Count: 37 > > Code: 41 ')' Count: 37 > > Code: 43 '+' Count: 331 > > Code: 49 '1' Count: 552 > > Code: 63 '?' Count: 1 > > Code: 67 'C' Count: 37 > > Code: 104 'h' Count: 37 > > Code: 114 'r' Count: 37 > > -----TOTAL CHARACTERS: 1069 > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 distinct bytes ``` ‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ọ ``` [Try it online!](https://tio.run/##7dVBDcAgEEVBS5jiQjDArQIQgBfUgJHlXgkwyTPQ@Slbcq0tYn/j2dbs6eXvZ3cdmVmwIsYnWM6ZNUQWKGi5d5YRUM@KCCJGKaaOoIBSRibvtA3FzpNhK2EijtukfgGg@sFFHA "Jelly – Try It Online") [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 3 distinct characters (1ZP), ~~4143~~ 3707 bytes A trivial dc solution is to use as many `1`s as the ASCII code of a character (except for 'o'), then to print the size of the (unary) number with P. No arithmetic necessary! ``` 111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111P11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111P111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP111P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP11111111111111111111111111111111ZP1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP111P1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111ZP ``` [Try it online!](https://tio.run/##7ZbBDcAgDANnyiZ550v3XyFILEA/9bmILHCyYxye0R0fTGWIRkTaY3SSSaQYK0FJbfQIEpGcxWQSqxfs0xeo7Wa9eX5hMioRX19GK@PknWNFbvjO7qfz/7ILu1Qo22XT0sas7J4) I used the following bash code, not golfed, to generate the above dc script: ``` echo "The quick brown fox jumps over the lazy dog"|fold -1|while IFS= read -r c;do [ "$c" = "o" ] && echo 111P || yes 1|sed "$(echo -n "$c"|od -An -tuC)"q|paste -sd ''|sed 's:$:ZP:' done|paste -sd '' ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) (GNU), 3 distinct characters (`z|P`), 453 bytes Generator program: [Try it online!](https://tio.run/##nVZtb@NEEP5s/4qp@6F260RJ@@WI2EMHBQkJ0cIdnyILre11s9Te9XnXTX3AX6fMvtiJ27siISVRdmZ2Xp55Zux20Dsprt603dOTItGHHYOPPS/uIe/kXkAlH@GPvmkVyAfWgUZ1TT8NUMq7aMlEIUsWn/VvzpKwoY/XrNU7crlahWHVyQb00HJxB7xpZafhJ650Cjet5lLQOoXvaF3TvGYp/CZQlMKHvjWnd2JI4ZoXOvQXnZvxpPq87WTBlBolVS8KLWU9CdSgQvwuFdMdK/pOofuaN1zH69X5@VdJGL7XtLj/nWAoOAVa6B5zGcBKU8h7Dc3QmiKZEmcmZGv9FkNR8wJKVnHBTRnOD7H5b3@Wgvkits5/ClzoLAvD8LSQQvESETRWoCXkzIK5l53CALozFaJjlGvNuphuJqS2qM0wq2eSZPF2dt6EAa@AAlc2xgY6pvtOQB4GrEZN/kJDw8D/a7iIKYZI4Z4NpGYCITLJVDXFbESsTDkbh0/iAlnRc5dhMHBWl2C7P7u8XWXJqHWCdeZiIK14NcxCpAgxMmlj4EtB9M01ryp7MsGpUgybYU2ISTbens9iJSaUt/KXCVF9E/MT8oCM7oCn8IDugKGadVSzz7hACE5tHR971rORxL@Yg2N3IeuaFaYDatSWDI2RUYrfCV7xggqNtKqowpYul0tDF83IEUVSV@L4k4XKWKiN5/zy2jjc2msZsd7jJMyZ0hs7IU6TGv5k5M@/Q0tLWpPYcXHlPon3uqRty0QZeyvnaOtPGYki15A7KctYsEdtnduWaIZsy3HEEH511KGpOSngmJHp0kSsSQJCaoO4CQlUlBCHQRDMSATYmJErRzJj56Ms4pE6J8TGX6yTxcSvI/FlQsjKXEywGW3XC7OGcARLN7Vh2DHV15qYEOF@x2sGHvhX68Ov66DHs5XYyErHR3TDKlucZR1/2Q1aH3P@uQ3yLrCBzEogtkVjXJyY2eiZaBYlA@gIDVLdXMg2WDra6B3@0HpPB1zhuC8aWn@DyKAbNLpYuwFSZq6CwKMyRb@IbiM4bXpsmV9Xaoc0Ny3sGC12ZnuDiZ@zgvaKwbc/vDcb7V6ZVnNRoJUy0Je4@qkoTDtxB5pQOarusRzcTYrZ4BNVyNRRD81iPYHzOQakrpLEOOHP6esKCyyMkzCbl2gt5iNyuO8gt7Eu1l@T8Sln3B5lPGtlko72Lxr/pQRfye9TFL6W3pTdW3JlXHkivuAIquIYG4yLhmKCuYGNWCvPhhOyet4HC0zgb8W6aS83pJV7/6gokmSsdHGZOltfrjssYjp26SoZRflhRkdRceilE13YWIe73jmC4v7831b/9V@t9uC5OZih54Y6@tVqNhCl3iiZawCn6c48udDADJY3mqze2VcNkL1ue@fm8DqzxD0Vx1FZoDRasEOI1CylEu@QI@PbH2@/R0WydCpM/unpH2lfCNTT4ubmXw "Python 3.8 (pre-release) – Try It Online") Because there can be a lot of possible different states of the stack, this solution prunes the states to be considered (only the topmost 2 can have value different from the default value pushed by `z`); therefore the result might not be optimal. (after thinking about it for a while, turns out that finding a good solution is terribly hard) ### Analysis There are some options of using a digit, an arithmetic operator and `P`. Possible cases for the arithmetic operator are: * `+`: 1065 bytes. (proven to be optimal) Throws a lot of errors. Generator program: [Try it online!](https://tio.run/##pVdbb9s2FH62fgWrYIhoy4adoUAnVMaKtQ8FgqZot2KAESS60DZbWVJJKrFb5K8vO@eQki3X7QrsxRF57offuaTemXVV/vqsVo869v9cC/a5kdknlqrqvmTLass@Nptas@pOKGaAXCRfdiyvVv5ElFmVi@C8eXbOH5eq2jCzq2W5YnJTV8qwS6lNyK5qI6syKUL2R1IUSVoIz9H1TrefstS1yEx7tHra0yYx606mSWtVZUJ3osumzExVFdrzQOFEC6NE1igNRgu5kSaYTYfD37jn/d5xTgrV3GRJthbBJtlq@UXEb6pScC8XS7YS5kNSNCKQEbgFAXykv3w8h9@IKWEaVeLNBEO@SXdG6EAvZPTxOmR@Klc@2DrLqlLLHFKGipmpWCooe/eV0hCFURgfmkuFMUIFSdQlagFUUJUe3YADvXPkDeSSJUxqstF5lnoDUQAl/YaSeAP3tZFlkICJkH0Su7gQJbgMmXgpV9LEF9PplFzTVXEnghwv2xSAYbDrDfbkVGjzTtQq6p53saC0LYsqMddhP4hTUQxaFfF/PlBnjZ@B3E886IA8haR/CgqxNO5FlVytu5C@cQfTisxx7Phc0nwfiegBKcfDslKQyzwvBChjKilXguyMZs7IaMZJ5QDcuhTlyqxjRPNElku6PgNbTkFZYRmwvjxnSZmzwGzqKO6iCJ0I5/jEKGefeW8DXhRlONmAYojbvAUdunuKwr2slQG3QKxDEN0NEq0FliPJPIlbR3uqQnbaglU7gLIwsmxE69iFjaqVtTEfeHCxB3FPlF7BlQ5@h8g88t/6IxQiDW05ANXrTmRtGjJMkAanAMkI7/cGwOd/tVD/@8GH@zuMIZ66Dx3bljTJEm0CbGwIckD3Ap275uyMlc0mhXqvlozUaDaeI8I8AsnNHh9tnREwrBX6Hc6mI5Jsr/UkqWtR5gGdyFfAcim25nWZi@37z8pY0mF/AmGfgPrOBow9R2@gMiEN7Fai4C000WwNlARurKUFEa5v2Tx2V7chA7dVIrVgZO6VUpWadOpJALC8DQABYNh6MkmluSkIRwEfEtKLajWbBhecj@lZHIaseDxDIz0XntMJQEXHsE90R9Rzv5ZQMydEI6t7FM/21npshzWzBwbRXIrbYjnK8EGRRLa7neoeFvUE5NjFQn9G6A9gBJUirAZG7aiuepEEZRT3Xxj1cX49d82orY1y5HTND5xysbTdiXyhMh3iD11Zx@h3SL9063TZpLUpaStjWI78O3/oeIBBbDNRmwNYRAdSZNz7cW/GifyU95P9Is9/mGu6IZPU3Wy@@Hh26g0gP0T/hUJ4Ek97qYFabUpsBDCsdkwX1T27l7AENbB3rKXewwZRUisEN/SGc3Y@RMNuU5lok2TQSjh/yKC6cOv5SjYf2NfOdftNTj/4/AiP86nXnyaupGA0t0JHbdkihdjmUzupOhF5gr9XbGSuy0xbDLHFaPSdptpBgLi7xozE740e57892UaL7HYA0GJyqmi9g/nyk2kPTuabtD5wbL6OYdyzd8g@tsydkP/tvOxQOT5qREdKQtbPkBueXYLs9LOExXh2/ST2R35EQwu/3HBs1CzGq37aRx0DLSZlgHz8ebyvEEs9PRRnbvL@r3cjP8a2O5zQQ0uKBfVTWB73qyjynbGVEiLfMZyDRaJWbbNjAWzyKRVhBRUMQ4p7/bHtdQvr4fSFKg8ZbV9di1EibzLcRTF2GB4Ucn8/xd7FwxMEeGJ3b2OFQespoZvCUE6Cgy2YUwz0uZ/nMP9mT2HP426ZTjZpnrBtxNpFj0HGtu0ew0QBExWzuwVzFub@OzIXMR8GB30eUVjhOqFvH8YxdVwvMtMkBYMOVjdWzf7fpIlqIAg/z@DWH4u9CYhZmxxk4gPmt6/fvgLCGVCEUoeUl68@vPnr8hKIfGLluPf4@E9FvVc/jq@u/gU "Python 3.8 (pre-release) – Try It Online") * `v`: 7617 bytes. (proven to be optimal) you can get it from the generator program above by removing the `solve(bestReprAdd),` line in the generator) * `-`: will probably result in the approximately-same or slightly-shorter program. * `%`: obviously impossible. (because, for example, `11111` mod `111` is `11`, so the constructible values are those already constructible with a literal or 0) * `~`: (unfortunately) also impossible because there's no way to discard the remainder without printing it out. * `/` and `|`: should be possible. Analysis pending. * `*` and `^`: probably impossible, because there can only be a small set of representable numbers. * `i`: An interesting possibility (`11i` to increase the input base, `1i` to set the input base to 1); however the input base must be between 2 and 16, so there's no way to decrease the input base, so it's not very likely to work. Other alternatives: * `z`, `P`, (arithmetic operator): Terribly hard to analyze. Using `zP|` results in the solution above. Some specific cases: + `+`, `-`: Should be possible. Analysis pending. + `v` and `~`: This can only decrease the value on the top of the stack without reducing the stack depth, so I think it's impossible. + `%`: Equivalent to `o` in this particular case, because `x%(x+1)==x`. + `/`: Obviously impossible because `x/(x+1)==0` and `x/0` raises an error. + `|`: Possible. (this also decrease the stack depth by 2 each time instead of 1) Used in this answer. + `*` and `^`: Because there can only a limited number of possible results, I'm not very sure this is useful.Note that "impossible" means "impossible to do efficiently", because `zP` alone is sufficient. * `z`, `P`, `o` (since the output radix is not used, it's the same as pop the stack and do nothing in this challenge): [1601 bytes](https://tio.run/##VZBNawIxEIbP5lcMuZil60LpRcQtlNJDoVApvYmHuBvd1JiZ5qNW//w27lo/bkme531nCO1Dg/ZhTK5tfck/GwXfUVcbWDrcWVjhL3zFLXnAH@UgJGzkYQ81rnmhbIW1EsM4HmaMrRxuIexJ2zXoLaEL8KZ9yOGdgkYrTQ7P0hi5NIqduI9Lclgp7xlzykcTSs6ZD7LaTLrwXNuwKOcLtkIHGrQFP2GDXaONAoup4KhCYt1hPrpfTHUSBn3ZXckPPN06WEgiZWthlBXdQ5b9N53Dj7dhvIQJSST/jGYJXRNGLq0q@EcnTIDn0LvZLYE0fh2aTjhucpLO1lMVojSAMVDsay5/VLhoheB1lV75SF1G5Mdd6pQpr@TZ6@wlgazoUda2fw "Python 3.8 (pre-release) – Try It Online") (obviously optimal). [Answer] # [naz](https://github.com/sporeball/naz) `-u`, 3 distinct characters I've been waiting for a chance to do this. It turns out that JavaScript's `String.fromCharCode()`, which the naz interpreter uses internally for output, will *truncate* any values passed to it to their four least significant digits in hexadecimal — so passing a value of \$41\_{16}\$ (\$65\_{10}\$) will return `A`, but so will passing \$10041\_{16}\$ (\$65601\_{10}\$). The upper \$1\$ is ignored. This essentially means given a function \$f(x)\$ which returns `String.fromCharCode(x)`, $$ \forall x \in \mathbb{Z}\_{0}^{+}: f(x) = f(x \bmod 65536) $$ making it possible to write a naz program to output any string using only the characters `1`, `a`, and `o`, as long as the `-u` command line flag (which removes naz's default integer limits) is used. The code to output `The quick brown fox jumps over the lazy dog` via this method, which I've now [stored in naz's GitHub repository](https://github.com/sporeball/naz/raw/master/examples/cg/generated.naz) (right-click > "Save linked content as" will work best), is over 5,500,000 bytes in size and finished running in just over **60 minutes** on my machine. You probably shouldn't run this if you need to do other things with your terminal. *Note: As of March 12, 2021 I've added a comment to the top of the file linked above, but this is simply a warning to anyone who happens to find it without reading this answer. The program works identically without it, so the header will contain the original score — **3 distinct characters**.* The best score that can be achieved without the `-u` flag is **4 distinct characters** (`1`, `a`, `s`, and `o`.) [Answer] # Javascript, 6 characters ``` [][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]])()((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[+!+[]+[!+[]+!+[]+!+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[(![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]]((+((+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+[+[]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+!+[]]])+[])[!+[]+!+[]]+[+!+[]])+(![]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]])()())[!+[]+!+[]+!+[]+[+[]]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]([+[]]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]])[!+[]+!+[]+[+[]]]+([][[]]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+[+!+[]])+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(+(!+[]+!+[]+!+[]+[!+[]+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]])+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+(+[![]]+[+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]]+[+[]])])[+!+[]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[+[]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+([+[]]+![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[!+[]+!+[]+[+[]]]) ``` Compiled using JSf\*ck. Not creative, but does the job... [Answer] ## PHP. 10 distinct characters. `e, c, h, o, r, (, 1, +, ), ;` (Line breaks can be removed.) ``` echo(chr(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+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+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+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1)); echo(chr(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+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+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+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+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1)); echo(chr(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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(111)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1)); echo(chr(111)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1)); echo(chr(111+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(111)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1)); echo(chr(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+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+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+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+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+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+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+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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)); echo(chr(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+1+1+1+1+1+1+1)); echo(chr(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+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+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+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)); echo(chr(111)); echo(chr(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+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+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+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+1+1+1)); ``` [Answer] # [Julia](http://julialang.org/), score 10, 578 bytes ``` print('i'-('t'-',')-('-'-'i'-('i'-'r')),'i'-('-'-','),')'-('-'-'i'),')'-('r'-'i'),'-'-(','-'p'),')'-('('-'t'),'i','n'-('t'-'i'),'n'-(','-')'),')'-('r'-'i'),'i'-('p'-'i'),'r','r'-(','-')'),'-'-('('-'r'),'n',')'-('r'-'i'),'i'-(','-')'),'r'-(','-')'),','-('('-'t'),')'-('r'-'i'),')'-('-'-'n'),')'-('('-'t'),')'-(','-'p'),'p',')'-('('-'r'),')'-('r'-'i'),'r'-(','-')'),','-('('-'r'),')'-('-'-'i'),'r',')'-('r'-'i'),'t','i'-('-'-','),')'-('-'-'i'),')'-('r'-'i'),'('-(','-'p'),'('-(','-'p')-('t'-'i'),'t'-('n'-'t'),'-'-('('-'t'),')'-('r'-'i'),'('-('-'-'i'),'r'-(','-')'),'p'-('r'-'i')) ``` [Try it online!](https://tio.run/##lVBbCgMgDDtOLNiPHWmfjiFSHOz2zgeVum6D4TOapk1vj3u6Xp6tFUm5BiRwQAUjgvqN@5hPfYOAKC7Ii9EnNkuRKOKBxlH23@BWTJWIrLkmOyubvNLMWRQJxrJsVm1ZSh/jN/uMjUddZ9x2l70DOtwVmH/xSl9yiu@huOor/ul6OOqyyHa7jvesXvhHD8JbddZHMUxq7QU "Julia 1.0 – Try It Online") the 10 characters used are `print()'-`. I don't think less is possible. Then, we use character arithmetic with the available characters (`'b'-'a'==1` and `'b'-1=='a'`) [Answer] # C: 16 distinct characters ``` main(a){putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a);putchar(a+a+a+a+a+a+a+a+a+a);} ``` [Answer] # Postscript (19 distinct characters) ``` <54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67>= ``` Uses the hexadecimal digits 0-9, a-f, hex-string delimiters < >, and = to print. # (13 distinct characters) ``` ( )dup 0 2#1010100 put dup print dup 0 2#1101000 put dup print dup 0 2#1100101 put dup print dup 0 2#100000 put dup print dup 0 2#1110001 put dup print dup 0 2#1110101 put dup print dup 0 2#1101001 put dup print dup 0 2#1100011 put dup print dup 0 2#1101011 put dup print dup 0 2#100000 put dup print dup 0 2#1100010 put dup print dup 0 2#1110010 put dup print dup 0 2#1101111 put dup print dup 0 2#1110111 put dup print dup 0 2#1101110 put dup print dup 0 2#100000 put dup print dup 0 2#1100110 put dup print dup 0 2#1101111 put dup print dup 0 2#1111000 put dup print dup 0 2#100000 put dup print dup 0 2#1101010 put dup print dup 0 2#1110101 put dup print dup 0 2#1101101 put dup print dup 0 2#1110000 put dup print dup 0 2#1110011 put dup print dup 0 2#100000 put dup print dup 0 2#1101111 put dup print dup 0 2#1110110 put dup print dup 0 2#1100101 put dup print dup 0 2#1110010 put dup print dup 0 2#100000 put dup print dup 0 2#1110100 put dup print dup 0 2#1101000 put dup print dup 0 2#1100101 put dup print dup 0 2#100000 put dup print dup 0 2#1101100 put dup print dup 0 2#1100001 put dup print dup 0 2#1111010 put dup print dup 0 2#1111001 put dup print dup 0 2#100000 put dup print dup 0 2#1100100 put dup print dup 0 2#1101111 put dup print dup 0 2#1100111 put dup print dup 0 % 1 2 3 4 5 6 7 8 9 0 1 2 3 % 0 1 2 # d i u n p r t ( ) ``` Binary radix numbers get the data in 4 chars (0,1,2,#), but it needs an empty string ( ) and some letters (put, dup (-up), print (-pt)) to insert the binary number in there. [Answer] ## APL 8 The following command converts a character string to its binary equivalent: ``` s←11 ⎕dr "The quick brown fox jumps over the lazy dog" ``` If we assign the resulting binary to the vector s to avoid having to display all the zeros and ones then we can print the result by reversing the process by applying: ``` 82 ⎕dr s "The quick brown fox jumps over the lazy dog" ``` So the 8 unique characters are 8,2,⎕,d,r,space and the 0 and 1 in the binary vector s. [Answer] # k 12 distinct characters ``` 1'10h$2/:'(01010100b;01101000b;01100101b;00100000b;01110001b;01110101b;01101001b;01100011b;01101011b;00100000b;01100010b;01110010b;01101111b;01110111b;01101110b;00100000b;01100110b;01101111b;01111000b;00100000b;01101010b;01110101b;01101101b;01110000b;01110011b;00100000b;01101111b;01110110b;01100101b;01110010b;00100000b;01110100b;01101000b;01100101b;00100000b;01101100b;01100001b;01111010b;01111001b;00100000b;01100100b;01101111b;01100111b); ``` The characters are `10h$2/:'(b;)` [Answer] ## K, 9 ``` 1@10h$(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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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;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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+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+1+1+1+1+1+1+1); ``` 1 @ 0 h $ ( + ; ) [Answer] # Perl, 10 chars Basically a rip-off of flornquake's Python solution. Using substitution with `ee` is a cheaper way to get `eval`. Unfortunately, Perl uses `.` for concatenation, which adds a character. I was hoping to eliminate parentheses (which are optional for functions in Perl), using a syntax like this: ``` s ss char 111+1 ... see ``` (Yes, `s` is a valid regex delimiter). However, I couldn't get that to work because the precedence of `.` is too high, trying to concatenate before it calls the function. ``` s()(chr(111+1).chr(111+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1).chr( 11+11+11+11+11+11+11+11+11+11).chr(111+1+1+1+1+1).chr(11+11+11+1).chr(11+11+11+ 11+11+11+11+1+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1).chr(11+11+ 11+11+11+11+11+11+11+1+1).chr(11+11+1+1+1+1+1+1+1+1+1+1).chr(111+1+1).chr(111+1 +1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1).chr(11+11+11+11+11+11+ 11+11+11).chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1).chr(11+11+1+1+1+1+1+1 +1+1+1+1).chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1).chr(111+1+1+1).chr( 111).chr(111+1+1+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+11).chr(11+11+1+1+ 1+1+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1).chr(111).chr(111+1+1+1+1 +1+1+1+1+1).chr(11+11+1+1+1+1+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1 +1+1+1+1).chr(111+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1 +1).chr(111+1).chr(111+1+1+1+1).chr(11+11+1+1+1+1+1+1+1+1+1+1).chr(111).chr(111 +1+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1).chr(111+1+1+1).chr(11+11+1+ 1+1+1+1+1+1+1+1+1).chr(111+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1) .chr(11+11+11+11+11+11+11+11+11+1+1).chr(11+11+1+1+1+1+1+1+1+1+1+1).chr(11+11+ 11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1).chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1 +1+1+1).chr(111+11).chr(111+1+1+1+1+1+1+1+1+1+1).chr(11+11+1+1+1+1+1+1+1+1+1+1) .chr(11+11+11+11+11+11+11+11+11+1).chr(111).chr(11+11+11+11+11+11+11+11+11+1+ 1+1+1).chr(11+11+11+1))ee ``` [Answer] ## Erlang 8 distinct characters Used characters: `012#<>:.` ``` <<2#1010100011010000110010100100000011100010111010101101001011000110110101100100000011000100111001001101111011101110110111000100000011001100110111101111000001000000110101001110101011011010111000001110011001000000110111101110110011001010111001000100000011101000110100001100101001000000110110001100001011110100111100100100000011001000110111101100111:2#101011000>>. ``` [Answer] # C (23 distinct characters) ``` main(){ puts("\124\150\145\040\161\165\151\143\153\040\142\162\157\167\156\040" "\146\157\170\040\152\165\155\160\163\040\157\166\145\162\040\164" "\150\145\040\154\141\172\171\040\144\157\147"); } ``` Note: I didn't include newlines in the distinct character count, but these can easily be removed if needed, at the expense of readability. ]
[Question] [ Given two integers, output the two integers, and then the range between them (excluding both). The order of the range must be the same as the input. ### Examples: ``` Input Output 0, 5 -> [0, 5, 1, 2, 3, 4] -3, 8 -> [-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] 4, 4 -> [4, 4] 4, 5 -> [4, 5] 8, 2 -> [8, 2, 7, 6, 5, 4, 3] -2, -7 -> [-2, -7, -3, -4, -5, -6] ``` [Answer] # [R](https://www.r-project.org/), ~~39~~ ~~33~~ 30 bytes ``` c(a<-scan(),setdiff(a:a[2],a)) ``` [Try it online!](https://tio.run/##VYpBCsIwEEX3nmLAzQxMQGLFIt16CnExxI4ENIUmBUU8e0wiLlz9x3t/zgqDAV2CS34K@OAnvSA6CX@aXCuwPt6XmyQfrt@PTjOkMVaRHcpgqkXiOKaLV0U5yMmeWYjye6W4YdhRWbNlgL5SV6D7QWt9AdtOlsHsKX8A "R – Try It Online") Thanks for saved bytes to user2390246 and J.Doe. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` Ÿ¦¨« ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6I5Dyw6tOLT6//9oCx2jWAA "05AB1E – Try It Online") **Explanation** ``` Ÿ # inclusive range [a ... b] ¦¨ # remove the first and last element « # append to input ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~52~~ ~~48~~ ~~47~~ ~~42~~ 41 bytes ``` lambda a,b:[a,b,*range(a,b,-(a>b)|1)[1:]] ``` [Try it online!](https://tio.run/##VY7NCsIwEITvPsWAl0Q20L80paAvUnNI0aqgtZReBN89blJ/6iFhNvPtZIbHdL73ue@2e391t/bg4KitG75oM7r@dBRBKuF2rXymsklra/0wXvpJdAIJAVpKrNGw1ISUkBFyQmFXH0rxiGqmgq4IiiHFbLLciAElwfxWwyOKebX4C42O/jp64XA@stmpYriJsTp@kS96hRLm3StqPlxEMaaYVqX1Lw "Python 3 – Try It Online") --- Combined former implementations. [Answer] # [Python 2 (Cython)](http://cython.org/), ~~36~~ 35 bytes ``` lambda x:x+range(*x,-cmp(*x)|1)[1:] ``` *Thanks to @nwellnhof for golfing off 1 byte!* [Try it online!](https://tio.run/##LYpBDoIwFAXXeoq3A/Q3gYqRNNGL1C4QrZJIaRoW3yBnr0DcvJlknv8Mr95J0ayMFmdc47vubvcarHgfavd8pDsm0XR@ZvYtMl0oE20fwGgddE44GoIWB0K1SEko/1xDRZDrQRLEyajtxofWDbDJyDo3Sk6E2YrFAIjLPKNNOZuS@AM "Python 2 (Cython) – Try It Online") --- # [Python 2](https://docs.python.org/2/), 37 bytes ``` lambda x:x+range(*x+[-cmp(*x)|1])[1:] ``` *Thanks to @JonasAusevicius for the port to CPython!* [Try it online!](https://tio.run/##LYpBDoIwFAXXeoq3IbTym9CKkZDoRWoXKIIkUgiy@CbevVbiZt4kb6b38hi9CS1OuIRnPVybGlxxNte@u4sdZ1bdhimK/Ggnra5caMcZjN7D5oSDI1i1J5Q/KQjFf9ejJJg1MAR1dNV2M829X5AmpiFEAFDniOSVIoFgm8ecrY5sBUsZvg "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~26~~ 22 bytes ``` {|@_,|[...^](@_).skip} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/usYhXqcmWk9PLy5WwyFeU684O7Og9n9xYqVCmkaNSrymQlp@kYKGgY6CqaaOgoausY6CBYhhoqNgAqXBEhY6CkZgBUY6Crrmmv8B "Perl 6 – Try It Online") ### Explanation ``` { } |@_, # Slip args a,b into result [...^](@_) # Reduce args a,b with ...^ operator, same as a...^b .skip # Skip first element | # Slip into result ``` [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` lambda x,y:[x,y]+range(x,y,-(y<x)|1)[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9IqGkjEahcl5qWnagCZOroalTYVmjWGmtGGVrH/C4oy80oU0jQy8wpKSzQ0daC05n9dYy4LAA "Python 2 – Try It Online") [Answer] # **Python 3, ~~64~~ ~~62~~ 51 bytes** `lambda a,b:[a,b]+[*range(a+1,b)]+[*range(a-1,b,-1)]` [Try it online!](https://tio.run/##bZBPi8IwEMXvfoqHp3adgLX/pNCDF0HYw4LHmEOK7W5BG2l78dN3J0NZu2Agyczk994keTzHH9fFU1Neppu9V1cLS1WheTEb/dHb7rsO7CaiKlzkinNSUWimsR7GASX0Cjy03lJqCLwhJUSEHSEmJMbQDChO9x6RgKCYYDtsl7ioM0L@0iXehWXJPzdPztX0VWXbna/uxTAXq1Rs48VFfONcbiIRT26tGFLMqsyTZtW4HgF/RkgObQd5biEObYNGTlCWcAUefduNwfrrcD4Xa5pFcDRToYjq21D/ocfD6fMtOv0C) # **Python 2, ~~58~~ 45 bytes** `lambda a,b:[a,b]+range(a+1,b)+range(a-1,b,-1)` [Try it online!](https://tio.run/##bZA/C8IwEMV3P8XDqcUL2NpaKXRwEQQHwbFmSLHVgjbSdvHT18tR/4GBJHeX33uX5P7oL7YJhyo7DldzK04Ghoo050XPWtOcS8/MAir8V6I4IRX4Q192fYcM@QQ88nxOsSbwhpgQEELCghBpTSOgOF05RAKCYoLdMP/GRb0kJB9d5FxYFv24OXKsxp8q24auuhLDRKxisV18XcQ1TuQmEvHk1oohxaxaOlJPKtvC42/wyaJuIM9NxaGuUMkJsgw2xb2tm96b7teHQzqlUQRLI@WLqLx25RvdrLe7v@jwBA) [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ ~~41~~ 40 bytes ``` lambda a,b:[a,b]+range(a,b,a<b or-1)[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqGkjEahcl5qWnagCZOok2SQr5RbqGmtGGVrH/C4oy80oU0jQUDHQUTDW5YFxdYx0FCwRXwURHwQSVi6RYwUJHwQhJr5GOrrnmfwA "Python 2 – Try It Online") Here's mine, now that a lot of other Python answers have been posted -6 bytes, thanks to G B [Answer] # Japt, 8 bytes ``` cUr!õ kU ``` [Try it here](https://ethproductions.github.io/japt/?v=1.4.6&code=Y1VyIfUga1U=&input=WzgsMl0=) ``` :Implicit input of array U c :Concatenate Ur : Reduce U by !õ : Inclusive range kU : Remove all elements in original U ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ,œ|r ``` [Try it online!](https://tio.run/##y0rNyan8/1/n6OSaov@Hlxvpu///b6CjYKqjoKBrrKNgAaRNdEAIhEGiQBEjkCSQ0DUHAA "Jelly – Try It Online") ### How it works ``` ,œ|r Main link. Left argument: a. Right argument: b , Pair; yield [a, b]. r Range; yield [a, ..., b]. œ| Perform multiset union. ``` [Answer] # JavaScript (ES6), 51 bytes Takes input as `(a)(b)`. ``` a=>g=(b,c=b)=>(b+=b<a|-(b>a))-a?[...g(b,c),b]:[a,c] ``` [Try it online!](https://tio.run/##bczBCsIwEATQu1@yg0koVbFIN35I6WE3tkEpjdjiyX@PepQIc3rDzE2esoTH9b7aOV2GPHIW9pFJTWAFe9ItaysvS@oFsHLunHPx28Nof@rEhD6HNC9pGtyUIo1UgQ7A5hftDtQUuscnf7DcN6C6PK1B9gjkNw "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // main function, taking a g = ( // g = recursive function b, // taking b c = b // we save a backup of the original value of b into c ) => // (b += // add to b: b < a | // +1 if b is less than a -(b > a) // -1 if b is greater than a ) // (or 0 if b = a) - a ? // if the updated value of b is not equal to a: [ // generate a new array: ...g(b, c), // prepend all values generated by a recursive call b // append the current value of b ] // : // else: [a, c] // stop recursion and return the first 2 values: a and c ``` [Answer] # Java 10, ~~109~~ ~~108~~ ~~104~~ ~~102~~ ~~93~~ 62 bytes Using a space-delimited String: ``` b->a->{var r=a+" "+b;for(;a<b?++a<b:--a>b;)r+=" "+a;return r;} ``` [Try it online.](https://tio.run/##jZAxb4MwEIV3fsUpExa2VaWpGtWBbpU6dMpYdTgTiEyJQfaBFEX8dmooUsrW5fSe3539@SrsUVSn7zGv0Xv4QGNvEYAnJJNDFVLZkall2dmcTGPl2yIO75aKc@H4/5qO5Iw9ZxmUkMKoRYYiu/XowKWYbGCTaFU2LlZ40K9JEuqLEJhpxVySTjEqV1DnLDg1jCoKiG2n64C4kPaNOcEl0Me/L31@AbLpJwBUeIof@BNTdyse@f6v3/Hd2q6693y7Gt5y8TwfDNF9VzPBnBtLgHyqekE4Xj0VF9l0JNtAR7WNS4ltW19jzRaBbLlyGH8A) Using a List: ``` b->a->{var r=new java.util.Stack();for(r.add(a),r.add(b);a<b?++a<b:--a>b;)r.add(a);return r;} ``` [Try it online.](https://tio.run/##lZAxa8MwEIX3/IobLSKJkqY0VIm7FQrt5LF0ONtykOPIRjq7hODf7iquS@Ixy/Ge7km8TyV2KMr8MGQVeg@faOx5AeAJyWRQhq1syVSyaG1GprbybRLbd0t6rx2/N/RhPMUxFLCDIRUxivjcoQO3s/rnJpYQZoeIqaJ2kZOY5xEy/idSpnCbvi6XYb4IgXGq2H9EOU2ts@BUP6hFIGnatAokE1BXmxyOATJKyBm7//oGZBdgANKeogf@xNTVike@ufVrvp7bWXrDV7PLKy6ex4N@cf3SscG4N5YA@WWmU4Xk5EkfZd2SbEI7qmxUSGya6hSYJ4FserIffgE) (`a<b?++a<b:--a>b` can be `++a<b||(a-=2)>b` for the same byte-count: [Try it online for the String](https://tio.run/##jZAxb4MwEIV3fsUpky1sK6KpGsmBsVKGThmrDmcCkSkxyBxIUcJvp0CRUrYup/f87s6fXWCHsjh/D2mJTQMfaN09AGgIyaZQjKlqyZYqb11KtnLqfRGHo6Psknnxv6YTeesuSQI5xDAYmaBM7h168DGGG9iERueVZzoM8WAeD4YyjnhiNPdhPMWofUatd@B1P@hgRKxbU46IC2lX2TNcR3r2e9PnFyCfXgJAWUNsK165flr5IvZ//U7s1nbVvRfRajgS8m0@6IPnX80Ec24dAYqpmgXhdGsou6qqJVWPdFQ6lius6/LGDF8E8mVlP/wA) or [Try it online for the List](https://tio.run/##lZAxb4MwEIV3fsWNtmKsiKZqJAfGSpXaibHqcICJTIhB5qCKEn47dShVkrGL9Z7v@fQ@VzhgWBWHKa@x6@ADjT0HAB0hmRwqP5U9mVqWvc3JNFa@LmL3ZknvtRP/Db2bjpIESohhysIEw@Q8oAMXW/19F0sJ8wPjqmwccxKLgiEXvyLjarXCXXa5MAzjiCeZ4n8R5TT1zoJT46QCT9L2We1JFqChMQUcPSRLyRm7//wC5FdgANIdsbV45upmwyexvfcbsXm0D@mtiB4eRyJ8mS/G4Palc4N5biwBiuuZLRXSU0f6KJueZOvbUW1ZKbFt65NnXgTyZeU4/QA).) --- **Old (~~109~~ ~~108~~ ~~104~~ ~~102~~ 101 bytes) answer using an array:** ``` a->b->{int s=a<b?1:-1,i=a!=b?(b-a)*s+1:2,r[]=new int[i];for(r[0]=a,r[1]=b;i>2;)r[--i]=b-=s;return r;} ``` -7 bytes thanks to *@nwellnhof*. [Try it online.](https://tio.run/##jZAxb8IwEIV3foW72a1tkZSqCOOgLpU6dGKMMpwhQabBiewLFUL89tSkkShbF@vevTv5fbeHI4j99qvf1BAC@QTrzhNCAgLaDdlHV3Zoa1l1boO2cfJ9LJYfDstd6fn/hqzDvMgyUhFNehCZEdk59kjQsDSrZCESbjU8aLOiRgB7DE/JIuU@L7Qrv4dtW6iq8dTn00JDdJJCG2WzVDGfC2GjEjooX2LnHfHq0qtJBGk7U0eQkefY2C05REa6Rm/dLi8IsCsvIVgGpFP@wtRNimc@/6tnfHYv76bnPL1bTrl4HRqXye2iQ4LBv9IDv75mjLA@BSwPsulQtjEd1o7ebvvmPZyCxOY3Oa0ktG19osDGwjA2/nbpfwA) **Explanation:** ``` a->b->{ // Method with 2 int parameters & int-array return-type int s= // Step integer, starting at: a<b?1 // 1 if the first input is smaller than the second :-1; // -1 otherwise i= // Array-index integer, starting at: a!=b? // If the inputs aren't equal: (b-a)*s+1 // Set it to the absolute difference + 1 : // Else: 2, // Set it to 2 r[]=new int[i]; // Result-array of that size for(r[0]=a, // Fill the first value with the first input r[1]=b; // And the second value with the second input i>2;) // Loop `i` downwards in the range [`i`,2): r[--i]= // Decrease `i` by 1 first with `--i` // Set the `i`'th array-value to: b-=s; // If the step integer is 1: decrease `b` by 1 // If the step integer is -1: increase `b` by 1 // And set the array-value to this modified `b` return r;} // Return the result-array ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes Anonymous infix function. ``` ,,…~, ``` [Try it online!](https://tio.run/##XY6xDoIwFEV3vuJ9wHsJQgudXFxkMhE3w0ACuBBlcNDFmJgwmEB0cHR15R/4lP5IfXSqLm16e87NzZuainNeH3ZUno7lvigLYxD19XNBU@n2obte969kpe@3cQh1@@RXul7wuVkmqQG/ApAAoLs3zfne@ggSYYYQIIQIIvPYY0i5EPGPQiBmiFHfFawfIcSZB4JF4YrCNtpc/uWSc8V54ObK1sa2UNrycBoUVDAO8c@iaQpz0zJijJimKPsC "APL (Dyalog Extended) – Try It Online") `,` the first and last (lit. the concatenation of the arguments) `,` and (lit. concatenated to) `…` the range `~` without `,` the first and last (lit. the concatenation of the arguments) [Answer] ## Haskell, 34 bytes ``` a#b=a:b:[a+1..b-1]++[a-1,a-2..b+1] ``` [Try it online!](https://tio.run/##HYlLCoQwEAWv0uAmId3BZBRF8AieIIShMwwoapA4Lub08bN5RdUbeZ@/y5IzF6HnLnSOldE6kPFKOSaDTPZyZXxeeYrQw8rb8AaxpSn@QMMRP0dKfxCFlOBEibVEQS9sL1RYPXunFu19WKRG@nwC "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 26 bytes ``` ,,[|.@]^:(>{.)<.+1}.i.@|@- ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dXSia/QcYuOsNOyq9TRt9LQNa/Uy9RxqHHT/a3IpcKUmZ@QDVacpmEKY8cZAtgWEbQJkmiCYUBUWQKYRVLERkB1v/h8A "J – Try It Online") ## Explanation: A dyadic verb (takes left and right argument) ``` - subtracts the arguments |@ and finds the absolute value i.@ and makes a list 0..absolute difference 1}. drops the fist element + adds to the entire list <. the smaller of the arguments |.@] reverses the list ^: only if [ the left argument (>{.) is greater than the first item of the list , appends the list to , the right argument appended to the left one ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 45 bytes ``` @(a,b)[a b linspace(a,b,(t=abs(a-b))+1)(2:t)] ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnSTM6USFJISczr7ggMTkVJKKjUWKbmFSskaibpKmpbaipYWRVohn7PyWzuEAjTcNAx1RTkwvK0TXWsUDwTHRMkDlI6ix0jJA0Genommtq/gcA "Octave – Try It Online") [Answer] # [J](http://jsoftware.com/), 13 bytes ``` ,,<.+i.@-~-.= ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dXRs9LQz9Rx063T1bP9rcilwpSZn5AMVpCmYQpjxxkC2BYRtAmSaIJhQFRZAphFUsRGQHW/@HwA "J – Try It Online") ``` i.@-~ range [0 .. |difference|-1], reverse if the difference is positive -.= remove the zero (either "=" is 0 or there’s nothing to remove) <.+ to each element add the smaller of the args ,, prepend args ``` [Answer] ## Batch, 107 bytes ``` @echo %1 @echo %2 @for %%s in (1 -1)do @for /l %%i in (%1,%%s,%2)do @if %1 neq %%i if %%i neq %2 echo %%i ``` Takes input as command-line arguments. Explanation: ``` @echo %1 @echo %2 ``` Output the two integers. ``` @for %%s in (1 -1)do ``` Try both ascending and descending ranges. ``` @for /l %%i in (%1,%%s,%2)do ``` Loop over the inclusive range. ``` @if %1 neq %%i if %%i neq %2 ``` Exclude the two integers. ``` echo %%i ``` Output the current value. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` +QtrF ``` Input is a two-element list, `[input 1, input 2]`. Try it online [here](https://pyth.herokuapp.com/?code=%2BQtrF&input=%5B0%2C5%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=%2BQtrF&test_suite=1&test_suite_input=%5B0%2C5%5D%0A%5B-3%2C8%5D%0A%5B4%2C4%5D%0A%5B4%2C5%5D%0A%5B8%2C2%5D%0A%5B-2%2C-7%5D&debug=0). ``` +QtrFQ Implicit: Q=eval(input()) Trailing Q inferred rFQ Generate range [input 1 - input 2) t Discard first element +Q Prepend Q ``` [Answer] # [Red](http://www.red-lang.org), 75 bytes ``` func[a b][s: sign? d: b - a prin[a b]loop absolute d - s[prin[""a: a + s]]] ``` [Try it online!](https://tio.run/##VcvBCoQgFIXhvU9xcBvCUA0TbnqHtnIXmjoEodGt57em1bj8@c7Zgy9T8IZE1CWeaTYWjgxr8PJNI7yGg4LFti/psTXnDdZxXs8jwN/I5kEprb6HDZiISsQLb/GDA1KKCNVh@O8efZ3VekBbnVuoT7kA "Red – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 49 bytes ``` import StdEnv @a b=init[a,b:tl[a,a+sign(b-a)..b]] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4zLIVEhyTYzL7MkOlEnyaokB0glahdnpudpJOkmaurpJcXG/g8uSQRqsFVwULBQ0DX6/y85LScxvfi/rqfPf5fKvMTczORiAA "Clean – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~33~~ 40 bytes ``` ->a,b{[a,b]+[*a..b,*a.downto(b)][1..-2]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k6GkjEakdrJerpJekAyZT88rySfI0kzdhoQz09XaPY2v8FCmnRCgY6CgqmsVwgtq4xkG0BYSuYANkmSGyoGgULINsIqt5IR0HXPPY/AA "Ruby – Try It Online") Temporary fix, trying to find a better idea [Answer] # [Python 2](https://docs.python.org/2/), ~~52~~ ~~47~~ 41 bytes ``` lambda i,j:[i,j]+range(i,j,(i<j)*2-1)[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ8sqGkjEahcl5qWnagCZOhqZNlmaWka6hprRhlax/wuKMvNKFNI0DHRMNblgHF1jHQsEz0THBJmDpM5CxwhJk5GOrrnmfwA "Python 2 – Try It Online") -5 with thanks to @JoKing -6 by slicing the first element from the range (idea stolen from and with credit to @TFeld) Non-lambda version... # [Python 2](https://docs.python.org/2/), ~~51~~ ~~49~~ 47 bytes ``` i,j=input();print[i,j]+range(i,j,(i<j)*2-1)[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroK6u/j9TJ8s2M6@gtERD07qgKDOvJBooEqtdlJiXnqoBZOpoZNpkaWoZ6RpqRhtaxf4H6uFKrUhN1gCZoall9t9Ax5RL11jHgstExwSITbksdIy4dI10dM0B "Python 2 – Try It Online") -2 with thanks to @JoKing [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 29 bytes ``` {⍺,⍵,(⌽⍣(⍺>⍵))(⍺⌊⍵)+¯1↓⍳|⍺-⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbt0HvVu1dF41LP3Ue9iDSDfDsjX1ASxHvV0gdjah9YbPmqb/Kh3cw1QUBcoVPv/v4FCmoIp16H1xkDagssESJqASVMuCyBpBJQxAtKH1psDAA "APL (Dyalog Classic) – Try It Online") A port of my `J` solution [Answer] ## PHP (102 bytes) ``` function t($a,$b){count($r=range($a,$b))>1?array_splice($r,1,0,array_pop($r)):$r=[$a,$b];print_r($r);} ``` [Sandbox](http://sandbox.onlinephpfunctions.com/code/870c42af9617a26dda4cc80cca4aebf17f215b6d) Unfortunately (for golf) PHP has rather verbose function names, which contribute a lot to the length. But the basic idea is to create a range, then pop off the last element and stitch it back in at offset 1. For the `4,4` example I had to add `count($r=range($a,$b))>1?...:$r=[$a,$b];` which adds quite a bit, and unfortunately `array_splice()` is by reference which hit me for a few more bytes (`$r= and a ;`). All because of that "edge case", lol. Well anyway enjoy! [Answer] # [Clojure](https://clojure.org/), 61 bytes ``` (fn[[a b]](def s(if(> a b)-1 1))(list* a b(range(+ a s)b s))) ``` An anonymous function that takes a 2-vector as input and returns a list. [Try it online!](https://tio.run/##pY2xCsIwFEV3v@KOL9pCaxEKgl/g4B46pDXRSE20SQS/Pibd2tXhweVw7n3DaB9hkjGSMpwL9F1HV6ngSCs6IQFW1qgZo1E7v82AJmFuknYpO9anYyzOHYW/RhiOOEufZuQ7iBH@LiGMNd@nDQ4qmMFrayB6@5Ebek3a@NGkl@AVDt1cv2QIRbwqMlpaZYN2pZVNkdnSa7FfaW2RUfwB "Clojure – Try It Online") ## Explanation ``` (fn [[a b]] ; An anonymous function that accepts a 2-vector as input, and destructures it to a and b (def s (if (> a b) -1 1)) ; If a > b assigns -1 to s and assigns 1 to s otherwise. This determines the order of the elements of the output list. (list* a b ; Creates a list with a and b as the first two elements. The remaining elements will be appended from the following range: (range (+ a s) b s))) ; A range starting at a+s and ending at b with step s ``` [Answer] # [D](https://dlang.org/), 85 bytes ``` T[]f(T)(T a,T b){T[]v=[a,b];T c=2*(b>a)-1;for(T i=a+c;a!=b&&b!=i;i+=c)v~=i;return v;} ``` [Try it online!](https://tio.run/##XcxBDoIwEAXQNZxi2JBWClHESNLUU3RHWLQgySRCTa11QfDqlbhSFpP8vPw/fQiyaQciKZGgmARN5xW8aBTTLZfQiXJH9EXR/MAHY9cWCpV1XCVCp6lOBHLMREf9e0326p52As@X4A32MCqcCIU5jnC8G@vg4fpiPTQ8jgayZydavCy66236Qn5k9b9UrNrCZlOzcvOkZJCff2wJHw "D – Try It Online") A port of @HatsuPointerKun's C++ answer into D. [Answer] # TI-BASIC, ~~35~~ 34 bytes -1 byte from [Misha Lavrov](https://codegolf.stackexchange.com/users/74672/misha-lavrov) ``` Prompt A,B Disp A,B cos(π(A>B For(I,A+Ans,B-Ans,Ans Disp I End ``` [Answer] # JavaScript, 73 bytes Without recursion: ``` (s,e,m=s>e?-1:1)=>[s,e,...[...Array(m*(e-s||1)-1)].map((_,i)=>s+m*(i+1))] ``` Try it: ``` f=(s,e,m=s>e?-1:1)=>[s,e,...[...Array(m*(e-s||1)-1)].map((_,i)=>s+m*(i+1))] console.log(JSON.stringify(f(0,5))); console.log(JSON.stringify(f(-3,8))); console.log(JSON.stringify(f(4,4))); console.log(JSON.stringify(f(4,5))); console.log(JSON.stringify(f(8,2))); console.log(JSON.stringify(f(-2,-7))); ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` IE²NI…⊕θηI⮌…⊕ηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQMNIR8Ezr6C0xK80Nym1SEMTCKy5kNQEJealp2p45iUXpeam5pWkpmgUauooZGAoSy1LLSpOxaI8A6i8EGzs///RukDrdM1j/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` IE²N ``` Print the inputs on separate lines. ``` I…⊕θη ``` Print the ascending range, if any. ``` I⮌…⊕ηθ ``` Print the reverse ascending reverse range, if any. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/22975/edit). Closed 3 years ago. [Improve this question](/posts/22975/edit) Provided a digit between 0 and 9 (inclusive), your function/subroutine should print all numbers between -100 and 100 (inclusive) that contain the given digit. For example: ``` Input: 9 Output: -99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99 ``` **Rules:** * You cannot use strings (in whatever way they are represented in your chosen language) or char arrays. (Except to print the answer to the console.) * You cannot use arrays. **Scoring:** Score = length of subroutine/function (whitespace will not be counted) The answer with the lowest score wins. Whitespace will NOT be counted. Please format your code properly! Some answers are using regular expressions, which may violate the no strings rule, as pointed out by some members. These answers will not be accepted. Please test your code with `0` before posting. [Answer] ## Whitespace, 834 characters (0 if you subtract whitespaces) Used [this interpreter](http://ws2js.luilak.net/interpreter.html) to test it. This took me some 4 hour of hard work and horrible debugging to create. But it is done! ```                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ``` **EDIT**: Selectable text provided with HTML tricks. If you copy and paste it from here to some other place, please check if you got exactly `[space][tab][linefeed][linefeed][linefeed]` at the end with 100 or 101 lines (depending if your editor counts or not a new line if the last one ends with a linefeed). In the case that you can't use it this way, considering space as `S`, linefeed as `L` and tab as `T`, and breaking lines after the `L`'s, here it is: ``` SSSTSSSSTSL SSSTSSSSTSL TL TSSSSTSSSSTSL TTTSSSTTSSSSL TSSTTTSSSSTSSSSTTL SSTTTSSSTTL TTSSSSTSSSSSTL SSSL TTSSSSTSSSSTSL TTTL TSSTSSTSTTL SSSTSSSSTSL TTTSSSTL TSSTL TSSTSSTSTTL L SSSTSSSTSSL SSSTSSSSTTL TTTSL SSSSTTSSTSSL TSSTL TSSTSSSTSTL SL SSSTTL TSSL L TTSTSSSTTTL SSTTL TSSL L SSSTSSSTTTL SL SSSSTSSSSTSL TTTL TSSTSSTSSSL SSSTSTSL TSTSSSSTSSSSTSL TTTTSSTL TSSTSSTSSTL L SSSTSSTSSSL SSSTSTSL TSTTSSSTSSSSTSL TTTTSSTL TSSTSSTSSTL L SL STSSTSTSL L SSSTSSTSSTL SSSTSSSSSTL TTTL TSSTSSSTTSL SSSTSSSSSL TL SSL SSSTSSSTTSL SSSTSSSSSTL SSSTL TTSSSSTSSSSTTL TTTTL STL SSSTSSTSTSL SSSTSSSSTTL SSSTSSSSTTL TTTSSSTL TSSSTTSL SL STSSSTSSL L SSSTSSSTSTL SSSTSSSSTSL TTTL TSSTSSTTSSL SSSTSSSSTSL TTTSSSTL TSSTL TSSTSSTTSSL L L L L SSSTSSTSTTL SSTTTSSTSSL TL STSSSTSSSSSL TL SSL SL STSSSTSSL L SSSTSSTTSSL SSSTSSSSSL TL SSSSSTTSSTSSL TL STL L L ``` [Answer] **Bash+utils - 20** ``` seq -100 100|grep 9 ``` Or 21 bytes if in a script ``` seq -100 100|grep $1 ``` To run the script: ``` sh myscript 9 ``` [Answer] # JavaScript 133 - 1 = 132 Surely there couldn't possibly be anything wrong with this version now...? ``` for(k=prompt(),c=console,j=-100;100>=j;j++)if(i=j,0==j&j==k)c.log(0);else for(;i;)if(h=i%10,h=0>h?-h:h,i=i/10|0,h==k){c.log(j);break} ``` --- ``` PROMPT: 2 CONSOLE.LOG: -92 -82 -72 -62 -52 -42 -32 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -12 -2 2 12 20 21 22 23 24 25 26 27 28 29 32 42 52 62 72 82 92 CONTROL, using zero PROMPT: 0 CONSOLE.LOG: -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 ``` [Answer] # GolfScript [24 bytes] ``` `:x;201,{100-}%{`x?-1>}, ``` **Description:** ``` `:x; - save input value to variable 'x' and remove from the stack 201,{100-}% - create range from -100 to 100 {`x?-1>}, - filter the range by "index-of" condition ``` **DEMO:** <http://golfscript.apphb.com/?c=MwoKYDp4OzIwMSx7MTAwLX0le2B4Py0xPn0sYA%3D%3D> [Answer] # Ruby: 92 characters ``` s=gets.to_i $><<(-100..100).select{|n|a=n.abs;loop{break""if a%10==s;break if 0==a/=10}}*" " ``` Readable version: ``` searchfor = gets.to_i $><< (-100..100).select { |number| absnumber = number.abs loop { break "" if absnumber % 10 ==s break if 0 == absnumber /= 10 } } * " " ``` Sample run: ``` bash-4.2$ ruby -e 's=gets.to_i;$><<(-100..100).select{|n|a=n.abs;loop{break""if a%10==s;break if 0==a/=10}}*" "' <<< 9 -99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99 ``` Test run: ``` bash-4.2$ for i in {0..9}; do diff -w <(ruby -e 's=gets.to_i;$><<(-100..100).select{|n|a=n.abs;loop{break""if a%10==s;break if 0==a/=10}}*" "' <<< $i) <(seq -100 100|grep $i|tr \\n \ ) > /dev/null; echo "$i : $?"; done 0 : 0 1 : 0 2 : 0 3 : 0 4 : 0 5 : 0 6 : 0 7 : 0 8 : 0 9 : 0 ``` [Answer] # K - 45 char Not winning any awards, but K golfing is underrepresented. K doesn't get any prettier with proper spacing, so I'll just leave this as is, because K gets very picky about which whitespace is important and which isn't. ``` {|a@&x _in'@[10_vs'_ _abs a:100-!201;100;0,]} ``` Explained: * `a:100-!201` - Make a list from 0 to 200 inclusive, then subtract it from 100. Now we have the numbers from -100 to 100 inclusive, but backwards from the question's specs. We can always fix that later, so for now we'll just assign this to `a`. * `_ _abs` - Take the floor of the absolute value of these numbers, because for whatever reason K thinks that `_abs` should give floating point results. Thankfully, flooring them turns them back into integers. * `10_vs'` - Expand each (`'`) integer as a base 10 number (`_vs` stands for "vector from scalar"). Note that we did not have to use the Each operator `'` on the functions above because they operate on atoms. * `@[...;100;0,]` - Amend the item in our list at index 100 (an empty list, which is the result of expanding 0 into base 10) by the function `0,`, which prepends a zero to the front. Without this correction, this function will fail on the input 0. * `&x in'` - Now, return the indices (`&`) where `x` is a digit in (`_in`) each (`'`) of the expansions we so carefully constructed above. * `|a@` - Finally, use these indices to index `a`, and reverse the list into the right order. Usage is obvious, though good luck getting your hands on a K interpreter. (There's an open source implementation at [on Github](https://github.com/kevinlawler/kona) that you can compile.) ``` {|a@&x _in'@[10_vs'_ _abs a:100-!201;100;0,]} 0 -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 {|a@&x _in'@[10_vs'_ _abs a:100-!201;100;0,]} 5 -95 -85 -75 -65 -59 -58 -57 -56 -55 -54 -53 -52 -51 -50 -45 -35 -25 -15 -5 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95 ``` [Answer] ## bash ~~55~~ 49 characters: (not counting whitespace around `&&`) ``` for i in {-100..100} do [[ $i =~ $1 ]] && echo $i done ``` Executing it by saying: ``` bash filename 9 ``` would produce: ``` -99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99 ``` [Answer] # PHP 67 bytes: ``` for($i=-100;$i<101;++$i)if(strpos($i,$_GET[n])!==!1)echo$i,PHP_EOL; ``` Yes, there is a 'strpos' call, but I'm using only numbers! Here is a 'ungolfed' version: ``` for($i=-100;$i<101;++$i) { if(strpos($i,$_GET[n])!==false) { echo $i,PHP_EOL; } } ``` For this to work, you can test it here: <http://writecodeonline.com/php/> Just remember to add `$_GET[n]='<number>';` to the beginning of the code. Or, on a lamp or xampp server, you can create a page and then access it on the browser, with the parameter `?n=<number>` after the filename. [Answer] # Mathematica 28 Sorry, I just couldn't resist. :) The instructions are: "Provided a digit between 0 and 9 (inclusive), your function/subroutine should print all numbers between -100 and 100 (inclusive) that contain the given digit." --- The following prints all such numbers in order. ``` f@n_ :=Print/@Range[-100,100] ``` As a special bonus, it prints those numbers in the same range that do not contain the given digit. :) [Answer] My first attempt here, so maybe I am doing some things wrong, please excuse that ;) So, I wasn't sure if I had to add the whole class or just the logic within. # Java - 199 characters ``` intx=System.in.read()-48;for(inti=-100;i<101;i++){if((i<10&&i==-x)||(i>-10&&i==x)||(i<-9&&((i/100==x&&i<-99)||i%10==-x||i/10==-x))||(i>9&&((i/100==x&&i>99)||i%10==x||i/10==x)))System.out.println(i);} ``` Here a more readable form: ``` int x = System.in.read() - 48; for(int i = -100; i < 101; i++) { if((i < 10 && i == -x) || (i > -10 && i == x) || (i < -9 && ((i / 100 == x && i < -99 ) || i % 10 == -x || i / 10 == -x)) || (i > 9 && ((i / 100 == x && i > 99) || i % 10 == x || i / 10 == x))) System.out.println(i); } ``` I guess the basic idea was not that bad, but needed too much exceptions, to finally work out for all cases... :/ [Answer] # C - 104 107 114 characters - 0 = 104 107 114 ``` a,b;main(i){i=getchar()-48;for(a=-100;a<101;a++){for(b=a;a&&abs(a%10)!=i;a/=10);if(a|!i&!b)printf("%i ",b);a=b;}} ``` Ungolfed: ``` #include <stdio.h> int a, b; int main(int i) { i = getchar() - '0'; for( a = -100 ; a < 101 ; a++ ) { for( b = a ; a && abs(a % 10) != i ; a /= 10 ); if( a | !i & !b ) printf("%i ", b); a = b; } } ``` [Answer] ## R 87 93 Here's an improvement: ``` a=scan();r=-100:100;s=abs(r);r[(!a&!r%%10)|a&(a==s%%10|a==floor(s/10)|a==floor(s/100))] ``` (Potentially) More readable, with notes: ``` a=scan() # take user input of selected digit r=-100:100 # define our scanning range s=abs(r) # copy the range as the absolute value for proper floor() calculation #r[<criteria>] is functionally the same as subset(r,<criteria>) r[ # when any of the criteria below are met, use that value from the range (!a & !r%%10) # case when input is 0, !a is evaluated as "a when a<>0 == true" | a & # all other digits below a==s%%10 | a==floor(s/10) | a==floor(s/100) ] # R does not require a print command, so this as-is will display the corresponding values ``` [Answer] **Javascript 116** ``` a = 0 for(i=-100;101>i;i++){ m=Math f=m.floor j = m.abs(i) if((j>10&&f(j/10)==a)||j-f(j/10)*10==a||j/100==a){ console.log(i) } } ``` [Answer] # Prolog: 75 ``` f(D) :- between(-100,100,N) , number_chars(N,Ds) , member(D,Ds) , writeln(N) , fail . ``` [Answer] ## C answer in 98 characters This is one of the sexiest things I've ever coded ``` main() { int t=getchar()-48,i=100,j=-i; while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 ); } ``` The older version, with 104 non-whitespace chars: ``` int main() { int t=getchar()-48,i,j=-101; while(++j<101) { i=j<0?-j:j; while(i = t-i%10?i/10:!printf("%d\n",j)); } } ``` "Works for me" using GCC and CLANG. [Answer] # GW Basic: 107 characters excluding whitespace ``` 1 input n 2 for i=-100 to 100 3 j=abs(i):a=j mod 10 4 if a=n then 8 5 b=j\10 6 if (b=n) and b then 8 7 if (b<10) or n<>1 then 9 8 print i 9 next ``` Using single digits for the line numbers helps and stripping the whitespace means there isn't really a need for having multiple statements on a line more than once to keep numbers reaching 10. [Answer] # GNU coreutils (44) ``` read N seq -100 100 | grep $N | tr '\n' ' ' echo ``` where `tr` is used to convert newlines to spaces, and `echo` provides one final newline. ``` $ bash ./script 9 -99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99 ``` [Answer] # J - 27 chars All whitespace is safely removable, meaning 27 characters. Negative numbers in output will have `_` for a negative sign: this is just the way J writes its negative numbers. ``` ((e. 10 #.^:_1 |)"0 # ]) & (i: 100) ``` Explained: * `V & (i: 100)` - Bind (`&`) the set of numbers from -100 to 100 inclusive (`i:100`) as the right argument of the main verb (`V`). The single argument of the entire verb gets piped into the left side. * `(U"0 # ])` - Use the result of the verb `U` over each number from the right argument (`"0`) to select (`#`) items from the right argument (`]`). * `(e. 10 #.^:_1 |)` - Given the digit to test for as the left argument and the number to check as the right argument, expand in base 10 (`10 #.^:_1`) the absolute value of the number (`|`), and check if the digit is an element of that expansion (`e.`). Usage: ``` ((e. 10 #.^:_1 |)"0 # ]) & (i: 100) 0 _100 _90 _80 _70 _60 _50 _40 _30 _20 _10 0 10 20 30 40 50 60 70 80 90 100 ((e. 10 #.^:_1 |)"0 # ]) & (i: 100) 5 _95 _85 _75 _65 _59 _58 _57 _56 _55 _54 _53 _52 _51 _50 _45 _35 _25 _15 _5 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95 ``` [Answer] # Groovy, 127 ``` def x = args[0].toInteger() for (k in -100..100) if (k == x) print " ${k}" else for (n = Math.abs(k); n > 0; n = (int) n / 10) if (n % 10 == x) { print " ${k}" break } ``` No strings (except to output the spaces between the numbers), no char arrays or other arrays, no regexes. Tested with 0. Output: -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 [Answer] ## Javascript - 108 Not sure if existing javascript answer will be taken into consideration because it uses regex, so I created one without it: ``` for(x=+prompt(i=-100);i<101;i++)if((j=i<0?-i:i)&&j%10==x||((j/100==x||(0|j/10)==x)&&x)||j==x)console.log(i) ``` Can also be shortened to 101 if x variable is put directly, like: ``` for(x=5,i=-100;i<101;i++)if((j=i<0?-i:i)&&j%10==x||((j/100==x||(0|j/10)==x)&&x)||j==x)console.log(i) ``` It basically checks if absolute values of div or mod operations are equal to the digit (which also works for 100). [Answer] **GROOVY, 71** ``` f={z-> _=10 (-_*_.._*_).grep { a=it.abs() b=a%_==z a<_?b:b||(int)(a/_)%_==z } } println f(0) println f(9) ``` Results in ``` [-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] [-99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -79, -69, -59, -49, -39, -29, -19, -9, 9, 19, 29, 39, 49, 59, 69, 79, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] ``` [Answer] **Javascript 96** Using bitwise or: ``` b=Math.abs; a=prompt(); for(i=-100;i<101;) if(!(b(i++/10)^a && b(i%10)^a)||b(i)/a==100) console.log(i) ``` [Answer] # Haskell, 86 75 (78 with necessary whitespaces) ``` f 0=[-100,-90..100] f d=[b|b<-[-100..100],abs(b`quot`10)==d||abs(b`rem`10)==d] ``` Ungolfed: ``` f dig = if dig == 0 then [-100, 90 .. 100] else [num | num <- [-100 .. 100], abs (num `quot` 10) == d || abs (num `rem` 10) == d] ``` [Answer] # Python - 172 chars ``` def f(x,y,z): if x%10==y or (x>9 and x/10==y) or (x==100 and y==1): print z def g(x,y): f(abs(x),y,x) if x<100: g(x+1,y) def h(y): g(-100,y) ``` To test within Python: ``` >>> h(4) -94 -84 -74 ... -49 -48 ... ``` [Answer] ## VBA 121 (no whitespace or `Sub` definition counted): ``` Sub t(d) For n = -100 To 100 m = Abs(n) o = o & IIf(d = 0, IIf(d = n Mod 10, " " & n, ""), IIf(d = n Or d = m Mod 10 Or d = Int(m / 10) Or d = Int(m / 100), " " & n, "")) Next MsgBox o End Sub ``` [Answer] # perl, 117 with non-meaningful whitespace chars removed I think you were looking for something more like this. Reads from stdin, outputs one line per match. No regexps, arrays (or sets or hashes or anything else that is an array under the covers) or strings, implicit or otherwise, except the strings passed to print: ``` chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n" ``` eg: ``` ski@anito:~$ echo 0 | perl -e 'chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"' -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 ski@anito:~$ echo 1 | perl -e 'chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"' -100 -91 -81 -71 -61 -51 -41 -31 -21 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -1 1 10 11 12 13 14 15 16 17 18 19 21 31 41 51 61 71 81 91 100 ski@anito:~$ echo 2 | perl -e 'chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"' -92 -82 -72 -62 -52 -42 -32 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -12 -2 2 12 20 21 22 23 24 25 26 27 28 29 32 42 52 62 72 82 92 ``` [Answer] # F# 87 92 - 7 ``` let f n = {-100..100} |>Seq.filter(fun x->abs x%10=n||abs x/10=n&&n>0) |>Seq.iter(printf"%d ") ``` added 5 chars because 0 wasn't handled correctly. (Single digit values would all be returned.) [Answer] This is my first time playing code golf. This looks pretty interesting. I can't win, but I tried and wanted to show what I could do. **Python: 104 (89 if I can mulligan the import) - if the results must be printed exactly as shown in the example** ``` from math import * def g(x): t = 10 p = lambda i: x == i % t or i >= t and p(i / t) for i in range(-100, 101): if p(abs(i)): print i, print # g(0) # -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 ``` **Python: 71 - if the output can be done outside the function and the only restriction for the output is that no violating numbers are printed** ``` f = lambda x: [(-i, i) for i in range(101) for j in (10, 100) if i % j == x or i >= j and i / j == x] # print f(0) # [(0, 0), (0, 0), (-10, 10), (-20, 20), (-30, 30), (-40, 40), (-50, 50), (-60, 60), (-70, 70), (-80, 80), (-90, 90), (-100, 100), (-100, 100)] ``` [Answer] **JavaScript 125 char** Sorry for the several edits I've been having troubles doing this from my phone :) ``` function c(n,i){o=i||0;h=100;j=o-h;f=Math.abs(j);m=f/10|0;if((m==n&&m!=0)||n==f%10||f/h==n)console.log(j);if(o<h*2)c(n,o+1);} ``` [Answer] # Dogelang, 42 non-whitespace characters ``` f=n->for i in(-100..101)=>if n in str i=>print i ``` Same as my Python solution, just converted to [dogelang](http://pyos.github.io/dg/). ]
[Question] [ Over is a higher-order function in multiple languages such as [APL](https://aplwiki.com/) (`⍥`). It takes 2 functions and 2 values as arguments, applies the first function to both values, then applies the second to their result. For example, using `⍥` to represent Over: ``` 1 ²⍥+ 2 ``` We would first calculate `²` of each argument: `1² = 1` and `2² = 4`. We then apply `+` to these, yielding `5`. You are to take as input: * A [black box function](https://codegolf.meta.stackexchange.com/a/13706/66833), \$f\$, which takes an integer as input and returns an integer * A black box function, \$g\$, which takes 2 integers as input and returns a single integer * 2 integers, \$a\$ and \$b\$. You should then return the result of \$g(f(a), f(b))\$. If you have a builtin specifically for this (e.g. APL's `⍥`, Husk's `¤` etc.), consider including a non-builtin answer as well. It might even get you an upvote :) You may input and output in the most convenient format for your language, and in [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), **including taking \$a\$ and \$b\$ as a pair/list/tuple** `[a, b]` For the sake of simplicity, you can assume that the black-box function will always input and output integers within your language's integer domain, and that \$a\$, \$b\$ and the output will be with your language's integer domain. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases ``` f g a, b -> out f(x) = x² g(x,y) = x - y -2, 2 -> 0 f(x) = φ(x) (Euler totient function) g(x,y) = 2x + y 5, 9 -> 14 f(x) = x³-x²-x-1 g(x,y) = y⁴-x³-y²-x -1, -1 -> 22 f(x) = x g(x,y) = x / y (Integer division) -25, 5 -> -5 ``` [Answer] # [Haskell](https://www.haskell.org/), 12 bytes ``` f?g=(.f).g.f ``` [Try it online!](https://tio.run/##bU7LCsIwELznK@bgIVE30KoHwbYfoi2Uvgz2ha2Sgt9uTJDqpQu7DLMzO3tNh1tR18aUURVwWQpZydJ0AY8EY2M3qqIdoRFgeDQ4e3ihxYksklLHW1RZbgm7D@DFjDWpaq0279DflTWu0IEnvgAn1xb4DL/6a@YgftGYKPTXejMJHHBcVFsVhTrZkU580uSJ2Tcle3L85HgX6H3H4hWVI1dP99XBRpl3VtZpNRjK@v4D "Haskell – Try It Online") Haskell was made for this. Let's unpack it: ``` (f?g) x y = (((.f).g.f) x) y = (.f)(g (f x)) y = ((g (f x)).f) y = g (f x) (f y) ``` If you're wondering what happens if we make this further pointfree in `f` and `g`, we can express `(?)` as: ``` \f->((.f).).(.f) (.).(.).flip(.)<*>flip(.) ``` The flipped version of `?` that's invoked as `g?f` is a little nicer: ``` ((.).flip(.)<*>).(.) ``` (I used [pointfree.io](http://pointfree.io/) for these.) *Test cases copied [from Unrelated String](https://codegolf.stackexchange.com/a/223888/20260).* --- ## [Haskell](https://www.haskell.org/), 10 bytes ``` (.map).(.) ``` [Try it online!](https://tio.run/##bY/LCsIwEEX3@YpZuEg0E0i0C8Hqh7QplNZqsI9gq6TgtxtTxMeisxrm3jN35pz3l2Nde3pgceqpaHLLBBXMd3FVGxvGhAzdYI7tAA5i6G8NJBIe0MIOQyeE0xxORRkGQY9BakKa3LTBW3ZgryaAC@iAZooBTRPHR417hyODBBVXmsC3fu5P5BdQS7eakIhv5wmaurA2W6PLFDqUf2FjtsFJGSdlipUc5fwWU/6w0tzDS@87Ix5p/yyqOj/1HgtrXw "Haskell – Try It Online") If the input `[x,y]` is a two-element list, and the binary function `g` accepts its two arguments as such a list. The main function takes is arguments as `g` then `f. [Answer] # [Factor](https://factorcode.org/), 16 bytes ``` [ bi@ rot call ] ``` [Try it online!](https://tio.run/##tVTNctMwEL77KTa3pERObeoDATpcGCaXXoCTJ8y4tpxoasuuJIM9JAcuPEofAHgCHgDegRcJn@S2acJPw4GdWN5In3a//XaTPElNpTavX87OXkwpraQRskmMqKTGt/JcyATnmi64krygokqTQlOZmKVb/LyRaY@uFTemq5WQhjS/bLhMeY/0sVly7ecul6bH3uxsSouqyD1vQK8qIzju3ETyfd@b0rcrGpIkxqikkUew9251HsWUNTUF9ITm1ldVTcdw17@BPN1Cgh1IfOtZs@BGCtBm1zR3jmNctg@jIwRRPGtS7gLXqoJv4J8LmtDR7a2589ZW0gwVu0qXnHiblHXBSci6Mdrri7JsGUKwkEK4@tISxf6A8mE7Qgnt1087dPZtQIthO@4cFJG6e8AsHCMRO6Vj8Loh0Av2AKkz0b8jeoRddGKPzfeP9m1t@LwpuCKz18LRX/P/gXjYImn3DzejMfihiOBkW8UK9Xe0wnNCb@A/xAo9rKTMSQORA/txyNU1ot2eBw6zJ/5nhgawlgUHszvc7ijQ/fjwhdlsnc32X3KxYOwEOKUwvNP7iRu@CB2Pf6neO3DsJpAZEzGThi8wE5l4K/Q9s2AnEV2MLB8WeetNjF/RM1KVIfzNFDTHxjthlixLTKJNkl5QLpQ25INl2ijVEU/S5eYn "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a quotation with stack effect `( x x -- x )`, two integers, and a quotation with stack effect `( x -- x )` on the data stack as input. It takes them in that order, as that allows for what I believe is the shortest code. Assuming the data stack looks like `[ + ] 1 2 [ sq ]` when this quotation is called... * `bi@` Apply a quotation to two objects. **Stack:** `[ + ] 1 4` * `rot` Move the object third from the top to the top. **Stack:** `1 4 [ + ]` * `call` Call a quotation. **Stack:** `5` # [Factor](https://factorcode.org/), 10 bytes ``` map-reduce ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVBQlFpSUllQlJlXolCcWliampecWqxgzVWtYKhgpFCrEK1QXKgQC6S0FWL/5yYW6BalppQmp/7X@w8A "Factor – Try It Online") Built-in. [Answer] # [J](http://jsoftware.com/), 12 bytes ``` 2 :'(u v)~v' ``` [Try it online!](https://tio.run/##y/qvpKegrpCmYGuloK6jYKBgBcS6egrOQT5u/40UrNQ1ShXKNOvK1P9r/jdR0E5TVDDnMlHQBdEA "J – Try It Online") Non-built-in solution. This is an explicit conjunction that takes two functions on two sides and evaluates to a train that acts like "u over v", but with flipped arguments. ``` x ((u v)~v) y x (u v)~ v y (v y) (u v) x (v y) u v x ``` # [J](http://jsoftware.com/), 1 byte ``` & ``` [Try it online!](https://tio.run/##y/qvpKegrpCmYGuloK6jYKBgBcS6egrOQT5u/9X@a/43UdBOU1Qw5zJR0AXRAA "J – Try It Online") J's built-in conjunctions can be assigned to a variable, unlike in Dyalog APL. [Answer] # JavaScript (ES6), 23 bytes ``` (f,g,x,y)=>g(f(x),f(y)) ``` [Try it online!](https://tio.run/##dU5BDsIwDLvzihyTKgVtsGN33D@msVagaUVsQs3rS7pdQIKDFdmxLd/7V78Mz9tjtXO8jrlzGT0HTizk2oAeE7FHIcpDnJc4jccpBuwwgWshGVMzYGIQ2jhYEAarYk10@J04q6kEy1FUnwVizGV/F5cy2GxaWRX86fyecNonNAyNrn4D "JavaScript (Node.js) – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 21 bytes ``` |f,g,x,y|g(f(x),f(y)) ``` [Try it online!](https://tio.run/##VYzNCsIwEITveYp4y8oGSrwZ6qtIAtlS0IXmB1qMzx5TKogwDMzHzMSSciOWTzezgpd8hCzpSqy65osBfeuOR8Af@Etjq4QTrrjVSZFaAUltAM2K/S0txcUwysqVz/xlxctOHPrqtLfCpRRivofl1PfHAHsHDWoDOIAV7/YB "Rust – Try It Online") An anonymous function that has the signature ``` fn(fn(i32)->i32,fn(i32,i32)->i32,i32,i32)->i32 ``` Don't you love it when the function signature is twice as long as the function itself? [Answer] # [Haskell](https://www.haskell.org/), ~~17~~ ~~16~~ 15 bytes ``` (f!k)x=k(f x).f ``` [Try it online!](https://tio.run/##bU7LCsIwELznK6bgIVFTSLUHwfRHtIFiWw19ia2yBf@9Jkj10oVdhtmZnb1lfVXU9TTxMqgE6YqXIBGW09ANtmgHEDT6Z4OTwhstjtKhMKR0i@sld4Tba6iUsU7zQDDWZLZ1lrzD/WGdf4UO3EQCXPp2IGL41V8z5/EzYZRJtKbNKBDjsKh2KpmQ2UkykSSpxOwbzV56fvS8D1TfsXjF5sjty38Vu6jpAw "Haskell – Try It Online") *-1 thanks to Wheat Wizard repatterning the use of infix* [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 9 bytes ``` {⍺⍺/⍵⍵¨⍵} ``` ``` {⍺⍺/⍵⍵¨⍵} ⍺⍺ left operand (function argument) / reduce ⍵⍵ right operand ¨ each ⍵ right argument ``` APL has a builtin for this, ⍥, but here's a non builtin solution as an operator taking an array of arguments. Alternative 'proper' definition: `{(⍵⍵⍺)⍺⍺⍵⍵⍵}`, or more readably as `{(⍵⍵ ⍺) ⍺⍺ ⍵⍵ ⍵}` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbuASP9R71YgOrQCSNT@/6@dpqhgomAOAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Racket](https://racket-lang.org/), 26 bytes ``` (λ(f g x y)(g(f x)(f y))) ``` [Try it online!](https://tio.run/##ZYtLCoQwEET3OUWBm66FCz8XEqcNg6ISRJKzeYe5UuyRwVkIRVEF74WuH3XLxdTNHuE6Tl46vGfFsmvI8jlkgEdEonibkVaJZKZz8mVgDCQSUkI0rpvBDe9Z06oif5i5fzCh5dNJl2NGWVmYTw "Racket – Try It Online") `λ` is 2 bytes, BTW. Pretty self-explanatory, but: ``` (λ(f g x y)(g(f x)(f y))) Anonymous function submission (λ ) Lambda; (f g x y) accept functions f, g and arguments x, y and return (g ) g( (f x) f(x), (f y) f(y)) ``` [Answer] # [R](https://www.r-project.org/), 29 bytes ``` function(f,g,a,b)g(f(a),f(b)) ``` [Try it online!](https://tio.run/##bY1BCgIxDEX3nqIgAwkkaKvd2asMbcUWNzMw6NCevjYDiojb/Pdeljavt0VdWLX0nK6P@zxBokyBImZIEJASRMQNg@Q@UMEyGspfB6pYuFJwbCg6g2qvjrt/2om7yoX1r17HM8tcZZaQ7iHWUjLmnfLgu@eHw@C3X7YzVhC27QU "R – Try It Online") No surprises here. In a future version of R, `function` will be replaceable with `\` (which is supposed to look like a lambda). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes ``` #2@@#/@#3& ``` [Try it online!](https://tio.run/##JYy9CoMwFIV3nyJwIUvvpeRahw4tLt0tHUsDQRQD1YLEKcRXT5M4Hc53fmbjpmE2zvYmjrcI3LZwbqGWsVvt4t5A9zGhj9xfvVl2X3nQLFEAQRZPjBwCVv6xfYe1mywKhtORNXgtEeia0oqAVF6yvlBBnFk5UUjqqCb73H7ODosr7w2KJoQqxD8 "Wolfram Language (Mathematica) – Try It Online") Input `[f, g, {x, y}]`. [Answer] ## SKI-calculus, 71 bytes ``` S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(KK)))))(S(KS)K)))))(KK) ``` Edit: Another go at hand-translating the lambda calculus expression into SKI using the rules in [Wikipedia](https://en.wikipedia.org/wiki/Combinatory_logic#Completeness_of_the_S-K_basis), this time arriving at the same answer as @Bubbler. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 23 bytes ``` (q((f g x y)(g(f x)(f y ``` [Try it online!](https://tio.run/##FYoxDoAgEAR7XrHlrZ1@hDdgiISEoKIF9/rzbCaTzLy1a6vPZSYZUW6RAwUTSimukw41aWfKaHUfaShDkIh/9br4O0kiYcVG@wA "tinylisp – Try It Online") ## Ungolfed ``` (lambda (f g x y) ; a lambda function taking four arguments (g (f x) (f y))) ; apply f to x, f to y, and g to the results ``` [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes \$ a \$ and \$ b \$ are inputted as a tuple (called \$ x \$). ``` lambda f,g,x:g(*map(f,x)) ``` [Try it online!](https://tio.run/##ZY3NCoMwEITveYo5JmGX1rReBK8@RS@R1h/wJ5RIk6e3qSAohVnY3ZmPcdF382TWqnysgx3rp0VDLYWilXq0TjYUlFo/XT@8kBUimWgJ0hJqwrx4p1Cin9zipaK/RcC9@8mjkgdOJaTc2L0xFAhaG7GfFNODo2BDSLqKU@7GvzAHzk5A1PrOmx03W2QETmPMET93XH4dOSGJ8y8 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ñ€ç/ ``` [Try it online!](https://tio.run/##ATMAzP9qZWxsef804bi2VSpAwrVfLwoswrXhuosyKjRSwqRVXy//w5HigqzDpy////8tMSwgLTE "Jelly – Try It Online") Takes `f` on the first line, `g` on the second line, and the code is on the third line (this is standard for Jelly). Also, takes the arguments together as a list ``` € For each of the arguments Ñ Apply the next link (wraps around to `f`) / Reduce by (for a pair, applies dyad to the first and second element of the list) ç Apply the last link (`g`) ``` Also works: # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ÑçÑ} ``` [Try it online!](https://tio.run/##y0rNyan8b/Jwx7ZQLYdDW@P1uXQObX24q9tIyyTo0JLQeP3/hyceXn54Yu3///91DYEIAA "Jelly – Try It Online") ``` Ñ Apply `f` (to the left argument, since it's called as a monad) çÑ} 2-2 chain - given dyads x, y, computes x(a, y(a, b)) if the chain's current value is a and the right argument is b ç Apply `g` to the current value (f(left)) and Ñ} A dyad formed from a monad by ignoring the left argument ``` Basically, `Ñ}` is `(l, r) -> f(r)`, so this ends up evaluating as `λ x y -> g(f(x), (λ a b -> f(b))(x, y))` which simplifies to `λ x y -> g(f(x), f(y))` as required. (These chaining rules are absolutely beautiful. Thank you Dennis for Jelly :P) [Answer] # [Scala](http://www.scala-lang.org/), 16 bytes ``` _ map _ reduce _ ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzVWWmKOQZqURnFoY7ZlXEqsDJGztgISOBogAYk0wF0La/o9XyE0sUIhXKEpNKU1OVYj/X1CUmVeSk6eRBjJCw1jHVFNHN14nXjteU5Or9j8A "Scala – Try It Online") Takes ([a,b],f,g). There’s more ways to do this but I’m on mobile so I’ll add them later [Answer] # [Proton](https://github.com/alexander-liao/proton), 21 bytes ``` (f,g,a)=>g(*map(f,a)) ``` [Try it online!](https://tio.run/##Pc0xDoQgEAXQnlP8EshQ4G6LFzFbUCixEAgxRk7PDhptJn8yL/NzSXuKLR1zgWtyoUBeuTFIvfnMq1eqLXA44UYeWuMDc4fhCgZWBAbyJFTVVe3H76M6ry8XIpc17rL38XcEwmQswdgfF/0B "Proton – Try It Online") Time to bring out this garbage again :D [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 bytes ``` n!aa!a! ``` [Run and debug it](https://staxlang.xyz/#c=%7B%22Code%3A%22d%0An%21aa%21a%21%0A%7DY%0A%22Testcases%22d%0A%7B-%7D+2N+%7BJ%7D+2+y%21P%0A%7BH%2B%7D+5+%7B%3At%7D+9+y%21P&i=) A full program which can be executed as a block as well. accepts the arguments as `g x f y`. [Answer] # [Ruby](https://www.ruby-lang.org/), 23 bytes ``` ->f,g,x,y{g[f[x],f[y]]} ``` [Try it online!](https://tio.run/##KypNqvyfYftf1y5NJ12nQqeyOj06LboiVictujI2tvZ/gUJGtK5dRXWFlpZRrQ6QBVRRoVtZq2Oko2sU@x8A "Ruby – Try It Online") Or: # [Ruby](https://www.ruby-lang.org/), 23 bytes ``` ->f,g,*x{g[*x.map(&f)]} ``` [Try it online!](https://tio.run/##KypNqvyfYftf1y5NJ11Hq6I6PVqrQi83sUBDLU0ztvZ/gUJGtK5dRXWFlpZRrQ6QpVNZXaFbWatjpKNrFPsfAA "Ruby – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~54~~ \$\cdots\$ ~~37~~ 36 bytes ``` o(f(),g(),a,b){return g(f(a),f(b));} ``` [Try it online!](https://tio.run/##lVJLjtNAEN3nFG8iRWo73ZrYkMVgGhaIU5BZtL9jTegM7QC2Ii/YcCDgBFxg7jAHwVS37cQZDUKTqO1UV716r@olEclW6aLrdixnHi/oKB57B5PtPxuNgm6Vx3MWe17UdqXeo/pkWO3hgKGkho86QjuzybTMc1bz5iwv0Iz5IkmZ4ogn@RgXEiu8dbmYQ2Fh86@gRtDdTcm0RdjAQCKIkO8MmI1LisOIXq@hIyyXpWuNpXT9NAddSAdpR0ZzbLzbNiuSi6ne0M6D5UmzrQrOR/bpS2MNTzrBtDgcN9D4kroMoMZveogDud8jqEzP2x/v9T4tvzze56VT5go@qlIzb3aYgT7JjTI@PbPkNjMfrmkvh/mmfh9u6qt3dNZzjmn8Yt5GDudMpeodI2u5s5BDhByhdyrIqGDVh3eGLnI2z61oifr3D07/EydS9m4PcIg3WKRYVBtN3BU/aqukzK6puWvXU5PHvPeDY81xNVBb2uDlk7z33@lNLM6rHvQsQutqT0laRWDPhDQM/zHsT0EDi9oCjkM3D99@CZtqbGrs9hw1ZcoHt@3uaJb1RItYP63lbO2X/dot9L/EbfcnybeqqDrx9S8 "C (clang) – Try It Online") *Saved 8 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!* *Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* *Saved a byte thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)!!!* [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~8~~ 3 bytes ``` M$R ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=M%24R&inputs=&header=%CE%BB2%7C-%3B%20%0A2%202N%22%0A%CE%BB%C2%B2%3B&footer=) Takes `[g, [a, b], f]`. If reduction was reversible, then this would be 2 bytes. ## Explained ``` M$R M # map f over [a, b] $R # reduce that by g ``` [Answer] # Excel (Insider Beta), 29 bytes ``` =LAMBDA(f,g,a,b,g(f(a),f(b))) ``` `LAMBDA` is only available through Excel Insider Beta. The functions have to be defined as names to work. In my case, I defined a name q that is equal to the above and then used the formula `=q(LAMBDA(x,x^2),LAMBDA(x,y,x+y),1,2)` in a cell. This could also be done by defining the names `a=LAMBDA(x,x^2)` and `b=LAMBDA(x,y,x+y)` and then use the formula `q(a,b,1,5)`. [Answer] # [Red](http://www.red-lang.org), 24 bytes ``` func[f g x y][g f x f y] ``` [Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vfllpk9T@tNC85Ok0hXaFCoTI2Ol0hDchIAzL//wcA "Red – Try It Online") This version doesn't work in TIO (Red is not up-to date), that's why I provide a screenshot from my Red GUI console: [![enter image description here](https://i.stack.imgur.com/HDHRu.png)](https://i.stack.imgur.com/HDHRu.png) # TIO compatible version, 28 bytes ``` func[f g x y][do[g f x f y]] ``` [Try it online!](https://tio.run/##ZY69DoMwDIT3PMWNFIkBWpY8RtcoA8UJygIl/Ch5@tRBrURbyZbsu@8se0PpbkhpMe3Gy2S3sVcWAwKiVjSpAZZny5tOyyxxAEGrgBJBCxu@pBJXVCgO88JT4K4zFT9YPhszeHuDHMlkwSLikdHC0emqFuLp3bgifwi5zJAdEWo0f/qyPVbf9Suq5se1IXdEVXO9nbPvCJLc7shwtkWbXg "Red – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes ``` ₂₁⁰₁ ``` [Try it online!](https://tio.run/##yygtzv7//1FT06OmxkeNG4Dk/0fTFnJp//9v@N8IAA "Husk – Try It Online") Black-box functions are supplied as sequential lines in the code (in the footer in the TIO link), input values are given as program arguments. ``` ₂₁⁰₁ # 2 argument function: second argument is implicit ₁ # perform function ₁ using second argument ₁⁰ # perform function ₁ using first argument ₂ # perform function ₂ using the last 2 values as arguments ``` [Answer] # [Coconut](http://coconut-lang.org/), 11 bytes Takes input as `Ꙫ(g)(f, [a, b])`. ``` g->g<*..map ``` [Try it online!](https://tio.run/##S85Pzs8rLfn/auYqBVuFmP/punbpNlp6ermJBf@LC4FCFQq6dgoVWlpGXAVFmXklGkCFGrqaGsWFOgrRRjoKukaxmpr/AQ "Coconut – Try It Online") `<*..` is the *multi-arg backward function composition*, which makes this function equivalent to ``` g->*args->g(*map(*args)) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [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")) Full program version of [rak1507's implementation](https://codegolf.stackexchange.com/a/223885/43319). ``` ⎕/⎕¨⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jvqn6QHxoBZAAifxXAIMCLhMFcy5FLm0A "APL (Dyalog Unicode) – Try It Online") [Answer] # [Julia](http://julialang.org/), ~~17~~ 16 bytes ``` F(!,+,a,b)=!a+!b ``` [Try it online!](https://tio.run/##XY9BasMwEEX3PsWYbCQ8irBi0yQ0pZvmGAFFkWw1tlRimcon6wF6MNcOhTqF2Qzvf3j/vW@szOM4HkmKGUo800Mqs/Q8JoZECgeIJ5FUJOJwf9iQvHa1/4QjMVghEyhoMkXdTLu@JZa9VOpCLDr6LDDfT2AFb32jbxB8sNoFML1TwXoH5uZbqEP46PacK3/RlW/MugtSXXVUtXSVXivfcsm3m7J44rttWeR/MiJCBo8@Je7uOr/mGzbZs8gWpeFUsBkMM3jckk@3aC9Ww/cX/B9eYknHHw "Julia 1.0 – Try It Online") **Previous answer, 17 bytes** ``` g*f*x=g(f.(x)...) ``` [Try it online!](https://tio.run/##XY9BbsMgEEX3PsVI3UDCgHCMmkRN1U2vEckigEltqGKs4pP1AD2Ya0ddON3N6M3XvH8dWl/LPE1uYzf55IjlJFPOOZ3sPMAJ8rksHMlsvC84Fm99E79guSdYMihpUVgSFtoPHfH46vSFeBboS8nkcQZP8D605gYpJm9CAjsEnXwMYG@xgyalz/4ohI4X42JreZ9q/WGyburgDNexE7XY71T1LA57VcmVzDbDFh6EFDvcdf7MdzjbY8ZVaDxXuIBxAQ9dJEO5Cq/@wM83/OutGCo6/QI "Julia 1.0 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 10 bytes ``` ${z|x|>&y} ``` [Try it online!](https://tio.run/##XYyxCsIwFEX3fMUjFBeTSqsuhbqIxUkE3R5PKDVUQVppoyTWfntMURAd7nLuuTfXOi9OymVJ6oLu8TTPxcj2bqPUscXgei1KYjvdnKtyX2e3qtDnukJDkKSwuueXtWoU8qDjMAbjw3tOjG29r/eq1cu8VS2Ogi7DMAz/f9KFEWCpF4AMABCQm0PMBXAjLSePZSwgJiDx7afSO9LIaPDsYSYHZAf0XkQCZPQzGcTsUtcNmomlz@9cwNxbjMi9AA "Attache – Try It Online") Takes input as `F[f, g, [a, b]]`, where `F` is the above function. This is two separate pipes: The vectorizing pipe `|`, and the regular pipe `|>`. `z|x` pipes each element of `z` into the unary function `x`, i.e., `Map[x, z]`. Then, this array is piped to `&y`, which passes each element of the array as a separate parameter. ## Alternatives `${&y!x=>z}`, 10 bytes. Same input as above. `{_2@@Map[_]}`, 12 bytes. Takes parameters `f` and `g`, returns a function which takes a tuple `[a, b]` as input. # [Attache](https://github.com/ConorOBrien-Foxx/Attache) (builtin), 3 bytes ``` `#: ``` [Try it online!](https://tio.run/##XYzLCsIwFET3@YpLLKKYVFrtplA3YnElgu4uVyw1qCCttFESfPx6TVEQXczmzJnJtM7yg2rSOGm2nbhZKLWr0Tuf8z2xla6OxX5dppci18eyQEMQJzC7Zqe5qhRy78ZhAMaFPzgxtnS@XqtaT7Na1dj1br3/j2Ri4D6B7jPto@/7lh4CkAEAAnKzCbkAbqTl5LAMBYQEJL79SDpHGhm0nt2MZYtsi96LQIAMfiatmJ7KskIztPT5jQREzmJEzQs "Attache – Try It Online") Simple quote-operator. Called as `(`#:)[g, f][a, b]`. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 11 bytes ``` [@:g"!...g] ``` [Try it online!](https://tio.run/##TY7BCsIwEETv@xWjF5NDAkk95SA99SdKLUVLDyKGNgWD5NvjNoJ62J0d5g3sEobLbbzm3NZu2u@01lOXa9cQCSF6CyvxwhOOx@KMVFwsPkIhSQJzBr35gRWDH1yxKpgN/BYjjiWvSh7/uAQpiVo3j36GXwMOUCde28mPNXisocN98JTf "Stacked – Try It Online") Simple anonymous function. Takes input on stack as `(a b) f g`. Works by storing `g` as a temporary function variable. Then, applies the `"` transformation on function `f`, which makes it apply on each element its called on. `!` calls this function `f"` on the tuple `(a b)`. Then, we simply put these two elements on the stack and call `g`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 30 bytes ``` #define o(f,g,a,b)g(f(a),f(b)) ``` [Try it online!](https://tio.run/##PYzNCsIwEITveYqlIuzqetBr8WE2v@RgqmkLgdJnj0kFL8POzLdjbsGYWk/W@ZgcTOg5sLCmgB6F2KMmqjEtMH9WyQ77WWjLbllzgnIp4656JtYenXBX/SfkqhtxIC@JCZA2Bd1lNz8n/K1y@@Y7P2hU8M6t9YDD2Q7coJbt9Qs "C (gcc) – Try It Online") [Answer] # Standard ML, 24 bytes ``` fn(f,g,a,b)=>g(f a)(f b) ``` --- ### [Concurr pre-release](https://codeberg.org/Wezl/Concurr/commit/22c5242bfe500ba531b6f3808ec60af1f0e74386), 50 bytes ``` $lambda\f:lambda\g:lambda\a:lambda\b::g(:f a)$:f b ``` Wow that's horrible. ]
[Question] [ *Note: This is the **cops'** thread, where one should post the scrambled code. Here is the **[robbers' thread](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root)*** where the cracked source should be posted and linked to the cop's answer. --- **Task:** Write the shortest *safe* program which multiplies the square root of an integer ***n*** by the square of ***n*** This is [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"), so the rules are: * In your answer, post a scrambled version of your source code (the characters should be written in any order). The scrambled version **should not** work! * You can take input in any standard way, the same goes for output. Hardcoding is forbidden * After the code is cracked by the robbers (if this happens), you must mention that your code has been cracked in your title and add a ***[spoiler](https://meta.stackexchange.com/questions/1191/add-markdown-support-for-hidden-until-you-click-text-aka-spoilers)*** to your answer's body with your exact code * The same applies to safe answers (mention that it's safe and add the ***[spoiler](https://meta.stackexchange.com/questions/1191/add-markdown-support-for-hidden-until-you-click-text-aka-spoilers)***) * The code is considered *safe* if nobody has cracked it in 5 days after posting it and you can optionally specify that in the title * You must specify your programming language * You should specify your byte count * You must state the rounding mechanism in your answer (see below) --- You can assume that the result is lower than 232 and ***n*** is always positive. If the result is an integer, you must return the exact value with or without a decimal point; otherwise the minimum decimal precision will be 3 decimal places with any rounding mechanism of your choice, but can include more. **You must state the rounding mechanism in your answer.** You are not allowed to return as fractions (numerator, denominator pairs - sorry, Bash!) ### Examples: ``` In -> Out 4 -> 32.0 (or 32) 6 -> 88.18163074019441 (or 88.182 following the rules above) 9 -> 243.0 25 -> 3125.0 ``` The shortest safe answer by the end of April will be considered the winner. [Answer] # [Python 3](https://docs.python.org/3/), 44 bytes ([cracked](https://codegolf.stackexchange.com/a/116254/45151)) ``` '**:(((paraboloid / rabid,mad,immoral))):**' ``` No rounding. Floating point accuracy. [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ([cracked by @tehtmi](https://codegolf.stackexchange.com/a/115451/36398)) ``` 'Un&0P'/^:+1 ``` No rounding; uses floating point. Intended solution (different from that found by @tehtmi): > > `:&+n10U'P'/^` > > > ### Explanation > > `:&+ % Create a matrix of size n × n, where n is implicit input` > > `n % Number of elements. Gives n^2` > > `10U % 10 squared. Gives 100` > > `'P' % 'P' (ASCII code 80)` > > `/ % Divide. Gives 1.25` > > `^ % Power. Implicit display` > > > > [Answer] # [Röda](https://github.com/fergusq/roda/tree/roda-0.12), 28 bytes ([Cracked by @tehtmi](https://codegolf.stackexchange.com/a/115449/49958)) ``` (),.025^^cdfhnnnopprstuu{|} ``` Note the space at the beginning. No rounding, but it uses floating point numbers so precision is limited. [Answer] ## Perl, 42 bytes (Safe) There are 41 bytes of code and `-p` flag (no other flags). ``` /"/4~~r..rso4r<_$4va=eg1de|i/h0-&$c={}l+" ``` The result isn't rounded (or rather rounded up to the same point Perl would have round up by doing `$_ = (sqrt $_) * ($_ ** 2)`). **Solution:** > > `$_=eval".i44<4}{|~"=~s/./chr-10+ord$\&/gre` > > (without the `\` before the `&` - markdown spoiler seems to dislike `$` followed by `&`) > > [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K8Sb5talpijpJdpYmJjUltdU6dkW1esr6efnFGka2ignV@UoqKmn16U@v@/JQA "Perl 5 – TIO Nexus") > > > **Explanation:** > > `.i44<4}{|~` is `$_**2*sqrt` but with every character replaced by the character with its ascii code + 10. (ascii code of `$` is `36`, so it becomes `.` whose ascii code is `46`, etc.). > > The purpose of `s/./chr-10+ord$\&/gre` is then to undo this transformation: it replaces each character by the character with ascii code 10 lower. (`chr-10+ord$\&` is probably clearer as `chr(ord($\&)-10)` where `chr` returns the character corresponding to an ascii code, and `ord` returns the ascii code corresponding to a character). > > finally, `eval` evaluates this string, and thus computes the result, which is stored in `$_`, which is implicitly printed at the end thanks to `-p` flag. > > > [Answer] # Octave, 43 bytes (Safe) ``` $'()*+,-/23579:[]aelnouv'*,-23:[]lu',-23]', ``` This is a script that requires input from the command line (it's not a function). It's floating point accuracy (so no rounding). **Solution:** > > `eval(-[5,-2:3,-3:2]+['nlouu*$$',39,']2/7'])` > > > > **Explanation:** > > `eval( <string> ) % Evaluated the string inside the brackets and executes it` > > Everything inside the `eval` call gets evaluated to `input('')^2.5` > > > **How?** > > > `-[5,-2:3,-3:2] % A vector: [-5, 2, 1, 0, -1, -2, -3, 3, 2, 1, 0, -1, -2]` > > `['nlouu**$$',39,']2/7'] % This is a string: nlouu**$ concatenated with the number` > > `. % 39 (ASCII ']'), and ']2/7'. Thus, combined: 'nlouu**$$']2/7'` > > > Adding the first vector to this string will convert it to the integer vector: > > `[105, 110, 112, 117, 116, 40, 39, 39, 41, 94, 50, 46, 53]` > > > `eval` implicitly converts this to a string, and these numbers just so happens to be: > `input('')^2.5` > > > [Answer] # C, 50 bytes ([Cracked by fergusq](https://codegolf.stackexchange.com/a/115176/8927)) ``` %(()) ,-12225;>\\aaabbdddeeefffllnoooprrttuuuuw{ ``` Uses standard IEEE754 rounding. As noted by fergusq's answer, may require `-lm` depending on your compiler. [Answer] # Mathematica, 131 bytes, non-competing?, [cracked](https://codegolf.stackexchange.com/a/115146/66104) *This has been **cracked by [@lanlock4](https://codegolf.stackexchange.com/a/115146/66104)**! However, I still have internet points to bestow on someone who finds the original solution, where all the characters are actually needed....* ``` f[y_]:=With[{x=@@@@@@#####^^&&&(((()))){{}}111111,,+-/y},Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]] ``` This is intended as a puzzle. Although you may use the above characters however you want, I certainly intend for the answer to follow the form ``` f[y_]:=With[{x= @@@@@@#####^^&&&(((()))){{}}111111,,+-/y },Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]] ``` where the first and third lines are just a wrapper to make the rounding and display legal (it writes every output to exactly three decimal places, rounded), and the second line is the scrambled version of the guts of the code. Sample outputs: ``` 6 -> 88.182 9 -> 243.000 9999 -> 9997500187.497 ``` (Mathematica is non-free software, but there is a [Wolfram sandbox](https://sandbox.open.wolframcloud.com) where it is possible to test modest amounts of code. For example, cutting and pasting the code ``` f[y_]:=With[{x= y^2.5 },Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]] ``` defines a function, which you can subsequently call like `f@6` or `f[9]`, that does the same thing as the unscrambled version of the code above. So does this really have to be non-competing?) [Answer] # Swift - 64 bytes (Safe) ``` prot Fdnufi;nooitamunc xetgru(->atl)Ior:n{tFn pg,F(ao.o25t)(w)l} ``` No rounding, and displays a `.0` even if the result is an integer. [Answer] # Haskell, 16 bytes ([Cracked by @nimi](https://codegolf.stackexchange.com/a/115104/61405)) ``` ()*...25=eglopxx ``` No particular rounding [Answer] # R, 28 bytes ([Cracked by @Flounderer](https://codegolf.stackexchange.com/a/115132/26905)) ``` funny(p1)-tio(^*^)/pc(2)<p2; ``` Standard R floating-point accuracy. [Answer] # C#, 172 bytes ([Cracked by SLuck49](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115332#115332)) ``` (((((())))))***,,,,......1225;;;;;;<====>CFLMMMMMPPPRSSSSSWaaaaaaabbbbcccddddddeeeeeeeeeeegghiiiiiiiillllllmmnnnnnnnooooooooqqqqrrrssssssssstttttttttuuuuuuuvvwyy{{}} ``` This code is a full program. There are seven space characters at the start. The input is read form STDIN and printed to STDOUT. The result is in `double`, no rounding done. Original Code ungolfed: ``` using System; using S = System.Console; class P { static void Main() { var t = S.ReadLine(); double q = int.Parse(t); Func<double, double, double> M = Math.Pow; S.Write(M(q, 2 * .25) * M(q * q, 1)); } } ``` [Answer] ## Ohm, 11 bytes ``` M ⁿ¡D¼½;+1I ``` Use with `-c` flag. Uses CP-437 encoding. [Answer] ## JavaScript (ES7), 20 bytes ([Cracked by @IlmariKaronen](//codegolf.stackexchange.com/a/115142)) ``` ****..22255666=>____ ``` Standard JavaScript precision. [Answer] # Python 2, 60 Bytes ([Cracked by @notjagan](https://codegolf.stackexchange.com/a/115140/63641)) ``` 3n0)4 5)594p3(p5*5i9t4542)0/*((8(t.84- 90945 u)i*48/95n8r8 ``` No rounding involved. Accurate up to 10 decimal digits. [Answer] # Python 3.6, 59 bytes ``` ba(,b5,d' (,a/([m:'-)oa)(bl*aadplma dba](r)d )l*d,:)*m:-mml ``` No rounding. Floating point accuracy. [Answer] ## Haskell, 64 bytes, ([cracked by Laikoni](https://codegolf.stackexchange.com/a/115223/34531)) ``` $$$$$$(((((())))))**,...0<<<>>>[]cccccdddeffiiiiilloopppprrsstuu ``` Standard Haskell floating point operations. My original version is: > > product.((($succ$cos$0)(flip(\*\*).)[id,recip])).flip(id) > > > [Answer] # [Fourier](https://esolangs.org/wiki/Fourier), 124 119 Bytes ``` ((()))*******--011111<=>>>HHINNNN^^^eeehhhhkkkkmmmmmmmmmmmmmmmmossuuuuuuuuuuuuuuuuu{{{{{{{{{{}}}}}}}}}}~~~~~~~~~~~~~~~~ ``` There are no whitespaces or newline characters. Square root is rounded to the nearest whole number because Fourier doesn't seem to handle anything other than integers (and since @ATaco got permission, I hope this is ok) fixed an editing mistake, if you were already cracking this, the previous was functional Realized that I had misunderstood part of the code, and was using more characters than I needed to If I missed anything let me know [Answer] # [Inform 7](https://en.wikipedia.org/wiki/Inform#Inform_7), 71 bytes ([Cracked by @Ilmari Karonen](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115135#115135)) ``` ""()**-..:[] RT aaaabeeeffilmmnnnnnooooooqrrrrrssstuuy ``` The code includes 17 spaces and 2 new lines. This is a full Infrom 7 program defining a function that prints the result with a precision of 5 decimal places. [Answer] ## R, 19 bytes [(Cracked by @Steadybox)](https://codegolf.stackexchange.com/a/115136/26905) ``` mensana(4*5*c(.1)): ``` Standard rounding ## R, 33 bytes [(Cracked by @plannapus)](https://codegolf.stackexchange.com/a/115230/26905) ``` (rofl(17)^coins(2*e)/pisan(10))-- ``` ## R, 31 bytes [(Cracked by @plannapus)](https://codegolf.stackexchange.com/a/115993/26905) `h=f`l`u`n`c`t`i`o`n([],[])^(.9)` [Answer] # Octave, 30 bytes (Safe) ``` (((((())))))**++/:@eeeiiijmsu~ ``` A bit simpler than my first one. Shouldn't be too hard, but it's hopefully a fun puzzle. [Answer] # 05AB1E, 20 bytes - safe Another totally different approach from my previous answers. ``` ****++/133DDFPTs}¹¹Ð ``` No rounding. **Example runs** ``` In -> Out 0 -> 0 4 -> 32.0 6 -> 88.18163074019441 25 -> 3125.0 7131 -> 4294138928.896773 ``` I have no doubt @Emigna is going to crack it in a jiffy, but eh, one has to try! :-D --- **Solution** ``` D1TFÐ*D¹3*+s3*¹+/*}P ``` This is using the fact that this sequence: u\_0 = 1, u\_{n+1} = u\_n \* (u\_n ^ 2 + 3 x) / (3 u\_n ^ 2 + x) converges to sqrt(x), and cubically fast at that (sorry, didn't find how to format math equations in PCG). **Detailed explanation** ``` D1TFÐ*D¹3*+s3*¹+/*}P D1 # Duplicate the input, then push a 1: stack is now [x, x, 1] (where x is the input) TF # 10 times (enough because of the cubic convergence) do Ð # triplicate u_n * # compute u_n ^ 2 D # and duplicate it ¹3*+ # compute u_n ^ 2 + 3 x s # switch that last term with the second copy of u_n ^ 2 3*¹+ # compute 3 u_n ^ 2 + x / # compute the ratio (u_n ^ 2 + 3 x) / (3 u_n ^ 2 + x) * # compute u_n * (u_n ^ 2 + 3 x) / (3 u_n ^ 2 + x), i.e. u_{n+1}, the next term of the sequence } # end of the loop P # compute the product of the whole stack, which at that point contains u_10 (a sufficiently good approximation of sqrt(x)), and the 2 copies of the input from the initial D: we get x ^ 2 * sqrt(x) ``` [Try it online!](https://tio.run/nexus/05ab1e#@@9iGOJ2eIKWy6GdxlraxcZah3Zq62vVBvz/bwYA) [Answer] ## [OCaml](http://www.ocaml.org/), 13 bytes ([Cracked by @Dada](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115078#115078)) ``` 2*fn-5f>f*u . ``` No rounding (within IEEE 754 scope). [Answer] # Javascript, 123 bytes, [Cracked by notjagan](https://codegolf.stackexchange.com/a/115108/64505) ``` """"""((((((((()))))))))********,--.....//2;;======>>Seeeeeeegggggggggggghhhhhhhhhhhilllllnnnnnnnnnnorrrsstttttttttttttu{} ``` This code is a full function There is one space character at the very start of the list of characters The rounding of this answer is the floating point precision for Javascript, accuracy is within 10^-6 for every answer. Got shorter because the precision didn't need to be maintained quite as high as I thought it did. I had realized that it would be much easier to solve than I initially had made it but it was already there :P **Initial code:** ``` g=t=>t-(t*t-n)/("le".length*t);e=h=>{n=h*h*h*h*h,s=2**(n.toString("ng".length).length/"th".length);return g(g(g(g(g(s)))))} ``` Newtons method, applied 5 times from the closest power of 2 [Answer] # Python 3.6 - 52 bytes ([Cracked by @xnor](https://codegolf.stackexchange.com/a/115161/67047)) ``` f=lambda x:x**125*77*8+8/5/((('aafoort.hipie.xml'))) ``` Standard Python rounding [Answer] ## Ruby, 35 bytes (cracked by [xsot](https://codegolf.stackexchange.com/a/115171/18535)) ``` 'a'0-a<2<e<2<l<3<v<4<4<4<5<5<6>7{9} ``` No rounding. Floating point accuracy. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 47 bytes ``` )*.2555BFHIJJKKKPQRST``cgghilnstwx}«¹¹Áöž‚„………… ``` Does not round, uses floating point accuracy. [Answer] ## CJam, 8 bytes ([Cracked by E~~n~~mig~~m~~na](https://codegolf.stackexchange.com/a/115203/56341)) ``` WYdYl##+ ``` No rounding. Uses double precision. [Answer] # R, 32 bytes ([Cracked by @plannapus](https://codegolf.stackexchange.com/a/115227/61405)) ``` i=na*0.5f*n(2*s*cos(t))*22*s*12u ``` Standard floating-point accuracy. [Answer] ## Excel, 26 bytes ``` =(())*//11122AAAIINPQRSST^ ``` No rounding. *Note: As Excel is paid software, this works also in free LibreOffice* [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 6 Bytes ([Cracked by @notjagan](https://codegolf.stackexchange.com/a/115286/63641)) ``` š2]^*\ ``` No rounding, displays many decimal places. Does not display any for an integer solution. ]
[Question] [ Your task is to output the exact string ``` The Jabberwocky ``` without taking input. Normal rules for input and output apply, so both functions and programs are allowed. Of course there is a catch, it wouldn't be fun without a catch. Your program, when stripped of non-alphabetic characters, must start the poem [The Jabberwocky](https://en.wikipedia.org/wiki/Jabberwocky) (case insensitive). To start the poem it must be a continuous substring of the poem starting at the beginning. The empty string is fine (although you probably won't score very well). Here is the text for reference: ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthouslainthejabberwockcometomyarmsmybeamishboyofrabjousdaycalloohcallayhechortledinhisjoytwasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabe ``` [Here](https://tio.run/##vZPfa9swEMff/VeIMBYnZabbS1NYHtpuDLbBYAz6MAY92WdLjaQL0rmu@s9nJzddV9jzgpxE5@/9@JxOBtIOnTscrN9TZPUBGJorA7G63y54gqSjdc4OEDo2mJxlk5nuMHW2G3JEsQ/Wa4c2yPsJNIJz3vqUJ4woJk2RhuLwGMGTxwhsEo08RJFrcZqFt6A1xonanc@JwmyZEhtgbbkIWnfct7LMs9@oZWkbO8mQzFg8@zh6S2PSYsKYQnEwyEQ7Y9MdxT24NFHsbDCicBQGtr4E8xDupcKeUGBpHAwnipgYOyHJIuDRlxWxkCeJ2MFk7CP@rBczJBvGvrfJHG0SqyhfQE7SScySpO8deGzlkUCysVKMiUc/Ht2AeSppQqfHKI0u4bnIKSDLm/l7bu7s9PxP3B9RtYMOJwycgm13cz/anUGHPVvuEErsUo7lZGRnZu0AbvR7I9VoUYvCQOLCkxzY8AKllY4x@QzRJ59lAryga8rUywHfikcHuZWxIDLlB7KcpZFhExY5AJtuKf@PSVucnLS5dbhoFlW/FVHzYPfXkqbeblf3TW8dY6xvpC/@5ucSlk2zfFj@WjUe9orpK0maygv7tqNKwfs3A/KVzGnpa6X2Ucp61Ss4HArL6/UTzdnZ5u270KkfM5MqUOqbFKlmLDVzqU/WqyOZKmhK2NQMp4RucfxUVSWgSiRaUVSkBnnuUCVQQf1BvvjX5fp8cXn58fv1t6svT5drVa9X9aqu1@eb883p@emmrlfr@q8r9xs) is a program you can use to test this property. If you run out of poem to use you **may not** use any additional alphabetic characters. Alphabetic characters are characters `a`-`z` and `A`-`Z` here is the complete list: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` ## Scoring Your program will be scored in the number of non-alphabetic bytes used with fewer being better. [Here](https://tio.run/##vc1BCgIxDADAe1@Rg1A9mBe4p9WbPxBhA6bbYpqUbEDw8@svnA9Mpe3NIvve@jAPuFIQzpU8lUlY16hYmgT7cVGLm3BfHpkyYv7m5wk7DQi724c9dWo6vSwBXc4rx2warLElGN40DgXoP8sP) is a Haskell program that scores answers. (This assumes inputs are valid) ## Example program The following program would be valid: ``` twas&*brilliga77812nd Thesli thyt Oves didgy reand Gim bleinth ewab eal lmims ywe"""""""" ret h eb or o g o ve sa n dthemomerAthsoutgrabebewaretheJABBERWOCKmysonthe)(*)()((*98980908(()*(jawsthatbit ``` When stripped down to alphabetic characters it is: ``` twasbrilligandTheslithytOvesdidgyreandGimbleinthewabeallmimsyweretheb orogovesandthemomerAthsoutgrabebewaretheJABBERWOCKmysonthejawsthatbit ``` Which matches the first bit of the poem (case insensitive). This program would score 59 because it contains these non-alphabetic characters: ``` &*77812 """""""" )(*)()((*98980908(()*( ``` [Answer] ## [oOo CODE](https://github.com/TryItOnline/brainfuck), score 0 *Thanks to Dennis for golfing the Brainfuck code.* ``` TwASbRIlLIgAnDthEsliTHyTOvEsdiDgyreaNdgImbleinthEwaBeaLlmimSywEreThEBoroGoveSAndTheMOmERaTHSoutGRabEbeWArEthEjaBbeRWockMYsONtHEJawsTHaTBiTEThecLawSthATcaTChBeWAReTHeJuBJuBBiRDAndsHUNtHeFRuMIoUSbANdERSnatchheTooKHisvORpaLswORdinhAndLonGtiMetHEmanXomEFoEHeSOUg ``` [Try it online!](https://tio.run/##Dc1db4QgEIXh3waVXdyqJDBm28tRJ0IrTCN@xF9vSc7dyZOXmUee6L7hFG6w9dLUs0jV5lVeAugLzKHyFKr5Wgm7aa7jsFBI5T9REjZLDNFdp1oJvJK88pMPciJN4Kk1UVkE7XjfnhYHNdBbrKrYH5QD2TePv@13Nt2m1QvPDBpBBlCFjg2ebvMCRoQPL4uzBJpeuyyTwValkHVfJD3s3tbcu0F0k7Iu4TZ6T8D8qUM@jP3DJp/GTiH5ghpOzy20VJIR0xdH9WClyZl@vu9/ "oOo CODE – Try It Online") I've got bad news for this challenge... :( oOo CODE is just a binary encoding of brainfuck which uses the case of a letter for each bit. So yeah, since the poem is long enough (or the output short enough) to cover a Brainfuck program that prints `The Jabberwocky` (without actually trying hard to golf it), this becomes a trivial optimal answer. [Answer] # C, score ~~104~~ ~~79~~ 74 *Thanks to @gastropner for lowering the score to 79 and thanks to @wizzwizz4 for lowering it further to 74!* ``` *t,w;a(s,b,rilligand){*(t//he =s++)="lithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewareThe Jabberwock\0mysonthejawsthat"[b++]?//i :121;*t>12e1?*++t//hecl =0:a//wsthatcatchbewarethejubjubbirdandshunthefrumiou (s,b);}an;der(s,n){a(//tchhetookhi s,88);} ``` [Try it online!](https://tio.run/##LY@9bsMwDIR3P4WRyX@BYmcJYrjZO3dLM0gyI6mRrIKSaxhBXr0unZTgcsR3h6PcKimXpYjV1PIsVKJCY61RfOjze5FFxjQkXSjLvNtYE/Uc/Q@E3vRqRiBIGScsmCFqmLgAbq0zLswTINBJePRqNRBJ0nkHyKMOfowKCRdkQvjQkL5zIQAnL2@fOzcHvwZ@8SlEzePmLMrycmLMJMe6qdsivtUN1KeiLJ/9pE263ZEz9sIlrX4lryGjoBUGe@oQ9LgGX3F0xo/J@m/ePvjQ9oAkhvzOM8bIriF6f9MmCdXhQMhCH6aOmyHLk3uS0kjNMQ0Rz/vm0j4vz4yI@Ut9jzH8y8fyK6@Wq7Bs3b75Aw) [Answer] ## [Fission 2](https://github.com/C0deH4cker/Fission), score 3 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaRe"The Jabberwock"mysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthouslainthejabberwockcometomyarmsmybeamishboyO ``` [Try it online!](https://tio.run/##VVJRbuUwCLzKqkfYY/RnpdVeAMfE0GebCnC9Pv0rzntVVcmJAp4ZmFFONmPpv@93n2BJuVYu0LMTWmWn5fKBljmXpRj9wi1V5B73ExJCrY2brYmK0UqiUjbhodCkoYKTyfCiAU9B@osv/wh/vUJKqFOO20tbJlvwDaY5gSf2LXbUZ33EoU29ZryNFCex5hhiNDbz1NFYhqVooVrfBEIXuRHbh@g7VJuimTsFokovzm2LNej/Y8lTMPzKKOQmiuaYw8wKgI@2j@I2b6GYYRI/Erjw0QbjPs6TjZ690NrIy9KXyxlh4ooh51mh4RFPCEXBsQzpk@ejFlxzj@k5DY2st7xvuHT0uLneV74X6fsr6A@rqULGid2t83G78jhuhBVPZ88IW3uvw24UFV3YAnW0d4ptUqADQWC@/VgF7j@sHJGYS1ugzdqKn6CF9STrz/3@CQ "Fission 2 – Try It Online") ### Explanation We can ignore most of the lowercase letters, they just set an atom's energy to their code point. ``` ...Re"The Jabberwock"my...oyO ``` The uppercase `R` is the program's entry point, as it creates an atom going right. As I said, we can ignore the `e`. Then `"` toggles string mode, which just prints all characters it encounters to STDOUT, which gives us `The Jabberwock`. That only leaves the `y`. We could use the `y` that's coming up immediately in `y`, but then we'd have to waste at least one non-letter byte on printing it (`!`) and possibly another on terminating the program. Instead, we patiently wait for `y` to show up immediately before `o` in the poem. Because that lets us use `O` which prints the character *and* destroys the atom, terminating the program. This way, the only non-letter characters we need are the space and the two quotes. [Answer] # [Alice](https://github.com/m-ender/alice), score 7 ``` "T/was"bri@lligandtheslithytovesdidgyreandgimbleinthewabeallmimsywe rethe borogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbl adewentsn ``` [Try it online!](https://tio.run/##VVBbbgMhDPzPKapcoFfoIXoBvHjBDeDKNqGcfmM2kaJKBuFhZvwIhTY8juv35wh6BaGvUiiFFi2jFrI8je@okWKago4nqlCQmv@PABhKqVR1DrwIOvYBLJyW5OlRuaIEy8rdkrgAXHYyfwIAyuDtVqdyO5GhloMB2SJs5ZVvHvmt6@ABJNEraO5LuUuvxF3BIRRtS5DRmG@Z9M7yG4oOlkgtO6NwS0Z1mdXQ/rzDndHH5Z6yKQuqYcwI0wnW6wrBNbu6Ywwj03MBJ9/hoNT6vpPmF@Zei/lvyOG7xOlF9r2EipsfN/KEvJksL531knCOVaZF6OKrXva26NzQ/Oe8z@WeovfL5c9RoVxCxIHNtB3HAw "Alice – Try It Online") The `/` makes the IP move diagonally and bounce off the edges, so the instructions actually executed are `"The "ono@`. The `n` command (in ordinal mode) pushes the string "Jabberwocky" if the top of the stack is empty, and `o` outputs the top of the stack. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score ~~6~~ 4 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathSOUTGRABEBEWARE“The Jabberwock”m”y ``` A full program printing the result (as a monadic link it prints `The Jabberwock` as a side-effect and returns the character `y`) Inserts the characters `“ ””` into a case-changed prefix of the poem. This works because: 1. The last `h` before `SOUTGRABEBEWARE“The Jabberwock”m”y` is (at least at the time of writing!) an undefined atom, which makes that all become a new link which takes the default input of `0` and performs some monadic functions, `SOUTGRABEBEWARE`, which yield `1` (see below). 2. `1“The Jabberwock”m` then performs `m`, modulo slicing, on `"The Jabberwock"` with a slice size of `1`, yielding `"The Jabberwock"`. 3. The trailing `”y` is a new leading constant chain so Jelly prints that list of characters and then yields the character `y`, and since it's now the end of the program this then gets printed. ``` implicit input = 0 S sum 0 O cast to ordinal 0 U upend [0] T truthy indices [] G group [] R range [] A absolute value [] B to-binary [] E all-equal? 1 B to-binary [1] E all-equal? 1 W wrap [1] A absolute value [1] R range [[1]] E all-equal? 1 ``` --- Previous 6 byter: ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware “The Jabberwock”m1“y ``` **[Try it online!](https://tio.run/##JY7BDQIxDAT/VEELtMGbBmxiJQb7LDmGKL8rBJq7Ru6M@M7urPZBInPfY0BHZxGusJRo1IWjzbA39cKlTqfklRWFeMl8ABKIKGufg5wSobnVn/BfUFNyiNbtFdWzjik5nbb1c2t0vgIi@bD7c1u/ekmaNw4 "Jelly – Try It Online")** The six non-poem characters are a newline plus `“ ”1“`. --- Alternative 6s: ``` “T“wasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaret“he Jabberwock”m2“y ``` ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaret “The Jabberwockmy”ṪṭṖ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), score 3 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware⎚The Jabberwock⌈my ``` **[Try it online!](https://tio.run/##JYzBDQIxDARboZ5704CdWImFfZYcc1E64IEogPKukZAT35mdTRU8Gcic0aGhswgX2HNUasJRR9hBLXMuw2nxwopCvC/fAQlElLWNTk4LobmVK/g/qCk5RG32jOJrjityOj/fe6XbBojk3dLjfL90zPkD "Charcoal – Try It Online")** Inserted the three characters: `⎚ ⌈` ...it also works with [the whole poem](https://tio.run/##vVLbkRwhDEzF8fjbCQjQjLQL6EoSh8nAHy4H4PAukT0xuy6XE3AV80B0N@qGTKBZoD4ePsGScq18Qi9OaJWdlss7WuFyLsWon9xSRe6xPiEh1Nq42ZqoGKUkKucmPBWaNFRwMhl@asBTkBQ/fv3@RvjlK6SEOiXfP37@aMtki95gmhN4Yt@Cub7mOQY96Rs1UozEWmIjo7GZh47GMixFCdX6JhC6yJ3Y3kXfoNoULdwpEFX66dy2WIP@PRo9BMOzjJPcRNEcSxhaAfDR9lDcAVgoFpjEzxQufJTBuI/jYKNXLbQ28rL0x@eMQHHFJsdRoWGOJ4RiwtEM6Yvno5645t6mlzQ08t7yvuHS0WPlel8ZX6S/f0F/Wk0VCk7sbp3z/coj3wkrHs5eELb2bofdKGZ0YU@oo71RdJMCHQgC8@3HKnD/x0qOxFzaAm3WVlyEFtaTLDninG/BKLBy3A4R2h9YcZYk6uElDoDtJut/XLjH4xM "Charcoal – Try It Online"). ### How? ``` twas ... ware⎚The Jabberwock⌈my - no input twas ... ware - print this text > twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware ⎚ - clear the screen > The Jabberwock - print this text > The Jabberwock ⌈ - (print) maximum of: my - this text > The Jabberwocky ``` [Answer] # [Ruby](https://www.ruby-lang.org/) (`-p`), Score 12 ``` $_=#twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware 'The Jabberwock'+#m ?y ``` [Try it online!](https://tio.run/##JY7BCgIxDETv/QphhT2InyDePXuXxIY22DZLmrX0560Vr2/mDaM79jGOj8tiDSoqp8QBirdINbHFbvKm6tmHrjR54IyJuMy8ARKklDnX3khpIhSV8BP@C1kyKVisslvQWccpKbn1HulwA0TSJs/Xelqyu84b7iObsZQ6ztsX "Ruby – Try It Online") Abuse all the comments! With the `-p` flag, ruby will print whatever stored in `$_`. Requires a single line of any input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), score: ~~5~~ 4 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware⎚The Jabberwock¿m¦y ``` [Try it online!](https://tio.run/##JYzBDQIxDARboR7eNGAnVmJhnyXHd1GaoAAKoA2kK4VGQhDfmZ1NFTwZyJzRoaGzCBfYclRqwlFH2EEtcy7DafHCikK8Ld8BCUSUtY1OTguhuZVf8H9QU3KI2myP4muOK3L6PJ63SpcrIJJ3S/fzredrzPkF "Charcoal – Try It Online") Edit: Saved 1 byte thanks to @ASCII-only. Explanation: Translates to the following verbose code: ``` Print("twas...beware"); Clear(); Print("The Jabberwock"); if ("m") Print("y"); ``` [Answer] # [Foo](https://esolangs.org/wiki/Foo), score 5 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware"The Jabberwock"m"y" ``` [Try it online!](https://tio.run/##JYzBDQIxDARbQSmH9zVgc0tiYZ8lxxCl@hDEd2Znn@5r5aDOIapS6Tqzoatkm@kf9FPOOgObVzFWyLX9IAapmlifA4GN2MPrL/g/mBuCsnV/Z4095x0FytFwuxMzYvjjVazMstYX) [Answer] # [><>](https://esolangs.org/wiki/Fish), Score: ~~13~~ 12 ``` \twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware \"The Jabberwockmy"$~\sonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyeso fflamecamewhifflingth>ro< ``` [Try it online!](https://tio.run/##NVAxcgMhDOz9iownz8jkAalTuoFDIMWAMpIwuSZfvwjbmRGFlt2VVpkUj@NiM2gUqpVK6MkQtJLhbnwDTZTKLuB4oRYrUPf/GSKEWhs13ScIOBRZuCzBw6FxAwmGysOKOD26SOB0OX8ivHyEGEEmb9e2n19/L8rL9StMNQwWyZbjVp/95oUP/WKN6BVJkk9SHEuZZTTiodEhEO1LgGDMVyS9sXyHqpMlUUdnVO7FqC2zFvqPb5oZPDSPgqYsoAbJE@1OsNFWCawLqDumMJEeZ7jzHQ5KfeTst3xi7rWY90j/QadfFHYfcsq5hgabP3fyhnwbfBd@O44/ "><> – Try It Online") [Verification](https://tio.run/##5VM9b9wwDN39KwwjwCUI6l@Q65JORccCHXoFQlm0xTtJNCQ6PmXoX79SzgFpgM5ZCsgfot4j@SjSQT6h95cLhZmTtF9AoH90kJrzvpMVsknkPU0QrTjMnsQV4WfMluxUEqp9omA8UtTzFQyC94FCLismVJPhxFMlvHoIHDCBuMyLTEnhRkkb8AjGYFp5OIWSOW6WNYsDMSQVMPjrftDl3niL0WUoWY2Q3VKZY1oC8ZKNmjDlWAkOhfnkKD9zmsHnlZOl6BThOU5CoToLEM@a4cioYnmZnGROmAWtKikKkCXUlbAqz@rRwuroVf6GVzNkiss4UnZXm/qqyHciV60kFg0yjh4CDvqoI92QJuPSlSeLn7CsNUy0Zkla6OpeKpwjip5s7624G@ntT@mvUo0HiytGyZGG01aP4eTQ4ygkFqH6rumQZKc7t2En8EuYnWZjFK0IB1mqnuyB4jspg1ZMOBRIIYeiHRBUuuHCo17wURkWyqBtwezqB4repdNmUy16AZSPXD6i07r7@6EMHru@a8a9gvoXmn9omNv9/u7cj@QF0@2T1iU8/dzBru93L7tfd32AuRX@xhqmCap9b7lp4eHThPKofVrr2rRz0rRuxhYul8PHjU1z6L47bL/@NTrdze/D/zQ@zT/n53Pihz8 "Haskell – Try It Online") and [scoring](https://tio.run/##NVExbhwxDOz3FQvDwCVF9gV2GidNkDJdLoCpW2pJnyQeSK43myJfv1A@B6AKDWaGmhGBnbGU65XrRdTHL@AwPRHokB8LtsVpylwc9cNzE/9asD7/PMBhmg5/Dr8@ThUuo8t32VCHCtweZxlGePi0oD9Jc2xuw3hRbn6fR7hej76BJeVSeIE2O6EVdtpdXtFmnpddMfCFayoYKsINEkIplavtsQUDSqKydMHNoUpFBSeT1RcNegqR4nC8@0E4foOUUDc5net@d//3aNJdX2AzJ/DE3h1P5f1@iqGbvrPWFJNY59hktHZl1rWyrJYCQrXWBYQucia2V9ELFNtEZ24UjCJRIdduVqH9jpdmwQgt60JuomiOcyTag@Br7aPYG7BwnGEjvtXwxg8YjNuaMxu9Y@HVmW@R/gfdolHcY8mQc4GKpzjhFBfuH/pZ5eEf "Haskell – Try It Online"). Immediately redirects to the second line, which pushes "The Jabberwockmy" in reverse to the stack. `$~` pops the excess `m` and `>ro<` prints the whole stack, reversing it beforehand. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), score: ~~21~~ ~~20~~ ~~18~~ ~~16~~ ~~13~~ ~~8~~ 6 ``` |twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware The Jabberwock0$*my ``` [Try it online!](https://tio.run/##JYwxDgIxDAR7XkFBRcU7qPmATVaJhZ1IjiGKxN9D0LUzO@sIqbTWNwZ1dlGVTDVFQVeJMqN90JOkPB2bZzFWSN1@EINUTazPAcdG3Lzlf3A8WDM4RentHdn3nHfkOD0Kzndiho/2fN0uV5tr/QA "Retina 0.8.2 – Try It Online") Edit: Score reduced by 2 thanks to @MartinEnder. [Answer] # C, score 23 ``` twasbrilligandtheslithytovesdidgyreandgimble(int**h){//ewabeallmimsyweretheborogovesandthemomerat *h//soutgrabebeware ="The Jabberwock"//m "y";} ``` [Try it online!](https://tio.run/##lc9NasQwDAXgvU9hUihJYGpol9P2AF3PBfyj2qJ2XCRlQhjm6nU9nRNUuyf4npA/RO9bk82yI8wZo12CJOCMknapZ@CAIe4EfR@xuAwjLjLPaboYA5t1YHMuWHjfgKBLV6nGm7sXlVqArKg5GcN1lUiduA4J1NtwSqA/rHNAW/VfgzFFDftwvLYHXHxeA@hXloD1Kb2rflYXi8s46YvSfXyypGc@/oV/ffDI0119r8LjLVzbj//MNnI7lJfnXw) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), Score: ~~19~~ 10 ``` #twasbrilligandTheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethe 'The Jabberwock'+#m 'y' ``` [Try it online!](https://tio.run/##HY0xDgIxDAT7ewXSFSn4CTUfiDkrsbDPyDZEeX0wlLua2X3pQPOOzGvtMaqDETO1eh73js4UfYZ@0A862jTMvpEAI53RcVTAyiwkPnMHswI1bT8hyYyiglaju76jWeKQ0h/cSh5cbhUAbejjWa67bGWWtb4 "PowerShell – Try It Online") Port of Pavel's [Ruby answer](https://codegolf.stackexchange.com/a/157077/42963). Thanks to Jo King for -9 points. The strings are `+` concatenated together. Once the comments are removed and the code parsed, PowerShell sees this as `'The Jabberwock'+'y'`. That string is left on the pipeline and output is implicit. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), score 14 ``` "twasbrilligand""The ""slithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethe"Š"Jabberwock"+"my"Š ``` [Try it online!](https://tio.run/##HYuxDUIxDAVXQW5poGAJahaw@VZiYX9LTiDKNizDXMFQvnt3pwvSmdeCPrBRiKoU3DeAW@UDQFPpdXZ/cdtkKzM4zyJGyrL3ygOJUdXE2hwcnIg8vPyCNHOaGwf22vzZS6ROGf1F@LzhikQcw@8POILNRGt9AQ "05AB1E – Try It Online") [Answer] # [Yabasic](http://www.yabasic.de), 13 Thanks for @Pavel's Ruby answer! ``` #twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware ?"The Jabberwock";//m ?"y" ``` [Try it online!](https://tio.run/##JYwxDgIxDAR7XoHCA@4BFPTUfMC@WImFfZbsQJTXhwDt7MwOQAje57y0DoHOIlzgyK1SCLc6mr0pMucynBYvrCjEx9o7IIGIssbo5LQQmlv5Bv8HNSWHVsNerfjScUU/8XRLj0rnOyCSd9uf6bptuuhIc34A "Yabasic – Try It Online") [Answer] ## VBA, score 5 Run in the Immediate Window: ``` ?twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware"The Jabberwock"m"y ``` How it works: > > `?` - This prints out output as a string > > > - > > `twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware` - without Explicit declaration, this is treated as an empty string > > > - > > `"The Jabberwock"` - String. When you put 2 variables/strings next to each other, VBA will automatically concatenate them. (2 non-variable strings would require a space so as not to add a double-quote) > > > - > > `m` - Another implicit empty-string, automatically concatenated > > > - > > `"y` - Another string. Left open, the Immediate Window will automatically close this when it hits the end of the line - again, automatically concatenated > > > - 1 question-mark, 1 space and 3 double-quotes. VBA sees this as `?"" & "The Jabberwock" & "" & "y"` or `?"The Jabberwocky"` [Answer] # [Haskell](https://www.haskell.org/), score 12 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware="The Jabberwock"++{-m-}"y" ``` [Try it online!](https://tio.run/##vY7RDQMhDENXQfyeboRboN9dICkRRJdAFWgRqjo7peoO/bX9bCeoJ4nM2TpUNBbhCDm0RFW4pdHKk2rgEIfR0iMrCnFefgckEFHWOjoZLQmLlfgFfg1alAxaquXRoq04Lsjo8NdE7gKIZL3cTr9tr133tx9@KnB2h7vbmnD/uzQ/ "Haskell – Try It Online") Defines a zero-argument function `twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware :: String` whose output is `"The Jabberwocky"`. [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), score 11 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware->"The Jabberwock"+//m "y" ``` [Try it online!](https://tio.run/##LU89T8MwEN37K6xMiaDujICODEhMRSyI4ZxcnEvPdmRfElmovz24tNvpfd17IyywDxP6sTs/bS1DSuoDyKvfnVJJQKhVY9HoWYh1P/tWKHj9dj9evgJ1jyeJ5O1R9ep1kxWSicRMFnwnAyYmGbKEBVNHnc0RC27JGUbyhV/BIDA7cimvGLFAJsRgr4ZbggsOI8iQwiw2Frkppoj7Y/U5oHoHYzCuoT1XD4eD21W52p5L@Wk2XMrfNyylp3JlWH0r@/2jINrU/O9U6pSToNPlgZ4KLezrXsM0ca79zNw018TL7rL9AQ "Java (OpenJDK 9) – Try It Online") ### Credits * -2 score thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) * -3 score thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score: 8 ``` “ĠȥṘ®ṖȤ» ``` [Try it online!](https://tio.run/##ARwA4/9qZWxsef//4oCcxKDIpeG5mMKu4bmWyKTCu/// "Jelly – Try It Online") Just compresses the string, and is an empty string when all non-alphabet characters are removed. Annoyingly, the shortest compressed form, `“81Iȯd»` has alphabetical characters, neither of which are `t` or `w` [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 ``` £«≡¿«_→Ä:£◘ ``` [Run and debug online!](https://staxlang.xyz/#c=%C2%A3%C2%AB%E2%89%A1%C2%BF%C2%AB_%E2%86%92%C3%84%3A%C2%A3%E2%97%98&i=&a=1) Just a compressed string literal that is in turn packed. [Answer] # [Canvas](https://github.com/dzaima/Canvas), score 5 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware∙The Jabberwockpm∙yp ``` [Try it here!](https://dzaima.github.io/Canvas/?u=dHdhc2JyaWxsaWdhbmR0aGVzbGl0aHl0b3Zlc2RpZGd5cmVhbmRnaW1ibGVpbnRoZXdhYmVhbGxtaW1zeXdlcmV0aGVib3JvZ292ZXNhbmR0aGVtb21lcmF0aHNvdXRncmFiZWJld2FyZSV1MjIxOVRoZSUyMEphYmJlcndvY2sldUZGNTBtJXUyMjE5eSV1RkY1MA__,v=1) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), score 9 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware”The” Jabberwock”:⁄m+ y+ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=dHdhc2JyaWxsaWdhbmR0aGVzbGl0aHl0b3Zlc2RpZGd5cmVhbmRnaW1ibGVpbnRoZXdhYmVhbGxtaW1zeXdlcmV0aGVib3JvZ292ZXNhbmR0aGVtb21lcmF0aHNvdXRncmFiZWJld2FyZSV1MjAxRFRoZSV1MjAxRCUyMEphYmJlcndvY2sldTIwMUQlM0EldTIwNDRtKyUyMHkr,v=0.12) [Answer] # [Pip](https://github.com/dloscutoff/pip), score 5 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestOOD|"The Jabberwock"witheyesofflamecamewhifflingthroughthetulge'y ``` [Try it online!](https://tio.run/##RVBBbgMhDPxKlUs/0lMvufQDsHixG8CRbUKR8vetSaJWMgePZ8YernQ9DhtBo1AplENLhqCFDKfxDTRRylPA8Uw1FqDm8xEihFIqVZ0DBByKLJyX4OlQuYIEQ@VuWZweXfQgfocYQQZvlzqV2wMZahgski3CVl795oX/uh69IknyDYp9KXfplbhrdAhE2xIgGPMFSW8s11B0sCRq6IzCLRvVZVZD@/ELdwYPyz2jKQuoQfIk0wnW6yqBlVzdMYWB9Iz/4DsclFrfd1J8Ye5l5/PH/fSF8Pb5l/M0/Ddh@qJ9L6HC5s/NvCE/COWltV4yvM/j@AU "Pip – Try It Online") Fortunately, lowercase letters in Pip are all variables, which are no-ops in expressions by themselves. The interesting part of the code: ``` OOD|"The Jabberwock" ``` The scanner breaks up `OOD` as `O` followed by `OD`. `OD` is an undefined variable, which evaluates as nil (falsey); we then logical-or this with `"The Jabberwock"`, and `O` outputs it without a newline. ``` 'y ``` Single-character string `y`. Since it is the last expression in the program, it is printed. [Answer] # SmileBASIC, score 10 ``` @twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware?"The Jabberwock"; @m?"y ``` This was pretty much taken directly from the Yabasic answer, and ~~since SB is a better language,~~ we can shorten it by using labels rather than comments, which eliminates the need for some of the line breaks There is also this alternative solution, for the same size: ``` @twasbrillig ... ?"The Jabberwock"+@my[2] ``` A label inside an expression is treated as a string. (`@my == "@my"`), so taking character 2 gives "y". [Answer] # [C (gcc)](https://gcc.gnu.org/), score 58 The useful fact that // style comments + newlines are cheaper than old-style ones comes straight from @wizzwizz4's comment for @Steadybox's [answer](https://codegolf.stackexchange.com/a/157082/75886). The -m32 flag is required. Some might be brought to a frumious mood by the lengthy name of the function to call, whereas others might rightly find such objections mimsy; in the end, we must all of us heed the siren song of low scores. ``` twasbrilligan;d(t,h,e,slithytovesdidgyreandgimble)int*h,*e;//wabeallmimsywere {t--?*h++=*e++,//borogovesan d(t,h,e):0;}momerathsoutgrabebewar;*e="The Jabberwock\171";mysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoug(h,tsoreste){d(4,h,e);} ``` [Try it online!](https://tio.run/##zZDNbsIwDIDP9CkQp/6KAZMmrUK777zbtoOTmiSQHxS7dBXi1deliIeY5INt2Z8@WzZKymniAUhEY61R4Nsu51rXWJM1rEcOF6TOdGqMCL5TxgmLhfFc6rrEdr0eQCBY64yjccCI2ZWb5q3UVbUvsarq9VqEGNSMAZ894MXrU3tzwWEE1hR6VjFhBA4Q2xL3qw@Ny3cQAuMQ5Olr87JZtW6k4FnjEQZiDSwMYyqlfdQyhb4j5vaxFymEiV2yJt3Pm4fYOxN6EqmFkfy8oJFDOGlDlxDPYGkIsTNepwkbvGLjZpgD/5NkDwE1JluV65opRCTG4trlz/eT2tuU3rJ0YHxeZNdsITXEJX3utt9ttsgW/8mfiqR07pnu2W36lQcLiqbG7bZ/ "C (gcc) – Try It Online") [Answer] # Batch, score 15 11 ``` :twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbiteth @ec%lawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffisht%ho%ughthestood% The Jabberwock%withe%y ``` Basically just `echo The Jabberwocky` with unused variables and labels. Old version (score 24): ``` :twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewh @if %1%fl%i==%ngthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthousla%i n The Jabberwock%cometom%y :armsmybeamishboyofrabjousdaycalloohcallayh @echo %* ``` Requires code to be saved in a file named `n.bat` and run from the same directory. Alternate version which can have any name (score 27): ``` :twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewh @if %1%fl%i==%ngthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthousla%i %~n0 The Jabberwock%cometom%y :armsmybeamishboyofrabjousdaycalloohcallayh @echo %* ``` Explanation (with variables removed): ``` :twas... Label (No labels were used, no goto in the poem) @if %1i==i %~n0 The Jabberwocky If no command line arguments, run this batch file again :arms... with the arguments 'The Jabberwocky' @echo %* Echo all arguments ``` [Answer] # Perl 5, subroutine, score 11 ``` {twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware;'The Jabberwock'.~'X'} ``` but with the character \x86 (`v134`) instead of the X. (perlsub says "The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code.") [Answer] # [Ruby](https://www.ruby-lang.org/), 9 non letter bytes ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvor=p alswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestood="The Jabberwock"+withe=?y ``` [Try it online!](https://tio.run/##RZBBbgMhDEWvEmXbM4y677oXgMGD3QCubBPK6VMziVrJGz7vf/iWHufjYSNoFCqFcmjJELSQ4TS@gyZKeQq4nqnGAtT8foQIoZRKVecAAZciC@dleCZUriDBULlbFsejm07wK8QIMni/1ancTmWoYbBItoC9vM67D/77evSJJMlfUOzLeUivxF2jSyDalgHBmG9IemfZvi@h6GBJ1NCZwi0b1RVXQ/vxPx4MXpd7RlMWUIPkXaYD1usagdVdPTOFgfRcwMm7HJRaPw5SfGmetcjt@olw@fhren0bvlDY3n3Zvw "Ruby – Try It Online") ### Golfed version (for readability): ``` x=p z="The Jabberwock"+w=?y ``` Uses a few long and useless variables. In ruby, you can put `whatever_you_want=` before an expression, and it will still return that expression, just with the side effect of creating an oddly-named variable. [Answer] # [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), score 16 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware␀The Jabberwock␀my<[<<]>[.>]>>. ``` [Try it online!](https://tio.run/##JYxBDsMgDATzlL4gL0A8oOfeohzsxgWrdpCMW8TrCVWvMztbFV9jeIOKxiKc4Dw8UxX23L18qR58pG40eWJFIT6nb4AEIspaeyOjibBYSb/g/6BFycBzLR9PNuc4I6Plkel2B0SyVp7vRXvYQtjjtsY9xnWMcQE "Self-modifying Brainfuck – Try It Online") ## Explanation Initially the tape is set up like this: $$ \begin{aligned} \dots\ \texttt{␀}\ \texttt{T}\ \texttt{h}\ \texttt{e}\ \texttt{␠}\ \texttt{J}\ \texttt{a}\ \texttt{b}\ \texttt{b}\ \texttt{e}\ \texttt{r}\ \texttt{w}\ \texttt{o}\ \texttt{c}\ \texttt{k}\ \texttt{␀}\ \texttt{m}\ \texttt{y}\ \texttt{<}\ \texttt{[}\ \texttt{<}\ \texttt{<}\ \texttt{]}\ \texttt{>}\ \texttt{[}\ \texttt{.}\ \texttt{>}\ \texttt{]}\ \texttt{>}\ \texttt{>}\ \texttt{.}\ & \texttt{␀}\ \texttt{␀}\ \dots \\ & \uparrow \end{aligned} $$ Since we want to move to the beginning of the string we use `<[<<]` such that we jump over the first \$\texttt{␀}\$ character. Now we can just move to the \$\texttt{T}\$ with `>` and print the whole string with `[.>]` and since we picked the substring where the next \$\texttt{y}\$ is not far, we can just jump to it directely and print it with `>>.`. [Answer] # [Fission](https://github.com/C0deH4cker/Fission), score 6 ``` twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaRe"The Jabberwock"m"y"; ``` [Try it online!](https://tio.run/##JYxBDkIxCAWvYnoNb@DSeAHwY0uEkgDa9PS15m9n3rwXR7D1tXJAoLMIV@hHNgrhbDPtS3HwUafT5pUVhbhvPwAJRJQ15iCnjdDc6j84H9SUHLKFfbL6nuOO7lQejS43QCQf9nwXLbNc1/oB) ]
[Question] [ (heavily inspired by [Element of string at specified index](https://codegolf.stackexchange.com/q/120375/42545)) Given a string `s` and an integer `n` representing an index in `s`, output `s` with the character at the `n`-th position removed. 0-indexing and 1-indexing are allowed. * For 0-indexing, `n` will be non-negative and less than the length of `s`. * For 1-indexing, `n` will be positive and less than or equal to the length of `s`. `s` will consist of printable ASCII characters only (`\x20-\x7E`, or through `~`). Any reasonable input/output is permitted. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Testcases (0-indexed): ``` n s output 0 "abcde" "bcde" 1 "abcde" "acde" 2 "a != b" "a = b" 3 "+-*/" "+-*" 4 "1234.5" "12345" 3 "314151" "31451" ``` Testcases (1-indexed): ``` n s output 1 "abcde" "bcde" 2 "abcde" "acde" 3 "a != b" "a = b" 4 "+-*/" "+-*" 5 "1234.5" "12345" 4 "314151" "31451" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # C#, ~~20~~ 19 bytes ``` s=>n=>s.Remove(n,1) ``` [Answer] ## [Alice](https://github.com/m-ender/alice), ~~13~~ 12 bytes *Thanks to Leo for saving 1 byte.* ``` /oI\!e]& @ q ``` [Try it online!](https://tio.run/nexus/alice#@6@f7xmjmBqrxuWgUPj/f6KCoq1CEpcRAA "Alice – TIO Nexus") First line of the input is the string, second line is the 0-based index. ### Explanation ``` / Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces diagonally up and down through the code. I Read the first line of input (the string). ! Store the string on the tape, which writes the characters' code points to consecutive cells (the tape is initialised to all -1s). ] Move the tape head right. This moves it by an entire string, i.e. to the cell after the -1 that terminates the current string. The IP bounces off the bottom right corner and turns around. ] Move the tape head right by another cell. ! Store an implicit empty string on the tape, does nothing. It's actually important that we moved the tape head before this, because otherwise it would override the first input code point with a -1. I Read the second line of input (the index) as a string. / Reflect to W. Switch to Cardinal. The IP wraps around to the last column. &] Implicitly convert the first input to the integer value it contains (the index) and move the tape head that many cells to the right, i.e. onto the character we want to delete. Note that Ordinal and Cardinal mode have two independent tape heads on the same tape, so the Cardinal tape head is still on the first cell of the string input before we do this. e! Store a -1 in the cell we want to delete. \ Reflect to SW. Switch to Ordinal. q Push the entire tape contents as a single string. This basically takes all cells which hold valid code points from left to right on the tape and concatenates the corresponding characters into a single string. Since we wrote a -1 (which is not a valid code point) over the target character, this will simply push the entire input string without that character. o Output the result. @ Terminate the program. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` jV ``` [Try it online!](https://tio.run/nexus/japt#@58V9v@/krGhiaGpoZKCMQA "Japt – TIO Nexus") [Answer] ## K (Kona), 1 byte ``` _ ``` Gotta love builtins. 0-based indexing. Usage: ``` k)"abcdef" _ 3 "abcef" ``` [Answer] # [Haskell](https://www.haskell.org/documentation), ~~28~~ 24 Bytes -4 byte thanks to Laikoni, this version is 1-indexed. ``` s#n=take(n-1)s++drop n s ``` Old answer: ``` f(s:t)0=t;f(s:t)n=s:f t(n-1) ``` A simple recursive function that takes the value, it's 0-indexed. My first time code-golfing so maybe it's not the optimal solution. Oh well. [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` q~Lt ``` [Try it online!](https://tio.run/nexus/cjam#@19Y51Py/7@xgpKxoYmhqaESAA "CJam – TIO Nexus") ### Explanation ``` q~ e# Read and eval input (push the string and number to the stack). Lt e# Set the nth element of the string to the empty string. ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 3 bytes ``` À|x ``` [Try it online!](https://tio.run/nexus/v#@3@4oabi///EpOSU1P9GAA "V – TIO Nexus") This uses 1-indexing. [Answer] ## Mathematica, 18 bytes 1-indexed ``` #2~StringDrop~{#}& ``` input > > [1, "abcde"] > > > thanks Martin Ender [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` &)& ``` Uses 1-based indexing. [Try it online!](https://tio.run/nexus/matl#@6@mqfb/v3piUnJKqjqXEQA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/ivpqn2P8KlIuS/emJSckqqOpchF4xlBGQpKNoqJKlzGXOpa@tq6atzmXCpGxoZm@iZqnOZcqkbG5oYmhoCRQE). ### Explanation ``` & % Specify secondary default number of inputs/outputs for next function ) % Implicitly input string and number. Index: with & it pushes the char % defined by the index and the rest of the string & % Specify secondary default number of inputs/outputs for next function % Implicitly display (XD): with & it only displays the top of the stack ``` In the modified version with all the test cases, the code is within an infinite loop ``...T` until no input is found. At the end of each iteration the display function (`XD`) is explicitly called, and the stack is cleared (`x`) to ready it for the next iteration. [Answer] # Vim, 7 bytes ``` jDk@"|x ``` **How it works:** It expects two lines; one with the string and one with the number. 1. Go to line two, copy the number into register 2. Go to first line and then go to column in the register with @"| 3. Delete the character under the cursor [Answer] # Java 8, 39 bytes ``` s->n->s.substring(0,n)+s.substring(n+1) ``` [Try it here.](https://tio.run/nexus/java-openjdk#lY29jsIwEIT7PMVCFZPEh0moOFIiUVBRnq5wnIB8cjZWvEZCiGfPhb8IXZWrdmdmv1ld26Yl@JEnyT1pww8eFekG@ea5rAJlpHOwkxovAYD1hdEKHEnqx6nRJdR9FO6p1Xj8@gbJbmcAr4LPRxIPeotUHas2fvh5DgrWnUtyTHLHnS/c3Q/nMbLo3cBIsO7WvLr378@Oqpo3nrjtczIYKi6tNedwKgtVVlP2lHPG/ouIUQhM1lAMzGIMEyWzj4FIxxBikWZ8OTDZGCYVmViKv3@uwbX7BQ) # Java 7, 67 bytes ``` String c(int n,String s){return s.substring(0,n)+s.substring(n+1);} ``` [Try it here.](https://tio.run/nexus/java-openjdk#jc29DoIwEMDxnac4O7VSq@VjIj6CE6NxaAsxTaAQ2poYwrNjVQYX0fHufvmfaoS1cBojAOuE0wrm0g3aXEFhbRwYuoyWjEPt/GDAMuulfW3xgRoSfy5MzEkxzQC9l02oLdFbpytohTb4nTtfQJDnU4Dybl3dss471oeTawxWoYuEVFWNCCm@K/6XSoKCzRHkOkspinfb/TrKKOJJmrH8ZyvlGc/5wqZomh8) [Answer] # [Ruby](https://www.ruby-lang.org/), 16 bytes ``` ->n,s{s[n]='';s} ``` [Try it online!](https://tio.run/nexus/ruby#S7T9r2uXp1NcXRydF2urrm5dXPs/z9aAq9hWKTEpOSVViaugtKRYITEaqCb2PwA "Ruby – TIO Nexus") [Answer] # GCC c function, 25 1-based indexing. ``` f(n,s){strcpy(s-1,s+=n);} ``` Plenty of undefined behavior here so [watch out for stray velociraptors](https://xkcd.com/292/): * The [`strcpy()` man page](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strcpy.html) says *If copying takes place between objects that overlap, the behavior is undefined*. Here there clearly is overlap of the *src* and *dest* strings, but it seems to work, so either glibc is more careful or I got lucky. * The answer is reliant on the fact that the `s+=n` happens before the `s-1`. The [c](/questions/tagged/c "show questions tagged 'c'") standard gives no such guarantees, and in fact calls this out as undefined behaviour. Again, it seems to work as required with the gcc compiler on x86\_64 Linux. [Try it online](https://tio.run/nexus/c-gcc#jZHRboMwDEXf@QoPqVICKS0Fnli@pPBAIXSRthTFYdKG@PYulI7C1qmLosS2zrWVm3NNFEPaodFl80FwHTL0uaJpf5bKwFshFRmCQh9LBuVLocHzbPJOoXPALitsSwNGoCkLFNfqsAaZSqd01OJY6CcB7nPgM1UHgeIhgwC5bV21DXGLQ1kJl0LPltTuX1S0pOCJw@EOFi8wf@1t7kDJAgp3URwkD3tFYRwm4YCNTx8dGNyRY3g56pMGIq0V2xQkPAPKT3GqyWQThc2v2n6bU0v7Pp0Z2Gjbuiau4quKAfLMXWHmMrD7JpR5oH7kSG9/NZ/xAP0epwW2r@Y6LVPuH5LeuVxamFYr@1and85f). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṭœp ``` A full program taking the (1-based) index and the string (in that order) and printing the result. As a dyadic function it returns a list of the two parts. In fact the index may be a list of **n** indices, in which case it returns a list of the **n-1** parts. **[Try it online!](https://tio.run/nexus/jelly#@/9w55qjkwv@//9v@b84Pze1JCMzL10hv0ghvyQjtQgA "Jelly – TIO Nexus")**, or see a [test suite](https://tio.run/nexus/jelly#@/9w55qjkwv@H16uFPn/f7ShjpGOsY6JjqmOSez/aKXEpOSUVCUdBK2gaKuQBGRo62rpAylDI2MTPVMgw9jQxNDUUCkWAA). ### How? ``` Ṭœp - Main link: number i, string s e.g. "fish 'n chips", 6 Ṭ - untruth - get a list with 1s at the indexes of i 000001 <-- i.e. [0,0,0,0,0,1] œp - partition s at truthy indexes without borders ["fish ","n chips"] - implicit print fish n chips ``` As an example of using multiple indexes: ``` "fish and chips", [6,8] Ṭ 00000101 <- i.e. [0,0,0,0,0,1,0,1] œp ["fish ","n"," chips"] fish n chips ``` [Answer] # [Haskell](https://www.haskell.org/), 15 bytes This requires the recently released GHC 8.4.1 (or higher). [Now](https://prime.haskell.org/wiki/Libraries/Proposals/SemigroupMonoid) `<>`, as a function on Semigroups, is in Prelude. It is particularly useful on the function Semigroup ``` take<>drop.succ ``` [Try it online!](https://tio.run/##bco7EoIwEADQnlOsGQvQAQ0JHVBZ2tHaLCFghk92Qri@0Va0ffOeuI56moKZyToPN/SYNXo2g7MbxXFZJ0nUV4/gcdRl3TlL2bopFWY0C1TQ2QiANt94d1@OPVyBYas6zb6Z/@f8w3CooN25AHZOT5edSmA8FzIrfrfgkhechZfqJxzWkCqiNw "Haskell – Try It Online") Since tio is using an older bersion of GHC, I've imported `<>` in the header. [Answer] # R, 40 bytes Just goes to show the variety of ways, none of which particularly compact, you can fiddle with strings in R. ``` function(s,n)intToUtf8(utf8ToInt(s)[-n]) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` vNÊiy? ``` [Try it online!](https://tio.run/nexus/05ab1e#@1/md7grs9L@/39DI2MTPVMuEwA "05AB1E – TIO Nexus") **Explanation** ``` v # for each element, index (y,N) in input1 NÊi # if N is not equal to input2 y? # print y ``` [Answer] # Pyth, 3 bytes ``` .DE ``` [Try it here.](http://pyth.herokuapp.com/?code=.DE&test_suite=1&test_suite_input=0%0A%22abcde%22%0A1%0A%22abcde%22%0A2%0A%22a+%21%3D+b%22%0A3%0A%22%2B-%2a%2F%22%0A4%0A%221234.5%22%0A3%0A%22314151%22&debug=0&input_size=2) Takes index first. [Answer] # JS (ES6), ~~41~~ ~~32~~ 31 bytes ``` y=>i=>y.slice(0,i++)+y.slice(i) ``` Based on [this](https://stackoverflow.com/a/9933072/6560716). Takes input through currying, first is string, second is index. -9 thanks to @JohanKarlsson -1 thanks to @ETHproductions [Answer] ## vim, ~~10~~ 7 ``` DgJ@"|x ``` Takes 1-indexed input in the following format: ``` 2 abcde ``` ``` D delete the number on the first line into register " gJ remove the newline while preserving whitespace on line 2 @" run the " register as a macro - input is used as a count for... | the "go to nth column" command x delete the character at the cursor ``` Thanks to [@DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) for 3 bytes! [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 14 bytes ``` ,[>,.<-],,[.,] ``` [Try it online!](https://tio.run/nexus/brainfuck#@68TbaejZ6Mbq6MTracT@/8/U6KCoq1CEgA "brainfuck – TIO Nexus") Reads zero-based one-byte index immediately followed by the string. [Answer] # Java 8, ~~45~~ 41 bytes ``` s->n->new StringBuffer(s).deleteCharAt(n) ``` *Saved 4 bytes thanks to @OlivierGrégoire* My first code golf answer in something other than C#, even if it isn't the shortest for Java yet. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes Zero-indexed. Takes index `n` as left argument and string `s` as right argument. ``` ↑,1↓↓ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHbRN1DB@1TQai//8NFNIU1BOTklNS1bkMkdhGYLaCoq1CkjqXMYijraulr85lAmIaGhmb6JlCxY0NTQxNDdUB "APL (Dyalog Unicode) – Try It Online") `↑` `n` characters from `s` `,` followed by `1↓` one character dropped from `↓` `n` characters dropped from `s` [Answer] # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda n,a:a[:n]+a[n+1:] ``` [Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQp5NolRhtlRernRidp21oFfu/oCgzr0QjTcNARykxKTklVUlTkwsmZohFzAgopqBoq5CELGiso6Stq6WPLGSio2RoZGyiZ4qmztjQxNDUECj4HwA "Python 3 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Jḟị³ ``` [Try it online!](https://tio.run/nexus/jelly#@@/1cMf8h7u7D23@//9/ooKirULSf2MA "Jelly – TIO Nexus") **Explanation** ``` Jḟị³ J - all indices of the input string ḟ - except for the input index ị - return the elements at those indices ³ - of the input string ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ā²ÊÏJ ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@k8dCmw12H@73@/zc2NDE0NeQyAQA "05AB1E – TIO Nexus") ``` ā # push range(1, len(input string) + 1) ²Ê # Check each for != to input index Ï # Keep characters from input where this array is 1 J # Join ``` [Answer] # PHP, 42 Bytes 0 indexed ``` <?=substr_replace($argv[1],"",$argv[2],1); ``` [Try it online!](https://tio.run/nexus/php#@29jb1tcmlRcUhRflFqQk5icqqGSWJReFm0Yq6OkpANhG8XqGGpa////P1FB0VYh6b8RAA "PHP – TIO Nexus") [Answer] # [Befunge-98](https://github.com/catseye/FBBI), ~~35~~ ~~27~~ 25 bytes *-4 bytes thanks to @eush77* ``` &#;1-:!#v_~,; _@#:~;#~<;, ``` [Try it online!](https://tio.run/nexus/befunge-98#@6@mbG2oa6WoXBZfp2PNFe@gbFVnrVxnY63z/79JooKirUISAwA "Befunge-98 – TIO Nexus") 1-indexed, note that the input has a trailing null-byte. [Answer] # **PHP, 41 bytes, 35 bytes excluding ?php** ``` <?php $argv[1][$argv[2]]='';echo$argv[1]; ``` 0-indexed [TIO](https://tio.run/nexus/php#@29jX5BRoKCSWJReFm0YGw1hGMXG2qqrW6cmZ@TDZKz///@fWlySn5eZ@N8IAA "TIO") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~3~~ 2 bytes ``` jV ``` [Try it online!](https://tio.run/##y0osKPn/Pyvs/3@lxKTklNQ0JR0FIwA "Japt – Try It Online") ]
[Question] [ Again inspired by a task for Programming 101 here's another challenge. **Input:** * A positive integer `n >= 3`. (has to be odd) **Output:** * `n` lines of asterisks, where the first line has `n` asterisks and every new line has two asterisks less than the line before. Until hitting 1 asterisk. From there every new line has two asterisks more than the line before until getting back to `n` asterisks. Spaces or something like spaces have to used to align the asterisks so that it really will look like an hourglass. **General rules:** * Trailing newlines are allowed but do not have to be used. * indentation is a must. * This is code-golf, so shortest answer in bytes wins. * Since the course is taught in C++, I'm eager to see solutions in C++. **Test case (n=5):** ``` ***** *** * *** ***** ``` [Answer] ## [Charcoal](http://github.com/somebody1234/Charcoal), 6 bytes ``` G↘←↗N* ``` Dead simple. Draw a poly**G**on of `*`, with side length taken from an input **N**umber, where the sides go down-and-right, horizontally left, and up-and-right: ``` * * * * * * * ***** ``` Then autocomplete the outline and fill it. ``` ***** *** * *** ***** ``` [Try it online!](http://charcoal.tryitonline.net/#code=77yn4oaY4oaQ4oaX77yuKg&input=NQ) [Answer] ## Python 2, 57 bytes ``` N=n=input() exec"print('*'*max(n,2-n)).center(N);n-=2;"*n ``` A full program. Goes line by line, printing the right number of asterisks centered. A recursive function was longer (67 bytes): ``` f=lambda n,p='':p+n*'*'+'\n'+(1%n*' 'and f(n-2,p+' ')+p+n*'*'+'\n') ``` or ``` f=lambda n,p='':1/n*(p+'*\n')or f(n-2,p+' ').join([p+n*'*'+'\n']*2) ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 12 bytes ``` Àé*hòl3Äjxx> ``` [Try it online!](http://v.tryitonline.net/#code=w4DDqSpow7JsM8OEanh4Pg&input=&args=NQ) I like challenges like this because I get to show off the advantages of V's 2D nature. Explanation. First, we need to create a string of *n* asterisks. So, we do this: ``` À " Arg1 times: é " Insert the following single character: * " '*' ``` As a side note, this is directly equivalent to `@ai*<esc>` in vim, and register `@a` is pre-initialized to "arg1". This makes numeric input much more convenient. Then, we move on character to the right with `h`. Here is the fun part: ``` ò " Until an error is thrown: l " Move one character to the right. This will throw an error on anyline with only one asterisk in it 3Ä " Make 3 copies of this line j " Move down one line xx " Delete two characters > " Indent this line once. ``` Now technically, this last part is ``` òl3Äjxx>>ò ``` Because the indent command is actually `>>`. V conveniently assumes incomplete commands apply to the current line, and also implicitly fills in the second `ò` character for looping. [Answer] # C++ Metatemplates, 186 bytes With the explicit formula from [my C answer](https://codegolf.stackexchange.com/a/97401/53667) the Metatemplates are competing! ``` template<int N,int X=N*N+N-1>struct H{enum{I=X/(N+1)-N/2,J=X%(N+1)-N/2-1};S s{(J==-N/2-1?'\n':((I>=J&I>=-J)|(I<=J&I<=-J)?'*':' '))+H<N,X-1>().s};};template<int N>struct H<N,-1>{S s="";}; ``` Ungolfed: ``` using S=std::string; template <int N, int X=N*N+N-1> struct H{ enum{I=X/(N+1)-N/2,J=X%(N+1)-N/2-1}; S s{(J==-N/2-1 ? '\n' : ( (I>=J&I>=-J)|(I<=J&I<=-J) ?'*':' '))+H<N,X-1>().s}; }; template <int N> struct H<N,-1> {S s="";}; ``` usage: ``` std::cout << H<5>().s; ``` ### non-competing Just for the sake of fun: ``` //T: Tuple of chars template <char C, char...Tail> struct T { S r=S(1,C)+T<Tail...>().r; }; //specialization for single char template <char C> struct T<C> { S r=S(1,C); }; //M: Repeated char template <int N, char C> struct M { S r=S(N,C); }; //U: concatenates T and M template <class Head, class...Tail> struct U { S r=Head().r+U<Tail...>().r; }; //specialization for Tail=M template <int N, char C> struct U<M<N,C>> { S r{M<N,C>().r}; }; //specialization for Tail=T template <char...C> struct U<T<C...>> { S r=T<C...>().r; }; //finally the Hourglass template <int N, int I=0> struct H { S s=U< M<I,' '>, M<N,'*'>, T<'\n'> >().r; S r{s + H<N-2,I+1>().r + s}; }; //specialization for recursion end template <int I> struct H<1,I> { S r=U< M<I,' '>, T<'*','\n'> >().r; }; ``` Usage: ``` std::cout << H<5>().r; ``` [Answer] ## PowerShell v2+, 54 bytes ``` param($n)$n..1+2..$n|?{$_%2}|%{" "*(($n-$_)/2)+"*"*$_} ``` Takes input `$n` (guaranteed to be an odd integer), constructs two ranges with `$n..1` and `2..$n` and concatenates them together, then uses `Where-Object` to select only the odd ones with `|?{$_%2}`. Those are fed into a loop. Each iteration, we construct the appropriate number of spaces, string-concatenated with the appropriate number of asterisks. Those strings are left on the pipeline, and output via implicit `Write-Output` inserts newlines between them at program completion. ### Examples ``` PS C:\Tools\Scripts\golfing> 3,5,7|%{.\draw-an-hourglass.ps1 $_;""} *** * *** ***** *** * *** ***** ******* ***** *** * *** ***** ******* ``` [Answer] # Python, 78 bytes So only with indentation: ``` f=lambda n,i=0:n>1and' '*i+'*'*n+'\n'+f(n-2,i+1)+' '*i+'*'*n+'\n'or' '*i+'*\n' ``` Usage: ``` print f(5) ``` [Answer] # C, ~~114~~ 109 bytes ``` i,j;k(n){for(i=-n/2;i<=n/2;++i)for(j=-n/2;j<=n/2+1;++j)putchar(j==n/2+1?10:(i>=j&i>=-j)|(i<=j&i<=-j)?42:32);} ``` ungolfed: ``` i,j; k(n){ for(i=-n/2;i<=n/2;++i) for(j=-n/2;j<=n/2+1;++j) putchar(j==n/2+1?10:(i>=j&i>=-j)|(i<=j&i<=-j)?42:32); } ``` Previous recursive solution: ``` p(a,c){while(a--)putchar(c);} f(n,i){p(i,32);p(n,42);p(1,10);} g(n,i){if(n>1)f(n,i),g(n-2,i+1);f(n,i);} h(n){g(n,0);} ``` [Answer] # JavaScript (ES6), 66 bytes ``` f=(n,s="*".repeat(n))=>n>1?s+` `+f(n-2).replace(/^/gm," ")+` `+s:s ``` The idea here is to generate each hourglass from the previous: add a space at the beginning of every line, and both prepend and append `n` asterisks. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~21~~ ~~20~~ ~~19~~ 17 bytes Saved 2 bytes thanks to *carusocomputing* ``` ;ƒ'*¹N·-×Nð×ì})û» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=O8aSJyrCuU7Cty3Dl07DsMOXw6x9KcO7wrs&input=OQ) **Explanation** ``` ;ƒ # for N in [0 ... floor(input/2)+1] '* # push an asterisk ¹N·-× # repeat the asterisk input-N*2 times Nð×ì # prepend N spaces } # end loop ) # wrap stack in a list û # palendromize » # join with newlines ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 12 bytes ``` Q2/Zv&<~42*c ``` [Try it online!](http://matl.tryitonline.net/#code=UTIvWnYmPH40Mipj&input=NQ) ### Explanation This makes use of the [recently added](https://github.com/lmendo/MATL/releases/tag/19.3.0) *symmetric range* function. ``` Q % Input n implicitly. Add 1 % STACK: 6 2/ % Divide by 2 % STACK: 3 Zv % Symmetric range % STACK: [1 2 3 2 1] &<~ % Matrix of all pairwise "greater than or or equal to" comparisons % STACK: [1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1] 42* % Multiply by 42 (ASCII code of '*') % STACK: [42 42 42 42 42 0 42 42 42 0 0 0 42 0 0 0 42 42 42 0 42 42 42 42 42] c % Convert to char. Implicitly display, with char 0 shown as space % STACK: ['*****' ' *** ' ' * ' ' *** ' '*****'] ``` [Answer] # PHP, 95 bytes ``` for($c=str_pad,$m=$n=$argv[1];$n<=$m;$n+=$d=$d>0||$n<2?2:-2)echo$c($c('',$n,'*'),$m,' ',2)." "; ``` Instead of storing the rows in an array and then outputting everything, the for loop goes down until 1, and then goes back up to the original number. [Answer] # C++11, 93 bytes ``` #include<string> using S=std::string;S f(int n,int i=0){S s=S(i,32)+S(n,42)+'\n';return n>1?s+f(n-2,i+1)+s:s;} ``` Slightly ungolfed: ``` std::string f(int n,int i=0){ auto s=std::string(i,' ') + std::string(n,'*') + '\n'; return n>1 ? s+f(n-2,i+1)+s : s; } ``` Usage: ``` std::cout << f(5); ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 20 bytes ``` XyY>t1X!*t2X!+ZS42*c ``` [Try it online!](http://matl.tryitonline.net/#code=WHlZPnQxWCEqdDJYIStaUzQyKmM&input=NQ) [Answer] # C, 79 bytes ``` h(m,n,k){for(n=m++,k=n*m;--k;putchar(k%m?abs(k%m-m/2)>abs(k/m-n/2)?32:42:10));} ``` It splits the countdown variable `k` into row and column indices. If the column index is 0 (last char in a row), it outputs a newline character (10). Then it adjusts the row and column indices to be around the center asterisk. Then, `abs(x) < abs(y)` is a short condition for outputting a space. [Answer] # R, 77 bytes ``` M=matrix(" ",n<-scan(),n);for(i in 1:n)M[i:(n-i+1),i]="*";cat(M,sep="",fill=n) ``` Creates a character matrix, which it then prints out via `cat`, with `fill=n` making sure the lines align properly. Note that elements are stored in a matrix column-first (i.e the first two elements are `M[1,1]` and `M[2,1]`, not `M[1,2]`.) [Answer] # Java 7, ~~170 165~~ 164 bytes *Thanks to @Hypino for saving 5 bytes.* *Thanks to Kevin for saving 1 byte.* ``` String c(int n,int x){String s,c,t=c=s=" ";int i=0;for(;i++<n;s+="*");for(i=x;i-->=0;c+=" ");for(i=x;i-->0;t+=" ");return(n=n-2)>=0?s+"\n"+c+c(n,++x)+"\n"+t+s:"*";} ``` [Answer] ## PHP - 95 bytes ``` $c=2;for($i=$a=$argv[1];$i<=$a;$i-=$c*=$i<2?-1:1)echo str_pad(str_repeat("*",$i),$a," ",2)." "; ``` Saved a byte by using an actual new line instead of an `"\r"` [Answer] # APL, 19 bytes ``` ' *'[1+∘.≤⍨(⊢⌊⌽)⍳⎕] ``` Test: ``` ' *'[1+∘.≤⍨(⊢⌊⌽)⍳⎕] ⎕: 5 ***** *** * *** ***** ``` Explanation: ``` ⎕ ⍝ read number ⍳ ⍝ 1..N ( ⌊ ) ⍝ at each position, minimum of ⊢ ⍝ 1..N ⌽ ⍝ and N..1 (this gives 1..N/2..1) ∘.≤⍨ ⍝ outer product with ≤ 1+ ⍝ add 1 to each value ' *'[ ] ⍝ 1→space, 2→asterisk ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 7 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ⇵{*×]⤢┼ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMUY1JXVGRjVCKiVENyV1RkYzRCV1MjkyMiV1MjUzQw__,i=NQ__,v=0) Explanation: ``` ⇵{*×]⤢┼ ⇵ ceiling divide by 2 { ] map over [1..pop] * push * × repeat by the counter ⤢ transpose ┼ quad-palindromize with 1 overlap ``` [+1 byte](https://dzaima.github.io/Canvas/?u=JXUyMUY1JXVGRjVCKiVENyV1RkYzRCV1MjkyMiV1MjUzQyV1MjU2Qw__,i=Ng__,v=0) with support for even numbers [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~54~~ 50 bytes ``` filter f{if($_-1){'*'*$_;($_-2)|f|%{" $_"}}'*'*$_} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py0zpyS1SCGtOjNNQyVe11CzWl1LXUsl3hrEM9KsSatRrVZSUIlXqq2FSNT@N9Yx1TEHCnMpAIFKfE0amKGuzlX7HwA "PowerShell – Try It Online") [Answer] # [PHP](https://php.net/), ~~104~~ 88 bytes ``` for(;$i++<$argn;$a.='**',$i++>1?$o=$s.$o:1)$o.=$s=str_pad("*$a",$argn,' ',2)." ";echo$o; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoKCSWJSeZ5uWnlpSrBEc4uLpp2n9Py2/SMNaJVNb2wYsa62SqGerrqWlrgMSszO0V8m3VSnWU8m3MtRUydcDsm2LS4riCxJTNJS0VBKVdMC6dNQV1HWMNPWUuJSsU5Mz8lXyrf//NwcA "PHP – Try It Online") ~~This doesn't beat the lowest scores for PHP on this challenge, but it's just too crazy for me to throw away.~~ Okay, so I've golfed now it to be the (not for long) lowest score for PHP on this challenge, but it doesn't change the fact that it's still crazy. ``` $ echo 7|php -nF hour.php ******* ***** *** * *** ***** ******* ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 90 bytes ``` +? Fx,`i,j:i,-1,*" ",o,`j,x-,+1,+j,-1,*"a",O x-1 Fx,`i,+1,j:i,x-,+1,*" ",o,`j,*2,-1,*"a",O ``` [Try it online!](https://tio.run/##S0xJKSj4/1/bnsutQichUyfLKlNH11BHS0lBSSdfJyFLp0JXR9tQRzsLIpqopOPPVaFrCFUNlAFpgKhB6NEyQqj@//@/KQA "Add++ – Try It Online") Just two for loops. My first Add++ answer! [Answer] # [J](http://jsoftware.com/), ~~30~~ ~~28~~ ~~26~~ 25 bytes -2 bytes thanks to FrownyFrog! -3 bytes thanks to Jonah! ``` ' *'#~](],.(-+:))i.@-<.i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RW01JXrYjVidfQ0dLWtNDUz9Rx0bfQy9f5rcilwpSZn5CukKZhCGOrqMAFDw/8A "J – Try It Online") ## Previous version: ``` ' *'{~[:(>.|.)@(*|."1)]\@#&1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RW01Kvroq007PRq9DQdNLRq9JQMNWNjHJTVDP9rcilwpSZn5CukKZhCGOrqMAFDw/8A "J – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `C`, ~~14~~ ~~13~~ 11 bytes -2 thanks to @Lyxal ``` ½ʀƛd⁰ε×*;øm ``` Port of [Emigna's 05AB1E solution](https://codegolf.stackexchange.com/a/97414/80050). [Try it Online!](http://lyxal.pythonanywhere.com?flags=C&code=%C2%BD%CA%80%C6%9Bd%E2%81%B0%CE%B5%C3%97*%3B%C3%B8m&inputs=7&header=&footer=) ``` ½ʀƛd⁰ε×*;øm # Full program ƛ ; # Map each n ½ʀ # in range(0, input / 2 + 1): * # Repeat... × # the character `*`... d⁰ε # abs(2 * n - input) times øm # Palindromize # Implicit output (`C' flag): join the array on newlines and center each line ``` [Answer] # Pyth, 22 bytes ``` j+J.e+*dk*b\*_:1hQ2_PJ ``` A program that takes input of an integer on STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=j%2BJ.e%2B%2adk%2ab%5C%2a_%3A1hQ2_PJ&input=9&debug=0) **How it works** ``` j+J.e+*dk*b\*_:1hQ2_PJ Program. Input: Q :1hQ2 Range from 1 to Q+1 in steps of 2. Yields [1, 3, 5, ..., Q] _ Reverse .e Enumnerated map with b as elements and k as indices: *dk k spaces *b\* b asterisks + Concatenate the spaces and asterisks J Store in J PJ All of J except the last element _ Reverse + Concatenate J and its modified reverse j Join on newlines Implicitly print ``` [Answer] # C, ~~195~~ 191 Bytes Should golf down a bit smaller ``` x,y,i;f(n){for(i=0;i<n;i+=2,puts("")){for(y=n-i;y<n;y+=2,putchar(32));for(x=i;x++<n;putchar(42));}for(i=n-2;~i;i-=2,puts("")){for(y=n-i+2;y<n;y+=2,putchar(32));for(x=i-1;x++<n;putchar(42));}} ``` We can test it [here](http://ideone.com/cV2Oh1) on ideone [Answer] # Ruby, ~~55~~ 54 bytes ``` f=->n,s=0{puts a=' '*s+?**n;(f[n-2,s+1];puts a)if n>1} ``` [Answer] # Haskell, 84 bytes ``` f n|l<-div n 2,k<-[-l..l]=putStr$unlines[[" *"!!(fromEnum$abs x<=abs y)|x<-k]|y<-k] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~80~~ 74 bytes Thank ceilingcat for 6 bytes ``` -Du(x,k)=for(x=~n;x+=2,x<n;putchar(k)) i;j;f(n){u(i,10)u(j,i*i<j*j?32:42);} ``` [Try it online!](https://tio.run/##FcdBCoMwEADA7@xqBJP21DX04kfCQuzGGkUbCIg@3UjnNtwMzKUIBfIQcU8gSreYICippAtVeD/M62mQjjI5iYC7B63/vdh/3bCVpk@Q1YjWzytke0bKtTUqd5GW9OOPW2FEvAE) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` HŻżḂƇṚ$⁾ *xⱮŒḄY ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//SMW7xbzhuILGh@G5miTigb4gKnjisa7FkuG4hFn///8xNQ "Jelly – Try It Online") I'm surprised there wasn't a Jelly answer yet. Jelly is not good at strings. ## Explanation ``` HŻżḂƇṚ$⁾ *xⱮŒḄY Main monadic link H Halve: n/2 Ż Range from 0 to floor(n/2) ż Zip with $ ( Range from 1 to n Ƈ Filter by Ḃ parity [to get the odd numbers] Ṛ Reverse $ ) Ɱ For each pair of numbers x repeat ⁾ * the characters ' ' and '*' that many times ŒḄ Bounce (palindromize) Y Join with newlines ``` ]
[Question] [ ## Challenge Write a function which takes one parameter: an integer `t`. Your function has to stop your program for `t` seconds before continuing, similar to `time.sleep(t)` in Python and `WAIT t` in BBC BASIC. You must not use any built in waiting functions or any built in functions for executing code after a certain time, and your program must resume after `t` seconds. For testing your function, there is tolerance of 0.1 seconds more or less than the given `t` on your own machine: variances between computers are fine. If your answer is challenged by anyone, you must provide photographic (screenshotted) proof that your function works correctly for `t=1`, `t=5` and `t=25`. You may also provide the details of your computer so people can try to replicate it on their own machine. Your program should and will be run on a computer whose clock speed is 1.6 GHz or higher. ## Winning The shortest program wins. ## Bounty A bounty will go out to the shortest program which stops the program *without* using a loop checking how much time has elapsed. If you are in the running for this bounty, add a footnote saying that your answer is for the bounty. ## Leaderboard ``` /* Configuration */ var QUESTION_ID = 55293; // 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 = 30525; /* 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,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var patt = new RegExp(/[Bb]ounty/); var res = patt.test(body); var bountyyn = "no"; if (res) { bountyyn = "yes"; } var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, bounty: bountyyn }); }); 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) .replace("{{BOUNTY}}", a.bounty); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 400px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td><td>Bounty?</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>{{BOUNTY}}</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] # x86\_64 machine code, 10 bytes Hexdump of the code: ``` 48 69 c9 ca fc 59 38 e2 fe c3 ``` Source code (can be assembled by `ml64` of Visual Studio): ``` TITLE heh PUBLIC mywait _TEXT SEGMENT mywait PROC imul rcx, 945421514 myloop: loop myloop ret mywait ENDP _TEXT ENDS END ``` Performs an empty loop, starting from the specified value down to 0. I chose the multiplier 945421514 empirically by trial and error, until my test program output satisfactory results. Test program (waits 10 times for each of the durations 1, 5 and 25 seconds): ``` #include <stdio.h> #include <time.h> extern "C" void mywait(int); int main() { int durations[] = {1, 5, 25}; for (int duration: durations) { for (int i = 0; i < 10; ++i) { clock_t before = clock(); mywait(duration); clock_t after = clock(); printf("%f\n", (after - before) / (double)CLOCKS_PER_SEC); } } getchar(); // now take a screenshot } ``` The result: ``` 1.003000 1.000000 1.004000 1.006000 1.005000 0.998000 0.995000 1.000000 1.005000 1.004000 4.999000 5.003000 5.035000 5.010000 4.992000 5.003000 5.003000 5.019000 5.026000 4.989000 25.041000 24.993000 25.049000 24.988000 25.038000 24.948000 25.007000 25.014000 25.053000 25.021000 ``` I ran this program on a Windows computer that has nothing else to do. If it runs some applications, the waiting times are more erratic. The CPU speed is 3.9 GHz. It seems that this code is [barely good enough for current PC technology](https://en.wikipedia.org/wiki/Clock_rate#Historical_milestones_and_current_records) - if the clock frequency is about 8.8 GHz, the multiplier will not fit into a signed 32-bit int. --- P.S. As this answer doesn't check how much time has passed, it is a candidate for the bounty. [Answer] # Bash, ~~29~~ ~~25~~ ~~24~~ ~~23~~ 19 bytes ``` w()(ping -t$1 1.2) ``` Accuracy test (`time`) where `$1` = 1 second: ``` real 0m1.012s user 0m0.001s sys 0m0.002s ``` Thanks Dennis for shaving the byte count down to 19 from 23! **EDIT**: I've changed the IP to avoid `ping` on Linux pinging 0.0.0.0, which is the loopback device. --- ### How this works `ping` has a default timeout of 1 second, so, when contacting an IP address which does not exist, ping can't continue until either the time out has passed, or it has got a reply from the IP. `-t` tells `ping` to try `$1` number of times on this fake IP address, forcing `ping` to take `$1` seconds to complete the ping. --- **It's eligible for the bounty! No loop!** [Answer] ## Matlab, 33 bytes ``` function f(t) tic;while toc<t,end ``` Or you can also use this in Octave: [try it online](https://ideone.com/XxHpho) ## Matlab, 31 bytes As [suggested by @flawr](https://codegolf.stackexchange.com/questions/55293/stop-stand-there-where-you-are/55302?noredirect=1#comment134303_55302), it can be done with an anonymous function (it should be assigned a name in order to use it): ``` @(t)eval('tic;while toc<t,end') ``` Example: ``` >> f=@(t)eval('tic;while toc<t,end'); >> tic, f(2), toc Elapsed time is 2.000323 seconds. ``` [Answer] # Java, ~~63~~ 62 bytes ``` t->{for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);} ``` Nothing surprising - just grabs the number of nanoseconds since 1/1/1970 multiple times and checks if a second has passed. Saved 1 byte thanks to Ypnypn and aditsu. [Answer] # Batch, 27 Bytes ``` set /a c=%1+1 ping -n %c% 0 ``` A popular batch trick, since batch didn't have a sleep function. No loop, so bounty eligible [Answer] # Commodore 64 BASIC, 19 ~~16~~ bytes ``` 1000 FORI=1TO930*N:NEXT:RETURN ``` With a call `N=<number-of-secods>:GOSUB1000`. However, I cannot provide enough accuracy. Because C64 had about 1 MHz CPU speed, I remember it was good enough to make an empty `FOR`-`NEXT` loop 1000 times so that it was *about* 1 second. In fact there were two main versions of the machine: PAL 0.985 MHz and NTSC 1.023 MHz (all data from [C64 Wikipedia Page](https://en.wikipedia.org/wiki/Commodore_64)). As I had NTSC version, it was required to run loop about 930 times. Tests with the following program (`N` seconds, provided by user in `INPUT`): ``` 10 INPUT N 20 PRINT TI$ 30 GOSUB 1000 40 PRINT TI$ 50 END 1000 FOR I=1 TO 930*N:NEXT I:RETURN ``` where `TI$` is a system variable containing string (`hhmmss` format) with time elapsed from last reset (1 second accuracy, however also depending on CPU speed, so this is not quite relevant, because it's the same clock). [![enter image description here](https://i.stack.imgur.com/RBTI4.png)](https://i.stack.imgur.com/RBTI4.png) Screenshot made with online C64 emulator <http://codeazur.com.br/stuff/fc64_final/>. This program (line `1000` only) occupies ~~16~~ 19 bytes in memory, as tested with `PRINT FRE(0)+65535` both before typing the code (38908 bytes) and after (~~38893~~ 38889 bytes). `PRINT FRE(0)` returns free memory for BASIC program (it's a negative value and constant `65535` should be added, but in fact it does not matter). **Because this program does not test the time elapsed in a loop, it qualifies for a bounty.** [Answer] # JavaScript ES6, ~~50~~ ~~45~~ 40 bytes ``` n=>{for(g=Date.now,z=g();z+n*1e3>g(););} ``` this uses self-executing functions, not sure why `+new Date` isn't working. --- ## Usage I've tested this with Safari Nightly but it will also work on Firefox. Tested with: ``` ( n=>{for(g=Date.now,z=g();z+n*1e3>g(););} )(1); // 1 is the delay is seconds console.log( 'foo' ); ``` --- You can run it by either surrounding it with parenthesis: ``` ( n=>{for(g=Date.now,z=g();z+n*1e3>g(););} )(5) ``` Or by naming it: ``` const wait=n=>{for(g=Date.now,z=g();z+n*1e3>g(););} wait(5) ``` ## Explanation Here's the main logic behind the program: ``` function (n) { var start = Date.now(); // Save start time (ms) while ( // while is synchronous, it'll block the code execution until it has finished start + (n * 1000) // This is the end time (start + delay) > Date.now() // When the current time is 1 ms past the target end time, stop. resuming the code execution ); } ``` The version I'm using uses the same logic: ``` n=>{ // Function with argument n, { is required if the functions is not just an expression for( // For will also block code execution // This first part is used to define variables g=Date.now, // Add an alias for Date.now as "g" z=g() // get current time and store in z ; // Next part, condition z + n*1e3 // Target end time, ( start + delay (converted to seconds) ) 1e3 is 1000 but in big e notation ; // Is required for a valid for loop ); } ``` [Answer] # CJam, 15 ``` {e3es+{_es>}g;} ``` This is a block that can be executed or stored into a variable (thus becoming a named function). Dennis and Mr Consensus agree that counting only the block is acceptable :) **Explanation:** ``` e3 multiply the argument by 1000 (to get milliseconds) es get the current timestamp in milliseconds + add the values, obtaining the stopping time {…}g do…while _ duplicate the stopping time es> check if we reached that time yet (loop condition) ; discard the stopping time ``` [Try it online](http://cjam.aditsu.net/#code=5%0A%7Be3es%2B%7B_es%3E%7Dg%3B%7D%0A~%0A%22done%22) [Answer] # JavaScript, ~~68 54 51~~ 42 I think no screenshot is needed. But I suspect you could golf this even more... New version: I now finally managed to avoid `new` and using `Date` twice: ``` f=t=>{for(x=(d=Date.now)();d()<x+t*1e3;);} ``` Older versions: ``` f=t=>{for(x=new Date();(new Date()|0)<x|0+t*1e3;);} f=t=>{x=(new Date())|0;while((new Date()|0)<x+t*1e3);} f=t=>{x=new Date().getSeconds();while(new Date().getSeconds()<x+t);} ``` [Answer] # Julia, ~~33~~ 20 bytes ``` t->watch_file(".",t) ``` Only works in Julia v0.4 due to changes in the function signature of `watch_file`. Defines an anonymous function with a single parameter `t` that (ab)uses the timeout parameter in the `watch_file` function. This is a candidate for the bounty! Demonstration using the Julia REPL: ``` julia> f=t->watch_file(".",t) (anonymous function) julia> @elapsed f(1) 1.002134983 julia> @elapsed f(5) 5.006161965 julia> @elapsed f(25) 25.026096192 ``` Previous answer (33 bytes), also working in Julia stable ``` t->(b=time();while b+t>time()end) ``` [Answer] # PHP, ~~171~~ ~~177~~ ~~84~~ ~~79~~ ~~65~~ ~~64~~ 62 bytes ``` <?php function a($i){for($f=microtime,$e=$f(1)+$i;$f(1)<$e;);} ``` **Usage:** Call the function like so: `php -d error_reporting=0 -r "require 'script.php'; a(5);echo 'Hello, World!';"` Where 5 is the time in seconds the programm should wait before it echoes "Hello, World!". **Explanation:** At first the function gets the current time in milliseconds. Then the function does a loop until the current Time is smaller then the first time + the input. Afterwards "Hello World!" gets echo'ed. **Log:** [Answer] # Windows CMD, 22 bytes ``` ping -w 1000 -n %1 1.1 ``` This uses no loop (label and goto) so this qualifies for the bounty It sends `t` pings to to 1.0.0.1 (invalid) and waits for a responce for 1000 ms [Answer] # R, 48 bytes ``` f=function(t){a={g=Sys.time}();while(g()<a+t){}} ``` Demonstration: ``` t0 <- Sys.time();f(1); Sys.time() - t0 ## Time difference of 1.000272 secs t0 <- Sys.time();f(5); Sys.time() - t0 ## Time difference of 5.011189 secs t0 <- Sys.time();f(25); Sys.time() - t0 ## Time difference of 25.00848 secs ``` [Answer] # PHP, 39 bytes ``` function a($a){while($i++<.4583e8*$a);} ``` --- (Note that I can actually get this shorter if a full program is required by taking advantage of arguments passed on command line. Down to **35**) ``` <?php while($i++<.4583e8*$argv[1]); ``` --- Program used for testing: ``` <?php function a($a){while($i++<.4583e8*$a);} record(1); record(5); record(25); function record($t) { $time = microtime_float(); a($t); echo microtime_float() - $time."\n"; } function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } ``` Results: ``` JamesWebster:Documents jameswebster$ php A.php 1.0093479156494 4.9945771694183 24.971961975098 ``` [![enter image description here](https://i.stack.imgur.com/3oqJT.png)](https://i.stack.imgur.com/3oqJT.png) --- Though I qualify for the bounty, I'm hardly in the running with some of the other entries! [Answer] # TI-BASIC (84+SE), 21 bytes Input method: `T:prgmT`. This is the closest equivalent of a function in TI-BASIC. Program: ``` For(A,1,841Ans End ``` All accuracy is gained via trial-and-error; timing it with a stopwatch works for all of the given test cases to within a twentieth of a second. Device information: ``` RAM FREE 23312 ARC FREE 889802 TI-84 Plus Silver Edition 2.55MP PROD #: 0A-3-02-37 ID: 0A3DC-C3469-FFE8 ``` --- W00T eligible for a bounty! [Answer] # JavaScript ES6, 40 bytes ``` t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);} ``` Tested with the following: ``` elapsed=(f,t,b=(d=Date.now)())=>(f(t),console.log(d()-b+"ms elapsed")) // accepts func, delay STOP=t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);} elapsed(STOP,1) // prints 1000ms elapsed elapsed(STOP,5) // prints 5000ms elapsed elapsed(STOP,25) // prints 25000ms elapsed ``` [Answer] # Python, 57 bytes ``` import time b=time.time def y(i): x=b() while x+i>b():x ``` Call function `y()` [Answer] # PureBasic, 92 bytes ``` Procedure z(t) t=t*1e3+ElapsedMilliseconds() While t>ElapsedMilliseconds():Wend EndProcedure ``` It's the shortest I can think of. I suspect this will be the longest here as well... To test: ``` OpenConsole() i=Val(Input()) s=ElapsedMilliseconds() z(i) PrintN(Str(ElapsedMilliseconds()-s)) Input() ``` [Answer] # PowerShell, 75 bytes Long, descriptive procedure calls. Yay for clarity in a language. :) ``` function w{param($i);$n=(Get-Date).AddSeconds($i);while($n-gt(Get-Date)){}} ``` Called within a program with something like ``` Get-Date w(15) Get-Date ``` --- Alternatively, if we're allowed external programs to be called instead, we can get down to **59 Bytes** with the following: ``` $n=(Get-Date).AddSeconds($args[0]);while($n-lt(Get-Date)){} ``` This would be called within a program as follows (presuming the above to be saved as "wait-function.ps1" and saved in the same folder): ``` Get-Date & ((Split-Path $MyInvocation.InvocationName) + "\wait-function.ps1 15") Get-Date ``` What we save in writing the function/program is more than clobbered by the excess needed to actually execute it, though. Le sigh. [Answer] ## Python, 66 bytes Note, my implementation neither calls an inbuilt time function, nor using scheduling feature. ``` def S(t): try:__import__("Queue").Queue().get(1,t) except:pass ``` And yes, it is eligible for bounty. [Answer] # [Hassium](http://HassiumLang.com), 55 Bytes ``` func w(t){p=time().second;while((p+t)>time().second)0;} ``` Run and see expanded: <http://HassiumLang.com/Hassium/index.php?code=9f4e2bdb292b14b150fba63677a11a79> [Answer] # Pyth, 19 bytes Late entry but after finding `.d0` in the docs last night I decided to give it a go. ``` DCNK.d0W<-.d0KNJ1)) ``` Defines a function which loops until the time elapsed is `N` seconds. Try it [here](http://pyth.herokuapp.com/?code=DCNK.d0W<-.d0KNJ1%29%29"start"%2aCQ"end&input=5&debug=0). [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 13 bytes ``` °°°)*™+]³]™>: ``` ## Explained ``` °°°)*™+]³]™>: °°° # Push 3 tens to the stack. )* # Get the product of the entire stack, including the implicit input. This is the shortest way to multiply the input by 1000. ™+ # Add it to the current time in miliseconds. ] # Duplicate it to use as a (throwaway) conditional. ³ : # Create a function using the next 3 concepts, and while the top of the stack is truthy, execute it. ] # Duplicate the target time ™> # Is it larger than the current time? ``` The bounty specifically says "without using a loop checking how much time has **elapsed**", which this does not do. This sets a target time, and keeps checking if it's passed that target time, thus it's eligible for the bounty. [Try it online!](https://tio.run/##Kyooyk/P0zX6///QBhDU1HrUskg79tDmWCBtZ/X//39jAA "RProgN 2 – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 53 bytes ``` proc W t {while "\[clock mil]-[clock mil]<$t*1e3" {}} ``` [Try it online!](https://tio.run/##K0nO@f@/oCg/WSFcoUShujwjMydVQSkmOjknPzlbITczJ1YXiW2jUqJlmGqspFBdW/s/XMH4PwA "Tcl – Try It Online") # Explained Command `clock milliseconds` can be reduced to `clock mil`, with escaped 1st bracket, it'll be interpreted at each loop, and w/o just once. As it measures milliseconds, we need to multpily by 1000 or 1e3 which saves 1 Byte. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) + /u:System.Threading, 36 bytes ``` x=>new SemaphoreSlim(0).Wait(x*1000) ``` [Try it online!](https://tio.run/##Zc2xCsIwEADQvV@RMRFa4@BiTEFwFiEV5xCv9sAkJTlt/Xmj4uj8hudy7TKWnSOMYYuBWtYzXWbdBpiYAW/HISYwN/RciuZskfi8WEkpRVHVwyaW9d4SdOihOZE7xElVPV@LH8I/HtNn4VBnocorjt83l@V9Y56ZwDfdkMBeMFzf "C# (Visual C# Interactive Compiler) – Try It Online") Creates a semaphore with no capacity and tries to get it for the specified number of seconds. I realize I am "wait"ing on something here. To me this seems more like the ping/timeout solution as opposed to `Thread.Sleep`. The code tries to get a resource that it cannot get and stops trying after a limit. === Below is a variation that starts a `Task` with an infinite loop, then waits for it to complete with a timeout. All required namespaces are included by default, but the solution is a few bytes longer than the one above. # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 40 bytes ``` x=>Task.Run(()=>{for(;;);}).Wait(x*1000) ``` [Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2eTmVdip5CmYPu/wtYuJLE4Wy@oNE9DQ9PWrjotv0jD2lrTulZTLzwxs0SjQsvQwMBA8781V1likUKxrUtiSWpIZm6qXmhJsl9@uTVXmoapJkQyFVMyoAhok0aqbrGm9X8A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` kṡ+{:kṡ>| ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=k%E1%B9%A1%2B%7B%3Ak%E1%B9%A1%3E%7C&inputs=5&header=&footer=) For accuracy, use the offline interpreter, dowloadable via the link in the header. ``` kṡ # Push current epoch, in seconds + # Added to input { | # Until kṡ # Current epoch : > # Is greater than this { | # Loop ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žcžb60*+[Džcžb60*+αIQ# ``` [Try it online.](https://tio.run/##yy9OTMpM/f//6L7ko/uSzAy0tKNdEOxzGz0Dlf//NwUA) NOTE: Depending on how many microseconds in the current second have already passed, the tolerance might be slightly larger than 0.1 sec. But since almost halve the answers have similar issues, I figured it's allowed. **Explanation:** 05AB1E doesn't have any builtins for the current time. It does however have a builtin for the current year/month/day/hours/minutes/seconds/microseconds as separated builtins. Since only using seconds can potentially wrap around from 59 to 0 causing issues, I need both the minutes and seconds, making the code even longer than most answers in non-codegolfing languages unfortunately. ``` žc # Push the current seconds žb # Push the current minutes 60* # Multiply it by 60 + # Add them together [ # Start an infinite loop: D # Duplicate the initial (minutes*60 + seconds) from before the loop žcžb60*+ # Push the current (minutes*60 + seconds) again α # And take the absolute difference between the two IQ # And if this is equal to the input: # # Stop the infinite loop ``` [Answer] # SmileBASIC, 20 bytes ``` INPUT T DIALOG"",,,T ``` Opens a dialog box that closes automatically after `T` seconds. I'm not sure if this counts as a "built in waiting function", but I think this is just as valid as using `ping`. An alternative 37-byte program which definitely isn't cheating: ``` INPUT T FADE.,T*60WHILE FADECHK()WEND ``` Causes the screen fade color to change to 0 (alpha=0,red=0,green=0,blue=0) (no effect) gradually over `T` seconds, then waits for that animation to finish. [Answer] # QB64, 31 bytes Infinite loop until the time has elapsed ``` t=TIMER:DO:LOOP UNTIL t-TIMER>n ``` ]
[Question] [ # Problem Create a function that can determine whether or not an arbitrary DNA string is a Watson-Crick palindrome. The function will take a DNA string and output a true value if the string is a Watson-Crick palindrome and a false value if it is not. (True and False can also be represented as 1 and 0, respectively.) The DNA string may either be in all uppercase or all lowercase depending on your preference. Also, the DNA string will not be empty. # Explanation A DNA string is a Watson-Crick palindrome when the complement of its reverse is equal to itself. Given a DNA string, first reverse it, and then complement each character according to the DNA bases (A ↔ T and C ↔ G). If the original string is equal to the complemented-reverse string, it is a Watson-Crick palindrome. For more, see this [question](https://codegolf.stackexchange.com/questions/42184/longest-reverse-palindromic-dna-substring). It is a different challenge where you must find the longest substring of a DNA string where that substring is a Watson-Crick palindrome. # Goal This is code-golf and the shortest code wins. # Test Cases The format is `<input> = <output>`. ``` ATCGCGAT = true AGT = false GTGACGTCAC = true GCAGTGA = false GCGC = true AACTGCGTTTAC = false ACTG = false ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~10~~ 7 bytes ### Code: ``` Â'š×‡Q ``` ### Explanation: To check if a string is a palindrome, we just need to check the input with the input, with `at` swapped and `cg` swapped and then reverse it. So that is what we are going to do. We push the input and the input reversed using `Â` (bifurcate). Now comes a tricky part. `'š×` is the compressed version for `creating`. If we reverse it, you can see why it's in the code: ``` CreATinG | || | GniTAerC ``` This will be used to transliterate the reversed input. Transliteration is done with `‡`. After that, we just check if the input and the transliterated input are e`Q`ual and print that value. So this is how the stack looks like for input `actg` : ```  # ["actg", "gtca"] 'š× # ["actg", "gtca", "creating"]  # ["actg", "gtca", "creating", "gnitaerc"] ‡ # ["actg", "cagt"] Q # [0] ``` Which can also be seen with the debug flag ([Try it here](http://05ab1e.tryitonline.net/#code=w4InxaHDl8OC4oChUQ&input=Z3RnYWNndGNhYw&args=LWQ)). Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4InxaHDl8OC4oChUQ&input=Z3RnYWNndGNhYw). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O%8µ+U5ḍP ``` [Try it online!](http://jelly.tryitonline.net/#code=TyU4wrUrVTXhuI1Q&input=&args=QVRDR0NHQVQ) or [verify all test cases](http://jelly.tryitonline.net/#code=TyU4wrUrVTXhuI1QCsOH4oKs&input=&args=J0FUQ0dDR0FUJywgJ0FHVCcsICdHVEdBQ0dUQ0FDJywgJ0dDQUdUR0EnLCAnR0NHQycsICdBQUNUR0NHVFRUQUMnLCAnQUNURyc). ### How it works ``` O%8µ+U5ḍP Main link. Argument: S (string) O Compute the code points of all characters. %8 Compute the residues of division by 8. This maps 'ACGT' to [1, 3, 7, 4]. µ Begin a new, monadic link. Argument: A (array of residues) +U Add A and A reversed. 5ḍ Test the sums for divisibility by 5. Of the sums of all pairs of integers in [1, 3, 7, 4], only 1 + 4 = 5 and 3 + 7 = 10 are divisible by 5, thus identifying the proper pairings. P Take the product of the resulting Booleans. ``` [Answer] # Python 2, 56 45 44 bytes ``` lambda s:s==s[::-1].translate("_T_GA__C"*32) ``` [Answer] # Perl, 27 bytes Includes +2 for `-lp` Give input on STDIN, prints 1 or nothing: ``` dnapalin.pl <<< ATCGCGAT ``` `dnapalin.pl`: ``` #!/usr/bin/perl -lp $_=y/ATCG/TAGC/r=~reverse ``` Replace `$_=` by `$_+=` to get `0` instead of empty for the false case [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~34~~ 33 bytes ``` $ ;$_ T`ACGT`Ro`;.+ +`(.);\1 ; ^; ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAokCjskXwpUYEFDR1RgUm9gOy4rCitgKC4pO1wxCjsKXjs&input=R0NHQwpBVENHQ0dBVApHVEdBQ0dUQ0FDCkFHVApHQ0FHVEdBCkFDVEcKQUFDVEdDR1RUVEFD) (Slightly modified to run all test cases at once.) ### Explanation ``` $ ;$_ ``` Duplicate the input by matching the end of the string and inserting a `;` followed by the entire input. ``` T`ACGT`Ro`;.+ ``` Match only the second half of the input with `;.+` and perform the substitution of pairs with a transliteration. As for the target set `Ro`: `o` references the *other* set, that is `o` is replaced with `ACGT`. But `R` reverses this set, so the two sets are actually: ``` ACGT TGCA ``` If the input is a DNA palindrome, we will now have the input followed by its reverse (separated by `;`). ``` +`(.);\1 ; ``` Repeatedly (`+`) remove a pair of identical characters around the `;`. This will either continue until only the `;` is left or until the two characters around the `;` are no longer identical, which would mean that the strings aren't the reverse of each other. ``` ^; ``` Check whether the first character is `;` and print `0` or `1` accordingly. [Answer] # Pyth - 10 bytes ``` qQ_XQ"ACGT ``` [Try it online here](http://pyth.herokuapp.com/?code=qQ_XQ%22ACGT&test_suite=1&test_suite_input=%22ATCGCGAT%22%0A%22AGT%22%0A%22GTGACGTCAC%22%0A%22GCAGTGA%22%0A%22GCGC%22%0A%22AACTGCGTTTAC%22&debug=1). A 9 byte version: [Try it online here](http://pyth.herokuapp.com/?code=q_XQ%22ACGT&test_suite=1&test_suite_input=%22ATCGCGAT%22%0A%22AGT%22%0A%22GTGACGTCAC%22%0A%22GCAGTGA%22%0A%22GCGC%22%0A%22AACTGCGTTTAC%22&debug=1). [Answer] ## JavaScript (ES6), 59 bytes ``` f=s=>!s||/^(A.*T|C.*G|G.*C|T.*A)$/.test(s)&f(s.slice(1,-1)) ``` Best I could do without using Regexp was 62 bytes: ``` f=s=>!s||parseInt(s[0]+s.slice(-1),33)%32%7<1&f(s.slice(1,-1)) ``` [Answer] # Ruby, 35 I tried other ways, but the obvious way was the shortest: ``` ->s{s.tr('ACGT','TGCA').reverse==s} ``` **in test program** ``` f=->s{s.tr('ACGT','TGCA').reverse==s} puts f['ATCGCGAT'] puts f['AGT'] puts f['GTGACGTCAC'] puts f['GCAGTGA'] puts f['GCGC'] puts f['AACTGCGTTTAC'] ``` [Answer] ## Haskell, ~~48~~ 45 bytes ``` (==)=<<reverse.map((cycle"TCG_A"!!).fromEnum) ``` Usage example: `(==)=<<reverse.map((cycle"_T_GA__C"!!).fromEnum) $ "ATCGCGAT"`-> `True`. A non-pointfree version is ``` f x = reverse (map h x) == x -- map h to x, reverse and compare to x h c = cycle "TCG_A" !! fromEnum c -- take the ascii-value of c and take the -- char at this position of string -- "TCG_ATCG_ATCG_ATCG_A..." ``` Edit: @Mathias Dolidon saved 3 bytes. Thanks! [Answer] # Retina, 52 bytes ``` ^G(.*)C$ $1 ^A(.*)T$ $1 ^T(.*)A$ $1 }`^C(.*)G$ $1 ^$ ``` [Answer] # Julia, ~~47~~ 38 bytes ``` s->((x=map(Int,s)%8)+reverse(x))%5⊆0 ``` This is an anonymous function that accepts a `Char` array and returns a boolean. To call it, assign it to a variable. This uses Dennis' algorithm, which is shorter than the naïve solution. We get the remainder of each code point divided by 8, add that to itself reversed, get the remainders from division by 5, and check whether all are 0. The last step is accomplished using `⊆`, the infix version of `issubset`, which casts both arguments to `Set` before checking. This means that `[0,0,0]` is declared a subset of `0`, since `Set([0,0,0]) == Set(0)`. This is shorter than an explicit check against 0. [Try it online!](http://julia.tryitonline.net/#code=Zj1zLT4oKHg9bWFwKEludCxzKSU4KStyZXZlcnNlKHgpKSU14oqGMAoKZm9yIHRlc3QgaW4gKCJBVENHQ0dBVCIsICJBR1QiLCAiR1RHQUNHVENBQyIsICJHQ0FHVEdBIiwgIkdDR0MiLCAiQUFDVEdDR1RUVEFDIikKICAgIHByaW50bG4oZihbdGVzdC4uLl0pKQplbmQ&input=) Saved 9 bytes thanks to Dennis! [Answer] # Bash + coreutils, ~~43~~ 32 bytes ``` [ `tr ATCG TAGC<<<$1|rev` = $1 ] ``` ### Tests: ``` for i in ATCGCGAT AGT GTGACGTCAC GCAGTGA GCGC AACTGCGTTTAC; do ./78410.sh $i && echo $i = true || echo $i = false; done ATCGCGAT = true AGT = false GTGACGTCAC = true GCAGTGA = false GCGC = true AACTGCGTTTAC = false ``` [Answer] # Jolf, 15 Bytes [Try it!](http://conorobrien-foxx.github.io/Jolf/#code=PX5BX2nOsyJBR0NUIl_Os2k) ``` =~A_iγ"AGCT"_γi ``` Explanation: ``` _i Reverse the input ~A_iγ"AGCT"_γ DNA swap the reversed input =~A_iγ"AGCT"_γi Check if the new string is the same as the original input ``` [Answer] # Jolf, 16 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=cGUraX5Bac6zIkdBVEMiX86z) ``` pe+i~Aiγ"GATC"_γ ``` ## Explanation ``` pe+i~Aiγ"GATC"_γ ~Aiγ"GATC"_γ perform DNA transformation +i i + (^) pe is a palindrome ``` [Answer] ## Actually, 19 bytes ``` O`8@%`M;RZ`5@Σ%Y`Mπ ``` This uses [Dennis's algorithm](https://codegolf.stackexchange.com/a/78413/45941). [Try it online!](http://actually.tryitonline.net/#code=T2A4QCVgTTtSWmA1QM6jJVlgTc-A&input=J0FUQ0dDR0FUJw) Explanation: ``` O`8@%`M;RZ`5@Σ%Y`Mπ O push an array containing the Unicode code points of the input `8@%`M modulo each code point by 8 ;RZ zip with reverse `5@Σ%Y`M test sum for divisibility by 5 π product ``` [Answer] # Oracle SQL 11.2, 68 bytes ``` SELECT DECODE(TRANSLATE(REVERSE(:1),'ATCG','TAGC'),:1,1,0)FROM DUAL; ``` [Answer] # R, 101 bytes ``` g=function(x){y=unlist(strsplit(x,""));all(sapply(rev(y),switch,"C"="G","G"="C","A"="T","T"="A")==y)} ``` ### Test Cases ``` g("ATCGCGAT") [1] TRUE g("AGT") [1] FALSE g("GTGACGTCAC") [1] TRUE g("GCAGTGA") [1] FALSE g("GCGC") [1] TRUE g("AACTGCGTTTAC") [1] FALSE g("ACTG") [1] FALSE ``` [Answer] # Julia 0.4, 22 bytes ``` s->s$reverse(s)⊆"" ``` The string contains the control characters EOT (4) and NAK (21). Input must be in form of a character array. This approach XORs the characters of the input with the corresponding characters in the reversed input. For valid pairings, this results in the characters EOT or NAK. Testing for inclusion in the string of those characters produces the desired Boolean. [Try it online!](http://julia.tryitonline.net/#code=ZiA9IHMtPnMkcmV2ZXJzZShzKeKKhiIEFSIKCmZvciBzIGluICgiQVRDR0NHQVQiLCAiQUdUIiwgIkdUR0FDR1RDQUMiLCAiR0NBR1RHQSIsICJHQ0dDIiwgIkFBQ1RHQ0dUVFRBQyIsICJBQ1RHIikKICAgIHByaW50bG4oZihbcy4uLl0pKQplbmQ&input=) [Answer] # C,71 ``` r,e;f(char*s){for(r=0,e=strlen(s)+1;*s;s++)r|=*s*s[e-=2]%5^2;return!r;} ``` 2 bytes saved by Dennis. Additional 2 bytes saved by adapting for lowercase input: constants `37` and `21` are revised to `5` and `2`. # C,75 ``` i,j;f(char*s){for(i=j=0;s[i];i++)j|=s[i]*s[strlen(s)-i-1]%37!=21;return!j;} ``` Saved one byte: Eliminated parenthesis by taking the product of the two ASCII codes mod 37. The valid pairs evaluate to 21. Assumes uppercase input. # C,76 ``` i,j;f(char*s){for(i=j=0;s[i];i++)j|=(s[i]+s[strlen(s)-i-1])%11!=6;return!j;} ``` Uses the fact that ASCII codes of the valid pairs sum to 138 or 149. When taken mod 11, these are the only pairs that sum to 6. Assumes uppercase input. **ungolfed in test program** ``` i,j; f(char *s){ for(i=j=0;s[i];i++) //initialize i and j to 0; iterate i through the string j|=(s[i]+s[strlen(s)-i-1])%11!=6; //add characters at i from each end of string, take result mod 11. If not 6, set j to 1 return!j;} //return not j (true if mismatch NOT detected.) main(){ printf("%d\n", f("ATCGCGAT")); printf("%d\n", f("AGT")); printf("%d\n", f("GTGACGTCAC")); printf("%d\n", f("GCAGTGA")); printf("%d\n", f("GCGC")); printf("%d\n", f("AACTGCGTTTAC")); } ``` [Answer] # [Factor](http://factorcode.org), 72 bytes Unfortunately regex can't help me here. ``` [ dup reverse [ { { 67 71 } { 65 84 } { 71 67 } { 84 65 } } at ] map = ] ``` Reverse, lookup table, compare equal. [Answer] # J - 21 bytes ``` 0=[:+/5|[:(+|.)8|3&u: ``` Based on Dennis' method ## Usage ``` f =: 0=[:+/5|[:(+|.)8|3&u: f 'ATCGCGAT' 1 f 'AGT' 0 f 'GTGACGTCAC' 1 f 'GCAGTGA' 0 f 'GCGC' 1 f 'AACTGCGTTTAC' 0 f 'ACTG' 0 ``` ## Explanation ``` 0=[:+/5|[:(+|.)8|3&u: 3&u: - Convert from char to int 8| - Residues from division by 8 for each |. - Reverse the list + - Add from the list and its reverse element-wise [: - Cap, compose function 5| - Residues from division by 5 for each +/ - Fold right using addition to create a sum [: - Cap, compose function 0= - Test the sum for equality to zero ``` [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 42 bytes ``` _8 ,% ; "}{{+_5 "= %_! = """{ ;"{" )! ``` Terminates with a division-by-zero error (error message on STDERR). [Try it online!](http://labyrinth.tryitonline.net/#code=XzgKLCUKOwoifXt7K181CiI9ICAgICVfIQogPSAiIiJ7CiA7InsiICkh&input=R1RHQUNHVENBQw) The layout feels really inefficient but I'm just not seeing a way to golf it right now. ### Explanation This solution is based on Dennis's arithmetic trick: take all character codes modulo `8`, add a pair from both ends and make sure it's divisible by `5`. Labyrinth primer: * Labyrinth has two stacks of arbitrary-precision integers, *main* and *aux*(iliary), which are initially filled with an (implicit) infinite amount of zeros. * The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends. * Digits are processed by multiplying the top of the main stack by 10 and then adding the digit. The code starts with a small 2x2, clockwise loop, which reads all input modulo 8: ``` _ Push a 0. 8 Turn into 8. % Modulo. The last three commands do nothing on the first iteration and will take the last character code modulo 8 on further iterations. , Read a character from STDIN or -1 at EOF. At EOF we will leave loop. ``` Now `;` discards the `-1`. We enter another clockwise loop which moves the top of the main stack (i.e. the last character) down to the bottom: ``` " No-op, does nothing. } Move top of the stack over to aux. If it was at the bottom of the stack this will expose a zero underneath and we leave the loop. = Swap top of main with top of aux. The effect of the last two commands together is to move the second-to-top stack element from main to aux. " No-op. ``` Now there's a short linear bit: ``` {{ Pull two characters from aux to main, i.e. the first and last (remaining) characters of the input (mod 8). + Add them. _5 Push 5. % Modulo. ``` The IP is now at a junction which acts as a branch to test divisibility by 5. If the result of the modulo is non-zero, we know that the input is not a Watson-Crick palindrome and we turn east: ``` _ Push 0. ! Print it. The IP hits a dead end and turns around. _ Push 0. % Try to take modulo, but division by zero fails and the program terminates. ``` Otherwise, we need to keep checking the rest of the input, so the IP keeps going south. The `{` pulls over the bottom of the remaining input. If we've exhausted the input, then this will be a `0` (from the bottom of *aux*), and the IP continues moving south: ``` ) Increment 0 to 1. ! Print it. The IP hits a dead end and turns around. ) Increment 0 to 1. { Pull a zero over from aux, IP keeps moving north. % Try to take modulo, but division by zero fails and the program terminates. ``` Otherwise, there are more characters in the string to be checked. The IP turns west and moves into the next (clockwise) 2x2 loop which consists largely of no-ops: ``` " No-op. " No-op. { Pull one value over from aux. If it's the bottom of aux, this will be zero and the IP will leave the loop eastward. " No-op. ``` After this loop, we've got the input on the main stack again, except for its first and last character and with a zero on top. The `;` discards the `0` and then `=` swaps the tops of the stacks, but this is just to cancel the first `=` in the loop, because we're now entering the loop in a different location. Rinse and repeat. [Answer] # sed, ~~67~~ 61 bytes ``` G;H;:1;s/\(.\)\(.*\n\)/\2\1/;t1;y/ACGT/TGCA/;G;s/^\(.*\)\1$/1/;t;c0 ``` (67 bytes) ### Test ``` for line in ATCGCGAT AGT GTGACGTCAC GCAGTGA GCGC AACTGCGTTTAC ACTG do echo -n "$line " sed 'G;H;:1;s/\(.\)\(.*\n\)/\2\1/;t1;y/ACGT/TGCA/;G;s/^\(.*\)\1$/1/;t;c0' <<<"$line" done ``` ### Output ``` ATCGCGAT 1 AGT 0 GTGACGTCAC 1 GCAGTGA 0 GCGC 1 AACTGCGTTTAC 0 ACTG 0 ``` --- By using extended regular expressions, the byte count can be reduced to 61. ``` sed -r 'G;H;:1;s/(.)(.*\n)/\2\1/;t1;y/ACGT/TGCA/;G;s/^(.*)\1$/1/;t;c0' ``` [Answer] # C#, 65 bytes ``` bool F(string s)=>s.SequenceEqual(s.Reverse().Select(x=>"GACT"[("GACT".IndexOf(x)+2)%4])); ``` .NET has some fairly long framework method names at times, which doesn't necessarily make for the best code golf framework. In this case, framework method names make up 33 characters out of 90. :) Based on the modulus trick from elsewhere in the thread: ``` bool F(string s)=>s.Zip(s.Reverse(),(a,b)=>a%8+b%8).All(x=>x%5==0); ``` Now weighs in at 67 characters whereof 13 are method names. Another minor optimization to shave off a whopping 2 characters: ``` bool F(string s)=>s.Zip(s.Reverse(),(a,b)=>(a%8+b%8)%5).Sum()<1; ``` So, 65 of which 13 are framework names. Edit: Omitting some of the limited "boilerplate" from the solution and adding a couple of conditions leaves us with the expression ``` s.Zip(s.Reverse(),(a,b)=>(a%8+b%8)%5).Sum() ``` Which gives 0 if and only if the string s is a valid answer. As cat points out, "bool F(string s)=>" is actually replacable with "s=>" *if* it's otherwise clear in the code that the expression is a `Func<string,bool>`, ie. maps a string to a boolean. [Answer] **REXX** 37 ``` s='ATCGCGAT';say s=translate(reverse(s),'ATCG','TAGC') ``` [Answer] # Octave, 52 bytes ``` f=@(s) prod(mod((i=mod(toascii(s),8))+flip(i),5)==0) ``` Following Denis's trick ... take the ASCII values mod 8, flip and add together; if every sum is a multiple of five, you're golden. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~17~~ ~~11~~ ~~10~~ 8 bytes ``` Ṙ«Wṁ«ḂĿ= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmYwqtX4bmBwqvhuILEvz0iLCIiLCJhdGNnY2dhdFxuYWd0XG5hYWN0Z2NndHR0YWMiXQ=) ### Explained ``` Ṙ«Wṁ«ḂĿ= Ṙ # Input reverse «Wṁ«ḂĿ # Changes DNA and translate with string compression = # If original input is equal to the result output 1/0 ``` [Answer] # Clojure/ClojureScript, 49 chars ``` #(=(list* %)(map(zipmap"ATCG""TAGC")(reverse %))) ``` Works on strings. If the requirements are loosened to allow lists, I can take off the `(list* )` and save 7 chars. [Answer] # R, 70 bytes ``` f=function(x)all(chartr("GCTA","CGAT",y<-strsplit(x,"")[[1]])==rev(y)) ``` Usage: ``` > f=function(x)all(chartr("GCTA","CGAT",y<-strsplit(x,"")[[1]])==rev(y)) > f("GTGACGTCAC") [1] TRUE > f("AACTGCGTTTAC") [1] FALSE > f("AGT") [1] FALSE > f("ATCGCGAT") [1] TRUE ``` [Answer] # C, 71 bytes Requires ASCII codes for the relevant characters, but accepts uppercase, lowercase or mixed-case input. ``` f(char*s){char*p=s+strlen(s),b=0;for(;*s;b&=6)b|=*--p^*s++^4;return!b;} ``` This code maintains two pointers, `s` and `p`, traversing the string in opposite directions. At each step, we compare the corresponding characters, setting `b` true if they don't match. The matching is based on XOR of the character values: ``` 'A' ^ 'T' = 10101 'C' ^ 'G' = 00100 'C' ^ 'T' = 10111 'G' ^ 'A' = 00110 'A' ^ 'C' = 00010 'T' ^ 'G' = 10011 x ^ x = 00000 ``` We can see in the above table that we want to record success for `xx10x` and failure for anything else, so we XOR with `00100` (four) and mask with `00110` (six) to get zero for `AT` or `CG` and non-zero otherwise. Finally, we return true if all the pairs accumulated a zero result in `b`, false otherwise. ## Test program: ``` #include <stdio.h> int main(int argc, char **argv) { while (*++argv) printf("%s = %s\n", *argv, f(*argv)?"true":"false"); } ``` ]
[Question] [ In the game [Yahtzee](https://en.wikipedia.org/wiki/Yahtzee), players roll five six-sided dice, and attempt to create certain hands to score points. One such hand is a *small straight*: four consecutive numbers, not necessarily in order. The three possible small straights are `1, 2, 3, 4`, `2, 3, 4, 5`, and `3, 4, 5, 6`. For example, `[3, 5, 6, 1, 4]` contains the small straight `[3, 4, 5, 6]`. ### Input An unsorted list of five integers, each between 1 and 6 inclusive, representing a Yahtzee hand. ### Output A truthy value if the hand contains a small straight and a falsy value otherwise. ### Test cases Truthy: ``` [[1, 2, 3, 3, 4], [1, 2, 3, 4, 5], [3, 5, 6, 1, 4], [1, 5, 3, 4, 6], [4, 5, 2, 3, 5], [1, 4, 3, 2, 2], [5, 4, 3, 6, 3], [5, 3, 5, 4, 6], [2, 4, 5, 1, 3], [3, 6, 4, 5, 3], [5, 6, 4, 3, 5], [4, 5, 3, 6, 3], [4, 5, 5, 3, 2], [4, 5, 2, 3, 5], [4, 6, 5, 3, 6], [4, 2, 3, 1, 5], [3, 6, 4, 6, 5], [5, 2, 1, 3, 4], [4, 4, 1, 2, 3], [4, 1, 4, 2, 3], [5, 1, 4, 3, 6], [5, 2, 2, 3, 4], [4, 4, 6, 5, 3], [2, 4, 3, 5, 1], [5, 4, 2, 5, 3], [2, 3, 5, 5, 4], [1, 6, 3, 4, 5], [4, 5, 3, 3, 6], [6, 4, 3, 6, 5], [4, 6, 6, 5, 3], [4, 3, 5, 2, 2], [2, 3, 2, 1, 4], [4, 2, 6, 1, 3], [4, 4, 5, 3, 6], [4, 5, 6, 3, 6]] ``` Falsy: ``` [[1, 2, 3, 5, 6], [5, 1, 1, 6, 6], [4, 6, 4, 1, 1], [6, 4, 1, 6, 4], [4, 6, 3, 6, 6], [2, 1, 4, 6, 4], [2, 6, 1, 5, 6], [2, 6, 1, 5, 6], [3, 6, 5, 3, 2], [3, 2, 3, 5, 3], [5, 5, 6, 2, 3], [3, 4, 6, 4, 3], [1, 4, 5, 5, 1], [1, 4, 4, 4, 1], [1, 6, 5, 1, 4], [6, 6, 4, 5, 4], [5, 3, 3, 3, 2], [5, 2, 1, 5, 3], [3, 5, 1, 6, 2], [6, 4, 2, 1, 2], [1, 3, 1, 3, 2], [3, 1, 3, 4, 3], [4, 3, 1, 6, 3], [4, 6, 3, 3, 6], [3, 6, 3, 6, 4], [1, 1, 3, 1, 3], [5, 5, 1, 3, 2], [3, 4, 2, 6, 6], [5, 4, 2, 6, 1], [2, 4, 4, 5, 4], [3, 6, 2, 5, 5], [2, 5, 3, 5, 1], [3, 2, 2, 3, 4], [5, 2, 2, 6, 2], [5, 6, 2, 5, 6]] ``` Inspired by [this](http://tibasicdev.wikidot.com/forum/t-124256/comparing-lists) ## Catalogue ``` var QUESTION_ID=74997;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=30525;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.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)}} ``` ``` 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: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="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] # [MATL](https://esolangs.org/wiki/MATL), ~~7~~ ~~12~~ ~~11~~ ~~9~~ ~~8~~ 6 bytes *Thanks a lot to @lirtosiast for removing 2 bytes* ``` ud7BXf ``` Truthy is an array of nonzero values. Falsy is empty array (no output displayed). *As of release 16.2.0, `u` is stable by default. So the code needs an extra `S` to sort the output: `uSd7BXf` (**7 bytes**). The link includes this modification.* [**Try it online!**](http://matl.tryitonline.net/#code=dVNkN0JYZg&input=WzUsIDQsIDMsIDYsIDNd) ``` u % input array implicitly. Transform into array of unique elements sorted d % array of differences between consecutive elements 7B % push arrray [1 1 1] (number 7 converted to binary) Xf % indices of occurrences of the second array within the first ``` [Answer] ## Python, 44 bytes ``` lambda l:any({i+1,i+2,i+3}<set(l)for i in l) ``` Back after 9 months with an improvement. We don't need to check if `i` is in the set with Zgarb's idea of checking only start values in the set. We can now also use `<` for strict subsets because `i` must also be included. --- **47 bytes:** ``` lambda l:any({i,i+1,i+2,i+3}<=set(l)for i in l) ``` Checks if any die rolls is the start of a small straight set. Thanks to Zgarb for the idea of only checking start values in the list, saving 5 bytes. Python 3.5 has shorter set conversion, for 45 bytes ``` lambda l:any({i,i+1,i+2,i+3}<={*l}for i in l) ``` It's the same length to do `{*range(i,i+4)}` as `{i,i+1,i+2,i+3}`. [Answer] ## Labyrinth, 41 bytes ``` =|?30 0 _ }:/2 3 1 { "! ({( &{/ } ) +:" ``` A collab answer with @MartinBüttner. I think we've squeezed this one far beyond my initial expectations. Output is `1` for truthy, empty for falsy. [Try it online!](http://labyrinth.tryitonline.net/#code=PXw_MzAKMCBfIH06LzIKMyAxICB7ICIhCih7KCAgJnsvCn0gKQorOiI&input=MSA2IDMgNCAy) ### Quick explanation Convert each number `n` to a binary integer 1 followed by `n+1` zeroes, i.e. `2^(n+1)`. Bitwise OR the results and check for `1111` (in binary). Exponentiation needs to be implemented manually in Labyrinth. ### Detailed explanation The usual primer: * Labyrinth is a stack-based 2D programming language. For memory there is a main stack and an auxiliary stack, and popping from an empty stack produces 0 rather than an error. * At each junction, where the instruction pointer could move down two or more possible paths, the top of the stack is checked to decide where to go next. Negative is left, zero is forward, positive is right. * Digits in Labyrinth do not push the corresponding digit to the stack – rather, they pop `n` and push `n*10 + <digit>`. To start a new number, `_` pushes zero. **Setup** Execution begins at the top-left, with the instruction pointer facing rightwards. We execute: ``` = Swap tops of main and auxiliary stacks | Bitwise OR ``` Aside from effectively pushing zeroes, these instructions don't change the stack. **Left loop: exponentiate and bitwise OR** Labyrinth doesn't have exponentiation, so we need to implement it manually. First we read an integer with `?`, and since this is guaranteed to be positive we turn right. `_1` pushes 1 and we enter the inner loop. The inner loop does the following: ``` ( Decrement. For the first iteration this turns 1 into 0 so we move straight ahead downwards; for other iterations when we're coming from the left this turns 2^k into 2^k-1 > 0, making us turn right (also downwards) ) Increment again " No-op :+ Duplicate and add, i.e. double } Move result to aux ( Decrement input n. Since this is at a junction, we turn right and continue the loop if n is still positive, else we exit the loop by going forwards if n is 0 { Move result from aux to main ``` Since this is a do-while loop, for input `n` this calculates `2^(n+1)`. We end with the zeroed input on the stack, and `30` turns this zero into 30. We then perform the same instructions from the setup, but this time they're actually useful. ``` = Swap tops of main and aux, moving 30 to aux and 2^(n+1) to main | Bitwise OR (for the first input, this is bitwise OR with an implicit zero at the bottom of the stack) ``` This loop continues for each number in the input until EOF, when `?` returns 0. This makes us move forwards instead of turning, leading into... **Bridge: some extra setup** The `30` after the `?` turns the 0 from EOF into 30, which is pushed to the auxiliary stack via `}`. Of importance is the fact that we pushed a 30 to the auxiliary stack for every input number, so now **the auxiliary stack contains `5 + 1 = 6` copies of the number 30**. Meanwhile, the main stack contains the bitwise OR of `2^(n+1)` for each input `n`. Let's call this bitwise OR `b`, since it gets modified in the right loop. **Right loop: check result and output** Here's what happens in the right-hand side loop: ``` : Duplicate top of stack. This makes us turn right for the first iteration, since b is positive. For later iterations, when we're coming in from the right, we usually take the same turn (but see below) {& Bitwise AND with a 30 pulled from aux {/ Integer division by a 30 pulled from aux. This returns 1 or 0 depending on whether we have found a small straight. " No-op at a junction. Turn right if small straight, else go forward. [If small straight found] ! Output the previous 1. This is at a dead end, so we turn around. " No-op at junction. Turn right since top of stack is positive. (stuff happens - see below) [If small straight not found] 2 Turn 0 into 2 / Divide b by said 2 (continue loop) ``` Now, termination is a little tricky with this program. Here are the possible ways the program can terminate: * **After 3 iterations of the right loop, and `b` is still positive:** Remember how we put six 30s into the auxiliary stack? Since we use two of them each iteration, on the fourth iteration we start pulling zeroes from the bottom of the auxiliary stack. This causes a division by zero when we do `{/`, and the program terminates. * **After outputting a 1 for a small straight**: So we've executed `!` then turned right at the no-op `"` junction. Then we're in for a rollercoaster as we start crawling all over the left half again: ``` 2 Pops b, pushes 10*b + 2 /} Divide bottom zero by b, giving zero, pushing to aux 03 Zero at bottom of stack becomes 3 ? Push 0 due to EOF, main stack [3 0]. Go straight. |= Bitwise OR then swap tops of main and aux 03 Zero at bottom of stack becomes 3, stacks [3 | 3] ({( Dec, shift dec. Stacks [2 2 | ], and we're in the exponentiator again. ``` After a few trips in the exponentiator, the stack looks something like `[12 | 30 30]`, which errors out by division by zero after another two iterations in the right loop. * **After b becomes zero at some point**: The key here is that the `:` in the right loop is at a junction. If the input was, say, `1 1 1 1 1`, then `b` would be `4`, then `2`, then `1`, then `0` after the third iteration. Instead of turning at the `:`, the IP now moves straight ahead, and something like the previous case happens to cause an eventual termination. All in all it's a mess how the program terminates, but hey anything to save those few bytes! [Answer] # Mathematica, ~~39~~ ~~43~~ ~~44~~ ~~31~~ ~~39~~ 44 bytes ``` Differences@Union@#~MatchQ~{___,1,1,1,___} & ``` [Answer] ## Haskell, ~~39~~ 34 bytes ``` f x=any(\y->all(`elem`x)[y..y+3])x ``` Usage example: `f [1,2,3,3,4]` -> `True`. Similar to [@xnor's answer](https://codegolf.stackexchange.com/a/75026/34531), i.e. check if any of the small straights are in the input list. Actually I'm testing all "small straights" (i.e. 4 consecutive numbers) starting with any of the numbers from the input list, some of them being invalid and therefore always fail the `all` test and don't distort the `any` test, e.g. `[5,6,7,8]`. Edit: @Zgarb saved 5 bytes. Thanks! [Answer] # MATL, 11 bytes ``` udY'w1=)2>a ``` [Try it online](http://matl.tryitonline.net/#code=U3VkWSd3MT0pMj5h&input=WzEgMiAyIDMgNF0) ``` u unique (implicit sort) d diff Y' run-length-encode w1=) exract the length of all runs of ones 2> check whether they are longer than two a any (any non-zero element) ``` [Answer] # JavaScript (ES6), ~~55~~ 53 bytes ``` a=>(z=[0,1,2,3]).some(b=>z.every(c=>a.includes(c+b))) ``` returns `true` for truthy and `false` for falsy. ### How it works Return if some value in [0, 1, 2, 3] fulfills the condition that for every value in [0, 1, 2, 3] the sum of these two values is in the input array. So, return if the array has every value in [0, 1, 2, 3] (impossible), [1, 2, 3, 4], [2, 3, 4, 5], or [3, 4, 5, 6]. [Answer] # Perl, ~~47~~ ~~43~~ ~~42~~ ~~39~~ ~~37~~ 29 bytes Includes +1 for `-p` Run with the sequence on STDIN, e.g. ``` perl -p smallstraight.pl <<< "1 2 3 3 4" ``` `smallstraight.pl`: ``` s//$_|=1x$'.w/reg;$_=/.w{4}/ ``` ## Explanation ``` s// / eg Each possible postfix string (including the empty string) is assigned to $' in turn So each input digit will be the start of $' at least once 1x$'.w Put a w at position $'. e.g. digit 4 becomes 1111w $_|= Or into existing $_. w is binary 0111 0111 space is binary 0010 0000 digit<=7 is binary 0011 0xxx So an "or" with "w" is always w again: 0111 0111 And no other way can you get a w since w is the only thing that can set the high bits. So the already existing string in $_ has no effect on the number of w's in the result r The $_ that has been "or"ed several times is exfiltrated out of the substitution. It will have a w in every position that the original string had a digit with an extra w at position 0 since the s///g will also have matched the empty string at the end So e.g. "1 2 3 5 6" will become "wwww3ww 6" $_=/.w{4}/ We have a small straight if there were 4 consecutive numbers, now 4 consecutive w's. But the w we always get at the start of the string doesn't count. Notice that the string cannot have a newline since bit "0010 0000" is always set. So "." to skip one character is safe ``` [Answer] # Ruby, 31 Instead of trying to be smart like the first [Ruby answer](https://codegolf.stackexchange.com/a/75139), this just goes through the array of integers, and for each integer, sees if there's a small straight in the input starting with that integer. Doesn't worry about the possible values or uniqueness. This seems to be using the same algorithm as [Sherlock's answer](https://codegolf.stackexchange.com/a/75169/). ``` ->x{x.any?{|d|[*d..d+3]-x==[]}} ``` [Answer] # Ruby, ~~58~~ ~~55~~ ~~50~~ ~~47~~ ~~43~~ 33 bytes I just now saw that I have been beaten to the punch by [Paul's Ruby answer](https://codegolf.stackexchange.com/a/75139/47581). I am not deterred however as I think this could still be a decent answer with some more golfing. Based, in part, on [xnor's Python answer](https://codegolf.stackexchange.com/a/75026/47581). **Edit:** Some golfing and correcting a mix-up in the ternary conditional. **Edit:** I now use `.any?` like [Not that Charles does in their Ruby answer](https://codegolf.stackexchange.com/a/75273/47581) but only because I needed a simple way to remove `a` and to return only a truthy and a falsey with `!([*i..i+3]-l)[0]` since `.map` would return an array of `true` and `false`. ``` ->l{l.any?{|i|!([*i..i+3]-l)[0]}} ``` Returns either `true` or `false`. **Ungolfed:** ``` def f(l) a = p l.any? do |i| if ( (i..i+3).to_a - l )[0] # if (i..i+3) in l a = false # a[0] is equivalent to !a.empty? else a = true end end puts a end ``` Important note: For those who want to use the `(a2 - a1).empty?` code to determine if all elements of `a2` are in `a1`, note that if you want to make sure that, for example, `[2,1,2]` is in `[1,2,3,3]` to multiplicity of elements, you need other code. [Relevant discussion of this problem here](https://stackoverflow.com/questions/13553822/determine-if-one-array-contains-all-elements-of-another-array). [Answer] # Japt, ~~13~~ 12 bytes ``` Uá4 d@7o ¬fX ``` [**Test it online!**](http://ethproductions.github.io/japt?v=master&code=VeE0IGRAN28grGZY&input=WzQsMSwyLDMsNl0=) or [**Verify all test cases**](http://ethproductions.github.io/japt?v=master&code=Rj1Ve1XhNCBkQDdvIKxmWH19OwoiVHJ1dGh5OgoiK1VtRiC3KyIKCkZhbHN5OgoiK1ZtRiC3&input=VHJ1dGh5OgpbWzEsIDIsIDMsIDMsIDRdLCBbMSwgMiwgMywgNCwgNV0sIFszLCA1LCA2LCAxLCA0XSwgWzEsIDUsIDMsIDQsIDZdLCBbNCwgNSwgMiwgMywgNV0sIFsxLCA0LCAzLCAyLCAyXSwgWzUsIDQsIDMsIDYsIDNdLCBbNSwgMywgNSwgNCwgNl0sIFsyLCA0LCA1LCAxLCAzXSwgWzMsIDYsIDQsIDUsIDNdLCBbNSwgNiwgNCwgMywgNV0sIFs0LCA1LCAzLCA2LCAzXSwgWzQsIDUsIDUsIDMsIDJdLCBbNCwgNSwgMiwgMywgNV0sIFs0LCA2LCA1LCAzLCA2XSwgWzQsIDIsIDMsIDEsIDVdLCBbMywgNiwgNCwgNiwgNV0sIFs1LCAyLCAxLCAzLCA0XSwgWzQsIDQsIDEsIDIsIDNdLCBbNCwgMSwgNCwgMiwgM10sIFs1LCAxLCA0LCAzLCA2XSwgWzUsIDIsIDIsIDMsIDRdLCBbNCwgNCwgNiwgNSwgM10sIFsyLCA0LCAzLCA1LCAxXSwgWzUsIDQsIDIsIDUsIDNdLCBbMiwgMywgNSwgNSwgNF0sIFsxLCA2LCAzLCA0LCA1XSwgWzQsIDUsIDMsIDMsIDZdLCBbNiwgNCwgMywgNiwgNV0sIFs0LCA2LCA2LCA1LCAzXSwgWzQsIDMsIDUsIDIsIDJdLCBbMiwgMywgMiwgMSwgNF0sIFs0LCAyLCA2LCAxLCAzXSwgWzQsIDQsIDUsIDMsIDZdLCBbNCwgNSwgNiwgMywgNl1dCgpGYWxzeToKW1sxLCAyLCAzLCA1LCA2XSwgWzUsIDEsIDEsIDYsIDZdLCBbNCwgNiwgNCwgMSwgMV0sIFs2LCA0LCAxLCA2LCA0XSwgWzQsIDYsIDMsIDYsIDZdLCBbMiwgMSwgNCwgNiwgNF0sIFsyLCA2LCAxLCA1LCA2XSwgWzIsIDYsIDEsIDUsIDZdLCBbMywgNiwgNSwgMywgMl0sIFszLCAyLCAzLCA1LCAzXSwgWzUsIDUsIDYsIDIsIDNdLCBbMywgNCwgNiwgNCwgM10sIFsxLCA0LCA1LCA1LCAxXSwgWzEsIDQsIDQsIDQsIDFdLCBbMSwgNiwgNSwgMSwgNF0sIFs2LCA2LCA0LCA1LCA0XSwgWzUsIDMsIDMsIDMsIDJdLCBbNSwgMiwgMSwgNSwgM10sIFszLCA1LCAxLCA2LCAyXSwgWzYsIDQsIDIsIDEsIDJdLCBbMSwgMywgMSwgMywgMl0sIFszLCAxLCAzLCA0LCAzXSwgWzQsIDMsIDEsIDYsIDNdLCBbNCwgNiwgMywgMywgNl0sIFszLCA2LCAzLCA2LCA0XSwgWzEsIDEsIDMsIDEsIDNdLCBbNSwgNSwgMSwgMywgMl0sIFszLCA0LCAyLCA2LCA2XSwgWzUsIDQsIDIsIDYsIDFdLCBbMiwgNCwgNCwgNSwgNF0sIFszLCA2LCAyLCA1LCA1XSwgWzIsIDUsIDMsIDUsIDFdLCBbMywgMiwgMiwgMywgNF0sIFs1LCAyLCAyLCA2LCAyXSwgWzUsIDYsIDIsIDUsIDZdXQ==). ### How it works ``` // Implicit: U = input array Uá4 // Take all permutations of U of length 4. d@ // Return whether any item X returns truthily to this function: 7o ¬ // Take the range [0..7) and join. Produces "0123456". fX // Match X in this string. // This returns null if X is not a subset of [0..7), and a (truthy) array otherwise. // Implicit output ``` [Answer] # Pyth, ~~13~~ 11 ``` @.PQ4.:S6 4 ``` 2 bytes thanks to Jakube! Returns a non-empty list for truthy, empty list for falsy. [Try it online](http://pyth.herokuapp.com/?code=%40.PQ4.%3AS6+4&input=%5B4%2C2%2C2%2C3%2C1%5D&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=%40.PQ4.%3AS6+4&input=%5B4%2C2%2C2%2C3%2C1%5D&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B3%2C+5%2C+6%2C+1%2C+4%5D%0A%5B1%2C+5%2C+3%2C+4%2C+6%5D%0A%5B4%2C+5%2C+2%2C+3%2C+5%5D%0A%5B1%2C+4%2C+3%2C+2%2C+2%5D%0A%5B5%2C+4%2C+3%2C+6%2C+3%5D%0A%5B5%2C+3%2C+5%2C+4%2C+6%5D%0A%5B2%2C+4%2C+5%2C+1%2C+3%5D%0A%5B3%2C+6%2C+4%2C+5%2C+3%5D%0A%5B5%2C+6%2C+4%2C+3%2C+5%5D%0A%5B4%2C+5%2C+3%2C+6%2C+3%5D%0A%5B4%2C+5%2C+5%2C+3%2C+2%5D%0A%5B4%2C+5%2C+2%2C+3%2C+5%5D%0A%5B4%2C+6%2C+5%2C+3%2C+6%5D%0A%5B4%2C+2%2C+3%2C+1%2C+5%5D%0A%5B3%2C+6%2C+4%2C+6%2C+5%5D%0A%5B5%2C+2%2C+1%2C+3%2C+4%5D%0A%5B4%2C+4%2C+1%2C+2%2C+3%5D%0A%5B4%2C+1%2C+4%2C+2%2C+3%5D%0A%5B5%2C+1%2C+4%2C+3%2C+6%5D%0A%5B5%2C+2%2C+2%2C+3%2C+4%5D%0A%5B4%2C+4%2C+6%2C+5%2C+3%5D%0A%5B2%2C+4%2C+3%2C+5%2C+1%5D%0A%5B5%2C+4%2C+2%2C+5%2C+3%5D%0A%5B2%2C+3%2C+5%2C+5%2C+4%5D%0A%5B1%2C+6%2C+3%2C+4%2C+5%5D%0A%5B4%2C+5%2C+3%2C+3%2C+6%5D%0A%5B6%2C+4%2C+3%2C+6%2C+5%5D%0A%5B4%2C+6%2C+6%2C+5%2C+3%5D%0A%5B4%2C+3%2C+5%2C+2%2C+2%5D%0A%5B2%2C+3%2C+2%2C+1%2C+4%5D%0A%5B4%2C+2%2C+6%2C+1%2C+3%5D%0A%5B4%2C+4%2C+5%2C+3%2C+6%5D%0A%5B4%2C+5%2C+6%2C+3%2C+6%5D%0Ablarg%0A%5B5%2C+1%2C+1%2C+6%2C+6%5D%0A%5B4%2C+6%2C+4%2C+1%2C+1%5D%0A%5B6%2C+4%2C+1%2C+6%2C+4%5D%0A%5B4%2C+6%2C+3%2C+6%2C+6%5D%0A%5B2%2C+1%2C+4%2C+6%2C+4%5D%0A%5B2%2C+6%2C+1%2C+5%2C+6%5D%0A%5B2%2C+6%2C+1%2C+5%2C+6%5D%0A%5B3%2C+6%2C+5%2C+3%2C+2%5D%0A%5B3%2C+2%2C+3%2C+5%2C+3%5D%0A%5B5%2C+5%2C+6%2C+2%2C+3%5D%0A%5B3%2C+4%2C+6%2C+4%2C+3%5D%0A%5B1%2C+4%2C+5%2C+5%2C+1%5D%0A%5B1%2C+4%2C+4%2C+4%2C+1%5D%0A%5B1%2C+6%2C+5%2C+1%2C+4%5D%0A%5B6%2C+6%2C+4%2C+5%2C+4%5D%0A%5B5%2C+3%2C+3%2C+3%2C+2%5D%0A%5B5%2C+2%2C+1%2C+5%2C+3%5D%0A%5B3%2C+5%2C+1%2C+6%2C+2%5D%0A%5B6%2C+4%2C+2%2C+1%2C+2%5D%0A%5B1%2C+3%2C+1%2C+3%2C+2%5D%0A%5B3%2C+1%2C+3%2C+4%2C+3%5D%0A%5B4%2C+3%2C+1%2C+6%2C+3%5D%0A%5B4%2C+6%2C+3%2C+3%2C+6%5D%0A%5B3%2C+6%2C+3%2C+6%2C+4%5D%0A%5B1%2C+1%2C+3%2C+1%2C+3%5D%0A%5B5%2C+5%2C+1%2C+3%2C+2%5D%0A%5B3%2C+4%2C+2%2C+6%2C+6%5D%0A%5B5%2C+4%2C+2%2C+6%2C+1%5D%0A%5B2%2C+4%2C+4%2C+5%2C+4%5D%0A%5B3%2C+6%2C+2%2C+5%2C+5%5D%0A%5B2%2C+5%2C+3%2C+5%2C+1%5D%0A%5B3%2C+2%2C+2%2C+3%2C+4%5D%0A%5B5%2C+2%2C+2%2C+6%2C+2%5D%0A%5B5%2C+6%2C+2%2C+5%2C+6%5D&debug=0) (split by a syntax error for Readability™). [Answer] ## CJam, ~~16~~ ~~15~~ 12 bytes ``` 7,4ewl~f&3f> ``` Yields a non-empty string for truthy test cases and an empty string for falsy ones. [Test suite.](http://cjam.aditsu.net/#code=q'%2C-~%5D%7B%60%3AL%3B%0A%0A7%2C4ewL~f%263f%3E%0A%0A%5DoNo%7D%2F&input=%5B1%202%203%204%205%5D%20%5B3%205%206%201%204%5D%20%5B1%205%203%204%206%5D%20%5B4%205%202%203%205%5D%20%5B1%204%203%202%202%5D%20%5B5%204%203%206%203%5D%20%5B5%203%205%204%206%5D%20%5B2%204%205%201%203%5D%20%5B3%206%204%205%203%5D%20%5B5%206%204%203%205%5D%20%5B4%205%203%206%203%5D%20%5B4%205%205%203%202%5D%20%5B4%205%202%203%205%5D%20%5B4%206%205%203%206%5D%20%5B4%202%203%201%205%5D%20%5B3%206%204%206%205%5D%20%5B5%202%201%203%204%5D%20%5B4%204%201%202%203%5D%20%5B4%201%204%202%203%5D%20%5B5%201%204%203%206%5D%20%5B5%202%202%203%204%5D%20%5B4%204%206%205%203%5D%20%5B2%204%203%205%201%5D%20%5B5%204%202%205%203%5D%20%5B2%203%205%205%204%5D%20%5B1%206%203%204%205%5D%20%5B4%205%203%203%206%5D%20%5B6%204%203%206%205%5D%20%5B4%206%206%205%203%5D%20%5B4%203%205%202%202%5D%20%5B2%203%202%201%204%5D%20%5B4%202%206%201%203%5D%20%5B4%204%205%203%206%5D%20%5B4%205%206%203%206%5D%5B5%201%201%206%206%5D%20%5B4%206%204%201%201%5D%20%5B6%204%201%206%204%5D%20%5B4%206%203%206%206%5D%20%5B2%201%204%206%204%5D%20%5B2%206%201%205%206%5D%20%5B2%206%201%205%206%5D%20%5B3%206%205%203%202%5D%20%5B3%202%203%205%203%5D%20%5B5%205%206%202%203%5D%20%5B3%204%206%204%203%5D%20%5B1%204%205%205%201%5D%20%5B1%204%204%204%201%5D%20%5B1%206%205%201%204%5D%20%5B6%206%204%205%204%5D%20%5B5%203%203%203%202%5D%20%5B5%202%201%205%203%5D%20%5B3%205%201%206%202%5D%20%5B6%204%202%201%202%5D%20%5B1%203%201%203%202%5D%20%5B3%201%203%204%203%5D%20%5B4%203%201%206%203%5D%20%5B4%206%203%203%206%5D%20%5B3%206%203%206%204%5D%20%5B1%201%203%201%203%5D%20%5B5%205%201%203%202%5D%20%5B3%204%202%206%206%5D%20%5B5%204%202%206%201%5D%20%5B2%204%204%205%204%5D%20%5B3%206%202%205%205%5D%20%5B2%205%203%205%201%5D%20%5B3%202%202%203%204%5D%20%5B5%202%202%206%202%5D%20%5B5%206%202%205%206%5D) ### Explanation ``` 7, e# Push [0 1 2 3 4 5 6]. 4ew e# Get all length-4 sublists. This gives: e# [[0 1 2 3] e# [1 2 3 4] e# [2 3 4 5] e# [3 4 5 6]] e# i.e. all possible small straights (and an impossible one). l~ e# Read and evaluate input. f& e# Set intersection of each small straight with the full list. e# If any small straight is contained in the list, all 4 of its e# elements will be retained. 3f> e# Discard the first three elements of each intersection. If a e# small straight was not in the list, this will give an empty e# list. Otherwise, one element will remain. ``` At the end of the program, this list is flattened into a single string and printed to STDOUT. If any of the small straights were found, their remaining elements will be in the string. Otherwise all the lists were empty, and so the string is also empty. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ 10 bytes **Truthy** is containing an array in the output, **falsy** is when no output is produced. Code: ``` œvy¦¥1QPiy ``` Explanation *outdated*: ``` œ # Compute all permutations vy # Map over each permutation ¦ # Head, leaves [1:] ¥ # Delta, computes the differences between the elements P # Product, which computes the product of the array iy # If equal to 1, push the array again # Implicit, if there is a match, an array will be displayed. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xZN2ecKmwqUxUVBpeQ&input=WzEsIDIsIDMsIDYsIDZd) Uses **CP-1252** encoding. [Answer] # Javascript ES6 47 bytes ``` q=>/12+3+4|23+4+5|34+5+6/.test(q.sort().join``) ``` # Javascript ES6 52 bytes ``` q=>/1,+1,+1/.test(q.sort().map((a,i)=>a-q[i-1]||``)) //sort the array //map each element to the difference from the last element //Look for three 'increment by ones' (ignore increment by 0s) ``` --- Old answer # Javascript ES6 64 bytes thanks to ETHproductions for helping save several bytes ``` q=>q.sort().map(o=>(o-s?o-s<2?t++:t=t>3?t:1:0,s=o),t=1,s=-1)|t>3 ``` --- ``` q=> //take an input q.sort() //sort it .map( //for each number o=> s= //set current value = !(o-s) ? //if it's a duplicate o : //just keep the current state (set s to s again) ( o-s < 2 ? //if the current values is one more than the next one t++ : //increment the total t=t>4?t:1 //otherwise, set the total back to 1, unless we've hit 4 total already )&&o //set the current value to the current token ,t=1,s=-1) //init the total, and the current value (set it to -1 since we won't hit that anyways |t>3 //return total > 3 (so 1 if we get a run of 4 or 5) ``` **Testing** ``` //true and false test cases from OP tr = [[1, 2, 3, 3, 4], [1, 2, 3, 4, 5], [3, 5, 6, 1, 4], [1, 5, 3, 4, 6], [4, 5, 2, 3, 5], [1, 4, 3, 2, 2], [5, 4, 3, 6, 3], [5, 3, 5, 4, 6], [2, 4, 5, 1, 3], [3, 6, 4, 5, 3], [5, 6, 4, 3, 5], [4, 5, 3, 6, 3], [4, 5, 5, 3, 2], [4, 5, 2, 3, 5], [4, 6, 5, 3, 6], [4, 2, 3, 1, 5], [3, 6, 4, 6, 5], [5, 2, 1, 3, 4], [4, 4, 1, 2, 3], [4, 1, 4, 2, 3], [5, 1, 4, 3, 6], [5, 2, 2, 3, 4], [4, 4, 6, 5, 3], [2, 4, 3, 5, 1], [5, 4, 2, 5, 3], [2, 3, 5, 5, 4], [1, 6, 3, 4, 5], [4, 5, 3, 3, 6], [6, 4, 3, 6, 5], [4, 6, 6, 5, 3], [4, 3, 5, 2, 2], [2, 3, 2, 1, 4], [4, 2, 6, 1, 3], [4, 4, 5, 3, 6], [4, 5, 6, 3, 6]] fa = [[1, 2, 3, 5, 6], [5, 1, 1, 6, 6], [4, 6, 4, 1, 1], [6, 4, 1, 6, 4], [4, 6, 3, 6, 6], [2, 1, 4, 6, 4], [2, 6, 1, 5, 6], [2, 6, 1, 5, 6], [3, 6, 5, 3, 2], [3, 2, 3, 5, 3], [5, 5, 6, 2, 3], [3, 4, 6, 4, 3], [1, 4, 5, 5, 1], [1, 4, 4, 4, 1], [1, 6, 5, 1, 4], [6, 6, 4, 5, 4], [5, 3, 3, 3, 2], [5, 2, 1, 5, 3], [3, 5, 1, 6, 2], [6, 4, 2, 1, 2], [1, 3, 1, 3, 2], [3, 1, 3, 4, 3], [4, 3, 1, 6, 3], [4, 6, 3, 3, 6], [3, 6, 3, 6, 4], [1, 1, 3, 1, 3], [5, 5, 1, 3, 2], [3, 4, 2, 6, 6], [5, 4, 2, 6, 1], [2, 4, 4, 5, 4], [3, 6, 2, 5, 5], [2, 5, 3, 5, 1], [3, 2, 2, 3, 4], [5, 2, 2, 6, 2], [5, 6, 2, 5, 6]] f=q=>q.sort().map(o=>(o-s?o-s<2?t++:t=t>3?t:1:0,s=o),t=1,s=-1)|t>3 tr.map(f) //just look to make sure every value is true fa.map(f) //just look to make sure every value is false ``` [Answer] ## C#, ~~156~~ ~~151~~ ~~150~~ ~~131~~ ~~121~~ ~~93~~ ~~92~~ 90 bytes ``` int l;bool f(int[]a){foreach(var v in a)l|=1<<v-1;return(l&15)>14||(l&30)>29||(l&60)>59;} ``` **or:** (same number of bytes) ``` int l;bool f(int[]a){foreach(var v in a)l|=1<<v;return(l&30)>29||(l&60)>59||(l&120)>119;} ``` Ungolfed: ``` int l; bool f(int[] a) { foreach (var v in a) l |= 1 << v - 1; return (l & 15) > 14 || //Bits 1-4 are set OR (l & 30) > 29 || //Bits 2-5 are set OR (l & 60) > 59; //Bits 3-6 are set } ``` **Big Edit:** Just realized I only need to post a function, not a whole program. That saves a whole lot. No boilerplate, no need to convert string input into numbers, etc. Now we're actually approaching a respectable number of bytes (for a non-golfing language anyhow). [Answer] ## TI-BASIC, 25 bytes ``` not(min(fPart(prod(Ans+36)/(65{703,779,287 ``` An equivalent (ungolfed) Python expression which you can [test](https://repl.it/BuQb): ``` def has_small_straight(l): product = reduce(lambda x,y: x*y, [x + 36 for x in l], 1) numbers = [37*19*13*5, 19*13*5*41, 13*5*41*7] return not(all([product%x for x in numbers])) ``` The idea behind this is divisibility. To check whether a `1, 2, 3, 4`, `2, 3, 4, 5`, or `3, 4, 5, 6` occurs, we can map the numbers 1-6 to 37-42, and then multiply the correct numbers together. Each of the numbers in [37,42] have a prime factor that the other numbers lack. ``` n | 1 | 2 | 3 | 4 | 5 | 6 | n + 36 | 37 | 38 | 39 | 40 | 41 | 42 | Factor | 37 | 19 | 13 | 5 | 41 | 7 | ``` Therefore, if the product of the five numbers is divisible by 37, the original list contained a 1. If by 19, it contained a 2; etc. If it is divisible by `37*19*13*5` = `65*703`, it contains `1`, `2`, `3`, and `4` and similarly for the other two numbers. This solution is an improvement on [one](http://tibasicdev.wikidot.com/forum/t-124256/comparing-lists#post-370978) that [@Weregoose](https://codegolf.stackexchange.com/users/46581/weregoose) posted in 2009. [Answer] # Ruby - 80 -> 79 -> 76 -> 54 -> 48 -> 40 bytes Fifth Try (40 bytes): ``` ->x{/1234|2345|3456/===x.uniq.sort.join} ``` Uses lambda syntax to define the function. (Thanks to competing Ruby golfer @Sherlock9 for this idea.) To test using lambda call: ``` s = ->x{/1234|2345|3456/===x.uniq.sort.join} s.call([1,3,5,4,4]) s.call([1,3,5,4,2]) ``` Fourth Try: ``` def s?(x)/1234|2345|3456/===x.uniq.sort.join end ``` Replaced nil? and negation with === operator. Third Try: ``` def s?(x)!(/1234|2345|3456/=~x.uniq.sort.join).nil?end ``` Uses regular expression. Second Try: ``` def s?(x)[1234,2345,3456].select{|a|x.uniq.sort.join.include?a.to_s}.any?end ``` New approach uses dedup (uniq), sort and join, plus include? to search for a match of any solutions in the input rendered as a string. First Try: 79 bytes ``` def s?(x)[[1,2,3,4],[2,3,4,5],[3,4,5,6]].select{|a|(a&x.uniq).length>3}.any?end ``` Tester: ``` x = [1,4,3,3,6] s?(x) x = [2,4,5,1,3] s?(x) ``` Uses deduping (uniq function) plus set intersection (& operator) to test if any of the good sequences matches the given sequence. No sorting needed. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 15 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) [`{∨/∧/⍵∊⍨⍵∘.+⍳4}`](http://tryapl.org/?a=%u2395io%u21900%20%u22C4%20%7B%u2228/%u2227/%u2375%u220A%u2368%u2375%u2218.+%u23734%7D%203%205%206%201%204&run) uses `⎕IO=0` `⍳4` is `0 1 2 3` `⍵∘.+⍳4` is 5×4 a matrix of each die incremented by each of `⍳4` `⍵∊⍨` checks if the elements of the matrix are in the hand, result is a boolean (0-or-1) matrix, we need to find a row of all 1s `∧/` is the and-reduction by rows, result is a boolean vector `∨/` is the or-reduction of that vector [Answer] ## PHP, 95 bytes ``` function s($d){$a=array_diff;$r=range;return!($a($r(1,4),$d)&&$a($r(2,5),$d)&&$a($r(3,6),$d));} ``` **Exploded view** ``` function s($d){ $a = array_diff; $r = range; return !($a($r(1,4),$d) && $a($r(2,5),$d) && $a($r(3,6),$d)); } ``` **Input / function call** ``` s(Array[int, int, int, int, int]); ``` **Output** ``` bool ``` [Answer] ## Seriously, 21 bytes ``` 3R`;4+@x`M4,╨╗`╜íu`MΣ ``` [Try it online!](http://seriously.tryitonline.net/#code=M1JgOzQrQHhgTTQs4pWo4pWXYOKVnMOtdWBNzqM&input=WzEsMiwzLDYsNF0) Outputs a positive value for true, and a 0 for false. Explanation: ``` 3R`;4+@x`M4,╨╗`╜íu`MΣ 3R`;4+@x`M push [[1,2,3,4], [2,3,4,5], [3,4,5,6] 4,╨╗ push all 4-length permutations of input to register 0 ` `M map: ╜íu push 1-based index of list in permutations, 0 if not found Σ sum ``` [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr), 71 bytes This can probably be golfed further, but as a start: ``` s=setminus;v->t=s([1..6],Set(v));!#s(t,[1,2])+!#s(t,[5,6])+!#s(t,[1,6]) ``` I don't see a way of reducing duplication without using more space; this version is 75 bytes: ``` s=setminus;v->t=s([1..6],Set(v));z=(u->!#s(t,u));z([1,2])+z([5,6])+z([1,6]) ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~70~~ 54 bytes Input is a single string of the integers like `13342`. Output is a `1` if found, or a `0` if not. ``` . # Replace integer digits with unary $*x, +`(x+(x+,))\2 # Sorts the list by repeated swapping $2$1 (x+,)\1 # Removes adjacent duplicates $1 (x+,)x\1xx\1xxx\1 # Matches a small straight ``` Note that the removal of duplicates only needs to occur once, since there are only five numbers. Needing to remove more than one number would mean there isn't a small straight anyway. [**Try it online**](http://retina.tryitonline.net/#code=LgokKngsCitgKHgrKHgrLCkpXDIKJDIkMQooeCssKVwxCiQxCih4KywpeFwxeHhcMXh4eFwx&input=MTQ0MzQ) Thanks to Martin for the idea to move the commas inside the capture groups, saving a whopping 16 bytes. [Answer] # Pyth, 11 bytes ``` f!-TQ.:S6 4 ``` [Test suite](https://pyth.herokuapp.com/?code=f%21-TQ.%3AS6+4&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+3%2C+4%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B3%2C+5%2C+6%2C+1%2C+4%5D%0A%5B1%2C+5%2C+3%2C+4%2C+6%5D%0A%5B4%2C+5%2C+2%2C+3%2C+5%5D%0A%5B1%2C+4%2C+3%2C+2%2C+2%5D%0A%5B5%2C+4%2C+3%2C+6%2C+3%5D%0A%5B5%2C+3%2C+5%2C+4%2C+6%5D%0A%5B2%2C+4%2C+5%2C+1%2C+3%5D%0A%5B3%2C+6%2C+4%2C+5%2C+3%5D%0A%5B5%2C+6%2C+4%2C+3%2C+5%5D%0A%5B4%2C+5%2C+3%2C+6%2C+3%5D%0A%5B4%2C+5%2C+5%2C+3%2C+2%5D%0A%5B4%2C+5%2C+2%2C+3%2C+5%5D%0A%5B4%2C+6%2C+5%2C+3%2C+6%5D%0A%5B4%2C+2%2C+3%2C+1%2C+5%5D%0A%5B3%2C+6%2C+4%2C+6%2C+5%5D%0A%5B5%2C+2%2C+1%2C+3%2C+4%5D%0A%5B4%2C+4%2C+1%2C+2%2C+3%5D%0A%5B4%2C+1%2C+4%2C+2%2C+3%5D%0A%5B5%2C+1%2C+4%2C+3%2C+6%5D%0A%5B5%2C+2%2C+2%2C+3%2C+4%5D%0A%5B4%2C+4%2C+6%2C+5%2C+3%5D%0A%5B2%2C+4%2C+3%2C+5%2C+1%5D%0A%5B5%2C+4%2C+2%2C+5%2C+3%5D%0A%5B2%2C+3%2C+5%2C+5%2C+4%5D%0A%5B1%2C+6%2C+3%2C+4%2C+5%5D%0A%5B4%2C+5%2C+3%2C+3%2C+6%5D%0A%5B6%2C+4%2C+3%2C+6%2C+5%5D%0A%5B4%2C+6%2C+6%2C+5%2C+3%5D%0A%5B4%2C+3%2C+5%2C+2%2C+2%5D%0A%5B2%2C+3%2C+2%2C+1%2C+4%5D%0A%5B4%2C+2%2C+6%2C+1%2C+3%5D%0A%5B4%2C+4%2C+5%2C+3%2C+6%5D%0A%5B4%2C+5%2C+6%2C+3%2C+6%5D%0A%5B1%2C+2%2C+3%2C+5%2C+6%5D%0A%5B5%2C+1%2C+1%2C+6%2C+6%5D%0A%5B4%2C+6%2C+4%2C+1%2C+1%5D%0A%5B6%2C+4%2C+1%2C+6%2C+4%5D%0A%5B4%2C+6%2C+3%2C+6%2C+6%5D%0A%5B2%2C+1%2C+4%2C+6%2C+4%5D%0A%5B2%2C+6%2C+1%2C+5%2C+6%5D%0A%5B2%2C+6%2C+1%2C+5%2C+6%5D%0A%5B3%2C+6%2C+5%2C+3%2C+2%5D%0A%5B3%2C+2%2C+3%2C+5%2C+3%5D%0A%5B5%2C+5%2C+6%2C+2%2C+3%5D%0A%5B3%2C+4%2C+6%2C+4%2C+3%5D%0A%5B1%2C+4%2C+5%2C+5%2C+1%5D%0A%5B1%2C+4%2C+4%2C+4%2C+1%5D%0A%5B1%2C+6%2C+5%2C+1%2C+4%5D%0A%5B6%2C+6%2C+4%2C+5%2C+4%5D%0A%5B5%2C+3%2C+3%2C+3%2C+2%5D%0A%5B5%2C+2%2C+1%2C+5%2C+3%5D%0A%5B3%2C+5%2C+1%2C+6%2C+2%5D%0A%5B6%2C+4%2C+2%2C+1%2C+2%5D%0A%5B1%2C+3%2C+1%2C+3%2C+2%5D%0A%5B3%2C+1%2C+3%2C+4%2C+3%5D%0A%5B4%2C+3%2C+1%2C+6%2C+3%5D%0A%5B4%2C+6%2C+3%2C+3%2C+6%5D%0A%5B3%2C+6%2C+3%2C+6%2C+4%5D%0A%5B1%2C+1%2C+3%2C+1%2C+3%5D%0A%5B5%2C+5%2C+1%2C+3%2C+2%5D%0A%5B3%2C+4%2C+2%2C+6%2C+6%5D%0A%5B5%2C+4%2C+2%2C+6%2C+1%5D%0A%5B2%2C+4%2C+4%2C+5%2C+4%5D%0A%5B3%2C+6%2C+2%2C+5%2C+5%5D%0A%5B2%2C+5%2C+3%2C+5%2C+1%5D%0A%5B3%2C+2%2C+2%2C+3%2C+4%5D%0A%5B5%2C+2%2C+2%2C+6%2C+2%5D%0A%5B5%2C+6%2C+2%2C+5%2C+6%5D&debug=0) Generate the length 4 substrings of [1..6], then filter them on no elements remaining when the elements of the input are removed. [Answer] # Jelly, 9 bytes There has to be an 8-byte solution, will continue searching... Code: ``` Œ!Ḋ€Iµ7Be ``` This is the same as my [**05AB1E** solution](https://codegolf.stackexchange.com/a/75018/34388). Explanation: ``` Œ! # Compute all permutations Ḋ€ # Dequeue each, leaving [1:] I # Delta function µ # Start a new monadic chain 7B # 7 in binary, which is [1, 1, 1] e # Return 1 if this array exists ``` [Try it online!](http://jelly.tryitonline.net/#code=xZIh4biK4oKsScK1N0Jl&input=&args=WzEsIDIsIDMsIDIsIDFd) [Answer] # Jelly, 8 bytes ``` 6Rṡ4ḟ€ċ“ ``` [Try it online!](http://jelly.tryitonline.net/#code=NlLhuaE04bif4oKsxIvigJw&input=&args=WzEsIDIsIDMsIDMsIDRd) or verify the [truthy test cases](http://jelly.tryitonline.net/#code=NlLhuaE04bif4oKsxIvigJzigJ0Kw4figqw&input=&args=W1sxLCAyLCAzLCAzLCA0XSwgWzEsIDIsIDMsIDQsIDVdLCBbMywgNSwgNiwgMSwgNF0sIFsxLCA1LCAzLCA0LCA2XSwgWzQsIDUsIDIsIDMsIDVdLCBbMSwgNCwgMywgMiwgMl0sIFs1LCA0LCAzLCA2LCAzXSwgWzUsIDMsIDUsIDQsIDZdLCBbMiwgNCwgNSwgMSwgM10sIFszLCA2LCA0LCA1LCAzXSwgWzUsIDYsIDQsIDMsIDVdLCBbNCwgNSwgMywgNiwgM10sIFs0LCA1LCA1LCAzLCAyXSwgWzQsIDUsIDIsIDMsIDVdLCBbNCwgNiwgNSwgMywgNl0sIFs0LCAyLCAzLCAxLCA1XSwgWzMsIDYsIDQsIDYsIDVdLCBbNSwgMiwgMSwgMywgNF0sIFs0LCA0LCAxLCAyLCAzXSwgWzQsIDEsIDQsIDIsIDNdLCBbNSwgMSwgNCwgMywgNl0sIFs1LCAyLCAyLCAzLCA0XSwgWzQsIDQsIDYsIDUsIDNdLCBbMiwgNCwgMywgNSwgMV0sIFs1LCA0LCAyLCA1LCAzXSwgWzIsIDMsIDUsIDUsIDRdLCBbMSwgNiwgMywgNCwgNV0sIFs0LCA1LCAzLCAzLCA2XSwgWzYsIDQsIDMsIDYsIDVdLCBbNCwgNiwgNiwgNSwgM10sIFs0LCAzLCA1LCAyLCAyXSwgWzIsIDMsIDIsIDEsIDRdLCBbNCwgMiwgNiwgMSwgM10sIFs0LCA0LCA1LCAzLCA2XSwgWzQsIDUsIDYsIDMsIDZdXQ) and the [falsy test cases](http://jelly.tryitonline.net/#code=NlLhuaE04bif4oKsxIvigJzigJ0Kw4figqw&input=&args=W1sxLCAyLCAzLCA1LCA2XSwgWzUsIDEsIDEsIDYsIDZdLCBbNCwgNiwgNCwgMSwgMV0sIFs2LCA0LCAxLCA2LCA0XSwgWzQsIDYsIDMsIDYsIDZdLCBbMiwgMSwgNCwgNiwgNF0sIFsyLCA2LCAxLCA1LCA2XSwgWzIsIDYsIDEsIDUsIDZdLCBbMywgNiwgNSwgMywgMl0sIFszLCAyLCAzLCA1LCAzXSwgWzUsIDUsIDYsIDIsIDNdLCBbMywgNCwgNiwgNCwgM10sIFsxLCA0LCA1LCA1LCAxXSwgWzEsIDQsIDQsIDQsIDFdLCBbMSwgNiwgNSwgMSwgNF0sIFs2LCA2LCA0LCA1LCA0XSwgWzUsIDMsIDMsIDMsIDJdLCBbNSwgMiwgMSwgNSwgM10sIFszLCA1LCAxLCA2LCAyXSwgWzYsIDQsIDIsIDEsIDJdLCBbMSwgMywgMSwgMywgMl0sIFszLCAxLCAzLCA0LCAzXSwgWzQsIDMsIDEsIDYsIDNdLCBbNCwgNiwgMywgMywgNl0sIFszLCA2LCAzLCA2LCA0XSwgWzEsIDEsIDMsIDEsIDNdLCBbNSwgNSwgMSwgMywgMl0sIFszLCA0LCAyLCA2LCA2XSwgWzUsIDQsIDIsIDYsIDFdLCBbMiwgNCwgNCwgNSwgNF0sIFszLCA2LCAyLCA1LCA1XSwgWzIsIDUsIDMsIDUsIDFdLCBbMywgMiwgMiwgMywgNF0sIFs1LCAyLCAyLCA2LCAyXSwgWzUsIDYsIDIsIDUsIDZdXQ). ### How it works ``` 6Rṡ4ḟ€ċ“ Main link. Argument: A (list) 6R Yield [1, 2, 3, 4, 5, 6]. ṡ4 Split it into overlapping slices of length 4, yielding [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]. ḟ€ Remove all occurrences of A's elements from each slice. ċ“ Count the resulting number of empty list. This returns the number of distinct small straights in A (0, 1 or 2). ``` [Answer] # Scala, ~~76~~ ~~70~~ ~~61~~ 60 bytes ``` (s:Seq[Int])=>(1 to 6)sliding(4)exists(t=>(s diff t).size<2) ``` Tester: ``` val f = <code here> val truthy = Seq(Seq(1, 2, 3, 3, 4), Seq(1, 2, 3, 4, 5), Seq(3, 5, 6, 1, 4), Seq(1, 5, 3, 4, 6), Seq(4, 5, 2, 3, 5), Seq(1, 4, 3, 2, 2), Seq(5, 4, 3, 6, 3), Seq(5, 3, 5, 4, 6), Seq(2, 4, 5, 1, 3), Seq(3, 6, 4, 5, 3), Seq(5, 6, 4, 3, 5), Seq(4, 5, 3, 6, 3), Seq(4, 5, 5, 3, 2), Seq(4, 5, 2, 3, 5), Seq(4, 6, 5, 3, 6), Seq(4, 2, 3, 1, 5), Seq(3, 6, 4, 6, 5), Seq(5, 2, 1, 3, 4), Seq(4, 4, 1, 2, 3), Seq(4, 1, 4, 2, 3), Seq(5, 1, 4, 3, 6), Seq(5, 2, 2, 3, 4), Seq(4, 4, 6, 5, 3), Seq(2, 4, 3, 5, 1), Seq(5, 4, 2, 5, 3), Seq(2, 3, 5, 5, 4), Seq(1, 6, 3, 4, 5), Seq(4, 5, 3, 3, 6), Seq(6, 4, 3, 6, 5), Seq(4, 6, 6, 5, 3), Seq(4, 3, 5, 2, 2), Seq(2, 3, 2, 1, 4), Seq(4, 2, 6, 1, 3), Seq(4, 4, 5, 3, 6), Seq(4, 5, 6, 3, 6)) val falsy = Seq(Seq(1, 2, 3, 5, 6), Seq(5, 1, 1, 6, 6), Seq(4, 6, 4, 1, 1), Seq(6, 4, 1, 6, 4), Seq(4, 6, 3, 6, 6), Seq(2, 1, 4, 6, 4), Seq(2, 6, 1, 5, 6), Seq(2, 6, 1, 5, 6), Seq(3, 6, 5, 3, 2), Seq(3, 2, 3, 5, 3), Seq(5, 5, 6, 2, 3), Seq(3, 4, 6, 4, 3), Seq(1, 4, 5, 5, 1), Seq(1, 4, 4, 4, 1), Seq(1, 6, 5, 1, 4), Seq(6, 6, 4, 5, 4), Seq(5, 3, 3, 3, 2), Seq(5, 2, 1, 5, 3), Seq(3, 5, 1, 6, 2), Seq(6, 4, 2, 1, 2), Seq(1, 3, 1, 3, 2), Seq(3, 1, 3, 4, 3), Seq(4, 3, 1, 6, 3), Seq(4, 6, 3, 3, 6), Seq(3, 6, 3, 6, 4), Seq(1, 1, 3, 1, 3), Seq(5, 5, 1, 3, 2), Seq(3, 4, 2, 6, 6), Seq(5, 4, 2, 6, 1), Seq(2, 4, 4, 5, 4), Seq(3, 6, 2, 5, 5), Seq(2, 5, 3, 5, 1), Seq(3, 2, 2, 3, 4), Seq(5, 2, 2, 6, 2), Seq(5, 6, 2, 5, 6)) println("Failed truthy: " + truthy.filterNot(f)) println("Failed falsy: " + falsy.filter(f)) ``` [Answer] # Javascript ES6 43 bytes ``` q=>/1,1,1,1/.test(q.map(a=>l[a]=1,l=[])&&l) ``` --- //couldn't quite get this to work :/ ``` q=>q.map(a=>l&=~(1<<a),l=62)&&l<7||l==32 ``` This takes the number 62 (111110 in binary) For each number in the input array it removes that bit The resulting number should either be ``` 100000 or 000000 or 000010 or 000110 or 000100 ``` so I check if the result is less than 7 (0000111) or if it's equal to 32 (100000) [Answer] # Mumps, 113 78 Bytes The version of Mumps I'm using is InterSystems Cache. I can't think of a way of golfing this technique any shorter; with a different technique it might be possible, but for now this'll do and at least it's shorter than C++... but not by much. Anyway... OK, here's a shorter way. Instead of having 3 separate variables for the short runs, use a single variable for all 6 'dice' and extract the portions later: ``` R R S Y=111111 F F=1:1:5{S $E(Y,$E(R,F))=0} W '$E(Y,1,4)!'$E(Y,2,5)!'$E(Y,3,6) ``` *so much for me not finding a better way with the same technique... I should look before I leap, eh? ;-)* I'll leave my original answer below for historical purposes... --- --- ``` R R S (G,H,I)=1111 F F=1:1:5{S Q=$E(R,F) S:1234[Q $E(G,Q)=0 S:2345[Q $E(H,Q-1)=0 S:3456[Q $E(I,Q-2)=0} W 'G!'H!'I ``` and here's the explanation of what's going on with the code: ``` R R ; read from STDIN to variable R S (G,H,I)=1111 ; set our 3 possible short straights F F=1:1:5{ ; For loop from 1 to 5 S Q=$E(R,F) ; get each digit from the input and save in Q S:1234[Q $E(G,Q)=0 ; If Q is either 1,2,3 or 4, zero out that position in G. S:2345[Q $E(H,Q-1)=0 ; if Q is either 2,3,4 or 5, zero out that position (-1) in H. S:3456[Q $E(I,Q-2)=0 ; if Q is either 3,4,5 or 6, zero out that position (-2) in I. } ; and end the loop. W 'G!'H!'I ; If G,H, or I are all zeroes (indicating a full straight), ; taking the not of each will make (at least one) of the ; values true. OR-ing all three values will let us know if ; at least one short straight was complete. ; Output is 1 for truthy, 0 for falsy. ``` I didn't test *every single* truthy & falsy input as that involved manually typing them all in; but I did test approximately the first half of each, verified the long straights still show truthy and several of the runs noted to not necessarily work correctly ([4,2,5,3,4], [1,2,3,3,4] etc.) and seems to be working correctly. [Answer] # Jelly, 11 ``` QṢṡ4ðfø6Rṡ4 ``` [Try it online!](http://jelly.tryitonline.net/#code=UeG5ouG5oTTDsGbDuDZS4bmhNA&input=&args=WzQsMSwyLDIsM10) This is pretty much a copy of my Pyth answer, just trying to figure out how to chain stuff. Feels like it should be golfable. ### Expansion: ``` QṢṡ4ðfø6Rṡ4 ## 1, 2, 0 chain, 1 argument from command line QṢṡ4 ## first chain, uniQue and Sort the input, then ## get overlapping lists of length 4 (ṡ) ð ## separator f ## filter left argument on being a member of right argument ø ## separator 6Rṡ4 ## all overlapping lists of length 4, from 1-indexed range of 6 ## generates [1,2,3,4],[2,3,4,5],[3,4,5,6] ``` If you want to ask any hard questions, like why the separators are different, then my answer to you is: "I'll answer in 6-8 weeks" :P (More seriously, I think it's the pattern matching, monad-dyad vs nilad-dyad, but I don't know and don't want to spread misinformation.) ]
[Question] [ Given a square integer matrix as input, output the determinant of the matrix. ## Rules * You may assume that all elements in the matrix, the determinant of the matrix, and the total number of elements in the matrix are within the representable range of integers for your language. * Outputting a decimal/float value with a fractional part of 0 is allowed (e.g. `42.0` instead of `42`). * Builtins are allowed, but you are encouraged to include a solution that does not use builtins. ## Test Cases ``` [[42]] -> 42 [[2, 3], [1, 4]] -> 5 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 0 [[13, 17, 24], [19, 1, 3], [-5, 4, 0]] -> 1533 [[372, -152, 244], [-97, -191, 185], [-53, -397, -126]] -> 46548380 [[100, -200, 58, 4], [1, -90, -55, -165], [-67, -83, 239, 182], [238, -283, 384, 392]] -> 571026450 [[432, 45, 330, 284, 276], [-492, 497, 133, -289, -28], [-443, -400, 56, 150, -316], [-344, 316, 92, 205, 104], [277, 307, -464, 244, -422]] -> -51446016699154 [[416, 66, 340, 250, -436, -146], [-464, 68, 104, 471, -335, -442], [159, -407, 310, -489, -248, 370], [62, 277, 446, -325, 47, -193], [460, 460, -418, -28, 234, -374], [249, 375, 489, 172, -423, 125]] -> 39153009069988024 [[-246, -142, 378, -156, -373, 444], [186, 186, -23, 50, 349, -413], [216, 1, -418, 38, 47, -192], [109, 345, -356, -296, -47, -498], [-283, 91, 258, 66, -127, 79], [218, 465, -420, -326, -445, 19]] -> -925012040475554 [[-192, 141, -349, 447, -403, -21, 34], [260, -307, -333, -373, -324, 144, -190], [301, 277, 25, 8, -177, 180, 405], [-406, -9, -318, 337, -118, 44, -123], [-207, 33, -189, -229, -196, 58, -491], [-426, 48, -24, 72, -250, 160, 359], [-208, 120, -385, 251, 322, -349, -448]] -> -4248003140052269106 [[80, 159, 362, -30, -24, -493, 410, 249, -11, -109], [-110, -123, -461, -34, -266, 199, -437, 445, 498, 96], [175, -405, 432, -7, 157, 169, 336, -276, 337, -200], [-106, -379, -157, -199, 123, -172, 141, 329, 158, 309], [-316, -239, 327, -29, -482, 294, -86, -326, 490, -295], [64, -201, -155, 238, 131, 182, -487, -462, -312, 196], [-297, -75, -206, 471, -94, -46, -378, 334, 407, -97], [-140, -137, 297, -372, 228, 318, 251, -93, 117, 286], [-95, -300, -419, 41, -140, -205, 29, -481, -372, -49], [-140, -281, -88, -13, -128, -264, 165, 261, -469, -62]] -> 297434936630444226910432057 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` LŒ!ðŒcIṠ;ị"Pð€S ``` [Try it online!](https://tio.run/##y0rNyan8/9/n6CTFwxuOTkr2fLhzgfXD3d1KAYc3PGpaE/z////oaEMDAx0FXSMQaWqho2ASq6MQbQgUsQQJm5oCCUMzU5Cgrpk5kGNhrKNgZGypo2BoYQQSNTK2AGkHCRtbmAAJS6PYWAA "Jelly – Try It Online") ## How it works ``` LŒ!ðŒcIṠ;ị"Pð€S input L length Œ! all_permutations ð ð€ for each permutation: Œc take all unordered pairs I calculate the difference between the two integers of each pair Ṡ signum of each difference (positive -> 1, negative -> -1) ; append: ị" the list of elements generated by taking each row according to the index specified by each entry of the permutation P product of everything S sum ``` ## Why it works -- mathy version The operator **det** takes a matrix and returns a scalar. An *n*-by-*n* matrix can be thought of as a collection of *n* vectors of length *n*, so **det** is really a function that takes *n* vectors from ℤ*n* and returns a scalar. Therefore, I write **det**(*v*1, *v*2, *v*3, ..., *v**n*) for **det** [*v*1 *v*2 *v*3 ... *v*n]. Notice that **det** is linear in each argument, i.e. **det**(*v*1 + λ*w*1, *v*2, *v*3, ..., *v**n*) = **det**(*v*1, *v*2, *v*3, ..., *v**n*) + λ **det**(*w*1, *v*2, *v*3, ..., *v**n*). Therefore, it is a linear map from (ℤ*n*)⊗*n* to ℤ. It suffices to determine the image of the basis under the linear map. The basis of (ℤ*n*)⊗*n* consists of *n*-fold tensor products of the basis elements of ℤ*n*, i.e. e.g. e5 ⊗ e3 ⊗ e1 ⊗ e5 ⊗ e1. Tensor products that include identical tensors must be sent to zero, since the determinant of a matrix in which two columns are identical is zero. It remains to check what the tensor products of distinct basis elements are sent to. The indices of the vectors in the tensor product form a bijection, i.e. a permutation, in which even permutations are sent to 1 and odd permutations are sent to -1. For example, to find the determinant of [[1, 2], [3, 4]]: note that the columns are [1, 3] and [2, 4]. We decompose [1, 3] to give (1 e1 + 3 e2) and (2 e1 + 4 e2). The corresponding element in the tensor product is (1 e1 ⊗ 2 e1 + 1 e1 ⊗ 4 e2 + 3 e2 ⊗ 2 e1 + 3 e2 ⊗ 4 e2), which we simplify to (2 e1 ⊗ e1 + 4 e1 ⊗ e2 + 6 e2 ⊗ e1 + 12 e2 ⊗ e2). Therefore: **det** [[1, 2], [3, 4]] = **det**(1 e1 + 3 e2, 2 e1 + 4 e2) = **det**(2 e1 ⊗ e1 + 4 e1 ⊗ e2 + 6 e2 ⊗ e1 + 12 e2 ⊗ e2) = **det**(2 e1 ⊗ e1) + **det**(4 e1 ⊗ e2) + **det**(6 e2 ⊗ e1) + **det**(12 e2 ⊗ e2) = 2 **det**(e1 ⊗ e1) + 4 **det**(e1 ⊗ e2) + 6 **det**(e2 ⊗ e1) + 12 **det**( e2 ⊗ e2) = 2 (0) + 4 (1) + 6 (-1) + 12 (0) = 4 - 6 = -2 Now it remains to prove that the formula for finding the parity of the permutation is valid. What my code does is essentially find the number of inversions, i.e. the places where an element on the left is bigger than an element on the right (not necessarily consecutively). For example, in the permutation 3614572, there are 9 inversions (31, 32, 61, 64, 65, 62, 42, 52, 72), so the permutation is odd. The justification is that each transposition (swapping two elements) either adds one inversion or takes away one inversion, swapping the parity of the number of inversions, and the parity of the permutation is the parity of the number of transpositions needed to achieve the permutation. Therefore, in conclusion, our formula is given by: ## Why it works -- non-mathy version ![](https://i.stack.imgur.com/pfOYs.gif) where σ is a permutation of 𝕊*n* the group of all permutations on *n* letters, and **sgn** is the sign of the permutation, AKA (-1) raised to the parity of the permutation, and *a**ij* is the (*ij*)th entry in the matrix (*i* down, *j* across). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ ~~15~~ ~~12~~ 10 bytes ``` Ḣ×Zß-Ƥ$Ṛḅ- ``` Uses [Laplace expansion](https://en.wikipedia.org/wiki/Laplace_expansion "Laplace expansion - Wikipedia"). *Thanks to @miles for golfing off ~~3~~ 5 bytes!* [Try it online!](https://tio.run/##PVNLit1ADNznFD6AG7ol9e8oifEym2EuMNuBEMgFAtkEQpZzgJf1g9zj5SKOqmTP4jW23FUqVek9fX5@fjmOx@3bp/vP9Pf3/fvj9uvx58fj9iUd96//Xt8@Hse2bSb7vn5Ytk3WRfd12cq62Fnyx6tq61LXpeGxr8tYl3nd0XUpXhIjePrbCUkOcFg@L2p3rlSq4C4vp9lRmQ4oowbE2ZJGXdrVImd/F5x1QF2oTBPlWnG3BbwBOJxDFEKGoCo6AEdZhwvSeY1s6mLMCVSdSvBROmdMNvEJQooq4ZNnfDSUjIKa36gQoiWQauhRvA4KyU5fMjVLdzrN0GjNaAMe5V0OQM1/apBDVtOG@exUBVgbZHR5HS6owgEzzlrqpDI0KsSHbnOM9owrDaqgxAzUKogpgoikm@N4JCvhHPyEVO0xh02wAQf2wmBNsAhSz1m8ZQjHAvXB5NmuKzpHhgPm4UgAY1416i9UIvCjXDqQ4qkzRs1QgfSSklomTl6xGUExdOyXYHEaFYlf6DP4QdlonzBCIQM4y7XfaOevRquhzqJD5lZg18MTGhbhKjeGkzqlAW3UTf81lzMAOE9n8FIGbM@xx5YhZHKrMLpybsolk8QfTJgz2pSIWSb7tPijuA0l6DCXMUuHMy5uV4ForfMkw16FD6NCHYYTueZ2X8a@7/8B "Jelly – Try It Online") ### How it works ``` Ḣ×Zß-Ƥ$Ṛḅ- Main link. Argument: M (matrix / 2D array) Ḣ Head; pop and yield the first row of M. $ Combine the two links to the left into a monadic chain. Z Zip/transpose the matrix (M without its first row). ß-Ƥ Recursively map the main link over all outfixes of length 1, i.e., over the transpose without each of its rows. This yields an empty array if M = [[x]]. × Take the elementwise product of the first row and the result on the right hand. Due to Jelly's vectorizer, [x] × [] yields [x]. Ṛ Reverse the order of the products. ḅ- Convert from base -1 to integer. [a] -> (-1)**0*a [a, b] -> (-1)**1*a + (-1)**0*b = b - a [a, b, c] -> (-1)**2*a + (-1)**1*b + (-1)**0*c = c - b + a etc. ``` [Answer] # [R](https://www.r-project.org/), 3 bytes *Trivial Solution* ``` det ``` [Try it online!](https://tio.run/##K/r/PyW15P9/AA "R – Try It Online") # [R](https://www.r-project.org/), ~~94~~ ~~92~~ 89 bytes *re-implemented solution* *outgolfed by [Jarko Dubbeldam](https://codegolf.stackexchange.com/questions/147668/determinant-of-an-integer-matrix/147797#147797)* ``` d=function(m)"if"(x<-nrow(m),m[,1]%*%sapply(1:x,function(y)(-1)^y*-d(m[-y,-1,drop=F])),1) ``` [Try it online!](https://tio.run/##PcrLCoMwEEbhdxGEGflnMamrUrd9CbEgBiFgLqSWJk@fuuryfJzcmp32T9hOFwN57tzeUXlIyPF7JfwMXfqhf68pHZX0XvC/K5Mov@oglvwsFaKwOabpuTBDuV28ntkV2shAccPIMDDM7Qc "R – Try It Online") Recursively uses expansion by minors down the first column of the matrix. ``` f <- function(m){ x <- nrow(m) # number of rows of the matrix if(sum(x) > 1){ # when the recursion reaches a 1x1, it has 0 rows # b/c [] drops attributes minor <- function(y){ m[y] * (-1)^y * -d(m[-y,-1]) # recurse with the yth row and first column dropped } minors <- sapply(1:x,minor) # call on each row sum(minors) # return the sum } else { m # return the 1x1 matrix } } ``` [Answer] # [Haskell](https://www.haskell.org/), 71 bytes *-3 bytes thanks to Lynn. Another one bytes the dust thanks to Craig Roy.* ``` f[]=1 f(h:t)=foldr1(-)[v*f[take i l++drop(i+1)l|l<-t]|(i,v)<-zip[0..]h] ``` [Try it online!](https://tio.run/##VVTRjhMxDHznK/LYcptTYnuzCeI@AfEBVR8qoFx1BU7HiQfEt1M841ZaKjXazcbjsWecx8PPpy/n8@Vy3O0f6pvj5vHd6/bh@OP8@aVu8nb36@1x93p4@pJO6Xx39/nlx/PmdFe35z/n9/l1/2dzmn5t3@ffp@ddub/fP@4v3w6n7@khfTs8f0ib55fT99d0n47bN8l/u7Tbmez3fJn8Raake3@oU7LVtr/evtiU5ik1PC5T6lMa63M6perbYgQZ/nYNyx7koWV1WBfHzHUWnGdAHgt2hgfVPkeYI2aNfWnrVKX4nmCdO9gG6zywPc843wKiIbg7jigIdcGuaEc4trU7MR3rNpg6KXMQVYcTHJCFNWcb@ARCVZUQg2t8NGwZSTU/MYOM1ohUQ57q@4CQ4vC1kLcsDqcFPK0Z24FH@Y8SApv/1UCJyKYNddqVGUJbJ6pTXNANVXTCjDXXeZAdklXGB3fzGF0KjjQwAxszQKtAthAl1G8exyVbjQ6ir6CrS9RiA2iIA3qlyCYwhsyrejxtkIexlk4nMOWiyB56djQRSwYAalZjDZVsBD2pNy5Q9Mo1yi1gAhWzEloGVh6xEYLRAPCbwESNjMQPLCPwAdnYQqGUQgRg1rXvkdK3jC0HQ4sshQ7BDERv2LgQWukeVuuwhmgjd@qgpV6FgALsDl5qR/tL@NoKyAw6DOUraydlIkkMnlBvpKkhtwzmaTE43ooacKjNqKmHUza6rIK0zuMKBn9FL/oMdihO5Fa396av@gK6dJ02HilXdE8KlWFC@sVpYymRpNKcVThLLXqKQMhTB7MoLQqTDVxBHIC6UCjMFec3o2EzlgYGnBWf4lun/OqIbCVsRxpz@AfGZXral7oq2lbRMb3S5ChnXioqRCS1jhEaINzbzTLGW0kGhWssprBiXFS8iqry0uOw9LgI2LGK/FGfx@MDqxSQjhFnqpjWhTbA8NNiY4kCje1E0YHAi1cwuTQONcwQpPLu7pFtcHBKjDosTcIWty5oR7X1BuiartIJP3Q6l40UOgu1VwyUUFeDMrn5PZf2l7@fjufD15@X/PEf "Haskell – Try It Online") *Added `-O` flag for optimization purposes. It is not necessary.* ## Explanation (outdated) `f` recursively implements cofactor expansion. ``` f[[x]]=x ``` This line covers the base case of a **1** × **1** matrix, in which case the determinant is `mat[0, 0]`. ``` f(h:t)= ``` This uses Haskell's *pattern matching* to break the matrix into a *head* (the first row) and a *tail* (the rest of the matrix). ``` [ |(i,v)<-zip[0..]h] ``` Enumerate the head of the matrix (by zipping the infinite list of whole numbers and the head) and iterate over it. ``` (-1)*i*v ``` Negate the result based on whether its index is even since the calculation of the determinant involves alternating addition and subtraction. ``` [take i l++drop(i+1)l|l<-t] ``` This essentially removes the **ith** column of the tail by taking **i** elements and concatenating it with the row with the first **(i + 1)th** elements dropped for every row in the tail. ``` *f ``` Calculate the determinant of the result above and multiply it with the result of `(-1)*i*v`. ``` sum ``` Sum the result of the list above and return it. [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), between 14 and 42 bytes We've had a [3-byte built-in](https://codegolf.stackexchange.com/a/147671/66104) and a [53-byte solution](https://codegolf.stackexchange.com/a/147752/66104) that completely avoids built-ins, so here are some weirder solutions somewhere in between. The Wolfram Language has [a lot of](http://reference.wolfram.com/language/guide/MatrixDecompositions.html) very intense functions for decomposing matrices into products of other matrices with simpler structure. One of the simpler ones (meaning I've heard of it before) is Jordan decomposition. Every matrix is similar to a (possibly complex-valued) upper triangular matrix made of diagonal blocks with a specific structure, called the Jordan decomposition of that matrix. Similarity preserves determinants, and the determinant of a triangular matrix is the product of the diagonal elements, so we can compute the determinant with the following **42 bytes**: ``` 1##&@@Diagonal@Last@JordanDecomposition@#& ``` The determinant is also equal to the product of the eigenvalues of a matrix, with multiplicity. Luckily, Wolfram's eigenvalue function keeps track of multiplicity (even for non-diagonalisable matrices), so we get the following **20 byte** solution: ``` 1##&@@Eigenvalues@#& ``` The next solution is kind of cheating and I'm not really sure why it works. The Wronskian of a list of *n* functions is the determinant of the matrix of the first *n*-1 derivatives of the functions. If we give the `Wronskian` function a matrix of integers and say that the variable of differentiation is 1, somehow it spits out the determinant of the matrix. It's weird, but it doesn't involve the letters "`Det`" and it's only **14 bytes**… ``` #~Wronskian~1& ``` (The Casoratian determinant works as well, for 1 more byte: `#~Casoratian~1&`) In the realm of abstract algebra, the determinant of an *n* x *n* matrix (thought of as the map k → k that is multiplication by the determinant) is the *n*th exterior power of the matrix (after picking an isomorphism k → ⋀n kn). In Wolfram language, we can do this with the following **26 bytes**: ``` HodgeDual[TensorWedge@@#]& ``` And here's a solution that works for positive determinants only. If we take an *n*-dimensional unit hypercube and apply a linear transformation to it, the *n*-dimensional "volume" of the resulting region is the absolute value of the determinant of the transformation. Applying a linear transformation to a cube gives a parallelepiped, and we can take its volume with the following **39 bytes** of code: ``` RegionMeasure@Parallelepiped[Last@#,#]& ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` p%(l:r)=l!!0*f(tail<$>p++r)-(p++[l])%r []%_=1 p%_=0 f=([]%) ``` [Try it online!](https://tio.run/##VVTRihsxDHzPV2yhB0lvXWxJ67VL0z8o/YAQSihNezR3hNx9f1PNKIHtwTm7Xms00oz8@/D65@fpdL2eH9anT5fN9vTuXf5wXL8dnk6f3385Pz5eNmntP7vTfvNwWe32D9@3ZXX2Na@O27W/b67Ph6eXYTs8H85fh/X58vTyNnwcjpvV4H@7Ybcz2e/5MvqLjIPu/aGMgy22/fX@xcZhGoeKx3kc2jj05Tkdh@LbYgTp/nYLSx7koXlxWGfHTGUSnGdA6jN2ugeVNkWYIyaNfanLVDn7nmCdGtgG69SxPU04XwOiIrg5jigINcGuaEM4trU5Me3LNpg6KXMQVYcTHJCZNSfr@ARCRZUQnWt8NGwZSVU/MYGMlohUQ57i@4CQ7PAlk7fMDqcZPK0a24FH@Y8SAqv/q4ESkU0r6rQbM4TWRlSnOKMbquiEGWsuUyc7JCuMD@7mMTpnHKlgBjZmgFaBbCFKqF89jkuyEh1EX0FX56jFOtAQB/RCkU1gDJkW9XjaIA9jzY1OYMpZkT30bGgilgQA1KzGGgrZCHpS7lyg6I1rlJvBBComJbR0rDxiPQSjAeA3gYkqGYkfmHvgA7KyhUIphQjALEvfI6VvGVsOhhZZMh2CGYjesHEhtNI9rNZhDdFG7tRBc7kJAQXYHbyUhvbn8LVlkOl0GMpX1k7KRJIYPKHeSFNCbunMU2NwvBUl4FCbUVMPp2x0WQFpnfoNDP6KXrQJ7FCcyL1u701b9AV06TqtPJJv6J4UKsOE9IvTxpIjSaE5i3CWavQUgZCndGZRWhQm67iCOABlplCYK85vQsMmLBUMOCs@xfdO@dUR2XLYjjSm8A@My/S0L3VVtK2gY3qjyVFOvFRUiEhqDSPUQbjVu2WMt5J0CldZTGbFuKh4FRXlpcdhaXERsGMF@aM@j8cHVikgHSPOVDGtM22A4afF@hwFGtuJogOBF69gcmkcapggSOHd3SJb5@DkGHVYmoQtbl3QjmrLHdA1XaQTfmh0LhspdBZqLxgooa4GZVL1e27YX//@OJ4Ov16v6ds/ "Haskell – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 98 bytes ``` f=m=>(l=len(m))-1?sum((-1)**i*m[0][i]*f([[m[k][j]for k:1..l]for j:0..l if j-i])for i:0..l):m[0][0] ``` [Try it online!](https://tio.run/##HYxBCsMgEEWvMktHNGiTUirYHmSYZQVNjMGm57fR3fsP3j9qOcveWvDZv8Tmt88uMqK27@8vC6EtShllJsMUWQZBlGllShxKhdXZadoGJmcuhBgg6cjYVRwK3YgNt6PG/RT9ws4K7EPBbWEFZJ/XUjB31ncFiwLDjNj@ "Proton – Try It Online") -3 bytes thanks to Mr. Xcoder -3 bytes thanks to Erik the Outgolfer -1 byte thanks to S.S. Anne Expansion over the first row [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` œcL’$ṚÑ€ J-*×Ḣ€×ÇSµḢḢ$Ṗ? ``` [Try it online!](https://tio.run/##y0rNyan8///o5GSfRw0zVR7unHV44qOmNVxeulqHpz/csQjIPjz9cHvwoa1ADhABVUyz////f3S0obGOgqG5joKRSayOQrShJZCno2AMYuua6iiY6CgYxMYCAA "Jelly – Try It Online") # Explanation ``` œcL’$ṚÑ€ Helper Link; get the next level of subdeterminants (for Laplace Expansion) œc Combinations without replacement of length: L’$ Length of input - 1 (this will get all submatrices, except it's reversed) Ṛ Reverse the whole thing Ñ€ Get the determinant of each of these J-*×Ḣ€×ÇSµḢḢ$Ṗ? Main Link ? If the next value is truthy Ṗ Remove the last element (truthy if the matrix was at least size 2) J-*×Ḣ€×ÇSµ Then expand ḢḢ$ Otherwise, get the first element of the first element (m[0][0] in Python) J [1, 2, ..., len(z)] -* (-1 ** z) for each z in the length range × Vectorizing multiply with Ḣ€ The first element of each (this gets the first column); modifies each row (makes it golfier yay) ×Ç Vectorizing multiply with the subdeterminants S Sum ``` -2 bytes thanks to user202729's solution [Answer] # [R](https://www.r-project.org/), 32 bytes ``` function(m)Re(prod(eigen(m)$va)) ``` Uses Not a Tree's algorithm of taking the eigenvalues of the matrix and taking the real part of their product. [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jVzMoVaOgKD9FIzUzPRXEVylL1NT8n2ubm1hSlFmhUZyYW5CTqmFoYGCgowAkNUEkCGtyFRRl5pVopKSWAHXBeGkg9n8A "R – Try It Online") [Answer] # C, ~~ 176 ~~ 125 bytes *Thanks to @ceilingcat for golfing 42 bytes, and thanks to both @Lynn and @Jonathan Frech for saving a byte each!* ``` d(M,n)int*M;{int i=n--,s=*M*!n,c,T[n*n];for(;i--;s+=M[i]*(1-i%2*2)*d(T,n))for(c=n*n;c--;T[c]=M[n-~c+c/n+(c%n>=i)]);return s;} ``` Calculates the determinant using the [Laplace expansion](https://en.wikipedia.org/wiki/Laplace_expansion) along the first row. [Try it online!](https://tio.run/##fZDBasMwDIbvfQqtULBdmTW2kyaY7A1y6y3LYTjt8GHeSLJT6V49k5oxGB3NwcHyr@@THfRrCPPciwaTjGlSjT/TD2KdtMaxVo16SBjw0CaVOn96H4SPWvtxWzdt7JTIdNwYZaTqxYEQkhOhprAPFDu0oaNg0l9hGx7TVoRNeqqj7KQfjtPnkGD0l5mFby8xCbk6r4A@LkzHccraDmo4O3Px1/rHQCcnsd70z2mN0ItrCCGT0q/@dJql0yBYOkZw9wiUMjcEuxCod4E4hByhQNgjlAjVPSDF7Q3QLUC7J57OcpY6gupqz/uKr1GSQefUre1SNcU9jftPk//MvdsRwPCal9fpM3ZxMWdLVvBasKUkobEV@3koW3IjF23Jhur29X8nIIbjCS7zNw) **Unrolled:** ``` d(M, n)int*M; { int i=n--, s=*M*!n, c, T[n*n]; for (; i--; s+=M[i]*(1-i%2*2)*d(T,n)) for (c=n*n; c--;) T[c] = M[n-~c+c/n+(c%n>=i)]; return s; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes Finally I've done writing my non-builtin solution in a golfing language! ``` ḣ⁹’’¤;ṫḊ€Ç×⁸ị@⁹’¤¤ḷ/¤ çЀ⁸J‘¤µJ-*×NS ÇḢḢ$Ṗ? ``` Thanks to *HyperNeutrino* for saving a byte! [Try it online!](https://tio.run/##y0rNyan8///hjsUKjxp3PmqYCUSHlihYP9y5WuHhjq5HTWsUDrcrHJ4OlN3xcHe3A0TRoSWHljzcsV3/0BKuw8sPTwCpAsp7PWqYAdR7aKuCl4KuFkiTn0IwF1D7wx2LgEhF4eHOafb///@PNtNRMAeiWB2FaBMw0wzEBIoCeRaxAA "Jelly – Try It Online") (spaced code for clarity) *terribly long way to remove n'th elements from a list, will improve later* --- This answer had been outgolfed by answers of HyperNeutrino, Dennis and Leaky Nun. Jelly is *very* popular as a golfing language. Quick explanation: ``` ÇḢḢ$Ṗ? Main link. ? If Ṗ after remove the last element, the value is not empty (truthy) Ç then execute the last link ḢḢ$ else get the element at index [1, 1]. çЀ⁸J‘¤µJ-*×NS Helper link 1, take input as a matrix. çЀ Apply the previous link, thread right argument to ⁸J‘¤ the range [2, 3, ..., n+1] µ With the result, J-* generate the range [-1, 1, -1, 1, ...] with that length ×N Multiply by negative S Sum ḣ⁹’’¤;ṫḊ€Ç×⁸ị@⁹’¤¤ḷ/¤ Helper link 2, take left input as a matrix, right input as a number in range [2..n+1] ḣ ⁹’’¤ Take head ρ-2 of the matrix ; concatenate with ṫ tail ρ (that is, remove item ρ-1) Ḋ€ Remove first column Ç Calculate determinant of remaining matrix × ¤ multiply by ḷ/ the first column, ị@ row # ⁹’¤ ρ-1 (just removed in determinant calculation routine) of ⁸ ¤ the matrix. ``` [Answer] ## CJam (50 45 bytes) ``` {:A_,{1$_,,.=1b\)/:CAff*A@zf{\f.*1fb}..-}/;C} ``` This is an anonymous block (function) which takes a 2D array on the stack and leaves an integer on the stack. [Online test suite](http://cjam.aditsu.net/#code=q'%2C-~%5D2%2F%7B~%3AE%3B%0A%0A%7B%3AA_%2C%7B1%24_%2C%2C.%3D1b%5C)%2F%3ACAff*A%40zf%7B%5Cf.*1fb%7D..-%7D%2F%3BC%7D%0A%0A~%5B_%5CE%3D%5B%22Err%22%22Ok%22%5D%3D%5Dp%7D%2F&input=%5B%5B42%5D%5D%2042%0A%5B%5B2%2C%203%5D%2C%20%5B1%2C%204%5D%5D%205%0A%5B%5B1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209%5D%5D%200%0A%5B%5B13%2C%2017%2C%2024%5D%2C%20%5B19%2C%201%2C%203%5D%2C%20%5B-5%2C%204%2C%200%5D%5D%201533%0A%5B%5B372%2C%20-152%2C%20244%5D%2C%20%5B-97%2C%20-191%2C%20185%5D%2C%20%5B-53%2C%20-397%2C%20-126%5D%5D%2046548380%0A%5B%5B100%2C%20-200%2C%2058%2C%204%5D%2C%20%5B1%2C%20-90%2C%20-55%2C%20-165%5D%2C%20%5B-67%2C%20-83%2C%20239%2C%20182%5D%2C%20%5B238%2C%20-283%2C%20384%2C%20392%5D%5D%20571026450%0A%5B%5B432%2C%2045%2C%20330%2C%20284%2C%20276%5D%2C%20%5B-492%2C%20497%2C%20133%2C%20-289%2C%20-28%5D%2C%20%5B-443%2C%20-400%2C%2056%2C%20150%2C%20-316%5D%2C%20%5B-344%2C%20316%2C%2092%2C%20205%2C%20104%5D%2C%20%5B277%2C%20307%2C%20-464%2C%20244%2C%20-422%5D%5D%20-51446016699154%0A%5B%5B416%2C%2066%2C%20340%2C%20250%2C%20-436%2C%20-146%5D%2C%20%5B-464%2C%2068%2C%20104%2C%20471%2C%20-335%2C%20-442%5D%2C%20%5B159%2C%20-407%2C%20310%2C%20-489%2C%20-248%2C%20370%5D%2C%20%5B62%2C%20277%2C%20446%2C%20-325%2C%2047%2C%20-193%5D%2C%20%5B460%2C%20460%2C%20-418%2C%20-28%2C%20234%2C%20-374%5D%2C%20%5B249%2C%20375%2C%20489%2C%20172%2C%20-423%2C%20125%5D%5D%2039153009069988024%0A%5B%5B-246%2C%20-142%2C%20378%2C%20-156%2C%20-373%2C%20444%5D%2C%20%5B186%2C%20186%2C%20-23%2C%2050%2C%20349%2C%20-413%5D%2C%20%5B216%2C%201%2C%20-418%2C%2038%2C%2047%2C%20-192%5D%2C%20%5B109%2C%20345%2C%20-356%2C%20-296%2C%20-47%2C%20-498%5D%2C%20%5B-283%2C%2091%2C%20258%2C%2066%2C%20-127%2C%2079%5D%2C%20%5B218%2C%20465%2C%20-420%2C%20-326%2C%20-445%2C%2019%5D%5D%20-925012040475554%0A%5B%5B-192%2C%20141%2C%20-349%2C%20447%2C%20-403%2C%20-21%2C%2034%5D%2C%20%5B260%2C%20-307%2C%20-333%2C%20-373%2C%20-324%2C%20144%2C%20-190%5D%2C%20%5B301%2C%20277%2C%2025%2C%208%2C%20-177%2C%20180%2C%20405%5D%2C%20%5B-406%2C%20-9%2C%20-318%2C%20337%2C%20-118%2C%2044%2C%20-123%5D%2C%20%5B-207%2C%2033%2C%20-189%2C%20-229%2C%20-196%2C%2058%2C%20-491%5D%2C%20%5B-426%2C%2048%2C%20-24%2C%2072%2C%20-250%2C%20160%2C%20359%5D%2C%20%5B-208%2C%20120%2C%20-385%2C%20251%2C%20322%2C%20-349%2C%20-448%5D%5D%20-4248003140052269106%0A%5B%5B80%2C%20159%2C%20362%2C%20-30%2C%20-24%2C%20-493%2C%20410%2C%20249%2C%20-11%2C%20-109%5D%2C%20%5B-110%2C%20-123%2C%20-461%2C%20-34%2C%20-266%2C%20199%2C%20-437%2C%20445%2C%20498%2C%2096%5D%2C%20%5B175%2C%20-405%2C%20432%2C%20-7%2C%20157%2C%20169%2C%20336%2C%20-276%2C%20337%2C%20-200%5D%2C%20%5B-106%2C%20-379%2C%20-157%2C%20-199%2C%20123%2C%20-172%2C%20141%2C%20329%2C%20158%2C%20309%5D%2C%20%5B-316%2C%20-239%2C%20327%2C%20-29%2C%20-482%2C%20294%2C%20-86%2C%20-326%2C%20490%2C%20-295%5D%2C%20%5B64%2C%20-201%2C%20-155%2C%20238%2C%20131%2C%20182%2C%20-487%2C%20-462%2C%20-312%2C%20196%5D%2C%20%5B-297%2C%20-75%2C%20-206%2C%20471%2C%20-94%2C%20-46%2C%20-378%2C%20334%2C%20407%2C%20-97%5D%2C%20%5B-140%2C%20-137%2C%20297%2C%20-372%2C%20228%2C%20318%2C%20251%2C%20-93%2C%20117%2C%20286%5D%2C%20%5B-95%2C%20-300%2C%20-419%2C%2041%2C%20-140%2C%20-205%2C%2029%2C%20-481%2C%20-372%2C%20-49%5D%2C%20%5B-140%2C%20-281%2C%20-88%2C%20-13%2C%20-128%2C%20-264%2C%20165%2C%20261%2C%20-469%2C%20-62%5D%5D%20297434936630444226910432057) ### Dissection This implements the [Faddeev-LeVerrier algorithm](https://en.wikipedia.org/wiki/Faddeev%E2%80%93LeVerrier_algorithm), and I think it's the first answer to take that approach. > > The objective is to calculate the coefficients \$c\_k\$ of the characteristic polynomial of the \$n\times n\$ matrix \$A\$, > $$p(\lambda )\equiv \det(\lambda I\_{n}-A)=\sum \_{k=0}^{n}c\_{k}\lambda ^{k}$$ > where, evidently, \$c\_n = 1\$ and \$c\_0 = (−1)^n \det A\$. > > > The coefficients are determined recursively from the top down, by dint of the auxiliary matrices \$M\$, > $$\begin{aligned}M\_{0}&\equiv 0&c\_{n}&=1\qquad &(k=0)\\M\_{k}&\equiv AM\_{k-1}+c\_{n-k+1}I\qquad \qquad &c\_{n-k}&=-{\frac {1}{k}}\mathrm {tr} (AM\_{k})\qquad &k=1,\ldots ,n~.\end{aligned}$$ > > > The code never works directly with \$c\_{n-k}\$ and \$M\_k\$, but always with \$(-1)^k c\_{n-k}\$ and \$(-1)^{k+1}AM\_k\$, so the recurrence is $$(-1)^k c\_{n-k} = \frac1k \mathrm{tr} ((-1)^{k+1} AM\_{k}) \\ (-1)^{k+2} AM\_{k+1} = (-1)^k c\_{n-k}A - A((-1)^{k+1}A M\_k)$$ ``` { e# Define a block :A e# Store the input matrix in A _, e# Take the length of a copy { e# for i = 0 to n-1 e# Stack: (-1)^{i+2}AM_{i+1} i 1$_,,.=1b e# Calculate tr((-1)^{i+2}AM_{i+1}) \)/:C e# Divide by (i+1) and store in C Aff* e# Multiply by A A@ e# Push a copy of A, bring (-1)^{i+2}AM_{i+1} to the top zf{\f.*1fb} e# Matrix multiplication ..- e# Matrix subtraction }/ ; e# Pop (-1)^{n+2}AM_{n+1} (which incidentally is 0) C e# Fetch the last stored value of C } ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 28 bytes ``` @(x)round(prod(diag(qr(x)))) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzKL80L0WjoCg/RSMlMzFdo7AIKAgE/9M0oqONzY10FHQNTYGkkYlJrLVCtK6lOUjE0lBHwdDCFCxiagwUMYaIG5nFxmr@BwA "Octave – Try It Online") This uses the [QR decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a matrix **X** into an orthgonal matrix **Q** and an upper triangular matrix **R**. The determinant of **X** is the product of those of **Q** and **R**. An orthogonal matrix has unit determinant, and for a triangular matrix the determinant is the product of its diagonal entries. Octave's `qr` function called with a single output gives **R**. The result is rounded to the closest integer. For large input matrices, floating-point inaccuracies may produce an error exceeding `0.5` and thus produce a wrong result. [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes / 5 bytes ### With built-in function ``` &0| ``` [Try it online!](https://tio.run/##y00syfn/X82g5v//aGNzIx0FXUNTIGlkYmKtoGtpDuJbGuooGFqYAvmmxkC@MUTUyCwWAA) ### Without built-in *Thanks to [Misha Lavrov](https://codegolf.stackexchange.com/users/74672/misha-lavrov) for pointing out a mistake, now corrected* ``` YvpYo ``` [Try it online!](https://tio.run/##y00syfn/P7KsIDL///9oY3MjHQVdQ1MgaWRiYq2ga2kO4lsa6igYWpgC@abGQL4xRNTILBYA) This computes the determinant as the product of the eigenvalues, rounded to the closest integer to avoid floating-point inaccuracies. ``` Yv % Implicit input. Push vector containing the eigenvalues p % Product Yo % Round. Implicit display ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 30 bytes ``` @(x)-prod(diag([~,l,~]=lu(x))) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTt6AoP0UjJTMxXSO6TidHpy7WNqcUKK6p@T9NIzra2NxIR0HX0BRIGpmYxForROtamoNELA11FAwtTMEipsZAEWOIuJFZbKzmfwA "Octave – Try It Online") or, the boring 4 byte solution (saved 6 bytes thanks to Luis Mendo (forgot the rules regaring builtin functions)): ``` @det ``` ### Explanation: Coming up! :) [Answer] # TI-Basic, 2 bytes ``` det(Ans ``` Ah, well. [Please don't upvote trivial answers.](https://codegolf.meta.stackexchange.com/questions/10127/how-can-we-help-users-who-are-put-off-by-the-use-of-golfing-languages/10132#10132) As a high school student (who's forced to own one of these calculators), this function is hella useful so... [Answer] # Haskell, 62 bytes ``` a#((b:c):r)=b*d(a++map tail r)-(a++[c])#r _#_=0 d[]=1 d l=[]#l ``` [Try it online!](https://tio.run/##VVTRahsxEHz3Vwj8Yrd3Rdrd00kBf0K/wJjgxIWGOiG4@X93Z/YM10CEpdPOzu7M6vf5759f1@v9ft7udi9Pr/un2/7w8u2yO3///n7@TF/nt2u67Ufsj6@n/fa2ed4@H/LmcjwdyuaSrofjaXu9v5/fPtIhecjPtPu8vX18pR/pst8k/zum49HkdOJm8I0MSU/@owzJVse@fXyxIU1Dqvg5D6kNqa/v6ZCKH4sRpPtuCRs9yEPz6rLOjjmWSXCfAWOfcdI9qLQpwhxx1DiXuk6Vs58J1qmBbbAeO46nCfdrQFQEN8cRBaEmOBVtCMexNiemfd0GUydlDqLqcIILMrPm0To@gVBRJUTnGh8NR0ZS1W9MIKMlItWQp/g5ICQ7fMnkLbPDaQZPq8Z24Kf8RwmB1f/VQInIphV12sIMobUR1SnO6IYqOmHGmsvUyQ7JCuODu3mMzhlXKpiBjRmgVSBbiBLqV4/jMlqJDqKvoKtz1GIdaIgDeqHIJjCGTKt6PG2Qh7HmRicw5azIHno2NBHLCADUrMYaCtkIelIeXKDowjXKzWACFUcltHSsvGI9BKMB4DeBiSoZiV@Ye@ADsrKFQimFCMAsa98jpR8ZWw6GFlkyHYIZiN6wcSG00j2s1mEN0Ubu1EFzWYSAAuwONqWh/Tl8bRlkOh2G8pW1kzKRJAZPqDfSlJBbOvPUGBxvRQk41GbU1MMpG11WQFqnvoDBX9GLNoEdihN51O29aau@gC5dp5VX8oLuSaEyTEi/OG0sOZIUmrMIZ6lGTxEIeUpnFqVFYbKOJ4gDUGYKhbni/I5o2ISlggFnxaf40Sl/OiJbDtuRxhT@gXGZnvalroq2FXRMF5oc5ZGPigoRSa1hhDoIt/qwjPFVkk7hKovJrBgPFZ@ionz0OCwtHgJ2rCB/1Ofx@MAqBaRjxJkqpnWmDTD8tFifo0BjO1F0IPDhFUwujUMNRwhS@Ha3yNY5ODlGHZYmYYtXF7Sj2vIAdE1X6YQfGp3LRgqdhdoLBkqoq0GZsfo7l073fw "Haskell – Try It Online") (Footer with test cases taken from @totallyhuman's solution.) `d` computes the determinant using a Laplace expansion along the first column. Needs three bytes more than the [permanent](https://codegolf.stackexchange.com/a/96837/56725). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ 52 bytes ``` 1##&@@@(t=Tuples)@#.Signature/@t[Range@Tr[1^#]&/@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vfUFlZzcHBQaPENqS0ICe1WNNBWS84Mz0vsaS0KFXfoSQ6KDEvPdUhpCjaME45Vk3fAUj8DyjKzCuJBuqPrq5O1EnSSa7VqU7RSdVJA9LpOhk6mbW1sbFcEFUuqSX4VP0HAA "Wolfram Language (Mathematica) – Try It Online") Unfortunately, computing the determinant of an *n* by *n* matrix this way uses O(*n**n*) memory, which puts large test cases out of reach. ## How it works The first part, `1##&@@@(t=Tuples)@#`, computes all possible products of a term from each row of the given matrix. `t[Range@Tr[1^#]&/@#]` gives a list of the same length whose elements are things like `{3,2,1}` or `{2,2,3}` saying which entry of each row we picked out for the corresponding product. We apply `Signature` to the second list, which maps even permutations to `1`, odd permutations to `-1`, and non-permutations to `0`. This is precisely the coefficient with which the corresponding product appears in the determinant. Finally, we take the dot product of the two lists. --- If even `Signature` is too much of a built-in, at **73 bytes** we can take ``` 1##&@@@(t=Tuples)@#.(1##&@@Order@@@#~Subsets~{2}&/@t[Range@Tr[1^#]&/@#])& ``` replacing it by `1##&@@Order@@@#~Subsets~{2}&`. This computes `Signature` of a possibly-permutation by taking the product of `Order` applied to all pairs of elements of the permutation. `Order` will give `1` if the pair is in ascending order, `-1` if it's in descending order, and `0` if they're equal. --- *-1 byte thanks to @user202729* [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` f=lambda m,p=[]:m[0][0]*f(zip(*p+m[1:])[1:])-f(m[1:],p+m[:1])if m else[]==p ``` [Try it online!](https://tio.run/##TY/RqsIwEETf@xXz2Ho3YNLW2kK@JOyDl9twA6YG2xf9@bqNioYQdk5mBjbdlv/LZNbV2/Mp/v6dEClZx0N0e5a78@U9pHKXfqLTA1f5Ub7MijY6aK6CR8R4nkfH1qZ1GedlhoUrIMe5xjDTazaEmglOE5oPFfX@aAgt4bCNHeFI6L9sNUELNU2u6EW9Ukoyktx/vHUnjUq3ZrNnv@q7jfSS0cf2mZJCVT@5OTAXXBT@ckVAmJDXGHJduoZpgS9DtT4A "Python 2 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~195 192 177~~ 176 bytes ``` long d(int[][]m){long D=0;for(int i=m.length,l=i-1,t[][]=new int[l][l],j,k;i-->0;D+=m[0][i]*(1-i%2*2)*(l<1?1:d(t)))for(j=l*l;j-->0;)t[j/l][k=j%l]=m[1+j/l][k<i?k:k+1];return D;} ``` [Try it online!](https://tio.run/##rVZNb9tGEL3nV8wlgGhzbe4Hl7tR1Fx87SlHQQc1Ul1KlGTYdIrC0G93Z97IRoCsiqKqIYjycjjz5r354Gb5fWkOD@v9ZrV9/TYsn57o12W/f/lA9DQux/4bvQ6H/T2tJv1@nC/mi131goO7WTP9/fAox9TPdjfDen8//lEPs97YGpaz/fpPkqeGBX/qTb2d9sb80kzvrme7ebOY94uriTX9R3flqqvJ8Nl@sZ9Wk7GqKnG8mQ1Xw3SDJ6pxvrllN9vZ5uOw4Kfttf7/uf@y/bS9tovp43p8ftzT3fT4SvTw/NvA0E8ZfD/0K9pxVpOv42O/v58vlpUkSPT1r6dxvbs5PI83D3xnHPaT1eQNNqegVkTvRy/BHXF2rKrpf3ThavLH@qdjW1O42Dc7OeM@1NTWFAt3uppSTfny2L4my85cKGWXayJGV8RmGBkxQGouBuE7zt/Ylr8ZSAmJyZ1YZAFjU1uEw5kYr3YuXk5M07AnJ9/UMtX8VwKm/Jgsxm0rsWMRXezELDFG58FqcgUz55MEFTOfhFufLy/d4J3CF8G8l4QcnLuuVFkmZLEPwiRZ7wFIIPOlaB7EJIAoaqM81Aob3ha9@4C8rBgSIrlGgNmmRK/rBAX5RmQNMWiByG/3PxCjICjKxQcQA@jBR1EylOkBCopJQQtVnZV8vcgfQklX24LAIGlw7oghnBoXxI3vmsJDUWVTCkIQSN4JVRwQzVCcGBE64GKCTaqbZOaFNt8VWQ4ZLHdoaYht0ZLBefnt2ou55kyVU4d8E/odKXUe6RXnT4JAejHA0iI9L4A5vRID7qSqNOaJAX/qX6WtKFCjDEiPGA9gLiMqHgq5WPpoVK5ii8pBkIgsHaq2y0V4SQVCtTh0iouoHGhrL5/pkqPIFlCW0DZoGo0HkVZzLaFD@RjtN4/mh0CMMcBlAIWlcvUN3J46VguVoDNObBLPoSlOx9BAM5MxNyCZh1gnshDVFbeQa3RCCEirPeUyQMKlqMLy2WJUB5OgTYKuRtVjCJAFFb7N5ahof5UvtdAfi9K5N85Z0PSDlLe3/05MtfsxGIiTqZqJao@pYDDFgZmTQwNZjC@IzbQJAY0g/9kd322UToxUrC/MBoc5aDOwex06GAgZIuRYdGcxNFhBmOqqMRC8xXfMUBMd1cV3ZXmxnkHX6FSAhq12LAYS8GIsaWUz1zhH3/lzyWLRGN25Hm1pUB4hYfXkgLUc37qQk8Xaz23RnY5@Bg@CW@iO4WK9vplgaCZdVqgEC7xnuOM4YqoMOvQAdgk3AnDpzO@0H7BpUOz8MnSGuwBloZ26xpsVOWwAbSytU4OisRaW6Qy63Gqp6SrBgMRI0TC6tunEpn0PxgX5T@hcQvyEprPQ1OGlB9zaCE4jZjdKx0Re9OrtNBKPH46vfwM "Java (OpenJDK 8) – Try It Online") Like many other answers, this also uses the Laplace formula. A slightly less golfed version: ``` long d(int[][]m){ long D=0; int i=m.length,l=i-1,t[][]=new int[l][l],j,k for(;i-->0;) for(j=l*l;j-->0;) t[j/l][k=j%l]=m[1+j/l][k<i?k:k+1]; D+=m[0][i]*(1-i%2*2)*(l<1?1:d(t)); return D; } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 3 bytes ``` Det ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yW15H9AUWZeSXRadDVXNaehDqeRDqdxrQ6QbaLDaarDaQZmm@twWuhwWtZy1cbG/gcA "Wolfram Language (Mathematica) – Try It Online") Per the [meta consensus](https://codegolf.meta.stackexchange.com/questions/13128/non-trivial-answers-get-too-few-upvotes), mainly upvote nontrivial solutions that take effort to write. [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes *-12 bytes thanks to Lynn.* Port of [my Haskell answer](https://codegolf.stackexchange.com/a/147709/68615). ``` f=lambda m:sum((-1)**i*v*f([j[:i]+j[i+1:]for j in m[1:]])for i,v in enumerate(m[0]))if m else 1 ``` [Try it online!](https://tio.run/##TY/RroIwEETf@Yp9pLhNbAEREr@k2QdubptbYtFANfHrcVs13j7tnM5MMtdH/LvMetvc6TyGn98RwrDeQllKJarKV/fKlWYyg6fdZPxODeQuC0zgZwiGFYmkPd4TsfMt2GWMtgxmT0J4BwHsebWgtmjXuMIJTAH8jGk0Eb5vjVATglEIzZey@nw0CC3CIZ0dwhGh/2erERRT3eSKntU7JTnDyf3XW3fcKFWrkz37Zd8l0nNGHdtXigtl/eL6QFRQUeSRaWKeMeS66@LnCK70YnsC "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~**238 bytes**~~, ~~**227 bytes**~~, ~~**224 bytes**~~, **216 bytes** ``` from functools import* from itertools import* r=range;n=len;s=sum f=lambda l:s(reduce(lambda p,m:p*m,[l[a][b]for a,b in zip(r(n(l)),j)])*(-1)**s(s(y<j[x]for y in j[x:])for x in r(n(l)))for j in permutations(r(n(l)))) ``` [Try it online!](https://tio.run/##ZVPLbttADLznK/YoGRKgJanHJvWXCD44id3asB6QZCDpz7scroyi6sELL5czHA6p8Xv5NfT8eJynoXPne/@xDMNtdpduHKZl92Lhy3Ka/g1P@@nY/zy99fvbqX@b9/O9eznvb8fu/fPobq9zMp0@7x@nZI2MWfc67rqsvbXHQ/t@OA@TO2bv7tK735cxmZI@uaVpdk0P6S7JfbrbzcmcfP@4tl@W@41MvbweUly/cF1BFrgiMJ6m7r4cl8vQz0/KNH2M06VfknPStkKHQ5q@/A1Q5viQudZnTjZPGnq@SubKzFX4W2euyVzY5nLmvD6RGFnQ2wrNFajwYgPgWrlzXxIwBspDjUhQoG/KCFXWnGOcqm3JotA44SwbqI9d5AHhsgSmijQVCBrlIoawhhAlbgBHmBsVyGFrjbCKEyViVkpCEtXmQS4BTxDmmY0m2BkfBSExYZVmlBDEPiJZUMtrHBRUKL0vTDvVSscFtEolZgv@0n@yAK70xwJZxi5coV9Z1QFeNcasMmu4wgxHRKx3XwZTiILe8FG/KIbrAikV1EGRCKiZMMY4oLgRleLsyMVHJ@EvJHMd@5EANuDA7m3gQlgUKjc9aenYABaubmwzrGzNUBBn28BMHDlI0DeL9eFNEcEX/9SD6a56Y8sF1GCaORs1BZyWIiEOzpYB@0dYqMoUkSbUIfKDsjIbyUZKxgBOv/0eUFbDYtZDpcRKhW0Lvo3okRkYh862SdaxUgvQYvptHlz4dSCYhDmEi28whiLuuRQQFGzbYAFb/ybbmCh@kGRzRxkfx07B6lTxQ1I7fKRDf2KzVbiNz7bNQzSXYSXDnkU/mhLq0BzRs2/1p4E3jz8 "Python 3 – Try It Online") My solution uses the definition of a determinant for calculations. Unfortunately, the complexity of this algorithm is `n!` and I can not show the passage of the last test, but in theory this is possible. [Answer] ## [SageMath](http://www.sagemath.org/), various Here are a bunch of methods for computing the determinant that I found interesting, all programmed in SageMath. They can all be tried [here](http://sagecell.sagemath.org/?z=eJyVk11v0zAUhu8j5T8clRu7uFWTDSEqwd24mDqE4DIKzE1OUrf-iGyHdUP8d-x07VKtQqJXzfny857XvoOPoLi3Yk-KImdwVTIoMgbXZUnT5C4fp7MrBtl7Bvn1UPQhfD03zN6FDgaLoSlN3sC6F9ILDTX6NOms0D7-JXf07CsfqofAoa2zpu4rD6YBFC3qX1z26NKkCRiSq3XNQS0tckliJVHzURWh9DS9GZ3U_PucWvDWaC4BJSrU3kHAvjW25pG-MqozTnhhNMzAaPkID8buHDTGguUxHltfKGCNFe8dxtGNQFmDcG7Q0I41PONvh3N-hmGK0GLP9mWcu48IlusWQ4m25uFMWzto8_ZxmSYQfqdoVIn7Cjt_lpncfvkMDRfyAK2Nnl0Cn_znir4r4TfnG0qTzQWNLhYeJS7K-XEaeZG0Gdm1uWDXineSVwi477h20QsujW7Bmw7CetJkNT73tLNPGdc1uF4RMsvodLqdqmLBtuV0RVSRLdlyW85530ZJh8D2bbYsKY1r2p55UBk5eBASccSiPNKuRuSrS-Qo1lo8xc2rXvJAmo9RI5trNeno9LCtYse6YlfOsuEi7C5CxEwXM18xDPWDl25ccALKx3T5BbxvSPCHt0RqokIjG27I0SDxxNcSD8-_Cjd7BhZ9b7UD96jWRooqGmLRRUcYOAPx3t9rQu-DM9CiB90rtLHOeRHmYJrcvHrJYQaJe1C8Cxzs1Zt-0XMzknMT1TCYkN9_6GQe18s90WQIU_oXzJuCHw==&lang=sage). ### Builtin, 3 bytes ``` det ``` This one isn't too interesting. Sage provides global-level aliases to many common operations that would normally be object methods, so this is shorter than `lambda m:m.det()`. --- ### Real Part of Product of Eigenvalues, 36 bytes ``` lambda m:real(prod(m.eigenvalues())) ``` Unfortunately, `eigenvalues` is not one of those global-level aliases. That, combined with the fact that Sage doesn't have a neat way to compose functions, means we're stuck with a costly `lambda`. This function symbolic values which are automatically converted to numeric values when printed, so some floating point inaccuracy may be present in some outputs. --- ### Product of Diagonal in Jordan Normal Form, 60 bytes ``` lambda m:prod(m.jordan_form()[x,x]for x in range(m.nrows())) ``` In Jordan Normal form, an NxN matrix is represented as a block matrix, with N blocks on the diagonal. Each block consists of either a single eigenvalue, or a MxM matrix with a repeated eigenvalue on the diagonal and `1`s on the super-diagonal (the diagonal above and to the right of the "main" diagonal). This results in a matrix with all eigenvalues (with multiplicity) on the main diagonal, and some `1`s on the super-diagonal corresponding to repeated eigenvalues. This returns the product of the diagonal of the Jordan normal form, which is the product of the eigenvalues (with multiplicty), so this is a more roundabout way of performing the same computation as the previous solution. Because Sage wants the Jordan normal form to be over the same ring as the original matrix, this only works if all of the eigenvalues are rational. Complex eigenvalues result in an error (unless the original matrix is over the ring `CDF` (complex double floats) or `SR`). However, this means that taking the real part is not necessary, compared to the above solution. --- ### Product of Diagonal in Smith Decomposition ``` lambda m:prod(m.smith_form()[0].diagonal()) ``` Unlike Jordan normal form, Smith normal form is guaranteed to be over the same field as the original matrix. Rather than computing the eigenvalues and representing them with a block diagonal matrix, Smith decomposition computes the elementary divisors of the matrix (which is a topic a bit too complicated for this post), puts them into a diagonal matrix `D`, and computes two matrices with unit determinant `U` and `V` such that `D = U*A*V` (where `A` is the original matrix). Since the determinant of the product of matrices equals the product of the determinants of the matrices (`det(A*B*...) = det(A)*det(B)*...`), and `U` and `V` are defined to have unit determinants, `det(D) = det(A)`. The determinant of a diagonal matrix is simply the product of the elements on the diagonal. ### Laplace Expansion, 109 bytes ``` lambda m:m.nrows()>1and sum((-1)**j*m[0,j]*L(m[1:,:j].augment(m[1:,j+1:]))for j in range(m.ncols()))or m[0,0] ``` This performs Laplace expansion along the first row, using a recursive approach. `det([[a]]) = a` is used for the base case. It should be shorter to use `det([[]]) = 1` for the base case, but [my attempt](http://sagecell.sagemath.org/?z=eJxNjUEOgjAQRfck3GGWHRwILRgjiTeAEzRdVEFCQ4spED2-FTVhNZn35_1p4AJWL354MSkFQaEIJCcolcI4asQ-5gUBPxGIcjs6h-0npMdgEOSbFEd1sEZtr60GW9nM-ek5M9SuhXm1jKUck8QkVuZkVFIzK3lFlVGZXnvbueULzIFXCvE-eTAwOPDa9R0LbbdpDG2IIeCfbw8_uAVq1iBB2y1h7pj4Q4Fvguc_gA==&lang=sage) at that implementation had a bug that I haven't been able to track down yet. --- ### Leibniz's Formula, 100 bytes ``` L2 = lambda m:sum(sgn(p)*prod(m[k,p[k]-1]for k in range(m.ncols()))for p in Permutations(m.ncols())) ``` This directly implements Leibniz's formula. For a much better explanation of the formula and why it works than I could possibly write, see [this excellent answer](https://codegolf.stackexchange.com/a/147723/45941). --- ### Real Part of `e^(Tr(ln(M)))`, 48 bytes ``` lambda m:real(exp(sum(map(ln,m.eigenvalues())))) ``` This function returns symbolic expressions. To get a numerical approximation, call `n(result)` before printing. This is an approach that I haven't seen anyone use yet. I'm going to give a longer, more-detailed explanation for this one. Let `A` be a square matrix over the reals. By definition, the determinant of `A` is equal to the product of the eigenvalues of `A`. The trace of `A` is equal to the sum of `A`'s eigenvalues. For real numbers `r_1` and `r_2`, `exp(r_1) * exp(r_2) = exp(r_1 + r_2)`. Since the [matrix exponential function](https://en.wikipedia.org/wiki/Matrix_exponential) is defined to be analogous to the scalar exponential function (especially in the previous identity), and the matrix exponential can be computed by diagonalizing the matrix and applying the scalar exponential function to the eigenvalues on the diagonal, we can say `det(exp(A)) = exp(trace(A))` (the product of `exp(λ)` for each eigenvalue `λ` of `A` equals the sum of the eigenvalues of `exp(A)`). Thus, if we can find a matrix `L` such that `exp(L) = A`, we can compute `det(A) = exp(trace(L))`. We can find such a matrix `L` by computing `log(A)`. The matrix logarithm can be computed in the same way as the matrix exponential: form a square diagonal matrix by applying the scalar logarithm function to each eigenvalue of `A` (this is why we restriced `A` to the reals). Since we only care about the trace of `L`, we can skip the construction and just directly sum the exponentials of the eigenvalues. The eigenvalues can be complex, even if the matrix isn't over the complex ring, so we take the real part of the sum. [Answer] # Java 8, ~~266~~ ~~261~~ ~~259~~ 258 bytes ``` long d(int[][]m){long r=0;int i=0,j,k,l=m.length,t[][]=new int[l-1][l-1],q=m[0][0];if(l<3)return l<2?q:q*m[1][1]-m[0][1]*m[1][0];for(;i<l;r+=m[0][i]*(1-i++%2*2)*d(t))for(j=0;++j<l;)for(k=l;k-->0;){q=m[j][k];if(k<i)t[j-1][k]=q;if(k>i)t[j-1][k-1]=q;}return r;} ``` Look mom, no build-ins.. because Java has none.. >.> -7 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##rVbLbuNGELzvV8wlgGhxvPPicCayNl@Q0x4FHpSV1qFESbZMbxAY@nanu1p2FthREEQxDFIaNburq/rBzfLbUh8e1vvNavv6ZVg@Palfl/3@5YNST@Ny7L@o1@Gwv1erSb8fF92i21UvODjOzYyOVD839abe1sN8dzus9/fj7zXs5vv1H4qfGbTtcKkf57uF6eh/1n@dDHe@Oq7H5@NeDXful8efH292C7K0nYaV7eQ7WX89HCez/m6YHafioe9uJlb30@lP7sZVN6vJWFVstCFM0@mGLPF1Ox9mW60/mVn1wrE33WKL2Nu7vhoXGwa27eaPOPr09xFd6PB0RnecnV6Venj@bSAyzpx8O/QrtSOeJp/HY7@/X3TLiilT6vOfT@N6d3t4Hm8f6Jdx2E9WkzcqiBaxUur96CW4E85OVTX7jy5crfyp/uHY1ipc7ZucXHAfatXUKhZ@aWuVapWvj@1rZcmZC6Xscq0UoSti04RMEUBlrgbhW8pf24auBKSEROeWLTKDsakpwqFMtBc7F68nxhjy5PiqGqKa/krAhB@d2bhpOHYsoostmyXC6DxYTa5g5nzioGzmE3Pr8/WlG7wT@CyY95yQg3PXlipLh8z2gZlU1nsAYsh0K5oHNgkgSjWRH2qYDW@L3n1AXpYNFSI5w8CsKdHrWkahvGFZQwxSIPzZ/Q/ECAgV@eYDiAH04CMrGcr0AIWKSUAzVa3lfD3LH0JJV9uAwMBpUO6IwZxqF9iNb03hoSiyCQUhMCTvmCoKiGYoTowIHXDTwSbRjTPzTJtviyyHDJZbtDTEtmjJ4Dx/ds3VXFOmwqlDvgn9jpRaj/SK8ydBILlpYGmQnmfAlF6JAXdWlRvzzIA/96/QVhTICAPcI9oDmMuIiodCLpY@GpWq2KJyECQiS4eqbXMRXhKBUC0OneIiKgfa2utnOufIsgWUJbQNkobxINJKriV0KB8t/ebR/BCIMAa4DKCwVK7ewO25Y6VQFXTGiU3sOZjidAwGmumMuQHJPMQ6k4WorriFnJEJwSCt9JTLAAmXrArJZ4tRHUyCNAm6GlWPIaAsqPBNLkdF@4t8qYH@WJTOvXFOgqbvpPz48d@JKXbfBwNxPFWzUrXHVNCY4sBMyaGBLMYXxCbamADDyH90R78aoRMjFesLs8FhDtoM7F6GDgZChgg5Ft1ZDA1SEKayajQEb3CNGWqio9r4riwt1gvojEwFaNhIx2IgAS/GklQ2cY1z9J2/lCwWjZad69GWGuURElZPDljL8a0LKVms/dwU3cnoJ/AguIHuGC7Wy5sJhmaSZYVKsMB7gTuKw6bCoEMPYJdQIwCXzPxW@gGbBsVOL0MXuAtQFtqJa7xZKYcNII0ldapRNNbCMl1AlxspNVklGJAYKRJG1rY6s2nfg1FB/hM6lxA/oeksNHV46QG3NoLTiNmN0tGRFr14O4/E04fT618) (Only the last test case is too big to fit in a `long` of size 263-1.) ``` long d(int[][]m){ // Method with integer-matrix parameter and long return-type long r=0; // Return-long, starting at 0 int i=0,j,k, // Index-integers l=m.length, // Dimensions of the square matrix t[][]=new int[l-1][l-1],// Temp-matrix, one size smaller than `m` q=m[0][0]; // The first value in the matrix (to reduce bytes) if(l<3) // If the dimensions are 1 or 2: return l<2? // If the dimensions are 1: q // Simply return the only item in it : // Else (the dimensions are 2): q*m[1][1]-m[0][1]*m[1][0]; // Calculate the determinant of the 2x2 matrix // If the dimensions are 3 or larger: for(;i<l; // Loop (1) from 0 to `l` (exclusive) r+= // After every iteration: add the following to the result: m[0][i] // The item in the first row and `i`'th column, *(1-i++%2*2) // multiplied by 1 if `i` is even; -1 if odd, *d(t)) // multiplied by a recursive call with the temp-matrix for(j=0; // Reset index `j` to 0 ++j<l;) // Inner loop (2) from 0 to `l` (exclusive) for(k=l;k-->0;){ // Inner loop (3) from `l-1` to 0 (inclusive) q=m[j][k]; // Set the integer at location `j,k` to reduce bytes if(k<i) // If `k` is smaller than `i`: t[j-1][k]=q; // Set this integer at location `j-1,k` if(k>i) // Else-if `k` is larger than `i`: t[j-1][k-1]=q; // Set this integer at location `j-1,k-1` // Else: `k` and `i` are equals: do nothing (implicit) } // End of inner loop (3) // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return r; // Return the result-long } // End of method ``` [Answer] # JavaScript (ES6), 91 Recursive Laplace ``` q=(a,s=1)=>+a||a.reduce((v,[r],i)=>v-(s=-s)*r*q(a.map(r=>r.slice(1)).filter((r,j)=>j-i)),0) ``` *Less golfed* ``` q = (a,s=1) => // s used as a local variable a[1] // check if a is a single element array // if array, recursive call expanding along 1st column ? a.reduce((v,[r],i) => v-(s=-s)*r*q(a.map(r=>r.slice(1)).filter((r,j)=>j-i)),0) : +a // single element, convert to number ``` **Test** ``` q=(a,s=1)=>+a||a.reduce((v,[r],i)=>v-(s=-s)*r*q(a.map(r=>r.slice(1)).filter((r,j)=>j-i)),0) TestCases=`[[42]] -> 42 [[2, 3], [1, 4]] -> 5 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 0 [[13, 17, 24], [19, 1, 3], [-5, 4, 0]] -> 1533 [[372, -152, 244], [-97, -191, 185], [-53, -397, -126]] -> 46548380 [[100, -200, 58, 4], [1, -90, -55, -165], [-67, -83, 239, 182], [238, -283, 384, 392]] -> 571026450 [[432, 45, 330, 284, 276], [-492, 497, 133, -289, -28], [-443, -400, 56, 150, -316], [-344, 316, 92, 205, 104], [277, 307, -464, 244, -422]] -> -51446016699154` .split('\n') TestCases.forEach(r=>{ [a,k] = r.split (' -> ') a = eval(a) d = q(a) console.log('Test '+(k==d ? 'OK':'KO')+ '\nMatrix '+a.join('|')+ '\nResult '+d+ '\nCheck '+k) }) ``` [Answer] # [Python 2](https://docs.python.org/2/) + [numpy](https://pypi.python.org/pypi/numpy/1.13.3), 29 bytes ``` from numpy.linalg import* det ``` [Try it online!](https://tio.run/##Jci7CoAgFADQva@4Y4UFviqHvkQcgrKEfCA29PVmtZzhhDsd3pGcdfQW3GXD3Z/GLecOxgYfU1vped1SDtG4VOtaSjoSBB3mRcKYQiA7Mb4jMAI88W84LUP/J4NSTZMf "Python 2 – Try It Online") [Answer] # [Julia](http://julialang.org/), 3 bytes ``` det ``` [Try it online!](https://tio.run/##yyrNyUw0/f8/zTYlteR/QVFmXolGmka0kYKxtaGCSaym5n8A "Julia 0.5 – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 6 bytes ``` matdet ``` [Try it online!](https://tio.run/##PVHJagMxDP0VHxOwwVq8iKFfEnoItCk5tAxh/n@ip2lyEbYsvcVvvT7u5Wfdb@kj7b/X7et729fH/W873U6XWXOiZjlJ55yK@LWwelGTnJT8zurPhQil2oIjpogFYx19wQb37liGYZXhy9q82MzJ@pJoNDxU9ARUA8QoHezSgTA6jgPHWsFU0ZYRAjBcAv@gpuEwpM4vjGZzJgmBQoEmAOZAC1HT59kgdQYsd@gLx9aW1MNEDZ/NZbI4IInfCZu@P8Jw/BOBG758F@1wx5CrAwhBo4d66MIPacWkDRjT@EJYPfYFZpgxSl64BYjbJMLMBJO1SAibSoZ08guJ8a//LukF5xm@qTjacwZrpDcjMkUA2I0cFVmUzp/n8/4E "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 52 bytes ``` f(a)=if(#a,sum(n=1,#a,-(-1)^n*a[1,n]*f(a[^1,^n])),1) ``` [Try it online!](https://tio.run/##PVLJasMwEP0VQS92kECzaCPkS0ICvrjkUBPS9PvdeZOml0Eav3mLxvflcUuf930Np7Cv0zKfbuv0scTvn69pO1G0Y5oSzdftsJwpbpeDgc5XitftMs@R5v3@uG3PaZ3OPcdAZcQglWNIYtfEakWHxKBkd1b7nIhQ8jjiCBSxAFbRF0xwrcY1AFZpNqzFyugxjHoM1Ao@ZPQEUg3CKBXqUsHQKo4Nx5yhlNGW5gYATs7/kqZmNKSmL4xmMSVxg0LOJiBmZ3NT3fA8YLU7LVf488SjHEP1ENlzFrPJYoQkdidM2nzzwP5OBG3kslm0PR3DrjYwuIy@3MMXXkgzkKMhmPoTIuprXhCGGVCywsVJLCYRMB1Ko/iGMKk0sJ34ZmK8619KetPZDv@l2Nu9u6pvr/vKFAvArO9RsYtU2f6S/Rc "Pari/GP – Try It Online") [Answer] # [J](http://jsoftware.com/), 5 bytes ``` -/ .* ``` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/3X1FfS0/mtyKekpqKfZWqkr6CjUWimkFXOlJmfkK6Qp2BkpGFsrGCqYwAUMjRUMzRWMTICilkAJoGy8qYKJAtAsAA "J – Try It Online") ]
[Question] [ ## Introduction How much of the English alphabet does a given string use? The previous sentence uses 77%. It has 20 unique letters (howmucftenglisapbdvr), and 20/26 ≃ 0.77. ## Challenge For an input string, return the percentage of letters of the English alphabet present in the string. * The answer can be in percentage or in decimal form. * The input string can have upper and lower case, as well as punctuation. However you can assume they have no diacritics or accentuated characters. ## Test cases Input ``` "Did you put your name in the Goblet of Fire, Harry?" he asked calmly. ``` Some valid outputs ``` 77%, 76.9, 0.7692 ``` Input: ``` The quick brown fox jumps over the lazy dog ``` All valid outputs: ``` 100%, 100, 1 ``` The expected output for `"@#$%^&*?!"` and `""` is 0. [Answer] # [Python 3](https://docs.python.org/3/), 42 bytes ``` lambda s:len({*s.upper()}-{*s.lower()})/26 ``` [Try it online!](https://tio.run/##PYyxDoIwFEV3v@KGhWIUE00cTIyLUT/A0aVA0Urpq6UVq/HbERicbk5O7jHB3UivunJ76RSvs4Kj2Sih2WfapN4YYVnynQ@gqB0hWSzXnbFSO1ayONrLAoE8jHfDWmheC0gNdxM4UqaEA5U4SCtmOHFrwy5Cr3hTiQI5V7UKaZwkk3/y3NuHl3mFzFKrUdILd1@bBvQUduwq/g4o6Nr/uh8 "Python 3 – Try It Online") We filter all the non-alphabetic characters out of the string by taking the (set) difference of the uppercase and lowercase representations. Then, we take the length and divide by 26. # [Python 3](https://docs.python.org/3/), 46 bytes ``` lambda s:sum(map(str.isalpha,{*s.lower()}))/26 ``` [Try it online!](https://tio.run/##PYyxbgIxEAX7fMUTDXaEDolIKSJFNCjJB1DS7HG@nMH2OmsbMCjffhwpUk0xmok1Dxxexv59NzrybUdIb6l45SmqlKWxiVwcaHF7To3jsxGlf7Verl7HKDZk1av5bGM7VC6IJT8oCOQNbEAeDD65dSaDe3xYMQt8kUhdzzApSkfTYU/Ou9rMtX76X24n@1Ps/ohW@BzQ8wWH4mMCn4z8fR1dKzr@nrrxDg "Python 3 – Try It Online") Count the unique alphabetic (lowercase) characters, and divide by 26. In Python 2 it would require 3 more characters; two for changing `{*...}` to `set(...)`, and one for making 26 a float: `26.`, to avoid floor division. # [Python 3](https://docs.python.org/3/), 46 bytes ``` lambda s:sum('`'<c<'{'for c in{*s.lower()})/26 ``` [Try it online!](https://tio.run/##PYyxbsIwGAZ3nuITixNUUQkkBgTqgmgfgJGhTmITg@0//W1DDeLZQ2BguuF01@XYkp/3er3vrXRVIxGWIblC/IpVvRI3oYlRw/jbJEwtXRQX5b38nC36jo2PhS7EeGMaZEroUnyS4aVTQ4LYKnxTZVUEaWwNqw/8SOb8NcagZDipBrW0zuapKMvRe7kb7F8y9QkV08VD0z@OyXUBdFb8@lp5zWjoMHT9Aw "Python 3 – Try It Online") Same length, essentially the same as the previous one, but without "built-in" string method. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 8 bytes ``` 2Y2jkmYm ``` Try it at [MATL Online](https://matl.io/?code=2Y2jkmYm&inputs=%22Did+you+put+your+name+in+the+Goblet+of+Fire%2C+Harry%3F%22+he+asked+calmly.&version=20.11.0) **Explanation** ``` 2Y2 % Predefined literal for 'abcdefghijklmnopqrstuvwxyz' j % Explicitly grab input as a string k % Convert to lower-case m % Check for membership of the alphabet characters in the string. % Results in a 26-element array with a 1 where a given character in % the alphabet string was present in the input and a 0 otherwise Ym % Compute the mean of this array to yield the percentage as a decimal % Implicitly display the result ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` lASåÅA ``` -1 byte thanks to *@LuisMendo*. [Try it online](https://tio.run/##yy9OTMpM/f8/xzH48NLDrY7//yu5ZKYoVOaXKhSUloDoIoW8xNxUhcw8hZKMVAX3/KSc1BKF/DQFt8yiVB0Fj8Siokp7JQWgVGJxdmqKQnJiTm5OpR4A) or [verify a few more test cases](https://tio.run/##HY5BbsIwFET3OcU0pSwQ6hUCEgX2sEb6ST6Ji@Mf7DjUVbflANyBk3ATLhIMq5FmNE9PHOWKh78@ZCnu5wvSLAx6vrldb//zYTqs5YTGFzVkj65mfJlKK1eDdFtTzh1KYQdCpXo2cJ1VpoJ3nCXpQpUI4tH67pkWhhqGMi/OSnId35G6VJanWJO1T4U4kTtwiYJ0o8Nnso3N0avigNzKyWAvP/j2TesgPdsXS9NviB5VMnsffezGk@ztAQ). **6 bytes alternative provided by *@Grimy*:** ``` láÙg₂/ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/5/DCwzPTHzU16f//r@SSmaJQmV@qUFBaAqKLFPISc1MVMvMUSjJSFdzzk3JSSxTy0xTcMotSdRQ8EouKKu2VFIBSicXZqSkKyYk5uTmVegA) or [verify a few more test cases](https://tio.run/##HY69bcMwFIR7TXFREheB4YygFP4bIHWAJ@mZokXxyaQoh0YqFxkgXcrM4k28iEK7OuAO9@ETT6Xm6WuMRY7r9w/yIk7m8nf5Vdfz@XWaT1s5ogtVA9lhaBgrq4z2Dcj0DZU8oBb2ICg9soUfnLYKwXOR5UtdI0pAH4ZbOljqGNreORspTXon6lo7nmNLzt0k0kS@5RoVmc7ERfaemkPQVYvSydFiJ5/Yh673kJHdnWXoFJOHyt4en54/Zi/Fwz8). Both programs output as decimal. **Explanation:** ``` l # Convert the (implicit) input-string to lowercase AS # Push the lowercase alphabet as character-list å # Check for each if it's in the lowercase input-string # (1 if truthy; 0 if falsey) ÅA # Get the arithmetic mean of this list # (and output the result implicitly) l # Convert the (implicit) input-string to lowercase á # Only leave the letters in this lowercase string Ù # Uniquify it g # Get the amount of the unique lowercase letters by taking the length ₂/ # Divide this by 26 # (and output the result implicitly) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 33 bytes ``` @(s)mean(any(65:90==upper(s)',1)) ``` [Try it online!](https://tio.run/##FclLCsIwFEbhrfx0kgRK0IGCQtCBqNu4tjdYzIs0EbL6WEcHvhOnQl/u1mit@1WuyjMFSaHJ4@F82hlTU@K8uRj3SnUrxXBbZrRYkWr5NyOQZywB5c14xJfjgmhxXzKPeFLO7TJgW7R@eMZEzrumheo/) ### Explanation ``` @(s) % Anonymous function with input s: row vector of chars 65:90 % Row vector with ASCII codes of uppercase letters upper(s) % Input converted to uppercase ' % Transform into column vector == % Equality test, element-wise with broadcast. Gives a % matrix containing true and false any( ,1) % Row vector containing true for columns that have at % least one entry with value true mean( ) % Mean ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~56~~ 49 bytes ``` a=>a.ToUpper().Distinct().Count(x=>x>64&x<91)/26f ``` [Try it online!](https://tio.run/##VY29bsJAEIR7nmLkIrIlcJQoQorApggiKShBaWiO8x5ZsG@d@wl2Xt6YdKlmpJn5RvuZ9jxsotVLHxzb07SSeKyphCkGVZQq38m@bcmlWb5mH9jqMNo3iTakXVF25fzloVu@PmWPz3MzLCaTT8eBtmwpNWlySNZcoZeINoa7OljVENgifBHeZbwKEIMNO5riQznXY4VDgjFV/kIVtKqbus@TLFv8Z@/GyndkfcHRydXCSIdzbFoP@SH3x6/Vb49KTvfxcAM "C# (Visual C# Interactive Compiler) – Try It Online") *-6 bytes thanks to [innat3](https://codegolf.stackexchange.com/users/86178/innat3)* [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. Returns decimal fraction. ``` 26÷⍨∘≢⎕A∩⌈ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/38js8PZHvSsedcx41LnoUd9Ux0cdKx/1dPxPe9Q24VFvH1DE0/9RV/Oh9caP2iYCecFBzkAyxMMz@H@agrqSS2aKQmV@qUJBaQmILlLIS8xNVcjMUyjJSFVwz0/KSS1RyE9TcMssStVR8EgsKqq0V1IASiUWZ6emKCQn5uTmVOqpcwGNCgGKFpZmJmcrJBXll@cppOVXKGSV5hYUK@SXpRaBzctJrKpUSMlPB6t3UFZRjVPTslcE89QB "APL (Dyalog Extended) – Try It Online") `⌈` uppercase `⎕A∩` intersection with the uppercase **A**lphabet `≢` tally length `∘` then `26÷⍨` divide by twenty-six [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~27~~ 24 bytes *-3 bytes thanks to nwellnhof* ``` *.uc.comb(/<:L>/).Set/26 ``` [Try it online!](https://tio.run/##HYy9DoIwGEV3nuKGgagxJXFg8AcXow5u@gKlfGilpVhatb58RZd7knOS25NVRdQBWYMN4ox5wYTR1SRfL09lPmVncvmiiKtEyY6GsmRZM87AQ0x3skYwHr13P1p0XBNkB3cjHEylyME02EtLcxy5tWGbYkx8aKmG4EqrwJLLaB5eihaVNa8OjXnj7nU/wDzJ/r8U/wTU5voF "Perl 6 – Try It Online") [Answer] ## Bash and Gnu utils (81 78 68 60 42 bytes) ``` bc -l<<<`grep -io [a-z]|sort -fu|wc -l`/26 ``` -8 bytes thanks to [@wastl](https://codegolf.stackexchange.com/users/78123/wastl) -18 bytes thanks to [Nahuel](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul) using some tricks I didn't know: * `sort -f` and `grep -i` ignore case * `sort -u` is a replacement for `| uniq` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ 15 bytes **Solution:** ``` 1%26%+/26>?97!_ ``` [Try it online!](https://tio.run/##y9bNz/7/31DVyExVW9/IzM7e0lwxXilGySUzRaEyv1ShoLQERBcp5CXmpipk5imUZKQquOcn5aSWKOSnKbhlFqXqKHgkFhVV2scoKQDlEouzU1MUkhNzcnMq9ZT@/wcA "K (oK) – Try It Online") **Explanation:** Convert input to lowercase, modulo 97 ("a-z" is 97-122 in ASCII, modulo 97 gives 0-25), take unique, sum up results that are lower than 26, and convert to the percentage of 26. ``` 1%26%+/26>?97!_ / the solution _ / lowercase 97! / modulo (!) 97 ? / distinct 26> / is 26 greater than this? +/ / sum (+) over (/) 26% / 26 divided by ... 1% / 1 divided by ... ``` **Notes:** * **-1 bytes** thanks to ngn, `1-%[;26]` => `1-1%26%` * **-3 bytes** inspired by ngn `#(!26)^` => `+/26>?` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 55 52 bytes ``` ($args|% *per|% t*y|sort|gu|?{$_-in65..90}).count/26 ``` [Try it online!](https://tio.run/##FclBCsIwEADAryylUi0aRbDgqRdRfyGxXdvQNBs2CRKMb4/1NIex9EZ2I2qd87qUPLi0gtoiL/g6Jkfs0xBS@ykfO2WakxDnw3cjOgrG749NzrkqLqqHSAFs8H8ZjJwRlAE/ItzoqdEDveCqGLdwl8yxLWAp6SbsoZN61lFUPw "PowerShell – Try It Online") First attempt, still trying random ideas EDIT: @Veskah pointed out ToUpper saves a byte due to the number range, also removed extra `()` and a space Expansion: `($args|% ToUpper|% ToCharArray|sort|get-unique|where{$_-in 65..90}).count/26` Changes string to all loweruppercase, expands to an array, sorts the elements and selects the unique letters (gu needs sorted input), keep only characters of ascii value 97 to 122 (a to z) 65 to 90 (A to Z), count the total and divide by 26 for the decimal output [Answer] # [R](https://www.r-project.org/), 47 bytes ``` function(x)mean(65:90%in%utf8ToInt(toupper(x))) ``` [Try it online!](https://tio.run/##HYxND8EwHMbvPsWjjFVEXAgSmYN4uTtLamupbf1P17L58jM7PXnefrZR2KJR3sROkwkrnkthwuVis54H2gTeqdWFzsaFjnxRSNsuOG9UOGZ7naAmj8K7v1oYkUtoA/eQONItkw6kcNBWTnES1tYRQ1uJMpUJYpHlWT0b817LurTxy@s4xc3Sx0BRhafPixL0lrYDZuJbI6F7d2C7wTC4jiZRn3WW8eYH "R – Try It Online") Converts to upper case then to ASCII code-points, and checks for values 65:90 corresponding to A:Z. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` T`Llp`ll_ +`(.)(.*\1) $2 . 100$* ^ 13$* .{26} ``` [Try it online!](https://tio.run/##HY49T8MwGIR3/4qjpCgNyGqKxJoOQDswdkQlTvI2cevYwR8tAfHbg@n0SHe6R2fJSy2mebopp135poZSqQ92X6Z8kfLsPV@wZMU4y5fLJGN7lj9G8J/V0@80bc0Ffag7mAN8R3jRrZKug1BDJyryaAw5CLTyTBrOW6lbBEcFmz3LBqMJGIL/p4UWPUHqq2djKhXX0foqLT1gK6wdixliJdyJGtRC9WrkbBeTzyDrEyprLhoH84Vj6AcHcyZ7dSnxPcYfLVvfJvP9XVbc/AE "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` T`Llp`ll_ ``` Lowercase letters and delete punctuation. ``` +`(.)(.*\1) $2 ``` Deduplicate. ``` . 100$* ``` Multiply by 100. ``` ^ 13$* ``` Add 13. ``` .{26} ``` Integer divide by 26 and convert to decimal. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes ``` ⌹∘≤⍨⎕A∊⌈ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HPzkcdMx51LnnUu@JR31THRx1dj3o6/qc9apvwqLcPKOLp/6ir@dB640dtE4G84CBnIBni4Rn8P01BXcklM0WhMr9UoaC0BEQXKeQl5qYqZOYplGSkKrjnJ@Wklijkpym4ZRal6ih4JBYVVdorKQClEouzU1MUkhNzcnMq9dS5gEaFAEULSzOTsxWSivLL8xTS8isUskpzC4oV8stSi8Dm5SRWVSqk5KeD1Tsoq6jGqWnZK4J56gA "APL (Dyalog Extended) – Try It Online") loosely based on [Adám's answer](https://codegolf.stackexchange.com/a/187211/24908) `⌈` uppercase `⎕A∊` boolean (0 or 1) vector of length 26 indicating which letters of the English **A**lphabet are in the string `⌹∘≤⍨` arithmetic mean, i.e. matrix division of the argument and an all-1 vector of the same length [Answer] # Java 8, ~~62~~ 59 bytes ``` s->s.map(c->c&95).distinct().filter(c->c%91>64).count()/26. ``` -3 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##jZFPbxMxEMXv/RSPhVa7tDEqaiu1iIQD0HJoL@VGW2nidbJOvPbisROWKp89TJZwRfXB/2b8fm/GC1rRaFEvt9oRM27J@ucDwPpk4oy0wd3uCNQhT52BLhfyQOVkneIUDbXqm0/3ww5cfZDczYFMnChZjTt4fMSWR2NWLXWlHo310eV5pWrLyXqdykrNrBPWEDq8PB1fnFVKh@wl9O79hdruJDthi9pedBVsjVaMlsK1fv7jEVT9dTkLcX8JxhW8WeNfznNxE9Zos24QZkiNwRc/d5YbkOsampokNRoGYW5XxgtskMlsJsXJIP6/UTwUn8VVH7KYTbs1wlNrpJED6zpI99KO/NVGc4IbirGfPBSQGPHS1NDkWterl7C@y6Of2eolpjGsvVT9C4vcdoywMnHgOfrdSz3zl8h9ev3m8Ono7eRVsan22fc9J9OqkJPqpA3J@ZKPiysUx17pkpVuKHJZVfsP32z/AA) **Explanation:** ``` s-> // Method with IntStream as parameter and double return-type s.map(c->c&95) // Convert all letters to uppercase .distinct() // Uniquify it .filter(c->c%91>64) // Only leave letters (unicode value range [65,90]) .count() // Count the amount of unique letters left /26. // Divide it by 26.0 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` I∕LΦβ№↧θι²⁶ ``` [Try it online!](https://tio.run/##FYoxEoIwEAB7X3FDlcxECwsbCwsYtKDwC0c45caQ6HHg8PoYm91i148oPmHI@S4c1dQ4q2l45YFMR/Gpo2k5KInpHdRpKUuXviQeZzIf64CtLTyeis45Vw0PsKUF3ov@LRBxIuAIOhJcUx9IIT2gZSEHNxTZLhWUhPOLBvAYprAddnm/hh8 "Charcoal – Try It Online") Link is to verbose version of code. Output is as a decimal (or `1` for pangrams). Explanation: ``` L Length of β Lowercase alphabet Φ Filtered on № Count of ι Current letter in ↧ Lowercased θ Input ∕ Divided by ²⁶ Literal 26 I Cast to string Implicitly printed ``` [Answer] ## Batch, 197 bytes ``` @set/ps= @set s=%s:"=% @set n=13 @for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set t="%%s:%%c=%%"&call:c @cmd/cset/an/26 @exit/b :c @if not "%s%"==%t% set/an+=100 ``` Takes input on STDIN and outputs a rounded percentage. Explanation: ``` @set/ps= ``` Input the string. ``` @set s=%s:"=% ``` Strip quotes, because they're a headache to deal with in Batch. ``` @set n=13 ``` Start with half a letter for rounding purposes. ``` @for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set t="%%s:%%c=%%"&call:c ``` Delete each letter in turn from the string. Invoke the subroutine to check whether anything changed, because of the way Batch parses variables. ``` @cmd/cset/an/26 ``` Calculate the result as a percentage. ``` @exit/b :c ``` Start of subroutine. ``` @if not "%s%"=="%t%" set/an+=100 ``` If deleting a letter changed the string then increment the letter count. [Answer] # [Pepe](https://github.com/Soaku/Pepe), ~~155~~ 138 bytes ``` rEeEeeeeeEREeEeEEeEeREERrEEEEErEEEeReeReRrEeeEeeeeerEEEEREEeRERrErEErerREEEEEeREEeeRrEreerererEEEEeeerERrEeeeREEEERREeeeEEeEerRrEEEEeereEE ``` [Try it online!](https://soaku.github.io/Pepe/#!aa!bpF--i!o/.-!8g!qT&-_E$@&1!l-_*$$Ds_-!c!r-!85@-_wM) Output is in decimal form. **Explanation:** ``` rEeEeeeeeE REeEeEEeEe # Push 65 -> (r), 90 -> (R) REE # Create loop labeled 90 // creates [65,66,...,89,90] RrEEEEE # Increment (R flag: preserve the number) in (r) rEEEe # ...then move the pointer to the last Ree # Do this while (r) != 90 Re # Pop 90 -> (R) RrEeeEeeeee rEEEE # Push 32 and go to first item -> (r) REEe # Push input -> (R) RE RrE # Push 0 on both stacks, (r) prepend 0 rEE # Create loop labeled 0 // makes input minus 32, so the # lowercase can be accepted, since of rEEEEeee (below) re # Pop 0 -> (r) rREEEEEe REEee # Push item of (R) minus 32, then go to next item RrE # Push 0 -> (R) ree # Do while (R) != 0 rere # Pop 0 & 32 -> (r) rEEEEeee # Remove items from (r) that don't occur in (R) # Remove everything from (r) except the unique letters rE # Push 0 -> (r) RrEeee # Push reverse pointer pos -> (r) REEEE # Move pointer to first position -> (R) RREeeeEEeEe # Push 26 -> (R) rRrEEEEee reEE # Divide it and output it ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 19 bytes ``` 1%26%26-#(!26)^97!_ ``` [Try it online!](https://tio.run/##y9bNz/7/P83KUNXIDIh0lTUUjcw04yzNFeP/pykoxSi5ZKYoVOaXKhSUloDoIoW8xNxUhcw8hZKMVAX3/KSc1BKF/DQFt8yiVB0Fj8Siokr7GCUFoFxicXZqikJyYk5uTqWeEtd/AA "K (oK) – Try It Online") # [J](http://jsoftware.com/), 30 bytes ``` 26%~26-u:@(97+i.26)#@-.tolower ``` [Try it online!](https://tio.run/##PYzBCoJAGAbvPsWHEVukS3gwEiKhqA6dohdYda2t1d9Wt7JDr27WocMwh4G5dC5nORYRGDxMEfX4HKvDftMF4fAdhL6N4tF8NlE8CMeD2OcNaXpI040dODI9E3Iwd60ytGRR2eZrg1IUEqpEc5bYUqJlA8qxUUZ62Alj2qWLPon6KjOkQhe65ez/O/bpZlV6RWLoUSKnJy62qGrQXZrfVItXi4xOrPsA "J – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~57~~ ~~46~~ 35 bytes ``` . $L [^a-z] D`. . 100* ^ 13* _{26} ``` -11 bytes taking inspiration from [*@Neil*'s trick of adding unary 13 before dividing](https://codegolf.stackexchange.com/a/187223/52210). Another -11 bytes thanks to *@Neil* directly. [Try it online.](https://tio.run/##HY5NT8JAGITv768YEYxptGlBUU/1A4WDR2/Gwtt2aVe2u7jbBYvxt9fKaZKZPE/GikZqjrvR@XzVhTR8pfeULw8fRLNVSCHFURRQSvEkoOXPePrbdQuzR@3zCmaNphJ41qWSrgKrbcWZaFAY4cAo5U5ouMZKXcI7kdBgJgu0xmPrm/@00FwLSH30zE2merq3vkgrLrBga9tkgH5itxEFcla1akN665svL/MNMmv2GmvzjU9fbx3MTtijS/Gh7X@UdH86HKVnQXJCnOXF0@MDxePJ1fX05vYuWvIf) **~~57~~ ~~46~~ 40 bytes version which works with decimal output:** ``` . $L [^a-z] D`. . 1000* C`_{26} -1`\B . ``` Same -11 bytes as well as an additional -6 bytes thanks to *@Neil*. Outputs with one ***truncated****†* decimal after the comma (*†* i.e. \$0.1538\$ (\$\frac{4}{26}\$) is output as `15.3` instead of `15.4`). This is done by calculating \$\lfloor{\frac{1000 × \text{unique\_letters}}{26}\rfloor}\$ and then inserting the decimal dot manually. [Try it online.](https://tio.run/##HY5NT8JAFEX371c8EYwhMmlRUVdVQGHh0p0KfW2HdmQ6U@cDKMbfXkdWN7k35@Qa7oSiuBtcLtKOQf8V3lc0On4CzFMGDOIoioYwS9c/48kvjOL0Ywqs65Z6j7XPK9QbdBXHZ1VKYSsk2VSUcYeF5hYJS7HjCq0zQpXoLU@gNxcFttpj491/GlRUcxTq5FnoTAY6WF@E4Ve4JGPapIdhIrvlBeYka9kyeAvNtxf5FjOj9wo3@oBfvm4s6h03J5ekYxt@lPB43h@sLobJGVCWF7PpE8Tj65vbyd39Q7SmPw) **Explanation:** Convert all letters to lowercase: ``` . $L ``` Remove all non-letters: ``` [^a-z] ``` Uniquify all letters: ``` D`. ``` Replace every unique letter with 1000 underscores: ``` . 1000* ``` Count the amount of times 26 adjacent underscores fit into it: ``` C`_{26} ``` Insert a dot at the correct place: ``` -1`\B . ``` [Answer] # [Julia 1.0](http://julialang.org/), 34 bytes ``` s->sum('a':'z'.∈lowercase(s))/26 ``` Uses the [vectorized](https://docs.julialang.org/en/v1/manual/mathematical-operations/#man-dot-operators-1) version of the ∈ operator, checking containment in the string for all characters in the range from a to z. Then sums over the resulting BitArray and divides by total number of possible letters. [Try it online!](https://tio.run/##ZYxLDoIwFEXnruKJH8D4iQ4cmCgOjLoAxyZPKFooLb5S@azAdboRrM6Md3KT@zmJERznVRuvWz3ZaJN5Lrort3Gnr@dTqJJRiJp52vdni2WbE5eFkF7sEZaO1Y5HUCsDuSk@TiAxY8AlFDcGB3URrAAVw54TG8MRierAAVuhTlkEIYpM1FPL8f3OL/tkR3fDwxQupEoJsaogMVmuQT0YffECmxoidf0//yfbXn9wHo6Crq3aNw "Julia 1.0 – Try It Online") [Answer] # C, 96 bytes ``` float f(char*s){int i=66,l[256]={};for(;*s;)l[1+*s++&~32]=1;for(;i<92;*l+=l[i++]);return*l/26.;} ``` [Try it online!](https://tio.run/##fY3RToMwFIbv9xRHdAttcWYYSUwl88KoD@AdYNKVdqsrLRZQEdmrI5vXcm7@5Hx//o9fbjkfBqktq0H6fMccrlCnTA0qjqJAJ@FNlMVdT6V1PsUVRTpZEVwRsjhch1m8@gPq7jakWJNYJ4qQDFEn6sYZrK/CaEn74ThYMGV8NOtmMF7pxpf0vblMjReMai/1HlQOrW2gbOpjOjCsEKAM1DsBT3ajRQ1WwqNyIoBn5ly7Tj0YGav2IgfOdKHbpYcQ/UfxMnbfG8X3sHH204C0X/DWFGUF9kO4k0az7xZyu51YuT@/mL8u8PpsotP99IcJfEL98As) [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=uniq -p`, 24 bytes ``` $_=uniq(lc=~/[a-z]/g)/26 ``` [Try it online!](https://tio.run/##Hc2xCgIxDADQX8ngoEMpCDocHE6Cgzc6iUg9YxuoTb2kCg5@uhF8P/AqTnllNjv3rdBjnsf@44/BvU8@LvxybbbjF9zbmIBvoAlhW2ImSRByTeGCCldGgQCRnlhAdKISoQluvlyVuIi5YU@iXXdQyv/FXP0B "Perl 5 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ░║üy$}╙+C ``` [Run and debug it](https://staxlang.xyz/#p=b0ba8179247dd32b43&i=%22Did+you+put+your+name+in+the+Goblet+of+Fire,+Harry%3F%22+he+asked+calmly.%0AThe+quick+brown+fox+jumps+over+the+lazy+dog%0A%21%40%23%24%25%5E%26*%28%29%0A%22%22&a=1&m=2) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ŒuØAe€Æm ``` [Try it online!](https://tio.run/##y0rNyan8///opNLDMxxTHzWtOdyW@///fyWXzBSFyvxShYLSEhBdpJCXmJuqkJmnUJKRquCen5STWqKQn6bgllmUqqPgkVhUVGmvpACUSizOTk1RSE7Myc2p1AMA "Jelly – Try It Online") ### Explanation ``` Œu | Convert to upper case ØAe€ | Check whether each capital letter is present, returning a list of 26 0s and 1s Æm | Mean ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes ``` s=>~-s.match(/$|([a-z])(?!.*\1)/ig).length/26 ``` [Try it online!](https://tio.run/##Xcy9CsIwFEDh3ae4gmAitEUHF6lOgg/gpg4x3ibRNLf2pvUH8dVrdXQ98J2zahXr2lUxCXTCrsg7zpfvhNNSRW1FNnqJnUqeBylWw3Syn8rMGZl6DCbabDbvNAUmj6knIwox3tANykZboAKiRVgH4x1bUL6y6ogRToQMCoxrMQDH2gUDDeNqLOXg77Xt/bVx@gLHmm4BCrrDuSkrBmqx/u29ej76pen14p9/W/cB "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 47 bytes ``` s=>(s.match(/([a-z])(?!.*\1)/ig)||[]).length/26 ``` [Try it online!](https://tio.run/##XcyxDoIwEIDh3ac4J1sTITq4GHUy8QHclKGWo62WHnIFlfjuiI6sf/L9N9Uq1rWr4iJQjn2x7Xm7E5yUKmorUnFWiy6TYj9N5pelTJ2Rn885k4nHYKJNV@teU2DymHgyohCzIz2hbLQFKiBahEMw3rEF5SurrhghJ2RQYFyLATjWLhhoGPczKSej12nwj8bpO1xregYo6AW3pqwYqMX6v/eqew9LM@jNmP9a/wU "JavaScript (Node.js) – Try It Online") [Answer] # Swift 5.9, ~~105~~ 100 bytes ``` var p={(s:String)in Float((65...90).filter{s.uppercased().map(\.asciiValue).contains($0)}.count)/26} ``` Using `Float` instead of `Double` saved a byte. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` ;CoU Ê/26 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0NvVSDKLzI2&input=IkhvdyBtdWNoIG9mIHRoZSBFbmdsaXNoIGFscGhhYmV0IGRvZXMgYSBnaXZlbiBzdHJpbmcgdXNlPyI) ``` ;CoU Ê/26 :Implicit input of string U ;C :Lowercase alphabet oU :Remove the characters not included in U, case insensitive Ê :Length /26 :Divide by 26 ``` [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda i:len(set(o for o in i.lower()if o.isalpha()))/26. ``` [Try it online!](https://tio.run/##rY9NSwMxEIbv/orX@pFEZYUeeijYehD1B3gsQrabuLHZTJxkrfHPr1sRhXoSPA3MzPPMO7HklsJ0sFerweuubjTc3Jsgk8mSYIlBcAGu8rQ1LJWzoMol7WOrpVLqcjqrhsguZIjJjWtQqEfs864ygu7MDs@twR3V3mSQxa1jc4F7zVyWE4wjnTamwVr7zpcKiwUEzpEySyv/SSqUGpViFcTBV9iHceWld@sNaqZtGF99w3PfxQR6Nfwp9/q9oKGnvUR/IH@fvT46Pnk8PVse7km/@z/I8AE "Python 2 – Try It Online") A bit longer than the [Python 3 answer from ArBo](https://codegolf.stackexchange.com/a/187210/56555) but posted as a different approach in Python 2 anyway. [Answer] # [Ruby](https://www.ruby-lang.org/) `-n`, ~~38~~ 34 bytes -4 bytes from @historcrat! ``` p (?A..?Z).count{|c|~/#{c}/i}/26.0 ``` [Try it online!](https://tio.run/##HYzLDgExGEb3nuIzLkHoiIXtkAgewMpC0ukUZab/6LSo26Ory@ok5yTHuNSHUKKTTBlL1l0myGl7f4jHK27cxTNWz3g0ZsMQopnK4MmhdPZHA80LCaVh9xILSnNpQVvMlZF9LLkxPonwTbw6ygyC50XuWW31NSenxBGpoYvGlq44uKKsQGdp/q@c3zwy2tWiSaPZ2rR7ST16U2kV6SoM9Ac "Ruby – Try It Online") [Answer] # C, 95 bytes ``` f(char*s){int a[256]={},z;while(*s)a[*s++|32]=1;for(z=97;z<'z';*a+=a[z++]);return(*a*100)/26;} ``` (note: rounds down) ### Alternate decimal-returning version (95 bytes): ``` float f(char*s){int a[256]={},z;while(*s&&a[*s++|32]=1);for(z=97;z<'z';*a+=a[z++]);return*a/26.;} ``` This borrows some from @Steadybox' answer. ]
[Question] [ # Problem Given no input write a program or a function that outputs or returns the following string: `(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)` # Rules * Shortest program wins. * Trailing whitespace allowed. * Trailing newlines allowed. * Unused parameters for functions allowed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` "(<>.".∞ηJÀ24£.∞ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fScPGTk9J71HHvHPbvQ43GJkcWgzi/P8PAA "05AB1E – Try It Online") **Explanation** ``` "(<>." # push this string # STACK: "(<>." .∞ # intersected mirror # STACK: "(<>.<>)" η # compute prefixes J # join to string # STACK: "((<(<>(<>.(<>.<(<>.<>(<>.<>)" À # rotate left 24£ # take the first 24 chars # STACK: "(<(<>(<>.(<>.<(<>.<>(<>." .∞ # intersected mirror # STACK: "(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)" ``` [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` for i in range(11):print(end='(<>.<>)'[i-12:i+2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw9BQ06qgKDOvRCM1L8VWXcPGTs/GTlM9OlPX0MgqU9soVvP/fwA "Python 3 – Try It Online") [Answer] # JS (Jsfuck), 10,614 bytes Didn't have access to the website, had to figure this all out manually -.- ``` (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] ``` # Explanation: Most of the characters are relatively easy: For the brackets im executing ``` ([]["fill"]+[])[13] // '(' ([]["fill"]+[])[14] // ')' ``` The full stop is gotten by making js create a scientific notation number like 1.1e+21 And taking the dot character after converting to a string The square brackets are harder, we have to execute the function to create an italic html object string and steal the angle brackets. The main trick in this is getting the 'c' for the word italics, which requires building up another function to take the c from 'function' There's a lot of scope for improvement here, mostly on which functions are used to get the square brackets. I also recall an easier way to get the character 'c' if italics is better, but i'd have to look though my old files to find it ``` console.log( (!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])] +(+[]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+!+[]] +(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]])[+!+[]+(+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+[])]) ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 12 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` pΙ2○3V?hG]‘Γ ``` Explanation: ``` pΙ2○3V?hG]‘ Push compressed string of the first half of the string (this is the kind of thing this compressor was made for) Γ mirror, swap chars & palindromize with one character overlap ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=cCV1MDM5OTIldTI1Q0IzViUzRmhHJTVEJXUyMDE4JXUwMzkz) [Answer] # [C# (Mono)](http://www.mono-project.com/), ~~54~~ 52 bytes ``` s=>"(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)" ``` [Try it online!](https://tio.run/##XYyxCsIwEIZn8xRHpwS0uCcNSMFJJwcHcUhjKJE2kV4iSOmzx9hswt338x/cp3E3eudTROt6uHwwmJETPShEOMyEvGI3WA0YVMhxjE4L3z2NDtt8m/KPVNAkbGRFBRUyT/1bsUIWssIVpTLJqsT/5G9vH3BW1tFivt1BTT0ymMmm9Q79YOrrZIM5WWeoonvGOFnIkr4 "C# (Mono) – Try It Online") *-2 bytes thanks to Kevin Cruijssen* RIP C# [Answer] ## [Retina](https://github.com/m-ender/retina), 30 bytes ``` (<>.<>) 5`. $&$' 7`. $`$& ^. ``` [Try it online!](https://tio.run/##K0otycxL/P@fS8PGTs/GTpPLNEGPS0VNRZ3LHMRIUFHjitPj@v8fAA "Retina – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~28~~ ~~27~~ ~~25~~ 22 bytes 3? 4? bytes thanks to @KritixiLithos ``` i(<>.<>)òÙxlHÄ$xGòxÍî ``` [Try it online!](https://tio.run/##K/v/P1PDxk7Pxk5T@vCmwzMrcjwOt6hUuB/eVHG49/C6//8B "V – Try It Online") ``` i(<>.<>) 'insert (<>.<>) ò ò 'recursively Ù 'duplicate this (bottom line) down x 'delete the first character l 'and break when there's only one character left H 'go to the top of the buffer Ä 'duplicate that line up $x 'delete the last character G 'and go back to the bottom of the buffer x 'delete the extra ) left by the loop Íî 'and remove all newlines ``` [Answer] # [R](https://www.r-project.org/), 42 bytes ``` cat(substring('(<>.<>)',-4:6,2:12),sep='') ``` Fairly simple program that takes advantage of the way substring works in R. So `substring('(<>.<>)',-4:6,2:12)` produces the following vector ``` > substring('(<>.<>)',-4:6,2:12) [1] "(<" "(<>" "(<>." "(<>.<" "(<>.<>" "(<>.<>)" "<>.<>)" ">.<>)" [9] ".<>)" "<>)" ">)" ``` `cat` with an empty separator outputs it to STDOUT in the required format. [Try it online!](https://tio.run/##K/r/PzmxRKO4NKm4pCgzL11DXcPGTs/GTlNdR9fEykzHyMrQSFOnOLXAVl1d8/9/AA "R – Try It Online") [Answer] # Charcoal, ~~18~~ 17 bytes ``` F⁶…(<>.<>)⁺²ι‖BO⁷ ``` [Try it online!](https://tio.run/##BcExCoAwDADA3VcUpwTUwUEHxcE@QPEHpaRUCFZiK/j6eOejE58cq4YkBgY0u5xXBvt5JhvTDTXMSzcvWDdm5/JA35gTEafqoMDk81pyJgn8bS8JuxtGnFS1fbV9@Ac "Charcoal – Try It Online") Link is to verbose version of code. ~~Uses the new Slice operator.~~ [Answer] # TrumpScript, 70 Bytes I know, it's a boring solution. ``` say "(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)" America is great ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes ``` "(<>.<>)"aᶠckb ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X0nDxk7Pxk5TKfHhtgXJ2Un///@PAgA "Brachylog – Try It Online") ``` "(<>.<>)" # string aᶠ # get all Affixes (pre- and suffixes) c # Concatenate kb # remove last (Knife) and first (Behead) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~59~~ 57 bytes ~~2~~ 4 bytes less than a simple `puts()` solution. There is sure to be some elegant recursive solution, but so far the overhead becomes too large at every attempt. ``` f(i){for(i=1;i++<12;)printf("%.*s",i,"(<>.<>)"+i/7*i%7);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPT1tA6U1vbxtDIWrOgKDOvJE1DSVVPq1hJJ1NHScPGTs/GTlNJO1PfXCtT1VzTuvY/UIlCbmJmngZQvwZIAAA "C (gcc) – Try It Online") [Answer] # Brainfuck, ~~198~~ ~~175~~ 167 Bytes I have never done a codegolf, so this is my first one. Feedback is highly appreciated. ``` ++++[>+++++<-]>[>++>+++>+++>++>++[<]>-]>.>.<.>.>++.<<.>.>.>>++++++.<<<<.>.>.>>.<<<.<.>.>.>>.<<<.>.<<.>.>.>>.<<<.>.>+.<<.>.>>.<<<.>.>.<.>>.<<<.>.>.>.<<<.>.>.<<.>.>.<.>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwii7UCkto1urB2ICeJBMRBF28TaASX07PRsgBgooGcDZujZQXSB@HAREFsPhWOnZ4PGt4OZABcA6UBwkIThsnr//wMA) I went for the most obvious solution in my opinion. First, I set cells 1-5 to one of the letters "().<>". Then I just go to the right cells and output the character. UPDATE: I changed the order in which the characters appear on the "tape" making the program way shorter and more efficient. UPDATE 2: Just revisited my post after a while and realized, that using a shorter sequence for setting up the cells I could save some bytes. [Answer] # JavaScript, 47 bytes ``` g=(i=2)=>i>12?'':'(<>.<>)'.slice(i-14,i)+g(i+1) f=(i=11)=>i?f(i-1)+'(<>.<>)'.slice(i-13,i+1):'' // Both of the above work and are the same size document.write('<pre>Actual g(): ' + g() + '\nActual f(): ' + f() + '\nExpected: (<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)</pre>'); ``` Uses the same method as [Rod's Python](https://codegolf.stackexchange.com/a/127443/48878) answer. [Answer] ## Mathematica 41 bytes ``` ""<>"(<>.<>)"~StringDrop~i~Table~{i,-5,5} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` A(<>ι(<ιι.ι.<ι.ιι.‖B ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noUaNnbndmrYnNt5bqceENmAKSDxqGHa@z2L/v8HAA "Charcoal – Try It Online") Thanks to [Destructible Lemon](https://codegolf.stackexchange.com/users/55896/destructible-lemon) for noticing a pattern (-4). AST: ``` Program ├A: Assign │├'(<>': String '(<>' │└ι: Identifier ι ├Print │└'(<': String '(<' ├Print │└ι: Identifier ι ├Print │└ι: Identifier ι ├Print │└'.': String '.' ├Print │└ι: Identifier ι ├Print │└'.<': String '.<' ├Print │└ι: Identifier ι ├Print │└'.': String '.' ├Print │└ι: Identifier ι ├Print │└ι: Identifier ι ├Print │└'.': String '.' └‖B: Reflect butterfly └Multidirectional ``` What `‖B` does is basically visually palindromize canvas. [Answer] # [C (gcc)](https://gcc.gnu.org/), 61 bytes I know this is lame but it's much shorter than my other solution... ``` f(){puts("(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)");} ``` # [C (gcc)](https://gcc.gnu.org/), 103 bytes Here's a version where I'm trying to be somewhat tricky... ``` char*e="(<>.<>)<>.<>)>.<>).<>)<>)>)";f(i,n){for(n=2;n<8;n++)for(i=0;i<n;i++)putchar(e[i]);puts(&e[i]);} ``` # [C (gcc)](https://gcc.gnu.org/), ~~117~~ 115 bytes A recursive version that's fully tricky... ``` char*e="(<>.<>)";main(i,j){if(i<6){for(++i,j=0;j<i;putchar(e[j++]));main(i);}else if(i<12)printf(e+i++-6),main(i);} ``` [Try it online!](https://tio.run/##Pcs9DsIwDEDhq6BONm4QMHRJ2osghshyqCNIq7RMVY/dOfwIsT69j82NuRTufd5LW4HrDq7Dyj68JtA64qIB1DW4hCED0Tu1Rxud2vE5fxTIJRJdEX8E7Sr3SXZfdjrjmDXNAYSUyDRY/69StjQY9tzLCw "C (gcc) – Try It Online") [Answer] A crowd of blank stares watching Batman [in honor of Adam West](https://codegolf.stackexchange.com/q/126223/70347)... # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 393 bytes ``` s=>{string b="NanananaNanaBATMAN!NanaBATMAN!NANANanaBATMAN!NANAnanaNanaBATMAN!NANABATMAN!NanaBATMAN!NANABATMAN!naNABATMAN!NANABATMAN!naNANAnaNANABATMAN!naNANANABATMAN!naNABATMAN!naNANAnanaNA",r="",t;for(int i=0;i<176;)if(b[i]=='B'){r+="<>";i+=7;}else{t=b.Substring(i,4);if(t=="Nana")r+="(";else if(t=="nana")r+="<";else if(t=="NAna")r+=">";else if(t=="NANA")r+=".";else r+=")";i+=4;}return r;} ``` [Try it online!](https://tio.run/##bVFPa4MwFL/7Kd5yaUKdbFDWQ4xgB7u1DDroYewQbSwBjZDEwRA/u0vUubXzPch7@f0JL0lu7vNaix5c5CU3Bl51fdG8CjzSDqsPY7mVOXzW8gx7LhUmM/Ur8nH8MlZU0Uuj8thYLdUlhLEmUAALesOSdgQgY@jA1ZC@7tK3fXq4@9umLq@3t2IHLfum1qnTZdSf9Q9a8v2IfUWhZgiFlha1xlJZkOyByvhx@0SJLHD2Lj8YW@1WpNVrhuIEUblmW9qJ0ojWsiw6Ntl4eyzDDaHOY9n4DIh4C0bUa2Ei1EzE14QfaCSSW8JNORDRRPieDINsaKeFbbQCTbueBks/91wrU5ciOmlpBS4wSs@8gpMwFhFCZ0c3dF3/DQ "C# (.NET Core) – Try It Online") [Answer] ## **[q](http://code.kx.com/q/ref/card/), 29 bytes** `raze"(<>.<>)"{(y-5)_x}/:(!)11` *-2 bytes thanks to streetster* EDIT for explanation: Language is right to left interpreted. **How it works** ``` raze"(<>.<>)"{(y-5)_x}/:(!)11 (!)11 /yields indices [0-10], right parameter of function (y) /: /each right: loop right parameter of a dyadic function { } /function "(<>.<>)" /left parameter of function (x) (y-5) /subtract 5 from y (indices) _ /remove first y chars from x, or last y chars if negative raze /flatten string output to produce the final string ``` [Answer] # [Haskell](https://www.haskell.org/), ~~55~~ 45 bytes ``` map take[2..7]++map drop[1..5]>>=($"(<>.<>)") ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexQKEkMTs12khPzzxWWxvETynKL4g21NMzjbWzs9VQUdKwsdOzsdNU0gSqzsyzLSgtCS4pUkn7/y85LScxvfi/boRzQAAA "Haskell – Try It Online") First Haskell answer to beat the hardcoded solution! ## Explanation The way this answer works is by building a list of functions to be applied to the string `(<>.<>)`. First we build the left and center with ``` map take[2..7] ``` which gives us all the prefixes from size two to seven. Then we build the right with ``` map drop[1..5] ``` which gives us all the suffixes from size six to two. Once we have the list of functions we use a monadic bind (`>>=`) which is just `concatMap` but shorter. The function we concatmap with is `($"(<>.<>)")` which applies the input to the string `(<>.<>)`. This makes the string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes 1 byte thanks to Kritixi Lithos. ``` U;\UṚṖ “(<>.<>)”;\ḊṖ,Ç ``` [Try it online!](https://tio.run/##y0rNyan8/z/UOib04c5ZD3dO43rUMEfDxk7Pxk7zUcNc65iHO7qAojqH2///BwA "Jelly – Try It Online") [Answer] # Java 8, 52 bytes ``` x->"(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)" ``` Boring, but there isn't any way to make this shorter in Java.. Just initializing a temp String is already 11 bytes.. (`String t="something";`), and using `substring` a couple of times certainly costs too many bytes.. Shortest alternative to a literal return is probably this (58 bytes): ``` x->"(<(x(x.(x.<(x.x(x.x)x.x)>.x).x)x)>)".replace("x","<>") ``` [Try it here.](https://tio.run/##LY5BDoMgEEX3PcXEFSzkAlpuULvosukCkTZYRAODsTGenaKYzLzkzyQ/rxezKMdJ2b77RmmE93AT2q4XAG1RubeQCpo9AjzQafsBSe5tryTCQqt03y4JHgVqCQ1YuEJcSr46hcHZgtSk5mnYvvUBnkkzD@RIOS2qLVZ74RRakwrP3nnUHQzJi2SH5wsEPaV@HtXAxoBsSi8klkligzH0tNviHw) [Answer] ## Python 2, 57 bytes ``` print''.join("(<>.<>)"[max(0,n-5):n+2]for n in range(11)) ``` I say it looks like a gang of owls peeking out behind their leader. Just saying. [Answer] # [MATL](https://github.com/lmendo/MATL), 28 bytes ``` '(<>.<>)'XH5:"H7@-:)wh2M@+)h ``` [Try it online!](https://tio.run/##y00syfn/X13Dxk7Pxk5TPcLD1ErJw9xB10qzPMPI10FbM@P/fwA "MATL – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), ~~245~~ 210 bytes Golfing in progress. ``` >++++++++[<+++++>-]>++++++[<++++++++++>-]>++++++[<++++++++++>-]<++>>++++++++[<+++++>-]<++++++<<<.>.<.>.>.<<.>.>.>.<<<.>.>.>.<<.<.>.>.>.<<.>.<<.>.>.>.<<.>.<<+.>.>.>.<<.>.<<.>>.>.<<.>.<<.>>>.<<.>.<<.>.>.<<.>>.<<. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v/fThsKom3AlJ1urB2KAH5RIM8OixFQRTY2Nnp2eiAMJCEUiIFg6SExUZSACW10SVQOqi6IPJD8/x8A "brainfuck – Try It Online") [Answer] # Haskell, 95 bytes ``` import Data.List import Control.Arrow concat$tail$init$uncurry(++)$inits&&&tail.tails$"(<>.<>)" ``` This is far longer than the 49 bytes necessary for a string literal with the output, but the best I could do to utilise [the structure](https://codegolf.stackexchange.com/questions/127428/a-crowd-of-blank-stares#comment314011_127428). As usual, I love arrows, and `inits &&& tails` does produce a tuple of the list of leading substrings and the list of trailing substrings of the input. Then those two tuple elements are put together in one list by passing the tuple to `++`, and that list is `concat`enated to one large string. The `tail` and `init` calls avoid duplicating the `(<>.<>)` in the middle (one generated by `inits`, the other by `tails`) and drop the unwanted parenthesis from the start and end, taking only substrings of length 2 or more into account. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` “(<>.<>)”ḣJœ|ṫJ$ḊṖ ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//4oCcKDw@Ljw@KeKAneG4o0rFk3zhuatKJOG4iuG5lv// "Jelly – Try It Online") ### How it works ``` “(<>.<>)”ḣJœ|ṫJ$ḊṖ Main link. No arguments. “(<>.<>)” Set the argument and return value to s := "(<>.<>)". J Yield all indices of s, i.e., [1, 2, 3, 4, 5, 6, 7]. ḣ Dyadic head; yield s's prefixes of lengths 1 to 7. $ Combine the two links to the left into a chain. J Indices; yield [1, 2, 3, 4, 5, 6, 7]. ṫ Dyadic tail; yield s's postfixes of lengths 1 to 7. œ| Multiset union; concatenate the results to both sides, discarding the copy of s. (s is both a prefix and a postfix.) Ḋ Dequeue; remove the first prefix, i.e., "(". Ṗ Pop; remove the last postfix, i.e., ")". ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~62~~ 61 bytes ``` main(n){while(write(++n<13,n/7*(n-7)+"(<>.<>)",n/7?14-n:n));} ``` This terminates only after timing out on TIO because the write to standard *input* fails, but it *will* terminate in a terminal. The program relies on a specific order of evaluation (undefined behavior) and won't work with, e.g., gcc. *Thanks to @Steadybox for an idea that saved a byte!* [Try it online!](https://tio.run/##S9ZNzknMS///PzcxM08jT7O6PCMzJ1WjvCizJFVDWzvPxtBYJ0/fXEsjT9dcU1tJw8ZOz8ZOUwkkZm9ooptnlaepaV37/z8A "C (clang) – Try It Online") ### Verification ``` $ cat crowd.c main(n){while(write(++n<12,n/7*(n-7)+"(<>.<>)",n/7?14-n:n));} $ clang -o crowd crowd.c 2> /dev/null $ ./crowd 0> /dev/null (<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>) ``` ## Alternate version, 62 bytes ``` main(n){while(++n<13)write(1,n/7*(n-7)+"(<>.<>)",n/7?14-n:n);} ``` At the cost of one more byte, the solution becomes a lot more portable. [Try it online!](https://tio.run/##S9ZNzknMS///PzcxM08jT7O6PCMzJ1VDWzvPxtBYs7wosyRVw1AnT99cSyNP11xTW0nDxk7Pxk5TCSRmb2iim2eVp2ld@/8/AA "C (clang) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes couldn't resist beating the [current python 2 answer](https://codegolf.stackexchange.com/a/127525/76162) ``` print "(<(<>(<>.(<>.<(<>.<>(<>.<>)<>.<>)>.<>).<>)<>)>)" ``` [Try it online!](https://tio.run/##K6gsycjPM/qvrGGjYWMHRHogbAMm7CCkJoQEExCupp3m/4KizLwSBSUStSn9/w8A "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` “(<>.<>)”µṖ¹Ƥ;¹ÐƤṖḊ ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//4oCcKDw@Ljw@KeKAncK14bmWwrnGpDvCucOQxqThuZbhuIr//w "Jelly – Try It Online") ]
[Question] [ ## Defintion A [centrosymmetric matrix](https://en.wikipedia.org/wiki/Centrosymmetric_matrix) is a square [matrix](https://en.wikipedia.org/wiki/Matrix_(mathematics)) that is symmetric about its center. More rigorously, a matrix \$A\$ of size \$n \times n\$ is centrosymmetric if, for any \$i,\: j \in ([1, n] \cap \mathbb{Z})\$ the following relation is satisfied: $$A\_{i,\:j}=A\_{n+1-i,\:n+1-j}$$ ## Examples of such matrices Here is an illustration of the symmetry of a matrices like these (borrowed from the aforementioned Wikipedia article): [![Centrosymmetric 5 by 5 matrix illustrated in a really nice way](https://i.stack.imgur.com/a3ZBh.png)](https://i.stack.imgur.com/a3ZBh.png) An even-side-length (\$4\times 4\$) centrosymmetric matrix: $$\left(\begin{matrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 8 & 7 & 6 & 5 \\ 4 & 3 & 2 & 1\end{matrix}\right)$$ And an odd-side-length (\$3\times 3\$) one: $$\left(\begin{matrix} 1 & 2 & 3 \\ 5 & 6 & 5 \\ 3 & 2 & 1\end{matrix}\right)$$ ## Task and Specs Given a square matrix of size at least \$2\$, output one of two distinct and consistent values, deciding whether the matrix is centrosymmetric or not. You can assume that the matrix will consist entirely of positive integers. **However, your code must also be centrosymmetric.** That is, it must be a program / function (or equivalents) consisting of \$n\$ lines, each of which containing \$n\$ **bytes** in your language's encoding, and must satisfy the definition given above, but with bytes instead of positive integers. Your submission's score will be the value of \$n\$, with a lower \$n\$ being better. You can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and in any reasonable format, while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. You may (optionally) choose to take the size, \$n\$, as input too (unless you take input as a 1D list, in which case you may only take \$n^2\$ as additional input). ## Test cases Truthy: ``` [[1, 2], [2, 1]] [[1, 2, 3], [5, 6, 5], [3, 2, 1]] [[10, 5, 30], [2, 6, 2], [30, 5, 10]] [[100, 100, 100], [100, 50, 100], [100, 100, 100]] [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]] [[3, 4, 5, 6, 7], [5, 6, 7, 8, 9], [3, 2, 10, 2, 3], [9, 8, 7, 6, 5], [7, 6, 5, 4, 3]] ``` Falsy: ``` [[1, 2], [1, 2]] [[1, 2, 10], [5, 6, 5], [11, 2, 1]] [[14, 5, 32], [2, 6, 2], [30, 5, 16]] [[19, 19, 19], [40, 50, 4], [19, 19, 19]] [[1, 2, 20, 4], [7, 6, 7, 8], [8, 7, 6, 6], [3, 3, 2, 1]] [[3, 4, 5, 6, 7], [5, 6, 7, 8, 9], [4, 5, 10, 4, 5], [5, 6, 7, 8, 9], [3, 4, 5, 6, 7]] ``` [Answer] # JavaScript (ES6), size ~~12~~ ~~11~~ 9 All versions return **false** for centrosymmetric or **true** for non-centrosymmetric. --- ## 1-dimensional array + length, size 9 (89 bytes) Takes input in currying syntax `(length)(array)`, where *array* is 1-dimensional. ``` w=>a=> // a.some // (v=>v- // a[--w])// ///////// //)]w--[a // -v>=v( // emos.a // >=a>=w ``` [Try it online!](https://tio.run/##rZNba4MwFMff/RSHvmhotN7bDhRG3/cFOh8ks1tHNUWdsk/vcky8rPTCYILxf@4m/vxMm7Ri5fFcmwV/y7pD1LVRnEYxrFZaalU8z1AZTRQ3Zu/bm2abEKFWwyUUSVrT3KdCgdnEUWOgynJeWb0vjtI4ajvGi4qfMuvE3w19lxV1yavvPM/q8siedKLN4wfDJ8ZeA3AouFQ8XQqOlpDLrO0sCzxMDCiEVKxCevRRmY2Z4NmYjbmiUo7zZMSx7xXbdFoGBwQXjmG50sgJf789@NMG1hQ2aG16OezIp3c25QayXd9o6jO2lD1hOzsaezq3bR@cD5MSi3HslYEbRwy0LEvkLkZsFrBEe4RH2SNCQ3wASdkjTqOtoBpthdZkS8AmW2K20BIrT88Gi2JmsY@03Amwn2uDEAJL0MGo@FfJMmDCTQR1v/akvxYvvDDZH@HE521Q1Pd1JGXBcKpY5zwk1JeEujcJDe8Ui2@qbmQHC5DQnrIp9hBM11ZkrmcYjWiiK1RIeRT@A05f/XtUqlsAz/rgwO4H "JavaScript (Node.js) – Try It Online") --- ## Matrix + width, size 11 (131 bytes) Takes input in currying syntax `(width)(matrix)`. ``` /**/w=>a=>a .some(r=>r. some(v=>v-a [y][w-++x], x=!y--),y=w );'*/'/*';) w=y,)--y!=x ,]x++-w[]y[ a-v>=v(emos .r>=r(emos. a>=a>=w/**/ ``` [Try it online!](https://tio.run/##pZPZUoMwFIbv8xSxN5CSpCxdXCbMON77AsgFE6nWEeKECuXpaxZqY5U6jkyAkz9nyfLlpWiLhsvN25bU4rHcr9l@Np3OOpYWqgHaiKr0JUslBcZsWdqSAmR9nnUkCHY5Bjt20ROCcM86gG686cybTb0bBDrWY0RIf8F2AOe7ICBdlvcZKEibstYvK9EAKlMmjUlBkTLVOl1@z0XdiNeSvoon37sr660UTV9V5VZu@LWHgDu@9mPkZ1mEYZxjmMUYRnmOTn2Sgw@GiXZbYLjEcKHNxKjjQaHyU1HhkH05FEqsHoXjgaEeth8dYezFSf/T4XuWuTNnDOfHaa8wvNS9S2Me1jE3biNLWehcOouZtM7xNR2GV85ehMeNujKDTpnBNKmSHypFkSoFIJw4IE2wFhyarOAgZQWHKys4cFnBIcwKDmZWcFizggPcMI8jdYPHEb0JyGlVvPkNSzNKaWN7nKWc8udC3qlLcrv1kXpgAD3oN@Jd8hJypSMF5pe98B7qe1ET/id@zf8sv1F4AnAU/UKwPfQkHiF4ORqoDt@@hq@BXgOiM3QW3PgQsPqZ3OVA3b/JnQ@30TqOwe0kUZX2Hw "JavaScript (Node.js) – Try It Online") ### Payload ``` w => a => a.some(r => r.some(v => v - a[y][w - ++x], x = !y--), y = w) ``` ### Container ``` /**/CODE;'*/'/*';EDOC/**/ ``` --- ## Matrix only, size 12 (155 bytes) This is my original solution, which computes the width of the matrix by itself. ``` /**/a=>a[w=a .length-1,s= 'some']((r,y )=>r[s]((v,x )=>v-a[w-y][ w-x]))////*/ /*////))]x-w []y-w[a-v>=) x,v((]s[r>=) y,r((]'emos' =s,1-htgnel. a=w[a>=a/**/ ``` [Try it online!](https://tio.run/##pZPdbtsgGIbPuQqUE@wMHDtO0nYSlqae7wYYB4jRpFNsKvCc@OozftyURXE1aUjYfC/fH@jhlxiEleb1rSed/qkuL/SyWi5XgjaCnagAxVF1@/5AKmwpQFa3CvEsM3gEOW0Ms84Y8NkbA3ERZOQMnMiZ5/nKjeUKuOlGnvMzOQHGR3JiggwNzcEZD1nGLTPeGLFxBlKttghQiyty6PedOhZAUBfRUOHbukjdWX1UxVHvM/Ssut5oO7at6s2r/IpykO6/ZIxVGK45hmyNYcVdU3cdMKy9zxbDHYZbv6yDOhNROicXUk55d1OJOupVORNV@r348e5hvb2xrw6ftIrh5qPbBwwfvfUYlu/tb4Lb7Al8itCrT/B3LgyfkvOXH5fzFDaTGtMypKpDmds6AMJFytICeyUFKiopVVFJ0boqV76ikkIWlZS0qKS4RSVlLiopeFFJ6YtKiuAC8KIVb5mlDSuKwkZL0kYW8iDMs3tE3/osdwN@gQhmVv82UkHp9BzdXBL60X3XHZH/znH4z8NRlTcgV9VnJEcK6vUMybv7UQ6FOANqE8WByWRrvsf1u/fDfYJ3E4D/R/BmeozRcQ7yJIkrc/kD "JavaScript (Node.js) – Try It Online") ### How? We need a few critical tokens that cannot be split: * `some` * `length` * `)=>` Line-feeds may be inserted almost anywhere else. The unrolled payload code reads as: ``` a => a[w = a.length - 1, s = 'some']((r, y) => r[s]((v, x) => v - a[w - y][w - x])) ``` and is wrapped inside the following structure: ``` /**/CODE////*/ ``` which, once reversed, becomes a valid block comment: ``` /*////EDOC/**/ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 2 ``` ⁼Ṛ Ṛ⁼ ``` [Try it online!](https://tio.run/##y0rNyan8//9R456HO2dxATGQ9f///2hjHQUTHQVTHQUzHQVzJIaFjoKljgJQ1khHwdAATBmDhSzA0mZgpXAG0AjjWAA "Jelly – Try It Online") Takes input as a flattened square matrix (vector of size \$n^2\$). [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), size 24 ``` &:00p110p920p::*:v vp01:+1g01-1pg02g01&_v#< >00g`#v_>: 1$^ v2p011< v:g00p029p01< @ >0g1+20p^>*:#v_1# .#<@ . v+1g00gg02g01<$ >1+10pv0 >:10g-\88++20g -g- | vg02p011_v#`g00g01-1 <1 >1+20p >: ^ ^ < < ^ ^ :> p02+1> 1< 1-10g00g`#v_110p20gv | -g- g02++88\-g01:> 0vp01+1> $<10g20gg00g1+v . @<#. #1_v#:*>^p02+1g0> @ <10p920p00g:v <110p2v ^$1 :>_v#`g00> <#v_&10g20gp1-10g1+:10pv v:*::p029p011p00:& ``` [Try it online!](https://tio.run/##xVLLboQwDLz7KyyBOBCBbPZRsKKID1mxq0rb3CouzWn/nU4CUnvpuUYyxPHY4zHvz4@vz/jcNmZuTGRVlXUaZDVrLSFIaRU1p1G00zXKgI/mnipPQSQ@qnQPxj@m9UJpAEQ9c7KIijJMOHuegYjqUHsJrQGoFfeVn7mnlOtL3Kv7moM60EhCwVRidxtHB1zkLnaly4sScnMXMHlkaGbH7JVC6YCcQmvBU8wT/2H/e@H3987TAhz0choo64eZJB4q571AgkSvAshKQALnxvHWYXoLJHlTgHLtARuynFnvRD3Pvuq5ymJZG5bSIUqgGYLt20Zm3rYvXRIttf4iaeFQOZAHk2avvhZ26ixvKg@Y8MfYsW1FRWsQ3LYLn/jMF77y2@FHnhAbWAXuhMOI4BWXuz/z6Rs "Befunge-93 – Try It Online") **Input:** `n`, followed by the elements of the array, all separated by spaces. NOTE: you may need to use a different interpreter if you have a large enough input. I'm sure there's a better way to do this, I just wanted to try this in Befunge. The actual code portion is the top half. ## How? The code is divided into two main sections, the **initialization** and the **verification**. **Initialization:** ``` &:00p110p920p::*:v vp01:+1g01-1pg02g01&_v#< >00g`#v_>: 1$^ ``` This section of the code writes the input matrix right below the code as ASCII characters. Both this and the next section use the three cells at the top left of the code as data. They are stored as `n, i, j`. **Verification:** ``` v 1 v2p011< v:g00p029p01< @ >0g1+20p^>*:#v_1# .#<@ . v+1g00gg02g01<$ >1+10pv0 >:10g-\88++20g -g- | vg02p011_v#`g00g01-1 <1 >1+20p >: ^ ^ < ``` This sections checks every index \$i, j\$ [1-indexed] against the condition \$ A\_{i, j} = A\_{n+1-i, n+1-j} \$. However, we have a problem: we have \$j\$ offset by \$8\$. To fix that, the following formulae are used: \$ i' = (n + 1) - i \$ \$ j' = n + 1 - (j - 8) + 8 = (n + 1) + (8 + 8) - j\$ The other portions of code are unread garbage to make it centrosymmetric. [Answer] # [Haskell](https://www.haskell.org/), \$n = 8\$ *No comments!* Takes input as a 1-D list ``` s a b= a/=b f =s<*> reverse esrever >*<s= f b=/a =b a s ``` [Try it online!](https://tio.run/##JYzBCsIwEETv@Yo9eGhLsKR6zObUq18gHjaYYLBtSjb4@3GrMww8BmZexO@wLC2tey4VZqp0vuUtpyd0nXV93xgIPAIoENGIXkVAtoOTpoRPKBxU4B9J4wbLCFF5HOkYHDP0csFtpbThXtJWTxHuRk/6oo3kKv7TpM2jfQE "Haskell – Try It Online") # \$n= 10\$ Takes input as a 2-D matrix ``` r =reverse s a b=a/=b f =s<*>r c =concat g = f<$>c c>$<f = g tacnoc= c r>*<s= f b=/a=b a s esrever= r ``` [Try it online!](https://tio.run/##HY2xDoMwEEP3@4obGABFRUDHXKau/QLEcKSBokKCkqi/n54qL0@2Zb85fdxxlP28Qsz44My3Z/Bhf2Fda9M0JSJF93UxOUjIuBB3tMCKiJR0ayJYIRu85QwbEuKqK2PBmkpLiXCDzNYHK4mFaFqdhHCFhTqmRRYTuPR/IIzl5N3TFXefqw2nqVeDGlU/q2lUd9Eo1IsziDeXHw "Haskell – Try It Online") Thanks to [potato44](https://codegolf.stackexchange.com/users/69655/potato44) for all their help in chat. And [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for golfing off a row. ## Explanation The general idea here is a simple one, we `concat` the list and compare it to it's reverse. However since we want to be centrosymmetric we have to tread carefully. First we write the code as we would normally: ``` g=((==)<*>reverse).concat ``` Now in order for our reverse lines to also be valid Haskell we need the left hand side of our equations to look like a function definition `tacnoc.)esrever>*<)==((` doesn't. The first step to fixing this is disposing of parentheses. ``` s a b=a==b f=s<*>reverse g=f.concat ``` However we have some new problems now. Both `.` and `==` when reversed are the same, so our reversed lines attempt to redefine the operators (`<*>` reversed is `>*<` so we are fine on that front). `.` can be replaced with `<$>` since functions are functors. And we can replace `==` with `/=`, which negates our output, but that is still within the specs. Now we have ``` s a b=a/=b f=s<*>reverse g=f<$>concat ``` In order to trim down our line length we alias `concat` and `reverse`. ``` r=reverse s a b=a/=b f=s<*>r c=concat g=f<$>c ``` Now we just finish this by making everything centrosymmetric and square. The shorter 1-D version works in much the same way except since there is no need to `concat` we can save two lines by removing it. [Answer] # [Python 2](https://docs.python.org/2/), size 10 (109 bytes) ``` def f(a):# return(a# ==[r[::-1# ]for r in# a[::-1]])# #)]]1-::[a #ni r rof] #1-::[r[== #a(nruter #:)a(f fed ``` [Try it online!](https://tio.run/##vVO7boMwFJ3rr7jCAyA5FYaEJJboUqlf0M31YCmgIEUmcsiQryd@0ThRU6lLB@D6nHNfx@J4GfeDKqdp13bQZTJnGIFux7NWmcSoabjmjC0oRqIbNGjoFUbSQULkGOFcCLpgjEuEVW94PXQCYQdp3jQIy0zp89hqQJjlMjNd2t101L0aIfk0zP6SIFtamtLAOacESkGAlwRMCxM4hEBl4xWBmsDKhpVDZ0lhUKMpQmYdilQep8UsK@zBvyzi4tXD@VsQdyewvA2wJrCxp40L54mWTnYbyua49jbjPpnANtqhuC24dWRUNISuVCWEYOjFmydJ2rylxN4ZQg4KH0g@5OHUPrHVfaPFaPHgK6V3xvoNqvKJsXWQmbn944wIpjrHIipqW870@mdD62DPHw1dhuv2wmeeR0V@N9QT6fuwa9OZTZLkX/8V0@/1dDz0Y5Z@qTTPpys "Python 2 – Try It Online") ### Previous [Python 2](https://docs.python.org/2/), size 14 (209 bytes) ``` lambda a:all(# a[i][j]==a[-i# -1][-j-1]for # i in range( # len(a))for j # in range(len(# a))) # # )))a #(nel(egnar ni # j rof))a(nel # (egnar ni i # rof]1-j-[]1- #i-[a==]j[]i[a #(lla:a adbmal ``` [Try it online!](https://tio.run/##3VPLboMwEDzXX7GCAyCZikdCHhK9VOoX9Ob44CiQGDkmIvSQr6deAwmJmkq9Fgmznpld747F6dIeap10Zb7plDhudwLEWijlu0QwyVnF81ywULokjDkLK7OWdQMukSA1NELvCx/MVhXaF0GAXIXsyCFuSgVBAOPjEvcaG1wQ19eF8ou9Fg1oadgKmro0DOIovnKArOF4bDphZiWuDJnIc14xLhmWUsr0D2K3PQrVnRqpW3A@m6/2cHEIdiewb8ZYTCHhFFhCIeYYWIRCivGcQkZhjmFq0VESGdRooiEzG4qkPR5HoyzCTb8gYuP5w/4qmJ5OYXZrYEFhibulDceOZlZ2awpz7PGYcZ9MYTWZIboNuLLkpOgQ2lIp53xNXnrzBPXyN4@W5nYJsdDwAedDqHPxxFb7nQwWRw@@xvGdsf0EafLE2GyQmb771xoxmGodm1CTY5ORXvxsaDbY80dDZ8N198Jnnk@K/G5oT3jv9a7wRtZxnH/3P5qZXs8nJVvf22gvCLpv "Python 2 – Try It Online") [Answer] # Pyth, size 6 (41 bytes) ``` q_M_QQ q.q q.q QQ_M_q ``` [Try it here](http://pyth.herokuapp.com/?code=q_M_QQ%0Aq.q%20%20%20%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20%0A%20%20%20q.q%0AQQ_M_q&input=%5B%5B1%2C%202%2C%203%2C%204%5D%2C%20%5B5%2C%206%2C%207%2C%208%5D%2C%20%5B8%2C%207%2C%206%2C%205%5D%2C%20%5B4%2C%203%2C%202%2C%201%5D%5D&debug=0) ### Explanation The first line reverses the input and each row, and checks if we're left with a copy of the input. The `.q` in the second line exits the program, so everything after that, as well as the `q` before it, is a no-op. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), score ~~7~~ ~~6~~ ~~5~~ 4 Full program. Prompts for matrix expression from stdin. Prints a 1 or a 0 and then throws a consistent error. No comments! ``` r←,⎕ r≡⌽r r⌽≡r ⎕,←r ``` [Try it online!](https://tio.run/##pVJLTsMwEN3nFLMzSEZykjZt2SEQCyQ@gu6qLqzUbSKFJrKDql6ggFQQLFiy4CC9TC4SxnZKQ0XTBZESj2fmvfm88Cw5Gs15kk7K4vWjf3tyUyzeGJBTAqRYvKPv7JJA8fIJIc/DCHiSgJAylQr4dASjWGUJn@PJJ9NU5XEI90IpPhFwkOaRkLNYCZgJgrCIJznwcS4kYATGsVS55Tp0iqfHrJRYmmJFRxbPX8VyJdFYrtCWDnopRmWJiSXpy4c8mh8TB8yTObbTi7vrKzIYuBS8IYWBR8EdDhuSKPg6r00hoNDWpm@8DSiGiQhjFX9QlfKt32UNSKbj9qMhxm5v3X8S9rRNobXpvEOhq29dY65HaZm0xmk0jelbk/zmo9Cr7YNtltUzwVqdyjRUvi5Fznmi9opjzuYpXbaljuvuk8eO43s75Al2I3Eu@5rdVdKYJddCzf16a0Tnb1mCaqP/l6VV/W02cZdyNRIs9Q0 "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for expression and evaluate it `,` ravel (flatten) it `r←` store the result in `r` (for **r**avelled) `⌽r` mirror `r` `r≡` implicitly print whether `r` is identical to that `≡` depth of `r` (gives 1) `r⌽` use `r` to rotate that (this will always cause a `RANK ERROR` and quit because a matrix is not permitted as left argument to `⌽`) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), size ~~9 8~~ 7 ``` {.flat# #}talf. # ],R[ eq # qe [R,] # .flat}# #talf.{ ``` [Try it online!](https://tio.run/##nZLLbsIwEEX3/oorIkFSWVbeQFDZVOoHoO4oi0jYLVKAkKSLCPHt1HacYqAs2kXi8cyd10lKXhXpedtiKPCM85GJIm8c4pyavBCMOMCKLpaEH@DgwMlyQVeAQ7TsJHVadjzXeYvRW/XVfLbZaEbEvoLrBhShR@GGFIHnUdJ5KCLlTChSikSZkfb2El96pcY3makpEnX@wO9lvrp0LxXXdnJz/xHY3SniywBjiom6TbTZTxRr2WUolaPbq4zrZIqptYN/WXCqg1ZRY@pSkefhSAA2FEyyIydCFMLB@@41L2reZoNbiPq01gj8G4pBcIWxmzcKH2BMjUxO2T16bYNQ87FCVtuwD49/x5caGH/EF5uP2wkfEbaK3OErq82uUQBf9muOTVPzQmSQGIlwi82O1/M521frmm3z0n1iPP/gldcfssbsv//@Nw "Perl 6 – Try It Online") ~~`reverse` is the bottleneck here. I've changed it to the technically longer, but much more splittable `[*-1 X-^*]`.~~ Okay, I've changed it to `[R,]` after seeing [Brad Gilbert's answer](https://codegolf.stackexchange.com/a/169008/76162) to another question. The flattened code is `{.flat eq [R,] .flat}`. Edit: Damn, I've realised I don't even *need* to flatten the first list, but attempts at shortening it to a size 6 have failed with just *one* byte too many to fit... ``` {@_#}_@ eq#<<| [R,] # # ],R[ |<<#qe @_}#_@{ ``` :( Though if we take it as a one dimensional array, it's easy to fit it in a size 6. ``` {$_# } eq #_$ [R,] # # ],R[ $_# qe } #_${ ``` [Try it online!](https://tio.run/##lZPZaoNAFIbv5ylOojRaBnGJJlGSm0IfIPQuDUHI2ApGzWgLEnx26yzWSWhKe6Ge5T/LfIMloVnQnRp4SGAN3UU/aNAicgbtoKPdFu9BQxrs8XaHWOpMUMtSl66KG5i90I/6vQlnEUoKCobhYHBNDIaLwTFNjEQEg8eCPoYAg89Mj0cHid1He40tKwPZxBNxxx5kNnPEi@W57d/43wJ1Oob5uMACw5J5S24OG825bFyK1fDxrOK6GMNKOYM9HnDFk0pTafJWnmnCBQEkhpVkcW2R@I1Q0@oxohYhRnP6mj/HWUWacHrLk3@VEzn2DVDHuSIqVvfcO0QDKesXFg8nIGlyVEpKGesO6cXPJAPJ5Z8k5/KehfAebKXJbyRLmuY1Y/lUHAmkdUWyJISeKEoMfbLO0pxUm41V0GNlneLSeBzqxzaRuA99wvtHqmNR8kloRaK//ylf "Perl 6 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) (REPL only), size 8 (71 bytes) ``` f=#[[c=- 1;;1;;-1 ,c]]==#& (* *( &#==]]c, 1-;;1;;1 -=c[[#=f ``` Returns `True` for centrosymmetric input, and `False` otherwise. On Mathematica REPL, lines with syntax errors are ignored (with a thick red bar appearing on the side of the screen). Here, only the first three lines, `f=#[[c=-1;;1;;-1,c]]==#&`, are executed. This code captures the function in the name `f`. Sadly, the built-in `PalindromeQ` is too long. [Answer] # [Pyt](https://github.com/mudkip201/pyt), size 1 ``` ₽ ``` [Try it online!](https://tio.run/##K6gs@f//UdPe//@jjXUUTHQUTHUUzHQUzJEYFjoKljoKQFkjHQVDAzBlDBayAEubgZXCGUAjjGMB "Pyt – Try It Online") Checks if the input (in the form of concatenated rows) is a palindrome. [Answer] # [Japt](https://github.com/ETHproductions/japt), size ~~9~~ 4 (11 bytes) ``` UªSê êSªU ``` [Try it online!](https://tio.run/##y0osKPn/P/TQquDDq7i4uA6vCj60KvT//2hDSx0IMjHQMTUAkTCRWAA "Japt – Try It Online") Takes one-dimensional input, checks if it is a palindrome. If you want, you can fill the two empty lines for some ascii art. The old two-dimensional version, rotates the input twice and checks if it's equal to the original: ``` W=U I Wz2;II Vc)eUc cUe)cV II;2zW I U=W ``` [Try it online!](https://tio.run/##y0osKPn/P9w2VEHBkyu8ysja05MrLFkzNTSZKzk0VTM5jMvT09qoKpzLU0Eh1Db8///oaENLHQUIjtVRiDYx0FEwBWITEAdJKhYA) [Answer] # [Husk](https://github.com/barbuz/Husk), size 3 ``` Ṡ=↔ =↔= ↔=Ṡ ``` [Try it online!](https://tio.run/##yygtzv7//@HOBbaP2qZwgQhbLhABFPn//78SVAKOgXwlAA "Husk – Try It Online") Input as 1D-List. Each line defines a function, but only the one on the first line is called. `Ṡ=↔` is a palindrome tests which checks whether the input equals (`=`) its reverse (`↔`). --- ## [Husk](https://github.com/barbuz/Husk), size 4 ``` Ṡ=↔Σ Σ↔=Ṡ Ṡ=↔Σ Σ↔=Ṡ ``` [Try it online!](https://tio.run/##yygtzv7//@HOBbaP2qacW8x1bjGQtgXyubCI/f//P1oJLq6kowSXAbKxi8cCAA "Husk – Try It Online") For input as 2D-matrix, we concatenate (`Σ`) the list of lists before checking that it is a palindrome. [Answer] # [MATL](https://github.com/lmendo/MATL), score 4 ``` t,!P ]=%? ?%=] P!,t ``` Input has the format `[1 2; 2 1]`, using `;` as row separator. Output is via STDERR ([allowed](https://codegolf.meta.stackexchange.com/a/2451/36398) by default): * For centrosymmetric input a consistent error error is produced. With the current Linux and Octave versions in TIO the following STDERR output is produced (disregarding the final lines that start with `Real time: ...`): ``` octave: X11 DISPLAY environment variable not set octave: disabling GUI features Python 2.7.15 (default, May 16 2018, 17:50:09) [GCC 8.1.1 20180502 (Red Hat 8.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> /usr/include/c++/8/bits/basic_string.h:1048: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]: Assertion '__pos <= size()' failed. panic: Aborted -- stopping myself... ``` The error may be different depending on the Linux and Octave versions, but will be consistent across inputs. * For non-centrosymmetric input no error is produced, and the STDERR output on TIO is ``` octave: X11 DISPLAY environment variable not set octave: disabling GUI features Python 2.7.15 (default, May 16 2018, 17:50:09) [GCC 8.1.1 20180502 (Red Hat 8.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> ``` [Try it online!](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDBSNrBSMFw1gA) Or verify all test cases: * Centrosymmetric: [1](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDBSNrBSMFw1gA), [2](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDHQUjHQVjawVTHQUzHQVTawVjsIhhLAA), [3](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDAx0FUx0FYwNrBSMdBTMdBSNrIAcsZmgQCwA), [4](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDAwMdBRhhDWGZovBgRCwA), [5](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDHQUjHQVjHQUTawVTHQUzHQVzHQULawULMAPINbVWMAErACozjAUA), [6](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hjHQUTHQVTHQUzHQVzaxhDR8FCR8HSWgEoa6SjYGgApoytFSzBEuZgRabWMAbYCONYAA). * Non-centrosymmetric: [1](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDHQUjawUQGQsA), [2](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDHQUjHQVDA2sFUx0FMx0FU2sFQ6hYLAA), [3](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDEx0FUx0FYyNrBSMdBTMdBSDD2AAsZmgWCwA), [4](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDSx0FCLZWMDHQUTAFYhNrBYRwLAA), [5](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hDHQUjIDLQUTCxVjDXUTDTAZEW1goWOlCumbWCsQ4IAdUZxgIA), [6](https://tio.run/##y00syfn/v0RHMYAr1lbVnste1TaWK0BRp@T//2hjHQUTHQVTHQUzHQVzaxhDR8FCR8HSGiplaABRhCGNojkWAA). [Check](https://tio.run/##y00syfn/v0QnQJEr1lbVnste1TaWSzFAp@T//2h1kLC6tYI6SAZEgyRBNEhePRYA) that the program is centrosymmetric. ### Explanation `%` is the comment symbol, which causes the rest of the line o be ignored. Newlines are also ignored. So the code is just ``` t,!P]=?P!,t ``` which does the following: ``` t % Input, implicit. Duplicate , % Do twice ! % Transpose P % Flip vertically ] % End = % Compare element-wise ? % If all comparisons gave true P % Implicit input. Transpose. Actually, since there is no more input, an % error is prand the program exits. The rest of the code is not executed, % and will be described in parentheses ! % (Transpose) , % (Do twice) t % (Duplicate) % (End, implicit) % (End, implicit) ``` [Answer] # Haskell, size ~~11~~, ~~10~~, ~~9~~, 8 Takes the input as a 2D list! (Credit to Ørjan Johansen) ``` r= --r}- reverse (==)<*> r.map{- -{pam.r >*<)==( esrever -}r-- =r ``` [Answer] # [Python 2](https://docs.python.org/2/), size 8 ``` i=input# a=i()### a[::-1## ]!=a<_## ##_<a=!] ##1-::[a ###)(i=a #tupni=i ``` [Try it online!](https://tio.run/##NcwhEoAgEAXQ7i10CwYCRoY9iTDMNikrAYOnx@8o7aVX73acuvVeuGi9Gk3CxaxEwO69dUCaWUIGiHIQnhPgrPe7ALSawkC7quLofRlT1FFB/xV1ZFHH9urrXn0f9IfLAw "Python 2 – Try It Online") Takes input as a 1D list of concatenated rows (of length \$n^2\$) and outputs via exit code (0 for symmetric inputs, 1 otherwise). The list is simply checked to be a palindrome. If it is, the comparison chain `a[::-1]!=a<_` fails at the `!=` step and short-circuits; otherwise the unknown variable `_` gets evaluated, crashing the program. [Answer] # [R](https://www.r-project.org/), size 9 ``` #)x-)) #(nacs-<x #(ver(yna # # # # # # any(rev(# x<-scan(# ))-x)# ``` [Try it online!](https://tio.run/##bcq7CsAgDEbh3af4IUsyZKu9gC8TiquDgujTp5auPdM3nOoOgGSoSCAudjdNY6nnyrNYIHzRr6xMrrkzhZG03VaWRHTIu3jEiQM7LkRs/gA "R – Try It Online") The last three lines are the actual program that takes a 1D array as input and checks if it's equal to its reverse. Truthy value: FALSE, Falsy value: TRUE. ``` any(rev(x<-scan())-x) ``` ## [R](https://www.r-project.org/) + pryr, size 9 ``` pryr::f(# any(rev(# x)-x))# #))x-)x #(ver(yna #(f::ryrp ``` [Try it online!](https://tio.run/##DcshCsAwDEZh31MEYvKLirkRdpkyGjlKRElPn@WpzzxPe3ouP65qwm18R3zuUqAHwEStImIgOqKx7OlyvlEy1RpXmrxy6Q3kDw "R – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), score 13 11 10 ``` l=>a=>a.// Where((e// ,i)=>e!=// a[l-i-1]// ).Any()/// ///()ynA.) //]1-i-l[a //=!e>=)i, //e((erehW //.a>=a>=l ``` [Try it online!](https://tio.run/##pVJRb9MwEH7Pr/iWJxtcV6UbTAwHVZV4AgmJSX2o8mCy22qR2sL2gDDlt3eXtNsqkACJiyN9dz5/3519TZo0IdLuNjl/g09dyrTV753/elEUTWtTwsfirgBbyja7BpHsVfBt95D77tY3b5zP6tfAulb4HEJbVbiG2bWmsrz0dFqsNhRJCGKonDQVnRiGdt1O3GRWM5R64Tshpwz5F7LzCy0Z1jPOaNeWoTmhykinGA5UkTYrhtpWhle7w8G4i6PavwV3hQ/WeZFy5H7XNWy8SXLM2Xc52FC8qpEpZRh4@v4QueNvpvBCYa5wil6xf6bwUuGVwvnePx8dDp3t/dMxmY/M0KO/eBRZbqj5cskSYtBhOvm090flY9mDxj8JzP9bYP53gXGz//3Sn3KPLlcN4kjuJ0mY6pH3MEfL4FNoSa@iy8QTSaIcCLC1/HY/4BJKPIe4FgPBs5FlLEQvbcrDAFZC6suwiNHyLEm8RemDn5R4jbKUfLRsyOcYUrfdElM2uuQG@t09 "C# (.NET Core) – Try It Online") Takes input as 1D array and n2 as length; returns `false` for centrosymmetric and `true` for non-centrosymmetric. This version uses `System.Linq` but I don't know how to fit it in the code submission due to the particular requirements of the challenge. Unrolled code: ``` l => a => a.Where((e,i) => e != a[l-i-1]).Any() ``` Following is my previous submission that does not use LINQ: # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), score 16 15 13 ``` l=>a=>{/////* var r=1<2;for (int i=0;i<l; )r&=a[i]==a[l -i++-1]; return r;} /*/ };r nruter ;]1-++i- l[a==]i[a=&r) ;l<i;0=i tni( rof;2<1=r rav */////{>=a>=l ``` [Try it online!](https://tio.run/##pVJRa9swEH7Xrzj8UOxYduqk3cpkeYzAnlYYrLCH4AfNVToxRWInJVsW/Nuzs5O2YYNtsBMI3en0fXefrgtF51EfNsG4B/iwC1Gvy3fGfRWMdVaFAO/ZngFZiCqaDlCre@/s7jH37cZ1tXGR/xpYthw@eW@bBlYgD1Y2Sjb76WATtlUIKKt6JlYeWUrpYOSlMLUVLMMLqZamlbRbVpg8L6pWMNRxgw5Q9GM5MJ1Mh0MvEBxuosZjWLRVkeemYHappGwN7ReYMWFrIy6lgehMytCvxKyuJBWhtmwyFrVvpGqkPcDJSICztrfe3MOtMi4NEUmqZQsKH0I25hwFGmzom7cQdYggwelvj5E9rYrDjMOcwxX0nPxrDi84vORwc/RvRodC10f/akymJxX01OcTyeKz7r7cEUU68BBc9nz3R@Zz2hPHPxHM/5tg/neC8bL/XfTn3DNx@UAOwfzQGcjmCfc0ggvvgre6/IgmahpmnSYDAKwV/d13MAESyCFdpQPAZEQZCykXKsRhdps0K@/8G0S1S7MMXkOSwCtInHdFktHTpNMuog@79VoTZFcm1EB/@Ak "C# (.NET Core) – Try It Online") Unrolled code: ``` l => a => { var r = 1<2; for (int i = 0; i < l;) r &= a[i] == a[l-i++-1]; return r; } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), score ~~9~~ 8 ``` ->z{z==# z.###### reverse# }####### #######} #esrever ######.z #==z{z>- ``` [Try it online!](https://tio.run/##pVPbboIwGL7vU/wpN1tWGg6KugRvdr8XIGRxrGQmCqaFJaI@O6MnRWPdxUho@5@/8n3w9nPfl2nvL7tDl6Ye6qinHsTZD@OCeejkGY/ZT8hjQkWNh3bIS9Ohfun3u7YRgN9Y1fBa7Ldb1vB18YqR8pdZloUEopxAFhEI85yWm1XTsCq/TiAQy5wpgYTAVB5j5XVUBEPSUBKYvokZEWt/GDiqAhnTi0xX5@mNfU54AJXA5IJ2RmAurbk6WvgTlea8gWyhsMoG170ILEb3Dy4fZ6GCoxnmqFrF4zHnOQgAW6IxkZZlW1uWcm1Z3rVlyTeWUcA4RjtjGS1glNPtanc4btYVO4JcafG94uJ0hkab@kPAC2B4EnXLCwZF/cWesYasceP3uvKLvwWldjdLYXCjqDB8JClNRxw5JJXcrxo40a/i3MhJiWMUcmOMbPbsvpQSo4T/SWli/gqd6FLbqMllTP8L "Ruby – Try It Online") A lambda taking a flattened matrix as input. Returns true for centrosymmetric, false otherwise. -1 thanks to Mr.XCoder, Unpacked: ``` ->z{ z == z.reverse } ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), size 9 Thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen)! ``` import // StdEnv// r=reverse ?m=m==r// m //r==m=m? esrever=r //vnEdtS // tropmi ``` [Try it online!](https://tio.run/##TYyxDsIwDET3fIU/wCjQQilD1IUOSGwdEUPUBhSpTisnVOLnCWkGhIfz6d7p@tFoF2kaXqMB0tZFS/PEAaQU0IWhdUtyrNgshr0RDSlSileajlYRUrJKKTXC@NxTnLLFtUPoVgqBp5ls7IJOwwoauJUIe4QDQoVw/DM1wgkh0QJht82vzFGdcZWrP5Mmynv89I9RP33cXK7x/HaabO@/ "Clean – Try It Online") # [Clean](https://github.com/Ourous/curated-clean-linux), size 10 ``` import/*// */StdEnv// r =reverse ?m // =m==r m// //m r==m= // m? esrever= r //vnEdtS/* //*/tropmi ``` [Try it online!](https://tio.run/##TYw9C8IwEIb3/op3LpGo9XMIXXQQHISO4hDaKIVeWq6x4J83HhHEW@55P@7qzlkfqW@enQPZ1seWhp6DzrXOcl2F5ugnQYZhNzkeXVYS0ogLQ8YwSFBrAhvREPwWqMzcmK4MWNzJH5tQ6Vww14H7gdpYBcsBBiWuhcJKYa2wUdj@wU5hryDpUmExT6tI1i7Fm1T9gbwobvFd3zv7GOPsdI6Hl7fU1l9x6Wy490wf "Clean – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), size 3 (11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` ÂQq qQÂ ``` Input as a single list. [Try it online.](https://tio.run/##MzBNTDJM/f//9JzDTYFchQqFXIGHm07P@f8/OtpYR8FER8FUR8FMR8E8VkchGsrUUbDQUbAECQBVGOkoGBqAKWOQiCVY0hys0BQkAGWCjTKOjQUA) I guess this one doesn't count.. ;p ``` ÂQ qâ ``` Input as a single list. [Try it online.](https://tio.run/##MzBNTDJM/f//cFMgV@HhRf//RxvrKJjoKJjqKJjpKJgjMSx0FCx1FICyRjoKhgZgyhgsZAGWNgMrhTOARhjHAgA) **Explanation:** ``` Â # Bifurcate this list (short for DR: Duplicate & Reverse copy) Q # Check if the input-list and the reversed list are equal q # Terminate the program qQâ # No-ops ``` --- **Some size 3 (11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) alternatives:** ``` R€R QqQ R€R ``` Matrix as input. [Try it online.](https://tio.run/##MzBNTDJM/f8/6FHTmiCuwMJALjDr///oaGMdBRMdBVMdBTMdBfNYHYVoKFNHwUJHwRIkAFRhpKNgaACmjEEilmBJc7BCU5AAlAk2yjg2FgA) ``` RQ q QR ``` Single list as input. [Try it online.](https://tio.run/##MzBNTDJM/f8/KFCBS6EQiAOD/v@PNtZRMNFRMNVRMNNRMEdiWOgoWOooAGWNdBQMDcCUMVjIAixtBlYKZwCNMI4FAA) [Answer] # [C (gcc)](https://gcc.gnu.org/), 12 x 12 ``` C(e,n,t,r)// int*e;{for// (r=t=0;e[t// ];r|=e[t]^// e[~t+++n])// ;n=!!!!r;}// //};r!!!!=n; //)]n+++t~[e //^]t[e=|r;] //t[e;0=t=r( //rof{;e*tni //)r,t,n,e(C ``` [Try it online!](https://tio.run/##vZRNb4JAEIbP9VesNk0WnIZFPqzZkB7stTdvFJNGl4ZDV7PdnhD/Oh1ALSoaa4kENvsuM/MM7Auzx4/ZLM/HVIAEDcqwrE4itSl4Gi8UCqoCHTAuQo0i4moV4DSaohDhWvf7fRkVOVwGXTwUz1BYVsZVIQPJURiRxDi9DgWKaaRDEawUj1DglDOsrygKtYhTLkwtkyJHYTcSBB3n93MRJ1KQCX2FF@xwqbDBmPYe5iR4JsVIug/zN9mDcRFhQFdhFO98vieSGmnnbkIpxZQwMlJCiA1kAMQB4gLxgPhAhkCeynNYSq@85ZRhNjl/AMsMDDcxwTZOkrxt3cuKniE5plORlt/6i/Z6@JiN0GspjdCBObj14x2QWFWelfX9ilut2axlEoPDwTtewuHfpJvZ8IBRh412ALZtZ7Tfwl4vO5JnehfZsBjbtSE78SI3Fql6te1rjVjbsgZS9RqdQYMN/XZJuAvby91Y0IXacnuk6ndR1R82@dAvbXGRD2s2ZH@0obv5mrezY5f@Ju/bEElZ/gM "C (gcc) – Try It Online") [Answer] # ><>, Size 6 ``` !/l2(\ s\?\ ? /{=/ ; : /={/ ? \?\s \(2l/! ``` [Try it online!](https://tio.run/##S8sszvj/X1E/x0gjhqs4xj5GwZ5Lv9pWX8Gay0pB37Zan8teAShazBWjYZSjr/j//3/dMgVDEGEEJwwB "><> – Try It Online") (It turns out it's a pain passing multiple value to -v in tio) Input is taken as a one dimensional array as the initial stack state with -v. Exits with no output if the matrix is centrosymmetric, exits with an error (prints "Something smells fishy...") if not. ``` l2( Checks if the length of the stack is less than 2 ?; Exits cleanly if so {= Checks if the first and last elements are equal ?\s Causes an error ('s' is not a valid instruction) if not ``` I wasn't entirely happy with this output format, so here's a size 7 one which outputs 1 for true, and 0 for false. ``` !/l2(\\ ? ?0 =;n1/n ;{ {; n/1n;= 0? ? \\(2l/! ``` [Try it online!](https://tio.run/##S8sszvj/X1E/x0gjJoZLwV5BQcHegEvB1jrPUD@Py7oayK@25srTN8yztlXgMgDLK3DFxGgY5egr/v//X7dMwRBEGMEJQwA "><> – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), n = 3 ``` $cr =q= rc$ ``` [Run and debug it](https://staxlang.xyz/#c=%24cr%0A%3Dq%3D%0Arc%24&i=[[1,+2],+[2,+1]]%0A[[1,+2,+3],+[5,+6,+5],+[3,+2,+1]]%0A[[10,+5,+30],+[2,+6,+2],+[30,+5,+10]]%0A[[100,+100,+100],+[100,+50,+100],+[100,+100,+100]]%0A[[1,+2,+3,+4],+[5,+6,+7,+8],+[8,+7,+6,+5],+[4,+3,+2,+1]]%0A[[3,+4,+5,+6,+7],+[5,+6,+7,+8,+9],+[3,+2,+10,+2,+3],+[9,+8,+7,+6,+5],+[7,+6,+5,+4,+3]]%0A%0A[[1,+2],+[1,+2]]%0A[[1,+2,+10],+[5,+6,+5],+[11,+2,+1]]%0A[[14,+5,+32],+[2,+6,+2],+[30,+5,+16]]%0A[[19,+19,+19],+[40,+50,+4],+[19,+19,+19]]%0A[[1,+2,+20,+4],+[7,+6,+7,+8],+[8,+7,+6,+6],+[3,+3,+2,+1]]%0A[[3,+4,+5,+6,+7],+[5,+6,+7,+8,+9],+[4,+5,+10,+4,+5],+[5,+6,+7,+8,+9],+[3,+4,+5,+6,+7]]&m=2) Explanation: ``` $cr =q= rc$ Full program, implicit input $ Flatten cr Copy and reverse = Compare to original q Print result = Silently error because there is only one item on stack rc$ Not executed ``` 3 is the best possible because I need at least three commands: Copy, reverse, and compare ### [Stax](https://github.com/tomtheisen/stax), n = 4 ``` Mrxr M=qX Xq=M rxrM ``` [Run and debug it](https://staxlang.xyz/#c=Mrxr%0AM%3DqX%0AXq%3DM%0ArxrM&i=[[1,+2],+[2,+1]]%0A[[1,+2,+3],+[5,+6,+5],+[3,+2,+1]]%0A[[10,+5,+30],+[2,+6,+2],+[30,+5,+10]]%0A[[100,+100,+100],+[100,+50,+100],+[100,+100,+100]]%0A[[1,+2,+3,+4],+[5,+6,+7,+8],+[8,+7,+6,+5],+[4,+3,+2,+1]]%0A[[3,+4,+5,+6,+7],+[5,+6,+7,+8,+9],+[3,+2,+10,+2,+3],+[9,+8,+7,+6,+5],+[7,+6,+5,+4,+3]]%0A%0A[[1,+2],+[1,+2]]%0A[[1,+2,+10],+[5,+6,+5],+[11,+2,+1]]%0A[[14,+5,+32],+[2,+6,+2],+[30,+5,+16]]%0A[[19,+19,+19],+[40,+50,+4],+[19,+19,+19]]%0A[[1,+2,+20,+4],+[7,+6,+7,+8],+[8,+7,+6,+6],+[3,+3,+2,+1]]%0A[[3,+4,+5,+6,+7],+[5,+6,+7,+8,+9],+[4,+5,+10,+4,+5],+[5,+6,+7,+8,+9],+[3,+4,+5,+6,+7]]&m=2) Explanation: ``` Mrxr M=qX Xq=M rxrM Full program, implicit input Mr Transpose and reverse x Push input again r M Reverse and transpose = Compare qX Xq Print result twice and save to X = Silently error because there is only one item on stack M rxrM Not executed ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), size 2 (5 bytes) ``` ê" "ê ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=6iIKIuo=&input=WzEsMiwzLDQsNSw0LDMsMiwxXQ==) [Answer] # Java 10, size 13 (181 bytes) ``` a->{var r///* =1>0;for(int l=a.length,i= 0;i<l;)r&=a[i ]==a[l-++i]; return r;} /*/ };r nruter ;]i++-l[a==] i[a=&r);l<i;0 =i,htgnel.a=l tni(rof;0>1= *///r rav{>-a ``` [Try it online.](https://tio.run/##rVRNj9owEL37V4z2sEogn8BCqdcceuite2FvKAcTDHjrdVaOQ4VQfjudGNiuL9tGqpLJaBLPx5sXvRd@4PHL5ue5VLyu4QeX@kQApLbCbHkp4KkLAdZVpQTXUAbroxWrAnhI8UNL8FFbbmUJT6CBwZnHi9OBGzBpmg4IyxcZ3VYmwIpAFOOJEnpn95FkJKPyUdHQ3DO@kqRg6FQ8HMqCAjHCNkaDoS02dxNAOkid76KWGtCmwSEJ0EIOh7FaccYKItHdm5CqR0kzwmS0tzstVMKZImC1DEy1pdkiZ2SA8@GU/HBaxPxMOyBvzVohkCueQyU38IoLCZbWSL1zoC/bSFN4xu7741cXLo@1Fa9J1djkDU9apQOdlIEWv@CyrVMejfDK29Bt7V8zxtFDNEUb983NuqQMs6ZdlS7Ks175WfTRHvwQrTeQiYMyi77gNXOgJr1h/alyqzW/1Mhci/l76fcGnxUPHeWOy@9c1aIXl2g9V@A46cbK875sdqjHI4/NaZ/8eXS5J47JSXR70RPBqMudeSxOce3/g8WJ@0Od@0jt9eBfWLxpQsfksmoMilZZbcSndN55KuWJlKdRnkR5CuUJlKdPnjx56uSJk6dNnjR5ynSX7IT9hqurgzC8am57/g0) Inspired by [*@Charlie*'s C# answer](https://codegolf.stackexchange.com/a/168715/52210). **Golfed explanation:** ``` a->{var r=1>0;for(int l=a.length,i=0;i<l;)r&=a[i]==a[l-++i];return r;} a->{ // Method with byte-array parameter and boolean return-type var r=1>0; // Result-boolean, starting at true for(int l=a.length, // The length of the input-array i=0;i<l;) // Loop `i` in the range [0, length) r&= // Bitwise-AND the result-boolean with: a[i] // Whether the current item ==a[l-++i]; // equals the opposite item return r;} // Return the result ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), score 11 Takes a list of int and n as arguments. Returns n as truthy value, 0 as falsy. ``` /*//};n=l;k --*==++l*=* n);l>k;n*n+ l=k(rof{;l* tni)n,l(f;k */*/////*/* k;f(l,n)int *l;{for(k=l +n*n;k>l;)n *=*l++==*-- k;l=n;}//*/ ``` [Try it online!](https://tio.run/##jVLdboIwGL2mT9GYLGkLjfyJc0293BPsbu7CuLAZurogXiyEZ2f9oQNUdAYL6Tnn6/lOvx392O3adk7m84ZJLlgBKCWc@74gnACJmVgXTBLpA8ELVB7ymgkCKrnHMhAoV3yixeqn3qBgORKBxHtZASJYnR9KVHABfFWBFWvBsASqrvB9zgmlii@4ZI0Wt0oDv7Z7iTCogacreF5VnqrPn@j1DXJYRwGMzRM1wR8WD7EkgIsAZmZNLqhJRw0tHhpCZoV2LwoH9NTRQw2MlsXllloG2sWZq9QZWwbw0TxL5zO9ZjWz@jPlsMTqTxa6Q1bjwqMTGgY8F2q@Fcdxpno1pxtoFGmXlq0URQOnhusytTaT@EqmWc92kSqn7p92cab9VrTqFaMgY8tbXksyMxEk5/7@FWTaXb77usy5F9sgv0/VEc1ezF09bSSldCNn2EKlSjlHs4d3tRXAHHUzrJxhzZjAdWC38OQOnt7B9RzcwvUFYzxobiOfdYD3urPDNNmcHahJb3aGbsPpbXi6MTsAXV9N@ws "C (gcc) – Try It Online") [Answer] # Javascript ES6, size 8: ``` /***/a=> ""+a==a. reverse( )/////*/ /*/////) (esrever .a==a+"" >=a/***/ ``` # Javascript ES6, size 7 (is it valid?): ``` a=>""+a ==a.//= reverse ` ` esrever =//.a== a+"">=a ``` ### Test: ``` <script> f= a=>""+a ==a.//= reverse ` ` esrever =//.a== a+"">=a </script> <script> console.log([ [1, 2, 2, 1], [1, 2, 3, 5, 6, 5, 3, 2, 1], [10, 5, 30, 2, 6, 2, 30, 5, 10], [100, 100, 100, 100, 50, 100, 100, 100, 100], [1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1], [3, 4, 5, 6, 7, 5, 6, 7, 8, 9, 3, 2, 10, 2, 3, 9, 8, 7, 6, 5, 7, 6, 5, 4, 3], ].every(f)) console.log([ [1, 2, 1, 2], [1, 2, 10, 5, 6, 5, 11, 2, 1], [14, 5, 32, 2, 6, 2, 30, 5, 16], [19, 19, 19, 40, 50, 4, 19, 19, 19], [1, 2, 20, 4, 7, 6, 7, 8, 8, 7, 6, 6, 3, 3, 2, 1], [3, 4, 5, 6, 7, 5, 6, 7, 8, 9, 4, 5, 10, 4, 5, 5, 6, 7, 8, 9, 3, 4, 5, 6, 7], ].every(x=>!f(x))) </script> ``` or with lambda saved to variable named `a`: ``` a= a=>""+a ==a.//= reverse ` ` esrever =//.a== a+"">=a console.log([ [1, 2, 2, 1], [1, 2, 3, 5, 6, 5, 3, 2, 1], [10, 5, 30, 2, 6, 2, 30, 5, 10], [100, 100, 100, 100, 50, 100, 100, 100, 100], [1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1], [3, 4, 5, 6, 7, 5, 6, 7, 8, 9, 3, 2, 10, 2, 3, 9, 8, 7, 6, 5, 7, 6, 5, 4, 3], ].every(a)) console.log([ [1, 2, 1, 2], [1, 2, 10, 5, 6, 5, 11, 2, 1], [14, 5, 32, 2, 6, 2, 30, 5, 16], [19, 19, 19, 40, 50, 4, 19, 19, 19], [1, 2, 20, 4, 7, 6, 7, 8, 8, 7, 6, 6, 3, 3, 2, 1], [3, 4, 5, 6, 7, 5, 6, 7, 8, 9, 4, 5, 10, 4, 5, 5, 6, 7, 8, 9, 3, 4, 5, 6, 7], ].every(x=>!a(x))) ``` [Answer] # Clojure, Size 9 ``` #(= %(;;; reverse;; (map;;;;; reverse;; %)));)))% ;;esrever ;;;;;pam( ;;esrever ;;;(% =(# ``` [Try it online!](https://tio.run/##lVJNj4MgEL3zKyZpTDDh4HfbkKa3/QV7Mx4aS7M2ahukm/jrXRhoxe562AM6PN68GR5Tt7frQ4qJnsUFatEreRvGrhNKNvVx2tADBJRzTqT4FnIQOqLd6c75EgvCMOR6BYRzMSBOkHM/dXSJ0QAOdDOFhGBJJR/qayQlKcuYQVIxKBMGcVU5gEFqsJxBwSA3YYqoY0Qa1JTI5RVOIrV4HDlWZGL7MccY52/7F8ErzSCbq28Z7Mxuh@GznQxpr45MCtY2CctcBnuv/2i@3B4PPU0XolSqZaunW5dTO4ilW/ifW46jN7vi2PfL9pYmK34VlqUbsgsv6LxCJ7yjuWbyPN3@7VPhrv0/nzL3hJa4ZqUn4vmkxKA@7WQBUDN64xGasx7vRo1gJvjXrLtJ1EM8S3xYu2eJ/qZWsu3LmGxC77LpVdt7XYRL0OqG0w8 "Clojure – Try It Online") ]
[Question] [ So you are given a **POSITIVE** base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number. ### Examples: ``` 1 => 1 (1 => 1) 2 => 1 (10 => 01) 3 => 3 (11 => 11) 4 => 1 (100 => 001) 5 => 5 (101 => 101) 6 => 3 (110 => 011) 7 => 7 (111 => 111) 8 => 1 (1000 => 0001) 9 => 9 (1001 => 1001) 10 => 5 (1010 => 0101) ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the solution that uses the least bytes wins. This is [A030101](http://oeis.org/A030101) in the OEIS. [Answer] # [Python](https://docs.python.org/3/), 29 bytes ``` lambda n:int(bin(n)[:1:-1],2) ``` [**Try it online!**](https://tio.run/nexus/python2#K1KwVYj5n5OYm5SSqJBnlZlXopGUmaeRpxltZWilaxirY6T5v6AIJFykYWiiqfkfAA) This is an anonymous, unnamed function which returns the result. --- First, `bin(n)` converts the argument to a binary string. We would ordinarily reverse this with the slice notation `[::-1]`. This reads the string with a step of **-1**, i.e. backwards. However, binary strings in Python are prefixed with an `0b`, and therefore we give the slicing's second argument as **1**, telling Python to read backwards terminating at index **1**, thus not reading indexes **1** and **0**. Now that we have the backwards binary string, we pass it to `int(...)` with the second argument as **2**. This reads the string as a base 2 integer, which is then implicity returned by the lambda expression. [Answer] # Python, 29 bytes ``` lambda n:int(bin(n)[:1:-1],2) ``` [**Try it online**](https://tio.run/nexus/python2#@59mm5OYm5SSqJBnlZlXopGUmaeRpxltZWilaxirY6T5v6AIKKyQpmFooPkfAA) [Answer] ## JavaScript (ES6), ~~30~~ 28 bytes *Saved 2 bytes thanks to @Arnauld* ``` f=(n,q)=>n?f(n>>1,q*2|n%2):q ``` This basically calculates the reverse one bit at a time: We start with **q = 0**; while **n** is positive, we multiply **q** by 2, sever the last bit off of **n** with `n>>1`, and add it to **q** with `|n%2`. When **n** reaches 0, the number has been successfully reversed, and we return **q**. Thanks to JS's long built-in names, solving this challenge the easy way takes 44 bytes: ``` n=>+[...n.toString(2),'0b'].reverse().join`` ``` Using recursion and a string, you can get a 32 byte solution that does the same thing: ``` f=(n,q='0b')=>n?f(n>>1,q+n%2):+q ``` [Answer] # Java 8, ~~53~~ ~~47~~ ~~46~~ 45 bytes * *-4 bytes thanks to Titus* * *-1 byte thanks to Kevin Cruijssen* This is a lambda expression which has the same principle as [ETH's answer](https://codegolf.stackexchange.com/a/105633/60919) (although recursion would have been too verbose in Java, so we loop instead): ``` x->{int t=0;for(;x>0;x/=2)t+=t+x%2;return t;} ``` [**Try it online!**](https://repl.it/FAsU/9) This can be assigned with `IntFunction<Integer> f = ...`, and then called with `f.apply(num)`. Expanded, ungolfed and commented, it looks like this: ``` x -> { int t = 0; // Initialize result holder while (x > 0) { // While there are bits left in input: t <<= 1; // Add a 0 bit at the end of result t += x%2; // Set it to the last bit of x x >>= 1; // Hack off the last bit of x } return t; // Return the final result }; ``` [Answer] # J, 6 bytes ``` |.&.#: ``` `|.` reverse `&.` under `#:` base 2 [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` BUḄ ``` [Try it online!](https://tio.run/nexus/jelly#@@8U@nBHy////w0NAA "Jelly – TIO Nexus") ``` B # convert to binary U # reverse Ḅ # convert to decimal ``` [Answer] ## Mathematica, 19 bytes ``` #~IntegerReverse~2& ``` [Answer] # C, ~~48~~ ~~44~~ ~~43~~ 42 bytes -1 byte thanks to gurka and -1 byte thanks to anatolyg: ``` r;f(n){for(r=n&1;n/=2;r+=r+n%2);return r;} ``` Previous 44 bytes solution: ``` r;f(n){r=n&1;while(n/=2)r=2*r+n%2;return r;} ``` Previous 48 bytes solution: ``` r;f(n){r=0;while(n)r=2*(r+n%2),n/=2;return r/2;} ``` Ungolfed and usage: ``` r; f(n){ for( r=n&1; n/=2; r+=r+n%2 ); return r;} } main() { #define P(x) printf("%d %d\n",x,f(x)) P(1); P(2); P(3); P(4); P(5); P(6); P(7); P(8); P(9); P(10); } ``` [Answer] # Labyrinth, 23 bytes ``` ?_";:_2 : % @/2_"! ``` Well, this is awkward... this returns the reverse BINARY number... Thanks @Martin Ender for pointing out both my bug and my ID 10T error. So this doesn't work, I'll have to find another solution. [Answer] # Ruby, ~~29~~ 28 bytes ``` ->n{("%b"%n).reverse.to_i 2} ``` "%b" % n formats the input n as a binary string, reverse, then convert back to a number Usage/Test cases: ``` m=->n{("%b"%n).reverse.to_i 2} m[1] #=> 1 m[2] #=> 1 m[3] #=> 3 m[4] #=> 1 m[5] #=> 5 m[6] #=> 3 m[7] #=> 7 m[8] #=> 1 m[9] #=> 9 m[10] #=> 5 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` bRC ``` [Try it online!](https://tio.run/nexus/05ab1e#@58U5Pz/v6EBAA "05AB1E – TIO Nexus") [Answer] # [Java (OpenJDK)](http://openjdk.java.net/), 63 bytes ``` a->a.valueOf(new StringBuffer(a.toString(a,2)).reverse()+"",2); ``` [Try it online!](https://tio.run/nexus/java-openjdk#TY49C8IwFEXn9Fc8OiWoQV2LDm6C4uBYHJ71pQTatOSjKqW/vaZUxPW8e899bbhXuoCiQufgjNpAnzDn0UeojSersCA4YX1/IPQTAhsMP8ZTSRZeIoMhS1g7a77FrtEPqKOMX73VpsxvgLZ0YnKzr0vtRlztUXZYBboobugJc/oQlCLLUfpmBhyXWyGkpY6sIy4WaRpBNjIWl9n17TzVsgletjHtK8OV/PvxtzC9kK9vQohYG5JhHDfrDw "Java (OpenJDK) – TIO Nexus") Thanks to poke for -12 bytes and to Cyoce for -8 bytes! [Answer] # [Perl 6](http://perl6.org/), 19 bytes ``` {:2(.base(2).flip)} ``` [Answer] # Haskell, 36 bytes ``` 0!b=b a!b=div a 2!(b+b+mod a 2) (!0) ``` Same algorithm (and length!) as ETHproductions’ [JavaScript](https://codegolf.stackexchange.com/a/105633/3852) answer. [Answer] # [Bash](https://www.gnu.org/software/bash/)/Unix utilities, ~~24~~ 23 bytes ``` dc -e2i`dc -e2o?p|rev`p ``` [Try it online!](https://tio.run/nexus/bash#@5@SrKCbapSZAKHz7QtqilLLEgr@/zc0@A8A "Bash – TIO Nexus") [Answer] # PHP, 33 bytes ``` <?=bindec(strrev(decbin($argn))); ``` convert to base2, reverse string, convert to decimal. Save to file and run as pipe with `-F`. **no builtins:** **iterative, 41 bytes** ``` for(;$n=&$argn;$n>>=1)$r+=$r+$n%2;echo$r; ``` While input has set bits, pop a bit from input and push it to output. Run as pipe with `-nR`. **recursive, 52 bytes** ``` function r($n,$r=0){return$n?r($n>>1,$r*2+$n%2):$r;} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~5~~ 3 bytes -2 bytes thanks to Shaggy ``` ¢ÔÍ ``` [Try it online!](https://tio.run/##y0osKPn//9Ciw1MO9/7/b2gAAA "Japt – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` BPXB ``` [Try it online!](https://tio.run/nexus/matl#@@8UEOH0/78ZAA "MATL – TIO Nexus") ### Explanation ``` B % Input a number implicitly. Convert to binary array P % Reverse array XB % Convert from binary array to number. Display implicitly ``` [Answer] # Pyth, 6 bytes ``` i_.BQ2 ``` [Test suite available here.](http://pyth.herokuapp.com/?code=i_.BQ2&input=2&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0) ### Explanation ``` i_.BQ2 Q eval(input()) .B convert to binary _ reverse i 2 convert from base 2 to base 10 ``` [Answer] # Scala, 40 bytes ``` i=>BigInt(BigInt(i)toString 2 reverse,2) ``` ### Usage: ``` val f:(Int=>Any)=i=>BigInt(BigInt(i)toString 2 reverse,2) f(10) //returns 5 ``` ### Explanation: ``` i => // create an anonymous function with a parameter i BigInt( //return a BigInt contructed from BigInt(i) //i converted to a BigInt toString 2 //converted to a binary string reverse //revered , 2 //interpreted as a binary string ) ``` [Answer] # [APL (Dyalog Unicode)](http://www.dyalog.com/), 10 [bytes](//codegolf.meta.stackexchange.com/a/9429/74163) ``` 2⊥∘⊖2∘⊥⍣¯1 ``` [Try it!](http://tryapl.org/?a=f%u21902%u22A5%u2218%u22962%u2218%u22A5%u2363%AF1&run) Thanks to @Adám for 2 bytes. ### How it works: This is a tacit function. To use it, it has to be assigned a name (like `f←`) and then called over an input; for the test cases: `f 1`, `f 2`, etc. ``` 2⊥∘⊖2∘⊥⍣¯1 # Main function; tacit. ⍣¯1 # invert 2∘⊥ # convert from base 2 (which is inverted to 'convert to base 2') ∘⊖ # flip, then 2⊥ # convert from base 2 ``` [Answer] # Mathematica, 38 bytes ``` #+##&~Fold~Reverse[#~IntegerDigits~2]& ``` [Answer] # Groovy, 46 bytes ``` {0.parseInt(0.toBinaryString(it).reverse(),2)} ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 8 bytes ``` ri2bW%2b ``` [Try it online!](https://tio.run/nexus/cjam#@1@UaZQUrmqU9P@/GQA "CJam – TIO Nexus") ### Explanation ``` ri e# Read integer 2b e# Convert to binary array W% e# Reverse array 2b e# Convert from binary array to number. Implicitly display ``` [Answer] ## Batch, 62 bytes ``` @set/an=%1/2,r=%2+%1%%2 @if %n% gtr 0 %0 %n% %r%*2 @echo %r% ``` Explanation: On the first pass, `%1` contains the input parameter while `%2` is empty. We therefore evaluate `n` as half of `%1` and `r` as `+%1` modulo 2 (the `%` operator has to be doubled to quote it). If `n` is not zero, we then call ourselves tail recursively passing in `n` and an expression that gets evaluated on the next pass effectively doubling `r` each time. [Answer] # C#, 98 bytes ``` using System.Linq;using b=System.Convert;a=>b.ToInt64(string.Concat(b.ToString(a,2).Reverse()),2); ``` [Answer] ## R, 55 bytes ``` sum(2^((length(y<-rev(miscFuncs::bin(scan()))):1)-1)*y) ``` Reads input from stdin and consequently uses the `bin` function from the `miscFuncs` package to convert from decimal to a binary vector. [Answer] # [Pushy](https://github.com/FTcode/Pushy), 19 bytes No builtin base conversion! ``` $&2%v2/;FL:vK2*;OS# ``` [**Try it online!**](https://tio.run/##Kygtzqj8/19FzUi1zEjf2s3HqszbSMvaP1j5////hgYA "Pushy – Try It Online") Pushy has two stacks, and this answer makes use of this extensively. There are two parts two this program. First, `$&2%v2/;F`, converts the number to its reverse binary representation: ``` \ Implicit: Input is an integer on main stack. $ ; \ While i != 0: &2%v \ Put i % 2 on auxiliary stack 2/ \ i = i // 2 (integer division) F \ Swap stacks (so result is on main stack) ``` Given the example 10, the stacks would appear as following on each iteration: ``` 1: [10] 2: [] 1: [5] 2: [0] 1: [2] 2: [0, 1] 1: [1] 2: [0, 1, 0] 1: [0] 2: [0, 1, 0, 1] ``` We can see that after the final iteration, `0, 1, 0, 1` has been created on the second stack - the reverse binary digits of 10, `0b1010`. The second part of the code, `L:vK2*;OS#`, is taken from my previous answer which converts [binary to decimal](https://codegolf.stackexchange.com/a/102269/60919). Using the method decsribed and explained in that answer, it converts the binary digits on the stack into a base 10 integer, and prints the result. [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 22 bytes ``` _2/?+:{! } " ++:{%# ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P8/3kjfXtuqWpGrVgEIlLi0gRxV5f//DQ0MAA "Labyrinth – Try It Online") ### Explanation The idea is to disassemble the input bit-by-bit while assembling the output from the other end. Luckily, it's easiest to deconstruct a number from the right, and build one up from the left, so this automatically reverses the bits. We'll generally be keeping what's left of the input on top the main stack, and what we've already computed of the result on top of the auxiliary stack. ``` _2/ When the program starts out, this doesn't really do anything, because it just divides an implicit zero by 2. ?+ Read an integer N from STDIN and add it to the implicit zero on top of the stack. The main loop starts here: : Duplicate what's left of N. This is also used as the conditional to end the loop. Once this reaches zero, the IP moves straight ahead, exiting the loop. Otherwise, the IP turns south which continues the loop. # Push the stack depth, 2. % Take N modulo 2, i.e. get its least significant bit. { Fetch the intermediate result R from the auxiliary stack. :+ Double it (shifting its existing bits left by one position). + Add the bit we just extracted from N to R. } Put R back on the auxiliary stack. _2/ Divide N by 2, dropping its least significant bit. ?+ We're at EOF, so ? just pushes zero and the + gets rid of that zero. Then the main loop starts over. When we exit the loop (once N is zero), this bit is run: { Retrieve R from the auxiliary stack. ! Print it. The IP hits a dead end and turns around. {:+? Various shenanigans which simply leave a zero on top of the stack. / Terminates the program due to the attempted division by zero. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` bṘB ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQQSIsIiIsImLhuZhCIiwiIiwiIl0=) Converts to a binary string, reverses it, then puts it back in base 10. ]
[Question] [ ## The Challenge Given a list of integers, the "bittiest" number among them is the one with the most bits on - that is, the largest amount of bits set to 1 in its 32-bit [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) representation. Write a function (or a program) that takes as input a list of integers between \$ -2^{31} \$ and \$ 2^{31}-1 \$ (the range of 32-bit signed integers) and returns as output the "bittiest" number among them. You may assume the list has at least one item. ## Test Cases ``` 1, 2, 3, 4 => 3 123, 64, 0, -4 => -4 7, 11 => either 7 or 11 1073741824, 1073741823 => 1073741823 ``` Good Luck! This is code golf, so the shortest program in bytes wins. [Answer] # x86 Machine Language, 18 bytes ``` 31 D2 AD F3 0F B8 F8 39 FA 77 03 87 FA 93 E2 F2 93 C3 ``` The above bytes define a function that accepts the address of the array in the `esi` register and the number of elements in the array in the `ecx` register, and returns the "bittiest" number in the array in the `eax` register. Note that this is a custom calling convention that accepts arguments in the `ecx` and `esi` registers, but it is otherwise much like a C function that takes the length of the array and a pointer to the array as its two arguments. This custom calling convention treats all registers as caller-save, including `ebx`. The implementation of this function pulls some dirty tricks, which assume that the array has at least 1 element, as provided for in the challenge. It also assumes that the direction flag (`DF`) is clear (`0`), which is standard in all calling conventions that I'm aware of. In ungolfed assembly-language mnemonics: ``` ; ecx = length of array ; esi = address of first element in array Find: 31 D2 xor edx, edx ; start with max bit count set to 0 Next: AD lods eax, DWORD PTR [esi] ; load the next value from the array, and ; increment ptr by element size F3 0F B8 F8 popcnt edi, eax ; count # of set bits in value 39 FA cmp edx, edi ; if # of set bits in value is less than 77 03 ja SHORT Skip ; the running maximum, skip next 2 insns 87 FA xchg edx, edi ; save current # of set bits (for comparisons) 93 xchg eax, ebx ; save current array value (for comparisons) Skip: E2 F2 loop SHORT Next ; decrement element count, looping until it is 0 93 xchg eax, ebx ; move running maximum value to eax C3 ret ; return, with result in eax ``` The key feature of this code is, of course, the x86 `popcnt` instruction, which counts the number of set bits in an integer. It iterates through the input array, keeping track of both the value of the maximum element and the number of set bits that it contains. It checks each value in the array to see if its number of set bits is higher than any value it has seen before. If so, it updates the tracking values; if not, it skips this step. The `popcnt` instruction is a large (4-byte) instruction, but there's nothing that can be done to avoid that. However, the very short (1-byte) `lods` instruction has been used to load values from the array while simultaneously incrementing the pointer, the short (2-byte) `loop` instruction has been used for loop control (automatically decrementing the element counter and looping as long as there are more elements remaining to go through), and the very short (1-byte) `xchg` instruction has been used throughout. An extra `xchg` had to be used at the end in order to enable use of the `lods` instruction, which *always* loads into the `eax` register, but that trade-off is more than worth it. ## [Try it online!](https://tio.run/##lVNdb5swFH0ev@LKFRKkzhKg27SkdKq67EOa@tBU06YSRQSc1BsBhM2EFuWvL7ONaUnDUo0o2D4@59zry3XUj5IwXe12NOXwgaaxJSfR1zApCcMQZSnjIKAe5DVmGxsDxCNpZFFhILF6UfEKq7Ham89Dtp7PLRSkAa@yIgEwTcVTQ5AiRWsedE0qbvqjAzzgSRazpAPPszxKeSL9Qm1LO2jROk/kVO3/K3rAf4T1dPqT5qbfQaii@1XyvE@LtqizChXthdqv3btPmeX1oq7Ef1i3WCNA/gKBJQh2G8cCjyUeH@LvFU4P8FDi4T5f@EcIwNLNYcOgJ7ogLzkUZEUZJwVQBpOrb9AbPPGbSl1@XDf9/EQ3gvbKrlurILws0rrVtrsTmkZJGRM4Zzym2cv7C8M4icmSpgQub24uv8@/TK4/3n6ywqKwhdpi9DfJlmo50POeXNiG8SujMdwSxp@7Abju/SonESexvg95IcClhTaA6kyXWQHKiYIPw7EYzhvTMZye1iXf6BM2apOZMcJCB@9AjEjWHNm4iXxHZ7X5VoUsObMQbGVAQ9/IgrAy4SKiusoPh2hKP26nGnD58y/AjMFkopmwlosErMbIfzyozCmoJm5Qvb0Sf09l1wJeIVsE2BqGITNZhzS1dHEeaghc1Hd4NxMJbsDB4GLwMJzBdnxIcxqaKyivzzAMMfS7qa6mvsHgOJ0MTzP6ant/vzmgpngyjDTCLbbqi72OUicRn0aN@NFkqD9Rt8LRCqelcI4qXK1wWwr3qMLTCq@l8Ga6SfT9Gcrb8ydaJuGK7Xb9tef@BQ "C (clang) – Try It Online") My first attempt was a 20-byte function. So far, 18 bytes is the best I have been able to come up with. I'm curious to see if anyone else can beat this score! The only route of improvement that I see would be if a `LOOPA` instruction existed. Unfortunately, it doesn't—the only condition codes supported by `LOOP` are `E`/`Z` and `NE`/`NZ`. But maybe someone else can stretch their mind further than me! [Answer] # JavaScript (ES6), ~~49 48 47~~ 45 bytes *Saved 2 bytes thanks to @user81655* ``` a=>a.sort(g=(p,q)=>!p|-!q||g(p&p-1,q&q-1))[0] ``` [Try it online!](https://tio.run/##XcsxCoMwFIDhvad4LpLAixoNFgrxCj2AOASroUVMYmKn3D2Vdin@8/e/1Fv5cXvawFbzmNIsk5KdKrzZAtGSWHRUdpmNLHMxamJzyzi63DFOaV8NaTSrN8tULEaTmfQcoUZoEMRAKXwrS7jvwe7hBs3lzOuDtgKhQmC/5Y8zcfZXBM4Plj4 "JavaScript (Node.js) – Try It Online") ### How? We `.sort()` the input list with a recursive function that, given `p` and `q`, clears the least significant bit set in each variable until one of them is equal to 0 (or both of them simultaneously). This allows to order the list from most to least bits set. We then return the first entry, i.e. the "bittiest" one. ### Commented ``` a => // a[] = input list a.sort( // sort a[] ... g = (p, q) => // ... using the recursive function g: !p | -!q // -> +1 if p = 0 and q ≠ 0, // or -1 if q = 0, || // or 0 if p ≠ 0 and q ≠ 0, in which case ... g( // ... we do a recursive call: p & p - 1, // clear the least significant bit set in p q & q - 1 // clear the least significant bit set in q ) // end of recursive call )[0] // end of sort(); return the first entry ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ 8 bytes ``` %Ø%B§µÞṪ ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//JcOYJULCp8K1w57huar///9bMSwgMiwgMywgNCwgLTRd "Jelly – Try It Online") ## Explanation ``` µÞ | sort input by %Ø% | modulo by 2^32 (Ø% is a quick for 2^32) B | converted to binary § | sum Ṫ | get the last ``` Edit: thank you all for the kind response to my first question! I think I've fixed it now, it seems to work for all test cases. ## Original code ``` 2*31 B%¢S€iṀị ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes Saved many bytes thanks to Adam and ngn. ``` {⊃⍒+⌿⍵⊤⍨32⍴2}⊃⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR13Nj3onaT/q2f@od@ujriWPelcYGz3q3WJUC5LpWvT/Ud9UoLo0BUMjYwUzEwUDhUPrTbjggjoKRjoKxjoKCCFzBUPD/wA "APL (Dyalog Unicode) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~80~~ 77 bytes Saved 3 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!! ``` #define b __builtin_popcount(f(n,l f(n,l)int*l;{n=--n?f(n,l+(b))<b+1)))):*l;} ``` [Try it online!](https://tio.run/##bZJhb4IwEIa/8ysuLCYUSiboZiYyPyz7FZMYgbI1Y8VYTMgMv51dW1DUNaGlfd57C3eX@Z9Z1nUPOSu4YJDCdpseeVlzsd1X@6w6itopHEFLS8@Ei9oto5OIfV@s9ZHnpISsUi8gOJYI225/QJmjpFBSwBUEgZMFOIrqoABwiGEa4bICEYHncaKxGjq6cOyJnOQ2BYevcbaXtk0olB88IZHVWsrjZ8eFQyxjrA6gZrKefiTofQoohBRmFOZtdC0IekGI8HlOYUrBvxOFRrSgEAQX5momDdOXUWNplvDWRRil5L@sKhwdQB77nWu2FEY0uKbBNQ2vaUhG17Fmz7Ka5ebCmfolCotekH3tDi7OLPtmB6OwN817uGle3vB5Uvkd7Wc2xg3VAlMukbOmL5l@XQ0fNlx8@bbzia6rUg/Fv2QRrUwmNU@iMQYQPRZ32HRWTbGhbmIkxqh@hPqWMCTn9PxriM0G/itMcpjIjcBsSHrOFotjmfSWrdV2fw "C (gcc) – Try It Online") [Answer] # [C++ (GCC)](https://gcc.gnu.org/), ~~145~~ ~~141~~ ~~140~~ ~~135~~ ~~134~~ ~~133~~ ~~130~~ ~~128~~ 116 bytes 145->141 thanks to user 128->116 thanks to ceilingcat ``` #import<bits/stdc++.h> int i,b,v,c;main(){for(;std::cin>>i;b<c?b=c,v=i:0)c=std::bitset<32>(i).count();std::cout<<v;} ``` [Try it online!](https://tio.run/##LY3LDoIwEEX3fkUTN20oyCua0IffQkfBSaAlMLAx/roVjetzzr0wTWkPEOMRxynMpB3SclroBkmSPewBPTGUTm4S1Nii5@LZhZmr3WgaQG8tKqfh6gzIzWCTCzA/9t25k65Ky1FkEFZPXPyzsJLWm3rFWJQVO9csZ2n9hm5o@yWmu2P29@LyAQ) [Answer] # [Kotlin](https://kotlinlang.org), ~~41~~ ~~38~~ 29 bytes Correct code with much fewer bytes :) { Thanks @vrintle } ``` {it.maxBy{it.countOneBits()}} ``` [Kotlin Playground](https://pl.kotl.in/TXODGPxpM) --- ``` {it.maxBy{it.toByte().countOneBits()}} ``` [Kotlin Playground](https://pl.kotl.in/Isc4eXZOB) --- ``` {it.maxBy{it.toString(2).count{it=='1'}}} ``` [Try it online!](https://tio.run/##TY3BCoJAEIbP7VPMzR1YpTUpiDQIOgRBh55gi6wh3RUdoxCf3bYQ6vbxffwzd8cF2SFvLZSGrEToREENH3IpJiNoBbGCmYIE1U/GXswTBVMF4X9YKNAaBUa5q7fmfIMOyFYtQ5iJhyngRMx0aZYg936w2lnO0DfwsIZ06Iij0jw3rw@wO3JN9ipjjM6utexlmgY66Pt@qHzhwsrxoPx@QfTlDQ "Kotlin – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ΣžJ%b1¢}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3OKj@7xUkwwPLao9t@P//2hDI2MdBTMTHQUDHQVdk1gA "05AB1E – Try It Online") ``` ΣžJ%b1¢}θ # full program θ # last element of... # implicit input... Σ # sorted in increasing order by... ¢ # number of... 1 # ones... ¢ # in... # (implicit) current element in list... % # modulo... žJ # 4294967296... b # in binary # implicit output ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 11 bytes ``` {*x@>+/2\x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlqrwsFOW98opqL2f5qCoZGxgpmJgoGCrgkXkKdgpGCsAGKZKxga/gcA "K (ngn/k) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~58~~ ~~55~~ 54 bytes ``` function(x)x[order(colSums(sapply(x,intToBits)<1))][1] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCsyI6vygltUgjOT8nuDS3WKM4saAgp1KjQiczryQk3ymzpFjTxlBTMzbaMPZ/mkayhqGRsY6CmYmOgoGOgq6JpuZ/AA "R – Try It Online") [-2 thanks to Robin Ryder](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCsyK6PCMzOUMvN7FCIzk/J7g0t1ijOLGgIKdSo0InM68kJN8ps6RY085AUzP2f5pGsoaZjrmOoaGm5n8A) -1 thanks to Dominic van Essen. [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é·║⌂╞8Q⌡ë♀NM╟¥É▌╦! ``` [Run and debug it](https://staxlang.xyz/#p=82faba7fc63851f5890c4e4dc79d90ddcb21&i=%5B1,2,3,4%5D%0A%5B123,+64,+0,+-4%5D%0A%5B7,+11%5D&m=2) Manually pads with 1s/0s to get the correct representation. Displays a single number for each testcase. [Answer] # [Python 3](https://docs.python.org/3/), 52 bytes ``` lambda l:max(l,key=lambda n:bin(n%2**31).count("1")) ``` [Try it online!](https://tio.run/##RY1RC4IwHMTf/RSHEGzxL5qTBGGfZO1hK6WRTrEF2ZdfGkL3cA/34@7GOd6HIFOrLqmzvbtZdHVv36yjRzOrLQq184GFXbHfS8GP1@EVIstFznmKzTNCQWtBKAiSUBrKsEmLYknOJeFEOCwEf1QRhDAmy9phgiU4@ICPH9k6SdBybRAqw@tfaZz88toyywmrQyk4jvQF "Python 3 – Try It Online") `n%2**31` - since in python integers are infinite, have to change negative numbers. for example `-4` becomes `2147483644` `bin(...)` - translate to binary format `count("1")` - count the number of units --- # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda n:n and n%2+z(n//b) f=lambda l:max(l,key=z) ``` [Try it online!](https://tio.run/##RYxBCoMwFET3nmI2hYR@sFFpQchJ0iwSVCrVr9gsai6fqgidxSze8GZew2viMkX9TIMbfePANcNxA74U1yg4z73MOn2OQz26rxjo3a46yhTaT4CGMYpQEEpCZSnDGaOKjdwrws0S/vhBUMraLOumBY7g0TNiP4v9jmA26TAfVtaHNS89B9EJJwl7Q2t4ifQD "Python 3 – Try It Online") two bytes shorter, but doesn't work with negative numbers [Answer] # [Scala](http://www.scala-lang.org/), 54 42 40 36 bytes Saved some bytes thanks to caird coinheringaahing, didymus, user, and [some tips](https://codegolf.stackexchange.com/questions/3885/tips-for-golfing-in-scala) ``` _.maxBy(_.toBinaryString.count(48<)) ``` [Try it online!](https://tio.run/##bYxBC4IwAEbv@xXfcYMpaVIhGeStswSBSCxTMXTWXJKIv30tukWnB@/B63PRCNNdbkWucZoIIdeiRCtqSYWq@hB7pcSYJlrVsspYiKOsNSJMBBhEgzJEUjzSg9QZoh0sbSTm7LbiFY/07OourqVQ4/fg5t1TahpstowZQu7W6UbSktoJ9Th8jiVHwBj7bb71q4BjweH86WsOz/toMs/GOEPzBg "Scala – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ ~~16~~ 13 bytes *Edit: -1 byte thanks to Razetime, and then -3 bytes thanks to Leo* ``` ►(ΣḋΩ≥0+^32 2 ``` [Try it online!](https://tio.run/##ASoA1f9odXNr///ilroozqPhuIvOqeKJpTArXjMyIDL///9bMCwxLDIsMywtNF0 "Husk – Try It Online") [Husk](https://github.com/barbuz/Husk) natively uses arbitrary-precision integers, and so has no notion of 32-bit 2's complement for representing negative 4-byte signed integers: as a result, the 'get binary digits' function - `ḋ` - is sadly useless here for negative inputs. So we need to calculate the '2's complement bittiness' by hand. Thanks to [Husk](https://github.com/barbuz/Husk) help from [Leo](https://codegolf.stackexchange.com/users/62393/leo) for the use of `Ω` here. ``` ► # element of input that maximises result of: (Σḋ # sum of binary digits of Ω # repeat until result is ≥0 # greater than or equal to zero: +^32 2 # add 2^32 ``` [Answer] # Java 10, 73 bytes ``` a->{int r=0,m=0,t;for(var i:a)if((t=i.bitCount(i))>m){m=t;r=i;}return r;} ``` [Try it online.](https://tio.run/##PZBBi8JADIXv/orgaQang1VZoaXCsqc9rBeP4iHWaZluO5U0dZEyv707VfGQkDzCex@p8IZRdfkd8xq7Dn7QumEGYB0bKjA3sJ/WhwC5@A5yaeh4ApRp0P0stI6RbQ57cJDBiNFumI4pW6omFKdFS@KGBDZBaQshOLP6bPmr7R0LK@WukUOTcUqZTT0Z7skBpX5MJ/Nrf66D@Svj1toLNIFRHJisKycQKjv5ZJyC3oQICTjzB2/heBqGWK3UWm28GuLVWn1s1FJF07ZVcey9fLgAHO4dm0a3PetrSOHaiSq8Sfdsa/1JhPdOc/skECgX8wTmC6fzML@@4sd/) **Explanation:** ``` a->{ // Method with Integer-array parameter and int return-type int r=0, // Result-integer, starting at 0 m=0, // Maximum bit-count integer, starting at 0 t; // Temp integer, uninitialized for(var i:a) // Loop over each Integer in the input-array: if((t=i.bitCount(i)) // If its amount of 1s in the binary representation >m){ // is larger than the current maximum: m=t; // Update the maximum with this bit-count r=i;} // And update the result with this integer return r;} // After the loop, return the resulting integer ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 8 bytes ``` %Ø%BSƲÞṪ ``` [Try it online!](https://tio.run/##y0rNyan8/1/18AxVp@Bjmw7Pe7hz1f///6MNjYx1zEx0DHR0TWIB "Jelly – Try It Online") *-1 byte by using `Þ` (sort) instead of `ÐṀ` (maximum). This was inspired by Gio D's answer and after their and my edit, both solutions are pretty much the same.* ## Explanation ``` %Ø%BSƲÞṪ Main monadic link Þ Sort by Ʋ ( % Modulo Ø% 2^32 B Binary S Sum Ʋ ) Ṫ Last item ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ñÈu2pH)¤¬x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=8ch1MnBIKaSseA&input=WzEyMyA2NCAwIC00XQ) ``` ñÈu2pH)¤¬x :Implicit input of array ñ :Sort by È :Passing each element through the following function u :Positive modulo 2p : 2 raised to the power of H : 32 ) :End modulo ¤ :To binary string ¬ :Split x :Reduce by addition :Implicit output of last element ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), ~~36~~ ~~33~~ 34 bytes *Thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) for correcting my code for a special case! :)* ``` p$*.max_by{("%034b"%_1)[2,32].sum} ``` [Try it online!](https://tio.run/##KypNqvz/v0BFSy83sSI@qbK6JrtGQ0nVwNgkSUk1WzPaSMfYKFavuDS39v///0aGJuYmFsZmJub/dQ0NzI3NTQwtjEwA "Ruby – Try It Online") Uses command-line args for input, outputs the *bittiest number* as a string. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes. [Answer] # [Java (JDK)](http://jdk.java.net/), 44 bytes ``` a->a.max((x,y)->x.bitCount(x)-x.bitCount(y)) ``` [Try it online!](https://tio.run/##ZZAxb8IwEIV3fsWJyRaO1QBqJWgjVZ06lA6MUYYjmMhpYke2QxNF@e2pQ1BBYrH1zt@9e74czxjkx58hLdBa@EKpuhmAVE6YE6YCdqMEyD3HaycL/l05qRUWr5@eyYSJICW3V@uMwJLvL9cNQbr1Nv3MH9ahkynsQMEbDBhEyEtsCGlYS4Oo4QfpPnStHGlocKdaSoft2F/Vh8L3X23OWh6h9KmJHylVFieAJrN0Sn3ShlwzxAnCBpT4hf9CnHRdyJZsxdY968Llij2v2RMLRvXCwrDv6cUFYN9aJ0qua8crP8UV6u7L78Zga7nTUwKCdDHfwHyhePpITfvxDL1upB/@AA "Java (JDK) – Try It Online") This is kind of cheating, as it accepts a `Stream<Integer>` as input and returns an `Optional<Int>`. [Answer] # [Scala](http://www.scala-lang.org/), 24 bytes ``` _ maxBy Integer.bitCount ``` [Try it online!](https://tio.run/##bYxBC4IwAIXv@xXvOGFGmhQIBtWpswSBSMyasliz5pJE/O1rXqPT472P93VXrrhrq7u4WpxHQshN1HhwqSk3TZdiZwwfitwaqZsySHHS0iLDSICeK9QpcvEqjtqWyLbw6SFxF6/47Ie5i0aYRSXtoX1r6wh5epNVmtbUH2nEEDOsGJIgCH5Z7Pd1wrBkCP/wDUMUzTOZJufCXn0B "Scala – Try It Online") Split off from [Gabber's](https://codegolf.stackexchange.com/users/99988/gabber) great [first answer](https://codegolf.stackexchange.com/a/216711/95792). [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~71~~ 58 bytes ``` l=>l.OrderBy(r=>Convert.ToString(r,2).Sum(c=>c-48)).Last() ``` [Try it online!](https://tio.run/##jcuxCsIwFEDR3a94YwKvwdaggiaDglPBoYJD6WDTIIGawkuqiPjtsfgDOt3lXBMyE1w6jN5snY91gzBFQwsq9Ur34kidpd2TkdL7wd8tRXEaqkjOXxlhwUU13phR2mRyzbkoLyEynjazCYeht@JMLtrSecta5u2jbuAFebFAWEqEOUIm4c35D49QIEzPH3aFef5V6QM "C# (Visual C# Interactive Compiler) – Try It Online") * Refactored to use a lambda as suggested by @user in comments [Answer] # [Perl 5](https://www.perl.org/) `-pa`, ~~54~~ 45 bytes ``` map$a[(sprintf"%b",$_)=~y/1//]=$_,@F;$_=pop@a ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUAlMVqjuKAoM68kTUk1SUlHJV7Ttq5S31BfP9ZWJV7Hwc1aJd62IL/AIfH/f0MFIwVjBV0TBV3Df/kFJZn5ecX/dQsSAQ "Perl 5 – Try It Online") [Answer] # Zsh, 71 bytes [Try it Online!](https://tio.run/##HcdLCsIwFAXQeVZxIaEkVWk@RUETuxBxkIChLwMFqxNL1x6ts3M@01izVDN736fbCxEJhFLz4wk6xSBmISV5PVw4t1fbts5u6PgPKdV1emkaKQWP5zTIEmibwi9KKea9F6UuLMPAwqFfZR32PTR26w4wpn4B)  ~~[81bytes](https://tio.run/##HcdBCsIwFEXReVfxIKH8XxWapCjE1K7AFYijxNJkoGB1Ysnao3VyueczT2UkXqr3fb694BEQkcr4eCIefS8XIRc68y@ztSyJomuHixD6qpvG6E20f0TmLFTOdU3kT2Gg1Mdt6D0zV845mUquRihoGHTraYN9hxa7VQcoVb4)~~  ~~[85bytes](https://tio.run/##HcdBCsIwFEXReVbxICHkV4QmLQppoitwBeIotfg7ULA6MWTt0Tq53PNZbnUylMX7vlxfSBjBmOv0eIKHnKLKUmVzol8W70kZw6E9nqV0F9c0nduw/4OJirSlCGPSYSTSeo6KtR6jSkMRIQQ11yImWDh06NdzHXY9WmxX7WFt/QI)~~ ``` for i;a=${$((i<0?[##2]2**32+i:[##2]i))//0}&&(($#a>b?(j=i,b=$#a))) <<<$j ``` Great challenge, required some of the weirdest `Zsh` incantations! Explanation: `for i;` ... implicit iteration over all arguments `$((i<0?[##2]2**32+i:[##2]i))` ... convert `i` to 32-bit format, using two's complement trick if `i<0` `a=${ ~string~ //0}` ... remove all `0`s from string `(($#a>b?(j=i,b=$#a)))` ... keep track of which input `i` is the "**b**ittiest" according to the length of string `a` `<<<$j` ... output the winner [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ≔EθΣ⍘﹪ιX²¦³²¦²ηI§θ⌕η⌈η ``` [Try it online!](https://tio.run/##FYyxCoMwFAD3fsUbX@AJrUoXJysUOgQER3F4qJiAJm0SW/8@jTfcdNyo2I2W1xhr7/ViUPIbPwTdvuGD/dwFp82C0k77alETtPY3O8wJilwIgqRkJapLm8KADfuAdXiZaT7Oz1ObCRWB5ENv6anESRVj39/yguBeElwJsnIYYvZd/w "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔EθΣ⍘﹪ιX²¦³²¦²η ``` For each number in the list, cast it to a 32-bit unsigned number, convert it to binary, and sum the bits. ``` I§θ⌕η⌈η ``` Output the number at the position of the highest bit count. [Answer] ## SystemVerilog, 66 bytes This will be an imperfect answer for now as I’m posting from my phone, but SV’s`$countones()` function is perfect here. ``` function m(int q[$]); m=q.max with ($countones(item)); endfunction ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` Last@*SortBy[Mod[#,2^32]~DigitCount~2&] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMRBKzi/qMSpMto3PyVaWccoztgots4lMz2zxDm/NK@kzkgt9n9AUWZeSbSyrl2ag3KsWl1wcmJeXTVXtaGOkY6xjkmtDpBpZKxjZqJjoKML5prrGBrWctX@BwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # PowerShell, 53 56 bytes +5 bytes because it did not handle negatives properly -2 bytes thanks to mazzy ``` $args|sort{$v=$_;0..31|%{$o+=!!(1-shl$_-band$v)};$o}-b 1 ``` [Answer] # [Nim](http://nim-lang.org/), 75 bytes ``` import algorithm,bitops func b(n:seq):int=n.sortedByIt(it.countSetBits)[^1] ``` [Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEITEnPb8osyQjVycpsyS/oJgrrTQvWSFJI8@qOLVQ0yozr8Q2T68YqDI1xanSs0Qjs0QvOb80ryQ4tcQps6RYMzrOMPZ/anJGvoJDtKF6prGRjoIRhDKGUCYgKlYviQumyAgqYWYCoQ0glC66QnOIuKEhVPw/AA "Nim – Try It Online") [Answer] # [J](http://jsoftware.com/), 20 bytes ``` {.@\:[:+/"1(32$2)&#: ``` As written, when given multiple equally, maximally bitty numbers, returns the first in the array. If `{.\:` is changed to `{:/:`, it gives the last. [Try it online!](https://tio.run/##y/r/P83WqlrPIcYq2kpbX8lQw9hIxUhTTdkKKOFgp2CoYKRgrGCiYK1gaGSsYGaiYKAQD@KZKxgacgEA "J – Try It Online") [Answer] ## AArch64, 48 44 bytes Raw instructions (32-bit little endian hex): ``` 1e2703e4 bc404400 0e205801 2e303821 0ea43c23 2ea31c02 2ea31c24 f1000421 54ffff21 1e260040 d65f03c0 ``` Uncommented assembly: ``` .globl bittiest bittiest: fmov s4, #0 .Lloop: ldr s0, [x0], #4 cnt v1.8b, v0.8b uaddlv h1, v1.8b cmge v3.2s, v1.2s, v4.2s bit v2.8b, v0.8b, v3.8b bit v4.8b, v1.8b, v3.8b subs x1, x1, #1 bne .Lloop fmov w0, s2 ret ``` ### Explanation C function signature: ``` int32_t bittiest(int32_t *words, size_t len); ``` Pseudo-C: ``` int32_t bittiest(int32_t *words, size_t len) { int32_t maxcount = 0; int32_t maxvalue; do { int32_t value = *words++; int8_t counts[4] = popcount8x4((int8_t *)&value); int32_t count = counts[0] + counts[1] + counts[2] + counts[3]; if (count >= maxcount) { maxvalue = value; maxcount = count; } } while (--len); return maxvalue; } ``` AArch64's population count instruction is in NEON (the SIMD/floating point instruction set), and it counts each byte individually. Therefore, it is a little awkward to work with scalars here so we do everything in NEON. v4 is the max population count (v4, s4, h4, and d4 all refer to the same register). Set it to 0. ``` fmov s4, #0 ``` Load the next int32 word into v0, and increment words (x0) by 4. ``` ldr s0, [x0], #4 ``` Store the population count of each byte in v0 into the corresponding byte in v1. ``` cnt v1.8b, v0.8b ``` Add all of the 8-bit lanes in v1 together to get the full population count, and store into v1 again. ``` uaddlv h1, v1.8b ``` Compare the population count of this word to the maximum. If it is larger or equal, v3 will be all 1 bits (true), otherwise it will be all 0 bits (false). ``` cmge v3.2s, v1.2s, v4.2s ``` If v3 is true, set the max word (v2) to the current word. max is not initialized on the first iteration, but it will always be set because the population count will always be >= 0. ``` bit v2.8b, v0.8b, v3.8b ``` Same, but for the new max population count. ``` bit v4.8b, v1.8b, v3.8b ``` Decrement len (x1), and loop if it is not zero ``` subs x1, x1, #1 bne .Lloop ``` End of loop: Move the maximum value from a NEON register to the return register (w0), and return. ``` fmov w0, s2 ret ``` 11 instructions = 44 bytes ]
[Question] [ The goal here is to simply reverse a string, with one twist: Keep the capitalization in the same places. Example Input 1: `Hello, Midnightas` Example Output 1: `SathginDim ,olleh` Example Input 2: `.Q` Exmaple Output 2: `q.` **Rules**: * Output to STDOUT, input from STDIN * The winner will be picked 13th of July on GMT+3 12:00 (One week) * The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters. * Any punctuation ending up in a position where there was an upper-case letter must be ignored. [Answer] ## Python, 71 bytes ``` lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1])) ``` [Try it online](http://ideone.com/fork/py1Kjj) -3 bytes from Ruud, plus the inspiration for 2 more. -4 more bytes from FryAmTheEggman [Answer] # Python 2, 73 bytes Since the rules specify the input is ascii: ``` lambda s:''.join([z.lower,z.upper]['@'<c<'[']()for c,z in zip(s,s[::-1])) ``` All the credit goes to @Mego though, but I had not the reputation to just comment on his answer. [Answer] ## Perl, 31 + 2 (`-lp`) = 33 bytes *This solution is from [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) (13 bytes shorter thant mine).* ``` s%.%(lc$&gt$&?u:l)."c chop"%eeg ``` But you'll need `l` and `p` switches on. To run it : ``` perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg' ``` [Answer] # Pyth, ~~13~~ ~~11~~ ~~10~~ 9 bytes *Thanks to @FryAmTheEggman for reminding me about `V` and @LeakyNun for another byte.* ``` srV_Qm!/G ``` [Try it online!](http://pyth.tryitonline.net/#code=c3JWX1F9UnJHMQ&input=IkhlbGxvLCBNaWRuaWdodGFzIg) now on mobile, updating link in a bit [Answer] ## Python, 66 bytes ``` f=lambda s,i=0:s[i:]and(s[~i]*2).title()[~('@'<s[i]<'[')]+f(s,i+1) ``` Recurses through the indices `i`, taking the character `s[~i]` from the back and the case of `s[i]` from the front. Being capital is checked as lying in the contiguous range `@ABC...XYZ[`. Credit to FryAmTheEggman from the `(_*2).title()` trick. [Answer] ## TCC - 4 bytes ``` <>ci ``` [Try it online!](https://www.ccode.gq/projects/tcc.html?code=%3C%3Eci&input=Hello%2C%20Midnightas) Explanation: ``` - output is implicit in TCC <> - reverse string c - preserve capitalization i - get input ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~75~~ ~~67~~ 65 bytes Byte count assumes ISO 8859-1 encoding. ``` $ ±·$` O$^`\G[^·] s{T`L`l`±. T01`l`L`±.*·[A-Z] ±· ±(.) $1± ·. · ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAokCsKxwrckYApPJF5gXEdbXsK3XQoKc3tUYExgbGDCsS4KVDAxYGxgTGDCsS4qwrdbQS1aXQrCscK3CgrCsSguKQokMcKxCsK3LgrCtw&input=SGVsbG8sIE1pZG5pZ2h0YXMKLlEKLnE) (The first line enables a test suite with multiple linefeed-separated test cases.) [Answer] ## JavaScript (ES6), ~~95~~ 83 bytes ``` s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join`` ``` Edit: Saved a massive 12 bytes thanks to @edc65. [Answer] ## Pyke, ~~11~~ ~~10~~ 9 bytes ``` _FQo@UhAl ``` [Try it here!](http://pyke.catbus.co.uk/?code=_FQo%40UhAl&input=Hello%2C+Midnightas) ``` _ - reversed(input) F - for i in ^ o - o+=1 Q @ - input[^] Uh - ^.is_upper()+1 Al - [len, str.lower, str.upper, ...][^](i) - "".join(^) ``` [Answer] # [J](http://jsoftware.com), 30 bytes ``` (={"_1 toupper@]|.@,.])tolower ``` Doesn't support non-ASCII [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ ~~16~~ ~~15~~ 13 bytes Thanks to **Emigna** for saving a 3 bytes! Probably gonna get beat by Jelly... Code: ``` Âuvy¹Nè.lil}? ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4J1dnnCuU7DqC5saWx9Pw&input=SGVsbG8sIE1pZG5pZ2h0YXM). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes ``` @lr:?z:1ac. h@u.,@A@um~t?|h. ``` ### Explanation * Main Predicate: ``` @lr Reverse the lowercase version of the Input :?z Zip that reversed string with the Input :1a Apply predicate 1 to each couple [char i of reverse, char i of Input] c. Output is the concatenation of the result ``` * Predicate 1: ``` h@u., Output is the uppercase version of the first char of Input @A@um~t? The second char of Input is an uppercase letter | Or h. Output is the first char of Input ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` PktGtk<)Xk5M( ``` [**Try it online!**](http://matl.tryitonline.net/#code=UGt0R3RrPClYazVNKA&input=J0hlbGxvLCBNaWRuaWdodGFzJw) ``` Pk % Implicit inpput. Flip, lowercase t % Duplicate Gtk< % Logical index of uppercase letters in the input string ) % Get letters at those positions in the flipped string Xk % Make them uppercase 5M( % Assign them to the indicated positions. Implicit display ``` [Answer] # TSQL, 175 bytes Golfed: ``` DECLARE @ varchar(99)='Hello, Midnightas' ,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z PRINT @o ``` Ungolfed ``` DECLARE @ varchar(99)='Hello, Midnightas' ,@o varchar(99)='' ,@i INT=0 WHILE @i<LEN(@) SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y)) FROM (SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z PRINT @o ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/508510/reverse-a-string-while-maintaining-the-capitalization-in-the-same-places)** [Answer] ## Actually, 25 bytes ``` ;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ ``` [Try it online!](http://actually.tryitonline.net/#code=O2DDusOtdVkiw7nDuyJFwqNgTUDDuVJaYGlAxpJgTc6j&input=ImFiQ2Qi) Explanation: ``` ;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ ; create a copy of the input `úíuY"ùû"E£`M for each character in input: úíuY 0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0) "ùû"E£ `û` if the character is lowercase else `ù` (str.lower vs str.upper) @ùRZ make the other copy of the input lowercase, reverse it, and zip it with the map result `i@ƒ`M for each (string, function) pair: i@ƒ flatten, swap, apply (apply the function to the string) Σ concatenate the strings ``` [Answer] # Haskell, ~~83~~ ~~80~~ ~~75~~ 71 bytes The most straightforward way I could think of. ``` import Data.Char f a|isUpper a=toUpper|1>0=toLower zipWith f<*>reverse ``` [Answer] # PowerShell, ~~154~~, ~~152~~, ~~99~~, 86 bytes Thank you @TimmyD for saving me a whopping 47 bytes (I also saved an additional 6) Thank you @TessellatingHeckler for saving an additional 13 bytes. Latest: ``` param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]}) ``` Original: ``` param($a);$x=0;(($a[-1..-$a.length])|%{$_=$_.tostring().tolower();if([regex]::matches($a,"[A-Z]").index-contains$x){$_.toupper()}else{$_};$x++})-join'' ``` Normal formatting: Latest (looks best as two lines in my opinion): ``` param($a) -join($a[$a.length..0] | %{("$_".ToLower(), "$_".ToUpper())[$a[$i++] -in 65..90]}) ``` Explanation: ``` param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]}) param($a) # Sets the first passed parameter to variable $a -join( ) # Converts a char array to a string $a[$a.length..0] # Reverses $a as a char array |%{ } # Shorthand pipe to foreach loop ("$_".ToLower(),"$_".ToUpper()) # Creates an array of the looped char in lower and upper cases [$a[$i++]-in65..90] # Resolves to 1 if the current index of $a is upper, which would output "$_".ToUpper() which is index 1 of the previous array ``` Original: ``` param($a) $x = 0 (($a[-1..-$a.length]) | %{ $_ = $_.tostring().tolower() if([regex]::matches($a,"[A-Z]").index -contains $x){ $_.toupper() }else{ $_ } $x++ } ) -join '' ``` First time poster here, was motivated because I rarely see PowerShell, ~~but at ~~154~~ 152 bytes on this one... I can see why!~~ Any suggestions appreciated. I have learned that I must completely change my way of thinking to golf in code and its fun! [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⌽f¨⍨⊢≠f←819⌶ ``` `819⌶` is the case folding function `f←` because its name is long, we assign it to *f* `⊢≠f` Boolean where text differs from lower-cased text `f¨⍨` use that (1 means uppercase, 0 means lowercase) to fold each letter... `⌽` ... of the reversed text Handles non-ASCII according to the Unicode Consortium's rules. [Answer] ## CJam, 22 bytes ``` q_W%.{el\'[,65>&{eu}&} ``` [Test it here.](http://cjam.aditsu.net/#code=q_W%25.%7Bel%5C'%5B%2C65%3E%26%7Beu%7D%26%7D&input=Hello%2C%20Midnightas) [Answer] # Racket, 146 bytes ``` (λ(s)(build-string(string-length s)(λ(n)((if(char-upper-case?(string-ref s n))char-upcase char-downcase)(list-ref(reverse(string->list s))n))))) ``` Racket is bad at this whole "golfing" thing. *Shrug* As always, any help with shortening this would be much appreciated. [Answer] # Jolf, 21 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpxpZD8mzrMuX3BYaVM9cHhISHB4zrPOsw&input=SGVsbG8sIE1pZG5pZ2h0YXMKCi5R) ``` Μid?&γ._pXiS=pxHHpxγγ ``` ## Explanation ``` Μid?&γ._pXiS=pxHHpxγγ Μid (Μ)ap (i)nput with (d)is fucntion: ? =pxHH (H is current element) if H = lowercase(H) &γ._pXiS and set γ to the uppercase entity in the reversed string pxγ lowercase γ γ else, return γ ``` [Answer] # [Perl 6](http://perl6.org), 29 bytes ``` $_=get;put .flip.samecase($_) ``` [Answer] # C#, ~~86~~ 85 bytes ``` s=>string.Concat(s.Reverse().Select((c,i)=>s[i]>96?char.ToLower(c):char.ToUpper(c))); ``` A C# lambda where the input and the output is a string. You can try it on [.NetFiddle](https://dotnetfiddle.net/0NjPq2). --- ~~I am struggling to understand why I cant achieve to convert `char.ToLower(c)` to `c+32`. I hope to fix it!~~ 12 bytes saved thanks to @PeterTaylor (`c|32` to add 32 to the ascii value of `c` and `c&~32` to substract 32). The result would be 72 bytes (but can fail on non alpha char). ``` s=>string.Join("",s.Reverse().Select((c,i)=>(char)(s[i]>96?c|32:c&~32))); ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~9~~ 2 bytes ``` Ṙ• ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwi4bmY4oCiIiwiIiwiSGVsbG8iXQ==) [Answer] # [Julia 1.0](http://julialang.org/), ~~73, 65~~ 64 bytes ``` !s=prod(titlecase(s[end-i+1]^2)[2-('@'<s[i]<'[')] for i=keys(s)) ``` [Try it online!](https://tio.run/##NcqxDsIgEADQ3a@44gDE1qSd26SDg4uDcSSYEIvl9ATTw6hfj5NvfrcXoWs/pVQ8PJc0qYyZ/MWxV2x8nBrctPbcadM1So6yZ4O2l0ZqC9e0AA53/2XFWpeRQ3pDJfaeKNVwwCniHLJjAWs4uRxmjDt8QJ2IfFj9@/Yoyg8 "Julia 1.0 – Try It Online") -9 MarcMush [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 bytes ``` ŒlðUŒuT}¦n ``` [Try it online!](https://tio.run/##y0rNyan8///opJzDG0KPTioNqT20LO////8eQPF8HQXfzJS8zPSMksRiAA "Jelly – Try It Online") Did I say this was extremely golfable by someone who understands `¦`? Turns out it's just understanding anything at all about chaining in general. ``` Œl Lowercase the input, U reverse it, Œu then uppercase it T}¦ at indices where ð n the lowercase input doesn't equal the original input. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 139 bytes ``` #define B v[c+~i] #define C(x,y)isupper(x)?toupper(y):tolower(y) i,t,c;f(char*v){for(c=strlen(v);i<c/2;i++)t=C(B,v[i]),v[i]=C(v[i],B),B=t;} ``` [Try it online!](https://tio.run/##XY7NasMwEITveoqFXKRYbWmPVdyCc8kb9GB8cPXjLCiSkWUlIaSv7spOA6F7mJ35GJaVT52U07RS2qDTUEGqZfGDDbmTLT3xM8Nh7Hsd6Il9Rn@zZ/YevfXHxRLkkUthqNy3YZ3YxfhAZTnEYLWjiQncyJc3gUXBYrmlFU81NmzRHOfFK8arMorrtEIn7ag0bIaoLH4/7z/IIwvouv9MoZ8RugiHFh2dTRs6yWF@CNbZp7ph5EIgz43lS1BCVjX2dCm8NkyQpWFo5vfQj3F4zCZo/ZevME07ba2HLx@s@gU "C (gcc) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~114~~ ~~92~~ 78 bytes ``` ~x=(b=reverse(lowercase(x));prod(i->b[i]-32('@'<x[i]<'['<b[i]-5<'v'),keys(b))) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v67CViPJtii1LLWoOFUjJ788tSg5Eciq0NS0LijKT9HI1LVLis6M1TU20lB3ULepALJt1KPVbcCCpjbqZeqaOtmplcUaSZqamv8dijPyyxXqlDxSc3LydRR8M1PyMtMzShKLlbhgUnqBCHZilWMUgucIBA7RCdVK/wE "Julia 1.0 – Try It Online") * -22 bytes thanks to amelies: use `prod` * -10 bytes thanks to MarcMush: avoid `uppercase` and `isuppercase` * -4 bytes thanks to MarcMush: use `keys(b)` instead of `1:length(b)` [Answer] # PHP, 128 bytes ``` $s=$argv[1];$l=strrev($s);for($i=0;$i<strlen($s);++$i){echo(strtolower($s[$i])!==$s[$i]?strtoupper($l[$i]):strtolower($l[$i]));} ``` I may attempt to optimize this further but I'll just leave it as is for now. [Answer] # Octave, ~~51~~ 50 bytes ~~`@(s)merge(isupper(s),b=flip(toupper(s)),tolower(b))`~~ ``` @(s)merge(s>64&s<91,b=flip(toupper(s)),tolower(b)) ``` ]
[Question] [ The challenge is to make any [Roman numerals](http://en.wikipedia.org/wiki/Roman_numerals) valid code in your chosen language. They should **not** appear inside of strings or anything similar, but work just like any other tokens, [literals](http://en.wikipedia.org/wiki/Literal_%28computer_programming%29) such as ([Arabic](http://en.wikipedia.org/wiki/Arabic_numerals)) numbers, characters or strings; or variable/method/function identifiers, etc. For instance, in Java, the following would have to compile and run just as if `i` was initialized to `42`: ``` int i = XLII; ``` The actual parsing of the numerals is secondary, so you can use a library if you want to, but this is a popularity contest, so creativity is encouraged. You cannot use any language that actually uses roman numerals, if there is such a thing. Good luck. [Answer] # C There are only so many Roman numerals, since 4000 and higher have no standard notation, and the preprocessor is a wonderful decompression tool, especially if you have no problems with the fact that the code has undefined behaviour. ``` enum{_ #define a_ #define d_ #define g_ #define j_ #define a(x)c(x)b #define b(x)c(x)a #define c(x)x, #define d(x)f(x)e #define e(x)f(x)d #define f(x)m(a(x)(x##I)(x##II)(x##III)(x##IV)(x##V)(x##VI)(x##VII)(x##VIII)(x##IX)) #define g(x)i(x)h #define h(x)i(x)g #define i(x)m(d(x)(x##X)(x##XX)(x##XXX)(x##XL)(x##L)(x##LX)(x##LXX)(x##LXXX)(x##XC)) #define j(x)l(x)k #define k(x)l(x)j #define l(x)m(g(x)(x##C)(x##CC)(x##CCC)(x##CD)(x##D)(x##DC)(x##DCC)(x##DCCC)(x##CM)) #define m(x)n(x) #define n(...)__VA_ARGS__##_ m(j()(M)(MM)(MMM)) }; ``` This defines all Roman numerals from `I` to `MMMCMXCIX` as enumeration constants, plus `_` (which can be replaced by anything you like) as zero. [Answer] ## Ruby ``` def Object.const_missing(const) i = const.to_s if i =~ /^[IVXLCDM]+$/ #http://codegolf.stackexchange.com/questions/16254/convert-arbitrary-roman-numeral-input-to-integer-output %w[IV,4 IX,9 XL,40 XC,90 CD,400 CM,900 I,1 V,5 X,10 L,50 C,100 D,500 M,1000].map{|s|k,v=s.split ?,;i.gsub!(k,?++v)} eval(i) else super end end ``` Any (uppercase) Roman numerals will now be parsed like their decimal equivalents. The only issue is that they're still assignable: you can do `X = 9`, but not `10 = 9`. I don't think there's a way to fix that. [Answer] # JavaScript (ES6) Use `Proxy` to catch roman numerals. Testable in Firefox (latest) on [JSFiddle](http://jsfiddle.net/ooflorent/LD5Xm/). Not testable in Chrome (with Traceur) since `Proxy` implementation is broken. ``` // Convert roman numeral to integer. // Borrowed from http://codegolf.stackexchange.com/a/20702/10920 var toDecimal = (s) => { var n = 0; var X = { M: 1e3, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }; s.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, (d) => n += X[d]); return n; }; // Whether a string is a valid roman numeral. var isRoman = (s) => s.match(/^[MDCLXVI]+$/); // Profixy global environment to catch roman numerals. // Since it uses `this`, global definitions are still accessible. var romanEnv = new Proxy(this, { get: (target, name) => isRoman(name) ? toDecimal(name) : target[name], set: (target, name, value) => isRoman(name) ? undefined : (target[name] = value), has: (target, name) => isRoman(name) || name in target, hasOwn: (target, name) => name in target }); ``` Usage: ``` with (romanEnv) { var i = MIV + XLVIII; console.log(i); // 1052 } ``` [Answer] # C & C++ (Updated Answer) As observed in a comment, my original solution had two problems: 1. Optional parameters are only available in C99 and later standards of the language family. 2. Trailing comma in enum definition is also specific to C99 and later. Since I wanted my code to be as generic as possible to work on older platforms, I decided to take another stab at it. It is longer than it was before, but it works on compilers and preprocessors set to C89/C90 compatibility mode. All macros are passed an appropriate number of arguments in the source code, though sometimes those macros "expand" into nothing. Visual C++ 2013 (aka version 12) emits warnings about missing parameters, but neither mcpp (an open source preprocessor that claims high compliance with the standard) nor gcc 4.8.1 (with -std=iso9899:1990 -pedantic-errors switches) emit warnings or errors for those macro invocations with an effectively empty argument list. After reviewing the relevant standard (ANSI/ISO 9899-1990, 6.8.3, Macro Replacement), I think there is sufficient ambiguity that this should not be considered non-standard. "The number of arguments in an invocation of a function-like macro shall agree with the number of parameters in the macro definition...". It does not seem to preclude an empty argument list as long as the needed parentheses (and commas in the case of multiple parameters) are in place to invoke the macro As for the trailing comma problem, that is resolved by adding an extra identifier to the enumeration (in my case, MMMM which seems as reasonable as anything for the identifier to follow 3999 even if it doesn't obey the accepted rules of Roman numeral sequencing exactly). A slightly cleaner solution would involve moving the enum and supporting macros to a separate header file as was implied in a comment elsewhere, and using undef of the macro names immediately after they were used so as to avoid polluting the namespace. Better macro names should undoubtedly be chosen as well, but this is adequate for the task at hand. My updated solution, followed by my original solution: ``` #define _0(i,v,x) #define _1(i,v,x) i #define _2(i,v,x) i##i #define _3(i,v,x) i##i##i #define _4(i,v,x) i##v #define _5(i,v,x) v #define _6(i,v,x) v##i #define _7(i,v,x) v##i##i #define _8(i,v,x) v##i##i##i #define _9(i,v,x) i##x #define k(p,s) p##s, #define j(p,s) k(p,s) #define i(p) j(p,_0(I,V,X)) j(p,_1(I,V,X)) j(p,_2(I,V,X)) j(p,_3(I,V,X)) j(p,_4(I,V,X)) j(p,_5(I,V,X)) j(p,_6(I,V,X)) j(p,_7(I,V,X)) j(p,_8(I,V,X)) j(p,_9(I,V,X)) #define h(p,s) i(p##s) #define g(p,s) h(p,s) #define f(p) g(p,_0(X,L,C)) g(p,_1(X,L,C)) g(p,_2(X,L,C)) g(p,_3(X,L,C)) g(p,_4(X,L,C)) g(p,_5(X,L,C)) g(p,_6(X,L,C)) g(p,_7(X,L,C)) g(p,_8(X,L,C)) g(p,_9(X,L,C)) #define e(p,s) f(p##s) #define d(p,s) e(p,s) #define c(p) d(p,_0(C,D,M)) d(p,_1(C,D,M)) d(p,_2(C,D,M)) d(p,_3(C,D,M)) d(p,_4(C,D,M)) d(p,_5(C,D,M)) d(p,_6(C,D,M)) d(p,_7(C,D,M)) d(p,_8(C,D,M)) d(p,_9(C,D,M)) #define b(p) c(p) #define a() b(_0(M,N,O)) b(_1(M,N,O)) b(_2(M,N,O)) b(_3(M,N,O)) enum { _ a() MMMM }; #include <stdio.h> int main(int argc, char** argv) { printf("%d", MMMCMXCIX * MMMCMXCIX); return 0; } ``` The original answer (which received the first six upvotes, so if no one ever upvotes this again, you shouldn't think my updated solution got the upvotes): In the same spirit as an earlier answer, but done in a way that *should* be portable using only defined behavior (though different environments don't always agree on some aspects of the preprocessor). Treats some parameters as optional, ignores others, it should work on preprocessors that don't support the `__VA_ARGS__` macro, including C++, it uses indirect macros to ensure parameters are expanded before token pasting, and finally it is shorter and I think easier to read (though it is still tricky and probably not *easy* to read, just easier): ``` #define g(_,__) _, _##I, _##II, _##III, _##IV, _##V, _##VI, _##VII, _##VIII, _##IX, #define f(_,__) g(_,) #define e(_,__) f(_,) f(_##X,) f(_##XX,) f(_##XXX,) f(_##XL,) f(_##L,) f(_##LX,) f(_##LXX,) f(_##LXXX,) f(_##XC,) #define d(_,__) e(_,) #define c(_,__) d(_,) d(_##C,) d(_##CC,) d(_##CCC,) d(_##CD,) d(_##D,) d(_##DC,) d(_##DCC,) d(_##DCCC,) d(_##CM,) #define b(_,__) c(_,) #define a b(,) b(M,) b(MM,) b(MMM,) enum { _ a }; ``` [Answer] # Common Lisp The following is a rather lengthy explanation of how I made a macro that you can use like this: ``` (roman-progn (+ XIV XXVIII)) ``` When a macro is called in Common Lisp, it basically acts like a function, only that the arguments are received *before* they are evaluated. Actually, since in Common Lisp code is just data, what we receive is a (nested) list representing an unparsed syntax tree that we can do whatever we want with, and it's done in compile-time. ### Helper functions The first step of the plan is to take this tree and scan it for anything that looks like Roman Numerals. This being Lisp and all, let's try to do it somewhat functionally: We need a function that will do a deep traversal of a tree and return every object for which a provided function `searchp` returns true. This one is even (semi) tail-recursive. ``` (defun deep-find-all (searchp tree &optional found) (if (null tree) found (let* ((item (car tree)) (new-found (if (consp item) (deep-find-all searchp item found) (if (funcall searchp item) (cons item found) found)))) (deep-find-all searchp (cdr tree) new-found)))) ``` Then some code for parsing the roman numerals, courtesy of [Rosetta Code](http://rosettacode.org/wiki/Roman_numerals/Decode#Common_Lisp): ``` (defun mapcn (chars nums string) (loop as char across string as i = (position char chars) collect (and i (nth i nums)))) (defun parse-roman (R) (loop with nums = (mapcn "IVXLCDM" '(1 5 10 50 100 500 1000) R) as (A B) on nums if A sum (if (and B (< A B)) (- A) A))) ``` ### The actual macro We take the syntax tree (`body`), search it with our deep-find-all procedure and somehow make the roman numerals that we find, available. ``` (defmacro roman-progn (&body body) (let* ((symbols (deep-find-all (lambda (sym) (and (symbolp sym) (loop for c across (string sym) always (find c "IVXLCDM")))) body)) (parsed-romans (mapcar (lambda (sym) (list sym (parse-roman (string sym)))) symbols))) (if parsed-romans `(let (,@parsed-romans) ,@body) `(progn ,@body)))) ``` So, what is `1 + 2 + 3 + (4 * (5 + 6)) + 7` ? ``` (roman-progn (+ I II III (* IV (+ V VI)) VII)) => 57 ``` And to see what actually happened when the macro was invoked: ``` (macroexpand-1 +) => (LET ((VII 7) (VI 6) (V 5) (IV 4) (III 3) (II 2) (I 1)) (+ I II III (* IV (+ V VI)) VII)) ``` [Answer] # Lua ``` setmetatable(_G, { __index = function(_, k) if k:match"^[IVXLCDM]*$" then local n = 0 for _, v in ipairs{{IV = 4}, {IX = 9}, {I = 1}, {V = 5}, {XL = 40}, {X = 10}, {XC = 900}, {CD = 400}, {CM = 900}, {C = 100}, {D = 500}, {M = 1000}} do local p, q = next(v) local r k, r = k:gsub(p, "") n = n + r * q end return n end end }) ``` Simply a fallback \_\_index for the global table. The actual conversion using gsub turned out much prettier than I imagined it to be. [Answer] # Smalltalk (Smalltalk/X) (87/101 chars) of course we could easily modify the parser's tokenizer (as it is part of the class library, and as such open for modification, and always present), but a challenge is to affect only evaluations in a given context, so that the rest of the system works as usual. ### Version 1: define a number of variables in the evaluation namespace. So this will affect interactive doIts (aka evals): ``` (1 to:3999) do:[:n | Workspace workspaceVariables at:(n romanPrintString asUppercase) put:n] ``` then I can do (in a doIt, but not in compiled code): ``` |a b| a := MMXIV. b := V. a + b ``` -> 2019 Notice: the 101 chars includes whitespace; actually it can be done with 87 chars. Also notice, when define in the global Smalltalk namespace, I'd see those constants also in compiled code. ### Version 2: Use a methodWrapper hook, which allows for any existing code to be wrapped without recompiling. The following wraps the Parser's tokenizer to look for a roman identifier to be scanned and makes it an integer. The tricky part is to dynamically detect if the calling context is from the roman empire or not. This is done using a query signal (which is technically a proceedable exception): define the query: ``` InRomanScope := QuerySignal new defaultAnswer:false. ``` So we can ask at any time ("InRomanScope query") to get false by default. Then wrap the scanner's checkIdentifier method: ``` MessageTracer wrapMethod:(Scanner compiledMethodAt:#checkForKeyword:) onEntry:nil onExit:[:ctx :ret | InRomanScope query ifTrue:[ |scanner string token n| scanner := ctx receiver. string := ctx argAt:1. (n := Integer readFromRomanString:string onError:nil) notNil ifTrue:[ scanner "/ hack; there is no setter for those two instVarNamed:'tokenType' put:#Integer; instVarNamed:'tokenValue' put:n. true ] ifFalse:[ ret ]. ] ifFalse:[ ret ] ]. ``` Now the scanner works as usual, unless we are in the roman empire: ``` InRomanScope answer:true do:[ (Parser evaluate:'MMDXXV') printCR. ]. ``` -> 2525 we can even compile code: ``` Compiler compile:' inTheYear2525 ^ MMDXXV ' forClass:Integer. ``` nice try; but this fails with a syntax error (which is exactly what we want). However, in the roman empire, we CAN compile: ``` InRomanScope answer:true do:[ Compiler compile:' inTheYear2525 ^ MMDXXV ' forClass:Integer. ] ``` and now, we can ask any integer (sending that message) from inside and outside of Rome: ``` (1000 factorial) inTheYear2525 ``` -> 2525 [Answer] ## D using D's compile time function evaluation ``` import std.algorithm; string numerals(){ auto s = cartesianProduct(["","I","II","III","IV","V","VI","VII","VIII","IX"], ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"], ["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"], ["","M","MM","MMM"]); s.popFront();//skip first char[] result="enum "; int i=1; foreach(p;s){ result~=p[3]~p[2]~p[1]~p[0]~"="~i++~","; } result[$-1]=';';//replace last , with a ; return result.idup; } mixin(numerals()); ``` [Answer] # Postscript I tried to follow the C one but I didn't understand it. So I did it this way: ``` /strcat{ 2 copy length exch length add string % 1 2 3 3 2 roll % 2 3 1 2 copy 0 exch putinterval % 2 3 1 2 copy length % 2 3 1 3 n(1) 5 4 roll putinterval % 3 1 pop }def /S{ dup length string cvs } def [ /u {/ /I /II /III /IV /V /VI /VII /VIII /IX} /t {/ /X /XX /XXX /XL /L /LX /LXX /LXXX /XC} /h {/ /C /CC /CCC /CD /D /DC /DCC /DCCC /CM} /m {/ /M /MM /MMM /MMMM} >>begin [0 [ [m]{ % M* S [h]{ % M* H* S [t]{ % M* H* T* S [u]{ % M* H* T* U* S 4 copy strcat strcat strcat % M* H* T* U* M*H*T*U* 5 1 roll % M*H*T*U* M* H* T* U* pop % (M*H*T*U*)* M* H* T* }forall pop % (M*H*T*U*)** M* H* }forall pop % (M*H*T*U*)*** M* }forall pop % (M*H*T*U*)**** }forall ] {exch dup 1 add}forall pop>>end begin ``` Postscript doesn't have `enum` but we can construct a dictionary with sequential integer values and fold them into an array. This reduces the problem to generating all the strings in sequence, which is done by concatenating in 4 nested loops. So it generates all the strings, then interleaves each string with an increasing counter value, resulting in a long series of *<string> <int>* pairs on the stack which are wrapped in `<<`...`>>` to produce a dictionary object. The program constructs and installs a dictionary mapping all names for the roman numerals to their corresponding value. So mentioning the names in source text invokes the automatic name-lookup and yields the integer value on the stack. ``` II IV MC pstack ``` prints ``` 2 4 600 ``` [Answer] # J - 78 char This only goes up to MMMCMXCIX = 3999, as with the other solutions. ``` (}.,;L:1{M`CDM`XLC`IVX('';&;:(_1,~3#.inv]){' ',[)&.>841,3#79bc5yuukh)=:}.i.4e3 ``` Breaking it down (recall J is usually read from right to left, unless superseded by parentheses): * `M`CDM`XLC`IVX` - Four boxes of letters. We're going to use numeric arrays into index into these letters and build up subwords of Roman numerals. * `841,3#79bc5yuukh` - This is the numeric data, tightly encoded.\* * `(_1,~3#.inv])` - This will decode the above data, by expanding in ternary and appending -1. * `('';&;:(...){' ',[)&.>` - Pairing up the numbers on the left with the boxes on the right (`&.>`), decode the arrays of numbers and use them to index into the letters. We treat 0 as space by prepending a space character to the letter lists. This procedure builds lists of words like `I II III IV V VI VII VIII IX` and `M MM MMM`. * `{` - Take the Cartesian product of these four boxes full of words. Now we have a 4D array of all the Roman numerals. * `}.,;L:1` - Run all that into a single 1D list of Roman numerals, and remove the empty string at the front because it would create an error. (`L:` is a rare sight in J golf! Usually there are not this many levels of boxing involved.) * `}.i.4e3` - The integers from 0 to 4000, *excluding* the endpoints. * Finally, we put everything together with a global assignment `=:`. J allows you to have a boxed list of names on the LHS, as a form of computed multiple assignment, so this works out fine. Now the J namespace is full of variables representing Roman numerals. ``` XCIX 99 MMCDLXXVIII 2478 V * LXIII NB. 5*63 315 #4!:1]0 NB. How many variables are now defined in the J namespace? 3999 ``` \* I need the number 2933774030998 to later be read in base 3. It so happens that I can express it in base 79 using digits no greater than 30, which is good because J can only understand digits up to 35 (0-9 and then a-z). This saves 3 characters over decimal. [Answer] Haskell, using meta-programming in [Template Haskell](http://www.haskell.org/haskellwiki/Template_Haskell) and [roman-numerals](https://hackage.haskell.org/package/roman-numerals-0.5.1.3): ``` {-# LANGUAGE TemplateHaskell #-} import Data.Char (toLower) import Language.Haskell.TH import Text.Numeral.Roman $( mapM (\n -> funD (mkName . map toLower . toRoman $ n) [ clause [] (normalB [| n |]) []]) $ [1..1000 :: Int] ) main = print xlii ``` Haskell reserves identifiers starting with upper case letters for constructors, so I used lower-case. [Answer] ## Python The Idea is simple as the other answers. But Just to be neat and not to pollute the global namespace, a context manager is used. This also imposes the restriction, that you need to declare before hand, the extent of Roman numerical you are planning to use. **Note** Just to keep it simple, and not to reinvent the wheel, I have utilized the [Roman python package](https://pypi.python.org/pypi/rome/0.0.2) **Implementation** ``` class Roman(object): memo = [0] def __init__(self, hi): import rome if hi <= len(RomanNumericals.memo): self.romans = Roman.memo[0:hi] else: Roman.memo += [str(rome.Roman(i)) for i in range(len(Roman.memo), hi+1)] self.romans = Roman.memo def __enter__(self): from copy import copy self.saved_globals = copy(globals()) globals().update((v,k) for k,v in enumerate(self.romans[1:], 1)) def __exit__(self,*args ): globals().clear() globals().update(self.saved_globals) ``` **Demo** ``` with Roman(5): with Roman(10): print X print V print X 10 5 Traceback (most recent call last): File "<pyshell#311>", line 5, in <module> print X NameError: name 'X' is not defined ``` [Answer] # Rebol ``` Rebol [] roman-dialect: func [ {Dialect which allows Roman numerals as numbers (integer!)} block [block!] /local word w m1 m2 when-in-rome rule word-rule block-rule ][ when-in-rome: does [ if roman? w: to-string word [change/part m1 roman-to-integer w m2] ] word-rule: [m1: copy word word! m2: (when-in-rome)] block-rule: [m1: any-block! (parse m1/1 rule)] rule: [any [block-rule | word-rule | skip]] parse block rule do block ] ; couple of helper functions used in above parse rules roman-to-integer: func [roman /local r eval] [ r: [IV 4 IX 9 XL 40 XC 90 CD 400 CM 900 I 1 V 5 X 10 L 50 C 100 D 500 M 1000] eval: join "0" copy roman foreach [k v] r [replace/all eval k join " + " v] do replace/all to-block eval '+ '+ ] roman?: func [s /local roman-chars] [ roman-char: charset "IVXLCDM" parse/case s [some roman-char] ] ``` ### Example ``` roman-dialect [ m: X + V print m print M + m ; doesn't confuse the variable m with Roman Numeral M if now/year = MMXIV [print "Yes it is 2014"] for n I V I [ print [rejoin [n "+" X "="] n + X] ] ] ``` Output: > > 15 > > > 1015 > > > Yes it is 2014 > > > 1+10= 11 > > > 2+10= 12 > > > 3+10= 13 > > > 4+10= 14 > > > 5+10= 15 > > > Disclaimer: I'm sure there are other (and probably better!) ways of doing this in Rebol as well. PS. My `roman-to-integer` function is a transliteration of *histocrat*'s nice Ruby algorithm for converting Roman Numeral string into a number. Returned with thanks! +1 [Answer] **Python** This is possibly the simplest solution using Python: ``` ns = [1000,900,500,400,100,90,50,40,10,9,5,4,1] ls = 'M CM D CD C XC L XL X IX V IV I'.split() for N in range(1, 4000): r='' p=N for n,l in zip(ns,ls): while p>=n: r+=l p-=n exec('%s=%d'%(r,N)) i, j = XIX, MCXIV print i, j ``` [Answer] # [APL (Dyalog APL)](https://www.dyalog.com/), 77 bytes Prompts for Roman numeral maximum length and defines all variables. ``` t←'IVXLCDM',⊂⍬ {⍎⍕⍵'←',+/2(⊣ׯ1*<)/0,⍨(∊1 5∘ר10*⍳4)[t⍳⍵]}¨,/t[⍉8⊥⍣¯1⍳¯1+8*⎕] ``` `t←` *t* gets `'IVXLCDM',` Roman chars followed by `⊂` an enclosed `⍬` empty list `t[`…`]` index *t* with…  `⍉` the transposed (to get the right order)  `8⊥⍣¯1` appropriate width base-eight representation of  `⍳` the first *n* indices, where *n* is  `¯1+` one less than  `8*⎕` eight to the power of numeric input `,/` flatten rows (each representation) `{`…`}¨` apply the following anonymous function on each representation…  `(`…`)[t⍳⍵]` corresponding to the positions of the argument's items in *t*, select from…   `∊` the enlisted   `1 5∘ר` one and five times each of   `10*` ten to the power of   `⍳4` zero through three  `0,⍨` append zero  `2(…)/` on each length-two sliding window, apply the following anonymous function train…   `⊣×` the left argument times   `¯1*` negative one to the power of   `<` whether the left argument is less than the right argument  `+/` sum  `⍵'←',` prepend the argument (the Roman numeral) and an assignment arrow  `⍕` format (to flatten and convert the number to text)  `⍎` execute that (makes the assignment outside the anonymous function) [Try it online!](https://tio.run/nexus/apl-dyalog#LU67CsJAEOzzFdvldZBEDESwyzULBq1OIeQv0omNhcSDCzYh9kFIIViI2Cd/sj8SV3SL2ZkdZliqG1zT6RJaVDebLbMFz1QysVHtVqnMbEH6SOZu7cnUZBoyL/trCz@YOaS7sR0ekbd0g1CQ6R2qdAQxVVe@91HokXnO3bzkxcHiMPQiKHMy54T0jUzHWbYY/cTjF4qJgdsVwtiCQrR@WioJ4xtS@dcIEiVkmGEKKSpGlFP8AQ "APL (Dyalog APL) – TIO Nexus") (using max-length 5) [Answer] # PHP There a several rules for valid roman numbers 1. Write the greatest value befor the lower values 2. Subtract only `[I,X,C]` before the next 2 greater values 3. Subtract double `[I,X,C]` before the next 2 greater values 4. Subtract double `[I,X,C]` before the greater values 5. Combine 4+5 [Online Version](http://sandbox.onlinephpfunctions.com/code/ca0588c9910bdeaf885496dc518e75f45aa15091) ## Step 1 Create the rules ``` {"M":1000,"IM":999,"IIM":998,"XM":990,"XXM":980,"CM":900,"CCM":800,"D":500,"ID":499,"IID":498,"XD":490,"XXD":480,"CD":400,"C":100,"IC":99,"IIC":98,"XC":90,"XXC":80,"L":50,"IL":49,"IIL":48,"XL":40,"X":10,"IX":9,"IIX":8,"V":5,"IV":4,"I":1} ``` is the JSON output for all valid roman numbers ``` $rule_sub_all=$rule_add=$rule_sub_simple=["M"=>1000,"D"=>500,"C"=>100,"L"=>50,"X"=>10,"V"=>5,"I"=>1]; foreach(["I","X","C"]as$roman_letter){ $rule_sub_simple[$roman_letter.array_search($value=$rule_add[$roman_letter]*5,$rule_add)]=$value-$rule_add[$roman_letter]; $rule_sub_simple[$roman_letter.array_search($value=$rule_add[$roman_letter]*10,$rule_add)]=$value-$rule_add[$roman_letter]; } $rule_sub_lower_one=$rule_sub_double=$rule_sub_simple; foreach(["I","X","C"]as$roman_letter){ $rule_sub_double[$roman_letter.$roman_letter.array_search($value=$rule_add[$roman_letter]*10,$rule_add)]=$value-2*$rule_add[$roman_letter]; foreach($rule_add as$key=>$value){ if($value>$rule_add[$roman_letter])$rule_sub_all[$roman_letter.$key]=$value-$rule_add[$roman_letter]; if($value>5*$rule_add[$roman_letter])$rule_sub_all[$roman_letter.$roman_letter.$key]=$value-2*$rule_add[$roman_letter]; if($value>10*$rule_add[$roman_letter])$rule_sub_lower_one[$roman_letter.$key]=$value-$rule_add[$roman_letter]; } } arsort($rule_sub_all); arsort($rule_sub_lower_one); arsort($rule_sub_double); arsort($rule_sub_simple); ``` ## Step 2 Make lists for all rules till 3999 ``` $array_sub_lower_one=$array_sub_double=$array_sub_all=$array_add=$array_sub_simple=[]; for($i=1;$i<4000;$i++){ $number_sub_all=$number_add=$number_sub_simple=$number_sub_double=$number_sub_lower_one=$i; $roman_letter_sub_all=$roman_letter_add=$roman_letter_sub_simple=$roman_letter_sub_double=$roman_letter_sub_lower_one=""; foreach($rule_sub_all as$key=>$value){ $roman_letter_sub_all.=str_repeat($key,$d=$number_sub_all/$value^0);$number_sub_all-=$value*$d; if(in_array($value,$rule_sub_lower_one)){ $roman_letter_sub_lower_one.=str_repeat($key,$d=$number_sub_lower_one/$value^0);$number_sub_lower_one-=$value*$d;} if(in_array($value,$rule_add)){ $roman_letter_add.=str_repeat($key,$d=$number_add/$value^0);$number_add-=$value*$d;} if(in_array($value,$rule_sub_simple)){ $roman_letter_sub_simple.=str_repeat($key,$d=$number_sub_simple/$value^0);$number_sub_simple-=$value*$d;} if(in_array($value,$rule_sub_double)){ $roman_letter_sub_double.=str_repeat($key,$d=$number_sub_double/$value^0);$number_sub_double-=$value*$d;} } $array_sub_lower_one[$roman_letter_sub_lower_one]=$i; $array_sub_all[$roman_letter_sub_all]=$i; $array_add[$roman_letter_add]=$i; $array_sub_simple[$roman_letter_sub_simple]=$i; $array_sub_double[$roman_letter_sub_double]=$i; } ``` ## Step 3 Create constants Combine all lists and define constants ``` foreach(array_merge($array_add,$array_sub_simple,$array_sub_lower_one,$array_sub_double,$array_sub_all)as$key=>$value){ define($key,$value); } ``` ## Output In the example mutiply two valid versions of the number 8 ``` echo IIX * VIII; ``` [Answer] # Lua ``` local g={} setmetatable(_G,g) local romans = {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000} local larger = { -- Precalced, for faster computing. I = "VXLCDM", V = "XLCDM", X = "LCDM", L = "CDM", C = "DM", D = "M", M = " " -- A space will never be found, and it prevents the pattern matcher from erroring. } local storedRomans = {} function g:__index(key) if storedRomans[key] then return storedRomans[key] end if key:match"^[IVXLCDM]+$" then local n = 0 local i = 1 for s in key:gmatch"." do local N = romans[s] if key:find('['..larger[s]..']',i) then n = n - N else n = n + N end i = i + 1 end storedRomans[key] = n return n end end ``` This effects the metatable of the global table, giving it a new index function. When a global variable which only contains roman numerals is asked for, eg `XVII`, it parses it. Easy to test; ``` print(XVII) -- 42 print(VI) -- 6 print(III) -- 3 print(MMM) -- 3000 ``` [Try it online!](https://tio.run/nexus/lua#ZZJba8JAEIWfk18xLAUN1WAf@iL0oVgogUZKH0QQK2syiUvjJuyuvVD87XYmGy9FQZlzZjPz7YmHqs5kBeXD7z606LbopJPrCvur50EZhb5r6q3UFh7gN6Gfu0EY0GdG5b0v5@yOfP3CdldPWr8TT22jE6nvjPbdhkqaEg1vCIZDeDVIZob5AIraQCGto2ZWb5udU7qM2xGMImbzl8lTKs5E4tJgLnGhmU2cJeOJk2I@cRTMJ0AwzCPYRmYIX6qqQOMnkayRuHaa8KTOQTloDPnaWXAbhEY6wtWwlS7b0OmC4gM0pjYt@/HK1tUG87dTtPuw2OnMqVpDOV6tlM7xu/@BP1EYqOLf6QW5S16lidWg29Gyq34YoM7bR0mNWxbxvkh8YMvbG3Ec4Gk0IYxOSvHrIcXpW1C6nVH6IbGAvOaQ/NEpHfX/j4Vdst1tLOgC/d6iF8f@3VI3jnvL3kBFx81BwFs1DGHKCiuLF@5t5/ItaCp5ijym8tZ1IvTUORDtA6DvoaHgXX8@S5Io9PXsVCVnM03T6PAH "Lua – TIO Nexus") [Answer] # Excel VBA, ~~204~~ 183 bytes A subroutine which takes no input, and when run, creates `Enum R`, which contains all of the Roman Numeral values. These values may be used directly, without referencing the Enum. Requires programmatic access to the VBE Project module. Enum hold values from 1 to 3999. *Note:* Terminal `"`s on lines 7, 8, and 13 are included for syntax highlighting only, and do not contribute to the bytecount ``` Global c Sub a(s) c.AddFromString s End Sub Sub b Set c=ThisWorkbook.VBProject.VBComponents.Add(1).CodeModule a"Enum R" a"I=1" For n=2To 3999 [A1]=n a[Roman(A1)] Next a"End Enum" End Sub ``` ## Ungolfed and Explained ``` Global C As CodeModule '' dim object to hold module to be added Private Sub pWriteLine(ByRef s As String) '' define a helper sub that writes a single C.AddFromString s '' line containing string `s` to global End Sub '' codemodule `c` Public Sub InitializeRomanNumerals() Set C = ThisWorkbook.VBProject.VBComponents.Add(1).CodeModule '' Create Module Call pWriteLine("Public Enum RomanNumeral") '' Write Enum Header Call pWriteLine("I = 1") '' Write First line, and set value to 1 For n = 2 To 3999 '' iter from 2 to 3999 [A1] = n '' push value to A1 Call pWriteLine([Roman(A1)]) '' write a line containing roman numeral value of A1, '' enum value will auto increment to be 1 over '' that of the line above Next n '' Call pWriteLine("End Enum") '' Write Enum Footer End Sub ``` [Answer] # JavaScript, 167 bytes ``` f=n=>n<4e3?"M1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1".replace(/(\D+)(\d+)/g,(_,r,d)=>r.repeat(n/d,n%=d)):`(${f(n/1e3)})`+f(n%1e3) for(i=0;i<4e3;i++)this[f(i)]=i ``` The Decimal to Roman function comes from [this answer](https://codegolf.stackexchange.com/a/77961/98630) (thanks [Neil](https://codegolf.stackexchange.com/users/17602/neil) !) Then it will add all of them to the root object (`this`). Very optimized, and definitively a good practice I know ! Just paste it to the browser's console to try it out ! ]
[Question] [ It's become somewhat of a tradition in PPCG that some users temporarily change their names by an anagram (a new name formed by reordering the letters of the old). Sometimes it gets difficult to find out who is who. I could use a program or function to tell if two phrases are anagrams of each other. ### The challenge The program or function should take two strings and produce a truthy result if they are anagrams of each other, and falsy otherwise. ### Rules * Input will only contain letters (ASCII 65 to 90 and 97 to 122), digits (ASCII 48 to 57) or space (ASCII 32). * The anagram relation is independendent of case. So "Arm" and "RAM" are anagrams. * Spaces don't count either. So "keyboard" and "Barked Yo" are anagrams * All builtins allowed * Input format is flexible (two strings, an array of two strings, a string containing both phrases with a suitable separator ...) Code golf. Fewest bytes wins. ### Test cases Truthy: ``` Lynn, Nyl N Digital Trauma, Tau Digital Arm Sp3000, P S 3000 Manage Trash So, Those anagrams ``` Falsy ``` Calvins Hobbies, Helka Homba Android, rains odd In between days, bayed entwine Code golf, cod elf got ``` [Answer] # Retina, 25 ``` i+`(\w)(.*,.*)\1 $2 ^\W*$ ``` [Try it Online!](http://retina.tryitonline.net/#code=aStgKFx3KSguKiwuKilcMQokMgpeXFcqJA&input=RGlnaXRhbCBUcmF1bWEsIFRhdSBEaWdpdGFsIEFybQ) Additionally, you can run a modified [multi-line version](http://retina.tryitonline.net/#code=aStgKFx3KSguKiwuKilcMQokMgptYF5bLCBdKiQKcGFzcwptYF5bXsK2LV0qLFtewrYtXSokCmZhaWw&input=THlubiwgTnlsIE4KRGlnaXRhbCBUcmF1bWEsIFRhdSBEaWdpdGFsIEFybQpTcDMwMDAsIFAgUyAzMDAwCk1hbmFnZSBUcmFzaCBTbywgVGhvc2UgYW5hZ3JhbXMKLS0tLS0KQ2FsdmlucyBIb2JiaWVzLCBIZWxrYSBIb21iYQpBbmRyb2lkLCByYWlucyBvZGQKSW4gYmV0d2VlbiBkYXlzLCBiYXllZCBlbnR3aW5lCkNvZGUgZ29sZiwgY29kIGVsZiBnb3Q). Delete letters from before the comma along with their matches after the comma. If we have no letters left then it was an anagram. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes Code: ``` lvyð-{}Q ``` Explanation: ``` l # Lowercase the strings vy } # Map over the list, for each... ð- # remove spaces { # and sort Q # Check equality ``` [Try it online!](http://05ab1e.tryitonline.net/#code=bHZ5w7Ate31R&input=WyJMdWlzIE1lbmRvIiwgIkRvbiBNdWVzbGkiXQ) [Answer] # Pyth, ~~11~~ 10 bytes Thanks to @FryAmTheEggman for teaching me the power of `;`! ``` qFmSr-d;0Q ``` [Try it here!](http://pyth.herokuapp.com/?code=qFmSr-d%3B0Q&input=%5B%22Code+golf%22%2C%22cod+elf+got%22%5D&test_suite=1&test_suite_input=%5B%22Lynn%22%2C%22Nyl+N%22%5D%0A%5B%22Digital+Trauma%22%2C%22Tau+Digital+Arm%22%5D%0A%5B%22Sp3000%22%2C%22P+S+3000%22%5D%0A%5B%22Manage+Trash+So%22%2C%22Those+anagrams%22%5D%0A%5B%22Calvin%27s+Hobbies%22%2C%22Helka+Homba%22%5D%0A%5B%22Android%22%2C%22rains+odd%22%5D%0A%5B%22In+between+days%22%2C%22bayed+entwine%22%5D%0A%5B%22Code+golf%22%2C%22cod+elf+got%22%5D&debug=0) Takes a list of two strings as input. ## Explanation ``` qFmSr-d;0Q # Q = input m Q # map Q with d as lambda variable -d; # filter spaces out of the string r 0 # convert to lowercase S # sort all characters in string qF # Unfold resulting list and check for equality ``` [Answer] # Python 2, ~~63~~ 61 bytes ``` lambda*l:len({`sorted(s.lower())`[2::5].strip()for s in l})<2 ``` An anonymous function that, in fact, takes *n* arguments and determines if all *n* of them are mutual palindromes! `f("Lynn", "Nyl N")` returns `True`. This set comprehension trick is by xnor. It saved two bytes, but the old approach looked very neat: ``` exec"a=`sorted(input().lower())`[2::5].strip();a"*2;print a==aa ``` [Answer] # Jelly, 12 bytes ``` ḟ€⁶O&95Ṣ€QLḂ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bif4oKs4oG2TyY5NeG5ouKCrFFM4biC&input=&args=Ik1hbmFnZSBUcmFzaCBTbyIsICJUaG9zZSBhbmFncmFtcyI) ### How it works ``` ḟ€⁶O&95Ṣ€QLḂ Main link. Input: A (list of strings) ⁶ Yield ' '. ḟ€ Filter it from each string. O Apply ordinal to all characters. &95 Take bitwise AND with 95 to make the ordinals case-insensitive. Ṣ€ Sort each list of ordinals. Q Deduplicate the list. L Get the length. Ḃ Compute the length's parity (1 -> 1, 2 -> 0). ``` ## Alternate version (9 bytes) Jelly's uppercase atom had a bug, and Jelly still had no built-in to test lists for equality... ``` ḟ⁶ŒuṢµ€⁼/ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bif4oG2xZJs4bmiwrXigqzigbwv&input=&args=Ik1hbmFnZSBUcmFzaCBTbyIsICJUaG9zZSBhbmFncmFtcyI) ### How it works ``` ḟ⁶ŒuṢµ€⁼/ Main link. Input: A (list of strings) µ€ Map the chain to the left over A. ⁶ Yield ' '. ḟ Filter it from the string. Œu Cast to uppercase. Ṣ Sort. ⁼/ Reduce by equality. ``` [Answer] # CJam, 11 ~~12~~ ~~14~~ bytes *3 ~~2~~ bytes removed thanks to @FryAmTheEggman* ``` {lelS-$}2*= ``` [**Try it online!**](http://cjam.tryitonline.net/#code=e2xlbFMtJH0yKj0&input=QW5kcm9pZApyYWlucyBvZGQ) ``` { }2* e# do this twice l e# read line as a string el e# make lowercase S- e# remove spaces from string $ e# sort = e# compare strings ``` [Answer] # Javascript, ~~69~~ ~~61~~ ~~60~~ 59 bytes 1 byte off thanks [@ӍѲꝆΛҐӍΛПҒЦꝆ](https://codegolf.stackexchange.com/users/41247/%D3%8D%D1%B2%EA%9D%86%CE%9B%D2%90%D3%8D%CE%9B%D0%9F%D2%92%D0%A6%EA%9D%86). 1 byte off with currying ([pointed out](https://codegolf.meta.stackexchange.com/a/8427/48943) by [@apsillers](https://codegolf.stackexchange.com/users/7796/apsillers)) ``` n=>m=>(G=s=>[]+s.toLowerCase().split(/ */).sort())(n)==G(m) ``` ``` f=n=>m=> (G=s=>[]+s.toLowerCase() .split(/ */) .sort() )(n)==G(m) F=(n,m)=>document.body.innerHTML+=`<pre>f('${n}')('${m}') -> ${f(n)(m)}</pre>` F('Luis Mendo','Don Muesli') F('Calvins Hobbies','Helka Homba') F('Android','rains odd') F('In between days','bayed entwine') F('Code golf','cod elf got') F('Lynn','Nyl N') F('Digital Trauma','Tau Digital Arm') F('Sp3000','P S 3000') F('Manage Trash So','Those anagrams') ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 11 bytes ``` 2:"jkXvS]X= ``` *EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.* [**Try it online!**](http://matl.tryitonline.net/#code=MjoiamtYelNdWD0&input=TWFuYWdlIFRyYXNoIFNvClRob3NlIGFuYWdyYW1z) ``` 2:" ] % do this twice j % read input line as a string k % convert to lowercase Xv % remove spaces S % sort X= % are they equal? ``` [Answer] ## Seriously, ~~11~~ 9 bytes ``` 2`,ùSô`n= ``` [Try It Online!](http://seriously.tryitonline.net/#code=MmAsw7lTw7Rgbj0&input=) Everyone seems to be using the same algorithm. Here it is yet again. ``` 2` `n Do it twice , Read a string ù Make it lowercase S Sort ô Strip spaces. = Check equality. ``` Edit: realized sorting does work correctly on strings, and sorts spaces to the front so strip() will work. [Answer] # C, 165 bytes ``` #define d(x) int x(char*a,char*b){ d(q)return*a&224-*b&224;} #define n(x) for(qsort(x,strlen(x),1,(__compar_fn_t)q);*x<33;x++); d(s)n(a)n(b)return strcasecmp(a,b);} ``` Readable and in working context, ``` #include <stdlib.h> #include <string.h> #include <stdio.h> // start of comparison int q(char *a, char *b){ return ((*a)&0xdf)-((*b)&0xdf); // case-insensitive } int s(char *a, char *b){ for(qsort(a,strlen(a),1,(__compar_fn_t)q); *a<33; a++) /**/; for(qsort(b,strlen(b),1,(__compar_fn_t)q); *b<33; b++) /**/; return strcasecmp(a,b); } // end of comparison int main(int i, char **v){ printf("'%s' '%s'", v[1], v[2]); printf("=> %d\n", s(v[1], v[2])); // 0 if equalish return 0; } ``` [Answer] ## zsh, 85 bytes ``` [ $(for x in $@;{tr -d \ <<<$x|tr A-Z a-z|fold -1|sort|paste -sd x}|uniq|wc -l) = 1 ] ``` Input as command line arguments, output as return code. The `for` syntax makes this Bash-incompatible. ``` [ # test... $(for x in $@; # map over arguments {tr -d \ <<<$x # remove spaces |tr A-Z a-z # lowercase |fold -1 # put each character on its own line |sort # sort lines |paste -sd x # remove all newlines except last }|uniq # take only unique lines |wc -l # how many lines remain? ) = 1 ] # if only 1 line left, it must have been an anagram ``` [Answer] # Japt, 12 bytes ``` N®v ¬n ¬xÃä¥ ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=Tq52IKxuIKx4w+Sl&input=Ik1hbmFnZSBUcmFzaCBTbyIgIlRob3NlIEFuYWdyYW1zIg==) ### How it works ``` // Implicit: N = array of input strings N® à // Take N, and map each item Z to: v ¬n // Take Z.toLowerCase(), split into chars, and sort. ¬x // Join and trim off whitespace. ä¥ // Reduce each pair of items (that's exactly one pair) X and Y to X == Y. ``` [Answer] # Bash + GNU utilities, 51 ``` f()(fold -1<<<${@^^}|sort) f $1|diff -qBw - <(f $2) ``` * Define a function `f()` which: + `${@^^}` converts all parameters to upper case + `fold -1` splits chars - one per line + `sort`s lines * call `diff` with `-q` to suppress full diff output and `-Bw` to ignore whitespace changes [Answer] # GNU Sed, 33 Score includes +2 for `-rn` options to sed. This is almost a direct port of @FryAmTheEggman's [Retina answer](https://codegolf.stackexchange.com/a/74183/11259): ``` : s/(\w)(.*,.*)\1/\2/i t /\w/Q1 ``` [Ideone.](https://ideone.com/ANy32v) [Answer] ## Perl, ~~34~~ 33 + 1 = 34 bytes ``` s/(.)(.*,.*)\1/$2/i?redo:say!/\w/ ``` Requires the `-n` flag and the free `-M5.010`|`-E`: ``` $ perl -M5.010 -ne's/(.)(.*,.*)\1/$2/i?redo:say!/\w/' <<< 'hello, lloeh' 1 ``` How it works: ``` # '-n' make a implicit while loop around the code s/(.)(.*,.*)\1/$2/i # Remove a letter that occurs on both sides of the comma. ? redo: # Redo is a glorified goto statement that goes to the top of the while loop say!/\w/ # Check to see if any letter is left ``` Thanks to [msh210](https://codegolf.stackexchange.com/users/1976/msh210) for suggesting using ternary operators to save one byte [Answer] # [Zsh](https://zsh.sourceforge.io/), 51 bytes [Try it Online!](https://tio.run/##NY3NTsMwEITveYpVyME@oCSABIoCqIJDkaBCah@gm9j5AcdGcUoUqjy72fz04vHON7P7ZytXMH52JeNpmgZn9pUknMRY0jhRYxjC6M0oYCUEMQ9nveGjGz3USGUPQOaVIUg@DfgYsD6H65xqx2Kxj5zAcuGKB4zhU/x8HyUPd5yP3rwI/PdBax/83aBg5y/Wa13WHSo4tHhqkOABT3AxN22zxvY/t1EUEf6EPczfxf@gt5RT21awN1O/MlbCZLfY2DX2guq31ha2JstqaSm2leobaW4yXDMbLVpTC2ItTlkjxEreNGSy66XUIHCY2hkOUoDUXV9reblhhITSqIJ4boiqgsbOd879Aw) ``` g()<<<${(j::)${(os::)1:l}// } <<<${$(g $1)/$(g $2)} ``` Similar to [my other anagram solution](https://codegolf.stackexchange.com/a/254780/15940), again using Zsh's gnarly [parameter expansion](https://zsh.sourceforge.io/Doc/Release/Expansion.html#Parameter-Expansion). Added a few bits to lowercase everything and parse out spaces. [Answer] # [Arturo](https://arturo-lang.io), 33 bytes ``` $=>[=do map&=>[tally--lower&` `]] ``` [Try it!](http://arturo-lang.io/playground?RiBHsL) Takes input as a list of two strings. ``` $=>[ ; a function where input is assigned to & map&=>[ ; map over input, assign current elt to & lower& ; lowercase current elt -- _ ` ` ; remove spaces tally ; create dictionary of occurrences ] ; end map do ; put the pair on the stack = ; are they equal? ] ; end function ``` [Answer] # [Cyborg Hal](https://github.com/JCumin/Brachylog), ~~9~~ 8 bytes ``` {ṇ₁cḷo}ᵛ ``` [Try it online!](https://tio.run/##NYwxTsQwEEWvMnK9QhGcYAXFIsEKKdtFKcbxJLFwbGQ7RNGyBSmAO9DR0NIg4AycIrlIsLOim//f@8MtFnWvTHU676enj2kYppd35m1L7OQhniUqR@zw@9bN@/HneRoei/H7yxzGz9d5zjJ21WvNVmzbK9iyfJWxC1lJjwp2FtsGA9phC//l2jaLlN6dJUkS4A2ksJyxvUaNFcWlqyE1cVsbRxBri41bpHNU91I72BjOJbkgbUjdYsgNx8VYa2GNFIFYjKYRYukvNXDyHZEGgX1ccuxJAGnfSU3H70YQVEaVgRYmMFWG6Fme/wE "Brachylog – Try It Online") Truthy/falsy output is achieved through predicate success/failure, this being Brachylog. Previously saved a byte using `cṇ₁cḷḍ` instead of `{ṇ₁cḷ}ᵐ` under the assumption that the two input strings would be the same length minus whitespace, but I realized that it would succeed where it should fail on `Ah Hass, haha`. ``` { }ᵛ For both strings in the input, ṇ₁ split on spaces, c concatenate, ḷ lowercase, o and sort. ᵛ Are the results the same? ``` [Answer] # PHP, ~~109~~ 94 bytes ``` function f($x){return str_split((trim($x));}function g($x,$y){return array_diff(f($x),f($y));} ``` Blech, the two `function/return`s are killing me here. Returns the difference between two `string` inputs as an `array` of characters. PHP considers `[]` falsy, satisfying the `return` requirements. [Answer] ## [Pyke](https://github.com/muddyfish/PYKE) (commit 30, noncompetitive), 9 bytes ``` Fl1dk:S)q ``` Explanation: ``` F ) - for _ in eval_or_not(input()) l1 - ^.lower() dk: - ^.replace(" ", "") S - sorted(^) q - ^==^ ``` [Answer] # Mathematica, ~~77~~ 76 bytes ``` StringMatchQ[##,IgnoreCase->1>0]&@@(""<>Sort[Characters@#/." "->""]&/@{##})& ``` The first part is actually one of my answers to another question! [Answer] # Pike, ~~54~~ ~~112~~ ~~109~~ ~~109~~ 96 bytes ``` #define a(x) sort((array)replace(lower_case(x)," ","")) int s(mixed i){return a(i[0])==a(i[1]);} ``` `mixed` happens to be shorter than `array(string)`. `s` returns `1` if its arguments are anagrams. [Answer] ## APL, 31 chars ``` {≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵} ``` To be used so: ``` {≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}'Sp3000' 'P S 3000' 1 ``` In English: * `{ ... }¨⍵`: for each of the two elements of the argument * `x←('.'⎕R'\u0')⍵~' '`: transform to uppercase (using a regex...) the string without the spaces and assign the temporary result to `x` * `x[⍋x]`: sort x * `≡/`: compare the two results of the sorting: if they match, return 1. [Answer] # Java, 218 Bytes *First time I've ever written Java...* Golfed: ``` import java.util.Arrays;boolean M(String a,String b){char[]A=a.toUpperCase().replace(" ","").toCharArray();char[]B=b.toUpperCase().replace(" ","").toCharArray();Arrays.sort(A);Arrays.sort(B);return Arrays.equals(A,B);} ``` Ungolfed: ``` import java.util.Arrays; public class ManageTrashSo { public boolean M(String a, String b) { char[] A = a.toUpperCase().replace(" ", "").toCharArray(); char[] B = b.toUpperCase().replace(" ", "").toCharArray(); Arrays.sort(A); Arrays.sort(B); return Arrays.equals(A, B); } } ``` Testing: ``` ManageTrashSo manageTrashSo = new ManageTrashSo(); //True System.out.println(manageTrashSo.M("Lynn", "Nyl N")); System.out.println(manageTrashSo.M("Digital Trauma", "Tau Digital Arm")); //False System.out.println(manageTrashSo.M("Android", "rains odd")); System.out.println(manageTrashSo.M("In between days", "bayed entwine")); ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), 10 bytes ``` v á øVrS v ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=diDhIPhWclMgdg==&input=Ikx5bm4iLCJOeWwgTiI=) [Answer] # [lyxaV](https://github.com/Vyxal/Vyxal), 5 bytes ``` ɽȧvs≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvcindnPiiYgiLCIiLCJbXCJWeXhhbFwiLCBcImx5eGFWXCJdIl0=) Or [try a testsuite](https://vyxal.pythonanywhere.com/#WyJBIiwiXCIiLCLJvcindnPiiYgiLCIiLCJMeW5uLCBOeWwgTlxuRGlnaXRhbCBUcmF1bWEsIFRhdSBEaWdpdGFsIEFybVxuU3AzMDAwLCBQIFMgMzAwMFxuTWFuYWdlIFRyYXNoIFNvLCBUaG9zZSBhbmFncmFtc1xua2V5Ym9hcmQsIEJhcmtlZCBZb1xuYXJtLCBSQU1cbkNhbHZpbnMgSG9iYmllcywgSGVsa2EgSG9tYmFcbkFuZHJvaWQsIHJhaW5zIG9kZFxuSW4gYmV0d2VlbiBkYXlzLCBiYXllZCBlbnR3aW5lXG5Db2RlIGdvbGYsIGNvZCBlbGYgZ290Il0=) to verify the test cases. Takes inputs as a list of strings. ## Explained ``` ɽȧvs≈ ɽ # Convert each string to lowercase ȧ # Remove whitespace from each string vs # Sort each string ≈ # Are they equal? ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Rw€Ṡạ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVJ3JUUyJTgyJUFDJUUxJUI5JUEwJUUxJUJBJUExJmZvb3Rlcj0maW5wdXQ9JTVCJTIyTHlubiUyMiUyQyUyMCUyMk55bCUyME4lMjIlNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwMSUwQSU1QiUyMkRpZ2l0YWwlMjBUcmF1bWElMjIlMkMlMjAlMjJUYXUlMjBEaWdpdGFsJTIwQXJtJTIyJTVEJTIwJTIwLSUzRSUyMDElMEElNUIlMjJTcDMwMDAlMjIlMkMlMjAlMjJQJTIwUyUyMDMwMDAlMjIlNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwMSUwQSU1QiUyMk1hbmFnZSUyMFRyYXNoJTIwU28lMjIlMkMlMjAlMjJUaG9zZSUyMGFuYWdyYW1zJTIyJTVEJTIwJTIwLSUzRSUyMDElMEElNUIlMjJDYWx2aW5zJTIwSG9iYmllcyUyMiUyQyUyMCUyMkhlbGthJTIwSG9tYmElMjIlNUQlMjAlMjAlMjAlMjAlMjAtJTNFJTIwMCUwQSU1QiUyMkFuZHJvaWQlMjIlMkMlMjAlMjJyYWlucyUyMG9kZCUyMiU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAwJTBBJTVCJTIySW4lMjBiZXR3ZWVuJTIwZGF5cyUyMiUyQyUyMCUyMmJheWVkJTIwZW50d2luZSUyMiU1RCUyMCUyMCUyMC0lM0UlMjAwJTBBJTVCJTIyQ29kZSUyMGdvbGYlMjIlMkMlMjAlMjJjb2QlMjBlbGYlMjBnb3QlMjIlNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwMCZmbGFncz1DZQ==) Input as a list of both strings. #### Explanation ``` Rw€Ṡạ # Implicit input R # Uppercase the input w # Remove all whitespace €Ṡ # Sort each string ạ # All equal? # Implicit output ``` [Answer] # Ruby, 50 bytes ``` def f;gets.upcase.chars.sort.join.strip;end p f==f ``` Writing `f=->{...}` and `f[]==f[]` is just as long. :( [Answer] ## PowerShell, 81 bytes ``` param([char[]]$a,[char[]]$b)-join($a-replace' '|sort)-eq-join($b-replace' '|sort) ``` A slight rewrite of [my answer](https://codegolf.stackexchange.com/a/54496/42963) on the linked Anagram challenge. Takes input as char-arrays, performs a `-replace` operation to remove spaces, `sort`s them (which sorts alphabetically, not by ASCII value), then `-join`s them back into a string. The `-eq` in PowerShell is by default case-insensitive, but here it must be performed on strings, as `[char]'a'` is not equal to `[char]'A'`, hence the reason for `-join`. [Answer] # Perl, 35 bytes Include +1 for `-p` Somewhat abusive since it depends on the program being given on the commandline. ``` perl -pe'<>=~s%\S%*_=s/$&//i?_:0%reg;$_=!//' ``` Then give the strings as 2 consecutive lines on STDIN A very abusive solution is 30 bytes: ``` perl -ne'<>=~s%\w%1/!s/$&//i%reg;1/!//' ``` This crashes if the strings are not anagrams and therefore gives a false exit code from the point of view of the shell. It also gives garbage on STDERR for that case. If the strings are anagrams the program is silent and gives a "true" exit code ]
[Question] [ Given N, output the Nth term of this infinite sequence: ``` -1 2 -2 1 -3 4 -4 3 -5 6 -6 5 -7 8 -8 7 -9 10 -10 9 -11 12 -12 11 ... etc. ``` N may be 0-indexed or 1-indexed as you desire. For example, if 0-indexed then inputs `0`, `1`, `2`, `3`, `4` should produce respective outputs `-1`, `2`, `-2`, `1`, `-3`. If 1-indexed then inputs `1`, `2`, `3`, `4`, `5` should produce respective outputs `-1`, `2`, `-2`, `1`, `-3`. To be clear, this sequence is generated by taking the sequence of positive integers repeated twice ``` 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 ... ``` and rearranging each pair of odd numbers to surround the even numbers just above it ``` 1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7 9 10 10 9 11 12 12 11 ... ``` and finally negating every other term, starting with the first ``` -1 2 -2 1 -3 4 -4 3 -5 6 -6 5 -7 8 -8 7 -9 10 -10 9 -11 12 -12 11 ... ``` **The shortest code in bytes wins.** [Answer] # [Python 2](https://docs.python.org/2/), 23 bytes ``` lambda n:~n/2+n%2*(n|2) ``` Odd inputs give roughly `n/2`, even ones roughly `-n/2`. So, I started with `-n/2+n%2*n` and tweaked from there. [Try it online!](https://tio.run/nexus/python2#BcFLCoAgFAXQca3iTkTtQ/BqJNRKmhiWBHULaRht3c6J45wPfy7Bg@5jJzWVVIav2LxdCcROJM@4GhmsK4s77XyglQS0E1QfNBQMG0RDa/MP "Python 2 – TIO Nexus") [Answer] # Mathematica, 29 bytes ``` ((#~GCD~4/. 4->-2)+#)/2(-1)^#& ``` Pure function taking a 1-indexed input. Other than the alternating signs `(-1)^#`, twice the sequence is close to the input, the differences being 1, 2, 1, -2 cyclically. It's nice that `#~GCD~4`, the greatest common divisor of the input and `4`, is 1, 2, 1, 4 cyclically; so we just manually replace `4->-2` and call it a day. I like this approach because it avoids most of the many-character Mathematica commands. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~24~~ 22 bytes ``` v**a*YaBA2|1+:--a//4*2 ``` Takes input, 1-indexed, as a command-line argument. [Try it online](https://tio.run/nexus/pip#@1@mpZWoFZno5GhUY6htpaubqK9vomX0//9/UwA "Pip – TIO Nexus") or [verify 1-20](https://tio.run/nexus/pip#q/5fpqWVqBWZ6ORoVGOobaWrm6ivb6Jl9L/WN0bHyOD/f91iAA). ### Explanation Observe that the sequence can be obtained by combining three other sequences, one zero-indexed and the others one-indexed: * Start with `0 0 0 0 2 2 2 2 4 4 4 4` = `a//4*2` (0-indexed); * Add `1 2 2 1 1 2 2 1 1 2 2 1` = `aBA2|1`, where `BA` is bitwise AND, and `|` is logical OR (1-indexed); * Multiply the sum by `-1 1 -1 1 -1 1 -1 1 -1 1 -1 1` = `(-1)**a` (1-indexed). If we start with `a` 1-indexed, we can compute the 1-indexed parts first (reading the expression left to right) and then decrement `a` for the 0-indexed part. Using the builtin variable `v=-1`, we get ``` v**a*((aBA2|1)+--a//4*2) ``` To shave two more bytes, we have to use some precedence-manipulation tricks. We can eliminate the inner parentheses by replacing `+` with `+:` (equivalent to `+=` in a lot of languages). Any compute-and-assign operator is of very low precedence, so `aBA2|1+:--a//4*2` is equivalent to `(aBA2|1)+:(--a//4*2)`. Pip will emit a warning about assigning to something that isn't a variable, but only if we have warnings enabled. The only thing that's lower precedence than `:` is `Y`, the yank operator.\* It assigns its operand's value to the `y` variable and passes it through unchanged; so we can eliminate the outer parentheses as well by yanking the value rather than parenthesizing it: `YaBA2|1+:--a//4*2`. \* `P`rint and `O`utput have the same precedence as `Y`ank, but aren't useful here. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` H^Ḃ~N⁸¡ ``` This uses the algorithm from [my Python answer](https://codegolf.stackexchange.com/a/113347/12012), which was improved significantly by [@GB](https://codegolf.stackexchange.com/users/18535/g-b). [Try it online!](https://tio.run/nexus/jelly#AR4A4f//SF7huIJ@TuKBuMKh/zI04bi2wrXFvMOH4oKsR/8 "Jelly – TIO Nexus") ### How it works ``` H^Ḃ~N⁸¡ Main link. Argument: n H Halve; yield n/2. This returns a float, but ^ will cast it to int. Ḃ Bit; yield n%2. ^ Apply bitwise XOR to both results. ~ Take the bitwise NOT. N⁸¡ Negate the result n times. ``` [Answer] # Java 8, 19 bytes ``` n->~(n/2)+n%2*(n|2) ``` # Java 7, ~~47~~ 37 bytes ``` int c(int n){return~(n/2)+n%2*(n|2);} ``` First time Java (8) actually competes and is shorter than some other answers. Still can't beat the actual golfing languages like Jelly and alike, though (duhuh.. what a suprise.. >.> ;P) 0-indexed Port from [*@Xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/113355/52210). -10 bytes thanks to *@G.B.* [Try it here.](https://tio.run/nexus/java-openjdk#LY7BDoIwEETvfMWExKS1BpEr@AmeOBoPFdE0gYW0i4nB@uvYEg6zO4c3k1maTjuHy5wAjjWbBoYYjYiX5Gxbniz9BB0LqWhX7AV9C1n6JPDjdO8Cv8Xeg3mg14ZEzdbQ63qDlrEWeA527TM4Iy/Dq3DKo1FqI4D647jts2HibAxxFmGChEJ6QCrLFfJJlF@WPw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ ~~12~~ 11 bytes ``` Ḷ^1‘ż@N€Fị@ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx7Y4w0cNM47ucfB71LTG7eHubof/RiaHtgYd3XO4HSji/h8A "Jelly – TIO Nexus") ### How it works ``` Ḷ^1‘ż@N€Fị@ Main link. Argument: n Ḷ Unlength; yield [0, 1, 2, 3, ..., n-1]. ^1 Bitwise XOR 1; yield [1, 0, 3, 2, ..., n-1^1]. ‘ Increment; yield [2, 1, 4, 3, ..., (n-1^1)+1]. N€ Negate each; yield [-1, -2, -3, -4, ..., -n]. ż@ Zip with swapped arguments; yield [[-1, 2], [-2, 1], [-3, 4], [-4, 3], ..., [-n, (n-1^1)+1]]. F Flatten, yield [-1, 2, -2, 1, -3, 4, -4, 3, ..., -n, (n-1^1)+1]. ị@ At-index with swapped arguments; select the item at index n. ``` [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), ~~31~~ ~~25~~ 22 bytes ``` nx=x2÷1x4%{+$-1x^*}#-? ``` ## Explained ``` nx= # Convert the input to a number, set x to it. x2÷ # Floor divide x by 2. 1 # Place a 1 on the stack. x4%{ }#-? # If x%4 is 0, subtract 1 from x//2, otherwise... + # Add the 1 and the x together. $-1 # Push -1 x^ # To the power of x. * # Multiply x//2+1 by -1^x. (Invert if odd, do nothing if even) ``` [Try it online!](https://tio.run/nexus/rprogn-2#@59XYVthdHi7YYWJarW2iq5hRZxWrbKu/f///3V1U4E45b8FAA "RProgN 2 – TIO Nexus") [Answer] # Ruby, ~~26 23~~ 18 bytes ``` ->n{~n/2+n%2*n|=2} ``` 0-based -3 bytes stealing the -1^n idea from [Greg Martin](https://codegolf.stackexchange.com/a/113348/18535), [Dennis](https://codegolf.stackexchange.com/a/113347/18535) and maybe somebody else, then -5 bytes stealing the n|2 idea from [xnor](https://codegolf.stackexchange.com/a/113355/18535). [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~30~~ 28 bytes ``` :2%([:2/\4%2=tmo+][1+2/_])\# ``` [Try it online!](https://tio.run/nexus/stacked#MzRUqLNTqFZIVbBSSP1vZaSqEW1lpB9jompkW5Kbrx0bbahtpB8fqxmj/F8RqChGQVlHoVYhN7FAISWzuOA/AA "Stacked – TIO Nexus") Returns a function, which as allowed [per meta consensus.](https://codegolf.meta.stackexchange.com/a/11317/31957). Takes input from the top of the stack. Using the same approach as the [RProgN 2 answer](https://codegolf.stackexchange.com/a/113343/31957). --- Alternatively, 46 bytes. [Try it online!](https://tio.run/nexus/stacked#MzRUqLNTqFZIVbBSSP1fraihaRhtZWWorWNVlFqmE1MMJGN0Yoy0Y/O0HPTyFAx1lfMUjFRLcvO14mv/KwK1xSgo6yjUKuQmFiikZBYX/AcA "Stacked – TIO Nexus"): ``` {!()1[::1+,:rev,\srev\,\2+]n*@.n 1-#n 2%tmo*_} ``` This one generates the range then selects and negates the member as appropriate. [Answer] # [Python 2](https://docs.python.org/2/), ~~44~~ ~~33~~ 27 bytes ``` lambda n:(-1)**n*~(n/2^n%2) ``` *Thanks to @GB for golfing off 6 bytes!* [Try it online!](https://tio.run/nexus/python2#BcFBCoMwEAXQdT3F3wzOBKV07EqwJylCSkwR9FeCa6@evpcx4V23uH9SBEftHxYCw6W8@0xxq/lXQKxEifwu6k8bm9tRVp5oxRP6F2RILQTKDllpVv8 "Python 2 – TIO Nexus") [Answer] # 05AB1E, 8 bytes ``` 2‰`^±¹F( ``` [**Try it online**](https://tio.run/nexus/05ab1e#@2/0qGFDQtyhjYd2umn8/28CAA) **Explanation** ``` 2‰ divmod by 2 ` flatten list ^ XOR ± NOT ¹F( Push 1st argument, loop N times, negate ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` |2×Ḃ+H~$ ``` [Try it online!](https://tio.run/nexus/jelly#@19jdHj6wx1N2h51Kv///zcyBgA "Jelly – TIO Nexus") *-1 thanks to [Dennis](/users/12012). Duh float conversions.* Uses @xnor's Python 2 approach. **EDIT**: [>\_>](/a/113373/41024) [Answer] ## [CJam](https://sourceforge.net/p/cjam), 16 bytes ``` {_(_1&)^2/)W@#*} ``` 1-based input. [Try it online!](https://tio.run/nexus/cjam#MzKo1vxfHa8Rb6imGWekrxnuoKxV@78uPzi/Vv8/AA "CJam – TIO Nexus") ### Explanation Here is a breakdown of the code with the values on the stack for each input from `1` to `4`. The first few commands only affect the two least significant bits of `n-1` so after `4`, this stuff just repeats cyclically, with the results incremented by 2, due to the halving. ``` Cmd Stack: [1] [2] [3] [4] _ Duplicate. [1 1] [2 2] [3 3] [4 4] ( Decrement. [1 0] [2 1] [3 2] [4 3] _ Duplicate. [1 0 0] [2 1 1] [3 2 2] [4 3 3] 1& AND 1. [1 0 0] [2 1 1] [3 2 0] [4 3 1] ) Increment. [1 0 1] [2 1 2] [3 2 1] [4 3 2] ^ XOR. [1 1] [2 3] [3 3] [4 1] 2/ Halve. [1 0] [2 1] [3 1] [4 0] ) Increment. [1 1] [2 2] [3 2] [4 1] W Push -1. [1 1 -1] [2 2 -1] [3 2 -1] [4 1 -1] @ Rotate. [1 -1 1] [2 -1 2] [2 -1 3] [1 -1 4] # -1^n. [1 -1] [2 1] [2 -1] [1 1] * Multiply. [-1] [2] [-2] [1] ``` [Answer] # [Perl 6](https://perl6.org), ~~55 27 24~~ 22 bytes ``` {(-1,2,-2,1,{|($^a,$^b,$^c,$^d Z+ -2,2,-2,2)}...*)[$_]} ``` (Inspired by the Haskell `zipWith` answer) [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X62ha6hjpKNrpGOoU12joRKXqKMSlwTEyUCcohClrQCUAssbadbq6elpaUarxMfW/i8oLVFIyVdIyy9SiDMyUdC1U4jJzAMJViuATNZQAPM0FWr/AwA "Perl 6 – TIO Nexus") ``` {+^($_ div 2)+$_%2*($_+|2)} ``` (Inspired by several answers) [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X60dp6ESr5CSWaZgpKmtEq9qpAXka9cYadb@LygtUUjJV0jLL1KIMzJR0LVTiMnMAwlWK4B0ayiAeZoKtf8B "Perl 6 – TIO Nexus") ``` {+^($_+>1)+$_%2*($_+|2)} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X60dp6ESr21nqKmtEq9qpAXi1Bhp1v4vKC1RSMlXSMsvUogzMlHQtVOIycwDCVYrgLRqKIB5mgq1/wE "Perl 6 – TIO Nexus") ``` {+^$_+>1+$_%2*($_+|2)} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X60dpxKvbWeorRKvaqSlAWTXGGnW/i8oLVFIyVdIyy9SiDMyUdC1U4jJzAMJViuANGoogHmaCrX/AQ "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 +^ # numeric binary invert the following $_ +> 1 # numeric bit shift right by one + $_ % 2 # the input modulo 2 * ($_ +| 2) # numeric binary inclusive or 2 } ``` (All are 0 based) [Answer] # [Haskell](https://www.haskell.org/), ~~37~~ 36 bytes ``` (([1,3..]>>= \x->[-x,x+1,-x-1,x])!!) ``` [Try it online!](https://tio.run/nexus/haskell#@59mq6ERbahjrKcXa2dnqxBToWsXrVuhU6FtqKNboWuoUxGrqaio@T83MTNPwVahKDUxxSdPAaSyoCgzr0RBTyHtvzEA "Haskell – TIO Nexus") This is an anonymous function which takes one number `n` as argument and returns 0-indexed the `n`th element of the sequence. [Answer] # Haskell, 56 bytes ``` f n=concat(iterate(zipWith(+)[-2,2,-2,2])[-1,2,-2,1])!!n ``` 0-indexed [Answer] # Perl 5 47 + 1 (for flag) = 48 Bytes ``` print(((sin$_%4>.5)+1+2*int$_/4)*($_%4&1?1:-1)) ``` ### Old Submission 82 Bytes ``` @f=(sub{-$_[0]},sub{$_[0]+1},sub{-$_[0]-1},sub{$_[0]});print$f[$_%4](1+2*int$_/4) ``` Run like so: ``` perl -n <name of file storing script> <<< n ``` [Answer] # JavaScript (ES7), 28 bytes ``` n=>(n+2>>2)*2*(-1)**n-!(n&2) ``` 1-indexed. I haven't looked at any other answers yet so I don't know if this is the best algorithm, but I suspect not. [Answer] # JavaScript, ~~28~~ 22 bytes Thanks @ETHproductions for golfing off 6 bytes ``` x=>x%2?~x>>1:x%4+x/2-1 ``` [Try it online!](https://tio.run/nexus/javascript-node#S7P9n2ZbYWtXoWpkX1dhZ2doVaFqol2hb6Rr@D/PNtpQx0jHWMdEx1THTMdcx0LHUsfQIJYrOT@vOD8nVS8nP10jTy83sUAjTVPzPwA "JavaScript (Node.js) – TIO Nexus") [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 98 bytes ``` ?sa0sb1sq[lq1+dsqla!<i3Q]sf[lb1-lfx]su[lblfx]sx[lb1+dsblfx]sj[lqdd4%d0=u1=j2%1=xljxlfx]dsix_1la^*p ``` Gosh, this is the longest answer here, mainly because I went the path of generating the absolute value of each element of the sequence one by one based on the following recursive formula: [![enter image description here](https://i.stack.imgur.com/X1g8j.png)](https://i.stack.imgur.com/X1g8j.png) then outputting `(-1)^n * a_n`, rather than directly computing the `n`'th element. Anyways, this is `1`-indexed. [Try it online!](https://tio.run/nexus/dc#@29fnGhQnGRYXBidU2ionVJcmJOoaJNpHBhbnBadk2Som5NWEVtcCmSCGRUgMaAqCC8LqCclxUQ1xcC21NA2y0jV0LYiJ6sCJJdSnFkRb5iTGKdV8P@/yde8fN3kxOSMVAA "dc – TIO Nexus") [Answer] # R, 38 bytes ``` function(n)floor(n/2+1-2*!n%%4)*(-1)^n ``` Explanation ``` floor(n/2+1) -> 1 2 2 3 3 4 4 5... floor(n/2+1-2*!n%%4) -> 1 2 2 1 3 4 4 3... (subtract 2 where n%%4 == 0) floor(n/2+1-2*!n%%4)*(-1)^n -> -1 2 -2 1 -3 4 -4 3... (multiply odd n by -1) ``` [Answer] # TI-Basic (TI-84 Plus CE), 31 bytes ``` .5(Ans+1+remainder(Ans+1,2)-4not(remainder(Ans,4)))i^(2Ans ``` TI-Basic is a tokenized language and each token used here is one byte, except `remainder(`, which is two. This uses the 1-indexed version. Explanation: There is a pattern that repeats every four numbers. In the 1-indexed version, it is: -(x+1)/2, (x+1)/2, -(x+1)/2, (x-1)/2 for the input value x. This can be represented as a piecewise-defined function. f(x) = -(x+1)/2 if x ≡ 1 mod 4; (x+1)/2 if x ≡ 2 mod 4; -(x+1)/2 if x ≡ 3 mod 4; (x-1)/2 if x ≡ 0 mod 4 Because the "x ≡ 1 mod 4" and "x ≡ 3 mod 4" parts are the same, we can combine them into "x ≡ 1 mod 2". Now are piecewise function is: f(x) = -(x+1)/2 if x ≡ 1 mod 2; (x+2)/2 if x ≡ 2 mod 4; (x-2)/2 if x ≡ 0 mod 4 This is where I start breaking it into actual commands. Since the value is positive for even indexes and negative for odd ones, we can use (-1)^x. However, in TI-Basic `i^(2X` (5 bytes) is shorter than `(-1)^Ans` (6 bytes). Note that parentheses are required due to order of operations. Now that we have the way to negate the odd inputs out of the way, we move on to the mods (adding the negating back on later). I made the case of an odd input the default, so we start with `.5(Ans+1)`. To fix the case of even input, just add one to the number in the parentheses, but only when x ≡ 0 mod 2. This could be represented as `.5(Ans+1+remainder(Ans+1,2))` or `.5(Ans+1+not(remainder(Ans,2)))`, but they have the same byte count, so it doesn't matter which. To fix the case of multiple-of-4 input, we need to subtract 3 from the number in the parentheses, but also another 1 because all multiples of 4 are even, which would add one from our previous step, so we now have `.5(Ans+1+remainder(Ans+1,2)-4not(remainder(Ans,4)))`. Now, just tack on the sign-determining part to the end to get the full program. [Answer] # Befunge 93, 25 bytes Zero-indexed ``` &4/2*1+&4%3%!!+&2%2*1-*.@ ``` [Try it Online!](https://tio.run/nexus/befunge#@69mom@kZaitZqJqrKqoqK1mpArk6mrpOfz/bwoA) The number is given by `((2(n / 4) + 1) + !!((n % 4) % 3)) * (2(n % 2) - 1)` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 53 bytes ``` b=1:{[b,b+3|~b=a|_x(-(b%2)*2+1)*(q+(b%4>1)*-1)]]q=q+2 ``` Explanation: ``` b=1 Set b to a starting value of 1 QBIC would usually use the pre-initialised variable q, but that is already in use : Get an input number from the cmd-line, our term to find { Start an infinite loop [b,b+3| FOR-loop: this runs in groups of 4, incrementing its own bounds between runs ~b=a| If we've reached the term requested _x QUIT the program and print: (-(b%2)*2+1) The b%2 gives a 1 or a 0, times 2 (2,0), negged (-2,0) and plus one (-1,1) * That gives us the sign of our term. Now the value: (q+(b%4>1)*-1) This is q + 1 if the inner loop counter MOD 4 (1,2,3,0...) is 2 or 3. ] Close the IF that checks the term ] Close the FOR-loop q=q+2 And raise q by 2 for the next iteration of the DO-loop. ``` [Answer] # [Wise](https://github.com/Wheatwizard/Wise), 19 bytes ``` ::>!:><^^~![!-!-~]| ``` [Try it Online!](https://tio.run/nexus/wise#@29lZadoZWcTF1enGK2oq6hbF1vz//9/EwA) This is just a port of [@Dennis' Jelly answer](https://codegolf.stackexchange.com/a/113373/62574) to Wise. [Answer] ## Q, 52 bytes ``` {(1 rotate(,/){x,(-)x}each 1_((_)x%4)+til 3)x mod 4} ``` 0 indexed solution. 1. Gets the block number ie. which [-x x+1 -(x+1) x] block within the sequence contains the index. 2. Gets the index of the value within the block based on the index of the value within the whole sequence. 3. Creates the block. 4. Indexes into it via index derived in step 2. ]
[Question] [ ### ...but hey, no need to be strict. Given a non-empty array of strictly positive integers, determine if it is: 1. *Monotone strictly decreasing*. This means that each entry is strictly less than the previous one. 2. *Monotone non-increasing, but not strictly decreasing*. This means that each entry is less than or equal to the preceding, and the array does not fall in the above category. 3. *None of the above*. Note the following corner cases: * An array with a single number is monotone strictly decreasing (vacuously so). * An array with the same number repeated is monotone non-increasing, but not strictly decreasing. # Rules You may provide a program or a function Input can be taken in any reasonable format: array, list, string with numbers separated by spaces, ... You can choose any three consistent outputs for the three categories respectively. For example, outputs can be numbers `0`, `1`, `2`; or strings `1 1`, `1 0`, empty string. Shortest code in bytes wins # Test cases Monotone strictly decreasing: ``` 7 5 4 3 1 42 41 5 ``` Monotone non-increasing, but not strictly decreasing: ``` 27 19 19 10 3 6 4 2 2 2 9 9 9 9 ``` None of the above: ``` 1 2 3 2 10 9 8 7 12 4 6 4 4 2 ``` [Answer] # [Perl 6](https://perl6.org), 17 bytes ``` {[>](@_)+[>=] @_} ``` * Monotone strictly decreasing: `2` * Monotone non-increasing: `1` * Other: `0` ## Expanded: ``` { # bare block lambda with implicit parameter list 「@_」 [>]( @_ ) # reduce using 「&infix:« > »」 + [>=] @_ # reduce using 「&infix:« >= »」 } ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~10~~, 7 bytes ``` 0hdX>ZS ``` [Try it online!](http://matl.tryitonline.net/#code=MGhkWD5aUw&input=WzcgNV0) or [verify all test cases!](http://matl.tryitonline.net/#code=IkBnMGhkWD5aUw&input=e1s3IDUgNCAzIDFdIFs0MiA0MV0gWzVdIFsyNyAxOSAxOSAxMCAzXSBbNiA0IDIgMiAyXSBbOSA5IDkgOV0gWzEgMiAzIDJdIFsxMCA5IDggNyAxMl0gWzQgNiA0IDQgMl19) *3 bytes saved, thanks to @LuisMendo!* The outputs are * Strictly decreasing: -1 * Non-increasing: 0 * Other: 1 Explanation: ``` 0 % Push a '0' h % Join the 0 to the end of the input array. d % Get consecutive differences X> % Get the largest difference ZS % Get its sign % Implicitly print it ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10 9~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -Method found by [DrMcMoylex, go give some credit!](https://codegolf.stackexchange.com/a/101041/53748) ``` ;0IṠṀ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=OzBJ4bmg4bmA&input=&args=WzI3LCAxOSwgMTksIDEwLCAzXQ)** or [run all tests](http://jelly.tryitonline.net/#code=OzBJ4bmg4bmACsW8w4figqw&input=&args=W1s3LCA1LCA0LCAzLCAxXSwgWzQyLCA0MV0sIFs1XSwgWzI3LCAxOSwgMTksIDEwLCAzXSwgWzYsIDQsIDIsIDIsIDJdLCBbOSwgOSwgOSwgOV0sIFsxLCAyLCAzLCAyXSwgWzEwLCA5LCA4LCA3LCAxMl0sIFs0LCA2LCA0LCA0LCAyXV0) Returns :`-1`=monotone strictly decreasing; `0`=monotone non-increasing; `1`=other. ### How? ``` ;0IṠṀ - Main link: list ;0 - concatenate with a zero I - incremental differences Ṡ - sign Ṁ - maximum ``` [Answer] # Mathematica, 22 bytes ``` Sign@*Max@*Differences ``` Unnamed function taking a list of numbers as input. Returns `-1` if the list is strictly decreasing, `0` if it's nonincreasing but not strictly decreasing, and `1` if it's neither. Pretty simple algorithm: take the differences of consecutive pairs, take the largest one, and take the sign of that largest one. (I feel like there must exist some language in which this algorithm is 3 bytes....) Regarding an array with a single entry: `Differences` yields an empty list; `Max` of an empty list gives `-∞` (!); and `Sign[-∞]` evaluates to `-1` (!!). So it actually works on this corner case. Gotta love Mathematica sometimes. (Indeed, the function also correctly labels an empty list as strictly decreasing.) [Answer] ## Haskell, ~~40~~ ~~38~~ 37 bytes ``` foldl min GT.(zipWith compare<*>tail) ``` Returns * `GT` for Monotone strictly decreasing * `EQ` for Monotone non-increasing * `LT` else `compare` compares two numbers and returns `GT` (`EQ`, `LT`) if the first number is greater than (equal to, less than) the second number. `zipWith compare<*>tail` compares neighbor elements. `foldl min GT` reduces the list of the comparison results with the min function starting with GT (note: `LT` < `EQ` < `GT`). Edit: @xnor found ~~2~~ 3 bytes. Thanks! [Answer] ## Common Lisp, ~~43~~ 40 bytes ``` (defun f(x)`(,(apply'> x),(apply'>= x))) ``` This takes input as a Lisp list, and returns `(T T)`, `(NIL T)` and `(NIL NIL)` to distinguish the 3 categories. Here it is running on the provided test cases: ``` CL-USER> (mapcar #'f '((7 5 4 3 1) (42 41) (5) (27 19 19 10 3) (6 4 2 2 2) (9 9 9 9) (1 2 3 2) (10 9 8 7 12) (4 6 4 4 2))) ((T T) (T T) (T T) (NIL T) (NIL T) (NIL T) (NIL NIL) (NIL NIL) (NIL NIL)) ``` [Answer] ## Python 2, 30 bytes ``` lambda l:max(map(cmp,l[1:],l)) ``` `-1` for strictly decreasing, `0` for weakly decreasing, `+1` for non-decreasing Using `cmp` to compare consecutive elements, and takes the maximum. This is done by removing the first element of one copy of the list, then mapping `cmp` . For example, `l=[2,2,1]` gives ``` l[1:] 2 1 None l 2 2 1 cmp 0 -1 -1 ``` which has `max` 0 because an equality exists. The shorter list is automatically extended with `None`, which is less than all numbers and so harmless. This phantom element also insulates against taking the `min` of an empty list when the input has length 1. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 7 bytes ``` >,1|>=, ``` [Try it online!](http://brachylog.tryitonline.net/#code=PiwxfD49LA&input=WzI3OjE5OjE5OjEwOjNd&args=Wg) This prints `1` for strictly decreasing, `0` for non-increasing and `false.` otherwise. ### Explanation ``` (?)> Input is a strictly decreasing list ,1(.) Output = 1 | Or (?)>= Input is a non-increasing list ,(.) Output is a free variable; gets automatically labeled as an integer at the end of execution. Since its domain is [-inf, +inf], the first value it takes is 0 Or No other possibility, thus this main predicate is false. ``` ### Other 7 bytes solutions ``` >=!>,;1 Returns 0 for strictly decreasing, false. for non-increasing, 1 otherwise. >=!>,1| Returns 1 for strictly decreasing, false. for non-increasing, 0 otherwise. ``` [Answer] ## R, 44 bytes ``` d=diff(scan());c(any(!d)&all(d<=0),all(d<0)) ``` Reads input from stdin and prints the following depending on the input: **Output:** `[1] FALSE TRUE`: Monotone non-increasing `[1] TRUE FALSE`: Monotone strictly decreasing `[1] FALSE FALSE`: None of the above [Answer] ## JavaScript (ES6), 51 bytes ``` a=>a.some((e,i)=>e>a[i-1])+a.some((e,i)=>e>=a[i-1]) ``` Returns 0 for strict decreasing, 1 for non-increasing, 2 otherwise. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~5~~ 8 bytes Bug fixed by Emigna, thanks! It uses the same method as [DrMcMoylex](https://codegolf.stackexchange.com/questions/101036/lets-decrease-the-monotony/101041#101041)'s. ``` ®¸ì¥Z0.S ®¸ì Implicitly take input and appends -1 to it ¥ Yield deltas Z Take the largest delta 0.S Take its sign and implicitly display it ``` [Try it online!](http://05ab1e.tryitonline.net/#code=wq7CuMOswqVaMC5T&input=WzcsIDUsIDQsIDMsIDFd) Output is: ``` -1 if strictly decreasing sequence 0 if non-strictly decreasing sequence 1 otherwise ``` [Answer] # Ruby, 37 bytes ``` ->l{[d=l==l.sort.reverse,d&&l|[]==l]} ``` Output:`[true,true]`, `[true,false]` or `[false,false]` [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` maximum.(zipWith compare<*>(1/0:)) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexIjO3NFdPoyqzIDyzJEMhOT@3ILEo1UbLTsNQ38BKUxOoJDPPtqAoM69EJS3aWMdIxzj2/7/ktJzE9OL/uskFBQA "Haskell – Try It Online") Outputs `LT`,`EQ`,`GT` for strictly monotonic, non-increasing, and otherwise, respectively. Thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for pointing out that my previous version failed on singleton lists and suggesting this alternative. Takes the maximum of the sighn of the differences between adjacent pairs, prepending with `inf`. (`zipWith compare<*>(1/0:)` applied to `l` computes `compare l inf:l` elementwise). This is competitive with the existing Haskell answers and ekes out ahead by being pointfree and anonymous. [Answer] ## Mathematica, ~~15~~ 11 bytes ``` ##>0|##>=0& ``` This is a variadic function, taking all input integers as separate arguments. * Strictly decreasing: `True | True` * Non-increasing: `False | True` * Neither: `False | False` Note that `|` is not `Or` but `Alternatives`, which is part of pattern matching syntax, which explains why these expressions don't get evaluated to `True`, `True`, `False`, respectively. The code itself is mostly an application of [this tip](https://codegolf.stackexchange.com/a/47929/8478). For example `##>0` is `Greater[##, 0]` but then `##` expands to all the input values so we get something like `Greater[5, 3, 2, 0]`, which itself means `5>3>2>0`. [Answer] # [Racket](https://racket-lang.org/), 44 bytes ``` (λ(x)(map(λ(p)(apply p`(,@x 0)))`(,>,>=))) ``` Invoked: ``` (map (λ(x)(map(λ(p)(apply p`(,@x 0)))`(,>,>=))) '((7 5 4 3 1) (42 41) (5) (27 19 19 10 3) (6 4 2 2 2) (9 9 9 9) (1 2 3 2) (10 9 8 7 12) (4 6 4 4 2))) ``` Result: ``` '((#t #t) (#t #t) (#t #t) (#f #t) (#f #t) (#f #t) (#f #f) (#f #f) (#f #f)) ``` [Answer] # C++14, 85 bytes ``` int f(int x){return 3;}int f(int x,int y,auto...p){return((x>=y)+2*(x>y))&f(y,p...);} ``` Returns 3 (0b11) for strict decreasing, 1 (0b01) for non-increasing and 0 otherwise. Ungolfed: ``` int f(int x) {return 3;} int f(int x,int y,auto...p){ return ((x>=y)+2*(x>y)) & f(y,p...); } ``` I thought this was a perfect problem for C++17's folding expressions: ``` int g(auto...x){return(x>...)+(x>=...);} ``` Unfortunately it does not chain the relational operators but does ``` ((x1>x2)>x3)>x4)... ``` which is not was wanted. [Answer] # Python 2, ~~61~~ 74 bytes +13 bytes for the single number input ``` x=map(str,input()) print[2,eval(">".join(x))+eval(">=".join(x))][len(x)>1] ``` Requires input in bracket list form like `[3,2,1]`. Returns 2 for strict decreasing, 1 for non-increasing and 0 otherwise. Old solution: ``` print eval(">".join(x))+eval(">=".join(x)) ``` [Answer] # Python 3, 81 52 bytes (Thanks to [FryAmTheEggMan](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)) ``` e=sorted lambda a:(a==e(a)[::-1])+(e({*a})[::-1]==a) ``` [Try it online !](https://repl.it/E7eG/0) [Answer] ## Haskell, 36 bytes ``` f l=[scanl1(min.(+x))l==l|x<-[0,-1]] ``` `(+x)` is because haskell mis-interprets `(-x)` as a value instead of a section. I wonder if the whole expression can be profitably made pointfree. [Answer] # Befunge, 50 bytes ``` &: >~1+#^_v>:0`| 1\:^ @.$$<[[email protected]](/cdn-cgi/l/email-protection)_ -: ^ >& ^ > ``` [Try it online!](http://befunge.tryitonline.net/#code=JjogPn4xKyNeX3Y-OjBgfAoxXDpeICBALiQkPC1ALjJfCi06IF4gICAgPiYgXiAgID4&input=MjcgMTkgMTkgMTAgMw) Accepts input as a sequence of int separated by spaces, and returns 0 if strictly decreasing, 1 if non-strictly decreasing, 2 otherwise. Since reading befunge is kind of impossible if you don't know the language, this is the algorithm in pseudocode: ``` push(input()) while( getchar()!=EOF ){ push(input()) subtract() duplicate() if(pop()>0){ subtract() //we are doing a-(a-b), so b is now on top duplicate() } else{ if(pop()==0){ push(1) //the sequence is not strictly decreasing swap() duplicate() } else{ push(2) //the sequence has just increased output(pop) return } } } pop() pop() output(pop()) ``` \*in befunge memory is a stack which starts with an infinite amount of 0 on it. pop(), push(x), input() and output(x) are self-explainatory, the other pseudofunctions i used work like this: ``` function duplicate(){ a=pop() push(a) push(a) } function subtract(){ a=pop() b=pop() push(b-a) } function swap(){ a=pop() b=pop() push(a) push(b) } ``` Funge! --- Previous version, just 41 bytes but invalid since it requires a 0 to terminate the input sequence (or using an interpreter like [this](http://www.quirkster.com/iano/js/befunge.html)) ``` &: >&:|>:0`| 1\v@.$_<[[email protected]](/cdn-cgi/l/email-protection)_ - >:v >^ > ``` [Try it online!](http://befunge.tryitonline.net/#code=JjogID4mOnw-OjBgfAoxXHZALiRfPC1ALjJfCi0gPjp2ICA-XiAgID4&input=MjcgMTkgMTkgMTAgMyAw) [Answer] # J, 14 bytes Monadic verb taking the list on the right, returning `1` for strictly decreasing, `0` for weakly decreasing, and `_1` otherwise. ``` *@([:<./2-/\]) ``` Takes the sign `*` of the minimum `<./` of consecutive differences `2-/\` of the list. J doesn't swap the order of the differences when taking them so e.g. the sequence is strictly decreasing if these are all positive. Notably, `<./` returns positive infinity on zero-element lists. In use at the REPL: ``` *@([:<./2-/\]) 3 1 *@([:<./2-/\]) 3 2 1 *@([:<./2-/\]) 3 2 2 0 *@([:<./2-/\]) 3 2 2 3 _1 ``` [Answer] # C, ~~68~~ 67 Bytes A function `f`, which is passed an array of ints (`l`) preceded by its length (`n`, also an int). Returns 3 if monotone strictly decreasing, 1 if monotone non-increasing, but not strictly decreasing, 0 otherwise. ``` f(int n,int*l){return n<2?3:((l[0]>l[1])*2|l[0]>=l[1])&f(n-1,l+1);} ``` Un-golfed slightly for readability: ``` int f_semiungolfed(int n, int* l) { return (n < 2) ? 3 : ((l[0] > l[1]) * 2 | l[0] >= l[1]) & f(n - 1, l + 1); } ``` Rearranged and commented to show logic: ``` int f_ungolfed(int n, int* l) { int case1 = 0, case2 = 0, recursion = 0; if (n < 2) { // Analogous to the ternary conditional I used - n < 2 means we have a single-element/empty list return 3; // Handles the vacuous-truth scenario for single lists } else { case1 = l[0] > l[1]; // The first case - are the two numbers in the list strictly decreasing? (case1 is 1 if so) case2 = l[0] >= l[1]; // The second case - are the two numbers strictly non-increasing (case2 is 1 if so) recursion = f_ungolfed(n - 1, l + 1); // Recursively call ourselves on the "rest" of the list (that is, everything other than the first element). Consider that comparison is transitive, and that we already have a vacuous-truth scenario covered. case1 *= 2; // Shift case1's value over to the left by one bit by multiplying by 2. If case1 was 1 (0b01), it's now 2 (0b10) - otherwise it's still 0 (0b00) return (case1 | case2) & recursion; // The bitwise OR operator (|) will combine any 1-bits from case1's value (either 0b10 or 0b00) or case2's value (either 0b01 or 0b00) into either 3, 2, 1, or 0 (0b11, 0b10, 0b01, or 0b00 respectively). // The bitwise AND operator (&) will combine only matching 1-bits from (case1|case2) and the return value of the recursive call - if recursion = 0b11 and case1|case2 = 0b01, then the return value will be 0b01. } } ``` Test cases (courtesy [IDEOne](http://ideone.com/er1lsf)): ``` {7, 5, 4, 3, 1}: 3 {42, 41}: 3 {5}: 3 {27, 19, 19, 10, 3}: 1 {6, 4, 2, 2, 2}: 1 {9, 9, 9, 9}: 1 {1, 2, 3, 2}: 0 {10, 9, 8, 7, 12}: 0 {4, 6, 4, 4, 2}: 0 ``` [Answer] ## [Retina](http://github.com/mbuettner/retina), 41 bytes ``` \d+ $* A`\b(1+) 1\1 S`\b$ \b(1+) \1\b.*|$ ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoKQWBcYigxKykgMVwxClNgXGIkClxiKDErKSBcMVxiLip8JA&input=NyA1IDQgMyAxCjQyIDQxCjUKMjcgMTkgMTkgMTAgMwo2IDQgMiAyIDIKOSA5IDkgOQoxIDIgMyAyCjEwIDkgOCA3IDEyCjQgNiA0IDQgMg) (The first line enables a linefeed-separated test suite.) * Strictly decreasing: `2` * Non-increasing: `3` * Neither: `1` ### Explanation ``` \d+ $* ``` Converts the input unary. ``` A`\b(1+) 1\1 ``` The regex here matches an increasing pair of consecutive numbers. If this is the case, the input can clearly not be non-increasing. The `A` denotes it as an "anti-grep" stage which means that the input line is discarded and replaced with the empty string if the regex matches. ``` S`\b$ ``` This is a split stage which is used to append a linefeed to the input *only* if the input wasn't discarded. So we've got two possible outcomes so far: non-increasing inputs get a linefeed at the end and others are still empty. ``` \b(1+) \1\b.*|$ ``` Finally, we count the number of matches of this regex. The regex either matches to identical numbers (and then everything to the end of the string to avoid multiple matches of this kind for inputs like `1 1 1 1`), or the "end of the input". Let's go through the three types of inputs: * Strictly decreasing: the first part of the regex can't match because all values are unique, but the `$` matches. Now `$` isn't *exactly* "the end of the string". It can also match in front of a trailing linefeed. So we'll actually get two matches from it, one at the end of the input, and one after the linefeed we inserted. * Non-increasing: now the first part of the regex also provides a match, and we end up with three matches. * Neither: remember that we took care to turn the input into an empty string, so now `$` matches only once. [Answer] # Vim, 69 bytes ``` V}JYu:sor!n V}JP:%s/^\(.*\)\n\1/m\r\1 :%s/\vm\n.*<(.+) \1.*/n :g/\d/d ``` [Try it online!](https://tio.run/##K/v/P6zWK7LUqji/SDGPC8gOsFIt1o@L0dDTitGMyYsx1M@NKYox5AKJxpTlxuTpadlo6GlrKsQY6mnp53FZpevHpOin/P9vYmTMZWRsyGXOZf4fAA "V (vim) – Try It Online") This is vanilla vim (TIO supports [V (vim)](https://github.com/DJMcMayhem/V), which is backwards compatible). Takes input as a list of integers, one per line. Outputs `m` for strictly monotonic, `n` for non-increasing, and empty string otherwise. ``` V} " select everything J " space-join it all into one line Y " yank that u " undo back to one per line :sor!n " reverse sort (the whole file, by line) numerically V}J " space join again P " paste the previously yanked original list " now we have the list on line 1 and a sorted copy on line 2 ``` Next we have two regexes. ``` :%s/^\(.*\)\n\1/m\r\1 ``` Matches two copies of the same line and replaces the first with "m". ``` :%s/\vm\n.*<(\d+) \1.*/n ``` Matches that "m" followed by a line containing `<(.+) \1`, i.e. a word boundary followed by `<foo> <foo>`, and if found replaces everything with `n`. The `\v` at the start says "all characters are special" so we don't have to escape any of `<()+`. There's a bit of careful cleverness here: we don't need a word boundary after the `\1` because the first number can't be a prefix of the second in a reverse sorted list. Furthermore, even though `(.+)` can match several numbers (as opposed to `(\d+)` which would match only one for an extra byte), this won't result in any false positives for the same reason: we can't have a repeated string of multiple numbers in a reverse sorted list unless they're all the same, in which case we want to match them anyway. The state after all this is one of: ``` monotonic non-increasing other --------- -------------- ----- m n 3 1 2 3 2 1 3 2 1 ``` So, to collapse these states, we just delete any line which still has a digit: `:g/\d/d`, resulting in the desired output. I do wonder whether the regexes can be golfed some (maybe avoiding some cross-line stuff?) but the corner cases can be a bit tricky. [Answer] # Axiom, 114 bytes ``` m(c:List(INT)):INT==(i:=r:=1;repeat(~index?(i+1,c)=>break;c.i<c.(i+1)=>return 0;if c.i=c.(i+1)then r:=2;i:=i+1);r) ``` **Ungolfed** ``` -- if [a,b,..n] decrescente ritorna 1 -- non crescente ritorna 2 -- altrimenti ritorna 0 m(c:List(INT)):INT== i:=r:=1 repeat ~index?(i+1,c)=>break c.i<c.(i+1) =>return 0 if c.i=c.(i+1) then r:=2 i:=i+1 r ``` **Results** ``` (x) -> m([3,1])=1, m([1,1])=2, m([])=1, m([1])=1, m([1,3])=0 (x) [1= 1,2= 2,1= 1,1= 1,0= 0] ``` [Answer] # APL, 16 bytes ``` (a≡a[⍒a])×1+a≡∪a ``` Note: enter one element array as eg `a←1⍴3` otherwise: `a←4 3 2 1` Interpreting output: ``` 2 Monotone strictly decreasing 1 Monotone non-increasing, but not strictly decreasing 0 None of the above ``` Idea: test for monotonicity by comparing original to sorted array, check for non-increasing by comparing to array with removed duplications. (And I think it can be improved...) [Answer] # LabVIEW, 12 nodes, 18 wires ==> 48 bytes by convention [![enter image description here](https://i.stack.imgur.com/mfLrI.png)](https://i.stack.imgur.com/mfLrI.png) No functions hidden in the other case frames, just a single wire across. [Answer] # Ceylon, 86 bytes ``` Object m(Integer+l)=>let(c=l.paired.map(([x,y])=>x<=>y))[if(!smaller in c)equal in c]; ``` The function takes the input as its parameters, and returns a tuple of zero or one booleans – `[false]` for *Monotone strictly decreasing*, `[true]` for *Monotone non-increasing, but not strictly decreasing*, and `[]` for *None of the above*. It can be used like this: ``` shared void run() { print("Monotone strictly decreasing:"); print(m(7, 5, 4, 3, 1)); print(m(42, 41)); print(m(5)); print("Monotone non-increasing, but not strictly decreasing:"); print(m(27, 19, 19, 10, 3)); print(m(6, 4, 2, 2, 2)); print(m(9, 9, 9, 9)); print("None of the above:"); print(m(1, 2, 3, 2)); print(m(10, 9, 8, 7, 12)); print(m(4, 6, 4, 4, 2)); } ``` Output: ``` Monotone strictly decreasing: [false] [false] [false] Monotone non-increasing, but not strictly decreasing: [true] [true] [true] None of the above: [] [] [] ``` An ungolfed and commented version: ``` // Let's decrease the monotony! // // Question: http://codegolf.stackexchange.com/q/101036/2338 // My Answer: http://codegolf.stackexchange.com/a/101309/2338 // Define a function which takes a non-empty list `l` of Integers) // (which arrive as a tuple) and returns an Object (actually // a `[Boolean*]`, but that is longer.) Object m(Integer+ l) => // the let-clause declares a variable c, which is created by taking // pairs of consecutive elements in the input, and then comparing // them. This results in lists like those (for the example inputs): // { larger, larger, larger, larger } // { larger } // {} // { larger, equal, larger, larger } // { larger, larger, equal, equal } // { equal, equal, equal } // { smaller, smaller, larger } // { larger, larger, larger, smaller } // { smaller, larger, equal, larger } let (c = l.paired.map( ([x,y]) => x<=>y) ) // now we analyze c ... // If it contains `smaller`, we have an non-decreasing sequence. // We return `[]` in this case (an empty tuple). // Otherwise we check whether `equal` is in the list, returning // `[true]` (a non-strictly decreasing sequence) if so, // and `[false]` (a strictly decreasing sequence) otherwise. [if(!smaller in c) equal in c]; ``` [Answer] **Clojure, 34 bytes** ``` #(if(apply > %)1(if(apply >= %)2)) ``` Very straight-forward, returns `1` for if strictly decreasing, `2` if non-increasin and `nil` otherwise. Also tried avoiding `apply` with macro's `~@` but it is just longer at 43 chars (this results in `[1 2 nil]`): ``` (defmacro f[& i]`(if(> ~@i)1(if(>= ~@i)2))) [(f 7 5 4 3 1) (f 27 19 19 10 3) (f 1 2 3 2)] ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 8 bytes ``` O$>g$>=g ``` Full program. Takes the input list as command-line arguments. Outputs `11` for strictly decreasing, `01` for non-increasing, `00` for neither. [Try it online!](https://tio.run/##K8gs@P/fX8UuXcXONv3///9G5v8NLcHIAAA "Pip – Try It Online") ### Explanation This approach works because Pip's comparison operators, like Python's, chain together: `4>3>2` is true, rather than being `(4>3)>2` (false) as in C. And the same behavior holds when the comparison operators are modified with the `$` fold meta-operator. ``` g is list of command-line args (implicit) $>g Fold g on > O Output without newline $>=g Fold g on >= Print (implicit) ``` ]
[Question] [ [Inspiration.](https://twitter.com/dyalogapl/status/806443935811993600)\* I cannot believe we have not had this challenge before: **Task** Given one or more printable ASCII strings, interleave them by taking one character from each string, cyclically until out of characters. If a string runs out of characters before the others, just skip that one from then on. **Examples** `SIMPLE` gives `SIMPLE` `POLLS` and `EPEES` gives `PEOPLELESS` `LYES` and `APRONS` gives `LAYPERSONS` `ABCDE` and `a c` and `123 567` gives `Aa1B 2Cc3D E567` `"\n$?*` and `​` (empty string) and `,(.)"` (trailing space) gives `",\(n.$)?"*` (trailing space) --- \* There are shorter APL solutions. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 1 byte ``` Z ``` [Try it online!](http://jelly.tryitonline.net/#code=Wg&input=&args=WydBQkNERScsJ2EgYycsJzEyMyA1NjcnXQ) The “transpose” built-in will do exactly this to a list of strings. [Answer] # Python 2, ~~101~~ ~~89~~ ~~86~~ 69 bytes ~~I'm hoping I can get this into a lambda somehow, shortening it down by making it recursive.~~ It isn't ideal because you would hope transposing is shorter, unfortunately it isn't (from what I have managed to come up with so far). ``` f=lambda s:' '*any(s)and''.join(x[:1]for x in s)+f([x[1:]for x in s]) ``` Old solutions: ``` w=input();o='' while any(w): for i in range(len(w)):o+=w[i][:1];w[i]=w[i][1:] print o ``` `lambda s:''.join(''.join([c,''][c<' ']for c in x)for x in map(None,*[list(y)for y in s]))` ``` w=input();o='' while any(x>=' 'for x in w): for i in range(len(w)):o+=w[i][:1];w[i]=w[i][1:] print o ``` *thanks to mathmandan for making me feel dumb ;) saved me a bunch of bytes! (on an old solution)* [Answer] ## [Perl 6](http://perl6.org/), 34 32 bytes ``` {[~] flat roundrobin |$_».comb} ``` ``` {roundrobin(|$_».comb).flat.join} ``` A lambda that takes an array of strings as argument, and returns a string. ([Try it online](https://ideone.com/3yFIAL)) [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 4 bytes ``` qN/z ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4veg&input=QUJDREUKYSBjCjEyMyA1Njc) We can also write an unnamed function for 4 bytes, which expects a list of strings on top of the stack: ``` {zs} ``` [Try it online!](http://cjam.tryitonline.net/#code=WyJBQkNERSIgImEgYyIgIjEyMyA1NjciXQoKe3pzfQoKfg&input=) [Answer] # Pyth - 3 bytes Very simple, will add expansion later, on mobile. ``` s.T ``` [Test Suite](http://pyth.herokuapp.com/?code=s.T&test_suite=1&test_suite_input=%22SIMPLE%22%0A%22LYES%22%2C%20%22APRON%22%0A%22ABCDE%22%2C%20%22a%20c%22%2C%20%22123%20567%22&debug=0) ``` s Join all the strings together .T Transpose, without chopping off overhang (Q implicit) ``` [Answer] # JavaScript (ES6), ~~52~~ 46 bytes ``` f=([[c,...s],...a])=>s+a?c+f(s+s?[...a,s]:a):c ``` Takes input as an array of strings and outputs as a single string. ### Test snippet ``` f=([[c,...s],...a])=>s+a?c+f(s+s?[...a,s]:a):c g=a=>console.log("Input:",JSON.stringify(a),"Output:",JSON.stringify(f(a))) g(["SIMPLE"]) g(["POLLS","EPEES"]) g(["LYES","APRONS"]) g(["ABCDE","a c","123 567"]) g(["\"\\n$?*",",(.)\" "]) // Backslash and quote are escaped, but in/output are correct ``` [Answer] # Haskell, 33 bytes ``` import Data.List concat.transpose ``` [Try it on Ideone.](http://ideone.com/fU5986) Usage: ``` Prelude Data.List> concat.transpose$["ABCDE","a c","123 567"] "Aa1B 2Cc3D E567" ``` --- ### Without using a build-in: (~~38~~ 34 bytes) ``` f[]=[] f x=[h|h:_<-x]++f[t|_:t<-x] ``` [Try it on Ideone.](http://ideone.com/d8vZGp) 4 bytes off thanks to Zgarb! Usage: ``` Prelude> f["ABCDE","a c","123 567"] "Aa1B 2Cc3D E567" ``` [Answer] # [J](http://jsoftware.com), 13 bytes ``` ({~/:)&;#\&.> ``` [Try it online!](https://tio.run/nexus/j#@5@mYGuloFFdp2@lqWatHKOmZ8eVmpyRr5CmYKMe7Okb4OOqDhNQD/D38QlWt1Z3DXB1DUYI@0S6gkQdA4L8/ZCEHZ2cXVyB4okKyUDS0MhYwdTMHCGtFJOnYq8FlAEiHQ09TSUF9f//AQ "J – TIO Nexus") Based on the [inspiration](https://twitter.com/dyalogapl/status/806443935811993600) for this question. Another way to do it takes 27 bytes but operates using transpose. Most of the bytes are to handle the automatically added zeroes from padding. ``` [:u:0<:@-.~[:,@|:(1+3&u:)&> ``` ## Explanation ``` ({~/:)&;#\&.> Input: list of boxed strings S &.> For each boxed string x in S #\ Get the length of each prefix from shortest to longest This forms the range [1, 2, ..., len(x)] Rebox it ( ) Operate on S and the prefix lengths &; Raze both /: Grade up the raze of the prefix lengths {~ Index into the raze of S using the grades Return ``` [Answer] # C, ~~114~~ 84 bytes -20 bytes for not calculating the length. ``` i,b;f(char**s){b=1;while(b){i=-1;b=0;while(s[++i]>0)if(*s[i])putchar(*s[i]++),++b;}} ``` Accepts array of char pointers and requires last item to be a null-pointer (see usage). Ungolfed and usage: ``` i,b;f(char**s){ b=1; while(b){ i=-1; b=0; while(s[++i]>0) if(*s[i]) putchar(*s[i]++),++b; } } int main(){ char*a[]={ // "POLLS","EPEES" // "LYES","APRONS" "ABCDE","a c","123 567" ,0}; f(a); puts(""); } ``` [Answer] # PHP, ~~68~~ 67 bytes ``` for(;$f=!$k=$f;$i++)for(;y|$v=$argv[++$k];$f&=""==$c)echo$c=$v[$i]; ``` Loops over command line arguments. Run with `-r`. After the inner loop, `$f` is `1` when all strings are finished, `0` else (bitwise `&` casts `""==$c` to int). Next iteration of the outer loop: copy `$f` to `$k` (saves one byte from `$k=0`) and toggle `$f`: When all strings are done, `$f` is now `false` and the loop gets broken. [Answer] ## [Retina](http://github.com/mbuettner/retina), 13 bytes Byte count assumes ISO 8859-1 encoding. ``` O$#`. $.%` ¶ ``` [Try it online!](http://retina.tryitonline.net/#code=TyQjYC4KJC4lYArCtgo&input=QUJDREUKYSBjCjEyMyA1Njc) ### Explanation ``` O$#`. $.%` ``` This is based on the standard transposition technique in Retina. We sort (`O`) all non-linefeed characters (`.`), by (`$#`) the number of characters in front of them on the same line (`$.%``), i.e. their horizontal position. The second stage then simply removes linefeeds from the input. [Answer] # Java, 19+155=174 160 ``` String f(java.util.Queue<String> q){String s,r="";while(!q.isEmpty()){s=q.poll();r+=s.isEmpty()?"":s.charAt(0);if(s.length()>1)q.add(s.substring(1));}return r;} ``` Ungolfed: ``` String f(java.util.Queue<String> q) { String s, r = ""; while (!q.isEmpty()) { s = q.poll(); r += s.isEmpty() ? "" : s.charAt(0); if (s.length() > 1) { q.add(s.substring(1)); } } return r; } ``` Output: > > SIMPLE > > > PEOPLELESS > > > LAYPERSONS > > > Aa1B 2Cc3D E567 > > > ",(n.$)?"\* ​ > > > First modification: merged string declaration to save some bytes. Removed `import`, it was used by the `main()` method (not shown here) that also needed `LinkedList`. It is fewer bytes to referece `Queue` directly. [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` lambda*m:''.join(map(lambda*r:''.join(filter(None,r)),*m)) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiVa6WurpeVn5mnkZtYoAEVLIILpmXmlKQWafjl56XqFGlq6mjlamr@LyjKzCtRSNPIzCsoLdHQ1EGjNf@rOzo5u7iqc6knKiQDSUMjYwVTM3N1AA "Python 2 – TIO Nexus") [Answer] # PHP, 77 bytes ## Golfed ``` function($a){for($d=1;$d!=$s;$i++){$d=$s;foreach($a as$v)$s.=$v[$i];}echo$s;} ``` Anonymous function that takes an array of strings. I'm sure this could be golfed more, but it's early. On each iteration, we grab the i-th letter from each given string and append it to our final string, one at a time. PHP just throws warnings if we access bits of strings that don't exist, so that's fine. We only stop when no changes have been made after looping through all the strings once. I feel like the usage of `$d` can be golfed more, but it's early. :P [Answer] # [Actually](http://github.com/Mego/Seriously), ~~7~~ 6 bytes Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=YSBa4pmCzqPOow&input=IkFCQ0RFIgoiYSBjIgoiMTIzIDU2NyI) **Edit:** -1 byte thanks to Teal pelican. ``` a Z♂ΣΣ ``` **Ungolfing** ``` Implicit input each string. a Invert the stack so that the strings are in the correct order. <space> Get the number of items on the stack, len(stack). Z Zip all len(stack) strings into one, transposing them. ♂Σ sum() every transposed list of chars into strings. Σ sum() again to join the strings together. ``` [Answer] ## JavaScript (ES6), 46 bytes ``` f=([[c,...s],...a])=>c?c+f([...a,s]):a+a&&f(a) ``` ``` <textarea oninput=o.textContent=f(this.value.split`\n`)></textarea><div id=o> ``` [Answer] # Bash + GNU utilities, 55 ``` eval paste `sed "s/.*/<(fold -1<<<'&')/g"`|tr -d \\n\\t ``` I/O via STDIN (line-separated) and STDOUT. The `sed` formats each line to a [bash process substitution](https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html#Process-Substitution). These are then `eval`ed into `paste` to do the actual interleaving. `tr` then removes unnecessary newlines and tabs. [Ideone.](https://ideone.com/KYkv8V) [Answer] # PHP, 63 bytes Note: uses IBM-850 encoding ``` for(;$s^=1;$i++)for(;n|$w=$argv[++$$i];$s&=$x<~■)echo$x=$w[$i]; ``` Run like this: ``` php -r 'for(;$s^=1;$i++)for(;n|$w=$argv[++$$i];$s&=$x<~■)echo$x=$w[$i];' "\"\n\$?*" "" ",(.)\" " 2>/dev/null;echo > ",\(n.$)?"* ``` # Explanation ``` for( # Iterate over string index. ; $s ^= 1; # Continue until $s (stop iterating) is 1. # Flip $s so each iteration starts with $s # being 1. $i++ # Increment string index. ) for( ; "n" | $w=$argv[++$$i]; # Iterate over all input strings. OR with "n" # to allow for empty strings. $s &= $x<~■ # If last character printed was greater than # \x0 (all printable chars), set $s to 0, # causing the loop to continue. ) echo $x = $w[$i]; # Print char $i of current string. ``` [Answer] # Python 3, 75 Bytes I know the other Python one is shorter, but this is the first time I've used `map` ever in my life so I'm pretty proud of it ``` lambda n:''.join(i[k]for k in range(max(map(len,n)))for i in n if len(i)>k) ``` [Answer] ## Python 2, 128 96 I was hoping not to have to use itertools ``` a=lambda a:"".join([i for i in reduce(lambda: b,c:b+c, map(None,*map(lambda m:list(m),a)) if i]) ``` Ungolfed ``` a=lambda a: #Start a lambda taking in a "".join( #Join the result together with empty string [i for i in reduce( #For every item, apply the function and 'keep' lambda: b,c:b+c, #Add lists from... map(None,*map( #None = Identity function, over a map of... lambda m:list(m), a) #list made for mthe strings m ) if i #truthy values only (otherwise the outer map will padd with None. ]) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 3 bytes ``` WVg ``` [Try it online!](https://tio.run/##K8gs@P8/PCz9////jk7OLq7/ExWS/xsaGSuYmpkDAA "Pip – Try It Online") The `WV` (weave) builtin does exactly this. It's commonly used as a binary operator to weave two iterables together, but it can also be used as a unary operator to weave a list of iterables together. Here, `g` is the list of command-line arguments. [Answer] # [Python 3](https://docs.python.org/3/), 59 bytes ``` f=lambda s:s and s[0][:1]+f(s[1:]+[s[0][1:]][:s[0]>""])or"" ``` A recursive function that takes a list of strings and returns a string. [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRodiqWCExL0WhONogNtrKMFY7TaM42tAqVjsaLAJkAYVBTDslpVjN/CIlpf8FRZl5JRppGtFKPpGuwUo6SokFRfl5xUAGUIXmfwA "Python 3 – Try It Online") ### Explanation We're going to build the interleaved string one character at a time. There are several cases to consider: * Is the first string in the list nonempty? Take its first character, move the rest of it to the end of the list, and recurse. * Is the first string in the list empty? Remove it from the list and recurse. * Is the list of strings empty? Then we're done. Return empty string. The implementation goes as follows: ``` f = lambda s: s and ... or "" ``` Define `f` to be a function of one argument, `s`, which is a list of strings. If `s` is nonempty, do the `...` part (see below); otherwise, return `""`. ``` s[0][:1] + f(...) ``` Since we now know `s` is nonempty, we can refer to its first element, `s[0]`. We don't know yet whether `s[0]` is empty, though. If it isn't, we want to concatenate its first character to a recursive call; if it is, we can concatenate the empty string to a recursive call. Slicing everything left of index 1 works in both cases. ``` s[1:] + ... ``` The argument to the recursive call is going to be all but the first element of `s`, concatenated to either a 1-element list (the rest of `s[0]` if it was nonempty) or an empty list (if `s[0]` was empty). ``` [s[0][1:]][:s[0] > ""] ``` We put `s[0][1:]` (the part of `s[0]` after the first character, which is the empty string if `s[0]` is empty) into a singleton list and then take a slice of that list. If `s[0]` is empty, `s[0] > ""` is `False`, which is treated as `0` in a slice; thus, we slice from index 0 to index 0--an empty slice. If `s[0]` is not empty, `s[0] > ""` is `True`, which is treated as `1`; thus, we slice from index 0 to index 1--the whole 1-element list. --- If lists of single-character strings can be used in place of strings, this solution can be **54 bytes**: ``` f=lambda s:s and s[0][:1]+f(s[1:]+(s[0]and[s[0][1:]])) ``` [Try it online!](https://tio.run/##HYsxCsQgEAC/slitJEXkOiFlunSpwmLhEeSEZBXXJq83Xrphhsl3/SX@tBbm01/fw4NYAc8HCE2OrHFDQCFj3YB/0wu9pRundcslcsWAdEapKBpCKiAQGUit@7KpUflcEksH9R4P) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` <!/,/'(!#:)'\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs7JR1NfRV9dQVLbSVI/h4kpT0FBydHJ2cVWyVkpUSAaShkbGCqZm5kqaQDmdaKVgT98AH1elWLBKn0jXYKASx4Agf79gJU0AfEcQ7w==) Port of [miles's J](https://codegolf.stackexchange.com/a/102518/16766) and [DLosc's BQN](https://codegolf.stackexchange.com/a/251298/78410). For a language with flatten and grade/sort-by but not zip-longest, I guess this is one of the best possible approaches. More straightforward port would be `{(,/x)@<,/!'#'x}` because K doesn't have fork or over. But it is possible to use K train by abusing repeat-scan: ``` <!/,/'(!#:)'\ ( )'\ Given a list of strings, apply this to each list until convergence and collect all intermediate values (including the input): !#: get the indices of the list This always converges after step 1, giving (x;!#x) ,/' Flatten each <!/ Sort first by second ``` [Answer] # C, ~~75~~ 71 bytes Only limitation is the output length. Currently it's 99, but can be easily stretched to 999 (+1 byte). ``` i;main(a,b)char**b;{a--;for(;i<99;i++)*b[i%a+1]&&putchar(*b[i%a+1]++);} ``` Ungolfed: ``` i; main( a, b ) char **b; { a--; for( ; i < 99; i++ ) *b[i % a + 1] && putchar( *b[i % a + 1]++ ); } ``` [Answer] # Oracle SQL, 195 bytes ``` select listagg(b,'') within group(order by l,o) from(select substr(a,level,1) b,level l,o from i start with length(a)>0 connect by prior a=a and level<=length(a) and prior sys_guid() is not null) ``` Takes its input from a table named `i` with columns `a` (containing the string) and `o` (order of the string): ``` create table i (a varchar2(4000), a integer) ``` Explanation: We're exploiting `CONNECT BY` to break up the strings into each of the characters making them up. `PRIOR SYS_GUID()` being `NOT NULL` ensures we don't end up stuck in a loop. We then concatenate the single characters with `LISTAGG` but we shuffle them around with an `ORDER BY` clause, ordering them first by their position in the original string and only then by the string they came from. Not as short as the other answers but SQL isn't really meant as a string manipulation language :) [Answer] # [R](https://www.r-project.org/), 73 bytes ``` for(i in 1:max(nchar(s<-scan(,""))))for(j in seq(s))cat(substr(s[j],i,i)) ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdAqN7FCIy85I7FIo9hGtzg5MU9DR0lJEwhAarJAaopTCzWKNTWTE0s0ikuTikuAKqOzYnUydTI1Nf8rOTo5u7gqcSklKiQDSUMjYwVTM3Mlrv8A "R – Try It Online") Explanation: very simple (but verbose), just loop through printing `i`th character of the `j`th string. Fortunately, `substr` returns an empty string if given an out-of-range input. [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 49 bytes ``` map(explode)|transpose|map(map(values)[])|implode ``` Explanation ``` # example input: ["LYES","APRONS"] map(explode) # make list of ordinals [[76,89,69,83],[65,80,82,79,78,83]] | transpose # zip lists [[76,65],[89,80],[69,82],[83,79],[null,78],[null,83]] | map(map(values)[]) # rm nulls and flatten [76,65,89,80,69,82,83,79,78,83] | implode # convert back to string "LAYPERSONS" ``` Sample Run ``` $ paste input <(jq -Mrc 'map(explode)|transpose|map(map(values)[])|implode' input) ["SIMPLE"] SIMPLE ["POLLS","EPEES"] PEOPLELESS ["LYES","APRONS"] LAYPERSONS ["ABCDE", "a c", "123 567"] Aa1B 2Cc3D E567 ["\"\\n$?*", "", ",(.)\" "] ",\(n.$)?"* $ echo -n 'map(explode)|transpose|map(map(values)[])|implode' | wc -c 49 ``` [**Try it online**](https://jqplay.org/s/u4OgJj_3j2) [Answer] # [Perl 5](https://www.perl.org/), + `-0n` 24 bytes ``` 1while s/^./!print$&/gem ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1WhWD9OT1@xoCgzr0RFTT89Nff//wB/H59gLtcAV9fgf/kFJZn5ecX/dfMMAA "Perl 5 – Try It Online") ## Explanation `-0n` slurps the input into `$_` and repeatedly replaces the first char of each line with the result of negating the `print` of each match (which is the empty string since `print` returns `1` by default) [Answer] # [Factor](https://factorcode.org/), 22 bytes ``` [ round-robin ""like ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQma@QnVqUl5qjUJxaWJqal5xajGDppVaUFCUWK1hzcVUrKDk6Obu4KikoJSokA0lDI2MFUzNzJYXa/9EKRfmleSm6RflJmXkKSko5mdmpCrH/kxNzchQKijLzSv4DAA "Factor – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 1 byte ``` ∩ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4oipIiwiIiwiWydBQkNERScsICdhIGMnLCAnMTIzIDU2NyddIl0=) ]
[Question] [ Given an integer, output a [truthy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value if it is the same upside-down (rotated 180°) or a [falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value otherwise. `0`, `1`, and `8` have rotational symmetry. `6` becomes `9` and vice versa. Sequence of numbers producing truthy results: [OEIS A000787](https://oeis.org/A000787) ``` 0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 888, 906, 916, 986, 1001, 1111, 1691, 1881, 1961, 6009, 6119, 6699, 6889, 6969, 8008, 8118, 8698, 8888, 8968, 9006, 9116, 9696, 9886, 9966, 10001, 10101, 10801, 11011, 11111, 11811, 16091, ... ``` This question is inspired by my own reputation at the time of posting: `6009`. [Answer] ## Python 2, 50 bytes ``` lambda n:`n`==`map('01xxxx9x86'.find,`n`)`[-2::-3] ``` The method `'01xxxx9x86'.find` takes a digit character to it's upside-down number, with any unflippable digit giving `-1`. This function is mapped to the reversed number string, producing a list of digits. This is converted to a string with the [`[1::3]` trick](https://codegolf.stackexchange.com/a/49791/20260), except it's reversed instead by doing `[-2::-3]` (thanks to Dennis for this, saving 4 bytes), and compared to the original number string. Any `-1`'s from unflippable digits will misalign the conversion, making it fail. --- **56 bytes:** ``` lambda n:`n`[::-1]==`n`.translate('01xxxx9x86______'*16) ``` Checks if the number string reversed is the same as it with the upside-down replacements. Digits that can't be flipped are replaced with `'x'` to always give the wrong answer. The replacement is done with `translate` on a string of 256 chars, replacing the corresponding ASCII values. Only the 10 values `48` to `57` matter, but I padded to length 16 to make the total length be 256. I wonder if there's a shorter way. Some other approaches (lengths 59, 60, 60): ``` lambda n:set(zip(`n`,`n`[::-1]))<=set(zip('01896','01869')) r=lambda s:set(zip(s,s[::-1]));lambda n:r(`n`)<=r('9018106') lambda n:all(a+b in'001188969'for a,b in zip(`n`,`n`[::-1])) ``` [Answer] # Regex (ECMAScript / Python), ~~366~~ ~~323~~ ~~254~~ ~~201~~ ~~180~~ ~~148~~ 135 bytes `^(x$|x{8}$|(?=.*?(?=(((x*)\4{8}(?=\4$))+x$))(x*)\5{99})(?=(\2x)(|\6{5}(\6\6|\2{3}|xxx))(?!\2)(x*)\9{9}$)(?=(x*(?=\5|$))(|\5x)\9$)\10)*$` Takes its input in unary, as the length of a string of `x`s. [Try it online!](https://tio.run/##TU9dT8IwFP0rQBa4d8jYEIgwC08@@MKDPlpNGiijWsrSFqis@@3YYUx8Ock9Xzfnk52YWWtR2oEpxYbr/UF98e@rJoqfWy@8eHIlwIUshvH1A1zkXfVQRx6WJImXAQHAxUjHgQ0XHUeIfRfgxk6q2azGxkVHDsHTaTWpgU7p1NNRdV9751ywLtt09BuYVbM6ugVc3NRNfFPl6cQFLUKapRhH13h4wcQeXq0WqgBMjBRrDtO7wRgxNyTNzzshOYAkmrONFIoDYpuoo5RYFUQmppTCQm/Qw1xsARQpEslVYXe4GHkvzIqtQJCSacOflYXiLX1H/BP4f0EtsmU2b2S0O304d57ViUmxaWmmCj5vdfoy3x405OKR8Fz0@xgedlwn0bzkzILAZM/segcasTLdbhkmWWhWZHl5tMbqYMnr@poOsjRNfwA "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##TY7RboMgFIbvfQpGvACrBm110470JXZXbNKsdGVhaMAmNOKzO7C72M0JnO///pzhMd56tV3Ez9DrEZiHSTVPv02v9kBTDSFcTsjGzk5vc@zQgebJwU@EkE0w2/mt/7FdjPHG@rFuq6lpZhxSrLQYOVZP1YxYzWrHymk7O2utjx5eWPkUmqmZ41WwSairXKhyrLKexZgVBCfx4m85Fm1WdHsgKImuvQYSCBVuzs14EaqNgKQyN4MUI4IZxBEQVyC5QhK/ly2Qx6Kj8ki6CARZBVmf1RdHQo0oAJw@X0WHNwX2faFA89zws/68IZ0CaGGiVhKQaMGgg3KVd3OjH/rO8Yposf8jZtRI4RRwdaEQpuBfciFZSUhUE5K9EvIL "Python 3 – Try It Online") - Python [Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Rotationally-symmetric-numbers-01689) - RegexMathEngine (much faster), in ECMAScript mode It's impossible for a ECMAScript regex to match the sequence in decimal, but as demonstrated here, it's possible in unary. The regex works by looping the following logic: 1. Carve away both the leading and trailing digit if they are an allowed pair, or (for single-digit values) an allowed single digit. 2. Prevent the value sent to the next iteration from having any leading zeroes, since the regex operates on numbers, not strings, so any leading zeroes would be stripped. If it has a leading zero, add \$1\$ to both the leading and trailing digit. If both were zero, both will be changed to \$1\$, preserving the trait of symmetry. If the trailing digit was nonzero (meaning the input is not a rotationally symmetric number), adding one of \$11, 101, 1001, ...\$ is guaranteed not to change it to one that is symmetric, because for example \$1001\$ could only be added to any number in the range \$0001\$ to \$0999\$ with a nonzero last digit, which can only yield a number in the range \$1002\$ to \$2000\$ with a last digit other than \$1\$, none of which are rotationally symmetric. This allows us to golf off 13 bytes, due to not needing the trailing zero check `(?=(x{10})*$)`. The 135 byte version has been tested from 0 to 1000000 using [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/) without finding any false positives or negatives. The test took 29.342 hours (single-threaded) on my i7-4930K @ 4.1 GHz. (This was originally part of [this answer](https://codegolf.stackexchange.com/a/248959/17216) and was split due to being very different in nature. See that post's edit history for changes made prior to the 254 byte length.) ``` ^ # tail = input number ( x$ # If tail==1, let tail=0 and end the loop | x{8}$ # If tail==8, let tail=0 and end the loop | # Assert tail >= 10; find \2 = the largest power of 10 that is <= tail (?= .*? # Decrease tail by the minimum necessary to satisfy # the following assertion: (?= # Assert tail is a power of 10 >= 10; \2 = tail (((x*)\4{8}(?=\4$))+x$) ) (x*)\5{99} # \5 = floor(tail / 100) ) # Require tail is of the form 1.*1, 8.*8, 6.*9, or 9.*6 (?= (\2x) # \6 = \2 + 1 ( # 1.*1 | \6{5} ( \6\6 # 8.*8 | \2{3} # 9.*6 | xxx # 6.*9 ) ) (?!\2) (x*)\9{9}$ # Assert tail is divisible by 10; # \9 = tail / 10 == floor((N % \2) / 10) ) # Set tail = \9, but if \9 is of the form 0.*0, the next iteration would # not be able to see its leading zero, so change it to the form 1.*1 in # that case, otherwise leave it unchanged. If \9 is of the form 0.*[1-9], # don't go to the next iteration. (?= ( # \10 = tool to make tail = \9 or \9 + \5 + 1 x* # Assert that the leading digit of tail is not 0, unless tail==0 (?= \5 # Assert that the leading digit of tail is not 0 | # or $ # Assert that tail==0 ) ) # Iff necessary to satisfy the above, tail += \5 + 1 ( | \5x ) \9$ # tail = \9 ) \10 # tail = \9 or \9 + \5 + 1 )* # Execute the above loop as many times as possible, # with a minimum of zero iterations. $ # Assert tail==0 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~22~~ ~~16~~ ~~15~~ 14 bytes Code: ``` Â23457ð«-69‡Q ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4IyMzQ1N8OwwqstNjnDguKAoVE&input=Njg5) --- Previous code: ``` Â69‡Q¹¹„vd•ÃQ* ``` To figure out if the string is rotational symmetric, we just need to transliterate `69` with `96`, reverse the string and check if they are equal. The other thing we need to know is if the number *only* contains the digits `0`, `1`, `8`, `6` and `9`. So that's exactly what we are going to do: ```  # Bifurcate the input, which pushes input and input[::-1] 69 # Bifurcate 69, which pushes 69 and 96. ‡ # Transliterate 69 with 96 in the input, e.g. 1299 becomes 1266. Q # Check for equality. ¹¹ # Push input again twice. „vd• # Compressed version for 10869. ``` The `„vd•` part actually converts the string `vd` from *base 190* to *base 10*. You can try this out [here](http://05ab1e.tryitonline.net/#code=4oCedmTigKI&input=). ``` à # Keep the characters of the second string in the first string. 667788 would become 6688 (since 7 is not in 10869). Q # Check for equality. * # Multiply the top two numbers, which actually does an AND function. ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4I2OcOC4oChUcK5wrnigJ52ZOKAosODUSo&input=Njg5) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` žhÀ•yΘOñ•‡RQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6L6Mww2PGhZVnpvhf3gjkPGoYWFQ4P//RkZGAA "05AB1E – Try It Online") I somehow managed to beat Adnan's 05AB1E answer lol. This ## Explained ``` žhÀ # Push "1234567890" •yΘOñ• # Push "1000090860" ‡ # Transliterate the input based upon the previous two strings RQ # Check if the reverse of that equals the input ``` [Answer] # Ruby, 54 46 bytes ``` ->a{(b=a.to_s).tr('1-9','1w-z9x86').reverse==b} ``` I don't know, is anonymous functions like that allowed or not Basically same idea as Python2 answer. If input is not integer, act bad (i.e. `aba` gives `true`) [Answer] # Regex (Perl / PCRE2 / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 35 bytes ``` ^(([018])((?1)\2|)|6(?1)9|9(?1)6|)$ ``` Takes its input in decimal. [Try it online!](https://tio.run/##RU7LasMwEPyVJYhES2wsGRqaykocSK899Za4Ii0xCNTEldxDkdVfdyU3kD3s7szsY7qzNQ/j5w8QK8Cb68fJAClEhLLa7153mwDt1VLiJBPVRqAH3UaEvrP60sPseJmJALWRrjO6p4t8kbnvd9fHFZXlPON4/kpD2zvLIo9PRKFIt1z8eLK1qUr0tTnwRsbMGnH7q2@Q6EpOcuyWS/S6hSiC/IWC2AI9cfP5ZGlyFO1y8e@QaBFCUOr5Za/U@EbpgfHHBindcjyWAw6r1K2HdSqrAck4srxkKf4A "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##dVBda8IwFH33V4QQMHe22hbnVmLxZRsIYw/b3qwL2qU2rKYhjTDQ/XZ3I3sSFkhyP84593BtY8/zhW0sYY4UhE4oGRPr1E46ZdtNpfhwMr5ZSNlsWi@rbm91q1zJSxDl66QfRmSIt8ai3KkAMF4Z33Mpn5bPj1JCRFJASRQWA2207JXn1FZOjbeb6ss7fGSr99rTiNBplk/z2V2W31K4hjtVHVyvO/MfvO4cZ7pIBGuLGs30/O39YfkCAo5E15y1q967VhmMIE7XRUFLQwHB/WGLHSxHSRSnEPjq27bdp@I0phHCBfKr7mB84M4zJK1QAN9kLQaEXCabv5yZeXHpYzQaAY4m/LLQ/cZXDWcuYgaAHIMlDapquuBDELSeChJywoz4Qdmfq61zEOcPzldJer8GzhcplNkJTrMQ5ac8fLMTsPM5ibMknF8 "PHP – Try It Online") - PCRE2 [Try it online!](https://tio.run/##XZBvT8IwEMbf71Nc1IRWBjJMiG4MEz@C8YUGcSmlbI2ja9ouk39f3dkWUfBetNfL3T2/PlTKXk5pe8kFLesFg/G8qrS5USxnn/1CyklAC6Igk9MZpPB08dg0H/Pb@nW9fnkuRk2B2neEpoPoboYReojw23CHdyOX3e/u3TXa4asW/x@7COFappnsRknwp82ttGJkNQm4MCCVPTOmVKUQrYQ24FGuV0xrkjO81WYRx9Q2wHgMP1WX@joTizIBxUytBETJ3q9cES4Qhm0ANuTUqpVMIIl70SwdJFDbntthZqByLzeQ28Q3HwC8OXHs3bG7kQzPSnHMKdEMJ8eqXhFDC2gKYg5rlpUC5BZv0kEI3MuM0@HARQLdLj/CufD/sIxc5KCt@/5tquxQQhwnv618CeiUJNOMKFogHXrx0MLi09XHmQ0GWRvnK@q8iY4l36RRcta2bBQ3DOk@dcIIh6D7mm@Yy6LQQVW1OUHZB3/nj/3Ww337RZclyXXbKz1o5jm/AQ "C++ (gcc) – Try It Online") - Boost [Attempt This Online!](https://ato.pxeger.com/run?1=NY9LTsMwEIb3OcXIsJgRSRRnUbUJEQcJRqrAaY2MHY1dQaXchE03IC7BhltwG-qkzGYe_3zzeP8cj3Hv3enbvIyeI4RjyFnv9Fv-HLxrgTsWQnwc4lCsf68eEPtKrhUh3km6ryeaVinaTJvkVhNdX1p_zlQvm0KqFkxXZYNnsGBcWlCG-GRck4HtbBlGayKKQlAGZgCrHVq6rRuwvVSd7SuVQYJdgnnrdhqNi5gEypdIKrqRdJ6XBszHl0Fv-XGPnEOIjI5mNcmmgZETRnOhk-3_Rf4Qy1c2UeMFWT45fVVFXSVb8j8 "Python - Attempt This Online") - Python `import regex` ``` ^ # Assert this is the start of the string ( # Define (?1) recursive subroutine call ([018]) # \2 = match a 0, 1, or 8 ((?1)\2|) # Optionally match (?1) followed by \2 | # or 6(?1)9 | # or 9(?1)6 | # or # Match an empty string ) $ # Assert this is the end of the string ``` ## Regex (Ruby), 43 bytes ``` ^(([018])(\g<1>\k<2+0>|)|6\g<1>9|9\g<1>6|)$ ``` [Try it online!](https://tio.run/##PY5RS8MwFIXf/RXXISxBG5I@DLc0g@KK@DJh@tbWoCzrgiEracYUin@9Jp0ucBPOd8@5ue748T04ELBRjfpqiVUnWOWvOXHqfXt3hovF0@P6eVM85C8FBy0oh9NeGwVGNMp3VwB6B6ZMWC3EpLITHhqmpIQkac1B2W1wBEK61miPpskU/0WIUbbxe4SzNGTKkA@xS2R3cGBBW4iQ@IPUiFFMSDReZPCNs2wkHcIgfsDxSPR1XLQ9@m4cGBdnQTttPdj/P@IdS8pivZJyeEOopOy@xqhqMrasPrP0li573M9GPe/n4zvr8c0w0CSl8fwC "Ruby – Try It Online") This is a direct port of the Perl/PCRE2/Boost version to Ruby's subroutine call syntax and behavior; `(?1)` has been changed to `\g<1>`, and `\2` to `\k<2+0>`. In Perl, PCRE, and Boost, the contents of capture groups are passed to deeper recursion levels, but upon return from a subroutine call, all captures are returned to the state they were in before the subroutine was called, i.e. there is no way to pass captures done within a subroutine call back to its caller. But in Ruby, captures *are* passed to the caller. So `\2` will refer to whatever it captured at the deepest recursion level, and so would `\k<2>`. It is possible, however, to refer to a capture's value at a specific recursion level; that is why `\k<2+0>` is used here to refer to its value at the current level. ## Regex (.NET), ~~94~~ ~~77~~ ~~66~~ 53 bytes ``` ^((?=([018]|6.*9|9.*6)(?<=(.))).?)+(?<-3>\3)*(?(3)^)$ ``` [Try it online!](https://tio.run/##RY/haoNAEIRfRWQhu9o7NEJoYq4G@rtPYA2IvdSDy52cFywxPrvVltL59w2zw05nB@n6Vmo9gxOlk5/yqzocjBzwtJnPiIXAMkmfq8eOR/vHnkc7wuIokBMRLyhegGUv7xlFWGBGZ4J5c3oKX@21U1p@hJTDXST5xTpZNy2CDpQJQJnu5mmEWoBmfaeVD1mYqwtCzRt7M55pH2zXQCygLpNqWgoQjCiV8dWPk4NhWv5xunIc07h2OP5W@6aV/XJBv9adxsEpL1lrez8tL6X5PwfM2GWxVkYGYKZpmhO2TVZ9Aw "PowerShell – Try It Online") Implementing this using .NET's Balancing Groups feature turns out to provide an edge over the 57 byte .NET-compatible version that doesn't use any .NET-specific features. ``` ^ # Assert we're at the beginning of the string ( (?= # Depending on what the next left-edge digit is, push its corresponding # right-edge digit onto the Group 3 stack. ( [018] | 6.*9 | 9.*6 ) (?<=(.)) # \3 = the right-edge digit (push it onto the Group 3 stack) ) .? )+ (?<-3>\3)* # Match all right-edge digits in reverse order as they're # popped from the stack. (?(3)^) # Assert that the Group 3 stack is now empty (literally: if # its stack is not empty, assert something impossible, that # we're at the beginning of the string). $ # Assert we've reached the end of the string, having matched # all of its characters. ``` ## Regex (Perl / PCRE / .NET), ~~106~~ ~~62~~ 57 bytes ``` ^((?=([018]|6.*9|9.*6)(?<=(.))).?(?=.*(\3(?(4)\4))))*\4?$ ``` [Try it online!](https://tio.run/##RU7LTsMwEPwVq7Jab5qHU0JFsV2nUrly4tYEq6BGsmTaYIcDcsOvBydUYg@rnZndnWlP1twPH98IW4a8ubwfDcIZC1Dw/e5lt@1Rc7EEO0EZ3zLwSDcBgW@tPndoVp1nrEelEa41uiOLZBG7rzfXhRMVJ3mcw@lzXJL/LA08PGIFbPzlguPRloavwJfmkNcidFqzm6@@Qay5mOQwLZfgdYOCiMQPyrDNwGM3n0@RpkQhbs7@EmLN@r5X6ul5r9TwSogU5EDzh/q6TqPNdZNGayCSC5ICQCqDnEakuiOSFFAVgYOoKiQeBpqs6Fi/ "Perl 5 – Try It Online") - Perl **[Try it online!](https://tio.run/##hVNhb9owEP3Or7iytdgQUFKqqk1IUdcx7QNrJ0SlTcAiFhywFpzIMevawl8fO9vQUlppUT6cz@d3z@@d4zyvT@N4/Y6LOF1MGLTyWLLG7KIUz8YSonwwghB65Q93d79@Nhff7@@/9WendzOy/kFIOyQD1zsbLU8b1fPleaN6Skm7FZIGpbTRxu1GlQybpE1O6PAEc7Q6PGm/X9N9sLID1TyM8poXlJ6JFGrCM81kNyW5mL7M8QyzbDx/XXdR4kJBjqGKmJSZJHEmCgXmZtU5K4rxlNFH7OP7MRZAqwWbrA5NnolJGoBkaiEFeMHKQM7HXBAKjyXALx9gt5QJktO6NwrdABZY0zyOFGR6pQ9MMTDFBtOyw418oQLQekNVsgB22SGdXEl7WrJikSob63skScGUA9lCYdupmtmd7DeLVSYHzZFthaihAY/ibJ7zlJHcga9XvU708aZ/2e3C0q5u@5/OHDiyDW2w7eBSC8UTIAeS0a0OidE0IXgbrHagrIEMNQljZGKOw@HEh8NiKNDdHUzbZwOc4AGiyT9opYw4U6ZSLhixrnDhWJ1ogDXeVnNDCo8JF@84VhknpqgRR6gtodQB4TmQZwVu252Eiwmp1CubxvoTnhYIaw7CXV98X@hk@w1cqJn6GiARH5s/Yz1dhIdCe94KhRdArcZ3Ge8PgGZn1iqLbIrwHX7WRG391kj2h8VEMgeub7tdB4otLx0W/IHpyDX/ZhgcaO4Bais3oBchuLBcbnugCmYeOr3eTS@6vvly2b/6vE9/C/FAAXXRo0oqQ1Gx7gSvSq2JOKj6PfHgTahN@xaSOTr6D5kXeGUfOnrkyi9xV28LuGOWrViVzMD6dhAlY8iEPj31zZsrrdZu/djV3984ScfTYl1PtRf/AA "C++ (gcc) – Try It Online") - PCRE1** [Try it online!](https://tio.run/##dVBdS8MwFH33V4QQ2L2169pZpyUrfVFBEB/Ut3WGWTMb7NKQZiCov33eDp8EA7ncj3POPVzXusOycq1jwrOS8RlnCXNevymvXbdpNExmSVQp1W66oJp@50ynfQ01yvphNkxiNqG/paZ60yPABm3DAErd3N5dK4Uxy5AkSVieGGvUoANw13idvGya9@ApqM7sTOAx4/m8yIvFxbw45/gX7nWz94Pp7X/wbe9BmDKVoiu3ZGaAx6er23uU@MnMFkS3GoLvtKUMp9m6LHltORJ42L/QhNpxGk8zHPn6w3X9qwY@5THBJfGbfm/DyF3OibQiAYrpWp4wdtxsf2thl@VxTtnpKdJqBseD7jahaUH4WFhE9jlaMqibth99SEbWM8nGmgkrv0n2@8/VAeXhGaAqYZVml@uvRRIVX0USLRCqZQkJIiYVjZMI6jOoIMc6px5GdV6JwyGdztPx/QA "PHP – Try It Online") - PCRE2 [Try it online!](https://tio.run/##RY9ha4MwEIb/ishBL7oE7aSsdcHCPu8XqIPg0hnIEokpjlp/u4sbY/ftee7u5W6wk3RjL7VewfHayQ/51Z5ORk543q1viBXHOsuf2vuBJcf7kSUHgtUzR0YIYVVoswSbR6ywIE0RHEmaooJ1d36IX@znoLR8j0kJN56VF@uk6HoEHSkTgTLD1ZMZBAdNx0ErH9O4VBcEwTp7NZ5qH@23gZSDqLN2CQEIhtfK@PbHlGColn@cb5ymZN4yHHsVvuvlGDbIr7qReXLKS9rb0S/hpLz854gaG77WysgIzLIsa0b32Vbf "PowerShell – Try It Online") - .NET In PCRE1, subroutine calls are atomic, which prevents the Perl/PCRE2/Boost version (which requires backtracking to extend into nested subroutine calls) from working. As for .NET (and Java), subroutine calls are not supported. In this version, instead of using recursion, we read inward from the left and right edges, one pair of characters at a time, remembering the right-edge position using capture group `\4`. A set of alternatives followed by a lookbehind is used to set the required right-edge digit based on whether the left-edge digit was `[018]`, `6`, or `9`. ``` ^ ( # Depending on the next left digit, capture the required right digit in \3 (?= ( [018] | 6.*9 | 9.*6 ) (?<=(.)) # Capture the previous character (the right digit) in \3 ) .? (?= .* ( # Capture \4 as the following: \3 # Match \4 iff it has been captured (i.e., iff this is not the # first iteration). As such, \4 will be prepended with the current # right digit. (?(4)\4) ) ) )* \4? $ ``` ## Regex (Perl / PCRE / Java / .NET), ~~113~~ ~~76~~ ~~69~~ 64 bytes ``` ^((?=([018]|6.*9|9.*6)(?<=(.))).?(?=.*(\3(\6\4|(?!\6))())))*\4?$ ``` [Try it online!](https://tio.run/##RU7LTsMwEPwVU1mtN83DKSWiOG5SqVw5cauDVVAjWTJtsMMBOeHXg5NWYg@rnZndnWlORj8Mnz8IG4acvnwcNcIJ85Dn@93rbtuj@mIItpyyfMvAIVV7BK4x6tyimTjPWI9KzW2jVUsW0SK03@@29ScyjNIwhdPXuFT8s9Tz8IQlsPGX9Y5HU@p8Ba7Uh7TivtOK3XzVDWKV80n203IJTtXIi4j/ogSbBBy28/kUaUrk46bsmhAr1ve9lM8veymHN0IKTg40fay6LA423SYOMiBFzkkMAHHh5Tgg4p6ITKw7UtyJDIB4CQKxLvAw0GhFx/oD "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##hVNhb9owEP3Or7iytdgQUFIq1CakqOs67QNrJ0SlTcAiFhywFpzIMevawl8fO9vQUlppUT6cz@d3z@@d4zyvT@N4/Y6LOF1MGLTzWLLG7LwUz8YSonwwghB65Q93d79@Nhff7@@/9WetuxlZ/yCkE5KB652Olq1G9Wx51qi2KOm0Q9KglDY6uN2okmGTDFvDkyXpHAxblBLcotXhSef9mu5jlh2o5mGU17yg9MynUBOeaUK7KcnF9GWOZ5hl4/nruvMSFwpyDFXEpMwkiTNRKDAXrM5ZUYynjD5iH9@PsQDabdhkdWjyTEzSACRTCynAC1YGcj7mglB4LAF@@QC7pUyQnNa9UegGsMCa5nGkINMrfWCKgSk2mJYdbuQLFYCWHaqSBbDLDunkStrTkhWLVNlY3yNJCqYcyBYK207VzO5kv1msMjlojmwrRA0NeBRn85ynjOQOfL3sXUUfb/oX3S4s7eq2/@nUgSPb0AbbDi61UDwBciAZ3eqQGE0TgrfBagfKGshQkzBGJuY4HE58OCyGAt3dwbR9NsAJHiCa/INWyogzZSrlghHrCheO1YkGWONtNTek8Jhw8Y5jlXFiihpxhNripDkgPAfyrMBtu5NwMSGVemXTWH/C0wJhzUG464vvC53svIELNVNfAyTiY/NnrKeL8FBoz9uh8AKo1fgu4/0B0OzMWmWRTRG@w8@aqK3fGsn@sJhI5sD1bbfrQLHlpcOCPzAduebfDIMDzT1AbeUG9DwEF5bLbQ9UwczDVa9304uub75c9C8/79PfQjxQQF30qJLKUFSsO8GrUmsiDqp@Tzx4E2rTvo1kjo7@Q@YFXtmHKz1y5Ze4q7cF3DHLVqxKZmB9O4iSMWRCn5765s2VVmu3fuzq72@cpONpsa6n2ot/ "C++ (gcc) – Try It Online") - PCRE1 [Try it online!](https://tio.run/##dVBNa@MwEL33V6hCkBnXcexs6q5RjC@7hULZw7a3KCtSr1KLdWQhK7DQ9Len47Cnwgo0zMd7bx7jO39eN77zTARWM77gLGM@mFcdjO93rYHZIksarbtdH3U7HLztTVCgUKqfi3GWshn9PTX1q5kALhoXR9D6/uHxu9aYsgJJkoTllXVWjyYC920w2cuu/RMDBd3bg408ZXy1rFZVebesbjl@hgfTHsNoB/c/@H4IIGydS9HXezIzwtPzt4cfKPGN2T2IfjPG0BtHGc6LbV1z5TgSeDy@0ITaaZ7OC5z45q/vh98G@JynBJfEb4ejixN3vSTShgQo5lt5xdhls/tXC7euL3PKbm6QVjO4HPSwi20HIqTCIbK3yZJF03bD5EMysl5INtVMOPlOsu@frg4oz78Amho2efF1eyqzpDpVWVIiNOsaMkTMGhpnCagvoEq1OkFzrUpEoBEmatWI8zmfL/PpfQA "PHP – Try It Online") - PCRE2 **[Try it online!](https://tio.run/##bVJhT9swEP3OrziiTZwDmJahaixElSZt0qQxTevHtpPcxmkNjpPZF9pR@O3duc02kOov57v3/Hzv7Dv1oM7vivutqZraE9xxLk0t0wxeVloy9mDN64VeM3LUtDNr5jC3KgS4VcbBBrpaIEUcHmpTQMUIjsgbtwDlF2E8FUBLX68CfFrPdUOm5pNHAJ@N1VDmTq92W0zkvC60ZDwR2ce2LLXXxQ@tCu1htqO9LuLfk11aCpF194YzylbLqI8Y8hl7UMVX4zQKcZy71lphSgxS/2qVDZhcpGmaCLF5Td0rINJBgQ0r0D8FFrhghRnz7rNwmp9M3EmMlD3va8/fFZH2Dnze7dht1cQLgsh4GrO6tlo5eMxLVtQZjObKObZuXNMS5BDddjUc/Q6kK2mcyKDzuaPJpQrf9Jq4zd2IAbqBWO6dNfYkx4zOYoePp2AZjiwZGmsIk3N@BOYTuB4jXxzxN/CyUT5oTtCOe1NxBq5/EJRWuwUtby5hCJEJHzj0pzujAGXtY78snbteBu4md30Op6fcdNfv@oUs1fsiRre3iuZLnkrFBC@rfYbr2GsJWMnSuILdx9d5FN2Yava88oY0xmcR2WNOvo0T/g83fAGVmLwNCZsS2XNcR/FfbH8iDnMc9/rvp08DmV4/Xct0IHB4k6MUQsghwzLFyTucDCZXTzg8ngyE4B6ESCdXwzfb@De2vfPLXlx/AA "Java (JDK) – Try It Online") - Java** [Try it online!](https://tio.run/##RY/haoQwEIRfxUrgdrUJej2kdzZ40N99AvVAbK4G0kRiDsupz25jS@n@@2Z2h9nejMIOnVBqJZaXVnyIr/p00mKE8269ABQcyiR9rueMRcf5yKIMoXjhwBCRFd5mEVRPUGXVYYbiocoQwVsYVYeCrLvzY/hqPnupxHuIObnzJL8aK5q2A6ICqQMidX9zOJGGE0WHXkkX0jCXVyANa81NO6pcsN8WYk6aMqkXHwBE81JqV/8oOdFUiT9ON45jnLYMy94a13Zi8Bf4K91xGq10gnZmcIuvlOb/HFBt/PNKahEQvSzLmtB9ss03 "PowerShell – Try It Online") - .NET This is a port of the Perl/PCRE/.NET version, removing the use of the conditional due to their lack in Java, and emulating it with an empty capture whose set/unset status can be detected. Only the modified portion is shown below: ``` # Match \4 iff it has been captured (i.e., iff this is not the # first iteration). As such, \4 will be prepended with the current # right digit. ( \6\4 | (?!\6) ) () # \6 = set and empty, to signal \4 is captured ``` [Answer] ## JavaScript (ES6), 56 bytes ``` n=>n==[...''+n].reverse().map(c=>'0100009086'[c]).join`` ``` [Answer] # sh, ~~40~~ 33 bytes ``` [ `rev<<<$1|tr 6923457 96` = $1 ] ``` Input via command line argument, output via exit code. Generate all testcases: ``` for i in `seq 0 10000` do if [ `rev<<<$i|tr 6923457 96` = $i ] then echo $i fi done ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~40~~ ~~38~~ 33 bytes ``` $ ;$_ T`92-7`69`;.+ +`(.);\1 ; ^; ``` [Try it online!](http://retina.tryitonline.net/#code=JAo7JF8KVGA5Mi03YDY5YDsuKworYCguKTtcMQo7Cl47&input=MTYxMDg4MDE5MQ) ### Explanation This uses a completely different approach from the other Retina answer. Instead of removing all symmetric parts, we simply perform the transformation of reversing the string and swapping `6` and `9`s and then compare for equality. To make sure that no non-symmetric digits appear we also turn them into `9`s in one half. ``` $ ;$_ ``` We duplicate the input by matching the end of the string and inserting `;` followed by the entire input. ``` T`92-7`69`;.+ ``` This performs a character transliteration only on the second half by matching it with `;.+`. The two transliteration sets expand to: ``` 9234567 6999999 ``` Because `2-7` denotes a range and the target set is padded with the last character to match the length of the source set. Hence, the stage swaps `6` and `9` and also turns all of `23457` into `9`s. ``` +`(.);\1 ; ``` Repeatedly (`+`) remove a pair of identical characters around the `;`. This will either continue until only the `;` is left or until the two characters around the `;` are no longer identical, which would mean that the strings aren't the reverse of each other. ``` ^; ``` Check whether the first character is `;` and print `0` or `1` accordingly. [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 70 bytes ``` ;=p=sP;=a'';Ws;=a+I|?54=bAs?57bA-111bI||?48b?49b?56bAb''a=sSsF1''O?a p ``` Working with strings is a pain in Knight [Try It Online!](https://tio.run/##lVhpd9s2Fv3eX0GzqUWINC3lOGktmtZxXKfHZxo5E7vNmZGUCAAhiQ1FKlxspyLnr3sewA3U5vRLIgIXb8N9C/wXvscRDd1lfOQHDnuiHo4i5V@@O5vHV2EYhAp7jJnvRIr4WmU54D0OI9bcl86UqA@JH7uL53G3ccjwYkUDP4rDhMZBqGG0iuduZEZBElJm4wx23OXHuRuzaIkp04r9BY7pXDv@pA1H49FwFMF61hvr6Y/DTyN/3NZGfvoCofYxypaMfYHdkMVJ6CuS8GFnnKZ@4nlZLowY1O6glcdiBdvEZI@MahIcWYUIfsS2bdznP3oyxJZ@m1FCwHYNgxrTY/4sniMDD@kYZXEAjrv@bKtVWSbCodz95/3VrT0cW3mo/sRewlZRjGOXKkt@CxpBK2JuhMeaQhTvcQg@dCx8JsQU@i2s67l/1BbrQzw2S1mWO9UoKuyhmeRrFia@CHsYPCg@e8gZkTmMJLMt6zu8E0LMehNwg2RBWLgDV24C7k0QeAz7O4DVblaw6ncIRoi9inh56NZIFiVLLt0Qoj47OMbAtdxRSckWZ4rv@tw2T4rvJmjDjXJBhrGvHjevQGDFBauxT1kwzb2W3Dg8lIwHPua/yihw4VUIipBs8Kfkep1Nd2/HaHhx9N9x@9joVpTHh4f8grlMTb1TuTaUOcliWTkzKZ15IfIzQ5PMi@e1Kwe1rYeHuHFtMxmnyLiDJjDLybxMornGV5GVp8rV4M/rDzeDd1eDO3uVFQlz7TA/XuPAc@4P8dHfn8f8387R6WcIwXoAhFAwNtvHJpeDgE3N@Iij7tQFXB6iHMcDBea6M5/LkTwZ1phxRc3c4B0onsH3gesonQN@P6XlVp2gcl3WJn/4X/zgwVfcyjKl1TCtNWnGXLiAyvhK0f1eeo0cfTOkENAiXTBaJ1WxUXMKO47ElfJ8zRkdS6UDZVCD98KPmvBF4u2Ft5twx72Xvay3@E00LqEU9Q7HcxN441NJ6jH4veuS1Evs@0GsgCq4E4V8U/5mYaCCqYHzD3XXCn/Cz@oD8YkXSPqWwcN@fbX4ND3Q8FkHfZfz7fZ3eM8el4HPSYpjJgxS4gBqo89mwLd7poBxLAQjvR2V5Ey@t5315ryBahC/pv0AGuJ@3kvVuyL@oCipKOc8F9IoIWUF4e12LQdUDtaQuq8zCHmF88@EkgYLMJOJI6ZaBeMfnpKDw9fK6EBzfDY4nELExlLPUVtjBHNcNLodt/to1D02Xgpa8WgAs4hMJNDAh5V8iMFmPtxxsNribYmmaUtt8R@odqkeWnnRA6sWrg9McpSvSQCEYj4NEr7MnJ7yYoWzybaWLuxv5pHR7aA07azVrGJA2FezuBOTAlAo3Cw9HFTrMkO2ZBh6j1yBnmF8NWrtZXyFki8VFovuCqewc/vNpz2c2SH7mrgh09RppCJjxUdksUWkLTp3PefzMgwoizjq7R@Dy7vrm8Ft3ZvfQg3Y15olluQXDJN5JWZIpE4nblqaVS2JV/2eyDo9NdFxzhjG52k@H/MPB@Zj54yWs7FTzsZTW1hklqZwZQfTHXR650Lv9mcKDmfJgg8cL1aO3s0UUKJMuZfQUQlvpBbLAztFmXTHPBAaNYjB1kYKWKJrYwUXZ@P8t48XzCb5b1Ad2XRzdhUHNNM0K1RVWfIqrnLtsRv4mqpXUqvwEKUcOcVRrNuqoag6MXMZVRfX1Y3adEP@YjQ23Ujw14BxKZsWqpSQzdwoZsJFtILQdnmvKh9Ia28JTR2AScoigSGPQKI@Yhp73xToBQqd4xC@YGbxAn8GNcmqCYLHNpE0QmCqziVfbZFk8ALViJQHSK499RiVvzesrTRQB4FyzyVDoUw8h9sqVDgHUCulrOIBR0YVAvW9amjIPi@eZKpqEPtNMp2y0MSeF1ANBnAn4EHCWgcY0YGJ3ADKE3hSIgKGf7GoDq4@QMYxrQtdWOyIl5zJc@ujC4mvjnwVIWpTM/JceCF2DOWonuzLSkNRJlv2Ibes0bqnXgC@nrw8PTl9/fPL09dtsRpi3wkWPGzy@SvVwPY5DxluhLaGtC5aHFIleh7ewioidzcwoF@amUsyp2GwuAQGXAYODJrF2wn1SnPl6zRpgbuI@cwmG/lGGInlpct8qXhcin/l7YnYrvpQ07kdjqr/FoeKgmiyR3e9ikvYg0qBeGs1H0AN5O8VknssG1Imk4z@lXPrvBrfGsEuLYtiJ0hi8yGExg0C8zxHBm7E7KYpqNZaSFNHI/E8LMgGTOvvkF@yESCotxUz4b3xhwkyqplJtkQHivIiUl8Xb7SFbw3njzaQ/F2wDdneQPK@vA15vIEUr4EtyJ82ZQbb7fy0gRRT9xbkWYWsqFIe4RNBdUQ@c777zGzXmf7uM7zkbz1zWJ3RcJnXjb/T9ItjvUbmpc8ewz2ymZGWdCzfNbYFzJZgjdrCn7RpCiql530zkbFZvM@JXeknDeEfK@Er3j2tRtJaaC3dtpL5OhcBTd8@x1uDRTd9/006JIJW222QxiPN4OVf@iwrGC7/SsmFpKmqNqN2WyhwhIry0DOqHNvZ1FyBy1bPx/o@1mGqLE2ADod0qtcm6Q7vxXXD@F9LrnjNpzvgIDplFYGJ5X74Ejrh09NT93XntPvDk2Uv7ei9ZeNWy/oYwf/6ddp/dWKTi6j/6mdycdTtdsl1mvZPfiH9k1PSf/WaXJBWC9vRbfS222rd9LGy/D8) [Test Suite](https://tio.run/##lVhpV9tIFv3c/IpCSWMVEsLOIekBIXwIQ2Y4TUwmkM6ZsZ1Qksq2OnLJ0cLStvqv97ynteQF0nwASXXrbXXfUvzO7ljkhN4s3hOBy/9yfBZF5FfhjSfxeRgGIeEPMRduRLK3eZoDPrAw4s11aU@J@piI2Js@j7uOQ86mcycQURwmThyEKqPzeOJFRhQkocMtlsKKN/s88WIezZjD1WJ9ymJnou5/UfuD4aA/iOB7ejTUFi/6XwZiuKsOxOIlpbv7NJ1x/g1WQx4noSCS8H57uFiIxPfTXJitO1abzn0eE2bZBn/gjirBqVmIwC2WZbEuPhzJEEt6NqLEBttVBmoMn4txPKE66ztDmsYBOO6J8Vqr0jQLB7n574fza6s/NPNQ/cb8hM@jmMWeQ2Z4CqpN57axEh5zBFG8YyH40DbZcSam0G8yTcv9c6zse58NjVKW6Y1Uhxb2OKnkaxomIgt7GNwTwe9zRqQut5Pxmu8bvMuEGPUi4HrJ1ObhBly5CLi3QeBzJjYAq9W0YNUlBCNkfkW8PHRLJIuSGUrXM1FfXRYz4FruqKRkjTPFe71vnSfFexO04kb5QYbx7z6aVyAY8cBqJhwejHKvJTd2diTjgY/5UxkFFF6FoAjJCn9KrtfZdPNuSPune/8b7u7rnYrybGcHDxhlqsqNgtpo6ibTWeXMbenMyyw/U3qb@vGkdmW7tnVnhzWObSzjiIzbbgLTnMyzJJqo@JWaeaqc9367@HjVe3/eu7HmaZEwFy4X8RIHnnO/z/b@@DrE3@29w68QguUAZELB2PQpNnkIAjY145Nt9UYe4PIQ5TgMFJjrjQXKkTzp15hhRc3c4A0ozOC7wHNJexvPp7TcrBNUrsvq7SfxTQT3gniVZaTVMK1124x55gIt4ytF90fpNXC11ZBCQIt0YXSZVMVCzSnmuhJXyv01ZzQmlQ6aQg1@Er7XhE8T/0n4bhPueneyl/USnkTjEEpR71k8MYA3wpGk7oPfmw5JOWNCBDEBVXAmxH4kf/AwUMDUwP2bumuFP7Nn9YH4xA8kfbPg/ml9tfjFYltlx236Q87v7v6A9/xhFggkKYt5ZhCJA6iNgo@Bb3ecgHE8BCP9DZXkWD63jfXmpIFqEL@mfQ8a4tO8l6p3RfxeUVJpznkU0ighZQXBdruUAwqCVao81RkyeYXzz4TSCaZgJs@2GEoVjL@5Sw4OfiujA83x2eAghWyLST1HaQ0pzHHR4Hq426WDzr7@KqMVRgOYZctEAg04rORDDDPy4Q7BSgvbkrNYtJQWPtDapXpoxaIHVk09AUxyyfckAEJx4QQJfubuEXk5Z@ntupae2d/MI73TpotFe6lmFQPCUzULnbgtAIXC1dKDoFqXEfIZZ9B75Ar0DOOrUetJxlco@VDhY9FdYRdzrx@Fc8RSK@TfEy/kqjKKFKrPcUTOlmxpyZl4vvt1FgYOjxD17lPv7Obiqndd9@Z3UAOeas0SS/IDhsm8EtO3pU6XnbQ0q5oSr7pHWdZpC4Pu54zhOE/jfIwvLszH7rFTzsZuORuPrMwiozQFlW2PNtDpvQe9W4wJC8fJFAeOl3NX66QElJARegkd1cZGavI8sCOaSmeMgVAd3db50kgBn5ylsQLFWSx/FmzKLTt/BtWR5azOrtkG1TCMClVVlryKK6g99gKhKloltQqPTcqRM9vKNEvRiaLZRi6j6uKaslKbruzfuRMbXpTxV4dxKR0VqkjIx14U88xFOofQdrBXlRekpbuEqvTAJDJNYMizIVEfmBP7jwR6AXEmLIQ3mFn8QIyhJpk1QdjQsiWNEJiqc8lHWyQZ3EBVW8oDKteeeozK7xvmWhoovYDcoWQolInvoq2ZCncbaqWUVRhwqlchUD4oukqtk@JKpii6bb1NRiMeGsz3A0eFAdwNMEhMbQMj2jCR60B5G66U1AbDv5mOBq7eQ8ZxtQNdOFvJbnIG5tZnDxJfGQiFUsdyjMj34IbY1slePdmXlcahqWzZx9yyRuse@QH4evDq8ODwzS@vDt/sZl9DJtxgimGT958rOrNOMGSsEdoa0jptIaRK9Dy8hVW23N3AgG5pZi7JGIXB9AwYcBa4MGgWdyd6VJorH6fhFLjTGGc22ci3mZFM/nSWfyoul9lvefk2W676UNO5DY4q/8k2FQXR4A/echWXsNuVguyu1bwANZCXFRI9lg0pk0lG/xO5dVKNb41gl5ZFsRsksXEfQuMGgXmeU501YnbVFFRrLaQpg0F2PSzIBkzrbpBfshEg9Ggt5hZ749Yt1auZSbZEA4piEamPCxtt4VvD@b0VJN4L1iF3V5DYl9ch91eQ2W1gDfLnVZnBeju/rCCzqXsN8rhCVlQpt@BEUG2R95xs3jPetKe7eQ@W/LV7dqo9KivzuvF/mm6x7aiReYtnt7EjezUjTWlbvqqvC5glwRq1Ba@0iwWolK73zURmRnE/t61Kv90Q/rkSPsfuaTaS1qRL6baWzBe5CGj61glbGyxn1fd/SZuyoNV263bjkqZj@ZdeywrGyv9SopDFQlGaUbsuFLiZinLTM6pcy13VXIHLVo9jfZdpMFWWJkCHo5qj1SZpLvbiumH82ZIrXvPqDjiITllFYGK567@CTvgX/JjWiLy9vDr7lbyAxMP/c7jQpuEyHU8YTIEBj0QL/sJ4LVwYLYAdsyQmahSQe@jnTMCAEczo1k@mNbMirdUSpsVaLfNzBH@1i0X39YFln0bd17/Yp3udTse@WCy6B/@wuweHdvf1G/vUbrWYFV1H7zqtVpeR2ZZpCfJnZ@vzvy8uz8kxUeFV1UiHCEpJ53W73SYvUGVEcNZIxhPSxutu5@Dw8JAwtDGJwUJc5jDzYgCi3JcJg7twGOAkHQjmk@hxOuVx@Lj10w45O728JCNy9enmw6cbIsgLb0RsmDG@wUeOswtciCLUAyMo16EneDDM1hr@Dw) [Answer] # C, 73 ~~82~~ bytes ``` f(x){int y=0,z=x;for(;x;x/=10)y=y*10+"0100009086"[x%10]-'0';return z==y;} ``` ## Expanded ``` static const char s[] = "0100009086"; int f(int x) { int y=0, z=x; for(; x; x/=10) y = y*10 + s[x%10]-'0'; return z==y; } ``` ## Explanation We reverse the digits of `x` using modulo-10 arithmetic, replacing 6 and 9 by their reflections as we go. We replace the rotationally-asymmetric digits by zeros (note that we can handle symmetric fives and/or twos by simply changing the replacement table `s`). If the new number is equal to the original (saved in 'z'), then it is rotationally symmetric. ## Test program ``` #include <stdio.h> int main() { int i; for(i=0; i <= 16091; ++i) if (f(i)) printf("%d\n", i); } ``` This prints the list of symmetric numbers given in the question. [Answer] # Jelly, ~~16~~ 15 bytes ``` ,ȷ9+90860¤Dị/⁼Ṛ ``` [Try it online!](http://jelly.tryitonline.net/#code=LMi3OSs5MDg2MMKkROG7iy_igbzhuZo&input=&args=NjAwOQ) ### How it works ``` ,ȷ9+90860¤Dị/⁼Ṛ Main link. Argument: n (integer) ¤ Evaluate the three links to the left as a niladic chain: ȷ9 Yield 1000000000. 90860 Yield 90860. + Add to yield 1000090860. , Pair; yield [n, 1000090860]. D Convert both integers to base 10. ị/ Reduce by index, i.e., for each digit of n, retrieve the element of [1, 0, 0, 0, 0, 9, 0, 8, 6, 0] at that index (1-based). Ṛ Yield the digits of n in reversed order. ⁼ Test for equality. ``` [Answer] # Retina, ~~57~~ 49 bytes 8 bytes saved thanks to [@Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner). ``` +`^(([018])(.*)\2|9(.*)6|6(.*)9)$ $3$4$5 ^[018]?$ ``` * Apply reduction as such: `1610880191` -> `61088019` -> `108801` -> `0880` -> `88` -> (empty). * Returns `1` if only `0`, `1`, `8`, or (empty) is left. * Returns `0` otherwise. [Try it online!](http://retina.tryitonline.net/#code=K2BeKChbMDE4XSkoLiopXDJ8OSguKik2fDYoLiopOSkkCiQzJDQkNQpeWzAxOF0_JApZClxkKwpO&input=MTYxMDg4MDE5MQ) [Answer] # TSQL, 122 bytes I am new to code golf, so not quite sure how to count the characters. Counting it as 1 here since the number used in this case is 8 This will return 1 when the reversed value match and nothing when it doesn't match: ``` SELECT 1FROM(values(8))x(x)WHERE(x)NOT like'%[23457]%'and REPLACE(REPLACE(x,6,4),9,6)=REVERSE(REPLACE(REPLACE(x,9,4),9,6)) ``` Human readable: ``` SELECT 1 FROM (values(808))x(x) WHERE(x) NOT like'%[23457]%' and REPLACE(REPLACE(x,6,4),9,6)=REVERSE(REPLACE(REPLACE(x,9,4),9,6)) ``` [Answer] # GNU sed, 84 bytes (including +1 for `-r` flag) ``` : s/^6(.*)9$/\1/ s/^9(.*)6$/\1/ s/^([081])(.*)\1$/\2/ t s/^[081]$// s/.+/0/ s/^$/1/ ``` If the line ends with a rotation of its beginning character, trim both ends by one. Repeat until there's no match. Account for a single symmetric character, then if anything remains, the input was not symmetric, and we return false; otherwise return true. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes ``` #~ContainsNone~{2,3,4,5,7}&&Reverse@#==(#/.{6->9,9->6})& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOOT@vJDEzr9gvPy@1rtpIx1jHRMdUx7xWTS0otSy1qDjVQdnWVkNZX6/aTNfOUsdS186sVlPtf5qDZ15JanpqkUtmemZJsYOymr5DUGJeeqqDoYGBvn5AUWZeyX8A "Wolfram Language (Mathematica) – Try It Online") Takes input as a list of digits. ## Explanation: --- `#~ContainsNone~{2,3,4,5,7}` Check if the input contains no unflippable digits `&&Reverse@#` and that the reverse of the input `==(#` is equal to the input `/.{6->9,9->6})&` where all 6s are replaced with 9s and 9s with 6s. [Answer] # [Julia](https://julialang.org) ## 47 bytes The first attack. ``` !x=10(d=digits(x))+reverse(d)⊆[0,11,88,69,96] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LZA9TgMxEIVFg8SewokodkUQ44KRB2SJe6AUkdYhi1CQvF5kLkDBFWhCkUORMidhfrZ5Hv-87z355_g6vQ2bw-nisuSp7D7jM6ycX7nAygsSjzwT8h68HIoEuQK-Qy8S5BXws-BF1ADsIC8S1DubRZGUIRBPqChjKQxJkcJE0nwwtLKRLEGUUIMsSaOQNFASidByNRisPASrAX5uo0uwVkB-_XicyvY2_N0tavTQ9rEfXoYytrXrbnL6SHlMbd-dv7_4m9jFNbgh4Xq23W_fs2Png9Kaq6fNOKZc3KK6GF1b3bB39s-dW9Z4XZdN2vdmPvw2NvwD) ## 39 bytes Using `@b_str` it can be golfed further as proposed by @MarcMush and @Deadcode: [Attempt It Online!](https://ato.pxeger.com/run?1=LZBBTgMxDEVhg9Q5RTqqxIwokrPAiqkiOAI7FohFq0lhECpSJlOFC7DgCmzKooeCJSchtmfz7ST-71v5Or6Mr_368Ht6luKYnt_9AyyNXRpXtBSk0paesJzB8iWL4ycob2hZHE9BGXOWRQxQHGRZnHgnMyuSMBhiCQWlLIEhCZKZSJIPihY2kiawEkqQJkkUkgRyIhFqrgSDLg9O1wA7bSPF6VZA9nF1HNP20v2cz7OnpvNd_9SnocltexHDPsQhNF379_mxqU-qu5v7ehq_2r5Fk729Fko1u10PQ4jJzLPx3jTZ9Duj_9uaOvtFrquw69R8-K60-Qc) [Answer] # Pure bash, 99 bytes Using `shopt -s extglob`: ``` o=;for i in ${1//*()/ };do o=${i//6/_}$o;done; o=${o//9/6} o=${o//_/9} [[ ${o//[23457]} == "$1" ]] ``` There are 98 bytes +1 for *extglob* -> 99 bytes. ## Without extglob, 101 bytes ``` o=;for((i=${#1};i--;)){ o+=${1:i:1};};o=${o//6/_} o=${o//9/6} o=${o//_/9} [[ $1 == "${o//[23457]}" ]] ``` Sample: ``` rotatable() { o=;for i in ${1//*()/ };do o=${i//6/_}$o;done; o=${o//9/6} o=${o//_/9} [[ ${o//[23457]} == "$1" ]] } for((x=0;x<10000;x++)){ rotatable $x&&echo $x;}|column 0 69 111 689 906 1111 6009 6969 8888 9696 1 88 181 808 916 1691 6119 8008 8968 9886 8 96 609 818 986 1881 6699 8118 9006 9966 11 101 619 888 1001 1961 6889 8698 9116 ``` [Answer] # Perl, ~~29~~ 26 bytes Includes +1 for `-p` Run with the input on STDIN: ``` rotation.pl <<< 69 ``` `rotation.pl`: ``` #!/usr/bin/perl -p $_=reverse==y/962-7/69a/r ``` [Answer] # MATL, ~~25~~ ~~21~~ 22 bytes ``` j69801VmAGtP69VtPXE=vA ``` [**Try it Online!**](http://matl.tryitonline.net/#code=ajY5ODAxVm1BR3RQNjlWdFBYRT12QQ&input=MTYwOTE) **Explanation** ``` j % Explicitly grab input as string 69801 % Number literal V % Convert to a string mA % Check if all input chars are members of this list G % Explicitly grab the input tP % Duplicate and flip it 69 % Number literal V % Convert to string ('69') tP % Duplicate and flip it ('96') XE % Replace all '6' with '9', and '9' with '6' = % Check that this substituted string is equal to the original v % Vertically concatenate all items on the stack A % Ensure everything is true % Implicitly print boolean result ``` [Answer] # Pyth, 17 bytes ``` !-FmC_B`d,QC\􄽥 ``` Test it in the [Pyth Compiler](https://pyth.herokuapp.com/?code=%21-FmC_B%60d%2CQC%5C%F4%84%BD%A5&input=6009&debug=0). ### How it works ``` !-FmC_B`d,QC\􄽥 (implicit) Store the input in Q. \􄽥 Yield the Unicode character with code point 1068901. C Compute its code point. ,Q Pair the input and 1068901. m Map; for each d in [Q, 1068901]: `d Yield the string representation of d. _B Yield the pair of `d` and `d` reversed. C Zip. For the second string, this gives ['11', '00', '69', '88', '96', '00', '11']. -F Fold by difference, i.e., removes all pairs in the second list from the first list. ! Logically negate the result, returning True iff the list is empty. ``` [Answer] ## Visual Basic for Applications, ~~150~~ 111 bytes Usable in console or as an UDF. ``` Function c(b) c=(Not b Like"*[!01869]*")And b=Replace(Replace(Replace(StrReverse(b),9,7),6,9),7,6) End Function ``` Improved by taking advantage of implicit type conversions and by doing three steps swapping instead of two steps on each side of the equation. Count includes `Function` and `End Function` statements. [Answer] # [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ê±°";╙ñ♀C¼EE^☼ùΣ ``` [Run and debug it](https://staxlang.xyz/#p=88f1f8223bd3a40c43ac45455e0f97e4&i=7%0A69&m=2) [Answer] # AWK, ~~85~~ ~~84~~ ~~82~~ 80 bytes ``` {n=split($1,a,s="");for(;n;){b=a[n--];s=s (b~/[2-57]/?9:b~6?9:b~9?6:b)}$1=s~$1}1 ``` This feels like brute-forcing, but awk has very limited tools, mostly aimed to text processing. This code allows multiple inputs. ``` { n=split($1,a,s=""); # this splits $1 (the input) into the array _a_ # using an empty string as token. each element of the # array is a digit of the input number. # also, sets the number of elements to _n_, # and sets the empty string to _s_. for(; n; # loops until n==0 (evaluates to false) ){ b=a[n--]; # sets the _n_ element of the array to _b_. this will save bytes later # immediately after, decrements _n_ by 1 (one less byte here) # here the magic happens: s=s ( # this appends a chaining conditional to the variable _s_ b~/[2-57]/?9: # if _b_ equals 2, 3, 4, 5 or 7, returns 9 (dummy number) b~6?9: # otherwise, if _b_ equals 6, returns 9 b~9?6: # otherwise, if _b_ equals 9, returns 6 b # otherwise, returns its value ) } $1=s~$1 # evaluates if _s_ matches $1, and sets this boolean to $1 } 1 # prints $1. ``` [Try it online!](https://tio.run/##LYvBCoMwEETv@xVFPERQzNq6uobgh4iH5FAoLbE0hR5Efz2NaWdgGIY35nMPYXXaPx@3t8ixNKXXWVao6/ISyqlitdpMrqpm5bU/CbvXU1O13VyPPNidUvJIgy22HLXfc9wwBIQeJBADU0yMBaVEICJmhj4pTn9DA2e4QAvdQcRPwmXi8CDj8vMX "AWK – Try It Online") --- # AWK, 78 bytes This is almost the same as above, but without the `s` variable. Two less bytes, with the effect of allowing only one input. ``` {n=split($1,a,"");for(;n;){b=a[n--];s=s (b~/[2-57]/?9:b~6?9:b~9?6:b)}$1=s~$1}1 ``` [Try it online!](https://tio.run/##SyzP/v@/Os@2uCAns0RDxVAnUUdJSdM6Lb9IwzrPWrM6yTYxOk9XN9a62LZYQSOpTj/aSNfUPFbf3tIqqc4MTFram1kladaqGNoW16kY1hr@/29haGZmZmlpaWgBAA "AWK – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 45 bytes ``` !x=prod(d->"01....9.86"[1+d],digits(x))=="$x" ``` [Try it online!](https://tio.run/##DcrbCkBAEADQd18xNolcmn0Rav2IJDVopKVFzd@vPc/n@E5etHgfi7ndRRlVg0JdB13dNmrUBU0l8c7vk0meG6MSUX67HAiwBew14oyIEQSxQJrC7di@pw09Wi35Hw "Julia 1.0 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` »\Π»F∑69S*Ṙ= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu1xczqDCu0biiJE2OVMq4bmYPSIsIiIsIlwiOTA4MDZcIiJd) ``` F∑ # Remove elements of... »\Π» # 23457 * # Ring translate by... 69S # "69" Ṙ= # Does it, reversed, equal the input? ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` n=>!(e=[...''+n]).some(c=>'0x'+'01aaaa9a86'[c]-e.pop()) ``` [Try it online!](https://tio.run/##FcdBCsMgEADAe3/RS9ZFsphLaTHmIyEHsWuxpK7EUvJ7k85t3v7na9hS@fZZntyia9lNV8VuJiIAnRekKh9WwU1gdtBgBn96@PsN5rD0TEWKQmz2EmVTyRmbxsH8Wa0TRpWw64LkKivTKq/z7QA "JavaScript (Node.js) – Try It Online") Half test of `n=>![...''+n].some((c,i,e)=>'0100009086'[c]-e.slice(~i)[0])` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 58 bytes ``` n=>$"{n}".Aggregate("",(z,c)=>"01----9-86"[c-48]+z)==n+""; ``` [Try it online!](https://tio.run/##ZU9Na4QwED2bXzENe1D8IEKRWDdCKfTUew/LHmw2kaAkRbNtWclvt5OFnprDm6/33mTkWsrV7K9XK@ForC/gw7m5Bw0Cdiv6A91soNXzOC5qHLxKKS3SWyEz0VNWl/jakjf0JMtHfs5vmRA2p7Tbv4YF3IQmfrmqjsRS/Xwq6dUFm1Z9w@kMGyugLoAjYmhaTDFvG6xZHZsReBwxnDV1BB5ZDGm8jnAXMFS0dQTehI5ot0CKt4DBVazDcERDhlmem4xsJDEa0r/vVC/O@sHYNTUZPAjQGDOSICvByepmVb0vxqs3Y1V6oHows7o8wWYCzTok3a/Uw7zimUkggURzN933/DegboqysP8C "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [PHP](https://php.net/), 49 bytes (anonymous function) ``` fn($s)=>$s==strrev(strtr($s,"6923457","9600000")) ``` [Try it online!](https://tio.run/##LU89a8MwEP0rQmjQYRlkN00x8iVLli5dms3NUleKA0IWlhNCSn67ezK94b7fe3dxiEu7j0NkwuHighQJcCcSYpqnyd4khXmiruLbpn7ZvL5xxZutzsYBFuNGmj5QG@HRne2c5Ofx8P4BBn4vTgrfEYG3xOuhrE6I/CtwoN10/U6Z2Cutygoy3N6jH3@s5CVXtG4I34/XMGdsWxOoIwLy@mTYKhv@KxFaXKeUFQWwi2NSkHgAYOsVD7D9MGZpQ7dWhuWSiWCez0WX9frNHw "PHP – Try It Online") The `strtr` translates `6` to `9`, `9` to `6`, and all non-symmetric digits to `0` (any character other than themselves would work). The digits `0`, `1`, and `8` are left unchanged. (The order I put them in is purely a stylistic choice; I don't think it even makes a difference in speed.) Then `strrev` reverses this result, which is then compared with the original string; if they're equal, it has rotational symmetry. # [PHP](https://php.net/) `-F`, 51 bytes (full program) ``` <?=$argn==strrev(strtr($argn,"6923457","9600000")); ``` [Try it online!](https://tio.run/##LUxBCsIwELzvK8LioYUWum2TJtTYm6/wIlKMlySkwSf4AJ/oQ4xJcQ4zw8ww3vh0XLzxbL0Zxw7XcLcNss/rzZAtp9zpPdN6iyGszypLDNV/J1Q/jHzCBpXoCrCu57Q/4cXinDog6GGAETgImECCAsohQd6rQlSYiqfilSSSIgvnUnydjw9nt9Sefw "PHP – Try It Online") [Answer] # Pyth - 21 bytes ``` &!-z+`180K`69qzX_z_KK ``` [Test Suite](http://pyth.herokuapp.com/?code=%26%21-z%2B%60180K%6069qzX_z_KK&test_suite=1&test_suite_input=619%0A2%0A108%0A111&debug=0). ]
[Question] [ The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism! ## The Challenge When people use the term "average," they generally mean the arithmetic mean, which is the sum of the numbers divided by the number of numbers. There are, however, many more meanings to the word "mean," including the [harmonic mean](http://en.wikipedia.org/wiki/Harmonic_mean), the [geometric mean](http://en.wikipedia.org/wiki/Geometric_mean), the [arithmetic mean](http://en.wikipedia.org/wiki/Arithmetic_mean), the [quadratic mean](http://en.wikipedia.org/wiki/Root_mean_square), and the [contraharmonic mean](http://en.wikipedia.org/wiki/Contraharmonic_mean). Your challenge is to write a program which inputs a list of numbers and outputs those 5 different means. Additionally, you are trying to write programs in **as many languages as possible**. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase. ## Input Input will be a list of positive numbers. ``` 1,2,3,4,5 1.7,17.3,3.14,24,2.718,1.618 8.6 3,123456 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602 3,4,4,6.2,6.2,6.2 ``` ## Output Output will be the five means in the order listed above (harmonic, geometric, arithmetic, quadratic, contraharmonic). Conveniently, this is the same as increasing order. ``` 2.18978,2.6052,3,3.31662,3.66667 3.01183,4.62179,8.41267,12.2341,17.7915 8.6,8.6,8.6,8.6,8.6 5.99985,608.579,61729.5,87296.6,123453. 5.95799,14.3041,22.5453,27.9395,34.6243 4.5551,4.74682,4.93333,5.10425,5.28108 ``` There will be some reasonable leniency in I/O format, but I do want several decimal places of accuracy. Since I want floating-point output, you can assume floating-point input. # The Objective Winning Criterion As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language. If there is a tie, the winner would be the person with the most second-place submissions (and so on). ## Rules, Restrictions, and Notes Your program can be written in any language that existed prior to September 2th, 2014. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them. Please keep all of your different submissions contained within a single answer. Also, no shenanigans with basically the same answer in a slightly different language dialects. I will be the judge as to what submissions are different enough. --- # Current Leaderboard This section will be periodically updated to show the number of languages and who is leading in each. * Algoid (337) - Beta Decay * APL (42) - algorithmshark * Awk (78) - Dennis * BBC BASIC (155) - Beta Decay * C (136) - Dennis * C++ (195) - Zeta * C# (197) - Martin Büttner * CJam (43) - Dennis * Clojure (324) - Michael Easter * Cobra (132) - Ourous * CoffeeScript (155) - Martin Büttner * Commodore BASIC (104) - Mark * Common Lisp (183) - DLosc * Erlang (401) - Mark * Fortran (242) - Kyle Kanos * Fortran 77 (286) - Beta Decay * GNU bc (78) - Dennis * GolfScript (83) - Dennis * Groovy (157) - Michael Easter * Haskell (140) - Zeta * J (28) - algorithmshark * Java (235) - Michael Easter * JavaScript (ES6) (112) - Dennis * JRuby (538) - Michael Easter * Julia (79) - Martin Büttner * Lua (113) - AndoDaan * Mathematica (65) - Martin Büttner * Matlab (63) - Martin Büttner * Octave (68) - Dennis * Openscript (849?) - COTO * Pascal (172) - Mark * Perl (76) - Grimy * PHP (135) - Dennis * POV-Ray 3.7 (304) - Mark * Prolog (235) - DLosc * Pyth (52) - Dennis * Python 2 (96) - Dennis * Python 3 (103) - DLosc * Q (53) - algorithmshark * Q'Nial (68) - algorithmshark * QBasic (96) - DLosc * R (91) - plannapus * Ruby (118) - Martin Büttner * Rust (469) - Vi. * Scala (230) - Michael Easter * T-SQL (122) - MickyT * TI-Basic (85) - Ypnypn * TypeScript (393) - rink.attendant.6 * VBA (Excel) (387) - Stretch Maniac * wxMaxima (134) - Kyle Kanos --- # Current User Rankings 1. Dennis (10) 2. Martin Büttner (6) 3. Michael Easter (5) 4. Mark, DLosc, algorithmshark (4) 5. Beta Decay (3) 6. Zeta, Kyle Kanos (2) 7. Ourous, AndoDaan, COTO, Grimy, plannapus, Vi., MickyT, Ypnypn, rink.attendant.6, Stretch Maniac (1) (If I made a mistake in the above rankings, let me know and I'll fix it. Also, the tiebreaker has not been applied yet.) [Answer] # Languages: 1 ### Openscript (many hundreds) (My favourite obscure and sadly defunct programming language, because I learned to program on it many years ago. ;) ``` openFile "inputs.txt" readFile "inputs.txt" to EOF put it into my input_string closeFile "inputs.txt" local inputs[] fill the inputs with my input_string in [item] order put 0 into the harmonic_mean put 0 into the geometric_mean put 0 into the arithmetic_mean put 0 into the quadratic_mean put the length of the inputs into n step i from 1 to n get inputs[i] increment the harmonic_mean by 1/it increment the geometric_mean by log( it ) increment the arithmetic_mean by it increment the quadratic_mean by it*it end get "outputs.txt" createFile it writeFile n/harmonic_mean & "," to it writeFile exp( geometric_mean/n ) & "," to it writeFile arithmetic_mean/n & "," to it writeFile sqrt( quadratic_mean/n ) & "," to it writeFile quadratic_mean/arithmetic_mean to it closeFile it ``` [Answer] # Languages: 13 I think this list should now contain every programming language that I know sufficiently well to solve at least simple problems in. I'll try to keep this list complete over time as I look into some new languages. (I *used* to know some Smalltalk and Delphi, but I'd have to look up to much for adding them to feel right.) ## C, ~~196~~ ~~190~~ ~~171~~ 165 bytes ``` main(int c,char**v){float n=c-1,x,h,g=1,q,a=h=q=0;for(;c-1;h+=1/x,g*=pow(x,1/n),a+=x/n,q+=x*x/n)sscanf(v[--c],"%f",&x);printf("%f,%f,%f,%f,%f",n/h,g,a,sqrt(q),q/a);} ``` Reads the input as individual command line arguments and writes a comma-separated list of the means to STDOUT. Thanks for some improvements to Quentin. ## C++, 200 bytes This is the same as the above C code, plus two includes. I'm including this because it's longer than the winning C++ submission, so I guess no harm is done, and I'd like this post to actually contain every language I know. :) ``` #include <cmath> #include <cstdio> main(int c,char**v){float n=c-1,x,h,g=1,q,a=h=q=0;for(;c-1;h+=1/x,g*=pow(x,1/n),a+=x/n,q+=x*x/n)sscanf(v[--c],"%f",&x);printf("%f,%f,%f,%f,%f",n/h,g,a,sqrt(q),q/a);} ``` ## C#, ~~220~~ 197 bytes ``` namespace System{using Linq;class F{double[]f(double[]l){double n=l.Length,a=l.Sum()/n,q=l.Sum(x=>x*x)/n;return new[]{n/l.Sum(x=>1/x),l.Aggregate((p,x)=>p*Math.Pow(x,1.0/n)),a,Math.Sqrt(q),q/a};}}} ``` Defines a function in a class taking a `List` of doubles and returning an array of doubles with the five means. Thanks for some improvements to Visual Melon and Bob. ## CJam, 52 bytes ``` ea_,:L;:d_Wf#:+L\/\_:*1Ld/#\_:+L/:A\2f#:+L/:QmqQA/]p ``` Takes the input as command-line arguments and prints a list with the five values to STDOUT. ## CoffeeScript, 155 bytes This is almost the same as the JavaScript solution further down (and initially I didn't count it for that reason), but the OP included it in the scoreboard anyway, so I promoted it to a full submission. They *are* technically different languages after all. ``` f=(l)->l.r=l.reduce;n=l.length;[n/l.r(((s,x)->s+1/x),0),Math.pow(l.r(((p,x)->p*x),1),1/n),a=l.r(((s,x)->s+x),0)/n,Math.sqrt(q=l.r(((s,x)->s+x*x),0)/n),q/a] ``` ## JavaScript (ES6), ~~155~~ 153 bytes ``` f=l=>{l.r=l.reduce;n=l.length;return[n/l.r((s,x)=>s+1/x,0),Math.pow(l.r((p,x)=>p*x,1),1/n),a=l.r((s,x)=>s+x,0)/n,Math.sqrt(q=l.r((s,x)=>s+x*x,0)/n),q/a]} ``` Defines a function taking a array of numbers and returning a array with the five means. Thanks for some improvements to William Barbosa. ## Julia, 79 bytes ``` f(l)=(n=length(l);[n/sum(1/l),prod(l)^(1/n),a=mean(l),q=norm(l)/sqrt(n),q*q/a]) ``` Defines a function taking a list of numbers and returning a list with the five means. ## Lua, 120 bytes ``` f=function(l)h=0;q=0;a=0;g=1;for i=1,#l do x=l[i]h=h+1/x;a=a+x/#l;g=g*x^(1/#l)q=q+x*x/#l end;return#l/h,g,a,q^.5,q/a end ``` Defines a function taking a list of numbers and returning 5 separate values for the means. ## Mathematica, ~~73~~ ~~67~~ 65 bytes ``` f[l_]:={1/(m=Mean)[1/l],GeometricMean@l,a=m@l,Sqrt[q=m[l*l]],q/a} ``` Defines a function taking a list of floating point numbers and returning a list with the five means. *Fun fact:* Mathematica has all 5 means built in (and that was my original submission), but three of them can be implemented in fewer characters than their function names. ## Matlab, ~~65~~ 63 bytes ``` l=input('');a=mean(l);q=rms(l);harmmean(l) geomean(l) a q q*q/a ``` Requests the input as an array of numbers from the user and outputs the five means individually. Thanks for some improvements to Dennis Jaheruddin. ## PHP ≥ 5.4, ~~152~~ ~~149~~ 143 bytes ``` function f($l){$g=1;$n=count($l);foreach($l as$x){$q+=$x*$x/$n;$h+=1/$x;$g*=pow($x,1/$n);}return[$n/$h,$g,$a=array_sum($l)/$n,sqrt($q),$q/$a];} ``` Same functional implementation as the earlier ones. Thanks for some improvements to Ismael Miguel. ## Python 2, 127 bytes ``` def f(l):n=len(l);a=sum(l)/n;q=sum(x*x for x in l)/n;return[n/sum(1/x for x in l),reduce(lambda x,y:x*y,l)**(1./n),a,q**.5,q/a] ``` Same functional implementation as the earlier ones. ## Ruby, ~~129~~ 118 bytes ``` f=->l{n=l.size r=->l{l.reduce :+} [n/r[l.map{|x|1/x}],l.reduce(:*)**(1.0/n),a=r[l]/n,(q=r[l.map{|x|x*x}]/n)**0.5,q/a]} ``` Same functional implementation as the earlier ones. [Answer] # 4 languages ## J - ~~32~~ 28 char! A function taking the list of numbers as its sole argument. ``` %a,^.a,[a(,,]%%)*:a=.+/%#&.: ``` `a` here is an adverb, which is J's take on second-order functions. * `+/ % #` is a train in J, meaning Sum Divided-by Count, the definition of the arithmetic mean. * `&.:` is a conjunction called Under, where `u&.:v(y)` is equivalent to `vi(u(v(y)))` and `vi` is the functional inverse of `v`. Yes, *J can take functional inverses*. * Finally, a useful feature of J is that certain functions can automatically loop over lists, because J knows to apply them pointwise if it wouldn't make sense to apply them on the whole argument. So the square of a list is a list of the squares, for instance. Thus `a` takes a function on the left, and returns a mean that "adjusts" the values by the function, takes the arithmetic mean, and then reverses the adjustment afterwards. * `%a` is the harmonic mean, because `%` means Reciprocal, and is its own inverse. * `^.a` is the geometric mean, because `^.` is the natural logarithm and its inverse is the exponential. `(Π x)^(1/n) = exp(Σ log(x)/n)` * `[a` is the arithmetic mean, because `[` is the identity function. * `*:a` is the quadratic mean, because `*:` is Square, and its inverse is the square root. * The contraharmonic gives us a whole host of trouble—mean of the squares divided by mean—so we do a little math to get it: (`*:a` divided by (`[a` divided by `*:a`)). This looks like `[a(]%%)*:a`. While we're at it, we prepend each of the means, `[a(,,]*%~)*:a`. Finally, we use commas to append the rest of the results together. We require no further parens because concatenation is (in this case at least) associative. In use at the J REPL: ``` (%a,^.a,[a(,,]%%)*:a=.+/%#&.:) 1,2,3,4,5 NB. used inline 2.18978 2.60517 3 3.31662 3.66667 f =: %a,^.a,[a(,,]%%)*:a=.+/%#&.: NB. named f 1.7,17.3,3.14,24,2.718,1.618 3.01183 4.62179 8.41267 12.2341 17.7915 f 8.6 8.6 8.6 8.6 8.6 8.6 f 3,123456 5.99985 608.579 61729.5 87296.6 123453 f 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602 5.95799 14.3041 22.5453 27.9395 34.6243 f 3,4,4,6.2,6.2,6.2 4.5551 4.74682 4.93333 5.10425 5.28108 ``` ## Q - 53 char Single argument function. We just make a list of all the means we want. ``` {s:(a:avg)x*x;(1%a@1%x;exp a log x;a x;sqrt s;s%a x)} ``` The same thing in other versions of k is below. * k4, 51 char: `{s:(a:avg)x*x;(%a@%x;exp a log x;a x;sqrt s;s%a x)}` * k2, 54 char: `{s:(a:{(+/x)%#x})x*x;(%a@%x;(*/x)^%#x;a x;s^.5;s%a x)}` ## APL - 42 char Function taking list as argument. ``` {(÷M÷⍵)(*M⍟⍵)A(S*.5),(S←M⍵*2)÷A←(M←+/÷≢)⍵} ``` Explained by explosion: ``` { } ⍝ function with argument ⍵ +/÷≢ ⍝ Sum Divide Length, aka mean M← ⍝ assign function to M for Mean A←(M )⍵ ⍝ arithmetic Mean, assign to A (S←M⍵*2) ⍝ Mean of squares, assign to S S ÷A ⍝ S divide A, aka contraharmonic mean (S*.5) ⍝ sqrt(S), aka quadratic mean/RMS , ⍝ concatenate into a list A ⍝ prepend A (APL autoprepends to lists) *M⍟⍵ ⍝ exp of Mean of logs, aka geometric ( ) ⍝ prepend (auto) ÷M÷⍵ ⍝ recip of Mean of recips, aka harmonic ( ) ⍝ prepend (auto) ``` ## Q'Nial - 68 char You're going to love this one. ``` op\{$is/[+,tally];^is$*[pass,pass];[1/$(1/),exp$ln,$,sqrt^,/[^,$]]\} ``` Q'Nial is another array-oriented language, an implementation of [Nial](http://www.nial.com/AboutNial.html), which is based on an obscure Array Theory in the sam way Haskell is based on category theory. (Get it [here](http://www.nial.com/OpenSource.html).) It's very different from any of the other three—it parses left-to-right, first of all!—but it is still more related to them than to any other languages. [Answer] # 12 languages --- ## CJam, ~~45~~ ~~44~~ 43 bytes ``` q~:Q,:LQWf#:+/Q:*LW##Q:+L/_Q2f#:+L/_mq\@/]` ``` Reads an array of floats (e.g., `[1.0 2.0 3.0 4.0 5.0]`) from STDIN. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") --- ## APL, ~~67~~ ~~61~~ ~~53~~ ~~52~~ 50 bytes ``` {(N÷+/÷⍵)(×/⍵*÷N)A(Q*÷2),(Q←+/(⍵*2)÷N)÷A←+/⍵÷N←⍴⍵} ``` [Try it online.](http://ngn.github.io/apl/web/index.html#code=%7B%28N%F7+/%F7%u2375%29%28%D7/%u2375*%F7N%29A%28Q*%F72%29%2C%28Q%u2190+/%28%u2375*2%29%F7N%29%F7A%u2190+/%u2375%F7N%u2190%u2374%u2375%7D%201%202%203%204%205 "ngn/apl demo") --- ## Pyth, ~~55~~ 52 bytes ``` JyzKlJ=YcsJK=Zcsm^d2JK(cKsmc1kJ ^u*GHJc1K Y ^Z.5 cZY ``` Reads space-separated numbers (e.g., `1 2 3 4 5`) from STDIN. --- ## Octave, 68 bytes ``` #!/usr/bin/octave -qf [mean(I=input(''),"h") mean(I,"g") a=mean(I) q=mean(I.*I)**.5 q*q/a] ``` Not counting the shebang. Reads an array (e.g., `[1 2 3 4 5]`) from STDIN. --- ## GNU bc, 78 bytes ``` #!/usr/bin/bc -l while(i=read()){h+=1/i;g+=l(i);a+=i;q+=i*i;n+=1} n/h;e(g/n);a/n;sqrt(q/n);q/a ``` Counting the shebang as 1 byte (`-l` switch). Reads whitespace separated floats from STDIN, followed by a zero. --- ## Awk, 78 bytes ``` #!/usr/bin/awk -f {h+=1/$0;g+=log($0);a+=$0;q+=$0^2;n++}END{print n/h,exp(g/n),a/n,(q/n)^.5,q/a} ``` Not counting the shebang. Reads one number per line from STDIN. --- ## GolfScript, ~~86~~ 83 bytes ``` n%{~.2.-1:$??./*\`,10\?/\+\;}%..,:^0@{$?+}//p.{*}*^$??p.{+}*^/.p\0\{.*+}/^/.2$??p\/ ``` GolfScript has no built-in support for floats, so the code is parsing them. Therefore, the input format is rather restrictive: you must input `1.0` and `0.1` rather than `1`, `1.` or `.1`. Reads floats (as explained above) one by line, from STDIN. [Try it online.](http://golfscript.apphb.com/?c=IjAuMQogMC4yCiAwLjMKIDAuNAogMC41IiAjIFNpbXVsYXRpbmcgaW5wdXQgZnJvbSBTVERJTi4KCm4leyIuIiV%2BLn4yLi0xOiQ%2FPy4vKlwsMTBcPy9cfit9JS4uLDpeMEB7JD8rfS8vcC57Kn0qXiQ%2FP3Aueyt9Kl4vLnBcMFx7LiorfS9eLy4yJD8%2FcFwv "Web GolfScript") --- ## Perl, ~~90~~ 85 bytes ``` #!/usr/bin/perl -n $h+=1/$_;$g+=log;$a+=$_;$q+=$_**2}{$,=$";print$./$h,exp$g/$.,$a/$.,($q/$.)**.5,$q/$a ``` Counting the shebang as 1 byte (`-n` switch). Reads one number per line from STDIN. --- ## Python 2, ~~102~~ 96 bytes ``` #!/usr/bin/python h=a=q=n=0;g=1 for i in input():h+=1/i;g*=i;a+=i;q+=i*i;n+=1 print n/h,g**n**-1,a/n,(q/n)**.5,q/a ``` Not counting the shebang. Reads a list of floats (e.g., `1.0,2.0,3.0,4.0,5.0`) from STDIN. --- ## ECMAScript 6 (JavaScript), ~~114~~ 112 bytes ``` m=I=>{for(g=1,h=a=q=n=0,p=Math.pow;i=I.pop();h+=1/i,g*=i,a+=i,q+=i*i)n++; return[n/h,p(g,1/n),a/n,p(q/n,.5),q/a]} ``` Not counting the LF. Expects an array (e.g., `[1,2,3,4,5]`) as argument. --- ## PHP, 135 (or 108?) bytes ``` #!/usr/bin/php <?for($c=1;$c<$argc;$c++){$i=$argv[$c];$h+=1/$i;$g+=log($i);$a+=$i;$q+=$i*$i;$n++;} print_r([$n/$h,exp($g/$n),$a/$n,sqrt($q/$n),$q/$a]); ``` Not counting shebang or LF. Reads floats as command-line arguments. I have a shorter solution, but I don't know how to count the bytes: ``` php -R '$i=$argn;$h+=1/$i;$g+=log($i);$a+=$argn;$q+=$i^2;$n++;' \ -E 'print_r([$n/$h,exp($g/$n),$a/$n,sqrt($q/$n),$q/$a]);' ``` Counting the bytes in each code string and adding two for `-R` and `-E`, this approach would score 108. --- ## C, ~~172~~ ~~140~~ ~~139~~ ~~137~~ 136 bytes ``` float i,h,g=1,a,q,n;main(){for(;scanf("%f",&i)+1;n++)h+=1/i,g*=i,a+=i,q+=i*i; printf("%f %f %f %f %f",n/h,pow(g,1/n),a/n,sqrt(q/n),q/a);} ``` Not counting the LF. Compile with `gcc -lm`. Reads whitespace separated floats from STDIN. [Answer] # J (50): This is the sort of thing J is good at: ``` (#%+/@:%),(#%:*/),(+/%#),%:@(%@#*+/@:*:),+/@:*:%+/ ``` As always: an explosion in the smiley factory. However, some of the smileys were left intact this time around: `:)` and `:*:` (that's a guy with four eyes and a gem embeded in his face) My interactive session that was used to create this: <http://pastebin.com/gk0ksn2b> ## In action: ``` f=:(#%+/@:%),(#%:*/),(+/%#),%:@(%@#*+/@:*:),+/@:*:%+/ f 1,2,3,4,5 2.18978 2.60517 3 3.31662 3.66667 f 1.7,17.3,3.14,24,2.718,1.618 3.01183 4.62179 8.41267 12.2341 17.7915 f 8.6 8.6 8.6 8.6 8.6 8.6 f 3,123456 5.99985 608.579 61729.5 87296.6 123453 f 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602 5.95799 14.3041 22.5453 27.9395 34.6243 f 3,4,4,6.2,6.2,6.2 4.5551 4.74682 4.93333 5.10425 5.28108 ``` ## Explanation: As you might expect, there are actually 5 functions that are bundled into a list with a train of forks and hooks. (Don't worry about it, it's just a convenient way of making multiple functions output to a single list). The lines that I used to make J generate this answer might be a bit clearer: ``` f=:harmonic , Geometric , arithmatic , rms , contraharmonic f harmonic , Geometric , arithmatic , rms , contraharmonic f f. (# % +/@:%) , (# %: */) , (+/ % #) , %:@(%@# * +/@:*:) , +/ %~ +/@:*: ``` Let's look at them separately. ### Harmonic ``` (# % +/@:%) ``` * `#` - Length (of the array) * `%` - Divided by * `+/@:%` - The sum (`+/`, or fold `+` in the array (`+/1 2 3 4` == `1+2+3+4`)) atop divide, but this time in the monadic case. What this means here, is that J automatically "guesses" that 1 would be the most useful value. ### Geometric ``` (# %: */) ``` * `#` - Length (of the array) * `%:` - Root (`4 %: 7` would mean 'the fourth (or tesseract) root of seven) * `*/` - Product (`*/` is similar in meaning to `+/`, see the previous function for this) ### Arithmetic ``` (+/ % #) ``` * `+/` - sum, should be familiar now * `%` - divided by * `#` - Lenght ### Root mean square ``` %:@(%@# * +/@:*:) ``` Ehm, yeah... * `%:` - The root of + `%@#` - The inverse of the lenght + `*` - Times + `+/@:*:` - The sum of the squares (`*:` is squared, even though `*~` is as well.) ### Contraharmonic ``` +/@:*: % +/ ``` * `+/@:*:` - The sum of the squares * `%` - divided by * `+/` - the sum. > > I actually found out that my function was ~~one byte~~ two bytes too long by explaining this, so that's good! > > > If J were just this good at processing strings, we'd be winning a lot more golfing competitions... [Answer] # Languages: 5 ### POV-Ray 3.7 Scene Description Language: 304 bytes ``` #fopen I"i"read#declare S=0;#declare N=0;#declare Q=0;#declare P=1;#declare R=0;#while(defined(I))#read(I,V)#declare S=S+V;#declare N=N+1;#declare Q = Q+V*V;#declare P=P*V;#declare R=R+1/V;#end#warning concat(str(N/R,0,5),",",str(pow(P,1/N),0,5),",",str(S/N,0,5),",",str(sqrt(Q/N),0,5),",",str(Q/S,0,5)) ``` (POV-Ray SDL doesn't have console input functions, so I've substituted file input. Output is to the console, but is surrounded by a good deal of program status output.) ### Commodore BASIC: 111 104 bytes ``` 1 P=1:O┐1,0 2 I/#1 V:IF V=0T|G┌4 3 S=S+V:N=N+1:Q=Q+V*V:P=P*V:R=R+1/V:G┌2 4 ?N/R,P↑(1/N),S/N,(Q/N)↑.5,Q/S ``` (Not all of the characters in this program can be represented in Unicode. `|` is used to represent `SHIFT+H`, `┌` represents `SHIFT+O`, `┐` represents `SHIFT+P`, `/` represents `SHIFT+N`. Because of the limitations in Commodore Basic I/O, the input is entered one number at a time, with an input of -1 to indicate the end of input. Output is tab-delimited.) ### QBasic: 96 bytes ``` P=1:INPUT V:WHILE V:S=S+V:N=N+1:Q=Q+V*V:P=P*V:R=R+1/V:INPUT V:WEND:?N/R;P^(1/N);S/N;(Q/N)^.5;Q/S ``` Uses the same I/O scheme as DLosc's entry; I golfed 15 bytes off by using the fact that `INPUT V` returns 0 (which evaluates to false) when an empty line is input (at least in MS-DOS QBasic 1.1 -- I don't know if it also works in QB64). ### Pascal (FPC compiler): 172 bytes ``` program M;uses math;var v,p,s,n,q,r:real; begin p:=1;while not eoln do begin read(v);s:=s+v;n:=n+1;q:=q+v*v;p:=p*v;r:=r+1/v end;write(n/r,p**(1/n),s/n,(q/n)**0.5,q/s);end. ``` The input is separated by spaces, not commas, and is newline terminated. Output is space-separated. ### Erlang: 401 bytes ``` -module(means). -import(io). -import(math). -import(string). -import(lists). -export([means/6]). means(S,N,Q,P,R,[]) -> io:fwrite("~f,~f,~f,~f,~f~n", [N/R,math:pow(P,(1/N)),S/N,math:sqrt(Q/N),Q/S]); means(S,N,Q,P,R,[V|T]) -> means(S+V,N+1,Q+V*V,P*V,R+1/V,T). means:means(0,0,0,1,0,lists:map(fun({F,R}) -> F end, lists:map(fun(X) -> string:to_float(X) end, string:tokens(io:get_line(""), ",\n")))). ``` String handling in Erlang is a royal pain. Consequently, all floating-point numbers must be entered with at least one digit after the decimal point -- `string:to_float/1` will not convert `1`, but will convert `1.0`. (More to come, especially if I figure out how to do this in RoboTalk, a language with neither floating-point operations nor I/O) [Answer] # Languages: 3 Unless noted otherwise, numbers need to be seperated by space. ## C: 181 163 Takes numbers till end of input. ``` #include<math.h> main(){double h=0,g=1,a=0,q=0,k,n=0;for(;scanf("%lf",&k);++n)h+=1/k,g*=k,a+=k,q+=k*k;printf("%f %f %f %f %f\n",n/h,pow(g,1/n),a/n,sqrt(q/n),q/a);} ``` ## (ISO) C++: 195 Takes numbers till end of input. ``` #include<iostream> #include<cmath> int main(){double h=0,g=1,a=0,q=0,k,n=0;for(;std::cin>>k;++n)h+=1/k,g*=k,a+=k,q+=k*k;std::cout<<n/h<<" "<<pow(g,1/n)<<" "<<a/n<<" "<<sqrt(q/n)<<" "<<q/a<<"\n";} ``` ## Haskell: 185 180 164 159 149 140 Takes arbitrarily many lists of numbers seperated by newline. ### Implementation ``` m=map f x=let{s=sum;n=s$m(\_->1)x;t=s$m(^2)x}in[n/s(m(1/)x),product x**(1/n),s x/n,sqrt$t/n,t/s x] main=getLine>>=print.f.m read.words>>main ``` 50 41 (thanks shiona) bytes are just for IO :/. ### Example (Powershell's `echo` aka `Write-Output` prints every parameter on a single line) ``` PS> echo "1 2 3 4 5" "1.7 17.3 3.14 24 2.718 1.618" | runhaskell SO.hs [2.18978102189781,2.605171084697352,3.0,3.3166247903554,3.6666666666666665] [3.011834514901806,4.621794669196026,8.412666666666668,12.234139719108438,17.791525635945792] ``` [Answer] # Languages - 4 I always love an excuse to pull out good old ## QBasic, ~~112~~ 96 bytes ``` g=1:INPUT x:WHILE x:h=h+1/x:g=g*x:a=a+x:q=q+x^2:n=n+1:INPUT x:WEND:?n/h;g^(1/n);a/n;SQR(q/n);q/a ``` QBasic isn't good with variable numbers of inputs, so the program requires one number per line, terminated with 0 or an empty line. Output is separated with spaces. (Shortened once I realized that 0 isn't a valid number and can be used for input termination.) Tested using [QB64](http://en.wikipedia.org/wiki/QB64): ![Testing the QBasic means program](https://i.stack.imgur.com/GEDUy.png) ## Common Lisp, 183 bytes ``` (defun m(l)(let((a(apply #'+ l))(q(apply #'+(map'list #'(lambda(x)(* x x))l)))(n(length l)))(list(/ n(apply #'+(map'list #'/ l)))(expt(apply #'* l)(/ n))(/ a n)(sqrt(/ q n))(/ q a)))) ``` For some reason I expected this to be shorter. I'm not any kind of Lisp expert, so tips are appreciated. Ungolfed version: ``` (defun means (l) (let ((a (apply #'+ l)) ; sum of numbers (q (apply #'+ (map 'list #'(lambda (x) (* x x)) l))) ; sum of squares (n (length l))) (list ; Return a list containing: (/ n (apply #'+ (map 'list #'/ l))) ; n over sum of inverses (expt (apply #'* l) (/ n)) ; product to the power of 1/n (/ a n) ; a/n (sqrt (/ q n)) ; square root of q/n (/ q a) ; q/a ) ) ) ``` Probably the best way to test is by pasting the function into the `clisp` REPL, like so: ``` $ clisp -q [1]> (defun m(l)(let((a(apply #'+ l))(q(apply #'+(map'list #'(lambda(x)(* x x))l)))(n(length l)))(list(/ n(apply #'+(map'list #'/ l)))(expt(apply #'* l)(/ n))(/ a n)(sqrt(/ q n))(/ q a)))) M [2]> (m '(1 2 3 4 5)) (300/137 2.6051712 3 3.3166249 11/3) [3]> (m '(8.6)) (8.6 8.6 8.6 8.6 8.6) [4]> (m '(3 123456)) (246912/41153 608.5787 123459/2 87296.58 5080461315/41153) ``` I love how Lisp uses exact fractions instead of floats when dividing two integers. ## Prolog, 235 bytes Prolog isn't great at math, but we're gonna use it anyway. Tested with SWI-Prolog. I think the `sumlist` predicate may not be standard Prolog, but whatever, I'm using it. ``` m(L,H,G,A,Q,C):-length(L,N),h(L,I),H is N/I,p(L,P),G is P^(1/N),sumlist(L,S),A is S/N,q(L,R),Q is sqrt(R/N),C is R/S. p([H|T],R):-p(T,P),R is H*P. p([],1). q([H|T],R):-q(T,P),R is H*H+P. q([],0). h([H|T],R):-h(T,P),R is 1/H+P. h([],0). ``` Ungolfed: ``` m(L, H, G, A, Q, C) :- length(L, N), % stores the length into N h(L, I), % stores the sum of inverses into I H is N/I, p(L, P), % stores the product into P G is P^(1/N), sumlist(L, S), % stores the sum into S A is S/N, q(L, R), % stores the sum of squares into R Q is sqrt(R/N), C is R/S. % Helper predicates: % p calculates the product of a list p([H|T], R) :- p(T, P), % recursively get the product of the tail R is H*P. % multiply that by the head p([], 1). % product of empty list is 1 % q calculates the sum of squares of a list q([H|T], R) :- q(T, P), % recursively get the sum of squares of the tail R is H*H+P. % add that to the square of the head q([], 0). % sum of empty list is 0 % h calculates the sum of inverses of a list h([H|T], R) :- h(T, P), % recursively get the sum of inverses of the tail R is 1/H+P. % add that to the inverse of the head h([], 0). % sum of empty list is 0 ``` On Linux, with the code in a file called `means.pro`, test like this: ``` $ swipl -qs means.pro ?- m([1,2,3,4,5],H,G,A,Q,C). H = 2.18978102189781, G = 2.605171084697352, A = 3, Q = 3.3166247903554, C = 3.6666666666666665. ``` Gives a correct but rather amusing result when there's only one number: ``` ?- m([8.6],H,G,A,Q,C). H = G, G = A, A = Q, Q = C, C = 8.6. ``` ## Python 3, 103 bytes ``` h=a=q=n=0;g=1 for x in eval(input()):h+=1/x;g*=x;a+=x;q+=x*x;n+=1 print(n/h,g**(1/n),a/n,(q/n)**.5,q/a) ``` Same strategy as [Dennis's](https://codegolf.stackexchange.com/a/37239/16766) Python 2 version. Takes a comma-separated list of numbers; handles both ints and floats. A single-number input must be wrapped in square braces (and a list of numbers always *may* be); a fix would cost 4 bytes. [Answer] # 8 Languages ## Fortran 77 - 286 ``` READ*,l b1=0 b2=1 b3=0 b4=0 DO 10 i=1,l READ*,j b1=b1+1/j b2=b2*j b3=b3+j b4=b4+j**2 10 CONTINUE h=l/b1 g=b2**(1/l) a=b3/l q=(b4/l)**0.5 c=b4/b3 PRINT*,h,g,a,q,c END ``` ## BBC BASIC - 131 ``` INPUT l b=0:d=1:e=0:f=0 FOR i=1 TO l INPUTj:b+=1/j:d*=j:e+=j:f+=j^2 NEXT l h=l/b:g=d^(1/l):a=e/l:q=(f/l)^0.5:c=f/e PRINTh,g,a,q,c ``` **Output:** ``` 5 5 100 12 15 1 9.7914836236097695 26.600000000000001 45.596052460711988 78.15789473684211 ``` ## C++ - 292 ``` #include <iostream> #include <cmath> using namespace std;int main(){cout << "Length of sequence?: ";cin >> l;int b=0;int d=1;int e=0;int f=0;int j;int seq[l];for(int i=0;i<l;i++){cin >> j;b+=1/j;d*=j;e+=j;f+=pow(j,2);} h=l/b;g=pow(d,(1/l));a=e/l;q=pow((f/l),0.5);c=f/e;cout << h,g,a,q,c;} ``` ## Python 3 - 151 ``` s=input().split(',');l=len(s);b=0;d=1;e=0;f=0 for i in s:i=float(i);b+=1/i;d*=i;e+=i;f+=i**2 h=l/b;g=d**(1/l);a=e/l;q=(f/l)**0.5;c=f/e print(h,g,a,q,c) ``` **Output:** ``` 5,100,12,15,1 # Input 3.6764705882352944 9.7914836236097695 26.600000000000001 45.596052460711988 78.15789473684211 ``` ## Java - 421 ``` class Sequences { public static void main( String[] args){ System.out.println("Length of sequence?: ");Scanner reader = new Scanner(System.in);l=reader.nextInt();int b=0;int d=1;int e=0;int f=0;int j;int seq[l]; for(int i=0;i<l;i++){j=reader.nextInt();b+=1/j;d*=j;e+=j;f+=Math.pow(j,2);} h=l/b;g=Math.pow(d,(1/l));a=e/l;q=Math.sqrt(f/l);c=f/e;System.out.println(h+' '+g +' '+ a+' '+q+' '+c);}} ``` ## Javascript - 231 I'm not a Javascripter so any tips would be greatly appreciated ``` console.log("Length of sequence?: "); var l=readline(),b=0,d=1,e=0,f=0; for(var i = 0;i<l;i++) {var j=readline();b+=1/j;d*=j;e+=j;f+=pow(j,2);} h=l/b;g=pow(d,(1/l));a=e/l;q=sqrt(f/l);c=f/e; console.log(h+' '+g+' '+a+' '+q+' '+c); ``` ## Algoid - 337 Look it up on the [Google Play Store](https://play.google.com/store/apps/details?id=fr.cyann.algoid) or the [Raspberry Pi Store](http://store.raspberrypi.com/projects/algoid) ``` text.clear(); set l=text.inputNumber("Length of sequence?: ");set b=0;set d=1;set e=0;set f=0;set seq=array{}; for(set i=1; i<=l; i++){set j=text.inputNumber(i..": ");b+=1/j;d*=j;e+=j;f+=math.pow(j,2);} set h=l/b;set g=math.pow(d,(1/l));set a=e/l;set q=math.sqrt(f/l);set c=f/l;set str=h.." "..g.." "..a.." "..q.." "..c;text.output(str); ``` # var'aQ - 376 This is syntactically correct and all, but all current interpreters just *don't work*... ``` 0 ~ b cher 1 ~ d cher 0 ~ e cher 0 ~ f cher 'Ij mI'moH ~ l cher l { 'Ij mI'moH ~ j cher b 1 j wav boq ~ b cher d j boq'egh ~ d cher e j boq ~ e cher f j boqHa'qa boq ~ f cher } vangqa' l b boqHa''egh ~ h cher d 1 l boqHa''egh boqHa'qa ~ g cher e l boqHa''egh ~ a cher f l boqHa''egh loS'ar ~ q cher f e boqHa''egh c cher h cha' g cha' a cha' q cha' c cha' ``` [Answer] # Languages: 3 ## CJam, 58 ``` qS%:d:A{1\/}%:+A,\/SA:*1.A,/#SA:+A,/:BSA{2#}%:+A,/:CmqSCB/ ``` ## TI-Basic, 85 ``` Input L1:{dim(L1)/sum(1/(L1),dim(L1)√prod(L1),mean(L1),√(mean(L1²)),mean(L1²)/mean(L1 ``` ## Java, 457 ``` import java.util.*;class C{public static void main(String[]s){List r=new ArrayList();double[]d=Arrays.stream(new Scanner(System.in).nextLine().split(",")).mapToDouble(Double::new).toArray();double x=0,y,z;for(double D:d){x+=1/D;}r.add(d.length/x);x=1;for(double D:d){x*=D;}r.add(Math.pow(x,1./d.length));r.add(y=Arrays.stream(d).average().getAsDouble());x=1;for(double D:d){x+=D*D;}r.add(Math.sqrt(z=x/d.length));r.add(z/y);r.forEach(System.out::println);}} ``` [Answer] # Languages - 2 ## Cobra - 132 ``` def f(l as number[]) a,b,c,d=0d,1d,0d,0d for i in l,a,b,c,d=a+1/i,b*i,c+i,d+i**2 print (e=l.length)/a,b**(1/e),c/e,(d/e)**0.5,d/c ``` ## Python - 129 ``` def f(l):a,b,c=len(l),sum(i*i for i in l),sum(l);print(a/sum(1/i for i in l),eval('*'.join(map(str,l)))**(1/a),c/a,(b/a)**.5,b/c) ``` [Answer] # 1 language --- ## R, ~~92~~ 91 ``` f=function(x){n=length(x);s=sum;d=s(x^2);c(n/s(1/x),prod(x)^(1/n),mean(x),(d/n)^.5,d/s(x))} ``` Takes a vector of value and output a vector of means. [Answer] ## 1 Language ### Golfscript, 162 ``` n/:@,:^;'(1.0*'@'+'*+')/'+^+'('@'*'*+')**(1.0/'+^+')'+^'/(1.0/'+@'+1.0/'*+')'+'(1.0/'^+'*('+@'**2+'*+'**2))**0.5'+'('@'**2+'*+'**2)/'+4$+'*'+^+]{'"#{'\+'}"'+~}%n* ``` Yes, it's huge. And it can definitely be made smaller. Which I will do sometime later. Try it out [here](http://golfscript.apphb.com/?c=OyIxCjIKMwo0CjUiCm4vOkAsOl47JygxLjAqJ0AnKycqKycpLycrXisnKCdAJyonKisnKSoqKDEuMC8nK14rJyknK14nLygxLjAvJytAJysxLjAvJyorJyknKycoMS4wLydeKycqKCcrQCcqKjIrJyorJyoqMikpKiowLjUnKycoJ0AnKioyKycqKycqKjIpLycrNCQrJyonK14rXXsnIiN7J1wrJ30iJyt%2BfSVuKg%3D%3D). It expects the input to be newline separated. If that is not allowed, I'll fix it (+2 chars). It outputs the list newline separated. Here's a slightly more readable version: ``` n/:@,:^; '(1.0*'@'+'*+')/'+^+ '('@'*'*+')**(1.0/'+^+')'+ ^'/(1.0/'+@'+1.0/'*+')'+ '(1.0/'^+'*('+@'**2+'*+'**2))**0.5'+ '('@'**2+'*+'**2)/'+4$+'*'+^+ ]{'"#{'\+'}"'+~}% n* ``` [Answer] # Languages 2 ## Fortran: 242 I've ungolfed it for clarity, but the golfed version is what is counted. you first need to input the number of values to be added, then the values. ``` program g real,allocatable::x(:) read*,i allocate(x(i));read*,x print*,m(x) contains function m(x) result(p) real::x(:),p(5) n=size(x) p(1:4)=[n/sum(1/x),product(x)**(1./n),sum(x)/n,sqrt(sum(x**2)/n)] p(5)=p(4)**2/p(3) endfunction end ``` ## [wxMaxima](http://andrejv.github.io/wxmaxima/index.html) 134 Copy this into the editor, `ctrl+enter` and then call via `m([1,2,3,4,5]),numer` to get floating point output (otherwise you get symbolic output). ``` m(x):=block([n:length(x),d:0,c:mean(x)],for i:1 thru n do(g:x[i],d:d+g*g),return([1/mean(1/x),apply("*",x)^(1/n),c,sqrt(d/n),d/n/c])); ``` [Answer] # Perl, 86 76 ``` $,=$";$h+=1/uc,$g+=log,$a+=lc,$q+=$_**2for<>;print$./$h,exp$g/$.,$a/$.,sqrt$q/$.,$q/$a ``` Input: one number per line. EDIT: this is one character longer, but since apparently shebang lines aren’t counted toward the total, it ends up being better: ``` #!perl -pl $"+=1/uc,$,+=log,$}+=lc,$;+=$_**2}for($./$",exp$,/$.,$}/$.,sqrt$;/$.,$;/$}){ ``` [Answer] ## T-SQL, ~~136~~ 122 With the number lists stored in table S with I (integer) identifying the list and V (float) the value. ``` SELECT COUNT(*)/SUM(1/V),EXP(SUM(LOG(V))/COUNT(*)),AVG(V),SQRT((1./COUNT(*))*(SUM(V*V))),SUM(V*V)/SUM(V) FROM S GROUP BY I ``` [SQLFiddle](http://sqlfiddle.com/#!3/cc670/1/0) Saved 14 thanks to Alchymist [Answer] ## Languages: 5 Some entries strive to avoid rounding errors (to 4 decimal places), using Java's BigDecimal instead of float/double, and accept IO rules per OP. Newer entries relax both IO rules and BigDecimal. ## Groovy - 409 400 164 157 chars ``` float i=0,j=1,k=0,l,n=0,m=0,p;args.each{x=it as float;i+=1/x;j*=x;k+=x;m+=x*x;n++};l=k/n;p=m/n;println "${n/i},${Math.pow(j,1f/n)},$l,${Math.sqrt p},${p/l}" ``` sample run: ``` bash$ groovy F.groovy 10.1381 29.8481 14.7754 9.3796 44.3052 22.2936 49.5572 4.5940 39.6013 0.9602 5.957994213465398,14.304084339049883,22.545269,27.939471625408938,34.62429631138658 ``` ## Java - 900 235 chars ``` class F{public static void main(String[]a){float i=0,j=1,k=0,l,n=0,m=0,p;for(String s:a){float x=Float.valueOf(s);i+=1/x;j*=x;k+=x;m+=x*x;n++;}l=k/n;p=m/n;System.out.println(n/i+","+Math.pow(j,1f/n)+","+l+","+Math.sqrt(p)+","+p/l);}} ``` sample run: ``` bash$ java F 10.1381 29.8481 14.7754 9.3796 44.3052 22.2936 49.5572 4.5940 39.6013 0.9602 5.957994,14.304084906138343,22.545269,27.939471625408938,34.6243 ``` ## Clojure - 524 324 chars ``` (defn r[x](/ (reduce + 0.0 x)(count x))) (defn s[x](reduce #(+ %1 (* %2 %2)) 0.0 x)) (defn f[x](let[n (* 1.0 (count x))][(/ n(reduce #(+ %1 (/ 1.0 %2)) 0.0 x))(Math/pow(reduce * x)(/ 1.0 n))(r x)(Math/sqrt(/(s x) n))(/(/(s x) n)(r x))])) (doseq [x(f(map #(Float/valueOf %) *command-line-args*))](print(str x ","))) (println) ``` sample run (it does have a trailing comma at the end): ``` bash$ java -jar clojure-1.6.0.jar m2.clj 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602 5.957994368133907,14.30408424976292,22.545269936323166,27.93947151073554,34.62429460831333, ``` ## Scala - 841 663 230 chars ``` import java.math._ object F{def main(a:Array[String]){ var i,j,k,l,m,p=0f;var n=0 a.foreach{y=>var x=y.toFloat;i+=1/x;j*=x;k+=x;m+=x*x;n+=1} l=k/n;p=m/n;System.out.println(n/i+","+Math.pow(j,1f/n)+","+l+","+Math.sqrt(p)+","+p/l)}} ``` sample run: ``` bash$ scala F.scala 10.1381 29.8481 14.7754 9.3796 44.3052 22.2936 49.5572 4.5940 39.6013 0.9602 5.957994,0.0,22.545269,27.939471625408938,34.6243 ``` ## JRuby - 538 chars It is unclear if JRuby differs from Ruby: this must run on the JVM. Yet it is Ruby syntax. Either way, I'm including it in the spirit of a Rosetta Stone. ``` require 'java' java_import 'java.math.BigDecimal' o=BigDecimal::ONE z=BigDecimal::ZERO def b(s) java.math.BigDecimal.new s end def p(x,y) java.lang.Math::pow(x.doubleValue,y.doubleValue) end def d(x,y) x.divide y,5,BigDecimal::ROUND_UP end def r(x,n) d(x.inject(b(0)){|a,v|a.add v},n) end def s(x) x.inject(b(0)){|a,v|a.add(v.multiply v)} end x=[] ARGV[0].split(",").each{|i|x<<b(i)} n=b x.size puts "#{d n,x.inject(z){|a,v|a.add(d o,v)}},#{p x.inject(o){|a,v|a.multiply v},d(o,n)},#{r(x,n)},#{p d(s(x),n),b("0.5")},#{d d(s(x),n),r(x,n)}" ``` sample run (does print a warning to stderr): ``` bash$ jruby Mean.rb 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602 5.95781,14.30408436301878,22.54527,27.939471541172715,34.62430 ``` [Answer] # Languages 1 ### lua - 113 ``` e=arg s=#e h,g,a,r=0,1,0,0 for i=1,s do x=e[i]h=h+1/x g=g*x a=a+x/s r=r+x^2/s end print(s/h,g^(1/s),a,r^.5,r/a) ``` [Answer] # Languages - 1 ### Groovy: ``` def input = [1.7,17.3,3.14,24,2.718,1.618]; def arithmeticMean def harmonicMean def geometricMean def quadraticMean def contraharmonicMean def sum = 0 def product = 1 // Arithmetic Mean for(each in input){ sum += each } arithmeticMean = sum / input.size() // Harmonic Mean sum = 0 for(each in input){ sum += (1/each) } harmonicMean = input.size() / sum // Geometric Mean for(each in input){ product *= each } geometricMean = Math.pow(product,1/input.size()); // Quadratic Mean sum = 0 for(each in input){ sum += (each*each) } quadraticMean = Math.pow(sum/input.size() ,(1/2)) // Contraharmonic Mean sum = 0 def sum2 = 0 for( each in input ){ sum += each sum2 += (each * each) } contraharmonicMean = (sum2/input.size()) / (sum/input.size()) println "Arithmetic Mean: $arithmeticMean" println "Harmonic Mean: $harmonicMean" println "Geometric Mean: $geometricMean" println "Quadratic Mean: $quadraticMean" println "Contraharmoic Mean: $contraharmonicMean" ``` [Answer] # 2 Languages # Java - 243 bytes ``` class M{public static void main(String[]a){float h=0,l=a.length,p=1,s=0,q=0;for(int i=0;i<l;i++){float v=Float.valueOf(a[i]);q+=v*v;s+=v;h+=1/v;p*=v;}System.out.println(l/h+"\n"+Math.pow(p,1.0/l)+"\n"+s/l+"\n"+Math.sqrt((1.0/l)*q)+"\n"+q/s);}} ``` expanded: ``` class Means { public static void main(String[] a) { float h = 0, l = a.length, p = 1, s = 0, q = 0; for (int i = 0; i < l; i++) { float v = Float.valueOf(a[i]); q += v * v; s += v; h += 1 / v; p *= v; } System.out.println(l / h + "\n" + Math.pow(p, 1.0 / l) + "\n" + s / l + "\n" + Math.sqrt((1.0 / l) * q) + "\n" + q / s); } } ``` # vba - excel, 387 bytes Fill in values in the first column, then press the button (that triggers this code) and it outputs the values in the second column. ``` Private Sub a_Click() Dim d,s,q,h,p As Double Dim y As Integer h=0 q=0 s=0 p=1 y=1 While Not IsEmpty(Cells(y,1)) s=s+Cells(y,1) q=q+Cells(y,1)*Cells(y,1) h=h+1/Cells(y,1) p=p*Cells(y,1) y=y+1 Wend y=y-1 Cells(1,2)=y/h Cells(2,2)=p^(1/y) Cells(3,2)=s/y Cells(4,2)=((1/y)*q)^0.5 Cells(5,2)=q/s End Sub ``` [Answer] # 1 language ## Rust - 469 (`rustc 0.11.0-pre (3851d68 2014-06-13 22:46:35 +0000)`) ``` use std::io;use std::from_str::from_str;use std::num;fn main(){loop{let a:Vec<f64>=io::stdin().read_line().ok().expect("").as_slice().split(',').map(|x|std::from_str::from_str(x.trim_chars('\n')).expect("")).collect();let n:f64=num::from_uint(a.len()).expect("");let s=a.iter().fold(0.0,|a,b|a+*b);let q=a.iter().fold(0.0,|a,b|a+*b* *b);println!("{},{},{},{},{}",n / a.iter().fold(0.0,|a,b|a+1.0/ *b),(a.iter().fold(1.0,|a,b|a**b)).powf(1.0/n),s/n,(q/n).sqrt(),q/s,);}} ``` Ungolfed version: ``` use std::io; use std::from_str::from_str; use std::num; fn main() { loop { let a : Vec<f64> = io::stdin().read_line().ok().expect("").as_slice().split(',') .map(|x|std::from_str::from_str(x.trim_chars('\n')).expect("")).collect(); let n : f64 = num::from_uint(a.len()).expect(""); let s = a.iter().fold(0.0, |a, b| a + *b); let q = a.iter().fold(0.0, |a, b| a + *b * *b); println!("{},{},{},{},{}", n / a.iter().fold(0.0, |a, b| a + 1.0 / *b), (a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n), s / n, (q / n).sqrt(), q / s, ); } } ``` Compacted 430-byte version without loop or input, for testing in [playrust](http://play.rust-lang.org/): ``` use std::from_str::from_str;use std::num;fn main(){let a:Vec<f64>="1,2,3,4".as_slice().split(',').map(|x|std::from_str::from_str(x.trim_chars('\n')).expect("")).collect();let n:f64=num::from_uint(a.len()).expect("");let s=a.iter().fold(0.0,|a,b|a+*b);let q=a.iter().fold(0.0,|a,b|a+*b**b);println!("{},{},{},{},{}",n / a.iter().fold(0.0, |a, b| a + 1.0 / *b),(a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),s/n,(q/n).sqrt(),q/s);} ``` --- Updated for newer Rust: Ungolfed: ``` use std::io; fn main(){ let mut s=String::new(); io::stdin().read_line(&mut s); let a:Vec<f64>=s .split(',') .map(|x|x.trim().parse().expect("")) .collect(); let n:f64=a.len() as f64; let s=a.iter().fold(0.0,|a,b|a+*b); let q=a.iter().fold(0.0,|a,b|a+*b**b); println!("{},{},{},{},{}", n / a.iter().fold(0.0, |a, b| a + 1.0 / *b), (a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),s/n, (q/n).sqrt(),q/s); } ``` Golfed (402 bytes): ``` use std::io;fn main(){ let mut s=String::new(); io::stdin().read_line(&mut s); let a:Vec<f64>=s .split(',') .map(|x|x.trim().parse().expect("")) .collect(); let n:f64=a.len() as f64; let s=a.iter().fold(0.0,|a,b|a+*b); let q=a.iter().fold(0.0,|a,b|a+*b**b); println!("{},{},{},{},{}", n / a.iter().fold(0.0, |a, b| a + 1.0 / *b), (a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),s/n, (q/n).sqrt(),q/s);} ``` [Answer] # Languages: 4 ## CoffeeScript, 193 Takes a comma-separated string of input: ``` m=(q)->m=Math;q.r=q.reduce;q=q.split(',').map Number;l=q.length;x=q.r ((p,v)->(p+v)),0;y=q.r ((p,v)->(p+v*v)),0;[l/q.r(((p,v)->(p+1/v)),0),m.pow(q.r(((p,v)->(p*v)),1),1/l),x/l,m.sqrt(y/l),y/x]; ``` ## JavaScript (ES5), 256 Again, takes a comma-separated string of input: ``` function m(q){m=Math,q=q.split(',').map(Number),q.r=q.reduce,l=q.length,x=q.r(function(p, v){return p+v;},0),y=q.r(function(p,v){return p+v*v},0);return[l/q.r(function(p,v){return p+1/v},0),m.pow(q.r(function(p,v){return p*v},1),1/l),x/l,m.sqrt(y /l),y/x]} ``` ## PHP, 252 Same concept: ``` <?function m($q){$r=array_reduce;$q=explode(',',$q);$l=count($q);$x=array_sum($q);$y=$r($q,function($p,$v){return $p+$v*$v;});return[$l/$r($q,function($p,$v){return $p+1/$v;}),pow($r($q,function($p,$v){return $p*$v;},1),1/$l),$x/$l,sqrt($y/$l),$y/$x];} ``` ## TypeScript, 393\* Since TypeScript is a superset of JavaScript, I could have just submitted the same code but that wouldn't really be fair now. Here's a minified TypeScript code with all functions, variables, and parameters fully typed: ``` function m(q:String):number[]{var a:number[]=q.split(',').map(Number),l:number=a.length,x:number=a.reduce(function(p:number,v:number):number{return p+v},0),y:number=a.reduce(function(p:number,v:number):number{return p+v*v},0);return[l/a.reduce(function(p:number,v:number):number{return p+1/v},0),Math.pow(a.reduce(function(p:number,v:number):number{return p*v},1),1/l),x/l,Math.sqrt(y/l),y/x]} ``` Could have cheated and used the type `any` as well... but, you know. [Answer] # Excel - 120 Not sure if this counts as a "programming" language, but thought people may actually use a spreadsheet for this type of thing With the numbers in A2:J2 ``` L2 (harmonic) =HARMEAN(A2:J2) M2 (geometric) =GEOMEAN(A2:J2) N2 (arithmetic) =AVERAGE(A2:J2) O2 (quadratic) =SQRT(SUMSQ(A2:J2)/COUNT(A2:J2)) P2 (contraharmonic) =(SUMSQ(A2:J2)/COUNT(A2:J2))/AVERAGE(A2:J2) ``` [Answer] ## VBA (Excel) - 105 ``` a=1:for each n in i:a=a*n:b=b+1/n:c=c+n:d=d+n*n:next:x=ubound(i)+1:?x/b","a^(1/x)","c/x","(d/x)^0.5","d/c ``` Ungolfed : ``` a=1: set a variable to 1 (for the geometric mean) for each n in i: loop through the list a=a*n: product of the list b=b+1/n: sum of inverses of the list c=c+n: sum of the list d=d+n*n: sum of squares of the list next: end loop x=ubound(i)+1: get the number of elements in the list ? prepare to print x/b"," harmonic = count / sum(inverses) a^(1/x)"," geometric = product^(1/count) c/x"," arithmetic = sum / count (d/x)^0.5"," quadratic = square root of ( sum of squares / count ) d/c contraharmonic = sum of squares / sum ``` This code has to be run in the immediate window, and the array must be called *i*. Since there is no error collection, no cleaning, no variable dropping/releasing, if you want to test this code you can use the following piece of code (just paste in the immediate window and run the lines in order) : ``` b=0:c=0:d=0:set i = nothing:i= array(1,2,3,4,5) a=1:for each n in i:a=a*n:b=b+1/n:c=c+n:d=d+n*n:next:x=ubound(i)+1:?x/b","a^(1/x)","c/x","(d/x)^0.5","d/c ``` Nothing very special, just the choice to use the immediate window with *:* to replace line breaks, which saves a few bytes vs setting up a sub or function and closing it; using ? to print rather than debug.print (only in the immediate window); and relying on how vba determines implicit values (adding a value to an un-set variable returns the value) and implicit operations (anything involving a string is implicitly concatenation). ]
[Question] [ Inspired by [Is it double speak?](https://codegolf.stackexchange.com/questions/189358/is-it-double-speak/), I devised a harder challenge. Given a string, determine if the string is *n-speak*, for any \$n\geq 2\$. N-speak is defined by repeating each letter \$n\$ times. With \$n = 4\$, the string `Hello` is transformed to `HHHHeeeelllllllloooo`. Your goal is to figure out if the input is a valid output for any n-speak transformation. It should be noted that any sentence which is valid n-speak, for \$n = 2k\$, is also valid k-speak. Thus, the hard parts to solve will be odd values of \$n\$. ## Input A string consisting of at least 2 characters. Input could also be a list of characters. Input is case sensitive. ## Output `Truthy` if the string is n-speak, `falsey` otherwise. ## Examples ### True cases ``` HHeelllloo,, wwoorrlldd!! TTTrrriiipppllleee ssspppeeeaaakkk QQQQuuuuaaaaddddrrrruuuupppplllleeee ssssppppeeeeaaaakkkk 7777777-------ssssssspppppppeeeeeeeaaaaaaakkkkkkk 999999999 aaaabb aaaaaaaabbbbcc aaaaabbbbb @@@ ``` If you want to generate additional truthy cases, you can use [this MathGolf script](https://tio.run/##y00syUjPz0n7/18pPL9coSQjs1gBiBIVcvLz0hWKU/NKUvOSU5VyDy/L1jjcEv//v5EBAA). Place the string within the quotation marks, and the value of \$n\$ as the input. ### False cases ``` Hello, world! TTTrrriiipppllleee speak aaaaaaaaaaaaaaaab Ddoouubbllee ssppeeaakk aabbab aaaabbb a (does not need to be handled) (empty string, does not need to be handled) ``` Of course, since this is code golf, get ready to trim some bytes! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes Runs with `⎕io←0` ``` 1≠∨/⍸2≠/∊0⍞0 ``` [Try it online!](https://tio.run/##dY@9TsMwEID3PIU7ZUnVwIJgRqgrUl7gHF9RZEtn2YqivgBNkYpYWBEjj8Dz@EXCnY4iGPim@/vsO4hh7fYQ6GEpz68DlceXtirzYbdclON7mT825fR5yeGmzE9tOb21C3eXuksjmh4y5pu62lXbLWJgiJrGmGkiSikE51YrbnZdl1IahiHGyDOIaIzJOXPKMQB473nsnhkZLoBj2EmSR9XEE1FMUcUVWWzRr5S1kpWooAKKV9i5PsOxdKz9DjSxtu/PBclsVd9ByH8O57OpMROl4P6/NSL4Xy///MC1W0c0jtbKrNwmy8qKMv4F "APL (Dyalog Unicode) – Try It Online") Golfed together with [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m). On the input (example: `"aaccccaaaaaabb"`, using `""` to denote a string (an array of chars) and `''` to denote a char) `∊0⍞0` surround with 0s and flatten, `0 'a' 'a' 'c' 'c' 'c' 'c' 'a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 0` `2≠/` perform pairwise not-equal, `1 0 1 0 0 0 1 0 0 0 0 0 1 0 1` `⍸` get the 0-indexed indices, `0 2 6 12 14` `∨/` compute the GCD, `2` `1≠` is this not equal to 1? [Answer] # Java 10, 85 bytes ``` s->{var r=0>1;for(int i=0;++i<s.length();)r|=s.matches("((.)\\2{"+i+"})*");return r;} ``` Regex ported from [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/189782/52210). [Try it online.](https://tio.run/##jVJNT@MwEL33Vww@JaQNH5fVEsppteICEqI32MMkMdTEtS3baVWV/vYyjtNqU3rgHazMPM@b8ct84BInH3WzqyQ6Bw8o1GYEIJTn9g0rDo8hBCi1lhwVVMmzt0K9g0sLIrYjOpxHLyp4BAVT2LnJ3WaJFuz08u6qeNM2ITEQ08siy8StyyVX736epEVqP6cuX6Cv5twlLEny9PX1esMykbFtes7SwnLfWgW22O6K0Mi0paRGfb@lFjUsaOB@pJd/gGmc9uICZrb183UXee58wu7vOZcErcdjgNVKa2ulrOuzM9Y9ZX9vNptZa4UQxhi6zjknyjlHIX0jYtM0w4onQksgDmsCldsQm6gQJIJGEAkqQSboBKEjpV8RkwgXYSJ4BEY0EcPy33sM0@F@WX7PxXxZVtUJLhCHmue183yR69bnhqz2UtH/G@2t/ovS8fXN/16T03oMK21l/SN7Dcfm9ICHQYf0n1rrti3LoBCcDf4EV45EhiH7trPdDnVkv9ZCmdb3W3Ti1R2dsRtgmcqrGKa96nb3BQ) **Explanation:** ``` s->{ // Method with String parameter and boolean return-type var r=0>1; // Result-boolean, starting at false for(int i=0;++i<s.length();)// Loop `i` in the range [1, input-length): r|= // Change the result to true if: s.matches("((.)\\2{"+i+"})*"); // The input-String matches this regex // NOTE: String#matches implicitly adds a leading ^ and // trailing $ to match the full String return r;} // After the loop, return the result-boolean ``` *Regex explanation:* ``` ^((.)\2{i})*$ // Full regex to match, where `i` is the loop-integer ^ $ // If the full String matches: (.) // A character \2{i} // Appended with that same character `i` amount of times ( )* // And that repeated zero or more times for the entire string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Œɠg/’ ``` [Try it online!](https://tio.run/##y0rNyan8///opJML0vUfNcz8//9/SEhIUVFRZmZmQUFBTk5OamqqgoJCcUFqYjYA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` γ€g¿≠ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3OZHTWvSD@1/1Lng//@QkJCioqLMzMyCgoKcnJzU1FQFBYXigtTEbAA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), 53 bytes Derived from the regular expression used by @wastl in [*Is it double speak?*](https://codegolf.stackexchange.com/a/189379/58563). ``` s=>[...s].some((_,n)=>s.match(`^((.)\\2{${++n}})*$`)) ``` [Try it online!](https://tio.run/##jZFBT8MgFMfvfgqWLCm4joMX46E7GbOrSW/tdFCY1rI@Aqs9LPvslSfRaGSLvxPwf@8XeLyJd@Eb19rDsgelp10x@WJVcc79hnvYa0qf854VK8/34tC80u0TpZzV9c1xflws@tOJXc@3jE0N9B6M5gZeaFaVbtCbjF39PN3RbL3W2gQA8pyQcQRwzhilZrOM/Skuy9I517attTb0aK0JId77sA1rIUTXdYm2x8AQCAVCBYLD4d5GDXpQhCZUoQtlaEvpbiPLiI/YiI6ISBdJOO6@SGTYKeWZIIZSNs25Akw/u3@lWd1XD8L45B@EH4CcjOCM@v/YrRbdhUt@XzZRc68AhkFKdOHYcW44rZQudSZFfOL0AQ "JavaScript (Node.js) – Try It Online") --- # Recursive version, 55 bytes ``` s=>(g=n=>s[++n]&&!!s.match(`^((.)\\2{${n}})*$`)|g(n))`` ``` [Try it online!](https://tio.run/##jZFBT8MgFMfvfgqaLCu4rgcvxkN3MmZXk97amUJhtRaBwGoPc5@98iQazZjxdwL@7/0Cjxf6Rl1re3NYK83FvC9mV2xwV6hi46rVSu2WyyRx@Ss9tM@4ecI4J3V9c1wc1elErhcNee@wIqRp5lYrp6XIpe5wWpV2FLuUXP083eN0uxVCerTOMoSmSWtrpeQ8SVJyVlyWpbW273tjjO8RQiCEnHN@69eU0mEYIm2PntHjCyj3eIeFvQka8IAITKACF8jAFtPdBtYBFzABEaCBIRBx3H0RyaCTsQtBCBlr20sFkH52/0rTWlUPVLroH/gf0BmatJX8/2M3gg5/XPL7spGae671ODIGLhg7zA2mFdPFzhgNT5w/AA "JavaScript (Node.js) – Try It Online") ### Commented ``` s => ( // s = input string g = n => // g is a recursive function taking a repetition length n s[++n] && // increment n; abort if s[n] is not defined !!s.match( // otherwise, test whether s consists of groups of: `^((.)\\2{${n}})*$` // some character, followed by n copies of the same character ) // | g(n) // or whether it works for some greater n )`` // initial call to g with n = [''] (zero-ish) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ ~~70~~ ~~69~~ 67 bytes ``` lambda s:s in[''.join(c*n for c in s[::n])for n in range(2,len(s))] ``` [Try it online!](https://tio.run/##jZAxT8MwEIX3/oqrOiRBgaELolI3hLoiZSsd7NihJsZnnRNF/fXhThaQAgPf5Hv37tm@eBnOGLZzt3@ZvXrXRkHaJXDhWBR3b@hC2d4E6JCgZRHScbcLp0rqIDWp8GrLbe1tKFNVneZNQ@NwvqwiuTBAVxaHg7WeQaxrgGlCJPLemPW6qL5dTdMQkXMuxshmay0ApJS45LNSqu/7pf@ZGRnuKMPwMEkd87wESIJESIaESIrEXOXcZ24zKRMzNqMyfWY5/PDJUhSv1j@VrGrdtr86Ios/y6vNk/LJLhfI68MaJiRv/rGzaFX/1@1fr1g2Hw3iOGot07Is@bR89SqgqOYP "Python 2 – Try It Online") -4 bytes, thanks to Jitse [Answer] # [QuadS](https://github.com/abrudz/QuadRS), 16 [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≠∨/⍵ (.)\1* ⊃⍵L ``` [Try it online!](https://tio.run/##KyxNTCn@/9/wUeeCRx0r9B/1buXS0NOMMdTietTVDOT5/P@fmJgMBIlgkJQEAA "QuadS – Try It Online") `1≠` is 1 different from `∨/` the GCD `⍵` of the result of `(.)\1*` PCRE Searching for any character followed by 0 or more repetitions thereof `⊃⍵L` and returning the first of the match lengths (i.e. the length of the match) [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╢b}▄; ``` [Run and debug it](https://staxlang.xyz/#p=b6627ddc3b&i=%22HHeelllloo,,++wwoorrlldd%21%21%22%0A%22TTTrrriiipppllleee+++ssspppeeeaaakkk%22%0A%22QQQQuuuuaaaaddddrrrruuuupppplllleeee++++ssssppppeeeeaaaakkkk%22%0A%227777777-------ssssssspppppppeeeeeeeaaaaaaakkkkkkk%22%0A%22999999999%22%0A%22aaaabb%22%0A%22aaaaaaaabbbbcc%22%0A%22aaaaabbbbb%22%0A%22Hello,+world%21%22%0A%22TTTrrriiipppllleee+++speak%22%0A%22aaaaaaaaaaaaaaaab%22%0A%22Ddoouubbllee++ssppeeaakk%22%0A%22a%22&a=1&m=2) Procedure: * Calculate run-lengths. * GCD of array * Is > 1? [Answer] # T-SQL 2008 query, 193 bytes ``` DECLARE @ varchar(max)='bbbbbbccc'; WITH C as(SELECT number+2n,@ t FROM spt_values WHERE'P'=type UNION ALL SELECT n,stuff(t,1,n,'')FROM C WHERE left(t,n)collate Thai_Bin=replicate(left(t,1),n))SELECT 1+1/~count(*)FROM C WHERE''=t ``` **[Try it online](https://rextester.com/NST24626)** [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda s:any(s=="".join(i*k for i in s[::k])for k in range(2,len(s))) ``` [Try it online!](https://tio.run/##dZCxTsMwEIb3e4prJweFDjAgImVj6IqUrXSw6ys1NrZlOwp9@uDDwIDEN0T35/cXnROv5RL8/VrGwxGWi3GEU5ppACzpWp9YdjJG8loYH@ciug6QPk4UC5cqkbRwHl9WJ9@VlpgH6a8ij@N2u3sLxgtzY/EcEho0HvNhGOyx42w5J@lfSdz1jrzIXdet3GRuvr4ek/FFnLla93siVwmh7xGXJYSUnNN6s4FpmlJKxpgYYz1BRIiYc66xzlJKay08V@ZKjVJXqpE4xyaxxRp7LLLJKrsWHhq3jdyIDWrIhm3A4w/Ab5WC776OSp1O8Dsr2Nd7hR6XkJz@7zKRf7P8g4InHcI8K8XneHXehncA@Qk "Python 3 – Try It Online") [Answer] # [PHP](https://php.net/), ~~76~~ 75 bytes ``` while(($x=strspn($argn,$argn[$n+=$x],$n))>1&&($m=max($m,$x))%$x<1);echo!$x; ``` [Try it online!](https://tio.run/##fVHBTsMwDD0vX@FNYWtFp4kTQt3gMqFxQULsBjukq0ertkmUpKwI8e3DabYBF96h9Xv2sxNHF/owv9OFZow7tM7CAl7YYDYDZ1pXfLDBZLVCrAlKJQnAfq@UMXWd58PhJKH0er02xpRlqbWmKkQEAGstUYqFEFVV9YVPhJZAksgJ5DKe62D0Tm/1Xm/2bm/3/tDgOmAaYAN0AAaIgCqgd92c0DOfzbJzGGiWbbc/kud9BS1hJ2qLH2ffyZhlIoQr2oxKYK9Mnf@3Do2i@jP0PLxXl7lSbZtlvt4vwN/H34KSm5QxRiexZdPWwiHQW8H0Hp7Xy4dHKKVuHdspg2JbRHB8QmGBC/MmIYZPBoDbQgUhgdGrHKWHfVHWGEW8W1hnrJZRyPbfFy4vF7zbJFzG8e3VeBzxZtGIjn4J7@L4gnfzqzj1TYe8Sw/H/n1jGkZHNWjRAcr30ijZoHQkt5I0GhinP6T5TSSRr8M3 "PHP – Try It Online") First attempt, a somewhat naïve iterative approach. *Ungolfed:* ``` // get the length of the next span of the same char while( $s = strspn( $argn, $argn[ $n ], $n ) ) { // if span is less than 2 chars long, input is not n-speak if ( $s < 2 ) { break; } // k is GCD $k = max( $k, $s ); // if span length does not divide evenly into GCD, input is not n-speak if( ( $k % $s ) != 0 ) { break; } // increment current input string index $n += $s; } ``` ***-1 byte***, thx to @Night2! [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~30~~ ~~27~~ 26 bytes ``` {1-[gcd] m:g/(.)$0*/>>.to} ``` [Try it online!](https://tio.run/##dY/BasMwDIbvegoVythKmnaXlQ7aXXbIdZDb6MGO1RLsTsZeCGXs2TMJb7ntO0m2PvErUgpP0/WGd2c8TF@P6/dL5054fb5s7uuH5Xa1OR7rT/6esrnhSy1TZ04Y@g/KU9MQBYG5qhDHkTmlEJxbLKBt25RS3/cxRpkgIkTMOUsrtTHGew9vwiBIa5wgRtI@Fkkt1dRTUU1V1fWwK6wLuRALVDAFX4D9H6Cv1sLvv5TWdh3MtYVG7uIKR07B/XdMJOPnFfMqeHXMw2Ctzml0TaMZwPwA "Perl 6 – Try It Online") Also uses the GCD trick, but uses the index of the end position of each run matched by the regex. Returns a negative number (truthy) if n-speak, zero (falsey) otherwise. [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` import Data.List f=(>1).foldr(gcd.length)0.group ``` [Try it online!](https://tio.run/##fZCxboMwEEDn8BUXJpAoaqeqQyKGDAztUImtqqpzbIhlgy0bxOdTny5p06VvujvfO599wWiUtdumR@/CDCecsX7Vcc76Q3F8KuveWRmK4Sxrq6ZhvpSP9RDc4rcR9QQHGNG/fUHhg55mqKEvs90H5G2r0lRrnasqgHV1LgRrpdzv82xXQd51XQhBa@29T21KKQCIMaY0xYhojOHO98SSSDWUiaQFyj2bpJJLMtmkk08DrhOemQcmMp5RDDKGYe3lBqd0LsRvzLkQ5/NdjQrXnqZpOGjTR7gKVhes/Pf1XqH5O//nHi6fpHPLIgQZ9GBan5a@SUKguF@Wks9s@wY "Haskell – Try It Online") Straightforward; uses the GCD trick. [Answer] # [Red](http://www.red-lang.org), 80 bytes ``` func[s][repeat n length? s[if parse/case s[any[copy t skip n t]][return on]]off] ``` [Try it online!](https://tio.run/##hZIxb4QwDIX3@xU@pqtE1bFqly4dbm3FhjIkxNwhuDhKghC/ntqNiqJT1X4Ttt97JIaAdvtE26pD/wpbP7uujaoN6FEncDChu6TrG8R26MHrEPGp0xG51m5tO/IrJIjj4FmblBjTHByQU4r6Xm0@DC5BD9X5jDgxRHUNsCxEIUyTtcdjddhFTdOEEIZh8N6zFhEBIMbIJT9rrcdxLOQfzMzwQFuGvUFqn@3ilwBJkAjJkBBJKWOeM4@ZmPEZzOjMmCm8Lz8UPVEac9fITWO67n4g3V1dfZ@hkJx5a1TDQmGy/6@Kv9r4y4v3AxSzd0s0z8aIV1Ykd5UblnY4WcIIjvhXQLSQCAzCVTs7oX0olCe8@bRCTNy41PCna/sC "Red – Try It Online") ## More idiomatic [Red](http://www.red-lang.org): # [Red](http://www.red-lang.org), 81 bytes ``` func[s][any collect[repeat n length? s[keep parse/case s[any[copy t skip n t]]]]] ``` [Try it online!](https://tio.run/##hZG9T8MwEMX3/hXXTkUKYkSwsDB0BXWLOvjj2kZ2fZbtKMpfH@6wiKwKwW@K37334o@EdvlE258251dYzmMwfT71KsxgyHs0pU8YURUI4DFcyvUNcu8QI0SVMj4ZlZEVDvSG4gwFshsiu8tJWGIaQoEz7A4HRM8QdR3ANBGl5L212@1us5qOx2NKaRiGGCN7EREAcs685G@llHOusX8wI8MDZRnOJlnHGpe8FEiDVEiHlEhLW/NceazkSqxgRVVcpcm@/NBo4tT6Tqii1sbcD0Rd3bvvPTSWA98adTBR8vb/q@Kncr/8eN1AM3u3ROOotWTliuSscsI2DntLmCEQvz@ihUKgEa4qWI/2oXHu8RbLDLmwcOngz9TyBQ "Red – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ġz₂=Ṁ ``` [Try it online!](https://tio.run/##dY2xSgNBEIZfZbP1JYVNSKE2FtcK14nF7u2qxy3MMuuxxBAIJ4Sk8xWstLSx0NoXuX2Rc4ZNIAh@1cz8//y/RlU/LB3cn42rKMX0Qsh4uUrbj9Q/p92bfMTOzuQs7d7lnXKB5vXwvV8Pny/jz@tT6vvz4WszjjeyLK11BEBRCBEjAKJzxkwmspAlSVCICOgM71VVIWLTNN57@rHWCiFCCLTSrJRq2/Zfm7eKxWuiI8itDEFO5N1nM7vZzrGcy8GczNH8rv6g6TbPTDMh4zM2c3C3Gfq5MgBdpzUXchk7WSdpcYTrDpWae07qNVHXxwNvWt7@Ag "Brachylog – Try It Online") Takes input through the input variable and outputs through success or failure. At first I thought this would actually be *shorter* than [my solution to Is it double speak?](https://codegolf.stackexchange.com/a/189406/85334), but then I realized that `ġ` can and will try a group length of 1. ``` ġ It is possible to split the input into chunks of similar length z₂ such that they have strictly equal length, and zipped together Ṁ there are multiple results = which are all equal. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-¡`](https://codegolf.meta.stackexchange.com/a/14339/), 8 bytes ``` ò¦ mÊrÕÉ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LaE&code=8qYgbcpy1ck&input=IkhIZWVsbGxsb28sLCAgd3dvb3JybGxkZCEhIg) ``` ò¦ mÊrÕÉ :Implicit input of string ò :Partition by ¦ : Inequality m :Map Ê : Length r :Reduce by Õ : GCD É :Subtract 1 :Implicit output of boolean negation ``` [Answer] # [Kotlin](https://kotlinlang.org), 78 bytes ``` {s->(2..s.length/2).any{i->s.chunked(i).all{z->z.length==i&&z.all{z[0]==it}}}} ``` [Try it online!](https://tio.run/##bZIxa8MwEIV3/4qrCcEG2y1ZSgv2UDpkK6XZSgc5lhNhVXIkOSEx/u3pXZRQ4uSbdPfu3sFDjXZSqGNrxJY5DlsmYfMafTkj1CpOizetJWcKcjj2Ni2iWZbZTHK1cuvHWZwxte9FWthsue5Uw6tIYE/K/pAWh/NYnovp9OC7308/WLoBubrouHUWbzBj2P6jjgJAnOk4OA3hfM65RLROEoDdTmtjpKyqh4cwuZ5cLBbGGCFE27a4wDlH1VqLJb4ZY03TjHc@kQ5BlVUIGhiqW@9BJuRCNuRDRuREVjdez57UYz2th3uYp/GMDV4ujAXaKct7Xa@U5XJ5VyWJ9k5SzaQ9Z4qJ6gR22sjqEuO/ej/HlrPmZpSNKG8m3iutu64syYdipCgogDCIg6DuFPwyoaIYer@nDUQOhPKf4tIm8McoJ1UUTvpN5DLLl1pV8QB5DpPeZbUw1g1hfJofgiE4/gE "Kotlin – Try It Online") ## Explanation ``` {s-> Take a string as input (2..s.length/2) The each string needs two parts at least, prevents the case "aaa" is 3-speak .any{i-> If there is any n (in this case i) that is n-speak return true s.chunked(i) Split into length i substrings .all{z-> All substrings z z.length==i Should be completely full, ie. "aaa"->["aa","a"] && And z.all{ All chars (it) z[0]==it Should be the same as the first char } } } } ``` [Answer] # [Scala](http://www.scala-lang.org/), 80 bytes ``` s=>"(.)\\1*".r.findAllIn(s).map(_.size).reduce((x,y)=>(BigInt(x) gcd y).toInt)>1 ``` [Try it online!](https://tio.run/##jZBBS8MwFMfv@xRZT4nUwk6i0LIND9tR3HEgSfM6a2MTktRtip@95hEmmk3wd8p7L@@X8Hc1V3zU4gVqT2oCBw@9dGRhDPmYTN64Is3do7dtvyurpdYKeF@OrqwyWrDtdnaVFbZo2l4ulFr31LHilRv6VLj2HVhhQQ41UHrIj6ys6LLdrXtPD4zsakmOrPA61KyajSY84FVPM28H/3zM2OTUaWi2WgGogNZ5Tsh@r7W1Skk5nWbs18XNZmOtbdvWGBPuAwAhxDkXynDmnHddl6w8BIZAGHIZCPsWaxMV6EAJWlCDHhShKVXdRK4jLmIiEOGRLpLs355I@rghxIVmHAhR15eGOEm35vP5z07WcOUgTTtkrXOy11bJ/wVsgHd/fO/7m8n8Xmo9DEKgA8PFhDCXM40QXFzM46yb1Fh@juMX "Scala – Try It Online") PS. Original solution was based on `split` function but it's longer (83 bytes). ``` s=>(s+s).split("(.)(?!\\1)").map(_.size+1).reduce((x,y)=>(BigInt(x) gcd y).toInt)>1 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes ``` GCD@@Length/@Split@Characters@#>1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@9/d2cXBwSc1L70kQ98huCAns8TBOSOxKDG5JLWo2EHZzlDtf0BRZl5JtLKCrp2CW7RybKyagr7DoQXVSh4eqak5QJCfr6OjoFBenp9fVJSTk5KiqKiko6DkAZTL11Eozy/KSVFUqv0PAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~83~~ ~~79~~ ~~76~~ 74 bytes ``` $_=s,(.)\1+,$t=length$&;$t/=2while$t%2-1;$r+=$t==($g||=$t);'',ge==$r&&/^$/ ``` [Try it online!](https://tio.run/##dY@xasMwEEB3fYUDqhMTO04CoTRG0KGDh3YouFtokWzhCItISDJe8u1171DrrW/R3enecWel06d5pl/M55tddjlscxqYlrc@XGla0VCy43RVWtLwcCwOFXVbBg1sQ/v7HaKsWq/zXjJGXZqWn7Scq2fONllFW0Z7qLJ9Nde1lBowJs@TZJqMcU7rrlutSNM0zjmllLUWOqSUSZJ47yGFmHM@DAN5B0YAUt4BYDjMbZTQQg09FNFEFd2BPEaKiI/YiIzwyBAhT38QrApBfv8hFKJtyRILUsNdJk8m43T33zFW8mEZsYwiL50x4ygE9uHquA3u8G1sUObm5@LttNsf9vC@Kh/O54@gNONaz4XVPw "Perl 5 – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 96 bytes ``` {<>({}())<>({}[({})]){{}<>({}<>){{(({})){({}[()])<>}{}}<>([{}()]({}<>)<>)}(<>)<>}{}}<>{}({}[()]) ``` [Try it online!](https://tio.run/##LYtBCsAgDAS/4tEc/IH4Cm/iIQULohTRY8jb02gLCbub2VwT6@Pujk2EfLDEFuBo0oUMRHyiD2rtvgEdqswHJt447bf8tXTYHv2gor8uEmOcc9Zaxxi991KKMWatpVE9IrbWxOEL "Brain-Flak – Try It Online") Uses the same GCD trick that many other submissions use. Output is 0 if the input is not n-speak, and a positive integer otherwise. ``` # For each character in the input { # Add 1 to current run length <>({}())<> # If current and next characters differ: ({}[({})]){ # Clean up unneeded difference {}<> # Move current run length to left stack, exposing current GCD on right stack ({}<>) # GCD routine: repeat until L=0 { # Compute L mod R {(({})){({}[()])<>}{}}<> # Move R to left stack; finish computing L mod R and push to right stack ([{}()]({}<>)<>) } # Push 0 for new run length (<>)<> }{} } # Output GCD-1 <>{}({}[()]) ``` [Answer] # Oracle SQL, 182 bytes ``` select+1-sign(min(length(x)-(select sum(length(regexp_substr(x,'(.)\1{'||i||'}',1,level)))from t connect by level<length(x))))from(select x,level i from t connect by level<length(x)) ``` It works with an assumption that input data is stored in a table t(x), e.g. ``` with t(x) as (select 'HHeelllloo,, wwoorrlldd!!' from dual) ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~29~~ 23 bytes ``` {~|/(&/s@&1<s)!s:#'=:x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrquRl9DTb/YQc3QplhTsdhKWd3WqqL2f5pSSEhIUVFRZmZmQUFBTk5OamqqgoJCcXExkAtkJyYmZmdnK/0HAA "K (ngn/k) – Try It Online") edit: removed some unnecessary colons (i know when a monadic is required but it's not always clear to me if there's ambiguity so i default to including the colon) and changed the mod `x-y*x%y` to ngn/k's `y!x`, which meant i could remove a variable assignment [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~24~~ 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. ``` ⊂∊1↓⍳∘≢{⍵/⍨(≢⍵)⍴⍺↑⍺}¨⊂ ``` [Try it online!](https://tio.run/##fZDPSsNAEMbvPsX0lBZSpHgQvSrSnkSbF9jtTjVkzS67CaWIF4VSCymKCJ499eZBvXjso@yLxNksVnrpBwnzzXy//ce07Iopk@qqrt3i3s0XPTd7cdWnm7@5x/dbV/3su@qbvlWbPJUdV31R182ee3frFTH12M2eXLV0y9fBuVs8rD8OaEhueHlC/6Q/GNZRYkqEEbNoj6O9MUT9PqIkKRXHAJOJUsZIKUSr1YyTJDHGpGmqtaYUIgKAtZYs1YyxLMua4AWpJFGLCRJRxnsdQE961LMe9rTHPR8WOAzqBtkgHYRBLCgLaqijPzXOTznflMFyPhr9t7ynRHTGpN1@CHoGFcNEGSl23V0jy7Z22OzUdE@FUmXJuc/72/rD@yMHBNpCoYVcFZAjCigUcIRrlguJotNk2nijiynYwqT5VQw7878 "APL (Dyalog Unicode) – Try It Online") `⊂` enclose the string to treat map using the entire string  e.g. `"aaabbb"` `⍳∘≢{`…`}¨` for each of the `⍳` **ɩ**ndices 1 through the tally of characters in the string:  e.g. `3`  `⍺↑⍺` take the current number of elements from the current number, padding with 0s  e.g. `[3,0,0]`  `(≢⍵)⍴` cyclically **r**eshape into the shape of the tally of characters in the string   e.g. `[3,0,0,3,0,0]`  `⍵/⍨` use that to replicate the string's characters   `"aaabbb"` `1↓` drop the first one (*n* = 1) `⊂∊` is the the entire string a member of that list? [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes ``` M!`(.)\1* . . ^(..+)(\1|¶)*$ ``` [Try it online!](https://tio.run/##dY/BCsIwDEDv@YoOFLo5CzuJd8FdPAg7Dlm79jBabOkcu/hdfoA/NhOqu/l6SdK8kETzGO5y2fJzt1yyjou8rQoQ@G5ciF3O2@r5fuXFZlnq2hiHeF@WjM2z9zE6p3WWQdM0McZhGEII2GGMYYyN44gpxlJKay1ckQnBVGoEjUh5SBJZpJFHIpmkkmvhkNgnxkRImIRM2AQcfwBVlYLvP4ZK9T2ssYIa7/Ilm310@t8xwUi7jlhHwUl7P01KUR@tTtvQDiDhAw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` M!`(.)\1* ``` Split the text into runs of identical characters. ``` . . ``` Replace them all with the same character. ``` ^(..+)(\1|¶)*$ ``` Check whether the GCD of the lengths of the runs is greater than 1. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mR`](https://codegolf.meta.stackexchange.com/a/14339/), 12 bytes ``` ÊÆóXäd_äe e ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=ysbzWMOkZF/kZSBl&input=W1snSCcsJ0gnLCdlJywnZScsJ2wnLCdsJywnbCcsJ2wnLCdvJywnbycsJywnLCcsJywnICcsJyAnLCd3JywndycsJ28nLCdvJywncicsJ3InLCdsJywnbCcsJ2QnLCdkJywnIScsJyEnXSwKWydUJywnVCcsJ1QnLCdyJywncicsJ3InLCdpJywnaScsJ2knLCdwJywncCcsJ3AnLCdsJywnbCcsJ2wnLCdlJywnZScsJ2UnLCcgJywnICcsJyAnLCdzJywncycsJ3MnLCdwJywncCcsJ3AnLCdlJywnZScsJ2UnLCdhJywnYScsJ2EnLCdrJywnaycsJ2snXSwKWydRJywnUScsJ1EnLCdRJywndScsJ3UnLCd1JywndScsJ2EnLCdhJywnYScsJ2EnLCdkJywnZCcsJ2QnLCdkJywncicsJ3InLCdyJywncicsJ3UnLCd1JywndScsJ3UnLCdwJywncCcsJ3AnLCdwJywnbCcsJ2wnLCdsJywnbCcsJ2UnLCdlJywnZScsJ2UnLCcgJywnICcsJyAnLCcgJywncycsJ3MnLCdzJywncycsJ3AnLCdwJywncCcsJ3AnLCdlJywnZScsJ2UnLCdlJywnYScsJ2EnLCdhJywnYScsJ2snLCdrJywnaycsJ2snXSwKWyc3JywnNycsJzcnLCc3JywnNycsJzcnLCc3JywnLScsJy0nLCctJywnLScsJy0nLCctJywnLScsJ3MnLCdzJywncycsJ3MnLCdzJywncycsJ3MnLCdwJywncCcsJ3AnLCdwJywncCcsJ3AnLCdwJywnZScsJ2UnLCdlJywnZScsJ2UnLCdlJywnZScsJ2EnLCdhJywnYScsJ2EnLCdhJywnYScsJ2EnLCdrJywnaycsJ2snLCdrJywnaycsJ2snLCdrJ10sClsnOScsJzknLCc5JywnOScsJzknLCc5JywnOScsJzknLCc5J10sClsnYScsJ2EnLCdhJywnYScsJ2InLCdiJ10sClsnYScsJ2EnLCdhJywnYScsJ2EnLCdhJywnYScsJ2EnLCdiJywnYicsJ2InLCdiJywnYycsJ2MnXSwKWydhJywnYScsJ2EnLCdhJywnYScsJ2InLCdiJywnYicsJ2InLCdiJ10sClsnSCcsJ2UnLCdsJywnbCcsJ28nLCcsJywnICcsJ3cnLCdvJywncicsJ2wnLCdkJywnISddLApbJ1QnLCdUJywnVCcsJ3InLCdyJywncicsJ2knLCdpJywnaScsJ3AnLCdwJywncCcsJ2wnLCdsJywnbCcsJ2UnLCdlJywnZScsJyAnLCcgJywnICcsJ3MnLCdwJywnZScsJ2EnLCdrJ10sClsnYScsJ2EnLCdhJywnYScsJ2EnLCdhJywnYScsJ2EnLCdhJywnYScsJ2EnLCdhJywnYScsJ2EnLCdhJywnYScsJ2InXSwKWydEJywnZCcsJ28nLCdvJywndScsJ3UnLCdiJywnYicsJ2wnLCdsJywnZScsJ2UnLCcgJywnICcsJ3MnLCdzJywncCcsJ3AnLCdlJywnZScsJ2EnLCdhJywnaycsJ2snXV0) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 14 bytes ``` £─╞möl╠mÅ▀£╙╓┴ ``` [Try it online!](https://tio.run/##dY87DsIwDEB3ThGmLmVG7AxdkXqBhASokspRStW1CyeAIrEgJK6AOADcJBcJtgyIhTf59yy7ltvNGtwqpcc1Hvo4nOvn3cXhUj938dhjcTjFYR8Pt5SyojDGIQB5LkTXAYTgnNbjcTbKyrIMIVRV5b3HGWOMEKJpGkwxllJaa3FsgbQIFqRG0AmUe9bII5FMUsklmWzSp8yEaRjPGEYylkFn9gFj6ij1DjhRarn8FCijboF/Qi46CE7/f84baX9WfVdiba4B2lYpmqVn6Dq6KUsv "MathGolf – Try It Online") ## Explanation Checks all possible divisions of the input string into equal length chunks, and checks if there is a partition in which all chunks have just one unique character. ``` £ length of string with pop ─ get divisors ╞ discard from left of string/array (removes 1) mö explicit map using 7 operators l push input ╠ divide input into chunks of size k mÅ explicit map using 2 operators ▀£ number of unique elements of list ╙ get maximum number of unique characters per chunk loop ends here ╓ get the minimum of all maximums ┴ check if equal to 1 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes Outputs **0** for falsy inputs or a positive integer otherwise. ``` tiFhCr8 ``` [Try it online!](https://tio.run/##dY8xDsIwDEV3nyLdCyswg1BXpF4gaSI1SpAjp1UFlw@2DN14k534Wd/ltczt2ZZ4n690bsYf320YQsgMYt8bs22IRDl733UwjiMRxRhLKTwRQjDG1Fq55dpam1KCB7My3FrPsEHSF5XEEk08EcUUVdwEJ@WgVKUoQbFKUuDyA@TVOfj@c@ncNMFeOxj4LuzNhpT9v2NKsGlfsa@Cm0dcV@dkTqJLGsnwAQ "Pyth – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` <1iFhMr8 ``` [Try it online!](https://tio.run/##K6gsyfj/38Yw0y3Dt8ji/38lcwjQhYBiCCiAgFQISISAbAhQAgA "Pyth – Try It Online") ``` <1iFhMr8Q Implicit: Q=eval(input()) Trailing Q inferred r8Q Run length encode Q into [count, character] hM Take first element of each iF Reduce by GCD <1 Is 1 less than the above? Implicit print ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 38 bytes ``` for$i(1..y///c){print/^((.)\2{$i})*$/} ``` [Try it online!](https://tio.run/##dY89a8MwEEB3/QoleLCLY9FCCd07eC14DAXJUkFI@MQpxpSQv171rmq99U339Y675DA@l/IB2Pj2cRg@lVJzd0vol6t6b9uhuzzdGn/vHhp1Lz/l42U5lnF0LhIAfS/ltgEgxmjt4SCmaUJE731KiSacc1LKnDOlFGutQwjijVgJSrUlyEDOU5XYYo09Ftlkld0gzpVTJVdSxVV0JVTEyx@Cq8aI3z6Fxsyz2GMjRvoLerkBRvvfM8npsK/YV4lXC7CuxvAcn87X8A1fkK4ellxOyzc "Perl 5 – Try It Online") The `print"\n"` in the footer is needed to separate the outputs. Straightforward loop through all possible `n`s. Outputs nothing for "1-speak", anything else for n-speak where n > 1. ]
[Question] [ In chat, we are often fast-typers and don't really look at the [order](https://chat.stackexchange.com/transcript/message/41967809#41967809) of [letters](https://chat.stackexchange.com/transcript/message/41967812#41967812) before posting a message. Since we are lazy, we need a program that automatically swaps the last two letters in our words, but since we don't want to respond too late, the code must be short. Your task, if you wish to accept it, is to write a program that flips the last two letters of each word in a given string (so the word `Thansk` turns into `Thanks`). A *word* is a sequence of two or more letters in the English alphabet delimited by **a single** space. * The string / list of *characters* you receive as input is guaranteed to only contain alphabetic characters and spaces (ASCII [97 - 122], [65 - 90] and 32). * You can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. * The output may have one trailing space and / or one trailing newline. * The input will always contain words only (and the corresponding whitespace) and will consist of at least one word. This is code-golf, so the shortest submission (scored in bytes), in each language wins! ### Test cases Note that the strings are surrounded with quotes for readability. ``` Input -> Output "Thansk" -> "Thanks" "Youer welcoem" -> "Youre welcome" "This is an apple" -> "Thsi si na appel" "Flippign Lettesr Aroudn" -> "Flipping Letters Around" "tHe oDd chALlEneg wiht swappde lettesR" -> "teH odD chALlEnge with swapped letteRs" ``` Or, for test suite convenience, here are the inputs and their corresponding outputs separately: ``` Thansk Youer welcoem This is an apple Flippign Lettesr Aroudn tHe oDd chALlEneg wiht swappde lettesR ``` ``` Thanks Youre welcome Thsi si na appel Flipping Letters Around teH odD chALlEnge with swapped letteRs ``` Thanks to [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) for the title. This was originally a [CMC](https://chat.stackexchange.com/transcript/message/41967829#41967829). [Answer] # [V](https://github.com/DJMcMayhem/V), 4 ~~5~~ bytes ``` òeXp ``` [Try it online!](https://tio.run/##HcsxDsIwEETR3qeYq0QCRJEKpYDSikexxbJe2Q6@F1fgYCZC@uX77zG@H95tjCV6rU/3yDsLOmXNfLklpoojr/BmQneRZJY2xczWWAumkvegrl2JfApY4zTLWbmhp9hQ@7EFQv769gM "V – Try It Online") `||` denotes the cursor The buffer starts with `|w|ord and more words` and the cursor being on the first character. Recursively `ò` go to the `e`nd of a word `wor|d| and more words` remove `X` the character to the left of the cursor `wo|d| and more words` `p`aste it over the next character `wod|r| and more words` Implicit ending `ò`, repeat the same process for other words until the end of the buffer is reached [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḳœ?@€2K ``` A monadic link taking and returning lists of characters **[Try it online!](https://tio.run/##y0rNyan8///hjk1HJ9s7PGpaY@T9//9/JbeczIKCzPQ8BZ/UkpLU4iIFx6L80pQ8JQA "Jelly – Try It Online")** ### How? ``` Ḳœ?@€2K - Link: list of characters Ḳ - split at spaces 2 - literal two € - for €ach: @ - with sw@pped arguments: œ? - nth permutation (the 2nd permutation has the rightmost elements swapped) K - join with spaces ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 122 bytes ``` {(({})[((((()()){}){}){}){}])((){[()](<{}>)}{}){{}<>(({}({}))[({}[{}])])(<>)}{}({}<>)<>}<>(({}({}))[({}[{}])]){({}<>)<>}<> ``` [Try it online!](https://tio.run/##dYs9CoAwDIWv4pgMvUHpKdxKhyr@FKWD7RZy9pgIgovhLXnv@6Yrl@rWMx8iBECMEewQEPV5k1ArioAJPHFAtpbYB1PMUo04GqiofwCwHX34oeizi4x7aYOmL62Xuombbw "Brain-Flak – Try It Online") The worst language for the job :) ~~Readable~~ Slightly more readable version: ``` { (({})[((((()()){}){}){}){}])((){[()](<{}>)}{}) { {} <> (({}({}))[({}[{}])]) (<>) } {} ({}<>)<> }<> (({}({}))[({}[{}])]) { ({}<>) <> }<> ``` [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` print(*(w[:-2]+w[:-3:-1]for w in input().split())) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0ujPNpK1yhWG0QZW@kaxqblFymUK2TmAVFBaYmGpl5xQU4mkNbU/P@/JCOzWAGIkvNTUtPzc9IA "Python 3 – Try It Online") This answer abuses Python 3's behavior of print: Multiple arguments are printed with a single space between them. Of course, we can't just give it multiple arguments because we don't know how many words will be in the input. So we use the [splat operator](https://stackoverflow.com/q/2322355/3524982). Basically ``` print(*[a,b,c]) ``` is exactly the same thing as ``` print(a,b,c) ``` Abusing that makes a full program turn out shorter than a function/lambda where we'd have to use `' '.join` or something similar. [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` (f=<<).words f[a,b]=b:a:" " f(x:r)=x:f r ``` [Try it online!](https://tio.run/##BcGxDoIwEADQna@4NA6QqB/Q0MHFyY1RHA7o1cZaLtcS@HrP995YPj4lDW7Ullzfd9d9laU09MTz9HKTRWvANNQeVjp3WALRL8YMDnirQxU4QQBzT5E5hgwPX6svAjdZtyUb/c2UMBS9zMx/ "Haskell – Try It Online") Usage example: `(f=<<).words $ "abc xyz"` yields `"acb xzy "`. [Answer] # [Retina](https://github.com/m-ender/retina), 13 bytes ``` (.)(.)\b $2$1 ``` [Try it online!](https://tio.run/##HcuxCsIwEIDh/Z7ihg66CPoGBRWHTtKl4BKbozk8LyG5ksePQfjG/89krK61w@nYvd4wXIZza3NwWj6wxJ0yVpI10hfmwAU7p@hSEoK7cEq8KU5kRiXjmOPuFexBGK8e1zBOclPasHIwLLVvnlD@9fMH "Retina – Try It Online") Link includes test cases. [Answer] # [Matlab](https://www.mathworks.com/products/matlab.html) (R2016b), ~~51~~ 50 bytes Saved ~~49~~ 50 (!) bytes thanks to @Giuseppe. ``` function s(a),regexprep(a,'(\w)(\w)( |$)','$2$1 ') ``` And my previous answer: # [Matlab](https://www.mathworks.com/products/matlab.html) (R2016b), 100 bytes (Just for the fun of it :P) ``` function s(a),a=regexp(a,' ','split');for i=1:length(a),fprintf('%s ',a{i}([1:end-2 end end-1])),end ``` Explanation: ``` function s(a) % Defining as a function... a=regexp(a,' ','split'); % Splits the input string at the spaces for i=1:length(a) % Loops through each word fprintf('%s ',a{i}([1:end-2 end end-1])) % And prints everything with the last two characters swapped. end ``` [Answer] # C, ~~62~~ ~~58~~ 54 bytes *Thanks to @Dennis for saving ~~four~~ eight bytes!* ``` f(char*s){s[1]>32||(*s^=s[-1]^=*s^=s[-1]);*++s&&f(s);} ``` [Try it online!](https://tio.run/##XZBBa8MwDIXv/hWCQRun7Vg7tkuWQmEbO/Q0ehlZCsFRYjPXCZFDDm1@e2a3I4EJHcR7Tx9CYlUKMQxFIGTWhMTPlKzT7ePmcglCOsaUrNbpMR5HHoWLBc1mRUA86oc7ZYRuc4QXsrmq7uWWMWUsnDJlAs7ODFx5MpBtks3TcxpdpU4qjRAUJVoKnLUE5y3BQwzn18ht15cHaog9QqPxcR5NZgFeSbQ7DuIY5t9mzkd3gviacvAwEfpxKv6x6/Z23Z/Us344yMzQD/uqWmygQy0qPLGDVASuMwNZXWtk71rVtSoN7NFapAZ2TdXmhtkPhOo1dx/Z7fWbwRI6JS1Q59bcE/U1/fkL) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 60 bytes ``` [A,B]+[B,A]. [A,B,32|U]+[B,A,32|Y]:-U+Y,!. [A|U]+[A|Y]:-U+Y. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P9pRxylWO9pJxzFWjwvE0TE2qgmFiICYkbFWuqHakTqKIFmwhCNMTO///8SS/Nz45PyU1GIN9ZLU4hKF4pKizLx0dR1noJgmmNSO0EFS5ZIKonUiNPUA "Prolog (SWI) – Try It Online") ## Explanation First we define the base case: ``` p([A,B],[B,A]). ``` This means that the last two letters will always be swapped. Then we define what happens if we are right next to a space: ``` p([A,B,32|U],[B,A,32|Y]):-p(U,Y),!. ``` Two strings match if right before a space the letters before the space are swapped and the remainder if the strings match. We then use `!` to cut. Our last case is if we are not next to a space the first two letters need to match. ``` p([A|U],[A|Y]):-p(U,Y). ``` [Answer] # [Wolfram Language](http://reference.wolfram.com), 117 bytes ``` StringReplace[RegularExpression["\\b[[:alpha:]]{2,}\\b"]:>StringDrop[StringInsert["$0",StringTake["$0",{-1}],-3],-1]] ``` [Try it online!](https://tio.run/##JYvBasMwEETv/YpF9OjQpr0ZWhpISgs5FNeXouiwsTeWiCwJaY0Lxt/uKjXswM4bXo@sqUc2DS6Xl@Wbo3FdRcFiQ7KibrAYD78hUkrGOylOp7OUJdqgsVRqeirmTIQqX1dzH32Q6/vpEkWW4v5RFCup8UprnzbbWRWb55ytUstXXhkkXODhDSZRa3TpKgoQP36gCCPZxlN/A7U2CfKhAwzBUmZ3AOLdmhBM5@BIzJQi7KIfWncz@IPA71to9O5oD446GI1mSGP2WwL7L1RiBrX8AQ "Wolfram Language (Mathematica) – Try It Online") Applied to the test strings. ``` StringReplace[ RegularExpression["\\b[[:alpha:]]{2,}\\b"] :> StringDrop[StringInsert["$0", StringTake["$0", {-1}], -3], -1]] /@ {"Thansk", "Youer welcoem", "This is an apple", "Flippign Lettesr Aroudn", "tHe oDd chALlEneg wiht swappde lettesR"} // Column ``` > > > ``` > Thanks > Youre welcome > Thsi si na appel > Flipping Letters Around > teH odD chALlEnge with swapped letteRs > > ``` > > [Answer] # [R](http://www.r-project.org), ~~111~~ ~~51~~ 41 bytes Courtesy of @Giuseppe, a regex approach which blows my old method out of the water. ``` cat(gsub("(.)(.)\\b",'\\2\\1',scan(,""))) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 28 bytes ``` 1↓∊((¯2↓⊢),2↑⌽)¨' '(,⊂⍨⊣=,)⍞ ``` `⎕ML` and `⎕IO` are both `1`, [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TDB@1TX7U0aWhcWi9EYjZtUhTB8iY@Khnr@ahFeoK6ho6j7qaHvWueNS12FZH81HvvP//g/NzU0syMvPSFYoS81LycxXS81OLFTJSi1IB "APL (Dyalog Classic) – Try It Online") # Explanation * **`... (,⊂⍨⊣=,) ...`** Split (while keeping borders, and appending a border to the beginning) ... * **`... ⍞`** ... the input ... * **`... ' ' ...`** ... at spaces. * **`... ( ... )¨ ...`** Then, to each element of that: + **`... , ...`** Concatenate ... + **`... (¯2↓⊢) ...`** ... every item except the last two ... + **`... 2↑⌽ ...`** ... with the reverse of the last two elements. * **`1↓∊ ...`** Finally, return all but the first element of the flattened result. [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 34 bytes ``` s=>s::gsub("(.)(.)( |$)","$2$1$3") ``` [Try it online!](https://tio.run/##SyvNy678n2b7v9jWrtjKKr24NElDSUNPE4QUalQ0lXSUVIxUDFWMlTT/FxRl5pVopGlk5usVpSamaGhqav4v8UhVyHdJUUjOcPTJcc1LTVcoz8woUSguTywoSElVyEktKUktDgIA "Funky – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 45 bytes *-2 bytes thanks to H.PWiz.* ``` (r.g.r=<<).words g(x:y:z)=' ':y:x:z r=reverse ``` [Try it online!](https://tio.run/##DcY7DoQgEADQ3lNMjIlayAGIcwpbG4IDbhYXMvg/vLO@6s0mfykEcThKw8orxr5v1RF5yoVvTn3pu8Ua6jenvgtGpp04kyzm8wOEtK3DylCBg/KKGxMcFGxcqJTHumB8ls6m9Ac "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~20 19~~ 11 bytes Credit to @Bolce Bussiere ``` 1&A.&.>&.;: ``` [Try it online!](https://tio.run/##RYzBCgIhGITvPcWc1pvQtSgQKjrsKfbSUfTf1TIVdfHxbQlCmMvMNzOv1uYTx34QfODngR8PjZQJmMEmI31@s93fP8NKCZWcCvTp8WRsxibpIWN01MnN2Rjt4jFSKZQTRAqr9r1Q7oRw0VBGjO7qaUG1piDX7UgT3G/2YO0L) ``` &.;: on words &.> on each A. apply the permutation 1& number 1, swap the last two elements ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 24 bytes ``` /0RR'.%$1\' o \ix*o ne@/ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fIChIXU9VxTBGXSGfKyazQitfIS/VQf///5CMzGIFIErMU0gsKMhJBQA "Alice – Try It Online") ### Explanation ``` /...\' o \.../ ``` This forms a loop where the loop body is a linear Ordinal snippet and we execute `' o` in Cardinal mode between every two loop iterations. The latter just prints a space. Unfolding the zigzag structure of the Ordinal code, the linear loop body actually looks like this: ``` iR*' %e10xRo.n$@ ``` Breaking this down: ``` i Read all input. On subsequent iterations, this will push an empty string. R Reverse. * Join. On the first iteration, this joins the input to an implicit empty string, which does nothing. On subsequent iterations, it will join the empty string to the word on top of the string, thereby getting rid of the empty string. ' % Split around spaces. On the first iteration, this will split the input into individual words. On subsequent iterations, this does nothing. e10 Push "10". x Use this to permute the (reversed) word on top of the stack. In particular, the word is rearranged with the same permutation that is required to sort the string "10", which means the first two letters get swapped (which correspond to the last two letters of the actual word). R Reverse the swapped word. o Print it. .n$@ If there are no words left on the stack, terminate the program. ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~109~~ 100 bytes Edit: don’t have to handle one letter words ``` ,[>++++[-<-------->],]>+[-<[>++++[<++++++++>-]<[->>+<<]<]<<[->>+<<]>[[-<+>]>]<<[>+>+>]-<]>>>>>>>[.>] ``` [Try it online!](https://tio.run/##PYrBCoNADER/JfeYfkEYKLTQQ0@9hhysbqtUrNQVP39dcemby/Bmnr@6H19L80mpMnDGRKUArxy7KItyAeJqArCq5/w7LJ8Zjt2Bc1yyPbATPKV4C/S9tNR05/twHcOb1r6LNK/1NLWBhhBjmB8b "brainfuck – Try It Online") Prints a trailing space ### How It Works ``` ,[>++++[-<-------->],] Puts input on the tape and subtracts 32 from each character This separates each word >+[- Start the loop <[>++++[<++++++++>-]<[->>+<<]<] Add 32 to each letter of the word Skip this on the first iteration for the last word <<[->>+<<]>[[-<+>]>] Swaps the last two letters of the word <<[>+>+>]- If there is another word to the left continue loop Also set up to add a space to the end of the word <] End loop >>>>>>>[.>] Print the modified string ``` ### Previous version, 109 bytes ``` ,[>++++[-<-------->],]>+[-<[>++++[<++++++++>-]<[->>+<<]<]<<[[->>+<<]>[[-<+>]>]<<[<]]>[>]<[>+>+>]-<]>>>>>>[.>] ``` [Try it online!](https://tio.run/##NYu9DoJAEIRfZftjfYLNJCaaWFjZXrZAWIVIkMgRHv9YyPlNMz@Z56/ux9fSfHKuIoITWbgArRR7URYJBbBKZCCIqEviP8CdBCj2UtSzO3@7lH0@iCdozulm9L201HTn@3Ad7U1r3yWa13qaWqPBUrL5sQE "brainfuck – Try It Online") [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 8 bytes ``` ..\b ⌽⍵M ``` [Try it online!](https://tio.run/##KyxNTCn6/19PLyaJ61HP3ke9W33//w/JSMwrzuaKzC9NLVIoT81Jzk/N5QrJyCxWAKLEPIXEgoKcVC63nMyCgsz0PAWf1JKS1OIiBcei/NKUPK4Sj1SFfJcUheQMR58c17zUdIXyzIwSheJyoLaUVIUcsOogAA "QuadR – Try It Online") [Answer] # Google Sheets, 33 Bytes Anonymous worksheet function that takes input from cell `A1` and outputs to the calling cell ``` =RegExReplace(A1,"(.)(.)\b","$2$1 ``` -2 Bytes Thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for the use of `(.)` over `(\w)` [Answer] # [Julia 1.0](http://julialang.org/), 30 bytes ``` !s=replace(s,r"..\b"=>reverse) ``` [Try it online!](https://tio.run/##HY1BCsIwEEX3OcU0qxZKwAO0UFBx0ZW4EbqJ7dBGx2nIpNaFd49V@KvHe/z7Qs7u3illUgX0ZHvMpQzamO6mqzrgC4NgkWyltVaXybI81HVeMMCK1M/43KAT2GYZrPeE6kjOezcytBgjSoAmzMvAKp4Q5v0A/dS0dGAcYXVTBFm3bECgv31WvyNlMvHkYm5L3bEuwHxq8MFxJE5f "Julia 1.0 – Try It Online") detect end of words with a regex `r"..\b"` and apply `reverse` on the matches [Answer] # Curry, 33 bytes Tested in both [KiCS2](https://www-ps.informatik.uni-kiel.de/kics2/) and [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/). ``` f(u++[x,y])=u++[y,x] (>>=f).words ``` Curry's powerful patterns let it beat [the Haskell answer](https://codegolf.stackexchange.com/a/151919/56656)! To test it you can use [Smap](https://smap.informatik.uni-kiel.de/smap.cgi?new/curry). Just select `KiCS2 2.2.0` or `PAKCS 2.2.0` and paste the following complete code: ``` f(u++[x,y])=u++[y,x] g=(>>=f).words main=f "Hello world an happy day" ``` [Answer] # [Perl 5](https://www.perl.org/), 19 + 1 (`-p`) = 20 bytes ``` s/(\w)(\w)\b/$2$1/g ``` [Try it online!](https://tio.run/##K0gtyjH9/79YXyOmXBOEY5L0VYxUDPXT//8PycgsVgCiRIWS1OKSf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online") [Answer] # [PHP](https://php.net/), 119 107 bytes Edit: thanks to totallyhuman ``` <?php foreach(explode(" ",trim(fgets(STDIN)))as$w)echo substr($w,0,strlen($w)-2).strrev(substr($w,-2))," "; ``` [Try it online!](https://tio.run/##RYxBCsIwEEWvMpQuZiCKuFUQQQRB3OgFajttAmkyTFLr7WN27t5/fJ5YKeV4EiswRuWut8hf8XFgbKAxWd2M48Q54fN1uT2IqEvtStzbCGl5p6zYrmZnKngOlWmzp21dyh/8H6okU4OHUq7eibgpwJ1z5qRw1rgM4Qc "PHP – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` foldr(%)" " a%(b:' ':r)=b:a:' ':r a%s=a:s ``` [Try it online!](https://tio.run/##JYtBi8IwFITv/oohrKjg/oFCD4KKh3rZ9bKoh2f72gRfk5Ck9N9vjLswh5lvZjTFJ4vkvr7l3kkX1suNglrQcv2oVlhVYVM/Kvq3hcaaqphHMhY1RvJn@Cl9p9BYfLwzelzVRZONT7VVP27igJmldTyWfNEmoogsyHvhgo5ivDeDRcMpcQzYBTd1tjTpxHD7Dq3eNXKwPGA2OiHO5dox5G//pe75t@2Fhpg/W@9f "Haskell – Try It Online") Outputs with a trailing space. The repeated `' ':r` looks wasteful. But `a%(b:t@(' ':r))=b:a:t` is the same length and `a%(b:t)|' ':_<-t=b:a:t` is one byte longer. --- # [Haskell](https://www.haskell.org/), 41 bytes ``` f(a:b:t)|t<"A"=b:a:f t|1>0=a:f(b:t) f e=e ``` [Try it online!](https://tio.run/##HYtBi8IwFITv@yuG4MGFFfRa7EJBxUO9qJdF9vBsX5pgmobmlV787Wbjwhxm5psxFB/sXEp6ScW9kM@nbFWlyntBhYY8N9/rMrvlG31ocMmpJ@tRoqdwQpjkImPtsXhnaNzU1ZCPD/WlfoaJR8zsmoH7nK/GRmSRB4XgOFcHZ0OwnUfNIhxHVOMwtT4TOTKGXYvGVLXbe@4wWyOIc762DPe/P6vf9Gq0oy6mVRPCHw "Haskell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~53~~ 45 bytes ``` u[a,b]=[b,a] u(a:b)=a:u b unwords.map u.words ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/vzQ6UScp1jY6SScxlqtUI9EqSdM20apUIYkrzbY0rzy/KKVYLzexQKFUD8z@n5uYmWdbUJSZV6KSpuQBNCJfITy/KCdF6T8A "Haskell – Try It Online") ## Explanation `u` is a function that swaps the last two letters of a word. To apply it to all the words we use `words` to split the list, map it across all of the words and then use `unwords` to put it back together. [Answer] # [sed](https://www.gnu.org/software/sed/), ~~20~~ 17+1 (-r) = 18 bytes ``` s/(.)(.)\b/\2\1/g ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1hfQ08TiGKS9GOMYgz10///D8nILFYAosQ8hcSCgpxUrn/5BSWZ@XnF/3WLAA "sed – Try It Online") [Answer] # PHP, 65 bytes requires PHP 7.1 (or later) ``` for(;$s=$argv[++$i];$s[-1]=$s[-2],$s[-2]=$c,print"$s ")$c=$s[-1]; ``` takes sentence as separate command line arguments. Run with `-nr`. --- working on a single string, **77+1 bytes**: ``` foreach(explode(" ",$argn)as$s){$c=$s[-1];$s[-1]=$s[-2];$s[-2]=$c;echo"$s ";} ``` Run as pipe with `-nR`. --- [Answer] # Java 8, 35 bytes ``` s->s.replaceAll("(.)(.)\\b","$2$1") ``` Port of [*@TaylorScott*'s Google Sheets answer](https://codegolf.stackexchange.com/a/152412/52210), after I golfed two bytes. EDIT: I see it's now a port of [*Neil*'s Retina answer](https://codegolf.stackexchange.com/a/151947/52210) after my two golfed bytes. **Explanation:** [Try it online.](https://tio.run/##hY5PS8NAEMXv/RSPpYcEbECvRSGg4qH2oL2I9bDdjMm2m9lld9Mgks8e15qrBN7A/PvNm6M8y5V1xMfqNCojQ8Cz1Py9ADRH8p9SEba/JfAaveYaKpuSkK9Tf0iRFKKMWmELxi3GsLoLhSdnEl4ak4msyJP2@4O4Esub5bXIx/Uf6LqDSeDEn62u0KYPJpP3D8h8sv8KkdrCdrFwaRQNZ1yoTOwayeEk8ss3/6@92Y48ejLKUju7vWt0QJJkSOcMzQKPRjuna8aGYqTgUXrbVTzLxSeCva@gmnJjHphq9LqJCH2yrQjmcu1lOjMshvEH) ``` s-> // Method with String as both parameter and return-type s.replaceAll("(.)(.) // Replace any two characters, \\b", // with a word-boundary after it (space or end of String) "$2$1") // With the two characters swapped ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~38~~ ~~36~~ 32 bytes ``` ~~s=>s.replace(/(.)(.)( |$)/g,"$2$1 ")~~ ``` ``` s=>s.replace(/(.)(.)\b/g,"$2$1") ``` [Try it online!](https://tio.run/##bYyxCsIwFEV3v@JROiSgLbpKhYKKQyfp4hiS1yQak5CkdvHfY3WUwtnuuefOXizyoH3aWCcwD02OzSFWAb1hHElNKvoF3iWt5bood@UWCpr33NnoDFbGSTKQolfMxkdB6ep/ubkRA0xouMPnktArHWGGWWDeG1xyzkZ7r6WFDlPCGKANbhR2SU0XBHcUwFXbmZNFCZNWCeI0xwWC@QWu8zN/AA "JavaScript (Node.js) – Try It Online") RegExp approach courtesy @Giuseppe (although I thought of this independently), assuming words separated by only one space -2 for only considering 1 space and add trailing space -4 Thanks @Shaggy [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 22 bytes ``` " "/{x@prm[!#x]1}'" "\ ``` [Try it online!](https://tio.run/##y9bNz/7/X0lBSb@6oCg3uiLWsFYdyItRcsvJLCjITM9T8EktKUktLlJwLMovTclT@v8fAA "K (oK) – Try It Online") **Example:** ``` " "/{x@prm[!#x]1}'" "\"Hello World" "Helol Wordl" ``` **Explanation:** Port of [FrownyFrog](https://codegolf.stackexchange.com/a/151933/69200)'s solution to save **1 byte**. I'll come back to this. ``` " "/{prm[x]1}'" "\ / the solution " "\ / split input on " " { }' / apply lambda to each prm[x] / permute input x 1 / and take the 2nd result " "/ / join with " " ``` **Previous solution:** * `" "/-2{(x_y),|x#y}'" "\` **23 bytes** ]
[Question] [ Given a positive number `n`, rotate its base-10 digits `m` positions rightward. That is, output the result of `m` steps of moving the last digit to the start. The rotation count `m` will be a non-negative integer. You should remove leading zeroes in the final result, but not in any of the intermediate steps. For example, for the test case `100,2 => 1`, we first rotate to `010`, then to `001`, then finally drop the leading zeroes to get `1`. ## Tests ``` n,m => Output 123,1 => 312 123,2 => 231 123,3 => 123 123,4 => 312 1,637 => 1 10,1 => 1 100,2 => 1 10,2 => 10 110,2 => 101 123,0 => 123 9998,2 => 9899 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-N`](https://codegolf.meta.stackexchange.com/a/14339/), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes `m` as a string and `V=n` as an integer or string, outputs an integer. Prepend `s` or `ì` for +1 byte if we *have* to take both as integers. ``` éV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LU4&code=6VY&input=IjEyMCIKMQ) [Answer] # [R](https://www.r-project.org/), 51 bytes ``` function(n,m,p=10^nchar(n))sum(n*p^(0:m))%/%10^m%%p ``` [Try it online!](https://tio.run/##Xc5RCoMwDAbg950iMArtKCxtx4SBl9gBBCfV@dBUant@p1O021v4kp/8YQo@1tGWU5uoib0nTtLJoVRYUfOuAychxuQ4XYaK48MJwa5sXjrGhi3LlTZSCTiDUfqUmV5MG5WbWWwecrv9Z@XdFN87eKUInbcj@HnwLTyBkrOhbyDU1Nk9gWuB4xXi@j6TDRB2OuynI24dpw8 "R – Try It Online") Numeric solution (that fails for combinations of n & m that cause it to exceed R's numeric range): chains the digits of n, m times (so: `123` => `123123123123` for m=4) and then calculates DIV 10^m (so: `12312312` for m=4) MOD 10^digits(n) (so: `312`). --- # [R](https://www.r-project.org/), ~~61~~ 53 bytes *Edit: -8 bytes thanks to Giuseppe* ``` function(n,m,N=nchar(n),M=10^(m%%N))n%%M*10^N/M+n%/%M ``` [Try it online!](https://tio.run/##Xc7NCsIwDAfwu09RkECrgTWt6KmP0D6CMIaih2VQ6vPXzY4ZvSU//vnINU@lL7dQ7y8eynNizThiCjw8@qzZYAxkr3oESMYwQDzMberikaGDuE5rch7JqL3y5HbC3GLOkzS/2FxIO/3P4tlfPrlNbDsgwLb1MtLAqo2@9vODXX@obw "R – Try It Online") ~~Text-based function that~~ Rotates by combining the two parts of the number together, so does not go out of numeric range: puts the last (m MOD digits(n)) digits of n first, followed by the other digits of n. [Answer] # [Python 3](https://docs.python.org/3/), ~~61~~ 57 bytes ``` i=input n=i() k=int(i())%len(n) print(int(n[-k:]+n[:-k])) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9M2M6@gtIQrzzZTQ5MrG8gr0QCyNFVzUvM08jS5CorAIkCcF62bbRWrnRdtpZsdq6n5/7@hgQGXEQA "Python 3 – Try It Online") Uses string slicing to move the last k digits at the beginning and converts it to an integer to remove the leading zeroes. *-4 bytes thanks to Lyxal* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` (._ï ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fQy/@8Pr//424DA0MDAE "05AB1E – Try It Online") ## Explanation ``` (._ï ( : get negative of m ._ : rotate n left negative m times ï : remove leading zeros ``` [Answer] # [Perl 5](https://www.perl.org/) + `-pl`, 26 bytes ``` eval'$_=chop.$_;'x<>;$_|=0 ``` [Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHXSXeNjkjv0BPJd5avcLGzlolvsbW4P9/QyNjLkMuEGkEJoE8AwMQG0ga/8svKMnMzyv@r1uQAwA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` lambda n,m:int(((n*m)[-m:]+n)[:len(n)]) ``` **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFPJ9cqM69EQ0MjTytXM1o31ypWO08z2ionNU8jTzNW839BEUg6TUPdwtzM1MTY0sDQSF1HwdBYU/M/AA "Python 3 – Try It Online")** Or see the [test-suite](https://tio.run/##VY/RaoUwDIbvfYrgjc2WgbVjG4JP4rzotGWCraX2HLYVn921yi5GEvIn@QKJ@w6fqxVvzh@6ez8WaT4mCZZMO9vAGLMPBvsn0w6PFvt2UZZZHPDQq08QGAL15dQY1ASzhZ/ZMcYbQf@CeJ28PlOORiAxTg0JeqYX8UpZZ6tTX/CkBD83s@aX5e2zidgWMK6Tgg50qVn0ynm2BZ/uwp2i2bEsQI7hJpeEqLtcWMaxAOfzS7qMud7TMF7YDi3EvtJyXiqqnNy2auj/3uq6Cxr2Eo9f "Python 3 – Try It Online"). ### How? Rotating `n` right by `m` is the same as rotating `n` right by `m` modulo length `n` (`m%len(n)`), which is the concatenation of the last `m%len(n)` digits with the first `len(n)-m%len(n)` digits. A simple slice would give us ``` lambda n,m:int(n[-m%len(n):]+n[:-m%len(n)]) ``` for 43 bytes. To remove the need for the repeated `-m%` we can instead concatenate the last `m%len(n)` digits with all the digits of `n` and ***then*** take the first `len(n)` digits. This is ``` lambda n,m:int((n[-m%len(n):]+n)[:len(n)]) ``` for 42 bytes. The `n[-m%len(n):]` can then be replaced with taking the rightmost `m` digits of `m` `n`s concatenated together, `(n*m)[-m:]` giving us the 39 byte solution. [Answer] # [Taxi], ~~1698~~ 1678 bytes No need to wrap single-byte plan names in quote marks. 0.6% byte reduction! ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Addition Alley.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 2 l. Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to The Underground.Go to Chop Suey:n 1 r 2 r.[1]Switch to plan 2 if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan 1.[2]Go to Narrow Path Park:n 1 l 1 r 1 l.Switch to plan 3 if no one is waiting.Pickup a passenger going to Chop Suey.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan 2.[3]Go to Chop Suey:e 1 r 1 l 1 r.[a]Go to The Underground:s 1 r 1 l.Switch to plan b if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Chop Suey:n 3 r 1 l.Pickup a passenger going to Chop Suey.Switch to plan a.[b]Go to Chop Suey:n 2 r 1 l.[4]Switch to plan 5 if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan 4.[5]Go to Narrow Path Park:n 1 l 1 r 1 l.[c]Switch to plan d if no one is waiting.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 2 l.Switch to plan c.[d]Go to KonKat's:e 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s.Pickup a passenger going to The Babelfishery.Go to KonKat's:n.Go to The Babelfishery:s.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r. ``` [Try it online!](https://tio.run/##zVU9b4MwEN37K27rZglIFra0UjtESiOlmSwGBwxYcW1kjGh@PTWfSR2Uxpk6AOLse@/d3QNr8s2a5l2ClrCVpYaPNGUxDWvwgJtLtU@0ZfGxKoBAQcqSiowqyCQTWZv1mssCdhU93dz1mVN4IQfKU1bmVJ1QT2mHw3LkvYm2ShKmmRSw4twQe8BKqIkJmWWiYaeJinPGE9hUX1RJLrORcG4pFANpf/mmYHBg74F/B7v@KQi6/qk/62nbsBcJVZmSlUgGyKmznUBlhCmEvWhXMx3n7YaCE2GiLAUhQQp60YabdBuilKxhS3Rubuo48NnhqS@9CWxRdFzpyrNUeQj70V2wVmLgXs7ZgU4SfYSD6HYGJtHZpxcD6mw6K//gLn9@@G8V5WbXvgjLGTsETh@mpZEgfIiuMf0BEy9siy3/pcUWCC/vsxiO7YoS94rWUqyJfh6nMb72Gl0yZ8T610aKEU4iZ6q7f7OPoEw6xGOwF@cLuj5xppGhpvH84Mn7AQ) I chose to get fired rather than sacrifice the bytes required to return to the garage at the end. I have checked both very long inputs and very long rotations and the net gain is positive so you never run out of gas. --- Formatted for legibility and with comments: ``` [ Pick up the inputs, add 1 to the second, and chop the first into pieces. ] Go to Post Office:w 1 l 1 r 1 l. Pickup a passenger going to Chop Suey. Pickup a passenger going to The Babelfishery. Go to The Babelfishery:s 1 l 1 r. Pickup a passenger going to Addition Alley. 1 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 l 1 l 1 l 2 l. Pickup a passenger going to Addition Alley. Go to Addition Alley:w 1 r 3 r 1 r 1 r. Pickup a passenger going to The Underground. Go to Chop Suey:n 1 r 2 r. [ Reverse the order the charaters are stored in so we can right-shift instead of left-shift. ] [1] Switch to plan 2 if no one is waiting. Pickup a passenger going to Narrow Path Park. Go to Narrow Path Park:n 1 l 1 r 1 l. Go to Chop Suey:e 1 r 1 l 1 r. Switch to plan 1. [2] Go to Narrow Path Park:n 1 l 1 r 1 l. Switch to plan 3 if no one is waiting. Pickup a passenger going to Chop Suey. Go to Chop Suey:e 1 r 1 l 1 r. Switch to plan 2. [3] Go to Chop Suey:e 1 r 1 l 1 r. [ Loop the required times, rotating the passengers at Chop Suey each time. ] [a] Go to The Underground:s 1 r 1 l. Switch to plan b if no one is waiting. Pickup a passenger going to The Underground. Go to Fueler Up:s. Go to Chop Suey:n 3 r 1 l. Pickup a passenger going to Chop Suey. Switch to plan a. [b] Go to Chop Suey:n 2 r 1 l. [ Reverse the character order again. ] [4] Switch to plan 5 if no one is waiting. Pickup a passenger going to Narrow Path Park. Go to Narrow Path Park:n 1 l 1 r 1 l. Go to Chop Suey:e 1 r 1 l 1 r. Switch to plan 4. [5] Go to Narrow Path Park:n 1 l 1 r 1 l. [ Concatenate the passengers at Narrow Path Park. ] [c] Switch to plan d if no one is waiting. Pickup a passenger going to KonKat's. Go to KonKat's:e 1 r. Pickup a passenger going to KonKat's. Go to Narrow Path Park:n 2 l. Switch to plan c. [ Convert to a number to remove leading zeros and then back to a string so the Post Office can handle it. ] [d] Go to KonKat's:e 1 r. Pickup a passenger going to The Babelfishery. Go to The Babelfishery:s. Pickup a passenger going to The Babelfishery. Go to KonKat's:n. Go to The Babelfishery:s. Pickup a passenger going to Post Office. Go to Post Office:n 1 l 1 r. ``` [Try it online!](https://tio.run/##zVY9c9swDN31K7B1aX0nOVm8pblrh/RSX9NMPg2wCEm8yKRKUnHbP@@ClKVTZdWxNXWQLQPE18MDaIc/5eGwgbXMXqCpwZUEUtWNs@8BhYAYnA5CS5lWgoVKQFbq9mQujXV8ns/UkjKyC0ijz9rbrDVrvua5zGi1ZzcVP8Z/LyIfi0Mh1GgtqYIMFFqqwpvde9dPDf06f@w7B/@IW6pyaUsyfLqNOpavbBf6vL87IaSTWsFdVfnYMUgLe2QZ69HBk0OTlbIS8NjsyOhKF33MKd1KHeO2T8Jlw1UJtK7/lgYcDSwDjubtojwYz0qQKYxulOic9hCHJA0nx36iDXyjVzKWQmO1YbPwlpVo0LEC0DALnDYkuONgNexZiwqMLEr3wZYy91SwjlCAzqGi/Cj1pNjEafS0ly4rfQp1xXYJyByUBq1ogPb5kh7RGL2HNbqSP8xLV9NY3uN/pNy4cupULYqjzOJFtEnSC12PbJczqhqQ/rpEE050mb5lxL39oo8Ta@hHI30LndwRz7jRDgPJvbJPzXrO9/6A0Mdkg9BJTAfDNuBXmLVpULYzQPkHez81VPGx53plpwi9vHLJjBJFBnSbTvhNOr@jQQnjkfF8HEcGC5QqwHRzQvjb/5bwN1z27aWEZwTutcp4KSh@JohzkrOHIzuBQ8yA40GrB3Tv@tZ3v9v6rrOdqDOZ4G7WVcxNd16KoJrd1q9HzeO006/Euw6Fj/Kb178NVySjwrRHvlSDhXXG6217lw7uxrBBS7aoGIR2U4p0RnGXX4jz/PS5qLmeB0UvJv4j9CRbHA5xsoziPw) [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` YSU ``` [Try it online!](https://tio.run/##y00syfn/PzI49P9/JUMDQyNjJS4TAA "MATL – Try It Online") Takes `n` as a string and `m` as an integer. ### Explanation ``` YS % Shift first input second input number of times U % Convert to integer to remove leading 0s ``` --- # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` ViYSU ``` [Try it online!](https://tio.run/##y00syfn/PywzMjj0/39DA0MjYy4TAA "MATL – Try It Online") This answer takes both the inputs as integers. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` II⭆θ§θ⁻κη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sRhKBJcABdJ9Ews0CnUUHEs881JSK0BM38y80mKNbB2FDE0wsP7/39DAgMvkv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input `n` as a string ⭆ Map over characters and join κ Current index ⁻ Subtract η Input `m` § Cyclically indexed into θ Input `n` as a string I Cast to integer I Cast to string Implicitly print ``` Conveniently if you try to Subtract an integer and a string then the string gets cast to integer. [Answer] # [Python 3](https://docs.python.org/3/), 47 bytes ``` f=lambda n,m:m and f(n[-1]+n[:-1],m-1)or int(n) ``` [Try it online!](https://tio.run/##VVDRasMwDHz3V@gtNlMgjssKgexH0jCyxtkKtRpsF1ZCvz2TEvowZHEncRJnzY/8cyO3rlN7HcLXOABhaAIMNMKkqStt/0Zdw4ChtOYW4UJZk1mzT/mToAVta4f/Em3Fr9pAsnZGbfKwybFGhwd8d0cULlEZ5X9nf85@FImz3HR22ybc7lEBp933RdHdi9O9Ph7OBcJOrSuMmsQk24Q40LfXV0/6tdyYRoGYTjnq/QfdpTcKxNlukWsFnsvXzNZI3OBzYGDtHOUEU7FQ454IS2CA8gOWJGSJnW/b1D8Ls/4B "Python 3 – Try It Online") Inputs \$n\$ as a string and \$m\$ as an integer. Returns rotated \$n\$ as an integer. [Answer] # APL+WIN, ~~8~~ 7 bytes Prompts for n as integer and m as string: ``` ⍎(-⎕)⌽⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6u3T0AWKaT7q2Quk/gMF/6dxqRsaGatzGXLBWEZwljGcZQJmqXOZGZuDWQYwDQYGMA1wBoIF0mnAxQUA "APL (Dyalog Classic) – Try It Online") [Answer] # JavaScript (ES6), 36 bytes Expects `(m)(n)`, where `n` is a string and `m` is either a string or an integer. ``` m=>g=n=>m--?g(n%10+n.slice(0,-1)):+n ``` [Try it online!](https://tio.run/##hY/RCsIgFIbv9xTehMpy8@goCFzPMszJYtPI6PVNgmCbq@4OfN/5z3@u3bML@j7cHsz5i4m9ipNqrXKqnRg7W@J2wEtXhXHQhvA9A0pPpYvau@BHU43ekp4gBJRgEBJTiuoaSRDF2hALQ0jIDLkw0pQZzZ8rB3mkScPwySg2eibMv/J3S/6Tz/c52k6YGXkGX/8ZXw "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/)`-lm`, ~~65~~ \$\cdots\$ ~~56~~ 55 bytes Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` e;f(n,m){for(e=log10(n);m--;)n=n%10*exp10(e)+n/10;m=n;} ``` [Try it online!](https://tio.run/##bVHbboMwDH3vV1hIlZLWqAnZRVPGXqZ9xVpNFQ0dUuNWwAMa4tfHTKBTmZbExDk@x05MFh@zrO@dzQWhl21@LoVLT@ejVoKk9XFsJaW01GrlmguDTq5po5X1KdmuL6gGvy9IyEW7AB4DULuq/qD3HaTQ6sTgzFArXipsgyWms3Oln5SYoME7fDCPOPjDVDdcvo5rancIbGiNZoLRocjg63EqYNM3ZbLPfbmCcqwRbZu3ZNs8vbLdRwi3ZxOxIki4JyCGkgUdXMM6ZSf3Gariy51zcb2M3EzA6hexsF4HtoSxRdcHEGeaWhXiOzsL@2vY/xuuODz@sznuGP9tzV/hpWRKLqKlOSDwB@KXsC2rLfHzCcEjVMjt4fScZzcl7xZd/53lp/2x6uOT/wE "C (gcc) – Try It Online") Inputs integers \$n\$ and \$m\$. Base-10 digitally rotates \$n\$ right \$m\$-times and returns it. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` v.>z ``` [Try it online!](https://tio.run/##K6gsyfj/v0zPrur/f2MuQ3MjSwA "Pyth – Try It Online") # Explanation ``` v.>zQ Q : first line of input evaluated z : second line of input as string .> : cyclically rotate second line right by number in first line v : evaluate to remove leading 0s ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-hr`, 11 bytes ``` ÷(¿|")⑷⅍⑸⅀ℤ ``` [Try it online!](https://tio.run/##ASYA2f9rZWf//8O3KMK/fCIp4pG34oWN4pG44oWA4oSk//8xMAox/y1ocg "Keg – Try It Online") ## Explained ``` ÷(¿|")⑷⅍⑸⅀ℤ ÷ # Split m into individual numbers (¿|") # n times, shift the stack right ⑷⅍⑸ # turn each character into a string ⅀ℤ # sum stack and convert to integer. `-hr` prints it as integer ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 66 bytes ``` (n,x)->new Long((""+n+n).substring(x=(n=(""+n).length())-x%n,x+n)) ``` [Try it online!](https://tio.run/##jY8xT8MwEIX3/IpTpUo2Tay0QTCUdGBAQoKpI2Jw0yR1cM5WfC6pUH97MBGI1dPTvfvenV4nzzLrjh@T6q0ZCLowC09Ki8ZjRcqguNkmlZbOwatUCF8JgPUHrSpwJCnI2agj9GHH9jQobN/eQQ6t4zMK8Kiefi89PCPVbT2kf/pisN1BA@XEMB15tsP6E35MxhaLFa6QC@cPbr7KxpJhOftc6BpbOjHOs3EZksHi03b@tr84qnthPAkbYqSRNUJaqy9svSnSnPMobh3JbSK5IpK7jeHSu@I@hsvjauRxLf65a3KdvgE "Java (JDK) – Try It Online") [Answer] # [J](http://jsoftware.com/), 11 bytes ``` (".@|.":)~- ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NZT0HGr0lKw063T/a/43NDJWSFMw5ILQRlDaGEqbcBkCSTNjcy5DA4gyAwOIMigFo8GqDQA "J – Try It Online") ### How it works Uses [@Bubbler's tacit trick](https://codegolf.stackexchange.com/a/173657/95594) for `(F x) G (H y) = (G~F)~H`. ``` (".@|.":)~- - negate y to shift right ( )~ flip arguments, so ((-y) ".@|. (":x)) ": convert x to string |. shift that by negated y ".@ and convert back to number ``` [Answer] # [Io](http://iolanguage.org/), 89 bytes Uses a `reduce` trick to assign different lines of STDIN to variables. ``` File standardInput readLines reduce(a,b,a splitAt(-b asNumber)reverse join)asNumber print ``` [Try it online!](https://tio.run/##NcgxCoAwDADA3VdkVFBQf@AiCOIfUpshorEkqd@vLm7H8V3KzCeBOUpEjYuk7KCEcWUh@xTzTjW2oUWwdLJPXncB0LZ8BdJG6SE1guNmaf6FpCxeytD31fgC "Io – Try It Online") # [Io](http://iolanguage.org/), 56 bytes ``` method(a,b,doString(a splitAt(-b asNumber)reverse join)) ``` [Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0UjUSdJJyU/uKQoMy9dI1GhuCAns8SxREM3SSGx2K80Nym1SLMotSy1qDhVISs/M09T83@ahpKhgYGSjpGmQgFQV0lO3n8A "Io – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 34 bytes ``` ->m{($_*-~m*2)[~~/$/*m,~/$/].to_i} ``` [Try it online!](https://tio.run/##HYfLCoMwFAX3/YqLzaINJj5pV/ZHJIS2KBW8iZi4KDF@etMonGHmzMvrG/omsAe6C5GUbUjLa7ttGckoprsEt1oOPrQ057xOb9Vd8O75/jhYcYVpsQYSBQ2cHZE@BTwSY82dWUZ73L5F4RPwoTgVeVxkd1n99GQHrUxgavwD "Ruby – Try It Online") Takes \$n\$ from STDIN and \$m\$ as an argument. Concatenates \$n\$ \$2(m+1)\$ times, then from this string takes the substring of length \$d\$ (where \$d\$ is the number of digits in \$n\$) that begins \$m(d+1)\$ characters from the end. In the code, `$_` is \$n\$ and `~/$/` gives \$d\$. ### Example For \$n=123\$, \$m=2\$: 1. Concatenate \$n\$ \$2(m+1)=6\$ times: `123123123123123123` 2. Count back from the end \$m(d+1)=8\$ characters: `1231231231**2**3123123` 3. Take substring of length \$d=3\$: `1231231231**231**23123` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~42~~ 40 bytes ``` lambda x,r:int(x[(a:=-r%len(x)):]+x[:a]) ``` [Try it online!](https://tio.run/##ZcwxCoAgGEDhvVOEEPiTgWVUCJ2kGoySAjMRBzu90Wiu34NnHnfcmg3GBjnOQYlr3UTuieWndthPWPCxsoXaNfYAfCn9xMUCwdivS4zqhiFSA2SxNImwRNpIEOlYHwn9j@n/m8r3pQDhBQ "Python 3.8 (pre-release) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (4?) 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 4 if we may accept a list of digits (remove the leading `D`). ``` DṙN}Ḍ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/l4c6ZfrUPd/T8///f2MTUzNzC0sDQ6L@hMQA "Jelly – Try It Online")** ### How? ``` DṙN}Ḍ - Link: integer, n; integer, m D - convert to base ten } - use m as the input of: N - negate ṙ - rotate (n) left by (-m) Ḍ - convert from base ten ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 10 7 6 bytes Saved 3 bytes by remembering that you can preform most array operations on strings. -1 byte from @my pronoun is monicareinstate noting that `m>` takes arguments in either order. ``` rr~m>~ ``` [Try it online](https://tio.run/##S85KzP3/v6ioLteu7v9/QyNjBRMA) Explanation: ``` rr Read two string inputs ~ Parse m to number m> Rotate n string right m times ~ Parse n to number to remove leading zeros (implicit) output ``` ## Old version, 7 bytes: ``` q~\sm>~ ``` [Try it online](https://tio.run/##S85KzP3/v7AupjjXru7/f0MjYwUjAA) Explanation: ``` q~ Take input as a string, evaluate to two numbers \ Swap order s Convert n to string m> Rotate n string right m times ~ Parse n to number to remove leading zeros (implicit) output ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 4 [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 infix function. Takes string `n` as right argument and number `m` as left argument. ``` ⍎-⍛⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1Fvn@6j3tmPevb@T3vUNgHIfdTV/Kh3zaPeLYfWGz9qm/iob2pwkDOQDPHwDP5vmKZuaGSsrqDwqHeugrGhEZcRsoCRsSGXMbIAkMVlgq7FzNgcKARTwQUy0gDIg3JBBhoYqKNw4bIGCmABQ7i8gSGXAbqFQBWWlpYW6mABSwtLSwA "APL (Dyalog Extended) – Try It Online") `⍎` execute the result of `-⍛` negating the left argument, then using that to `⌽` cyclically rotate the right argument [Answer] # (non-competing) [L=tn](https://github.com/Ghilt/Listen), 10 ``` cα;θ2$cD=0 ``` Explanation (in order of execution): ``` cα; - Turn first number into a list of digits 2$c - Fetch second number as a number θ - Shift list from first step by number from second step D=0 - Drop while equals to zero ``` It prints result as a string. Note: The language is in progress and I did add stuff to code golf this. So it is not a competing submission. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes ``` FromDigits@RotateRight[IntegerDigits@#,#2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277360oP9clMz2zpNghKL8ksSQ1KDM9oyTaM68kNT21CCqjrKNsFKv2P6AoM69EwSE92tDIWMcwlguFb4TGN0bjmyDzdcyMzZH5BqjGGRigGofGRecDTTeI/f8fAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 29 bytes ``` ,.+ $*_ +`(.*)(\d)_ $2$1 ^0+ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0dPm0tFK55LO0FDT0tTIyZFM55LxUjFkCvOQJvr/39DI2MdQy4QaQQmjcGkCZehjpmxOZehAUjSwAAkCSYgJFCFAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as `n,m`. Explanation: ``` ,.+ $*_ ``` Convert `m` to unary. ``` +`(.*)(\d)_ $2$1 ``` Rotate `n` `m` times. This is O(m³) because of the way the regex backtracks trying to find a second match. Right-to-left matching, anchoring the match at the start, or rewriting the code to take input as `m,n` would reduce the time complexity (at a cost of a byte of course). ``` ^0+ ``` Delete leading zeros. [Answer] # Scala, 61 bytes ``` (n,m)=>{val s=n+""size;val(a,b)=n+""splitAt s-m%s;b++a toInt} ``` [Try it in Scastie](https://scastie.scala-lang.org/8jPaXDKbREuCSjrzyjAqKw) [Answer] # [PHP](https://www.php.net/), 45 43 bytes Saved 2 bytes, realized we can shorten the variable names. ``` <?=(int)(substr($s,-$n).substr($s,0,-$n))?> ``` [Try it online](https://tio.run/##K8go@G9jX5BRoKBSbKtkaGCgZK2SZ2tkrWBvBxS31cjMK9HUKC5NKi4p0lAp1tFVydPUQ3ANwAKaQLX/gVq5jAA) Explanation: ``` <?= ?> Shorthand for <?php echo ;?> (int) Typecast string to int, removes 0s from prefix substr() substr(string,start,[length]), returns part of string, if range go out of bounds, starts again from the opposite end. Basically returns part of from a 'circular' string. ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 47 bytes ``` (n,m,k=(e=n+'').length)=>+(e+e).substr(k-m%k,k) ``` [Try it online!](https://tio.run/##dc1LDsIgGATgvadgY/oT6ANwAQu8S21oVSiYUnt9bGqjia27Sb7MzL2e6tgMt8eYTzK1OoGnPbUajPYky3DhjO/GK9ZnAoYYXMTnJY4D2Lw/WmpxaoKPwZnChQ5aYFzQCmOEyhLNGR22zFYWjO8oX5ULtqPiO72jp//L1ft26aIt8g9WP6iUkgvPqKRS6QU "JavaScript (V8) – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 11 bytes ``` Àñ$x0Pñó^0« ``` [Try it online!](https://tio.run/##K/v//3DD4Y0qFQYBhzce3hxncGj1//@GBgb/jQA "V (vim) – Try It Online") ``` Àñ ñ # (M-@)rg number of times $ # end of line x # delete character (cut) 0 # beginning of line P # paste character ó # (M-s)ubsitute ^0« # ^0\+ # (implicitly) with nothing ``` ]
[Question] [ Do you know the optical effect of a tridimensional hand painted whit horizontal lines? [Examples](https://www.google.com/search?q=mano%20tridimensional%20pintada%20con%20lineas%20horizontales&rlz=1C1CHBF_esES920ES920&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjP8e-v99DwAhVDUhoKHW1tARkQ_AUoAXoECAEQAw&biw=1920&bih=937#imgrc=twMWoWZ6Msj0EM) This challenge consists of making something like that effect with ascii, and transforming one 2d input into a "3d" output. ## The algorithm To perform this transformation, you first replace all `1` with a `¯` and all `0` with a `_`. In order to make things more realistic, you should replace a `¯` that does not have another `¯` before it with `/`, and a `¯` that does not have another `¯` after it with `\`. Some examples: ``` Input: 001111100 Output: __/¯¯¯\__ ``` ``` Input: 0110 1111 Output: _/\_ /¯¯\ ``` ^ In this case, there are multiple lines, so apply this to all lines. ``` Input: 000000000000000000000000000000000 000000111100000000000001111100000 000000111110000000000111111000000 000000111111000000011111100000000 000000111111000001111110000000000 000000011111100011111100000000000 000000111111111111111100000000000 000000111101111111011110000000000 000000111100111110011110000000000 000000111111111111111110000000000 000000111111111111111110000000000 000000001111111111110000000000000 000000000001111100000000000000000 000000000000000000000000000000000 Output: _________________________________ ______/¯¯\_____________/¯¯¯\_____ ______/¯¯¯\__________/¯¯¯¯\______ ______/¯¯¯¯\_______/¯¯¯¯\________ ______/¯¯¯¯\_____/¯¯¯¯\__________ _______/¯¯¯¯\___/¯¯¯¯\___________ ______/¯¯¯¯¯¯¯¯¯¯¯¯¯¯\___________ ______/¯¯\_/¯¯¯¯¯\_/¯¯\__________ ______/¯¯\__/¯¯¯\__/¯¯\__________ ______/¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\__________ ______/¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\__________ ________/¯¯¯¯¯¯¯¯¯¯\_____________ ___________/¯¯¯\_________________ _________________________________ ``` Exceptions / rules: * The input will never have a single positive cell in a row (e.g. `00100`) * You can consider other characters for the input. However, it should only be two characters and not the same characters that the output uses. For instance: ``` Valid input: 0001111000 # two characters, different from the output Valid input: aaiiaiiaaa # two characters, different from the output Valid input: ,€€€€,,,,, # two characters, different from the output Invalid input: 0001223000 # four different characters are used. Invalid input: ___1111___ # invalid, because the output uses underscores. Invalid input: ///\\\\/// # both slash and backslash are used by the output. ``` * The output must use the four characters described above and **only** those four. Alternatively, you may use `-` instead of the macron (`¯`) * The macron (upper character) has a codepoint of 175, but you may count it as one byte. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), Score 25 26 bytes, but scoring `¯` as 1, as per note in challenge. ``` s|1(1*)1|/\1\\|g y/01/_¯/ ``` [Try it online!](https://tio.run/##K05N@f@/uMZQw1BL07BGP8YwJqYmnatS38BQP/7Qev3//w0MDEHAwICLC8gy4AJxgExCAKoCohUJGMJFuNAFEFxDDDPgSlA4WFQYopnHha4PXQGqGQiAwy8wWay2QAQNERRBW8hRgaoGW6hjC1gsKrCDf/kFJZn5ecX/dYsA "sed 4.2.2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` Ż<ƝoḤU)⁺ị“\/Ø-_” ``` [Try it online!](https://tio.run/##y0rNyan8///obptjc/Mf7lgSqvmocdfD3d2PGubE6B@eoRv/qGHu/4e7t9gCacNDO4@1H26P5Hq4czGQW3O4/VHTmqxHjfu4uP7/NzAwBAEDA64aLiDTgAvEA7EJAagKiGYkYAgX4UIXQHANMcyAK0HhYFFhiGYeF7o@dAWoZiAADr/AZLHaAhE0RFAEbSFHBaoabKGOLWCxqMAOAA "Jelly – Try It Online") Uses hyphens instead of macrons. Takes a good deal of inspiration from hyper-neutrino's answer, so don't forget to send him some votes. Feels like there's got to be some way to shave a byte off the string at the end, with the right replacement for `oḤ`... ``` ) For each line, ⁺ twice: Ż prepend a 0, Ɲ then for each pair of neighboring elements < is the second greater than the first? o Replace zeroes with corresponding elements of Ḥ the line doubled, U and reverse. ị Modular 1-index into “\/Ø-_ "\/Ø-_". (0 -> _, 1 -> \, 2 -> /, 4 -> -) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~26~~ 19 bytes ``` 1(1*)1 /$.1$*¯\ 0 _ ``` [Try it online!](https://tio.run/##K0otycxL/P/fUMNQS9OQS19Fz1BF69D6GC4Drvj//w0MDEHAwICLC8gy4AJxgExCAKoCohUJGMJFuNAFEFxDDDPgSlA4WFQYopnHha4PXQGqGQiAwy8wWay2QAQNERRBW8hRgaoGW6hjC1gsKrADAA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 7 bytes with inspiration from @DigitalTrauma. Explanation: ``` 1(1*)1 /$.1$*¯\ ``` Replace a run of `1`s with a run of `¯`s between `/` and `\`. ``` 0 _ ``` Replace `0`s with `_`s. (Note that Retina uses the ISO-8859-1 code page, so `¯` is 1 byte anyway.) [Answer] # [Perl 5](https://www.perl.org/) (`-p -Mutf8`), 25 bytes, score 24 ``` s|1(1*)1|/\1\\|g;y;01;_¯ ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4xlDDUEvTsEY/xjAmpibdutLawNA6/tD6//8NDAxBwMCAiwvIMuACcYBMQgCqAqIVCRjCRbjQBRBcQwwz4EpQOFhUGKKZx4WuD10BqhkIgMMvMFmstkAEDREUQVvIUYGqBluoYwtYLCqwg3/5BSWZ@XnF/3UL/uv6lpakWQAA "Perl 5 – Try It Online") Same as [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)'s [sed answer](https://codegolf.stackexchange.com/a/225829/70745), except the trick using semicolon delimiter the last character can be removed. [Answer] # [///](https://esolangs.org/wiki////), 80 bytes ``` /0/_//1/a//aaa/a-a//-aa/--a//aa-/a--//-a-/---//a-/\\\/-//-a/-\\\\//aa/\\\/\\\\/ ``` [Try it online!](https://tio.run/##nZExCsAgDEV37xK@uY9QMhQ6dPP@2KhU0UaEZsnP85tgjLfE64wpweMAGAKICIRUkAqiQkgJZUJKVGgOIaAgUMhaXYWVIvlduJpYY@DciJtBL/nTo1mGwnDw1M/N92bD2KPH4i3vqTmlQu5pO@WPY/RYW7cWazgWP5ce "/// – Try It Online") Uses `-` instead of the macron, as it is allowed. I'm marking it as 80 bytes because of the required newline at the end of the input. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 80 bytes (but actually 79 because ¯ is counted as a 1 byte char in this challenge) ``` import re while r:=re.sub:print(r(*"0_",r(*"1¯",r("1(1*)1",r"/\1\\",input())))) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRKEolas8IzMnVaHIyrYoVa@4NMmqoCgzr0SjSENLySBeSQdEGx5aD2IoGWoYamkaAplK@jGGMTFKOpl5BaUlGpog8P@/gaGhAZchEHBxGRACUBUg1SjihnARLnQBBNcQwwy4EhQOFhWGaOZxoetDV4BqBgLg8AtMFqstEEFDBEXQFnJUoKrBFurYAhaLCuwAAA "Python 3.8 (pre-release) – Try It Online") Because we love `re.sub` :) ## Old solution : 94 bytes (but actually 93, you know the song ...) I don't know why but I thought a pure vanilla python solution would beat a solution using regex ... I was wrong. ``` while r:=str.replace:print(r(r(r(r(f"0{input()}0","10","\\0"),"01","0/")[1:-1],*"1¯"),*"0_")) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/vzwjMydVocjKtrikSK8otSAnMTnVqqAoM69EowgK05QMqjPzCkpLNDRrDZR0lAxBREyMgZKmjpKBIZBtoK@kGW1opWsYq6OlZHhoPVBCS8kgXklT8/9/A0NDAy5DIODiMiAEoCpAqlHEDeEiXOgCCK4hhhlwJSgcLCoM0czjQteHrgDVDATA4ReYLFZbIIKGCIqgLeSoQFWDLdSxBSwWFdgBAA "Python 3.8 (pre-release) – Try It Online") Nothing too crazy here, just a few `str.replace`, and some `str.replace` and even more `str.replace` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ŒgḤ1¦€N0¦€)ị“-/\_” ``` [Try it online!](https://tio.run/##y0rNyan8///opPSHO5YYHlr2qGmNnwGY0ny4u/tRwxxd/Zj4Rw1z/z/cvSUMKApEh9sj//83IAS4IJQhEKCIG8JFuNAFEFxDDDPgSlA4WFQYopnHha4PXQGqGQiAwy8wWay2QAQNERRBW8hRgaoGW6hjC1gsKrADAA "Jelly – Try It Online") Inputs a matrix of `0` and `1`s, outputs a list of lines. Uses `-` instead of a macron ## How it works ``` ŒgḤ1¦€N0¦€)ị“-/\_” - Main link. Takes a matrix M on the left ) - Over each row R in M: Œg - Group adjacent equal elements in R € - Over each group G in R: Ḥ - Double: 1¦ - The first value € - Over each group G in R: N - Negate: 0¦ - The last value For zeros, these are left unchanged. For ones, the first becomes 2 and the last -1 “-/\_” - Yield the string "-/\_" ị - Index, 1 based and modularly. This means that: 1 or -3 -> - 2 or -2 -> / 3 or -1 -> \ 4 or 0 -> _ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` Ż;0ṡ3Ḅ)ị“_./__\-_” ``` [Try it online!](https://tio.run/##y0rNyan8///obmuDhzsXGj/c0aL5cHf3o4Y58Xr68fExuvGPGub@f7h7S9ijpjVAdLg98v9/A0KAC0IZAgGKuCFchAtdAME1xDADrgSFg0WFIZp5XOj60BWgmoEAOPwCk8VqC0TQEEERtIUcFahqsIU6toDFogI7AAA "Jelly – Try It Online") Uses `-` instead of the macron ``` Ż;0ṡ3Ḅ)ị“_./__\-_” Main Link; takes a matrix of bits and outputs a list of lines ) For each row Ż Prepend 0 ;0 Append 0 ṡ3 Get overlapping slices of length 3 Ḅ Convert from binary // basically, the center of the 3-slice is the character itself // and we need the left and right context to determine if it needs // to be changed. So ___, __-, -__, and -_- (0, 1, 4, 5) become _, // _-- (3) becomes /, --_ (6) becomes \, and --- (7) stays as - ị“_./_.\-_” index into "_./_.\-_", so 1=_ 3=/ 4=_ 5=_ 6=\ 7=- 0=_ // note that Jelly is 1-indexed and indexes wrap around ``` [Answer] # JavaScript (ES6), 54 bytes\* *\* by counting the macron as 1 byte, as allowed in this challenge* ``` s=>s.replace(/./g,(c,i)=>'_/¯\\'[c*=!+s[i+1]-~s[i-1]]) ``` [Try it online!](https://tio.run/##nZBBTsQgFIb3nAJXgJ1SWBu60wvMctoYwtCKIVChmhijV/IOXqy2GWdqK5NJ/DeP//Hxv/Ae5YuMKpiuz53f66ERQxRlpEF3ViqNC1q0G6w2hogS3Rdfn1WFdupaXGVxZzJe5x9jzXldkyHop2cTNEZNRGQMkPs7Y/X21SnMCO39tg/GtZjQ2FnTY1S5yo1g48OtVA84QlHCNwCh8i56q6n1LW5wJDCDaCJvwDsZGOOTGANgqgCMnh2Pl/RDHAJ@iZ86YN2YLf@TcUIWJkHwVR5Yv1sDy4xZZ/5yvE1OOTT5XC5O@Q@xZFJbTy02QaT1DQ "JavaScript (Node.js) – Try It Online") [Answer] # Excel (Insider Beta), ~~139~~ 96 bytes ``` =LET(s,LAMBDA(t,x,y,SUBSTITUTE(t,x,y)),s(s(s(s(s(A2,101,"\_/"),10,"\_"),0&1,"_/"),0,"_"),1,"-")) ``` Had to spend quite a few bytes shortening the `SUBSTITUTE` function. Originally, I thought you had to adapt to any two characters which is what I did below. ``` =LET(s,LAMBDA(t,x,y,SUBSTITUTE(t,x,y)),a,LEFT(A2),b,LEFT(s(s(A2,a,"")," ","")),s(s(s(s(s(A2,b&a&b,"\_/"),b&a,"\_"),a&b,"_/"),a,"_"),b,"-")) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes ``` εγεS¬·0ǝR¬(0ǝR}˜"_¯/\"sè ``` [Try it online!](https://tio.run/##yy9OTMpM/V/z/9zWc5vPbQ0@tObQdoPjc4MOrdEAUbWn5yjFH1qvH6NUfHjF/1qvQ7v/GxACXBDKEAhQxA3hIlzoAgiuIYYZcCUoHCwqDNHM40LXh64A1QwEwOEXmCxWWyCChgiKoC3kqEBVgy3UsQUsFhXYAQA "05AB1E – Try It Online") Takes input as a list of lines of ones and zeros and outputs as a list of lists of characters in each line. ``` εγεS¬·0ǝR¬(0ǝR}˜"..."sè # trimmed program # implicit input... ε # with each element replaced by... è # list of characters in... "..."s # literal... è # with indices in... ˜ s # flattened... γ # list of groups of consecutive equal elements in... # (implicit) current element in map... ε # with each element replaced by... R # reversed... R # reversed... S # list of characters in... # (implicit) current element in map... ǝ # with element at index... 0 # literal... ǝ # replaced with... ¬ # first element of... S # list of characters in... # (implicit) current element in map... · # doubled... ǝ # with element at index... 0 # literal... ǝ # replaced with... ¬ # first element of... R # reversed... S # list of characters in... # (implicit) current element in map... ǝ # with element at index... 0 # literal... ǝ # replaced with... ¬ # first element of... S # list of characters in... # (implicit) current element in map... · # doubled... ( # negated } # exit map # (implicit) exit map # implicit output ``` `R}` can also be a `}í` with no change in functionality: [Try it online!](https://tio.run/##yy9OTMpM/V/z/9zWc5vPbQ0@tObQdoPjc4MOrdEAUrWH156eoxR/aL1@jFLx4RX/a70O7f5vQAhwQShDIEARN4SLcKELILiGGGbAlaBwsKgwRDOPC10fugJUMxAAh19gslhtgQgaIiiCtpCjAlUNtlDHFrBYVGAHAA "05AB1E – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rl`, 21 "bytes" ``` gR+X1'/.TM_.'\TRt"¯_" ``` [Try it online!](https://tio.run/##K8gs@P8/PUg7wlBdXy/EN15PPSYkqETp0Pp4pf//DQ0NcAIuCGVoiKYIJGCIJGmIJmWIrBMuC@dgSiIxudBVI5uBohMBMF0Lk0A3FsI3RFD4jCVeElUaLfiwBROqJAb4r1uUAwA "Pip – Try It Online") ### Explanation ``` g With -r flag, g is a list of all lines from stdin R In each line, replace +X1 regex match of one or more 1's with this callback function: TM_ Trim the first and last characters from the match '/. Prepend / .'\ Append \ TR Transliterate t 10 "¯_" into ¯_ Autoprint, one list element per line (-l flag) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `aṠD`, 21 bytes *-1 from Aaron Miller* ``` ƛĠƛ⌊ḣ$NpṫdJ`_¯\/`$İ;f ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=a%E1%B9%A0D&code=%C6%9B%C4%A0%C6%9B%E2%8C%8A%E1%B8%A3%24Np%E1%B9%ABdJ%60_%C2%AF%5C%2F%60%24%C4%B0%3Bf&inputs=0110%0A1111&header=&footer=%23%20Print%20nicely%0A%E1%B9%85%3B%E2%81%8B) Heavily inspired by [@caird coinheringaahing's Jelly answer](https://codegolf.stackexchange.com/a/225819/80050). Outputs a list of lines containing a list of characters in each line. Uses the actual macron! ``` ƛĠƛ⌊ḣ$NpṫdJ`_¯\/`$İ;f ƛ For each line of (implicit) input... Ġƛ ; For each group of consecutive characters... ⌊ Convert each character to an integer (so double and negate work) N Negate... ḣ$ p the first element of the group. d Double... ṫ J the last element of the group. İ Index each element... `_¯\/`$ in "_¯\/" (negative indices start from the back) f Flatten the list of groups to a lists of chars ``` [Answer] # [J](http://jsoftware.com/), 48 44 43 41 bytes ``` '_^/\'{~(>./@,+:@g&.|.,:3*g=.1=2-/\,&0)"1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1ePj9GPUq@s07PT0HXS0rRzS1fRq9HSsjLXSbfUMbY109WN01Aw0lQz/a3KlJmfkK6QBNRsCoYGCjpUhmGX4HwA "J – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 56 bytes, 54 by the rules ``` gsub(0,"_")gsub(1,"/\\")gsub(/\\\//,"¯")gsub("/¯","/") ``` [Try it online!](https://tio.run/##SyzP/v8/vbg0ScNARyleSRPMNNRR0o@JgXKArBh9fR2lQ@uhAkr6QCZQhZLm//8GhAAXhDIEAhRxQ7gIF7oAgmuIYQZcCQoHiwpDNPO40PWhK0A1AwFw@AUmi9UWiKAhgiJoCzkqUNVgC3VsAYtFBXYAAA "AWK – Try It Online") Substitutes: all `0` to `_`; all `1` to `/\`; all `\/` to `¯`; and, finally, all `/¯` to `/`. # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 52 bytes, 51 by the rules ``` gsub("01","0/")gsub(10,"\\0")gsub(0,"_")gsub(1,"¯") ``` [Try it online!](https://tio.run/##SyzP/v8/vbg0SUPJwFBJR8lAX0kTzDU00FGKiTGA8oCceJiEjtKh9Uqa//8bEAJcEMoQCFDEDeEiXOgCCK4hhhlwJSgcLCoM0czjQteHrgDVDATA4ReYLFZbIIKGCIqgLeSoQFWDLdSxBSwWFdgBAA "AWK – Try It Online") Thanks to DLsoc for a 52 bytes/51 characters version. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepge) ``` γε¬i¦¦…/ÿ\]JT„¯_‡ ``` I/O as a multiline string. [Try it online.](https://tio.run/##yy9OTMpM/f//3OZzWw@tyTy07NCyRw3L9A/vj4n1CnnUMO/Q@vhHDQv//1dSUjIwMAQBAwMuIMOAC8TmMiAEoCogGpGAIVyEC10AwTXEMAOuBIWDRYUhmnlc6PrQFaCagQA4/AKTxWoLRNAQQRG0hRwVqGqwhTq2gMWiAjsAxvh/Xd28fN2cxKpKAA) **Explanation:** ``` γ # Split the (implicit) input-string into equal adjacent parts # i.e. "0110\n1111" → ["0","11","0","\n","1111"] ε # Map each part to: ¬ # Get its first character (without popping) i # If this is a 1: ¦¦ # Remove two characters from this string …/ÿ\ # Surround it with leading "/" and trailing "\" ] # Close both the if-statement and map # → ["0","/\","0","\n","/11\"] J # Join everything back together # → "0/\0\n/11\" T ‡ # Then transliterate the characters "1" and "0" „¯_ # to the characters "¯" and "_" # → "_/\_\n/¯¯\" # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` WS⟦⪫E⪪ι0∧κ⪫/\ׯ⁻Lκ²_ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1MhAMgo0Yj2ys/M0/BNLNAILsjJLNHI1FFQMlDS1FFwzEvRyNZRAEsr6cfEKOkohGTmphZrKB1aD2T7ZuaVFmv4pOall2RoZAPVG2mCAFB3vJJmrKb1//8GhAAXhDIEAhRxQ7gIF7oAgmuIYQZcCQoHiwpDNPO40PWhK0A1AwFw@AUmi9UWiKAhgiJoCzkqUNVgC3VsAYtFBY6Y@69blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⟦ ``` Loop over each input string and print each output on a new line until an empty line is reached. (String array input format would have saved a byte.) ``` ⪫E⪪ι0∧κ⪫/\ׯ⁻Lκ²_ ``` Split each string on `0`s, then replace each (non-empty) run of `1`s with a run of `¯`s wrapped in `/` and `\`, finally joining with `_`s. [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` √E6∙²δ♪₧♂─Ç,áR0Z◄@╖ ``` [Run and debug it](https://staxlang.xyz/#p=fb4536f9fdeb0d9e0bc4802ca052305a1140b7&i=%22%22%22%0A000000000000000000000000000000000%0A000000111100000000000001111100000%0A000000111110000000000111111000000%0A000000111111000000011111100000000%0A000000111111000001111110000000000%0A000000011111100011111100000000000%0A000000111111111111111100000000000%0A000000111101111111011110000000000%0A000000111100111110011110000000000%0A000000111111111111111110000000000%0A000000111111111111111110000000000%0A000000001111111111110000000000000%0A000000000001111100000000000000000%0A000000000000000000000000000000000%0A%22%22%22) A regex based solution similar to the Pip and sed answers. Takes a full multiline string. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~71 65~~ 61 bytes ``` n=>n.replace(/./g,(e,i)=>+e?+n[i+1]?+n[i-1]?'-':'/':'\\':'_') ``` [Try it online!](https://tio.run/##nVDRCoMgFH33R1RM3X0d2D5kjRXNohEaNfb7ThZLdI5gB/Rwj@eei/fePJulnYfpwY29adcpZ1RpxKynsWk1kUL2BdHFQFXJ9ImZ88Dg8mbuGXN8xNKfqvLXFVPXWrPYUYvR9qQj9WEPaCXwiHTYFJQKoYSvjM0SFRkHJHko7UsNcUbAj798XrNTVhEC7U75xxF7clvPLTbjyKOm1L0A "JavaScript (Node.js) – Try It Online") ## How it works Replaces every letter. For each letter in question: if the numerical representation is falsy (`0`) then replace with `_`, otherwise use a simple ternary to find the correct character to use. Uses `-` instead of macron, you know, just because. Saved 6 bytes by reorganizing and removing assignment to unused `a` variable. Then saved 4 thanks to a username by entirely getting rid of variables. [Answer] # Mathematica, 74 bytes ``` StringReplace[#,{"101"->"\_/","01"->"_/","10"->"¯\\","0"->"_","1"->"¯"}]& ``` ]
[Question] [ My stovetop has 10 (0 through 9) different settings of heat and a very odd way of cycling through them. * It always starts at 0 * When I hit plus it increments the number, *unless* the number is 9 in which case it becomes 0, or the number is 0 in which case it becomes 9. * When I hit minus it decrements the number, *unless* the number is zero in which case it becomes 4. There are no other temperature control buttons. In this challenge you will take as input a string of commands and output which setting my stovetop ends up on after running that sequence. Answers will be scored in bytes with fewer bytes being better. ## Input You may take input in any of the following formats: * A list/array/vector/stream of booleans/1s or 0s/1s or -1s * A string (or list/array/vector/stream) of two different characters (which should be consistent for your program) And you may output * An integer on the range 0-9. * A character on the range '0'-'9'. * A string of size 1 consisting of the above. ## Testcases Input as a string `-` for decrement and `+` for increment. ``` : 0 - : 4 + : 9 -- : 3 -+ : 5 +- : 8 ++ : 0 --- : 2 --+ : 4 -+- : 4 -++ : 6 +-- : 7 +-+ : 9 ++- : 4 +++ : 9 ---- : 1 ---+ : 3 ``` [Answer] # JavaScript (ES6), ~~38 37~~ 36 bytes Expects an array of Boolean values, with *false* for `+` and *true* for `-`. Returns an integer. ``` a=>a.map(c=>a=a++?c?a-2:a%10:9>>c)|a ``` [Try it online!](https://tio.run/##Zc7LDoIwEAXQPV8xITHQTFpUfEFS/BDjYlLBaBCIJa78d@Th1KhdNad35vZKD7LmfmlaWdWnvCt0RzojdaMmNP1FE@Le7EkuU5ot5mmSZUY8qWtz24IGCzoDU1e2LnNV1uewCA9KKXucFoyvoDUEMhBCeN4wFvo@9EdAFMH8LdJnWb0FnSScGUKjxCzIsuYpl9mxuIzrGhaNsnSC/ne7RPknnNm4Ls5snXAmce2/exB/M3L40CiLj@AkcfcC "JavaScript (Node.js) – Try It Online") ### Commented It's important to note that `a++` with `a = [ true ]` is evaluated to `NaN` because it's first coerced to the string `"true"` and then to a number. That's why we can safely re-use the array `a[]` to store the temperature even when we get the singleton `[ true ]` as input. ``` a => // a[] = input array, re-used to store the temperature a.map(c => // for each command c in a[]: a = // update the temperature: a++ ? // if a is numeric and not equal to 0 // (increment it afterwards): c ? // if this is a '-': a - 2 // subtract 2 : // else: a % 10 // apply a modulo 10 : // else: 9 >> c // yield 4 if this is a '-', or 9 if this is a '+' ) | a // end of map(); return the final result ``` [Answer] # [PHP](https://php.net/), ~~103~~ ~~90~~ ~~86~~ ~~75~~ 71 bytes ``` while($k=$argv[1][$i++])--$k?$p?$p++<9?:$p=0:$p=9:($p--?:$p=4);echo+$p; ``` [Try it online!](https://tio.run/##K8go@G9jXwAkyzMyc1I1VLJtVRKL0suiDWOjVTK1tWM1dXVVsu1VCoBIW9vG0t5KpcDWAERYWmmoFOjqggVMNK1TkzPytVUKrP///28EAA "PHP – Try It Online") - Add string as argument - 1 for `-`, 2 for `+`. Example: for `---+`, `1112`. Thanks to @Kaddath for -13 bytes (see comment). -4 by changing input format to 0/1. -11 thanks to @640KB. -4 thanks to @DewiMorgan. [Answer] # [C (clang)](http://clang.llvm.org/), ~~58~~ \$\cdots\$ ~~56~~ 54 bytes ``` t;f(*s){for(t=0;*s;)t=*s++-7?t?t-1:4:t?-~t%10:9;*s=t;} ``` [Try it online!](https://tio.run/##XVHLboMwELznK1ZISAZsFfJoGhw3h6pf0eRAiUlQUxJhV0WN6KeX@gWlscAsOzO743VO8lNWHbpO0gKFIrgW5xpJFtNQ0ECyUEQRWW7kRpIknadyQ76ln8TpSuFM0rYrKwnvWVmhYHKdgFr5MatDkFxI8bIDBlfPw@ARvUUmMiExcWTTLm8Bi5DI0RzPEp2ql/U6J1RoS40HbYo3F55LvrcmYgxzDCsMMwwLDA8YVGZqkuq5x7A0qOUkiuYq2dPkR56/8dqdZ9s8T7fN6km9C9159D/rHagpAtI2ymrPGyWLqQvXIMovfi5QbzC4c4lwyFCIIsMOwA51NFhVyw7XEHZ0wHW3E68ULmStAiSD/@DrR1G8aEYEyUj3Z9XZhDXThYyJYKDpZSqUegrSfBjMZ7CBJaQmMaqJNPWmv1C63sONb66g4cJuD3apFaVAni@APIK/B19sKzV4iUHg4W4EY3znOraTtvvJi1N2EB35/AU "C (clang) – Try It Online") *Saved ~~a~~ 3 bytes thanks to [Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit)!!!* Inputs a string of minuses and ~~pluses~~ bell-characters (ASCII 7) and returns the stovetop temperature in the input string (right at the end where the `'\0'` terminator would have been). [Answer] # [Rust](https://www.rust-lang.org/), 46 bytes ``` |x|x.fold(0,|u,v|if u>0{u-v*2+1}else{9>>v}%10) ``` [Try it online!](https://tio.run/##XY3vCoIwFMW/@xQ3Idhq1db/CHyRiBC7kmAmcxPD@ew2jcr1aef87tk5UheqjTO4h0lGaO2dSoxGpzOD/uUfIb6E8Z/8UvGjoqPeJztMD/JWOj1O07DL2XBX/nbcpe7feZ4olITO72FOTGUqxz@NmD3p27T9NX6kV8KZ0aw0SQw64LWelZPlVDSYFlgfgqBsxoLTltqsvGAY3breXCaZGhG/bsBnFaVH6EmaWeZxWMMBVrCBPXBYWreGLews67iAlW/ziwVglWOk8AoSC50qr2lf "Rust – Try It Online") Takes an `Iterator` of zeros (for `+`) and ones (for `-`), and returns the resulting stove temperature. Taking -1s and 1s doesn't seem to help, because `(-1,1) -> (4,9)` isn't trivial to represent in integer arithmetic. Uses [Arnauld's input method and bit-shift trick](https://codegolf.stackexchange.com/a/218367/78410) for the zero case. Also, Rust's if-else expression can be a part of larger expression, so `%10` is factored out to avoid the parentheses in `(u-v*2+1)%10`. [Answer] # [convey](http://xn--wxa.land/convey/), 41 bytes Takes in a list of 0 for + and 1 for -. ``` }{ 0>?@`"+1 ^ 1-0=v `15|8*v |<<,<+< ^10 ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiICB9e1xuMD4/QGBcIisxXG5eIDEtMD12XG5gMTV8OCp2XG58PDwsPCs8XG5eMTAiLCJ2IjoxLCJpIjoiMSAxIDAifQ==) [![stove](https://i.stack.imgur.com/mUhpA.gif)](https://i.stack.imgur.com/mUhpA.gif) `a` loops around and based on the input `}` goes `@` down towards `-1` and mod 15 `|15` (to set -1 to 14), or goes to `+1` and `+ ((a=0) * 8)` – thus gets set to 9 if `n` was 0. We join both paths `,` and with mod 10 `|10` we get 14 -> 4, 10 -> 0. If the input is empty, `a` goes on `?` to the side path to the output `}`. (The `^` next to the 10 shouldn't be necessary, but I haven't fixed the bug yet.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~15~~ ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Input as a list of `-1`/`1` for `-`/`+` respectively. ``` ÎvD_Ƶ≠yè*yOθ ``` [Try it online](https://tio.run/##yy9OTMpM/f//cF@ZS/yxrY86F1QeXqFV6X9ux///0YY6uoY6hrEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waf@oYZ6udmXK4RVeSgoah/drKjxqm6SgZP/foLLMJf7Y1kedCyoPr9Cq9D@343@tjmbM/@joWJ1oXUMgYQhm6OhCabAQhAfhgOXg0rpwQSQtcE0wfXBzECahmIVsHFhtLAA). **Explanation:** ``` Î # Push 0 and the input-list v # Loop `y` over the input-list: D # Duplicate the current value _ # Pop the copy, and check that it's 0 (1 if 0; 0 otherwise) Ƶ≠ # Push compressed integer 185 yè # Index `y` into it (0-based modulair, so the leading 1 is ignored, while # 1→8 and -1→5) * # Multiply it to the ==0 boolean y # Push `y` O # Take the sum of the three values on the stack θ # And only leave the last digit (for 10→0) # (after the loop, the value 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 `185`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes ``` ^ 0 {T`+09d`_9d`^.\+ T`-d`_4d`^.- ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP47LgKs6JEHbwDIlIR6I4/RitLlCEnSBPBMQT/f/fwUrBQMuXSBpwqUNJC25dEEcYy5dEM@USxvEs@DS1oaoA0saAWltsA5dbV0oDeKbAVWD@OZAGmKWNlReWxtmNliBIYgBEjEGAA "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` ^ 0 ``` Start with heat setting 0. ``` { ``` Process all of the control buttons. ``` T`+09d`_9d`^.\+ ``` If the control button is a plus, then delete it (by transliterating to `_`) and cyclically increment the digit (`T`9d`d` is the standard way to cyclically increment digits) but change `0` to `9` instead by listing it as an exception before the expansion of `d` to `0123456789`. ``` T`-d`_4d`^.- ``` If the control button is a minus, then delete it and decrement the digit, but use `4` instead of the usual `9` for cyclic decrement. [Answer] # [Coconut](http://coconut-lang.org/), 39 bytes Takes input as a list of `1/-1` ``` reduce$((p,k)->[k%7-2,p+k][p>0]%10,?,0) ``` [Try it online!](https://tio.run/##PY3LbsIwEEX3/opZgGxrbBQehRaJ9Ce6oyxCcFQrIVh@qAvKt6eehHYzd@7MmTv1rb71KQ7N4XPw5pJqMxPCqVbq8tjOd3qlHLanoyuL03xZqHdVyOH7y3YGPnwyewZQKTjDAWzvUhQSfkpYBNfZKDjsgctMeBNSFzNT0fZauRlwQL5obH@hSWdDJG0oLQTj4/8J5UZxphTnqW34vXqALuE@IQ8uh/ynYDrXDcNc35gms2aa3AtDcq8MceLG5Sorjhca9VPJbzNNfpd1ysLnHvEvewSW1NBk/Qs "Coconut – Try It Online") This uses `((-1)%7-2)%10 = (6-2)%10 = 4` and `(1%7-2)%10 = (-1)%10 = 9`, which works because in Python the result of the modulo operation has the same sign as the divisor. `-k%-7` would work instead of `k%7-2` and is one byte shorter if we swap `-1` and `1` in the input, but that feels like abusing the input format. [Answer] # [J](http://jsoftware.com/), 24 bytes Takes `-1` for `-` and `1` for `+`. ``` 0(10|15|++8*0=<.)/@|.@,] ``` [Try it online!](https://tio.run/##ZY8xDsIwDEX3nMJicYvrkACFEqiEhMTExIo6IVpg4QIVVw@taJwhQwY/fb/vvP1MYwu1A4QCDLjhsYbT9XL2JrOmt2VPVM1NfdD54tjrY9H4XKluXLm5Fix/ARkIX7pR6nF/fiDbd/nAmAknMjgddIAI/3k9zRzAbgIUwCokJFIGIpkqLEkm9JBkluLhpDyaBEXVRpCkttKX3p26iNJUdNl4F6d/Hm3@Bw "J – Try It Online") ``` 0(10|15|++8*0=<.)/@|.@,] 0 @,] prepend a 0 and … @|. rotate and … ( )/ fold from the left: 0=<. if the minimum of the step and the accumulator is 0 (can only happen if they are 1/0) +8* add 8 to … + the sum of the step and the accumulator 15| mod 15 to get -1 -> 14 10| mod 10 to get 10 -> 0, and 14 -> 4 ``` [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` n=0 for b in input():n=[b%7-2,n+b][n>0]%10 print n ``` [Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPQ/z9aAKy2/SCFJITMPiApKSzQ0rfJso5NUzXWNdPK0k2Kj8@wMYlUNDbgKijLzShTy/gO1cZVnZOakKhhapVakJiuADPsfHcsVrWsIJAzBDB0FXRgDLAjlQ7kQeSQ1ukgSKHqRtCOMQDIV2WB0s9HMh@gCAA "Python 2 – Try It Online") Takes input as ±1's. Pretty explicitly fixes the `n=0` case to have `b=-1` give `4` and `b=1` give `9`. There's probably a better way. **50 bytes** ``` n=0 for b in input():n=((n or 9-b%5)+b)%10 print n ``` [Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPQ/z9aAKy2/SCFJITMPiApKSzQ0rfJsNTTyFICilrpJqqaa2kmaqoYGXAVFmXklCnn/gdq4yjMyc1IVDK1SK1KTFUCG/Y@O5YrWNQQShmCGjoIujAEWhPKhXIg8khpdJAkUvUjaEUYgmYpsMLrZaOZDdAEA "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~45~~ 37 bytes ``` 0#1=9 0#a=4 9#1=0 x#a=x+a f=foldl(#)0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/30DZ0NaSy0A50daEyxLINuCqALIrtBO50mzT8nNScjSUNQ3@5yZm5tkWFGXmlaikRRvqKACRLhQbxv4HAA "Haskell – Try It Online") * Saved 8 thanks to @Wheat Wizard [Answer] ## [R](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjPp-ngrtDuAhUwy4UKHXuIDPQQFjAAegQIARAD&url=https%3A%2F%2Fcran.r-project.org%2F&usg=AOvVaw0pGNScRjIdSkNXK6Ky1j_m), ~~57~~ 55 bytes ``` f=function(x){for(i in x)F=(F+i)%%10+"if"(i>0,8,-5)*!F;F} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrM6Lb9II1MhM0@hQtPNVsNNO1NTVdXQQFspM01JI9POQMdCR9dUU0vRzdqt9n@aRnFibkFOqkayhq6hjqGmjqGBqZlOUWqBbUhQqKumJleaBpCjYahjAWeD1EF4yRogLZr/AQ "R – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~47~~ 43 bytes Expects each operation on a separate line with `+` for increment and `-` for decrement ``` /-/{a?a--:a=4}/+/{a=a?++a%10:9}END{print+a} ``` [Try it online!](https://tio.run/##SyzP/v9fX1e/OtE@UVfXKtHWpFZfG8izTbTX1k5UNTSwsqx19XOpLijKzCvRTqz9/1@XSxsBAQ "AWK – Try It Online") [Answer] ## x86-16 machine code, 40 bytes Port of @Arnauld's answer. Be sure to upvote him! (Example run is unneccecary since it's just a port.) ``` 0BAC:0100 31 DB E3 23 AC 84 DB 74-14 84 C0 75 04 FE CB EB 1..#...t...u.... 0BAC:0110 14 FE C3 89 D8 B7 0A F6-F7 88 C3 EB 08 B3 09 86 ................ 0BAC:0120 C8 D2 EB 86 C8 E2 DD C3 ........ ``` Callable function. Expects `[SI]` = index of list (0x00 for `-`, 0x01 for `+`), `CX` = length of list. Needs a spare `AX`. Function output is to `BL` (accumulator value). Disassembled: ``` 0BAC:0100 31DB XOR BX,BX 0BAC:0102 E323 JCXZ 0127 0BAC:0104 AC LODSB 0BAC:0105 84DB TEST BL,BL 0BAC:0107 7414 JZ 011D 0BAC:0109 84C0 TEST AL,AL 0BAC:010B 7504 JNZ 0111 0BAC:010D FECB DEC BL 0BAC:010F EB14 JMP 0125 0BAC:0111 FEC3 INC BL 0BAC:0113 89D8 MOV AX,BX 0BAC:0115 B70A MOV BH,0A 0BAC:0117 F6F7 DIV BH 0BAC:0119 88C3 MOV BL,AL 0BAC:011B EB08 JMP 0125 0BAC:011D B309 MOV BL,09 0BAC:011F 86C8 XCHG CL,AL 0BAC:0121 D2EB SHR BL,CL 0BAC:0123 86C8 XCHG CL,AL 0BAC:0125 E2DD LOOP 0104 0BAC:0127 C3 RET ``` [Answer] # [Perl 5](https://www.perl.org/) `-pF`, 36 bytes ``` $\+=$\?1-2*/-/:9-5*/-/,$\%=10for@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWJcbeUNdIS19X38pS1xRE66jEqNoaGqTlFzm41Vb//6@trf0vv6AkMz@v@L9ugRsA "Perl 5 – Try It Online") [Answer] # x86-16 machine code, ~~27~~ 26 bytes ``` 00000000: 33c0 803c 2d74 0a84 c075 02b0 0840 37eb 3..<-t...u...@7. 00000010: 0548 3f14 003f 46e2 e9c3 .H?..?F... ``` **Listing:** ``` 33 C0 XOR AX, AX ; clear accumulator SLOOP: 80 3C 2D CMP BYTE PTR[SI], '-' ; is a "-"? 74 0A JZ MINUS ; is a minus operation 84 C0 TEST AL, AL ; is plus op and 0? 75 02 JNZ PLUS ; if not, continue as plus op B0 08 MOV AL, 8 ; otherwise add 8 PLUS: 40 INC AX ; increment 37 AAA ; if al > 9 { al = 0, cf = 1 } EB 06 JMP DONE ; done MINUS: 48 DEC AX ; decrement 3F AAS ; if al < 0 { al = 9, cf = 1 } 14 00 ADC AL, 0 ; if cf { al = 10 } 3F AAS ; if al == 10 { al = 4 } DONE: 46 INC SI ; next input instruction E2 E8 LOOP SLOOP C3 RET ; return to caller ``` Callable function, input as string in `[SI]`, length in `CX`. Output to `AL`. This is the first time I can ever think of where [`AAA`](https://www.felixcloutier.com/x86/aaa) and [`AAS`](https://www.felixcloutier.com/x86/aas) were actually useful in a challenge! These instructions, intended for BCD math, are able to be abused a little to do a bit of the dirty work here. **Tests:** [![enter image description here](https://i.stack.imgur.com/CFCpC.png)](https://i.stack.imgur.com/CFCpC.png) [![enter image description here](https://i.stack.imgur.com/BvmPf.png)](https://i.stack.imgur.com/BvmPf.png) [Answer] # [Python 3](https://docs.python.org/3/), 92 bytes ``` f=lambda x,t=0:f(x[1:],{"+":{9:0,0:9},"-":{0:4}}[x[0]].get(t,t+eval(f"{x[0]}1")))if x else t ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8DWgCstv0ghWyEzD4gKSks0NK24FBQy0xSybW3VtdVBHDC3wNbWwKrA1hLMT82BiFhagQyAiBSnWhVo2xpyIas24YLJ6AJlCooy80o0CjT//9cFgv8A "Python 3 – Try It Online") Expects input as a string of "-" and "+" as in the test cases. Recursively looks up the few exceptions or defaults to adding and subtracting one based on the first character of the given string. [Answer] # TI-Basic, ~~52~~ 47 bytes ``` Prompt A For(I,1,dim(ʟA If ʟA(I:Then Ans+1+8not(Ans Ans(Ans≤9 Else Ans-1+5not(Ans End End ``` -5 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush). Takes input as a list of 0s and 1s. Output is stored in `Ans` as an integer. Note that there can not be empty lists in TI-Basic, so the first test case throws an error. The below version has 8 bytes more but outputs 0 for the first test case. --- ### ~~60~~ 55 bytes ``` Prompt Str1 For(I,1,length(Str1 If expr(sub(Str1,I,1:Then Ans+1+8not(Ans Ans(Ans≤9 Else Ans-1+5not(Ans End End ``` Takes input as a string of "0"s and "1"s. Output is stored in `Ans` as an integer. [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 132 bytes ``` ([](<()>)){({}[()]<((){[()](<(({}({})[()]{})[(()()()()()){}])((){[()](<{}>)}{}){((<{}{}>))}{}>)}{}){(<{}(((({})()){}){}{})>)}{}>)}{} ``` [Try it online!](https://tio.run/##RYwxCoAwDEWv8/9W99KLlA7VRREcuoacPSaKlgSS/3jJOvpx7X07zVAbMlhIgWgFWwYosTh35M1IzwC/omjjNEUL1RVB7JGokzkC4tl7yDBYfsPMFkuWbg "Brain-Flak (BrainHack) – Try It Online") This loses a lot of bytes to simple equality checks (equals 0 and equals 10). [Answer] # [Python 3](https://docs.python.org/3/), ~~151~~ 117 bytes ``` p=0 for k in input(): if k=='+': if p==0:p=9 elif p==9:p=0 else:p+=1 if p==0:p=4 else:p-=1 print(p) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8DWgCstv0ghWyEzD4gKSks0NK24FBQy0xSybW3VtdVBHDC3wNbWwKrA1hLMT82BiFhagQyAiBSnWhVo2xpyIas24YLJ6AJlCooy80o0CjT//9cFgv8A "Python 3 – Try It Online") @pxeger So Nice thank you -35 bytes [Answer] ## [CESIL](http://www.obelisk.me.uk/cesil/) , 850 bytes (including data section) CESIL was taught in UK schools until the mid-1980s (I may have been in one of the last years that had it as an introduction before moving on to the powerhouse of BASIC). This has been run through a parser I wrote in Python as a little exercise, each column is tab separated. Everything has to be moved in and out of the accumulator for any function to be performed on that. There was no real input, as it was designed for punched cards, so data has to be in a separate section at the end (I use -1 and 1 to indicate both temperature controls, and zero to terminate). It gave the correct results from the samples, but did mean I had to update the data section each time, save it, and run it again. ``` LOAD 0 STORE HEAT LOOP IN JIZERO END STORE BUTTON ADD HEAT STORE TMP * CHECK ZERO DOWN TO 4 JINEG ZTF * CHECK 9 UP TO 0 LOAD TMP SUBTRACT 10 JIZERO NTZ * CHECK 0 UP TO 9 LOAD BUTTON JINEG DEC LOAD TMP SUBTRACT 1 JIZERO ZTN LOAD TMP STORE HEAT SHOW LOAD HEAT PRINT "HEAT IS " OUT LINE JUMP LOOP DEC LOAD TMP STORE HEAT JUMP SHOW END HALT * 0 GOES DOWN TO 4 ZTF LOAD 4 STORE HEAT JUMP SHOW * 9 GOES UP TO 0 NTZ LOAD 0 STORE HEAT JUMP SHOW * ZERO GOES UP TO 9 ZTN LOAD 9 STORE HEAT JUMP SHOW % -1 -1 -1 1 0 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` m?Z=Z%?dhZtZT=Z?d9 4QZ ``` [Try it online!](https://tio.run/##K6gsyfj/XyHXPso2StU@JSOqJCrENso@xVLBJDDq//9oAx0FCDKMBQA "Pyth – Try It Online") ``` m?Z=Z%?dhZtZT=Z?d9 4QZ Q auto-initialized to input; Z auto-initialized to zero m Q Map through input, using 'd' as current element ?Z If Z is not 0: =Z%?dhZtZT Z++ or Z--, Then modulo by 10 Else: =Z?d9 4 Z = 9 if + or 4 if - Z Print Z ``` [Answer] # Python 3, 86 bytes ``` def f(c,t=0): if len(c):p=c[0];t=((0,9,4)[p],t+p)[t>0]%10;return f(c[1:],t) return t ``` Takes input as a list of 1s and -1s, 1 indicating a + button press and -1 indicating a - button press. [Try it online!](https://tio.run/##bVHBqsIwELznK5bCgyymkKIXK/XyfuHdYhCpCQY0hnR7eF9fU6tYo3vJ7szO7LIJ/3S6@uUwHI0Fy1tBjcSagbNwNp63WIemVVJvqOFcirVYoQpa0CKgoq3UP5XcREN99KNaVXXikMEDooFMR3vnQ08dNKAYpFBaTG9ZPbPqBQko36pXz5yZE5Mm15V5y6dzbp4NyKd/LPB1h297TE5MM3uNwJ2A8SwIzoPx/cXEAxk@u9T4ASlCdJ548ZcI@D10BgpYQEeRO0xJUe/8jp6QvesRcbgB "Python 3 – Try It Online") Recursively handles the exceptions that happen in what might be considered the expected function of the buttons, each at t==0. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 68 bytes Nice little lookup table solution. Thanks to Jay Ryan for -7 bytes, and for making me revisit my code to find and fix a bug! 8 definitely is not 0, much to my previous solutions disbelief. ``` lambda s,a=0:[[a:=b'49021324354657687980'[c+2*a]-48for c in s],a][1] ``` [Try it online!](https://tio.run/##NZDLjsMgDEX3fAU7whiqvB9IfAnNgnYUTaQ2RcAi/XoGp@nG19c@WFe4d/x7bc3ofFr0NT3s8/ZraRBWl8oYq/SNtVNZV03dNl3bd0M/DtNYMnOH@sfOsh2Xl6d3um40zMLOppoTidrsl@AeayyYYpwisiPCGKOKlkTm2hLIdSISTUMkuo4AupEAfLhjWWeF44UEeSr6PtPoh6yfW3DuAb63D6DCBidNDvANdt0YnwnBbEF4TBcVoc6vWyyCWIqndcX5HbvatWbARLiE6FdXcM6F5yn9Aw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ``` ¹o8 5<?+%⁵µƒ0 ``` [Try it online!](https://tio.run/##y0rNyan8///QznwLBVMbe23VR41bD209Nsng/8PdW2wfNczV1dU63P6oaU3k//9culzaXLq6XLraXNpAJogN5AB5utogQZAoUBgkC5YGy4MU6GoDAA "Jelly – Try It Online") -1 thanks to xigoi: -1 is always smaller than the accumulator, and the right argument to `o` doesn't matter if it's nonzero anyways Takes input as 1/-1. ``` ƒ Reduce from 0 zero µ : ¹ (break the leading triple dyad pattern.) o Logical OR the left argument with 8 eight <? if it is less than the right argument, 5 else five. + Add the right argument to the result, %⁵ mod 10. ``` [Answer] # [Julia](http://julialang.org/), 47 bytes ``` l->(n=0;[n=n>0 ? (n+2i-1)%10 : 4+5i for i=l];n) ``` [Try it online!](https://tio.run/##VU9BjsIwDLz7FVakFY1MpAa2yy4ocOYNpYcVS6WgyItokPh9sQMcmkOcGU/G4/MtxV9/H/swJretONSblgNva9xhxbSIztsPX@MaP6mJ2P9fMYbUbdiO@TTkAQMaY0D6NThVAcn9A07BEpyiBkjRNxA9daW5kErlhyP3qoq/RK14JfXpRa8@0du7CLw@qIzRCAAaTkNhZBwuKeaqRJybAxvb@vWJ/5zvAOVcrpFz4iKwhUmyyZ5zewxhRrOy6HFqNDcyS426qUeyE9gLMWUsyOTxAQ "Julia 1.0 – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 111 bytes ``` X =0 N I =INPUT :F(O)S($I) A X =REMDR(X + 1,10) X =EQ(X,1) 9 :(N) S X =X - 1 X =4 LT(X) :(N) O OUTPUT =X END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/nzNCwdaAy4/TU8HW0y8gNITTyk3DXzNYQ8VTk8sRJBnk6usSpBGhoK1gqGNooMkFEnMN1IjQMdRUsOS00vDT5AoGiUUo6CoYgmVNOH1CNCI0IXL@nP6hIUBzgQq4XP1c/v93BAA "SNOBOL4 (CSNOBOL4) – Try It Online") Uses `A` for `+` and `S` for `-`, separated by newlines. ``` X =0 ;* Set X N I =INPUT :F(O)S($I) ;* read input. If empty, goto O, else goto label identified by I A X =REMDR(X + 1,10) ;* Incremenet X, mod 10 X =EQ(X,1) 9 :(N) ;* if X = 1, set it to 9. Goto N S X =X - 1 ;* decrement X. X =4 LT(X) :(N) ;* If X is less than 0, set X to 4. Goto N. O OUTPUT =X ;* Output X and exit. END ``` SNOBOL won't reassign values on a FAILURE, so `X =EQ(X,1) 9` is a no-op if X isn't equal to 1. [Answer] # [><>](https://esolangs.org/wiki/Fish), 30 bytes ``` 0l1=?n:?v~49{?$~! +1-a%00.>{2* ``` [Try it online!](https://tio.run/##S8sszvj/3yDH0NY@z8q@rM7EstpepU6RS9tQN1HVwEDPrtpI6////7plCgYA "><> – Try It Online") (or [fishlanguage.com](https://fishlanguage.com/), as this input format is a bit tricky) Takes an array of `0`s(decrement) and `1`s(increment) ``` ---row 1--- 0 ! Initialisation l1=?n: Termination ? Branching to special case 0 ~49{?$~ 0 branch, discard 4 or 9 depending on button ---row 2--- +1-a% >{2* other branch, conditional increment/decrement mod 10 00. loop ``` [Answer] # [Befunge-98](https://esolangs.org/wiki/Funge-98), 21 bytes ``` :&|@>#. -1_4^ +1_9^%a ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3UqtxsFPW49I1jDeJ49I2jLeMU038/z/aUEcBggzAyDAWAA "Befunge-98 (PyFunge) – Try It Online") Input as a list of `0`s and `1`s (or any other format with some character after the last number). ## Explanation ``` :&|@>#. : Create a copy of the temperature counter (which starts at 0). & Get the next input number. | Is it 0 (minus) or 1 (plus)? If the input is 0, move down to the second line. If the input is nonzero, move up (and wrap around) to the third line. > Once the program has returned to the first line: # Skip the next instruction. . (skipped) Repeat. On EOF: : Duplicate the final temperature. . Print it. # Skip the next instruction. > (skipped) @ End the program. Second line (minus): -1_4^ _ Is the copy of the current temperature zero? If so, 4 replace it with 4, ^ and return to the first line. If not, - subtract 1 1, ^ and return to the first line. Third line (plus): +1_9^%a _ Is the copy of the current temperature zero? If so, 9 replace it with 9, ^ and return to the first line. Otherwise, + add 1 1, % take the result modulo a 10, ^ and return to the first line. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 7, 50 44 bytes ``` $args|%{$x=$_ ?$x ?++$x%10:9:$x ?$x-1:4};+$x ``` TIO still runs on PS 6, which this solution is incompatible with, so no Try It Online link, for now. # Explanation ``` $args|%{ #For each number in the argument list (0 or 1) $x= #Assign to x $_ #Ternary on the number ? #Number is non-zero, + button was pressed $x #Ternary on x ? ++$x%10 #x is non-zero, set x to its increment mod 10 : 9 #x is 0, set x to 9 : #Number is zero, - button was pressed $x #Ternary on x ? $x-1 #x is non-zero, decrement : 4 #x is zero, set x to 4 } #End for each loop +$x #Output x, coercing it to 0 if null ``` ]
[Question] [ Given a number determine if it is a folding number. A folding number is a number such that if you take it binary representation and "fold" it in half, That is take the result of XNOR multiplication of the first half of the number and the second half with it digits in reverse, you will get zero. If the number has a odd number of digits in binary its middle digit must be 1 and is ignored when folding. Since that might be a bit confusing I will give some examples: ### 178 The binary representation of 178 is ``` 10110010 ``` To fold this we first split it in half ``` 1011 0010 ``` We reverse the second half ``` 1011 0100 ``` And we XNOR the two halves: ``` 0000 ``` This is zero so this is a folding number. ### 1644 The binary representation of 1644 is ``` 11001101100 ``` To fold this we first split it in half ``` 11001 1 01100 ``` The middle bit is 1 so we throw it out. ``` 11001 01100 ``` We reverse the second half ``` 11001 00110 ``` And we XNOR the two halves: ``` 00000 ``` This is zero so this is a folding number. ### 4254 The binary representation of 4254 is ``` 1000010011110 ``` To fold this we first split it in half ``` 100001 0 011110 ``` The middle bit is 0 so this is not a folding number. ## Task Your task is to take in a positive number and return a truthy if the number is folding and falsy if it is not. This is code golf so try to keep the byte count down. ## Test Cases Here are the first 99 folding numbers: ``` [1, 2, 6, 10, 12, 22, 28, 38, 42, 52, 56, 78, 90, 108, 120, 142, 150, 170, 178, 204, 212, 232, 240, 286, 310, 346, 370, 412, 436, 472, 496, 542, 558, 598, 614, 666, 682, 722, 738, 796, 812, 852, 868, 920, 936, 976, 992, 1086, 1134, 1206, 1254, 1338, 1386, 1458, 1506, 1596, 1644, 1716, 1764, 1848, 1896, 1968, 2016, 2110, 2142, 2222, 2254, 2358, 2390, 2470, 2502, 2618, 2650, 2730, 2762, 2866, 2898, 2978, 3010, 3132, 3164, 3244, 3276, 3380, 3412, 3492, 3524, 3640, 3672, 3752, 3784, 3888, 3920, 4000, 4032, 4222, 4318, 4462, 4558] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Bœs2µḢ^UȦ ``` [Try it online!](http://jelly.tryitonline.net/#code=QsWTczLCteG4ol5VyKY&input=&args=MTY0NA) or [verify all test cases](http://jelly.tryitonline.net/#code=QsWTczLCteG4ol5VyKYKNDU1OFLDh8OQZg&input=). ### How it works ``` Bœs2µḢ^UȦ Main link. Argument: n B Binary; convert n to base 2. œs2 Evenly split 2; split the base 2 array into chunks of equal-ish length. For an odd amount of digits, the middle digit will form part of the first chunk. µ Begin a new, monadic chain. Argument: [A, B] (first and second half) Ḣ Head; remove and yield A. U Upend; reverse the digits in [B]. ^ Perform vectorized bitwise XOR of the results to both sides. If A is longer than B, the last digit will remain untouched. n is a folding number iff the result contains only 1's. Ȧ Octave-style all; yield 1 iff the result does not contain a 0. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ### Code: ``` bS2ä`R0¸«s^P ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=YlMyw6RgUjDCuMKrc15Q&input=MTY0NA) ### Explanation: First, we convert the number to binary using `b`. **1644** becomes **11001101100**. We split this into two pieces with `2ä`. For example, **11001101100** would become: ``` [1, 1, 0, 0, 1, 1] [0, 1, 1, 0, 0] ``` If there is an uneven number of bits, the first part will receive the extra bit. We `R`everse the last string and append a zero using `0¸«`. The reason for this is to only give truthy results when the middle bit is a **1** (**1 XOR 0 = 1** and **0 XOR 0 = 0**). If there is no middle bit, 05AB1E will just ignore the last bit (the zero that was appended) : ``` [1, 1, 0, 0, 1, 1] [0, 0, 1, 1, 0, 0] ``` The last thing we need to do is do an element-wise **XOR** and take the product of the result. If there is one element too many, the program will just leave the last element out (`[1, 0, 0] XOR [0, 1] = [1, 1]`) For example: ``` [1, 1, 0, 0, 1, 1] [0, 0, 1, 1, 0, 0] XOR ``` Becomes: ``` [1, 1, 1, 1, 1, 1] ``` And the product of that is **1**, which is truthy. [Answer] ## Java 7, ~~152 145 142 138~~ 134 bytes ``` boolean f(Long a){byte[]b=a.toString(a,2).getBytes();int i=0,l=b.length,z=l%2<1?1:b[l/2]-48;for(;i<l/2;)z*=b[i]-b[l-++i];return z!=0;} ``` Loops over the string like it would for a palindrome, looking for zeroes. Keeps track by repeatedly multiplying, so all you have to do is check that it's not zero at the end. Without scroll bars: ``` boolean f(Long a){ byte[]b=a.toString(a,2).getBytes(); int i=0,l=b.length,z=l%2<1?1:b[l/2]-48; for(;i<l/2;) z*=b[i]-b[l-++i]; return z!=0; } ``` [Answer] ## JavaScript (ES6), ~~61~~ ~~57~~ 52 bytes Recursively computes: ``` (bit(N) XOR bit(0)) AND (bit(N-1) XOR bit(1)) AND (bit(N-2) XOR bit(2)) etc. ``` where `N` is the rank of the highest bit set in the input. If the input has an odd number of bits, the middle bit is XOR'ed with *undefined* (the value returned by `pop()` on an empty array), which lets it unchanged. So, a `0` middle bit clears the output and a `1` middle bit doesn't alter the result of the other operations -- which is consistent with the challenge definition of a folding number. ``` f=(n,[a,...b]=n.toString(2))=>a?(a^b.pop())&f(n,b):1 // testing integers in [1 .. 99] for(var i = 1; i < 100; i++) { f(i) && console.log(i); } ``` [Answer] ## Python 2, 57 bytes ``` s=bin(input())[2:] while''<s!='1':s[-1]==s[0]<_;s=s[1:-1] ``` Outputs [via exit code](https://codegolf.meta.stackexchange.com/a/5330/20260): error for Falsey, and no error for Truthy. Converts the input into binary. Checks whether the first and last character are unequal, keeps and repeating this after removing those characters. The comparison `s[-1]==s[0]<_` gives an error if the first and last character are unequal by trying to evaluate the unassigned variable named `_`. If they are equal, the chain of inequalities is short-circuited instead. When we get to the middle element of `1`, the `while` loop is terminate to special-case it as OK. I suspect a purely arithmetic approach will be shorter with a recursion like `f=lambda n,r=0:...f(n/2,2*r+~n%2)...` to chomp off binary digits from the end flipped and reversed, and detect when `n` and `r` are equal up to a center `1`. There are subtleties though with leading zeroes and the center. [Answer] # Python 2, ~~94 79 72~~ 67 bytes ``` F=lambda s:s in'1'or(s[0]!=s[-1])*F(s[1:-1]) lambda n:F(bin(n)[2:]) ``` Saved 12 bytes thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) Defines an unnamed function on the second line. Explanation (with some whitespace added): ``` F = lambda s: # We define a function, F, which takes one argument, the string s, which returns the following: s in'1' # Gives true if s is '' or s is '1', the first case is a base case and the second is for the middle bit case. or(s[0] != s[-1]) # Or the first and last are different * F(s[1:-1]) # And check if s, without the first and last element is also foldable. lambda n: F(bin(n)[:-2]) # The main function, which calls F with the argument in binary form. ``` Try it [here!](https://repl.it/DqFL/2) [Answer] ## Haskell, ~~89~~ ~~88~~ 86 bytes ``` f n|n<2=[n]|1>0=mod n 2:f(div n 2) g n=elem(product$zipWith(+)(f n)$reverse$f n)[1,2] ``` Works by summing bitwise the bit representation with its reverse and taking the product. If it's 1 or 2, the number is a folding number (1 if there are even bits that fold, 2 if there are odd bits and a one in the middle). [Answer] # Python 2, ~~100~~ ~~99~~ ~~95~~ [94 Bytes](https://goo.gl/Ecld91) This feels a bit long, but I'll keep working at it :) Prints a `1` if the number can be folded, `0` otherwise. ``` a=bin(input())[2:] b=len(a) print(a[b/2]>=`b%2`)*all(c!=d for c,d in zip(a[:b/2],a[:~b/2:-1])) ``` Test it [here!](https://repl.it/DnAQ/5) *thanks to Wheat Wizard for the 1-byte save :)* *thanks to Rod for the 5-byte save! :)* [Answer] # [><>](https://esolangs.org/wiki/Fish), 37+3 = 40 bytes ``` <,2-@:%2:v!?: =2lrv?=1l<+={$r0? 0=n;> ``` Input is expected to be present on the stack at program start, so +3 bytes for the `-v` flag. [Try it online!](http://fish.tryitonline.net/#code=PCwyLUA6JTI6diE_Ogo9Mmxydj89MWw8Kz17JHIwPwowPW47Pg&input=&args=LXYgMTY0NA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Bœs2U0¦z0^/€Ạ ``` **[TryItOnline](http://jelly.tryitonline.net/#code=QsWTczJVMMKmejBeL-KCrOG6oA&input=&args=MTY0NA)** Or [matching terms up to 4558](http://jelly.tryitonline.net/#code=QsWTczJVMMKmejBeL-KCrOG6oAo0NTU4UsOHw5Bm&input=) ### How? ``` Bœs2U0¦z0^/€Ạ - Main link: n B - binary œs2 - split into 2 slices (odd length will have first longer than second) 0¦ - apply to index 0 (the right hand one) U - reverse z0 - zip together with filler 0 (thus central 1 or 0 will pair with 0) /€ - reduce with for each ^ - XOR Ạ - All truthy? ``` [Answer] # Perl, 46 bytes Includes +1 for `-p` Run with the number on STDIN ``` folding.pl <<< 178 ``` `folding.pl`: ``` #!/usr/bin/perl -p $_=($_=sprintf"%b",$_)<s%.%!/\G1$/^$&^chop%eg ``` I consider it a perl bug that this even works. Internal `$_` should not be getting match position updates once it is modified. In this program the match position actually moves beyond the end of `$_` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` ḃḍ{↔|h1&b↔}ᵗz₂≠ᵐ ``` [It doesn't quite work online...](https://tio.run/##SypKTM6ozMlPN/pfXa6kkFmsVG5f/ahtw6Om5kcdK5QU8vJLlMprH3UsV1JIVEjLz0nJzEtXyCvNTUot0lN6uKuz9uHWCf8f7mh@uKMXqG1KTYahWhKQBgpPr3rU1PSocwFIwf9oQ3MLHUMzExMdEyNTEx1DHSMdMx1DAx1DIx0jIALKmeoYmesYxwIA "Brachylog – Try It Online") Takes input through the input variable and outputs through success or failure. It relies heavily on `z₂`, which has been in the language since April 30, but we forgot to ask to have it pulled on TIO so for the time being this only works on a local installation of the language. Either way it's probably an overly naive approach. ``` The input ḃ 's binary representation ḍ split in half { }ᵗ with its second half ↔| either reversed, or h1 if it starts with 1 &b relieved of its first element ↔ and then reversed ≠ has no duplicate elements z ᵐ in any pair of elements zipped from the two halves ₂ which are equal in length. ``` # [Brachylog](https://github.com/JCumin/Brachylog) (on TIO), 19 bytes ``` ḃḍ{↔|h1&b↔}ᵗlᵛ↖Lz≠ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kkFmsVG5f/ahtw6Om5kcdK5QU8vJLlMprH3UsV1JIVEjLz0nJzEtXyCvNTUot0lN6uKuz9uHWCf8f7mh@uKMXqG1KTYahWhKQBgpPz3m4dfajtmk@VY86F4BU/Y82NLfQMTQzMdExMTI10THUMdIx0zE00DE00jECIqCcqY6RuY5xLAA "Brachylog – Try It Online") `lᵛ↖Lz` is functionally equivalent to `z₂` (if you don't use the variable L anywhere else), but it's also three bytes longer. [Answer] # Python 2, ~~76 71~~ 69 bytes -5 bytes thanks to @Dennis (`''` is present in `'1'`, so replace `in('','1')` with `in'1'`) -2 bytes thanks to @xnor (use multiplication, `(...)*` in place of `and`) ``` f=lambda n:f(bin(n)[2:])if n<''else n in'1'or(n[0]!=n[-1])*f(n[1:-1]) ``` **[Ideone](http://ideone.com/tT0NpQ)** Recursive function, upon first call `n` is a number so it evaluates as less than the empty string, with `if n<''`, and the function is called again but with `n` cast to a binary string; the tail is either an empty string (even bit-length) or the middle bit, which returns true for empty or a `'1'`; on it's way down it tests the outer bits for inequality (equivalent to XOR) and recurses on the inner bits, `n[1:-1]`. [Answer] ## Python 2, 63 bytes ``` s=bin(input())[2:] while s[0]!=s[-1]:s=s[1:-1]or'1' print'1'==s ``` Prints `True` or `False`. Takes the binary representation of `s` and repeatedly removed the first and last characters as long as they are unequal. Checks whether what remains is the empty string or a central `1`. This is done by converting `''` to `'1'` and checking if the result equals `'1'`, which also avoid an index error on the empty string. [Answer] ## PowerShell v2+, 143 bytes Two possible approaches, both the same byte count. Method 1: ``` param($n)if($n-eq1){$n++}$o=1;0..(($b=($n=[convert]::ToString($n,2)).length-1)/2-!($b%2))|%{$o*=$n[$_]-ne$n[$b-$_]};$o*(+"$($n[$b/2])",1)[$b%2] ``` Takes input `$n`, if it's `-eq`ual to `1` (a special case for this algorithm), increment it. Set `$o`utput to be `1` (i.e., assume truthy), then loop from `0` to the midway point of the input number that has been `[convert]`ed to binary. Note the `-!($b%2)` to account for odd length binary numbers. Each iteration, we compare the current digit `$n[$_]` with the digit the same length from the end `$n[$b-$_]`, and multiply the Boolean result into `$o` (essentially performing an `-and` on all of them). Once the loop is done, we need to potentially account for the middle binary digit, that's the pseudo-ternary at the end (array indexed via `$b%2`). That `1` or `0` is left on the pipeline, and output is implicit. --- Method 2: ``` param($n)for($n=[convert]::ToString($n,2);$n.Length-gt2){if($n[0]-ne$n[-1]){$n=$n[1..($n.Length-2)]}else{0;exit}}($n-join'+'|iex)-eq1-or$n-eq10 ``` Takes input and does the same process to `[convert]` the number to binary. Then we're in a `for` loop so long as the `.length` of the binary string is `-g`reater`t`han `2`. When we're in the loop, if the first `$n[0]` and last `$n[-1]` digits are `-n`ot`e`qual, slice those two digits off of `$n` and re-store it into `$n`. Otherwise, output `0` and `exit`. Once we're out of the loop, we either have (an array of `1`, `1,0`, `0,1`, `1,1`, or `0,0`), or the binary string for two `10`, or 3 `11`. So, we need to test those two possibilities. For the first, we `-join` `$n` together with `+` and evaluate the result and test that it's `1` (this is true for arrays `1`, `1,0`, and `0,1`, but is `$false` for arrays `0,0` and `1,1` or strings `10` or `11`). The other half of the `-or` is testing whether `$n` is `-eq`ual to `10` (i.e., input of `2`). That Boolean is left on the pipeline, and output is implicit. [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 13 bytes ``` ri2b_W%.+:*3& ``` [Try it online!](http://cjam.tryitonline.net/#code=cmkyYl9XJS4rOiozJg&input=Ng) or [generate a list](http://cjam.tryitonline.net/#code=J1tyaSl7SQoyYl9XJS4rOiozJgp7SScsU30mCn1mSTs7J10&input=NDU1OA) of folding numbers up to a given number. --- ``` ri2b e# convert input to binary _W%.+ e# flip and sum (if folding all bits are 1 except middle) :* e# product is 0 or power of 2 (2 if middle folds) 3& e# keep only 1 or 2, everything else becomes 0 (false) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 16 bytes ``` tBn2/kW&\hBZ}P=~ ``` Truthy is an array with all ones. Check truthy/falsy criteria [here](http://matl.tryitonline.net/#code=PyAgICAgICAgICUgaWYKJ3RydXRoeScgICUgcHVzaCBzdHJpbmcKfSAgICAgICAgICUgZWxzZQonZmFsc3knICAgJSBwdXNoIHN0cmluZw&input=WzEgMCAxXQ). [**Try it online!**](http://matl.tryitonline.net/#code=dEJuMi9rVyZcaEJafVA9fg&input=MTY0NA) Or [**Verify the first 20 test cases**](http://matl.tryitonline.net/#code=IkAKdEJuMi9rVyZcaEJafVA9fg&input=MToyMA). ### Explanation Let's use input `1644` as an example. ``` t % Imolicitly take input. Duplicate % STACK: 1644, 1644 Bn % Number of digits of binary expansion % STACK: 1644, 11 2/k % Divide by 2 and round down % STACK: 1644, 5 W % 2 raised to that % STACK: 1644, 32 &\ % Divmod % STACK: 12, 51 h % Concatenate horizontally % STACK: [12 51] B % Binary expansion. Each numnber gives a row, left-padded with zeros if needed % STACK: [0 0 1 1 0 0; 1 1 0 0 1 1] Z} % Split into rows % STACK: [0 0 1 1 0 0], [1 1 0 0 1 1] P % Reverse % STACK: [0 0 1 1 0 0], [1 1 0 0 1 1] =~ % True for entries that have different elements % STACK: [1 1 1 1 1 1] % Implicitly display ``` [Answer] # PHP, 101 Bytes ``` for($r=1;$i<($l=strlen($b=decbin($argv[1])))>>1;)$r*=$b[$i]^1^$b[$l-++$i]^1;$r*=$l%2?$b[$i]:1;echo$r; ``` or with log ``` for($r=1,$s=log($n=$argv[1],2)^0;2*$i<$s;)$r*=($n>>$i)%2^($n>>$s-$i++)%2;$s%2?:$r*=($n>>$i)%2;echo$r; ``` 108 Bytes with array ``` for($r=1,$a=str_split(decbin($argv[1]));$a;)$r*=array_pop($a)!=($a?array_shift($a):0);$r*=$a?$a[0]:1;echo$r; ``` True values <10000 ``` 1,2,6,10,12,22,28,38,42,52,56,78,90,108,120,142,150,170,178,204,212,232,240,286,310,346,370,412,436,472,496,542,558,598,614,666,682,722,738,796,812,852,868,920,936,976,992,1086,1134,1206,1254,1338,1386,1458,1506,1596,1644,1716,1764,1848,1896,1968,2016,2110,2142,2222,2254,2358,2390,2470,2502,2618,2650,2730,2762,2866,2898,2978,3010,3132,3164,3244,3276,3380,3412,3492,3524,3640,3672,3752,3784,3888,3920,4000,4032,4222,4318,4462,4558,4726,4822,4966,5062,5242,5338,5482,5578,5746,5842,5986,6082,6268,6364,6508,6604,6772,6868,7012,7108,7288,7384,7528,7624,7792,7888,8032,8128,8318,8382,8542,8606,8814,8878,9038,9102,9334,9398,9558,9622,9830,9894 ``` [Answer] # [Julia](http://julialang.org), 66 bytes ``` c(s)=s==""||s=="1"||(s[1]!=s[end]&&c(s[2:end-1])) f(x)=c(bin(x)) ``` My first golf! works the same way as the Python solution of the same length, minor differences due to language (I did come up with it on my own, though...). Explanation: ``` c(s) = s == "" || # Base case, we compared all the digits from # both halves. s == "1" || # We compared everything but left a 1 in the middle (s[1] != s[end] && # First digit neq last digit (XNOR gives 0). c(s[2:end-1])) # AND the XNOR condition is satisfied for the # 2nd to 2nd to last digit substring. f(x) = c(bin(x)) # Instead of a string f takes an integer now. ``` [Answer] # C, ~~223~~ ~~201~~ ~~189~~ ~~194~~ 178 Bytes ``` i,j,m,l,r;f(n){for(m=j=1,i=n;i/=2;++j);for(l=r=i=0;i<j/2;i++)r|=n&m?1<<j/2-i-1:0,m*=2;i=(j&1&&n&m)?i+1:(j&1)?l=r:i;n>>=i;for(m=1;i<j;i++)l|=n&m,m*=2;return !(~(l^r)&(1<<j/2)-1);} ``` Brute force algorithm. Let's see how far it can be golfed. Better test setup bugfixes... ``` main() { int t, s, u, testSet[] = { 1, 2, 6, 10, 12, 22, 28, 38, 42, 52, 56, 78, 90, 108, 120, 142, 150, 170, 178, 204, 212, 232, 240, 286, 310, 346, 370, 412, 436, 472, 496, 542, 558, 598, 614, 666, 682, 722, 738, 796, 812, 852, 868, 920, 936, 976, 992, 1086, 1134, 1206, 1254, 1338, 1386, 1458, 1506, 1596, 1644, 1716, 1764, 1848, 1896, 1968, 2016, 2110, 2142, 2222, 2254, 2358, 2390, 2470, 2502, 2618, 2650, 2730, 2762, 2866, 2898, 2978, 3010, 3132, 3164, 3244, 3276, 3380, 3412, 3492, 3524, 3640, 3672, 3752, 3784, 3888, 3920, 4000, 4032, 4222, 4318, 4462, 4558 }; for (u=s=0,t=1;t<=4558;t++) { if (f(t)) { u++; if (testSet[s++]!=t) printf("BAD VALUE %d %d\n", testSet[s-1], t); } } printf("%d == %d Success\n", u, sizeof(testSet)/sizeof(testSet[0])); } ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 13 bytes ``` BttP=<~5Ms2<* ``` Truthy is an array with all ones. Check truthy/falsy criteria [here](https://tio.run/##y00syfn/36mkJMDWps7Ut9jIRuu/vXpJUWlJRqU6V616WmJOcaX6f0MzExMA). [**Try it online!**](http://matl.tryitonline.net/#code=QnR0UD08fjVNczI8aA&input=MTY0NA) Or [**verify the first 20 test cases**](http://matl.tryitonline.net/#code=IkAKQnR0UD08fjVNczI8Kg&input=MToyMA). ### Explanation Using input `1644` as an example: ``` B % Implicit input. Convert to binary % STACK: [1 1 0 0 1 1 0 1 1 0 0] t % Duplicate % STACK: [1 1 0 0 1 1 0 1 1 0 0], [1 1 0 0 1 1 0 1 1 0 0] tP= % Element-wise compare each entry with that of the reversed array % STACK: [1 1 0 0 1 1 0 1 1 0 0], [0 0 0 0 0 1 0 0 0 0 0] <~ % True (1) if matching entries are equal or greater % STACK: [1 1 1 1 1 1 1 1 1 1 1] 5M % Push array of equality comparisons again % STACK: [1 1 1 1 1 1 1 1 1 1 1], [0 0 0 0 0 1 0 0 0 0 0] s % Sum of array % STACK: [1 1 1 1 1 1 1 1 1 1 1], 1 2< % True (1) if less than 2 % STACK: [1 1 1 1 1 1 1 1 1 1 1], 1 * % Multiply % STACK: [1 1 1 1 1 1 1 1 1 1 1] % Implicitly display ``` [Answer] # JavaScript, 71 bytes ``` (i,n=i.toString(2))=>/^(1*)2?\1$/.test(+n+ +n.split``.reverse().join``) ``` Defines an anonymous function. This method may not be the shortest, but as far as I know, it is unique. It adds the number in binary to itself reversed, treating them as decimal, then checking if the result is valid using a regex. [Answer] # Retina, 92 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $* +`(1+)\1 ${1}0 01 1 ^((.)*?)1??((?<-2>.)*$.*) $1¶$3 O$^`.(?=.*¶) T`01`10`^.* ^(.*)¶\1 ``` [**Try it online**](http://retina.tryitonline.net/#code=LisKJCoKK2AoMSspXDEKJHsxfTAKMDEKMQpeKCguKSo_KTE_PygoPzwtMj4uKSokLiopCiQxwrYkMwpPJF5gLig_PS4qwrYpCgpUYDAxYDEwYF4uKgpeKC4qKcK2XDE&input=NDU1OA) Convert to unary. Convert that to binary. Cut the number in half and remove a middle `1` if there is. Reverse the first half. Switch its ones and zeros. Match if both halves are equal. [Answer] ## Retina, ~~71~~ ~~70~~ 60 bytes ``` .+ $* +`^(1*)\1(1?)\b $1 $.2 +`^ (.)(.*) (?!\1).$ $2 ^( 1)?$ ``` I probably still have a lot to learn about Retina (e.g. recursive regex?). Explanation: Step 1 converts from decimal to unary. Step 2 converts from unary to pseudo-binary. Step 3 removes digits from both ends as long as they mismatch. Step four matches an optional final central 1 if necessary. Edit: Saved 1 byte thanks to @mbomb007. Saved 10 bytes by improving my unary to binary conversion. [Answer] # Python 2, ~~61~~ 59 bytes Saving two bytes for converting shifts to multiplications ``` m=n=input() i=0 while m:i*=2;i+=m&1;m/=2 print(n+i+1)&(n+i) ``` Returns `0` for a folding number and anything else for non-folding. Uses the bit-twiddling approach. [Answer] # C, ~~65~~ 63 bytes Two bytes for converting shifts to multiplications ``` i,m; f(n){ m=n;i=0; while(m)i*=2,i+=m&1,m/=2; return(n+i+1)&(n+i); } ``` Whitespace is already excluded from bytecount, returns 0 for a folding number and anything else for non-folding. Uses the bit-twiddling approach. [Answer] # k, 77 bytes ``` {X:2 0N#X@&:|\X:0b\:x;c:#:'X;$[(~*X 1)|(=). c;~|/(=).(::;|:)@'(-&/ c)#'X;0b]} ``` by way of explanation, a translation to `q` ``` {X:2 0N#X where maxs X:0b vs x; c:count each X; $[(not first last X)or(=). c; not any(=).(::;reverse)@'(neg min c)#'X;0b] }; ``` ]
[Question] [ As you may know it, the factorial of a positive integer `n` is the product of all the positive integers which are equal or smaller to `n`. For instance : ``` 6! = 6*5*4*3*2*1 = 720 0! = 1 ``` We will now define a special operation with an irrelevant name like `sumFac`: Given a positive integer `n`, `sumFac(n)` is the sum of the factorials of the digits. For instance : `sumFac(132) = 1! + 3! + 2! = 9` ## Task Your mission, whether or not you choose to accept it, is to return the sequence (potentially infinite) of the applications of `sumFac` to an integer given in input. Example : `132 -> 132, 9, 362880, 81369, 403927, ...` But that's not all! Indeed, the applications of `sumFac` will eventually create a cycle. You must also return this cycle! If your language has a built in factorial you can use it. I'm not picky about the return type, you just have to return the sequence of sumFac applications and the cycle in a format understandable by a human. EDIT : To help you visualize better what should the output look like I copied Leaky Nun's just below: ``` [132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454] ``` You just need to stop the sequence when the cycle is about to start for the second time! But this is [code-golf](https://codegolf.stackexchange.com/questions/tagged/code-golf) so the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` D!SµÐĿ ÐĿ Repeat until the results are no longer unique. Collects all intermediate results. D Convert from integer to decimal (list of digits) ! Factorial (each digit) S Sum ``` [Try it online!](https://tio.run/nexus/jelly#@@@iGHxo6@EJR/b////f0NgIAA "Jelly – TIO Nexus") I don't see any other way to make it shorter other than to do as told. ## Specs * Input: `132` (as command-line argument) * Output: `[132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]` [Answer] # [Python 2](https://docs.python.org/2/), 88 bytes ``` import math f=lambda x,l=[]:l*(x in l)or f(sum(math.factorial(int(i))for i in`x`),l+[x]) ``` [Try it online!](https://tio.run/nexus/python2#FcsxCoAwDEDR3VNkTFQEdRM8iQiNSjGQWqkVevta5/9@Fnf7EMFxPCs7K7vtYEitzss6aY0J5AIlH8Di8zr8XWd5jz4IK8oVUYhs6VKkSYZabZa0Ur5DieXqx4HyBw "Python 2 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` [DˆS!O©¯så#® ``` [Try it online!](https://tio.run/nexus/05ab1e#@x/tcrotWNH/0MpD64sPL1U@tO7/f0NjIwA "05AB1E – TIO Nexus") **Explanation** ``` [ # infinite loop Dˆ # add a copy of current value to the global list (initialized as input) S # split current number to digits !O # calculate factorial of each and sum © # save a copy in register ¯så# # if the current number is in the global list, exit loop ® # retrieve the value from the register for the next iteration # implicitly output the global list ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` g:I{tẹḟᵐ+}ᵃ⁾L¬≠Lk ``` [Try it online!](https://tio.run/nexus/brachylog2#ASYA2f//ZzpJe3ThurnhuJ/htZArfeG1g@KBvkzCrOKJoExr//8xMzL/Wg "Brachylog – TIO Nexus") ### Explanation ``` g:I{ }ᵃ⁾ Accumulate I (a variable) times, with [Input] as initial input: t Take the last integer ẹḟᵐ+ Compute the sum of the factorial of its digits L The result of the accumulation is L L¬≠ Not all elements of L are different Lk Output is L minus the last one (which is the start of the loop) ``` [Answer] # Wolfram Language, ~~62~~ ~~60~~ 56 bytes ``` Most@NestWhileList[Tr[IntegerDigits@#!]&,#,UnsameQ,All]& ``` It is really too bad that Wolfram Language has such abominably long function names. \*Sigh\* **Explanation:** ``` Most[NestWhileList[Tr[IntegerDigits[#]!]&,#,UnsameQ,All]]& IntegerDigits[#] (*Split input into list of digits*) ! (*Factorial each element in the list*) Tr[ ]& (*Sum the list together*) NestWhileList[ ,#,UnsameQ,All] (*Iterate the function over itself, pushing each to a list, until a repeat is detected*) Most[ ]& (*Remove the last element in the list*) ``` [Answer] # ClojureScript, ~~146~~ 109 bytes ``` #(loop[n[%]](let[f(apply +(for[a(str(last n))](apply *(range 1(int a))))](if(some #{f}n)n(recur(conj n f))))) ``` Yikes, that is a monstrosity. Someone please help me golf this... Thanks `@cliffroot` for shaving off a whopping 37 bytes! This is an anonymous function, to run the function, you have to do this: ``` (#(...) {arguments}) ``` TIO doesn't have ClojureScript, so [here's a link](http://clojurescript.io/) to a ClojureScript REPL. [Here's a link](https://tio.run/nexus/clojure#dVJBboQwDLzzipEqVaEVEvuAvgTtwQqBpgIHQTisVn07dZKNmm53cyBoZmyP7RyqNwNjIO0bfdGTQcfnClCTc4v87/MWkAAF0Hh0UStEhNJJxObXhqHkEoA2jxBd1@dCKFJalumC9z@gwINb0RHUSjwaKO129ogZ7zMUWd7@EcgZTg8oIS3rh0SIM9Q3UtHy@ESC2NxTUmj2n8k0qM4nu1d2kHg3G7xc8wy/04zityqc6L0sI9Pgr6hBDkypqyqtr5nJMrpX0DpuxfoI7W1zofYHCKe2baWcnbKp3v3WXaR3P4n32/5U8SxCP3cO4zRzo4eKJurjBw "Clojure – TIO Nexus") to a Clojure program which prints the last element in the list from 0 to 1000. Here's the output for `9999`: ``` [9999 1451520 269 363602 1455 265 842 40346 775 10200 6 720 5043 151 122 5 120 4 24 26 722 5044 169 363601 1454] ``` I have a strong suspicion that all numbers must eventually settle at `1` or the loop `[169 363601 1454]`. ## Ungolfed code: ``` (defn fact-cycle [n] (loop [nums [n]] (let [fact-num (let [str-n (str (last nums))] (apply + (for [a (range (count str-n))] (apply * (range 1 (inc (int (nth str-n a))))))))] (if (some #{fact-num} nums) nums (recur (conj nums fact-num)))))) ``` Explanation coming soon! [Answer] ## JavaScript (ES6), ~~91~~ 89 bytes *Saved 2 bytes thanks to fəˈnɛtɪk* It turns out to be quite similar to [the other JS answer](https://codegolf.stackexchange.com/a/117596/58563). ``` f=(n,x=!(a=[n]))=>n?f(n/10|0,x+(F=n=>n?n--*F(n):1)(n%10)):~a.indexOf(x)?a:f(x,!a.push(x)) ``` ``` f=(n,x=!(a=[n]))=>n?f(n/10|0,x+(F=n=>n?n--*F(n):1)(n%10)):~a.indexOf(x)?a:f(x,!a.push(x)) console.log(f(132)) ``` [Answer] # [Perl 6](https://perl6.org), 64 bytes ``` {my@a;$_,{[+] .comb.map:{[*] 2..$_}}...^{$_∈@a||[[email protected]](/cdn-cgi/l/email-protection): $_}} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFArLs3VTUtMLskvykzMUbD9X51b6ZBorRKvUx2tHaugl5yfm6SXm1hgVR2tFatgpKenEl9bq6enF1etEv@oo8MhsaZG0SFRr6C0OMNKAST3vzixUgHVUENjI2suTGELbIKGJqYm1v8B "Perl 6 – TIO Nexus") ## Expanded: ``` { my @a; # array of values already seen $_, # seed sequence with the input { [+] # reduce using &infix:<+> .comb # the digits of $_ (implicit method call) .map: # do the following for each { [*] 2..$_ # get the factorial of } } ...^ # keep generating values until # (「^」 means throw away the last value when done) { $_ ∈ @a # is it an elem of @a? (「∈」 is shorter than 「(cont)」) || # if it's not ! # boolean invert so this returns False @a.push: $_ # add the tested value to @a } } ``` Every line above that has `{` starts a new bare block lambda with an implicit parameter of `$_`. I used `[*] 2..$_` instead of `[*] 1..$_` purely as a micro optimization. [Answer] # JavaScript, 92 bytes Thanks @Shaggy for golfing off one byte with includes Thanks @Neil for golfing off two bytes **Code separated into individual functions 92 bytes** ``` f=(x,a=[])=>a.includes(x)?a:f(k(x),a,a.push(x)) p=y=>y?y*p(y-1):1 k=n=>n?p(n%10)+k(n/10|0):0 ``` **Code on one line 92 bytes** ``` f=(x,a=[])=>a.includes(x)?a:f((k=n=>n?(p=y=>y?y*p(y-1):1)(n%10)+k(n/10|0):0)(x),a,a.push(x)) ``` ## Explanation Initially call the function with just a single argument, therefore a=[]. If x exists in the array a return a `a.includes(x)?a:...` Otherwise, append x to a and pass the factorial digit sum and a to the function `(a.push(x),f(k(x),a))` ``` p=y=>y?y*p(y-1):1 k=n=>n?p(n%10)+k(n/10|0):0 ``` Factorial Digit sum performed so that it will not exceed the maximum recursion limit. **List of all possible endpoints:** 1, 2, 145, 169, 871, 872, 1454, 40585, 45361, 45362, 363601 [Try it online!](https://tio.run/nexus/javascript-node#DcbBCgIhEADQ@/5HMFOuad2E0Q@JDsO2ViijIAsr9O@27/RGJNgV0@OJ5Fl/Zcnba22wY2AXIR1RrFjXrX2O41Spk@@hnyv02aKzUyIhL6GCnKzBSwK5WvMz6MxYirSSV53LGyLY@w1x/AE) [Answer] # [Haskell](https://www.haskell.org/), ~~80~~ 67 bytes ``` g#n|elem n g=g|h<-g++[n]=h#sum[product[1..read[d]]|d<-show n] ([]#) ``` [Try it online!](https://tio.run/nexus/haskell#BcFBCoAgEADAe69YsEMRBtU1X7LsQdI0yE006eLfbaY5wdXeNgCDU676XbppQiblRS4BY3pMOV5c5jlZbdAQVbPL7J8PmLpTDUhibEFfDApiuviFHk5YtrX9 "Haskell – TIO Nexus") Usage: `([]#) 132` Edit: Saved 13 bytes with typs from Ørjan Johansen! [Answer] # Pyth, 9 bytes ``` .us.!MjNT .us.!MjNTQ implicit Q .u explained below N current value j T convert to decimal (list of digits) .!M factorial of each digit s sum ``` [Try it online!](http://pyth.herokuapp.com/?code=.us.%21MjNT&input=132&debug=0) This answer uses `.u` ("Cumulative fixed-point. Apply until a result that has occurred before is found. Return all intermediate results.") [Answer] # Pyth, 30 bytes ``` W!hxYQQ=+YQKQ=Q0WK=+Q.!%KT=/KT ``` [Try It Here](http://pyth.herokuapp.com/?code=W%21hxYQQ%3D%2BYQKQ%3DQ0WK%3D%2BQ.%21%25KT%3D%2FKT&input=132&debug=0) [Answer] # [Python 3](https://docs.python.org/3/), 110 bytes ``` g=lambda x:x<1or x*g(x-1) def f(n): a=[];b=n while b not in a:a+=[b];yield b;b=sum(g(int(x))for x in str(b)) ``` [Try it online!](https://tio.run/nexus/python3#PcxNCsMgEEDhvaeY5UxLF7Y7U08SsnDwp4IxxRhqT28SCt0@Pl4POpmZrYGm2lMuBdolYLtJEtZ58JhJCTB6nAbWWcDnFZMDhrxUiBmMMlc98jR8o0sW@EDrNmPAmCs2In8OT7jWgkzU/8GjfNxJvctP9h0 "Python 3 – TIO Nexus") [Answer] # R, 120 Bytes ``` o=scan() repeat { q=sum(factorial(as.double(el(strsplit(as.character(o[length(o)]), ""))))) if(q%in%o)break o=c(o,q) } o ``` [Answer] # Java 9 JSHell, 213 bytes ``` n->{Set<Integer>s=new HashSet<>(); return IntStream.iterate(n,i->(""+i).chars() .map(x->x<50?1:IntStream.rangeClosed(2,x-48) .reduce(1,(a,b)->a*b)).sum()).boxed() .takeWhile(x->s.add(x)).collect(Collectors.toList());} ``` [Try it online!](https://tio.run/nexus/java-openjdk9#bVCxTsMwEN3zFVYnuyQWLSAh0oahEgIJpgwMiOGSXFODY0f2paSq@u3FoamQELc8@b1357unmtY6Yh@wBdmR0nKaRuovt@5MScqaf0VPDqEZpKjtCq1KVmrwnr2AMmwfsVAj7wkowNaqijVB5Tk5Zeq3dwau9mI0D/Uwfrh4MoQ1upg9K0/nV5axNVseTZLtc/xl/dLgF3sEvxnYjIvUIXXOsGDIT0sqQgeE3MQqyfhkcqGELDfgPBeygZb3SdYvbi7vZ3e/PQ5MjSttPVZ8HvfJ9a2QDquuRD6LOcSFSDKYFkJI3zU8QGH7YBWS4BNfN0rjMNZLqCreB7m0WmNJfHVC67wkO5wXetPD8RxBmu88YSNtR7INMZE2fC2hbfWOD3fmJRiDjo82ZYQ02FPYO8wR6U@Uh@hwnF3NvwE "Java (OpenJDK 9) – TIO Nexus") Note: This solution relies on the string representation of a number having code points in the range 48-57. Works for ASCII, UTF-8, Latin-1, all ISO-8859-\* character sets, most code pages. Does not work for EBCDIC. I don't think anyone will deduct points for that. :) Ungolfed: ``` Function<Integer, List<Integer>> f = // function from Integer to List of Integer n -> { Set<Integer> s = new HashSet<>(); // memo of values we've seen return IntStream.iterate(n, // iterate over n, f(n), f(f(n)), etc. i -> (""+i).chars() // the sumFac function; for all chars .map(x -> x < 50? 1 : // give 1 for 0! or 1! IntStream.rangeClosed(2, x-48) // else produce range 2..d .reduce(1,(a,b)->a*b)) // reduction to get the factorial .sum()) // and sum up the factorii! // now we have a stream of ints // from applying sumFac repeatedly .boxed() // box them into Integers (thanks, Java) .takeWhile(x->s.add(x)) // and take them while not in the memo .collect(Collectors.toList()); // collect them into a list } ``` Notes: * The return value of Set::add is very helpful here; returns true **iff** the item was not in the set * I was being sarcastic when I said "Thanks, Java" * *factorii* isn't really a word; I just made that up [Answer] # Pyth, ~~22~~ 11 bytes ``` .usm.!sd+Nk ``` [Try it online!](http://pyth.herokuapp.com/?code=.usm.%21sd%2BNk&input=132&debug=0) Lots of credit to [Leaky Nun's answer](https://codegolf.stackexchange.com/a/117669/52152), which introduced me to `.u`, and helped save a massive 11 bytes of this program. Explanation: ``` .usm.!sd+NkQ | ending Q is implicitly added | Implicit: Q = eval(input()) .u Q | Repeat the function with initial value Q until a previous value is found. Return all intermediate values s | Summation m.!sd | For each character 'd' in the string, convert to integer and take the factorial +Nk | Convert function argument to string ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` U¡oṁΠd ``` [Try it online!](https://tio.run/##yygtzv7/P/TQwvyHOxvPLUj5//@/obERAA "Husk – Try It Online") [Answer] # Axiom, 231 bytes ``` l(a:NNI):List NNI==(r:List NNI:=[];repeat(r:=cons(a rem 10,r);a:=a quo 10;a=0=>break);r) g(a:NNI):NNI==reduce(+,[factorial(x) for x in l(a)]) h(a:NNI):List NNI==(r:=[a];repeat(a:=g(a);member?(a,r)=>break;r:=cons(a,r));reverse(r)) ``` not golfed functions and some test ``` -- convert one NNI in its list of digits listify(a:NNI):List NNI== r:List NNI:=[] repeat r:=cons(a rem 10,r) a:= a quo 10 a=0=>break r -- g(1234)=1!+2!+3!+4! SumfactorialDigits(a:NNI):NNI==reduce(+,[factorial(x) for x in listify(a)]) ListGenerateFromSumFactorialDigits(a:NNI):List NNI== r:=[a] repeat a:=SumfactorialDigits(a) member?(a,r)=>break r:=cons(a,r) reverse(r) (9) -> h 132 (9) [132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454] ``` [Answer] # Java 7, 220 bytes ``` String c(int n){String r=n+",",c;for(;!r.matches("^"+(c=(n=d(n))+",")+".*|.*,"+c+".*");r+=c);return r;}int d(int n){int s=0;for(String i:(n+"").split(""))s+=f(new Long(i));return s;}long f(long x){return x<2?1:x*f(x-1);} ``` **Explanation:** ``` String c(int n){ // Method with integer parameter and String return-type String r=n+",", // Result-String (which starts with the input integer + a comma c; // Temp String for(;!r.matches( // Loop as long as the result-String doesn't match the following regex: "^"+(c=(n=d(n))+",")+".*|.*,"+c+".*"); // "^i,.*|.*,i,.*" where `i` is the current integer // `n=d(n)` calculates the next integer in line // `c=(n=d(n))+","` sets the temp String to this integer + a comma r+=c // And append the result-String with this temp String ); // End of loop return r; // Return the result-String } // End of method int d(int n){ // Separate method (1) with integer parameter and integer return-type int s=0; // Sum for(String i:(n+"").split("")) // Loop over the digits of `n` s+=f(new Long(i)); // And add the factorial of these digits to the sum // End of loop (implicit / single-line body) return s; // Return the sum } // End of separate method (1) long f(long x){ // Separate method (2) with long parameter and long return-type (calculates the factorial) // (NOTE: 2x `long` and the `new Long(i)` is shorter than 2x `int` and `new Integer(i)`, hence long instead of int) return x<2? // If `x` is 1: 1 // return 1 : // Else: x*f(x-1); // return `x` multiplied by the recursive-call of `x-1` } // End of method (2) ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#PY4xb4MwEIX3/IqrpzugVki3uFbnSs2UMUol1wFiCQyyTUtF@e3UIFoP99757PedrpX3cBrnc3DGVqDR2ACWxq130qYsY5kWZetQPDjeqKDvhUf2zlLUEq28oSVaXsXCkx@eZCzVi2UkXCp1rEXonQUnpiX99sdYxMv9Gr3xzBEjkBH3XW0CRkc@lSXa4gveWluhof84L6Y6XkGJqww0boPh@fCSH4ekxOExJzHNAF3/URsNPqgQ5bM1N2iUsRv2cgVF4w7iOX/7UDS87QPv4ijUdmWfkLhe3asNRVU4VJf9leIy8de0m@Y5fzr8Ag) ``` class M{ String c(int n){String r=n+",",c;for(;!r.matches("^"+(c=(n=d(n))+",")+".*|.*,"+c+".*");r+=c);return r;}int d(int n){int s=0;for(String i:(n+"").split(""))s+=f(new Long(i));return s;}long f(long x){return x<2?1:x*f(x-1);} public static void main(String[] a){ System.out.println(new M().c(132)); } } ``` **Output:** ``` 132,9,362880,81369,403927,367953,368772,51128,40444,97,367920,368649,404670,5810,40442,75,5160,842,40346,775,10200,6,720,5043,151,122,5,120,4,24,26,722,5044,169,363601,1454, ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 44 bytes ``` ~]{..)\;10base{,1\{)*}/}%{+}*.@\+@@?)!}do);` ~ eval input ] initialization { }do do... ..)\; initialization 10base get digits {,1\{)*}/}% factorial each {+}* sum .@\+@@?)! while result not found ); drop last element ` tostring ``` [Try it online!](https://tio.run/nexus/golfscript#@18XW62npxljbWiQlFicWq1jGFOtqVWrX6tarV2rpecQo@3gYK@pWJuSr2md8P@/obERAA "GolfScript – TIO Nexus") The factorial part is from [here](https://codegolf.stackexchange.com/a/629/48934). [Answer] ## C, 161 bytes ``` f(a){return a?a*f(a-1):1;} a(l){return l?f(l%10)+a(l/10):0;} c,t,o;r(i){for(t=o=i;t=a(t),o=a(a(o)),c=t^o;);for(t=i;t^c;printf("%d ",t),c=c|t^o?c:o,t=a(t),o=a(o));} ``` [See it work online.](https://ideone.com/FiF0VM) [Answer] # TI-BASIC, ~~85~~ ~~79~~ ~~64~~ 60 bytes ``` :Prompt L₁ //Get input as 1 length list, 4 bytes :Lbl C //create marker for looping, see below, 3 bytes :int(10fPart(Xseq(10^(~A-1),A,0,log(X //split input into list of digits, 20 bytes :sum(Ans!→X //factorial and sum the list, write to new input, 6 bytes :If prod(L₁-X //Test to see if new element is repeated, see below, 7 bytes :Then //Part of If statement, 2 bytes :augment(L₁,{X→L₁ //Push new input to List 1, 10 bytes :Goto C //Loop back to beginning, 3 bytes :Else //Part of If statement, 2 bytes :L₁ //Print Answer, 2 bytes ``` Since this is running on a graphing calculator, there is limited RAM. Try testing it with numbers that loop quickly, like `169`. **More Explanation:** ``` :int(10fPart(Xseq(10^(~A-1),A,0,log(X seq(10^(~A-1),A,0,log(X //Get a list of powers of 10 for each digit (i.e. 1, 0.1, 0.01, etc.) X //Multiply by input fPart( //Remove everything but the decimal 10 //Multiply by 10 (move one digit in front of the decimal :int( //Truncate to an integer ``` `If prod(L₁-X` works by subtracting the new element from the old list, then multiplying all the elements of the list together. If the element was already in the list, the product will be `0`, a falsey value. Otherwise, the product will be a positive integer, a truthy value. [Answer] # [J](http://jsoftware.com/), 40 31 bytes Edit: 9 bytes saved using the improvements by FrownyFrog. Thanks! ``` f=.$:@,~`]@.e.~[:+/@:!10#.inv{: ``` Original code: ``` f=.[`($:@,)@.([:-.e.~)[:+/!@("."0&":@{:) ``` In this case I decided to count the bytes for the verb definition, since otherwise it doesn't work in the interpreter. Explanation: ``` ( {:) - Takes the last element of the array ":@ - converts it to string "."0& - converts each character back to integer !@ - finds the factorials +/ - sums them [: - cap (there are 2 derived verbs above, we need 3 for a fork) ( e.~) - check if the result is present in the list -. - negates the above check [: - cap @. - Agenda conjunction, needed for the recursion ($:@,) - if the result is not in the list, add it to the list and recur [` - if the result is in the list, display it and stop ``` [Try it online!](https://tio.run/##y/r/P81WLzpBQ8XKQUfTQU8j2kpXL1WvTjPaSltf0UFDSU/JQE3JyqHaSvN/anJGvkKagqGR8X8A "J – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 143 bytes ``` proc P {n L\ ""} {proc F n {expr $n?($n)*\[F $n-1]:1} while {[set n [expr [join [lmap d [split $n ""] {F $d}] +]]] ni $L} {lappend L $n} set L} ``` [Try it online!](https://tio.run/##HY69DoMwDIT3PMUJMfRHHWg3lm6dMrAHDwgiNVVqIkjVSlGePTVMPtnf3TmOvpSwzCM6JIbuUVUZad88wEj2FxbUfD/UfDz15iH60lDbZPV9Om@RzGqjgGYHzWt2ov17CJhg1uBdFIeEEpJ4p0w4ExHYodZS5IcQLE/QQmW1Relcdrt0q@Z2Vds3n7jKve3ZdDIpl/IH "Tcl – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~17~~ ~~16~~ 15 bytes Saved 1 byte thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) and another later ``` f←(#+.(!⍎)⍕)⌂traj ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R2wQNZW09DcVHvX2aj3qnaj7qaSopSswCSikYGhsBAA "APL (Dyalog Extended) – Try It Online") `traj` is a function in the dfns workspace that runs a function until a cycle is detected. Here, that function is `#+.(!⍎)⍕`. `⍕` turns the argument into a string. Each character/digit (`¨`) is executed/turned into a number (`⍎`). `!` finds the factorial of each of these digits. Then `+` adds up all these factorials. `#` is used because `#⍎foo` just executes `foo`, so it's `#f.⍎` is practically the same as `{f/⍎¨⍵}` here. # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ 20 bytes Saved 5 bytes thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)! ``` 1↓{⍵,⍨+/!⍎¨⍕⊃⍵}⍣(⊃∊) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wTDR22Tqx/1btV51LtCW1/xUW/foRWPeqc@6moGCtY@6l2sAWJ2dGkClSsYGhsBAA "APL (Dyalog Unicode) – Try It Online") Output is reversed. This is very similar to the code above, but uses the power operator (`⍣`) to run the dfn until a cycle is reached, then drops the first element (`1↓`) because it runs 1 extra time. `{⍵,⍨+/!⍎¨⍕⊃⍵}` applies the function in the question to the first element of the argument (`⊃⍵`), then prepends it to the argument (`⍵,⍨`). Each time it is called, the list grows by one. The train `⊃∊` is applied with the next result on the left side and the previous result on the right side and tells ⍣ when to stop. `∊` is membership and tells which of the next result's elements are in the previous results (if one of them is repeated, there is a cycle). Then it picks the first of these booleans (`⊃`) because we need a single value and the rest have been checked already in previous iterations. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 87 bytes ``` param($r)for(;$r-notin$l){$l+=,$r $r=("$r"|% t*y|%{1.."$_"-ne0-join'*'})-join'+'|iex}$l ``` [Try it online!](https://tio.run/##JcbBCoMwDADQ@75ilEhbXWXqcfgtQ0bEjqyRKOiwfnt22Du9mTeUZUKi8GJB1XmQ4eNA/MjiHiAh8RoTkD@Aqv4GcgHpnQExubiu5TcXR1PXBp4mJLyHN8dkS3v6/yqbI@4nkKo2XfsD "PowerShell Core – Try It Online") Thanks to mazzy for saving a lot of bytes! ## Explained (old implementation, but close enough) ``` param($r)for(;$r-notin$l # Checks that the last computed value isn't an existing one ){$l+=,$r # Adds it to the list $r=("$r"| # Converts r as a string % t*y| # Converts it to a char array %{1.."$_"-ne0-join'*'} # Builds the factorial calculation strings and handles 0!. e.g. 1*2*3*4 )-join'+'|iex} # Joins them with "+" and computes it. e.g. 1*2*3*4+1*2*3 $l # Returns all the values in the list ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=product,sum -n`, 49 bytes ``` say&&($_=sum map{product 1..$_}/./g)until$k{$_}++ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJNTUMl3ra4NFchN7GguqAoP6U0uUTBUE9PJb5WX08/XbM0ryQzRyW7GsjX1v7/39DY6F9@QUlmfl7xf11fn8ziEiurUKAKkBE6UO1ACVM9A0OD/7p5AA "Perl 5 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 72 bytes ``` Most@NestWhileList[Total[IntegerDigits@#!]&,#,DuplicateFreeQ@*List,All]& ``` [Try it online!](https://tio.run/##FctBCsIwEAXQs0ihizKLegAhQhEEKyqCi5DFINN0YJqW5Hv@qPv3FsYsC0PfXKdDHdcCd5WC16wmFy3wzxVs/pwgUfKgUVFcswstNTR8NvtFyCmL3F3393Q0C20defO3rAmum@jBKYrvad@HUL8 "Wolfram Language (Mathematica) – Try It Online") Keeps applying `sumFac` to it's own output until it sees a duplicate value, then returns a list of all values excluding that final duplicate. [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` │¼µ\Ä▬Éε╩X ``` [Run and debug it](https://staxlang.xyz/#p=b3ace65c8e1690eeca58&i=132) [Answer] # [Perl 5](https://www.perl.org/) `-n`, 65 bytes ``` say,(map{$f=1;map{$f*=$_}2..$_;$.+=$f}/./g),$_=$.until$.=$r{$_}++ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJHIzexoFolzdbQGsLQslWJrzXS01OJt1bR07ZVSavV19NP19RRibdV0SvNK8nMUdGzVSmqBqrS1v7/39DY6F9@QUlmfl7xf11fUz0DQ4P/unkA "Perl 5 – Try It Online") Uses `map` as regular loops (ignoring return value), and `$.` as a temporary variable (to save space before `until`). ]
[Question] [ # `cat` goes "Meow" We are all familiar with the concept of a `cat` program. The user types something in, it is echoed back to the user. Easy. But all `cat` programs I've seen so far have missed one fact: a `cat` goes "Meow". So your task is to write a program that copies all `STDIN` to `STDOUT` **UNLESS** the input is `cat`, in which case your program should output `cat goes "Meow"`. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your score is your byte count, with a few modifiers: * If your program works for any additional animals other than `cat` (e.g. `cow: cow goes "Moo"`), for each additional animal: -10 * If your program doesn't use the word "cat": -15 * If your program responds to `fox` with "What does the fox say": -25 ### Animals and sounds that go together: `cow goes moo` `duck goes quack` `sheep goes baa` `bees go buzz` `frogs go croak` Anything else on [this list](https://en.wikipedia.org/wiki/List_of_animal_sounds) is allowed. ## Rules * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * You must not write anything to `STDERR` * You can use single quotes/no quotes instead of double quotes. ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` 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=62500;var OVERRIDE_USER=46470;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Pyth, 231-255 = -24 bytes ### -24\*10 extra animals, -15 for no "cat" string ``` pzI}zJv.Z"xÚ]Arà E¯âñMOÛ|° Ø¢mÞ½`&ÉR¯'_ãPÍm1;ñÝ|,F ¹×z#½öÂ÷ÜAPúõMh#Ì©UOC *CÑ°k%¹ö´qÌzj,å<&{jàRFÖ(¥s ñ`GÂ:çkô#ù\M+üqíéaw ÑuW6Lã,¶w/'87ö×_r]¢:jkz»ÚFÙ¦ÈcÅËØíëûÖOa¿Þµ´6 ø¡ãEþþ:"jk(" goes "N@JzN ``` [Link to code](https://pyth.herokuapp.com/?code=pzI%7DzJv.Z%22x%C3%9A%5D%C2%90Ar%C3%83+%0CE%C2%AF%C3%A2%C3%B1%C2%86MO%C2%90%C3%9B%7C%C2%B0%0A%0C%C3%98%C2%A2%12m%16%C2%9D%C3%9E%C2%BD%60%26%C2%89%C3%89R%C2%8F%C2%AF%27%C2%89_%C3%A3P%C3%8Dm1%3B%C3%B1%C3%9D%7C%2CF%09%C2%B9%C3%97%16%C2%92z%C2%9D%23%1F%C2%BD%C3%B6%C3%82%C3%B7%C3%9CA%C2%80P%07%C3%BA%C3%B5Mh%11%23%C3%8C%C2%A9%C2%83%10UOC+*C%C2%81%C3%91%C2%B0k%25%C2%B9%C3%B6%C2%B4q%C3%8Czj%2C%C3%A5%3C%26%7B%C2%81j%C3%A0RF%C3%96%C2%85%28%C2%A5s%09%C3%B1%60G%C3%82%3A%C3%A7k%C3%B4%23%C3%B9%5CM%2B%C3%BC%C2%9Cq%C3%AD%C3%A9%C2%94a%1Cw+%C3%91uW%17%1D6L%C3%A3%2C%C2%B6w%2F%27%C2%948%C2%8B7%C3%B6%C3%97_r%12%5D%C2%A2%3A%C2%89jkz%C2%BB%C3%9AF%C3%99%C2%A6%C2%8C%16%C3%88c%C3%85%07%C3%8B%C3%98%C3%AD%C3%AB%C3%BB%C3%96Oa%C2%BF%C3%9E%C2%96%C2%B5%C2%9D%C2%82%C2%B46+%C3%B8%C2%A1%C3%A3E%C3%BE%C3%BE%01%C2%8E%07%C2%89%3A%22jk%28%22+goes+%22N%40JzN&input=cat&debug=0) Pseudocode ``` Auto assign z to input print z J = decompress animal-sound dict if z in J: print " goes ", J[z], '"' ``` Animals it knows: ``` {'hare': 'squeak', 'seal': 'bark', 'lion': 'growl', 'rook': 'hiss', 'sheep': 'baa', 'hamster': 'squeak', 'moose': 'bellow', 'grasshopper': 'chirp', 'rhinoceros': 'bellow', 'cat': 'meow', 'tiger': 'growl', 'stag': 'bellow', 'crow': 'caw', 'okapi': 'bellow', 'snake': 'hiss', 'cicada': 'chirp', 'badger': 'growl', 'dog': 'bark', 'cricket': 'chirp', 'tapir': 'squeak', 'bird': 'chirp', 'sparrow': 'chirp', 'lamb': 'baa', "frog": "croak", "raven": "croak"} ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 29 - 15 = 14 bytes Doesn't use string `cat`. ``` xr(/^c\at$/,'$& goes "Meow"') ``` "What does the fox say" (length = 21) is longer than the bonus is worth. [Answer] # PXLCODE, 114 bytes I SHOULD GET BONUS BECAUSE THIS IS CAT LANGUAGE RIGHT? ALSO FEED ME BUTTER ``` HAI 1.3 I HAS A V GIMMEH V BOTH SAEM V AN "cat",O RLY? YA RLY,VISIBLE "cat goes meow" NO WAI,VISIBLE V OIC KTHXBYE ``` [Answer] # APOL, 34 bytes `p(¿(=(i "cat") "cat goes meow" ⋔))` BEEP BOOP I AM NOT A ROBOT [Answer] # CJam, 12 bytes ``` q_:)"dbu"=" goes \"Meow\""* ``` The program is **27 bytes** bytes long and doesn't use the word `cat` (**-15 bytes**). Try it inline in the [CJam interpreter](http://cjam.aditsu.net/#code=q_%3A)%22dbu%22%3D%22%20goes%20%5C%22Meow%5C%22%22*&input=cat). ### How it works ``` q_ e# Read all input and push a copy. :) e# Increment all code points of the copy. "dbu"= e# Push 1/0 if the result is/isn't "dbu". " goes \"Meow\""* e# Repeat the string that many times. ``` [Answer] # JavaScript, 45 - 15 = 30 / 264 - 235 = 29 ``` alert((s=(d='MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/))[d.indexOf(i=prompt())-23])?i+' goes "'+s+'"':i) ``` **Downside: you have to write the name of the animal with the first letter in uppercase and the rest in lowercase. Look below for another version which fixes this.** This version escapes the `a` in cat with `\x61` and includes code for the 22 extra animals from this list (all the allowed animals which had short enough words to be worth it): > > bee buzz 7 > > bird song 8 > > cattle moo 9 > > cow moo 6 > > crow caw 7 > > dog bark 7 > > duck quack 9 > > frog croak 9 > > horse hiss 9 > > hog oink 7 > > lamb baa 7 > > lark sing 8 > > lion roar 8 > > ox low 5 > > pigeon coo 9 > > rook caw 7 > > seal bark 8 > > sheep baa 8 > > snake hiss 9 > > swan cry 7 > > tiger roar 9 > > whale sing 9 > > > (thanks to my friend for helping me with the tedious task of making this list) Ungolfed code: ``` data = 'MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/); input = prompt(); index = data.indexOf(input); sound = data[index-23]; result = sound ? input + ' goes "' + sound + '"' : input; alert(result); ``` --- ## First version, 45 bytes - 15 bonus = 30 ``` alert((i=prompt())=='\x63at'?i+' goes "Meow"':i) ``` Yes, I know. I went from 30 to 29 with ALL that extra work. It was fun! ## Version that allows full lowercase input, 294 bytes - 235 bonus = 59 ``` alert((s=(d='MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/))[d.indexOf((i=prompt())[0].toUpperCase()+i.slice(1))-23])?i+' goes "'+s+'"':i) ``` I also tried removing casing from the data array with `.join().toLowerCase().split(',')` but it ended up taking 297 characters instead. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 28 - 15 = 13 bytes ``` {⍵,' goes "Meow"'/⍨⍵≡⌽'tac'} ``` Input followed by `goes "Meow"` if input is equivalent to `tac` reversed. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///Pzmx5FHbhOpHvVt11BXS81OLFZR8U/PLldT1H/WuAIo@6lz4qGeveklisnotWLWCukdqTk6@jkJ4flFOiqI6F1gMSKgDAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous function  `⌽'tac'` reverse the string (to get the -15 bonus by avoiding the characters `cat`)  `⍵≡` Boolean for whether the argument is identical to that  `' goes "Meow"'/⍨` use that to filter the string (i.e. returns empty string if false)  `⍵,` append to the argument [Answer] # [Stack](https://github.com/StackLanguge/stack-language), 51 bytes ``` '' input dup 'cat' = { 'cat goes "meow"' } if print ``` [Answer] ## JavaScript, ~~81 - 20 - 15 = 46 bytes~~ 50 - 15 = 35 bytes ``` (o=prompt()=="ca"+"t")&&o+=' goes "Meow"';alert(o) ``` [Answer] # Python 3, ~~81~~ ~~70~~ ~~55~~ 46 - 15 = 31 bytes Thanks to Stewie Griffin for saving 15 bytes Thanks to grc for saving 8 bytes. Not using the string `cat` gives -15 bytes. ``` y=input() print(y+' goes "Meow"'*(y=="ca""t")) ``` [Answer] ## [LOLCODE](https://esolangs.org/wiki/LOLCODE), 100 109 Bytes ``` HAI 1 I HAS A I GIMMEH I BOTH SAEM I "cat",O RLY? YA RLY,VISIBLE "cat goes Meow" NO WAI,VISIBLE I OIC KTHXBYE ``` [Try it out online](https://tio.run/##PYoxCgIxFAX7f4pH6m08gfxI8D/cGDCLmlLWYLOQQsHjx9XCagZmlrbM7V57NyU2QphmKCh7xhhsFZ8mQ9YQQbj59nJDwmksWyn65XBmph/Dr@HR6hOxtreTY8JF@c@UxJ0cJrv6Enpf5w8) My first post on this platform, as well as my first code-golf challenge and my first code in LOLCODE, so there's probably lots to improve. I tried avoiding the "cat" with casting the equivalent hex-code `":(63):(61):(74)"` instead, but it didn't work out for me. If you know a solution to this, please let me know! \*+9 Bytes because I didn't read the instructions clear enough [Answer] ## Pyke, 391 -595 = -204 bytes -58\*10 extra animals, -15 for no "cat" string ``` "goes"Q.dt𛧷偮晪ꅢὐ𑈶ὥ𑈶墵𑈶셞𑈶𸣌᳙ᄷ쟿䁔𔣩𕕄漲𔵸ᬰ䵙ꄨ塋튖𴏵თ᠞鮔૪爟㍅爟⼱]꣟勒〥鴞᫠⬻䋥ュ⣹𓫌邦𴽩㺓𒀽𓫌堚퀦잓號漲ქ︆𐊷䦙ᔯ漲ᠥ쏔っ鮔𐩁牔鶇Ƒ䂝雥𐻳⬻⯎偮燩巺𑳦䯥𒀽봽鮔튖➒゗ᨼ𓫌䄇𓫌嚕𓫌㮷鮏𐓧ᘽ挳ᖘ𯃮漲𑙌𒀽睴윿꒲⬻𦼎鼤㨂ᘽdc2cY@]3J ``` [Try it here!](http://pyke.catbus.co.uk/?code=%22goes%22Q.dt%F0%9B%A7%B7%E5%81%AE%E6%99%AA%EA%85%A2%E1%BD%90%F0%91%88%B6%E1%BD%A5%F0%91%88%B6%E5%A2%B5%F0%91%88%B6%EC%85%9E%F0%91%88%B6%F0%B8%A3%8C%E1%B3%99%E1%84%B7%EC%9F%BF%E4%81%94%F0%94%A3%A9%F0%95%95%84%E6%BC%B2%F0%94%B5%B8%EE%AF%87%E1%AC%B0%E4%B5%99%EA%84%A8%EE%AF%87%E5%A1%8B%ED%8A%96%F0%B4%8F%B5%E1%83%97%E1%A0%9E%E9%AE%94%E0%AB%AA%E7%88%9F%E3%8D%85%E7%88%9F%E2%BC%B1%5D%EA%A3%9F%E5%8B%92%E3%80%A5%E9%B4%9E%E1%AB%A0%E2%AC%BB%E4%8B%A5%E3%83%A5%E2%A3%B9%F0%93%AB%8C%E9%82%A6%F0%B4%BD%A9%E3%BA%93%F0%92%80%BD%EE%91%8E%F0%93%AB%8C%E5%A0%9A%ED%80%A6%EC%9E%93%EE%AF%87%E8%99%9F%E6%BC%B2%E1%83%A5%EF%B8%86%F0%90%8A%B7%E4%A6%99%E1%94%AF%E6%BC%B2%E1%A0%A5%EC%8F%94%E3%81%A3%E9%AE%94%F0%90%A9%81%E7%89%94%E9%B6%87%C6%91%E4%82%9D%E9%9B%A5%F0%90%BB%B3%E2%AC%BB%E2%AF%8E%E5%81%AE%E7%87%A9%E5%B7%BA%EE%A9%9B%F0%91%B3%A6%E4%AF%A5%F0%92%80%BD%EB%B4%BD%E9%AE%94%EE%BF%A0%ED%8A%96%E2%9E%92%E3%82%97%E1%A8%BC%F0%93%AB%8C%E4%84%87%F0%93%AB%8C%E5%9A%95%F0%93%AB%8C%E3%AE%B7%E9%AE%8F%F0%90%93%A7%E1%98%BD%E6%8C%B3%E1%96%98%F0%AF%83%AE%E6%BC%B2%F0%91%99%8C%F0%92%80%BD%E7%9D%B4%EC%9C%BF%EA%92%B2%E2%AC%BB%F0%A6%BC%8E%E9%BC%A4%E3%A8%82%E1%98%BDdc2cY%40%5D3J&input=hamsters) Uses dictionary-based compression to store the words. Pyke is older than the question. Animals it knows: ``` {'seals': 'bark', 'turkeys': 'gobble', 'mosquitos': 'whine', 'curlews': 'pipe', 'dogs': 'howl', 'sheep': 'bleat', 'elephants': 'trumpet', 'eagles': 'scream', 'raccoons': 'trill', 'goats': 'bleat', 'donkeys': 'bray', 'monkey': 'whoop', 'snakes': 'hiss', 'wolves': 'howl', 'grasshoppers': 'chirp', 'ferrets': 'dook', 'geese': 'honk', 'ducks': 'quack', 'chinchillas': 'squeak', 'oxen': 'low', 'pigs': 'snort', 'lions': 'snarl', 'antelopes': 'snort', 'crows': 'caw', 'hamsters': 'squeak', 'ravens': 'croak', 'leopards': 'snarl', 'tapirs': 'squeak', 'lambs': 'bleat', 'horses': 'neigh', 'jaguars': 'snarl', 'crickets': 'chirp', 'moose': 'bellow', 'cattle': 'moo', 'deer': 'bellow', 'rooks': 'caw', 'dolphins': 'click', 'whales': 'sing', 'owls': 'hoot', 'walruses': 'groan', 'cicadas': 'chirp', 'tigers': 'snarl', 'chickens': 'cluck', 'giraffes': 'bleat', 'mice': 'squeak', 'peacocks': 'scream', 'songbirds': 'sing', 'geckos': 'croak', 'frogs': 'croak', 'pigeons': 'coo', 'swans': 'cry', 'bitterns': 'boom', 'rhinoceros': 'bellow', 'cats': 'purr', 'badgers': 'growl', 'magpies': 'chatter', 'vultures': 'scream', 'elk': 'bleat'} ``` [Answer] # GNU sed, 37 - 15 = 22 bytes ``` sed -r 's/^(\x63at)$/\1 goes "Meow"/' ``` [Answer] # MATLAB, 58 - 15 = 43 bytes Pretty straight forward, with bonus for not using `cat` in the code: ``` x=input('');if isequal(x,'dbu'-1);x=[x ' goes "Meow"'];end;x ``` Input must be given inside single quotes: `' '`. [Answer] ## Javascript, 117 bytes ``` for(c=0,s="bee.Buzz.bird.Song.c\at.Meow.cow.Moo.crow.Caw.dog.Bark.oxen.Low.owl.Who.rook.Caw.sheep.Baa.swan.Cry".split('.'),p=prompt(),a=![];c<s.length;c+=2){if(p==s[c])a=c}if(!a)alert(p=='fox'?'What does the fox say':p);else alert(s[a]+' goes "'+s[a+1]+'"') ``` I definitely haven't won here, but I've covered a lot of extra animals. ## Javascript, 31 bytes ``` p=prompt();alert(p=='c\at'?p+' goes "Meow"':p) ``` [Answer] # [HALT](https://esolangs.org/wiki/HALT), 71 - 15 = 56 bytes ``` 1 IF "cat" 2 ELSE 3 2 TYPE "MEOW";HALT 3 SET 0;NEXT 4 INCREMENT;STORE 0 ``` HALT is a language I (@Downgoat) made designed for string processing, the only problem is that it's a bit long ## Formatted ``` 1 IF "cat" 2 ELSE 3 2 TYPE "MEOW"; HALT 3 SET 0 ; GOTO 6 4 INCREMENT ; STORE 0 ``` [Answer] # C++11, 316 - 11\*10 - 15 = 191 bytes ``` #include <map> #define t(a,b){#a,#b}, using s=std::string;int main(){std::map<s,s>m{t(cow,moo)t(crow,caw)t(dog,bark)t(hog,oink)t(lark,sing)t(lion,roar)t(oxen,low)t(rook,caw)t(seal,bark)t(sheep,baa)t(swan,cry){"c""at","meow"}};s l;while(int i=~getchar())l+=~i;printf("%s",(m[l]==""?l:l+" goes \""+m[l]+'"').c_str());} ``` Compiles well with VisualStudio. GCC wants me to `#include <string>` and `#include <cstdio>`. It would be shorter if I wouldn't go for bonuses, but I still hope author revises bonuses. I can't think of language where defining `cow -> moo` or so is way way shorter than 10bytes. Mine cost `3+key+value` bytes for additional animal and flat `22+17` bytes for defining structure and so. Ungolfed ``` #include <map> #define t(a, b) { #a, #b }, using s = std::string; int main() { std::map<s, s> m{ t(cow,moo) t(crow,caw) t(dog,bark) t(hog,oink) t(lark,sing) t(lion,roar) t(oxen,low) t(rook,caw) t(seal,bark) t(sheep,baa) t(swan,cry) { "c""at", "meow" } }; s l; while (int i = ~getchar()) l += ~i; printf("%s", (m[l] == "" ? l : l + " goes " + m[l]).c_str()); } ``` [Answer] # Python, ~~62~~ ~~58~~ 48 - 15 = ~~48~~ ~~44~~ 33 bytes Thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) for -10 bytes! ``` x=input() print(x,*['goes "Meow"'][:"c""at"==x]) ``` 0x61 = a. ## Try it online! Revision 3: [with cat](https://tio.run/##K6gsycjPM7YoKPpfYauUnFii9F@5wjYzr6C0REOTq6AoM69Eo0JHK1o9PT@1WEHJNzW/XEk9NtpKKVlJCajY1rYiVvP/f2MA) [without cat](https://tio.run/##K6gsycjPM7YoKPpfYauUkp@u9F@5wjYzr6C0REOTq6AoM69Eo0JHK1o9PT@1WEHJNzW/XEk9NtpKKVlJKbFEyda2Ilbz/39jAA) Revision 2: [with cat](https://tio.run/##K6gsycjPM7YoKPpfYauUnFii9F@5wjYzr6C0REOTKzNNocIWKBxTYWZYomRVUJSZV6JRoaOenp9arKDkm5pfrqSuyZWaU5wKk9P8/98YAA) [without cat](https://tio.run/##K6gsycjPM7YoKPpfYauUkp@u9F@5wjYzr6C0REOTKzNNocLWVik5psLMsETJqqAoM69Eo0JHPT0/tVhByTc1v1xJXZMrNac4FSan@f@/MQA) Revision 1: [with cat](https://tio.run/##K6gsycjPM7YoKPpfYauUnFii9F@5wjYzr6C0REOTKzNNocIWKBxTYWZYomRVUJSZV6KhDuEqpOenFiso@abmlyupa3Kl5hSnQhVUaP7/bwwA) [without cat](https://tio.run/##K6gsycjPM7YoKPpfYauUkp@u9F@5wjYzr6C0REOTKzNNocLWVik5psLMsETJqqAoM69EQx3CVUjPTy1WUPJNzS9XUtfkSs0pToUqqND8/98YAA) [Answer] # JavaScript, 48 - 15 = 33 bytes Uses `\x61` as a substitute for the `a` in `cat`. ``` i=prompt();alert(i=="c\x61t"?i+' goes "Meow"':i) ``` [Answer] ## Perl, 46 - 15 = 31 ``` $_=join'',<>;s/(?<=^ca)t$/t goes "Meow"/;print ``` [Answer] # Ruby, ~~49~~ ~~46~~ 50 - 15 = 35 bytes Pretty straight-forward I guess. Not using cat. ``` $<.map{|l|puts l==?c+'at '??c+'at goes "Meow"':l} ``` Edit: Thanks for @w0lf for saving 3 bytes! [Answer] # PHP, 1204 - (10 \* 64) - 15 - 20 = 529 bytes ``` <?php $i = $argv[1];$s = json_decode(gzuncompress(hex2bin("78da555351b2db200cbc8a27dfee057a1b192bc018104f40dcbccebb7b25d9499d8fcc588b10abddcddf1b64e4e8a04c3bd1eac86db7df3774e136dfa0744c5451805688bb400bac1e5900cfb42703ba1e3bc6e3ce82dabe8cef6f2d22af52b910b95ad93b72d173a22c8083f4d0f63bc75c131aa2e332d2ae45886e43ed7769082f438afc52027df46b20182af457b83c24537ad2c199484b99f6fe669dd9afcd6cc70ef67972a03bb8c10915abb12aa995bc7206deac48555818a9e80ea46cf8142020fe0aa0ccd761327e0db00e046f745426d0c531610d22af609d47aea8dade91d998ad447aebcef6aef0b32d7d64b8df4ddd84a0173c436b816a35475efbf8110bc254a3bf6a1420b76e7d1788f1a346ceb14f8e61b98c0bc44ddb0a46afe284582b55ea9087e1af2004236b3999278a452726c8cb8bef3c2d0086b14ad362f1f3b4032fe67b8aa59cae88742744aab26ccff3f47a2583af11ad0f344c0a1119910553b2d864929562270577b14a87d10635ea351a3e0895572ffd11f0f8ac0867fadf36898668249c65a732448e387de481c1c96931272598863c8ed09ec6b17020874c5792ac1e5bea8ee234c7c238df1a42faff449360552b55c05660d3d5426c4dcb0a7c26f874ac75f0d7a7da0e079da7145d74f848418fc71f5a75d652947a4e1edd469715fae023e29e96c3b0c748027e847a87c4ef4cc893820438722f666bc9a6cb69facf3f28e87499")));echo array_key_exists($i,$s)?"$i goes {$s->$i}":($i=="fox"?"What does the $i say":$i); ``` I use a json encoded gz compressed array of animal sounds. This means it works with all 65 allowed animals, but my script is huge. Also works with fox and doesn't have the word cat in it. [Answer] ## MATLAB, 46 bytes ``` regexprep(input(''),'^cat$','cat goes "Meow"') ``` Admittedly trivial. The input must be given in single quotes. [Answer] # [Beam](http://esolangs.org/wiki/Beam), ~~208~~ 206 - 15 = 191 bytes Not a competitive entry, but a bit of fun to do. It checks the first for letters of the input against `cat`. If it gets a mismatch it will shortcut to the standard cat program. If it matches it will append `goes "Meow"` ``` '''''''''>`\/n@>`)'''>`++\ /++++++++++/r /SP''+(++++/ \+)'PSrn@--S/ \rn@`>`)rn'''''>`++++++)++@P'p++++@'p-----@`p++@'p-@``p@++@'''''>`+++++++++)--@'p++@'p-----@++++++++@``p++@H /@< (`< < `< ''< >ruH ``` [Answer] ## Java = 222 bytes (compressed) ``` public class A {public static void main(String[] args) {Scanner a=new Scanner(System.in);for(;;){String b=a.nextLine();if(!b.equalsIgnoreCase("cat"))System.out.println(b);else {System.out.println("meow");System.exit(0);}}} ``` Or I could decompress it. ## Batch = 52 bytes ``` set /p k= if "k"=="cat" (echo cat) ELSE (echo %k%) ``` [Answer] # Javascript: 48 Characters, 48 Bytes ``` function(s){return (s=="cat")?"cat goes meow":s} ``` ### Test `=>`"Dog" `<=`"Dog" `=>`"cat" `<=`"cat goes meow" [Answer] # Haskell, 52-15 = 37 bytes ``` c"\99at"="\99at goes \"Meow\"" c s=s main=interact c ``` Using `\99` as a substitute for c in “cat” so as to get the 15 bytes bonus. [Answer] # Prolog, 48 bytes ``` p:-read(X),write(X),X=cat,write(' goes "Meow"'). ``` Attempts to bring more animals to the party made the program longer even with bonuses. [Answer] # [O](https://github.com/phase/o), ~~22~~ ~~16~~ 14 bytes **29 bytes - 15** ``` Q"tac"`J=J" goes \"Meow\""+Q? ``` It's long and can be golfed more [Answer] # [𝔼𝕊𝕄𝕚𝕟](https://github.com/molarmanful/ESMin), 23 - 15 = 8 chars / 58 - 15 = 43 bytes ``` ïċɘ㴃탵ˠⓀ㐀攁退胦ްおр夁䰰ᷗȿ 쨀# ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=cat&code=%C3%AF%C4%8B%C9%98%E3%B4%83%ED%83%B5%CB%A0%E2%93%80%E3%90%80%E6%94%81%E9%80%80%E8%83%A6%DE%B0%E3%81%8A%D1%80%E5%A4%81%E4%B0%B0%E1%B7%97%00%C8%BF%E2%80%80%EF%88%85%EC%A8%80%23)` The byte to char ratio is real. ]
[Question] [ ## Introduction: A 3x3x3 Rubik's Cube has \$43,252,003,274,489,856,000\$ possible permutations, which is approximately 43 [quintillion](https://en.wikipedia.org/wiki/Names_of_large_numbers). You may have heard about this number before, but how is it actually calculated? A 3x3x3 Rubik's Cube has six sides, each with nine stickers. Looking at the (external) pieces instead of stickers however, we have six center pieces; eight corners pieces; and twelve edge pieces. Since the centers can't be moved, we can ignore those in the calculations. As for the corners and edges: * There are \$8!\$ (\$40,320\$) ways to arrange the eight corners. Each corner has three possible orientations, although only seven (of the eight) can be oriented independently; the orientation of the eighth/final corner depends on the preceding seven, given \$3^7\$ (\$2,187\$) possibilities. * There are \$\frac{12!}{2}\$ (\$239,500,800\$) ways to arrange the twelve edges. The halve from \$12!\$ is because edges must always be in an [even permutation](https://en.wikipedia.org/wiki/Parity_of_a_permutation) exactly when the corners are. Eleven edges can be flipped independently, with the flip of the twelfth/final edge depending on the preceding eleven, given \$2^{11}\$ (\$2,048\$) possibilities. Putting this together, we have the following formula: $$8!×3^7×\frac{12!}{2}×2^{11} = 43,252,003,274,489,856,000$$ [Source: Wikipedia - Rubik's Cube Permutations](https://en.wikipedia.org/wiki/Rubik%27s_Cube#Permutations) Although this may already look pretty complex, it's still rather straight-forward for a 3x3x3 Cube. For even cubes the formula is slightly different; this is the formula for a 4x4x4 Cube for example: $$\frac{8!×3^7×24!^2}{24^7} = 7,401,196,841,564,901,869,874,093,974,498,574,336,000,000,000$$ Which is approximately 7.40 [quattuordecillion on the short scale](https://en.wikipedia.org/wiki/Names_of_large_numbers). And for larger NxNxN Cubes (i.e. the current World Record 33x33x33) the formula will be extended quite a bit. To not make this introduction too long however, I put these links here instead, where the permutations of the 4x4x4 Cube and some other sized NxNxN Cubes are explained with a resulting formula: * [2x2x2](https://en.wikipedia.org/wiki/Pocket_Cube#Permutations) * [4x4x4](https://en.wikipedia.org/wiki/Rubik%27s_Revenge#Permutations) * [5x5x5](https://en.wikipedia.org/wiki/Professor%27s_Cube#Permutations) * [6x6x6](https://en.wikipedia.org/wiki/V-Cube_6#Permutations) * [7x7x7](https://en.wikipedia.org/wiki/V-Cube_7#Permutations) * [33x33x33](http://twistypuzzles.com/forum/viewtopic.php?f=15&t=32641&start=42) You may be wondering by now: is there a general formula based on \$N\$ for any \$N\$x\$N\$x\$N\$ Cube? There certainly is. Here are three completely different algorithms, all giving the exact same results based on \$N\$: 1: Chris Hardwick's Formula: $$\frac{(24×2^{10}×12!)^{N\pmod2}×(7!×3^6)×(24!)^{\lfloor{\frac{1}{4}×(N^2-2×N)}\rfloor}}{(4!)^{6×\lfloor{\frac{1}{4}×(N-2)^2}\rfloor}}$$ [Try it on WolframAlpha.](https://www.wolframalpha.com/input/?i=for+n+%3D+3,+((24*2%5E10*12!)%5EMod%5Bn,+2%5D+7!3%5E6+24!%5EFloor%5B(n%5E2+-+2+n)%2F4%5D)%2F4!%5E(6+Floor%5B(n+-+2)%5E2%2F4%5D)) 2: Christopher Mowla's trig Formula: $$8!×3^7×\left(\frac{24!}{(4!)^6}\right)^{\frac{1}{4}×((N-1)×(N-3)+\cos^2(\frac{N×\pi}{2}))}×(24!)^{\frac{1}{2}×(N-2-\sin^2(\frac{N×\pi}{2}))}×(12!×2^{10})^{\sin^2(\frac{N×\pi}{2})}×\frac{1}{24^{\cos^2(\frac{N×\pi}{2})}}$$ [Try it on WolframAlpha.](https://www.wolframalpha.com/input/?i=for+n%3D3,+8!*3%5E7*((24!)%2F(4!)%5E6)%5E(1%2F4*((n-1)*(n-3)%2Bcos%5E2((n*pi)%2F2)))*(24!)%5E(1%2F2*(n-2-sin%5E2((n*pi)%2F2)))*(12!*2%5E10)%5E(sin%5E2((n*pi)%2F2))*1%2F24%5E(cos%5E2((n*pi)%2F2))) 3: Christopher Mowla's primes Formula: $$2^{\frac{1}{2}×(2×N×(N+7)-17-11×(-1)^N)}×3^{N×(N+1)+2}×5^{\frac{1}{2}×(2×N×(N-2)+1+(-1)^N)}×7^{\frac{1}{8}×(6×N×(N-2)+3+5×(-1)^N)}×11^{\frac{1}{4}×(2×N×(N-2)-1+(-1)^N)}×96577^{\frac{1}{8}×(2×N×(N-2)-3+3×(-1)^N)}$$ where \$96577\$ is \$(13×17×19×23)\$. [Try it on WolframAlpha.](https://www.wolframalpha.com/input/?i=for+n%3D3,+2%5E((2n(n%2B7)-17-11(-1)%5En)%2F2)3%5E(n(n%2B1)%2B2)5%5E((2n(n-2)%2B1%2B(-1)%5En)%2F2)7%5E((6n(n-2)%2B3%2B5(-1)%5En)%2F8)11%5E((2n(n-2)-1%2B(-1)%5En)%2F4)96577%5E((2n(n-2)-3%2B3(-1)%5En)%2F8)) [Source: Cubers-reddit - Mathematical Counting Formulas of Number of Positions, God's Number, etc.](https://www.reddit.com/r/Cubers/comments/43xzov/mathematical_counting_formulas_for_number_of/) ## Challenge: Choose and implement one of these three formulas (or your own derivative), which given an input-integer \$N\$ in the range \$[2,100]\$, outputs the correct result. ## Challenge rules: * You are free to use another formula besides these three, but keep in mind that these three are proven to be correct. If you use another formula, please add a link of where you got it from (or if you come up with it yourself add an in-depth explanation). And I will check for all integers in the range if the output is correct. Perhaps inspiration could be found in [the oeis for this sequence: A075152](http://oeis.org/A075152). * If your language automatically outputs a scientific output (i.e. \$1.401...×10^{45}\$ instead of the number after the 4x4x4 formula) this is allowed. But please add additional code to your answer to convert this scientific rounding to an exact output so the results can be verified, since rounding errors due to floating point precision during the execution of the formula in your code is not allowed - the actual result should be exact. * Your program/function should be correct for at least the inputs in the range \$[2,100]\$ (although, since \$N=100\$ already results in a huge-ass number, any larger \$N\$ will probably work as well if you're able to output this one correctly). * You are not allowed to loop over all possible permutations with a counter, since that would never output anything in a reasonable amount of time. Only the implementation of a formula (either one of the three provided, a derivative of one of those, or a completely new formula), or another method that will give the correct results in a reasonable amount of time (without hard-coding of course) is allowed. I thought about adding a [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'") to enforce this, but I'm personally against [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'") in combination with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so I won't. Still, please make sure your program gives the answers, and if it's too slow for TIO for some reason, add some screenshots with the output from your local machine as verification. ## 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: Here the test cases for \$N\$ in the range \$[2,10]\$ (feel free to use the WolframAlpha links above for larger test cases): ``` n=2 3674160 n=3 43252003274489856000 n=4 7401196841564901869874093974498574336000000000 n=5 282870942277741856536180333107150328293127731985672134721536000000000000000 n=6 157152858401024063281013959519483771508510790313968742344694684829502629887168573442107637760000000000000000000000000 n=7 19500551183731307835329126754019748794904992692043434567152132912323232706135469180065278712755853360682328551719137311299993600000000000000000000000000000000000 n=8 35173780923109452777509592367006557398539936328978098352427605879843998663990903628634874024098344287402504043608416113016679717941937308041012307368528117622006727311360000000000000000000000000000000000000000000000000 n=9 14170392390542612915246393916889970752732946384514830589276833655387444667609821068034079045039617216635075219765012566330942990302517903971787699783519265329288048603083134861573075573092224082416866010882486829056000000000000000000000000000000000000000000000000000000000000000 n=10 82983598512782362708769381780036344745129162094677382883567691311764021348095163778336143207042993152056079271030423741110902768732457008486832096777758106509177169197894747758859723340177608764906985646389382047319811227549112086753524742719830990076805422479380054016000000000000000000000000000000000000000000000000000000000000000000000000000000000 ``` *NOTE: Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, it basically boils down to: implement one of these three formulas (or a derivative / your own method that still produces the correct results) as short as possible.* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes ``` f@n_:=(s=24^6)(24!/s)^(m=n-2)f@m f@2=7!3^6 f@3=4!12!2^10f@2 ``` [Try it online!](https://tio.run/##DchBCoAgEEDRfafInUJhjlIQDHiEaBsZElktdJHef3Lzefzoy3NFX97TEwWbjhl5RjBuFBwMk1k4HjH1IIKNTbCAE9NurNJomAIGTg110/K9qbTStqFm9em@NujUsBP9 "Wolfram Language (Mathematica) – Try It Online") uses Herbert Kociemba's algorithm found in [OEIS page](http://oeis.org/A075152) here is the recursive formula: `a(1)=1; a(2)=7!*3^6; a(3)=8!*3^7*12!*2^10; a(n)=a(n-2)*24^6*(24!/24^6)^(n-2)` *6 bytes saved by @Peter Taylor* *one more byte saved by @Expired Data* [Answer] # x86 machine code, 119 bytes Hexdump: ``` 60 c6 02 02 33 db be 25 01 10 00 f6 c1 01 74 05 be 26 2a b2 36 33 ed 51 b1 06 33 ff 53 8a 04 1a f6 e1 03 c7 b5 0a f6 f5 88 64 1a 02 66 98 8b f8 4b 79 ea 5b 43 43 f6 f5 66 89 02 84 c0 75 0c 60 8b fa 8d 72 01 8b cb f3 a4 61 4b 41 d1 ee 72 ca 75 f9 be 1d d4 0d 10 4d 79 be 59 49 49 8b e9 be 06 02 02 22 83 f9 02 73 ae c6 44 1a 01 00 80 0c 1a 30 4b 79 f9 61 c3 ``` The function receives the number `n` in `ecx`, and a pointer to a string to fill in `edx` (i.e. `fastcall` convention). Before I show the source code, some explanations on how it does the thing. It uses the recursive formula, which I wrote in the following way: ``` init = 2 m1 = 24^6 = 6*8*9*16*24*32*36 m2 = 24!/24^6 = 6*7*9*10*11*17*19*21*22*23*25*26*35 num(2) = init * 6*7*9*12*15*27 num(3) = init * 6*8*9*12*16*18*20*24*27*28*30*32*33*35*36 num(n+2) = num(n) * m1 * m2^n ``` So all the code should do is multiplication by small numbers. The numbers are in the range 6...36, which is small enough to be represented in a 32-bit bitmap. I actually don't store the bit which represents multiplication by 6 - this lets me arrange the code in a `do-while` loop, starting with unconditional multiplication by 6. The big numbers are represented using decimal form - each byte is a value in the range 0...9, starting from the MSB. The multiplication is performed from LSB to MSB; it assumes that the number of digits will grow by 2 for each multiplication. After doing multiplication by a small factor like 6, the number of digits may grow by only 1. So if MSB = 0, it moves the whole intermediate result left. It can actually happen that the number of digits doesn't grow at all, and then MSB will still be 0, but this problem will fix itself as the code proceeds to greater factors. Because the multiplication code is large, I don't want to put it twice. I don't want to move it to a function either, because the machine code for calling a function is large. So I rearranged the outer loops in such a way that the multiplying code is needed only once. C code: ``` void num(int n, char* x) { *x = 2; int len = 1; int exp_i; uint32_t m32_1; int m1; int carry; int temp; int str_i; bool cf; if (n % 2 == 0) { m32_1 = 0x100125; // 6*7*9*12*15*27 } else { m32_1 = 0x36b22a26; // 6*8*9*12*16*18*20*24*27*28*30*32*33*35*36 } exp_i = 0; while (true) { for (; exp_i >= 0; --exp_i) { m1 = 6; cf = true; do_mult: carry = 0; for (str_i = len - 1; str_i >= 0; --str_i) { temp = x[str_i] * m1 + carry; x[str_i + 2] = temp % 10; carry = temp / 10; } len += 2; x[1] = carry % 10; carry /= 10; x[0] = carry; if (carry == 0) { --len; for (str_i = 0; str_i < len; ++str_i) x[str_i] = x[str_i + 1]; } shift_m1: ++m1; cf = m32_1 & 1; m32_1 >>= 1; if (cf) goto do_mult; if (m32_1) goto shift_m1; m32_1 = 0x100dd41d; // 24!/24^6 = 6*7*9*10*11*17*19*21*22*23*25*26*35 } --n; --n; exp_i = n; if (n < 2) break; m32_1 = 0x22020206; // 24^6 } x[len] = 0; for (str_i = len - 1; str_i >= 0; --str_i) { x[str_i] += '0'; } } ``` Disassembly: ``` 60 pushad; C6 02 02 mov byte ptr [edx], 2; // edx = x 33 DB xor ebx, ebx; // ebx = len - 1 BE 25 01 10 00 mov esi, 0x100125; // esi = m32_1 F6 C1 01 test cl, 1; 74 05 jz skip1; BE 26 2A B2 36 mov esi, 0x36b22a26; // esi = m32_1 skip1: 33 ED xor ebp, ebp; // ebp = exp_i loop_n: 51 push ecx; loop_exp_i: B1 06 mov cl, 6; // cl = m1 do_mult: 33 FF xor edi, edi; // edi = carry 53 push ebx; // ebx = str_i loop_str_i: 8A 04 1A mov al, [edx + ebx]; F6 E1 mul cl; 03 C7 add eax, edi; B5 0A mov ch, 10; F6 F5 div ch; 88 64 1A 02 mov [edx + ebx + 2], ah; 66 98 cbw; 8B F8 mov edi, eax; 4B dec ebx; 79 EA jns loop_str_i; 5B pop ebx; // ebx = len - 1 43 inc ebx; 43 inc ebx; F6 F5 div ch; 66 89 02 mov [edx], ax; 84 C0 test al, al; 75 0C jnz skip2; 60 pushad; 8B FA mov edi, edx; 8D 72 01 lea esi, [edx + 1]; 8B CB mov ecx, ebx; F3 A4 rep movsb; 61 popad; 4B dec ebx; skip2: shift_m1: 41 inc ecx; D1 EE shr esi, 1; 72 CA jc do_mult; 75 F9 jnz shift_m1; BE 1D D4 0D 10 mov esi, 0x100dd41d; 4D dec ebp; 79 BE jns loop_exp_i; 59 pop ecx; // ecx = n 49 dec ecx; 49 dec ecx; 8B E9 mov ebp, ecx; BE 06 02 02 22 mov esi, 0x22020206; 83 F9 02 cmp ecx, 2; 73 AE jae loop_n; C6 44 1A 01 00 mov byte ptr [edx + ebx + 1], 0; loop_to_ascii: 80 0C 1A 30 or byte ptr [edx + ebx], '0'; 4B dec ebx; dec ebx 79 F9 jns loop_to_ascii; 61 popad; C3 ret; ``` The running time for n = 100 is about 4 seconds, and the result is a number with 38416 digits: 23491019577617 (many digits here) ... (many zeros here) 0000000000000000 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes Initial attempt. Uses *Chris Hardwick's Formula*. Will attempt to golf further and explain when I have time. ``` 24©To12!PIÉm7!729®!InI·-4÷mP®IÍn4÷6*m÷ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fyOTQypB8QyPFAM/DnbnmiuZGlofWKXrmeR7armtyeHtuwKF1nod784BMM63cw9v//zc0AAA "05AB1E – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~83~~ 76 bytes ``` n->^(24576*~12,n%2)*3^6*~7(~24)^((m=n-2)n÷4)/24^(m^2÷4*6) ~n=prod(big,1:n) ``` [Try it online!](https://tio.run/##HYxBCoJAFED3nkKC4H8ZzZkmBUEX7TpDNGCm8kO/Mlq08lodoIPZ1Fu9t3n3R0elfK1NvnJYGFD6kCbBIpXgrcJgb1yksCiNBqDPOVTIn7fGndIGeqOcBwl6C@ejHW5wpVbIjHGd6nm0dUUTDQwy/oNeX45AYTFa4rljILHxN6Ia@FnbGY7UnngWfvO7AKFD@GeVyTiKIuEeF1y/ "Julia 1.0 – Try It Online") Uses Chris Hardwick's Formula. Takes input as Big integer. Thanks to H.PWiz for -7 bytes [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` lambda n:3674160*61600**(n%2)*24**(~-n/2*6)*0xb88d4641131f0**(n*(n-2)/4) ``` [Try it online!](https://tio.run/##HYpBCsIwEADP@oq9CNnF0uw2bEvBn3hJqdGCbkvoQS9@PQZhGOYw22d/rCYlXa7lGV/THMHGTvvA6kmrPJGzkyBJqPVtrBVSJP@ehmEOGpg7Tv@p0gi2AUtaMxgsBjna/ebkDMw4Hg9bXmyH5AzLDw "Python 2 – Try It Online") Saved 4 bytes by copying `n*(n-2)/4` from [Neil](https://codegolf.stackexchange.com/a/183422/20260). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes Using Chris Hardwick's Formula. ``` (12!24576)^Mod[#,2]7!729(24!)^⌊#(#-2)/4⌋/24^(6⌊(#-2)^2/4⌋)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/Bfw9BI0cjE1NxMM843PyVaWcco1lzR3MhSw8hEUTPuUU@XsoayrpGmvsmjnm59I5M4DTOgGFgozggsqKn23yU/OqAoM68kOk9B104hLTovNlZHoTpPR8FIR8HQoDb2PwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 81 bytes Herbert Kociemba's recursive formula. Takes a BigInt as input. ``` f=n=>[1n,3674160n,322252536375n<<27n][--n]||f(--n)*0xb640000n*0xb88d4641131f0n**n ``` [Try it online!](https://tio.run/##FcpNCoMwFATgvad4CxeJ1pI/o6DpRUTQqikt8lK0lIJ69jTOZj6GefXffh2W5/uToRsn761Bc2s4XqQuFNcsQAiRi1xqWeRY16LAtskybPfdktA0Yb@7ViwET5blqLTiXHIbhgS9dQtBMCCwAoTaAGen0pTCFgEMDlc3T9fZPUjXk3jDg4Z3vFmC9OhoFR3@Dw "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), ~~102 98~~ 96 bytes Chris Hardwick's formula. Takes a BigInt as input. ``` n=>(n&1n?1403325n<<25n:4n)*918540n*0x83629343d3dcd1c00000n**(n*n-n-n>>2n)/24n**(6n*(n*n/4n-~-n)) ``` [Try it online!](https://tio.run/##HYrbCoJAAETf/Yp9kNhdMfemaLr2K8qqUchsaEQg9uumzcBwOMyjfbezm@7PVwzf9dtgN9ia4iRxlUZorVJU1T4XA8YLmadGgItPrjNVaKM73blOOnEEnFNwxHvrWoElyhwqw18nBvE3BmPb4CcKYolCSUAqS6Q4KIoYWQJCnMfsx/48@httWhouWNn@DpeBgq0NK4N1@wE "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~77~~ ~~75~~ 73 bytes ``` n=>0xb88d4641131f0n**(n*(n-2n)/4n)*13824n**n*851558400n**(n%2n)*315n>>14n ``` [Try it online!](https://tio.run/##JcrRCoIwGMXxe5/iuzDYJtamWwxsPoumLgo5C40IxGdfi@Bc/Dn8Hv27X4fl/nyVCOMUvYtwrfxcrR31WStVKy8hBENaWYGfNLhQta10eiGsUcZYLf/mkIColUHbKo3ow0IM5KhCQ6CLIyV/VRSctoxoCFjDPB3ncGNdz/INO0863zwD3zveZHv8Ag "JavaScript (Node.js) – Try It Online") Based on Christopher Mowla's formula. Takes a BigInt as input. Test harness shamelessly stolen from @Arnauld. `0xb88d4641131f0n` is `3246670537110000n` in decimal. Explanation: I started with the last prime exponent and simplified it to `n*(n-2n)/4n` (this is integer division, so I don't need the adjustment for odd numbers). I then examined the other primes to see whether their exponents were related to this value (which I shall refer to as `o`), and found that they were after a fashion, if I allowed the use of the parity of `n` (which I shall refer to as `p`). The formulae for the exponents are as follows: ``` 23: o 19: o 17: o 13: o 11: 2o + p 7: 3o + p + 1 5: 4o + 2p + 1 3: 3n + 4o + 3p + 2 2: 9n + 4o + 14p - 14 ``` The powers can then be grouped by exponent so for example `p` is the exponent of `11*7*5**2*3**3*2**14`. [Answer] ## [Racket](https://racket-lang.org/), ~~151~~ 141 bytes -7 bytes thanks to fede s.! ``` (λ(n[e expt])(/(*(e 11771943321600(modulo n 2))3674160(e 620448401733239439360000(floor(/(*(- n 2)n)4))))(e 24(*(floor(/(sqr(- n 2))4))6)))) ``` [Try it online!](https://tio.run/##XY1NDsIgEEb3PQWJm8HEyM8I9izGRWOpaURArIl38w5eCaeNLmR2b773zeTudHFTWfkunFleoIHeDWNwLBV4vyAcHHPPNB05bGENjklprWxRayWNEHCN/cNHFpjiXBuLtCTJKIG4RyEteZrsVpNM@uBjzMulzdIJHDkNVRTS8hffb/krzLmZlcIbSHkMkw8M0pz8sa4YK95VbCq29OED "Racket – Try It Online") The longest answer using Chris Hardwick's Formula :) [Answer] # [Python 2](https://docs.python.org/2/), 122 bytes ``` import math f=math.factorial x=lambda n:(1,f(7)*729,f(8)*3**7*f(12)*1024)[n-1]if n<4else x(n-2)*24**6*(f(24)/24**6)**(n-2) ``` [Try it online!](https://tio.run/##HYtBDsIgEEX3PQXLmYlVocQaY09iXKCWlKQMBFng6bFl9d/Py4u/vARWtTofQ8rCm7x0dtrnaM07h@TM2pVpNf71MYJvIA8WRqSB6LLRtdFIFqRCUkTyjA/u5dNZwXc9r99ZFOB@l3pLCCwojad2kKipGpPjDAUGxPoH "Python 2 – Try It Online") Uses the Herbert Kociemba recursive method. -2 bytes thanks to Herman L [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 38 [bytes](https://github.com/DennisMitchell/jelly/Code-page) I feel like I've missed some golfs, but... ``` 12!×⁽^K*Ḃɓ_2×ṭ¥⁸:4×1,6“ð¥‘!¤*:/ד9Ḟɠ’× ``` A monadic Link implementing Chris Hardwick's Formula. **[Try it online!](https://tio.run/##AU4Asf9qZWxsef//MTIhw5figb1eSyrhuILJk18yw5fhua3CpeKBuDo0w5cxLDbigJzDsMKl4oCYIcKkKjovw5figJw54bieyaDigJnDl////zU "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##AVQAq/9qZWxsef//MTIhw5figb1eSyrhuILJk18yw5fhua3CpeKBuDo0w5cxLDbigJzDsMKl4oCYIcKkKjovw5figJw54bieyaDigJnDl//Dh@KCrP//MzM "Jelly – Try It Online") (`n=[1..33]`). [Answer] ## CJam (47 bytes) ``` qi[1_7m!Z6#*_3*Cm!*2D#*]{2-_j24_m!\6#:P/@#*P*}j ``` [Online demo](http://cjam.aditsu.net/#code=qi%5B1_7m!Z6%23*_3*Cm!*2D%23*%5D%7B2-_j24_m!%5C6%23%3AP%2F%40%23*P*%7Dj&input=10) This implements Herbert Kociemba's recursion from OEIS: $$a(n) = \begin{cases} 1 & \textrm{ if } n \in \{0,1\} \\ 7! \times 3^6 & \textrm{ if } n=2 \\ a(n-1) \times 3\times 12!\times 2^{13} & \textrm{ if } n=3 \\ a(n-2) \times \left(\frac{24!}{24^6}\right)^{n-2} \times 24^6 & \textrm{ if } n>3 \end{cases}$$ using CJam's memoised recursion operator `j`. I've ordered the terms in the MathJax block in the same order as in the code to make the correspondence easy to verify for those who read CJam: any further dissection is not going to shed more light. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes ``` _2²:4×6*@24 ²_Ḥ:4;ḂU “€ð‘!×⁽^K,1*ÇPד9Ḟɠ’:Ñ ``` [Try it online!](https://tio.run/##AVMArP9qZWxsef//XzLCsjo0w5c2KkAyNArCsl/huKQ6NDvhuIJVCuKAnOKCrMOw4oCYIcOX4oG9XkssMSrDh1DDl@KAnDnhuJ7JoOKAmTrDkf///zEwMA "Jelly – Try It Online") [Answer] # [Icon](https://github.com/gtownsend/icon), ~~125~~ 110 bytes ``` procedure f(n) q:=1;every q*:=1 to 24 return 11771943321600^(n%2)*5040*3^6*q^(n*(t:=n-2)/4)/24^(6*(t^2/4)) end ``` [Try it online!](https://tio.run/##TY7BCsIwEETP5iv2IiQBabKNLUbyKwFpV@jBTRtSxa@vKb14m3kwvJmGxNs25zTQuGaCp2QlFh/snd6Uv7DomqEkQCcylTUzWNv39ubaFm1nTJR8RqWvxhndxk4vFWhZfOALqsapBl2UXSURa1OCePzTvR4TSyVOh4x9wN1lDYwJPnkqJPdDx@oH "Icon – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) -lgmp, 279 bytes ``` #include "gmp.h" #define s mpz_init_set_str #define m(X)mpz_##X f(int N,m(t)_){m(t)x;m(init)(x);m(init_set_str)(_,N&1?"3LFbOUwC":"1",62);m(mul_si)(_,_,3674160);m(fac_ui)(x,24);m(pow_ui)(x,x,(N*N-2*N)/4);m(mul)(_,_,x);m(set_si)(x,24);N-=2;m(pow_ui)(x,x,6*N*N/4);m(tdiv_q)(_,_,x);} ``` [Try it online!](https://tio.run/##XZFRa8MgFIXf8yvEsKHBbElaMlgpexjsaWRPg8JWJLNJKkSbGdOGlf71ZWrSPEwQ9ZzzXfHKwoqxYfC5ZHW3KwCsRHO3h56/K0ouC9AC0fxQLrmmbWGmVrMl0AZb0/c3Xom41CAjAmlM8dku/Uogy2HU42l7LYERJdlt/AQXry9fb@@nZ/gIY0jSxAZFV9OW2wgli/RhGaeRlcuc0c7IPUmW9twcTtO5JygLsjAJMny/nCqMuLvY3TmDWbhO/tFpYPCR1Dt@pN8zfBnsq0TOpXteripGANvnCgRmf/zYYnD2gBnW5bLpNFiDXB84cna8xStn2y5poIq2q/Wo2H6ZOJlEk3Nyo0ylEsGb9lNC4rhqbBmKCIijOX8FVKE7JUG08i7DEEe/rKzzqh3C2nzjHw "C (gcc) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 85 bytes ``` {0xAB4DE800000**($_%2)*3674160*([*] 1..24)**($_*($_-2)div 4)/24**(($_-2)**2 div 4*6)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@7/aoMLRycTF1cIABLS0NFTiVY00tYzNzE0MzQy0NKK1YhUM9fSMTDTBciCsa6SZklmmYKKpb2QCFISIaGkZKYBFtcw0a/9bc6XlFykY6ekZGihUc3EWJ1YqKKnEK@jaKVSnKajE1ypx1f4HAA "Perl 6 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~51~~ ~~48~~ 44 bytes -4 bytes thanks to H.PWiz ``` ÷^*6÷4□-2⁰Π4*^÷4-D⁰□⁰Π24*729*Π7^%2⁰*24576Π12 ``` [Try it online!](https://tio.run/##yygtzv7///D2OC2zw9tNHk1bqGv0qHHDuQUmWnFAvq4LkAMUBAsZmWiZG1lqnVtgHqcKUqRlZGJqbnZugaHR////jY0B "Husk – Try It Online") This is Chris Hardwick's Formula. Also, this is my first husk program, so any tips would be well appreciated. [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ ~~85~~ 74 bytes -1 byte saved thanks to H.PWiz -11 bytes saved thanks to Max Yekhlakov ``` a=24^6 r 2=3674160 r 3=r 2*a*61600 r n=r(n-2)*a*div(product[2..24])a^(n-2) ``` [Try it online!](https://tio.run/##HYxBCoMwEEX3nmKWRjAkY4irOUJPIFoGIzRUo6Ta66djd//9B@/Fn/eyrmXjmIAg7BXAxsfjCfWRYzp1VjCg1taYsTChm3yVAanzvbPeyO5IuOHGC96cKNepRSVXiF@p7OGaz7uBblQ8/WUp1vwA "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 92 bytes ``` lambda n:0xab4de800000**(n%2)*3674160*0x83629343d3dcd1c00000**(n*(n-2)/4)/24**((n-2)**2/4*6) ``` [Try it online!](https://tio.run/##PYrBCsIwEETP@hW5CMlSSbJZYi34J17SptWC3ZZQoX59TD04PBgeM8tnfc6Mebjd8ytMbQyCG7OFlmJfmz0Akk@owPkLWW/AbLXzeHXkootdtN3/VTij0qQ0UvGfAaAm8CoPcxL8nsTIIgV@9BIrYa1qjocljbzuWyUGWUrlLw "Python 2 – Try It Online") [Answer] [![enter image description here](https://i.stack.imgur.com/MMRSk.png)](https://i.stack.imgur.com/MMRSk.png) # C++, ~~187 185 180 176 195(there was a bug) 193~~ 175 bytes (with help from ceiling cat) This uses the GMP C++ wrapper (GNU multi-precision library), and the formula used by @J42161217 (<https://codegolf.stackexchange.com/a/183381/55953>). Use `g++ -g rubix.cpp -lgmp -lgmpxx` to compile and link ``` #include <gmpxx.h> #define R return using z=mpz_class;z p(z a,z b){z c=1;while(b--)c*=a;R c;}z r(z n){if(n==2)R 3674160;if(n==3)R z("pX4dIaR7jDk",62);R r(n-2)*p(24,6)*p(z("ErvSErbeq",62),n-2);} ``` ungolfed, with test code ``` #include <gmpxx.h> #include <iostream> mpz_class p(mpz_class a, mpz_class b) // returns a to power of b. Only works for b = positive integer { mpz_class c=1; while(b--) c*=a; return c; } mpz_class r(mpz_class n) // returns the rubix permutations for a cube of size n { if(n==2) return 3674160; // 7!*3^6; if(n==3) return z("pX4dIaR7jDk",62); // 43252003274489856000 = 8!*3^7*12!*2^10 return r(n-2) * p(24,6) * p(z("ErvSErbeq", 62), n-2); // "ErvSErbeq"base 62 = 3246670537110000 = (24!/24^6) } main() { for(int i=2; i<34; i++) std::cout<<i<<'\t'<<r(i) << std::endl; } ``` <https://tio.run/##PZAxb4MwEIV3foWVDrETqBpARMImWZqha7t0iFQZ4xC3xrg2tJERf73UIVXfcE937zvpdEzrqGZsmu6EYrKvOKkbfbncn3dBb4WqgSsa7d6YpNZiBzR0gIYOlGhwgBUb/H0WksMyihBbFRQb3vVGAYZHB4xnFRr@Rqoo4n2SbdNN9pD7Jtk7uNCvafVEn7fvjx@LMItRbqCKYrTSME7D7OoeOpivl4Mp@eeMhFcAj//3AiJa2xlOm13QUKEgCoYAeJ1aA4XqgChiDARJUl/XazRnXrar8py1fUeIIGR57JaE@AUECLllXFUSB2Mw/bCTpLWdIjm/5ua/> [Answer] # TI-BASIC, ~~63~~ 62 [bytes](http://tibasicdev.wikidot.com/one-byte-tokens), (noncompeting) ``` {fPart(.5Ans),1,1,-6}int(4⁻¹{8,4,Ans²-2Ans,(Ans-2)²:prod({9*11!2^15,7!3^6,24!,24}^Ans ``` Expression which takes input as an integer on `Ans`. Implementation of Chris Hardwick's formula. Noncompeting because the hardware it runs on will only store up to 16 decimal places, so the answer will never be 100% accurate. Explanation: ``` {fPart(.5Ans),1,1,-6} # the list {(N (mod 2))/2,1,1,-6} # implicitly multiplied by int(4⁻¹{8,4,Ans²-2Ans,(Ans-2)² # the list {2,1,⌊¼(N²-2N)⌋,⌊¼(N-2)²⌋} : # store this list of the formula's exponents as Ans {9*11!2^15,7!3^6,24!,24} # list of the formula's bases ^Ans # raised to their exponents prod( # multiplied together # implicit print ``` ]
[Question] [ I've recently realized how vim works great for golfing, especially for [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"). Also, according to [meta](https://codegolf.meta.stackexchange.com/a/4817/31716) vim is a perfectly acceptable 'programming language' at least, for the scope of this site, that is. What general tips do you have for golfing in Vim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Vim (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Be aware of the uppercase variants of common commands. This can trivially save one keystroke in a lot of contexts. For example: ``` A = $a C = c$ D = d$ I = ^i S = cc X = dh Y = yy ``` Another one is to use `G` instead of `gg`, but only if you use a count! For example, without a count, `gg` moves to the beginning, and `G` moves to the end. However, with a count, they both move to the line you specify, so `5G` is shorter than but equivalent to `5gg` . Another one, is to use `H` in place of `gg`, but it's important to note that this only works if you can guarantee that any input will not take up more than the default number of rows (I believe this is 24, but it may vary). [Answer] Anytime a command fails, it will make a ding noise, which will cancel the current macro. You can (ab)use this to create a crude form of loop. For example, if you want to repeat the keystrokes `<foobar>` until your buffer has less than 3 lines in it. You can do ``` qq<foobar>3G``@qq ``` which means: ``` qq 'Start recording in register q <foobar> 'Keystrokes 3G 'Go to line 3. If line 3 doesn't exist, this is effectively a "break" statement. `` 'Jump back to previous cursor location @q 'Call macro q q 'Stop recording ``` It's important to note that if you are testing this in a vim session, the `@q` might have unintended side effects, since macros are loaded from `.vim_profile`. You can get around this a couple different ways. Probably the best workaround is to launch vim with ``` vim -i NONE ``` You could also delete your `.viminfo`. If you have already launched vim, you can type ``` qqq ``` at the beginning to zero the macro out. Other conditions you can replace the 3G with are ``` f<char> 'Jump to first occurence of <char>. Also see F, t and T ``` or ``` <number>| 'Go to the <number>'th character on the current line. ``` [Answer] # The alphabet in 10 keystrokes All credit for this technique goes to Lynn, who first used it in [this answer](https://codegolf.stackexchange.com/questions/86986/print-a-tabula-recta/87010#87010). I'm writing it up here for posterity. Use the following ten keystrokes to yank the lowercase alphabet: ``` :h<_␍jjYZZ ``` (Where `␍` is a carriage return, i.e. the Enter key.) ## Explanation `:h<_␍` opens the help section `v_b_<_example` (an example of visual blockwise selection), which happens to contain the text `abcdefghijklmnopqrstuvwyxz`. `jjY` moves down to that line and yanks it, then `ZZ` closes the help window. [Answer] ``` :%s/\n//g ``` is *always* equivalent to ``` :%s/\n// ``` which happens to also be equivalent to ``` :%s/\n ``` surprisingly enough. (In general, without any flags, the last slash in a `:s` expression is never necessary.) [Answer] There are more shortened versions of ex commands that you think. For example, you probably already knew that `:global` can be shortened to `:g`, but did you know that `:nnoremap` is equivalent to `:nn`? It's a good idea to run `:h :foo` on all the ex commands you're using in your answer to see if there's a shorter version. [Answer] Let's say you're in insert mode, and you want to make a single normal mode command. You might write that like this: ``` isome_text<esc><foobar>gisome_more_text ``` Don't do it that way. Instead, use `<C-o>`, which executes a single normal command then immediately returns to insert mode. ``` isome_text<C-o><foobar>some_more_text ``` [Answer] # Golfier movements Frequently if you're working with a block of text (especially in [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenges), you'll need to move to the first or last character in the buffer. `G` and `gg` are pretty good, but there are some annoying things. For example, to get the last character, you need `G$` and `gg` will not necessarily put you on the first column if there's leading whitespace. Here are some nicer movements, although note that they only work if your text doesn't have empty lines in the middle of it: * First character of the buffer: `{` is better than `gg0`. If there are empty lines in the middle of the text, you can also use `go` which brings you to the first character in the buffer no matter what. * Last character of the buffer: `}` is better than `G$` These also work as an argument to an operator, but note that they are character-wise movements, not line-wise movements! [Answer] There are three "change case" operators, ``` gu "Convert to lowercase gU "Convert to uppercase g~ "Toggle case ``` Since these are operators, they take a motion, so to convert the current character to lowercase you would use ``` gul ``` Here's where the fun trick comes in. :) If you want to change the case of a single character or the current line, it's a byte shorter in visual mode. For example `gul` is equivalent to ``` vu ``` And `gu_` (\_ is current line) is equivalent to ``` Vu ``` This trick does *not* work for toggling, because `v?` triggers a backwards search in visual mode, (just like `v/` but moving in the opposite direction) so you need `vg?` instead. However, here's where you can use the `~` operator, to save even more bytes! (Thanks @Doorknob for pointing this out) You can see this trick in action on my [vim answer here](https://codegolf.stackexchange.com/questions/49950/capitalize-first-letter-of-each-word-of-input/83330#83330), and on the equivalent V answer on the and post. [Answer] # Know your registers Yanking or deleting text into a specific register (e.g. `"aY`) to use it later isn't always necessary. Vim has several registers that are automatically populated with the subjects of various commands. Type `:help registers` to see them all, but here's a few of particular note: * Unnamed register: `""` - The last text that was yanked or deleted. * Numbered register `"0` - The last text that was yanked. * Numbered registers `"1`–`"9` - The last text that was deleted unless it was less than one line. Each time `"1` is filled its previous contents are shifted to `"2` and so on. * Small delete register: `"-` - The last text shorter than one line that was deleted. * Last inserted text: `".` In particular, the `"-` and `"1` registers can be useful together, enabling you to delete some text with e.g. `dd` into the `"1` register and delete some other text with `D` into the `"-` (of course, the semantics aren't identical, but often they don't need to be). All of the registers can be a little tough to keep track of, but you can see the contents of all of your registers at any time by typing `:registers`. [Answer] This came up [in chat](http://chat.stackexchange.com/transcript/message/30943486#30943486) earlier, so I thought I might as well post it as a full tip. `<C-a>` and `<C-x>` increment and decrement the next number on the line. This is an extremely useful feature for some simple math, but it also allows for a neat little hack. Let's say you need to jump to the next number. For example, we need to change ``` I need 2 spell better ``` to ``` I need to spell better ``` The obvious way is to jump to the 2, then do: ``` sto "Synonymous with 'clto' ``` Since this is shorter than ``` :s/2/to<cr> ``` There are many different ways to jump to the 2. For example, ``` /2<cr> ww 2w ee 2e 8| f2 ``` As well as many other ways. These are all 2 (or more) keystrokes. However, since `<C-a>` and `<C-x>` not only increment/decrement numbers, but also jump to the next number, we can take a byte off with ``` <C-a>sto ``` [Answer] # Do calculations with the expression register You can do calculations in both normal mode and insert mode. ## Normal mode In normal mode, if you type `@=` your cursor will move to the command line, where you can enter any expression. When you press enter, the result of the expression will be executed as normal mode commands. For example, suppose you want to go to the middle column of the current line. The function call `col('$')` returns the number of columns in the line, so we can accomplish what by typing the following: ``` @=col('$')/2<CR>| ``` When you press enter, the cursor returns to the buffer and vim waits for an operator (like `|`) as though you had just entered a number. Alternatively, you could have entered this: ``` @=col('$')/2.'|' ``` ...but of course that's more bytes. ## Insert mode You can use the expression register in insert mode, too, by pressing `<Ctrl-r>=` instead of `@=`. It works the same in normal mode, except the result of the expression you enter will be executed in insert mode. For example, if you typed `<Ctrl-r>=col('$')<CR>`, the number of columns in the current line would be inserted at the cursor as though you had typed it. For more information on the expression register, type `:help "=`. ## Reusing expressions The last expression you used is stored in the expression register, `"=`. Typing `@=<CR>` in normal mode or `<Ctrl-r>=<CR>` in insert mode will evaluate the expression again, allowing you to use them much like macros. # Do calculations in substitutions You can evaluate expressions when doing regular expression substitutions, too. All you have to do is begin your substitution with `\=`. For example, suppose you wanted to number the lines in this file: ``` foo bar baz ``` The function call `line('.')` returns the current line number, so the job is easy. Entering this: ``` :s/^/\=line('.').' '/g<CR> ``` ...yields the desired result: ``` 1 foo 2 bar 3 baz ``` To use captured groups in such an expression you can use the `submatch()` function, where e.g. `submatch(0)` is equivalent to `\0` in an ordinary substitution, `submatch(1)` is equivalent to `\1`, etc. This eats up a lot of keystrokes, unfortunately. For more information on expression substitution, type `:help sub-replace-expression`. [Answer] # Rotate your loops Rotating loops is a golfing trick in many languages but I've found it to be more frequently useful in vim, largely due to the fact that loops usually [exit by failure](https://codegolf.stackexchange.com/a/74663/101474). This allows you to determine a *subset* of code to be executed on the first and/or last iteration. Thus, when you have code like `<init>qq<loop>@qq@q<finalize>`, try to see if you can rotate the loop in order to overlap with either the init code or the finalize code so that they can be merged. [Here's an example I used in a recent golf](http://golf.shinh.org/reveal.rb?Rotate+letters+FIXED/kops_1614663549&vi). A straightforward 16 byte solution might look like this: ``` x$pqqF xp@qq@qZZ ``` This moves the first character to the end, and then in the loop moves backwards to the previous space character and swaps it with the letter that follows it, once it reaches the first space character. One can check that this algorithm solves the challenge in general. The observation we can make here is that we wrote `p` twice: once just before the loop and once just at the end of it. It turns out we can merge them together like so: ``` x$qqpF x@qq@qZZ ``` Notice how we managed to save a character by only writing `p` once: we rotated the loop by one character and had the first iteration of the loop do us the favor of finishing up the `init` work of pasting the first character at the end of the string. Note that the total execution pattern of this solution is exactly the same as the previous one, since we will still exit the loop on failure of the final `F` command. (Technical NB: there's some added subtleties on the Anarchy Golf server since macro definitions are saved between test cases, and because of this the solution above won't work on the 2nd and 3rd test cases when `q` is already defined. My linked solution is roughly equivalent but loses a bit of generality to get around this.) [Answer] You can directly modify the text of a macro, which can be significantly shorter than a convoluted conditional. For example, let's say you want to paste something *n* times, where *n* is user input. I first tried to do this: ``` qq/[1-9]<enter><c-x>``p@qq@q ``` Explanation: ``` qq #Start Recording /[1-9]<enter> #Search for a number that isn't 0. <c-x> #Decrement that number ``p #jump back to your previous location and paste. @q #Recursive call to macro 'q' q@q #Stop recording, and run the macro ``` This is 18 keystrokes, and a really ugly way to do it. Instead, go to the location of that number, and do this: ``` Ap<esc>"qdd@q ``` Explanation: ``` Ap<esc> #Append a 'p' to the end of the current line. "qdd #Delete the current line into register q @q #Run macro q. ``` This is 9 keystrokes, a huge improvement. ## Edit: Even shorter is to run the macro for your number, and then type your command. For example: ``` "qdd@qp ``` Explanation: ``` "qdd #Delete the current line into register q @q #Run register q p #Paste ``` 7 keytstrokes. ]
[Question] [ Write the shortest program to transform the standard input into [Morse code](http://en.wikipedia.org/wiki/Morse_code). Characters not in the table should be printed as they are. ![International Morse Code](https://i.stack.imgur.com/oD2up.png) [Answer] **C# (213 characters)** I'm sure this wont stand long, but at least I got the technique here first! ``` class P{static void Main(string[] a){foreach(var t in a[0]){var c="";for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ 54 3 2 16 7 8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;System.Console.Write(c+" ");}}} ``` And in readable format: ``` class P { static void Main(string[] a) { foreach(var t in a[0]) { var c=""; for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ 54 3 2 16 7 8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c; System.Console.Write(c+" "); } } } ``` For a brief explanation, the string of characters is a heap in which the left child is a dot and the right child is a dash. To build the letter, you traverse back up and reverse the order. [Answer] ## Golfscript - 74 chars This answer supports only uppercase and digits. The letters are separated by newlines and words are separated by 2 newlines ``` {." ETIANMSURWDKGOHVF L PJBXCYZQ"?)"?/'#! 08<>"@))10%=or 2base(;{!45+}%n}% ``` Analysis ``` { }% as usual works like a map over the array . push a copy of the char onto the stack " ETIAN..." this is a lookup table for the uppercase characters ? like a string.find returns the index of the char in the string or -1 if it is not found (ie it's a digit) ) increment that index so E=>2 T=>3 I=>4 etc. notice that if the char is not an uppercase letter or space this is now 0 (False) "?/'#!..." this is a lookup table for the digits. it will be used in the reverse way to the other lookup table. @ pull that copy we made of the char to the top of the stack ))%10 convert ascii digit to a number by adding 2 and taking mod 10. It's important to do it this way because all the uppercase letters hit this code too, and we need to make sure they fall in the range 0..9 or the next step will fail. = pull the nth char from the string eg "Hello"1= gives "e" or remember if the uppercase lookup fails we have a 0 result, so the digit lookup will be used 2base convert to base 2 so E=>[1 0], T=>[1 1], I=>[1 0 0] etc. (; pop the front of the list and throw it away so E=>[0], T=>[1] {!45+}% negate each bit and add 45, this gives ascii value of . and - n newline separates each word. this could be 32 if you wanted to separate the words with spaces for a cost of 1 stroke ``` **Golfscript - 85 chars** This is shorter than my SO answer due to the relaxed requirements here The input must be uppercase/digits and the punctuation characters ".,?" ``` {." ETIANMSURWDKGOHVF!L!PJBXCYZQ"?)"UsL?/'#! 08<>"@".,?"58,48>+?=or 2base(;{!45+}%n}% ``` Since the punctuation is not even required here, I may shorten the answer even more My answer from SO **Golfscript - 107 chars** newline at the end of the input is not supported, so use something like this `echo -n Hello, Codegolfers| ../golfscript.rb morse.gs` Letters are a special case and converted to lowercase and ordered in their binary positions. Everything else is done by a translation table ``` ' '/{{.32|"!etianmsurwdkgohvf!l!pjbxcyzq"?)"UsL?/'#! 08<>"@".,?0123456789"?=or 2base(;>{'.-'\=}%' '}%}%'/'* ``` [Answer] ### tr + sed (347) ``` tr a-z A-Z | sed 's/0/--O/g;s/1/.-O/g;s/2/.J/g;s/3/..W/g;s/4/.V/g;s/5/.H/g; s/6/-.H/g;s/7/-B/g;s/8/-Z/g;s/9/--G/g;s/X/-U/g;s/V/.U/g;s/U/.A/g; s/Q/-K/g;s/K/-A/g;s/A/.T/g;s/J/.O/g;s/O/-M/g;s/Y/-W/g;s/W/.M/g; s/M/-T/g;s/T/- /g;s/H/.S/g;s/B/-S/g;s/S/.I/g;s/L/.D/g;s/Z/-D/g; s/D/-I/g;s/I/.E/g;s/C/-R/g;s/F/.R/g;s/R/.N/g;s/P/.G/g;s/G/-N/g; s/N/-E/g;s/E/. /g' ``` [Answer] ## Haskell — ~~314~~ ~~292~~ 291 characters ``` import Data.List i=intercalate m=i" ".map(i" ".map(\c->words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."!!(head.findIndices(==c)$['a'..'z']++['0'..'9']))).words ``` --- A more user readable form: ``` tbl :: [String] tbl = words ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----." lookupChar :: Char -> String lookupChar c = tbl !! (fromJust . elemIndex c $ ['a'..'z'] ++ ['0'..'9']) encWord :: String -> String encWord = intercalate " " . map lookupChar encSent :: String -> String encSent = intercalate " " . map encWord . words ``` Sample run: ``` *Main> m "welcome humans" ".-- . .-.. -.-. --- -- . .... ..- -- .- -. ..." ``` There's a single whitespace between two letters, and seven whitespaces between two words. [Answer] ## VB.NET, 233 bytes ``` Module Module1 Sub Main(a$()) For Each c In a(0) Dim i = "ETIANMSURWDKGOHVF L PJBXCYZQ 54 3 2 16 7 8 90".IndexOf(c) If c <> " " And i >= 0 Then Console.Write("{0} ", Morse(i)) Else Console.Write(c) End If Next End Sub Function Morse(i) As String Dim b = Math.Log(i) / Math.Log(2) Return (From m In MorseSeq(If(Double.IsInfinity(b), 0, b)) Order By m.Length)(i) End Function Function MorseSeq(i) As IEnumerable(Of String) Return If(i < 0, {}, From n In ".-" From m In MorseSeq(i - 1).DefaultIfEmpty Select n & m) End Function End Module ``` That last function is evil. **edit** A couple of improvements. ``` Function Morse(i) As String Return (From m In MorseSeq(i) Order By m.Length)(i) End Function Function MorseSeq(i) As IEnumerable(Of String) Return If(i=0,{".","-"},From n In".-"From m In MorseSeq(i>>1) Select n & m) End Function ``` [Answer] **Postscript ~~(310)~~ ~~(462)~~ ~~(414)~~ (319)** including **(46)** for the table. Combined numbers and letters with a ternary encoding. 5 ternary digits fit in a byte! This eliminates those silly difference loops, and special-casing numbers entirely. ASCII85 cuts 1/3 of each table. And simplifying the code (finally!) gets back under 400! ``` errordict/undefined{pop( )dup 0 4 3 roll put print{}}put<</*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def/#{load exec}/P{print}0{}1{(.)P}2{(---)P}/S{( )P}48<~o'u/0b'A;]L7n~>* 65 C 97 C/@{5{dup 3 mod # S 3 idiv}repeat # S S S}>>begin{(%stdin)(r)file read not{exit}if #}loop ``` Sample output ``` Luser Dr00g! . --- . . . . --- . . . . . --- . --- . . . --- . --- --- --- --- --- --- --- --- --- --- --- --- . ! ``` Ungolfed and commented. I'm very proud of this one. I feel it's *elegant,* making the numbers do the work. :) ``` %! %Morse Code Translator (Simplified) %if `load` signals /undefined in /#{load exec}, % pop --load--, % print the char, % leave dummy object for `exec` to find errordict/undefined{pop( )dup 0 4 3 roll put print{}}put << %create int->proc pairs %from initial int and string values /*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def %the alpha map is applied to Upper and Lower case /C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def 65 C 97 C %the number map 48<~o'u/0b'A;]L7n~>* /#{load exec} %execute a number /P{print} 0{} % 0: nop 1{(.)P} % 1: '.' dit 2{(---)P} % 2: '---' dah /S{( )P} % S: space %execute a morse sequence, from the table /@{5{dup 3 mod # S 3 idiv}repeat # S S S} >>begin %read and execute each char from stdin {(%stdin)(r)file read not{exit}if #}loop ``` **The tables (33)+(13)=(46)** Here's how the strings encode the table. Each byte represents a 5-digit ternary number. And the bytes are further encoded in ASCII85 (which postscript can automagically decode). ``` %The Morse Table in Ternary Encoding % 3 ^4 ^3 ^2 ^1 ^0 % 81 27 9 3 1 Dec Hex dc ->ASCII85 % --------------- --- --- --- % A 2 1 6+1 7 7 7 256*41+256*50+256*14+ % B 1 1 1 2 27+ 9+3+2 41 29 d85%n85/d85%n85/d85%n85/d85%n85/n % C 1 2 1 2 27+18+3+2 50 32 2 25 53 35 27 chr(x+33) % D 1 1 2 9+3+2 14 E # : V D < % E 1 1 1 1 % F 1 2 1 1 27+18+3+1 49 31 % G 1 2 2 9+6+2 17 11 0 32 47 15 22 % H 1 1 1 1 27+ 9+3+1 40 28 ! A P 0 7 % I 1 1 3+1 4 4 % J 2 2 2 1 54+18+6+1 79 4F % K 2 1 2 18+3+2 23 17 1 32 60 70 64 % L 1 1 2 1 27+ 9+6+1 43 2B " A ] g a % M 2 2 6+2 8 8 % N 1 2 3+2 5 5 % O 2 2 2 18+6+2 26 1A 2 49 8 11 6 % P 1 2 2 1 27+18+6+1 52 34 # R ) , ' % Q 2 1 2 2 54+ 9+6+2 71 47 % R 1 2 1 9+6+1 16 10 % S 1 1 1 9+3+1 13 D 22 71 30 10 17 % T 2 2 2 2 7 h ? + 2 % U 2 1 1 18+3+1 22 16 % V 2 1 1 1 54+ 9+3+1 67 43 % W 2 2 1 18+6+1 25 19 7 13 14 82 12 % X 2 1 1 2 54+ 9+3+2 68 44 ( . / s - % Y 2 2 1 2 54+18+3+2 77 4D 77 256*44+256*256* % Z 1 1 2 2 27+ 9+6+2 44 2C 24 68 21 [23 36] % 9 e 6 [ 8 E] (omit final 2) % 0 2 2 2 2 2 162+54+18+6+2 242 F2 % 1 2 2 2 2 1 162+54+18+6+1 241 F1 % 2 2 2 2 1 1 162+54+18+3+1 238 EE 78 6 84 14 15 % 3 2 2 1 1 1 162+54+ 9+3+1 229 E5 o ' u / 0 % 4 2 1 1 1 1 162+27+ 9+3+1 202 CA % 5 1 1 1 1 1 81+27+ 9+3+1 121 79 % 6 1 1 1 1 2 81+27+ 9+3+2 122 7A 65 6 32 26 60 % 7 1 1 1 2 2 81+27+ 9+6+2 125 7D b ' A ; ] % 8 1 1 2 2 2 81+27+18+6+2 134 86 134 256*161+256*256* % 9 1 2 2 2 2 81+54+18+6+2 161 A1 43 22 77 [50 40] % L 7 n [ S I] (omit final 2) ``` [Answer] ## Ruby, 161 ``` d=proc{|x|x>1?d[x/2]+".-"[x&1]:' '} $><<$<.gets.bytes.map{|i| e=i>64?"-@B4*:68,?5</.7>E20+193ACD"[(i&95)-65]:i>47?"gWOKIHX`df"[i-48]:nil e ?d[e.ord-40]:i.chr}*'' ``` Encodes each digit into a single char, where 1 is dash, 0 is dot, with a leading 1 as a marker bit (plus an offset to keep it printable. Uses ASCII math to use the input chars as lookup indices. [Answer] # Python 3, 99 Characters ``` lambda a:print(*[str(ord('ӆҼzࢤpࢮ࠿yࡊ oࡀѡÔÞÝࢭÓӅһѢ'[ord(c)%32])).translate(' -.'*18)for c in a]) ``` Works on upper and lowercase. [Answer] **Lisp (532 466 chars)** ``` (loop(princ(let((c(read-char)))(case c(#\a".- ")(#\b"-... ")(#\c"-.-. ")(#\d"-.. ")(#\e". ")(#\f"..-. ")(#\g"--. ")(#\h".... ")(#\i".. ")(#\j".--- ")(#\k"-.- ")(#\l".-.. ")(#\m"-- ")(#\n"-. ")(#\o"--- ")(#\p".--. ")(#\q"--.- ")(#\r".-. ")(#\s"... ")(#\t"- ")(#\u"..- ")(#\v"...- ")(#\w".-- ")(#\x"-..- ")(#\y"-.-- ")(#\z"--.. ")(#\1".---- ")(#\2"..--- ")(#\3"...-- ")(#\4"....- ")(#\5"..... ")(#\6"-.... ")(#\7"--... ")(#\8"---.. ")(#\9"----. ")(#\0"----- ")(t c))))) ``` This encodes lower case letters, and morse code sequences are printed with a trailing space [Answer] **In Java, 475 characters.** ``` import java.io.*;class M{public static void main(String[]b){String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}} ``` Translates a-z, A-Z and 0-9. Edit: Or in **447** characters, if you don't mind Java throwing an error after the translation. ``` import java.io.*;class M{static{String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}} ``` [Answer] Perl6 (238) ``` my%h="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.".split(/<wb>/)[1..72];while$*IN.getc ->$c{print %h{$c.uc}||$c} ``` Readable version ``` # Split string on word breaks to create a hash # I get an extra token at the beginning and end for some reason # [1..72] is a slice without the extra pieces my %h = "A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----." .split(/<wb>/)[1..72]; # For each character in STDIN, print either the looked up value, or itself while $*IN.getc -> $c { print %h{$c.uc} || $c; } ``` [Answer] # sed, 159 bytes ``` s/.*/\L&/ s/[02]/&-/g s/[89]/&./g : s/[b-ilnprsz5-9]/&./g s/[ajkmoqt-y0-4]/&-/g y/abcdefghijklmnopqrstuvwxyz0123456789/edri umsewnrttmwkai isadkgojuvhhbzoo/ t ``` We start by downcasing the entire line (because `y` can't do case-insensitive conversions); subtract 10 bytes if we are to only handle lower-case input. Then we preprocess the digits `0`, `2`, `8` and `9` to emit their final symbols. The loop generates the final symbol for each input character, then translates each character for the next iteration. This is equivalent to walking up the [dichotomic search table](https://en.wikipedia.org/wiki/Morse_code#Alternative_display_of_common_characters_in_International_Morse_code) shown in the Wikipedia article; the digits that needed special treatment can be seen to have parents that are not in our ASCII alphanumerics. The loop terminates when all characters have reached the terminating space (after 'e' or 't'). For example, the letter `k` is transformed in three passes: 1. `k` => `k-` => `n-` 2. `n-` => `n.-` => `t.-` 3. `t.-` => `t-.-` => `-.-` [Answer] ## C, ~~162~~ 160 chars ``` char M[256] = "_^\\XP@ACGO &15)\"4+0$>-2'%/6;*(#,8.9=3", v; main(c) { for (; c = getchar(), v = M[c + 208 & 255] - 32, ~c; putchar(v-1? c : 32)) for (; v > 1; v /= 2) putchar(".-"[v & 1]); } ``` (With non-significant whitespace stripped, no trailing newline) ``` char M[256]="_^\\XP@ACGO &15)\"4+0$>-2'%/6;*(#,8.9=3",v;main(c){for(;c=getchar(),v=M[c+208&255]-32,~c;putchar(v-1?c:32))for(;v>1;v/=2)putchar(".-"[v&1]);} ``` `M` is a lookup table where the characters' bitpatterns correspond to dots and dashes in the morse code. Characters `[0-9A-Z]` are decoded to morse using this table (with a space appended after the morse code), other characters are simply passed through unchanged. Sample run: ``` HELLO WORLD .... . .-.. .-.. --- .-- --- .-. .-.. -.. hello world hello world ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. ``` [Answer] # Powershell, 142 bytes ``` -join($args|% t*y|%{if($_-match'\w'){for($d='ihfbZJKMQY+mazzy+0;?3,>5:.H7<1/9@E42-6B8CG='[$_-48]-42;$d-1){'.-'[$d%2] $d=$d-shr1}' '}else{$_}}) ``` Less golfed test script: ``` $f = { -join( $args|% toCharArray|%{ if($_-match'\w'){ for($d='ihfbZJKMQY+mazzy+0;?3,>5:.H7<1/9@E42-6B8CG='[$_-48]-42;$d-1){ '.-'[$d%2] $d=$d-shr1 } ' ' }else{ $_ } } ) } @( ,("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. ") ,("HELLO WORLD", ".... . .-.. .-.. --- .-- --- .-. .-.. -.. ") ,("#$%^&","#$%^&") ) | % { $s,$expected = $_ $result = &$f $s "$($result-eq$expected): $result" } ``` Output: ``` True: .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. True: .... . .-.. .-.. --- .-- --- .-. .-.. -.. True: #$%^& ``` Note: The output contains trailing spaces. [Answer] # JavaScript (ES6), 184 bytes For both of these versions, they will put spaces between any characters. Converts 0-9 and a-z(case insensitive) are converted. A space is converted to 3. ``` s=>s.split("").map(e=>isNaN(d=parseInt(e.toLowerCase(),36))?e:`_OGCA@PX\\^\r\n `.charCodeAt(d).toString(2).substr(1).split("").map(e=>".-"[e]).join("")).join(" ") ``` Replace `\n` with a newline character(`0x0a`). It is not showing a couple of nonprintable characters because of SE. Going into edit mode shows it. Here is the hex: ``` 73 3d 3e 73 2e 73 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 65 3d 3e 69 73 4e 61 4e 28 64 3d 70 61 72 73 65 49 6e 74 28 65 2e 74 6f 4c 6f 77 65 72 43 61 73 65 28 29 2c 33 36 29 29 3f 65 3a 60 5f 4f 47 43 41 40 50 58 5c 5c 5e 05 18 1a 0c 02 12 0e 10 04 17 5c 72 14 07 06 0f 16 1d 0a 08 03 09 11 0b 19 1b 1c 60 2e 63 68 61 72 43 6f 64 65 41 74 28 64 29 2e 74 6f 53 74 72 69 6e 67 28 32 29 2e 73 75 62 73 74 72 28 31 29 2e 73 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 65 3d 3e 22 2e 2d 22 5b 65 5d 29 2e 6a 6f 69 6e 28 22 22 29 29 2e 6a 6f 69 6e 28 22 20 22 29 ``` ### Ungolfed ``` s=> //declare anonymous function s.split("") //split into array of characters .map( //for each character e=> //declare anonymous function isNaN( //is the character not in range 0-9a-zA-Z d=parseInt(e.toLowerCase(),36) //take it as base 36(digits are 0-9a-z) and assign to d )?e: //if outside range, return as is `_OGCA@PX\\^\r\n ` //table of the morse code as binary as code point with leading 1 .charCodeAt(d)//get the corresponding code .toString(2) //convert to binary, 0=., 1=-, with an extra 1 bit .substr(1) //remove the extra 1 bit .split("") //split into each bit .map( //for each bit e=> //declare anonymous function ".-" //the corresponding symbol for bits [e] //get it ) .join("") //join the bits ) .join(" ") //join the characters with a space between each character ``` ## Readable version, 234 bytes ``` s=>s.split("").map(e=>isNaN(d=parseInt(e.toLowerCase(),36))?e:[95,79,71,67,65,64,80,88,92,94,5,24,26,12,2,18,14,16,4,23,13,20,7,6,15,22,29,10,8,3,9,17,11,25,27,28][d].toString(2).substr(1).split("").map(e=>".-"[e]).join("")).join(" ") ``` ### Ungolfed ``` s=> //declare anonymous function s.split("") //split into array of characters .map( //for each character e=> //declare anonymous function isNaN( //is the character not in range 0-9a-zA-Z d=parseInt(e.toLowerCase(),36) //take it as base 36(digits are 0-9a-z) and assign to d )?e: //if outside range, return as is [95,79,71,67,65,64,80,88,92,94, 5,24,26,12, 2,18,14,16, 4,23, 13,20, 7, 6,15,22,29,10, 8, 3, 9,17,11,25,27,28] //table of the morse code as binary with leading 1 [d] //get the corresponding code .toString(2) //convert to binary, 0=., 1=-, with an extra 1 bit .substr(1) //remove the extra 1 bit .split("") //split into each bit .map( //for each bit e=> //declare anonymous function ".-" //the corresponding symbol for bits [e] //get it ) .join("") //join the bits ) .join(" ") //join the characters with a space between each character ``` [Answer] ## Perl (489 chars) ``` %c=("A"=>".-","B"=>"-...","C"=>"-.-.","D"=>"-..","E"=>".","F"=>"..-.","G"=>"--.","H"=>"....","I"=>"..","J"=>".---","K"=>"-.-","L"=>".-..","M"=>"--","N"=>"-.","O"=>"---","P"=>".--.","Q"=>"--.-","R"=>".-.","S"=>"...","T"=>"-","U"=>"..-","V"=>"...-","W"=>".--","X"=>"-..-","Y"=>"-.--","Z"=>"--..",1=>".----",2=>"..---",3=>"...--",4=>"..---",5=>".....",6=>"-....",7=>"--...",8=>"---..",9=>"----.",0=>"-----");while(<>){foreach(split(//)){if(exists($c{$_})){printf"%s ",$c{$_}}else{print"$_"}}} ``` Can be executed via command line like so. ``` $ perl -e '$CODE' < textfile ``` Edit: Thanks @tobyodavies for pointing out that my original solution had the translation backwards! [Answer] ## PHP, 474 characters ``` <?$a=strtoupper(fgets(STDIN));$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])]; ``` Its 462 characters if all input is in uppercase: ``` <?$a=fgets(STDIN);$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])]; ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 81 bytes (Non-competing) ``` Çvy©58‹i®58-•6V%·,Õo•2B5ôsè}®64›i®64-•4…·]ÑUZ“×\ó$9™¹“ÌLÈÎ%´•3B4ôsè}"012"".- "‡}) ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4vazy0EpTi0cNOzMPrTO10H3UsMgsTPXQdp3DU/OBbCMn08Nbig@vqD20zszkUcOuTBANUgTkLDu0PfbwxNCoRw1zDk@PObxZxfJRy6JDO0HcHp/DHYf7VA9tAao0djKBGKFkYGikpKSnq6D0qGFhreb//76OfqYA "05AB1E – TIO Nexus") Convert letter patterns to base-3, number patterns to base-2, use zero indexed ascii transliteration to get to periods and hyphens. Does not work on lowercase. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 50 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¤⁵©ḤọḌṄ’B‘s5;“ḄẇɗÞI/QẊṂjỵr’Œ?ḃ2¤ṖṖƊ⁺ị⁾.-; ØBiịÇ)K ``` A full program accepting a Python formatted string as a command line argument which prints space delimited output. **[Try it online!](https://tio.run/##FY6/SgNBEMZ7n2JMJxhFwcYUQjoRC2ux2NxNkkn2duPuRL3uooFA1MZCI4hVGh8gcH/AIkHBx9h7kXMPBmaG@X7fNwOUMq6qMvlYL8vJav3l0qUrnl365LJpmby3y2Rhj1r@7tKpy2d/b5vP0/0Ll89ddj9wxcp40c/LiUsfDtdLl736@p2Xk9wVj@Xke6/Z2tos2uS3zWznrKqqxuXB1TGca2MRAh0ikAUBEXJfh6C7wEYoGxEzqR4w3jGQ6moTCSatQNRii4bQ1mKtmrrrGa3Q7oKkXp991wYCScHQAvcFQyAUdBBCMhiwjGGsQjSWtc/rxLXdkKTE0OOWUaGped3xITd@viX/2JjBjjAgIQGvxzSKUPF24x8 "Jelly – Try It Online")** [Answer] # APL(NARS), 71 chars, 142 bytes ``` {36≥y←⍵⍳⍨⎕A,⎕D:'•-'[0∼⍨⌽(5⍴3)⊤y⊃∊(2⍴256)∘⊤¨⎕AV⍳'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠']⋄⍵} ``` test: ``` q←{36≥y←⍵⍳⍨⎕A,⎕D:'•-'[0∼⍨⌽(5⍴3)⊤y⊃∊(2⍴256)∘⊤¨⎕AV⍳'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠']⋄⍵} q¨'0123456789' ----- •---- ••--- •••-- ••••- ••••• -•••• --••• ---•• ----• q¨"HELLO WORLD" •••• • •-•• •-•• --- •-- --- •-• •-•• -•• ``` each letter is separated from one space, each word would be separated from 3 spaces. The table is build on alphanumeric string `⎕A,⎕D` and 16bit characters `'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠'` they split in 8bit characters each converted in base 3 with reversed digits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 52 bytes ``` Ažh«•1Ju&àøΘn₆δβαLmSÂZΘ=+BD1 ÷ΓùwÒмVšh•… .-ÅвJ#ðδJ‡ ``` [Try it online!](https://tio.run/##AWcAmP9vc2FiaWX//0HFvmjCq@KAojFKdSbDoMO4zphu4oKGzrTOss6xTG1Tw4Jazpg9K0JEMQogw7fOk8O5d8OS0LxWxaFo4oCi4oCmIC4tw4XQskojw7DOtErigKH//2hlbGxvIHdvcmxk "05AB1E – Try It Online") ``` •1Ju&àøΘn₆δβαLmSÂZΘ=+BD1 ÷ΓùwÒмVšh• push compressed number … .-ÅвJ# convert to custom base " .-" ðδJ append a space to each morse code Ažh« ‡ transliterate ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 56 bytes ``` ka»ƛ[¬τ*‹∧□C‛Ṡḣ6ƒO⌈=gṫO=D»`-.,`τ⌐Ŀkd5ɾ\.*5ʁṘ-:ƛ‛.-ḂĿ;JĿṄ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYcK7xptbwqzPhCrigLniiKfilqFD4oCb4bmg4bijNsaST+KMiD1n4bmrTz1EwrtgLS4sYM+E4oyQxL9rZDXJvlxcLio1yoHhuZgtOsab4oCbLi3huILEvztKxL/huYQiLCIiLCJoZWxsbyB3b3JsZCAxMjMhISEiXQ==) ``` »...» # Base-256 compressed integer `-.,`τ⌐ # Decompressed with the key `-.,`and split on commas ka Ŀ # Replace letters with those 5ɾ\.* # 1..5 . 5ʁṘ- # With 4..0 - appended :ƛ‛.-ḂĿ;J # Make a copy with `.-` swapped kd Ŀ # Replace digits with those Ṅ # Join on spaces and implicitly output ``` [Answer] # Python 2, ~~283~~ 274 Bytes I created a string of alphanumerics such that their placement in the string describes their Morse code representation. Originally I was going to use binary, but `01` would be the same as `1`. So I used ternary with `- = 1` and `. = 2`. Thus is character `c` is at index `1121` in this string, its Morse code representation is `--.-`. * To save bytes, I created variables for space, dash and dot. * Then I hard coded the 'decoder' string using a couple replace statements to reduce whitespace. * The part of the function converts an index into an array of the ternary digits * The other part function takes an string and converts each character into Morse code with 3 spaces after letters and 7 (4 extra) between words ``` q,d,D=" .-" s=" TE MN AI.OG KD.WR US-.QZ.YC XB- JP L. F VH---.09 8..7-- 6---.1-- 2..3 45".replace(D,d*3).replace(d,q*4) lambda n:''.join(''.join([0,D,d][i]for i in [s.index(c)//3**i%3 for i in range(5)if s.index(c)//3**i!=0][::-1])+q*3 if c!=q else q*4for c in n.upper()) ``` **Test Harness** ``` print(f("Hi")==".... .. ") print(f("Hello")==".... . .-.. .-.. --- ") print(f("Hello World")==".... . .-.. .-.. --- .-- --- .-. .-.. -.. ") print(f("To be or not to be")=="- --- -... . --- .-. -. --- - - --- -... . ") print(f("3 14 15")=="...-- .---- ....- .---- ..... ") ``` **Update** * **-9** [16-05-09] Incorporated the ternary calculating function into the main function **[NOTE:** There is always trailing white space but white space represents a pause, so I guest that is ok **]** [Answer] # PHP, ~~157~~ ~~150~~ 157 bytes ``` for(;$d=ord($c=$argv[1][$i++]);)echo ctype_alnum($c)?strtr(substr(decbin(ord($d>64?".CTRH@ZF\DUGXABEVOJL?K[ISQP"[$d&31]:"]muy{|ld`^"[$c])-48),1),10,".-"):$c; ``` takes input from first command line argument. no pause between letters. Run with `-nr`. **breakdown** ``` for(;$d=ord($c=$argv[1][$i++]);) # loop through input characters echo # print ... ctype_alnum($c) # if char is alphanumeric: ? strtr( substr( decbin( ord($d>64 # 1. map char to char-encoded morse ?".CTRH@ZF\DUGXABEVOJL?K[ISQP"[$d&31] :"]muy{|ld`^"[$c] )-60 # 2. subtract 60 from ordinal value ) # 3. decbin: convert to base 2 ,1) # 4. substr: skip leading `1` ,10,".-") # 5. strtr: translate binary digits to dash/dot :$c; # not alphanumeric: no conversion ``` Beating JavaScript, Python2, C, Ruby and sed. I´m happy. 4th step: un-merged the mapping to handle lowercase characters without using `strtoupper`. **previous versions:** fail for lowercase letters; +12 bytes to fix: Replace `$argv[1]` with `strtoupper($argv[1])`. **simple string translation, 254 bytes** ``` <?=strtr($argv[1],["-----",".----","..---","...--","....-",".....","-....","--...","---..","----.",A=>".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]); ``` straight forward: translates the whole string at once, character to morse code. Save to file to execute or replace `<?=` with `echo` and run with `-r`. **decimal interpretation of morse codes, 184 bytes** (-70) ``` for(;""<$c=$argv[1][$i++];)echo($m=[32,48,56,60,62,63,47,39,35,33,A=>6,23,21,11,3,29,9,31,7,24,10,27,4,5,8,25,18,13,15,2,14,30,12,22,20,19][$c])?strtr(substr(decbin($m),1),10,".-"):$c; ``` first golfing step: morse codes encoded to binary with an additional leading `1` to preserve leading zeroes. Loops through characters and translates them one by one. Run with `-nr`. **decimals encoded to character, 157 bytes** (-27) ``` for(;""<$c=$argv[1][$i++];)echo ctype_alnum($c)?strtr(substr(decbin(ord("@"<$c?"CTRH@ZF\DUGXABEVOJL?K[ISQP"[ord($c)-65]:"]muy{|ld`^"[$c])-60),1),10,".-"):$c; ``` second golfing: added 60 to the decimal value and encoded to character. **merged mapping, 150 bytes** (-7) ``` for(;""<$c=$argv[1][$i++];)echo ctype_alnum($c)?strtr(substr(decbin(ord("]muy{|ld`^8901234CTRH@ZF\DUGXABEVOJL?K[ISQP"[ord($c)-48])-60),1),10,".-"):$c; ``` third golfing: merged mapping for digits and letters to a single string. [Answer] # SmileBASIC, ~~194~~ 190 bytes ``` INPUT S$WHILE""<S$B=INSTR(" ETIANMSURWDKGOHVFLPJBXCYZQ 54 3 2 16 7 8 90",S$[0])+1IF B THEN S=LOG(B,2)FOR I=0TO S-1?"._"[B-(1<<S)AND S>>I||0];:NEXT?" "; ?SHIFT(S$)*!B; WEND ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 143 bytes ``` s=>[...s].map(t=>`?/'#! 08<>      `.charCodeAt(parseInt(t,36)+1).toString(2).slice(1).replace(/./g,e=>'.-'[e])||t).join` ` ``` [Try it online!](https://tio.run/##Dcw7C8IwFEBhfGsVX4hvQXFIgnqrFUTQVsTJ2bEIDTXWSk1KEpz877Xb4RvOm36p8mUY6xUXD5Y87UTZjgsA6g4fGmNtO17mZKL5bLreH51Cf1jLtuvNfM/olIqN7sQo5yqt6mA09sB/UXlJJ2eNYyoVu3KN9XK7I4sNAS1uWoY8wBYBFYU@wylKFkc0TRPMYMlsB8EKuexOfj9N4C1C7k29xBdciYhBJAL8xIhac0TIwUj@ "JavaScript (Node.js) – Try It Online") ]
[Question] [ Given two strings of letters, transfer the capitalization pattern of each string onto the other one. Fewest bytes wins. ``` Input: CodeGolf xxPPCGxx Output: coDEGOlf XxppCgxx ``` * Both strings will be equal-length and nonempty, with only letters `a..z` and `A..Z`. * You may output the two resulting strings in either order relative to the inputs. * You may represent a pair of strings as one string with a non-letter single-character separator for input and/or output. * You may represent a string as a list of characters or one-character strings, but not as a sequence of code point values unless these are simply strings in your language. * Your input and output may represent strings differently. **Test cases:** ``` CodeGolf xxPPCGxx -> coDEGOlf XxppCgxx lower UPPER -> LOWER upper MiXeD lower -> mixed LoWeR A A -> A A ABcd EfGh -> AbCd EFgh ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 66 bytes ``` a->b->{for(int i=a.length,t;i-->0;b[i]^=t)a[i]^=t=(a[i]^b[i])&32;} ``` [Try it online!](https://tio.run/##ZZBda8IwFIbv/RWHgqMdbdDtbl0LzjmvBJkMBqWDGFONq0lJTv1A/O0u/ZgOdxFOzvuevHmSNd3SYL34PotNoTTC2vakRJGT@7DzT8tKyVAoWZksp8bAhAoJxw5AUc5zwcAgRVu2SixgYz13hlrIZZIC1Uvj1aMAb23OM1tRnaT@UElTbrhu@ziGDKIzDeJ5EB8zpV0hEURESc7lElc@hiII4l44T0T6FaFHmxq59aZSvbvHh/B0DuvrLgzIDRqIWgoAZ6gWfKzyDPb76XQ43u8d/9fK1Y5r@JhOR@9XcSI@@SvU1lUcwOBP88IWMMrGK6dWTg1B9YaGomZ4aki8C8iV0NJVHjFFLtB1wPHCdqb5GzvDqhcAJr2UoBpadaA1Pbieb7X@jWYBANqAjNCiyA8usyc9QhnjBdqmn16umB0M8g1RJZLCAmHmOl0DXdOVjg@S71rOJuFGsTFtzqlTrdP5Bw "Java (JDK 10) – Try It Online") ## Explanations ``` a->b->{ // Curried lambda for(int i=a.length,t;i-->0; // Descending loop on i, // Declare t b[i]^=t // Apply the case difference to b[i] ) a[i]^=t=(a[i]^b[i])&32; // Assign the case difference of the two letters to t, and apply it to a[i]. } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~86~~ ~~58~~ ~~55~~ 53 bytes * Saved twenty-eight bytes thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack). * Saved three bytes. * Saved two bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire). ``` c(a,s,e)char*a,*s;{for(;*s++^=e=(*s^*a)&32;)*a++^=e;} ``` [Try it online!](https://tio.run/##TY5da8IwGIWv568IhY0kvt5sVyVzsFXXmw2LMpTOKTGmH6BtaTpWWvrba9L6sRDenDznHBIxCoVoW4E5KJBERDynHKhidZDmmFE1HG7Gcoyp2lBOHp4eGaG8Y6xpC6yggq2CbdU3FdAKqAZ0W7HaILT4tm37B/zuYCrL46QI8AIUuV58qAgTmvmEnZGF9LpXeq8TNHq5yOebXCcWIAWoArQA5APSryL9D9YMjjxOMKkHdwW2nHQv3fQQ6LBVlp7nuGVptEgnU3fW81WZZU6oOWFd55D@ydwYX543nRvxMVv24jfLtHXOfcYrOTH0WjjGpdx3hXQp55fcqyH/x4W/iS48DdyoM3ZOf38Po1vGEL67TU2017Qn "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` O&32^/^OỌ ``` [Try it online!](https://tio.run/##y0rNyan8/99fzdgoTj/O/@Hunv8Pd295uGPTo6Y1h9uBhDcQR/7/75yfkuqen5OmUFEREODsXlHBlZNfnlqkEBoQ4BrE5ZsZkeqiABbhclRw5HJ0Sk5RcE1zzwAA "Jelly – Try It Online") ### How it works ``` O&32^/^OỌ Main link. Argument: [s, t] (pair of strings) O Ordinal; replace each character with its code point. &32 Perform bitwise AND with 32, yielding 32 for lowercase letters, 0 for uppercase ones. ^/ Reduce by XOR, yielding 32 for letter pairs with different capitalizations, 0 for letter pair with matching capitalizations. ^O XOR the result with each of the code points. Ọ Unordinal; replace each code point with its character. ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~13~~ 12 bytes ``` ⊖⊖819⌶¨⍨∊∘⎕a ``` [Try it online!](https://tio.run/##LYu9bsJAEAb7PAXdQkGRLqEzxrhxhIWEoL3Yd8bKoTsZUC5C6SLEnyMoEqVNh@ihoORR9kXMmkPa4tPMLNOyHn8wqZJ6JNl4nEZFIXC@xdUv3dPjM25Olz3me1yscPGH3z@sKCYUzDA/4vI/oykwPzdAvQGuv0CwVAIB0tnnQxXnO3BVzH0lBVTAmDB0fWOgNilNpFqe37mZgdHaTcjYH6neeUa4F4Ze914HnT7tCky1Jme7l3TAW8Rsb7tRanhMLFB93i27/ACOU0o77KfTjMrIE/7w/ue8ujfSToZwBQ "APL (Dyalog Classic) – Try It Online") input and output is a 2×N character matrix `⎕a` is the uppercase English alphabet `'ABC...Z'` `∊∘⎕a` returns a boolean matrix indicating which letters in the input are uppercase `819⌶` converts its right argument to uppercase or lowercase depending on its boolean left argument ("819" is leetspeak for "BIG") `819⌶¨⍨` does that for each (`¨`) character, swapping (`⍨`) the arguments `⊖` means reverse vertically; one `⊖` acts as the left argument to `819⌶` and the other is the final action [Answer] # [Pyth](https://pyth.readthedocs.io), 10 bytes ``` rVV_mmrIk1 ``` [Try it here!](https://pyth.herokuapp.com/?code=rVV_mmrIk1&input=%5B%22CodeGolf%22%2C%22xxPPCGxx%22%5D&debug=0) ### Explanation & neat Pyth tricks used * `rVV_mmrIk1` — Full program. Input is taken from STDIN as a list of two strings, and the output is written to STDOUT as a list of two lists of characters. * `mm` — For each character in each of the strings: + `Ik` — Check if it is invariant under... + `r...1` — ... Converting to uppercase. Yields **True** for uppercase characters and **False** for lowercase ones. * `_` — Reverse that list. * `VV` — And double-vectorize the following function over the two lists: + `r` — Convert to uppercase if the value is `True` (aka `1`), else convert to lowercase. This submission abuses the fact that `r0` and `r1` are the lowercase and uppercase functions in Pyth, and we use truth values (the values obtained by checking if each character is uppercase, reversed) yielding `True` for uppercase and `False` for lowercase. The fact that booleans are subclasses of integers in Python is very handy for the approach this answer is using. Porting Dennis and Jonathan's Jelly approaches both resulted in more than 18 bytes, so I am quite happy with the Pyth-specific tricks used here. [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` kG91<P32*-c ``` [Try it online!](https://tio.run/##y00syfn/P9vd0tAmwNhISzf5//9odef8lFT3/Jw0dWsF9YqKgABn94oK9VgA) Or [verify all test cases](https://tio.run/##y00syflvaqWUGeH1P9vL0tAmwNhISzf5v7qurvr/aHXn/JRU9/ycNHVrBfWKioAAZ/eKCvVYrmj1nPzy1CKQaGhAgGsQWMg3MyLVBSQEkQMJOYK4jhCmU3IKiOea5p6hHgsA). ### Explanation ``` k % Implicit input: 2-row char matrix. Convert to lower-case G % Push input again 91< % Less than 91?, element-wise. Gives 1 for upper-case P % Flip vertically 32* % Multiply by 32, element-wise - % Subtract, element-wise c % Convert to char. Implicit display ``` [Answer] # [Haskell](https://www.haskell.org/), 78 bytes ``` import Data.Char c x|isUpper x=toUpper|1<2=toLower (!)=zipWith c x#y=(y!x,x!y) ``` [Try it online!](https://tio.run/##VYqxCoMwFAD3fMUzdlAohXZuJgsuGVyKc9AUH42@EFP6LP57Grr1poO7yaxP61xKOHsKEW4mmlMzmSAG4B3Xu/c2AKtIP9vP10t2TW8bRFXU6oO@xzjBILjcVLUVfORiq9NscAEFIwnI@IBLhAPIhkbbknvIUjJ3XdMyy/9Dv3SO1JNMXw "Haskell – Try It Online") [Answer] # x86-64 machine code, 14 bytes Callable from C (x86-64 SysV calling convention) with this prototype: ``` void casexchg(char *rdi, char *rsi); // modify both strings in place ``` An explicit-length version with length in `rcx` is the same size. `void casexchg(char *rdi, char *rsi, int dummy, size_t len);` --- This uses the same bit-exchange algo as the C and Java answers: **If both letters are the same case, neither needs to change. If they're opposite case, they both need to change.** Use XOR to diff the case bit of the two strings. `mask = (a XOR b) AND 0x20` is 0 for same or 0x20 for differing. **`a ^= mask; b ^= mask` caseflip both letters iff they were opposite case.** (Because the ASCII letter codes for upper and lower differ only in bit 5.) NASM listing (from `nasm -felf64 -l/dev/stdout`). Use `cut -b 26- <casexchg.lst >casexchg.lst` to turn this back into something you can assemble. ``` addr machine 6 code global casexchg 7 bytes casexchg: 8 .loop: 9 00000000 AC lodsb ; al=[rsi] ; rsi++ 10 00000001 3207 xor al, [rdi] 11 00000003 2420 and al, 0x20 ; 0 if their cases were the same: no flipping needed 12 13 00000005 3007 xor [rdi], al ; caseflip both iff their cases were opposite 14 00000007 3046FF xor [rsi-1], al 15 16 0000000A AE scasb ; cmp al,[rdi] / inc rdi 17 ; AL=0 or 0x20. 18 ; At the terminating 0 in both strings, AL will be 0 so JNE will fall through. 19 ; 0x20 is ASCII space, which isn't allowed, so AL=0x20 won't cause early exit 20 0000000B 75F3 jne .loop 21 ; loop .loop ; caller passes explict length in RCX 22 23 0000000D C3 ret size = 0xe bytes = 14 24 0000000E 0E db $ - casexchg_bitdiff ``` The slow `loop` instruction is also 2 bytes, same as a short `jcc`. `scasb` is still the best way to increment `rdi` with a one-byte instruction. I guess we could `xor al, [rdi]` / `stosb`. That would be the same size but probably faster for the `loop` case (memory src + store is cheaper than memory dst + reload). And would still set ZF appropriately for the implicit-length case! [Try it online! with a \_start that calls it on argv[1], argv[2] and uses sys\_write on the result](https://tio.run/##jVNRa9swEH73r7i3JcQpcTZGSehDCaN0jFK6l0EbjGyfHQ1FEpKaKL8@O8l262TZqB5k63T36bvv7pi1uC3EYSqZ3R6PjVAFE1Ayi77cNHnBXcXrOjk3LJIroZReJEBLqMoW8c8rQzsTKTybiq@jjcmqs838fAbtWsIMeA1ug9zE1yzs0WAwgGVbXIBUUAuuNZcNSMQKq2TwRIRPCbWHCxjBHwrlNgR9AVtprSx3eAJj@TSLQC26Jf8CztYSuCyBXkza0@2PmxlQfMjnqre5yN2h2XLJXGBNGcqWjnWGDDalSNhzIaBAurUKvj98aw01o81tjHptNj1klItbuP25ur8Hq1mJKew3vKT8rPzkiLRQe6zSgBQ4Bf@9Cjcle7UIyIw4AHruIuJviQCxbMmyLZvSneE025KA0YBmNmiHXgteOhAomyCthKfVr1Ytg67vmNw6ZlzSftq22KpddKp4aAerJ9nXdcRnptk9Z@uky5PUIexRZx0PY8GUPoVpNigZUFpko62joCmtt7ItQwTcwLQFhSnMo5tUrseL5wrLt/PHyA6dbO80/zJwmncZCWTR6zo4lX6SrTtdLdthJ@Mkg5rSEYwaJgYFzePnbPCG72Igl11mQnRPXUkjc10NbcXBYez4ial87PqZZy19rZGm9EWG6mpBjQYqDhB1ad/RypzghxpkIXgJef7wlO9NP1n2YLtk@n6Kd6Ms7bVMgwjj5J@S/p/0G@sX@TejDzGY9wyW78rHKRm22UmXDd@Yf778SqzwweYBKW9okvVoNj4eV6rCOyXqo/ePj6s77/8A "Assembly (nasm, x64, Linux) – Try It Online") [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 14 bytes ``` {`c$l+|x-l:_x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qOiFZJUe7pkI3xyq@ovZ/mrqGhpJzfkqqe35OmpK1UkVFQICze0WFkiaXhlJOfnlqEVAwNCDANQgs4psZkeoCFIHIAEV0lByVrEEESNbRKTkFKOma5p6hpKn5HwA "K (oK) – Try It Online") Input/output is a list of two strings. [Answer] # [J](http://jsoftware.com/), 36 31 27 bytes -9 bytes thanks to FrownyFrog! ``` (XOR"$32*[:~:/97>])&.(3&u:) ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F8jwj9IScXYSCvaqs5K39LcLlZTTU/DWK3USvO/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCunN@Sqp7fk6auo6VekVFQICze0WFOkRWXR2uKie/PLUIpCQ0IMA1CFPeNzMi1QUkD1GIIe8IknPEIu6UnAKSck1zz1D/DwA "J – Try It Online") The previous solution was: # [J](http://jsoftware.com/), 36 31 bytes -5 bytes thanks to FrownyFrog! ``` |:@(XOR 32*0~:/@|:97>])&.(3&u:) ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8L/GykEjwj9IwdhIy6DOSt@hxsrS3C5WU01Pw1it1ErzvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagrpzfkqqe35OmrqOnnpFRUCAs3tFhTpEVl0drionvzy1CKQkNCDANQhT3jczItUFJA9RiCHvCJTTAZKYEk7JKSB9rmnuGer/AQ "J – Try It Online") ## How it works: ``` (3&u:) converts the strings to code points ( )&. then do the following and convert back to chars 97>] check if they are uppercase letters 0~:/@|: transpose and check if the two values are different 32* multiply by 32 (32 if different, 0 otherwise) XOR xor the code point values with 32 or 0 |:@ and transpose ``` [Answer] # [R](https://www.r-project.org/), ~~118 94 75~~ 72 bytes ``` m=sapply(scan(,""),utf8ToInt);w=m>96;apply(m-32*(w-w[,2:1]),2,intToUtf8) ``` [Try it online!](https://tio.run/##jY1PC4IwAMXvfooxL1vMQ0Z/xS5W0ikPBUF0WMuFMLeRE@enX4YZHTs8ePAev9/T@UxttulBcHC2WicPaz1/V0tmCiWpAJUS9buC@RTcWpNXns/jLp8HoqSMK6q1aLtaG744qr00mDRxuV7OcL@UwSQcoSZoLiRcja@YhKSQ5qhO3R93MMQQTNQ9T5XgkEBrsyxJrYUYuy@9YlQiAiH@sUS9JfrD4gY@GOjuBQ "R – Try It Online") ~~There must be a much golfier way.~~ -43 bytes thanks to Giuseppe who pointed me to [the MATL solution by Luis Mendo.](https://codegolf.stackexchange.com/a/166014/80010) TIO link contains a function solution for the same byte count. ``` m=sapply(a<-scan(,""),utf8ToInt) # Turns input into a matrix of bytecode (2 columns) w=m>96 # Predicate : which chars are lower? apply(m-32*(w-w[,2:1]),2,intToUtf8) # -32*w turns the string to UPPER # +32*w[,2:1] swaps capitalization # intToUtf8 turns bytecode to strings ``` Bonus: The output is a named vector whose names are the original input strings! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, 4 bytes ``` •??• ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuaEiLCIiLCLigKI/P+KAoiIsIiIsIkNvZGVHb2xmXG54eFBQQ0d4eCJd) Explanation: ``` • # A with the capitalization of B ?? # Get both input strings (order ends up reversed) • # A with the capitalization of B # "ṡ" flag - Print entire stack, separated by spaces ``` [Answer] # [Python 3](https://docs.python.org/3/), 83 bytes ``` lambda a,b:(g(a,b),g(b,a)) g=lambda*a:[chr(ord(x)&95|(y>'Z')<<5)for x,y in zip(*a)] ``` [Try it online!](https://tio.run/##Lc9NC4JAEAbgc/6KPTUzsbfwkGRQJp4CCYLo47C2rgrmyiK0Rv/d3Ow0M88Lw0zbd6VuloMKb0MtnpkUTPAswALHQrzAjAsirwincCGC66M0qI1ES/OV/8F@Axeg9donpQ2zvGdVw95ViwtB98HZuMnZFSHSMk90rYAzsDZNo8RaIM4Qav3KjeNTmsbHyQ7VOd87m8Kfbd28/fe7h3RjrJIS6B54s9ZUTecu5xBugKvfEzR8AQ "Python 3 – Try It Online") -3 bytes thanks to Mr. Xcoder -3 bytes thanks to Chas Brown [Answer] # [Haskell](https://www.haskell.org/), 78 bytes ``` c!d=([c..'z']++[';'..])!!sum[32|(c>'Z')/=(d>'Z')] (#)=zipWith(!) s%t=(s#t,t#s) ``` [Try it online!](https://tio.run/##XcpPC4IwGMfxu69izmQbhkEdY4GZeAokiCLxINvEkf9wi0R67xbrpM/px/P5lrl6iqqaJmZzilPm@2hEmeelaI98PyO2rV51utt@MDugByIbirkZmYUdQkfZ3aQusU0s5WqKlaPX2lFkqnPZAAp4a4Hfdb1sNFgBGLZcxG1VQOACOAxJEsbDAOdN1b5Fb4JrkkSXhZ7lXZyM/ru5BkaC5ffIuIGoiEs4fQE "Haskell – Try It Online") [Answer] # QBasic, 133 bytes ``` INPUT a$,b$ FOR i=1TO LEN(a$) c=ASC(MID$(a$,i,1)) d=ASC(MID$(b$,i,1)) s=32AND(c XOR d) ?CHR$(c XOR s); r$=r$+CHR$(d XOR s) NEXT ? ?r$ ``` Takes the two strings comma-separated and outputs the results newline-separated. Uses the bit-fiddling algorithm from [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/166021/16766). Other than that, the main golf trick here is that the first result string is printed directly, one character at a time, which is a little shorter than saving both result strings in variables and printing them outside the loop. [Answer] # JavaScript, ~~77~~ ~~74~~ 73 bytes ``` W=>W.map((w,x)=>w.map((c,i)=>W[+!x][i][`to${c>{}?'Low':'Upp'}erCase`]())) ``` ``` f= W=>W.map((w,x)=>w.map((c,i)=>W[+!x][i][`to${c>{}?'Low':'Upp'}erCase`]())) console.log( f([[...'CodeGolf'],[...'xxPPCGxx']]) ) ``` Takes an array of char arrays, outputs an array of char arrays. -1 byte ([@Arnauld](https://codegolf.stackexchange.com/questions/166012/exchange-capitalization/166028?noredirect=1#comment401609_166028)): `c>'Z'` → `c>{}` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` =Œu=/ị"Ɱż"Œs$ ``` **[Try it online!](https://tio.run/##ATUAyv9qZWxsef//PcWSdT0v4buLIuKxrsW8IsWScyT/4bu0w4dZ//9Db2RlR29sZgp4eFBQQ0d4eA "Jelly – Try It Online")** Also 13: [`=ŒuṚ×32ạŒlO$Ọ`](https://tio.run/##ATcAyP9qZWxsef//PcWSdeG5msOXMzLhuqHFkmxPJOG7jP/hu7TDh1n//0NvZGVHb2xmCnh4UFBDR3h4 "Jelly – Try It Online") (or `=ŒuṚæ«5ạŒlO$Ọ`) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 75 bytes ``` ^ ¶ +`¶(([A-Z])|(.))(.*)¶(([A-Z])|(.)) $#6*$u$1$#7*$l$1¶$4$#2*$u$5$#3*$l$5¶ ``` [Try it online!](https://tio.run/##K0otycxLNPz/P47r0DYu7YRD2zQ0oh11o2I1azT0NDU19LQ00YS4VJTNtFRKVQxVlM21VHJUDA9tUzFRUTYCiZmqKBuDxEwPbfv/3zk/JdU9PyeNq6IiIMDZvaICAA "Retina – Try It Online") Explanation: The newlines are used as markers to determine how much of the string has been processed. The regex tries to match against uppercase letters or failing that any characters. If an uppercase letter was matched then the other character is uppercased otherwise it is lowercased and vice versa, while the newlines are advanced to the next character. [Answer] # [Python 3](https://docs.python.org/3/), ~~76~~ 75 bytes ``` lambda a,b:''.join(chr(ord(x)&95|ord(y)&32)for x,y in zip(a+' '+b,b+'a'+a)) ``` [Try it online!](https://tio.run/##LY5BC4IwFMfP9Sl28m04OiQdEgzMxFMwgiCoDps6XNgmQ2hG391cdvv9f@/Pe68b@sboaJTJbWz5U1QccSpigNXDKI3LxmJjK@xIsN18PA0kiNZEGoscHZDS6K06zENAEAoqQuAQckJGX5gW@cIVQ2aqujCtBIrAOcaywjkgFGFozau2Xp8Zy0@zO6pLffBuHv5c6nP6531Z@ZjLogFyj5eLzird4@kehWQHVHqcnvgC "Python 3 – Try It Online") Outputs the result as one string with a single-character separator. Thx to [Jonathon Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for 1 byte. [Answer] # [Crystal](https://crystal-lang.org), 108 bytes ``` def f(a,b)r=s="" a.zip(b){|x,y|r+="`"<x<"{"?y.downcase: y.upcase s+="`"<y<"{"?x.downcase: x.upcase} {s,r}end ``` [Try it online!](https://tio.run/##TY9dC4IwGIXv/RUvg2CjsR8QSZSJV4EEQRBBy00SJGVTfJf6282@uzvnOc/NSYyzlcyHQekUUir5mRnf@oR4Utyykp5Z2yF3nZn65ETmOCctWTihiuaaSKtn4ERdPpJnX4Z7Gvhn4NvovdZy0@urGg4ewKShQaF0VOQpIMZxECEy/hryotEGdnEcbj9ok@31Gp7DBy1h@Y2rREGYRpcRHIWWyQVa6ChycKyDsq7seA6FLfOsooSwkf8Kg364Aw "Crystal – Try It Online") ### How it works? ``` def f(a, b) # Strings as list of characters r = s = "" # Strings buffers initialization a.zip(b) do |x, y| # Join two arrays to paired tuples and iterate r+="`"<x<"{"?y.downcase: y.upcase # Check if character is downcase using triple s+="`"<y<"{"?x.downcase: x.upcase # comparison and ascii table. Then apply it to end # the other character using String methods {s, r} # Return two new strings using a tuple end # PS: Tuples are inmutable structures in Crystal ``` [Answer] # [Assembly (nasm, x64, Linux)](http://www.nasm.us/), 25 bytes (123 bytes source) [Hex bytes:](https://defuse.ca/online-x86-assembler.htm) ``` 0x88, 0xE6, 0x30, 0xC6, 0x80, 0xE6, 0x20, 0x88 0xF2, 0x66, 0x31, 0xD0, 0x88, 0x26, 0xAA, 0xAC 0x8A, 0x26, 0x8A, 0x07, 0x08, 0xE4, 0x75, 0xE8, 0xC3 ``` The function entry point is at `a`, with the strings passed in using `RDI` and `RSI`. ``` b:MOV DH,AH XOR DH,AL AND DH,32 MOV DL,DH XOR AX,DX MOV [RSI],AH STOSB LODSB a:MOV AH,[RSI] MOV AL,[RDI] OR AH,AH JNZ b RET ``` [Try it online!](https://tio.run/##dU5PT8MgFL@/T8FdNLaaHXqjsLRdWKnQad3SGJrV07Ymtgf89Ah0VhPjAXjv9xc9jv25O33eXvR4tmpN60KU6G7qzQQZFynhCL2Nk/6YAOY3Abqt0NOLkAwdpKpaHMOGo@Nw6QG24hlJVWBP3ESrdgbYFYgfW6CEc6SvStLgaJFE/7mbH7fapQFwKlCvyof9iVK/2haN/16yKFf30AgZWt35Vtku8QKWY5IH3k8cSMn89BAHO@OYzazLYU3AXF3RepOqhUqBC@ZuHcJIjgMbdIS7hbnFu0PLptyjDuS6ttbS4dhnw@ndGlNVNDPmCw "Assembly (nasm, x64, Linux) – Try It Online") [Answer] # TI-Basic, 225 bytes ``` Prompt Str1,Str2 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ→Str3 "seq(inString(Str3,sub(Ans,I,1),I,1,length(Ans→u Str1 u→F Str2 augment(u,ʟF→S augment(ʟF,Ans→F ". For(I,1,dim(ʟS Ans+sub(Str3,remainder(ʟF(I)-1,26)+1+26(ʟS(I)>26),1 End Disp sub(Ans,2,length(Str1 sub(Ans,2+length(Str2),length(Str2 ``` -1 byte if the `i` is replaced with the imaginary number `i`. +3 bytes by replacing `remainder(ʟF(I)-1,26)` with `26fPart((ʟF(I)-1)/26)` if the calculator does not support `remainder(`. Outputs are displayed, separated by a newline. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` Eθ⭆ι⎇№α§§θ¬κμ↥λ↧λ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUCjUEchuATISwdxMnUUQlKL8hKLKjWc80uBKhJ1FBxLPPNSUis0YDRQg19@iUa2pqaOQi6ICC0oSC1KTixO1cgB8nzyy@E8ELD@/z86Wsk5PyXVPT8nTUlHqaIiIMDZvaJCKTb2v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of two strings. Explanation: ``` θ Input array E Map over strings ι Current string ⭆ Map over characters θ Input array κ Outer loop index ¬ Logical Not § Index into array μ Inner loop index § Index into array α Uppercase characters № Count number of matches λ λ Current character ↥ Uppercase ↧ Lowercase ⎇ Ternary Implicitly print ``` [Answer] ## F#, 120 bytes Bugger. ``` open System let g=Seq.fold2(fun a x y->a+string(x|>if y>'Z'then Char.ToLower else Char.ToUpper))"" let b f s=g f s,g s f ``` [Try it online!](https://tio.run/##NU5Na8JAFLznVwwLYkKrFM8m0BbppYeC9qJ4iOa9TSDubve9VAP972kUchmYYb5YFmcfaRh8IIdtL0qXpCWFzbf0s2TfVquUO4cSN/SLonwSjY2z6e2vaBh9Md/PtR6j73UZlzv/6a8UQa3QpHyHQDHLjHnUnsCQ3N7x2ULAw2G9cRr7L984LY4P06VsxsFof5EnuAu@09Ap8jFuXt/OlYHZ8EdtEoTxjLKDmQlmYpCyTPYMqbhqIglehn8) The function `g` takes the two strings as parameters. `Seq.fold2` applies a function with an accumulator (`a`) to each element (`x` and `y`) in the strings. Initially `a` is an empty string, and it adds the converted character to it in each iteration. `b` is the main function. It first converts `f` with respect to `s`, and then converts `s` with respect to `f`. It then returns a tuple with both values. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 121 bytes ``` [H|T]-[I|U]-[J|V]-[K|W]:-((H>96,I>96;H<92,I<92),J=H,K=I;H>96,J is H-32,K is I+32;J is H+32,K is I-32),T-U-V-W. _-_-[]-[]. ``` [Try it online!](https://tio.run/##Xc1da4MwFMbx@36KUChEeo4XFgat64YvxTcGsmo7cKLQaheQZmghXvjd3dkKbuzmIfn9A/lsZSMv2Ckxjpk/JDlmwZDShsOBNhqO@QY595/WDxDQmP7j2oCARoNw60O0DcyfGDLRMR9XBkTfp2C5Msy7LSejqkGCKR7wqM8KLDCjP3J9VHwPibbBPSZooQ2su7XieilO8lx13AFL@0cu2ESqFbeq5vOFYgv1fp1D5oCba/rsGZnipUNPPdnUJZR9H8eO1/flFBupqpZKGse7119@EW@VS3zPE1tE1p@rfTqT7Grvg3D8Ag "Prolog (SWI) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~74~~ 69 bytes ``` ->a,b{a.zip(b).map{|x|x.one?{|y|y>?_}?x.map(&:swapcase):x}.transpose} ``` [Try it online!](https://tio.run/##LY/RaoMwGEbv@xQhg1GH8wEKqzibedNREUYLIiPGpDqsCYmlvzM@u4tdL79zzs2nr@Uwi7f5dUv9cqTBb6PWpRdcqBotWAhkx8PRDnbYht9TCItYP2/MjSpGDfc2MAW9pp1R0vBpznMcy4onshXYxwBpGicAuPDRE5M7khxagU6gVHwGWOW4lTeuXfiVpiS7V/vDkWToqhTXzn82J75z/r9b/KUBXqG9PPLM@ci56M4jFC37nVUOEZHUuHCwjCtEPs71qgg4ZfVoe6uQyF/6xw1WU2284rF@ZNN50/wH "Ruby – Try It Online") Input and output are arrays of chars, so the footer does back and forth transformations from strings. I'm not yet sure whether this is a good approach to the problem, but this challenge definitely looks like a nice use scenario for `swapcase` method. [Answer] ## [PHP 4.1.2](https://secure.php.net/releases/#4.1.2), 40 bytes Replace the pair of quotation marks with byte A0 (in ISO-8859-1 or Windows-1252, this is NBSP) to get the byte count shown, then run from a web browser (or from the command line), providing the strings as the query string arguments (or environment variables) `a` and `b`. ``` <?=$a^$c=($a^$b)&str_pad("",2e5),_,$b^$c; ``` In this version of PHP, [register\_globals](https://secure.php.net/manual/en/security.globals.php) is on by default, so the strings will automatically be assigned to the variables `$a` and `$b`. Increase the value `2e5` (200000) if necessary. ## PHP 7.1+, 58 bytes Run on the command line, using `php -r 'code here' string1 string2`: ``` [,$a,$b]=$argv;echo("$b $a"^$a.=" $b")&str_pad("",3e5)^$a; ``` The value `3e5` (300000) is chosen to exceed (MAX\_ARG\_STRLEN \* 2 + 1) on most Linux systems (specifically, x86 and other architectures for which PAGE\_SIZE is 4096, and MAX\_ARG\_STRLEN is thus 131072), to avoid problems with any possible input string. Increase if necessary. [Try it online!](https://tio.run/##DcnNCkBAEADgV9E0iVoucpKTg@vehWZZPyWzLWmf3vBdP7c5@b3s7p3PSzIvnUJSaPoaya9PZaeNE0ATIcGAlNcQoYE0vm4/OpoTAFXYMv2rkoZn2/KxSAhaN20IHw "PHP – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ▌Ö↑o╓→ì]yç ``` [Run and debug it](https://staxlang.xyz/#p=dd99186fd61a8d5d7987&i=[%22CodeGolf%22+%22xxPPCGxx%22]%0A[%22lower%22+%22UPPER%22]%0A[%22MiXeD%22+%22lower%22]%0A[%22A%22+%22A%22]%0A[%22ABcd%22+%22EfGh%22]&a=1&m=2) Here's an ungolfed representation of the same program to show how it works. ``` Example ["Ab", "cd"] :) [["Ab", "cd"], ["cd", "Ab"]] Get all rotations of input m ["cd", "Ab"] For each, run the rest of program; print result M ["cA", "db"] Transpose matrix { "cA" Begin block for mapping to result B "A" 99 "Pop" first element from string array; leave the rest 96> "A" 1 Is the character code > 96? :c "a" Set case of string; 0 -> upper, 1 -> lower m "ab" Perform the map using the block ``` [Run this one](https://staxlang.xyz/#c=+++++++%09Example%0A+++++++%09[%22Ab%22,+%22cd%22]++++++++++++++++%09%0A%3A%29+++++%09[[%22Ab%22,+%22cd%22],+[%22cd%22,+%22Ab%22]]%09Get+all+rotations+of+input%0Am++++++%09[%22cd%22,+%22Ab%22]++++++++++++++++%09For+each,+run+the+rest+of+program%3B+print+result%0A++M++++%09[%22cA%22,+%22db%22]++++++++++++++++%09Transpose+matrix%0A++%7B++++%09%22cA%22++++++++++++++++++++++++%09Begin+block+for+mapping+to+result%0A++++B++%09%22A%22+99++++++++++++++++++++++%09%22Pop%22+first+element+from+string+array%3B+leave+the+rest%0A++++96%3E%09%22A%22+1+++++++++++++++++++++++%09Is+the+character+code+%3E+96%3F%0A++++%3Ac+%09%22a%22+++++++++++++++++++++++++%09Set+case+of+string%3B+0+-%3E+upper,++1+-%3E+lower%0A++m++++%09%22ab%22++++++++++++++++++++++++%09Perform+the+map+using+the+block&i=[%22Ab%22+%22cd%22]&a=1&m=2) ]