text
stringlengths
180
608k
[Question] [ Sylvester's sequence, [OEIS A000058](http://oeis.org/A000058), is an integer sequence defined as follows: Each member is the product of all previous members plus one. The first member of the sequence is 2. ## Task Create a program to calculate the nth term of Sylvester's Sequence. Standard input, output and loopholes apply. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimize the size of your source code as measured in bytes. ## Test Cases You may use either zero or one indexing. (Here I use zero indexing) ``` >>0 2 >>1 3 >>2 7 >>3 43 >>4 1807 ``` [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), ~~76~~ ~~68~~ ~~58~~ ~~52~~ 46 bytes ``` <>(()())<>{({}[()])<>({({}[()])({})}{}())<>}<> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=PD4oKCkoKSk8Pnsoe31bKCldKTw-KHsoe31bKCldKSh7fSl9e30oKSk8Pn08Pg&input=NA) Uses this relationship instead: $$a(n) = 1+\sum^{a(n-1)-1}\_{i=0} 2i$$ which is derived from this relationship modified from that provided in the sequence: $$a(n+1) = a(n)(a(n) - 1) + 1.$$ ### Explanation For a documentation of what each command does, please visit [the GitHub page](https://github.com/DJMcMayhem/Brain-Flak). There are two stacks in Brain-Flak, which I shall name as Stack 1 and Stack 2 respectively. The input is stored in Stack 1. ``` <>(()())<> Store 2 in Stack 2. { while(Stack_1 != 0){ ({}[()]) Stack_1 <- Stack_1 - 1; <> Switch stack. ({({}[()])({})}{}()) Generate the next number in Stack 2. <> Switch back to Stack 1. } <> Switch to Stack 2, implicitly print. ``` For the generation algorithm: ``` ({({}[()])({})}{}()) Top <- (Top + Top + (Top-1) + (Top-1) + ... + 0) + 1 ( ) Push the sum of the numbers evaluated in the process: { } while(Top != 0){ ({}[()]) Pop Top, push Top-1 (added to sum) ({}) Pop again, push again (added to sum) } {} Top of stack is now zero, pop it. () Evaluates to 1 (added to sum). ``` ## Alternative 46-byte version This uses only one stack. ``` ({}<(()())>){({}<({({}[()])({})}{}())>[()])}{} ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKSgpKT4peyh7fTwoeyh7fVsoKV0pKHt9KX17fSgpKT5bKCldKX17fQ&input=NA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷ߀P‘ ``` This uses 0-based indexing and the definition from the challenge spec. [Try it online!](http://jelly.tryitonline.net/#code=4bi2w5_igqxQ4oCY&input=&args=NA) or [verify all test cases](http://jelly.tryitonline.net/#code=4bi2w5_igqxQ4oCYCjjhuLbCtcW8w4figqxH&input=). ### How it works ``` Ḷ߀P‘ Main link. Argument: n Ḷ Unlength; yield [0, ..., n - 1]. ߀ Recursively apply the main link to each integer in that range. P Take the product. This yields 1 for an empty range. ‘ Increment. ``` [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), 27 bytes ``` 1{?)=}&~".>")!@(</=+={"/>}* ``` Unfolded: ``` 1 { ? ) = } & ~ " . > " ) ! @ ( < / = + = { " / > } * . . . . . . . . . . ``` [Try it online!](http://hexagony.tryitonline.net/#code=MXs_KT19Jn4iLj4iKSFAKDwvPSs9eyIvPn0q&input=NA) ### Explanation Let's consider the sequence `b(a) = a(n) - 1` and do a little rearranging: ``` b(a) = a(n) - 1 = a(n-1)*(a(n-1)-1) + 1 - 1 = (b(n-1) + 1)*(b(n-1) + 1 - 1) = (b(n-1) + 1)*b(n-1) = b(n-1)^2 + b(n-1) ``` This sequence is very similar but we can defer the increment to the very end, which happens to save a byte in this program. So here is the annotated source code: [![enter image description here](https://i.stack.imgur.com/7QTqY.png)](https://i.stack.imgur.com/7QTqY.png) Created with Timwi's [HexagonyColorer](https://github.com/timwi/HexagonyColorer). And here is a memory diagram (the red triangle shows the memory pointer's initial position and orientation): [![enter image description here](https://i.stack.imgur.com/waiLM.png)](https://i.stack.imgur.com/waiLM.png) Created with Timwi's [EsotericIDE](https://github.com/timwi/EsotericIDE). The code begins on the grey path which wraps the left corner, so the initial linear bit is the following: ``` 1{?)( 1 Set edge b(1) to 1. { Move MP to edge N. ? Read input into edge N. )( Increment, decrement (no-op). ``` Then the code hits the `<` which is a branch and indicates the start (and end) of the main loop. As long as the **N** edge has a positive value, the green path will be executed. That path wraps around the grid a few times, but it's actually entirely linear: ``` ""~&}=.*}=+={....( ``` The `.` are no-ops, so the actual code is: ``` ""~&}=*}=+={( "" Move the MP to edge "copy". ~ Negate. This is to ensure that the value is negative so that &... & ...copies the left-hand neighbour, i.e. b(i). }= Move the MP to edge b(i)^2 and turn it around. * Multiply the two copies of b(i) to compute b(i)^2. }= Move the MP back to edge b(i) and turn it around. + Add the values in edges "copy" and b(i)^2 to compute b(i) + b(i)^2 = b(i+1). ={ Turn the memory pointer around and move to edge N. ( Decrement. ``` Once this decrementing reduces `N` to `0`, the red path is executed: ``` ")!@ " Move MP back to edge b(i) (which now holds b(N)). ) Increment to get a(N). ! Print as integer. @ Terminate the program. ``` [Answer] # J, ~~18~~ ~~14~~ 12 bytes This version thanks to randomra. I'll try to write a detailed explanation later. ``` 0&(]*:-<:)2: ``` # J, 14 bytes This version thanks to miles. Used the power adverb `^:` instead of an agenda as below. More explanation to come. ``` 2(]*:-<:)^:[~] ``` # J, 18 bytes ``` 2:`(1+*/@$:@i.)@.* ``` 0-indexed. ## Examples ``` e =: 2:`(1+*/@$:@i.)@.* e 1 3 e 2 7 e 3 43 e 4 1807 x: e i. 10 2 3 7 43 1807 3263443 10650056950807 113423713055421862298779648 12864938683278674737956996400574416174101565840293888 1655066473245199944217466828172807675196959605278049661438916426914992848 91480678309535880456026315554816 |: ,: x: e i. 10 2 3 7 43 1807 3263443 10650056950807 113423713055421862298779648 12864938683278674737956996400574416174101565840293888 165506647324519994421746682817280767519695960527804966143891642691499284891480678309535880456026315554816 ``` ## Explanation This is an agenda that looks like this: ``` ┌─ 2: │ ┌─ 1 ┌───┤ ├─ + │ └────┤ ┌─ / ─── * ── @. ─┤ │ ┌─ @ ─┴─ $: │ └─ @ ─┴─ i. └─ * ``` (Generated using `(9!:7)'┌┬┐├┼┤└┴┘│─'` then `5!:4<'e'`) Decomposing: ``` ┌─ ... │ ── @. ─┤ │ └─ * ``` Using the top branch as a the gerund `G`, and the bottom as the selector `F`, this is: ``` e n <=> ((F n) { G) n ``` This uses the constant function `2:` when `0 = * n`, that is, when the sign is zero (thus `n` is zero). Otherwise, we use this fork: ``` ┌─ 1 ├─ + ──┤ ┌─ / ─── * │ ┌─ @ ─┴─ $: └─ @ ─┴─ i. ``` Which is one plus the following atop series: ``` ┌─ / ─── * ┌─ @ ─┴─ $: ── @ ─┴─ i. ``` Decomposing further, this is product (`*/`) over self-reference (`$:`) over range (`i.`). [Answer] # [Perl 6](http://perl6.org), 24 bytes ``` {(2,{1+[*] @_}...*)[$_]} ``` ``` {(2,{1+.²-$_}...*)[$_]} ``` ## Explanation ``` # bare block with implicit parameter 「$_」 { ( # You can replace 2 with 1 here # so that it uses 1 based indexing # rather than 0 based 2, # bare block with implicit parameter 「@_」 { 1 + # reduce the input of this inner block with 「&infix:<*>」 # ( the input is all of them generated when using a slurpy @ var ) [*] @_ # that is the same as: # 「@_.reduce: &infix:<*>」 } # keep calling that to generate more values until: ... # forever * # get the value as indexed by the input )[ $_ ] } ``` ## Usage: ``` my &code = {(2,{1+[*] @_}...*)[$_]} say code 0; # 2 say code 1; # 3 say code 2; # 7 say code 3; # 43 say code 4; # 1807 # you can even give it a range say code 4..7; # (1807 3263443 10650056950807 113423713055421844361000443) say code 8; # 12864938683278671740537145998360961546653259485195807 say code 9; # 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443 say code 10; # 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920807 my $start = now; # how many digits are there in the 20th value say chars code 20; # 213441 my $finish = now; # how long did it take to generate the values up to 20 say $finish - $start, ' seconds'; # 49.7069076 seconds ``` [Answer] ## Haskell, 26 bytes ``` f n|n<1=2|m<-f$n-1=1+m*m-m ``` Usage example: `f 4` -> `1807`. [Answer] ## Java 7, ~~46~~ 42 bytes ``` int f(int n){return--n<0?2:f(n)*~-f(n)+1;} ``` Uses 0-indexing with the usual formula. I swapped `n*n-n` for `n*(n-1)` though, since Java doesn't have a handy power operator, and the `f()` calls were getting long. [Answer] ## Haskell, 25 bytes ``` (iterate(\m->m*m-m+1)2!!) ``` [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 60 bytes ``` readIO p = 2 lblL r = p r + 1 p * r i - 1 if i L printInt r ``` [Try it online!](http://silos.tryitonline.net/#code=cmVhZElPIApwID0gMgpsYmxMCnIgPSBwCnIgKyAxCnAgKiByCmkgLSAxCmlmIGkgTApwcmludEludCBy&input=&args=NA) Port of [my answer in C](https://codegolf.stackexchange.com/a/91162/48934). [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), 4 bytes Probably my last language from the golfing family! ~~Non-competing, since the language postdates the challenge.~~ Code: ``` ²->2 ``` Alternative solution thanks to *Zwei*: ``` <*>2 ``` Expanded version: ``` a(n) = ²-> a(0) = 2 ``` Explanation: ``` ² # Stack is empty, so calculate a(n - 1) ** 2. - # Subtract, arity 2, so use a(n - 1). > # Increment by 1. ``` Uses the **CP-1252** encoding. [Try it online!](http://oasis.tryitonline.net/#code=wrItPjI&input=&args=NQ) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~158~~ 154 bytes **Leaky Nun has me beat [here](https://codegolf.stackexchange.com/a/91157/56656)** ``` ({}<(()())>){({}[()]<<>(())<>([]){{}<>({}<<>(({}<>))><>)<>({<({}[()])><>({})<>}{})<>{}([])}{}<>({}())([]){{}({}<>)<>([])}{}<>>)}{}([][()]){{}{}([][()])}{} ``` [Try it Online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKSgpKT4peyh7fVsoKV08PD4oKCkpPD4oW10pe3t9PD4oe308PD4oKHt9PD4pKT48Pik8Pih7PCh7fVsoKV0pPjw-KHt9KTw-fXt9KTw-e308Pjw-KFtdKX17fTw-KHt9KCkpKFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-Pil9e30oW11bKCldKXt7fXt9KFtdWygpXSl9e30&input=) ## Explanation Put a two under the input a(0) ``` ({}<(()())>) ``` While the input is greater than zero subtract one from the input and... ``` { ({}[()] ``` Silently... ``` < ``` Put one on the other stack to act as a catalyst for multiplication <>(())<> While the stack is non-empty ``` ([]) { {} ``` Move the top of the list over and copy ``` <>({}<<>(({}<>))><>) ``` Multiply the catalyst by the copy ``` <>({<({}[()])><>({})<>}{})<>{} ([]) } {} ``` Add one ``` <>({}()) ``` Move the sequence back to the proper stack ``` ([]) { {} ({}<>)<> ([]) } {} <> >) }{} ``` Remove all but the bottom item (i.e. the last number created) ``` ([][()]) { {} {} ([][()]) } {} ``` [Answer] # C, 32 bytes ``` f(n){return--n?f(n)*~-f(n)+1:2;} ``` Uses 1-based indexing. Test it on [Ideone](http://ideone.com/v1l893). [Answer] # [Actually](http://github.com/Mego/Seriously), 9 bytes ``` 2@`rΣτu`n ``` [Try it online!](http://actually.tryitonline.net/#code=MkBgcs6jz4R1YG4&input=NA) Uses this relationship instead: ![formula](https://i.stack.imgur.com/ulqUV.gif) which is derived from this relationship modified from that provided in the sequence: `a(n+1) = a(n) * (a(n) - 1) + 1`. [Answer] ## R, 44 42 41 bytes 2 bytes save thanks to JDL 1 byte save thanks to user5957401 ``` f=function(n)ifelse(n,(a=f(n-1))^2-a+1,2) ``` [Answer] # Python, ~~38~~ 36 bytes **2 bytes thanks to Dennis.** ``` f=lambda n:0**n*2or~-f(n-1)*f(n-1)+1 ``` [Ideone it!](http://ideone.com/nHxzEn) Uses this relationship modified from that provided in the sequence instead: `a(n+1) = a(n) * (a(n) - 1) + 1` ### Explanation `0**n*2` returns `2` when `n=0` and `0` otherwise, because `0**0` is defined to be `1` in Python. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 12 bytes ``` {2|1+*/o'!x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82q2qjGUFtLP19dsaL2f5q6oqHhfwA "K (oK) – Try It Online") ~~Blatantly stolen from~~ Port of [Adám's answer](https://codegolf.stackexchange.com/a/91380/74163). Prints up to the first 11 elements of the sequence, after which the numbers become too big to handle. Thanks @ngn for 6 bytes! ### How: ``` {2|1+*/o'!x} # Main function, argument x. o'!x # recursively do (o) for each (') of [0..x-1] (!x) 1+*/ # 1 + the product of the list 2| # then return the maximum between that product and 2. ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 7 bytes ``` ²_’ 2Ç¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=wrJf4oCZCjLDh8Kh&input=NA) Uses this relationship provided in the sequence instead: `a(n+1) = a(n)^2 - a(n) + 1` ### Explanation ``` 2Ç¡ Main chain, argument in input 2 Start with 2 ¡ Repeat as many times as the input: Ç the helper link. ²_’ Helper link, argument: z ² z² ’ z - 1 _ subtraction, yielding z² - (z-1) = z² - z + 1 ``` [Answer] # [Cheddar](http://cheddar.vihan.org/), 26 bytes ``` n g->n?g(n-=1)**2-g(n)+1:2 ``` [Try it online!](http://cheddar.tryitonline.net/#code=biBnLT5uP2cobi09MSkqKjItZyhuKSsxOjI&input=NA) Pretty idiomatic. ## Explanation ``` n g -> // Input n, g is this function n ? // if n is > 1 g(n-=1)**2-g(n)+1 // Do equation specified in OEIS : 2 // if n == 0 return 2 ``` [Answer] # CJam, 10 bytes ``` 2{_(*)}ri* ``` Uses 0-based indexing. [Try it online!](http://cjam.tryitonline.net/#code=NXsKICAgIDJ7XygqKX1yaSoKTn0q&input=MAoxCjIKMwo0) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes ``` 2sFD<*> ``` **Explained** Uses zero-based indexing. ``` 2 # push 2 (initialization for n=0) sF # input nr of times do D<* # x(x-1) > # add 1 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MnNGRDwqPg&input=NA) [Answer] # R, ~~50 46~~ 44 bytes ``` n=scan();v=2;if(n)for(i in 1:n){v=v^2-v+1};v ``` Rather than tracking the whole sequence, we just keep track of the product, which follows the given quadratic update rule as long as ~~n>1~~ n>0. (This sequence uses the "start at ~~one~~ zero" convention) Using the start at zero convention saves a couple of bytes since we can use if(n) rather than if(n>1) [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish/blob/master/doc.md), 13 bytes ``` p \Ai &(* ><2 ``` [Try it online!](http://jellyfish.tryitonline.net/#code=cApcQWkKJigqCj48Mg&input=NA) ### Explanation Let's start from the bottom up: ``` (* < ``` This is a hook, which defines a function `f(x) = (x-1)*x`. ``` &(* >< ``` This composes the previous hook with the increment function so it gives us a function `g(x) = (x-1)*x+1`. ``` \Ai &(* >< ``` Finally, this generates a function `h` which is an iteration of the previous function `g`, as many times as given by the integer input. ``` \Ai &(* ><2 ``` And finally, we apply this iteration to the initial value `2`. The `p` at the top just prints the result. ### Alternative (also 13 bytes) ``` p > \Ai (* >1 ``` This defers the increment until the very end. [Answer] # Mathematica, 19 bytes ``` Nest[#^2-#+1&,2,#]& ``` --- Or 21 bytes: ``` Array[#0,#,0,1+1##&]& ``` [Answer] # Prolog, 49 bytes ``` a(0,2). a(N,R):-N>0,M is N-1,a(M,T),R is T*T-T+1. ``` [Answer] # SILOS 201 bytes ``` readIO def : lbl set 128 2 set 129 3 j = i if j z print 2 GOTO e :z j - 1 if j Z print 3 GOTO e :Z i - 1 :a a = 127 b = 1 c = 1 :b b * c a + 1 c = get a if c b b + 1 set a b i - 1 if i a printInt b :e ``` Feel free to [try it online!](http://silos.tryitonline.net/#code=cmVhZElPIApkZWYgOiBsYmwKc2V0IDEyOCAyCnNldCAxMjkgMwpqID0gaQppZiBqIHoKcHJpbnQgMgpHT1RPIGUKOnoKaiAtIDEKaWYgaiBaCnByaW50IDMKR09UTyBlCjpaCmkgLSAxCjphCmEgPSAxMjcKYiA9IDEKYyA9IDEKOmIKYiAqIGMKYSArIDEKYyA9IGdldCBhCmlmIGMgYgpiICsgMQpzZXQgYSBiCmkgLSAxCmlmIGkgYQpwcmludEludCBiCjpl&input=&args=NA) [Answer] # [Red](http://www.red-lang.org), ~~55 49 45~~ 39 bytes ``` func[n][x: 2 loop n[x: x * x - x + 1]x] ``` [Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85Oi82usJKwUghJz@/QCEPxK5Q0AJiXSDWVjCMrYj9X1CUmVeikKZgwAVjGcJZRnCWMZxl8h8A "Red – Try It Online") * *-6 thanks to Galen Ivanov* * *-4 thanks to Pedro Maimere* * *-6 thanks to 9214* This is the first real thing I wrote in Red. You have been warned. [Answer] # C, 46 bytes ``` s(n,p,r){for(p=r=2;n-->0;p*=r)r=p+1;return r;} ``` [Ideone it!](http://ideone.com/cDMGB6) Uses `p` as the temporary storage of the product. Basically, I defined two sequences `p(n)` and `r(n)`, where `r(n)=p(n-1)+1` and `p(n)=p(n-1)*r(n)`. `r(n)` is the required sequence. [Answer] # C, ~~43~~, ~~34~~, 33 bytes 1-indexed: ``` F(n){return--n?n=F(n),n*n-n+1:2;} ``` Test main: ``` int main() { printf("%d\n", F(1)); printf("%d\n", F(2)); printf("%d\n", F(3)); printf("%d\n", F(4)); printf("%d\n", F(5)); } ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 13 bytes ``` 0,2|-:0&-y+*+ ``` [Try it online!](http://brachylog.tryitonline.net/#code=MCwyfC06MCYteSsqKw&input=NA&args=Wg) Uses this relationship instead: ![formula](https://i.stack.imgur.com/ulqUV.gif) which is derived from this relationship modified from that provided in the sequence: `a(n+1) = a(n) * (a(n) - 1) + 1`. [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), 18 bytes *Credits to Sp3000 who found the same solution independently.* ``` ? # )}"{!@ * ( (:{ ``` [Try it online!](http://labyrinth.tryitonline.net/#code=PwojCil9InshQAoqICgKKDp7&input=NA) ]
[Question] [ ### Introduction While studying, I tried to come up with several ways to cheat a multiple choice test. It basically is a compressed version of the multiple choice answers. The method goes as following: The answers to the test: ``` BCAABABA ``` These can be converted to 3 different arrays, which indicates true or false if the current letter is the answer: ``` B C A A B A B A A: [0, 0, 1, 1, 0, 1, 0, 1] B: [1, 0, 0, 0, 1, 0, 1, 0] C: [0, 1, 0, 0, 0, 0, 0, 0] ``` Interpreting these numbers as binary would compress this a lot. But this can actually be compressed a bit more. If you know the positions of A and B, you don't need the positions for C. This can be done with a bitwise NOT operator: ``` A: [0, 0, 1, 1, 0, 1, 0, 1] B: [1, 0, 0, 0, 1, 0, 1, 0] A+B: [1, 0, 1, 1, 1, 1, 1, 1] C: [0, 1, 0, 0, 0, 0, 0, 0] ``` Converting the arrays A and B to binary numbers would result in: ``` A: 00110101 B: 10001010 ``` That means that 8 multiple choice answers can be compressed to two bytes! --- ### Task Given two numbers in binary, or two arrays consisting of only 0's and 1's with the same length, output the multiple choice answers --- ### Rules * Input can be in the any form you like, like `[1, 0, 0, 1]` or `1001`. * You may provide a program or a function. * You may assume that the input is always valid. * You may also output as a list, separated with spaces, etc. * The multiple choice answers only consist of A's, B's and C's. You may however use lower case instead. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! --- ### Test cases ``` Input: [1, 0, 0, 1, 0, 0, 1] [0, 1, 0, 0, 1, 0, 0] Output: ABCABCA Input: [0, 0, 0, 0, 1, 0, 1, 1] [1, 0, 1, 0, 0, 0, 0, 0] Output: BCBCACAA Input: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Output: CCCCCCCCCC ``` --- ### Leaderboard ``` var QUESTION_ID=69770,OVERRIDE_USER=34388;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;font-family:Arial}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Jelly, ~~7~~ 6 bytes ``` _/ị“ḃ» ``` ~~Typing on phone. Will add description.~~ `(1,0)` goes to `A`, `(0,1)` to `B`, and `(0,0)` to `C`. Arrays in Jelly are 1-based, and the indexing function `ị` works cyclically. Therefore, we can just fold subtraction over the input. ``` _ [vectorized] subtraction _/ Fold subtraction over the input “ḃ» "ABC" compressed. '»' terminates a compressed string. ị Vectorized cyclic index. ``` Try it [here](http://jelly.tryitonline.net/#code=Xy_hu4vigJxBQkM&input=&args=WzAsIDAsIDAsIDAsIDEsIDAsIDEsIDFdLFsxLCAwLCAxLCAwLCAwLCAwLCAwLCAwXQ). [Answer] # J, 8 bytes ``` 'CAB'{~- ``` Usage: ``` 0 0 1 0 0 1 ('CAB'{~-) 0 1 0 1 0 0 CBABCA ``` [Try it online here.](http://tryj.tk/) [Answer] ## [Retina](https://github.com/mbuettner/retina), 44 bytes ``` T`d`BA B(?=(.)* .*B(?<-1>.)*(?(1)!)$) C .+ ``` The trailing linefeed is significant. Input is like ``` 001101010 100010100 ``` [Try it online!](http://retina.tryitonline.net/#code=VGBkYEJBCkIoPz0oLikqIC4qQig_PC0xPi4pKig_KDEpISkkKQpDCiAuKwo&input=MDAxMTAxMDEwIDEwMDAxMDEwMA) ### Explanation ``` T`d`BA ``` Start by turning `0`s into `B` and `1`s into `A`. That makes the first half correct, except that it lists `B` when it should contain `C`. We can identify those erroneous `B`s by checking whether there's a `B` in the same position of the second string: ``` B(?=(.)* .*B(?<-1>.)*(?(1)!)$) C ``` The lookahead is a classic balancing group counting technique to match up the positions of the two `B`s. The `(.)*` counts the suffix after the first `B` by pushing one capture onto group `1` for each character. Then `(?<-1>.)*` pops from that group again. The `$` ensures that we can reach the end of the string like that, and the `(?(1)!)` ensures that we've actually depleted the entire group. Finally, we get rid of the separating space and the second string: ``` .+ ``` [Answer] ## Java, 81 bytes No reputation to comment the already existing Java solution, so here goes: ``` void x(int[]a,int[]b){int j=0;for(int i:a)System.out.printf("%c",67-2*i-b[j++]);} ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~14~~ 9 bytes ``` 2*+ 67w-c ``` Uses [current version (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0) [**Try it online!**](http://matl.tryitonline.net/#code=MiorIDY3dy1j&input=WzAsIDAsIDAsIDAsIDEsIDAsIDEsIDFdClsxLCAwLCAxLCAwLCAwLCAwLCAwLCAwXQ) ## Explanation **Summary of what the code does** ``` 2* % implicitly input array and multiply it by 2 + % implicitly input array and add it to the first one 67w- % subtract from 67 c % convert to char. Implicitly display ``` **Detailed explanation of how it works** ``` 2 % Push number 2 onto the stack * % Multiply the top two stack elements. Since there's only one % element, this triggers implicit input of a (yet inexistent) % element below the existing one. This is the first input array, % which will be called "A". Both "A" and number 2 are consumed, % and the array 2*A is left on the stack. + % Add the top two stack elements. Again, since there's only % one element (namely array 2*A) this triggers implicit input % of the second array, call it "B". Both 2*A and B are consumed % and 2*A+B is left on the stack % A blank space is needed after the "+" symbol to prevent it from % being interpreted as part of number "+67" 67 % Push number 67 onto the stack. The stack now contains, bottom % to top, 2*A+B and 67. w % Swap top two elements. The stack now contains 67 and 2*A+B - % Subtract top two elements. These are consumed and the result % 67-A*B is left on the stack c % Convert to char array, interpreting each number as ASCII code. % Number 67 corresponds to letter 'C'. Therefore at positions % where both arrays A and B were 0 this gives 'C' as result. % Where A was 1 and B was 0, i.e. 2*A+B is 2, this gives 'A'. % Where A was 0 and B was 1, i.e. 2*A+B is 1, this gives 'B'. % The stack contents, namely this char array, are implicitly % displayed at the end of the program. ``` [Answer] # JavaScript ES6, 36 bytes ``` (a,b)=>a.map((x,y)=>"CBA"[x*2+b[y]]) ``` Very simple, and probably obvious enough to understand: Map each item and index in `a` to the char at position (`x*2` + item at index `y` in `b`) in `"CBA"`. [Answer] # brainfuck, 52 bytes ``` ,+[->>----[<--->----],+]<[<[>--<-]<]>>[<,[>-<-]>.>>] ``` Requires an interpreter that lets you go left from cell 0 and has 8-bit wrapping cells. Unlike most of my answers, EOF behaviour doesn't matter. Takes byte input, with `0xFF` as a delimiter. A stream of bytes representing the first input under "Test cases" would look like this: ``` 0x01 0x00 0x00 0x01 0x00 0x00 0x01 0xFF 0x00 0x01 0x00 0x00 0x01 0x00 0x00 ``` I could save a couple bytes by having `0x00` as a delimiter and using `0x01` and `0x02` as 0 and 1 respectively, but that felt like cheating :P Once I figured out my strategy, writing this program was very easy. To find the nth letter to output, start with `0x43` (capital C in ASCII) and subtract ((nth element of first sequence)\*2 + nth element of second sequence) For what it's worth, here's the 52 byte program split into 3 lines and with some words beside them: ``` Get input until hitting a 255 byte; put a 67 byte to the right of each one ,+[->>----[<--->----],+] For each 67 byte: Subtract (value to the left)*2 from it <[<[>--<-]<] For each byte that used to contain 67: Subtract input and print result >>[<,[>-<-]>.>>] ``` [Answer] ## Haskell, 29 bytes ``` zipWith(\x y->"BCA"!!(x-y+1)) ``` An anonymous function. Use like: ``` >> zipWith(\x y->"BCA"!!(x-y+1)) [1, 0, 0, 1, 0, 0, 1] [0, 1, 0, 0, 1, 0, 0] "ABCABCA" ``` I tried making the function point-free but got a total mess. *2022 edit: Wheat Wizard found a version for 28 bytes, one shorter than nimi's 29-byte equivalent:* ``` zipWith$(!!).(["CB","AC"]!!) ``` [Answer] ## Pyth, 18 16 10 bytes **3rd attempt: 10 bytes** Thank FryAmTheEggman for reminding me of the existence of `G`! ``` VCQ@<G3xN1 ``` Input is of the form [ [0,0,1,1,0,1,0,1] , [1,0,0,0,1,0,1,0] ], which is essentially a matrix: row for choice and column for question number. Hand-compiled pythonic pseudocode: ``` G = "abcdefghijklmnopqrstuvwxyz" // preinitialized var VCQ for N in transpose(Q): // implicit N as var; C transposes 2D lists @<G3 G[:3][ // G[:3] gives me "abc" xN1 N.index(1) // returns -1 if no such element ] ``` --- **2nd attempt: 16 bytes** ``` VCQ?hN\A?.)N\B\C ``` Input is of the form [ [0,0,1,1,0,1,0,1] , [1,0,0,0,1,0,1,0] ], which is essentially a matrix: row for choice and column for question number. This compiles to ``` assign('Q',Pliteral_eval(input())) for N in num_to_range(Pchr(Q)): imp_print(("A" if head(N) else ("B" if N.pop() else "C"))) ``` Ok, I know that looks messy, so let's hand-compile to pythonic pseudocode ``` Q = eval(input()) VCQ for N in range transpose(Q): // implicit N as var; transposes 2D lists ?hN if head(N): // head(N)=1st element of N \A print("A") // implicit print for expressions else: ?.)N if pop(N): \B print("B") else: \C print("C") ``` --- **1st attempt: 18 bytes** ``` V8?@QN\A?@Q+8N\B\C ``` With input of the form [0,0,1,1,0,1,0,1,1,0,0,0,1,0,1,0], essentially concatenation of two lists. This compiles to ``` assign('Q',Pliteral_eval(input())) for N in num_to_range(8): imp_print(("A" if lookup(Q,N) else ("B" if lookup(Q,plus(8,N)) else "C"))) ``` Again, compiling by hand ``` Q = eval(input()) V8 for N in range(8): ?@QN if Q[N]: \A print("A") else: ?@Q+8N if Q[N+8]: \B print("B") else: \C print("C") ``` --- And there goes the first codegolf in my life!!! I just learned Pyth yesterday, and this is the first time I ever participated in a code golf. [Answer] # Python 3, 39 bytes. Saved 1 byte thanks to FryAmTheEggman. Saved 2 bytes thanks to histocrat. Haven't been able to solve with a one liner in a while! ``` lambda*x:['CBA'[b-a]for a,b in zip(*x)] ``` Here's my test cases. It also shows the way I'm assuming this function is called. ``` assert f([1,0,0,1,0,0,1], [0,1,0,0,1,0,0]) == ['A', 'B', 'C', 'A', 'B', 'C', 'A'] assert f([0, 0, 0, 0, 1, 0, 1, 1], [1, 0, 1, 0, 0, 0, 0, 0]) == ['B', 'C', 'B', 'C', 'A', 'C', 'A', 'A'] assert f([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) == ['C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'] ``` It uses `zip` to iterate through the arrays pairwise, and then indexes into a string to pick the correct letter. This all happens in a list comprehension, so it automagically becomes a list. The core of this solution is that the only possible combinations of `a` and `b` are `[0, 1], [1, 0], [0, 0]`. So if we subtract them, we get one of `-1, 0, 1` which gets us the last, first, middle element respectively. [Answer] # Mathematica, ~~30~~ ~~24~~ ~~22~~ 19 bytes *3 bytes saved due to [@alephalpha](http://ppcg.lol/users/9288).* ``` {A,B,C}[[3-2#-#2]]& ``` Quite simple. [Answer] # Ruby, 35 bytes ``` ->a,b{a.zip(b).map{|x,y|:CAB[x-y]}} ``` Usage: ``` ->a,b{a.zip(b).map{|x,y|:CAB[x-y]}}[[1,0,0],[0,1,0]] => ["A", "B", "C"] ``` Takes the (x-y)th zero-indexed character of "CAB". (1-0) gives 1, and thus A. (0-0) gives 0, and thus C. (0-1) gives -1, which wraps around to B. Alternate shorter solution with weirder output: ``` ->a,b{a.zip(b){|x,y|p :CAB[x-y]}} ``` Output is quoted strings separated by newlines, which seems a bridge too far somehow. [Answer] # Japt, 13 bytes ``` ¡#C-X*2-VgY)d ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=oSNDLVgqMi1WZ1kpZA==&input=WzEsIDAsIDAsIDEsIDAsIDAsIDFdIFswLCAxLCAwLCAwLCAxLCAwLCAwXQ==) ### How it works ``` ¡#C-X*2-VgY)d // Implicit: U, V = input lists ¡ // Map each item X and index Y in U to: #C-X*2 // The char code of C (67), minus 2X, -VgY) // minus the item at index Y in V. d // Convert to a char code. ``` [Answer] # Octave, 19 bytes ``` @(x,y)[67-y-2*x,''] ``` Test: ``` f([1 0 0 0 1 1],[0 1 0 0 0 0]) ans = ABCCAA ``` I'll add an explanation later when I have a computer in front of me. This was written and tested on [octave-online](http://octave-online.net/) on my cell. [Answer] # TI-BASIC, ~~59~~ ~~57~~ ~~50~~ ~~37~~ 36 bytes Takes one list from `Ans`, and the other from `Prompt L₁`. Saved 13 bytes thanks to Thomas Kwa's suggestion to switch from branching to `sub(`. ``` Prompt X For(A,1,dim(∟X Disp sub("ACB",2+∟X(A)-Ans(A),1 End ``` I'll have to look for what Thomas Kwa said he found in the comments tomorrow. ¯\\_(ツ)\_/¯ [Answer] # Rust, 79 Saved 8 bytes thanks to Shepmaster. Saved 23 bytes thanks to ker. I'm positive this could be golfed down a lot, but this is my first time writing a full Rust program. ``` fn b(a:&[&[u8]])->Vec<u8>{a[0].iter().zip(a[1]).map(|(c,d)|67-d-c*2).collect()} ``` Here's the ungolfed code and test cases in case anyone wants to try to shrink it. ``` fn b(a:&[&[u8]])->Vec<u8>{ a[0].iter().zip(a[1]).map(|(c,d)|67-d-c*2).collect() } fn main() { assert_eq!("ABCABCA", b(&[&[1, 0, 0, 1, 0, 0, 1], &[0, 1, 0, 0, 1, 0, 0]])); assert_eq!("BCBCACAA", b(&[&[0, 0, 0, 0, 1, 0, 1, 1], &[1, 0, 1, 0, 0, 0, 0, 0]])); assert_eq!("CCCCCCCCCC", b(&[&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])); } ``` The approach is pretty similar to my Python answer. The main difference being that I can't directly index strings, so I can't do the `c-d` trick. [Answer] # Vitsy, 40 bytes *sigh* My baby was not made to do array manipulation. Expects input through STDIN (something I never do) with a leading `"`. ``` WX&WXl\[68*-1+m] ?68*-2*"C"-i*O? "B"O?X? ``` Explanation in the (soon available) verbose mode: ``` 0: STDIN; remove top; make new stack; STDIN; remove top; push length of stack; repeat next instruction set top times; begin recursive area; push 6; push 8; multiply top two; subtract top two; push 1; add top two; goto top method; end recursive area; 1: rotate right a stack; push 6; push 8; multiply top two; subtract top two; push 2; multiply top two; toggle quote; push cosine of top; // this is character literal "C" toggle quote; subtract top two; push input item; multiply top two; output top as character; rotate right a stack; 2: toggle quote; B; toggle quote; output top as character; rotate right a stack; remove top; rotate right a stack; ``` This is getting golfed better real soon, people. I'm so sorry for its current length. Basically, I treat the input as a string, and then manipulate from there. [Try it online!](http://vitsy.tryitonline.net) [Answer] ## CJam, 10 bytes ``` 'Cq~z2fbf- ``` Input as a list of two lists, e.g. ``` [[1 0 0 1 0 0 1] [0 1 0 0 1 0 0]] ``` [Test it here.](http://cjam.aditsu.net/#code='Cq~z2fbf-&input=%5B%5B1%200%200%201%200%200%201%5D%20%5B0%201%200%200%201%200%200%5D%5D) ### Explanation Treating the pairs as bits of a base-2 number, we get `2` for `A`, `1` for `B` and `0` for `C`. ``` 'C e# Push the character C. q~ e# Read and evaluate input. z e# Transpose the pair of lists to get a list of pairs. 2fb e# Convert each pair from base 2. f- e# Subtract each result from the character C. ``` [Answer] # Python 3, ~~48~~ 45 bytes I thought I had an elegant solution, then I saw @Morgan Thrapp's answer... edit: Saved three bytes thanks to the aforementioned. ``` lambda*x:['A'*a+b*'B'or'C'for a,b in zip(*x)] ``` ~~`lambda *x:[a*'A'or b*'B'or'C'for a,b in zip(*x)]`~~ [Answer] # Java, ~~131~~ ~~122~~ ~~110~~ 90 bytes EDIT: Thanks to Bifz / FlagAsSpam for the help and inspiration ``` void x(int[]a,int[]b){int j=0;for(int i:a){System.out.print(i>0?"A":b[j]>0?"B":"C");j++;}} ``` ~~First submission, naive Java solution. Can almost certainly be improved :)~~ ``` static String x(int[]a,int[]b){String o="";for(int i=0;i<a.length;i++)o+=a[i]>0?"A":b[i]>0?"B":"C";return(o);} ``` [Answer] # R ~~29~~ 16 bytes ``` LETTERS[3-2*A-B] ``` removed declaration of function since I saw it's common in other contests. [Answer] ## PowerShell, 40 Bytes ``` param($a,$b)$a|%{"CBA"[2*$_+$b[++$d-1]]} ``` Takes input as two explicit arrays, e.g.. `PS C:\Tools\Scripts\golfing> .\cheating-a-multiple-choice-test.ps1 @(1,0,0,1,0,0,1) @(0,1,0,0,1,0,0)`, and stores them in `$a` and `$b`. Next, loop through `$a` with `$a|{...}`. Each loop, we output a character indexed into the string `"CBA"`, with the index decided by twice the current value `$_`, plus the value of `$b` indexed by our helper variable that's been pre-added then subtracted. As an example, for the first test case, `$a = @(1,0,0,1,0,0,1)` and `$b = @(0,1,0,0,1,0,0)`. The first loop iteration has `$_ = 1`, `$d = $null` (since `$d` hasn't previously been declared). We pre-add to `$d` so now `$_ = 1` and `$d = 1` (in PowerShell, `$null + 1 = 1`), meaning that `$b[1-1] = $b[0] = 0`. Then `2 * 1 + 0 = 2`, so we index `"CBA"[2]`, or `A`. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 12 chars / 22 bytes ``` Ⓒ…îⓜṃ-$*2-í_ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=true&input=%5B%5B1%2C0%2C0%2C1%2C0%2C0%2C1%5D%2C%5B0%2C1%2C0%2C0%2C1%2C0%2C0%5D%5D&code=%E2%92%B8%E2%80%A6%C3%AE%E2%93%9C%E1%B9%83-%24*2-%C3%AD_)` # Explanation Translates to Javascript ES6 as ``` String.fromCharCode(...input1.map(($,_)=>67-$*2-input2[_])) ``` [Answer] # R ~~36~~ 34 bytes ``` function(a,b)c('B','C','A')[a-b+2] ``` Two bytes saved removing unnecessary braces [Answer] # Perl 5 - 47 Already 30 answers and no perl? Here is a naive first attempt then :-) Just the function: ``` sub x{($g,$h)=@_;map{$_?a:$h->[$i++]?b:c}@{$g}} ``` Usage: ``` @f = (0, 0, 0, 0, 1, 0, 1, 1); @s = (1, 0, 1, 0, 0, 0, 0, 0); print x(\@f, \@s); ``` I'm pretty sure that something better could be done with regex, but I couldn't find how. [Answer] # JavaScript ES6, 75 bytes I went the extra mile to accept integer arguments instead of array arguments. ``` (a,b)=>[...Array(8)].map((_,n)=>'CBA'[(a&(s=128>>n)*2+b&s)/s]).join('') ``` Explanation: ``` (a,b)=> // input of two integers representing 8 answers (max value 255 each) [...Array(8)] // generates an array with 8 indices that allows .map() to work .map((_,n)=> // n is each index 0-7 'CBA'[...] // reading character from string via index reference (...) // grouping for division (a&...) // AND operator to test if answer is A (s=128>>n) // calculating binary index in integer input and storing reference *2 // bias index in 'CBA' so truthy is 2 instead of 1 +(b&s) // AND operator to test if answer is B /s // divide by binary index to convert AND operators to increments of 1 .join('') // convert to string without commas ``` Credit to @ETHproductions for string indexing logic. ### Test Here ``` f=(a,b)=>[...Array(8)].map((_,n)=>'CBA'[((a&(s=128>>n))*2+(b&s))/s]).join(''); console.log(f(0b01001001, 0b00100100)); console.log(f(0b00001011, 0b10100000)); console.log(f(0b00000000, 0b00000000)); ``` ``` <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> ``` ### Pssst For 3 extra bytes, it can display the representation for up to 30 answers: ``` (a,b)=>[...Array(30)].map((_,n)=>'CBA'[((a&(s=1<<30>>n))*2+(b&s))/s]).join('') ``` [Answer] # Retina, 46 bytes ``` ^ % +`%(.)(.* )(.) $1$3,%$2 10 A 01 B 00 C \W [empty line] ``` Merges the two strings and chooses the letters according to the digit pairs. [Try it online here.](http://retina.tryitonline.net/) [Answer] # Lua, 87 Bytes Simply testing the values in the arrays, and concatenating `A`, `B` or `C`. ``` function f(a,b)s=""for i=1,#a do s=s..(0<a[i]and"A"or 0<b[i]and"B"or"C")end print(s)end ``` [Answer] ## F#, 33 bytes ``` Seq.map2(fun a b->67-a*2-b|>char) ``` That's a partially applied function that takes two int sequences - two arrays work fine - and returns a new sequence of characters representing the correct answers. =) [Answer] ## Seriously, 14 bytes ``` ,,Z`i-"CBA"E`M ``` [Try It Online](http://seriously.tryitonline.net/#code=LCxaYGktIkNCQSJFYE1Y&input=WzEsMCwwLDEsMCwwLDFdClswLDEsMCwwLDEsMCwwXQ) Probably due to a bug in the safe mode version of the interpreter, you must add an `X` to get it to work right in the online version. Download the local version to get the above program working correctly as-is. It's too short to warrant a full explanation, so I'll just say: it uses the same algorithm as the Jelly answer. ]
[Question] [ Your task is to write a program that will output a readable list of every five letter words with the structure: **consonant - vowel - consonant - vowel - consonant** The output should be sorted alphabetically with one word per line and no words repeated twice. It can be lowercase or uppercase but not mixed. So the list could start and end like this: ``` babab babac babad ... zyzyw zyzyx zyzyz ``` Vowels are **a**-**e**-**i**-**o**-**u**-**y**, the other 20 English-alphabet letters are consonants. Words don't have to be actual dictionary words. Shortest code wins. *Note: A few years ago I stumbled upon a program on a university website that did exactly that. Turns out my first and last name fit the c-v-c-v-c constraint, and i'd been googling myself.* [Answer] ## Mathematica, ~~72~~ ~~65~~ 61 bytes ``` Print@@@Tuples@{a=##/(b=#5#9#15#21#25#)&@@Alphabet[],b,a,b,a} ``` For testing, I recommend replacing `Print@@@` with `""<>#&/@`. Mathematica will then display a truncated form showing the first few and last few words, instead of taking forever to print 288,000 lines. ### Explanation I finally found a use for dividing strings. :) I've been intrigued by the possibility of adding or multiplying strings for a while, but the actual use cases are fairly limited. The main point is that something like `"foo"+"bar"` or `"foo"*"bar"` (and consequently, the short form `"foo""bar"`) is completely valid in Mathematica. However, it doesn't really know what to do with the strings in arithmetic expressions, so these things remain unevaluated. Mathematica *does* apply generally applicable simplifications though. In particular, the strings will be sorted into canonical order (which is fairly messed up in Mathematica, once you start sorting strings containing letters of various cases, digits and non-letters), which is often a dealbreaker, but doesn't matter here. Furthermore, `"abc""abc"` will be simplified to `"abc"^2` (which is a problem when you have repeated strings, but we don't have that either), and something like `"abc"/"abc"` will actually cancel (which we'll be even making use of). So what are we trying to golf here. We need a list of vowels and a list of consonants, so we can feed them to `Tuples` to generate all possible combinations. My first approach was the naive solution: ``` Characters@{a="bcdfghjklmnpqrstvwxz",b="aeiouy",a,b,a} ``` That hardcoded list of consonants does hurt a bit. Mathematica does have an `Alphabet` built-in which would allow me to avoid it, if I were able to remove the vowels in a cheap way. This is where it gets tricky though. The simplest way to remove elements is `Complement`, but that ends up being longer, using one of the following options: ``` {a=Complement[Alphabet[],b=Characters@"aeiouy"],b,a,b,a} {a=Complement[x=Alphabet[],b=x[[{1,5,9,15,21,25}]]],b,a,b,a} ``` (Note that we don't need to apply `Characters` to the whole thing any more, because `Alphabet[]` gives a list of letters, not a string.) So let's try that arithmetic business. If we represent the entire alphabet as a product of letters instead of a list, then we can remove letters by simple division, due to the cancelling rule. That saves a lot of bytes because we won't need `Complement`. Furthermore, `"a""e""i""o""u""y"` is actually a byte shorter than `Characters@"aeiouy"`. So we do this with: ``` a=##/(b="a""e""i""o""u""y")&@@Alphabet[] ``` Where we're storing the consonant and vowel products in `a` and `b`, respectively. This works by writing a function which multiplies all its arguments with `##` and divides them by the product of vowels. This function is *applied* to the alphabet list, which passes each letter in as a separate argument. So far so good, but now we have ``` {a=##/(b="a""e""i""o""u""y")&@@Alphabet[],b,a,b,a} ``` as the argument to `Tuples`, and those things are still products, not lists. Normally, the shortest way to fix that is putting a `List@@@` at the front, which turns the products into lists again. Unfortunately, adding those 7 bytes makes it longer than the naive approach. However, it turns out that `Tuples` doesn't care about the heads of the inner lists at all. If you do ``` Tuples[{f[1, 2], f[3, 4]}] ``` (Yes, for an undefined `f`.) You'll get: ``` {{1, 3}, {1, 4}, {2, 3}, {2, 4}} ``` Just as if you had used a `List` instead of `f`. So we can actually pass those products straight to `Tuples` and still get the right result. This saves 5 bytes over the naive approach using two hardcoded strings. Now the `"a""e""i""o""u""y"` is still fairly annoying. But wait, we can save a few bytes here as well! The arguments of our function are the individual letters. So if we just pick out the right arguments, we can reuse those instead of the string literals, which is shorter for three of them. We want arguments `#` (short for `#1`), `#5`, `#9`, `#15`, `#21` and `#25`. If we put `#` at the end, then we also don't need to add any `*` to multiply them together, because (regex) `#\d+` is a complete token that can't have any non-digit appended to it. Hence we end up with `#5#9#15#21#25#`, saving another 4 bytes. [Answer] # Perl, 47 bytes ``` #!perl -l /((^|[aeiouy])[^aeiouy]){3}/&&print for a..1x5 ``` Counting the shebang as one. [Try it online!](https://tio.run/nexus/perl#@6@voRFXE52YmplfWhmrGR0HY1Ub1@qrqRUUZeaVKKTlFykk6ukZVpj@//9fNwcA "Perl – TIO Nexus") [Answer] # Python 3 - 110 bytes ``` a,b="bcdfghjklmnpqrstvwxz","aeiouy";print(*(c+d+e+f+g for c in a for d in b for e in a for f in b for g in a)) ``` Straightforward looping fun :) [Answer] ## Ruby, ~~72 71~~ 52 bytes ``` puts (?z..?z*5).grep /#{["[^aeiouy]"]*3*"[aeiouy]"}/ ``` Thanks to Value Ink for the basic idea, which brought that down to 60 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 16 bytes **05AB1E** uses [CP-1252](http://www.cp1252.com) encoding. ``` žP3ãžO3ãâ€øJ€¨ê» ``` **Explanation** ``` žP3ã # push all combinations of 3 consonants žO3ã # push all combinations of 3 vowels â # cartesian product €ø # zip each pair of [ccc,vvv] (c=consonant,v=vowel) J # join to list of strings ['cvcvcv','cvcvcv' ...] €¨ # remove last vowel from each ê # sort and remove duplicates » # join on newlines ``` For testing purposes I recommend replacing `žP` with a few consonants and `žO` with a few vowels. [Example using 5 consonants and 3 vowels](https://tio.run/nexus/05ab1e#@6@UlJySlq5kfHixUmJqJog@vOhR05rDO7yA5KEVh1cd2v3/PwA) [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ ~~102~~ 94 bytes ``` from itertools import* lambda:map(''.join,product(*(('AEIOUY','BCDFGHJKLMNPQRSTVWXZ')*3)[1:])) ``` [Try it online!](https://tio.run/nexus/python2#PcrJCoMwFEDRvV/xECSJSKF0J7iodrSDHexMF2mjkKJ5kqT4@ZZ20eXl3K7UWIO0hbaIlQFZN6it75RRxeuH4GHNG0pI74VSBY1G8X5a6lNKhuN5driQgMTJaDKdpYvlar3Z7vb58XS@EuYP2K0f3hnr2qikzGm0VBbcHC2voEUtDITgCderCkXbvyeoLJfKQDpMsvi7GNej5FcEpIKWdR8 "Python 2 – TIO Nexus") [Answer] # Pure Bash, 74 ``` v={a,e,i,o,u,y} c={b,c,d,f,g,h,{j..n},{p..t},v,w,x,z} eval echo $c$v$c$v$c ``` Straightforward brace expansion. [Try it online](https://tio.run/nexus/bash#JcM7DoAgEEDB3lNQUL7sDTgMIorGiIWuH8LZsXCSaeqKJzKTOXlqF1zpCQyMTCTKIrJVyi5yVJSLm7d2Uf1qYkjZ2GD139oH). --- If each item must be on its own line, then we have: # Pure Bash, 84 ``` v={a,e,i,o,u,y} c={b,c,d,f,g,h,{j..n},{p..t},v,w,x,z} eval printf '%s\\n' $c$v$c$v$c ``` [Answer] # PHP, ~~88~~ ~~86~~ ~~84~~ 80 bytes pretty string increment :) 6 bytes saved by @Christoph ``` for($s=$v=aeiouy;++$s<zyzza;preg_match("#[^$v]([$v][^$v]){2}#",$s)&&print"$s "); ``` loops through all strings from `bababa` to `zyzyz` and tests if they match the pattern. Run with `-nr`. [Answer] ## Haskell, ~~54~~ 51 bytes ``` l="bcdfghjklmnpqrstvwxz":"aeiouy":l mapM(l!!)[0..4] ``` `mapM func list` builds all words by taking the possible characters for index i from the list returned by `func (list!!i)`. Edit: @xnor found 2 bytes to save and looking at his solution, I found another one. [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` W='BCDFGHJKLMNPQRSTVWXZ' for s in['AEIOUY',W]*2:W=[w+c for w in W for c in s] print W ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9xW3cnZxc3dw8vbx9cvIDAoOCQsPCJKnSstv0ihWCEzL1rd0dXTPzRSXSc8VsvIKtw2ulw7WQEkWw6UVQgHM5NBzOJYroKizLwShfD//wE "Python 2 – Try It Online") I'm back six years later with a golf. The string `W` of consonants can also be used as the result of the first loop which gives all first-letter options. The fact that it's a string rather than a list is harmless because we just need to iterate over it. We can then write the other four letter sets cleanly as `['AEIOUY',W]*2`. # [Python](https://docs.python.org/3.8/), 92 bytes ``` f=lambda i=-4,s='':i*[s]or sum([f(i+1,s+c)for c in i%2*'AEIOUY'or'BCDFGHJKLMNPQRSTVWXZ'],[]) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRIdNW10Sn2FZd3SpTK7o4Nr9Iobg0VyM6TSNT21CnWDtZMw0olKyQmaeQqWqkpe7o6ukfGqmeX6Tu5Ozi5u7h5e3j6xcQGBQcEhYeEaUeqxMdq/m/oCgzr0QjTUNT8z8A "Python 3.8 (pre-release) – Try It Online") Can't let `itertools` win out. Iterative is 1 byte longer in Python 2. ``` W='', for s in(['AEIOUY','BCDFGHJKLMNPQRSTVWXZ']*3)[1:]:W=[w+c for w in W for c in s] print W ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` 11Y2'y'h2Y2X~6Myyy&Z* ``` [Try it online!](https://tio.run/nexus/matl#@29oGGmkXqmeYRRpFFFn5ltZWakWpfX/PwA "MATL – TIO Nexus") (but output is truncated). ``` 11Y2 % Push 'aeiou' (predefined literal) 'y' % Push 'y' h % Concatenate: gives 'aeiouy' 2Y2 % Push 'abcdefghijklmnopqrstuvwxyz' (predefined literal) X~ % Set symmetric difference: gives 'bcdfghjklmnpqrstvwxz' 6M % Push 'aeiouy' again yyy % Duplicate the second-top element three times onto the top. The stack now % contains 'bcdfghjklmnpqrstvwxz', 'aeiouy', 'bcdfghjklmnpqrstvwxz', % 'aeiouy', 'bcdfghjklmnpqrstvwxz' &Z* % Cartesian product of all arrays present in the stack. Implicity display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` @W:@Dg:2jcb:eac@w\ ``` [Try it online!](https://tio.run/nexus/brachylog#@@8QbuXgkm5llJWcZJWamOxQHvP/PwA "Brachylog – TIO Nexus") ### Explanation ``` @W:@D The list ["aeiouy", "bcdfghjklmnpqrstvwxz"] g:2jcb The list ["bcdfghjklmnpqrstvwxz", "aeiouy", "bcdfghjklmnpqrstvwxz", "aeiouy", "bcdfghjklmnpqrstvwxz"] :ea Take one character of each string c Concatenate into a single string @w Write to STDOUT followed by a newline \ Backtrack: try other characters of the string ``` [Answer] # JavaScript (ES6), ~~91~~ 90 bytes ``` f=(s='',i=4)=>{for(c of i%2?'aeiouy':'bcdfghjklmnpqrstvwxz')i?f(s+c,i-1):console.log(s+c)} ``` ### Edits * ETHproductions: -1 byte by removing extraneous group around ternary operator in `for` statement ### Explanation This defines a 5-deep recursive function that uses the parity of its depth of call to determine whether to iterate vowels or consonants. On each iteration, it checks to see whether to recurse or print by checking the amount of recursions left, and concatenates the letter of its current iteration to the end of the 5 character string that is currently being built depth-first. Alternative 89 byte solution assuming ISO8859-1 encoding: ``` f=(s='',i=4)=>{for(c of i%2?'aeiouy':btoa`mÇ_äi骻-¿s`)i?f(s+c,i-1):console.log(s+c)} ``` Alternative 96 byte solution that returns entire output as single string: ``` f=(s='',i=4,o='')=>eval("for(c of i%2?'aeiouy':'bcdfghjklmnpqrstvwxz')o+=i?f(s+c,i-1):s+c+`\n`") ``` **Run at your own risk.** For the 91 byte solution, just use `f()` and for the 97 byte alternative, use `console.log(f())`. [Answer] ## C, ~~201~~ ~~199~~ ~~186~~ ~~184~~ ~~183~~ ~~169~~ 163 bytes Doing it a bit differently than with the previous basic counting method: ``` f(){for(char*c="bcdfghjklmnpqrstvwxz",*v="aeiouy",i[5]={0},*s[]={c,v,c,v,c},j=0;j<5;puts("")){for(j=5;j--;putchar(s[j][i[j]]));for(;j++<5&&!s[j][++i[j]];i[j]=0);}} ``` Ungolfed: ``` f() { for(char *c="bcdfghjklmnpqrstvwxz", *v="aeiouy", i[5]={0}, *s[]={c,v,c,v,c}, j=0; j<5; puts("")) { for (j=5; j--; putchar(s[j][i[j]])) ; for (; j++ < 5 && !s[j][++i[j]]; i[j]=0) ; } } ``` And written in a bit more conventional way: ``` f() { char *c="bcdfghjklmnpqrstvwxz", *v="aeiouy", i[]={0,0,0,0,0}, *s[]={c,v,c,v,c}, j=0; while (j>=0) { for (j=0; j<5; j++) putchar(s[j][i[j]]); // output the word while (--j>=0 && !s[j][++i[j]]) i[j]=0; // increment the counters puts(""); } } ``` Basically, *i* are the counters, and *s* the array of strings containing all the chars over which we should iterate, for each counter. The trick is the inner *while* loop: it is used to increment the counters, starting from the rightmost one. If we see that the next character we should display is the ending null char, we restart the counter to zero and the "carry" will be propagated to the next counter. Thanks Cristoph! [Answer] # Befunge, 95 bytes ``` ::45*%\45*/:6%\6/:45*%\45*/:6%\6/1g,2g,1g,2g,1g,55+,1+:"}0":**-!#@_ bcdfghjklmnpqrstvwxz aeiouy ``` [Try it online!](http://befunge.tryitonline.net/#code=Ojo0NSolXDQ1Ki86NiVcNi86NDUqJVw0NSovOjYlXDYvMWcsMmcsMWcsMmcsMWcsNTUrLDErOiJ9MCI6KiotISNAXwpiY2RmZ2hqa2xtbnBxcnN0dnd4egphZWlvdXk&input=), although note that the output will be truncated. This is just a loop over the range 0 to 287999, outputting the index as a mixed based number 20-6-20-6-20, with the "digits" of the number retrieved from the tables on the last two lines. [Answer] # [Perl 6](http://perl6.org/), 70 bytes ``` $_=<a e i o u y>;my \c=[grep .none,"a".."z"];.say for [X~] c,$_,c,$_,c ``` Explanation of the interesting part: ``` .say for [X~] c, $_, c, $_, c c, $_, c, $_, c # list of five lists [X ] # lazily generate their Cartesian product ~ # and string-concatenate each result .say for # iterate to print each result ``` The code before that just generates the list of vowels (`$_`) and the list of consonants (`c`), which is regrettably verbose. [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ 117 bytes Thanks to @WheatWizard for the tabs tip. ``` x,y='aeiouy','bcdfghjklmnpqrstvwxz' for a in x: for e in x: for b in y: for c in y: for d in y:print b+a+c+e+d ``` [Try it online!](https://tio.run/nexus/python2#PcdLFkAgFADQMat4swavFTjHYvohn5BQNh/FcWc3ehpqwpSe90Ao4UI2bdcP42SW1W7uOP1Fyma2wEAb8FUJKepLkcJTwpM88S9Xvl2sNg44MhSoUMZ4Aw "Python 2 – TIO Nexus") Not sure that this can be golfed much. Try it online truncates at 128KB but shows enough to give an idea. A local run with debug code to count the words gave a total of 288000. Runs in about 45 seconds if anyone wants to test. ``` zyzyv zyzyw zyzyx zyzyz Total word count: 288000 ``` Non-compliant and therefore non-competing version (prints out nested arrays instead of the specified format) for 110 bytes: ``` x,y='aeiouy','bcdfghjklmnpqrstvwxz' print[[[[c+a+d+b+e for e in y]for d in y]for c in y]for b in x]for a in x] ``` [Answer] # Perl 6, 53 Bytes ``` /<-[aeiouy]>**3%<[aeiouy]>/&&.say for [...] <a z>Xx 5 ``` Takes a little time to have any output. Very inefficient. Does the job. [Answer] ## JavaScript (Firefox 30-57), 82 bytes ``` f=(i=5)=>i?[for(s of f(i-1))for(c of i%2?'bcdfghjklmnpqrstvwxz':'aeiouy')s+c]:[''] ``` Returns an array of strings. Very fast version for ~~102~~ 101 (1 byte thanks to @ETHproductions) bytes: ``` _=>[for(i of c='bcdfghjklmnpqrstvwxz')for(j of v='aeiouy')for(k of c)for(l of v)for(m of c)i+j+k+l+m] ``` [Answer] # Perl, 71 bytes ``` map{push@{1+/[aeiouy]/},$_}a..z;$"=",";say for glob"{@1}{@2}"x2 ."{@1}" ``` [Try it online!](https://tio.run/nexus/perl#Ky1OVTDVMzA0sP6fm1hQXVBanOFQbaitH52YmplfWhmrX6ujEl@bqKdXZa2iZKuko2RdnFipkJZfpJCek5@kVO1gWFvtYFSrVGGkoAfmKf3/DwA "Perl – TIO Nexus") **Explanation** *I'll add more explanations later.* `map{push@{1+/[aeiouy]/},$_}a..z;` creates two arrays: `@1` contains the consonants, and `@2` contains the vowels. `glob` when call with arguments like `{a,b}{c,d}` returns all permutations of the elements in the braces. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~32~~ ~~31~~ ~~29~~ 28 bytes *Saved 2 bytes thanks to Martin Ender and 1 byte thanks to kaine* ``` "aeiouy"_'{,97>^\1$1$1$N]:m* ``` [Try it online!](https://tio.run/nexus/cjam#fVFLS8QwEL7nVwyrIMhW8CR6EGTxKqIefTDbTE0gTUom3W7xx9dJu3W7F1sKbfq9Zr5hhWRD26@@gM7guWUDyRCw3cMudOQY0GvQbeNsiYnUxc/69uYe5FrCOxMcAbrG4JaS@oT5EtBrX9eUoi2BKYG2VUWRfEkQqpE7s6CzaVKbjNfQW3Kax6MyeA4efWII3vXq/cShwwZSkKcLQI5qEpy6Ps/3AbIJTT8NRiKliyqGupDvItNY0vlvURgRo5CJJG@2JlawtHozliESt06SWD8NECP2sKWsccxZTFMU/52op6X2g9aA4Klz1svEBiOWieKci6SHw8qc5aQ@ltxH@Yl@inIlvUg62lHsk8mpdBBBDlBhzKFn4OlobHMpIh@lT2Twsst9rt0m2RDG9FfYaKLu6ssj@YV0O7EP62g5G2@ERmzFsIlBEImH4Rc "CJam – TIO Nexus") (Note that the output gets cut off on TIO) **Explanation** ``` "aeiouy"_ e# Push the six vowels and duplicate '{,97> e# Push the whole alphabet ^ e# Symmetric set difference of the alphabet with the vowels, yields the consonants only \ e# Swap top two elements 1$1$1$ e# Copy the second-from-the-top string to the top three times e# This results in the array being consonants-vowels-consonants-vowels-consonants N e# Add a newline character to the end of the list ] e# End an array. Puts everything done so far in an array e# since there was no explicit start of the array. :m* e# Reduce the array using Cartesian products ``` [Answer] # Stacked, noncompeting, 51 bytes ``` (consonants:@c vowels:@v c v c)multicartprod$outmap ``` Pretty simple. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) [Answer] ## Scala, ~~87~~ 86 bytes ``` val a="aeiouy" val b='a'to'z'diff a for(c<-b;d<-a;e<-b;f<-a;g<-b)println(""+c+d+e+f+g) ``` [Answer] # R, ~~143~~ 132 bytes ``` q=letters;v=c(1,5,9,15,21,25);x=list(q[-v],q[v],q[-v],q[v],q[-v]);Reduce(paste0,mapply(function(a,b)rep(a,e=b/20),x,cumprod(sapply(x,length)))) ``` ``` q=letters;v=c(1,5,9,15,21,25);x=list(a<-q[-v],b<-q[v],a,b,a);Reduce(paste0,mapply(function(a,b)rep(a,e=b/20),x,cumprod(lengths(x)))) ``` This is my first go at code golf so I'd welcome any suggestions to chop it down further. So far it's all pretty standard R; the only possibly tricky thing here is that paste0 recycles its arguments to the length of the longest one. Edit: used assignment trick from rturnbull, replaced `sapply(x,length)` with `lengths`. [Answer] # R, ~~111~~ 98 bytes Added `y` as a vowel, and golfed off 13 bytes, thanks to @Patrick B. ``` l=letters v=c(1,5,9,15,21,25) apply(expand.grid(C<-l[-v],V<-l[v],C,V,C)[,5:1],1,cat,fill=T,sep="") ``` We use `expand.grid` to generate all possible combinations of `V` and `C` in a matrix, which we define from the preset variable `letters` (the alphabet). We reverse the combinations (as the default is for the first variable to rotate the fastest) to ensure alphabetical order. Then we iterate through each row of the matrix, printing each letter to stdout. We use the `fill` argument to `cat` to ensure that each word begins on a new line. [Answer] ## Clojure, 101 bytes ``` (print(apply str(for[V["aeiouy"]C["bcdfghjklmnpqrstvwxz"]a C b V c C d V e C](str a b c d e "\n"))))) ``` Not that exciting... [Answer] ## Ruby, ~~65~~ 61 bytes Completely different approach: ``` (b=[*?a..?z]-a="aeiouy".chars).product(a,b,a,b){|x|puts x*""} ``` New things I learned today: the **Array#product** function [Answer] ## C 361 bytes ``` f(){i,j,k,l,m;v[6]={97,101,105,111,117,121};c[25];s=26;for(i=0;i<26;i++)c[i]=97+i;for(i=0;i<26;i++){for(j=0;j<6;j++)if(c[i]==v[j])c[i]+=1;}for(i=0;i<s;i++)for(j=i+1;j<s;){ if(c[i]==c[j]){for(k=j;k<s-1;++k)c[k]=c[k+1];--s;}else ++j;}for(i=0;i<s;i++)for(j=0;j<6;j++)for(k=0;k<s;k++)for(l=0;l<6;l++)for(m=0;m<s;m++)printf("%c%c%c%c%c\n",c[i],v[j],c[k],v[l],c[m]);} ``` Ungolfed version: ``` void f() { int i,j, k,l,m; int s=26; int v[6]={97,101,105,111,117,121}; int c[s]; for(i=0;i<s;i++) c[i]=97+i; for(i=0;i<s;i++) { for(j=0;j<6;j++) if(c[i]==v[j]) c[i]+=1; } for(i=0;i<s;i++) for(j=i+1;j<s;) { if(c[i]==c[j]) { for(k=j;k<s-1;++k) c[k]=c[k+1]; --s; }else ++j; } for(i=0;i<s;i++) for(j=0;j<6;j++) for(k=0;k<s;k++) for(l=0;l<6;l++) for(m=0;m<s;m++) printf("%c%c%c%c%c\n",c[i],v[j],c[k],v[l],c[m]); } ``` There must be some way to shorten this definitely. ## Explanation * Stored the integer values of a,e,i,o,u,y in a numerical array, * Stored all alphabets in array, if it was a vowel, replaced it with a consonant, so there were duplicate consonant values in the array, * Removed duplicate consonant values, * Printed all combinations c-v-c-v-c. [Answer] # Pyth, ~~25~~ 23 bytes ``` s.n*F[K-GJ"aeiouy"JKJKb ``` In pseudocode: ``` ' ' G, b = "abcdefghijklmnopqrstuvwxyz", "\n" ' J"aeiouy" ' J = "aeiouy" ' K-GJ ' K = "bcdfghjklmnpqrstvwxz" 's.n ' "".join( flatten( ' *F ' reduce(cartesian_product, ' [K JKJKb' [K,J,K,J,K,b] ' ' # b makes it so that every word ends with \n so that ' ' # flattening and concatenating automatically deals with ' ' # newlines ``` [Try it online!](http://pyth.herokuapp.com/?code=s.n%2aF%5BK-GJ%22aeiouy%22JKJKb&debug=0) [Answer] # Perl, ~~63~~ ~~59~~ 54 bytes ``` $a="aeiouy";$b="[^$a][$a]"x2;for("a"x5.."z"x5){say if/$b[^$a]/} ``` ``` $a="aeiouy";$b="[^$a][$a]"x2;/$b[^$a]/&&say for"a"x5.."z"x5 ``` ``` $a=aeiouy;$b="[^$a][$a]"x2;/$b[^$a]/&&say for a.."z"x5 ``` Trying Perl golf for a change. EDIT: [Looks like](https://codegolf.stackexchange.com/a/106574/14880) I've still got much to learn... :) ]
[Question] [ While [Rust](https://www.rust-lang.org/) is very, very rarely competitive in code golfing competitions (Java is often shorter), it can still be fun to golf in. What are some tricks for making Rust code shorter? Please post only one tip in each answer. [Answer] ## Use closures instead of functions A closure: ``` |n|n+1 ``` is shorter than a function: ``` fn f(n:i32)->i32{n+1} ``` --- Closures longer than one statement need braces but are still far shorter than a function. [Answer] # Converting `&str` to `String` Never do these: ``` s.to_string() // 13 bytes s.to_owned() // 12 bytes ``` This is always shorter: ``` s.repeat(1) // 11 bytes ``` If `s` is a string literal: ``` format!(s) // 10 bytes ``` For example: use `format!("")` instead of `String::new()` to save 2 bytes. If type inference works: ``` s.into() // 8 bytes ``` [Answer] # Avoid .iter().enumerate() Let's say you have some x that implements the IntoIterator Trait and you need to call a function f that takes the index of an element and a reference to it. The standard way of doing this is ``` x.iter().enumerate().map(f) ``` instead you can do ``` (0..).zip(x).map(f) ``` and save yourself not only the unusually long enumerate but also the call to iter! [Answer] If you need many mutable variables, it can waste a lot of space declaring them and initializing them, since each requires the mut keyword and you can't do anything like a=b=c=0. A solution then is to declare a mutable array ``` let mut a=[0;5]; ``` You spend 3 extra bytes each time you use them vs. a normal variable: ``` a[0]+=1; ``` but it can often still be worth it. Using tuples for the same trick is often an even better option: ``` let mut t=(1,4,"this", 0.5, 'c'); ``` This has the advantage of saving a byte on each use vs. the array: ``` t.0=2 ``` It also lets them be of different types. On the downside, it requires more characters to initialize. [Answer] # Use `@` to define multiple variables to the same value `@` is meant to define an alias for pattern matching (like destructuring an array but also getting the original array at the same time). But it works with plain variables too. ``` let a=2;let b=2; // 16 bytes let(a,b)=(2,2); // 15 bytes let a@b=2; // 10 bytes ``` It works in destructuring too: ``` let a=1;let b=1;let c=2;let d=2; // 32 bytes let(a,b,c,d)=(1,1,2,2); // 23 bytes let(a@b,c@d)=(1,2); // 19 bytes ``` [Answer] When using string formatting for example with `print!()`, one can use both numbered and unnumbered formatters to save one byte per item to format: Best shown with an example: ``` fn main() { print!( "{}{}{}. Yes, {0}{}{2}. All you other{1}{2}s are just imitating.", "I'm", " Slim", " Shady", " the real", ); } ``` Which outputs: > > > ``` > I'm Slim Shady. Yes, I'm the real Shady. All you other Slim Shadys are just imitating. > > ``` > > So the unnumbered formatters will get assigned to the items in order, this allows you to skip the index on them. Note that you can only use one unnumbered formatter per item to format, after that it will get used up. [Answer] # Skipping trailing semicolons In functions returning `()`, where the last expression is also of type `()`, you don't need the trailing `;`: ``` fn main(){print!("Hello, world!")} ``` [Answer] # Replace all `filter_map` with `flat_map` It works because: * `filter_map` takes a `FnMut(Self::Item) -> Option<B>` * `flat_map` takes a `FnMut(Self::Item) -> impl IntoIterator` * [`Option` implements `IntoIterator`](https://doc.rust-lang.org/std/option/enum.Option.html#impl-IntoIterator), which will return an iterator with one item for `Some` and empty iterator for `None` [Answer] When working with strings with newlines in them, you save one byte if you use a literal line break in the source code vs having a `\n` in the string and/or using `println`. ``` print!("Hello World! "); ``` is 2 bytes less than: ``` println!("Hello\nWorld!"); ``` [Answer] # Do-while loops Rust does not have a C-style do-while loop: ``` do{do_work();}while(condition); ``` But blocks are also expressions in Rust, so you can write: ``` while{do_work();condition}{} ``` [Answer] # Reading lines After considering various things, I think that is generally the shortest way to retrieve a line. The line has a newline, it can be removed by trimming (`.trim()`) or if that cannot be done by slicing. ``` let y=&mut"".into();std::io::stdin().read_line(y); ``` For multiple lines, `lines` iterator can be used, the iterated line doesn't end in newline then. A glob import is needed to import `BufRead`, needed for `lines` to be available for `StdinLock<'_>` type. ``` use std::io::*;let y=stdin();y.lock().lines() ``` [Answer] When using whole number floating point numbers, you can omit the trailing `.0` to save one byte. ``` let a=1. ``` is 1 byte less than: ``` let a=1.0 ``` [Answer] # Use `..=` Replace all `..i+1` with `..=i` to save 1 byte, works on both array index `a[i..=i]` and range `(0..=n)` [Answer] # Use closure parameter to define variable instead of `let` ``` {let(a,b)=(A,B);X} ``` can be replaced by ``` (|a,b|X)(A,B) ``` to save 5 bytes if the type of `a` and `b` can be inferred, it usually works when they are integers or are passed to another function directly in `X`. This works well on 2 or more variables, but for a single variable, this could still save 2 bytes if it allows you to get rid of the `{}`. [Answer] # Declare multiple variables using pattern matching (Somewhat of an extension of <https://codegolf.stackexchange.com/a/99124/97519>) Using multiple `let` statements: ``` let a=x;let b=y; let a=x;let b=y;let c=z; ``` Using a tuple match saves 1 char for 2 variables and 3 more chars for ever variable after: ``` let(a,b)=(x,y); let(a,b,c)=(x,y,z); ``` Similarly, you can use array patterns for initializing multiple mutable variables to the same value (this works with immutable variables too but is pretty useless): ``` let[mut a,mut b]=[x;2]; ``` [Answer] # Prefer todo! over panic! [`todo!`](https://doc.rust-lang.org/std/macro.todo.html) is shorter than `panic!` by 1 byte, so prefer to use it if you need to panic and exit the program. It's also shorter than `print!` by a byte, so it can shorten your program if you can output to stderr instead of stdout. ``` todo!("optional message for stderr") ``` [Answer] Use the `?` operator to unwrap infallible results. `?` is used for error propagation in conjunction with the result and option types, and [per this meta post](https://codegolf.meta.stackexchange.com/a/13262/97691) returning them with infallible results is a standard output method. For example, the following code summing the value of a string when interpreted in base a and b, with `?`: ``` |s,a,b|Ok(i32::from_str_radix(s,a)?+i32::from_str_radix(s,b)?) ``` and without: ``` |s,a,b|i32::from_str_radix(s,a).unwrap()+i32::from_str_radix(s,b).unwrap() ``` As you can see, with `?` it is much shorter, and it works with options as well, although often for smaller gains. [Answer] # `if let` can sometimes be shorter than `match` Using `match`: ``` match a{M(v)=>expr,_=>other} ``` Using `if let` costs 2 bytes if there are only 2 branches and 1 is wildcard: ``` if let M(v)=a{expr}else{other} ``` More effective when your `match` needed `{}` anyways, like if the types don't match. For example: ``` match a{M(v)=>{expr;}_=>{other;}} ``` vs.: ``` if let M(v)=a{expr;}else{other;} ``` saves 1 byte. [Answer] # Loops are sometimes shorter than iterators Even with the extra curly braces, in some cases it can be shorter to declare a mutable variable and use a loop instead of using `Iterator` methods. For example, to do something with every third element of a slice and then return the last index: ``` |n:&[_]|{let mut i=0;while i<n.len(){println!("{}",n[i]);i+=3}i-3} ``` ``` |n:&[_]|(0..=n.len()/3).map(|i|{println!("{}",n[i*3]);i*3}).last().unwrap() ``` [Answer] # `(0..).scan` can be shorter than `std::iter::successors` If you want to make endless sequences that are based on previous state: ``` std::iter::successors(Some(a),|x,_|Some(/*something*/)) ``` This will be shorter by a character: ``` (0..).scan(a,|x,_|{let y=*x;*x=/*something*/;Some(y)}) ``` If you don't mind dropping the first case, it can be even shorter: ``` (0..).scan(a,|x,_|{*x=/*something*/;Some(*x)}) ``` [Answer] # Get the nth element of a `String` or `&str` slice In rust you can't directly index a string or slice. If you want to build a string from indexes of another string you would typically do this: ``` s.chars().nth(n).unwrap() // char s.bytes().nth(n).unwrap() // u8 ``` Shorter is this, but it will depend `s` so won't work if `s` is generated from a expression: ``` s.as_bytes()[n]as char // char, supports only single byte characters s.as_bytes()[n] // u8 ``` However, if you are ok with a `&str` (like if you want to collect into a `String` or concatenate with a existing `String`). This also supports only single byte characters. ``` &s[n..][..1] // &str &s[n..=n] // &str, if `n` is a single variable or sufficiently short expression ``` If your expression is a literal you can use byte string instead to index it directly: ``` b"hello world"[n] // u8 b"hello world"[n]as char // char ``` [Answer] # `scan` and `fold` on `Iterator`s can be used for stateful iteration If your closure consists of variable declarations and iterating over something while keeping an internal state, you might be able to save some bytes by using `scan` or `fold` instead of a `for` loop: ``` |i:&str|{let(mut a,mut b,mut c)=(1,2,0);for x in i.chars(){/*AAA*/;/*BBB*/;c=/*CCC*/}c} ``` `scan` is good for handling many mutable variables, at the cost of some operations (such as assignment) requiring dereferencing with `*` and needing to collect the final value using a method like `last`: ``` |i:&str|i.chars().scan((1,2),|(a,b),x|{/*AAA*/;/*BBB*/;Some(/*CCC*/)}).last() ``` `fold` can also be used in a similar manner by passing values in the accumulator: ``` |i:&str|i.chars().fold((1,2,3),|(a,b,c),x|(/*AAA*/,/*BBB*/,/*CCC*/)).2 ``` [Answer] ## Using slice patterns to get both an array and variables with the same value It is a common trick to use array slicing to compactly assign many variables to the same value: ``` let[a,b,c]=[0;3] // vs let(a,b,c)=(0,0,0) // or let a=0;let b=0;let c=0; ``` I've never really seen this used on arrays, even though it also saves bytes there: ``` let[a,..@b]=[0;99]; // store "the rest" of the slice in b // vs let(a,b)=(0,[0;98]); // or let a=0;let b=[0;98]; ``` Saves just one byte so may not be worth it if it increases the array size by one byte. It works for mutable variables too: ``` let[mut v,mut u@..]=[0;99]; // vs let(mut u,mut v)=(0,[0;98]); ``` ]
[Question] [ Given a non-negative integer input, write a program that converts the number to hexadecimal and returns a truthy value if the hexadecimal form of the number contains only the characters `A` through `F` and a falsey value otherwise. --- Test cases ``` 10 ==> True (A in hexadecimal) 100 ==> False (64 in hexadecimal) 161 ==> False (A1 in hexadecimal) 11259375 ==> True (ABCDEF in hexadecimal) 0 ==> False (0 in hexadecimal) ``` --- Bonus: **-40 bytes** if your program prints `Only letters` for the challenge described above, `Only numbers` if the hexadecimal version of the number only contains the digits `0-9` and `Mix` if the hexadecimal number contains at least one number and at least one letter. --- This is code golf. Standard rules apply. Shortest code in bytes wins. Either functions or full programs are allowed. [Answer] # Pyth, 43 - 40 = 3 bytes ``` ?&[[email protected]](/cdn-cgi/l/email-protection)"Mix"%"Only %sers"?K"lett""numb ``` [Test suite](https://pyth.herokuapp.com/?code=%3F%26K%40J.HQG-JG%22Mix%22%25%22Only+%25sers%22%3FK%22lett%22%22numb&test_suite=1&test_suite_input=10%0A100%0A161%0A11259375%0A0&debug=0) This achieves the bonus. `Only numbers` and `Only letters` fortunately only differ by 4 letters. printf-style formatting is used with `%`. The selection system is done by both taking the intersection of the hex with `G`, the alphabet, and subtracting out `G`. If neither ends up falsy, it's a mix, while if the intersection is falsy, it's numbers, and if the subtraction is falsy, it's letters. [Answer] # Pyth, 6 bytes ``` !-.HQG .HQ # Converts the input to hexadecimal - G # Deletes all letters ! # If empty, output True, else False ``` Test it [here](https://pyth.herokuapp.com/?code=%21-.HQG&debug=0) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes ``` b16>9P ``` [Try it online!](http://jelly.tryitonline.net/#code=YjE2PjlQ&input=&args=MTEyNTkzNzU) ### How it works ``` b16>9P Input: z b16 Convert the input to base 16. >9 Compare each resulting digit with 9; return 1 iff greater. P Take the product of the resulting Booleans. ``` [Answer] ## Python, 24 bytes ``` lambda n:min('%x'%n)>'9' ``` Converts the input a hex string (without `0x` prefix) with `'%x'%n`. Sees if all its chars are greater than `'9'` (which letters are) by seeing if the `min` is above `'9'`. [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 11 bytes ~~13 15 16~~ ``` xT(16)O(Sz) ``` Pretty simple. This uses TeaScript 2.0. You can get this version from the Github ## Explanation ``` // Implicit: x = input, Sz = alphabet xT(16) // input -> hex O(Sz) // Only letters? ``` [Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22xT(16)O(Sz,1)%22&inputs=%5B%2210%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) (slightly modified version that works on web) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 ``` i16YA1Y2mA ``` ### Examples ``` >> matl i16YA1Y2mA > 240 0 >> matl i16YA1Y2mA > 255 1 ``` ### Explanation ``` i % input 16YA % convert to string representation in base 16 1Y2 % predefined literal: 'A':'Z' m % true for set member A % all ``` --- # Bonus challenge: 53−40 = 13 ``` i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']] ``` ### Examples ``` >> matl > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']] > > 255 Only letters >> matl > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']] > > 100 Only numbers >> matl > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']] > > 240 Mix ``` ### Explanation ``` i % input 16YA % convert integer to string representation in base 16 1Y2 % predefined literal: 'A':'Z' m % true for set member XK % copy to clipboard K A % all ? % if (top of the stack) 'Only letters' % string literal } % else K % paste from clipboard K a % any ? % if (top of the stack) 'Mix' % string literal } % else 'Only numbers' % string literal ] % end ] % end ``` [Answer] # LabVIEW, 52-40 = 12 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) Praise the built-ins! [![enter image description here](https://i.stack.imgur.com/IEQHv.gif)](https://i.stack.imgur.com/IEQHv.gif) [Answer] # C, ~~46~~ ~~43~~ 37 bytes Now with more recursion! (Thanks Dennis): ``` F(x){return(x%16>9)*(x<16?:F(x/16));} ``` Bonus: even shorter (33 bytes), but fails for `x = 0`: ``` F(x){return!x?:(x%16>9)*F(x/16);} ``` --- ``` b;F(x){for(b=x;x;x/=16)b*=x%16>9;return b;} ``` `F()` takes an `int` and returns either `0` (false) or non-zero (true). I didn't even try to achieve the bonus, `"MixOnly lettersnumbers"` takes 23 bytes alone, tracking the new condition would have required 9 additional bytes, `printf()` is 8 bytes, which adds up to 40, nullifying the effort. Test main: ``` #include <stdio.h> int main() { int testdata[] = {10, 100, 161, 11259375, 0}; for (int i = 0; i < 5; ++i) { int d = testdata[i]; printf("%d (0x%x) -> %s\n", d, d, F(d)?"yep":"nope"); } } ``` [Answer] # Python 3, ~~30~~ 29 bytes 1 byte stripped thanks to [sysreq](https://codegolf.stackexchange.com/users/46231/sysreq) and Python 3. ``` lambda n:hex(n)[2:].isalpha() ``` Simple `lambda` and slicing. [Answer] # [Perl 6](http://perl6.org), 18 bytes ``` {.base(16)!~~/\d/} # 18 bytes ``` usage: ``` # give it a name my &code = {.base(16)!~~/\d/} for 10, 100, 161, 11259375, 0 { printf "%8s %6s %s\n", $_, .base(16), .&code } 10 A True 100 64 False 161 A1 False 11259375 ABCDEF True 0 0 False ``` [Answer] ## Mathematica, 32 bytes ``` Tr@DigitCount[#,16,0~Range~9]<1& ``` Explanation: ``` & A function returning whether Tr@ the sum of elements of DigitCount[ , , ] the numbers of 0~Range~9 zeros, ones, ..., nines in 16 the hexadecimal expansion of # the first argument <1 is less than one. ``` [Answer] # Javascript, ES6, no regexp, 28 bytes ``` F=n=>n%16>9&&(n<16||F(n>>4)) ``` There's also this 27-byte version but it returns the inverse value. ``` F=n=>n%16<10||n>15&&F(n>>4) ``` [Answer] # Julia, 18 bytes ``` n->isalpha(hex(n)) ``` This is an anonymous function that accepts an integer and returns a boolean. To call it, give it a name, e.g. `f=n->...`. The input is converted to a hexadecimal string using `hex`, then we check whether its entirely comprised of alphabetic characters using `isalpha`. [Answer] # JavaScript ES6, 29 No bonus ``` n=>!/\d/.test(n.toString(16)) ``` With the new value of **-40** the bonus is nearer now ... but not enough. Bonus score 70 ~~71~~ - 40 => **30 ~~31~~** ``` n=>/\d/.test(n=n.toString(16))?1/n?'Only numbers':'Mix':'Only letters' ``` Test snippet (type a number inside the input box) ``` #I { width:50%} ``` ``` <input id=I oninput="test()"/><br> Hex <span id=H></span><br> Result <span id=R></span> ``` [Answer] # [GS2](http://github.com/nooodl/gs2), 6 bytes ``` V↔i/◙s ``` The source code uses the CP437 encoding. [Try it online!](http://gs2.tryitonline.net/#code=VuKGlGkv4peZcw&input=MTEyNTkzNzU) ### How it works ``` V Evaluate the input. ↔ Push 16. i Perform base conversion. / Sort. ◙ Push [10]. s Perform greater-or-equal comparison. ``` [Answer] # Octave, 22 bytes ``` @(n)all(dec2hex(n)>64) ``` [Answer] # Ruby, 19 bytes ``` ->n{!('%x'%n)[/\d/]} ``` **Ungolfed:** ``` -> n { !('%x'%n)[/\d/] } ``` **Usage:** ``` f=->n{!('%x'%n)[/\d/]} # Assigning it to a variable f[0] => false f[10] => true f[100] => false f[161] => false f[11259375] => true ``` **With bonus, 70 - 40 = 30 bytes** ``` ->n{'%x'%n=~/^(\d+)|(\D+)$/;$1?'Only numbers':$2?'Only letters':'Mix'} ``` **Usage:** ``` f=->n{'%x'%n=~/^(\d+)|(\D+)$/;$1?'Only numbers':$2?'Only letters':'Mix'} f[10] => Only letters f[100] => Only numbers f[161] => Mix ``` [Answer] # Java, ~~46~~ ~~44~~ 38 bytes ``` i->i.toHexString(i).matches("[a-f]+"); ``` Pretty simple one-liner that converts the integer to a hexadecimal string and uses regex to determine if all characters are letters. -2 bytes thanks to @Eng.Fouad. [Answer] ## CJam (9 8 bytes) ``` {GbA,&!} ``` [Online demo](http://cjam.aditsu.net/#code=%7BGbA%2C%26!%7D%0A%0A%5B10%20100%20161%2011259375%200%5D%25%60) [Answer] ## Perl, 69 - 40 = 29 bytes ``` $_=sprintf"%X",<>;print s/\d//?$_?"Mix":"Only numbers":"Only letters" ``` [Answer] ## Ceylon, 55 bytes ``` Boolean l(Integer n)=>!any(formatInteger(n,16)*.digit); ``` Straightforward ... we format `n` as a hexadecimal number (which produces a string), call on each character of that string the `.digit` number (which returns true if it is a digit), then check whether any of them are true, then negate this. The version with bonus has a lot higher score of **119 - 25 = 94**: ``` String c(Integer n)=>let(s=formatInteger(n),d=s*.digit)(every(d)then"Only numbers"else(any(d)then"Mix"else"Only letters")); ``` I'm not sure how anyone could make a bonus version short enough to be better than the no-bonus version, even those strings alone have length 28 together. Maybe a language which makes it really hard to produce a truthy/falsey value. Here is a formatted version: ``` String c(Integer n) => let (d = formatInteger(n,16)*.digit) (every(d) then "Only numbers" else (any(d) then "Mix" else "Only letters")); ``` [Answer] ## Rust, 70 bytes ``` fn f(n:i32)->bool{format!("{:x}",n).chars().all(|c|c.is_alphabetic())} ``` Because, ya know, ~~Java~~ Rust. It's actually quite elegant, though: ``` format!("{:x}", n) // format n as hex (:x) .chars() // get an Iter over the characters .all( // do all Iter elements satisfy the closure? |c| c.is_alphabetic() // self-explanatory ) ``` But it's a shame the function definition boilerplate is so long.... :P [Answer] # CJam, 44 bytes - 40 bonus = 4 bytes ``` 2,riGbAf/&:-"Only numbersOnly lettersMix"C/= ``` [Try it here~](http://cjam.aditsu.net/#code=2%2CriGbAf%2F%26%3A-%22Only%20numbersOnly%20lettersMix%22C%2F%3D&input=10) [Answer] ## Seriously, 12 bytes ``` 4ª,¡OkúOkd-Y ``` Hex Dump: ``` 34a62cad4f6b a34f6b642d59 ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=34a62cad4f6ba34f6b642d59&input=255) It's the same as the other stack language answers. It would be only 7 bytes if Seriously supported string subtraction yet. EDIT: Seriously now supports string subtraction and the following 7 byte solution now works: ``` ú4╙,¡-Y ``` Hex Dump: ``` a334d32cad2d59 ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=a334d32cad2d59&input=100) [Answer] # Python 3, 28 bytes ``` lambda x:min(hex(x)[1:])>'@' ``` [Answer] # Common Lisp, 40 bytes ``` (every'alpha-char-p(format()"~x"(read))) ``` [Try it online!](https://tio.run/##S87JLC74r1FQlJmX/F8jtSy1qFI9MacgI1E3OSOxSLdAIy2/KDexRENTqa5CSaMoNTFFU1Pzv@Z/QzNDAA) [Answer] # SmileBASIC 3.2.1, 78 bytes ``` INPUT V FOR I=0 TO 9 IF INSTR(HEX$(V),STR$(I))>-1 THEN ?"FALSE"END NEXT?"TRUE" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes Code: ``` ha ``` Ha! That is two bytes! ~~Sadly non-competing because this language postdates the challenge :(~~ Explanation: ``` h # Convert input to hexadecimal a # is_alpha, checks if the value only contains letters ``` [Try it online!](http://05ab1e.tryitonline.net/#code=aGE&input=MTEyNTkzNzU) or [Verify all test cases!](http://05ab1e.tryitonline.net/#code=W0lExb0KCj8iIHlpZWxkcyAiP2hhLAoKXQ&input=MTAKMTAwCjE2MQoxMTI1OTM3NQow) [Answer] # Japt, 12 bytes ``` !UsG r"[a-f] ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=IVVzRyByIlthLWZd&input=MTEyNTkzNzU=) ### How it works ``` !UsG r"[a-f] // Implicit: U = input integer, G = 16 UsG // Convert U to a base-16 string. r"[a-f] // Replace all lowercase letters with an empty string. ! // Take the logical NOT of the result. // This returns true for an empty string; false for anything else. ``` [Answer] # Gema, 41 characters ``` *=@c{@radix{10;16;*}} c:<D>=f@end;?=;\Z=t ``` There is no boolean in Gema, so it simply outputs “t” or “f”. Sample run: ``` bash-4.3$ echo -n '11259375' | gema '*=@c{@radix{10;16;*}};c:<D>=f@end;?=;\Z=t' t ``` ]
[Question] [ ### Challenge Given a nonempty list of real numbers, compute its median. ### Definitions The median is computed as follows: First sort the list, * if the number of entries is *odd*, the median is the value in the center of the sorted list, * otherwise the median is the arithmetic mean of the two values closest to the center of the sorted list. ### Examples ``` [1,2,3,4,5,6,7,8,9] -> 5 [1,4,3,2] -> 2.5 [1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] -> 1.5 [1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] -> 1.5 ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes An unnamed function which returns the result. -1 byte thanks to xnor. ``` lambda l:l.sort()or(l[len(l)/2]+l[~len(l)/2])/2. ``` The first step is obviously to sort the array, using `l.sort()`. However, we can only have one statement in a lambda, so we utilise the fact that the sort function returns `None` by adding an `or` - as `None` is falsy in Python, this tells it to evaluate and return the next part of the statement. Now we have the sorted list, we need to find either the middle, or the middle two, values. Using a conditional to check the length's parity would be too verbose, so instead we get the indexes `len(l)/2` and `~len(l)/2`: * The first is **floor(length / 2)**, which gets the middle element if the length is odd, or the left item in the central pair if the length is even. * The second is the binary inversion of the list length's, evaluating to **-1 - floor(length / 2)**. Due Python's negative indexing, this essentially does the same as the first index, but backwards from the end of the array. If the list is of odd length, these indexes will point to the same value. If it is of even length, then they will point to the central two items. Now that we have these two indexes, we find these values in the list, sum them, and divide them by 2. The trailing decimal place in `/2.` makes sure that it is float division rather than integer division. The result is implicitly returned, as this is a lambda function. [**Try it online!**](https://tio.run/nexus/python2#@5@mYKuQk5iblJKokGOVo1ecX1SioZlfpJETnZOap5GjqW8Uq50TXQfnALHe/4KizLwSjTSNzLyCUqByTc3/0YY6JjpGOsax/wE) [Answer] # Python3 - ~~31~~ 30 bytes *Saved a byte thanks to @Dennis!* I wasn't planning on a builtin answer, but I found [this module](https://docs.python.org/3/library/statistics.html) and thought it was really cool cuz I had no idea it existed. ``` from statistics import*;median ``` [Try it online here](http://vihan.org/p/tio/?l=python3&p=KyjKzCvRiI/PzC3ILyqJj9dQLy5JLMksLslMLlbX1MtNTclMzNNILUvM0cjMKygt0dAEgv/RhnqmOoSwLpAyAAEgzxiITWIB). [Answer] ## [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` L‘HịṢµ÷LS ``` [Try it online!](https://tio.run/nexus/jelly#AR4A4f//TOKAmEjhu4vhuaLCtcO3TFP///9bMSw0LDMsMl0 "Jelly – TIO Nexus") ### Explanation I'm still getting the hang of Jelly... I wasn't able to find built-ins for either the median or the mean of a list, but it's very convenient for this challenge that Jelly allows non-integer indices into lists, in which case it will return a pair of the two closest values. That means we can work with half the input length as an index, and get a pair of values when we need to average it. ``` L Get the length of the input. ‘ Increment it. H Halve it. This gives us the index of the median for an odd-length list (Jelly uses 1-based indexing), and a half-integer between the two indices we need to average for even-length lists. ịṢ Use this as an index into the sorted input. As explained above this will either give us the median (in case of an odd-length list) or a pair of values we'll now need to average. µ Starts a monadic chain which is then applied to this median or pair... ÷L Divide by the length. L treats atomic values like singleton lists. S Sum. This also treats atomic values like singleton lists. Hence this monadic chain leaves a single value unchanged but will return the mean of a pair. ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 914 + 1 = 915 bytes ``` ([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{}([]<(()())>(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}<(())>){((<{}{}([[]]()){({}()()<{}>)}{}(({}){}<([]){{}{}([])}{}>)>))}{}{(<{}([[]]()()){({}()()<{}>)}{}({}{}<([]){{}{}([])}{}>)>)}{}([(({}<((((((()()()){}){}){}()){})[()()()])>)<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}(({}<>)<{(<{}([{}])>)}{}{(({})<((()()()()()){})>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})({}<({}<>)<>>((((()()()){}){}){}){})((()()()()()){})<>({}<>)(()()){({}[()]<([([({})](<()>))](<>())){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}(({})<>)<>{(<{}([{}])>)}{}({}<>)<>({}<><({}<>)>)>)}{}({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)<>(({}{}[(())])){{}{}(((<{}>)))}{}{}{(<{}<>([{}])><>)}{}<>}{}>){(<{}(((((()()()()())){}{})){}{})>)}{} ``` Requires the `-A` flag to run. [Try it online!](https://tio.run/nexus/brain-flak#lVNbasQwDLyKP6WPfDR9QMAYeg6jkxifPdVo5H2RQrubbCxbI81MtKd00yFjdlGrgqjew@7fMX17TK3NL9wVW02bxYlqUxOPo4qHtU1/IqUOXzUdWEugiGSZrKIrO7YnVg5C@wdaz@fEdNBV9I/uDguaNxSJBEA6mN35emZwk97NZDEXVz5ZG4WQDW@YaBpavJE/B@AJvoIDcgmOSGhpfJQFJi8uO3fN83/1FyaFMkrOINNTASxLpmMa9@lRXZ1X96ao/Wcb9eldXgjB9dpjvXG5efY4Y9AosBda/fzfajmfr3oXSc7jGrl1lIoFRIZovVLO/jnKpIBjb21JRWKavFIYzOGgWU6i5szynxDs7n6FEwpQ/kbyeX6Vj7If5e0oe9k@y7aXo2zvvndu3z8 "Brain-Flak – TIO Nexus") # Explanation The backbone of this algorithm is a bubble sort I wrote a while ago. ``` ([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{} ``` I don't remember how this works so don't ask me. But I do know it sorts the stack and even works for negatives After everything has been sorted I find 2 times the median with the following chunk ``` ([]<(()())>(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}<(())>) #Stack height modulo 2 {((<{}{} #If odd ([[]]()) #Push negative stack height +1 { #Until zero ({}()()<{}>) #add 2 to the stack height and pop one }{} #Get rid of garbage (({}){}< #Pickup and double the top value ([]){{}{}([])}{} #Remove everything on the stack >) #Put it back down >))}{} #End if {(<{} #If even ([[]]()()) #Push -sh + 2 {({}()()<{}>)}{} #Remove one value for every 2 in that value ({}{}<([]){{}{}([])}{}>)#Add the top two and remove everything under them >)}{} #End if ``` Now all that is left is to make convert to ASCII ``` ([(({}<((((((()()()){}){}){}()){})[()()()])>)<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}(({}<>)< {(<{}([{}])>)}{} #Absolute value (put "/2" beneath everything) { #Until the residue is zero (({})< #|Convert to base 10 ((()()()()()){}) #| >) #|... ({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}) ({}<({}<>)<>>((((()()()){}){}){}){})((()()()()()){})<>({}<>) #| (()()){({}[()]<([([({})](<()>))](<>())){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}(({})<>)<>{(<{}([{}])>)}{}({}<>)<>({}<><({}<>)>)>)}{}({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)<>(({}{}[(())])){{}{}(((<{}>)))}{}{}{(<{}<>([{}])><>)}{}<> }{} #| >) {(<{}(((((()()()()())){}{})){}{})>)}{} #If it was negative put a minus sign ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 1 byte ``` ║ ``` [Try it online!](https://tio.run/nexus/actually#@/9o6sT//6MN9Ux1CGFdIGUAAkCeMRCbxAIA "Actually – TIO Nexus") [Answer] # R, 6 bytes ``` median ``` Not surprising that R, a statistical programming language, has this built-in. [Answer] # Matlab/Octave, 6 bytes A boring built-in: ``` median ``` [Try it online!](https://tio.run/nexus/octave#@5@bmpKZmKcRbahjomOsYxSr@f8/AA "Octave – TIO Nexus") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes ``` ≢⊃2+/2/⊂∘⍋⌷÷∘2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHnYsedTUbaesb6T/qanrUMeNRb/ejnu2HtwOZRkAlh1ZoGOoY6RjrmOiY6pjpmOtY6FhqAoVMgEJGQIaeqQ4hfGg9kDYAASDXGIhNiNOHQy8A "APL (Dyalog Unicode) – Try It Online") This is a train. The original dfn was `{(2+/2/⍵[⍋⍵])[≢⍵]÷2}`. The train is structured as follows ``` ┌─┼───┐ ≢ ⊃ ┌─┼───┐ 2 / ┌─┼───┐ ┌─┘ 2 / ┌─┼─┐ + ∘ ⌷ ∘ ┌┴┐ ┌┴┐ ⊂ ⍋ ÷ 2 ``` `⊢` denotes the right argument. `⌷` index * `⊂∘⍋` the indices which indexed into `⊢` results in `⊢` being sorted * `÷∘2` into `⊢` divided by 2 `2/` replicate this twice, so `1 5 7 8` becomes `1 1 5 5 7 7 8 8` `2+/` take the pairwise sum, this becomes `(1+1)(1+5)(5+5)(5+7)(7+7)(7+8)(8+8)` `⊃` from this pick * `≢` element with index equal to the length of `⊢` Previous solutions ``` {.5×+/(⍵[⍋⍵])[(⌈,⌊).5×1+≢⍵]} {+/(2/⍵[⍋⍵]÷2)[0 1+≢⍵]} {+/¯2↑(1-≢⍵)↓2/⍵[⍋⍵]÷2} {(2+/2/⍵[⍋⍵])[≢⍵]÷2} {(≢⍵)⊃2+/2/⍵[⍋⍵]÷2} ≢⊃2+/2/2÷⍨⊂∘⍋⌷⊢ ≢⊃2+/2/⊂∘⍋⌷÷∘2 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 38 bytes ``` @(x)mean(([1;1]*sort(x))(end/2+[0 1])) ``` This defines an anonymous function. Input is a row vector. [Try it online!](https://tio.run/nexus/octave#@@@gUaGZm5qYp6ERbWhtGKtVnF9UAhTS1EjNS9E30o42UDCM1dT8n2abmFdszZUGVKVjpGOsY6JjqmOmY65joWMZqwkRNgEKG0E5eqY6hLAukDIAASDPGIhNYjX/AwA "Octave – TIO Nexus") ### Explanation ``` sort(x) % Sort input x, of length k [1;1]* % Matrix-multiply by column vector of two ones % This vertically concatenates sort(x) with % itself. In column-major order, this effectively % repeats each entry of sort(x) ( )(end/2+[0 1]) % Select the entry at position end/2 and the next. % Entries are indexed in column-major order. Since % the array has 2*k elements, this picks the k-th % and (k+1)-th (1-based indexing). Because entries % were repeated, for odd k this takes the original % (k+1)/2-th entry twice. For even k this takes % the original (k/2)-th and (k/2+1)-th entries mean( ) % Mean of the two selected entries ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` .5Xq ``` This finds the 0.5-quantile, which is the median. [Try it online!](https://tio.run/nexus/matl#@69nGlH4/3@0oZ6pDiGsC6QMQADIMwZik1gA "MATL – TIO Nexus") [Answer] # Pyth - 11 bytes Finds the average of the middle item taken both backwards and forwards. ``` .O@R/lQ2_BS ``` [Test Suite](http://pyth.herokuapp.com/?code=.O%40R%2FlQ2_BS&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%5D%0A%5B1%2C4%2C3%2C2%5D%0A%5B1.5%2C1.5%2C1.5%2C1.5%2C1.5%2C1.5%2C1.5%2C1.5%2C1.5%2C-5%2C100000%2C1.3%2C1.4%5D&debug=0). [Answer] # JavaScript, 57 52 bytes ``` v=>(v.sort((a,b)=>a-b)[(x=v.length)>>1]+v[--x>>1])/2 ``` Sort the array numerically. If the array is an even length, find the 2 middle numbers and average them. If the array is odd, find the middle number twice and divide by 2. [Answer] # Mathematica, 6 bytes ``` Median ``` As soon as I figure out [Mthmtca](https://github.com/LegionMammal978/Mthmtca), I'm posting a solution in it. [Answer] # [Perl 6](https://perl6.org), 31 bytes ``` *.sort[{($/=$_/2),$/-.5}].sum/2 ``` [Try it](https://tio.run/nexus/perl6#hY7BTsMwDIbveQofoiXp3ASydoBKCw/BrVTT1Aap0kqnJUWgaU/EW/BixSkHjrNk2b9/f7In7@Bjq9uCTdS9OB8KxoYvWLVj56CcE@3HU6jPkpuS74xVyE2q80uj/TQYOxfsbTzBoX93Xio4MwCCn7t92EMJ65/vwYhawKPUyZOqQDTCaH889EEKFKr4W@fu8@ja4LqIEJBWAl59QhQQBsRFxQ19BtB7iK/J5YbCf5jaHbvM9S1a3GCGOW7xDu/xoYG0gpyRkZFhF2l1HOgcr2VK5SYGqQ1ltuDk/AI "Perl 6 – TIO Nexus") ## Expanded: ``` *\ # WhateverCode lambda ( this is the parameter ) .sort\ # sort it [{ # index into the sorted list using a code ref to calculate the positions ( $/ = $_ / 2 # the count of elements divided by 2 stored in 「$/」 ), # that was the first index $/ - .5 # subtract 1/2 to get the second index # indexing operations round down to nearest Int # so both are effectively the same index if given # an odd length array }]\ .sum / 2 # get the average of the two values ``` [Answer] # TI-Basic, 2 bytes ``` median(Ans ``` Very straightforward. [Answer] # [J](http://jsoftware.com/), ~~16~~ 14 bytes ``` 2%~#{2#/:~+\:~ ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjUGulYKAAxP@NVOuUq42U9a3qtGOs6v5rcqUmZ@QrpCkYKhgrmCqYKRgpmCgYYRH8DwA "J – Try It Online") In addition to [BMO's array duplication trick](https://codegolf.stackexchange.com/a/173080/78410), I found that we can add the whole array sorted in two directions. Then I realized that the two steps can be reversed, i.e. add the two arrays, *then* duplicate them and take the `n`th element. ### How it works ``` 2%~#{2#/:~+\:~ Input: array of length n /:~ Sort ascending \:~ Sort descending + Add the two element-wise 2# Duplicate each element #{ Take n-th element 2%~ Halve ``` --- # Previous answers ## [J](http://jsoftware.com/) with `stats` addon, 18 bytes ``` load'stats' median ``` [Try it online!](https://tio.run/##y/rv56SnoKSnoJ6mYGulrqCjUGulYKAAxP9z8hNT1ItLEkuK1blyU1MyE/PAajW5UpMz8hUgIgqGCsYKpgpmCkYKJgpGuGT@AwA "J – Try It Online") Library function FTW. `median`'s implementation looks like this: ## [J](http://jsoftware.com/), 31 bytes ``` -:@(+/)@((<.,>.)@(-:@<:@#){/:~) ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/3WtHDS09TUdNDRs9HTs9IAMoIiNlYOyZrW@VZ3mf02u1OSMfIU0BUMFYwVTBTMFIwUTBSMsgv8B "J – Try It Online") ### How it works ``` -:@(+/)@((<.,>.)@(-:@<:@#){/:~) (<.,>.)@(-:@<:@#) Find center indices: -:@<:@# Compute half of given array's length - 1 <.,>. Form 2-element array of its floor and ceiling {/:~ Extract elements at those indices from sorted array -:@(+/) Sum and half ``` A bit of golfing gives this: ## [J](http://jsoftware.com/), 28 bytes ``` 2%~[:+/(<.,>.)@(-:@<:@#){/:~ ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjUGulYKAAxP@NVOuirbT1NWz0dOz0NB00dK0cbKwclDWr9a3q/mtypSZn5CukKRgqGCuYKpgpGCmYKBhhEfwPAA "J – Try It Online") [Answer] ## Common Lisp, 89 ``` (lambda(s &aux(m(1-(length s)))(s(sort s'<)))(/(+(nth(floor m 2)s)(nth(ceiling m 2)s))2)) ``` I compute the mean of elements at position `(floor middle)` and `(ceiling middle)`, where `middle` is the zero-based index for the middle element of the sorted list. It is possible for `middle` to be a whole number, like `1` for an input list of size 3 such as `(10 20 30)`, or a fraction for lists with an even numbers of elements, like `3/2` for `(10 20 30 40)`. In both cases, we compute the expected median value. ``` (lambda (list &aux (m (1-(length list))) (list (sort list #'<))) (/ (+ (nth (floor m 2) list) (nth (ceiling m 2) list)) 2)) ``` [Answer] # Vim, 62 bytes I originally did this in V using only text manipulation until the end, but got frustrated with handling [X] and [X,Y], so here's the easy version. They're about the same length. ``` c$:let m=sort(")[(len(")-1)/2:len(")/2] =(m[0]+m[-1])/2.0 ``` [Try it online!](https://tio.run/nexus/v#@5@swm@Vk1qikGtbnF9UoiGkpBmtkZOaB2LoGmrqG1lBOfpGsVxCthq50Qax2rnRuoaxQBE9g///ow31THUIYV0gZQACQJ4xEJvEAgA "V – TIO Nexus") Unprintables: ``` c$^O:let m=sort(^R")[(len(^R")-1)/2:len(^R")/2] ^R=(m[0]+m[-1])/2.0 ``` Honorable mention: * `^O` takes you out of insert mode for one command (the let command). * `^R"` inserts the text that was yanked (in this case the list) [Answer] # C#, 126 bytes ``` using System.Linq;float m(float[] a){var x=a.Length;return a.OrderBy(g=>g).Skip(x/2-(x%2==0?1:0)).Take(x%2==0?2:1).Average();} ``` Pretty straightforward, here with LINQ to order the values, skip half the list, take one or two values depending on even/odd and average them. [Answer] # C++ 112 Bytes Thanks to @original.legin for helping me save bytes. ``` #include<vector> #include<algorithm> float a(float*b,int s){std::sort(b,b+s);return(b[s/2-(s&1^1)]+b[s/2])/2;} ``` Usage: ``` int main() { int n = 4; float e[4] = {1,4,3,2}; std::cout<<a(e,n); /// Prints 2.5 n = 9; float e1[9] = {1,2,3,4,5,6,7,8,9}; std::cout<<a(e1,n); /// Prints 5 n = 13; float e2[13] = {1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4}; std::cout<<a(e2,n); /// Prints 1.5 return 0; } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ½ΣF~e→←½OD ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/h/ae26xW13qo7ZJj9omHNrr7/L///9oQx0jHWMdEx1THTMdcx0LHctYLqCYCVDMCMTSM9UhhHWBlAEIAHnGQGxCpD7segE "Husk – Try It Online") ### Explanation This function uses that the median of \$[a\_1 \dots a\_N]\$ is the same as the median of \$[a\_1 \; a\_1 \dots a\_N \; a\_N]\$ which avoids the ugly distinction of odd-/even-length lists. ``` ½ΣF~e→←½OD -- example input: [2,3,4,1] D -- duplicate: [2,3,4,1,2,3,4,1] O -- sort: [1,1,2,2,3,3,4,4] ½ -- halve: [[1,1,2,2],[3,3,4,4]] F -- fold the following ~ -- | compose the arguments .. → -- | | last element: 2 ← -- | | first element: 3 e -- | .. and create list: [2,3] -- : [2,3] Σ -- sum: 5 ½ -- halve: 5/2 ``` Unfortunately `½` for lists has the type `[a] -> [[a]]` and not `[a] -> ([a],[a])` which doesn't allow `F~+→←` since `foldl1` needs a function of type `a -> a -> a` as first argument, forcing me to use `e`. [Answer] # [Fig](https://github.com/Seggan/Fig), \$11\log\_{256}(96)\approx\$ 9.054 bytes ``` KY HSt2s{HL ``` [Try it online!](https://fig.fly.dev/#WyJLWVxuSFN0MnN7SEwiLCJbMSw0LDMsMl0iXQ==) -3 chars because bugfixes ``` KY HSt2s{HL -------- KY # First helper function Y # Interleave with self K # Sort -------- # Send the result to the next function: HSt2s{HL # Main function {HL # Compute len(input)/2-1 s # Drop that many items from the input t2 # Take 2 S # Sum H # Halve ``` [Answer] # J, 19 bytes ``` <.@-:@#{(/:-:@+\:)~ ``` Explanation: ``` ( )~ apply monadic argument twice to dyadic function /: /:~ = sort the list upwards \: \:~ = sort the list downwards -:@+ half of sum of both lists, element-wise <.@-:@# floor of half of length of list { get that element from the list of sums ``` [Answer] # JavaScript, 273 Bytes ``` function m(l){a=(function(){i=l;o=[];while(i.length){p1=i[0];p2=0;for(a=0;a<i.length;a++)if(i[a]<p1){p1=i[a];p2=a}o.push(p1);i[p2]=i[i.length-1];i.pop()}return o})();return a.length%2==1?l[Math.round(l.length/2)-1]:(l[Math.round(l.length/2)-1]+l[Math.round(l.length/2)])/2} ``` [Answer] # Java 7, 99 bytes Golfed: ``` float m(Float[]a){java.util.Arrays.sort(a);int l=a.length;return l%2>0?a[l/2]:(a[l/2-1]+a[l/2])/2;} ``` Ungolfed: ``` float m(Float[] a) { java.util.Arrays.sort(a); int l = a.length; return l % 2 > 0 ? a[l / 2] : (a[l / 2 - 1] + a[l / 2]) / 2; } ``` [Try it online](https://ideone.com/bEhZOY) [Answer] # Pari/GP - 37 ~~39~~ Bytes Let *a* be a rowvector containing the values. ``` b=vecsort(a);n=#b+1;(b[n\2]+b[n-n\2])/2 \\ 39 byte n=1+#b=vecsort(a);(b[n\2]+b[n-n\2])/2 \\ obfuscated but only 37 byte ``` Since Pari/GP is interactive, no additional command is needed to display the result. --- For the ***"try-it-online"*** link a line before and after is added. To get printed, the median-result in stored in variable *w* ``` a=vector(8,r,random(999)) n=1+#b=vecsort(a);w=(b[n\2]+b[n-n\2])/2 print(a);print(b);print(w) ``` [Try it online!](https://tio.run/nexus/pari-gp#@59oW5aaXJJfpGGhU6RTlJiXkp@rYWlpqanJlWtrqK2cBJIuzi8q0UjUtC631UiKzo0xitUGUroghqa@EVdBUWYeWBrCSIIxyjX//wcA "Pari/GP – TIO Nexus") [Answer] # Japt, 20 bytes ``` n gV=0|½*Ul)+Ug~V)/2 ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=biBnVj0wfL0qVWwpK1VnflYpLzI=&input=WzEgNCA5IDE2IDI1IDM2XQ==) Japt really lacks any built-ins necessary to create a really short answer for this challenge... ### Explanation ``` n gV=0|½*Ul)+Ug~V)/2 // Implicit: U = input list n // Sort U. V=0|½*Ul) // Set variable V to floor(U.length / 2). g // Get the item at index V in U. +Ug~V // Add to that the item at index -V - 1 in U. )/2 // Divide by 2 to give the median. // Implicit: output result of last expression ``` [Answer] # Java 8, 71 bytes Parity is fun! Here's a lambda from `double[]` to `Double`. ``` l->{java.util.Arrays.sort(l);int s=l.length;return(l[s/2]+l[--s/2])/2;} ``` Nothing too complex going on here. The array gets sorted, and then I take the mean of two numbers from the array. There are two cases: * If the length is even, then the first number is taken from just ahead of the middle of the array, and the second number is taken from the position before that by integer division. The mean of these numbers is the median of the input. * If the length is odd, `s` and `s-1` both divide to the index of the middle element. The number is added to itself and the result divided by two, yielding the original value. [Try It Online](https://tio.run/##lY9NS8QwEIbP3V8xxxY3WawfCHUXBPHmaY@lh9jEmjqdlGRaKUt/e826Fc8e3uGF4RmeadWohOsNtfpz6Yc3tDXUqEKAV2UJTpuk93ZUbCCw4rhsIyAHtijfB6rZOpIva3nULh4wZbWF5592gM5oqwj2C4rD6Q998l5NQQbnOcWssMQQ9ijRUMMfhTc8eEqxDLu8usJSiHPJdnkxL0kRjS6aq9DorIYuyqZH9paasgLlm5Cd3ZPjFNh00g0s4x/ESOlFSaq@xykl8wW/1nASd3oLNzHiNo4HPWdZ8e8j9xHNY65XfN7Myzc) [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~120~~ 122 bytes ``` 9kzsa0si[li:sli1+dsila>A]dsAx[1scddd;sr1-;sli:sr1-:s]sR[lidd1-;sr;s<R1+dsila>S]sS[1si0sclSxlc1=M]dsMxla2/dd1%-;sr.5-;s+2/p ``` [Try it online!](https://tio.run/##NYyxCsMwEEN/JUun0MZnaGjitJAPyBKPwYPxLaY3lGgx/Xn3PHSRhHgSp2o7ssaYbpy6R3Ma6/T@IhrkQ/IMydQzssTXGhhrOQiJmR1Oujo0QsOMgF1x5laeDsv@X/kAr5tskMQXSfTc9GcrEu2g@KXxt7tqb4dPrT8 "dc – Try It Online") *My original code worked for all the provided test cases, but was actually faulty, so +2 bytes for the fix. Dang!* Lots of bytes since `dc` doesn't have any inbuilt sorting mechanism, and very little in the way of stack manipulation. `9k` sets the precision to 9 places since we need the possibility of digits past the decimal point. `dc` doesn't float, so hopefully this is satisfactory. `zsa0si[li:sli1+dsila>A]dsAx` dumps the entirety of the stack into array `s`, and preserves the number of items in register `a`. Macros `M`, `S`, and `R` all make up a bubble sort. `M` is our 'main' macro, so to speak, so I'll cover that one first. `[1si0sclSxlc1=M]dsMx` We reset increment register `i` to 1, and check register `c` to 0. We run macro `S`, which is one pass through the array. If `S` (actually, `R`, but `S` by proxy) made any changes, it would have set register `c` to one, so if this is the case we loop through `M` again. `[lidd1-;sr;s<R1+dsila>S]sS` One pass through the array. We load the increment counter `i`, duplicate it twice, and decrement the top version of it by one. Essentially `i` is always high, so we compare `i` and `i-1`. Load the two values from array `s`, compare them, and if they're going the wrong way we run our swapping macro, `R`. Then we keep on incrementing `i`, comparing it to `a`, and running `S` until that comparison tells us we've hit the end of our array. `[1scddd;sr1-;sli:sr1-:s]sR` An individual instance of swappery in array `a`. First we set our check register `c` to 1 so that `M` knows we made changes to the array. `i` should still be on the stack from earlier, so we duplicate it three times. We retrieve `i` indexed item from `a`, swap our top-of-stack so that `i` is present again, subtract one from it, and then retrieve that item from `a`. Here we run into a stack manipulation limitation, so we have to load `i` again and we store our previous `i-1` value into that index in `a`. Now we just have our old `i`-indexed `a` value on the stack and `i` itself, so we swap these, subtract 1 from `i`, and replace the value in `a`. Eventually `M` will stop running when it sees no changes have been made, and now that things are sorted we can do the actual median operation. `la2/dd1%-;sr.5-;s+2/p` Since `a` already has the length of array `s`, we load it and divide by two. Testing for evenness would be costly, so we rely on the fact that dc uses the floor of a non-whole value for its index. We divide `a` by two and duplicate the value. We then get from `s` the values indexed by (`a`/2-.5) and (`a`/2-((`a`/2)mod 1)). This gives us the middle value twice for an odd number of values, or the middle two values for an even number. `+2/p` averages them and prints the result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Æṁ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Odjf///4821DPVIYR1gZQBCAB5xkBsEgsA "Jelly – Try It Online") ]
[Question] [ Output terminal dimensions (columns and rows) [in any two-number decimal format](https://codegolf.stackexchange.com/questions/118402/tell-me-my-screen-resolution#comment290065_118402)\*. For example, an output could be `80x25`. --- [Inspiration](https://codegolf.stackexchange.com/q/118402/43319). [Prompt](https://codegolf.stackexchange.com/questions/118402/tell-me-my-screen-resolution?noredirect=1#comment290557_118402). \* Output must have both measures on a single or two consecutive lines, and there may be no more than one leading and/or trailing line of output (optionally followed by a newline). The (up to four) lines must be no longer than max(cols,1+len(str(cols))+len(str(ro‌​ws))). [Answer] # \*sh, 9 ``` stty size ``` Output: ``` 97 364 ``` [Answer] # 8086 machine code, 11 bytes (as a function, non-competing) Not really competing since it doesn't have visible output. This is just showing the shortest way to find the current screen dimensions, without the boilerplate code required for printing. ``` 00000000 6a 40 1f a0 84 00 40 8a 26 4a 00 |j@....@.&J.| 0000000b ``` ### How it works: ``` 6a 40 | push 0x40 ; bios data segment 1f | pop ds a0 84 00 | mov al, [0x84] ; console rows - 1 40 | inc ax 8a 26 4a 00 | mov ah, [0x4a] ; console columns ``` --- # 8086 machine code, 48 bytes (as a complete program) ``` 00000000 1f bf 30 01 a0 84 04 40 e8 1a 00 b0 78 aa a0 4a |[[email protected]](/cdn-cgi/l/email-protection)| 00000010 04 e8 11 00 8d 8d d0 fe 8d 75 ff 06 1f fd ac cd |.........u......| 00000020 29 e2 fb cd 20 d4 0a 0c 30 aa c1 e8 08 75 f6 c3 |)... ...0....u..| 00000030 ``` ### How it works: ``` | org 0x100 | use16 1f | pop ds ; clear ds (the stack always contains 0 on entry) bf 30 01 | mov di, d ; set destination ptr a0 84 04 | mov al, [0x484] ; console rows - 1 40 | inc ax e8 1a 00 | call to_ascii ; convert to ascii b0 78 | mov al, 'x' aa | stosb a0 4a 04 | mov al, [0x44a] ; console columns e8 11 00 | call to_ascii 8d 8d d0 fe | lea cx, [di-d] ; number of characters to print 8d 75 ff | lea si, [di-1] ; set source ptr 06 | push es 1f | pop ds fd | std ; reverse direction flag ac | @@: lodsb ; load (al = *si--) cd 29 | int 0x29 ; print al to console, bypassing stdout e2 fb | loop @b ; repeat while (--cx != 0) cd 20 | int 0x20 ; terminate | | to_ascii: d4 0a | aam 10 ; ah = (al / 10), al = (al % 10) 0c 30 | or al, 0x30 ; convert al to ascii number aa | stosb ; store (*di++ = al) c1 e8 08 | shr ax, 8 ; shift ah to al 75 f6 | jnz to_ascii ; repeat if non-zero c3 | ret | | d rb 0 ``` [Answer] # Bash, ~~22~~ 20 characters ``` echo $COLUMNS $LINES ``` Thanks to: * [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob) for optimal output format (2 characters) Sample run: ``` bash-4.3$ echo $COLUMNS $LINES 80 24 ``` [Answer] ## xterm, 6 bytes As you don't need specific formate, you can simply use the **`resize`** (6 character) command of `xterm`: ``` $ resize COLUMNS=120; LINES=31; export COLUMNS LINES; ``` [Answer] # sh, 20 bytes ``` tput lines;tput cols ``` .. Too obvious, maybe.. [Answer] # [Python 3](https://docs.python.org/3/), 30 bytes ``` import os os.get_terminal_size ``` As it does not work in TIO, an alternative is used there: [Try it online!](https://tio.run/nexus/python3#@5@ZW5BfVKJQnFFakpnDlWYLYeilp5bEl6QW5WbmJebEF2dWpf4vKMrMK9FI09DU/A8A "Python 3 – TIO Nexus") [Answer] # C (linux only), ~~63~~ 61 ``` short m[4];main(){ioctl(0,21523,m);printf("%dx%d",*m,m[1]);} ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 3 bytes (Posting an answer already since this really isn't my challenge.) `⎕SD` [**S**creen **D**imensions](http://help.dyalog.com/15.0/Content/Language/System%20Functions/sd.htm) Sample run: ``` ⎕SD 25 79 ``` [Answer] ## C#, 59 bytes ``` using c=System.Console;_=>c.WindowWidth+"x"+c.WindowHeight; ``` Compiles to a `Func<int, string`, however, the input is not used. [Answer] # NodeJS, ~~50~~ ~~48~~ 46 bytes ``` > s=process.stdout;console.log(s.columns,s.rows) 80 25 ``` Uses `process.stdout`s `columns` and `rows` values. [Answer] # Ruby, ~~41~~ ~~36~~ 21 + 13 = 34 bytes Run with the command line flag `-rio/console` ``` p IO.console.winsize ``` This is my first Ruby golf, so tell me if there is anything I can do better. *5 bytes saved thanks to SztupY* *2 bytes saved thanks to manatwork* --- This outputs height then width as a length two list. Example output: ``` [25, 80] ``` [Answer] # GNU Forth, 7 bytes ``` form .s ``` > > form – urows ucols gforth “form” > > > The number of lines and columns in the terminal. > > > ## Sample Output ``` <2> 24 80 ``` [Try It Online !](https://tio.run/nexus/forth-gforth#@5@WX5SroFf8/z8A) [Answer] # C# 94 bytes (whole app) MetaColon's whole app answer can be shortened quite a lot: ``` using c=System.Console;class P{static void Main(){c.Write(c.WindowWidth+' '+c.WindowHeight);}} ``` [Answer] # PowerShell + Mode, 11 Bytes? Output may not be acceptable in current form. the `mode` command is a default windows utility [Meta Post](https://codegolf.meta.stackexchange.com/questions/12268/making-assumptions-about-hardware) regarding usage of `mode` without specifying `con` ``` (mode)[3,4] ``` gets the output of mode: ``` <Whitespace> Status for device CON: ---------------------- Lines: 3000 Columns: 120 Keyboard rate: 31 Keyboard delay: 1 Code page: 850 ``` then the 4th & 5th lines (`[3,4]`) outputting: ``` PS H:\> (mode)[3,4] Lines: 3000 Columns: 120 ``` [Answer] # Swift, 99 bytes ``` import Foundation;var w=winsize();ioctl(STDOUT_FILENO,UInt(TIOCGWINSZ),&w);print(w.ws_col,w.ws_row) ``` Thanks to the guys at Vapor for their [Console package](https://github.com/vapor/console/blob/master/Sources/Console/Terminal/Terminal.swift#L175). [Answer] # Batch, ~~25~~ ~~19~~ ~~18~~ 17 bytes Saved 6 bytes by piping directly to the "find" command. Saved 1 byte thanks to [Adám / OP](https://codegolf.stackexchange.com/questions/118636/tell-me-my-console-dimensions/118681#comment290720_118681). ``` mode con|find "n" ``` This outputs the command itself since echo is on but, as [commented by OP](https://codegolf.stackexchange.com/questions/118636/tell-me-my-console-dimensions/118687#comment290692_118636), a leading line is OK. --- Depending on your setup, it may work with only 13 bytes. However, it seems that having anything using COM ports will cause overly verbose output. ``` mode|find "n" ``` [Answer] # C#, 85 Bytes ``` ()=>System.Console.Write(System.Console.WindowWidth+"x"+System.Console.WindowHeight); ``` If you want a whole application code, we'd have **115 101 94 Bytes**: ``` using C=System.Console;class P{static void Main()=>C.Write(C.WindowWidth+"x"+C.WindowHeight);} ``` However you could mean the *Buffer* size as well, we'd have **85 Bytes** again ``` ()=>System.Console.Write(System.Console.BufferWidth+"x"+System.Console.BufferHeight); ``` Or as a whole application code (obviously **115 101 94 Bytes** again): ``` using C=System.Console;class P{static void Main()=>C.Write(C.BufferWidth+"x"+C.BufferHeight);} ``` *Saved 14 Bytes in the whole application code with the help of Caius Jard* [Answer] # Java 8 (no libraries), Windows, 270 bytes [Posting seperately by recommendation of Adam.](http://chat.stackexchange.com/rooms/58225/discussion-between-meq5anlrk3lqs3kfsa5hbvstwe0niu-and-adam) ``` interface B{static void main(String[] a)throws Exception{Object[]r=new java.io.BufferedReader(new java.io.InputStreamReader(Runtime.getRuntime().exec("cmd /c mode").getInputStream())).lines().toArray();System.out.print(r[3]+"\n"+r[4]);}} ``` Ungolfed: ``` interface B { static void main(String[] a) throws Exception { Object[] r = new java.io.BufferedReader(new java.io.InputStreamReader( Runtime.getRuntime().exec("cmd /c mode").getInputStream()) ).lines().toArray(); System.out.print(r[3] + "\n" + r[4]); } } ``` [Answer] # [8th](http://8th-dev.com/), ~~24~~ ~~16~~ 12 bytes *Revised after Anders Tornblad comment.* ``` con:size? .s ``` Returns the current size of the console in rows and columns printing stack content. Output: ``` 2 n: 000000000285e5e0 1 300 1 n: 000000000285e4c0 1 90 ``` [Answer] # Java + \*nix, 113 ``` interface B{static void main(String[] a)throws Exception{new ProcessBuilder("stty","size").inheritIO().start();}} ``` Ungolfed: ``` interface B{ static void main(String[] a)throws Exception{ new ProcessBuilder("stty","size").inheritIO().start(); } } ``` `ProcessBuilder.inheritIO` causes a child process input/output to be inherited; this is the default in C with `exec`. In Java, the default is "piped." As you can see, this is way shorter than using `Runtime.getRuntime().exec()` (which is also deprecated) and constructing a `BufferedReader` through a long and convoluted call that is the result of the Java API designers' apparent unwillingness to add an overload for convenience. [Answer] # [Red](http://www.red-lang.org/), 19 Bytes ``` system/console/size ``` Output: ``` >> system/console/size == 106x26 ``` Can also get the screen resolution as in the previous [question](https://codegolf.stackexchange.com/a/118894/49214) [Answer] # Commodore 64 BASIC, 7 bytes ``` ?"40x25 ``` The C64 has a fixed-size text console of 40 x 25 characters. It is not necessary to query the console size, which is a good thing, as there is no way to query it. [Answer] # Kotlin + [Jline 2](https://github.com/jline/jline2), 58 bytes ``` {print(jline.TerminalFactory.get().run{"$width $height"})} ``` Because why not. Turns out the standard lib [actually has no way to determine console size](https://stackoverflow.com/a/1286677/7079453) so pulling in a library is required, lest you want to gold launching another process and parsing the input stream... [*would be a shame if somebody did that..*](https://codegolf.stackexchange.com/a/119012/62024) [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 7 bytes ``` termdim ``` Leaves output on the stack, as is allowed per default. Example usage: ``` λ stacked -pe "termdim" (117 26) ``` Bonus: `termdim'x'#`` to have it `117x26`. [Answer] # C (linux, C89 only), ~~45~~ 41 inspired by <https://codegolf.stackexchange.com/a/118696/42186> by @dieter ``` main(m){ioctl(0,21523,&m);write(1,&m,4);} ``` this outputs the size as binary data. Not sure if this counts as "any format". You would need something extra (less, hexdump, od, ascii table) (or an esoteric terminal emulator that automatically does this for you) to make it human readable. Example usage: ``` $ ./a.out | od -sAn 58 204 ``` The terminal size is 204 cols by 58 rows. Thanks to @Random832 for using `od` instead of `hexdump`. ]
[Question] [ **The Task** Your task is to create a program or a function that, given an input, outputs the input text with random letters capitalized, while keeping already capitalized letters capitalized. Every combination of capitalizations of the lowercase letters should be possible. For example, if the input was `abc`, there should be a non-zero probability of outputting any of the following combinations: `abc`, `Abc`, `aBc`, `abC`, `ABc`, `AbC`, `aBC` or `ABC`. **Input** Your input is a string, containing any number of printable ASCII characters, for example `Hello World`. The outputs for that input include `HeLLo WoRlD`, `HElLO WOrld`, etc. **Scoring** This is code-golf, so the shortest answer in each language wins! [Answer] # TI-Basic (83 series), 137 bytes ``` For(I,1,length(Ans Ans+sub(sub(Ans,I,1)+"ABCDEFGHIJKLMNOPQRSTUVWXYZ",1+int(2rand)inString("abcdefghijklmnopqrstuvwxyz",sub(Ans,I,1)),1 End sub(Ans,I,I-1 ``` Takes input in `Ans`, as illustrated in the screenshot below: [![enter image description here](https://i.stack.imgur.com/gvOR8.gif)](https://i.stack.imgur.com/gvOR8.gif) (If the screenshot looks scrambled, as it sometimes does for me, try [opening it in a new tab](https://i.stack.imgur.com/gvOR8.gif)?) TI-Basic (at least the TI-83 version... maybe I should branch out into TI-89 golfing) is a terrible language to try to golf this challenge in, since: 1. It provides absolutely no support for any arithmetic with characters, knowing the uppercase version of a lowercase character, or even knowing the alphabet. 2. Every single lowercase character takes 2 bytes to store. (In fact, I had to use an [assembly script](http://tibasicdev.wikidot.com/hexcodes#toc5) just to be able to type the lowercase letters.) The result is that 78 bytes of this program (more than half) are just storing the alphabet, *twice*. Anyway, the idea is that we loop through the string, with a chance of turning lowercase characters into uppercase ones as we go, and adding the result onto the end of the string so that both the input and the output are stored in `Ans`. When we leave the `For(` loop, `I` is one more than the length of the original string, so taking the `I-1` characters starting at `I` gives the output. [Answer] # [Python 2](https://docs.python.org/2/), 66 65 bytes ``` lambda s:`map(choice,zip(s.upper(),s))`[2::5] from random import* ``` [Try it online!](https://tio.run/##DcWxCoMwEADQ3a8ITndFOghdAt37Bx20YGoSDCS54xIH/fnoWx4fdaM8Nv@eWzTpb40qekmGYd0orG44A0N57sxOAIeCuEyj1q9f54WSEpPtXUhMUh@NJeQKHvqPi5HUlyTaHrFd "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` ®m`«`ö ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=rm1gq2D2&input=IkhlbGxvLCBXb3JsZCEi) ### Explanation ``` ®m`«`ö Implicit input ® Map each char in the input by m mapping each char in this char through `«`ö a random character of "us". (`«` is "us" compressed) The u function converts to uppercase, and s is slice, which does nothing here. Implicit output ``` [Answer] # C, ~~47~~ 46 bytes *Thanks to @l4m2 for saving a byte!* ``` f(char*s){for(;*s++-=(*s-97u<26&rand())*32;);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLM6Lb9Iw1qrWFtb11ZDq1jX0rzUxshMrSgxL0VDU1PL2Mha07r2f2ZeiUJuYmaehiZXNZcCEBSDFZRk5qZqGGhqWoPFQCYqFJcURRsbxUJEgJzkgkoNIKWjoOSRmpOTrxCeX5STogTVkQaSgrILSkuKodza/wA) **Would be 42 bytes, if it could be assumed that `{|}~` don't appear in the input:** ``` f(char*s){for(;*s++-=(*s>96&rand())*32;);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLM6Lb9Iw1qrWFtb11ZDq9jO0kytKDEvRUNTU8vYyFrTuvZ/Zl6JQm5iZp6GJlc1lwIQFIMVlGTmpmoYaGpag8VApikUlxRFGxvFQkSAnOSCSg0gpaOg5JGak5OvEJ5flJOiBNWRBpKCsgtKS4qh3Nr/AA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes *Another one bytes the dust thanks to dylnan.* ``` żŒuX€ ``` [Try it online!](https://tio.run/##y0rNyan8///onqOTSiMeNa35//@/B1AoX6E8vygnBQA "Jelly – Try It Online") ## Explanation ``` żŒuX€ main link: s = "Hello world" żŒu zip s with s uppercased ["HH", "eE", "lL", "lL", "oO", " ", ...] X€ map random choice "HeLLo woRlD" ``` [Answer] # [Perl 5](https://www.perl.org/), 23 bytes **22 bytes code + 1 for `-p`.** ``` s/./rand>.5?uc$&:$&/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0@/KDEvxU7P1L40WUXNSkVNPz31/3@P1JycfB2F8PyinBTFf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") [Answer] # JavaScript (ES6), 56 bytes ``` s=>s.replace(/./g,x=>Math.random()<.5?x.toUpperCase():x) ``` If uniform randomness is not required, we can save 6 bytes by using the current time as the source of randomness: ``` s=>s.replace(/./g,x=>new Date&1?x.toUpperCase():x) ``` This tends to either uppercase or leave alone all letters at once. [Answer] # [R](https://www.r-project.org/), 66 bytes ``` for(i in el(strsplit(scan(,""),"")))cat(sample(c(i,toupper(i)),1)) ``` [Try it online!](https://tio.run/##FcsxDoAgDEDRqxCmNmHxFt7AGaHGJoWSgoOnRxz@8pJvU/i0aC8UGrfmjvNSA3ZcHQn0Yb0JD@gpVgje4x9iiotiaUKQgMPQpzVaG2LYEKffSUTdoSbZzw8 "R – Try It Online") Another [R](https://www.r-project.org/) answer. [Answer] # Excel VBA, ~~74~~ ~~71~~ 64 Bytes ~~The `Randomize` call always makes random output costly in VBA :(~~ Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window. Produces a 50% (on average) `UCase`d output. ``` For i=1To[Len(A1)]:a=Mid([A1],i,1):?IIf(Rnd>.5,a,UCase(a));:Next ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~8~~ 7 bytes ``` ⭆S‽⁺↥ιι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKQYl5Kfm5GgE5pcUaoQUFqUXOicWpGplAmUxNILD@/98jNScnX0chPL8oJ0WR679uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string ι Character ↥ι Uppercase character ⁺ Concatenate ‽ Random element ⭆ Map over each character and join the result Implicitly print ``` [Answer] # Ruby, 40 Bytes Lambda function that takes a string. Saved 1 byte thanks to Arnauld. Saved 5 bytes thanks to Snack. ``` ->s{s.gsub(/./){|x|[x,x.upcase].sample}} ``` [Answer] # APL+WIN, 37 bytes ``` ⎕av[c-((n÷2)<n?n←⍴s)×32×s←98<c←⎕av⍳⎕] ``` Prompts for screen input, identifies lower case letters and randomly converts them to upper case. [Answer] # [R](https://www.r-project.org/), ~~89~~ 88 bytes *[outgolfed by djhurio!](http://codegolf.stackexchange.com/a/149518/13849)* ``` cat(sapply(el(strsplit(scan(,""),"")),function(x)"if"(rt(1,1)<0,toupper,`(`)(x)),sep="") ``` [Try it online!](https://tio.run/##FYsxDsIwDAC/gjzZkge6w84PWBtSV0QyieW4En19CMMtdzofWl6e/MSPxLttnUZOgT2Z6Ymi2MO7aZkqp4oMQH@I96PmKK3il6DsgB648EK3K0c7zMR5xZVmJe5i9/kMeIhquzyb6wbjBw "R – Try It Online") This program takes each character, and with probability 1/2 converts it to uppercase or leaves it alone. It's possible to tweak this probability by playing with different values of `df` and `0`. `rt` draws from the Student's t-distribution, which has median 0 with any degree of freedom (I selected `1` since it's the smallest number possible). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~52~~ ~~49~~ 44 bytes ``` StringReplace[c_/;Random[]<.5:>Capitalize@c] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T@4BEinB6UW5CQmp0Ynx@tbByXmpeTnRsfa6Jla2TknFmSWJOZkVqU6JMf@d1BQ8kjNycnXUSjPL8pJUVSK/Q8A "Wolfram Language (Mathematica) – Try It Online") Uses the operator form of `StringReplace`: providing it a rule (or a list of rules) but no string gives a function which applies that rule to any string you give it as input. We could do a lot better (`RandomChoice@{#,Capitalize@#}&/@#&` is 34 bytes) if we decided to take as input (and produce as output) a list of characters, which people sometimes argue is okay in Mathematica because it's the only kind of string there is in other languages. But that's no fun. --- *-5 bytes thanks to M. Stern* [Answer] # Ruby, 39 bytes `->s{s.gsub(/./){[$&,$&.upcase].sample}}` Largely inspired from [displayname's answer](https://codegolf.stackexchange.com/a/149514/76468). (I couldn't comment to suggest this one-byte-less version for lack of reputation, sorry [displayname](https://codegolf.stackexchange.com/users/75921/displayname)) [Answer] # Swift 4, 86 bytes ``` s.map{let s="\($0)",u=s.uppercased();return u==s ? u:arc4random()%2==0 ? u:s}.joined() ``` [Answer] # Java 8, 46 bytes This lambda is from `IntStream` to `IntStream` (streams of code points). ``` s->s.map(c->c>96&c<'{'&Math.random()>0?c-32:c) ``` [Try It Online](https://tio.run/##dU/BSgMxED23XzH20CawG4qCoG1XRBA9FIQePIiHMZt2U7NJSGYra@m3r6ktVESZw7yZx5v3Zo0bzJ1Xdl2@d755M1qCNBgjzFFb2PZ7x2UkpNSW2qKBdVKJhrQRy8ZK0s6K@yOYnrhIQWEtHi0tvlEG/3MFBLSlq017h14TGv2pYNbFvIiiRs9kXsji6nIop6PtaDhHqsRBwHgxvpH5xfm15F1v0v8deON0CXX6hSUjbVcvr4BhFfn@tZ62lGbpSvXkEo4w@yOGQO9NywYPyhgHzy6Y8my729dAyApDZJwLcrchYMv4JJ1dtJFULVxDwidPMpZZ9QGHAOxkl8E4@@EujLIrqvj@xq6/674A) ## Capitalization distribution Whether to capitalize a letter used to be the quite sensible condition that `Math.random()<.5`, which was satisfied about half the time. With the current condition of `Math.random()>0` (which saves a byte), capitalization occurs virtually every time, which makes a test program kind of pointless. But it does satisfy the randomness requirement. ## Acknowledgments * -1 byte thanks to Olivier Grégoire [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 55 bytes ``` s=>s::gsub("."c=>{0s.upper,s.lower}[math.random(2)](c)) ``` [Try it online!](https://tio.run/##SyvNy678n2b7v9jWrtjKKr24NElDSU8p2dau2qBYr7SgILVIp1gvJ788tag2OjexJEOvKDEvJT9Xw0gzViNZU/N/QVFmXolGmoaSR2pOTr6OQnh@UU6KohJQBgA "Funky – Try It Online") Thanks to optional commas, it's one byte shorter to do `0s.upper` in the table definition, which means the `math.random` will randomly pick either `1` or `2`, than to do `math.random(0,1)` in the random and not have the `0`. [Answer] # [R](https://www.r-project.org/), ~~60 59 58 57 56~~ 63 bytes ``` intToUtf8((s=utf8ToInt(scan(,"")))-32*rbinom(s,s%in%97:122,.5)) ``` [Try it online!](https://tio.run/##K/r/PzOvJCQ/tCTNQkOj2LYUSIfke@aVaBQnJ@Zp6CgpaWpq6hobaRUlZebl52oU6xSrZuapWppbGRoZ6eiZamr@V/JIzcnJVwjPL8pJUQQCpf8A "R – Try It Online") Different approach from the other two R answers [here](https://codegolf.stackexchange.com/a/149518/80010) and [here](https://codegolf.stackexchange.com/a/149501/80010). Improved and fixed thanks to Giuseppe! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes *Thank you Adnan for -1 byte* ``` uø€ΩJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/9PCOR01rzq30@v@/qqrK0REA "05AB1E – Try It Online") **Explanation** ``` uø€ΩJ u Upper case of top of stack. Stack: ['ZZZAA'] ø Zip(a,b) (uses implicit input). Stack: ['zZ', 'zZ', 'zZ', 'AA', 'AA'] € Following operator at each element of its operand Ω Random choice. Stack: ['z', 'Z', 'z', 'A', 'A'] (for example) J Join a by ''. Stack: 'zZzAA' Implicit output ``` Method taken from @totallyhuman's answer [Answer] # Dyalog APL, ~~23~~ ~~18~~ ~~17~~ 14 bytes This is a function which takes a string and returns it with random capitalization (as specified in the question). ``` {(?2)⌷⍵,1⎕C⍵}¨ ``` **Edits:** Answer improved using suggestions by @LdBeth and @EliasMårtenson at the [APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard). **New Edit:** Answer improved using suggestion by @Adam at APL Orchard. [Answer] # [Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros), 25 bytes ``` i.b*)..96>\123<*?2*>32*-o ``` [Try it here](http://dloscutoff.github.io/Esolangs/) The only fancy part is the control flow, `.b*)`. Let's talk about the rest first. ``` i.. Get a character of input, duplicate twice 96> Test if charcode greater than 96 \ Swap with copy #2 123< Test if charcode less than 123 * Multiply the two tests (logical AND): test if it is lowercase letter ? Random number between 0 and 1 2* Times 2 > Is lcase test greater? If test was 1 and rand*2 < 1, then 1, else 0 32*- Multiply by 32 and subtract from charcode to ucase lcase letter o Output as character ``` We then loop back to the beginning of the line. Control flow involves changing where the end of the line is; if it is moved to the left of the IP, execution terminates. Thus: ``` . Duplicate input charcode b* Push 11 and multiply ) Move end of line that many characters to the right ``` When the charcode is positive, `)` is a no-op, since the end of the line is as far right as it can go. But when all characters have been read, `i` gives `-1`. Then we move the end of the code `-11` characters to the right--that is, 11 characters to the left. It takes a couple iterations, but eventually the IP is past the end of the code and the program halts. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes ``` "@rEk?Xk]v! ``` [Try it online!](https://tio.run/##y00syfn/X8mhyDXbPiI7tkzx/391j9ScnHyF8PyinBRFdQA "MATL – Try It Online") Saved 1 byte thanks to @LuisMendo [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ụᶻṛᵐc ``` [Try it online!](https://tio.run/##ASwA0/9icmFjaHlsb2cy///hu6XhtrvhuZvhtZBj//8iSGVsbG8sIFdvcmxkISL/Wg "Brachylog – Try It Online") ### Explanation ``` Example input: "Test" ụᶻ Zip uppercase: [["T","T"],["e","E"],["s","S"],["t","T"]] ṛᵐ Map random element: ["T","e","S","T"] c Concatenate: "TeST" ``` [Answer] ## [Alice](https://github.com/m-ender/alice), ~~17~~ 15 bytes *Thanks to Leo for saving 2 bytes.* ``` /uRUwk \i*&o.@/ ``` [Try it online!](https://tio.run/##S8zJTE79/1@/NCi0PJsrJlNLLV/PQf//f4/UnJx8HYXw/KKcFEUA "Alice – Try It Online") ### Explanation ``` /... \...@/ ``` This is the usual framework for largely linear programs operating entirely in Ordinal mode. ``` i Read all input as a string. R Reverse the input. &w Fold w over the characters of the string. w is nullary which means it doesn't actually use the individual characters. So what this does is that a) it just splits the string into individual characters and b) it invokes w once for each character in the string. w itself stores the current IP position on the return address stack to begin the main loop which will then run N+1 times where N is the length of the string. The one additional iteration at the end doesn't matter because it will just output an empty string. . Duplicate the current character. u Convert it to upper case (does nothing for characters that aren't lower case letters). * Join the original character to the upper case variant. U Choose a character at random (uniformly). o Print the character. k If the return address stack is not empty yet, pop an address from it and jump back to the w. @ Terminate the program. ``` I first tried doing this entirely in Cardinal mode, but determining if something is a letter just based on character code would probably take more bytes. [Answer] # Pyth, ~~10~~ ~~7~~ 6 bytes ``` smO,r1 ``` Saved 3 bytes thanks to ovs and 1 thanks to Steven H. [Try it online](http://pyth.herokuapp.com/?code=smO%2Cr1&input=%22Hello+World%21%22&debug=0) ### Explanation ``` smO,r1 m Q For each character in the (implicit) input... ,r1dd ... get the capitalized version and the (implicit) character, ... O ... and pick one at random. s Concatenate the result. ``` [Answer] # PHP, ~~63~~ 53 bytes ``` while($a=$argv[1][$i++])echo rand()%2?ucfirst($a):$a; ``` Managed to reduce the code with 10 bytes by (partialy) following Titus' suggestion. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~57~~ 56 bytes ``` -join([char[]]"$args"|%{(("$_"|% *per),$_)[(Random)%2]}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPIzo5I7EoOjZWSSWxKL1YqUa1WkNDSSUeyFDQKkgt0tRRideM1ghKzEvJz9VUNYqt1fz//7@6B9CEfIXw/KKcFHUA "PowerShell – Try It Online") *-1 byte thanks to briantist* Takes input as a string, explicitly casts the `$args` array to a string, casts it as a `char`-array, then feeds the characters through a loop. Each iteration, we 50-50 either output the character as-is `$_` or convert it to upper-case `"$_".ToUpper()` (that's the `("$_"|% *per)` garbage). That's chosen by getting a `Random` integer and taking it mod `2`. Those characters are left on the pipeline and then `-join`ed back together into a single string, which is itself left on the pipeline and output is implicit. [Answer] # [Julia](http://julialang.org/), 35 bytes ``` s->map(c->rand([c,uppercase(c)]),s) ``` [Try it online!](https://tio.run/##yyrNyUw0@/9fySM1JydfITy/KCdFUUmhxk6hWNcuN7FAI1nXrigxL0UjOlmntKAgtSg5sThVI1kzVlOnWBOkrKAoM6/k/38A "Julia 0.6 – Try It Online") Still pretty easy to read as a human. In Julia rand(A) returns a random element from A. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 bytes 28 bytes (<https://github.com/abrudz/SBCS/>) 50 bytes (UTF-8) ``` {1(819⌶)@(?n⍴⍨?n←≢⍸~⍵∊⎕A)⊢⍵} ``` Inspired by [Graham](https://codegolf.stackexchange.com/users/6949/graham)'s [APL+Win solution](https://codegolf.stackexchange.com/a/149505/84204) [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9pQw8LQ8lHPNk0HDfu8R71bHvWuANJtEx51LnrUu6PuUe/WRx1dj/qmOmo@6gKKbK39/x8A "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ This is the cop's thread. The [robber's thread is here](https://codegolf.stackexchange.com/questions/112300/robbers-crack-the-regex-make-a-snake). --- Write a code that takes an input `n` and creates a n-by-n "snake matrix". A snake matrix is a matrix that follows this pattern: 3-by-3: ``` 1 2 3 6 5 4 7 8 9 ``` and 4-by-4: ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` The exact output format is optional. You may for instance output `[[1 2 3],[6 5 4],[7 8 9]]`, or something similar. You must provide the language name, and a regex that fully matches your code. You can choose how detailed your regex should be. In the extreme, you can write a regex that matches every possible string, in which case it will be very easy to crack your code. You must also provide the output for `n=4`, so that robbers know the exact format you have opted for. You may use one of the regex-flavors that are available on [regex101.com](https://regex101.com/), or the Ruby flavor. * PCRE (PHP) * Javascript * Python * Golang * [Ruby](http://rubular.com/) You must specify which one you are using. Notes: * You must support any reasonably large `n`. You may assume it won't overflow the datatype or memory. If the default datatype is 8-bit signed integers, then you can assume `n<=11`, if it's unsigned 8-bit integers, then you can assume `n<=15`. * The robbers have to match the submission's output format, except leading/trailing spaces and newlines, since that might have been stripped away by the SE formatting. **Winning criterion:** The winner will be the uncracked submission with the shortest regex, measured in number of characters. If your post has remained uncracked for 7 days, then you may post the intended solution and mark your submission as safe. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), [Cracked by mbomb007](https://codegolf.stackexchange.com/a/112307/47066) Hopefully fun to crack and not too obvious. **Regex (PCRE):** ``` ^\w*[+\-*\/%]*\w*.{0,2}$ ``` **Output n=4:** ``` [[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]] ``` **Original solution** ``` UXFXLNX*+NFR}ˆ ``` [Answer] # [Python 2](https://docs.python.org/2/), length 62, [cracked](http://codegolf.stackexchange.com/a/112626/12012) ### Regex (PCRE) ``` ^while ((?=\S)[1di\W]|an|eval|nput|nt|or|pr){55}s(?1){45}n...$ ``` ### Sample output ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), length 6, [cracked](https://codegolf.stackexchange.com/a/112349/12012) ### Regex (PCRE) ``` ^.{9}$ ``` ### Sample output ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` [Answer] # R, length 14 [Cracked by plannapus](https://codegolf.stackexchange.com/a/112389/31347) I hope I got this regex right. What I trying to say is 77 characters excluding `<space>`, `#`, `;` and `[`. I tested it [here](https://regex101.com/) **Regex** ``` ^[^ #;\[]{77}$ ``` **Sample output n= 4** ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), [Cracked by Value Ink](https://codegolf.stackexchange.com/a/112607/47066) Lets kick it up a notch :) Hopefully a nice puzzle. **Regex (PCRE)** ``` ^\w*..\w*$ ``` **Output n=4** ``` [[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]] ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), length 49, [Cracked by Aaron](https://codegolf.stackexchange.com/a/112764/44807) ### Regex (Javascript) ``` ^.{7}\n.{12}\n\?.{6};[^v^]{27}(\n.{13}:&.{2}){2}$ ``` ### Sample output (n=4) ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` Formatting is a bit weird, but checking for number length would have made it a lot longer. Might have gone a bit overboard on the regex, not sure! Edit: Also I forgot to mention, I use the initial stack (-v flag) for input, not the usual fish input. Sorry! ### Original Code: ``` <v1*2&: >:{:}=?v:1+ ?^{r0}v;>&:&[r]{&:&2*+}::&:::&*@+@( +:}=?v>n" "o&:&{1 0~{oa<^v?)*&::&:} ``` Aaron's is a lot simpler! The complexity of my original code is based around the idea of using `n[r]` every n-th number to flip that segment (row), then printing all numbers at once at the end [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), [cracked](https://codegolf.stackexchange.com/a/112403/65298) Also my first Cops and Robbers challenge, so tell me if there are issues with this pattern (especially since this is a fairly unknown language). ### Regex (PCRE) ``` ^\S{6}\W{0,3}\w$ ``` ### Output (n = 4) ``` [[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]] ``` [Answer] # PHP, 221 Bytes ([Cracked](https://codegolf.stackexchange.com/a/112405/32353)) I hope it is difficult enough. ## Regex (PCRE): 16 Bytes ``` ^[^\s/\#6]{221}$ ``` No space, No comments, no use of base64\_decode. Have Fun. ## Output ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` ## Original Code ``` $w=$argv[1];$s="";$r=range(1,$w**2);for($i=0;$i<$w;$i++)if($i%2)array_splice($r,$i*$w,$w,array_reverse(array_slice($r,$i*$w,$w)));foreach(($r)as$v)$s.=str_pad($v,$l=strlen(max($r))+1,"\x20",0);echo(chunk_split($s,$l*$w)); ``` [Answer] # C# net46 [(Cracked)](https://codegolf.stackexchange.com/a/112636/32353 "(Cracked)") (<http://ideone.com/> works) ## Regex PCRE flavor length 58 tested at regex101 ``` ^sta((?![\d%bh\/]|==|if|(\[.*){4}|(i.*){6}).){142}urn....$ ``` Only the method is regexed. Method returns a 2d int[,] array (int[4,4]) for an input n=4. If printed looks like this: ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` This is my first entry into anything like this, let me know if I did anything wrong. Not trying to win by regex length for sure, I'm just interested to see how well I did at preventing cracking :) Original code: ``` static int[,]g(int n){int l,j,k=n-n,c,s;var _=new int[n,n];var d=n!=n;c=k;c++;s=k;for(l=k;l<n;l++){for(j=k;j<n;j++){_[l,d?n-j-c:j]=++s;}d=!d;}return _;} ``` [Answer] # QBasic, regex length 10 ([cracked](https://codegolf.stackexchange.com/a/112653/32353)) ### Regex Should work in any regex flavor, but we'll call it Python flavor. ``` ([A-Z]+.)+ ``` **NOTE:** My solution uses unformatted QBasic; after formatting, the code doesn't match the regex due to added spaces. (But I *can* tell you that that's the only change that makes a difference. `([A-Z]+ ?. ?)+` still works on the formatted version.) For testing purposes, I used [QB64](http://qb64.net) with code formatting turned off (under Options > Code layout). If you don't want to download something, you can also run QBasic online at [archive.org](https://archive.org/details/msdos_qbasic_megapack) (but there you can't turn formatting off). ### Sample output ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` [Answer] # Python 3, 55 bytes [(Cracked)](https://codegolf.stackexchange.com/a/112677/32353) PCRE / Python / Golang flavor. ``` def [triangles=(1,SNAKE)]{27}:print[]SNAKE(--:>or[]{48} ``` *(Be reminded that [Full match is required](https://codegolf.stackexchange.com/a/112472/32353). Assume `^` and `$` when testing.)* Sample output: ``` [1, 2, 3, 4] [8, 7, 6, 5] [9, 10, 11, 12] [16, 15, 14, 13] ``` --- Original solution: ``` def r(N,S=1,A=1,K=range,E=list):print(E(K(S,S+N))[::A])or(S+N>N*N)or(r(N,S+N,-A,K,E)) ``` Should have trimmed 4 bytes :p [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), Regex length 12   [Cracked by seshoumara!](https://codegolf.stackexchange.com/a/112512/59825) ``` ^[^# !]{59}$ ``` This regular expression is simple enough that I don't think the flavor of regex matters -- it should work across the board. (Note the space after the # in the regex.) I've tested all four flavors at regex101.com (PCRE/PHP, Javascript, Python, and Golang), as well as the Ruby version at rubular.com. The dc program matches the regex in all five regex versions. --- The dc program takes its input on stdin and puts its output on stdout. Sample output for input 4 (there's a trailing space at the end of each line): ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` --- # Original code (added after being cracked) This has been [cracked by @seshoumara](https://codegolf.stackexchange.com/a/112512/59825). Here's my intended code: ``` ?sd[AP]s+0[dddld/2%rld%2*1+ldr-*+1+n2CP1+dld%0=+dvld>l]dslx ``` Explanation: ``` ?sd Input number and store it in register d. [AP]s+ Macro that prints a newline. The macro is stored in register '+'. 0 Push 0 on the stack, initializing a loop. (The top of the stack is the index variable. It will go up to d^2-1.) [ Start a macro definition. (The macro will be stored in register l.) ddd Push 3 copies of the loop index variable on the stack, so they'll be available later. I'll call this number i. ld/ Divide the last copy of i by d (integer division); this computes the row of the square that we're in (starting with row 0). 2% Replace the row number with 0 if the row number is even, with 1 if the row number is odd. r Swap the top two items on the stack, so the top item is now the next to last copy of i, and the second item on the stack is the row number mod 2. ld% Compute i mod d; this goes from 0 to d-1. It is the column in the square that the next number will be placed in. (The leftmost column is column 0.) 2*1+ Top of the stack is replaced with 2*(column number)+1. ldr Inserts d as the second item on the stack. - Computes d-2*(column number)-1. * The second item on the stack is the row number mod 2, so multiplying yields 0 if the row number is even, and d-2*(column number)-1 if the row number is odd. + Add to the remaining copy of i. The sum is i itself in even-numbered rows, and it's i+d-2*(column number)-1 in odd-numbered rows. ``` The sum at the top of the stack now is the next number we want to print: * It's easy to see that that's correct if the row number is even, since then the sum is just i. * For odd-numbered rows, notice that i = d\*(i/d)+(i%d) = d \* (row number) + column number. It follows that the sum i+d-2\*(column number)-1 is d \* (row number) + column number + d - 2\*(column number)- 1 = d \* (row number + 1) - column number - 1, which is the number we want to put in the indicated row and column to ensure that we're counting backwards in the odd-numbered rows. Returning to the explanation now: ``` n Print the desired number for the current row and column. 2CP Print a space. (2C, which is computed by dc as 20 + 12, is 32, the ASCII code for a space.) 1+ The original copy of i is at the top of the stack; add 1 to it. dld%0=+ If (the incremented value of) i is a multiple of d, call the macro at register '+', which prints a newline. dvld>l If d > sqrt(i) (in other words, if i < d^2), then go back to the top of the loop by calling macro l again. ]dslx End the macro definition, store the macro in register l, and execute it. ``` [Answer] # Bash, regex length 38, cracked ([@kennytm](https://codegolf.stackexchange.com/a/112656/32353 "@kennytm")) ``` ^sort -n <[1adegnopqrstx$\-*()|'; ]+$ ``` Input: ``` n=4; <command> ``` Output: ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` [Answer] # PHP I hope this will be a fun one! :D ### Output (n=4) ``` [[1,2,3,4],[8,7,6,5],[9,10,11,12],[16,15,14,13]] ``` --- ### Level 1: PCRE (length=17) ([Cracked by Jörg Hülsermann](https://codegolf.stackexchange.com/questions/112300/robbers-crack-the-regex-make-a-snake/112639#112639)) ``` ^<[^'"\d{vV;<$]+$ ``` * No single or double quotes so... no strings! * No digits! * No `{` so... no anonymous functions! * No `v` so... no `eval()`! * No `;` so... it must be a single statement! * No `<` so... no `Heredoc` nor multiple PHP blocks! * The big one! No **$** so... good luck defining variables! >:D --- [@JörgHülsermann](https://codegolf.stackexchange.com/questions/112300/robbers-crack-the-regex-make-a-snake/112639#112639) had an interesting approach, but it's not what I had in mind :). Therefore, I'm introducing a new level of difficulty (I promise I have the code that fits this and I'm not just messing with you): ### Level 2: PCRE (length=23) ([Cracked by Jörg Hülsermann](https://regex101.com/r/XtVl9G/1)) ``` ^<[^'"\d{v;<$_~|&A-Z]+$ ``` * All the restrictions of **Level 1** * New on this level: none of these `_~|&A-Z`! :) --- Have fun! --- ### THE ORIGINAL SOLUTION So, forbidding the `$` meant the variables couldn't be accessed the regular way, but that doesn't mean they can't be used at all! You can still use `extract()/compact()` to import/export variables into the current scope. :) ``` $i = 1; // can be written as extract(['i' => 1]) echo $i; // can be written as echo compact('i')['i']; ``` However, there's a gotcha: `compact('x')['x']++` wouldn't work because variables in PHP are passed by value... with one exception! Objects. ``` $x = (object) ['i' => 1]; // is extract(['x' => (object) ['i' => 1]]); // and compact('x')['x']->i++; // works just fine! ``` The rest is easy. * Numbers `0` and `1` are easily generated by converting `false` and `true` to `int` by prepending them with the `+` sign * Use `and` and `or` since `&` and `|` are forbidden * To work around the forbidden quotes, just use undefined constants, which are treated as strings * To suppress the notices generated by using undefined constants, just use `@` * The forbidden letter `v` can be generated by using `chr(ord('u') + 1)`, which translates to `@chr(ord(u) + true)` using the above workarounds * The underscore is similar to the above: `chr(ord('a') - 2)` which translates to `chr(ord(a) - true - true)` * Calling functions which contain forbidden characters can be done by taking advantage of PHP's `callable` type, which can be a string containing the name of the function. So, you can concatenate undefined constants and single character strings generated by `ord()` to build the name of the function and invoke it like this: `array_reverse()` becomes `(a.rray.chr(ord(a)-true-true).re.chr(ord(u)+true).erse)()` (`array` is a language construct, that's why it's split into the undefined constants `a` and `rray`) * Take advantage of the fact that, when it comes to conditional and loop constructs, the curly brackets are optional if the construct applies just to the immediately following statement. This means you can do stuff like: `if ($n = $argv[1] and $i = 0) while ($n > $i++ and do_some and other_stuff or exit)` The logic in human readable code would be: ``` if ( $x = (object) [ 'result' => [], 'i' => 0 ] and define('n', $argv[1]) and define('un', '_') and // create the initial set which we'll loop through define('segments', array_chunk(range(1, pow(n, 2)), n)) ) while ( // store each odd segment as-is and increment the "pointer" ($x->result[] = @segments[$x->i++]) and // store each even segment reversed and increment the "pointer" ($x->result[] = @array_reverse(segments[$x->i++])) and // check if we need to break out of the loop n > $x->i or // exit and output the result if the above is false die(json_encode( // if n is odd, the above would have copied a NULL entry // from the segments, so it needs to be filtered out array_filter($x->result) )) ) ``` And the unfriendly version that matches the regex: `<?php if (@extract([x=>(object)[s=>[],i=>+false]])and@define(n,compact(arg.chr(ord(u)+true))[arg.chr(ord(u)+true)][+true]?:+true)and@define(un,chr(ord(a)-true-true))and@define(s,(a.rray.un.chunk)(range(+true,pow(n,true+true)),n)))while((@compact(x)[x]->s[]=s[@compact(x)[x]->i++])and(@compact(x)[x]->s[]=(a.rray.un.re.chr(ord(u)+true).erse)(s[@compact(x)[x]->i++]))and(n>@compact(x)[x]->i)or(@die((json.un.encode)((a.rray.un.filter)(@compact(x)[x]->s)))))?>` [Answer] # Ruby [[cracked]](https://codegolf.stackexchange.com/a/112640/32353) First Cops and Robbers challenge. Hope I didn't make this too easy. EDIT: replaced `\g<1>` with `(?1)` because they're evidently equivalent in PCRE. ### Regex(PCRE) ``` ^(\W?\W\w){4}..(?1){2}[(-=Z-~]*(?1){5}\w*(?1)(.)\2$ ``` ### Output (n=4) ``` [[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]] ``` (Returns an array of arrays. It's a lambda, BTW, but maybe that gives away too much?) [Answer] # JavaScript [(Cracked)](https://codegolf.stackexchange.com/a/112313/64424) First time doing a Cops and Robbers challenge, hopefully doing it right. ### Regex (JavaScript) ``` ^.*(\.\w+\(.*\)){4}$ ``` ### Output An array equal to: ``` [[1,2,3,4],[8,7,6,5],[9,10,11,12],[16,15,14,13]] ``` [Answer] # Swift, regex 25 [(Cracked)](https://codegolf.stackexchange.com/a/112401/15394) Right, let's see if I've got the hang of this. This is my first cops and robbers post, so lemme know if I've messed up! ## Regex *I used javascript flavour on regex101.com* ``` ^.{21}print[^/]{49}o.{7}$ ``` ## Sample Output ``` [1, 2, 3, 4] [8, 7, 6, 5] [9, 10, 11, 12] [16, 15, 14, 13] ``` ## Original Code ``` (0..<n).forEach{i in print((0..<n).map{i%2>0 ?(i+1)*n-$0 :i*n+$0+1},separator:",")} ``` [Answer] # C – regex of 42 characters in length – [cracked](https://codegolf.stackexchange.com/a/112447/15259) Javascript regex as used in [regex101](https://regex101.com). ``` ^[-h<=*c+m?{printf("\/a: %d\\',o);}]{137}$ ``` Guessing this will be trivial... ``` > main 4 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 > ``` Output is tab-delimited with `\n` after each line. My solution, here integers 0 - 2 were obtained via `t-t`, `t/t`, and `t`: ``` main(int t,char**a){int o=t-t,i=t/t,m,n,h=atoi(*(a+i));for(m=o;m<h;m++)for(n=o;n<h;n++)printf("%d%c",m*h+(m%t?h-n:n+i),n<h-i?'\t':'\n');} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), length 14 [cracked](https://codegolf.stackexchange.com/a/112500/12012) cracked by Dennis ``` [^/P-`mvḊ-ṫ€]* ``` Python regex. Added `m` back in again after I let it slip. `/` (reduce quick); from `P` (product) to ``` (monad from dyad quick); `m` (modulo indexing); `v` (eval dyad); from `Ḋ` (dequeue) to `ṫ` (tail); and `€` (for each quick) For an input of `4` mine outputs: ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` ...because I formatted a list of lists as a grid with `G`. [Answer] # Powershell, 23 Bytes [Cracked By Matt](https://codegolf.stackexchange.com/a/112598/59735) ``` ^.+?%.{42}%.{11}:.{35}$ ``` Original Solution: ``` $n="$args";$script:r=0;$a=1..$n|%{$t=++$script:r..($script:r+=$n-1);if(!($_%2)){[Array]::Reverse($t)};,$t};$a|%{$_-join" "} ``` Takes input as argument and outputs to stdout Hopefully this regex is OK, I don't expect this being too difficult to crack, as I haven't obfuscated much of it, and the regex gives a good few starting points to fill in the gaps, there's one thing in the first segment which is very uncommon in code golf though, which may catch someone out, I think a non-greedy match is required there to make this a bit tougher. First cops challenge anyway. ``` 1..4 | % { "----$_----" ; .\snake-cops.ps1 $_ } ----1---- 1 ----2---- 1 2 4 3 ----3---- 1 2 3 6 5 4 7 8 9 ----4---- 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` [Answer] # [Röda 0.12](https://github.com/fergusq/roda/tree/roda-0.12), length 19 [(Cracked by @KritixiLithos)](https://codegolf.stackexchange.com/a/112631/66323) PCRE: ``` ^{(\|[^\/#\s]*){8}$ ``` Sample output (n=4): ``` [1, 2, 3, 4][8, 7, 6, 5][9, 10, 11, 12][16, 15, 14, 13] ``` Original code: ``` {|n|seq(0,n-1+n%2)|push([{|i|seq(n*i+1,n*i+n)}(_)],[{|j|seq(n*j+n,n*j+1,step=-1)}(_)])|head(n)} ``` [Try it online!](https://tio.run/nexus/roda#y03MzKtOs435X12TV1OcWqhhoJOna6idp2qkWVNQWpyhEV1dkwmWyNPK1DbUAZF5mrUa8ZqxOkCpLKhUlnaeDog01CkuSS2w1TWEKNGsyUhNTNEAavifpmBS@x8A "Röda – TIO Nexus") [Answer] # PHP 7 (Safe) ## Original Code ``` for($z=0,$q="";$z<($x=$argv[1])**2;){$w=($d=intdiv($z,$x))%2?($d+1)*$x-$z%$x:($z+1);for($f=0;$f<(log10($x**2)^0)-(log10($w)^0);$f++)$q.="\x20";$q.=++$z%$x?"$w\x20":"$w\n";}print(rtrim($q)); ``` Second Try ## Regex (PCRE): 29 Bytes ``` ^[^A-Z#\/\s\>busy_heck]{189}$ ``` No space, No comments, no use of base64\_decode. Many functions are not allowed! underscore ## Output n=11 ``` 1 2 3 4 5 6 7 8 9 10 11 22 21 20 19 18 17 16 15 14 13 12 23 24 25 26 27 28 29 30 31 32 33 44 43 42 41 40 39 38 37 36 35 34 45 46 47 48 49 50 51 52 53 54 55 66 65 64 63 62 61 60 59 58 57 56 67 68 69 70 71 72 73 74 75 76 77 88 87 86 85 84 83 82 81 80 79 78 89 90 91 92 93 94 95 96 97 98 99 110 109 108 107 106 105 104 103 102 101 100 111 112 113 114 115 116 117 118 119 120 121 ``` ## Output n=4 ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` ## Output n=3 ``` 1 2 3 6 5 4 7 8 9 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), length 12 (safe) ## Regex Uses Python flavour: ``` (\w{3}\W){5} ``` ## Example output For `n=4`: ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` --- ### Solution ``` txU:GeG:oEq*S5M*TTx! ``` To see how this works, consider input `n=4`. ``` tx % Implicit input n, duplicate, delete. So this does nothing % STACK: 4 U % Square % STACK: 16 : % Range % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] Ge % Reshape as an n-row array in column major order % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16] G: % Push range [1 2 ... n] % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16] [1 2 3 4] o % Modulo 2 % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16] [1 0 1 0] Eq % Times 2, minus 1 (element-wise) % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16] [1 -1 1 -1] * % Multiply (element-wise with broadcast) % STACK: [1 -5 9 -13; 2 -6 10 -14 3 -7 11 -15 4 -8 12 -16] S % Sort each column % STACK: [1 -8 9 -16; 2 -7 10 -15; 3 -6 11 -14; 4 -5 12 -13] 5M % Push [1 -1 1 -1] again % STACK: [1 -8 9 -16; 2 -7 10 -15; 3 -6 11 -14; 4 -5 12 -13] [1 -1 1 -1] * % Multiply (element-wise with broadcast) % STACK: [1 8 9 16; 2 7 10 15; 3 6 11 14; 4 5 12 13] TTx % Push [true true] and delete it. So this does nothing ! % Transpose. Implicitly display % STACK: [ 1 2 3 4; 8 7 6 5; 9 10 11 12; 16 15 14 13] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), length 17 (safe) ``` [^/P-`mvÇ-ıḃ-ṫ€]* ``` Python regex. Tightening the knot, this bans some more useful things, for your aid here are the banned bytes: ``` /PQRSTUVWXYZ[\]^_`mvÇÐÑ×ØÞßæçðñ÷øþĊċĖėĠġİıḃḄḅḊḋḌḍḞḟḢḣḤḥḲḳḶḷṀṁṂṃṄṅṆṇṖṗṘṙṚṛṠṡṢṣṪṫ€ ``` *just under a third of them!* For an input of `4` mine outputs: ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` ...because I formatted a list of lists as a grid with `G`. ### A solution: ``` ’:2o1 Ḃ¬aẋ@0 ’r0;0ẋ$ẋ1Ŀ¬0¦;2ĿÆ¡œ?⁸²¤s⁸G ``` **[Try it online!](https://tio.run/nexus/jelly#@/@oYaaVUb4h18MdTYfWJD7c1e1gwAUUKzKwNgByVIDY8Mj@Q2sMDi2zNjqy/3DboYVHJ9s/atxxaNOhJcVA2v3///8WAA)** / **[regex101](https://regex101.com/r/ad5STi/1/)** The main trick here is to index into a lexicographically sorted list of the permutations of the natural numbers up to **n2** (using `œ?` to avoid building the list of length **n2!**), and to split the result into chunks of length **n**. The aforementioned index is found by forming its representation in the [factorial number system](https://en.wikipedia.org/wiki/Factorial_number_system) which is formulaic since the "unsliced" snake is created by permuting elements in a prescribed manner (this may be readily converted to a number with `Æ¡`). The solution I present uses `Ŀ` to reference previous links as monads (replacing `Ñ` and `Ç`), but multiple `$` in a row could be employed instead to "inline" these helper functions. It also uses `r` since `Ḷ` and `R` are banned. ``` ’:2o1 - Link 1, periodic repetitions in the factorial base representation: n ’ - decrement n :2 - integer divide by 2 o1 - or 1 (keep one period in the cases n=1 and n=2) Ḃ¬aẋ@0 - Link 2, n zeros if n is even, else an empty list: n Ḃ - mod 2 ¬ - not ẋ@0 - 0 repeated n times a - and ’r0;0ẋ$ẋ1Ŀ¬0¦;2ĿÆ¡œ?⁸²¤s⁸G - Main link: n e.g. 6 ’r0 - inclusive range(n-1, 0) [5,4,3,2,1,0] 0ẋ$ - 0 repeated n times [0,0,0,0,0,0] ; - concatenate (makes one "period") [5,4,3,2,1,0,0,0,0,0,0,0] 1Ŀ - call link 1 as a monad 2 ẋ - repeat list [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,0] 0¦ - apply to index 0 (rightmost index): ¬ - not (make the last 0 a 1) [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,1] 2Ŀ - call link 2 as a monad [0,0,0,0,0,0] ; - concatenate [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0] Æ¡ - convert from factorial base 45461852049628918679695458739920 ¤ - nilad followed by link(s) as a nilad ⁸ - left argument, n 6 ² - square 36 œ? - lexicographical permutation lookup [1,2,3,4,5,6,12,11,10,9,8,7,13,14,15,16,17,18,24,23,22,21,20,19,25,26,27,28,29,30,36,35,34,33,32,31] s⁸ - split into chunks of length n [[1,2,3,4,5,6],[12,11,10,9,8,7],[13,14,15,16,17,18],[24,23,22,21,20,19],[25,26,27,28,29,30],[36,35,34,33,32,31]] G - format as a grid ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), regex length 3 (safe) The solution is a full program that takes *n* as a command-line argument. It does not use any command-line flags. ### Regex (any flavor) ``` \w+ ``` ### Sample output ``` 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ``` --- ## My solution ``` YENsXaPBsPOyY_MUyFi_MUENsXaIiBA1PsPUPODQENsXiXaPBsX_PBsMRVyEI1PsPUPODQENsXiXaPBsX_PBsMy ``` [Try it online!](https://tio.run/nexus/pip#@x/p6lcckRjgVBzgXxkZ7xta6ZYJJMGCnplOjoYBxQGhAf4ugSCRTLDCiHgg4RsUVunqiVO28v///yYA) ## Strategy Here's the code we would *like* to write: ``` Y \,a F i ,a I i%2 P i*a+_.s M RVy E P i*a+_.s M y ``` That is: * Store the numbers 1 through `a` in `y` * Loop over values of `i` from 0 through `a-1` * If `i` is odd, reverse y, add `i*a` to each element, concatenate a space to each element, and print * Otherwise, do the same thing, but without reversing first ### Difficulties A lot of commands and variables in Pip use letters, but some important ones don't: * Range and inclusive range (`,` and `\,`) * Most math operations (`+`, `-`, `*`, `%`, `++`) * Assignment (`:`) * We can't have a loop or function body with more than one statement (that would need `{}`) * We can't use parentheses to enforce precedence How we get around those limitations: * `EN`umerate can be used in place of `,`; we just need a string with the number of characters we want, and we need to extract the first element of each sublist in a structure like `[[0 "H"] [1 "i"]]`. * We don't need to increment anything if we can solve the problem with `F`or loops. * We can assign to the `y` variable with the `Y`ank operator. * We can do math with strings: `X` is string multiplication, and `PU`sh (or `PB` "push-back") will concatenate a string to another string in-place. To take the length of a string, we can `EN`umerate it and extract the right number from the resulting list. * We can use functions as long as they can be written as single-expression lambda functions using `_`. ## Specifics The building blocks of our program: ### Range ``` _MUENsXa ``` That's `map-unpack(_, enumerate(repeat(space, a)))` in pseudocode. Map-unpack is like Python's `itertools.starmap`: given a list of lists, it calls a function on the items of each sublist. `_` returns its first argument, so `_MU` just gets the first item of each sublist. For example, if a = 3: ``` sXa " " EN [[0 " "] [1 " "] [2 " "]] _MU [0 1 2] ``` ... which is the same as `,a`. ### Inclusive range I'm not sure there's a way to do `inclusive-range(1, a)` in a single expression, but fortunately we only need it once, so we can construct it in the `y` variable in three steps. ``` YENsXaPBs ``` In pseudocode, `yank(enumerate(repeat(space, a).push-back(space)))`: ``` sXa " " PBs " " EN [[0 " "] [1 " "] [2 " "] [3 " "]] Y Store that in y ``` Next `POy` pops the first item from `y` and discards it, leaving `[[1 " "] [2 " "] [3 " "]]`. Finally, ``` Y_MUy ``` That is, `yank(map-unpack(_, y))`: extract the first element of each sublist and yank the resulting list back into `y`. `y` is now `[1 2 3]`. ### Length ``` PODQENaPBs ``` In pseudocode, `pop(dequeue(enumerate(a.push-back(space))))`. The difficulty here is that enumerate only gives us numbers up to `len(a)-1`, but we want `len(a)`. So we first push a space to `a`, lengthening it by one character, and then take `len-1` of the new string. ``` a "xyz" PBs "xyz " EN [[0 "x"] [1 "y"] [2 "z"] [3 " "]] DQ [3 " "] PO 3 ``` ### Math Now that we have a way to take the length of strings, we can use strings to do multiplication and addition of numbers: ``` PODQENsXaXbPBs PODQENsXaPBsXbPBs ``` The first does `sXaXb` to create a string of `a*b` spaces and then takes the length of it; the second does `sXaPBsXb` to push a string of `b` spaces to a string of `a` spaces and then takes the length of it. The nice part is that all the operators we're using here (`PU`, `PO`, `PB`, `DQ`, `EN`, `X`) can be used with `_` to form lambda expressions. So we can map mathematical transformations to the inclusive range we constructed earlier. We also need to check `i%2` inside the loop, but this is easily accomplished with bitwise AND: `iBA1`. ### Put them together The full code, with some added whitespace: ``` YENsXaPBs POy Y_MUy Get \,a into y F i _MUENsXa For i in ,a I iBA1 If i%2=1 P sPUPODQENsXiXaPBsX_PBs M RVy Print sPUi*a+_ M RVy EI1 Elseif 1 (using E would cause a parsing problem) P sPUPODQENsXiXaPBsX_PBs M y Print sPUi*a+_ M y ``` [Answer] # CJam, PCRE, length 8, [cracked](https://codegolf.stackexchange.com/a/112743/8478) ``` ^[a-~]*$ ``` Example output for 4: ``` [[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]] ``` [Answer] # CJam, PCRE, length 9, [cracked](https://codegolf.stackexchange.com/a/112749/8478) ``` ^[a-z~]*$ ``` Example output for 4: ``` [[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]] ``` Now `{|}` are banned, too. [Answer] ## Mathematica, regex length 11, [non-competing](https://codegolf.meta.stackexchange.com/q/11726/8478), [cracked](https://codegolf.stackexchange.com/a/112863/8478) PCRE flavour: ``` ^[^]@]{49}$ ``` The correct solution will be a function which takes an integer and returns the output as a nested list like: ``` {{1, 2, 3, 4}, {8, 7, 6, 5}, {9, 10, 11, 12}, {16, 15, 14, 13}} ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), regex length 3 ([cracked](https://codegolf.stackexchange.com/a/113018/56183)) You can test tinylisp code at [Try it online!](https://tio.run/nexus/tinylisp) ### Regex (any flavor) ``` \S+ ``` Time to go hardcore. ### Output The solution defines a **function** that takes a single integer argument and returns a list like this (for n=4): ``` ((1 2 3 4) (8 7 6 5) (9 10 11 12) (16 15 14 13)) ``` --- My original code uses the same basic idea Brian McCutchon came up with, building lists and eval'ing them. Here it is in one line: ``` (v(c(h(q(d)))(c(h(q(d')))(c(c(h(q(q)))(c(c()(c(q(arglist))(c(c(h(q(v)))(c(c(h(q(c)))(c(c(h(q(q)))(q(d)))(q(arglist))))()))())))()))()))))(d'(seq-args(c(h(q(start)))(c(h(q(stop)))(c(h(q(step)))())))))(d'(seq(c(c(h(q(accum)))seq-args)(q((i(e(v(h(q(start))))stop)(c(v(h(q(start))))accum)(seq(c(v(h(q(stop))))accum)start(s(v(h(q(stop))))step)step)))))))(d'(f'(c(c(h(q(index)))(c(h(q(size)))seq-args))(q((i(e(v(h(q(index))))size)()(c(seq()start(v(h(q(stop))))step)(f'(a(h(q(1)))index)size(a(v(h(q(stop))))size)(a(v(h(q(start))))size)(s(h(q(0)))step)))))))))(d'(f(q((size)(f'(h(q(0)))size(h(q(1)))size(h(q(1)))))))) ``` I used the full construct-and-eval method once, to define a macro `d'` that makes definitions like `d`, but takes its arguments wrapped in a list: so instead of `(d x 42)`, you can do `(d'(x 42))`. Then it was just a matter of rewriting any lists in the definitions that might need whitespace: `(q(a b))` -> `(c a(q(b)))` -> `(c(h(q(a)))(q(b)))`. [Answer] # Python3, length 162 [(Cracked!)](https://codegolf.stackexchange.com/a/112462/41754) Regex: `^([^"' #]){24}"(?1){11}i%n(?1){4}2\*n-(?1){4}i%n(?1){10}i\/n(\)\/\/1)(?1){5}(?2)(?1){3}2\*\(i%n\)(?1){4}[int()2\/]{16}for i in range\(j,(?1){4}\]\)(?1){6}\"\*n\)$` Okay, I know, it's *quite* long. Fortunately, it won't be cracked in under a week... :'D. I think I didn't make a mistake anywhere, that would allow loophole-y answers. ## Output format ``` 4: [1, 2, 3, 4] [8, 7, 6, 5] [9, 10, 11, 12] [16, 15, 14, 13] ``` Original code:`n=int(input());j=0;exec("print([int(i%n+1+(2*n-(2*(i%n)+1))*((((i/n)//1+1)/2)//1)+(2*(i%n)+1)*int(int(i/n)/2))for i in range(j,j+n)]);j+=n;"*n)` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 8 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Your boss asks you to write a "hello world" program. Since you get paid for lines of code, you want to make it as complex as possible. *However* if you just add nonsense lines, or obviously useless or obfuscating stuff, you will never get it through code review. Therefore the challenge is: **Write a "hello world" program which is as complex as possible under the condition that you can give a "justification" for every complexity in the code.** The required behavior of the program is to just output a single line "Hello world" (without the quotes, but with a newline at the end) and then exit successfully. "Justifications" include: * buzzword compatibility ("Modern software is object oriented!") * generally accepted good programming practices ("Everyone knows that you should separate model and view") * maintainability ("If we do it this way, we can more easily do XXX later") * and of course any other justification you can imagine using (in other situations) for real code. Obviously silly justifications will not be accepted. Also, you have to "justify" your choice of language (so if you choose an inherently verbose language, you'll have to justify why it is the "right" choice). Fun languages like Unlambda or Intercal are not acceptable (unless you can give a *very* good justification for using them). The score of qualifying entries is computed as follows: * 1 point for each statement (or whatever the equivalent to a statement is in your language of choice). * 1 point for each definition of a function, type, variable etc (with the exception of the main function, where applicable). * 1 point for each module use statement, file include directive, namespace using statement or similar. * 1 point for each source file. * 1 point for each necessary forward declaration (if you could get rid of it by rearranging code, you have to "justify" why the arrangement you've chosen is the "right" one). * 1 point for each control structure (if, while, for, etc.) Remember that you have to "justify" each single line. If the chosen language is different enough that this scheme cannot be applied (and you can give a good "justification" for its use), please suggest a scoring method which most closely resembles the above for your language of choice. Contestants are asked to calculate the score of their entry and write it in the answer. [Answer] ## C++, trollpost > > Most complex “Hello world” program you can justify > > > ``` #include <iostream> using namespace std; int main(int argc, char * argv[]) { cout << "Hello, world!" << endl; return 0; } ``` My brain cannot justify writing a longer one :) [Answer] I will here demonstrate the power and usability of the scripting language called *Python* by solving a rather complex task in a graceful and efficient manner through the aforementioned scripting language's operators on – and generators of – data structures such as *lists* and *dictionaries*. However, I'm afraid I don't fully comprehend the use of the phrases "complex as possible" and "justification". Nevertheless, here is a rundown of my usual, quite self-explanatory and straight-forward strategy, followed by the actual implementation in Python which you will find, is quite true to the playful, high-order nature of the language: 1. Define the alphabet – obvious first step. For expandability, we choose the entire ascii range. Note the use of the built-in list-generator that can save us for hours of tedious list initialization. 2. tell how many of each letter in the alphabet we will be using. This is simply represented as another list! 3. Merge these two lists into one handy dictionary, where the keys are ascii points and the values are the desired amount. 4. We are now ready to start making characters! Start by creating a string of character out of the dictionary. This will contain all the characters we need in our final output, and the right amount of each one! 5. Declare the desired order of the characters and initiate a new list that will hold our final output. With simple iteration we will put the generated characters into their final position and print the result! Here is the actual implementation ``` # 1: Define alphabet: a = range(255) # 2: Letter count: n = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 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, 1, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 2, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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) # 3: Merge to dictionary: d = { x: y for x, y in zip(a,n) } # 4: 'Initialize' characters l = ''.join([chr(c) *n for c,n in d.items()]) # 5: Define the order of the characters, initialize final string # and sort before outputting: z = [6,5,0,7,11,1,2,3,4,8,9] o = [0] * 13 for c in l: i = z.pop(0) o[i] = c print ''.join(o) ``` --- Ok, Just went for a short but stupid one and added a bunch of text rather than a TL;DR code solution [Answer] ## Dart's Hello World compiled to JS (2 936 012) <http://code.google.com/p/dart/issues/detail?id=14686> (I'll let Google justify it, though) [Answer] ## Scala, score: 62 Okay, I throw my hat into the ring. ContentProvider.scala: ``` /* As we all know, the future is functional programming. And one of the mantras of pure functional programming is, to avoid mutable data as hell. Using case classes and case objects allows us to create very small, immutable Flight-Weight-Pattern like objects (Singletons, if you like). I'm choosing scala, because its compiled to bytecode for the JVM and therefore very portable. I could of course have implemented it in Java, but as we all know, Javacode is boilerplaty, while scala is a concise language. S: for easy grepping of scoring hints. Scoring summary: 1 import 3 control structures 8 function calls 22 function definitions 14 type definitions 14 files: Seperate files speed up the compilation process, if you only happen to make a local change. */ /** To change the content and replace it with something else later, we generate a generic Content trait, which will be 'Char' in the beginning, but could be Int or something. S: 1 type definition. S: 1 function */ trait ContentProvider [T] { // ce is the content-element, but we like to stay short and lean. def ce () : T } ``` HWCChain.scala: ``` //S: 1 import, for the tailcall annotation later. import annotation._ /** HWCChain is a Chain of HelloWordCharacters, but as a lean, concise language, we do some abbrev. here. We need hasNext () and next (), which is the iterator Pattern. S: 1 type S: 2 functions definitions S: 4 function calls S: 1 if */ trait HWCChain[T] extends Iterator [HWCChain[T]] with ContentProvider[T] { // tailrec is just an instruction for the compiler, to warn us, if this code // can't be tail call optimized. @tailrec final def go () : Unit = { // ce is our ContentProvider.ce System.out.print (ce); // and here is our iterator at work, hasNext and next: if (hasNext ()) next ().go () } // per default, we have a next element (except our TermHWWChain, see close to bottom) // this follows the DRY-principle, and reduces the code drastically. override def hasNext (): Boolean = true } ``` HHWCChain.scala: ``` /** This is a 'H'-element, followed by the 'e'-Element. S: 1 type S: 2 functions */ case object HHWCChain extends HWCChain[Char] with ContentProvider[Char] { override def ce = 'H' override def next = eHWCChain } ``` eHWCChain.scala: ``` /* and here is the 'e'-Element, followed by l-Element 1, which is a new Type S: 1 type S: 2 functions */ case object eHWCChain extends HWCChain[Char] { override def ce = 'e' override def next = new indexedLHWCChain (1) } ``` theLThing.scala: ``` /** we have to distinguish the first, second and third 'l'-thing. But of course, since all of them provide a l-character, we extract the l for convenient reuse. That saves a lotta code, boy! S: 1 type S: 1 function */ trait theLThing extends HWCChain[Char] { override def ce = 'l' } ``` indexedLHWCChain.scala: ``` /** depending on the l-number, we either have another l as next, or an o, or the d. S: 1 type S: 1 function definition S: 2 function calls S: 1 control structure (match/case) */ case class indexedLHWCChain (i: Int) extends theLThing { override def next = i match { case 1 => new indexedLHWCChain (2) case 2 => new indexedOHWCChain (1) case _ => dHWCChain } } ``` theOThing.scala: ``` // see theLTHing ... //S: 1 type //S: 1 function trait theOThing extends HWCChain[Char] { override def ce = 'o' } ``` indexedOHWCChain.scala: ``` // and indexedOHWCCHain ... //S: 1 type //S: 1 function definition //S: 1 function call //S: 1 control structure case class indexedOHWCChain (i: Int) extends theOThing { override def next = i match { case 1 => BlankHWCChain case _ => rHWCChain } } ``` BlankHWCChain.scala: ``` // and indexedOHWCCHain ... //S: 1 type //S: 2 function definitions case object BlankHWCChain extends HWCChain[Char] { override def ce = ' ' override def next = WHWCChain } ``` WHWCChain.scala: ``` //S: 1 type //S: 2 function definitions case object WHWCChain extends HWCChain[Char] { override def ce = 'W' override def next = new indexedOHWCChain (2) } ``` rHWCChain.scala: ``` //S: 1 type //S: 2 function definitions case object rHWCChain extends HWCChain[Char] { override def ce = 'r' override def next = new indexedLHWCChain (3) } ``` dHWCChain.scala: ``` //S: 1 type //S: 2 function definitions case object dHWCChain extends HWCChain[Char] { override def ce = 'd' override def next = TermHWCChain } ``` TermHWCChain.scala: ``` /* Here is the only case, where hasNext returns false. For scientists: If you're interested in terminating programs, this type is for you! S: 1 type S: 3 function definitions */ case object TermHWCChain extends HWCChain[Char] { override def ce = '\n' override def hasNext (): Boolean = false override def next = TermHWCChain // dummy - has next is always false } ``` HelloWorldCharChainChecker.scala: ``` /* S: 1 type S: 1 function call */ object HelloWorldCharChainChecker extends App { HHWCChain.go () } ``` Of course, for a pure functional approach, 0 stinky variables. Everything is layed out in the type system and straight forward. A clever compiler can optimize it down to the bare nothing. The program is clear, simple and easy to understand. It is easy testable and generic and avoids the trap of overengineering (my team wanted to recode the indexedOHWCChain and indexedLHWCChain to a common secondary trait, which has an array of targets and a length field, but that would have been just silly!). [Answer] ### Pure Bash *no fork* (some count, seem to be approx 85...) * **6** function *initRotString* 2 variables, 3 statments * **14** function *binToChar* 2 variables, 7 statements + sub define: 1 func, 1 var, 2 stat * **34** function *rotIO* 9 variables, 25 statments * **9** function *rle* 4 variables, 5 statments * **22** *MAIN* 13 variables, 9 statments **Features**: * Two level *RLE*: first binary encode each chars and second for repeated chars * *Key based modified rot13*: The *rotIO* function perform rotation like *Rot13*, but on 96 values instead of 26 (\*rot47), but shifted by submited key. * Second version use `gzip` and `uuencode` via `perl` (more commonly installed than `uudecode`) Complete rewrite (bugs corrections, ascii-art drawing and two level rle): ``` #!/bin/bash BUNCHS="114 11122 112111 11311 1213 15 21112 11311 1123 2121 12112 21211" MKey="V922/G/,2:" export RotString="" function initRotString() { local _i _char RotString="" for _i in {1..94} ;do printf -v _char "\\%03o" $((_i+32)) printf -v RotString "%s%b" "$RotString" $_char done } ```   ``` function rotIO() { local _line _i _idx _key _cidx _ckey _o _cchar _kcnt=0 while read -r _line ;do _o="" for (( _i=0 ; _i < ${#_line} ; _i++)) ;do ((_kcnt++ )) _cchar="${_line:_i:1}" [ "${_cchar//\(}" ] || _cchar="\(" [ "${_cchar//\*}" ] || _cchar="\*" [ "${_cchar//\?}" ] || _cchar="\?" [ "${_cchar//\[}" ] || _cchar="\[" [ "${_cchar//\\}" ] || _cchar='\\' if [ "${RotString//${_cchar}*}" == "$RotString" ] ;then _o+="${_line:_i:1}" else _kchar="${1:_kcnt%${#1}:1}" [ "${_kchar//\(}" ] || _kchar="\(" [ "${_kchar//\*}" ] || _kchar="\*" [ "${_kchar//\?}" ] || _kchar="\?" [ "${_kchar//\[}" ] || _kchar="\[" [ "${_kchar//\\}" ] || _kchar='\\' _key="${RotString//${_kchar}*}" _ckey=${#_key} _idx="${RotString//${_cchar}*}" _cidx=$(((1+_ckey+${#_idx})%94)) _o+=${RotString:_cidx:1} fi; done if [ "$_o" ] ; then echo "$_o" fi ; done ; } ```   ``` function rle() { local _out="" _c=1 _l _a=$1 while [ "${_a}" ] ; do printf -v _l "%${_a:0:1}s" "" _out+="${_l// /$_c}" _a=${_a:1} _c=$((1-_c)) done printf ${2+-v} $2 "%s" $_out } function binToChar() { local _i _func="local _c;printf -v _c \"\\%o\" \$((" for _i in {0..7} ;do _func+="(\${1:$_i:1}<<$((7-_i)))+" done _func="${_func%+}));printf \${2+-v} \$2 \"%b\" \$_c;" eval "function ${FUNCNAME}() { $_func }" $FUNCNAME $@ } initRotString ```   ``` for bunch in "${BUNCHS[@]}" ; do out="" bunchArray=($bunch) for ((k=0;k<${#bunchArray[@]};k++)) ; do enum=1 if [ "${bunchArray[$k]:0:1}" == "-" ];then enum=${bunchArray[$k]:1} ((k++)) fi ltr=${bunchArray[$k]} rle $ltr binltr printf -v bin8ltr "%08d" $binltr binToChar $bin8ltr outltr printf -v mult "%${enum}s" "" out+="${mult// /$outltr}" done rotIO "$MKey" <<< "$out" done ``` (The key used `V922/G/,2:` is based on `HelloWorld` too, but that's no matter;) Result (as requested): ``` Hello world! ``` ## There is another version: ``` #!/bin/bash eval "BUNCHS=(" $(perl <<EOF | gunzip my\$u="";sub d{my\$l=pack("c",32+.75*length(\$_[0]));print unpack("u",\$l.\$ _[0]);"";}while(<DATA>){tr#A-Za-z0-9+/##cd;tr#A-Za-z0-9+/# -_#;\$u.=\$_;while (\$u=~s/(.{80})/d(\$1)/egx){};};d(\$u);__DATA__ H4sIAETywVICA8VZyZLcMAi9z1e4+q6qAHIr+f8fi7UgyQYs3DOp5JBxywKxPDZr27bthRFgA4B9C0Db 8YdoC+UB6Fjewrs8A8TyFzGv4e+2iLh9HVy2sI+3lQdk4pk55hdIdQNS/Qll2/FUuAD035V3Y1gEAUI4 0yBg3xxnaZqURYvAXLoi2Hj1N4U84HQsy1MPLiRC4qpj3CgKxc6qVwMB8+/0sR0/k8a+LZ4M2o6tUu1V /oMM5SZWBLslsdqtsMaTvbG9gqpbU/d4iDgrmtXXtD3+0bBVleJ4o+hpYAGH1dkBhRfN7mjeapbpPu8P 1QzsKRLmCsNvk2Hq6ntYJjOirGaks58ZK2x7nDHKj7H8Fe5sK21btwKDvZtCxcKZuPxgL0xY5/fEWmVx OxEfHAdptnqcIVI4F15v2CYKRkXsMVBDsOzPNqsuOBjXh8mBjA+Om/mkwruFSTwZDlC30is/vYiaRkWG otG0QDVsz2uHQwP+6usNpwYHDgbJgvPiWOfsQAbBW6wjFHSdzoPmwtNyckiF1980cwrYXyyFqCbS1dN3 L60+yE727rSTeFDgc+fWor5kltEnJLsKkqSRWICZ2WWTEAmve5JmK/yHnNxYj26oX+0nTyXViwaMlwh2 CJW1ugBEargbGtJFhigVFCs6Tn36GFjThTIUukPIQqSyMcgso6stk8xnxp8K9Cr2HDhhFR3glpa6ZiKO HfIkFSt+PoO7wB7hjaEc7tJEk8w8CNcB5uB1ySaWJVsZRHzqLoPTMvaSp1wocFezmxI/M5SfptDkyO3f gJNeUUNaNweooE6xkaNe3TUxAW+taR+jGoo0cCtHJC3e+xGXLKq1CKumAbW0kDxtldGLLfLLDeWicIkg 1jOEFtadl9D9scGSm9ESfTR/WngEIu3Eaqv0lEzbsm7aPfJVvTyBmBY/jZZIslEDaNnH+Ojs4KwTYZ/+ Lx8D1ulL7YmUOPkhNur0piXlMH2QkcWFvMs36crIqVrSv3p7TKjhzwMba3axh6WP2SwwQKvBc2ind7E/ wUhLlLujdK3KL67HVG2Wf8pj7T1zBjBOGT22VUPcY9NdNRXOWNUcw4dqSvJ3V8+lMptHtQ+696DdiPo9 z/ks2lI9C5aBkJ9gpNaG/fkk0UYmTyHViWWDYTShrq9OeoZJvi7zBm3rLhRpOR0BqpUmo2T/BKLTZ/HV vLfsa40wdlDezKUBP5PNF8RP1nx2WuPkCGeV1YNQ0aDuJL5c5OBN72m1Oo7PVpWZ7+uIb6BMzwuWVnb0 2cYxyciKaRneNRi5eQWfwYKvCLr5uScSh67/k1HS0MrotsPwHCbl+up00Y712mtvd33j4g/4UnNvyahe hLabuPm+71jmG+l6v5qv2na+OtwHL2jfROv/+daOYLr9LZdur6+/stxCnQsgAAA= EOF ) ")" MKey="V922/G/,2:" export RotString="" function initRotString() { local _i _char RotString="" for _i in {1..94} ;do printf -v _char "\\%03o" $((_i+32)) printf -v RotString "%s%b" "$RotString" $_char done } function rotIO() { local _line _i _idx _key _cidx _ckey _o _cchar _kcnt=0 while read -r _line ;do _o="" for (( _i=0 ; _i < ${#_line} ; _i++)) ;do ((_kcnt++ )) _cchar="${_line:_i:1}" [ "${_cchar//\(}" ] || _cchar="\(" [ "${_cchar//\*}" ] || _cchar="\*" [ "${_cchar//\?}" ] || _cchar="\?" [ "${_cchar//\[}" ] || _cchar="\[" [ "${_cchar//\\}" ] || _cchar='\\' if [ "${RotString//${_cchar}*}" == "$RotString" ] ;then _o+="${_line:_i:1}" else _kchar="${1:_kcnt%${#1}:1}" [ "${_kchar//\(}" ] || _kchar="\(" [ "${_kchar//\*}" ] || _kchar="\*" [ "${_kchar//\?}" ] || _kchar="\?" [ "${_kchar//\[}" ] || _kchar="\[" [ "${_kchar//\\}" ] || _kchar='\\' _key="${RotString//${_kchar}*}" _ckey=${#_key} _idx="${RotString//${_cchar}*}" _cidx=$(((1+_ckey+${#_idx})%94)) _o+=${RotString:_cidx:1} fi; done if [ "$_o" ] ; then echo "$_o" fi; done } function rle() { local _out="" _c=1 _l _a=$1 while [ "${_a}" ] ; do printf -v _l "%${_a:0:1}s" "" _out+="${_l// /$_c}" _a=${_a:1} _c=$((1-_c)) done printf ${2+-v} $2 "%s" $_out } function binToChar() { local _i _func="local _c;printf -v _c \"\\%o\" \$((" for _i in {0..7} ;do _func+="(\${1:$_i:1}<<$((7-_i)))+" done _func="${_func%+}));printf \${2+-v} \$2 \"%b\" \$_c;" eval "function ${FUNCNAME}() { $_func }" $FUNCNAME $@ } initRotString for bunch in "${BUNCHS[@]}" ; do out="" bunchArray=($bunch) for ((k=0;k<${#bunchArray[@]};k++)) ; do enum=1 if [ "${bunchArray[$k]:0:1}" == "-" ];then enum=${bunchArray[$k]:1} ((k++)) fi ltr=${bunchArray[$k]} rle $ltr binltr printf -v bin8ltr "%08d" $binltr binToChar $bin8ltr outltr printf -v mult "%${enum}s" "" out+="${mult// /$outltr}" done rotIO "$MKey" <<< "$out" done ``` Using same key and may render something like: ```   _ _ _ _ _ _ _   | | | | ___| | | ___ __ _____ _ __| | __| | |   | |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | |   | _ | __/ | | (_) | \ V V / (_) | | | | (_| |_|   |_| |_|\___|_|_|\___/ \_/\_/ \___/|_| |_|\__,_(_)   ▐▌ █ ▐▙ █ █ █ ▗▛▀▙ ▟▜▖ ▗█ ▗█▌ ▗█▖ ▐▙▄█ ▀▜▖▝▙▀▙▝▙▀▙▐▌ █ ▐▛▙█▗▛▀▙▐▌▖█ ▜▄▛▗▛▀▙ ▀▜▖▝▙▛▙ ▄▛▐▌▖█ █ ▗▛▐▌ ▝█▘ ▐▌ █▗▛▜▌ █▄▛ █▄▛▝▙▄█ ▐▌▝█▐▛▀▀▐▙▙█ █ ▐▛▀▀▗▛▜▌ █ ▟▘▄▝▙▗▛ █ ▝▀▜▛ ▀ ▝▘ ▀ ▀▘▀▗█▖ ▗█▖ ▗▄▄▛ ▝▘ ▀ ▀▀▘ ▀▝▘ ▝▀▘ ▀▀▘ ▀▘▀▝▀▘ ▝▀▀▀ ▝▀ ▀▀▀ ▀▀ ▀     ▟▙█▖▟▙█▖ ▜▌ █ █ ▝▘ █ ▝█ ▟▙█▖▟▙█▖   ███▌███▌ ▟▀▟▘▟▀▜▖▟▀▜▖▐▌▟▘ ▝▀▙ ▀█▀ ▀█▀ ▜▌ ▀█▀ █ █ ▟▀█ ▟▀▜▖ ███▌███▌   ▝█▛ ▝█▛ ▜▄█ █▀▀▘█▀▀▘▐▛▙ ▟▀█ █▗▖ █▗▖ ▐▌ █▗▖█ █ █ █ █▀▀▘ ▝█▛ ▝█▛   ▝ ▝ ▄▄▛ ▝▀▀ ▝▀▀ ▀▘▝▘ ▝▀▝▘ ▝▀ ▝▀ ▀▀ ▝▀ ▝▀▝▘▝▀▝▘▝▀▀ ▝ ▝   ... And thank you for reading!! ``` ![Hello world and happy new year 2014](https://i.stack.imgur.com/TJhAq.png) [Answer] Everyone knows that Moore's Law has taken a new turn, and that all real advances in computing power in the next decade will come in the GPU. With that in mind, I've used LWJGL to write a blazingly fast Hello World program that fully takes advantage of the GPU to generate the string "Hello World." Since I'm writing java, it is idiomatic to start by copying and pasting someone elses code, I used <http://lwjgl.org/wiki/index.php?title=Sum_Example> ``` package magic; import org.lwjgl.opencl.Util; import org.lwjgl.opencl.CLMem; import org.lwjgl.opencl.CLCommandQueue; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import org.lwjgl.opencl.CLProgram; import org.lwjgl.opencl.CLKernel; import java.nio.IntBuffer; import java.util.List; import org.lwjgl.opencl.CL; import org.lwjgl.opencl.CLContext; import org.lwjgl.opencl.CLDevice; import org.lwjgl.opencl.CLPlatform; import static org.lwjgl.opencl.CL10.*; public class OpenCLHello { static String letters = "HeloWrd "; // The OpenCL kernel static final String source = "" + "kernel void decode(global const int *a, global int *answer) { " + " unsigned int xid = get_global_id(0);" + " answer[xid] = a[xid] -1;" + "}"; // Data buffers to store the input and result data in static final IntBuffer a = toIntBuffer(new int[]{1, 2, 3, 3, 4, 8, 5, 4, 6, 3, 7}); static final IntBuffer answer = BufferUtils.createIntBuffer(11); public static void main(String[] args) throws Exception { // Initialize OpenCL and create a context and command queue CL.create(); CLPlatform platform = CLPlatform.getPlatforms().get(0); List<CLDevice> devices = platform.getDevices(CL_DEVICE_TYPE_GPU); CLContext context = CLContext.create(platform, devices, null, null, null); CLCommandQueue queue = clCreateCommandQueue(context, devices.get(0), CL_QUEUE_PROFILING_ENABLE, null); // Allocate memory for our input buffer and our result buffer CLMem aMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, a, null); clEnqueueWriteBuffer(queue, aMem, 1, 0, a, null, null); CLMem answerMem = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, answer, null); clFinish(queue); // Create our program and kernel CLProgram program = clCreateProgramWithSource(context, source, null); Util.checkCLError(clBuildProgram(program, devices.get(0), "", null)); // sum has to match a kernel method name in the OpenCL source CLKernel kernel = clCreateKernel(program, "decode", null); // Execution our kernel PointerBuffer kernel1DGlobalWorkSize = BufferUtils.createPointerBuffer(1); kernel1DGlobalWorkSize.put(0, 11); kernel.setArg(0, aMem); kernel.setArg(1, answerMem); clEnqueueNDRangeKernel(queue, kernel, 1, null, kernel1DGlobalWorkSize, null, null, null); // Read the results memory back into our result buffer clEnqueueReadBuffer(queue, answerMem, 1, 0, answer, null, null); clFinish(queue); // Print the result memory print(answer); // Clean up OpenCL resources clReleaseKernel(kernel); clReleaseProgram(program); clReleaseMemObject(aMem); clReleaseMemObject(answerMem); clReleaseCommandQueue(queue); clReleaseContext(context); CL.destroy(); } /** Utility method to convert int array to int buffer * @param ints - the float array to convert * @return a int buffer containing the input float array */ static IntBuffer toIntBuffer(int[] ints) { IntBuffer buf = BufferUtils.createIntBuffer(ints.length).put(ints); buf.rewind(); return buf; } /** Utility method to print an int buffer as a string in our optimized encoding * @param answer2 - the int buffer to print to System.out */ static void print(IntBuffer answer2) { for (int i = 0; i < answer2.capacity(); i++) { System.out.print(letters.charAt(answer2.get(i) )); } System.out.println(""); } } ``` [Answer] # Assembly (x86, Linux/Elf32): 55 points Everyone knows that when you want a fast program, you need to write in assembly. Sometimes we can't rely on `ld` doing its job properly - For optimal performance, it's preferable to build our own Elf header for our hello world executable. This code requires only `nasm` to build, so is very portable. It relies on no external libraries or runtimes. Every line and statement is absolutely crucial to the correct functioning of the program - there is no cruft, nothing can be omitted. Moreover, this really is the shortest way to do it without using the linker - there are no unnecessary loops or declarations to bloat out the answer. ``` BITS 32 org 0x08048000 ehdr: ; Elf32_Ehdr db 0x7F, "ELF", 1, 1, 1, 0 ; e_ident times 8 db 0 dw 2 ; e_type dw 3 ; e_machine dd 1 ; e_version dd _start ; e_entry dd phdr - $$ ; e_phoff dd 0 ; e_shoff dd 0 ; e_flags dw ehdrsize ; e_ehsize dw phdrsize ; e_phentsize dw 1 ; e_phnum dw 0 ; e_shentsize dw 0 ; e_shnum dw 0 ; e_shstrndx ehdrsize equ $ - ehdr phdr: ; Elf32_Phdr dd 1 ; p_type dd 0 ; p_offset dd $$ ; p_vaddr dd $$ ; p_paddr dd filesize ; p_filesz dd filesize ; p_memsz dd 5 ; p_flags dd 0x1000 ; p_align phdrsize equ $ - phdr section .data msg db 'hello world', 0AH len equ $-msg section .text global _start _start: mov edx, len mov ecx, msg mov ebx, 1 mov eax, 4 int 80h mov ebx, 0 mov eax, 1 int 80h filesize equ $ - $$ ``` ### Scoring * "Statements" (counting mov, int): 8 * "Functions, types, variables" (counting `org`, `db`, `dw`, `dd`, `equ`, `global _start`): 37 * "Source files": 1 * "Forward declarations" (counting `dd _start`, `dd filesize`, `dw ehdrsize`, `dw phdrsize`: 4 * "Control structures" (counting `ehdr:`, `phdr:`, `section .data,` `,section .text`, `_start:`): 5 [Answer] **PHP/HTML/CSS (88pts)** All the code is available here : <https://github.com/martin-damien/code-golf_hello-world> * This "Hello World" use the Twig template language for PHP (http://twig.sensiolabs.org/). * I use an autoload mecanism to simply load classes on the fly. * I use a Page class that could handle as many type of elements (implementing the XMLElement interface) and restitute all those lement in a correct XML format. * Finally, I use shiny CSS to display a beautifull "Hello World" :) **index.php** ``` <?php /* * SCORE ( 18 pts ) * * file : 1 * statements : 11 * variables : 6 (arrays and class instance are counted as a variable) */ /* * We use the PHP's autoload function to load dynamicaly classes. */ require_once("autoload.php"); /* * We use a template engine because as you know it is far better * to use MVC :-) */ require_once("lib/twig/lib/Twig/Autoloader.php"); Twig_Autoloader::register(); /* * We create a new Twig Environment with debug and templates cache. */ $twig = new Twig_Environment( new Twig_Loader_Filesystem( "design/templates" /* The place where to look for templates */ ), array( 'debug' => true, 'cache' => 'var/cache/templates' ) ); /* * We add the debug extension because we should be able to detect what is wrong if needed */ $twig->addExtension(new Twig_Extension_Debug()); /* * We create a new page to be displayed in the body. */ $page = new Page(); /* * We add our famous title : Hello World !!! */ $page->add( 'Title', array( 'level' => 1, 'text' => 'Hello World' ) ); /* * We are now ready to render the content and display it. */ $final_result = $twig->render( 'pages/hello_world.twig', array( 'Page' => $page->toXML() ) ); /* * Everything is OK, we can print the final_result to the page. */ echo $final_result; ?> ``` **autoload.php** ``` <?php /* * SCORE ( 7 pts ) * * file : 1 * statements : 4 * variables : 1 * controls: 1 */ /** * Load automaticaly classes when needed. * @param string $class_name The name of the class we try to load. */ function __hello_world_autoload( $class_name ) { /* * We test if the corresponding file exists. */ if ( file_exists( "classes/$class_name.php" ) ) { /* * If we found it we load it. */ require_once "classes/$class_name.php"; } } spl_autoload_register( '__hello_world_autoload' ); ?> ``` **classes/Page.php** ``` <?php /* * SCORE ( 20 pts ) * * file : 1 * statements : 11 * variables : 7 * controls : 1 */ /** * A web page. */ class Page { /** * All the elements of the page (ordered) * @var array */ private $elements; /** * Create a new page. */ public function __construct() { /* Init an array for elements. */ $this->elements = array(); } /** * Add a new element to the list. * @param string $class The name of the class we wants to use. * @param array $options An indexed array of all the options usefull for the element. */ public function add( $class, $options ) { /* Add a new element to the list. */ $this->elements[] = new $class( $options ); } /** * Render the page to XML (by calling the toXML() of all the elements). */ public function toXML() { /* Init a result string */ $result = ""; /* * Render all elements and add them to the final result. */ foreach ( $this->elements as $element ) { $result = $result . $element->toXML(); } return $result; } } ?> ``` **classes/Title.php** ``` <?php /* * SCORE ( 13 pts ) * * file : 1 * statements : 8 * variables : 4 * */ class Title implements XMLElement { private $options; public function __construct( $options ) { $this->options = $options; } public function toXML() { $level = $this->options['level']; $text = $this->options['text']; return "<h$level>$text</h$level>"; } } ?> ``` **classes/XMLElement.php** ``` <?php /* * SCORE ( 3 pts ) * * file : 1 * statements : 2 * variables : 0 */ /** * Every element that could be used in a Page must implements this interface !!! */ interface XMLElement { /** * This method will be used to get the XML version of the XMLElement. */ function toXML(); } ?> ``` **design/stylesheets/hello\_world.css** ``` /* * SCORE ( 10 pts ) * * file : 1 * statements : 9 */ body { background: #000; } h1 { text-align: center; margin: 200px auto; font-family: "Museo"; font-size: 200px; text-transform: uppercase; color: #fff; text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #ff00de, 0 0 70px #ff00de, 0 0 80px #ff00de, 0 0 100px #ff00de, 0 0 150px #ff00de; } ``` **design/templates/layouts/pagelayout.twig** ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr"> <!-- SCORE ( 11 pts ) file: 1 statements: html, head, title, css, body, content, block * 2 : 8 variables : 2 blocks defined : 2 --> <head> <title>{% block page_title %}{% endblock %}</title> <link href="design/stylesheets/hello_world.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body> <div id="content"> {% block page_content %}{% endblock %} </div> </body> </html> ``` **design/templates/pages/hello\_world.twig** ``` {# SCORE ( 6 pts ) file : 1 statements : 4 variables : 1 #} {% extends 'layouts/pagelayout.twig' %} {% block page_title %}Hello World{% endblock %} {% block page_content %} {# Display the content of the page (we use raw to avoid html_entities) #} {{ Page|raw }} {% endblock %} ``` [Answer] # Brainfuck *369 expression, 29 while loops =* **398** ``` > ; first cell empty ;; All the chars made in a generic way ;; by first adding the modulus of char by ;; 16 and then adding mutiples of 16 ;; This simplifies adding more characters ;; for later versions ------>>++++[-<++++>]<[-<+>] ; CR +>>++++[-<++++>]<[-<++>] ; ! ++++>>++++[-<++++>]<[-<++++++>] ; d ---->>++++[-<++++>]<[-<+++++++>] ; l ++>>++++[-<++++>]<[-<+++++++>] ; r ->>++++[-<++++>]<[-<+++++++>] ; o +++++++>>++++[-<++++>]<[-<+++++++>] ; w >>++++[-<++++>]<[-<++>] ; space ---->>++++[-<++++>]<[-<+++>] ; comma ->>++++[-<++++>]<[-<+++++++>] ; o ---->>++++[-<++++>]<[-<+++++++>] ; l ---->>++++[-<++++>]<[-<+++++++>] ; l +++++>>++++[-<++++>]<[-<++++++>] ; e -------->>++++[-<++++>]<[-<+++++++>]; h <[.<] ; print until the first empty cell ``` Output as from K&R The C Programming Language example: ``` hello, world! ``` [Answer] ## Ti-Basic 84, 1 Point ``` :Disp "HELLO WORLD!" ``` Ti-Basic is pretty basic. But if you really want a justified explanation, here it is: `:` starts every command, function, statement, structure, subprogram, you name it `Disp` is a predefined function that displays a parameter on the screen aka`whitespace` Lets the function `Disp` know that it has been called and that a parameter should follow the single character of whitespace which actually comes pasted in along with `Disp` `"` Starts defining the string literal `HELLO WORLD` Part of the text in the string literal `!` Although it is a factorial math operator, it is not evaluated because it is inside a string literal `"` Ends the definition of the string literal [Answer] So, I have a very... ... ...peculiar manager. He has this strange idea that the simpler a program is, the more beautiful, the more artistic it should be. Since the `Hello World` is arguably one of the easiest programs to write, he has asked for something so great he could hang on the wall. After doing some research, he insisted that the thing be written in Piet. Now, I am not one to question the merits of the most intelligent person to ever grace upper management, so I was tasked with "writing" this program, which can be run on [this online piet interpreter.](http://www.bertnase.de/npiet/npiet-execute.php "this online Piet interpreter") Maybe it's time to look for a more sane manager... ![enter image description here](https://i.stack.imgur.com/2xtPK.png) [Answer] ## A [Lipogram](http://en.wikipedia.org/wiki/Gadsby_%28novel%29) in C: ``` int main(){ printf("H%cllo World\n", 'd'+1); } ``` Th ky btwn 'w' and 'r' on my computr is brokn. It causs problms with som languags. Almost all pr-compilr dirctivs in C us that lttr. Th abov cod spits out warnings about an implicit dclaration of printf(), sinc I cannot us #includ(stdio.h), but it runs fin. [Answer] Ill put this up for reference as community wiki. It is a C# one with bad practices. I define my own ascii data structure. I don't want this to be a competitor but rather "Kid's, you see that man over there... if you don't eat your vegetables you will become like him" kind of example. **IF YOU ARE EASILY DISTURBED BY BAD CODE LOOK AWAY NOW** I usually use this to scare children on Halloween. You should also note that I could not fit all my 256 ascii characters on here because the total chars shoots to around 40,000. Don't try and reproduce this for 2 reasons: * It's terrible, horrible, worse than code golf code code. * I wrote a program to write most of it. So uhh... yeah "enjoy!". Also if you enjoy cleaning and improving code *cough* code review *cough* this could keep you busy for a while if you are looking for a non-profitable occupation. ``` namespace System { class P { static void Main() { Bit t = new Bit { State = true }; Bit f = new Bit { State = false }; Nybble n0 = new Nybble() { Bits = new Bit[4] { f, f, f, f } }; Nybble n1 = new Nybble() { Bits = new Bit[4] { f, f, f, t } }; Nybble n2 = new Nybble() { Bits = new Bit[4] { f, f, t, f } }; Nybble n3 = new Nybble() { Bits = new Bit[4] { f, f, t, t } }; Nybble n4 = new Nybble() { Bits = new Bit[4] { f, t, f, f } }; Nybble n5 = new Nybble() { Bits = new Bit[4] { f, t, f, t } }; Nybble n6 = new Nybble() { Bits = new Bit[4] { f, t, t, f } }; Nybble n7 = new Nybble() { Bits = new Bit[4] { f, t, t, t } }; Nybble n8 = new Nybble() { Bits = new Bit[4] { t, f, f, f } }; Nybble n9 = new Nybble() { Bits = new Bit[4] { t, f, f, t } }; Nybble n10 = new Nybble() { Bits = new Bit[4] { t, f, t, f } }; Nybble n11 = new Nybble() { Bits = new Bit[4] { t, f, t, t } }; Nybble n12 = new Nybble() { Bits = new Bit[4] { t, t, f, f } }; Nybble n13 = new Nybble() { Bits = new Bit[4] { t, t, f, t } }; Nybble n14 = new Nybble() { Bits = new Bit[4] { t, t, t, f } }; Nybble n15 = new Nybble() { Bits = new Bit[4] { t, t, t, t } }; HByte b0 = new HByte() { Nybbles = new Nybble[2] { n0, n0 } }; HByte b1 = new HByte() { Nybbles = new Nybble[2] { n0, n1 } }; HByte b2 = new HByte() { Nybbles = new Nybble[2] { n0, n2 } }; HByte b3 = new HByte() { Nybbles = new Nybble[2] { n0, n3 } }; HByte b4 = new HByte() { Nybbles = new Nybble[2] { n0, n4 } }; HByte b5 = new HByte() { Nybbles = new Nybble[2] { n0, n5 } }; HByte b6 = new HByte() { Nybbles = new Nybble[2] { n0, n6 } }; HByte b7 = new HByte() { Nybbles = new Nybble[2] { n0, n7 } }; HByte b8 = new HByte() { Nybbles = new Nybble[2] { n0, n8 } }; HByte b9 = new HByte() { Nybbles = new Nybble[2] { n0, n9 } }; HByte b10 = new HByte() { Nybbles = new Nybble[2] { n0, n10 } }; HByte b11 = new HByte() { Nybbles = new Nybble[2] { n0, n11 } }; HByte b12 = new HByte() { Nybbles = new Nybble[2] { n0, n12 } }; HByte b13 = new HByte() { Nybbles = new Nybble[2] { n0, n13 } }; HByte b14 = new HByte() { Nybbles = new Nybble[2] { n0, n14 } }; HByte b15 = new HByte() { Nybbles = new Nybble[2] { n0, n15 } }; HByte b16 = new HByte() { Nybbles = new Nybble[2] { n1, n0 } }; HByte b17 = new HByte() { Nybbles = new Nybble[2] { n1, n1 } }; HByte b18 = new HByte() { Nybbles = new Nybble[2] { n1, n2 } }; HByte b19 = new HByte() { Nybbles = new Nybble[2] { n1, n3 } }; HByte b20 = new HByte() { Nybbles = new Nybble[2] { n1, n4 } }; HByte b21 = new HByte() { Nybbles = new Nybble[2] { n1, n5 } }; HByte b22 = new HByte() { Nybbles = new Nybble[2] { n1, n6 } }; HByte b23 = new HByte() { Nybbles = new Nybble[2] { n1, n7 } }; HByte b24 = new HByte() { Nybbles = new Nybble[2] { n1, n8 } }; HByte b25 = new HByte() { Nybbles = new Nybble[2] { n1, n9 } }; HByte b26 = new HByte() { Nybbles = new Nybble[2] { n1, n10 } }; HByte b27 = new HByte() { Nybbles = new Nybble[2] { n1, n11 } }; HByte b28 = new HByte() { Nybbles = new Nybble[2] { n1, n12 } }; HByte b29 = new HByte() { Nybbles = new Nybble[2] { n1, n13 } }; HByte b30 = new HByte() { Nybbles = new Nybble[2] { n1, n14 } }; HByte b31 = new HByte() { Nybbles = new Nybble[2] { n1, n15 } }; HByte b32 = new HByte() { Nybbles = new Nybble[2] { n2, n0 } }; HByte b33 = new HByte() { Nybbles = new Nybble[2] { n2, n1 } }; HByte b34 = new HByte() { Nybbles = new Nybble[2] { n2, n2 } }; HByte b35 = new HByte() { Nybbles = new Nybble[2] { n2, n3 } }; HByte b36 = new HByte() { Nybbles = new Nybble[2] { n2, n4 } }; HByte b37 = new HByte() { Nybbles = new Nybble[2] { n2, n5 } }; HByte b38 = new HByte() { Nybbles = new Nybble[2] { n2, n6 } }; HByte b39 = new HByte() { Nybbles = new Nybble[2] { n2, n7 } }; HByte b40 = new HByte() { Nybbles = new Nybble[2] { n2, n8 } }; HByte b41 = new HByte() { Nybbles = new Nybble[2] { n2, n9 } }; HByte b42 = new HByte() { Nybbles = new Nybble[2] { n2, n10 } }; HByte b43 = new HByte() { Nybbles = new Nybble[2] { n2, n11 } }; HByte b44 = new HByte() { Nybbles = new Nybble[2] { n2, n12 } }; HByte b45 = new HByte() { Nybbles = new Nybble[2] { n2, n13 } }; HByte b46 = new HByte() { Nybbles = new Nybble[2] { n2, n14 } }; HByte b47 = new HByte() { Nybbles = new Nybble[2] { n2, n15 } }; HByte b48 = new HByte() { Nybbles = new Nybble[2] { n3, n0 } }; HByte b49 = new HByte() { Nybbles = new Nybble[2] { n3, n1 } }; HByte b50 = new HByte() { Nybbles = new Nybble[2] { n3, n2 } }; HByte b51 = new HByte() { Nybbles = new Nybble[2] { n3, n3 } }; HByte b52 = new HByte() { Nybbles = new Nybble[2] { n3, n4 } }; HByte b53 = new HByte() { Nybbles = new Nybble[2] { n3, n5 } }; HByte b54 = new HByte() { Nybbles = new Nybble[2] { n3, n6 } }; HByte b55 = new HByte() { Nybbles = new Nybble[2] { n3, n7 } }; HByte b56 = new HByte() { Nybbles = new Nybble[2] { n3, n8 } }; HByte b57 = new HByte() { Nybbles = new Nybble[2] { n3, n9 } }; HByte b58 = new HByte() { Nybbles = new Nybble[2] { n3, n10 } }; HByte b59 = new HByte() { Nybbles = new Nybble[2] { n3, n11 } }; HByte b60 = new HByte() { Nybbles = new Nybble[2] { n3, n12 } }; HByte b61 = new HByte() { Nybbles = new Nybble[2] { n3, n13 } }; HByte b62 = new HByte() { Nybbles = new Nybble[2] { n3, n14 } }; HByte b63 = new HByte() { Nybbles = new Nybble[2] { n3, n15 } }; HByte b64 = new HByte() { Nybbles = new Nybble[2] { n4, n0 } }; HByte b65 = new HByte() { Nybbles = new Nybble[2] { n4, n1 } }; HByte b66 = new HByte() { Nybbles = new Nybble[2] { n4, n2 } }; HByte b67 = new HByte() { Nybbles = new Nybble[2] { n4, n3 } }; HByte b68 = new HByte() { Nybbles = new Nybble[2] { n4, n4 } }; HByte b69 = new HByte() { Nybbles = new Nybble[2] { n4, n5 } }; HByte b70 = new HByte() { Nybbles = new Nybble[2] { n4, n6 } }; HByte b71 = new HByte() { Nybbles = new Nybble[2] { n4, n7 } }; HByte b72 = new HByte() { Nybbles = new Nybble[2] { n4, n8 } }; HByte b73 = new HByte() { Nybbles = new Nybble[2] { n4, n9 } }; HByte b74 = new HByte() { Nybbles = new Nybble[2] { n4, n10 } }; HByte b75 = new HByte() { Nybbles = new Nybble[2] { n4, n11 } }; HByte b76 = new HByte() { Nybbles = new Nybble[2] { n4, n12 } }; HByte b77 = new HByte() { Nybbles = new Nybble[2] { n4, n13 } }; HByte b78 = new HByte() { Nybbles = new Nybble[2] { n4, n14 } }; HByte b79 = new HByte() { Nybbles = new Nybble[2] { n4, n15 } }; HByte b80 = new HByte() { Nybbles = new Nybble[2] { n5, n0 } }; HByte b81 = new HByte() { Nybbles = new Nybble[2] { n5, n1 } }; HByte b82 = new HByte() { Nybbles = new Nybble[2] { n5, n2 } }; HByte b83 = new HByte() { Nybbles = new Nybble[2] { n5, n3 } }; HByte b84 = new HByte() { Nybbles = new Nybble[2] { n5, n4 } }; HByte b85 = new HByte() { Nybbles = new Nybble[2] { n5, n5 } }; HByte b86 = new HByte() { Nybbles = new Nybble[2] { n5, n6 } }; HByte b87 = new HByte() { Nybbles = new Nybble[2] { n5, n7 } }; HByte b88 = new HByte() { Nybbles = new Nybble[2] { n5, n8 } }; HByte b89 = new HByte() { Nybbles = new Nybble[2] { n5, n9 } }; HByte b90 = new HByte() { Nybbles = new Nybble[2] { n5, n10 } }; HByte b91 = new HByte() { Nybbles = new Nybble[2] { n5, n11 } }; HByte b92 = new HByte() { Nybbles = new Nybble[2] { n5, n12 } }; HByte b93 = new HByte() { Nybbles = new Nybble[2] { n5, n13 } }; HByte b94 = new HByte() { Nybbles = new Nybble[2] { n5, n14 } }; HByte b95 = new HByte() { Nybbles = new Nybble[2] { n5, n15 } }; HByte b96 = new HByte() { Nybbles = new Nybble[2] { n6, n0 } }; HByte b97 = new HByte() { Nybbles = new Nybble[2] { n6, n1 } }; HByte b98 = new HByte() { Nybbles = new Nybble[2] { n6, n2 } }; HByte b99 = new HByte() { Nybbles = new Nybble[2] { n6, n3 } }; HByte b100 = new HByte() { Nybbles = new Nybble[2] { n6, n4 } }; HByte b101 = new HByte() { Nybbles = new Nybble[2] { n6, n5 } }; HByte b102 = new HByte() { Nybbles = new Nybble[2] { n6, n6 } }; HByte b103 = new HByte() { Nybbles = new Nybble[2] { n6, n7 } }; HByte b104 = new HByte() { Nybbles = new Nybble[2] { n6, n8 } }; HByte b105 = new HByte() { Nybbles = new Nybble[2] { n6, n9 } }; HByte b106 = new HByte() { Nybbles = new Nybble[2] { n6, n10 } }; HByte b107 = new HByte() { Nybbles = new Nybble[2] { n6, n11 } }; HByte b108 = new HByte() { Nybbles = new Nybble[2] { n6, n12 } }; HByte b109 = new HByte() { Nybbles = new Nybble[2] { n6, n13 } }; HByte b110 = new HByte() { Nybbles = new Nybble[2] { n6, n14 } }; HByte b111 = new HByte() { Nybbles = new Nybble[2] { n6, n15 } }; HByte b112 = new HByte() { Nybbles = new Nybble[2] { n7, n0 } }; HByte b113 = new HByte() { Nybbles = new Nybble[2] { n7, n1 } }; HByte b114 = new HByte() { Nybbles = new Nybble[2] { n7, n2 } }; HByte b115 = new HByte() { Nybbles = new Nybble[2] { n7, n3 } }; HByte b116 = new HByte() { Nybbles = new Nybble[2] { n7, n4 } }; HByte b117 = new HByte() { Nybbles = new Nybble[2] { n7, n5 } }; HByte b118 = new HByte() { Nybbles = new Nybble[2] { n7, n6 } }; HByte b119 = new HByte() { Nybbles = new Nybble[2] { n7, n7 } }; HByte b120 = new HByte() { Nybbles = new Nybble[2] { n7, n8 } }; HChar c0 = new HChar() { Code = b0 }; HChar c1 = new HChar() { Code = b1 }; HChar c2 = new HChar() { Code = b2 }; HChar c3 = new HChar() { Code = b3 }; HChar c4 = new HChar() { Code = b4 }; HChar c5 = new HChar() { Code = b5 }; HChar c6 = new HChar() { Code = b6 }; HChar c7 = new HChar() { Code = b7 }; HChar c8 = new HChar() { Code = b8 }; HChar c9 = new HChar() { Code = b9 }; HChar c10 = new HChar() { Code = b10 }; HChar c11 = new HChar() { Code = b11 }; HChar c12 = new HChar() { Code = b12 }; HChar c13 = new HChar() { Code = b13 }; HChar c14 = new HChar() { Code = b14 }; HChar c15 = new HChar() { Code = b15 }; HChar c16 = new HChar() { Code = b16 }; HChar c17 = new HChar() { Code = b17 }; HChar c18 = new HChar() { Code = b18 }; HChar c19 = new HChar() { Code = b19 }; HChar c20 = new HChar() { Code = b20 }; HChar c21 = new HChar() { Code = b21 }; HChar c22 = new HChar() { Code = b22 }; HChar c23 = new HChar() { Code = b23 }; HChar c24 = new HChar() { Code = b24 }; HChar c25 = new HChar() { Code = b25 }; HChar c26 = new HChar() { Code = b26 }; HChar c27 = new HChar() { Code = b27 }; HChar c28 = new HChar() { Code = b28 }; HChar c29 = new HChar() { Code = b29 }; HChar c30 = new HChar() { Code = b30 }; HChar c31 = new HChar() { Code = b31 }; HChar c32 = new HChar() { Code = b32 }; HChar c33 = new HChar() { Code = b33 }; HChar c34 = new HChar() { Code = b34 }; HChar c35 = new HChar() { Code = b35 }; HChar c36 = new HChar() { Code = b36 }; HChar c37 = new HChar() { Code = b37 }; HChar c38 = new HChar() { Code = b38 }; HChar c39 = new HChar() { Code = b39 }; HChar c40 = new HChar() { Code = b40 }; HChar c41 = new HChar() { Code = b41 }; HChar c42 = new HChar() { Code = b42 }; HChar c43 = new HChar() { Code = b43 }; HChar c44 = new HChar() { Code = b44 }; HChar c45 = new HChar() { Code = b45 }; HChar c46 = new HChar() { Code = b46 }; HChar c47 = new HChar() { Code = b47 }; HChar c48 = new HChar() { Code = b48 }; HChar c49 = new HChar() { Code = b49 }; HChar c50 = new HChar() { Code = b50 }; HChar c51 = new HChar() { Code = b51 }; HChar c52 = new HChar() { Code = b52 }; HChar c53 = new HChar() { Code = b53 }; HChar c54 = new HChar() { Code = b54 }; HChar c55 = new HChar() { Code = b55 }; HChar c56 = new HChar() { Code = b56 }; HChar c57 = new HChar() { Code = b57 }; HChar c58 = new HChar() { Code = b58 }; HChar c59 = new HChar() { Code = b59 }; HChar c60 = new HChar() { Code = b60 }; HChar c61 = new HChar() { Code = b61 }; HChar c62 = new HChar() { Code = b62 }; HChar c63 = new HChar() { Code = b63 }; HChar c64 = new HChar() { Code = b64 }; HChar c65 = new HChar() { Code = b65 }; HChar c66 = new HChar() { Code = b66 }; HChar c67 = new HChar() { Code = b67 }; HChar c68 = new HChar() { Code = b68 }; HChar c69 = new HChar() { Code = b69 }; HChar c70 = new HChar() { Code = b70 }; HChar c71 = new HChar() { Code = b71 }; HChar c72 = new HChar() { Code = b72 }; HChar c73 = new HChar() { Code = b73 }; HChar c74 = new HChar() { Code = b74 }; HChar c75 = new HChar() { Code = b75 }; HChar c76 = new HChar() { Code = b76 }; HChar c77 = new HChar() { Code = b77 }; HChar c78 = new HChar() { Code = b78 }; HChar c79 = new HChar() { Code = b79 }; HChar c80 = new HChar() { Code = b80 }; HChar c81 = new HChar() { Code = b81 }; HChar c82 = new HChar() { Code = b82 }; HChar c83 = new HChar() { Code = b83 }; HChar c84 = new HChar() { Code = b84 }; HChar c85 = new HChar() { Code = b85 }; HChar c86 = new HChar() { Code = b86 }; HChar c87 = new HChar() { Code = b87 }; HChar c88 = new HChar() { Code = b88 }; HChar c89 = new HChar() { Code = b89 }; HChar c90 = new HChar() { Code = b90 }; HChar c91 = new HChar() { Code = b91 }; HChar c92 = new HChar() { Code = b92 }; HChar c93 = new HChar() { Code = b93 }; HChar c94 = new HChar() { Code = b94 }; HChar c95 = new HChar() { Code = b95 }; HChar c96 = new HChar() { Code = b96 }; HChar c97 = new HChar() { Code = b97 }; HChar c98 = new HChar() { Code = b98 }; HChar c99 = new HChar() { Code = b99 }; HChar c100 = new HChar() { Code = b100 }; HChar c101 = new HChar() { Code = b101 }; HChar c102 = new HChar() { Code = b102 }; HChar c103 = new HChar() { Code = b103 }; HChar c104 = new HChar() { Code = b104 }; HChar c105 = new HChar() { Code = b105 }; HChar c106 = new HChar() { Code = b106 }; HChar c107 = new HChar() { Code = b107 }; HChar c108 = new HChar() { Code = b108 }; HChar c109 = new HChar() { Code = b109 }; HChar c110 = new HChar() { Code = b110 }; HChar c111 = new HChar() { Code = b111 }; HChar c112 = new HChar() { Code = b112 }; HChar c113 = new HChar() { Code = b113 }; HChar c114 = new HChar() { Code = b114 }; HChar c115 = new HChar() { Code = b115 }; HChar c116 = new HChar() { Code = b116 }; HChar c117 = new HChar() { Code = b117 }; HChar c118 = new HChar() { Code = b118 }; HChar c119 = new HChar() { Code = b119 }; HChar c120 = new HChar() { Code = b120 }; //72 101 108 108 111 32 87 111 114 108 100 Console.WriteLine(c72.ToChar() + "" + c101.ToChar() + c108.ToChar() + c108.ToChar() + c111.ToChar() + c32.ToChar() + c87.ToChar() + c111.ToChar() + c114.ToChar() + c108.ToChar() + c100.ToChar()); Console.ReadLine(); } public static string FixString(string s, int length) { return s.Length < length ? FixString("0" + s, length) : s; } } class HChar { private HByte code; public HChar() { code = new HByte(); } public HByte Code { get { return code; } set { code = value; } } public char ToChar() { return (char)Convert.ToUInt32(code + "", 2); } public override string ToString() { return base.ToString(); } } struct Bit { private bool state; public bool State { get { return state; } set { state = value; } } public override string ToString() { return state ? "1" : "0"; } } class Nybble { private Bit[] bits; public Nybble() { bits = new Bit[4]; } public Bit[] Bits { get { return bits; } set { bits = value; } } public static Nybble Parse(string s) { s = P.FixString(s, 4); Nybble n = new Nybble(); for (int i = 0; i < 4; i++) { n.bits[i].State = s[i] == '1'; } return n; } public override string ToString() { Text.StringBuilder sb = new Text.StringBuilder(); foreach (Bit b in bits ) { sb.Append(b + ""); } return sb + ""; } } class HByte { private Nybble[] nybbles; public HByte() { nybbles = new Nybble[2]; } public Nybble[] Nybbles { get { return nybbles; } set { nybbles = value; } } public static HByte SetAsByte(byte b) { var hb = new HByte(); hb.Nybbles[0] = Nybble.Parse(Convert.ToString((byte)(b << 4) >> 4, 2)); hb.Nybbles[1] = Nybble.Parse(Convert.ToString((b >> 4), 2)); return hb; } public static HByte Parse(string s) { s = P.FixString(s, 8); var hb = new HByte(); for (int i = 0; i < 2; i++) hb.Nybbles[i] = Nybble.Parse(s.Substring(i * 4, 4)); return hb; } public override string ToString() { return nybbles[0] + "" + nybbles[1]; } } } ``` [Answer] ``` package my.complex.hello.world; /** * Messages have the purpose to be passed as communication between * different parts of the system. * @param <B> The type of the message content. */ public interface Message<B> { /** * Returns the body of the message. * @return The body of the message. */ public B getMessageBody(); /** * Shows this message in the given display. * @param display The {@linkplain Display} where the message should be show. */ public void render(Display display); } ``` ``` package my.complex.hello.world; /** * This abstract class is a partial implementation of the {@linkplain Message} * interface, which provides a implementation for the {@linkplain #getMessageBody()} * method. * @param <B> The type of the message content. */ public abstract class AbstractGenericMessageImpl<B> implements Message<B> { private B messageBody; public GenericMessageImpl(B messageBody) { this.messageBody = messageBody; } public void setMessageBody(B messageBody) { this.messageBody = messageBody; } @Override public B getMessageBody() { return messageContent; } } ``` ``` package my.complex.hello.world; public class StringMessage extends AbstractGenericMessageImpl<String> { public StringText(String text) { super(text); } /** * {@inheritDoc} * @param display {@inheritDoc} */ @Override public void render(Display display) { if (display == null) { throw new IllegalArgumentException("The display should not be null."); } display.printString(text); display.newLine(); } } ``` ``` package my.complex.hello.world; import java.awt.Color; import java.awt.Image; /** * A {@code Display} is a canvas where objects can be drawn as output. */ public interface Display { public void printString(String text); public void newLine(); public Color getColor(); public void setColor(Color color); public Color getBackgroundColor(); public void setBackgroundColor(Color color); public void setXPosition(int xPosition); public int getXPosition(); public void setYPosition(int yPosition); public int getYPosition(); public void setFontSize(int fontSize); public int getFontSize(); public void setDrawAngle(float drawAngle); public float getDrawAngle(); public void drawImage(Image image); public void putPixel(); } ``` ``` package my.complex.hello.world; import java.awt.Color; import java.awt.Image; import java.io.PrintStream; /** * The {@code ConsoleDisplay} is a type of {@linkplain Display} that renders text * output to {@linkplain PrintWriter}s. This is a very primitive type of * {@linkplain Display} and is not capable of any complex drawing operations. * All the drawing methods throws an {@linkplain UnsupportedOpeartionException}. */ public class ConsoleDisplay implements Display { private PrintWriter writer; public ConsoleDisplay(PrintWriter writer) { this.writer = writer; } public void setWriter(PrintWriter writer) { this.writer = writer; } public PrintWriter getWriter() { return writer; } @Override public void printString(String text) { writer.print(text); } @Override public void newLine() { writer.println(); } @Override public Color getColor() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void setColor(Color color) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public Color getBackgroundColor() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void setBackgroundColor(Color color) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void setXPosition(int xPosition) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public int getXPosition() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void setYPosition(int yPosition) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public int getYPosition() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void setFontSize(int fontSize) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public int getFontSize() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void setDrawAngle(float drawAngle) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public float getDrawAngle() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void drawImage(Image image) { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } @Override public void putPixel() { throw new UnsupportedOperationExcepion("The Console display can't operate with graphics."); } } ``` ``` package my.complex.hello.world; /** * A {@linkplain Display} is a complex object. To decouple the creation of the * {@linkplain Display} from it's use, an object for it's creation is needed. This * interface provides a way to get instances of these {@linkplain Display}s. */ public interface DisplayFactory { public Display getDisplay(); } ``` ``` package my.complex.hello.world; /** * A {@linkplain DisplayFactory} that always produces {@linkplain ConsoleDisplay}s * based on the {@linkplain System#out} field. This class is a singleton, and instances * should be obtained through the {@linkplain #getInstance()} method. */ public final class ConsoleDisplayFactory implements DisplayFactory { private static final ConsoleDisplayFactory instance = new ConsoleDisplayFactory(); private final ConsoleDisplay display; public static ConsoleDisplayFactory getInstance() { return instance; } private ConsoleDisplayFactory() { display = new ConsoleDisplay(System.out); } @Override public ConsoleDisplay getDisplay() { return display; } } ``` ``` package my.complex.hello.world; public class Main { public static void main(String[] args) { Display display = ConsoleDisplay.getInstance().getDisplay(); StringMessage message = new StringMessage("Hello World"); message.render(display); } } ``` I will add some comments later. [Answer] ## Points: 183 * 62 statements\* * 10 classes + 25 methods (properties' getters & setters are distinct) + 8 variable declarations (I think) = 43 declarations of something * No module use statements. It does have some defaults, though, and using the full qualification was part of my bowling. So maybe 1 for `System`? Well, anyway, let's say 0. * 1 source file. * Not a language that uses forward declarations. Well, 1 `MustOverride`, which I will count. * 76 control statements. Not counted manually so may be slightly inaccurate. **Total: 62 + 43 + 0 + 1 + 1 + 76 = 183** ## Entry ``` Public NotInheritable Class OptimizedStringFactory Private Shared ReadOnly _stringCache As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of Char)) = New System.Collections.Generic.List(Of System.Collections.Generic.IEnumerable(Of Char)) Private Shared ReadOnly Property StringCache() As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of Char)) Get Debug.Assert(OptimizedStringFactory._stringCache IsNot Nothing) Return OptimizedStringFactory._stringCache End Get End Property Public Shared Function GetOrCache(ByRef s As System.Collections.Generic.IEnumerable(Of Char)) As String If s IsNot Nothing Then Dim equalFlag As Boolean = False For Each cachedStringItemInCache As System.Collections.Generic.IEnumerable(Of Char) In OptimizedStringFactory.StringCache equalFlag = True For currentStringCharacterIndex As Integer = 0 To cachedStringItemInCache.Count() - 1 If equalFlag AndAlso cachedStringItemInCache.Skip(currentStringCharacterIndex).FirstOrDefault() <> s.Skip(currentStringCharacterIndex).FirstOrDefault() Then equalFlag = False End If Next If Not equalFlag Then Continue For End If Return New String(cachedStringItemInCache.ToArray()) Next DirectCast(OptimizedStringFactory.StringCache, System.Collections.Generic.IList(Of System.Collections.Generic.IEnumerable(Of Char))).Add(s) Return OptimizedStringFactory.GetOrCache(s) End If End Function End Class Public MustInherit Class ConcurrentCharacterOutputter Public Event OutputComplete() Private _previousCharacter As ConcurrentCharacterOutputter Private _canOutput, _shouldOutput As Boolean Public WriteOnly Property PreviousCharacter() As ConcurrentCharacterOutputter Set(ByVal value As ConcurrentCharacterOutputter) If Me._previousCharacter IsNot Nothing Then RemoveHandler Me._previousCharacter.OutputComplete, AddressOf Me.DoOutput End If Me._previousCharacter = value If value IsNot Nothing Then AddHandler Me._previousCharacter.OutputComplete, AddressOf Me.DoOutput End If End Set End Property Protected Property CanOutput() As Boolean Get Return _canOutput End Get Set(ByVal value As Boolean) Debug.Assert(value OrElse Not value) _canOutput = value End Set End Property Protected Property ShouldOutput() As Boolean Get Return _shouldOutput End Get Set(ByVal value As Boolean) Debug.Assert(value OrElse Not value) _shouldOutput = value End Set End Property Protected MustOverride Sub DoOutput() Public Sub Output() Me.CanOutput = True If Me.ShouldOutput OrElse Me._previousCharacter Is Nothing Then Me.CanOutput = True Me.DoOutput() End If End Sub Protected Sub Finished() RaiseEvent OutputComplete() End Sub End Class Public NotInheritable Class HCharacter Inherits ConcurrentCharacterOutputter Protected Overrides Sub DoOutput() If Me.CanOutput Then Console.Write("H"c) Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public NotInheritable Class ECharacter Inherits ConcurrentCharacterOutputter Protected Overrides Sub DoOutput() If Me.CanOutput Then Console.Write("e"c) Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public NotInheritable Class WCharacter Inherits ConcurrentCharacterOutputter Protected Overrides Sub DoOutput() If Me.CanOutput Then Console.Write("w"c) Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public NotInheritable Class OCharacter Inherits ConcurrentCharacterOutputter Private Shared Called As Boolean = False Protected Overrides Sub DoOutput() If Me.CanOutput Then If OCharacter.Called Then Console.Write("o"c) Else Console.Write("o ") OCharacter.Called = True End If Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public NotInheritable Class RCharacter Inherits ConcurrentCharacterOutputter Protected Overrides Sub DoOutput() If Me.CanOutput Then Console.Write("r"c) Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public NotInheritable Class LCharacter Inherits ConcurrentCharacterOutputter Protected Overrides Sub DoOutput() If Me.CanOutput Then Console.Write("l"c) Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public NotInheritable Class DCharacter Inherits ConcurrentCharacterOutputter Protected Overrides Sub DoOutput() If Me.CanOutput Then Console.WriteLine("d") Me.Finished() Else Me.ShouldOutput = True End If End Sub End Class Public Module MainApplicationModule Private Function CreateThread(ByVal c As Char) As System.Threading.Thread Static last As ConcurrentCharacterOutputter Dim a As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly() Dim cco As ConcurrentCharacterOutputter = DirectCast(a.CreateInstance(GetType(MainApplicationModule).Namespace & "."c & Char.ToUpper(c) & "Character"), ConcurrentCharacterOutputter) cco.PreviousCharacter = last last = cco Return New System.Threading.Thread(AddressOf cco.Output) With {.IsBackground = True} End Function Public Sub Main() Dim threads As New List(Of System.Threading.Thread) For Each c As Char In "Helloworld" threads.Add(MainApplicationModule.CreateThread(c)) Next For Each t As System.Threading.Thread In threads t.Start() Next For Each t As System.Threading.Thread In threads t.Join() Next End Sub End Module ``` ## Documentation * There are no comments in the code. This helps reduce clutter, and comments are unnecessary regardless because I am the sole developer and we have this amazing, detailed documentation - once again written by yours truly. * The `OptimizedStringFactory` holds optimized strings. It has a cache that allows references to efficient `IEnumerable(Of Char)`s to be used, while avoiding the inherent problems of references. It has been brought to my attention that .NET includes some kind of string pool. However, built-in caching doesn't know enough about the objects we are using - it's unreliable, so I have created my own solution. * The `ConcurrentOutputCharacter` class allows for easy synchronization of multithreaded, single-character output. This stops the output from getting garbled. In the best practices of object-oriented programming, it's declared `MustInherit` and every character or string to output is derived from it, and also declared `NotInheritable`. It contains several assertions to assure valid data is being passed. * Each `*Character` contains a single character for our specific case of string output. * The main module contains the code for creating the threads. Threading is a very new feature that allows us to take advantage of multicore processors and process output more efficiently. To prevent code duplication, I've used a loop to create the characters. # Beautiful, no? It's even extensible, due to the aforementioned loops and inheritance, plus the dynamic, reflection-based class loading. This also prevents overzealous obfuscation, so nobody can claim our code by obfuscating it. To change the strings, simply create a dictionary that maps input characters to different output character classes before the reflection code loads them dynamically. [Answer] # Javascript, a LOT of points * Fully integrated i18n support * Multiplatform JS, can run on Node and web browsers with customizable context (browsers should use "window") * Configurable data source, uses static "Hello world" message by default (for performance) * Completely async, great concurrency * Good debugging mode, with time analysis on code invoke. Here we go: ``` (function(context){ /** * Basic app configuration */ var config = { DEBUG: true, WRITER_SIGNATURE: "write", LANGUAGE: "en-US" // default language }; /** * Hardcoded translation data */ var translationData = { "en-US": { "hello_world": "Hello World!", // greeting in main view "invocation": "invoked", // date of invokation "styled_invocation": "[%str%]" // some decoration for better style } }; /** * Internationalization module * Supports dynamic formatting and language pick after load */ var i18n = (function(){ return { format: function(source, info){ // properly formats a i18n resource return source.replace("%str%", info); }, originTranslate: function(origin){ var invoc_stf = i18n.translate("invocation") + " " + origin.lastModified; return i18n.format(i18n.translate("styled_invocation"), invoc_stf); }, translate: function(message){ var localData = translationData[config.LANGUAGE]; return localData[message]; }, get: function(message, origin){ var timestamp = origin.lastModified; if(config.DEBUG) return i18n.translate(message) + " " + i18n.originTranslate(origin); else return i18n.translate(message); } }; }()); /** * A clone of a document-wrapper containing valid, ready DOM */ var fallbackDocument = function(){ var _document = function(){ this.native_context = context; this.modules = new Array(); }; _document.prototype.clear = function(){ for(var i = 0; i < this.modules.length; i++){ var module = this.modules[i]; module.signalClear(); }; }; return _document; }; /** * Provides a native document, scoped to the context * Uses a fallback if document not initialized or not supported */ var provideDocument = function(){ if(typeof context.document == "undefined") context.document = new fallbackDocument(); context.document.lastModified = new context.Date(); context.document.exception = function(string_exception){ this.origin = context.navigator; this.serialized = string_exception; }; return context.document; }; /** * Sends a data request, and tries to call the document writer */ var documentPrinter = function(document, dataCallback){ if(dataCallback == null) throw new document.exception("Did not receive a data callback!"); data = i18n.get(dataCallback(), document); // translate data into proper lang. if(typeof document[config.WRITER_SIGNATURE] == "undefined") throw new document.exception("Document provides no valid writer!"); var writer = document[config.WRITER_SIGNATURE]; writer.apply(document, [data]); //apply the writer using correct context }; /** * Produces a "Hello world" message-box * Warning! Message may vary depending on initial configuration */ var HelloWorldFactory = (function(){ return function(){ this.produceMessage = function(){ this.validDocument = provideDocument(); new documentPrinter(this.validDocument, function(){ return "hello_world"; }); }; }; }()); context.onload = function(){ // f**k yeah! we are ready try{ var newFactory = new HelloWorldFactory(); newFactory.produceMessage(); } catch(err){ console.log(err); // silently log the error }; }; }(window || {})); ``` [Answer] ## C Program for Hello World:9(?) ``` #include<stdio.h> void main(){ char a[100]={4,1,8,8,11,-68,19,11,14,8,0,0}; for(;a[12]<a[4];a[12]++) { printf("%c",sizeof(a)+a[a[12]]); } } ``` Combination of ASCII Characters and character array containing integer! Basically,Printing Every digit in character format. [Answer] ## Python using if-else statements ``` from itertools import permutations from sys import stdout, argv reference = { 100: 'd', 101: 'e', 104: 'h', 108: 'l', 111: 'o', 114: 'r', 119: 'w' } vowels = [ 'e', 'o' ] words = [ { 'len': 5, 'first': 104, 'last': 111, 'repeat': True, 'r_char': 108 }, { 'len': 5, 'first': 119, 'last': 100, 'repeat': False, 'r_char': None } ] second_last = 108 def find_words(repeat, r_char): output = [] chars = [ y for x, y in reference.iteritems() ] if repeat: chars.append(reference[r_char]) for value in xrange(0, len(chars)): output += [ x for x in permutations(chars[value:]) ] return output def filter_word(value, first, last, repeat, r_char): output = False value = [ x for x in value ] first_char, second_char, second_last_char, last_char = value[0], value[1], value[-2], value[-1] if first_char == first and last_char == last and second_char != last_char and ord(second_last_char) == second_last: if second_char in vowels and second_char in [ y for x, y in reference.iteritems() ]: string = [] last = None for char in value: if last != None: if char == last and char not in vowels: string.append(char) elif char != last: string.append(char) else: string.append(char) last = char if len(string) == len(value): if repeat: last = None for char in value: if last != None: if char == last: output = True last = char else: third_char = value[2] if ord(third_char) > ord(second_last_char) and ord(second_char) > ord(second_last_char): output = True return output def find_word(values, first, last, length, repeat, r_char): first, last, output, items, count = reference[first], reference[last], [], [], 0 if repeat: r_char = reference[r_char] for value in values: count += 1 for item in [ x[:length] for x in permutations(value) ]: item = ''.join(item) if item not in items and filter_word(value=item, first=first, last=last, r_char=r_char, repeat=repeat): items.append(item) if debug: count_out = '(%s/%s) (%s%%) (%s found)' % (count, len(values), (round(100 * float(count) / float(len(values)), 2)), len(items)) stdout.write('%s%s' % (('\r' * len(count_out)), count_out)) stdout.flush() if len(items) >= 1 and aggressive: break for item in items: output.append(item) return output if __name__ == '__main__': debug = 'debug' in argv aggressive = 'aggressive' not in argv if debug: print 'Building string...' data = [] for word in words: repeat = word['repeat'] r_char = word['r_char'] length = word['len'] first_letter = word['first'] last_letter = word['last'] possible = find_words(repeat=repeat, r_char=r_char) data.append(find_word(values=possible, first=first_letter, last=last_letter, length=5, repeat=repeat, r_char=r_char)) print ' '.join(x[0] for x in data) ``` **Explanation** This creates a dictionary of ASCII values and their associated characters as it will permit the code to only use those values and nothing else. We ensure that we reference vowels in a separate list and then let it be known that the second last character repeats itself in both strings. Having done that, we create a list of dictionaries with set rules defining the word length, its first, last, and repeating characters, and then also set a true/false statement for if repeats should be checked. Once this is done, the script iterates through the list of dictionaries and feeds it through a function that creates all possible permutations of characters from the reference dictionary, taking care to add any repeating characters if necessary. Afterward, it is then fed through a second function that creates even more permutations for each permutation, but setting a maximum length. This is done to ensure that we find the words that we want to chew through. During this process, it then feeds it through a function that uses a combination of if-else statements that determines if it is worthy of being spat out. If the permutation matches what the statements are calling for, it then spits out a true/false statement and the function that called it adds it to a list. Once this is done, the script then takes the first item from each list and combines them to state "hello world". I added some debug features too to let you know how slow it is going. I chose to do this as you don't need to write "hello world" to have it spit out "hello world" if you know how to construct the sentence. [Answer] Well, this is good. ``` [ uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820) ] library LHello { // bring in the master library importlib("actimp.tlb"); importlib("actexp.tlb"); // bring in my interfaces #include "pshlo.idl" [ uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820) ] cotype THello { interface IHello; interface IPersistFile; }; }; [ exe, uuid(2573F890-CFEE-101A-9A9F-00AA00342820) ] module CHelloLib { // some code related header files importheader(<windows.h>); importheader(<ole2.h>); importheader(<except.hxx>); importheader("pshlo.h"); importheader("shlo.hxx"); importheader("mycls.hxx"); // needed typelibs importlib("actimp.tlb"); importlib("actexp.tlb"); importlib("thlo.tlb"); [ uuid(2573F891-CFEE-101A-9A9F-00AA00342820), aggregatable ] coclass CHello { cotype THello; }; }; #include "ipfix.hxx" extern HANDLE hEvent; class CHello : public CHelloBase { public: IPFIX(CLSID_CHello); CHello(IUnknown *pUnk); ~CHello(); HRESULT __stdcall PrintSz(LPWSTR pwszString); private: static int cObjRef; }; #include <windows.h> #include <ole2.h> #include <stdio.h> #include <stdlib.h> #include "thlo.h" #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx" int CHello::cObjRef = 0; CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk) { cObjRef++; return; } HRESULT __stdcall CHello::PrintSz(LPWSTR pwszString) { printf("%ws ", pwszString); return(ResultFromScode(S_OK)); } CHello::~CHello(void) { // when the object count goes to zero, stop the server cObjRef--; if( cObjRef == 0 ) PulseEvent(hEvent); return; } #include <windows.h> #include <ole2.h> #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx" HANDLE hEvent; int _cdecl main( int argc, char * argv[] ) { ULONG ulRef; DWORD dwRegistration; CHelloCF *pCF = new CHelloCF(); hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); // Initialize the OLE libraries CoInitializeEx(NULL, COINIT_MULTITHREADED); CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegistration); // wait on an event to stop WaitForSingleObject(hEvent, INFINITE); // revoke and release the class object CoRevokeClassObject(dwRegistration); ulRef = pCF->Release(); // Tell OLE we are going away. CoUninitialize(); return(0); } extern CLSID CLSID_CHello; extern UUID LIBID_CHelloLib; CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */ 0x2573F891, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */ 0x2573F890, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; #include <windows.h> #include <ole2.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "pshlo.h" #include "shlo.hxx" #include "clsid.h" int _cdecl main( int argc, char * argv[] ) { HRESULT hRslt; IHello *pHello; ULONG ulCnt; IMoniker * pmk; WCHAR wcsT[_MAX_PATH]; WCHAR wcsPath[2 * _MAX_PATH]; // get object path wcsPath[0] = '\0'; wcsT[0] = '\0'; if( argc > 1) { mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1); wcsupr(wcsPath); } else { fprintf(stderr, "Object path must be specified\n"); return(1); } // get print string if(argc > 2) mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1); else wcscpy(wcsT, L"Hello World"); printf("Linking to object %ws\n", wcsPath); printf("Text String %ws\n", wcsT); // Initialize the OLE libraries hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(SUCCEEDED(hRslt)) { hRslt = CreateFileMoniker(wcsPath, &pmk); if(SUCCEEDED(hRslt)) hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello); if(SUCCEEDED(hRslt)) { // print a string out pHello->PrintSz(wcsT); Sleep(2000); ulCnt = pHello->Release(); } else printf("Failure to connect, status: %lx", hRslt); // Tell OLE we are going away. CoUninitialize(); } return(0); } ``` [Answer] ## Golf-Basic 84, 9 Points ``` i`I@I:1_A#:0_A@I:0_A#:Endt`Hello World" ``` **Explanation** ``` i`I ``` Ask the user if they want to quit ``` @I:1_A#0_A ``` Record their answer ``` @I:0_A#:End ``` If they did in fact wish to end, it terminates ``` t`Hello World" ``` If they didn't end, it prints Hello World. [Answer] Hashes and then brute-force de-hashes the characters for "Hello, World!", adds those to a `StringBuilder`, and logs that with a Logger. ``` import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; import sun.security.provider.SHA2; /** * ComplexHelloWorld, made for a challenge, is copyright Blue Husky Programming ©2014 GPLv3<HR/> * * @author Kyli Rouge of Blue Husky Programming * @version 1.0.0 * @since 2014-02-19 */ public class ComplexHelloWorld { private static final SHA2 SHA2; private static final byte[] OBJECTIVE_BYTES; private static final String OBJECTIVE; public static final String[] HASHES; private static final Logger LOGGER; static { SHA2 = new SHA2(); OBJECTIVE_BYTES = new byte[] { 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33 }; OBJECTIVE = new String(OBJECTIVE_BYTES); HASHES = hashAllChars(OBJECTIVE); LOGGER = Logger.getLogger(ComplexHelloWorld.class.getName()); } public static String hash(String password) { String algorithm = "SHA-256"; MessageDigest sha256; try { sha256 = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException ex) { try { LOGGER.logrb(Level.SEVERE, ComplexHelloWorld.class.getName(), "hash", null, "There is no such algorithm as " + algorithm, ex); } catch (Throwable t2) { //welp. } return "[ERROR]"; } byte[] passBytes = password.getBytes(); byte[] passHash = sha256.digest(passBytes); return new String(passHash); } public static void main(String... args) { StringBuilder sb = new StringBuilder(); allHashes: for (String hash : HASHES) checking: for (char c = 0; c < 256; c++) if (hash(c + "").equals(hash)) try { sb.append(c); break checking; } catch (Throwable t) { try { LOGGER.logrb(Level.SEVERE, ComplexHelloWorld.class.getName(), "main", null, "An unexpected error occurred", t); } catch (Throwable t2) { //welp. } } try { LOGGER.logrb(Level.INFO, ComplexHelloWorld.class.getName(), "main", null, sb + "", new Object[] { }); } catch (Throwable t) { try { LOGGER.logrb(Level.SEVERE, ComplexHelloWorld.class.getName(), "main", null, "An unexpected error occurred", t); } catch (Throwable t2) { //welp. } } } private static String[] hashAllChars(String passwords) { String[] ret = new String[passwords.length()]; for (int i = 0; i < ret.length; i++) ret[i] = hash(passwords.charAt(i) + ""); return ret; } } ``` [Answer] ## C# - 158 I tell you what, developers these days, paying no attention to SOLID principles. People these days neglect how important it is to do even the simple tasks properly. First, we need to start with requirements: * Prints the specified string to the console * Allows for localization * Follows SOLID principles First, let's start with localization. To properly localize strings, we need an alias for the string to use within the program, and the locale we want the string in. We obviously need to store this data in an easily interoperable format, XML. And to do XML properly, we need a schema. StringDictionary.xsd ``` <?xml version="1.0" encoding="utf-8"?> <xs:schema id="StringDictionary" targetNamespace="http://stackoverflow.com/StringDictionary.xsd" elementFormDefault="qualified" xmlns="http://stackoverflow.com/StringDictionary.xsd" xmlns:mstns="http://stackoverflow.com/StringDictionary.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="stringDictionary" type="localizedStringDictionary"/> <xs:complexType name="localizedStringDictionary"> <xs:sequence minOccurs="1" maxOccurs="unbounded"> <xs:element name="localized" type="namedStringElement"></xs:element> </xs:sequence> </xs:complexType> <xs:complexType name="localizedStringElement"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="locale" type="xs:string"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="namedStringElement"> <xs:sequence minOccurs="1" maxOccurs="unbounded"> <xs:element name="translated" type="localizedStringElement"></xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string"></xs:attribute> </xs:complexType> ``` This defines our XML structure and gets us off to a good start. Next, we need the XML file itself, containing the strings. Make this file an embedded resource in your project. ``` <?xml version="1.0" encoding="utf-8" ?> <stringDictionary xmlns="http://stackoverflow.com/StringDictionary.xsd"> <localized name="helloWorld"> <translated locale="en-US">Hello, World</translated> <translated locale="ja-JP">こんにちは世界</translated> </localized> </stringDictionary> ``` With that out of the way, one thing we absolutely do not want is any hard coded strings in our program. Use Visual Studio to make resources in your project that we will use for our strings. Ensure to change `XmlDictionaryName` to match the name of your XML strings file defined earlier. [![enter image description here](https://i.stack.imgur.com/TBuru.png)](https://i.stack.imgur.com/TBuru.png) Since we're dependency inversion, we need a dependency container to handle registering and creating our objects. IDependencyRegister.cs ``` public interface IDependencyRegister { void Register<T1, T2>(); } ``` IDependencyResolver.cs ``` public interface IDependencyResolver { T Get<T>(); object Get(Type type); } ``` We can provide a simple implementation of both of these interfaces together on one class. DependencyProvider.cs ``` public class DependencyProvider : IDependencyRegister, IDependencyResolver { private IReadOnlyDictionary<Type, Func<object>> _typeRegistration; public DependencyProvider() { _typeRegistration = new Dictionary<Type, Func<object>>(); } public void Register<T1, T2>() { var newDict = new Dictionary<Type, Func<object>>((IDictionary<Type, Func<object>>)_typeRegistration) { [typeof(T1)] = () => Get(typeof(T2)) }; _typeRegistration = newDict; } public object Get(Type type) { Func<object> creator; if (_typeRegistration.TryGetValue(type, out creator)) return creator(); else if (!type.IsAbstract) return this.CreateInstance(type); else throw new InvalidOperationException("No registration for " + type); } public T Get<T>() { return (T)Get(typeof(T)); } private object CreateInstance(Type implementationType) { var ctor = implementationType.GetConstructors().Single(); var parameterTypes = ctor.GetParameters().Select(p => p.ParameterType); var dependencies = parameterTypes.Select(Get).ToArray(); return Activator.CreateInstance(implementationType, dependencies); } } ``` Starting at the lowest level and working our way up, we need a way to read the XML. Following the `S` and `I` in SOLID, we define an interface that our XML string dictionary code uses: ``` public interface IStringDictionaryStore { string GetLocalizedString(string name, string locale); } ``` Thinking about proper design for performance. Retrieving these strings is going to be on the critical path on our program. And we want to be sure that we always retrieve the correct string. For this, we're going to use a dictionary where they key is the hash of the string name and locale, and the value contains our translated string. Once again, following the single responsibility principle, our string dictionary should not care how the strings are hashed, so we make an interface, and provide a basic implementation IStringHasher.cs ``` public interface IStringHasher { string HashString(string name, string locale); } ``` Sha512StringHasher.cs ``` public class Sha512StringHasher : IStringHasher { private readonly SHA512Managed _sha; public Sha512StringHasher() { _sha = new SHA512Managed(); } public string HashString(string name, string locale) { return Convert.ToBase64String(_sha.ComputeHash(Encoding.UTF8.GetBytes(name + locale))); } } ``` With this, we can define our XML string store that reads an XML file from an embedded resource, and creates a dictionary holding the string definitions EmbeddedXmlStringStore.cs ``` public class EmbeddedXmlStringStore : IStringDictionaryStore { private readonly XNamespace _ns = (string)Resources.XmlNamespaceName; private readonly IStringHasher _hasher; private readonly IReadOnlyDictionary<string, StringInfo> _stringStore; public EmbeddedXmlStringStore(IStringHasher hasher) { _hasher = hasher; var resourceName = this.GetType().Namespace + Resources.NamespaceSeperator + Resources.XmlDictionaryName; using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { var doc = XElement.Load(s); _stringStore = LoadStringInfo(doc).ToDictionary(k => _hasher.HashString(k.Name, k.Locale), v => v); } } private IEnumerable<StringInfo> LoadStringInfo(XElement doc) { foreach (var e in doc.Elements(_ns + Resources.LocalizedElementName)) { var name = (string)e.Attribute(Resources.LocalizedElementNameAttribute); foreach (var e2 in e.Elements(_ns + Resources.TranslatedElementName)) { var locale = (string)e2.Attribute(Resources.TranslatedElementLocaleName); var localized = (string)e2; yield return new StringInfo(name,locale,localized); } } } public string GetLocalizedString(string name, string locale) { return _stringStore[_hasher.HashString(name, locale)].Localized; } } ``` And the associated `StringInfo` structure to hold the string information: StringInfo.cs ``` public struct StringInfo { public StringInfo(string name, string locale, string localized) { Name = name; Locale = locale; Localized = localized; } public string Name { get; } public string Locale { get; } public string Localized { get; } } ``` Since we might have several ways of looking up strings, we need to insulate the rest of the program from how exactly strings are retrieved, to do this, we define `IStringProvider`, which will be used throughout the rest of the program to resolve strings: ILocaleStringProvider.cs ``` public interface ILocaleStringProvider { string GetString(string stringName, string locale); } ``` With an implementation: StringDictionaryStoreLocaleStringProvider.cs ``` public class StringDictionaryStoreLocaleStringProvider: ILocaleStringProvider { private readonly IStringDictionaryStore _dictionaryStore; public StringDictionaryStoreStringProvider(IStringDictionaryStore dictionaryStore) { _dictionaryStore = dictionaryStore; } public string GetString(string stringName, string locale) { return _dictionaryStore.GetLocalizedString(stringName, locale); } } ``` Now, to handle locales. We define an interface to get the user's current locale. Isolating this is important, since a program running on the user's computer can read the locale off of the process, but on a web site, the user's locale might come from a database field assoicated with their user. ILocaleProvider.cs ``` public interface ILocaleProvider { string GetCurrentLocale(); } ``` And a default implementation That uses the current culture of the process, since this sample is a console application: ``` class DefaultLocaleProvider : ILocaleProvider { public string GetCurrentLocale() { return CultureInfo.CurrentCulture.Name; } } ``` The rest of our program doesn't really care if we're serving up localized strings or not, so we can hide the localization lookup behind an interface: IStringProvider.cs ``` public interface IStringProvider { string GetString(string name); } ``` Our implementation of StringProvider is responsible for using the provided implementations of `ILocaleStringProvider` and `ILocaleProvider` to return a localized string DefaultStringProvider.cs ``` public class DefaultStringProvider : IStringProvider { private readonly ILocaleStringProvider _localeStringProvider; private readonly ILocaleProvider _localeProvider; public DefaultStringProvider(ILocaleStringProvider localeStringProvider, ILocaleProvider localeProvider) { _localeStringProvider = localeStringProvider; _localeProvider = localeProvider; } public string GetString(string name) { return _localeStringProvider.GetString(name, _localeProvider.GetCurrentLocale()); } } ``` Finally, we have our program entry point, which provides the composition root, and gets the string, printing it to the console: Program.cs ``` class Program { static void Main(string[] args) { var container = new DependencyProvider(); container.Register<IStringHasher, Sha512StringHasher>(); container.Register<IStringDictionaryStore, EmbeddedXmlStringStore>(); container.Register<ILocaleProvider, DefaultLocaleProvider>(); container.Register<ILocaleStringProvider, StringDictionaryStoreLocaleStringProvider>(); container.Register<IStringProvider, DefaultStringProvider>(); var consumer = container.Get<IStringProvider>(); Console.WriteLine(consumer.GetString(Resources.HelloStringName)); } } ``` And that is how you write an enterprise microservice ready, locale aware, Hello World program. Scores: Files: 17 Namespace Includes: 11 Classes: 14 Variables: 26 Methods: 17 Statements: 60 Control Flow: 2 Forward Declarations (Interface members, xsd complexTypes): 11 Total: 158 [Answer] ## iX2Web ``` **iX2001B2 A1CAA3MwlI ZWxsbyBXb3 JsZHxfMAkw DQo==* ``` ]
[Question] [ Write a program with the following properties: * When run as-is, the program produces no output (i.e. 0 bytes of output). * There is a location within the program (of your choice: it could be at the start, end, or somewhere in the middle) with the following property: modifying the program via placing *any* string there will cause the resulting program to print that string when executed. This must work regardless of whether the string contains quotes, backslashes, comment marks, delimiters, NUL bytes, etc.; no matter what you place there, the string is still interpreted as a string and printed entirely verbatim. You can, however, fail to handle very very long strings if they would cause the compiler to run out of memory, or the like (to be precise, you should at least be able to handle strings up to 1000 bytes long or three times the length of your program, whichever is longer). An example of an *invalid* solution would be ``` print(""); # ^ text goes here ``` in Python, Perl, Ruby, etc.; although it works for many strings, it will not work for a string containing a double quote, or a string containing the substring `\n` (which would be interpreted as a newline). Note that this problem is probably impossible in most languages; the challenge is at least partially about finding a language where it works. Your chosen language must be a programming language under [this site's definition](http://meta.codegolf.stackexchange.com/a/2073/62131), e.g. no submitting a solution in [Text](http://esolangs.org/wiki/Text). As this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program template wins. However, do not be discouraged from submitting solutions even if they can't beat the current winner! You can still compete for second, third, etc. place, or simply to find as many answers where it works as possible. You should, however, ensure that your program meets the entire specification before submitting it; approximate solutions would miss the point of the problem. [Answer] ## Excel, 1 byte ``` ' ``` Ungolfed version ``` ' <-- print the following text, and exit the current formula ``` [Answer] # Jolf, 6 bytes ``` a Lq6( ``` ## Explanation ``` a Lq6( a print L 6 all but the first 6 characters of q the source code ( and exit ``` [Answer] # Zsh, 6 bytes ``` <<' ' ``` There is a trailing newline. The string is inserted at the end of the program. # Bash, ~~20~~ 17 bytes Thanks to [Adam](https://codegolf.stackexchange.com/users/62418/adam) for removing 3 bytes. ``` exec sed 1d "$0" ``` # \*nix shell script, ~~21~~ 14 bytes Thanks to [Adam](https://codegolf.stackexchange.com/users/62418/adam) for removing 7 bytes. ``` #!/bin/sed 1d ``` [Answer] # [Perl 5](https://www.perl.org/), ~~30~~ ~~21~~ 19 bytes ``` print<DATA>__END__ ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvxMbFMcTRLj7e1c8lPv6/kkdqTk6@ko5CeX5RTooil6ad3X8A "Perl 5 – Try It Online") Trailing newline. This makes use of a Perl feature which allows arbitrary data to be appended to the source file, which can then be read via the `DATA` filehandle. When we give a filehandle as an argument to `print`, it's given a list context, which causes the filehandle to return a list of all the lines in the file, newlines included (likewise, a newline on the final line will be omitted). Then `print` implicitly concatenates them all, undoing the splitting into lines and giving us the exact original string regardless of where the newlines were. Thanks to @Dada, who realised there was no need to handle newlines manually, and @ninjalj and @b\_jonas, who each spotted a character which could be golfed off. [Answer] # brainfuck ([Unreadable Brainfuck](http://esolangs.org/wiki/User:Marinus/Brainfuck_interpreters#Unreadable)), 9 bytes ``` ,+[-.,+]! ``` Append the input to the end. There isn't a trailing newline, this time. Looking for languages which would accept input appended to the end of the program, brainfuck seemed like a distinct possibility; many brainfuck interpreters written in esolangs take both the program and the program's input from standard input, and thus need some way to tell between them. There's a convention that's used in this case that a `!` character differentiates between the program and the input, a trick that's often used to write short brainfuck programs like `,[.,]!Hello, world!`; this basically creates a different dialect of brainfuck in which `!` has a different meaning from normal. In theory, therefore, we could just find one of these interpreters and give it a `cat` program in order to fulfil the spec. There's a major subtlety, though; brainfuck typically uses 256 values for each cell, there are 256 octets, and one needs to be used for EOF. So if we want to be able to echo all 256 octets literally, we can't detect EOF at all and will need to end the program some other way. In other words, we need to find an implementation that either gives the 256 octets and EOF 257 different values, or that crashes on EOF. Enter [Unreadable](http://esolangs.org/wiki/Unreadable). There's a brainfuck interpreter in Unreadable that predates this challenge, and which accepts input after an `!`; additionally, unlike most brainfuck interpreters, it uses bignum cells and -1 for EOF, allowing EOF to be distinguished from the other 256 possible octets. Thus, by use of Unreadable Brainfuck as the specific interpreter for the program, we can solve the challenge in just 9 bytes, via writing a brainfuck `cat` program that halts on EOF=-1. Is it possible to do better? Well, we could try the following 7-byte program, which attempts to *output* EOF at the end of the string before it breaks out of the loop: ``` +[,.+]! ``` The behaviour of this program depends on the behaviour of the Unreadable interpreter on error conditions (thus, it depends not only on the implementation of brainfuck, but on the implementation used to *run* the implementation of brainfuck). Unfortunately, the Unreadable interpreter I use outputs errors on standard *output*, meaning that this saving doesn't work. If anyone knows of an Unreadable interpreter that exits on an attempt to output EOF, or silently skips the attempt, let me know; that would be a seven-byte solution right there. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 11 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) The following is the body of the function *f*: ``` 2↓⎕CR'f'⋄→ ``` There is a trailing newline, after which anything may be inserted. `2↓` drop the first two lines (header and this line) of `⎕CR'f'` the **C**haracter **R**epresentation of *f* `⋄` then `→` quit [Answer] # Ruby, 20 bytes ``` print *DATA __END__ ``` Input goes at the end (after the trailing newline). The `DATA` idiom is one of many that Ruby [stole from Perl](https://codegolf.stackexchange.com/a/100934/11261). Try it on eval.in: <https://eval.in/684370> [Answer] # JavaScript + HTML5 DOM, 163 Bytes ``` <html><body><script>fetch(location).then((r)=>r.text().then((t)=>console.log(t.slice(145,t.lastIndexOf("</b")))));document.body.remove()</script></body></html> ``` You may insert anything you like directly before the closing body tag. This works by fetching the page source and stripping the opening code and the closing tags. The real kicker was figuring out how to escape an infinite loop. Putting `while(true){}` in the page blocks all callbacks forever, freezing the execution, and JavaScript has no way of pausing the main thread. However, code that no longer exists never runs, so the document body commits seppuku in the very last command, deleting itself while it waits for its clone to load. Yeah, it's long and roundabout, but the mere fact that it's possible in JS is kind of amazing. [Answer] # PHP, 46 bytes (including the trailing linebreak) ``` <?=join([""]+file(__FILE__));halt_compiler(); STRING HERE ``` Yes: even the `file` function is binary safe. `[""]+` replaces the 0-index (first line of the file) with an empty string [Answer] # [gs2](http://github.com/nooodl/gs2), 4 bytes ``` ╥¶=☼ ``` Uses CP437 encoding. The string goes at the end. `╥` gets the source code, `¶` pushes 4, `=` drops that many leading characters, and `☼` exits. [Try it online!](http://gs2.tryitonline.net/#code=4pWlwrY94pi8SGVsbG8sIFdvcmxkIQohQCMkJV4mKigp&input=) [Answer] # PHP 94 bytes ``` <?$f=fopen(__FILE__,'rb');fseek($f,93);while(false!==($c=fgetc($f)))echo$c;__halt_compiler(); ``` Place your string after the final semicolon. Yay for obscure features I guess? \_\_halt\_compiler() does exactly what you'd expect from the name. The prior code just opens the file and writes any bytes after that last semicolon to stdout. NUL, BEL etc come out fine. Unicode literals (♪) get screwed up on Windows but I think that's just Windows cmd failing at unicode. [Answer] # [Perl 6](https://perl6.org), 23 bytes ``` print $=finish =finish ``` The string is placed starting on the newline after `=finish`. [Answer] # PHP, ~~48~~ 60 bytes ``` <?=substr(file_get_contents(__FILE__),60);__halt_compiler();STRING HERE ``` Just became aware that closing PHP does not prevent the string from containing `<?`. [Answer] # [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), 1 byte ``` [text goes here] ``` That’s a single space (0x20) before the text. [Try it online!](https://tio.run/##S8pJ/v/fAAqsFIwMTCwUzEzNkhXMks3SFIySjQwUzM2BLHMjkJiJkaECFHik5uTk6yiU5xflpCj@/w8A "Binary Lambda Calculus – Try It Online") ### How it works 0x20 = 001000002 is parsed as ``` 00 λx. 01 x 0000 (ignored, can be anything) ``` (So in fact, any of the characters `!"#$%&\'()*+,-./` will work equally well.) Since this is a complete expression, the remainder of the program is interpreted as input data, and under the binary lambda calculus I/O conventions, the identity function λ*x.* *x* copies the input directly to the output. [Answer] # Bash, 17 bytes ``` tail -n+3 $0 exit <string here> ``` Developed independently of [jimmy23013's answer](https://codegolf.stackexchange.com/a/100933/41088). [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 19 Bytes ``` Q 19 Q L sub exit ``` Note the trailing space. Insert any text after that chunk and it will be printed. Based off of [Lynn's](https://codegolf.stackexchange.com/users/3852/lynn) [gs2 answer](https://codegolf.stackexchange.com/a/100979/58375). [Try it Online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=Q%2019%20Q%20L%20sub%20exit%20Hello%2C%20World!&input=) [Answer] # Excel VBA, 6 Bytes This is mainly to answer the question of how to print the text as held in [Adam's Answer](https://codegolf.stackexchange.com/a/101023/61846) to the Immediates Window in the VBA environment ## Basic Setup: In cell *A1* in the activesheet the use the formula below to hold the string to be printed. *For the sake of byte counting this shall add 1 Byte* ``` '[Your Text Here] ``` eg: ``` 'Hello World ``` ## Immediates Window Function, 5 + 1 = 6 Bytes ``` ?[A1] ``` +1 Byte for a `'` in cell A1 [Answer] # Vim (in ex mode), 28 bytes ``` #!/bin/ex -c ':1d' -c ':wq' [string] ``` 28 bytes is including the last newline. [Answer] # Vim, 738 bytes ``` :imap <esc> <c-v><esc> :imap <c-a> <c-v><c-a> :imap <c-b> <c-v><c-b> :imap <c-c> <c-v><c-c> :imap <c-d> <c-v><c-d> :imap <c-e> <c-v><c-e> :imap <c-f> <c-v><c-f> :imap <c-g> <c-v><c-g> :imap <c-h> <c-v><c-h> :imap <c-i> <c-v><c-i> :imap <c-j> <c-v><c-j> :imap <c-k> <c-v><c-k> :imap <c-l> <c-v><c-l> :imap <c-m> <c-v><c-m> :imap <c-n> <c-v><c-n> :imap <c-o> <c-v><c-o> :imap <c-p> <c-v><c-p> :imap <c-q> <c-v><c-q> :imap <c-r> <c-v><c-r> :imap <c-s> <c-v><c-s> :imap <c-t> <c-v><c-t> :imap <c-u> <c-v><c-u> :imap <c-v> <c-v><c-v> :imap <c-w> <c-v><c-w> :imap <c-x> <c-v><c-x> :imap <c-y> <c-v><c-y> :imap <c-z> <c-v><c-z> :imap <c-@> <c-v><c-@> :imap <c-\> <c-v><c-\> :imap <c-]> <c-v><c-]> :imap <c-^> <c-v><c-^> :imap <c-?> <c-v><c-?> i ``` Rebinds all control characters in insert mode to `<c-v>`, followed by that control character, which will enter them literally. ^\_ (unit seperator) doesn't seem to need rebinding, as it gets outputted literally by default. The variable text comes at the end, of course. ]
[Question] [ What general tips do you have for golfing in PHP? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PHP (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] **Understand how variables and whitespace interact with PHP's language constructs.** In my (admittedly short) time golfing, I have found that PHP's language constructs (e.g. echo, return, for, while, etc) behave in a less-than-intuitive way when interacting with variables and whitespace. `echo$v;`, for example, is perfectly valid, as are `return$v;` and other similar constructs. These small reductions in whitespace can lead to a significant cumulative decrease in length. Keep in mind, though, that variables **before** language constructs require a space after, as in the following example: ``` foreach($a AS$b){} ``` Because `AS` is a language construct, a space is not required before the variable `$b`, but if one were to omit the space *before it*, resulting in `$aAS`, this would be parsed as a variable name and lead to a syntax error. [Answer] **Use strings wisely.** This answer is two-fold. The first part is that when declaring strings, you can utilize PHP's implicit conversion of unknown constants to strings to save space, e.g: ``` @$s=string; ``` The `@` is necessary to override the warnings this will produce. Overall, you end up with a one-character reduction. is that sometimes, it may be space effective to set a variable to the name of an often used function. Normally, you might have: ``` preg_match(..);preg_match(..); ``` But when golfing, this can be shortened easily to: ``` @$p=preg_match;$p(..);$p(..); ``` With only two instances of "preg\_match", you're only saving a single character, but the more you use a function, the more space you will save. [Answer] You don't always need to write out conditional checks. For example, some frameworks use this at the top of their files to block access: ``` <?php defined('BASE_PATH')||die('not allowed'); ``` Or in normal functions ``` $value && run_this(); ``` instead of ``` if($value) { run_this(); } ``` [Answer] ## Use short array syntax Since PHP 5.4, arrays can be declared using square brackets (just like JavaScript) instead of the `array()` function: ``` $arr=['foo','bar','baz']; // instead of $arr=array('foo','bar','baz'); ``` It will save five bytes. --- But It may cost bytes if you have "holes" in an associative array: ``` $arr=array(,1,,3,,5); // is one byte shorter than $arr=[1=>1,3=>3,5=>5]; ``` the disadvantage hits a little later if you can fill the holes with "empty" values: ``` // saves two bytes over array() $arr=[0,1,0,3,0,5]; // but for a larger array $arr=[0,1,0,3,0,5,0,7,0,9,0,11]; // costs two byte more than $arr=array(,1,,3,,5,,7,,9,,11); ``` [Answer] ## Use ${0}, ${1}, ${2}, ... instead of $a[0], $a[1], $a[2], ... Unless you're performing an array manipulation, most references to an array index `$a[$i]` can be replaced with simply `$$i`. This is even true if the index is an integer, as integers are valid variable names in PHP (although literals will require brackets, e.g. `${0}`). Consider the following implementation of the Rabonowitz Wagon spigot: ``` 3.<?for(;$g?$d=0|($a[$g]=$d*$g--/2+($a[$g]?:2)%$g*1e4)/$g--:238<<printf($e?'%04d':'',$e+$d/$g=1e4)^$e=$d%$g;); ``` This can be improved by 6 bytes, simply by replacing both array references `$a[$g]` with `$$g` instead: ``` 3.<?for(;$g?$d=0|($$g=$d*$g--/2+($$g?:2)%$g*1e4)/$g--:238<<printf($e?'%04d':'',$e+$d/$g=1e4)^$e=$d%$g;); ``` [Answer] **Learn a large subset of the library functions**. PHP's library is pretty huge and provides a ton of convenient functions that can greatly shorten various tasks. You could just search every time you try to do something, but beyond wasting time you might not find anything that matches your particular search. The best way is just to get familiar with the library and memorize function names and what they do. [Answer] Running functions inside strings. Try this: ``` $a='strlen'; echo "This text has {$a('15')} chars"; ``` Or try this: ``` //only php>=5.3 $if=function($c,$t,$f){return$c?$t:$f;}; echo <<<HEREDOCS Heredocs can{$if(true,' be','not be')} used too and can{$if(<<<BE {$if(true,1,0)} BE ,'','not')} be nested HEREDOCS; //Expected output: Heredocs can be used too and can be nested ``` This only works with strings using `""` and heredocs (DON'T make confusion with nowdocs). Using nested functions is only possible inside nested heredocs (or you will run into parse errors)! [Answer] ## by any other name ... function aliases use ... * `join` instead of `implode` * `chop` instead of `rtrim` (`chop` in PERL is different!) * `die` instead of `exit` * `fputs` instead of `fwrite` * `is_int` instead of `is_integer` or `is_long` * `is_real` instead of `is_float` or `is_double` * `key_exists` instead of `array_key_exists` * `mysql` instead of `mysql_db_query` ... to name the most important aliases. Take a look at <http://php.net/aliases> for more. [Answer] **looping through strings** can be done with 26 bytes or with 24 down to 18: ``` foreach(str_split($s)as$c) # A) 26 - general for($p=0;a&$c=$s[$p++];) # B) 24 - general for($p=0;$c=$s[$p++];) # C) 22 - if $s has no `0` character for(;a&$c=$s[$p++];) # D) 20 - if $p is already NULL or 0 (does NOT work for false) for(;$c=$s[$p++];) # E) 18 - both C and D for(;$o=ord($s[$p++]);) # F) 23 - work on ASCII codes, if $s has no NULL byte and D for(;~$c=$s[$p++];) # G) 19 - if $s has no chr(207) and D ``` --- `$a&$b` does a bitwise AND on the (ascii codes of) the characters in `$a` and `$b` and results in a string that has the same length as the shorter of `$a` and `$b`. [Answer] # fun with typecasts * `!!$foo` will turn any truthy value to `true` (or `1` in output), falsy values (0, empty string, empty array) to `false` (or empty output) This will rarely be needed in code golf, for in most cases where you need a boolean, there is an implicit cast anyway. * `(int)$foo` can be written as `$foo|0` or `foo^0`, but may need parentheses. For booleans and strings, `$foo*1` or `+$foo` can be used to cast to int. * Unlike most other languages, PHP handles strings with numeric values as numbers. So if you have any string that contains a number you have to calculate with, just calculate. * The other way does *not* work: To multiply any number in a variable with `10`, you could append a zero: `*10` -> `.0`. But in this case, PHP will take the dot as decimal point and complain. (It´s different though if you have a variable amount of zeroes in a string.) * To turn an array into a string, use `join` instead of `implode`. If you don´t need a delimiter, don´t use it: `join($a)` does the same as `join('',$a)` * Incrementing strings: The most amazing feature imo is that `$s=a;$s++;` produces `$s=b;`. This works with uppercase and lowercase characters. `$s=Z;$s++;` results in `$s=AA;`. This also works with mixed case: `aZ` to `bA`, `A1` to `A2`, `A9` to `B0` and `z99Z` to `aa00A`. Decrement does *not* work on strings. (And it does not on `NULL`). Back in PHP 3, `$n="001";$n++;` produced `$n="002";`. I am a little sad they removed that. Whatever you golf: **always have the [operator precedence table](http://php.net/manual/language.operators.precedence.php) at hand.** [Answer] # Use shorttags In normal code, it's good practice to use `<?php` and `?>`. However, this is *not* normal code - you are writing a code golf code. Instead of `<?php`, write `<?`. Instead of `<?php echo`, write `<?=`. Don't type `?>` at end - it's completely optional. If you need `?>` for some reason (for example to output text, and it's shorter somehow, or something, don't put a semicolon before it - it's not needed, as `?>` implies semicolon. Wrong (definitely too long): ``` <?php echo ucfirst(trim(fgets(STDIN)));?>s! ``` Correct: ``` <?=ucfirst(trim(fgets(STDIN)))?>s! ``` [Answer] # array\_flip vs array\_search use ``` array_flip($array)[$value] ``` instead of ``` array_search($value,$array) ``` to save 1 Byte in arrays where the occurence of each value is unique [Answer] # Use ternary operators ``` if(a==2){some code;}else{some other code;} ``` can be abbreviated to this: ``` (a==2?some code:some other code); ``` Shorter, huh? [Answer] # Combining `for` loops Suppose you have code of the following form: ``` for($pre1; $cond1; $post1) for($pre2; $cond2; $post2) $code; ``` this can generally be re-rolled in the following form: ``` for($pre1; $cond2 • $post2 || $cond1 • $pre2 • $post1; ) $code; ``` where `•` represents a generic combining operator. This usually results in an byte count reduction, but will likely require some creativity. `$cond2` will need to be written so that it fails the first time through. `$post1` should also fail to execute the first time, although it may be easier to refactor beforehand so that `$post1` is not present. If you're working with three or more nested loops, you can also combine two first, and then combine that to another, and so on. I find that it has generally been easier to combine from the inside outwards. --- As an example, consider the following solution to the [H-carpet fractal](https://codegolf.stackexchange.com/q/157664/4098) (*97 bytes*): ``` for(;$i<$n=3**$argn;$i+=print"$s\n")for($s=H,$e=1;$e<$n;$e*=3)$s.=str_pad($i/$e%3&1?$s:'',$e).$s; ``` This can be reformulated in the following way: ``` for(;($i+=$e&&print"$s\n")<$n=3**$argn;)for($s=H,$e=1;$e<$n;$e*=3)$s.=str_pad($i/$e%3&1?$s:'',$e).$s; ``` *`$e&&print` prevents `print` on first iteration, and also does not increment `$i`.* and finally (*93 bytes*): ``` for(;$H>$e*=3or$e=($i+=$e&&print"$s\n")<${$s=H}=3**$argn;)$s.=str_pad($i/$e%3&1?$s:'',$e).$s; ``` *`$H>$e*=3` will fail the first time as both variables are undefined.* [Answer] **line breaks** if the output requires line breaks, use a physical line break (1 byte) instead of `"\n"` This also gives you a possible benefit to chose between single and double quotes. [Answer] ### Associative arrays can be merged with the `+` operator. Instead of: ``` $merged = array_merge($a, $b); ``` Use: ``` $merged = $a + $b; ``` Note the `+` operator works with indexed arrays as well, but probably doesn't do what you want. [Answer] **some interesting facts on [variable variables](http://php.net/variables.variable)** I just had to share them (even before I [verified](https://codegolf.stackexchange.com/a/105831#105831) that at least one of them helps golfing): * Use letters: `$x=a;$$x=1;$x++;$$x=2;echo"$a,$b";` prints `1,2` but other arithmetic operations do not work with letters. * As [primo mentioned earlier](https://codegolf.stackexchange.com/a/86394#86394), you can use pure numbers as variable names: `$a=1;$$a=5;$a++;$$a=4;${++$a}=3;echo${1},${2},${3};` prints `543`. * You can not only use `[0-9a-zA-Z_]` for variable names, but EVERY string: `$x="Hello!";$$x="Goodbye.";echo${"Hello!"};` prints `Goodbye.`. * But: Everything but `[a-zA-Z_][a-zA-Z_0-9]*` as variable names requires braces for literal use. * With no variables defined, `$$x=1` sets `${NULL}`, which is the same as `${false}` and `${""}`. * `$a=1;$$a=5;` does not only set `${1}`, but also `${true}`. * one more, the weirdest one I´ve found so far: Try `$a=[];$$a=3;echo${[]};`. Yes, it prints `3`! The reason for most of this: variable names are always evaluated to strings. (Thanks @Christoph for pointing out.) So, whatever you get when you `print` or `echo` the expression, that´s what you get as variable name. [Answer] ## PCRE-Related (Regex) ### Functions If the pattern always matches the subject string (thanks to the comment by @Deadcode), instead of `preg_replace`, you can use `preg_filter` (1 byte shorter). ### Patterns Sometimes [espace sequences](https://www.php.net/manual/en/regexp.reference.escape.php) are useful, like `\d`, `\w`, `\W`, `\s` or `\S`. ### Examples Filter non-alphabet characters: ``` preg_replace("/[^a-z]/i", "", $s); preg_filter("/\W|\d/", "", $s); // 3 bytes shorter ``` [Answer] **avoid quotes where possible** PHP implicitly casts unknown words to literal strings. `$foo=foo;` is the same as `$foo='foo';` (assuming that `foo` is neither a key word or a defined constant): `$foo=echo;` does not work. BUT: `$p=str_pad;` does; and `$p(ab,3,c)` evaluates to `abc`. Using string literals without quotes will yield a Notice for `Use of undefined constant`; but that won´t show if you use the default value for `error_reporting` (CLI parameter `-n`). [Answer] # array\_merge vs array\_push ``` array_push($a,...$b); ``` is one byte shorter than ``` $a=array_merge($a,$b); ``` Does not work the same with Associative arrays [variable-arg-list PHP >5.6](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list) [Answer] # Use boolean operators instead of `strtoupper()` and `strtolower()` If you're working exclusively with strings consisting of alphabet characters, you can use boolean operators to change them to uppercase or lowercase with fewer keystrokes than PHP's built-in functions. ### Example: ``` // Convert lowercase to uppercase $s = "g"; echo strtoupper($s); // Outputs 'G', uses 20 characters echo~" "&$s; // Outputs 'G', uses 12 characters // Convert uppercase to lowercase $s = "G"; echo strtolower($s); // Outputs 'g', uses 20 characters echo$s^" "; // Outputs 'g', uses 11 characters // Switch case of each character $s = "Gg"; echo$s^" "; // Outputs 'gG', uses 12 characters ``` Things are a little trickier for strings of arbitrary length, but the `&` and `^` operators will truncate the result to the length of the shorter input string. So for example, if `$W` is a string of spaces at least as long as any input `$s`, then `~$W&$s` is equivalent to `strtoupper($s)`, and `$s|$W^$s` is equivalent to `strtolower($s)` (whereas `$s|$W` by itself will produce a string with additional spaces unless `$s` and `$W` are of equal length). [Answer] # Arrow functions in PHP 7.4 PHP 7.4 is on RC2 version now and hopefully will be released in about 2 months. List of new features are [here](https://www.php.net/manual/en/migration74.new-features.php) (this page can actually be updated when 7.4 is released). In 7.4, finally PHP has got the arrow functions, so not only function answers can be shorter now, but also passing closures to other functions can be a lot shorter too. Here are a few examples: **Return input + 1:** Anonymous function (closure) - 25 bytes - [Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7P600L7kkMz9PQyVPs7ootaS0KE8lT9vQuva/NRdXanJGvoJKmoaRpvV/AA "PHP – Try It Online") ``` function($n){return$n+1;} ``` Arrow function - 12 bytes - [Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7Py1PQyVP09ZOJU/b8L81F1dqcka@gkqahpGm9X8A "PHP – Try It Online") ``` fn($n)=>$n+1 ``` **Multiply items of first input (array of ints) by second input (int):** Anonymous function (closure) - 72 bytes - [Try it online!](https://tio.run/##RcqxDoJADADQ/b6CoUNruojAcho/xBhSCBcYrE29G4zh28@RNz9brV7vtloIkG41FZ3z9lYEYVD6@ZKLayPu8h1fYniEicpnwSPBdAKNO4NQ3GsMwXzTPDpCwseZW75wxz0PT25aolj/ "PHP – Try It Online") ``` function($a,$n){return array_map(function($b)use($n){return$b*$n;},$a);} ``` Arrow function - 38 bytes - [Try it online!](https://tio.run/##Fcg7DoAgDADQnVM4dADTRfwsih7EGFIGgoNNQ1w8fdU3PimiyyZFjIEcNLMFQmAXVqqVnniR2D/TN5BaYARyOhsj9eQ7VgvZ7h167HHAEacDG@/crC8 "PHP – Try It Online") ``` fn($a,$n)=>array_map(fn($b)=>$b*$n,$a) ``` Did you notice that `$n` is accessible in the inner function without a `use $n` statement? Yeah that is one of the arrow function features. --- As a side note, I could not get arrow functions to work recursively (call the same arrow function inside itself), because we cannot give them a name and storing them as a closure in a variable like `$f` doesn't make `$f` accessible withing itself (sad). So this example **doesn't work** and using `$f` in first line causes a fatal error: ``` $f=fn($n)=>$n?$f($n-1):0; $f(5); // Causes error: "PHP Notice: Undefined variable: f" + "PHP Fatal error: Uncaught Error: Function name must be a string" ``` But calling an arrow function withing a different arrow function works: ``` $f1=fn($n)=>$n+1; $f2=fn($n)=>$f1($n-1); $f1(2) // Returns 3 $f2(2) // Returns 2 ``` [Answer] Regarding file I/O: Linking to another [related question](https://codegolf.stackexchange.com/q/5713/3862), the answers to which fit here. [Answer] ### Use negative indexes to reference the end of a string If you need the last character in a string, you can use the array reference method, and provide a negative index: ``` $lastChar = $string[-1]; ``` This also works for functions like `substr()`: ``` $lastFour = substr($string, -4); ``` [Answer] ### Directly dereference arrays returned from functions. E.g., instead of this: ``` $a = foo(); echo $a[$n]; ``` You can do: ``` echo foo()[$n]; ``` This works with methods too: ``` echo $obj->foo()[$n]; ``` You can also directly dereference array declarations: ``` echo [1, 2, 3, 4, 5][$n]; ``` [Answer] ### Use `end()` instead of `array_pop()` The `end()` function doesn't just move the internal pointer to the end of the array, it also returns the last value. Note of course that it doesn't *remove* that value, so if you don't care what the array contains afterwards, you can use it instead of `array_pop()`. [Answer] # double array\_flip vs in\_array vs array\_unique in this [special case](https://codegolf.stackexchange.com/questions/116786/find-the-translation-table) a double array\_flip saves 10 Bytes `($f=array_flip)($k=$f($c)))` remove all double values in the array and I have dropped this `$c=[],` , `|in_array($o,$c)` and replace `array_keys($c)` with `$k` ``` for([,$x,$y]=$argv;a&$o=$y[$i];$i++) $x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2 echo strtr($x,($f=array_flip)($k=$f($c)))==$y # boolean replacement string 1 equal to string 2 ?join($k)." ".join($c) # output for true cases :0; #Output false cases ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/15c1d9bddf3b7132a6998e6563b08e728dff0343) against ``` for($c=[],[,$x,$y]=$argv;a&$o=$y[$i];$i++) $x[$i]==$o|in_array($o,$c)?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2 echo strtr($x,$c)==$y # boolean replacement string 1 equal to string 2 ?join(array_keys($c))." ".join($c) # output for true cases :0; #Output false cases ``` [Online version](http://sandbox.onlinephpfunctions.com/code/806278a6c8ec65d86984b234f7d3f0bec8017477) against array\_unique it saves 2 Bytes ``` for([,$x,$y]=$argv;a&$o=$y[$i];$i++) $x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2 echo strtr($x,array_unique($c))==$y # boolean replacement string 1 equal to string 2 ?join(array_keys($c))." ".join($c) # output for true cases :0; #Output false cases ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/3bcf8625977f94b64cdea19bf39fd2c3cabd866a) After finding a bug in this program and replacement `$x[$i]==$o?:$c[$x[$i]]=$o` to `($p=$x[$i])==$o?:$k[$c[$p]=$o]=$p` the double array\_flip was not necessary longer [Answer] ## Return two copies of an expression If you want to get two copies of the result of an expression, you can use this: ``` $v.$v=expr ``` But it won't be shorter than the more straightforward `($v=expr).$v` if you need to append more things to the result. For 4 copies: ``` $v.$v.=$v=expr ``` You cannot use it to get 3 copies. [Answer] **intersecting strings** Have you ever used `join("DELIMITER",str_split($s))` (31 bytes) or even `preg_replace(".","DELIMITER",$s)` (32 bytes) ? There´s a builtin for that: Try `chunk_split($s,1,"DELIMITER")` (29 bytes). --- If you omit the third parameter, [`chunk_split`](http://php.net/chunk-split) will use `\r\n`; that can save you 7 or 8 bytes. But beware: `chunk_split` also appends the delimiter to the string, so you may not get exactly what you want. (If you don´t provide the chunk length, it will use 76. Rather unusual for code golf, but who knows.) [Answer] # unset() vs INF In a case search for a minimum in an array you can use instead of ``` unset($var[$k]); $var[$k]=INF; ``` to save 3 Bytes ]
[Question] [ # Center The Text! In this challenge you will be centering various lines. ## Examples ``` Foo barbaz Foo barbaz ``` ``` Hello World Hello World ``` ``` Programming Puzzles & Code Golf Programming Puzzles & Code Golf ``` ## Specifications Each input line will always have at least one non-whitespace character, you may assume the only whitespace character are spaces () and newlines. Each input line won't have any trailing and/or leading whitespace (except for the newline). Trailing whitespace in the output is *not* allowed. You should be centering among the longest line in the input. If that line is even in length, your program/function should prefer to center to the left. The maximum line length is whatever your language can handle but your program should function on lines of at least 500 in length. --- ## 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=66731,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> ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins! [Answer] ## vim, ~~43~~ ~~36~~ 35 bytes ``` VGrx:sor G:let &tw=col("$") uu:%ce ``` Too good not to post. Note the trailing newline; it is significant. Thanks to [@Marth](https://codegolf.stackexchange.com/users/30991/marth) for saving a character! vim-friendly format: ``` VGrx:sor<cr>G:let &tw=col("$")<cr>uu:%ce<cr> ``` Explanation: ``` VGrx replace every character with an "x" :sor<cr> sort (since all chars are now same, sorts by line length) G go to the very last line :let &tw=col("$")<cr> set &tw to column number of last char on this line "let &tw" is equivalent to "set tw" tw is short for textwidth, used in :center uu undo the sort, and the replacing-with-x too :%ce<cr> center over entire file (%), using textwidth set earlier ``` [Answer] ## Mathematica, 96 bytes ``` StringRiffle[#~StringPadLeft~Floor[Max@(l=StringLength)@a/2+l@#/2]&/@(a=#~StringSplit~" ")," "]& ``` Don't ask me how it worked, I just fiddled with it until it produced the correct output. [Answer] # Pyth, ~~19~~ 17 bytes *2 bytes thanks to Jakube* ``` V.ztr+1.[l.T.zNd6 ``` [Demonstration](https://pyth.herokuapp.com/?code=V.ztr%2B1.%5Bl.T.zNd6&input=Foo%0Abarbaz&debug=0) I think this is the first time the center-pad function of `.[` has been useful. The length of the longest line is found using non-truncating transpose (`.T`). Trailing spaces are removed by adding a non-space character to the front, stripping spaces, then removing the added character. [Answer] # [Funciton](http://esolangs.org/wiki/Funciton), non-competitive This challenge has highlighted the sore lack of a “maximum value” (and minimum value) function for lazy sequences, so... I added them to the core library (they’re called ⊤ and ⊥, respectively). Therefore I didn’t bother to submit this as a *golfed* answer (it would have to include the ⊤ function declaration to be valid), so here’s just the main program. Execute `(function(){$('pre,code').css({lineHeight:5/4,fontFamily:'DejaVu Sans Mono'});})()` in your browser console to get some nicer rendering. ``` ╓───╖ ╔════╗ ┌───╖ ╔═══╗ ┌─╢ ‡ ╟─┐ ║ 10 ╟──┤ ǁ ╟──╢ ║ │ ╙───╜ │ ╚════╝ ╘═╤═╝ ╚═══╝ │ ┌───╖ │ ┌──────────────┴──────────────────┐ └─┤ ‼ ╟─┘┌─┴─╖ ┌───╖ ┌───╖ ┌───╖ ┌───╖ │ │ ╘═╤═╝ │ ɱ ╟─┤ ⊤ ╟─┤ + ╟─┤ ~ ╟─┤ ℓ ╟───┐ ┌─┴─╖ ┌─┴─╖ ╔════╗ │ ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╘═══╝ ╘═══╝ │ │ ɱ ╟─┤ ʝ ╟─╢ 10 ║ ┌───╖ ╔═╧═╕ ╔═══╗ ┌─┴──╖ ┌───╖ ╔════╗ │ ╘═╤═╝ ╘═══╝ ╚════╝ ┌─┤ ℓ ╟─╢ ├─╢ 1 ║ │ >> ╟─┤ … ╟─╢ 32 ║ │ │ │ ╘═══╝ ╚═╤═╛ ╚═╤═╝ ╘═╤══╝ ╘═╤═╝ ╚════╝ │ ╔═╧═╕ ╔═══╗ └─────────┘ └─────┘ │ ┌───╖ ├─╢ ├─╢ 0 ║ └───┤ ‡ ╟──┘ ╚═╤═╛ ╚═══╝ ╘═╤═╝ │ └────────┘ ``` ## Explanation I believe this may be the first Funciton answer on this site that uses lambda expressions. * First, we use `ǁ` to split the input string at the newlines (ASCII 10). This returns a lazy sequence. * We pass that sequence through `ɱ` (map), giving it a lambda that calculates the length of each string, and then pass the final sequence through `⊤` to get the length of the longest line. * We *also* pass that sequence through another `ɱ`, giving it a lambda that calculates the length of each string, subtracts it from the maximum line length calculated earlier, divides that by 2 (actually shift-right 1), generates that many spaces (ASCII 32) and then concatenates the string onto those spaces. (For geometric reasons, I declared a `‡` function that calls `‼` (string concatenate) with the parameters reversed.) * Finally, we use `ʝ` to put all of the strings back together, using newlines (ASCII 10) as the separator. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~54~~ 52 bytes ``` +m`^(.)+$(?<=(?=[^\t]*^..(?<-1>.)+(?(1)^))[^\t]*) $0 ``` The `\t`s can replaced with actual tabs, but I've used `\t` here, because otherwise SE will convert the tabs to spaces. Note that there is a leading space on the second line. [Try it online.](http://retina.tryitonline.net/#code=K21gXiguKSskKD88PSg_PVteCV0qXi4uKD88LTE-LikrKD8oMSleKSlbXgldKikKICQwIA&input=UHJvZ3JhbW1pbmcgUHV6emxlcwomCkNvZGUgR29sZg) ### Explanation The basic idea is to match a line which is at least two characters shorter than the longest line (or technically, two characters shorter than *any* other line), and surround it in two spaces. This is repeated until we can no longer find such a line, which means that all lines are within one character of the maximum length (where the one character is to account for parity mismatches, and guarantees that these lines are shifted to the left off-centre). As for the actual regex: ``` ^(.)+$ ``` Just matches any one line while pushing one capture onto group `1` for each character. ``` (?<=...[^\t]*) ``` Is a lookbehind which is matched right-to-left and moves the cursor to the beginning of the string, so that the lookahead inside can check the entire string. Note that due to a lack of an anchor, the lookahead could be applied from anywhere else, but that does not create additional matches. We know that `[^\t]` will always match *any* character in the string, because the input is guaranteed to contain only spaces and linefeeds as far as whitespace is concerned. ``` (?=[^\t]*^..(?<-1>.)+(?(1)^)) ``` This lookahead tries to find a line which is at least two characters longer than the one we're currently matching. `[^\t]*` moves through the string in order to be able to match any line. `^` ensures that we're starting from the beginning of the line. `..` then matches the two additional characters we require for the longer line. Now `(?<-1>.)+` matches individual characters in that line while popping from group `1` (note that `.` cannot match a linefeed, so this is constrained to one line). Finally, `(?(1)^)` asserts that we managed to empty the entire group `1`. If the line is shorter than required, this is not possible, because there are not enough characters in the line to pop from group 1 often enough to empty it. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 3 bytes *Noncompeting, update postdates question.* [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=cGNp&input=UHJvZ3JhbW1pbmcgUHV6emxlcwomCkNvZGUgR29sZg). ``` pci pc center i string input ``` ¯\\_(ツ)\_/¯ I thought it'd be a useful function. [Answer] # JavaScript (ES6), ~~93~~ 91 bytes ``` s=>(m=l=s.split` `).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join` ` ``` *2 bytes saved thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)!* ## Explanation ``` s=>( m= // m = max line length (divided by 2) l=s.split` `) // l = array of lines .map(x=> // for each line (v=x.length/2) // v = current line length / 2 <m?v:m=v // set m to the max line length and return v ) .map((x,i)=> // for each line length / 2 " ".repeat(m-x) // add spaces before +l[i] // add line text ) .join` ` // return lines as a newline-separated string ``` ## Test ``` var solution = s=>(m=l=s.split` `).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join` ` ``` ``` <textarea id="input" rows="4" cols="20">Programming Puzzles & Code Golf</textarea><br /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # CJam, ~~26~~ ~~23~~ 19 bytes ``` qN/_z,f{1$,m2/S*\N} ``` My first time using CJam! Four bytes saved thanks to Martin Büttner. [Try it online.](http://cjam.aditsu.net/#code=qN%2F_z%2Cf%7B1%24%2Cm2%2FS*%5CN%7D&input=Programming%20Puzzles%0A%26%0ACode%20Golf) ### Explanation ``` qN/ e# Read input and split each line _z, e# Transpose a copy and get its length to find the longest line f{ e# For each line... 1$,- e# Subtract its length from the longest length 2/ e# Divide by two to get just the spaces to add to the left S*\ e# Add a string with that many spaces to the beginning N e# Add a newline to go on to the next line } ``` [Answer] # LabVIEW, 3 or 35 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) Finds lines until none are left, then calculates how many spaces to add and puts everything together. [![](https://i.stack.imgur.com/9SHUE.gif)](https://i.stack.imgur.com/9SHUE.gif) Alternatively you could use the built-in center alignment on string indicators, it kinda does feel like cheating though. [![](https://i.stack.imgur.com/CiOoK.jpg)](https://i.stack.imgur.com/CiOoK.jpg) [Answer] # Python 2, ~~83~~ 81 bytes ``` def f(s): t=s.split('\n') for y in t:print(max(len(f)for f in t)-len(y))/2*' '+y ``` Thanks to @xnor for saving 2 chars example input: ``` f("""Programming Puzzles & Code Golf""") ``` example output: ``` Programming Puzzles & Code Golf ``` And ending in second place with 84 bytes using str.center() and str.rstrip (thanks @J F). ``` def f(s): t=s.split('\n') for y in t:print y.center(max(len(f)for f in t)).rstrip() ``` [Answer] # [TeaScript](http://github.com/vihanb/TeaScript), 24 bytes ``` £p.R((aßln)¯-ln)/2)+l,§) ``` Loops through lines, adds `floor((max line length - line length) / 2)` spaces to the beginning. ## Ungolfed ``` £ p.R((aß ln)¯ -ln)/2)+l,§ ) xl(#p.R((am(#ln)X()-ln)/2)+l,`\n`) xl(# // Loops through newlines p.R( // Repeats spaces ( am(#ln) // Map all line lengths X() // Get largest line length -ln) // Subtract current line length /2) // Divide by two +l, // Add current line text `\n`) ``` [Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22%C2%A3p.R((a%C3%9Fln)%C2%AF-ln)%2F2)%2Bl,%C2%A7)%22&inputs=%5B%22Programming%20Puzzles%5Cn%26%5CnCode%20Golf%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) [Answer] # PowerShell, 58 67 bytes down to 58 bytes thanks to @mazzy's comments: ``` param($a)$a|%{$_|% *ft(($a|% le*|sort)[-1]/2+$_.length/2)} # It takes an array of strings as input PS C:\Temp> .\center.ps1 'aaa','bb','c' aaa bb c # Or here, read from a file PS C:\Temp> .\center.ps1 (gc t.txt) info0:info1:info2:info3 info0:info1 ttt tt t ``` * It takes an array of strings as `$a`, loops over each string with `|%{...}`. * calls the `string.padleft()` method on each string, via `% -member` shortcut, which takes desired final line length as a parameter. + we need `array_longest_line_length/2 + current_line_length/2` + the end part is `current_line_length/2` -> `$_.length/2` + the other part is recalculating the array's maximum line length every time through the loop, and it does so with a nested loop making an array of line lengths, sorts that, then takes the last one. [Answer] # Emacs Lisp, 203 bytes ``` (let((f 0)(l 0))(dolist(s(split-string(buffer-string)"\n"))(set'l(string-width s))(when(> l f)(set'f l)))(let((fill-column f))(goto-char(point-min))(while(<(point)(point-max))(center-line)(next-line))))) ``` Ungolfed: ``` (let ((f 0) (l 0)) (dolist (s (split-string(buffer-string) "\n")) (set 'l (string-width s)) (when (> l f) (set 'f l))) (let ((fill-column f)) (goto-char (point-min)) (while (< (point) (point-max)) (center-line) (next-line))))) ``` Centered: ``` (let ((f 0) (l 0)) (dolist (s (split-string(buffer-string) "\n")) (set 'l (string-width s)) (when (> l f) (set 'f l))) (let ((fill-column f)) (goto-char (point-min)) (while (< (point) (point-max)) (center-line) (next-line))))) ``` [Answer] # Ruby, ~~76~~ ~~68~~ 61 bytes ``` ->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}} ``` Sample run: ``` 2.1.5 :001 > puts ->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}["Programming Puzzles\n&\nCode Golf"] Programming Puzzles & Code Golf ``` [Answer] ## HTML, 40 bytes ``` <xmp style=float:left;text-align:center> ``` ``` <xmp style=float:left;text-align:center> Programming Puzzles & Code Golf </xmp> ``` Snippet includes `</xmp>` tag because the code snippet viewer wants my tags to be balanced. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 22 ~~31~~ bytes ``` `jtYz~]xXhc4X4H$ZuZ{Zv ``` Each line is input with a trailing line (that is, an `enter` keystroke). An empty line (two `enter` keystrokes) marks the end of input. ### Example ``` >> matl `jtYz~]xXhc4X4H$ZuZ{Zv > foo > barbaz > foo barbaz ``` ### Explanation ``` ` % do... j % input one string tYz~ % is it not empty? ] % ...while x % delete last input (empty string) Xh % concatenate all inputs into a cell array c % convert to char (2D array). This fills with spaces to the right 4X4H$Zu % center justify Z{ % convert to cell array of strings Zv % remove trailing blanks of each string ``` [Answer] # Haskell, ~~111~~ ~~81~~ 77 bytes ``` l=length f s|q<-lines s=unlines[([1..div(maximum(l<$>q)-l w)2]>>" ")++w|w<-q] ``` Input to the f function, the output is not printed. Usage: load in interpreter `ghci center.hs` and then if you want to print the output of f on a given string `putStr$f"Programming Puzzles\n&\nCode Golf"` Edit: Thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) for 34 bytes, great job! :D [Answer] # R, 126 bytes ### code ``` for(z in 1){l=scan(,"");m=sapply(l,nchar);t=max(m[m==max(m)]);for(i in 1:length(m))cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")} ``` ### ungolfed ``` for(z in 1){ # any way to get rid of this? l=scan(,"") m <- sapply(l,nchar) t <- max(m[m==max(m)]) for(i in 1:length(m)){ cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="") } } ``` Probably there are waay better ways to do this, still working on it. [Answer] # Gema, 160 bytes ``` \L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}} ?= \Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o ``` Written mostly for my curiosity to see what can be done in a language without proper array structure and proper loop instruction. Sample run: ``` bash-4.3$ gema '\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}};?=;\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o' <<< $'Programming Puzzles\n&\nCode Golf' Programming Puzzles & Code Golf ``` [Answer] # [Perl 6](http://perl6.org), 61 bytes ``` $/=(my@l=lines)».chars.max;for @l {put ' 'x($/-.chars)/2~$_} # 61 bytes ``` usage: ``` $ perl6 -e '$/=(my@l=lines)».chars.max;for @l {put " "x($/-.chars)/2~$_}' <<< \ 'Programming Puzzles & Code Golf' ``` ``` Programming Puzzles & Code Golf ``` [Answer] # Japt, ~~28~~ 25 ``` ¡V=VwXl}R;¡Sp½*(V-Xl¹+X}R ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=oVY9VndYbH1SO6FTcL0qKFYtWGy5K1h9Ug==&input=IlByb2dyYW1taW5nIFB1enpsZXMKJgpDb2RlIEdvbGYi) ### How it works ``` ¡ V=VwXl}R;¡ Sp½*(V-Xl¹ +X}R UmXYZ{V=VwXl}R;UmXYZ{Sp½*(V-Xl) +X}R // Implicit: U = input string, V = 0 UmXYZ{ } // Map each item X in U through this function, R // splitting U at newlines beforehand: V=VwXl // Set V to max(X, Y.length). // V is now set to the length of the longest line. UmXYZ{ } // Map each item X in U with this function, R // again splitting U at newlines beforehand: ½*(V-Xl) // Take V minus X.length, and multiply by 1/2. Sp // Repeat a space that many times. +X // Concatenate X to the end. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .c ``` Builtins ftw ¯\\_(ツ)\_/¯ [Try it online](https://tio.run/##yy9OTMpM/f9fL/n/fyUlpYCi/PSixNzczLx0hYDSqqqc1GIuNS7n/JRUBff8nDSgCgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@V8v@b/OoW32/6OV3PLzY/KSEouSEquUdJQ8UnNygPzw/KKcFCA3oCg/vSgxNzczL10hoLSqKie1OCZPLSbPOT8lVcE9PydNKRYA). **Explanation:** ``` .c # Centralize the (implicit) multi-line input-string with preference to the left # (output the result implicitly) ``` (Preference to the right would be with a capital `.C` instead: [see the differences](https://tio.run/##yy9OTMpM/f9fySc1rUShoCg1LbUoNS851UpJx1MvWefQNnuloMz0DAwpZx2gHiUlt/x8rqTEoqTEKiAHAA).) [Answer] # [PHP](https://php.net/), 98 bytes ``` function($s){foreach($a=explode(" ",$s)as$l)echo str_pad($l,max(array_map(strlen,$a)),' ',2)," ";} ``` [Try it online!](https://tio.run/##Dc5NCsIwEEDhfU8RJNgJBBSX1uLChVtvEIZ20hbSTJhE8AfPXrN@PPjSnLbLNc1JkQiLE0osZYkTHE2ntO83/4xDWTiCzubrWQiHGTT29EqBR4Jds7M1YdbB0DCzykVcwhF0sCu@AEXw7VZMUEOgaDUaY1vV2pOxde5@W6c9@CWQm6i4gWOhWDK0VXU@HHIZl9ga020P4UlwXatOPZ6fT6Dc7JtbRag7B/8H "PHP – Try It Online") Ungolfed: ``` function str_center( $s ) { $a = explode( PHP_EOL, $s ); $m = max( array_map( 'strlen', $a ) ); foreach( $a as $l ) { echo str_pad( $l, $m, ' ', STR_PAD_BOTH ), PHP_EOL; } } ``` Output: ``` Programming Puzzles & Code Golf ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 byte ``` û ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bw==&input=IkZvbwpiYXJiYXoi) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=%2bw==&input=WyJGb28KYmFyYmF6IgoiSGVsbG8KV29ybGQiCiJQcm9ncmFtbWluZyBQdXp6bGVzCiYKQ29kZSBHb2xmIgpd) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 25 bytes ``` {↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵} ``` There's an APLcart snippet for centering in a field: `Is(⊢↑⍨∘-∘⌊2÷⍨+∘≢)Dv` This answer is partly based on it. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR20QN3Uc9XRoaj3o69B91Ljq04lHvVk1tOOvwdiNNoCIwp/Z/2qO2CY96@x51NT/qXfOod8uh9cZAyUd9U4ODnIFkiIdn8P80BXW3/Hx1BfWkxKKkxCp1LqAEUJu6OhdQxiM1JwckF55flJOCKhVQlJ9elJibm5mXrhBQWlWVk1oMVKgGxM75KakK7vk5aeoA "APL (Dyalog Extended) – Try It Online") ## Explanation ``` {↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵} (⌈/≢¨⍵) Maximum of lengths of each line +≢¨⍵ Plus length of each line ( )÷2 divided by two -⌊( ) Floor it, and take negative ( )↑¨⍵ Take that much from each line (taking a negative value prepends spaces) ↑ Mix the final array to print on each line { } dfn ``` [Answer] ## Pascal, 404 bytes This complete `program` is suitable for any processor complying with ISO standards 7185 (“Standard Pascal”) or 10206 (“Extended Pascal”). The `maximumLineLength` algorithm requires that every line has a maximum length of `maxInt` characters. ``` program p(input,output);type Z=integer;var b:text;l:file of Z;c,m:Z;begin m:=0;c:=0;rewrite(b);rewrite(l);while not EOF do begin if EOLn then begin write(l,c);c:=0;writeLn(b)end else begin c:=c+1;if c>m then m:=c;write(b,input^)end;get(input)end;reset(b);reset(l);while not EOF(b)do begin read(l,c);for c:=1 to(m-c)div 2 do write(' ');while not EOLn(b)do begin write(b^);get(b)end;writeLn;get(b)end end. ``` Ungolfed: ``` program centerTheText(input, output); type integerNonNegative = 0‥maxInt; var { The behavior of `reset(input)` is implementation-defined. Using a buffer `text` file avoids relying on specific behavior. } buffer: text; { Stores the length of a line in `input` (buffered in `buffer`). } lineLength: file of integerNonNegative; { The length of the currently processed line. } currentLineLength: integerNonNegative; { The length of the longest line found. } maximumLineLength: integerNonNegative; begin maximumLineLength ≔ 0; currentLineLength ≔ 0; { Open files for writing and set their lengths to zero (“truncate”). } rewrite(buffer); rewrite(lineLength); { process and analyze `input` ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ } while not EOF(input) do begin { Invocation of `EOLn(input)` is only valid if `not EOF(input)`. } if EOLn(input) then begin { `input↑` contains a space so we cannot just copy it. } writeLn(buffer); { Store the determined line length for the centering. } write(lineLength, currentLineLength); { Prepare `currentLineLength` for the next line. } currentLineLength ≔ 0; end else begin currentLineLength ≔ currentLineLength + 1; { In Extended Pascal you could write: `maximumLineLength ≔ card([0‥currentLineLength, 0‥maximumLineLength]) − 1`. } if currentLineLength > maximumLineLength then begin maximumLineLength ≔ currentLineLength; end; { For later reference store `input↑` in `buffer`. } write(buffer, input↑); end; { Advance reading cursor. } get(input); end; { Open files for reading from the start. } reset(buffer); reset(lineLength); { Reproduce `input` but centered. ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ } while not EOF(buffer) do begin read(lineLength, currentLineLength); { In Extended Pascal you could also just write: `write('':(maximumLineLength − currentLineLength) div 2)` } for currentLineLength ≔ 1 to (maximumLineLength − currentLineLength) div 2 do begin write(output, ' '); end; { Do not enter loop in case of an empty line. } while not EOLn(buffer) do begin write(output, buffer↑); get(buffer); end; { Discard the end-of-line marker character. } get(buffer); { Emit the implementation-specific end-of-line marker character. } writeLn(output); end; end. ``` ## Extended Pascal, 252 bytes Requiring a processor compliant with ISO standard 10206 “Extended Pascal” the schema data type `string` becomes available. Lots of operations can be thus abbreviated: ``` program p(input,output);var b:text;l:string(maxInt);m:integer;begin m:=0;rewrite(b);while not EOF do begin readLn(l);if m<length(l)then m:=length(l);writeLn(b,l)end;reset(b);while not EOF(b)do begin readLn(b,l);writeLn('':(m-length(l))div 2,l)end end. ``` Ungolfed: ``` program centerTheText(input, output); type { `integer…` prefix to facilitate sorting in documentation tools. } integerNonNegative = 0‥maxInt; var buffer: text; line: string(maxInt); maximumLineLength: integerNonNegative value 0; begin { The size of `buffer` immediately becomes zero. } rewrite(buffer); { Find the length of the longest line in `input`. } while not EOF(input) do begin readLn(input, line); { Is the current line longer than the longest line so far? } if length(line) > maximumLineLength then begin maximumLineLength ≔ length(line); end; { Store the read `input` line in `buffer` for later retrieval. } writeLn(buffer, line); end; { (Re‑)open `buffer` and start reading `buffer` from the start. } reset(buffer); { The `while` loop is not entered in case `buffer` is an empty file. } while not EOF(buffer) do begin readLn(buffer, line); { Empty strings (`''`) are only allowed in Extended Pascal. For `string` values the `integer` expression after the colon dictates the _exact_ width of the string padded with spaces. } writeLn('':(maximumLineLength − length(line)) div 2, line); end; end. ``` ]
[Question] [ Write a script that writes to standard output, or your language's equivalent, 100 lines of (valid) Java code that begins with: ``` class Tuple1 {public Object _0;} class Tuple2 {public Object _0,_1;} class Tuple3 {public Object _0,_1,_2;} class Tuple4 {public Object _0,_1,_2,_3;} class Tuple5 {public Object _0,_1,_2,_3,_4;} class Tuple6 {public Object _0,_1,_2,_3,_4,_5;} class Tuple7 {public Object _0,_1,_2,_3,_4,_5,_6;} class Tuple8 {public Object _0,_1,_2,_3,_4,_5,_6,_7;} class Tuple9 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8;} class Tuple10 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9;} class Tuple11 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10;} class Tuple12 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11;} ``` The last line should begin with `class Tuple100`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # vim ~~56~~ 54 keystrokes ``` iclass Tuple1 {public Object _0;}<esc>qyYp<C-a>$y2bPr,<C-a>q98@y ``` Since V is backwards compatible, you can [Try it online!](https://tio.run/##K/v/PzM5J7G4WCGktCAn1VChuqA0KSczWcE/KSs1uUQh3sC61ia1ONmusDKywMZZN9FOpdIoKaBIB8wutLRwqPz//79uGQA "V – Try It Online") This is the perfect task for vim! I might golf it a little bit more later. Also note that `<c-a>` means Control-A, and it counts as one keystroke. Explanation: ``` iclass Tuple1 {public Object _0;}<esc> 'Enter the starting text qy 'Start recording in register y Yp 'Yank the current line, the print on the line below <C-a> 'Increment the next digit to occur by one $ 'Move to the end of this line y2b '(yank) 2 words (b)ack. This will grab '_0;' P 'Print the previously yanked word before the cursor. r, '(r)eplace the char under the cursor with a comma. <c-a>q 'Increment the current digit, then stop recording 99@y 'Playback macro 'y' 99 times. ``` [Answer] # Jelly, 44 bytes ``` R’j“,_” “¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶” ȷ2RÇ€ ``` My first Jelly answer. [Try it online!](http://jelly.tryitonline.net/#code=UuKAmWrigJwsX-KAnQrigJzCpD4lLG_hu4rIpMqg4oCcw5jhu6XEijVEwrPhuYPhuaDJvFHCu2o7w4c74oCcO33CtuKAnQrItzJSw4figqw&input=) [Answer] # Java, 160, 125 Bytes Thanks to @DenkerAffe, @Denham Coote and @Mathias Ettinger for the improvements. Java writing java( because someone had to!) ``` void z(){String s="_0";for(int i=1;i<101;){System.out.println("class Tuple"+(i++)+" {public Object "+s+";}");s+=",_"+i;}} ``` ### And the un-golfed version ``` void z(){ String s = "_0"; for(int i = 1 ;i < 101;){ System.out.println("class Tuple" + (i++) + " {public Object "+ s + ";}"); s += ",_" + i; } } ``` [Answer] # Jolf, 42 bytes Do I get bonus points for beating Jelly with the best score ever? Contains unprintables, so you may want to try it [online here](http://conorobrien-foxx.github.io/Jolf/#code=wp_OnHp-MWQizp4vwojOryBUdXBsZSUge86eMMKMfyDOnjJRzrwgXyU7fSJIUnpIIixf). I replaced the unprintables with their respective alt index for readability. ``` ‼Μz~1d"Ξ/êί Tuple% {Ξ0î⌂ Ξ2Qμ_ %;}"HRzH",_ ``` ## Explanation ``` ‼Μz~1d"Ξ/êί Tuple% {Ξ0î⌂ Ξ2Qμ _%;}"HRzH",_ Μz~1d map the range 1..100 with the following function " begin a string Ξ/êί short for "class" Tuple% { H string interpolate H (current number) Ξ0î⌂ Ξ2Qμ short for "public Object" _%;}" RzH string interpolate with a range from 1..H joined ",_ by the string ",_" (auto-closed quotes) ``` [Answer] ## Pyth, ~~53~~ ~~50~~ 48 bytes ``` VS100%." }SüÆðQ´Ó3Ô«%&a´4UçõÛ"[Nj",_"UN ``` [Try it online!](http://pyth.herokuapp.com/?code=VS100%25.%22+%7DS%C2%92%C3%BC%C3%86%C3%B0Q%C2%B4%C3%933%C3%94%10%C2%AB%25%07%C2%93%17%06%26%C2%89%19a%C2%B4%C2%9A4U%C3%A7%C3%B5%C3%9B%22%5BNj%22%2C_%22UN&debug=0) Straightforward iteration over range(1,100) and building the corrosponding string from a packed string through formatting it. ## Explanation ``` VS100%." }SüÆðQ´Ó3Ô«%&a´4UçõÛ"[Nj",_"UN VS100 # Iterate over range(1,100) %." }SüÆðQ´Ó3Ô«%&a´4UçõÛ" # Unpack the string and format it [ # List for formatting arguments N # Number of the Tuple j UN # Join Object numbers... ",_" # ...on the seperator ",_" ``` The unpacked string is `class Tuple%i {public Object _%s;}` [Answer] # CoffeeScript, ~~86~~ 84 bytes ``` console.log "class Tuple#{i} {public Object _#{[0...i].join ',_'};}"for i in[1..100] ``` [View the solution online](https://jsfiddle.net/1500535g/) [Answer] ## Powershell - 65 bytes (Amended in response to comment) All credit to TimmyD ``` 1..100|%{"class Tuple$_ {public Object _$(0..($_-1)-Join",_");}"} ``` [Answer] # Oracle SQL 9.2, ~~138~~ 137 Bytes ``` SELECT REPLACE('class Tuple'||LEVEL||' {public Object'||SYS_CONNECT_BY_PATH(LEVEL-1,',_')||';}','t,','t ')FROM DUAL CONNECT BY LEVEL<101; ``` @Peter Thanks for pointing the 0/1 mistake. The query use the CONNECT BY CLAUSE of hierarchical query to generate 100 rows. The LEVEL pseudocolumn contains the row number of each row. SYS\_CONNECT\_BY\_PATH concatenate the first parameter, the row number, of each row, and use the second parameter as the separator. [Answer] ## Batch, 128 bytes ``` @set m=_0 @for /l %%t in (1,1,100)do @call:b %%t @exit/b :b @echo class Tuple%1 {public Object %m%;}&set m=%m%,_%1 ``` Edit: Saved 10 bytes thanks to @Bob. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ. [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~80~~ 79 bytes Byte count assumes ISO 8859-1 encoding. ``` 100$*1 1 class Tuple11$` {public Object 1$`}¶ 1(?<= (1+)) _$1, 1(1)* $#1 ,} ;} ``` [Try it online!](http://retina.tryitonline.net/#code=CjEwMCQqMQoxCmNsYXNzIFR1cGxlMTEkYCB7cHVibGljIE9iamVjdCAxJGB9wrYKMSg_PD0gKDErKSkKXyQxLAoxKDEpKgokIzEKLH0KO30&input=) [Answer] # [Perl 6](http://perl6.org), 65 bytes ``` say "class Tuple$_ \{public Object _{join ',_',^$_};}" for 1..100 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 66 bytes ``` ↑{∊'class Tuple'(⍕1+⍵)' {public Object _0'(',_'∘,∘⍕¨⍳⍵)';}'}¨0,⍳99 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jtonVjzq61JNzEouLFUJKC3JS1TUe9U411H7Uu1VTXaG6oDQpJzNZwT8pKzW5RCHeQF1DXSde/VHHDB0gBio8tOJR72awWuta9dpDKwx0gHxLS5Dp/9MA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ↑{∊'class Tuple'(⍕1+⍵)' {public Object _0'(',_'∘,∘⍕¨⍳⍵)';}'}¨0,⍳99 0,⍳99⍝ Numbers 0-99 ¨ ⍝ map to dfn ↑ ⍝ mix the result ∊'...'(⍕1+⍵)'...' ⍝ join the class header, tuple name (index + 1) ⍝ and the first tuple element. (',_'∘,∘⍕¨⍳⍵) ⍝ numbers from 1 to ⍵ prepended with ',_' ';}' ⍝ finish the class declaration ``` [Answer] # R - ~~199~~ ~~132~~ ~~123~~ 118 bytes Version 4 ``` p=paste0;for(i in 1:10)cat(p("class Tuple",i," {public Object ",toString(sapply(0:(i-1),function(x)p("_",x))),";}\n")) ``` Version 3 ``` p=paste0;for(i in 1:8)cat(p("class Tuple",i," {public Object ",p(sapply(0:(i-1),function(x)p("_",x)),collapse=","),";}\n")) ``` Version 2 ``` p=paste0;for(i in 1:100)cat(p("class Tuple",i," {public Object ",p(sapply(0:(i-1),function(x)p("_",x)),collapse=","),";}"),sep="\n") ``` Version 1 ``` for (i in 1:100){ foo <- paste0("class Tuple", i, " {public Object ") for (j in 0:(i - 1)){ foo <- if (j < (i - 1)) paste0(foo, "_", j, ",") else paste0(foo, "_", j, ";}") } print(foo) } ``` [Answer] # Ruby, 71 bytes ``` 100.times{|i|puts"class Tuple#{i+1} {public Object _#{[*0..i]*',_'};}"} ``` [Answer] # Java, 103 bytes ``` s->{s="_0";for(int i=0;i++<100;s+=",_"+i)System.out.printf("class Tuple%s {public Object %s;}\n",i,s);} ``` My first time here. Hi there! I went for a Java8 lambda expression (aka an anonymous function). ## Ungolfed version ``` s -> { s = "_0"; for (int i = 0; i++ < 100; s += ",_" + i) System.out.printf("class Tuple%s {public Object %s;}\n", i, s); } ``` To actually use this, as usual in Java8, you have to assign it to a variable of (or cast it to) an appropriate functional interface and then call its method; but technically, the function is only the lambda expression itself, so I am counting only that. It also requires an input parameter, which saves me a couple bytes, since I can abuse it as a local variable without having to specify its type. I'm not sure if that's considered cheating, but to me it appears to be within the rules: I only saw people state that posting a function is allowed, not *how* that function needs to be invoked. :) And it doesn't actually read the parameter, so the function is still self-contained; you can pass any String to it, or even null, and it will still produce the correct output. ## And here is how to use it: ``` import java.util.function.Consumer; public class Main { public static void main(String[] args) { Consumer<?> r = s->{s="_0";for(int i=0;i++<100;s+=",_"+i)System.out.printf("class Tuple%s {public Object %s;}\n",i,s);} ; r.accept(null); } } ``` [Answer] # Python 2, 96 ``` def f(n=99):s=n and f(n-1)+',_'+`n`or"class Tuple%d {public Object _0";print s%-~n+';}';return s ``` # Python 3, 98 ``` def f(n=99):s=n and f(n-1)+',_%d'%n or"class Tuple%d {public Object _0";print(s%-~n+';}');return s ``` **Usage:** ``` f() ``` **Ungolfed:** ``` def javatuple(n=99): if n == 0: s = "class Tuple%d {public Object _0" else: s = javatuple(n-1) + ',_' + str(n) print(s%(n+1) + ';}') return s ``` **formers:** **103** ``` r=range for i in r(100): print"class Tuple%d {public Object _%s;}"%(i+1,',_'.join(`j`for j in r(i+1))) ``` **108** ``` def f(n=99): if n:f(n-1) print"class Tuple%d {public Object _%s;}"%(n+1,',_'.join(`i`for i in range(n+1))) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes ``` 1..100|%{"class Tuple$_ {public Object _$(0..--$_-Join",_");}"} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz9DAoEa1Wik5J7G4WCGktCAnVSVeobqgNCknM1nBPykrNblEIV5Fw0BPT1dXJV7XKz8zT0knXknTulap9v9/AA "PowerShell – Try It Online") Two byte improvement of [bulletprooffool's answer](https://codegolf.stackexchange.com/a/70915/78849), who seems to be an abandoned account now. [Answer] # CJam, 53 bytes ``` 100{)"class Tuple"\" {public Object _"1$,",_"*";} "}/ ``` [Try it here](http://cjam.aditsu.net/#code=100%7B)%22class%20Tuple%22%5C%22%20%7Bpublic%20Object%20_%221%24%2C%22%2C_%22*%22%3B%7D%0A%22%7D%2F). [Answer] # Groovy, 74 chars "join()" is unbeatable... New solution, thanks to @yariash ``` 100.times{println"class Tuple$it {public Object _${(0..it-1).join',_'};}"} ``` Old solution, 78 chars: ``` (1..100).each{println"class Tuple$it {public Object _${(0..it-1).join',_'};}"} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 43 bytes ``` тFNÝ„,_ý'_ì'Œº™'‚ÆN>'„à"ÿ Tupleÿ {ÿ ÿ ÿ;}"= ``` [Try it online!](https://tio.run/##yy9OTMpM/f//YpOb3@G5jxrm6cQf3qsef3iN@tFJh3Y9almk/qhh1uE2PzsgPe/wAqXD@xVCSgtyUoF0NRCDkXWtku3//wA "05AB1E – Try It Online") [Answer] # FALSE, 85 bytes ``` 1[$100>~][$$0"class Tuple"\." {public Object "[$@$@=~][\$0>[","]?$"_".1+]#";} "%%1+]# ``` [Try it online!](https://tio.run/##S0vMKU79/98wWsXQwMCuLjZaRcVAKTknsbhYIaS0ICdVKUZPSaG6oDQpJzNZwT8pKzW5REEpWsVBxcEWqDhGxcAuWklHKdZeRSleSc9QO1ZZybqWS0lVFcT8/x8A) Loops through 1-100 to get the Tuple number and then within that loops from 0 to currnum-1 to get underscores. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 36 bytes ``` `⟑↓ Tuɖ¾% {ƛḊ ß₂ %;}`₁ƛɾ\_$+\,j";v%⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJg4p+R4oaTIFR1yZbCviUge8ab4biKIMOf4oKCICU7fWDigoHGm8m+XFxfJCtcXCxqXCI7diXigYsiLCIiLCJbOSwgNywgLTEsIDYsIDUsIDIsIDExLCAxNiwgMjddIl0=) ``` ₁ƛ ; # map 1...100 to... ɾ # 1...n \_$+ # Prepend underscores to each \,j # Join by commas " # Pair with n `...` # Compressed string `class Tuple% {public object %;}` v% # Formatted with (n, names) ⁋ # Join by newlines ``` [Answer] # Julia, 77 bytes ``` for i=1:100;println("class Tuple$i {public Object _$(join(0:i-1,",_"));}")end ``` [Answer] # Lua, ~~128~~ 106 Bytes I'm still trying to find a way to directly work on a printed value, and not on a string. **Edit : Partially found it! I still need a string for the "\_0,\_1..." part, but it already is better :).** ``` s=""for i=0,99 do s=(s..",_"..i):gsub("^,",s)print(("class Tuple"..(i+1).." {public Object ")..s..";}")end ``` ### Old 128 Bytes solution ``` s="class Tuple1 {public Object _0;}"print(s)for i=1,99 do s=s:sub(1,s:find";"-1):gsub("e%d+","e"..i+1)..",_"..i..";}"print(s)end ``` ### Ungolfed ``` s="" for i=0,99 do s=(s..",_"..i) -- concatenate s with ",_i" :gsub("^,",s) -- remove the leading "," for ",_0" -- then print the concatenated string print(("class Tuple"..(i+1).." {public Object ")..s..";}") end ``` [Answer] # Python 3, 111 109 105 bytes ``` [print('class Tuple%s {public Object %s;}'%(i,','.join('_%i'%j for j in range(i))))for i in range(1,101)] ``` It's not the shortest thing in the world, I'm just participating. edit1: down 2 bytes by removing `0,` in first `range` edit2: I was unnecessarily casting `int` to `str` instead of just using `%i`... Down to 105. [Answer] # Mathematica, 130 Bytes ``` {"class Tuple",ToString[#]," {public Object ",StringReplace[ToString[#-1&/@Range@#],{" "|"{" ->"_","}"->";}\n"}]}&/@Range[100]<>"" ``` [Answer] # Scala, 85 Bytes ``` for(u<-1 to 100)println(s"class Tuple$u {public Object _${0 to u-1 mkString ",_"};}") ``` [Answer] ## Java, 116 (for the printing function only - according to some comments, this is in line with the rules) ``` import static java.lang.System.*; public class T { public static void main(String[] args) { T t = new T(); t.p(); } void p(){String s="_0";for(int i=0;i<100;){out.println("class Tuple"+ ++i+" {public Object "+ s + ";}");s+=",_"+i;}} } ``` [Answer] ## PHP, 112 bytes ``` <?php for($i=0;$i<100;$i++){$m.=$i==0?'_'.$i:',_'.$i;echo 'class Tuple'.($i+1).' {public Object '.$m.';}<br/>';} ``` [Answer] ## Seriously, 55 bytes ``` 2╤R`;r"$'_+"£M',j@k"c╙ò T╒α%d {pu▐V Object %s;}"⌡%`M' j ``` Hexdump (reversible with `xxd -r`): ``` 00000000: 32e2 95a4 5260 3b72 2224 275f 2b22 c2a3 2...R`;r"$'_+".. 00000010: 4d27 2c6a 406b 2263 e295 99c3 b220 54e2 M',j@k"c..... T. 00000020: 9592 ceb1 2564 207b 7075 e296 9056 204f ....%d {pu...V O 00000030: 626a 6563 7420 2573 3b7d 22e2 8ca1 2560 bject %s;}"...%` 00000040: 4d27 0a6a M'.j ``` [Try it online!](http://seriously.tryitonline.net/#code=MuKVpFJgO3IiJCdfKyLCo00nLGpAayJj4pWZw7IgVOKVks6xJWQge3B14paQViBPYmplY3QgJXM7fSLijKElYE0nCmo&input=) Yes, that newline is supposed to be there. Explanation (newline replaced with `\n`): ``` 2╤R`;r"$'_+"£M',j@k"c╙ò T╒α%d {pu▐V Object %s;}"⌡%`M'\nj 2╤R push range [1,100] ` `M map: ;r push a, range(a) "$'_+"£M map: $'_+ stringify, prepend "_" ',j join with commas @k swap and push stack as list "c╙ò T╒α%d {pu▐V Object %s;}"⌡ decompress, result is "class Tuple%d {public Object %s;}" % string format '\nj join with newlines ``` ]
[Question] [ This is a 2-dimensional version of [this question](https://codegolf.stackexchange.com/q/71877/9288). Given a non-empty 2-dimensional array/matrix containing only non-negative integers: $$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & 0 & 1 & 0 \\ {\color{Red}0} & {\color{Red}0} & 0 & 0 & 1 \\ {\color{Red}0} & {\color{Red}0} & 1 & 1 & 1 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} $$ Output the array with surrounding zeroes removed, i.e. the largest contiguous subarray without surrounding zeroes: $$ \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 1 \end{bmatrix} $$ ## Examples: $$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & 0 & 1 & 0 \\ {\color{Red}0} & {\color{Red}0} & 0 & 0 & 1 \\ {\color{Red}0} & {\color{Red}0} & 1 & 1 & 1 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 1 \end{bmatrix} $$ ``` Input: [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 0, 0, 0]] Output: [[0, 1, 0], [0, 0, 1], [1, 1, 1]] ``` $$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & 0 & 0 & 3 \\ {\color{Red}0} & 0 & 0 & 0 \\ {\color{Red}0} & 5 & 0 & 0 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 0 & 0 & 3 \\ 0 & 0 & 0 \\ 5 & 0 & 0 \end{bmatrix} $$ ``` Input: [[0, 0, 0, 0], [0, 0, 0, 3], [0, 0, 0, 0], [0, 5, 0, 0], [0, 0, 0, 0]] Output: [[0, 0, 3], [0, 0, 0], [5, 0, 0]] ``` $$ \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \mapsto \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} $$ ``` Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` $$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} \end{bmatrix} $$ ``` Input: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] Output: [] ``` $$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ 1 & 1 & 1 & 1 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 1 & 1 & 1 & 1 \end{bmatrix} $$ ``` Input: [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]] Output: [[1, 1, 1, 1]] ``` $$ \begin{bmatrix} {\color{Red}0} & 1 & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & 1 & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & 1 & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 1 \\ 1 \\ 1 \end{bmatrix} $$ ``` Input: [[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]] Output: [[1], [1], [1]] ``` $$ \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & 2 & 3 & 1 \\ 1 & 1 & 1 & 1 \end{bmatrix} \mapsto \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & 2 & 3 & 1 \\ 1 & 1 & 1 & 1 \end{bmatrix} $$ ``` Input: [[1, 1, 1, 1], [1, 2, 3, 1], [1, 1, 1, 1]] Output: [[1, 1, 1, 1], [1, 2, 3, 1], [1, 1, 1, 1]] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` #&@@CellularAutomaton[{,{},0{,}},{#,0},0]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7875@WFh1cmVeSWGFllZyfG2vNlWar8V9ZzcHBOTUnpzQnscixtCQfqDg/L7pap7pWx6Bap7ZWp1pZxwDIjlX7r2nNFVCUmVcSneagHKum71DNxVVdbaCjgEC1OgoIAUN0AZAYQsAQgtBVGACtRDEWRYExqnIozxSLSqg5QCuMoNpMwArNQExzHQULHQVLFKuQdCMza7m4av8DAA "Wolfram Language (Mathematica) – Try It Online") Cellular automata are indeed the answer to [life](https://www.wolfram.com/language/gallery/implement-conways-game-of-life/), [the universe](https://xkcd.com/505/), and [everything](https://cs.stackexchange.com/q/4779).1 ### How? `CellularAutomaton` accepts an input array and an optional background value. Thus, `{#,0}` specifies that a cellular automaton rule should be applied to the input, assuming a background of `0`s. A neat thing here is that `CellularAutomaton` crops the output so that no border of background cells is present (because otherwise the output lies on an infinite plane). The code applies the rule `{Null, {}, {0, 0}}` -- applying the head `Null` to the 0-radius neighbor of each cell (i.e. only the center: the cell itself) -- exactly `0` times. The result of this is the original input, but with background removed (i.e. cropping out surrounding `0`s). --- 1. See the bytecount of my answer? ;) [Answer] # JavaScript (ES6), 98 bytes ``` (a,z)=>(g=A=>A.slice(A.map(m=M=(r,i)=>M=(z?a:r).some(n=>z?n[i]:n)?1/m?i:m=i:M)|m,M+1))(a).map(z=g) ``` [Try it online!](https://tio.run/##nVHLboMwELz3K3z0qi7EaZsH0oL4AL4A@WBRghxhO4KqB9R/J@AEIWgiUFd7WI/HM2P7LH9knVXq8v1m7FfenrClkjWAIS0wxjD26lJlOY09LS9UY4K0Yqrb7oYmkkEFXm11Tg2GTWRSJQIDEfd1pAKNKkjgV7PklQNQCU6iwQLazJralrlX2oKeaJpuGBlbMDICfA702AjwW88ZGyEAiO8TJz3VcOThnHh5HmUi@j61uK8@HzBv3rMaosyU@nHQ@BulS7i98z@c164f94wcGDk@cllVLsqC9NpXWXHzpShLXvzJJ//HKyWjGhGivQI "JavaScript (Node.js) – Try It Online") ### How? To overcome the lack of a *zip* built-in, we define a function ***g()*** that is able to operate on either the rows or the columns of the input matrix ***a[ ]***, depending on the value of the global flag ***z***. ***g()*** looks for the minimum index ***m*** and maximum index ***M*** of either non-empty rows (if ***z*** is undefined) or non-empty columns (if ***z*** is defined) and returns the corresponding *slice* of either the matrix itself or a given row of the matrix. To summarize: * we first remove rows by invoking ***g()*** on the matrix with ***z*** undefined * we then remove columns by invoking ***g()*** on each row with ***z*** defined, which leads to this rather unusual `.map(z=g)` ### Commented ``` (a, z) => ( // a[] = input matrix; z is initially undefined g = A => // g() = function taking A = matrix or row A.slice( // eventually return A.slice(m, M + 1) A.map(m = M = // initialize m and M to non-numeric values (r, i) => // for each row or cell r at position i in A: M = (z ? a : r) // iterate on either the matrix or the row .some(n => // and test whether there's at least one z ? n[i] : n // non-zero cell in the corresponding column or row ) ? // if so: 1 / m ? i // update the maximum index M (last matching index) : m = i // and minimum index m (first matching index) : // otherwise: M // let M (and m) unchanged ) | m, // end of map(); use m as the first parameter of slice() M + 1 // use M+1 as the second parameter of slice() ) // end of slice() )(a) // invoke g() on the matrix with z undefined .map(z = g) // invoke g() on each row of the matrix with z defined ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` JYa ``` [Try it online!](https://tio.run/##y00syfn/3ysy8f//aAMdBQSyRrANUbkgEWuElCESF4piAQ "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N8rMvG/uq6ueoRLyP9oAx0FBLJGsA1RuSARa4SUIRIXimK5orEaZGyNboEphhqQZqCRRmDVJmAVZtYK5joKFjoKlrgMRjUAAA). ### Explanation ``` J % Push 1j Ya % With complex 2nd input, this unpads the matrix in the % 1st input (implicit). The unpad value is 0 by default % Display (implicit) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~62~~ 61 bytes ``` f.f.f.f f=reverse.foldr(zipWith(:))e.snd.span(all(<1)) e=[]:e ``` [Try it online!](https://tio.run/##y0gszk7NyfmfrmCrEPM/TQ8MudJsi1LLUouKU/XS8nNSijSqMgvCM0syNKw0NVP1ivNS9IoLEvM0EnNyNAztNDW5Um2jY61S/@cmZuYBjSkoyswrUVBRSFeI5lKINtCBwlgdMM8QhWeAxjPCIhf7/19yWk5ievF/3QjngAAA "Haskell – Try It Online") `foldr(zipWith(:))e` with `e=[]:e` is a [slightly shorter `transpose`](https://codegolf.stackexchange.com/a/111362/56433), and `snd.span(all(<1))` drops leading lists of zeros from a list of list. As `transpose` followed by `reverse` on a 2D list equals an rotation by 90°, the code `f.f.f.f` is just four times *drop leading lists of zeros and rotate*. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` V2=.sCQ]m0Q;Q ``` [Try it online!](https://tio.run/##bUxLCoMwEF03pxik4CZ@ov2i7aYnyKYbycKalAjWiArF06cxFatQBmbem/d55J3UUuQcvMIjkKbgCvV04QqF4kLfo4vf3Sh7hTSh2igIvWVZCWhtpIWqrEUCXKFNM/RS1TEEqumDkdjlN4NtMs0pONvR7iCuaqGzLMTTMDxhssCGTZiMs/iHjKE5Pf/jn8Oi/Ur9ZgiOrG9n1IO5R3zC579t6@QH "Bash – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` œr€0z0Uµ4¡ ``` [Try it online!](https://tio.run/##y0rNyan8///o5KJHTWsMqgxCD201ObTw/@H2o5Me7pzx/390tIGOAhTF6iggeMYoPJicKRaVBrGxAA "Jelly – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~24~~ ~~22~~ ~~20~~ 19 bytes ``` {s.h+>0∧.t+>0∧}\↰₁\ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7pYL0PbzuBRx3K9EghdG/OobcOjpsaY//@jow10FKAoVkcBwTNG4cHkTLGoNIiN/R8FAA "Brachylog – Try It Online") Outputs the result matrix as an array of arrays, or false for empty output. *(Thanks to @Fatalize for suggesting inline predicate and saving 1 byte.)* ### Explanation **Predicate 0 (Main):** ``` {...} Define and call predicate 1 to remove all-zero rows \ Transpose the result ↰₁ Call pred 1 again, now to remove all-zero columns \ Transpose the result to have correct output orientation ``` **Predicate 1:** ``` ?s.h+>0∧.t+>0∧ . output is s a subsequence of the rows of ? the input (implicit) h also, output's head element (first row) +>0 has a sum > 0 (i.e. has at least one non-zero value) ∧.t+>0 and similarly the output's tail element (last row) ∧ (don't implicitly unify that 0 with the output) ``` [Answer] # [R](https://www.r-project.org/), ~~96 100~~ 97 bytes ``` function(m)m[~m,~t(m),drop=F] "~"=function(x,z=seq(r<-rowSums(x)))z>=min(y<-which(r>0))&z<=max(y) ``` [Try it online!](https://tio.run/##jVFdT8JAEHzvr9icidmL1wj4nVDe9AcgPkFjoB6lSXutd9dQUPnruNdWEUIiyV1yM92Z2d3q7RmMSq0MFEUU@8auUgnG6kTFkCibwxCyKcEK5rkGK42FaGoklEZ6TtHT0PdhXqrIJrnCisOHB1A5MjblDBkwwZioOLHqVedL4z6lUsV2YVDLmNyjhTRYCYgJyqrQyCaTMRNQcc7Bh24tjfK0luJ/WvGjvIAuh8s21XmUWe1A09k8wVKlibFIyBRpYrFpN/qkbLohubDaSbgJyI8cmk2gMxKtr2hbEzBbEYYARsOXR@59ed7chW1/V5PxbLzJxMbSS7zpvAieQo9tWLBbnlgHRr6j7vtk9Uwp6AZZD4IsUbjq@8tFEi1QDzqcn6/7QTatcMW3c2x@BLLxuCNgd0IBO6J7SDhuR3Sbc1jRCUOanWY5mrFXfbWvbdHNkcpjphTeaz2ua9Wte94JuBfwcHoTJwX9Ke3toat94fYb "R – Try It Online") The `~` helper takes a non-negative vector and returns a vector with `FALSE` for the "exterior" `0`s of the vector and `TRUE` for positives and any "interior" `0`s. This function is applied to the row and column sums of the input matrix. `~` and `!` [use R's parser treatment of operators.](https://codegolf.stackexchange.com/a/164914/79980) Corrected as per @DigEmAll's comment, but with some bytes golfed back from @J.Doe [Answer] # [R](https://www.r-project.org/), ~~89~~ 79 bytes ``` function(m,y=apply(which(m>0,T),2,range)){y[!1/y]=0;m[y:y[2],y[3]:y[4],drop=F]} ``` [Try it online!](https://tio.run/##jVDLbsIwELznK7bpxVYXkQB9N721H4DoKVgVpCZESpzIdkQsyrdTO6RFoFStZEue8c7M7sr9JcxqKRRUVZIOlDY5B6VlJlLIhC5hCsXCwgZWpQTNlYZkoTjUintOMZLwNIBVLRKdlYI0FLYeQOPIVNVL4oOPvo8Ntax4l@VGua@ci1SvFZE8te7JmivSIKQW8qaSxJ/PYx@hoZTCAMJWmpR5KyV/afFbeQUhhWGX6jzqonWw0@kyI7XIM6WJRarKM00O7SafNtteZl381gndBNbPOhw2QZwRdr7YtYawNBZDBLPp2wv1dp63cmH7n9UUaKJFVeWGbNZZsibFc4AziiOUC5FySrcmvgiHhkXBYxGbBxOPGJp4zOxrwvBDllX0ynb7FTmsnfhxHCAcD0M4EuE54bgjER7OeUXAmJ3Udt6bcVI9PtV26Lqnss/Uho86j0mrunHPW4Q7hPv/N/F30Glp@Mvk/cLwJKMfOeH@Cw "R – Try It Online") Thanks to @ngm for the test cases code, and @J.Doe for saving 10 bytes ! * I had to add `drop=F` parameter due to the default R behavior turning single row/col matrix into vectors... [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~17~~ 15 bytes ``` {⍉⌽⍵⌿⍨∨\∨/×⍵}⍣4 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9aPezkc9ex/1bn3Us/9R74pHHStigFj/8HSgUO2j3sUm//@rp2QWF@QkVqoDtSZXqqek5RWrc5VANG991LmwCMhMe9S7y0o9P1v9UXcLTHlaYmaOOlAcqKqolkvjUdtEDQMFKNSEMg0RTCAHwjQEQU0ktZolEL1wxUBZiCIUU2FajDWRRUyRpRBmIZRpakCUQMwyVDACyZgA9ZlpapgrWChYQvVgk8FqP4ptIOpR7xYDAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 71 bytes Returns by modifying the input. A list should be passed as input. ``` def f(a):exec'while a and 1>sum(a[-1]):a.pop()\na[:]=zip(*a)[::-1]\n'*4 ``` [Try it online!](https://tio.run/##fZDLCoMwEEXXzVfMzqSkxVj7CljwO2IWoSoG2hispY@fT9VaRFsKs5i5c@ZeGPuoi9IEzqVZDjlWhGf37OjdCn3KQIEyKbDD5XrGSiyYJFwtbWkxSYwSXEZPbfFcEcF5s0yMNw9dHAk0E8KnMJSkMAhsKrTaILB3TQlfSjr2HRGrMd9P6x/kx6gJCfq7sCM3bbulsKOw/x/2ZYgkQnlZNf/SBmKOukcisJU2Nai@cS8 "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 77 bytes This also modifies the input, but it works.... ``` def f(a):exec'while a and 1>sum(a[-1]):a.pop()\na=zip(*a)[::-1]\n'*4;return a ``` [Try it online!](https://tio.run/##fZDdDoIwDIWv3VP0jo1MA/g/g4nPMXbR6AgkOpYJ8eflERVDQGPSi/b06zlJ7a3MChPV9UGnkFJkQl/13rtk@VEDApoDhNtzdaIox6FiAie2sJQlBuN7bqmPTArRbBLj@bON02XlDGC9iyUZSRlw6Epx6IRwKDy1TgjfNSQCpXjft0dM@3w7zX@QH6MmJGrvZi9y8WyXHFYc1v/DvgyJIiQtXPO13MBOEHBxSk9oaVnZo@bIGAHrclOCa5v6AQ "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes ``` If[Max@#>0,ImageCrop@Image[#~ArrayPad~1,r="Real"]~ImageData~r,{}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d8zLdo3scJB2c5AxzM3MT3VuSi/wAHMilaucywqSqwMSEypM9QpslUKSk3MUYqtA0u6JJYk1hXpVNfGqv3X5AooyswriU6Lrq420FGAolodBQTPGIUHkzPFotKgtjY2FtNAJDXITFS1hjpAWKsDpI2gNIgPVPMfAA "Wolfram Language (Mathematica) – Try It Online") Now works by padding the array with zeroes (thanks @JungHwanMin)! A second thanks to @JungHwanMin for saving 4 bytes [Answer] # [J](http://jsoftware.com/), 24 bytes ``` (|.@|:@}.~0=+/@{.)^:4^:_ ``` [Try it online!](https://tio.run/##bVHLbsIwELz7K0YowkQlBpekBZdEkSr11FOvlahQHjRIJIjm0KrAr6e2sSGN4pW9692ZHT@2zYCB5ggFKMaYQsjpMTy/vb40oyOLjyI@sfM0vJvEv8xdCX8lPhqXbNJip0kjRaOuXM@g3xTbqii/6kNRbvAuMBBDFuFpEjuE1IkirIUJ5DrGMkAAR0paM47fQrUxjttQW6eP3@pj3AztTNAu/WfPJNSRze8VxZfIB@ARcyw6KK3Rl7MqlzPyXgjvkfW1rLnZRZ8TQnZVuU6RZnlRZlAveGJ1QoAs@axAl2FnRNTWfmyg/@e6o/C8CDfUHiFD3kXvr3BK3OYP "J – Try It Online") ## Explanation ``` (|.@|:@}.~0=+/@{.)^:4^:_ +/ sum @ of {. the first row 0= is zero? (1 = true, 0 = false) }.~ chop off that many rows from the front |.@|:@ rotate by 90 deg (transpose then reverse) ( )^:4 repeat this process 4 times (rotating a total of 360 deg) ^:_ fixpoint - repeat until no change ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ṗ§Ṫ¬ȧƲ¿UZµ4¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzmmHlj/cuerQmhPLj206tD806tBWk0ML/x9uf9S0RuHopIc7Z/z/H82lEB1toGMQqwMmY3UgfEOoiBGSGEjEUMcQoTIWAA "Jelly – Try It Online") As a function. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes ``` Nest[Reverse@Thread@#//.{{0..},a___}->{a}&,#,4]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7875@WFh1cmVeSWGFllZyfG2vNlWar8d8vtbgkOii1LLWoONUhJKMoNTHFQVlfX6@62kBPr1YnMT4@vlbXrjqxVk1HWcckVu2/pjVXQFFmXkl0moNyrJq@QzUXF1CtjgIU1eooIHjGKDyYnCkWlQa1tToIc5CkkJm1XFy1/wE "Wolfram Language (Mathematica) – Try It Online") Doing it the normal way. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` !5¡(T0mo↔↓¬ ``` [Try it online!](https://tio.run/##yygtzv7/X9H00EKNEIPc/EdtUx61TT605v///9HRBjpgGKsDZRnDWRAxUxRZg9hYAA "Husk – Try It Online") I feel like some bytes could be shaved off by shortening the `!5¡` part. ### How it works ``` !5¡( ``` Repeatedly apply the function explained below, collecting the results in an infinite list. Then, retrive the \$5^{\text{th}}\$ element. In other words, apply the function to the input 4 times. ``` mo↔↓¬ ``` Map over the current version of the input and: reverse each, after having dropped the longest prefix consiting of zeroes only (dropping this prefix is performed by using Husk's `↓`, which is a function that crops the longest run of consecutive elements from the beginning of the list that yield truthy results when ran through a function, namely `¬`, logical not). ``` T0 ``` Transpose, replacing missing entries with **0**. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 87 bytes ``` /.\[(?!0,)/^+`\[0, [ /(?<! 0)]./^+`, 0] ] \[(\[0(, 0)*], )+ [ (, \[0(, 0)*])+]|\[0]] ] ``` [Try it online!](https://tio.run/##bYwxDoAgDAD3vgI2KgSqcTThIVCjg4OLg3H071gmEkPS5a7X3sdzXvtYSvA5majJYVjtlhM5BQmCiYtWhOyrdYoYGCSUvRHCgZ1CK6FQc2j5FWKJS0n1VRs5qGL6C@qLuVvwBw "Retina – Try It Online") Explanation: ``` /.\[(?!0,)/^+` ``` Until at least one row doesn't begin with zero... ``` \[0, [ ``` ... remove the leading zero from each row. ``` /(?<! 0)]./^+` ``` Until at least one row doesn't end with zero... ``` , 0] ] ``` ... remove the trailing zero from each row. ``` \[(\[0(, 0)*], )+ [ ``` Remove leading rows of zeros. ``` (, \[0(, 0)*])+]|\[0]] ] ``` Remove trailing rows of zeros, or the last remaining zero. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` F⁴«W∧θ¬Σ§θ±¹Σ⊟θ¿θ≔⮌E§θ⁰E觧θνλθ»⪫[]⪫Eθ⪫[]⪫ι, ¦, ``` [Try it online!](https://tio.run/##bY3LCoMwEEXX@hWDqxFSsMWdK5cttEi7DC6CRg3YxFdtofTb0/hoETHM4nBmcm9SsCZRrNQ6Uw2g78Lbtp6FKDlgKFOsCVxUh7fHHcPuKFP@GhXPWcdx744PokbI6SZSFdZGBbYlMjAIYduKXOKV97xpOZ5ZtQzyXAKDMvizi60023JoIFCbyI89FZ2UkOjQ2CEw4hyw1oKAQWf8PkOgNaXUM73/iQkM4rAW3rbwNy/iWO/68gs "Charcoal – Try It Online") Link is to verbose version of code. Includes 15 bytes for formatting. Explanation: ``` F⁴« ``` Repeat 4 times. ``` W∧θ¬Σ§θ±¹ ``` Repeat while the array is not empty but its last row sums to zero... ``` Σ⊟θ ``` Remove the last row from the array and print a line of the length of its sum, i.e. nothing. ``` ¿θ≔⮌E§θ⁰E觧θνλθ» ``` If the array isn't empty then transpose it. ``` ⪫[]⪫Eθ⪫[]⪫ι, ¦, ``` Format the array nicely for display. (Standard output would be `Iθ` instead.) [Answer] # JavaScript, 144 140 129 127 bytes ``` w=>(t=w=>(q=(s=w=>w.some((r,j)=>r.find(e=>e,i=j))?w.slice(i).reverse():[[]])(s(w)))[0].map((e,j)=>q.map((e,i)=>q[i][j])))(t(w)) ``` 140 -> 129 bytes, thanks @Arnauld ### Algorithm * Do twice: + Find first non-zero row + Slice off preceding rows + Reverse + Find first non-zero row + Slice off preceding rows + Reverse + Transpose ``` f = w=>(t=w=>(q=(s=w=>w.some((r,j)=>r.find(e=>e,i=j))?w.slice(i).reverse():[[]])(s(w)))[0].map((e,j)=>q.map((e,i)=>q[i][j])))(t(w)); w1 = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 0, 0, 0]]; w2 = [[0, 0, 0, 0], [0, 0, 0, 3], [0, 0, 0, 0], [0, 5, 0, 0], [0, 0, 0, 0]]; w3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; w4 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]; console.log(f(w1).join("\n")); console.log(f(w2).join("\n")); console.log(f(w3).join("\n")); console.log(f(w4)); ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~118~~ 116 bytes ``` f=lambda a,n=4,s=sum:n and f(zip(*a[max(i for i in range(len(a))if s(s(a[:i],()))<1):][::-1]),n-1)or(s(s(a,()))>0)*a ``` [Try it online!](https://tio.run/##fZDdasMwDIWv56fQpVxUiLvuz8yFPofxhUbj1ZA4xklh68unTZoR0o2BLqSjT0dw0nd3bOKm772puP44MDBFs6XWtKdaR@B4AI/nkHDFtuYvDOCbDAFChMzxs8SqjMhSBg8ttshWB0copXxXUjur9Vo5SXGtZJNxJMbtrpAr7vfGigdrC4K5HMEsqHth0GZB3eqeKJyjpe@CeFzy0/T0B/ljdH2yme62I/k8tC8ErwRv/z/7ZSicEEOEPES41wKy8Vhzwu6UqpKuUQpIOcQO8tT0Fw "Python 2 – Try It Online") --- Saved: * -2 bytes, thanks to shooqie [Answer] # [PHP](http://www.php.net/) (>=5.4), ~~200~~ ~~194~~ ~~186~~ 184 bytes (-6 bytes by returning `null` instead of empty array) (-8 bytes thanks to [Titus](https://codegolf.stackexchange.com/users/55735/titus)) (-2 bytes with calling by reference thanks to [Titus](https://codegolf.stackexchange.com/users/55735/titus)) ``` function R(&$a){$m=$n=1e9;foreach($a as$r=>$R)foreach($R as$c=>$C)if($C){$m>$r&&$m=$r;$M>$r||$M=$r;$n>$c&&$n=$c;$N>$c||$N=$c;}for(;$m<=$M;)$o[]=array_slice($a[$m++],$n,$N-$n+1);$a=$o;} ``` [Try it online!](https://tio.run/##hVJda4MwFH3WXxHKpVVqx9x3SeMe9tw@@GpliKQoaJRoGaP1t3c3sfWjKxvxI@fcc87NhZRJeVq9l0lpmlDzqq4II4Fp4GME9855hU4P3TFEooeuWuOqFqt3mDiUPI70F/B8LRvnuM7DxfiE2pd2@@q8Ocv/@v2ROhK4N6a5UrvDuNsA35CednsR12khiG9NIbIPkDMQzOVLuiskj@LEgohEFUjmgW93nK@4GLkPO91Z@EWjB3I6VX5JYY3geIS1BsKDGCuCQUxhgwArGwUazLMo5CsGa2pDEYQskjL6/qyyNObYOYB8Pg8dEA5sFiDmrk0hYlDQpj94KVNRf2ofOtTPPpgGnornZd1RijN4nBRkEpBwKybUNBqeVVzx/ahKi6MRkMWXtnQeZRgosa51cZG1ulao8N2MzLS46f3njopqzMY0u5z2YqsktVNRIHm1z2q87JpCl2@dORvBaFztQbJtwry2y0jSO1vRVizIr7UV2tmcfgA "PHP – Try It Online") # How? Finds min and max index for rows (`$m` & `$M`) and columns (`$n` & `$N`) and replaces the input with a sub array from `$m,$n` to `$M,$N` (this is a call by reference). [Answer] # Octave, ~~48~~ 49 bytes ``` @(a)sparse(1-min([x y v]=find(a))+x,1-min(y)+y,v) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNRs7ggsag4VcNQNzczTyO6QqFSoSzWNi0zLwUop6ldoQORqNTUrtQp0/yfmFesEc1loACFRLIMYzX/AwA "Octave – Try It Online") Find nonzero points and rearrange them in a new sparse matrix. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~73~~ 63 bytes ``` ->a{4.times{_,*a=a while a[0]&.sum==0;a=a.reverse.transpose};a} ``` [Try it online!](https://tio.run/##xZFNC8IwDIbv/RXBg4MRy@a3jHoT8Sx4GWVUqTjwY7SbItt@@3ROrIp6EEECIc@bUN4mKpkfiyUrGkORtmkcbqROA7QFE3BYhWsJwnd4nepkw5jjnWWq5F4qLWmsxFZHOy1zT@RFAAx8AuA7eA2OBt1HPAsG3TIeuw4nnJAAAKgUi1WahVmUxBpC2wIrJ2V9SVAbT2ajaa1Sln7AX85Xs7dUvvzOrItNbBns4wDbBnvYxc7zV/5n9iv8xmwEpd0P1tz7K1Y7vEHV@eWOihM "Ruby – Try It Online") Edit: simplified, also the previous version crashed for all `0`s ### How it works: * do 4 times: + remove the first line while there is a first line and it's full of `0`s + rotate the array clockwise by 90° * return the array [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~22~~ 19 bytes ``` 4{+|(+/&\~+/x)_'x}/ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLszKp1q7R0NZXi6nT1q/QjFevqNXn4iqxqlaJrqwrskpTqLBOyM+21khIS8zMsa6wrrQu0oyt5SqJ1jBQgEJrCG0IZwHZ1hARQygLDDW5FBQ0EOoMrcHymrFIhkEVG1sj+KZI4jAj4CqswbIQIwwVjIDCJkANZtbmChYKlmDFmKJY7EMx30BZR9EgFgCcqjj3) [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~78~~ 74 bytes ``` function x=f(x) for k=1:nnz(~x)*4,x=rot90(x);x=x(:,~~cumsum(any(x,1)));end ``` [Try it online!](https://tio.run/##fY3LCoMwEEX3fsVsCknJwrT2oSFfUroQTUBaJ6CxTbvw11MVqY9C4Q7MzJ17xmQ2fSjvdYOZLQyCk5o4GmhTwU3yBPFNWke3EXOyMjYOO1M46UjC2jZryropSYov4hinlAqFue8KNoDGAiqVqxx6VgrfD0UnW4N5IujirgJNLiGDSWLq@XLsN2Ky@GwcdaVL3Mzei/WPw8/NmO/AuyEQDUdHAScGZwbxH/wK44MP "Octave – Try It Online") ### Explanation This rotates the matrix by `90` degrees (`x=rot90(x)`) a sufficient number of times (`for k=1:... end`). The number of rotations is a multiple of `4`, so the final matrix has the original orientation. Specifically, the number of rotations is `4` times the number of zeros in the matrix (`nnz(~x)*4`). For each rotation, if there are one or more columns on the left consisting of only zeros they are removed (`x=x(:,~~cumsum(any(x,1)))`). What remains of the matrix after this process is output by the function (`function x=f(x)`). [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç·W≈y§╗♦º{¬║8• ``` [Run and debug it](https://staxlang.xyz/#p=80fa57f77915bb04a77baaba3807&i=[[0,+0,+0,+0,+0],+[0,+0,+0,+1,+0],+[0,+0,+0,+0,+1],+[0,+0,+1,+1,+1],+[0,+0,+0,+0,+0]]%0A[[0,+0,+0,+0],+[0,+0,+0,+3],+[0,+0,+0,+0],+[0,+5,+0,+0],+[0,+0,+0,+0]]%0A[[1,+2,+3],+[4,+5,+6],+[7,+8,+9]]%0A[[0,+0,+0,+0],+[0,+0,+0,+0],+[0,+0,+0,+0]]%0A[[0,+0,+0,+0],+[1,+1,+1,+1],+[0,+0,+0,+0]]%0A[[0,+1,+0,+0],+[0,+1,+0,+0],+[0,+1,+0,+0]]%0A[[1,+1,+1,+1],+[1,+2,+3,+1],+[1,+1,+1,+1]]&a=1&m=2) ### Alternative, also 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç·W≈x≈ƒHq♣☻»íÅ ``` [Run and debug it](https://staxlang.xyz/#p=80fa57f778f79f48710502afa18f&i=[[0,+0,+0,+0,+0],+[0,+0,+0,+1,+0],+[0,+0,+0,+0,+1],+[0,+0,+1,+1,+1],+[0,+0,+0,+0,+0]]%0A[[0,+0,+0,+0],+[0,+0,+0,+3],+[0,+0,+0,+0],+[0,+5,+0,+0],+[0,+0,+0,+0]]%0A[[1,+2,+3],+[4,+5,+6],+[7,+8,+9]]%0A[[0,+0,+0,+0],+[0,+0,+0,+0],+[0,+0,+0,+0]]%0A[[0,+0,+0,+0],+[1,+1,+1,+1],+[0,+0,+0,+0]]%0A[[0,+1,+0,+0],+[0,+1,+0,+0],+[0,+1,+0,+0]]%0A[[1,+1,+1,+1],+[1,+2,+3,+1],+[1,+1,+1,+1]]&a=1&m=2) [Answer] # PHP, 188 bytes ``` function f(&$a){for($s=array_shift;!max($a[0]);)$s($a);for($p=array_pop;!max(end($a));)$p($a);for($w=array_walk;!max(($m=array_map)(reset,$a));)$w($a,$s);while(!max($m(end,$a)))$w($a,$p);} ``` call by reference. **breakdown** ``` // call by reference function f(&$a) { // while first row is all zeroes, remove it while(!max($a[0]))array_shift($a); // while last row is all zeroes, remove it while(!max(end($a)))array_pop($a); // while first column is all zeroes, remove it while(!max(array_map(reset,$a)))array_walk($a,array_shift); // while last column is all zeroes, remove it while(!max(array_map(end,$a)))array_walk($a,array_pop); } ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 73 bytes ``` import StdEnv,StdLib $ =dropWhile(all((>)1))o reverse o transpose ``` # ``` $o$o$o$ ``` [Try it online!](https://tio.run/##bY4xC8IwEIX3/ooDO7RQoSKOddJB6NbBoXSI6VUDyV1I0oJ/3ihWKYK8B4/v3Q1PahQUDfejRjBCUVTGsgvQhP5IU/GKWl2SFKresT3flMZMaJ1l@3yT5wwOJ3QegSE4Qd6yx9gE4UKygmEkGRQTVJDyW0m1lG1bFvBxV8BC2x/63nZ/Psuuiw85aHH1cX2q4@FOwig5w7z8CQ "Clean – Try It Online") Very similar to [Laikoni's Haskell answer](https://codegolf.stackexchange.com/questions/169366/remove-surrounding-zeroes-of-a-2d-array#169389). [Answer] # [Python 2](https://docs.python.org/2/), 86 bytes ``` lambda a,l=1:a if l>4else([a.pop()for b in a if sum(a[-1])<1],f(zip(*a[::-1]),l+1))[1] ``` [Try it online!](https://tio.run/##hVLRUoMwEHznK@4x0ej0atWWEX8k5iEdychMChmSPujPIxeoNJRaJsMky@7t5jj3Hb6aet2Z4qOz@rD/1KCFLTDXUBmw75vS@pJJ/egax7hpWthDVUP86o8HpuUDKv6GShj2Uzl2p2WeEyTsPXIuUXWh9MFDATKD/mFSrgRMSwmYAJwDhE0ADmvOWClC5IU@Ek@aPtGlf1LpKa07np4XmJPhTEbbk@DMsA@wHombWPGFtq8CtgJ2Q60blJvhlwJeVeGVVv5FWW4aJk7Lp6FCNBleaRvObMcbp78pms5C/MvlmcoyGkuaMgFt6Y820ITGqcujtWurOoBhBPHuFw "Python 2 – Try It Online") Takes a list of lists, returns a list of tuples. ## Explanation Abuses the heck out of list comprehension. This is the equivalent expanded code: ``` def f(a,l=1): # after 4 rotations, the list is back in its original orientation, return if l > 4: return a else: # helper variable to store return values ret = [] # "trim" all rows from "bottom" of list that only contain 0s # since we are always checking le that item in the list, don't need range(len(a)) # since we are only removing at most one item per iteration, will never try to remove more than len(a) items # brackets surrounding generator force it to be consumed make a list, and therefore actually pop() list items ret.append([a.pop() for b in a if sum(a[-1]) < 1]) # rotate the array, increase the number of rotations, and recursively call this function on the new array/counter ret.append(f(zip(*a[::-1]), l + 1))) # we only put both items in a list in order to stay in the one-line lambda format # discard the popped items and return the value from the recursive call return ret[1] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-h`, ~~23~~ 11 bytes ``` 4Æ=sUb_dà z ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=NMY9c1ViX2TDIHo=&input=W1swLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDNdLCBbMCwgMCwgMCwgMF0sIFswLCA1LCAwLCAwXSwgWzAsIDAsIDAsIDBdXQotaFE=) --- ## Explanation ``` :Implicit input of 2D-array U 4Æ :Map the range [0,4) s : Slice U from Ub : The first index in U where _dà : Any element is truthy (not zero) z : Rotate 90 degrees = : Reassign to U for the next iteration :Implicitly output the last element ``` ]
[Question] [ A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first *two* occurrences are kept. Here is an example where the characters that should be deleted are labelled with `^`: ``` aaabcbccdbabdcd ^ ^ ^^^ ^^ aabcbcdd ``` Your task is to implement exactly this operation. ## Rules Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range. Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept). Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output. You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases Every pair of lines is one test case, input followed by output. ``` xxxxx xx abcabc abcabc abcdabcaba abcdabc abacbadcba abacbdc aaabcbccdbabdcd aabcbcdd ``` ### Leaderboard The Stack Snippet at the bottom of this post generates a leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 3 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 86503; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Qx2œ&@ ``` [Try it online!](http://jelly.tryitonline.net/#code=UXgyxZMmQA&input=&args=J2FhYWJjYmNjZGJhYmRjZCc) or [verify all test cases](http://jelly.tryitonline.net/#code=UXgyxZMmQArFvMOH4oKsOy9q4oG3&input=&args=JycsICd4eHh4eCcsICdhYmNhYmMnLCAnYWJjZGFiY2FiYScsICdhYmFjYmFkY2JhJywgJ2FhYWJjYmNjZGJhYmRjZCc). ### How it works ``` Qx2œ&@ Main link. Argument: s (string) Q Unique; deduplicate s. x2 Repeat each character. œ&@ Take the multiset intersection of s and the previous result. ``` [Answer] # JavaScript (ES6), 42 ~~48~~ **Edit** A whopping 6 bytes saved thx @Neil ``` s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c) ``` Explanation: I use the properties 'a'...'z' of object `k` to store info for each character (object k is a regexp in this case just to save bytes). These properties are initially `undefined`. In javascript adding a number to `undefined` gives `NaN` (quite sensible), but adding a string 'X' gives `"undefinedX"` - a string of length 10 (silly). Adding more characters you get longer strings. If the obtained string for a given character is longer than 11, that character is not copied to output. **Test** ``` F= s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c) test=` xxxxx xx abcabc abcabc abcdabcaba abcdabc abacbadcba abacbdc aaabcbccdbabdcd aabcbcdd`.split`\n` for(i=0;i<test.length;) a=test[i++],b=test[i++],r=F(a), console.log(r==b?'OK':'KO',a,'->',r,b) ``` [Answer] ## Python 2, 48 bytes ``` lambda s:reduce(lambda r,c:r+c*(r.count(c)<2),s) ``` `c[r.count(c)/2:]` is a same-length alternative to `c*(r.count(c)<2)` . --- **49 bytes:** ``` r='' for c in input():r+=c*(r.count(c)<2) print r ``` [Answer] # [Retina](https://github.com/m-ender/retina), 17 bytes ``` (.)(?<=\1.*\1.+) ``` [Try it online!](http://retina.tryitonline.net/#code=KC4pKD88PVwxLipcMS4rKQo&input=eHh4eHgKeHgKYWJjCmFiYwphYmNhYmMKYWJjYWJjCmFiY2RhYmNhYmEKYWJjZGFiYwphYmFjYmFkY2JhCmFiYWNiZGMKYWFhYmNiY2NkYmFiZGNkCmFhYmNiY2Rk) Simple regex replace - match a character if it already appeared twice, and remove it. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes ``` .v|s.g:.z:1a :2fl<3 he~t? ``` [Try it online!](http://brachylog.tryitonline.net/#code=LnZ8cy5nOi56OjFhCjoyZmw8MwpoZX50Pw&input=ImFhYWJjYmNjZGJhYmRjZCI&args=Wg) or [verify all test cases](http://brachylog.tryitonline.net/#code=Ons6MiZ3QE53fWEKLnZ8cy5nOi56OjNhCjo0Zmw8MwpoZX50Pw&input=WyIiOiJ4eHh4eCI6ImFiY2FiYyI6ImFiY2RhYmNhYmEiOiJhYmFjYmFkY2JhIjoiYWFhYmNiY2NkYmFiZGNkIl0). ### Explanation This works because `s - Subset` will unify with bigger subsets first, thus e.g. for `"aaa"` it will try `"aa"` before `"a"`. * Main predicate: ``` .v input = Output = "" | Or s. Output is an ordered subset of the input g:.z Zip each character of the output with the output itself :1a Apply predicate 1 on each element of the zip ``` * Predicate 1: Check that all characters only appear at most twice. Input = `[String:Char]` ``` :2f Find all valid outputs of predicate 2 (i.e. one output per occurence of the char) l<3 There are less than 3 occurences ``` * Predicate 2: Get an occurence of a character. Input = `[String:Char]` ``` he Take a character of the string in the input ~t? That character is the char of the input ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), 22 bytes ``` i:0(?;::9g:}2(?o{1+$9p ``` [Try it online!](http://fish.tryitonline.net/#code=aTowKD87Ojo5Zzp9Mig_b3sxKyQ5cA&input=YWFhYmNiY2NkYmFiZGNk) Uses the codebox to keep track of counts so far. ``` i Read a char c of input :0(?; Halt if EOF : Make a copy - stack has [c c] at the top :9g Get count stored at (c, 9) :} Copy the count and move to bottom of stack 2(?o If the count is less than 2, output c {1+ Move the count back to the top of the stack and increment $9p Update cell at (c, 9) [Instruction pointer moves to start as ><> is toroidal] ``` [Answer] ## J, ~~20~~ 15 bytes ``` #~(3>[+/@:={:)\ ``` This defines a monadic function that takes and returns a string. [Try it here](http://tryj.tk/). Usage: ``` f =: #~(3>[+/@:={:)\ f 'abaacbb' abacb ``` ## Explanation I switched to the same algorithm that some other solutions use, since it turned out to be shorter... ``` #~(3>[+/@:={:)\ Input is y. ( )\ For each prefix of y: = compute the equality vector [ {: of the prefix and its last element, and +/@: take its sum. Now we have a vector r such that y[i] has its r[i]'th occurrence at position i. 3> Mark those coordinates where r[i] < 3. #~ Remove the non-marked characters from y. ``` [Answer] ## Haskell, ~~40~~ 39 bytes ``` foldl(\s c->s++[c|filter(==c)s<=[c]])"" ``` Usage example: `foldl(\s c->s++[c|filter(==c)s<=[c]])"" "aaabcbccdbabdcd"` -> `"aabcbcdd"`. Keep the next char `c` if the string of all `c`s so far are lexicographical less or equal the singleton string `[c]`. Edit: @xnor saved a byte by switching from list comprehension to `filter`. Thanks! [Answer] ## Perl, 22 bytes **21 bytes code + 1 for `-p`.** ``` s/./$&x(2>${$&}++)/ge ``` ### Usage ``` perl -pe 's/./$&x(2>${$&}++)/ge' <<< 'aaabcbccdbabdcd' aabcbcdd ``` [Answer] # C, 57 bytes Call `f()` with the string to detriplicate. The function modifies its parameter. Requires C99 because of the `for`-loop declaration. ``` f(char*p){for(char*s=p,m[256]={0};*s=*p;s+=++m[*p++]<3);} ``` [Answer] # JavaScript (ES6), 35 bytes ``` s=>s.filter(c=>(s[c]=(s[c]|0)+1)<3) ``` Takes an array of characters as input and returns the detriplicated array. [Answer] ## PowerShell v2+, 31 bytes ``` $args-replace'(.)(?<=\1.*\1.+)' ``` Uses the same regex as in [Kobi's Retina answer](https://codegolf.stackexchange.com/a/86517/42963), just encapsulated in the PowerShell `-replace` operator. Works because both are using .NET-flavor regex in the background. ### Alternatively, without regex, 56 bytes ``` $b=,0*200;-join([char[]]$args[0]|%{"$_"*($b[$_]++-lt2)}) ``` Creates a helper array `$b` pre-populated with `0`s. Casts the input string `$args[0]` as a `char`-array, pipes it through a loop `|%{...}`. Each iteration outputs the current character `$_` as a string `"$_"` multiplied by a Boolean that is only `$TRUE` (implicitly cast to `1` here) if the appropriate point in the helper array is less than `2` (i.e., we haven't seen this char twice already). The resultant collection of strings is encapsulated in parens and `-join`ed together to form a single output string. That's left on the pipeline and output is implicit. [Answer] # Mathematica, 39 bytes ``` Fold[If[Count@##<2,Append@##,#]&,{},#]& ``` Anonymous function. Takes a character list as input, and returns the detriplicated list as output. Uses the method of folding over the list and rejecting triplicate elements, it's not too complicated. [Answer] ## 05AB1E, 12 bytes ``` vyˆ¯y¢O3‹iy? ``` **Explanation** ``` v # for each char in input yˆ # push to global array ¯y¢O3‹i # if nr of occurrences are less than 3 y? # print it ``` [Try it online](http://05ab1e.tryitonline.net/#code=dnnLhsKvecKiTzPigLlpeT8&input=YWFhYmNiY2NkYmFiZGNk) [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` t&=Rs3<) ``` [**Try it online!**](http://matl.tryitonline.net/#code=dCY9UnMzPCk&input=J2FhYWJjYmNjZGJhYmRjZCc) ### Explanation ``` t % Input string implicitly. Push another copy &= % Matrix of all pairwise equality comparisons of string elements R % Keep only upper triangular part, making the rest of the entries zero s % Sum of each column. This gives a vector with number of occurrences % of the current character up to the current position 3< % True for entries that are less than 3 ) % Use as logical index into initial copy of the input. Display implicitly ``` ### Example Assuming input `'aaababbc'`, the stack contains the following after the indicated statements: * `t` ``` 'aaababbc' 'aaababbc' ``` * `t&=` ``` 'aaababbc' [ 1 1 1 0 1 0 0 0; 1 1 1 0 1 0 0 0; 1 1 1 0 1 0 0 0; 0 0 0 1 0 1 1 0; 1 1 1 0 1 0 0 0; 0 0 0 1 0 1 1 0; 0 0 0 1 0 1 1 0; 0 0 0 0 0 0 0 1 ] ``` * `t&=R` ``` 'aaababbc' [ 1 1 1 0 1 0 0 0; 0 1 1 0 1 0 0 0; 0 0 1 0 1 0 0 0; 0 0 0 1 0 1 1 0; 0 0 0 0 1 0 0 0; 0 0 0 0 0 1 1 0; 0 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 1 ] ``` * `t&=Rs` ``` 'aaababbc' [ 1 2 3 1 4 2 3 1 ] ``` * `t&=Rs3<` ``` 'aaababbc' [ true true false true false true false true ] ``` * `t&=Rs3<)` ``` 'aabbc' ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 14 bytes ``` D`(.)(?<=\1.*) ``` [Verify all test cases.](http://retina.tryitonline.net/#code=RCVgKC4pKD88PVwxLisp&input=Cnh4eHh4Cnh4CmFiYwphYmMKYWJjYWJjCmFiY2FiYwphYmNkYWJjYWJhCmFiY2RhYmMKYWJhY2JhZGNiYQphYmFjYmRjCmFhYWJjYmNjZGJhYmRjZAphYWJjYmNkZA) (The `%` enables per-line mode) Uses the new "Deduplicate" stage to save a couple bytes over [Kobi's approach](https://codegolf.stackexchange.com/a/86517/31625). Deduplicate gathers a list of all matches to the regex and replaces all but the first with the empty string. The regex matches a character that already appears once in the string, meaning that the first two will be kept. [Answer] ## K, 18 Bytes ``` g:{x{?x@<x}@,/2#'=x} g "abc" "abc" g "aaabcbccdbabdcd" "aabcbcdd" /k4 request test vectors from internet R:"GET /raw/ftHe0bpE HTTP/1.0\r\nHost: pastebin.com\r\n\r\n" t:+0N 2#t@1_&|\(0=#:)'t:1_"\r\n"\:`:http://pastebin.com:80 R /k4 no internet? use a file called "t.txt" in current directory t:+0N 2#0:`:t.txt /k6? t:+0N 2#0:"t.txt" /visually inspect test cases g't[0] (();"xx";"abcabc";"abcdabc";"abacbdc";"aabcbcdd") /do all tests pass? |/ t[1] {$[0=#x;0=#y;x~y]}' g't[0] 1b ``` K4 is available for [free download](http://kx.com/); K6 is [in development](http://kparc.com/). If you've downloaded KDB, you can get into K with [backslash](http://code.kx.com/wiki/Reference/BackSlash#toggle_q.2Fk). It may be easiest to see this broken apart, but first some syntax: `g:x` sets `g` to `x`. `{x+1}` is a function which takes an argument *x*. In K the first argument to a function is `x` (the second is `y` and the third is `z`. Don't need a fourth). Now: ``` x:"aaabcbccdbabdcd" ``` `=x` means *group x*, which produces: ``` "abcd"!(0 1 2 10;3 5 9 11;4 6 7 13;8 12 14) ``` `2#'` means *two taken(from) each* which produces ``` "abcd"!(0 1;3 5;4 6;8 12) ``` As you can see, these are the offsets of the first two matches of each character. The *2* could be generalised. `,/` means *join each* and is often called [raze](http://code.kx.com/wiki/Reference/raze). It's going to get us just the values of our dictionary. Thus, `,/"abcd"!(0 1;3 5;4 6;8 12)` produces: ``` 0 1 3 5 4 6 8 12 ``` which we need to sort. `{x@<x}@` is an idiom K programmers often see (Q calls it [asc](http://code.kx.com/wiki/Reference/asc)), which says *x at grade-up x*. Breaking it apart: ``` <0 1 3 5 4 6 8 12 0 1 2 4 3 5 6 7 ``` returned the indices of the sorted array, which we want taken from the original array. `x@y` means *x at y* so this indexes the array with the indices of the sort (if that makes any sense). ``` {x@<x}@0 1 3 5 4 6 8 12 0 1 3 4 5 6 8 12 ``` which we simply now index into our original array. We *could* say `x@` here, but K supports a really powerful concept which we can take advantage of here: function application is indexing. That means that `a[0]` could be looking up the zeroth slot of `a` or it could be applying the `0` to the function called `a`. The reason we needed the `@` previously in `{x@<x}` is because `x<y` means *xs less than ys*: Operators in K have a dyadic form (two-argument) and a monadic form (one-argument) that comes from APL. [Q](http://code.kx.com/wiki/Reference/Grammar) doesn't have this "ambivalence". [Answer] ## Pyke, 16 bytes ``` F~kR/2<Ii?+k(K~k ``` [Try it here!](http://pyke.catbus.co.uk/?code=F%7EkR%2F2%3CIi%3F%2Bk%28K%7Ek&input=abcabcabc) [Answer] # Python 2, 51 bytes ``` f=lambda s:s and f(s[:-1])+s[-1]*(s.count(s[-1])<3) ``` Test it on [Ideone](http://ideone.com/Igi8bC). [Answer] ## Java 8 lambda, 90 characters ``` i->{int[]o=new int[128];String r="";for(char c:i.toCharArray())if(++o[c]<3)r+=c;return r;} ``` Ungolfed version: ``` public class Q86503 { static String detriplicate(String input) { int[] occurences = new int[128]; String result = ""; for (char c : input.toCharArray()) { if (++occurences[c] < 3) { result += c; } } return result; } } ``` Creates an array for all ascii characters. If a character occurs the corresponding counter will be increased. If it is over 2 the character won't be appended to the result string. Very easy, very short ;) [Answer] # Perl 6, 27 bytes ``` {.comb.grep({++%.{$_} <3})} ``` Explanation: ``` {.comb.grep({++%.{$_} <3})} { } # a function .comb # get all the characters in the argument .grep({ }) # filter %. # an anonymous hash (shared between calls to grep) ++ {$_} # increment the value at the current key (current letter). # if the key doesn't exist, it defaults to 0 (then gets incremented) <3 # return True if it wasn't seen 3 times ``` (Note: Perl 6 isn't as "golf-oriented" as its sister Perl 5 ... So yes, that space before the `<` is necessary. The `%.{}` is an anonymous hash). [Answer] # SmileBASIC, ~~77~~ ~~72~~ ~~69~~ 68 bytes ``` DIM R[#Y]READ S$WHILE""<S$Q=ASC(S$)INC R[Q]?SHIFT(S$)*(R[Q]<3); WEND ``` Explained: ``` DIM R[128] 'array to store letter frequencies READ S$ 'get input string WHILE""<S$ 'much shorter than LEN(S$) Q=ASC(S$) 'get ascii value of first character in S$ INC R[Q] ?SHIFT(S$)*(R[Q]<3); 'remove the first character of S$, and print it if there are less than 3 occurrences. WEND ``` [Answer] ## Common Lisp, 127 ``` (lambda(s)(map()(lambda(x)(flet((p(b)(1+(position x s :start b))))(setf s(remove x s :start(p(p 0))))))(remove-duplicates s))s) ``` ### Pretty-printed ``` (lambda (s) (map nil (lambda (x) (flet ((p (b) (1+ (position x s :start b)))) (setf s (remove x s :start (p (p 0)))))) (remove-duplicates s)) s) ``` [Answer] ## [Q](http://code.kx.com/wiki/Reference), 52 Bytes ``` q)f2:{x asc raze{distinct 2#where x}each x~'/:distinct x} q)f2 each testList "xx" "abcabc" "abcdabc" "abacbdc" "aabcbcdd" q) ``` [Answer] ## [K](http://code.kx.com/wiki/Reference), 27 Bytes ``` f:{x{x@<x}@,/{?2#&x}'x~'/:?x} testList:("xxxxx";"abcabc";"abcdabcaba";"abacbadcba";"aaabcbccdbabdcd") f'testList ("xx";"abcabc";"abcdabc";"abacbdc";"aabcbcdd") ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~79~~ ~~62~~ 57 bytes This is pretty unwieldy, but I'm not sure I can golf this much better at the moment. Any golfing suggestions are welcome. [Try it online!](https://tio.run/nexus/ruby#@69rV1xdrJeckVhUrJebWFBdk1hTHF2sV5SZl5JaoZAYa6ukVJ6RmZOqAFSUX5pXopGoaWdUa11c@z/dlmy9XAWlJcUK6dFKiUmJyYkpiUlFiUqx/wE "Ruby – TIO Nexus") **Edit:** -17 bytes thanks to Value Ink by suggesting a golfier way to remove triplicate characters. -5 bytes from removing the `.uniq` method. ``` ->s{s.chars.map{|a|s[s.rindex a]=""while s.count(a)>2};s} ``` **Ungolfed:** ``` def g(s) s.chars.each do |a| while s.count(a) > 2 i = s.rindex(a) s[i] = "" end end return s end ``` [Answer] # JavaScript, 30 bytes ``` v=>v.filter(x=>!(v[x]+=x)[11]) ``` Using the method that @edc65 came up with for counting but with an array filter. First time character appears, the object value gets "undefined" plus the character (i.e. "undefinedx"). The next time the object value becomes "undefinedxx". After that, v[x][11] returns true and when combined with the not operator, false, meaning characters that have already appeared twice will be filtered. [Answer] # [Kotlin](https://kotlinlang.org), 50 bytes ``` {it.filterIndexed{i,c->it.take(i).count{it==c}<2}} ``` [Try it online!](https://tio.run/##NY3NCsIwEITvfYqlpwS0B4@lqXgUvPkE2/yUpXEraSpKybPHYHFOw8fwzTRHT5zdyvBAYoFhXFq4hICf7h4D8dhL2CooeaEH14LYsYRjD3sFlTeKjSMfbbiysW9rNjroY19oxMkKko2eV45lppRO3Sml/FcuoCBYNDdiKyScW6jr39@zuKNn4cQiZZUyIg560NoMOBhtvg "Kotlin – Try It Online") [Answer] # [PHP](https://php.net/), 42 bytes Loop through the string, count each character in an array, only echo if the letter hasn't reached a count of 3 yet. ``` while($e=$argn[$x++])if($s[$e]++<2)echo$e; ``` [Try it online!](https://tio.run/##K8go@G9jXwAkyzMyc1I1VFJtVRKL0vOiVSq0tWM1M9M0VIqjVVJjtbVtjDRTkzPyVVKt//9PTExMSk5KTk5JSkxKSU75l19QkpmfV/xf1w0A "PHP – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 85 bytes ``` int f(char*i){int v[255]={};int x,y;x=y=0;do++v[i[x]]<3?i[y++]=i[x]:0;while(i[x++]);} ``` [Try it online!](https://tio.run/##bYzRCoIwGEav9SlkEcy0sIk3zdWDrF3Y1BzYDDVTxGe3zSgLHP/Fzgfn8O2V83ElJM8fcRJWdSyKXXYchaytFPIsKjfC7jU1FAUBI/2ANbVuh1vSEQ/HheM0VNCWsdA/Cdo5DiMaDx5@ZiJPoAK12XiYqrdISGibvWnoulUnVb2nzCIWaPUD2DRSOK22@t5L5aQQrKuzBO5n/nHR240uXN0so2UZ/cv@V46nQDQH/OWAnofxBQ "C (gcc) – Try It Online") de-golfed version: ``` int f(char* i) { int v[255]={}; int x,y; x=y=0; do { ++v[i[x]]<3?i[y++]=i[x]:0; }while(i[x++]); } ``` Takes input as an array of characters and outputs by updating it in-place. ]
[Question] [ **This question already has answers here**: [The Versatile Integer Printer](/questions/65641/the-versatile-integer-printer) (41 answers) Closed 6 years ago. > > **Note:** This challenge has been moved to [Polyglot the (non constant) OEIS!](https://codegolf.stackexchange.com/q/139036/61563) to avoid closure. > > > ## Introduction We all know and love the *on-line encyclopedia of integer sequences* ([OEIS](https://oeis.org/)). So what if we made an *off-line* version? Well, that would be kinda too easy, wouldn't it and how would you select a sequence with our standard interface!? No. We need an easier solution to this. A polyglot! ## Input Your input will be a non-negative integer `n`. ## Output Your output will either be * The `n`-th entry of an OEIS sequence OR * The first `n` entries of an OEIS sequence. You may take the index to be 1-based or 0-based as you prefer. ## Uhm, so where is the Challenge? You have to polyglot the above functionality. That is if you support languages A, B and C all must implement different OEIS sequences. The choice of sequence is not limited except that you need different ones for all languages. That is, if you run the provided program in language A, then sequence X shall be generated, if you run the provided program in language B, then sequence Y shall be generated (with X!=Y) and if you run the provided program in language C, then sequence Z shall be generated (with X!=Z && Y!=Z). ## Who wins? The answer with the most sequence/language pairs wins. First tie-breaker is code-size (in bytes) with lower being better. Second tie-breaker is submission time with earlier being better. ## Any final Words / Rules? * You must declare which language will generate which sequence. * [Standard I/O rules apply.](https://codegolf.meta.stackexchange.com/q/2447/55329) * If different encodings are used between languages, both programs must use the same byte-sequence. * Language (Python 2/3) revisions *do* count as different languages. Different implementations of a language (such as Browser JS vs Node.js) also count as different languages. * [Standard loopholes apply.](https://codegolf.meta.stackexchange.com/q/1061/55329) [Answer] # 26 languages: C, C++, Cubically, rk, what, Bash, Morse, Ook!, str, Charcoal, Commercial, S.I.L.O.S, memescript, Forked, TRANSCRIPT, Braingolf, Fission, Arcyou, Beam, Beatnik, Cood, COW, Emoji, ><>, Set, NTFJ Over 1000 bytes >.< but I'm gonna go for the most languages. Hit `Page Down` about 10 times if you don't want a description of all the languages. ``` #\ //ha kkkkkkkkkk ja ha kkkkkkkkkkd ja skd I7Oq2_ #include<stdio.h>//$+77%6& ..... rk:start print: "11" rk:end ?!!!!!!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!????! Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. ⎚8» ########################################## /* echo -n 3;exit Hey, waiter! I want 25 of this. How much is it? The bill, please. foo now 9 dollars off! foo has been selling out worldwide! a = 10 printInt a filler what the frick frack thumbtack diddily dack crack pack quarterback frick frack (p 22) >F9+%&'L+:+:H Ju is here. >Ju, 32 >X Ju set ! 50 set ! 56 oom MoO OOM 💬26💬➡ #####/ */main(int a){getchar();printf("%d",sizeof(' '));}/* R"21" >2n7n; */ ``` This outputs: * [A010709](https://oeis.org/A010709) in [C](https://tio.run/##7ZNBbhMxFIb3PsU/U9JMmjTTTNSEJjDZoSSiioRYsKiEnLEnNpnYqe3RUBBXYMGSBYg9N2DHUXoCbhA8I2jFDRDiyfr8@9nPfk/Wy043WXY4HF2ROBYU2zvDK4o/HKz2WD8txqvr5CU5kiorSsYfWcek7os0jh90x@PW6Bj92mC2E@uocdgbqdwE4WAQ1k6u2CxobDb7C4cHVnrbr3GvZnfqP/5Z/Pru2/cfH37/RhCfEJ4JjVOF4ZS/lo7M@U0PFZWOm4AsvFIOyTl0Diek7ZO5rrArMwFpId2MPBcca1kUPewLTi3vk1xrKH/qAkwXBTXWB@dB4xbUYs25guVFIdUGunSotClYJRkPCMVjDM5I000L/zAlub@aG1SCOp8AR25ktvWknk6Uu7WrFZOMyeIGrF5kzea@xnXpm5ObNW1i7iOjPZKkQ9InF93Wcftpd9KdzMmyrGsS3Pga0mXZwzAh6QssS2K5Q4Dzs99iRLTe4VKvsFpdAj8@f/iajGrefvpCTuIdlSqSdfqdtxvuMkFN1Jk2ReVR2GJhz8o3XOdRG@1OZ/oujp@FySC8IkgTNVbTw2H4Ew) `a(n) = 4` * [A000012](https://oeis.org/A000012) in [C++](https://tio.run/##7ZNBbhMxFIb3PsWfKWkmTZppJmpCE8jsUBJRjYRYsKiEnLEnNpnYU9ujUBBXYMGSBYg9N2DHUXoCbhA8I2jFDRDiyfr8@9nPfk/Wy8rydJNlh8PRFYkiQbG9M7yi@MPBao/103KSXscvyZFUWVEx/sg6JvVAzKPoQW8yaY@PMagNZju1jhqH0kjlpgiGw6B2csWSVmNJ8hcOD6R6O6hxr5I79R//LH599@37jw@/fyOITgjPhMapwmjGX0tHFvymjz2VjpsWWXqlHOJz6BxOSDsgC73HrsoEpIV0CXkuONayKPooC04tH5Bcayh/6gJMFwU11gfnrcYtqMWacwXLi0KqDXTlsNemYHvJeItQPMbwjDTdtPQPU5L7q7nBXlDnE@DIjcy2ntTTiWq3drVikjFZ3IDVi6zZLGtcV745uVnTJuY@MiwRx10yf3LRax93nvamvemCrKq6JsGNr2G@qvoYxWT@AquKWO7QwvnZbzEmWu9wqVOk6SXw4/OHr/G45u2nL@Qk2lGpQlmn33274S4T1ITdWVNUHgZtFvStfMN1HnbQ6XZn76LoWRAPgyuCeawmanY4jH4C) `a(n) = 1` * [A005843](http://oeis.org/A005843) in [Cubically](https://tio.run/##7ZNBbhMxFIb3PsWfKWkyTcg0EzWhCSQ7lERUIyEWLCohZ@ypTRw7tT1KA@IKLFiyALHnBuw4Sk/ADYJnBK24AUI8WZ9/P/vZ78l6ebmSOVVqfzgcXZIkERTrO8Nrij8crPK4MC1G2XX6ihxJnauS8cfOM2l6YpokDzqjUXN4jF5lsOux89R6bK3Ufoyo348qJ9ds1qhtNvsLRwAys@5VuFezO/Uf/yx@ffft@4@Pvn8jSE4Iz4XBQ43BhN9IT@Z838WOSs9tgyyC0h7pGUwBL6TrkbnZYVPmAtJB@hl5IThWUqkutopTx3ukMAY6nDoHM0pR60Jw0ajdgjqsONdwXCmpr2BKj52xiu0k4w1C8QT9U1J30yI8TEkRruYWO0F9SICjsDJfB9JAL8rNyleKScak2oNVi7ze3Fa4LkNzcruidcx9ZHuLNI3J9Ol5p3ncetYZd8ZzsiyrmgS3oYbpsuxikJLpSyxL4rhHA2env8WQGLPBhcmQZRfAj88fvqbDirefvpCTZEOlbssq/fjtFfe5oLYdT@qiinbUZFHXyTfcFO0WWnE8eZckz6O0H10STFM90pPDYfAT) `a(n) = 2n` * [A010850](http://oeis.org/A010850) in [rk](https://tio.run/##7ZNBbhMxFIb3PsU/U9IkTcg0EzWhCSQ7lERUIyEWLCohZ@ypzUzs1PZoWhBX6KJLFiD23IAdR@kJuEHwjKAVN0CIJ@vz72c/@z1Zz@T7/cE5iSJBkd8b3lL84WC1x/ppNUku4zfkQKq0KBl/ah2TeiDmUfSoN5m0xocY1AaTT62jxmFnpHJThMNhWDu5YougscXiLxweSHQ@qPGgFvfqP/5Z/Pruu5uPT75/I4iOCE@FxmOF0YxfSUeW/LqPikrHTUBWXimH@AQ6gxPSDshSV9iWqYC0kG5BXgmOjSyKPnYFp5YPSKY1lD91CqaLghrrg7OgcQtqseFcwfKikOoCunSotClYJRkPCMUzDI9J000r/zAlmb@aG1SCOp8AR2ZkmntSTyfK7cbViknGZHENVi/SZnNX47L0zcnNhjYxD5GdHeK4S@bPT3utw/aL3rQ3XZJ1WdckuPE1zNdlH6OYzF9jXRLLHQKcHP8WY6L1Fmc6QZKcAT8@336NxzXvPn0hR9GWStWRdfrd9xfcpYKaTnfWFJV1whYL@1a@4zrrtNHudmcfouhlGA/Dc4J5rCZqtt@PfgI) `a(n) = 11` * [A007395](http://oeis.org/A007395) in [what](https://github.com/gimmetehcodez/what) `a(n) = 2` * [A010701](http://oeis.org/A010701) in [Bash](https://tio.run/##7ZNBbhMxFIb3PsU/U9IkTcg0EzWhCSQ7lERUIyEWLCohz9hTm0zs1PZoWhBX6KJLFiD23IAdR@kJuEHwjKAVN0CIJ@vz72c/@z1ZL6VW7PcH5ySKBMXm3vCW4g8Hqz3WT6tJchm/IQdSZUXJ@FPrmNQDMY@iR73JpDU@xKA2mM3UOmocdkYqN0U4HIa1kyu2CBpbLP7C4YFEbwY1HtTiXv3HP4tf33138/HJ928E0RHhmdB4rDCa8SvpyJJf91FR6bgJyMor5RCfQOdwQtoBWeoK2zITkBbSLcgrwZHKouhjV3Bq@YDkWkP5U6dguiiosT44Dxq3oBYp5wqWF4VUF9ClQ6VNwSrJeEAonmF4TJpuWvmHKcn91dygEtT5BDhyI7ONJ/V0otymrlZMMiaLa7B6kTWbuxqXpW9OblLaxDxEdnaI4y6ZPz/ttQ7bL3rT3nRJ1mVdk@DG1zBfl32MYjJ/jXVJLHcIcHL8W4yJ1luc6QRJcgb8@Hz7NR7XvPv0hRxFWypVR9bpd99fcJcJajrdWVNU3glbLOxb@Y7rvNNGu9udfYiil2E8DM8J5rGaqNl@P/oJ) `a(n) = 3` * [A010716](http://oeis.org/A010716) in [Morse](https://github.com/aaronryank/minproj/blob/master/morse/morse.c) `a(n) = 5` * [A000004](http://oeis.org/A000004) in [Ook!](https://github.com/gimmetehcodez/ook) `a(n) = 0` * [A010727](http://oeis.org/A010727) in [str](https://tio.run/##7ZNBbhMxFIb3PsU/U9IkTcg0UzWhCWR2KImoRkIsWFRCzthTm0zs1PYoLYgrsGDJAsSeG7DjKD0BNwj2CFpxA4R4sj7/fvaz35P1rDP7/cEFSRJBsb4zvKb4w8GCx/ppMc6v0lfkQKqiqhl/bB2TeiBmSfKgNx63RocYBINZT6yjxmFrpHITxMNhHJxcsSxqLMv@wuGBXK8HAfcqu1P/8c/i13ffvv/46Ps3guSI8EJoPFQ4mfJr6cic3/Sxo9JxE5GFV8ohPYUu4YS0AzLXO2zqQkBaSJeRF4JjJauqj23FqeUDUmoN5U@dgemqosb64DJq3IJarDhXsLyqpLqErh122lRsJxmPCMUTDI9J000L/zAlpb@aG@wEdT4BjtLIYu1JPZ2oNysXFJOMyeoGLCyKZnMbcFX75uRmRZuY@8jOFmnaJbOnZ73WYftZb9KbzMmyDjUJbnwNs2Xdx0lKZi@xrInlDhFOj3@LEdF6g3OdI8/PgR@fP3xNR4G3n76Qo2RDperIkH737SV3haCm0502RZWduMXivpVvuC47bbS73em7JHkep8P4gmCWqrGa7vc/AQ) `a(n) = 7` * [A010731](http://oeis.org/A010731) in [Charcoal](https://tio.run/##7ZRBbhMxFIb3PsWfKWlmmpBppmpCE8jsUBJRRUIsWFRCzthTmzh2anuUFsQVWLBkAWLPDdhxlJ6AGwTPCFpxA4R4sj7/fvaz35NlF4LawlC13x9ckDQVFOs7w2uKPxys9rjQzUfLq@wVOZC6UBXjj51n0vTFNE0fdEej9vAQ/dpg12PnqfXYWqn9GNFgENVOrlneaizP/8IWgKVZ92vcq/xO/cc/i1/Xffv@46Pv3wjSI8ILYfBQ42TCr6UnM37Tw45Kz22LzIPSHtkpTAkvpOuTmdlhUxUC0kH6nLwQHCupVA9bxanjfVIaAx1WnYEZpah1IbhsNW5BHVacaziulNSXMJXHzljFdpLxFqF4gsExaV7TPBxMSRm25hY7QX1IgKO0slgH0kAvqs3K14pJxqS6AasHRTO5rXFVhcfJ7Yo2MfeR8RZZlpDp07Nu@7DzrDvujmdkUdU1CW5DDdNF1cNJRqYvsaiI4x4tnB7/FkNizAbnZonl8hz48fnD12xY8/bTF3KUbqjUsazTT95ecl@ELyhOJk1RZRy1WdRz8g03ZdxBJ0km79L0eZQNoguCaaZHerLf/wQ) `a(n) = 8` * [A010734](http://oeis.org/A010734) in [Commercial](https://tio.run/##7ZNBbhMxFIb3PsWfKWkyTcg0UzWhCSQ7lERUIyEWLCohZ@ypTTx2anuUFsQVWLBkAWLPDdhxlJ6AGwTPCFpxA4R4sj7/fvaz35P1clOW3OaSqv3@4IIkiaDY3BleU/zhYLXHhWk5zq7SV@RA6lxVjD92nkkzELMkedAbj9ujQwxqg91MnKfWY2ul9hNEw2FUO7lm81Zj8/lfOAKQmc2gxr2a36n/@Gfx67tv33989P0bQXJEeC4MHmqcTPm19GTBb/rYUem5bZFlUNojPYUp4IV0A7IwO5RVLiAdpJ@TF4JjLZXqY6s4dXxACmOgw6kzMKMUtS4EF63GLajDmnMNx5WS@hKm8tgZq9hOMt4iFE8wPCZNNy3Dw5QU4WpusRPUhwQ4CivzTSAN9KIq175WTDIm1Q1YvcibzW2Nqyo0J7dr2sTcR3a3SNOYzJ6e9dqHnWe9SW@yIKuqrklwG2qYrao@TlIye4lVRRz3aOH0@LcYEWNKnJsMWXYO/Pj84Ws6qnn76Qs5SkoqdVfW6cdvL7nPBbXdeNoUVXSjNov6Tr7hpuh20Inj6bskeR6lw@iCYJbqsZ7u9z8B) `a(n) = 9` * [A010692](http://oeis.org/A010692) in [S.I.L.O.S](https://tio.run/##7ZNBbhMxFIb3PsWfKWmSJsw0UzWhCWR2KImoIiEWLCohZ@ypTRw7tT2aFsQVWLBkAWLPDdhxlJ6AGwTPCFpxA4R4sj7/fvaz35P1nFTG7fcHFyRJBMXmzvCa4g8Hqz0uTIvx6ip9RQ6kzlXJ@GPnmTSxmCXJg/543B4dIq4NdjNxnlqPnZXaTxANh1Ht5Jplrcay7C8cAViZTVzjXmV36j/@Wfz67tv3Hx99/0aQHBGeC4OHGidTfi09mfObASoqPbctsghKe6SnMAW8kC4mc1NhW@YC0kH6jLwQHGup1AA7xanjMSmMgQ6nzsCMUtS6EFy0GregDmvONRxXSupLmNKjMlaxSjLeIhRPMDwmTTctwsOUFOFqblEJ6kMCHIWV@SaQBnpRbte@VkwyJtUNWL3Im81djasyNCe3a9rE3Ed2d0jTHpk9Peu3DzvP@pP@ZE6WZV2T4DbUMFuWA5ykZPYSy5I47tHC6fFvMSLGbHFuVlitzoEfnz98TUc1bz99IUfJlkrdlXX6vbeX3OeC2m5v2hRVdKM2iwZOvuGm6HbQ6fWm75LkeZQOowuCWarHerrf/wQ) `a(n) = 10` * [A010855](http://oeis.org/A010855) in [memescript 1.0](https://github.com/aaronryank/memescript-1.0/) `a(n) = 16` * [A010863](http://oeis.org/A010863) in [Forked](//git.io/Forked) `a(n) = 24` * [A010871](http://oeis.org/A010871) in [TRANSCRIPT](https://tio.run/##7ZNBbhMxFIb3PsU/U9IkTcg0UzWhCczsUBJRjYRYsKiEnLGnNpnYU9ujtCCuwIIlCxB7bsCOo/QE3CB4RtCKGyDEk/X597Of/Z6s5wxVNjeycvv9wQWJIkGxuTO8pvjDwRqP9dNyml3Fr8iBVHlZM/7YOib1SCRR9GAwnXYmhxg1BrOZWUeNQ2WkcjOE43HYOLliadBamv6FwwOZ3owa3Kv0Tv3HP4tf3337/uOj798IoiPCc6HxUOFkzq@lIwt@M8SOSsdNQJZeKYf4FLqAE9KOyELvsK1zAWkhXUpeCI61LMshqpJTy0ek0BrKnzoD02VJjfXBRdC6BbVYc65geVlKdQldO@y0KdlOMh4QiicYH5O2m5b@YUoKfzU32AnqfAIchZH5xpN6OlFv165RTDImyxuwZpG3m1WDq9o3Jzdr2sbcR/YqxHGfJE/PBp3D7rPBbDBbkFXd1CS48TUkq3qIk5gkL7GqieUOAU6Pf4sJ0XqLc50hy86BH58/fI0nDW8/fSFH0ZZK1ZNN@v23l9zlgppef94WVfTCDguHVr7huuh10e335@@i6HkYj8MLgiRWUzXf738C) `a(n) = 32` * [A010859](http://oeis.org/A010859) in [Braingolf](https://tio.run/##7ZRBbhMxFIb3PsWfKWmSJsw0UzWhCczsUBJRRUIsWFRCnrGnNnHGqe3RtCCuwIIlCxB7bsCOo/QE3CB4RtCKGyDEk/X597Of7SfrOTNUlpdaFfv9wQWJIkGxuTO8pvjDwRqP9d1yur6KX5EDWeaqYvyxdUzqUCRR9GA4nXYnhwgbg9nMrKPGYWdk6WYIxuOgcfKSpZ3W0vQvbB5Y603Y4F6ld@o//ln8eu7b9x8fff9GEB0RnguNhyVO5vxaOrLgNyPUVDpuOmTpVekQn0IXcELakCx0jW2VC0gL6VLyQnBkUqkRdopTy0NSaI3SrzoD00pRY31w0WndglpknJewXClfmNCVQ62NYrVkvEMonmB8TNpqWvqDKSn81tygFtT5C3AURuYbT@rpRLXNXKOYZEyqG7BmkLeTuwZXlS9ObjLaxtxH9neI4wFJnp4Nu4e9Z8PZcLYgq6rJSXDjc0hW1QgnMUleYlURyx06OD3@LSZE6y3O9Rrr9Tnw4/OHr/Gk4e2nL@Qo2vo/py@b6w/eXnKXC2r6g3mbVNEPuiwYWfmG66LfQ28wmL@LoudBPA4uCJK4nJbz/f4n) `a(n) = 20` * [A010860](http://oeis.org/A010860) in [Fission](https://tio.run/##7ZNfTsJAEMbf9xTTItACthYSEdD2zQReSHzywcQs3V12w7ILu9vgn3gFD@BVfPMoXqS2jXIGY/wy@eWbmUwyyWSYsFZoVZatOxTH8/FyP7xHLaFyWRB6aR0ROuJpHJ/0x@P2eQeiWmA2U@uwcbAzQrkp@Eni10WqSOY1yrJfGBXgR0u9iWp4R5cd3T/@LL7P/fn6dvHxjiDuIZpzDacKRjP6IBxiWoPSB5gA0VJiY0Ez5jVlji2sKFVgqZRCrUEXDg7aSHIQhHoIwxUkZ6j5iblygFEaXU/67Q5aFCAscGpohNJFMYDREKW3sCgQE1JSAweOHThOgRmRbyriio4X25WrHRGECPkIpE7yprmrsS@qJ6RmhZuZ4yTqxVssVBA@r6nLOTZBOGu2YoHfJv7AiieqWdCFbhjOXuL4xh8mfll@AQ) `a(n) = 21` * [A010861](http://oeis.org/A010861) in [Arcyou](https://tio.run/##7ZNRSsNAEIbf9xST1LZJWxOTgrWtJm9C@1LwyQdBttlNd@l2t93sUqt4BQ/gVXzzKF4kJkHrFUT8GT7@mWFgYBiss4OyZdm6Q2E4Gy128T1qcZkJS@hlYQhXAUvC8KQ/GrXPOxDUAr2eFAZrA1vNpZmAG0VuXaSSpE6jNP2FUQG@tVDroIZzdOnR/ePP4uvcHy@vF@9vCMIeohlTcCphOKUP3KBcKZBqD2MgSgisC1B57jRlhgtYUiqhoEJwuQJlDeyVFmTPCXUQhiuIzlDzEzNpAKMkuB732x00t8ALYFTTACVzO4BhjJJbmFuUcyGohj3DBgyjkGuerSviiobZzdLUjnBCuDgAqZOsaW5r7Gz1hFQvcTPzM@ltIY591As3mEsP@08rajKGtedPm@1yz20Td1DwR6pyrwtd358@h@GNG0duWX4C) `a(n) = 22` * [A010862](http://oeis.org/A010862) in [Beam](https://tio.run/##7ZPBbhMxEIbvfoo/W9IkTcg2WzWhCWRvKImoIiEOHCohZz1bm2zs1PYqLYhX4MCRA4g7b8CNR@kT8AbBu4JWvAFCjKzPv8cee0bWrIhv9vuDCxbHkmN9Z3jN8YdDVB4XpvloeZW8YgdKZ0Up6LHzQpm@nMbxg@5o1Bweol8Z7HrsPLceW6u0HyMaDKLKSVqkjdrS9C8cAViadb/CvUrv1H/8s/j13bfvPz76/o0hPmKUSYOHGicTulaeTZ@edZuHrWfdcXc8YzO66WHHlSfbYPOgtEdyCpPDS@X6bGZ22JSZhHJQPmUvJGGliqKHbUHcUZ/lxkCHU2cQpii4dSE4b9RuyR1WRBqOikLpS5jSY2dsIXZKUINxPMHgmNW9NQ8Pc5aHq8liJ7kPCRByq7J1IA/0stysfKWEEkIVNxDVIqs3txWuytCqZFe8jrmPbG@RJB22KKsqJNmQ9XRR9nCSsOlLLErmyKOB0@PfYsiM2eDcLLFcngM/Pn/4mgwr3n76wo7iDVe6raqEO28vyWeS23ZnUpeRt6OmiHpOvSGTt1todTqTd3H8PEoG0QXDNNEjPdnvfwI) `a(n) = 23` * [A010863](http://oeis.org/A010863) in [Beatnik](https://tio.run/##7ZPfSsMwFMbv8xRnndvaVRvXgXOdbnfihjDwygtBsiZdYrNkS1PmH3wFH8BX8c5H8UVqW2TDNxDxI/zy5TscOBDOghGrRFoUzVuEMSeQ7gT3BH4EtEqy8poO5pvwDjWFimVO2VlmqdABH2N84A8GrZM2BJXApFFmibGwNkLZCJxez6lCpuikUWsy@YWnBMx1GlTYu8nO/ePP4vu7P1/fTj/eEeAuYjHXcKSgP2IPwqJEa1B6C0OgWkpiMtBJ0qhjTjJYMKYgY1IKtQSdW9hqI@lWUNZABM6hd4zqXZgqCwSNg4uh32p3rvzIjy7RLAeRAWeGBWg8yw@hH6LxDcxylAgpmYEtJxYsZ5AYEaclSUnL89XCVo4KSoV8BFo94rq4rrDJyx1kZkHqnn2nu4Yw9FAXr4hQrqhG8p6XzMacGNcb1YMmrtOizmEmnphO3A50PG/0gvG1E/acouh/AQ) `a(n) = 24` * [A010864](http://oeis.org/A010864) in [Cood](https://tio.run/##7ZNBbhMxFIb3PsU/U9IkTcg0UzWhCWR2KImoRkIsWFRCzthTm0zs1PYoLYgrsGDJAsSeG7DjKD0BNwj2CFpxA4R4sj7/fvaz35P1Cq3Zfn9wQZJEUKzvDK8p/nCw4LF@Wozzq/QVOZCqqGrGH1vHpB6IWZI86I3HrdEhBsFg1hPrqHHYGqncBPFwGAcnVyyLGsuyv3B4INfrQcC9yu7Uf/yz@PXdt@8/Pvr@jSA5IrwQGg8VTqb8Wjoye3rWax22n/UmvcmczPlNHzsqHTcRWXilHNJT6BJOSDsgc73Dpi4EpIV0GXkhOFayqvrYVpxaPiCl1lD@1BmYripqrA8uo8YtqMWKcwXLq0qqS@jaYadNxXaS8YhQPMHwmDS9tfAPU1L6q7nBTlDnE@AojSzWntTTiXqzckExyZisbsDComg2twFXtW9Vbla0ibmP7GyRpl2yrEMVghuf9WxZ93GSktlLLGtiuUOE0@PfYkS03uBc58jzc@DH5w9f01Hg7acv5CjZUKk6MiTcfXvJXSGo6XSnTRllJ26xuG/lG67LThvtbnf6Lkmex@kwviCYpWqspvv9Tw) `a(n) = 25` * [A000027](http://oeis.org/A000027) in [COW](https://tio.run/##7ZNBbhMxFIb3PsWfKWlmmpBpJmpCE8jsUBJRRUIsWFRCzthTm0zs1PZoWhBX6KJLFiD23IAdR@kJuEHwjKAVN0CIJ@vz72c/@z1ZL9PVfn9wTuJYUGzuDW8p/nCw2mP9tBivLpM35ECqrCgZf2odk7ovZnH8qDset0eH6NcGs5lYR43DzkjlJggGg6B2csXSVmNp@hcOD6z0pl/jQaX36j/@Wfz67rubj0@@fyOIjwjPhMZjheGUX0lHZs9Pu@3DzovupDuZkzm/7qGi0nHTIguvlENyAp3DCWn7ZK4rbMtMQFpIl5JXgmMti6KHXcGp5X2Saw3lT52C6aKgxvrgvNW4BbVYc65geVFIdQFdOlTaFKySjLcIxTMMjknTWwv/MCW5v5obVII6nwBHbmS28aSeTpTbtasVk4zJ4hqsXmTN5q7GZelblZs1bWIeIsMdkiQiy7KuQnDjs54tyx6GCZm9xrIklju0cHL8W4yI1luc6RVWqzPgx@fbr8mo5t2nL@Qo3lKpQlknHL2/4C4T1ITRtCkjD4M2C3pWvuM6DzvoRNH0Qxy/DJJBcE4wS9RYTff74U8) `a(n) = n + 1` * [A010865](http://oeis.org/A010865) in [Emoji](https://tio.run/##7ZPBbhMxEIbvfoo/W9IkTcg2GzWhCSQ3lERUkRAHDpWQs56t3Wzs1PYqFNRX6IEjBxB33oAbj9In4A2CdwWteAOEGFmff4899oysoY25VPv9wTmLY8mxvjdccvzhEKXHhWk@XF4lb9iB0mleCHrqvFCmKydx/Kg9HNYHh@iWBrseOc@tx9Yq7UeIer2odJIW01pl0@lfOAKwNOtuiQc1vVf/8c/i13ff3X588v0bQ3zEKJUGjzX6Y3qrPJs8P23XDxsv2qP2aMZmdN3BjitPtsbmQWmP5AQmg5fKddnM7LApUgnloPyUvZKElcrzDrY5cUddlhkDHU6dQpg859aF4KxWuSV3WBFpOMpzpS9gCo@dsbnYKUE1xvEMvWNW9dY8PMxZFq4mi53kPiRAyKxK14E80Mtis/KlEkoIlV9DlIu02tyWuCpCq5Jd8SrmIbK5RZK02KIoq5BkQ9aTRdFBP2GT11gUzJFHDSfHv8WAGbPBmVliuTwDfnz@8DUZlLz79IUdxRuudFOVCbfeX5BPJbfN1rgqI2tGdRF1nHpHJms20Gi1xjdx/DJKetE5wyTRQz3e7/s/AQ) `a(n) = 26` * [A010866](http://oeis.org/A010866) in [><>](https://tio.run/##7ZNBbhMxFIb3PsU/U9IkTcg0UzWhCWR2KImoRkIsWFRCzthTm0zs1PYoLYgrsGDJAsSeG7DjKD0BNwj2CFpxA4R4sj7/fvaz35P1SmnFfn9wQZJEUKzvDK8p/nCw4LF@Wozzq/QVOZCqqGrGH1vHpB6IWZI86I3HrdEhBsFg1hPrqHHYGqncBPFwGAcnVyyLGsuyv3B4INfrQcC9yu7Uf/yz@PXdt@8/Pvr@jSA5IrwQGg8VTqb8Wjoye3rWax22n/UmvcmczPlNHzsqHTcRWXilHNJT6BJOSDsgc73Dpi4EpIV0GXkhOFayqvrYVpxaPiCl1lD@1BmYripqrA8uo8YtqMWKcwXLq0qqS@jaYadNxXaS8YhQPMHwmDS9tfAPU1L6q7nBTlDnE@AojSzWntTTiXqzckExyZisbsDComg2twFXtW9Vbla0ibmP7GyRpl2yrEMVghuf9WxZ93GSktlLLGtiuUOE0@PfYkS03uBc58jzc@DH5w9f01Hg7acv5CjZUKk6MiTcfXvJXSGo6XSnTRllJ26xuG/lG67LThvtbnf6Lkmex@kwviCYpWqspvv9Tw) `a(n) = 27` * [A010867](http://oeis.org/A010867) in [Set](https://tio.run/##7ZPBbhMxEIbvfoo/W9IkTcg2WzWhCWRvKImoIiEOHCohZz1bm2zs1PYqLYhX4MCRA4g7b8CNR@kT8AbBu4JWvAFCjKzPv8cee0bWOPL7/cEFi2PJsb4zvOb4wyEqjwvTfLS8Sl6xA6WzohT02HmhTF9O4/hBdzRqDg/Rrwx2PXaeW4@tVdqPEQ0GUeUkLdJGbWn6F44ALM26X@FepXfqP/5Z/Pru2/cfH33/xhAfMcqkwUONkwldK89mdNPDjitPtsHmQWmP5BQmh5fK9dnM7LApMwnloHzKXkjCShVFD9uCuKM@y42BDqfOIExRcOtCcN6o3ZI7rIg0HBWF0pcwpcfO2ELslKAG43iCwTGru2keHuYsD1eTxU5yHxIg5FZl60Ae6GW5WflKCSWEKm4gqkVWb24rXJWhOcmueB1zH9neIkk6bPr0rNs8bD3rjrvjGVuUVU2SbKhhuih7OEnY9CUWJXPk0cDp8W8xZMZscG6WWC7PgR@fP3xNhhVvP31hR/GGK91WVfqdt5fkM8ltuzOpi8rbUVNEPafekMnbLbQ6ncm7OH4eJYPogmGa6JGe7Pc/AQ) `a(n) = 28` * [A010868](http://oeis.org/A010868) in [NTFJ](https://tio.run/##7VNBbhMxFN37FG8mpJk0YaaZqglNYLJDSUQVCbFgUQk5Y0/tZmKntkehIK7AgiULEHtuwI6j9ATcIHgGaMWOJUI8Wc/P3/62n62vXHGZ7/etc5IkgmJ9C1xS/BZgdcT6bj5aXqUvSEuqvKwYf2gdkzoWWZLc641G7eEB4how67F11DhsjVRujHAwCOsgV2waNJhO/8LmCUu9jmu6U9Nb9Z/@Wfr53Tdv3z/4@gWtPwZBckh4LjTuKxxP@EvpyIxf97Gj0nETkLlXyiE9gS7ghLQxmekdNlUuIC2km5JngmMly7KPbcmp5TEptIbyq07BdFlSY31yETRhQS1WnCtYXpZSXUBXDjttSraTjAeE4hEGR6QpvLk/mJLCb80NdoI6fwGOwsh87Zl6dqLarFytmGRMltdg9SBvJrc1XVW@jrlZ0SbnLjPaIk27JHt82msfdJ70xr3xjCyq2pPgxnvIFlUfxynJnmNREcsdApwc/RJDovUGZ3qJ5fIM@Pbx3ed0WPPNh08/nj8hh8mGShXJ2kX39QV3uaAm6k4ab0UUtlnYt/IV10XUQafbnbxJkqdhOgjPCbJUjdRkv/8O) `a(n) = 29` (Links are not all current, I'll eventually update them. I have verified each language.) # C/C++ `sizeof(' ')` is 1 in C++ and 4 in C. Here's the C/C++ code: ``` #include <stdio.h> main(){getchar();printf("%d",sizeof(' '));} ``` * `#include <stdio.h>` is needed for C++. (This is why I don't like it.) * `getchar();` is there because we still technically need input. * `printf("%d",sizeof(' ')` prints 4 in C and 1 in C++. **Update** - the `echo -n 3;exit` is ignored via `\` at the end of the comment on line 1. # [Cubically](//git.io/Cubically) Cubically ignores everything it doesn't care about as long as no functions get called. ``` $+7+7%6& $ read int as input +7+7 double it (could be +77, I'll golf everything more if it comes to that) %6 print output & exit (the `main()` would cause an infinite loop) ``` # [rk](https://github.com/aaronryank/rk-lang) rk is horrible, but good for polyglotting. It ignores everything before `rk:start` and after `rk:end`: ``` rk:start print: "11" rk:end ``` Pretty simple. A010850 is a constant sequence. "Input is taken via command line arguments." :P # [what](https://github.com/gimmetehcodez/what) The `what` interpreter reads three bytes at a time. Very stupid but useful. ``` ?!!!??(x50)??! ``` Gets input (uselessly), goes to next memory cell, adds the ASCII value for 2 (50) to the current memory cell and outputs. # Bash ``` # <comment> echo -n 3; exit <everything ignored because parser already exited> ``` Also takes input via "command line arguments". I love constant sequences. # [Morse](https://github.com/aaronryank/minproj/blob/master/morse/morse.c) Morse Code is the oldest language used in this thread, I can guarantee. ;) This uses an interpreter I wrote last year for fun. It conveniently ignores everything it doesn't care about. ``` ..... ``` Constant sequences probably weren't what the OP had in mind when creating the challenge... # Ook! Ook! is a Trivial Brainf\*\*k Substitution. The interpreter I found is really crappy, reads 11 characters at a time and checks if it's something it cares about. Pasting the code at the end of the first line magically lined it up properly, so the interpreter noticed the Ook! code. ``` Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. ``` This is equivalent to Brainf\*\*k's `,>+(x48).`. Read a character, move to next memory cell, increment to 48 (ASCII code for `0`) and print. # [str](https://github.com/ConorOBrien-Foxx/str/) The str code wanted to be right at the top because something around `#include <stdio.h>` made it bug out. I had to rearrange the what and Ook! code, since I added something before both of them. ``` # // I7Oq ``` `#` is apparently a valid preprocessing token in C/C++. `//` comments it out. (That's a capital letter o, in case your screen tries to deceive you.) * `I` - read input * `7` - push 7 * `O` - output * `q` - turn off STDOUT just in case I think it's real clever how `I` is for input and `O` is for output. Nice language, Conor! # [Charcoal](https://github.com/somebody1234/Charcoal) Wow, I like this language, I'm gonna use it more sometime. Luckily, there's a command to clear the output buffer, `⎚`. So it just echoes everything up to the `⎚` on line 2, then clears that. The Charcoal code we care about looks like this: ``` ⎚8» ``` 8 prints 8. `»` exits with a parse error, which is allowed by default. # [Commercial](https://github.com/tuxcrafting/commercial) This one was a bit less nice because it wanted me to have its code on separate lines. I had to rearrange the C/C++ comments a bit. For some reason, C emitted a warning and then didn't compile when I replaced the `//` with `/*`. So it's on its own line, making Bash annoyed but still prints the desired number. ``` foo now 9 dollars off! foo has been selling out worldwide! ``` * `variable now x dollars off` creates a new variable `variable` with value `x`. * `variable has been selling out worldwide!` prints the variable's value. At least the interpreter is forgiving about *unrecognized* code... Oh, I also updated all the TIO links. That was a pain so I'll probably only do so every 10 or when I quit working on this polyglot. Fun challenge, thanks! # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S) That had one of the clearest, most concise READMEs I've ever seen. Simple as this: ``` a = 10 printInt 10 ``` Adding this code didn't even break anything! # [Memescript 1.0](https://github.com/aaronryank/memescript-1.0/) Why does this language exist >.< The interpreter was being lame so I had to add `filler` to get it to see `what the`. ``` filler what the frick frack thumbtack diddily dack crack pack quarterback frick frack ``` * `what the` - start code * `frick frack thumbtack` - push 11 * `diddily dack crack pack` - add 5 * `quarterback frick frack` - output as integer # Forked Forked is my new 2d lang, it's only partially implemented. It's not in a triangle or a cube or anything interesting, it's just a fun simple esolang. Unfortunately, having `# // I70q` on the first line had a mirror `/` in the way of the source code. I moved some things around so the mirrors look like this: ``` \ // ``` The mirrors are pretty self-explanatory; the code enters from the top left and exits at the bottom left. Then it hits this code near the bottom: ``` >F9+%& ``` `>` directs the IP west. `F` pushes 15, `9` pushes 9. `+` adds them, `%` prints as integer, `&` exits. Note: This may not work in future Forked versions, depending on how `#` will handle invalidity. # [TRANSCRIPT](https://github.com/TryItOnline/transcript/blob/master/README.txt) This is a cool language. I don't really understand some of the syntax (specifically, `>`), but it's fun nevertheless. Also forgiving about syntax errors which is why I chose to use it. Here's the code we care about: ``` Ju is here. >Ju, 32 >X Ju ``` * `Ju is here.` defines an NPC (variable) named Ju. (Short for Julie, which was used in the example.) * `>Ju, 32` puts 32 in Ju's memory (sets it to 32). * `>X Ju` prints Ju. (Where did `X` come from?!?) # [Braingolf](https://github.com/gunnerwolf/braingolf) Apparently, the code does some wacked out stuff to the stack but outputs 0 at EOF, so I found a place I could put the code without breaking anything else, found a sequence that ended in 0, and let it do its implicit output at the end. ``` 2_ ``` Pushes 2 and prints it. `0` is printed at the end, printing 20. More constant sequences, yay! # [Fission](https://github.com/C0deH4cker/Fission) For such a complicated language, this was pretty easy - just modified [this](https://chat.stackexchange.com/transcript/message/39301825#39301825): ``` R"21" ``` Prints 21. Surprisingly, putting this *anywhere* in the code worked just fine. * `R` creates atom travelling right. * `"21"` stores the string 21 in that atom. * Implicit output at the end of the program, I guess. # [Arcyou](https://github.com/Nazek42/arcyou) Another language forgiving about syntax errors. Here's the code we care about: ``` (p 22) ``` Arcyou is pretty much identical to LISP, but golfier. `p` is print, `22` is 22. Also, it printed `None` due to the `main()`. I added `a` there, C++ complained, I made it `int a` and everything's running smoothly again. # [Beam](http://esolangs.zem.fi/wiki/Beam) The hardest part about adding this language was finding the spec. Luckily, there's a mirror of esolangs.org! Thanks, totallyhuman! Beam uses the same control flow as Forked but that's it. So I put its code after Forked's exit command. ``` 'L+:+:H ``` `'` increments the store and `L` sets the beam to the store. `+` increments, `:` outputs as integer. I tried `++:+:H` first, but the beam apparently is not initialized to 0. The store is, though. # [Beatnik](http://esolangs.zem.fi/wiki/Beatnik) Beatnik is a language almost as awful as some I've written and am planning to write. It uses Scrabble word values. Here's its code: ``` ha kkkkkkkkkk ja ha kkkkkkkkkkd ja skd ``` Here is the Scrabble values for those: ``` 5 50 9 5 52 9 17 ``` * `5 50` - push 50 * `9` - print as ASCII * `5 52` - push 52 * `9` - print as ASCII * `17` - exit I used a comma and a bunch of Z's initially, which messed with str. Fixed by removing the useless comma and changing 5 z's to 10 k's. # [Cood](https://github.com/jesobreira/cood) Cood cares about this (explanation on the right) ``` Hey, waiter! (start program) I want 25 of this. (set memory to 25) How much is it? (print as int) The bill, please. (finish script) ``` # [COW](https://bigzaphod.github.io/COW/) Yay, a non-constant sequence! :D ``` oom MoO OOM oom read integer MoO increment OOM print as integer ``` # Emoji ``` 💬26💬➡ 💬..💬 push string 26 "26" âž¡ print top of stack ``` # ><> Another language I'm going to use more; I love how this wraps. It initially hits `#`, which bounces the IP backwards, wraps around, hits `\`, which wraps vertically to the bottom, hits `>`, then it sees `2n7n;`. ``` 2n7n; 2 push 2 n output 7 push 7 n output ; exit ``` # Set I recall this being used in the [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'"). Luckily, ASCII-only's TIO interpreter doesn't care about syntax errors!\ ``` set ! 50 (print 2) set ! 56 (print 8) ``` # [NTFJ](https://github.com/ConorOBrien-Foxx/NTFJ) That's another one of your langs I've used, Conor.... this is possibly the strangest. All I do is push truthy values (`#`) and use `/` to push the number of items on the stack to the stack and `*` to print. ``` (line 3) ########################################## (line 4) /* (line 21) #####/ (line 22) * ``` I didn't really mess with the code in the middle. It probably does things to the stack, and this will probably be a pain down the road, but whatever, it works. [Answer] # 9 Languages, 217 bytes ``` 2/3#^4 9 5 if 1: x="+++++++[>+++++++<-]>."#3 R = input() try: print(int(eval(chr(49)+chr(47)+chr(40)+chr(49)+chr(47)+chr(50)+chr(41))*int(R))) except: print(7**int(R)) R="6"#N; n=2 R ``` * In [Jelly](https://tio.run/##y0rNyan8/99I31g5zkTBUoFLQYGTi5PLFEhmpikYWgH5FbZK2hAQbQdl2OjG2ukpKRsDZYMUbBUy8wpKSzQ0gbySokqQFgWFgqLMvBINEE4tS8zRSM4o0jCx1NQG0@ZQ2gBKo4mbwsQNNTW1QCYEaWqCzE6tSE4tKEE23lwLJg8WDLJVMlNS9rMGc/JsjUCu@///vwkA), produces [A000027](https://oeis.org/A000027). * In [Python2](https://tio.run/##K6gsycjPM/r/30jfWDnORMFSgUtBgZOLk8sUSGamKRhaAfkVtkraEBBtB2XY6Mba6SkpGwNlgxRsFTLzCkpLNDSBvJKiSpAWBYWCosy8Eg0QTi1LzNFIzijSMLHU1AbT5lDaAEqjiZvCxA01NbVAJgRpaoLMTq1ITi0oQTbeXAsmDxYMslUyU1L2swZz8myNQK77/98EAA), produces [A000420](https://oeis.org/A000420). * In [Python3](https://tio.run/##K6gsycjPM/7/30jfWDnORMFSgUtBgZOLk8sUSGamKRhaAfkVtkraEBBtB2XY6Mba6SkpGwNlgxRsFTLzCkpLNDSBvJKiSpAWBYWCosy8Eg0QTi1LzNFIzijSMLHU1AbT5lDaAEqjiZvCxA01NbVAJgRpaoLMTq1ITi0oQTbeXAsmDxYMslUyU1L2swZz8myNQK77/98EAA), produces [A005843](https://oeis.org/A005843). * In [Brainfuck](https://tio.run/##SypKzMxLK03O/v/fSN9YOc5EwVKBS0GBk4uTyxRIZqYpGFoB@RW2StoQEG0HZdjoxtrpKSkbA2WDFGwVMvMKSks0NIG8kqJKkBYFhYKizLwSDRBOLUvM0UjOKNIwsdTUBtPmUNoASqOJm8LEDTU1tUAmBGlqgsxOrUhOLShBNt5cCyYPFgyyVTJTUvazBnPybI1Arvv/HwA), produces [A000012](https://oeis.org/A000012). * In [///](https://tio.run/##K85JLM5ILf7/30jfWDnORMFSgUtBgZOLk8sUSGamKRhaAfkVtkraEBBtB2XY6Mba6SkpGwNlgxRsFTLzCkpLNDSBvJKiSpAWBYWCosy8Eg0QTi1LzNFIzijSMLHU1AbT5lDaAEqjiZvCxA01NbVAJgRpaoLMTq1ITi0oQTbeXAsmDxYMslUyU1L2swZz8myNQK77/x8A), produces [A007395](https://oeis.org/A007395). * In [Ohm](https://tio.run/##y8/I/f/fSN9YOc5EwVKBS0GBk4uTyxRIZqYpGFoB@RW2StoQEG0HZdjoxtrpKSkbA2WDFGwVMvMKSks0NIG8kqJKkBYFhYKizLwSDRBOLUvM0UjOKNIwsdTUBtPmUNoASqOJm8LEDTU1tUAmBGlqgsxOrUhOLShBNt5cCyYPFgyyVTJTUvazBnPybI1Arvv/HwA), produces [A010734](https://oeis.org/A010734). * In [><>](https://tio.run/##S8sszvj/30jfWDnORMFSgUtBgZOLk8sUSGamKRhaAfkVtkraEBBtB2XY6Mba6SkpGwNlgxRsFTLzCkpLNDSBvJKiSpAWBYWCosy8Eg0QTi1LzNFIzijSMLHU1AbT5lDaAEqjiZvCxA01NbVAJgRpaoLMTq1ITi0oQTbeXAsmDxYMslUyU1L2swZz8myNQK77/x8A), produces [A010709](https://oeis.org/A010709). * In [Fission 2](https://tio.run/##S8ssLs7MzzP6/99I31g5zkTBUoFLQYGTi5PLFEhmpikYWgH5FbZK2hAQbQdl2OjG2ukpKRsDZYMUbBUy8wpKSzQ0gbySokqQFgWFgqLMvBINEE4tS8zRSM4o0jCx1NQG0@ZQ2gBKo4mbwsQNNTW1QCYEaWqCzE6tSE4tKEE23lwLJg8WDLJVMlNS9rMGc/JsjUCu@/8fAA), produces [A010722](https://oeis.org/A010722) * In [Whitespace](https://tio.run/##K8/ILEktLkhMTv3/30jfWDnORMFSgUtBgZOLk8sUSGamKRhaAfkVtkraEBBtB2XY6Mba6SkpGwNlgxRsFTLzCkpLNDSBvJKiSpAWBYWCosy8Eg0QTi1LzNFIzijSMLHU1AbT5lDaAEqjiZvCxA01NbVAJgRpaoLMTq1ITi0oQTbeXAsmDxYMslUyU1L2swZz8myNQK77/x8A), produces [A0000004](https://oeis.org/A000004) Jelly outputs the first `n` elements of the sequence instead of the `n`-th element. ><> and Whitespace exit with an error after giving the correct output, which is allowed by default. ## How it works **Jelly** Jelly sees only the `R` at the bottom, which tells it to output `range(input)`. **Python 2** After removing unused lines, Python 2 sees: ``` if 1: # just do it, where it is the following: R = input() # set input to R try: # try: print(int(eval(chr(49)+chr(47)+chr(40)+chr(49)+chr(47)+chr(50)+chr(41))*int(R)) # print(int(1/(1/2))*int(R)). Floor division causes 1/(1/2) to be # 1/0, raising a division by 0 error, going into the except block except: print(7**int(R)) # print 7 to the power of R. ``` **Python 3** ``` if 1: # just do it, where it is the following: R = input() # set input to R try: # try: print(int(eval(chr(49)+chr(47)+chr(40)+chr(49)+chr(47)+chr(50)+chr(41))*int(R)) # print(int(1/(1/2))*int(R)). Float division causes 1/(1/2) to be # 1/0.5=2. This is multiplies by R and printed. except: # The except block is not called print(7**int(R)) ``` **Brainfuck** Brainfuck sees: ``` +++++++ Set counter cell to 7 [ While counter != 0 > Go to storage cell (default to 0) +++++++ Increase by 7 < Return to counter cell - Decrement ] EndWhile >. Print out chr value of storage cell => chr(49) = "1" ``` **///** /// sees: ``` <Something including the top-left 2> # replace the empty string with 2 and output ``` **Ohm** Ohm sees: ``` <Something including the top 9> # implicitly output 9. ``` **><>** ><> sees: ``` 2/3#^4 9 -- the IP travels right (pushing 2) until it hits `/` f -- it travels up (pushing f=15) until it hits `/` -- it travels right (pushing 3) until it hits `#` -- it travels left (pushing 3) until it hits `/` -- it travels down (pushing f=15) until it hits `/` -- it travels left (pushing 2 then 9 then 4) until it hits `^` -- it travels up. When it hits `n`, it prints the 4 -- it then hits some characters ><> doesn't like, -- ending the program with an error. n ``` **Fission** Fission sees: ``` R="6"#N; R - start an IP/atom going right " - start string 6 - 6 " - end string N - add newline ; - end program. (implicit) print ``` (it sees other lines, but those don't affect output) **Whitespace** Some of this has likely been lost in copy-paste. Whitespace sees the following, where N represents linefeed, S represents space, and T represents tab. All actual newlines should be ignored. ``` NSSN SSSN -- push 0 TN -- print it NTNSNSSNSSSSNSSNSSSSNSSNSSSSNSSSSNSSSSNSSN ``` [Answer] # 9 Languages, ~~107~~ 98 bytes Sub 100! Python 2, Python 3, JavaScript, PHP, brainfuck, Retina, Gaia, ><>, Ohm. ``` 2 //1;""""0 ;function a($n){return $n**(2+!"0");}; /*.""" print(input()*2) 1#/i$%o< () #\7751cep*/ ``` [A005843](http://oeis.org/A005843) in [Python 2](https://tio.run/##DcrBCgIhEADQ@3yFuQYzEzQqxB7sU7rEspGXUUQPEX277Tu/@unvonHOaERCsgcP6TV067moeaJT@ra9j6bGKTPGy8l6S@mXQPh6dKgta8esdXQkjgRhkezO5Q5IZnms6y1se2WZM/g/) [A020338](http://oeis.org/A020338) in [Python 3](https://tio.run/##DcqxCsMgEADQ3a@wxsJ5hZ5aQgb7KV1KSKnLKXIOoeTbbd786i7fwo8xoiYKyZy8Sp/Oq@TC@g2W3a9t0htry4gQbxfjjUtHUoT3s6vaMgtkrl3AYXQqTJTttTwVOD29lmUO61aRxgj@Dw) [A000290](http://oeis.org/A000290) in [JavaScript](https://tio.run/##DcpLDsIgEADQPafAFpMZjOWTNF3gUdwQRINpBkKpG@PZsW/93v7jt1BTaVfKj9i75UoZNxw0c8@dQkuZuAdB@K2x7ZW4ICnBXk6DHtD9HFNyOjorNVGDRGVvgNIiM6NK4pxvDJCP92WZTYhFqh4ybXmN05pf4MFoxP4H) [A000578](http://oeis.org/A000578) in [PHP](https://tio.run/##DYy7CgMhEAD7/QrjGXANxAeEKzzIj6QJYjibdRGtQr7dOMVUw/DJ83jychDW@igXDuJnUOqlknhrRfhtuY9GQpExOtwu0kmMvwjW3FcO3Ap1XYhH12gCgt9sUdd6gEaxvfb94VNmY2dOZ11H7zDOPw) (run with `-r`) [A000012](https://oeis.org/A000012) in [brainfuck](https://tio.run/##DcpBCsMgEADAu6@wxsLuFmoUSg7mKblYSWApbET0VPp2mznPuyaWo@fPGEE756O5zCoeXXLjU3QCK/ite@tVtBUiCI@bmQ3GX1SOnldXpbI0YCm9AVJA5SfH9n6uClBP27K8fN4LuTHSHw) (IO by byte value) [A001477](http://oeis.org/A001477) in [Retina](https://tio.run/##DcrBCsMgDADQe77CWQfGwaLC6MF9yi6lOMglFYmnsm93fefXq7Jsc2ZDlIq9RCjfIbvyIWbzTvDsVUcX4yQEnx83Gy2WXwEKz6tD6yzqWdpQjyEjpIXY3Y83eDTLZ11faa8t0Jwp/gE) [A000040](https://oeis.org/A000040) in [Gaia](https://tio.run/##Dco7CsMwDADQXadwHRckFeoPlAzuUbqYkBYtijH2VHp2N29@nyJlzmS8j9meAuT30K3LoaagU/q2vY@mxikzptvFBkv5l8Hz/exQm2hH0To6EieCuHhx1@MJSGZ5resjbntlP2cMfw) [A000035](https://oeis.org/A000035) in [><>](https://tio.run/##DcrBCsMgDADQe77CWQcmg6UKowf7KbuU0rJcUnF6Gvt223d@u3w/vUfDHJK9jJD2pmuVQ83ineKvbLUVNU6JfHzc7Ggx/RMwPa8OuYhWL5pb9UgRIQws7n7M4NEM72l6hXXLxL0vJw) (IO by byte value) [A000004](http://oeis.org/A000004) in [Ohm](https://tio.run/##DcrBCgIhEADQ@3yFuQYzEzQqxB7sU7rEspGHRhE9Rd9u@86vvD9zRiMSkj14SK@hW89FzROd0rftfTQ1TpkxXk7WW0q/BMLXo0NtWTtmraMjcSQIi2R3LndAMstjXW9h2yvLnMH/AQ) ## Explanations ### Python 2 and 3 All the two Python versions see is the following: ``` print(input()*2) ``` The difference in their behaviour is that `input()` evals the line of input read in Python 2, but just returns the string in Python 3. So Python 2 prints **2n**, but Python 3 prints the string of **n** repeated twice. ### JavaScript and PHP What these languages see is the following: ``` 2 ;function a($n){return $n**(2+!"0");}; ``` Which defines a function `a` that computes the result. The difference in behaviour comes from `!"0"`. In JavaScript, `"0"` is a truthy value. So `!"0"` becomes `false`, which gets cast to 0. Thus JavaScript computes `$n` to the power 2+0. In PHP, the `"0"` is actually a falsy value, because (for whatever reason) it gets cast to the number `0` before being treated as a boolean. So `!"0"` is true. Thus PHP computes `$n` to the power 2+1. ### brainfuck The `+` in the JS/PHP part increments the cell, then the `.` in the middle outputs it. Thus it outputs the byte value 1 for any input. ### Retina Retina does a lot of regex substitutions on the input, using regexes that don't even remotely match any number that would be given as input (so no replacements are made). Then it prints the result of the replacements, which is just the input. ### Gaia The only line executed by Gaia is: ``` () #\7751cep*/ ( Decrement the input ) # Find the first (input-1) numbers such that (number+1) is true \ Delete that list of numbers 7751c Push the string "ṇ" e Eval it (the command for "nth prime number") p Print the result */ Some other stuff that doesn't matter ``` ### ><> What's relevant to ><> is ``` 2 / /i$%o< ``` The fish starts at the top left, pushing `2`. It moves over to the `/`, mirroring and looping to the bottom of the code. It hits the other `/` and move right. It pushes input (`i`), swaps the top stack elements (`$`), computes input mod 2 (`%`), and outputs as a byte (`o`). Then it moves left and tries to output again, which causes the program to exit with an error since there's nothing left on the stack. ### Ohm Ohm only executes the first line: ``` 2 //1;""""0 ``` Which is some random stuff and then `0`. Only the top stack element is printed implicitly. [Answer] # 5 languages - [Braingolf](https://github.com/gunnerwolf/braingolf), [Pyth](https://pyth.readthedocs.io) / [GolfScript](http://www.golfscript.com/golfscript/) / [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) / [Pyke](https://github.com/muddyfish/PYKE) / [Brachylog](https://github.com/JCumin/Brachylog), [MATL](https://github.com/lmendo/MATL), [Retina](https://github.com/m-ender/retina) / [Jelly](https://github.com/DennisMitchell/jelly) / [Commentator](https://github.com/SatansSon/Commentator) and [05AB1E](https://github.com/Adriandmen/05AB1E) / [2sable](https://github.com/Adriandmen/2sable) / [Oasis](https://github.com/Adriandmen/Oasis) ``` Q ``` This has ~~two~~ three multi-language-sequence polyglots. In Braingolf, this computes the triangular numbers ([A000217](https://oeis.org/A000217)), Pyth and GolfScript and Pyke (and Brain-Flak) are 0-indexed and use the non-negative integers ([A001477](https://oeis.org/A001477)), MATL is 0-indexed and uses the positive integers ([A000027](https://oeis.org/A000027)), Retina, Commentator and Jelly always output `0` ([A000004](https://oeis.org/A000004)), regardless of the input and 05AB1E, Oasis and 2sable always output `1` ([A000012](https://oeis.org/A000012)). * **[Try Braingolf online!](https://tio.run/##SypKzMxLz89J@/8/8P///yYA)** * **[Try Pyth online!](https://tio.run/##K6gsyfj/P/D/fxMA)** or **[Try GolfScript!](https://tio.run/##S8/PSStOLsosKPn/P/D/f0MA)** or **[Try Pyke!](https://tio.run/##K6jMTv3/P/D/fwMA)** or **[Try Brachylog!](https://tio.run/##SypKTM6ozMlPN/r/P/D/f@P//gA)** (thanks to @DanTheMan) or **[Check out Brain-Flak instead!](https://tio.run/##SypKzMzTTctJzP7/P/D/f0MA)** * **[Try MATL online!](https://tio.run/##y00syfn/P/D/fxMA)** * **[Try Retina online!](https://tio.run/##K0otycxL/P8/8P9/EwA)** (thanks to @jimmy23013) or **[Try Jelly!](https://tio.run/##y0rNyan8/z/w/38TAA)** or **[Check out Commentator instead!](https://tio.run/##S87PzU3NK0ksyS/6/z/w/38TAA)** * **[Try 05AB1E online!](https://tio.run/##MzBNTDJM/f8/8P9/C2NLEwA)** or **[Try 2sable!](https://tio.run/##MypOTMpJ/f8/8P9/EwA)** or **[Check out Oasis instead!](https://tio.run/##y08sziz@/z/w/38TAA)** --- # How? In Braingolf, the nth triangular number is calculated using `Q` (1-indexed). In Pyth and GolfScipt and Pyke (and Brain-Flak), the input just gets printed as it is. In MATL, `Q` means increment by 1, hence it displays the number given as input plus 1. In Retina, Commentator and Jelly, `Q` always prints `0`. Similarly, 05AB1E, Oasis and 2sable output `1`. [Answer] # 5 languages ([05AB1E](https://github.com/Adriandmen/05AB1E), [CJam](https://sourceforge.net/projects/cjam/), [Jelly](https://github.com/DennisMitchell/jelly), [MATL](https://github.com/lmendo/MATL), [Retina](https://github.com/m-ender/retina)), 8 bytes ``` rdK*p %2 ``` This produces: * In [05AB1E](https://tio.run/##MzBNTDJM/f@/KMVbq4BL1ej/f0MDAA): sequence [A007395](https://oeis.org/A007395); * In [CJam](https://tio.run/##S85KzP3/vyjFW6uAS9Xo/38zAA): sequence [A008602](https://oeis.org/A008602); * In [Jelly](https://tio.run/##y0rNyan8/78oxVurgEvV6P///0bmAA): sequence [A000035](https://oeis.org/A000035); * In [MATL](https://tio.run/##y00syfn/vyjFW6uAS9Xo/39DEwA): sequence [A000012](https://oeis.org/A000012); * In [Retina](https://tio.run/##K0otycxL/P@/KMVbq4BL1ej/f2MTAA): sequence [A000027](https://oeis.org/A000027). The CJam program exits with an error after producing the correct result in STDOUT, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4781/36398). [Answer] # 3 languages, [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), [QBasic](https://drive.google.com/open?id=0B0R1Jgqp8Gg4UVliSTE0MzdLcEU) and [Javascript](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/19d3VpfK4ErM6@gtEQhkcs@UauQS11dSz/NVkPT1s7Q@n9yfl5xfk6qXk5@ukaahqam9X8A) ``` '';/*` input a ?a*q ''*/f=()=>1; ``` ## [QBasic, all 0's; A000004](https://oeis.org/A000004) ``` '';/*` the ' makes this a comment for QBasic input a this asks for an input, stores it in a ?a*q Multiplies a by q, which is not set in QBasic and therefore 0. ? prints this. ''*/f=()=>1; And another comment ``` ## [QBIC, positive ints, A000027](https://oeis.org/A000027) ``` '';/*` The ' opens a code literal: This tells the QBIC interpreter that the next bit is pure QBasic. The following ' injects a comment in the output QBasic code, the ` at the end closes the code literal. input a this does the same as the QBasic bit ?a*q Multiplies a by q, which is 1 in QBIC and just yields the input. ? prints this. ''*/f=()=>1; And another comment ``` ## [Javascript, all 1's, A000012](https://oeis.org/A000012) ``` '';/*` ''; is mostly harmless. /* opens a multiline comment. ` is ignored input a commented ?a*q and commented ''*/f=()=>1; This closes the comment and defines function f() that always just returns 1 ``` [Answer] # 3 languages: [Gaia](https://github.com/splcurran/Gaia), [CJam](https://sourceforge.net/p/cjam), [Retina](https://github.com/m-ender/retina), 7 bytes ``` 1_0 @+ ``` [A005843](http://oeis.org/A005843) in Gaia, [A010850](http://oeis.org/A010850) in CJam, and [A000004](http://oeis.org/A000004) in Retina. [Try it Gaia!](https://tio.run/##S0/MTPz/3zDegIvLQRvIMAAA "Gaia – Try It Online") [Try it CJam!](https://tio.run/##S85KzP3/3zDegIvLQRvIMAAA "CJam – Try It Online") [Try it Retina!](https://tio.run/##K0otycxL/P/fMN6Ai8tBG8gwAAA "Retina – Try It Online") ### Explanations **Gaia** Gaia only executes the bottom line, which reads input (`@`) and adds it to itself. **CJam** ``` 1 Push 1 _ Copy it 0 Push 0 @ Bring the bottom 1 to the top + Add 1+0, making the stack `[1 1]`. Implicity push the stack flatten and joined. ``` **Retina** Replaces instances of `1_0` in the input with nothing. Then counts and outputs the matches of the regex `@+` in the result. Since this won't ever appear, it outputs 0 for any *n*. [Answer] # 11 languages: C, C++, JavaScript (nodejs), Ruby, JavaScript (modern browser), Perl, dc, ><>, brainfuck, JavaScript (spidermonkey), and Pyramid Scheme, 342 bytes I wanted to see if I could break ~~9~~ 10. I decided to use mainly non-esoteric languages. ``` //;<<E;#6nq>>>-[++>+[+<]>]>^\ /* ;n7<>> / \: #include <stdio.h> //out\ // ^----- // - struct k {};int main(){printf("%i",1+sizeof(struct k));} //;\ E //;\ `echo`; print($??3:5) ;//;#*/ console['log'](this['window']?4:this['print']?9:10) ``` Results I was able to verify (for input 4) on my machine: ``` Result in "C" (A000004): > gcc normal.c -o normal && normal.exe 4 1 Result in "C++" (A000012): > g++ normal.cpp -o normal && normal.exe 4 2 Result in "JavaScript" (A007395): > node normal.js 4 10 Result in "Ruby" (A010701): > ruby normal.rb 4 3 Result in "Perl" (A010716): > perl -f normal.pl 4 5 Result in "dc" (A010722): > echo 4 | dc -f normal.dc 6 ``` [Pyramid Scheme](https://tio.run/##hY7NTsMwEITvfopVA4rdEExVfkRsOac@RZKqleMSi8QusaMKqj57MKFcEKLfZTW7M6Pdv/fbTtepk43q1DjCGUoZ5ysWPZo3IURaJIlIioRXohLrEtF5sDDzxIWAv6FQZijSRrZDrYA7X2t72/xyU2oHH9oo/Ms6/eKiLUXO94P08ArHE9PGQ7fVBpPjvg9ih2fXenazSJz@UHaHf7yEsFOoZiWg1TTRRsnGbhjAlMNXeb7MHghi4RjNww/SGmdbVcStfYkr7BvtivigTW0PcZXfZ9@LKRz0c7a4I@P4CQ "Pyramid Scheme – Try It Online") [Answer] # 2 languages: /// and ><> ``` /9/0//8/0//7/0//6/0//5/0//4/0//3/0//2/0//1/0//00/0// >1n;// ``` **///** outputs <https://oeis.org/A000004> all 0's, and **><>** does <https://oeis.org/A000012> all 1's [Try ><> online!](https://tio.run/##S8sszvj/X99S30Bf3wJEmIMIMxBhCiJMQIQxiDACEYYgwsAARHLZGeZZ6@v///9ft0zB0AAA) [Try /// online!](https://tio.run/##K85JLM5ILf7/X99S30Bf3wJEmIMIMxBhCiJMQIQxiDACEYYgwsAARHLZGeZZ6@v/NzQw@A8A) [Answer] # 4 languages, [Braingolf](https://github.com/gunnerwolf/braingolf), [2col](https://gunnerwolf.github.io/2col/index.php), [arcplus](https://gunnerwolf.github.io/arcplus/index.php), [Lean Mean Bean Machine](https://github.com/gunnerwolf/lmbm) ``` O 2 +$ _/ 1_ ; (p 4) 3 ``` That's right! I've successfully created a polyglot of all of my own languages! # Braingolf, [A000012](https://oeis.org/A000012), the all 1s sequence. [Try it online!](https://tio.run/##SypKzMxLz89J@/9fwZ9LwYhLW4UrXp/LMJ7LWoFLo4DLRJPLWOH/fwA "Braingolf – Try It Online") Braingolf usually has implicit output of the top of the stack at program termination, but the semicolon prevents that. As a result, the only important code is this: ``` 1_ ; ``` `1_` pushes 1, then pops and prints the top of the stack, while `;` suppresses implicit output. There are no other braingolf print operators in the code, so nothing else is printed. However it's a little more difficult than that, as polyglots tend to be. The `$` on line 3 is LMBM's "print value" operator, but is Braingolf's "silent" operator. This means that normally the `$` would "silence" the `_` in Braingolf, and cause it to silently pop the top of the stack. As a result we throw in an extra line: ``` _/ ``` The slash is explained under LMBM, but the underscore is for Braingolf, it pops the top of the stack *before* we push the 1, consuming the silent operator in the process. This allows our `1_` to function as expected. # 2col, [A010701](https://oeis.org/A010701), the all 3s sequence. [Try it in 2collIDE!](https://gunnerwolf.github.io/2col/index.html?code=IE8KIDIKKyQKXy8KMV8KOyAKKHAKNCkKMyA) 2col is to blame for the peculiar layout of the code, as 2col requires every line to be no more than 2 characters in width. Some of these lines do some weird stuff in 2col, but ultimately as there is no valid 2col print operator in this code, the implicit output kicks in and outputs the return value of the last line. ``` 3 ``` This is the last line, an integer literal, which returns itself. 2col is also the cause of the `+` on line 3. This does nothing, but prevents 2col throwing a TypeError when trying to execute the `$` command. # arcplus, [A010709](https://oeis.org/A010709), the all 4s sequence. [Try it online!](https://gunnerwolf.github.io/arcplus/index.html) (code not included) arcplus is inspired by arcyou, which is inspired by LISP. arcplus ignores everything not in parentheses. Here's the bit in parentheses: ``` (p 4) ``` This is a function call. Specifically the `p` function, which is shorthand for `print`. Any whitespace is valid separator between the function name and the argument, including a newline, so this is essentially `(print 4)`. I hope I don't need to explain what that does. # Lean Mean Bean Machine, [A007395](https://oeis.org/A007395), the all 2s sequence. *No online interpreter available* This one was surprisingly easy, despite being a rather awkward 2d language. Here's what matters for LMBM: ``` O 2 +$ _/ 1_ ; ``` `O` is a spawn point. A marble is spawned here with a spin of 1, and a value of 0. It hits the 2, setting its value to 2, then hits the `$`, printing its value. The `/` moves the marble one space to the left, and changes its spin to 0, *note that the underscore to the left of the slash is not executed, as "gravity" takes effect after the left shift before the marble has time to execute another symbol.* The marble then drops to 1, setting its value to 1, and finally hits the semicolon, silently killing the marble. LMBM terminates once all marbles are destroyed. [Answer] # 30 languageversions, 4 bytes ``` B3%0 ``` This works with 30 different versions (cube sizes) of Cubically. # I promise I'm not cheating! However, I'd appreciate it if this answer didn't get accepted. There are other more impressive polyglots, including [my other (previously winning) one](https://codegolf.stackexchange.com/a/137874/61563). > > Language (Python 2/3) revisions do count as different languages. Different implementations of a language (such as Browser JS vs Node.js) also count as different languages. > > > This works in 30 different cube sizes a.k.a. versions of [Cubically](//git.io/Cubically). I added support for multiple cube sizes last night and made changes live this morning. Each cube size is considered a different language version due to the fact that each cube size *completely* changes how math is done in the language. I realized afterwards that this feature is very useful for polyglotting. As making the change was very difficult, useful for lots of things, and required hours of messing with dynamic memory in C, I clearly did not add it just for that reason. # Explanation `B3` turns the BACK face 90° clockwise three times. In Cubically 3x3x3, faces have nine cubelets (three per line), so this gets the cube to look like this: ``` 111 000 000 511222330444 511222330444 511222330444 555 555 333 ``` That's useful, because in Cubically 4x4x4, it looks like this: ``` 1111 0000 0000 0000 5111222233304444 5111222233304444 5111222233304444 5111222233304444 5555 5555 5555 3333 ``` # Run-down ``` Version Sequence 2x2x2 A007395 3x3x3 A010701 4x4x4 A010709 5x5x5 A010716 6x6x6 A010722 7x7x7 A010727 8x8x8 A010731 9x9x9 A010734 10x10x10 A010692 ... ... 32x32x32 A010871 ``` Looks like the constant sequences *finally* stopped at 32. Seems random but there you are. [Answer] # C89, C99, C++, Bash, Python Look, ma, no esolangs! ``` #include<stdio.h>/* """ "; */int x=32//* /4+//* */ 4;/* echo 3;exit """ #*/ #define print(y)main(){printf("%d",x-(int)sizeof(' '));} print(2) ``` This prints: * <https://oeis.org/A010709> in C89 * <https://oeis.org/A010731> in C99 * <https://oeis.org/A010850> in C++ * <https://oeis.org/A010701> in Bash * <https://oeis.org/A007395> in Python # C89 Single-line comments did not exist in C89, so it sees this: ``` #include<stdio.h> int x=32/ 4; #define print(y)main(){printf("%d",x-(int)sizeof(' '));} ``` So `x` is 8, `sizeof(' ')` is 4, outputs 4. # C99 Single-line comments *did* exist in C99, so it sees this: ``` #include <stdio.h> int x=32 /4+ 4; #define print(y)main(){printf("%d",x-(int)sizeof(' '));} ``` So `x` is set to 12, `sizeof(' ')` is 4, output is 8. # C++ C++ sees the same thing as C99 but `sizeof(' ')` is 1. Outputs 11. # Bash Bash sees this: ``` """ "; */int x=32//* /4+//* */ 4;/* echo 3;exit ``` Okay, so those first four lines cause a lot of parsing errors. Other than that, prints 3. # Python Python sees this: ``` print(2) ``` Everything else is commented out one way or another. Prints 2. ]
[Question] [ Consider taking some non-negative integer such as 8675309 and computing the absolute values of the differences between all the pairs of neighboring digits. For \$8675309\$ we get \$|8-6| = 2\$, \$|6-7| = 1\$, \$|7-5| = 2\$, \$|5-3| = 2\$, \$|3-0| = 3\$, \$|0-9| = 9\$. Stringing these results together yields another, smaller non-negative integer: \$212239\$. Repeating the process gives \$11016\$, then \$0115\$, which by the convention that leading zeros are not written simplifies as \$115\$, which becomes \$04\$ or \$4\$, which can't be reduced any further. Summing all these values up we get \$8675309 + 212239 + 11016 + 115 + 4 = 8898683\$. Let's define the Digit Difference Sum (or DDS) as this operation of repeatedly taking the digit differences of a number to form a new number, then adding all the resulting numbers to the original. Here are the first 20 values in the corresponding DDS sequence: ``` N DDS(N) 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 11 11 11 12 13 13 15 14 17 15 19 16 21 17 23 18 25 19 27 ``` [Here are the first 10000 values](http://pastebin.com/raw.php?i=smY5B93g), the graph for which is quite curious: [![DDS 10000 plot](https://i.stack.imgur.com/j1Im7.png)](https://i.stack.imgur.com/j1Im7.png) Especially since it looks the same when you plot it to 1000 or even 100: [![DDS 1000 plot](https://i.stack.imgur.com/5gohE.png)](https://i.stack.imgur.com/gyhhV.png) [![DDS 100 plot](https://i.stack.imgur.com/06p5T.png)](https://i.stack.imgur.com/ghmjq.png) (I'd call it the dentist's [staircase](https://codegolf.stackexchange.com/q/46821/26997)...) # Challenge Write a program or function that takes in a non-negative integer and prints or returns its DDS value. For example, if the input was `8675309`, the output should be `8898683`. **The shortest code in bytes wins.** [Answer] # Python 2, 73 Luckily, I managed to avoid any string operations. ``` t=lambda n:n>9and abs(n%10-n/10%10)+10*t(n/10) g=lambda n:n and n+g(t(n)) ``` `g` is the function that computes the answer. [Answer] # Matlab, 101 ~~105~~ bytes Thanks a lot to @beaker for his suggestion to use `polyval` instead if `base2dec`. That allowed me to * save 4 bytes; * greatly simplify the generalization to arbitrary base (see below) and save 22 bytes there; and most of all, * helped me realize that the code for the general case was wrong (leading zeros were not being removed). The code and the graphs are correct now. Code: ``` function y=f(y) x=+num2str(y);while numel(x)>1 x=polyval(abs(diff(x)),10);y=y+x;x=+dec2base(x,10);end ``` Example: ``` >> f(8675309) ans = 8898683 ``` ## Bonus: arbitrary base A small generalization allows one to use an arbitrary number base, not necessarily decimal: * Arbitrary base from 2 to 10, **~~108~~ 104 bytes** ``` function y=f(y,b) x=+dec2base(y,b);while numel(x)>1 x=polyval(abs(diff(x)),b);y=y+x;x=+dec2base(x,b);end ``` The reason why this works only for base up to `10` is that Matlab's `dec2base` function uses digits `0`, `1`, ..., `9`, `A`, `B`, ..., and there's a jump in character (ASCII) codes from `9` to `A`. * Arbitrary base from 2 to 36, **124 ~~146~~ bytes** The jump from `9` to `A` referred to above needs special treatment. The maximum base is `36` as per Matlab's `dec2base` function. ``` function y=f(y,b) x=+dec2base(y,b);x(x>57)=x(x>57)-7;while numel(x)>1 x=abs(diff(x));x=x(find(x,1):end);y=y+polyval(x,b);end ``` This is how the dentist's staircases look for different bases: [![enter image description here](https://i.stack.imgur.com/P5len.png)](https://i.stack.imgur.com/P5len.png) [![enter image description here](https://i.stack.imgur.com/lWz41.png)](https://i.stack.imgur.com/lWz41.png) [![enter image description here](https://i.stack.imgur.com/leSWm.png)](https://i.stack.imgur.com/leSWm.png) [![enter image description here](https://i.stack.imgur.com/wQad1.png)](https://i.stack.imgur.com/wQad1.png) [![enter image description here](https://i.stack.imgur.com/TEaig.png)](https://i.stack.imgur.com/TEaig.png) [![enter image description here](https://i.stack.imgur.com/v3J5k.png)](https://i.stack.imgur.com/v3J5k.png) [Answer] # Pyth, 17 ``` s.ui.aM-VJjNTtJTQ ``` [Try it here](https://pyth.herokuapp.com/?code=s.ui.aM-VJjNTtJTQ&input=8675309&debug=0) or run the [Test Suite](https://pyth.herokuapp.com/?code=s.ui.aM-VJjNTtJTQ&input=19&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A8675309&debug=0) ### Explanation: ``` s.u Q # Cumulative reduce, i.e. getting the intermediate values of each reduce step and returning them as a list, then sum the list i ... T # Convert the resulting list of numbers into a base 10 number .aM # Get the absolute value of each element of ... -VJjNTtJ # Perform vector subtraction on the lists given by JjNT # assign J the number we currently have converted to its base 10 digits tJ # and J[1:]. e.x. for 123 we get J = [1,2,3] then we do # zip(J,J[1:]) which gives [[1,2],[2,3]] then element wise subtract # to get [-1, -1] ``` [Answer] # CJam, ~~22~~ 21 bytes ``` ri_{\s2ew::-:zsi_@+}h ``` Note that this program exits with an error, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4781). With the Java interpreter, errors can be suppressed by closing STDERR. If you try this code online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_%7B%5Cs2ew%3A%3A-%3Azsi_%40%2B%7Dh&input=8675309), ignore all output before the last line. *Thanks to @Sp3000 for pointing out an error in the original revision.* *Thanks to @MartinBüttner for golfing off 1 byte.* ### Example run ``` $ cjam digit-difference.cjam 2>&- <<< 8675309 8898683 ``` ### How it works ``` ri_ e# Read an integer (I) from STDIN and push a copy (A). { e# Do: \ e# Swap I on top of A. s e# Cast I to string. e# For example, 123 -> "123". 2ew e# Push the overlapping slices of length 2 (pair of adjacent digits). ::- e# Replace each pair by its difference. :z e# Apply absolute value to each difference. si e# Cast to string, then to integer. This is the new I. e# For example, [1 2 3] -> "123" -> 123. _ e# Push a copy of I. @ e# Rotate A on top of the copy of I. + e# Add I to A, updating A. }h e# While A is truthy, repeat the loop. ``` **A** will always be truthy when checked by `h`. However, once **I** is a single-digit integer, `2ew` will fail with an error after consuming the array it was called on. This leaves only the desired result on the stack, which is printed before exiting. [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), ~~176~~ ~~134~~ ~~127~~ ~~119~~ ~~103~~ ~~97~~ ~~88~~ ~~82~~ ~~79~~ ~~76~~ 72 bytes *Thanks to Sp3000 for saving 1 byte and paving the way for 2 more.* This could probably still be shortened, but hey, it beats ~~Java~~ ~~Matlab~~ Python... ``` ? _ )/:}+{:`};! 9 " _ :}-"" :_10 ;;{: `" " : { (_:/=%} 0+;`" ``` [Try it online.](http://labyrinth.tryitonline.net/#code=PwpfCikvOn0rezpgfTshCjkgICAgICAgIgpfIDp9LSIiIDpfMTAKOzt7OiBgIiAiICA6CiAgeyAgKF86Lz0lfQogIDArO2Ai&input=ODY3NTMwOQ) This [terminates with an error](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781) but the error message is written to STDERR (which is why you don't see it in TIO). The implementation is fairly straight-forward. We add the current value to a running total. If the current value was greater than `9`, we compute its base-10 digits (via repeated div-mod), and form a new number from the absolute differences. If we get to `9` or less, we print the running total. The digits of the current number are collected on the auxiliary stack with the most significant digit on top. Well, the fancy implementation of `abs(...)` I had here turned out to be ridiculously complicated compared to the new solution... I'll add an updated explanation when I'm done golfing this further. [Answer] # [Julia 0.4](http://julialang.org/), ~~81~~ 60 bytes ``` n->(s=n;while n>9 s+=n=int(join(abs(diff(["$n"...]))))end;s) ``` Ungolfed: ``` function f(n::Int) # Initialize a sum to the input s = n while n > 9 # Get absolute values of the pairwise differences of the # digits of n, join as a string, convert it to an integer, # and reassign n n = int(join(abs(diff(["$n"...])))) # ["$n"...] actually splits n as a string into a vector # of its characters, but the difference between ASCII # codes is the same as the difference between the numbers # so it works as expected # Add the new n to the running sum s += n end # Return the sum return s end ``` [Try it online!](https://tio.run/##DcsxCoQwEEbh3lMMssUEMcRSJbmIbKHo4Ej4FaPs8bP56veON@qcxWe0gZPH@Ns1boTQU2o8vOLh41TwvCReVYSn@oPaWvs1xYZ1TCbLeZOSgrqhc85VVFx3eSNYWI2pSpj/ "Julia 0.4 – Try It Online") Saved 21 bytes thanks to feersum and Glen O! [Answer] ## Java - 300 bytes Golfed Version ``` static Long t=new Scanner(System.in).nextLong();static char[]c=t.toString().toCharArray();public static void main(String[]z){while(c.length>1)s();System.out.print(t);}static void s(){String s="";for(int i=0;i<c.length-1;)s+=Math.abs(c[i]-c[++i]);Long a=new Long(s);t+=a;c=a.toString().toCharArray();} ``` Ungolfed / Full version ``` import java.util.Scanner; public class DigitDifference { static Long t = new Scanner(System.in).nextLong(); static char[] c = t.toString().toCharArray(); public static void main(String[] args){ while( c.length > 1 ) s(); System.out.print(t); } static void s(){ String s=""; for(int i = 0; i < c.length-1;) s += Math.abs(c[i]-c[++i]); Long a = new Long(s); t += a; c = a.toString().toCharArray(); } } ``` [Answer] # [oK](http://johnearnest.github.io/ok/index.html), ~~37~~ ~~32~~ ~~24~~ 23 bytes ``` +/(10/{%x*x}1_-':.:'$)\ ``` In action: ``` +/(10/{%x*x}1_-':.:'$)\8675309 8898683 (+/(10/{%x*x}1_-':.:'$)\)'!20 0 1 2 3 4 5 6 7 8 9 11 11 13 15 17 19 21 23 25 27 ``` K5 has a few features which are well suited to this- "encode" and "decode" can perform base conversion, each-pair (`':`) pairs up sequential elements in a list and fixed point scan (`\`) can produce the iterated sequence until it stops changing. The lack of a primitive `abs()` leads to some unsightly bulk in the form of `{(x;-x)x<0}'`, though. ## Edit: Instead of `{(x;-x)x<0}'`, I can (somewhat wastefully) take the square root of the square of the sequence (`{%x*x}`, saving 5 bytes. ## Edit 2: Inspired by @maurinus' APL solution, I can replace the "decode" (`((#$x)#10)\x`) with evaluating each character of the string representation of the number- `.:'$x`! This also lets me use a tacit form of the whole expression, saving additional characters. [Answer] ## Python 2, 87 bytes ``` f=lambda n:n and n+f(int('0'+''.join(`abs(int(a)-int(b))`for a,b in zip(`n`,`n`[1:])))) ``` Recursively adds the current number and takes the digits differences. Lots of converting between numbers and strings. Probably can be improved. [Answer] # Julia, ~~55~~ 48 bytes ``` h=n->(n>9&&h(int(join(abs(diff(["$n"...]))))))+n ``` Ungolfed: ``` function h(n) if n>9 # If multiple digits, find the digit difference... digitdiff=int(join(abs(diff(["$n"...])))) # ... recurse the function... downsum=h(digitdiff) # ... and return the sum so far (working up from the bottom) return downsum+n else # If single digit, no further recursion, return the current number return n end end ``` Essentially, this recurses down to the single-digit level (where no digit difference can be performed), then sums back up as it exits the recursion, level by level. [Answer] # APL (22) ``` {⍵≤9:⍵⋄⍵+∇10⊥|2-/⍎¨⍕⍵} ``` Explanation: * `⍵≤9:⍵`: if ⍵ ≤ 9, return ⍵ unchanged. * `⍎¨⍕⍵`: convert ⍵ to a string, then evaluate each character * `2-/`: subtract every two adjacent numbers * `|`: take the absolute values * `10⊥`: turn the array into a base-10 number * `⍵+∇`: call the function recursively with this new value, and add the result to the input [Answer] # Mathematica, ~~72~~ ~~69~~ 65 bytes ``` Tr@FixedPointList[FromDigits@*Abs@*Differences@*IntegerDigits,#]& ``` I'm open to suggestions here. [Answer] # Haskell, 140 bytes `d` does the job. ``` import Data.Char d n=sum.m(read.m intToDigit).fst.span(/=[]).iterate s.m digitToInt.show$n s l@(h:t)=snd$span(==0)$m abs$zipWith(-)l t m=map ``` Does anyone know how to avoid importing the long conversion functions? [Answer] # K5, 50 bytes ``` +/{(r;x)@~r:.,/"0",{$(0;-r;r)@(~^r)+0<r:x-y}':$x}\ ``` [Answer] # JavaScript ES6, 73 bytes ``` t=n=>(b=10,M=Math).ceil(n&&n+t((j=n=>n>9&&M.abs(n%b-n/b%b)+b*j(n/b))(n))) ``` This isn't getting any shorter :/ I'll try more approaches but this is the shortest one so far [Answer] # JavaScript (ES6), 69 Test running the snippet below in an EcmaScript 6 compliant browser (but not Chrome as it still does not support the spread operator `...`) MS Edge maybe? ``` f=n=>n&&(n+=r='',[...n].map(d=>(r+=d>p?d-p:p-d,p=d),p=n[0]),+n+f(+r)) function test() { var i=+I.value O.innerHTML = i+' -> '+f(i) + '\n' + O.innerHTML } ``` ``` <input id=I value=8675309><button onclick=test()>-></button> <pre id=O></pre> ``` Alternative, using *array comprehension* that is now targeted EcmaScript 2016 (ES7), 67 bytes: ``` f=n=>n&&(n+=r='',p=n[0],[for(d of n)(r+=d>p?d-p:p-d,p=d)],+n+f(+r)) ``` [Answer] # Python 3, 125 bytes I used to like the shortness of regex until I tried to use it for this challenge...`re.findall('\d\d',s,overlapped=True)` is *not* on ;) ``` s=input() p=int x=p(s) while p(s)>9:g=str(s);s=p(''.join(str(abs(p(g[i])-p(g[i+1])))for i in range(len(g)-1)));x+=s print(x) ``` Cheers @Todd :) [Answer] # [Perl 5](https://www.perl.org/) `-p`, 49 bytes ``` $\+=$_;s/.(?=(.))/abs$&-$1/ge;s/^0+|.$//g&&redo}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWJd66WF9Pw95WQ09TUz8xqVhFTVfFUD89FSgcZ6Bdo6eir5@uplaUmpJfW/3/v4WZuamxgeW//IKSzPy84v@6vqZ6BoYG/3ULAA "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ 7 bytes ``` ≬¯ṅ⌊İ∑+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiazCr+G5heKMisSw4oiRKyIsIiIsIjg2NzUzMDkiXQ==) *-5 bytes thanks to allxy* ## How? ``` ≬¯ṅ⌊İ∑+ # full program ≬¯ṅ⌊ # Three element lambda ¯ # Deltas (consecutive differences of digits) ṅ # Join by nothing ⌊ # Convert to integer İ # Apply this lambda on the (implicit) input and collect unique values ∑ # Summate + # Add to (implicit) input ``` [Answer] # J, 70 bytes ``` +/([:10&#.[:(2|@:-/\])[:10&(]#:~[#~[:>.[^.])])`]@.(11&>)^:a:".(1!:1)3 ``` [Answer] ## MATLAB ~~(141)~~(137) > > **EDIT:** 4 bytes less, thanks to @Andras > > > ``` function[s j]=n(T,b,c),if(T/b>9),u=fix(T/10);[x e]=n(T,b*10,0);y=n(u,b,0);[w z]=n(u,b,c);s=abs(x-y);j=s+e+10*c*z;else,s=mod(T,10);j=s;end ``` * This doest beat @LuisMendo 's answer but atleast I could reduce execution time, which by, I would have just tried to diversify ways of tackling this problem. * I could reduce it more but as I go for less time, i waste more bytes, so here is the principle: The program is summing up digits of same row before inlined digits , it does mean it used integer division "n/10" log\_10(n) times only, complexity is O(N). If `n= a b c d` ``` a b c d |a-b| |b-c| |c-d| ||a-b|-|b-c|| ||b-c|-|c-d|| .... ``` My program calculates: ``` a+|a-b| + | |a-b|-|b-c| | + | | |a-b|-|b-c| | - | |b-c|-|c-d| | | +10*( b+|b-c| + | |b-c|-|c-d| | +10*( c+|c-d| +10*( d ) ) ) ``` ## Usage: ``` [a b]=n(13652,1,1) ``` a = 1 ``` b = 16098 ``` [Answer] # Prolog, 143 bytes **Code:** ``` q(X,N):-X<9,N=0;A is abs(X mod 10-X//10 mod 10),Y is X//10,q(Y,M),N is A+M*10. r(X,N):-X<9,N=X;q(X,Y),r(Y,M),N is X+M. p(X):-r(X,N),write(N). ``` **Explained:** ``` q(X,N):-X<9,N=0; % If only one digit, the difference is 0 A is abs(X mod 10-X//10 mod 10),Y is X//10,q(Y,M),N is A+M*10. % Else, the difference is the difference between the last 2 digits + the recursive difference of the number without the last digit r(X,N):-X<9,N=X; % If we only have 1 digit the final answer is that digit q(X,Y),r(Y,M),N is X+M. % Else, the final answer is the current number + the recursive difference of that number p(X):-r(X,N),write(N). ``` **q** does the calculations that convert a number into it's Digit Difference. **r** recursively calls **q** and sums up the results to find the Digit Difference Sum. **p** is the entry point. Takes a number, calls **r** and prints the answer. **Example:** ``` >p(8675309). 8898683 ``` Try it online [here](http://swish.swi-prolog.org/p/FEbBzrgH.pl). [Answer] # PHP - 198 bytes ``` <?$x=$t=$_GET['V'];function z($x){global$t;for($i=0;$i<strlen($x)-1;$i++){$z=str_split($x);$r.=str_replace('-','',$z[$i]-$z[$i+1]);}$r=ltrim($r,'0');$t+=$r;return strlen($r)>1?z($r):0;}z($x);echo$t; ``` Ungolfed ``` <? $x=$t=$_GET['V']; // Gets the value from input function z($x){ global$t; for($i=0;$i<strlen($x)-1;$i++){ $z=str_split($x); //Turns the string into an array $r.=str_replace('-','',$z[$i]-$z[$i+1]); // Sums the two values and removes the minus signal } $r=ltrim($r,'0'); // Remove trailing zeroes $t+=$r; // Adds to global var return strlen($r)>1?z($r):0; // Checks the size of the string. If >1, calls the function again } z($x); echo$t; ``` [Answer] ## [Perl 6](http://perl6.org), 56 bytes ``` {[+] $_,{+.comb.rotor(2=>-1)».map((*-*).abs).join}…0} # 56 bytes ``` usage: ``` my &code = {...} # insert code from above (180..190).map: &code; # (259 258 259 260 261 262 263 264 265 266 280) say code 8675309; # 8898683 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ạƝḌ$ƬS ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//4bqhxp3huIwkxqxT/zg2NzUzMDk7MjDhuLbCpDvDhyTigqxH/w "Jelly – Try It Online") ## How it works ``` ạƝḌ$ƬS - Main link. Takes an integer n on the left $Ƭ - Repeat the following until a repeated value, collected intermediate results: Ɲ - Convert an integer to digits, and on overlapping pairs: ạ - Take the absolute difference Ḍ - Convert from digits to an integer S - Take the sum of these values ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ΣU¡ȯdẊ≠d ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///Oo1XCocivZOG6iuKJoGT///84Njc1MzA5 "Husk – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Èìä'a}hN ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=yOzkJ2F9aE4&input=MTAyNA) [Answer] # [Factor](https://factorcode.org) + `math.extras project-euler.common`, ~~83~~ 81 bytes ``` [ 0 swap [ [ + ] keep number>digits differences vabs digits>number ] until-zero ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JY47DsIwDIZ3TuEdtUJMCFBXxIKEEBNiCKkDgeaB4_C6CksXuFNvQ0pkyY_fn3_5_VVCsqO2e2w3y9ViChckiw0YccGU-FTesAdCHgIL1oG1DODJndOqwNggldIZ42yG8MEkegCZn5605b8OAa8RrcQAs8FgPIK5diyqT2RVTLr1DkYQ7sLDLsUQ9ukT9GCjOSBVtT5qDlBrpZCyx00ceqHXq0ylm2hZN8ULycE-G39Msixz37a5_gA) * `0 swap` Initialize the sum. * `[ ... ] until-zero` Call a quotation until its result is 0, dropping the 0 from the stack. * `[ + ] keep` Add the current summand to our sum. * `number>digits differences vabs digits>number` Get the next summand. [Answer] # C 162 bytes golfed: ``` main(int argc,char **argv){char *c=argv[1];int u=atoi(c),d;do{while(c[1]!=0){*c=abs(*c-*(c+1))+48;c++;}*c=0;c=argv[1];d=atoi(c);u+=d;}while(d>9);printf("%d",u);} ``` ungolfed: ``` main(int argc, char **argv) { char *c=argv[1]; int u=atoi(c),d; do { while(c[1]!=0) { *c=abs(*c-*(c+1))+48; c++; } *c=0; c=argv[1]; d=atoi(c); u+=d; } while(d>9); printf("%d\n",u); } ``` [Answer] # R, 134 Bytes ### Code ``` f=function(x){z=x;while(z>9){n=seq(nchar(z));z=abs(diff(strtoi(substring(z,n,n))));z=sum(z*10**(rev(seq(length(z)))-1));x=x+z};cat(k)} ``` Test it [online](http://www.r-fiddle.org/#/fiddle?id=iX6pcHCs&version=3). ### Ungolfed ``` f=function(x){ z=x; while(z>9){ n=seq(nchar(z)); z=abs(diff(strtoi(substring(z,n,n)))); z=sum(z*10**(rev(seq(length(z)))-1)); x=x+z }; cat(x) } ``` Here is the plot of the difference of the "Digit Difference Sum of a Number" series from f(1) to f(1m). Just because I love to diff. ![](https://i.stack.imgur.com/jVL2a.png) ### Plot code ``` s <- seq(1,100000) serie <- sapply(s,f) plot(diff(ts(serie)),xlab="",ylab="") ``` ]
[Question] [ ## Challenge Given an ASCII representation of a Babylonian number as input, output the number in Western Arabic numerals. ## Babylonian Numeral System How did the Babylonians count? Interestingly, they used a Base 60 system with an element of a Base 10 system. Let's first consider the unit column of the system: The Babylonians had only three symbols: `T` (or, if you can render it: `𒐕`) which represented 1, and `<` (or, if you can render it: `𒌋`) which represented 10, and `\` (or, if you render it: `𒑊`) which represented zero. **Note:** Technically, `\` (or `𒑊`) isn't zero (because the Babylonians did not have a notion of 'zero'). 'Zero' was invented later, so `\` was a placeholder symbol added later to prevent ambiguity. However, for the purposes of this challenge, it's enough to consider `\` as zero So, in each column you just add up the value of the symbols, e.g.: ``` <<< = 30 <<<<TTTTTT = 46 TTTTTTTTT = 9 \ = 0 ``` There will never be more than five `<` or more than nine `T` in each column. `\` will always appear alone in the column. Now, we need to extend this to adding more columns. This works exactly the same as any other base sixty, where you multiply the value of the rightmost column by \$60^0\$, the one to the left by \$60^1\$, the one to the left by \$60^2\$ and so on. You then add up the value of each to get the value of the number. Columns will be separated by spaces to prevent ambiguity. Some examples: ``` << <TT = 20*60 + 12*1 = 1212 <<<TT \ TTTT = 32*60^2 + 0*60 + 4*1 = 115204 ``` ## Rules * You are free to accept either ASCII input (`T<\`) or Unicode input (`𒐕𒌋𒑊`) * The inputted number will always be under \$10^7\$ * The `<`s will always be to the left of the `T`s in each column * `\` will always appear alone in a column ## Winning Shortest code in bytes wins. [Answer] # JavaScript (ES6), 44 bytes Takes input as an array of ASCII characters. ``` a=>a.map(c=>k+=c<1?k*59:c<'?'?10:c<{},k=0)|k ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPZ1i5b2zbZxtA@W8vU0irZRt1e3d7QAMiortXJtjXQrMn@n5yfV5yfk6qXk5@ukaYRraenp2RjY6MUq6mpgAT09RWMDbiwq7UJAQO4FqBaEzNsakNgAGE6UK0lNqUxMeguACnF4QIFG2QjIUoNjQyNcLg3JEQhJkYB4Q6QakNTIwOT/wA "JavaScript (Node.js) – Try It Online") ### How? The Babylonian Numeral System can be seen as a 4-instruction language working with a single register -- let's call it the accumulator. Starting with \$k=0\$, each character \$c\$ in the input array \$a\$ modifies the accumulator \$k\$ as follows: * `space`: multiply \$k\$ by \$60\$ (implemented as: add \$59k\$ to \$k\$) * `<`: add \$10\$ to \$k\$ * `T`: increment \$k\$ * `\`: do nothing; this is the `NOP` instruction of this language (implemented as: add \$0\$ to \$k\$) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~140~~ ~~138~~ 136 bytes * Saved two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` B,a,b,y;l(char*o){y=B=0,a=1;for(char*n=o;*n;n++,B++[o]=b,a*=60)for(b=0;*n&&*n-32;n++)b+=*n-84?*n-60?:10:1;for(B=a;B/=60;y+=*o++*B);B=y;} ``` [Try it online!](https://tio.run/##LY3BboMwEETPzVdYVIm82FFxW6EqyyqSfwGfaHIwDrRIxI5ILgjx7dRJelnNzL6dddsf55ZFSytrOWLP3a8d0gDTSJoyaUlhG4Zn6ilg6tELIbUQ3@FItbQp5RnckZqyuN1sUr/9eL9DUAuK5utzH2ee7Xcq2z3bNFnUb/EQx4gEIVINqGnEeXk9NW3nG2Z4CdPja0Vn2/fB8ett6Bsfc6EAo3GXkVeyBLwMnb@1PFkrdWXE1vnp4BNZyp5XANgOTRMFzquz7TyHafVieFIUrDAmgX8TNTswYx7RvPwB "C (gcc) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes *-3 bytes thanks to nwellnhof* ``` {:60[.words>>.&{sum .ords X%151 X%27}]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9rKzCBarzy/KKXYzk5Prbq4NFdBD8RTiFA1NDUEkkbmtbG1/4sTKxXSNJRsbGyU9EqKEvOKNZRCbGJilGztlD5MmjD1w6Se7g@TJnYpaWpacyHU2oSAgQLRekJggFgd6jEx6sQ7SMGGeJOVwM5XiIlRIM49///rpgAA "Perl 6 – Try It Online") Uses the cuneiform characters. ### Explanation: ``` { } # Anonymous code block .words # Split input on spaces >>.&{ } # Convert each value to sum # The sum of: .ords # The codepoints X%151 X%27 # Converted to 0,1 and 10 through modulo :60[ ] # Convert the list of values to base 60 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 13 ~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḲO%7C%13§ḅ60 ``` A monadic link accepting a list of characters which yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///hjk3@qubOqobGh5Y/3NFqZvD//38bG5uQEIUYhRAgAAA "Jelly – Try It Online")** ### How? ``` ḲO%7C%13§ḅ60 - Link: list of characters e.g. "<<<TT \ TTTT" Ḳ - split at spaces ["<<<TT", "\", "TTTT"] O - cast to ordinals [[60,60,60,84,84],[92],[84,84,84,84]] %7 - modulo by seven (vectorises) [[4,4,4,0,0],[1],[0,0,0,0]] C - compliment (1-X) [[-3,-3,-3,1,1],[0],[1,1,1,1]] %13 - modulo by thirteen [[10,10,10,1,1],[0],[1,1,1,1]] § - sum each [32,0,4] ḅ60 - convert from base sixty 115204 ``` --- Another 12: [`ḲO⁽¡€%:5§ḅ60`](https://tio.run/##y0rNyan8///hjk3@jxr3Hlr4qGmNqpXpoeUPd7SaGfz//9/GxiYkRCFGIQQIAA "Jelly – Try It Online") (`⁽¡€` is `1013`, so this modulos `1013` by the `O`rdinal values getting `53`, `5`, and `1` for `<`, `T`, `\` respectively then performs integer division, `:` by `5` to get `10`, `1` and `0`) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` 8740|Ç%4/O60β ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fwtzEoOZwu6qJvr@ZwblN///b2NiEhHDFcIUAAQA "05AB1E – Try It Online") To make up for [how lazy](https://chat.stackexchange.com/transcript/message/46178902#46178902) I've been with my Jelly answer, here is a submission in 05AB1E xD. [Answer] # [Python 2](https://docs.python.org/2/), ~~96~~ ~~93~~ ~~87~~ 85 bytes ``` lambda s:sum(60**i*sum(8740%ord(c)/4for c in v)for i,v in enumerate(s.split()[::-1])) ``` [Try it online!](https://tio.run/##Tci9DsIgFEDh3ae4iymXWK2m0YbgW7BZB2whkpSfAG3i06Nsbud84ZPf3l2Kvo9lkfY1S0gsrZZcO0oNrTXc@m7v40wmPPXaR5jAONiwpjlsdZRbrYoyK5KOKSwmE3ww1p6fiCVE4zJo0nAOXIgGd3/yAxhBiOrlCw "Python 2 – Try It Online") --- Saved: * -1 byte, thanks to Mr. Xcoder * -4 bytes, thanks to Poon Levi * -2 bytes, thanks to Matthew Jensen [Answer] # Excel VBA, 121 bytes Restricted to 32-Bit Office as `^` serves as the `LongLong` type literal in 64-Bit versions Takes input from cell `A1` and outputs to the vbe immediate window. ``` a=Split([A1]):u=UBound(a):For i=0 To u:v=a(i):j=InStrRev(v,"<"):s=s+(j*10-(InStr(1,v,"T")>0)*(Len(v)-j))*60^(u-i):Next:?s ``` ### Ungolfed and Commented ``` a=Split([A1]) '' Split input into array u=UBound(a) '' Get length of array For i=0 To u '' Iter from 0 to length v=a(i) '' Get i'th column of input j=InStrRev(v,"<") '' Get count of <'s in input '' Multiply count of <'s by 10; check for any T's, if present '' add count of T's t=t+(j*10-(InStr(1,v,"T")>0)*(Len(v)-j)) *60^(u-i) '' Multiply by base Next '' Loop ?s '' Output to the VBE immediate window ``` [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~33~~ 30 bytes ``` {+/(⌊10*⍵-3)×60*+\2=⍵}'\ T<'⍳⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqbX2NRz1dhgZaj3q36hprHp5uZqClHWNkC@TWqscohNioP@rd/KhnL1C5grqNjU1IiAJQFAjUAQ "Dyalog APL – Try It Online") **Edit:** -3 bytes thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn) `'\ T<'⍳` replaces the characters with numbers (their position in the string constant), and `⌽` reverses the input so most significant 'digits' are last. This allows `+\2=` to keep a running count of the desired power of 60 (applied by `60*`) by counting the number of times a space (index 2 in the string constant) is encountered. `⌊10*⍵-3` gives the desired power of ten for each character. The order of characters in the string constant and the -3 offset cause '\' and space to go to negative numbers, resulting in fractions when those characters are raised to the power of 10, allowing them to be eliminated by `⌊`. All we have to do now is multiply the powers-of-10 digits by the powers-of-60 place values and sum the lot up with `+/`. [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` lambda s:reduce(lambda x,y:x+[10,0,59*x,1]["<\ ".find(y)],s,0) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqig1pTQ5VQPKr9CptKrQjjY00DHQMbXUqtAxjI1WsolRUNJLy8xL0ajUjNUp1jHQ/F9QlJlXopCmoW5jY6OuyYXMtQkBA2TREBhAFoyJQdWoYIMqDzZJIUYBou8/AA "Python 2 – Try It Online") This uses the technique from [Arnauld's answer](https://codegolf.stackexchange.com/a/170553/76162). [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~20~~ ~~17~~ 16 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` S{{<≡AײT≡]∑]<c┴ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjMzJXVGRjVCJXVGRjVCJTNDJXUyMjYxJXVGRjIxJUQ3JUIyVCV1MjI2MSV1RkYzRCV1MjIxMSV1RkYzRCUzQyV1RkY0MyV1MjUzNA__,i=JTNDJTNDJTNDVFQlMjAlNUMlMjBUVFRU,v=6) Explanation: ``` E{ ] map over input split on spaces { ] map over the characters <≡A× (x=="<") * 10 ²T≡ x=="T" ∑ sum all of the results <c┴ and encode from base (codepoint of "<") to 10 ``` [Answer] # APL(NARS ⎕io←0), 28 chars, 56 bytes ``` {60⊥{+/⍵⍳⍨10⍴'\T'}¨⍵⊂⍨⍵≠' '} ``` some test with type check: ``` q←{60⊥{+/⍵⍳⍨10⍴'\T'}¨⍵⊂⍨⍵≠' '} o←⎕fmt o q '<< <TT' 1212 ~~~~ o q '<<<TT \ TTTT' 115204 ~~~~~~ ``` Each type result is number. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~122~~ ~~114~~ ~~107~~ ~~106~~ 83 bytes ``` a=>a.split` `.map(b=>[...b].map(c=>x+=c<'T'?10:c<'U',x=0)&&x).reduce((a,b)=>a*60+b) ``` [Try it online!](https://tio.run/##bc7RCoIwGAXg@55idKFb2pxmQrHZS6yrDJxTwzAVtfDtTQ1FzHP1Dz7O2VN8RCXLpKj3WR5GbcxawVyBqyJNah/4@CUKGDD3hjEO7sNLMrfRmKQqVy8mOXfHVdUbRpCiNAiXUfiWEYRCD1BXtHOIFqBW5lmVpxFO8weM4ZZSukUIzGIY4EA2/4zyIaPumO0sGR8zdXbstFSet5js1cokoLOinzIt01r5G@fA88A03EPzaBG7/QI "JavaScript (Node.js) – Try It Online") I'm a little obsessed with "functional-style" array operations, uses ASCII input, as far as I can tell, JS isn't very good at getting charcodes golfily I'm keeping this for posterity's sake, but this is a naive/dumb solution, I suggest you check out [Arnauld's answer](https://codegolf.stackexchange.com/a/170553/44998) which is far more interesting an implementation of the challenge [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~29~~ ~~26~~ 23 bytes ``` < 10*T +`^(.*)¶ 60*$1 T ``` [Try it online!](https://tio.run/##K0otycxLNPyvqhGcoPDfhsvQQCuESzshTkNPS/PQNi4zAy0VQ66Q//9tbBRsQkK4bGyApEKMQggQAAA "Retina – Try It Online") Uses newline separation, but link includes header to use spaces instead for convenience. Edit: Saved 3 bytes with help from @KevinCruijssen. Saved a further 3 bytes thanks to @FryAmTheEggman. Explanation: ``` < 10*T ``` Replace each `<` with 10 `T`s. ``` +`^(.*)¶ 60*$1 ``` Take the first line, multiply it by 60, and add the next line. Then repeat until there is only one line left. ``` T ``` Count the `T`s. Faster 51-byte version: ``` %`^(<*)(T*).* $.(10*$1$2 +`^(.+)¶(.+) $.($1*60*_$2* ``` [Try it online!](https://tio.run/##K0otycxLNPyvqhGcoPBfNSFOw0ZLUyNES1NPi0tFT8PQQEvFUMWISxsooaeteWgbiARJqBhqmRloxasYaf3/b2OjYBMSwmVjAyQVYhRCgAAA "Retina – Try It Online") Uses newline separation, but link includes header to use spaces instead for convenience. Explanation: ``` %`^(<*)(T*).* $.(10*$1$2 ``` Match each line individually, and count the number of `T`s and 10 times the number of `<`s. This converts each line into its base-60 "digit" value. ``` +`^(.+)¶(.+) $.($1*60*_$2* ``` Base 60 conversion, running a line at a time. The computation is done in decimal for speed. [Answer] # [Bash](https://www.gnu.org/software/bash/) (with sed and dc), 50 bytes ``` sed 's/</A+/g s/T/1+/g s/ /60*/g s/\\//g'|dc -ez?p ``` Takes space-delimited input from `stdin`, outputs to `stdout` [Try it online!](https://tio.run/##S0oszvj/vzg1RUG9WN9G31FbP52rWD9E3xDCUNA3M9ACs2Ji9PXT1WtSkhV0U6vsC/7/twGCEDAAAA "Bash – Try It Online") # Explanation Uses sed to transform the input with a bunch of regular expression matches until, for example, the input `<<<TT \ TTTT` has been transformed to `A+A+A+1+1+60*60*1+1+1+1+`. Then this input is fed to dc with the explicit input execution command `?`, preceded by `z` (pushes the stack length (0) to the stack so that we have somewhere to ground the addition) and followed by `p` (print). [Answer] # [J](http://jsoftware.com/), 34 30 bytes ``` 60#.1#.^:2(10 1*'<T'=/])&>@cut ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/MQFnPUFkvzspIw9BAwVBL3SZE3VY/VlPNziG5tOS/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCuo2NjToyxyYEDBBiMcjSCjbIUmDVCjEKYA3/AQ "J – Try It Online") [Answer] # Dyalog APL, ~~35~~ 32 bytes ``` f←{⍵+('<T\ '⍳⍺)⌷10,1,0,59×⍵}/∘⌽0∘, ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71btTXUbUJiFNQf9W5@1LtL81HPdkMDHUMdAx1Ty8PTgfK1@o86Zjzq2WsApHSA2hTUbWxsQkIUYhRCgEAdAA "APL (Dyalog Unicode) – Try It Online") [31](https://tio.run/##SyzI0U2pSszMTfz/P@1R24TqR71btTXUbUJiFNQf9W5@1LtL81HPdkMDHUMdAx1Ty8PTgfK1@o86Zjzq2WugA9SjoG5jYxMSohCjEAIE6v/yC0oy8/OK/@sWAwA) in dzaima/APL [Answer] # [Noether](https://github.com/beta-decay/Noether), 55 bytes ``` I~sL(si/~c{"<"=}{k10+~k}c{"T"=}{!k}c{" "=}{k60*~k}!i)kP ``` [Try it online!](https://tio.run/##y8tPLclILfr/37Ou2EejOFO/LrlayUbJtrY629BAuy67FsgNAXEVwUwFsIyZgRZQRjFTMzvg/38lGxubkBCFGIUQIFACAA "Noether – Try It Online") Same approach as @Arnauld. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ≔⁰θFS«≡ι ≦×⁶⁰θ<≦⁺χθT≦⊕θ»Iθ ``` [Try it online!](https://tio.run/##Zc4xC8IwEAXg2fyKo9MFFHRxsFnESVAomNElxLQNtGmbXHWQ/vYYtIPi2x58dzxdK6871cS4D8FWDtdLGHjOys4DHl0/0oW8dRVyDk@2CA9Luga076ZVMJBBtoOz6j/3J1MSStuasITt/Gt24s8VzZjY5pfJb5YmaG9a48jcZjWxiRVpEuFBBcKB8zxGIYSUcAWZwuLq3qgX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰θ ``` Clear the result. ``` FS«...» ``` Loop over the input characters. The `≡` command is wrapped in a block to prevent it from finding a "default" block. ``` ≡ι ``` Switch over the current character... ``` ≦×⁶⁰θ ``` if it's a space then multiply the result by 60... ``` <≦⁺χθ ``` if it's a `<` then add 10 to the result... ``` T≦⊕θ ``` if it's a `T` then increment the result. ``` Iθ ``` Print the result. [Answer] # [R](https://www.r-project.org/), ~~98~~ 81 bytes ``` (u=sapply(scan(,""),function(x,y=utf8ToInt(x))y%%3%*%(y%%6)))%*%60^(sum(u|1):1-1) ``` [Try it online!](https://tio.run/##jU/baoNAEH33K4YJwkzZQtY2UoJ@QN63bxIQqTSQrKK7IUK/IPHBCv6nf2BWpPTy1Kc5wzln5pxqWoEpICv0@a0yM3w1@YuXx7nVmTkUmi6cvaeVqQhVlCQocOy7Yezb29h/XlFc2MsJowgipZBhBbhw7Q0WMIu7AR0jAxksYqeFJAGl/np@WmB@AF/br0NyE6yfJ7JxnZblsaE6SzUJRBbfsUUTW1dFFTttXAlufP/Jf/DJzZCZHQzXe6rtieyH5K18lDz9P8Z0Bw "R – Try It Online") ~~Ridiculously long due to string parsing.~~ Thanks Giusppe for shaving off 16 unnecessary bytes. Define `y` the bytecode value of unicode input and `R = y("T<\") = y("𒐕𒌋𒑊")` Observe that `R%%3 = 1,2,0` and `R%%6 = 1,5,0`... so `R%%3 * R%%6 = 1,10,0` ! The rest is easy: sum per column, then dot-product with decreasing powers of 60. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ 46 bytes ``` ->a{x=0;a.bytes{|c|x+=[59*x,10,0,1][c%9%5]};x} ``` [Try it online!](https://tio.run/##NYqxCoAgFAD3vkKClrKwoSF69hVt6mBSNEYZKOq3Gxrdchzc9aw27jS2s3SGkkl2q9Xb7bzypqFsGGuDe4IJ7gVT1VgNIkwmRFYCQImLJFgyqZafFJx/A4Kv84k4R3kQ3SbV4bz2J9qZFiG@ "Ruby – Try It Online") A basic port of [Arnauld's answer](https://codegolf.stackexchange.com/a/170553/78274) improved by G B for -4 bytes. [Answer] # [C (gcc)](https://gcc.gnu.org/), 65 64 63 bytes ``` f(s,o)char*s;{for(o=0;*s;s++)o+=*s>32?(93^*s)/9:o*59;return o;} ``` [Try it online!](https://tio.run/##VY9fC4IwFMXf/RSXgbCpUSQ92NS@xB5HICtrD22xa0GIn31NI3Bv55z7h99Rm5tS3vcUC8vUvXMZ8rG3jtpmx4PGPGc2bzJsy/2JVuU5Q7atjjY7VNxdh5czYPnktRng0WlDGYwJwOA@lEhJGP8bsdYQOymjoF5riF1YjYJaQC3E/GJOpyR5W31ZZksXwB/P0wXAPiCRFCWBpoVUS0MKwAJCdTbf@i8 "C (gcc) – Try It Online") [Answer] # Java 8, ~~64~~ 60 bytes ``` a->{int r=0;for(int c:a)r+=c<33?r*59:c<63?10:84/c;return r;} ``` -4 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##lY89T8NADIb3/Aqr0wXUUBRAkLtQIWa6tBthMG4KV9JL5TiVqiq/PVwOOoIUD5b88b5@vMUDTrfrr54qbBp4QetOEYB1UvIGqYTFUIYGkKJP5Nc3wFj7Zhf51AiKJViAgxx6nD6ehk3OZ3pTswqqDGO@zMmk6Zwvbh8yMnfp/HqW3d9ckeZSWnbAuuv14Ldv3yvv92t7qO0adp5JLYWt@wi3f4CWx0bKXVK3kuz9SCqnXEJqYoyZJFI/e9InZjyqOA60/yrMKsRI4eocI3VFMZoQzOgr4SsoCviTsIu6/hs) **Explanation:** ``` a->{ // Method with character-array parameter and integer return-type int r=0; // Result-integer, starting at 0 for(int c:a) // Loop over each character `c` of the input-array r+= // Increase the result by: c<33? // Is the current character `c` a space: r*59 // Increase it by 59 times itself :c<63? // Else-if it's a '<': 10 // Increase it by 10 :c<85? // Else (it's a 'T' or '\'): 84/c; // Increase it by 84 integer-divided by `c`, // (which is 1 for 'T' and 0 for '\') return r;} // Return the result ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 18 [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. ``` 60⊥10⊥¨≠'<T'∘⍧¨⍤⊆⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/38zgUddSQxBxaMWjzgXqNiHqjzpmPOpdDuT2LnnU1faoa9H/tEdtEx719j3qm@rp/6ir@dB640dtE4G84CBnIBni4Rn8P01B3cZGwSYkRJ0LzASyFGIUQoBAHQA "APL (Dyalog Extended) – Try It Online") ``` ⊢ the argument; "<<<TT \ TTTT" ≠ mask where different from space; [1,1,1,1,1,0,1,0,1,1,1,1] ⊆ enclose runs of 1; ["<<<TT","\","TTTT"] ⍤ on that ¨ for each one ⍧ Count the occurrences In it of the elements ∘ of the entire list '<T' ["<","T"]; [[3,2],[0,0],[0,4]] ¨ for each one 10⊥ evaluate as base-10 digits 60⊥ evaluate as base-60 digits ``` [Answer] # Perl -F// -E, 39 bytes ``` $w+=/</?10:/T/?1:/ /?59*$w:0for@F;say$w ``` This reads the to be converted number from STDIN. This is essential the same solution as given by @Arnauld using JavaScript. [Answer] ## F#, 128 bytes ``` let s(v:string)=Seq.mapFoldBack(fun r i->i*Seq.sumBy(fun c->match c with|'<'->10|'T'->1|_->0)r,i*60)(v.Split ' ')1|>fst|>Seq.sum ``` [Try it online!](https://tio.run/##PU/BasMwDL33K0ShOC5zSS87DNeHwnouNLd1FOMlrVjiZLaaUfC/e7YpewcJvfd4kjovzOjaGPuWwFfzmyeH9sp3p/ZnM@jpMPZfe22@q@5uwQEKhess@fuwfxTSCDVoMjcw8It0C0wyobZ1YE3u4SJUzd0Lrl9rXs2b09QjAQPGt0F1noJ6psUP@W7JPY4jWlKfi3zPoNGCdtcZdgtIyFak1kFZnAQQqggZPhP/U1AwpUeos7Bc@TOtcJl1XuKKq45RSpBNk1qqcIYm4Q8) Ungolfed it would look like this: ``` let s (v:string) = Seq.mapFoldBack(fun r i -> i * Seq.sumBy(fun c -> match c with | '<' -> 10 | 'T' ->1 | _ -> 0 ) r, i * 60) (v.Split ' ') 1 |> fst |> Seq.sum ``` `Seq.mapFoldBack` combines `Seq.map` and `Seq.foldBack`. `Seq.mapFoldBack` iterates through the sequence backwards, and threads an accumulator value through the sequence (in this case, `i`). For each element in the sequence, the Babylonian number is computed (by `Seq.sumBy`, which maps each character to a number and totals the result) and then multiplied by `i`. `i` is then multiplied by 60, and this value is then passed to the next item in the sequence. The initial state for the accumulator is 1. For example, the order of calls and results in `Seq.mapFoldBack` for input `<<<TT \ TTTT` would be: ``` (TTTT, 1) -> (4, 60) (\, 60) -> (0, 3600) (<<<TT, 3600) -> (115200, 216000) ``` The function will return a tuple of `seq<int>, int`. The `fst` function returns the first item in that tuple, and `Seq.sum` does the actual summing. ### Why not use `Seq.mapi` or similar? `Seq.mapi` maps each element in the sequence, and provides the index to the mapping function. From there you could do `60 ** index` (where `**` is the power operator in F#). But `**` requires `floats`, not `ints`, which means that you need to either initialise or cast all the values in the function as `float`. The entire function will return a `float`, which (in my opinion) is a little messy. Using `Seq.mapi` it can be done like this for **139 bytes**: ``` let f(v:string)=v.Split ' '|>Seq.rev|>Seq.mapi(fun i r->Seq.sumBy(fun c->match c with|'<'->10.0|'T'->1.0|_->0.0)r*(60.0**float i))|>Seq.sum ``` [Answer] # [Tcl](http://tcl.tk/), 134 bytes ``` proc B l {regsub {\\} $l 0 l lmap c [lreverse $l] {incr s [expr 60**([incr i]-1)*([regexp -all < $c]*10+[regexp -all T $c])]} expr $s} ``` [Try it online!](https://tio.run/##VY8xDoMwDEX3nOIPGQoVEiydMvUMbJABoqhCMhAlUFWKcvY0RBSpf7Kf7W97UxSd3rCs82i1g/dCiMCQdESizTpB@9OZo8fVCnHhPJZquTNEY1eFJwje6pfbR/i@D@CEGsRoHgwUOrL6ra3TiUv4aVEWDp3@GItHXZa3LqNJVk2RkmSUSqgGIghwJcumvv/R9qCFDCxbcBdi3rSAX5/mY82@pT3PhCUL8Qs "Tcl – Try It Online") In the reversed list, I loop incrementing the result in counting `<` and `T` (with `-all` regexp option) and incrementing a natural as power of 60. Correct version (see comment) [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 10 bytes ``` #Ç9%5BO60β ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f@XC7paqpk7@ZwblN//9/mNTTjcATpoKwwodJE7sUYDwYBgA "05AB1E (legacy) – Try It Online") ``` # # split input on spaces Ç # convert each character to its codepoint 9% # modulo 9 (maps 𒌋 to 5, 𒐕 to 1, 𒑊 to 0) 5B # convert each to base 5 (5 becomes 10, 0 and 1 unchanged) O # sum each column 60β # convert from base 60 ``` --- ## [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` #Ç9%5B€O60β ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f@XC7paqp06OmNf5mBuc2/f//YVJPNwJPmArCCh8mTexSgPFgGAA "05AB1E – Try It Online") Same algorithm, but in modern 05AB1E `O` doesn't work on lists of mixed ints and lists, so we need `€O` instead. ]
[Question] [ *Unlike many C&R challenges, this does not require a separate robbers post; the goal of the robbers is to crack the previous answer and then post a new one as a cop.* As answerers, you will write a series of polyglots that look like this (each column is a language, and each entry is the output of the answer in that language): ``` Language: 1 2 3 4 5 6 7 8 ... Answer 1: 0 1 2 Answer 2: 1 2 3 Answer 3: 2 3 4 Answer 4: 3 4 5 Answer 5: 4 5 6 Answer 6: 5 6 7 ... ``` (blank spaces mean that no behavior is required in that case). Each answer should work in 3 languages and print 3 different consecutive numbers which are each one more than the numbers printed by the previous answer (the first answer prints `0`, `1`, and `2`). Each answer uses two languages from the previous submission, and a third new language. The answerer should try to obfuscate what this third language is. To post a new answer, you should: * Crack the most recent answer by finding what its third language is. * Preferably, add an explanation for your crack and notify the poster of the answer. Once your submission has been cracked, you should preferably add an explanation as well. * Write a polyglot consisting of this answer's second and third languages, along with another language of your choice. Reveal your first two languages, but do not reveal your new one. It will be the next poster's goal to find this language (or any other language in which it works), so you should try to obfuscate it. ## Specifications * The criteria for a valid programming language are the same as those of [The Programming Language Quiz, Mark II - Cops](https://codegolf.stackexchange.com/questions/155018/the-programming-language-quiz-mark-ii-): > > > + It has [an English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), [an esolangs article](http://esolangs.org/wiki/Language_list) or [a Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted, or is on [Try It Online!](https://tio.run/#). Having an interpreter linked in any of these pages makes that interpreter completely legal. > + It must satisfy our rules on [what constitutes a programming language](http://meta.codegolf.stackexchange.com/a/2073/8478). > + It must have a free interpreter (as in beer). Free here means that anyone can use the program without having to pay to do so. > * Each answer must run in less than a minute on a reasonable PC. * You *can* reuse programming languages, but there must be at least two answers in between (so an individual answer cannot reuse a language). * Cracking a submission consists of finding *any* programming language that prints the correct result, not just the intended one. If a submission is run in any language that was not declared or found to work, there are no requirements to do anything. * You may not post twice (or more) in a row. ## Winning Criterion The winning answer is whichever answer took to most time to be cracked. The challenge will never end, so it is always possible for the winning answer to change. [Answer] # Hexagony, Klein (101) and ??? ``` xx={puts/} gets87!@xx=p main\ >9.*5,6v ``` This prints [`7` in Hexagony](https://tio.run/##y0itSEzPz6v8/19BoaLCtrqgtKRYv5YrPbWk2MJc0QEoVMDFlZuYmRfDxWVnqadlqmNW9v8/AA "Hexagony – Try It Online"), [`8` in Klein (101)](https://tio.run/##y85Jzcz7/19BoaLCtrqgtKRYv5YrPbWk2MJc0QEoVMDFlZuYmRfDxWVnqadlqmNW9v//f0MDQwA "Klein – Try It Online"), and `9` in ???. The `9` does not work if a newline is added at the end of the code. Be careful if you're testing locally. **Edit:** Being live for 20 hours is already a record, so I'll give some hints from now on. (Also because the language in question is IMO not yet well-known.) ### Hints 1. "The `9` does not work if a newline is added at the end" is *very* significant, as well as the first two spaces (which are ignored by both Hexagony and Klein). 2. The language is on TIO. 3. The first two spaces make the program jump to the last line. (It's *not* a 2D language.) 4. There's no explicit output command, and the `v` command ends the program. ### Explanation ([cracked post](https://codegolf.stackexchange.com/a/171901/78410)) In the source code ``` abcd={} -- a gaffe avoiding tactic in C++/C# abcd[!1]= 1+2+3+4+5+6+7+8+9+10+11+12+13+17! print(abcd[0>1+2+3 and 4+8+6<0-0]//35) if 0>1 then a.next=';' en\ >1+6.@.@ ``` The relevant instructions in Klein (101) are: ``` IP->.....................^...........IP->/ .........................|................... .........................8 .........................\<-.............IP<- @ ``` Klein is fungelike 2D language where crossing the boundary of code area (which is a square) depends on the Klein topology. `/` and `\` are mirrors. The IP starts at upper left corner facing right. It meets a mirror towards the top boundary, and re-enters the code area on the right side as shown above. Then it hits the mirror again, 8 is pushed, and then (after passing through the boundary several times) stops at `@`. Then the content of the stack is printed to stdout, which is single 8. [Answer] # Befunge-96, Hexagony and ??? ``` abcd={} -- a gaffe avoiding tactic in C++/C# abcd[!1]= 1+2+3+4+5+6+7+8+9+10+11+12+13+17! print(abcd[0>1+2+3 and 4+8+6<0-0]//35) if 0>1 then a.next=';' en\ >1+6.@.@ ``` This prints [`6` in Befunge-96](https://tio.run/##bcxLDoIwGATgPacY4gLNnwLlUSSKIeEYyqJAi11YjanGxHh2RNbOdr6ZTumHHRUrBbs4baZJdv1QvT9gDBKj1FpBPq9mMHaEk70zPYxFQxQ1K@@Hjz5vKwCcEkopo5wEFbSlknhMnBNPiKfEC9@73Y1162UTHxYOaQdkMxb7mMVtFKX5xjMacw13VhYytOrlqmAXQNmThz@Zn0RYh/U0fQE), [`7` in hexagony](https://tio.run/##bcxLDoIwGATgfU8xxAWaP0DLU6MYEo6hLCoU6KYY0xiM8ewVWTvb@WZGNcthMi/n5K3tyvcHQQCJQfa9gnxOutNmgJWt1S20QU0U1Rv2wxdPNCUAQTEllFJGORW0pwMJTkKQiEkkJAqP3R/a2O264eeVQ5oO6YLzEw94E0VJtmO6x1LDjspAhkbNtvSPPpS5MvzJ8pSHVVg59wU) and `8` in ???. ### Explanation The hexagony code, when "prettified" is: ``` a b c d = { } - - a g a f f e a v o i d i n g t a c t i c i n C + + a b c d [ f a l s e ] = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 0 + 1 1 + 1 2 + 1 3 + 1 7 ! p r i n t ( a b c d [ 0 > 1 + 2 + 3 a n d 4 + 5 + 6 < 0 - 0 ] / / 3 5 ) i f 0 > 1 t h e n a . n e x t = ' ; ' e n d > 1 + 6 . @ . . . . . . . . . . . . . . . . . . . . . . . . . . ``` The path of execution begins in the top left heading East. The top row doesn't do much. `-` changes the current memory edge so the value in it is `0`. Execution continues heading east on the middle row where `7!` loads `7` in the current memory edge and prints is as an integer. `[` changes the instruction pointer to North East starting back at `7`. After `7+3`, execution then reaches `[` which changes the instruction pointer to North West starting in the South East corner. Finally the path is `..@` where `@` terminates the program. [Answer] # [Trigger](http://yiap.nfshost.com/esoteric/trigger/trigger.html), [JavaScript](https://babeljs.io/) and ??? ``` [ //aТ/\\ ][ //е"6 console.log(111-111+12)] //!'!/-²6-²52 ``` Prints [`11` in Trigger](https://tio.run/##KynKTE9PLfr/P1pBXz/xwiL9mBiFWBD7wlYlM67k/Lzi/JxUvZz8dA1DQ0NdINY2NNKM5dLXV1RX1Nc9tMkMiE2N/v8HAA "Trigger – Try It Online"), [`12` in JavaScript](https://tio.run/##y0osSyxOLsosKNFNSkxKzdHNy09J/f8/WkFfP/HCIv2YGIVYEPvCViUzruT8vOL8nFS9nPx0DUNDQ10g1jY00ozl0tdXVFfU1z20yQyITY3@/wcA "JavaScript (Babel Node) – Try It Online"), and `13` in ***`REDACTED`***. Since this has not been cracked for longer than any other answer so far, here are some hints: * In case you didn't notice, the `Т` and `е` on the first line are multibyte characters. * `[ //` and `\\ ][ //` are no-ops. * The second line, as well as `-²52`, is dead code. * The language does not have a concept of termination, so `²6` forms an infinite loop. * To be specific, the second byte of the UTF-8 encoding of `²`, together with the `6`, forms an infinite loop. * The number being outputted is encoded by the `/!'!/` * The language is not on Try It Online, Rosetta Code or Esolangs. * The only available form of output is a 1bpp screen. * The screen's aspect ratio is 2. * While the language was not originally intended as machine code, FPGA implementations do exist. * According to Wikipedia, the intended purpose of the language were video games. * The only way to access the screen is a special instruction, that takes coordinates in selectable registers, and the height as an immediate, and XORs an 8 by n bitmap onto the screen. To make collision detection easier, as well as make it possible to clear the screen, one of the registers will be set when any pixel gets set back to off. ## Explanation Well, this took some time to get cracked. Let's see how the code looks: ``` 0200 5b20 SE VB, V2 ; Skip the next instruction if VB = V2. Since all 0202 2f2f CALL 0xF2F ; registers start at 0, this call will be skipped. This ; hides the bytecode from JavaScript. 0204 61d0 LD V1, 0xD0 ; A useless load. Necessary to use a UTF-8 continuation 0206 a22f LD I, 0x22F ; byte as an instruction and load the address of ; the sprite. 0208 5c5c SE VC, V5 ; A red herring supposed to suggest symmetry is ; important, as well as a totally intended eliminator ; of inaccurate implementations. Most documentation ; claims that the lowest nibble must be zero, but in ; the original COSMAC VIP implementation it's ; a don't-care. ``` This means that, while [many](https://github.com/dmatlack/chip8) available [emulators](https://github.com/wernsey/chip8) behave correctly, the by-the-rules implementation is linked to in the second sentence of the [Wikipedia page](https://en.wikipedia.org/wiki/CHIP-8). Of course, it can't be run directly on an average PC, but I've found the [Emma 02](http://www.emma02.hobby-site.com/) emulator linked to on the [COSMAC VIP page](https://en.wikipedia.org/wiki/COSMAC_VIP) to work the best. ``` 020A 205d CALL 0x05D ; Skipped. 020C 5b20 SE VB, V2 ; Same as with the very beginning. Red herring. 020E 2f2f CALL 0xF2F 0210 d0b5 DRW V0, VB, 5 ; Draw the sprite pointed to by I. Since V0 and VB ; haven't been written to yet, the sprite will be drawn ; in the top-left corner of the screen. The height is ; an immediate. 0212 2236 CALL 0x236 ; Jump over the JavaScript and Trigger code. It doesn't ; matter that we never return. 0214-022E *never used* 022F 2f DB %00101111 ; Sprite data. 0230 21 DB %00100001 0231 27 DB %00100111 0232 21 DB %00100001 0233 2f DB %00101111 0234-0235 *never used* 0236 b236 JP V0, 0x236 ; Since V0 is still zero, this is an infinite loop. 0238-023C *never used* ; Together with the previous two lines, it's the ; -²6-²52. It's a red herring supposed to suggest ; prefix, or Polish, notation. ``` [Answer] # Python 2, Python 3, ??? ``` a={1,2} print(1+#a --bool(1/2) ) ``` This prints 1 in Python 2, 2 in Python 3, and 3 in ???. Crack explanation [(Cracked post)](https://codegolf.stackexchange.com/a/171885/44694): ``` #define print(A) main(){puts("0");} print(1+bool(1/2)) ``` * `0`: C: The first line defines a function-like macro `print` that ignores its single argument and evaluates to `main(){puts("0");}`, a full program that prints `0` and exits. The whole expression `1+bool(1/2)` is ignored when the `print( )` macro on the second line is expanded to `main(){puts("0");}`. * `1`: Python 2: The first line is a comment. `1/2` uses integer division in Python 2, giving 0. This value is then interpreted as a boolean (`bool(0)` -> `False`) and then added to `1` (`1+False` -> `1`), and then printed. * `2`: Python 3: The first line is a comment. `1/2` uses float division in Python 3, giving 0.5. This value is then interpreted as a boolean (`bool(0.5)` -> `True`) and then added to `1` (`1+True` -> `2`), and then printed. [Answer] # Lua, brainfuck, ??? ``` abcd={} -- a gaffe avoiding tactic in C++ abcd[false]=1+2+3+4+5+6+7+8+9+10+11+12+13+14 print(abcd[0>1+2+3 and 4+5+6<0-0]//35) if 0>1 then a.next=';' end ``` Prints 3 in Lua, 4 in brainfuck and 5 in ???. Explanation for [cracked post](https://codegolf.stackexchange.com/a/171887/60483): ``` a=1+2+3+3+4+5+6+7+8+9 b=1+1+1 f=3--(-1) c=7+9+13+11+12+3--1 g=a+b+c+1+2+3+4+5 j=9+7+g+c+b+a+g+g+g+g+g+g+1+2+3+4+1+1 h=1+1+1+1+333+1+1+1+111+1+1+1+333+1+1+1+1+1. print(f) ``` * In Python 3, `3--(-1)` is 2, so `print(f)` prints 2 (the other stuff is unnecessary) * In Lua, `--` again is a comment, so `3--(-1)` is just 3, so `print(f)` prints 3 (other stuff is again unnecessary) * In brainfuck, there are 57 plusses and 5 minuses setting the first cell on the tape to 52, and the `.` outputs character 52 which is 4. [Answer] # [JavaScript](https://babeljs.io/), [CHIP-8](https://johnearnest.github.io/Octo/), and ??? ``` [ //aТ/\\ ][ //е"6 console.log(111-111+12)] //!'!/-²6-²52@++++2345 ``` [`12` in JavaScript](https://tio.run/##y0osSyxOLsosKNFNSkxKzdHNy09J/f8/WkFfP/HCIv2YGIVYEPvCViUzruT8vOL8nFS9nPx0DUNDQ10g1jY00ozl0tdXVFfU1z20yQyITY0ctIHAyNjE9P///wA "JavaScript (Babel Node) – Try It Online"), `13` in CHIP-8, and `14` in ??? I'm going to go out on a limb and call this one cracked, although I can't quite get it to work I'm sure of the language (which seems to be what the rules ask for.) Here is an imperfect explanation of the [cracked post](https://codegolf.stackexchange.com/a/172076/79980) The code in hexadecimal "is" (I might be slightly off): ``` [ 0x5b, 0x20, 0x2f, 0x2f, 0x61, 0xD0, 0xA2, 0x2f, 0x5c, 0x5c, 0x20, 0x5d, 0x5b, 0x20, 0x2f, 0x2f, 0xD0, 0xB5, 0x22, 0x36, 0x0a, 0x63, 0x6f, 0x6e, 0x73, 0x6f, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x67, 0x28, 0x31, 0x31, 0x31, 0x2d, 0x31, 0x31, 0x31, 0x2b, 0x31, 0x32, 0x29, 0x5d, 0x0a, 0x2f, 0x2f, 0x21, 0x27, 0x21, 0x2f, 0x2d, 0xb2, 0x36, 0x2d, 0xb2, 0x35, 0x32 ] ``` You can go [here](https://johnearnest.github.io/Octo/), click "Binary Tools" and paste this into the byte array box. Click "Decompile". The key elements of the code are: instructions to say where the "number" is, the `sprite` command that prints the number, the correct amount of junk here and there, and the following: ``` : label-0 0x2F 0x21 0x27 0x21 0x2F ``` To see what this represents you can click "Sprite Editor" and paste these hexadecimals into the box underneath. You'll see the answer: [![enter image description here](https://i.stack.imgur.com/mYdAC.png)](https://i.stack.imgur.com/mYdAC.png) I'm pretty sure you can then put anything you like at the end and the CHIP-8 result will not change, hence the new entry. I would be delighted if someone could get this fully working, rather than the "proof" of the answer I've given here. [Answer] # C, Python 2, ??? ``` #define print(A) main(){puts("0");} print(1+bool(1/2)) ``` This prints `0` in C, `1` in Python 2, and `2` in ???. This will be extremely easy to crack for people who know Python, but I wanted a starting-off point for other answers. Subsequent answers should try to obfuscate the third language (I did not do this). [Answer] # Python 3, Lua, ??? ``` a=1+2+3+3+4+5+6+7+8+9 b=1+1+1 f=3--(-1) c=7+9+13+11+12+3--1 g=a+b+c+1+2+3+4+5 j=9+7+g+c+b+a+g+g+g+g+g+g+1+2+3+4+1+1 h=1+1+1+1+333+1+1+1+111+1+1+1+333+1+1+1+1+1. print(f) ``` Prints 2 in Python 3, 3 in Lua and 4 in ???. Explanation for [cracked post](https://codegolf.stackexchange.com/a/171886/71631): ``` a={1,2} print(1+#a --bool(1/2) ) ``` * In Lua, -- is a comment. In Python 2 and 3, -- indicates double negative in arithmetic. * In Python 2 and 3, # is a comment. In Lua, # is the length operator. * In Python 2, 1/2 is floor division, so it evaluates to zero. In Python 3 this is not the case. Because both versions of Python evaluate 0 to False, bool(1/2) evaluates to False in Python 2 and True in Python 3. When used in arithmetic, False is cast to 0 and True is cast to 1. [Answer] # [Beatnik](https://tio.run/##S0pNLMnLzP7/Py1PIbGsKDVdQ7O6listT18rsaqiqqoKIqiQrVBVWAnmVigUlmanKgABl51dgIGCtnZBaUkxhIwuyC@L5YpxeL9/b7WdVi2yFDGkKpeWfm5iZh7QCQVFmXklihpKhuZKmrX//wMA), [Rust](https://tio.run/##KyotLvn/Py1PIbGsKDVdQ7O6listT18rsaqiqqoKIqiQrVBVWAnmVigUlmanKgABl51dgIGCtnZBaUkxhIwuyC@L5YpxeL9/b7WdVi2yFDGkKpeWfm5iZh7QCQVFmXklihpKhuZKmrX//wMA), ??? ``` fn avreg(){} fn/*azxzzz avreg k zqyzzz ax quke >>P0 ++puts++puts[pov] \@�{>*}++puts++puts++puts++puts++puts++puts++puts++puts% */main(){print!("17")} ``` This prints 16 in Beatnik, 17 in Rust, and 18 in ???. The `�` character on line 4 should be replaced with ASCII character 18 (this was not done in the TIO links since it's not relevant to either of them). ## Explanation ([cracked](https://codegolf.stackexchange.com/a/173943/61384)): The previous answer's language was Rust: specifically, Rust compiled with [mrustc](https://github.com/thepowersgang/mrustc). mrustc is an experimental compiler, and as it is mostly intended for bootstrapping a valid version of `rustc`, it ignores borrow checking and mutability checking, allowing @NieDzejkob's snippet to compile without errors. This program will work with the normal Rust compiler, so you don't need to install mrustc to test it. ## Hints Since this answer has now gone the longest without being cracked, I'll leave a hint, and continue to do so regularly until it is cracked: * The secret language is two-dimensional and can be found on the Esolang wiki page for two-dimensional languages. * As I mentioned in the comments, the language is not on TIO. * The `�` character is a red herring and has very little significance. Most bytes can be substituted in its place and the program will still work. [Answer] # ><>, Befunge-96 and ??? ``` abcd={} -- a gaffe avoiding tactic in C++ abcd[false]=1+2+3+4+5+6+7+8+9+10+11+12+13+17! print(abcd[0>1+2+3 and 4+5+6<0-0]//35) if 0>1 then a.next=';' end >1+6.@ ``` This prints [5 in `><>`](https://tio.run/##bYzBCoJAFEX3fsVrZXFRZzS1KCPoM8LFy5nRgZgihwiib5/MdXd7zrnGjkMIfOlU8/5QkhBTz8Zo4ufNKut68tx525F1dAKin3k2fB1120jkKLBGiQo1NthCCkgJmUMWkPUiuj@s88u5EYdZJ3aK5mQvEtFmWVGuImtowuQH7YhTp1@@iXcxaaci@rPpqUqPIXwB), [6 in `Befunge-96`](https://tio.run/##bYxBDoIwEEX3nGJcoZkUWhCQKMbEYxgWA22xiY5GqzExnr0ia//2vfc7Yx88GFGX4uytC4G6XjfvDwgBBANZa4CeF6cdD@Cp964Hx7BHjH7mwdLpbtpGYYY5LrHAEitcYY1KolKoMlQ5qmoWXW@O/Xxq5HbSgVjDlGykkG2a5sUichZGDP5oGChh8/JNvI7BsI7gz8anMtmF8AU) and `7` in ???. I know the intended solution was Befunge-93, but I couldn't resist. ### Explanation: Befunge-96 follows the same path as `><>`, but ignores unknown instructions, ending up adding one to the 5 and multiplying it by 9 to get 54, the ascii code for `6`. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) (100), [Commentator](https://github.com/cairdcoinheringaahing/Commentator), ??? ``` /@++++2345 start: program: db 'function',10 add program,program jp null+$8 sbc rbp,rbp jnz program jr program add start halt ex: ``` Outputs [14 in Klein (100)](https://tio.run/##RU3bCoMwFHs/X5GHgQ8WVneB0Sd/pbVuc@uO5Vhh7OdrJ4KBkEBC8g79wDkf27rgdL5caUpWkqEo40PsxxC8Q3WfuUvDyJVqNMF6jy1XmxJeETyHUB9uhMl1EBdVYQn4h70lu//PrG@Epw2J@q/JOTdaLw "Klein – Try It Online"), [15 in Commentator](https://tio.run/##RU3LCsMwDLv7K3wY9NDA1j1g5LRfcZLuReIE14Wxn0@zUahASCAh@ZzSyEqapdb9rW84ns4XmJRELRTJD6FkAYPD7j6z11fmzgwHQAoB19ysCvguyHOM/e4KODmP4oppbAF/cWvJ5n8z/zfAJ0WF8WNrXQA "Commentator – Try It Online"), 16 in ???. I'm seriously bad at obfuscating polyglots. ### Explanation ([Cracked post](https://codegolf.stackexchange.com/a/173033/78410)) ``` %/ <#> 13 14 + 15 ``` In Commentator, common comment tokens and spaces are the important commands, and any other characters are ignored. * Space increments the current memory cell. * `<#` does XOR 1 on the current memory cell. * `%` is used to reset the current memory cell to zero. Wait, there are 16 spaces after `%`, what happened? It's actually a small bug (or feature?) in the interpreter. `/` is treated as the start of a 2-char command, so the space after it is consumed. But `/<space>` is undefined command (thus a no-op), so the space is effectively skipped. [Answer] # [Commentator](https://github.com/cairdcoinheringaahing/Commentator), [Beatnik](https://esolangs.org/wiki/Beatnik), ??? ``` // k... nak... naKaka pagpAbaGaBag static answer: Option<&String> = None; fn llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch(s: &String){ answer = Some(s); } fn pneumonoultramicroscopicsilicovolcanoconiosis(){ println!("{}", answer.unwrap()); } fn main(){ let s = String::from("17"); let t = "Hi! I am a cat. AOOOWRRRWWW! Me need Whiskas! Noow! Mee hungry hast bekommen. Feedme! sudo !!. Sad... six cable hostage wire cable diediediediee # */"; llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch(&s); pneumonoultramicroscopicsilicovolcanoconiosis(); } ``` Outputs [15 in Commentator](https://tio.run/##nZFNa9wwEIbv/hVjF4K3FC89BTZNYHvoB6Fd2D34PCvPymKlGSPJcU3Ib9/IXpPQYysJBubjmdG8SpwjjhjFXy7rNZyrqgLGxTziGaFD3W2P@B2/os5CSjUKkMNAfgO7LhrhLzeH6A3rB7iH38J0l0F2YrAW@YTGd4O1ehhZj8mKJj@qdhg9N16OKTSlxTEYa0TPV7Vl2MDCXD1nsLRL9IM4KsPqLnu5tuiYeicsvY0enVFegpLOqImm5EmsQhYlbCSYUM6sLlGj5bwsnl@KTwu66nnw2JWrd7RDw9cKSxHC1HweaLM5eXFl8fm2SMnXaEzR4ofJ4SegAwSFsYLtbrer9/t9Xdc5/CJgogbq1oQzhjztSYbJTdD2rP0ILYYIRzrPglTwLWU7yiH0jUCeV3DAZhIlmD8Jf7SpTpIYmmAwnhZXY@jtEXyAv8/HdTEP/P@y3IT5y/@49bTSy@UV "Commentator – Try It Online"), [16 in Beatnik](https://tio.run/##nZFNi9wwDIbv@RVKCkumlAw9FWa7C9tDPyjtwMwhZ8XROCa2FGynaVj2t0@dTGjpsbUNAr3SI1lqCCOb/nrd76GvqgoYN/MVe4QB9fDU4Cf8gDoLEaNRgBwm8gc4DtEIv787R29YP8IDfBem@wyyC4O1yBc0fpis1dPMek5WNPlZddPsufXSJGkJi3Mw1oher@rKcICNuXvOYCuX6GdxVIbdffZyKzEwjU5YRhs9OqO8BCWDUQtNyQ@xClmUsJFgQrmyhkSNlvOyeH4p3mzoauTJ41Du/qAdGr5lWIoQluJrQ4fDxYsri7fvihR8U2NSi88mhy@ADhAUxgqejsdjfTqd6rrO4RsBE7VQdyb0GPI0J5kWN0E3svYzdBgiNNSLc8QVfEzRjnIIYyuQ5xWcsV2WEszPhG9sypO0DE0wGU@bqzX0@xG8gr/P632xNvz/a7kL65f/cepppNfrLw), and 17 in the hopefully one language you are supposed to find. Okay, it's clue time: * The name of the language refers to a compound of two elements, both of which make up your body, but with wildly varying percentages (which way depending on whether you're a robot). * The language itself is on TIO, but the implementation isn't. * Oh come on. [Answer] # Brainfuck, ><>, and ??? ``` abcd={} -- a gaffe avoiding tactic in C++ abcd[false]=1+2+3+4+5+6+7+8+9+10+11+12+13+14 print(abcd[0>1+2+3 and 4+5+6<0-0]//35) if 0>1 then a.next=';' end >1+9*,@ ``` Prints `4` in Brainfuck, `5` in ><>, and `6` in ??? * In brainfuck, nothing changes. * In ><>, `v` redirects the flow of the program downwards. The `n` is **n**umeric output. `;` ends execution. [Answer] # Klein (101), Z80Golf, ??? ``` !!8@e6v+4>9 \ Almost everything you can find on the internet is true ~Albert Einstein ~HUMAN IMAGE MACROS ``` Prints [`8` in Klein (101)](https://tio.run/##Dcw9CsJAEAbQfk/xpbYxIKKNOEhQi1VQ7Gz8Gc3gOgu7k0CaXH31HeB9AouWUlWLNc/7yWy1xNVR@MZs4J7TYK3oG0Ps8LgpXqJPRIW1DFHjpGyQDEsdu5HCnZOhEc32bx3G3cXTAXtP2waeNqfjuZRST@sf), [`9` in Z80Golf](https://tio.run/##XdC9asMwFAXgvU9xMheCfq6u7AylpoS2Q1po6dYlieXEkMrgKIF0yKu7kuUs1SAkIX33XP0WYtcdmmEQ01hASSWhCxJgoxmW1QaatIMulYDZijVI8haYzYpHx@d7eijxPa8Od1mQ0eCaG1htCUqwiUaalC1hiQtwyQ5so4af7hjgzq6/hH3rd5gMFQ1bJsPEW6xZgl1aMZdxxaPb5DNcuhO2a4@m9TU6fzN0MsZyo5Fqxm3KkaqbnC0m0skIe4fWB9d7F9AebwaNhlUxR3wp1tbl3lnlhpJBJuMI/cnNr9Vh4/qAZesnwyQjfQWbMXz8PyUSVBgDqkmCUhtUUg0cg2v9HNeXr1X1htfVZHA0SJIFpV7yI20UqDEa/0f1vMSqevp4/xyGPw), and [`10` in ???](https://youtu.be/KbgiQHUnW3I). [Answer] # [Z80Golf](https://github.com/lynn/z80golf), [Somme](https://github.com/ConorOBrien-Foxx/Somme), ??? ``` !!8@e6v+4>9 \ 1((111+111)/111) 00 ~tz ``` This prints [9 in Z80Golf](https://tio.run/##fY27CsJAFER7v2LSRQLxPjb7sBA/xGYjGxvBRlKk8NfXGxIsHZhhmjmzRHq8nlOttOsMYWFodAQ/qEfwMkKdFmgSwnCnDGWJQNPEa/Fz5y4Jt57bw0bglRHVGGwh468lmbZm8wTKSkDLzJ35eFqjp50hxlCyp1CCQ8j4J@o/76XWLw), [10 in Somme](https://tio.run/##K87PzU39/19R0cIh1axM28TOUiGGy1BDw9DQUBuINfVBBJeBAVddSdX//wA) and 11 in [???](https://esolangs.org/wiki/Unary?). Credit to Bubbler for [cracking the previous post](https://chat.stackexchange.com/transcript/message/46692241#46692241) as Somme, which takes the column sum as the instructions. The first three columns evaluate to ``` A.; ``` Which pushes 10, prints it and exits. [Answer] # [Somme](https://github.com/ConorOBrien-Foxx/Somme), [Trigger](http://yiap.nfshost.com/esoteric/trigger/trigger.html) and ??? ``` [,,E,D,,$,H,_,K,,$,,_,F,L]=! []+[]+!![]+[][111] _=[111][F+L+E+E];[,J,,A,I,,B,C,S]= []+_;$=A+B+C+D+I+H+J+A+I+B+H R=_[$](H+K+I+J+H+C+S+H+B+B+I)();G=($[$]+[])[14] R[A+B+C+D+B+E+K][E+B+G](12);` iP<` ``` This prints [`10` in Somme](https://tio.run/##NY27CsMwDEV3/0UgQ4zu4tLN9RDn/RhKMgqRLB06hA79f1wlUCR0Lnrd7@c4Xikx0KAGcvTYMJ1C2WKWkBkW0syyi@ycE7OFi9zSTA014hkjUGIAIiqsEs6rzeehpEgV1TRQTyOVyki9WcLGuRQ9TdoYdVTRqjVqDLawvgtFrgvqZ9ndxSz8/xPVbxJuVHRSuJv1u3k/H3tKPw "Somme – Try It Online"), [`11` in Trigger](https://tio.run/##NY27CoRADEX7@QvBQsltZtludgrH96NYtAxBm0VsZf9/NgpLQs4lr/s9j33/nDEyUKMCUnRYMV5C2WASnxgW0kySm2ytFbP6m9zQRDXV4hgDUKAHAkos4q@r1aW@oEAlVdRTRwMVykCdmf3KqWQdjdoYdFTSojVo9HmWu9ZnqS6oX872KWbm/5@gfqNwraKVzD5yt5nj/dpi/AE "Trigger – Try It Online"), and `12` in ???. Since the last two languages are easy to polyglot, I decided to mix *that language* in. ### Explanation ([cracked post](https://codegolf.stackexchange.com/a/172030/78410)) Trigger sees the whole code as a series of tokens (tokenization is greedy): * Single byte (denote `A`) * Two same bytes followed by a different byte (denote `AAB`) * Three same bytes (denoted `AAA`) * Four same bytes (denoted `AAAA`) In the source code ``` !!8@e6v+4>9 \ 1((111+111)/111) 00 ~tz ``` the significant tokens are `((1` `11+` `111` `111`, where the first two does nothing and the last two prints 1 each - thus 11. [Answer] # [CHIP-8](https://johnearnest.github.io/Octo/), [Klein (100)](https://github.com/Wheatwizard/Klein), ??? ``` [ //aТ/\\ ][ //е"6 console.log(111-111+12)] //!'!/-²6-²52@++++2345 %/ <#> 13 say 14 + not not 15 ``` Outputs 13 in CHIP-8 (I assume), [14 in Klein](https://tio.run/##y85Jzcz7/z9aQV8/8cIi/ZgYhVgQ@8JWJTOu5Py84vycVL2c/HQNQ0NDXSDWNjTSjOXS11dUV9TXPbTJDIhNjRy0gcDI2MSUS0FVXwEIbJTtFAyNuRQgoDixUsHQhEtBWyEvvwSMDU3///9vaGAAAA), and 15 in ???. *Another* Klein topology, tsk tsk. I've preserved the code before the `@`, since I don't know what will affect CHIP-8. ### Clues I'm kinda overdue for these, sorry. I'll try and add one a day. * Removing the first half (first three lines) of the program still works. * This is not a 2D language * The language is on TIO * The `not`s and the `say` can be removed without affecting the program For reference, the program without that stuff looks like this: ``` %/ <#> 13 14 + 15 ``` [Try it online!](https://tio.run/##y85Jzcz7/19BVV8BCGyU7RQMjbkUoMDQhEtBG0Sb/v//HwA "Klein – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), [BrainSpace](https://esolangs.org/wiki/BrainSpace_1.0), ??? ``` fn v(){} /*{>*}+++++++++++++++++++++++++[[[%]]]*\ \mop+p+p+pox */fn main(){print!("17")} //print!(19)$f($f(-x++this::id()++x)++x@);"v2" //):/ //////////////////////////////////////[]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ``` This prints [17 in Rust](https://tio.run/##KyotLvn/Py1PoUxDs7qWS1@r2k6rVhsXiI6OVo2NjdWK4YrJzS/QBsP8Ci4tfaABuYmZeUAzCooy80oUNZQMzZU0axWQgb4@VM7QUlMlTQOIdCu0tUsyMoutrDJTNDS1tStA2EHTWqnMSIkLpEHTSp9LnygQHWtDAvj/HwA), [18 in BrainSpace](https://tio.run/##SypKzMwrLkhMTv3/Py1PoUxDs7qWS1@r2k6rVhsXiI6OVo2NjdWK4YrJzS/QBsP8Ci4tfaABuUDjgGYUFGXmlShqKBmaK2nWKiADfX2onKGlpkqaBhDpVmhrl2RkFltZZaZoaGprV4Cwg6a1UpmREhdIg6aVPpc@USA61oYE8P8/AA), and 19 in ???. ## [Crack](https://codegolf.stackexchange.com/a/179406/85334) explanation Remembered this existed looking through old messages, figured I could scrape Esolangs for every implemented 2D language where the article body has an `o` surrounded by non-letters, and fortunately couldn't be bothered to filter out languages that are on TIO because it turns out [BrainSpace got added to TIO about five months after it was confirmed not on TIO](https://github.com/TryItOnline/tryitonline/commits/master/wrappers/brainspace). (It's also fortunate that it was alphabetically the second candidate out of 48.) For posterity (as comments can be ephemeral), the full sequence of hints given was: * The language is not on TIO. (as of 2019/4/3) * The language is 2D and listed as such on Esolangs. * The ASCII character 18 is a red herring. * `s` doesn't square, `[` doesn't halve, and `o` doesn't end the program. * `o` performs output. BrainSpace is some kind of weird half-Brainfuck-half-fungeoid where `{}` move the tape head, `*` is a conditional jump, `%` is an omnidirectional reflect, all three of `pP+` are equivalent increment commands, and all three of `oO0` are equivalent output commands. The instruction pointer starts in the top left moving right, so `fn avreg(){}` sends the pointer down in column 5, `{>*}` sends it careening into a bunch of increments that it gets bounced through again on the way back then passes it right along to the left, and `P0 ++puts++puts[pov]` increments 48 to 49, prints that, slaps another 7 on, prints, then terminates the program by leaving the edge--BrainSpace's field is not toroidal. --- This should be considerably easier, but you might take some wrong turns. ]
[Question] [ I was surprised to not find this asked already, though there is a great question on darts checkouts: [Darts meets Codegolf](https://codegolf.stackexchange.com/questions/20076/darts-meets-codegolf) Your challenge is to calculate which scores are not possible with 'n' darts below the maximum score for 'n' darts. E.g. for n=3, the maximum possible score is 180 so you would return [163,166,169,172,173,175,176,178,179] For a bare bones rule summary: Possible scores for a single dart are: * 0 (miss) * 1-20, 25, 50 * double or triple of 1-20 Rules: * standard code golf rules apply * you must take a single parameter 'n' in whatever way your language allows and return a list/array of all unique scores below the maximum score which cannot be scored with n darts. You may also print these values to the console. * order of results is unimportant * shortest code in bytes wins [Answer] # [Python 3](https://docs.python.org/3/), ~~80~~ ~~79~~ ~~59~~ 57 bytes -1 byte thanks to Arnauld -20 bytes thanks to ArBo -2 bytes thanks to negative seven ``` lambda x:[-i-~x*60for i in(x<2)*b'a[YUSOLI'+b'MJGDCA@>='] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKlo3U7euQsvMIC2/SCFTITNPo8LGSFMrST0xOjI02N/HU107Sd3Xy93F2dHBzlY99n9BUWZeiUaahqGmJheMbYTENkZim2hq/gcA "Python 3 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 42 bytes ``` {^60*$_∖[X+] [[|(^21 X*^4),25,50]xx$_,]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Os7MQEsl/lHHtOgI7ViF6OgajTgjQ4UIrTgTTR0jUx1Tg9iKCpV4ndja/2n5RQpxJgrVXAoKxYmVCkoq8Qq2dgpKOnpqaVy1/wE "Perl 6 – Try It Online") Brute force solution that works out all possible dart values. [Answer] # JavaScript (ES6), ~~55~~ 54 bytes *Saved 1 byte thanks to @Shaggy* Based on the pattern used by [Rod](https://codegolf.stackexchange.com/a/187110/58563). ``` n=>[...1121213+[n-1?33:2121242426]].map(x=>n-=x,n*=60) ``` [Try it online!](https://tio.run/##FYlBDoIwEAC/sre2lm4sVQ7o4kMIhwbBQHCXgDH8vtbMYTKZOX7j3m/T@nEszyGNlJiaFhG9LzPBtuz8I4T6X@UlU3UdvuOqD2rY0VHwiaqzSaNsmoHA34DhDtcsaw30wrssAy7yytuCqkFljZoNzjKxVgUoY9IP "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes (37 chars) This is definitely using a massive sledgehammer but it works. (It doesn't just brute force it, it brutally brute forces it) ``` {^60*$_∖[X+] (|(^21 X*^4),25,50)xx$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzrOzEBLJf5Rx7ToCO1YBY0ajTgjQ4UIrTgTTR0jUx1TA82KCpX42v/WXFzKxYkgXRqGmtYKygpJpekKmXkKRYnZpSn5ConFCvlpCkYGhpa6Bma6hpZcULVGmtYwpjGQqawA5ZiAzSjPL8ou1gEaVaJQkpidWqxQkp@vkJOfl66Qll@kEOLp/x8A "Perl 6 – Try It Online") Here's an explanation of it: ``` { } anonymous block for the ∖ set difference of ^60*$_ - 0 .. max score (60 * throwcount) [X+] xx$_ - the cross addition (throwcount times) of ( ) all possible score values, being |( X* ) flattened cross multiplication of ^21 ^4 0..20 and 0..3 (for double and triple) ,25,50 and 25 and 50 ``` The `X* ^4` cross multiplier generates a lot of duplicate values (there will be 20+ zeros involved and that's *before* doing the cross addition), but that doesn't cause any problems since we use the set difference `∖` which works with the unique values. This currently fails for `$n == 1` (which should return an empty set), but there is an [issue filed](https://github.com/rakudo/rakudo/issues/2025) and will likely work in future versions. [JoKing's version](https://codegolf.stackexchange.com/a/187125/30284) is a teeny bit longer, but works for `$n == 1` in current Rakudo. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` 20Ż;25×Ɱ3ẎṖœċ⁸§ṪṖḟƊ ``` [Try it online!](https://tio.run/##ATIAzf9qZWxsef//MjDFuzsyNcOX4rGuM@G6juG5lsWTxIvigbjCp@G5quG5luG4n8aK////Mw "Jelly – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~25~~ 23 bytes *Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe), who fixed a mistake and golfed 2 bytes!* ``` 25tE3:!21:q*vZ^!stP:wX- ``` [Try it online!](https://tio.run/##y00syfn/38i0xNXYStHI0KpQqywqTrG4JMCqPEIXKAEA) ### Explanation Brute force approach. ``` 25 % Push 25 tE % Duplicate, double: gives 50 3:! % Push column vector [1;2;3] 21:q % Push row vector [0 1 ... 20] * % Multiply with broadcast. Gives a matrix with all products v % Concatenate everything into a column vector Z^ % Implicit input: n. Cartesian power with exponent n !s % Sum of each row tP % Duplicate, flip: The first entry is now 60*n : % Push row vector [1 2 ... 60*n] w % Swap X- % Set difference. Implicit display ``` [Answer] # [J](http://jsoftware.com/), ~~48~~ 45 bytes ``` 2&>(35 44,q:626b66jh)&,60&*-1 4 8 14,q:@13090 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jdTsNIxNFUxMdAqtzIzMkszMsjI01XTMDNS0dA0VTBQsFAxBUg6GxgaWBv81uVKTM/IV9K3qFNIUDJE5RsgcY67/AA "J – Try It Online") *-3 bytes thanks to FrownyFrog* Attempted a brute force solution, but was not able to beat this translation of Rod's idea. [Answer] # [R](https://www.r-project.org/), 64 bytes ``` function(n,`!`=utf8ToInt)c(60*n-!" ",(!" #%),/")[n<2]) ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jTydBMcG2tCTNIiTfM69EM1nDzEArT1dRSZCPm4OdlYWJUUlHQ1FJXFZeWVVTR19JMzrPxihW83@ahqEmV5qGEYgw1vwPAA "R – Try It Online") Ports the [amazing answer found by Rod](https://codegolf.stackexchange.com/a/187110/67312). # [R](https://www.r-project.org/), ~~85~~ ~~73~~ 68 bytes ``` function(n)setdiff(0:(60*n),combn(rep(c(0:20%o%1:3,25,50),n),n,sum)) ``` [Try it online!](https://tio.run/##Fco9DoAgDEDh3VO4mLSmJvwEB@NpRJowUAzg@RGXN3x5pfN8bp1f8S1mAcEa2h2ZQR2wq1WQfE6XQAkP@IFGLXnRhyXjyCmkMQjVNyF2Bo0Tg/ljsX8 "R – Try It Online") Brute force generates all possible scores with `n` darts, then takes the appropriate set difference. Credit to [OrangeCherries' Octave solution](https://codegolf.stackexchange.com/a/187112/67312) for reminding me of `combn`. 5 more bytes thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder)'s suggestion of using `%o%`. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~91 bytes~~ ~~73 bytes~~ 71 Bytes Another brute force method. ``` @(n)setdiff(0:60*n,sum(combnk(repmat([x=0:20,x*2,x*3,25,50],1,n),n),2)) ``` Down to ~~73 Bytes~~ thanks to Giuseppe Down to 71 Bytes by replacing nchoosek with combnk [Try it online!](https://tio.run/##FcNBCoAgEADAr3jcjUU2ow6B0D@ig5VChBZp4e@tYOZYknlscUILKWUZIGC0ad2cA@47rgLF28Ny@DnscNnTmwRj1twrplypb0OqpZYnqingTyEWBw2WFw "Octave – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 bytes ``` -S*60Q+M^+yB25*M*U4U21 ``` [Try it online!](https://tio.run/##K6gsyfj/XzdYy8wgUNs3TrvSychUy1cr1CTUyPD/f2MA "Pyth – Try It Online") Times out in TIO for inputs greater than 3. ``` -S*60Q+M^+yB25*M*U4U21Q Implicit: Q=eval(input()) Trailing Q inferred U4 Range [0-3] U21 Range [0-20] * Cartesian product of the two previous results *M Product of each yB25 [25, 50] + Concatenate ^ Q Cartesian product of the above with itself Q times +M Sum each The result is all the possible results from Q darts, with repeats *60Q 60 * Q S Range from 1 to the above, inclusive - Setwise difference between the above and the possible results list Implicit print ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ¿ß☺o↕αg╠╩╬ò▼í¬«¥↕▄í■♣▓î► ``` [Run and debug it](https://staxlang.xyz/#p=a8e1016f12e067cccace951fa1aaae9d12dca1fe05b28c10&i=1%0A3&a=1&m=2) It's pretty slow for n=3, and gets worse from there. [Answer] # [Python 2](https://docs.python.org/2/), 125 bytes ``` lambda n:set(range(60*n))-set(map(sum,product(sum([range(0,21*j,j)for j in 1,2,3],[25,50]),repeat=n))) from itertools import* ``` [Try it online!](https://tio.run/##PYxBDoIwEEX3nGKWLRkTqOKChJMgiyqtltBOMwwLT18lJu5@Xt77@S0vSqb44VZWG@@zhdRvThTb9HTq2tRJ69MBos1q2yNmpnl/yLHV@LMaNG294KI9MSwQErRo8DzhaDrsmkkju@ysDN8vXXmmCEEcC9G6QYiZWOpytOHf4qWvIHNIAl4FXT4 "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), ~~126~~ ~~125~~ 122 bytes ``` lambda n:{*range(60*n)}-{*map(sum,product(sum([[i,i*2,i*3]for i in range(21)],[25,50]),repeat=n))} from itertools import* ``` [Try it online!](https://tio.run/##PYzLCoMwEADvfsUek7AFjbUHwS@xHtKatAvmwRoPRfz2tKXQw8BcZtIrP2NoixuuZTH@NhsI/a7YhIcVl1oFeZx25U0S6@YxcZy3e/66GEdCUvpDO7nIQEABfp1u5ISj7rCrJ4lskzV5CFIeUDmOHihbzjEuK5BPkbMq/0GDGls89xUkppCFEyRleQM "Python 3 – Try It Online") -3 bytes, thanks to Rod [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ ~~20~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 20Ý25ª3Lδ*˜¨ãOZÝsK ``` -3 bytes thanks to *@Grimy*. Times out pretty quickly the higher the input goes due to the cartesian product builtin `ã`. [Try it online](https://tio.run/##yy9OTMpM/f/fyODwXCPTQ6uMfc5t0To959CKw4v9ow7PLfYGSgEA) or [verify a few more test cases](https://tio.run/##ATEAzv9vc2FiaWX/M0VOPyIg4oaSICI//zIww50yNcKqM0zOtCrLnMKoTsOjT1rDnXNL/yz/). **Explanation:** ``` 20Ý # Push a list in the range [0, 20] 25ª # Append 25 to this list 3L # Push a list [1,2,3] δ* # Multiply the top two lists double-vectorized: # [[0,0,0],[1,2,3],[2,4,6],[3,6,9],...,[20,40,60],[25,50,75]] ˜ # Flatten this list: [0,0,0,1,2,...,40,60,25,50,75] ¨ # Remove the last value (the 75) ã # Create all possible combinations of the (implicit) input size, # by using the cartesian power O # Sum each inner list of input amount of values together Z # Get the maximum (without popping the list), which is 60*input Ý # Create a list in the range [0, 60*input] s # Swap so the initially created list is at the top of the stack again K # And remove them all from the [0, 60*input] ranged list # (then output the result implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` 21Ḷ×þ3R¤;25;50FœċµS€³×60¤R¤ḟ ``` [Try it online!](https://tio.run/##ATcAyP9qZWxsef//MjHhuLbDl8O@M1LCpDsyNTs1MEbFk8SLwrVT4oKswrPDlzYwwqRSwqThuJ////8z "Jelly – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 26 bytes ``` ╟*rJrN▐3╒*mÅ~*╡ak.ε*mÉa─Σ- ``` [Try it online!](https://tio.run/##y00syUjPz0n7///R1PlaRV5Ffo@mTTB@NHWSVu7h1jqtR1MXJmbrndsK5HUmPprScG6x7v//hlxGXMb/AQ "MathGolf – Try It Online") -2 bytes thanks to Kevin Cruijssen ## Explanation ``` ╟*r push [0, ..., 60*input-1] Jr push [0, ..., 20] N▐ append 25 to the end of the list 3╒ push [1, 2, 3] * cartesian product mÅ explicit map ~ evaluate string, dump array, negate integer * pop a, b : push(a*b) ╡ discard from right of string/array a wrap in array k push input to TOS . pop a, b : push(b*a) (repeats inner array input times) ε* reduce list with multiplication (cartesian power) mÉ explicit map with 3 operators a wrap in array (needed to handle n=1) ─ flatten array Σ sum(list), digit sum(int) - remove possible scores from [0, 60*input-1] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes ``` Complement[Range[60#],Tr/@{Array[1##&,{4,21},0,##&],25,50}~Tuples~#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zk/tyAnNTc1ryQ6KDEvPTXazEA5ViekSN@h2rGoKLEy2lBZWU2n2kTHyLBWx0AHyInVMTLVMTWorQspBeosrlOOVfsfUJSZV@KQFm0c@x8A "Wolfram Language (Mathematica) – Try It Online") Based off of [lirtosiast's answer](https://codegolf.stackexchange.com/a/187137/81203). `Array`'s third argument specifies the offset (default 1), and its fourth argument specifies the head to use instead of `List`. `##&` is equivalent to [`Sequence`](https://reference.wolfram.com/language/ref/Sequence), so `Array[1##&,{4,21},0,##&]` returns a (flattened) `Sequence` containing members of the outer product of `0..3` and `0..20`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` I⁺E…wvtsqpmjgkhea_[YS⎇⊖θ⁹¦¹⁷℅ι×⁶⁰⁻θ² ``` [Try it online!](https://tio.run/##FY09C8IwFAD/Suj0AhGsg@Ic12LBLuIgj/RhokmaLyv99bG96W46pTGpCW2tfTK@gMRcoLffDB0GkIuyJPUUoPnNJcfg3q@PJnw@7rdGsIGSx7TAhVQiR77QCJELdhasPfFVrmk0Hi2YLQbjKMNxL1hn/DqIgh34Rq1t3c32Dw "Charcoal – Try It Online") Link is to verbose version of code. Uses @Rod's algorithm; brute force would have taken 60 bytes. Works by truncating the string to 9 characters if the input is greater than 1, then taking the ordinals of the characters and adding the appropriate multiple of 60. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 305 bytes ``` (a,b)=>(int)Math.Pow(a,b);f=n=>{var l=new List<int>(new int[21].SelectMany((_,x)=>new[]{x,x*2,x*3})){25,50};int a=l.Count,b,c,d,e=P(a,n),f;var r=new int[e];for(b=e;b>0;b--)for(c=0;c<n;c++){d=b;while(d>P(a,c+1))d-=P(a,c+1);f=(d/P(a,c))-1;r[b-1]+=l[f>0?f:0];}return Enumerable.Range(0,l.Max()*n).Except(r);} ``` Well, there doesn't seem to be an easy way of calculating all the possible combinations in C#, so this disaster of a code is all I could come up with. Plus it takes about 30s to complete... Would love to see a better solution. ``` P=(a,b)=>(int)Math.Pow(a,b); F=n=> { var l=new List<int>(new int[21].SelectMany((_,x)=>new[]{x,x*2,x*3})){25,50}; int a=l.Count,b,c,d,e=P(a,n),f; var r=new int[e]; for(b=e;b>0;b--) for(c=0;c<n;c++) { d=b; while(d>P(a,c+1)) d-=P(a,c+1); f=(d/P(a,c))-1; r[b-1]+=l[f>0?f:0]; } return Enumerable.Range(0,l.Max()*n).Except(r); } ``` [Try it online!](https://tio.run/##RVBBasMwELznFSInbSy7dkIvVaQeSgotCYT20EMwRZLlRODKRZYbF@O3u3Jo2sPAzC47s7uqiVVjxsfWqrWxnjxtbPuhnZCVnjTnqKSzv@4vONojNmJBJDCOQwF2wp@SfX2@1GjJLOP9l3CoYlaf0dY0/uKGJxXIYZnlyauutPI7Yb8xfiddsArdQ953pFssA1YDQL@8JbfpQMMMEqxKHuo2rCCJIgXRbB/iLJCSTlGOXc11TsvaYck0lTylMo5h0oqlVK0tVVEEfcEkPZ9MpXHBJxsVZQBFzK483ICLm4sCiDPqDjLO8ohVh5Kn9@VdmtPBad86i/4/lrwIe9Q4JVWyEx2GhYVk0yn96bEDOox09uaM11tjNW68M/aYPNfG4jmZE1TiFQDQ8Qc "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 118 bytes ``` {n:Int->val i=if(n<2)listOf(23,24,31,25,37,41,44,47) else List(0){0} i+List(9){n*60-listOf(17,14,11,8,7,5,4,2,1)[it]}} ``` [Try it online!](https://tio.run/##fVbRbts4EHz3V2z6UvlOlS3HiRMjCdDrtUCAHlr0ChRF0QdaomwiEqmSVB0j8LfnZknJTq5Ag0CWqeVydmZ25Tvja6UfJxO61W3n3ZK08Rul1@QN2U5TKSvR1Z4K4aQjY0cIFZqU9nItLa2k30qpKcdiSbNpNuKAN1YKL0uqjCVkc1SYUtLa1BUVG1HXUq/lkgM33rduOZnwc36cOS@KO3mPKIRkhWkmPyb5xSKfnnH4bdMa59SqllQK6x25wljpwpm3tBVY6GxrlcPZwI9SqFLAFTAIdyfLAL8GvHKXYtl06w0@pJXEEbRm4PSjk84roznY6P6oYiOLOxMo@jssNFLi@qZHHjB8NZ09VsgpgaIQddHV4IO2G1VsBswMBMcyxkNRW@U39FK/7I9cydpsGR4HN@JeNV0TtwdmD4EZvc3WWVjT16cpR2PTYcchfdwKVPnFlJyhnek4dmu6uiQrfWc1fcvPT1PKz8/5conLYsYXXluchdT5gp8tLvhy@T3U/Q4nC1pxPSuj4RPb8XFd0wi7W4aQj89AuABWkIPTejGZjRjKf1NKGuXcePiev5pNU5qdpXQ2HdZK03FC9phVLd9VIS4k@QQE7pgPvtI4pXziRMYIzdu23g1RIISaznny4k4e4bXCikZ6GSlXwRfbDRT9iaWt2PE@SzUs2wnIDvnN1oWGiKQGralWzk@EtYgHUARRpxWsNjDyG7WjcQqh2S2rfkcZ7RKy9zb4yviRX9RQF32gPedzkn6KGp6GGwdvFEY7U8tsqNzYErUAF5Cg3R27BPDQbxbM@QONG3xHc0QalabVDl8BRMcmfNfpgjsnQpP3LUgA0Fo0q1LETVjhSLR2IzVAjypMmdaaQjqX6CXmkB8v6T3IusLtDT2MRkTY8IUzGl2DPd07JjYuu65hlmKRMdpDHiaMdBAJnKGz0cIl@34ttbTckCIGszJcO/I1KcjGPHt@ECZLjHStLFSlZJnRBz59i1GTPsmnSTat3x3TZrgFLlClvMLn9SjwSKqiRNMVzcb9AoXwD1UyQ6vN5imd5tHvp4uU5rifY22@GMJl7eRhJ5OVTMf0gLbZ93R9iu3MWg9nhzLbunNhtS86RmtjGzhyB80DT4IbS3fNSlrY6oukzv3ClqkqxxOwsqZ5Nm@CDr0MT8cfxq2TB2Ve@ieqME39AOrR/hmKuuSi9B/n01c9OznYyOdpX3oOXjCHsAaiwA@PqvE35b@Dhj2f3/sqePMfAb9Wg0GBrK3RKvH1NIzs6MYGkYmwa4z619yvV/9iwOj1zfhgxvfR0PH9Jp/uj3K3QWgelvlF7JHHB72En1/dBDdcqyrRV7PxUXNIDsUhOPSG3FCbxQ4y9/I@TPcjNdDy8D9SwAnIuEgX6Vk6T2dppGG/fwwoPtsdM13ye/03L@8IuRCd6wPxIpZtoAv/GMdor4w@9pwe@6wRete/skrlmNawHxMOrwAXYobUv8ruge0h6MnMaLoOSN8rLZPxyUnmDVhLou1j05xAxjzLZtOhF/zGYnDeQoG1qF/bdceD5e0APTm0CdGLv0SJ6vFD5@RF3B2GZK2TNtHjcS/uhyeFpzyoUBHOZI56P4UpHWKf/Tzicva49RjWibTW2CV9ZnDcTuO@yuHEIxaKfPep3ACNzZWwWFztfCj2OWBeCUZHcHQ8e/fxPw "Kotlin – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-n`, ~~96~~ ~~93~~ 91 bytes ``` $"=',';@b=map{$_,$_*2,$_*3,25,50}0..20;map$r[eval]=1,glob"+{@b}"x$_;map$r[$_]||say,0..$_*60 ``` [Try it online!](https://tio.run/##K0gtyjH9/19FyVZdR93aIck2N7GgWiVeRyVeywhEGOsYmeqYGtQa6OkZGVgDJVWKolPLEnNibQ110nPyk5S0qx2SapUqVOKhkirxsTU1xYmVOkAdQP1mBv//G//LLyjJzM8r/q/ra6pnYGjwXzcPAA "Perl 5 – Try It Online") It was optimized for code length rather than run time, so it's kind of slow. It generates a lot of redundant entries for its lookup hash. Running the `@b` array through `uniq` speeds it up greatly, but costs 5 more bytes, so I didn't do it. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes ``` Complement[Range[60#-1],Total/@Tuples[Flatten[{Array[Times,{3,20}],0,25,50}],#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zk/tyAnNTc1ryQ6KDEvPTXazEBZ1zBWJyS/JDFH3yGkFChbHO2Wk1hSkpoXXe1YVJRYGR2SmZtarFNtrGNkUBurY6BjZKpjCmIpx8aq/Q8oyswrcUiLNo79DwA "Wolfram Language (Mathematica) – Try It Online") Mathematica has a few related builtins including `FrobeniusSolve` and the restricted form of `IntegerPartitions`, but none of them are shorter than brute force. ]
[Question] [ Given an input string, output that string with all vowels `a`, `e`, `i`, `o` and `u` swapped at random between each other. For example, in the string `this is a test`, there are 4 vowels: `[i, i, a, e]`. A valid shuffling of those vowels could be `[a, i, e, i]` therefore yielding the output `thas is e tist`. ### About shuffling All shuffles shall be equally likely **if we consider equal vowels to be distinct**. For the example above, those 24 shuffles are possible: ``` [i1, i2, a, e] [i1, i2, e, a] [i1, a, i2, e] [i1, a, e, i2] [i1, e, i2, a] [i1, e, a, i2] [i2, i1, a, e] [i2, i1, e, a] [i2, a, i1, e] [i2, a, e, i1] [i2, e, i1, a] [i2, e, a, i1] [a, i1, i2, e] [a, i1, e, i2] [a, i2, i1, e] [a, i2, e, i1] [a, e, i1, i2] [a, e, i2, i1] [e, i1, i2, a] [e, i1, a, i2] [e, i2, i1, a] [e, i2, a, i1] [e, a, i1, i2] [e, a, i2, i1] ``` Each one should be equally as likely. You may not try random shuffles of the entire string until finding one where all vowels are in the right place. In short, your code's running time shall be constant if the input is constant. ### Inputs and outputs * You may assume that all letters in the input will be lowercase or uppercase. You may also support mixed casing, though this won't give you any bonus. * The input will always consist of printable ASCII characters. All characters that are in the input shall be in the output, only the vowels must be shuffled around and nothing else. * The input can be empty. There is no guarantee that the input will contain at least one vowel or at least one non-vowel. * You may take the input from `STDIN`, as a function parameter, or anything similar. * You may print the output to `STDOUT`, return it from a function, or anything similar. ### Test cases The first line is the given input. The second line is one of the possible outputs. ``` <empty string> <empty string> a a cwm cwm the quick brown fox jumps over the lazy dog. tho qeuck brewn fax jumps ovir the lozy dog. abcdefghijklmnopqrstuvwxyz abcdefghujklmnipqrstovwxyz programming puzzles & code golf pregromming pezzlos & coda gulf fatalize fitaleza martin ender mirten ander ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), *sa tho shirtist enswer en bytes wons*. [Answer] ## R, 92 91 Can't comment yet so I'm adding my own answer albeit very similar to @Andreï Kostyrka answer (believe it or not but came up with it independently). ``` s=strsplit(readline(),"")[[1]];v=s%in%c("a","e","i","o","u");s[v]=sample(s[v]);cat(s,sep="") ``` ### Ungolfed ``` s=strsplit(readline(),"")[[1]] # Read input and store as a vector v=s%in%c("a","e","i","o","u") # Return TRUE/FALSE vector if vowel s[v]=sample(s[v]) # Replace vector if TRUE with a random permutation of vowels cat(s,sep="") # Print concatenated vector ``` --- Saved one byte thanks to @Vlo ``` s=strsplit(readline(),"")[[1]];s[v]=sample(s[v<-s%in%c("a","e","i","o","u")]);cat(s,sep="") ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` f€“¡ẎṢɱ»ðœpżFẊ¥ ``` [Try it online!](http://jelly.tryitonline.net/#code=ZuKCrOKAnMKh4bqO4bmiybHCu8OwxZNwxbxG4bqKwqU&input=&args=dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4) ### How it works ``` f€“¡ẎṢɱ»ðœpżFẊ¥ Main link. Argument: s (string) “¡ẎṢɱ» Yield "aeuoi"; concatenate "a" with the dictionary word "euoi". f€ Filter each character in s by presence in "aeuoi". This yields A, an array of singleton and empty strings. ð Begin a new, dyadic chain. Left argument: A. Right argument: s œp Partition s at truthy values (singleton strings of vowels) in A. FẊ¥ Flatten and shuffle A. This yields a permutation of the vowels. ż Zip the partition of consonants with the shuffled vowels. ``` [Answer] # R, ~~99~~ ~~98~~ 89 bytes ``` x=el(strsplit(readline(),"")) z=grepl("[aeiou]",x) x[z]=x[sample(which(z))] cat(x,sep="") ``` Seems to be the first human-readable solution! Thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for saving 9 bytes! Test cases: ``` tho qaeck bruwn fux jemps over tho lozy dig. progremmang pozzlos & cide gulf ``` Seems that there is no way to make an internal variable assignment (inside, like, `cat`), and again some people are going to prove I am wrong... [Answer] ## CJam, 23 bytes ``` lee_{"aeiou"&},_mrerWf= ``` [Try it online!](http://cjam.tryitonline.net/#code=bGVlX3siYWVpb3UiJn0sX21yZXJXZj0&input=c2hlbmFuaWdhbnM) ### Explanation ``` l e# Read input, e.g. "foobar". ee e# Enumerate, e.g. [[0 'f] [1 'o] [2 'o] [3 'b] [4 'a] [5 'r]]. _ e# Duplicate. {"aeiou"&}, e# Keep those which have a non-empty intersection with this string e# of vowels, i.e. those where the enumerated character is a vowel. e# E.g. [[1 'o] [2 'o] [4 'a]]. _ e# Duplicate. mr e# Shuffle the copy. E.g. [[2 'o] [4 'a] [1 'o]]. er e# Transliteration. Replaces elements from the sorted copy with e# the corresponding element in the shuffled copy in the original list. e# [[0 'f] [2 'o] [4 'a] [3 'b] [1 'o] [5 'r]]. Wf= e# Get the last element of each pair, e.g. "foabor". ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 17 bytes ``` žMÃ.r`¹vžMyå_iy}? ``` **Explanation** ``` žMà # get all vowels from input .r` # randomize them and place on stack ¹v # for each in input žMyå_i } # if it is not a vowel y # push it on stack ? # print top of stack ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xb5Nw4MucmDCuXbFvk15w6VfaXl9Pw&input=dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4) [Answer] # Python 3, 109 bytes Only supports lowercase vowels. Thanks to @Alissa for saving an extra byte. ``` import re,random def f(s):r='[aeiou]';a=re.findall(r,s);random.shuffle(a);return re.sub(r,lambda m:a.pop(),s) ``` [**Ideone it!**](http://ideone.com/78JIDe) [Answer] # TSQL, 275 bytes **Golfed:** ``` DECLARE @ VARCHAR(99)='the quick brown fox jumps over the lazy dog.' ;WITH c as(SELECT LEFT(@,0)x,0i UNION ALL SELECT LEFT(substring(@,i+1,1),1),i+1FROM c WHERE i<LEN(@)),d as(SELECT *,rank()over(order by newid())a,row_number()over(order by 1/0)b FROM c WHERE x IN('a','e','i','o','u'))SELECT @=STUFF(@,d.i,1,e.x)FROM d,d e WHERE d.a=e.b PRINT @ ``` **Ungolfed:** ``` DECLARE @ VARCHAR(max)='the quick brown fox jumps over the lazy dog.' ;WITH c as ( SELECT LEFT(@,0)x,0i UNION ALL SELECT LEFT(substring(@,i+1,1),1),i+1 FROM c WHERE i<LEN(@) ),d as ( SELECT *, rank()over(order by newid())a, row_number()over(order by 1/0)b FROM c WHERE x IN('a','e','i','o','u') ) SELECT @=STUFF(@,d.i,1,e.x)FROM d,d e WHERE d.a=e.b -- next row will be necessary in order to handle texts longer than 99 bytes -- not included in the golfed version, also using varchar(max) instead of varchar(99) OPTION(MAXRECURSION 0) PRINT @ ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/531859/sheffle-tho-vawols-ureund)** [Answer] # Perl, 38 bytes Includes +1 for `-p` Run with the sentence on STDIN ``` vawols.pl <<< "programming puzzles & code golf" ``` `vawols.pl`: ``` #!/usr/bin/perl -p @Q=/[aeiou]/g;s//splice@Q,rand@Q,1/eg ``` [Answer] # Java 7, ~~243~~ 241 bytes ``` import java.util.*;String c(char[]z){List l=new ArrayList();char i,c;for(i=0;i<z.length;i++)if("aeiou".indexOf(c=z[i])>=0){l.add(c);z[i]=0;}Collections.shuffle(l);String r="";for(i=0;i<z.length;i++)r+=z[i]<1?(char)l.remove(0):z[i];return r;} ``` Yes, this can probably be golfed quite a bit, but Java doesn't have any handy built-ins for this a.f.a.i.k... Also, I kinda forgot the codegolfed array-variant for `Collections.shuffle`.. **Ungolfed & test cases:** [Try it here.](https://ideone.com/DrIglP) ``` import java.util.*; class M{ static String c(char[] z){ List l = new ArrayList(); char i, c; for(i = 0; i < z.length; i++){ if("aeiou".indexOf(c = z[i]) >= 0){ l.add(c); z[i] = 0; } } Collections.shuffle(l); String r = ""; for(i = 0; i < z.length; i++){ r += z[i] < 1 ? (char)l.remove(0) : z[i]; } return r; } public static void main(String[] a){ System.out.println(c("".toCharArray())); System.out.println(c("a".toCharArray())); System.out.println(c("cwm".toCharArray())); System.out.println(c("the quick brown fox jumps over the lazy dog.".toCharArray())); System.out.println(c("abcdefghijklmnopqrstuvwxyz".toCharArray())); System.out.println(c("programming puzzles & code golf".toCharArray())); System.out.println(c("fatalize".toCharArray())); System.out.println(c("martin ender".toCharArray())); } } ``` **Possible output:** ``` a cwm tha queck brown fox jumps evor tho lezy dig. ebcdifghujklmnopqrstavwxyz prigrommeng puzzlos & cade golf fatelazi mertan inder ``` [Answer] # [Perl 6](http://perl6.org/), 65 bytes ``` {my \v=m:g/<[aeiou]>/;my @a=.comb;@a[v».from]=v.pick(*);@a.join} ``` Anonymous function. Assumes lower-case input. ([try it online](https://glot.io/snippets/ei0d9dkfpl)) [Answer] # Ruby 45 + 1 = 46 bytes +1 byte for `-p` flag ``` a=$_.scan(e=/[aeiou]/).shuffle gsub(e){a.pop} ``` [Answer] # Bash, 75 bytes ``` paste -d '' <(tr aeoiu \\n<<<$1) <(grep -o \[aeiou]<<<$1|shuf)|paste -sd '' ``` Takes the string as an argument and prints the result to stdout. Eg ``` for x in "" "a" "cwm" \ "the quick brown fox jumps over the lazy dog." \ "abcdefghijklmnopqrstuvwxyz" \ "programming puzzles & code golf" \ "fatalize" "martin ender"; do echo "$x";. sheffle.sh "$x"; echo done ``` prints ``` <blank line> <blank line> a a cwm cwm the quick brown fox jumps over the lazy dog. tho quuck brown fix jamps ever the lozy dog. abcdefghijklmnopqrstuvwxyz ibcdefghajklmnopqrstuvwxyz programming puzzles & code golf progremmong pazzlus & cedo gilf fatalize fetilaza martin ender mertan endir ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 39 bytes ``` @eI:1aToS,I:2f@~:LcS,Tc .'~e@V; e.~e@V, ``` [Try it online!](http://brachylog.tryitonline.net/#code=QGVJOjFhVG9TLEk6MmZAfjpMY1MsVGMKLid-ZUBWOwplLn5lQFYs&input=InRoZSBxdWljayBicm93biBmb3gganVtcHMgb3ZlciB0aGUgbGF6eSBkb2cuIg&args=Wg) ### Explanation * Main predicate: ``` @eI I is the list of chars of the input. :1aT T is I where all vowels are replaced with free variables. oS, S is T sorted (all free variables come first). I:2f Find all vowels in I. @~ Shuffle them. :LcS, This shuffle concatenated with L (whatever it may be) results in S. This will unify the free variables in S with the shuffled vowels. Tc Output is the concatenation of elements of T. ``` * Predicate 1: ``` . Input = Output… '~e@V …provided that it is not a vowel. ; Otherwise Output is a free variable. ``` * Predicate 2: ``` e. Output is an element of the input… ~e@V, … and it is a vowel. ``` [Answer] ## Javascript (ES6), ~~78~~ 76 bytes ``` s=>s.replace(r=/[aeiou]/g,_=>l.pop(),l=s.match(r).sort(_=>Math.random()-.5)) ``` *Saved 2 bytes thanks to apsillers* ### Alternate version proposed by apsillers (76 bytes as well) ``` s=>s.replace(r=/[aeiou]/g,[].pop.bind(s.match(r).sort(_=>Math.random()-.5))) ``` ### Test ``` let f = s=>s.replace(r=/[aeiou]/g,_=>l.pop(),l=s.match(r).sort(_=>Math.random()-.5)) console.log(f("the quick brown fox jumps over the lazy dog.")) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 15 bytes ``` tt11Y2m)tnZr7M( ``` [Try it online!](http://matl.tryitonline.net/#code=dHQxMVkybSl0blpyN00o&input=J3RoZSBxdWljayBicm93biBmb3gganVtcHMgb3ZlciB0aGUgbGF6eSBkb2cuJw) ### Explanation ``` tt % Take input string implicitly. Duplicate twice 11Y2 % Predefined string: 'aeiou' m % Logical index that contains true for chars of the input that are vowels ) % Get those chars from the input string. Gives a substring formed by the % vowels in their input order tnZr % Random permutation of that substring. This is done via random sampling % of that many elements without replacement 7M % Push logical index of vowel positions again ( % Assign the shuffled vowels into the input string. Display implicitly ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~14~~ 13 bytes ``` ō²f\v NÌr\v@o ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=9rJmXHYKTsxyXHZAbw==&input=InRoaXMgaXMgYSB0ZXN0IgotUQ==) --- ## Explanation ``` :Implicit input of string U. ö² :Generate a random permutation of U. f\v :Get all the vowels as an array. \n :Assign that array to U. NÌ :Get the last element in the array of inputs (i.e., the original value of U) r\v :Replace each vowel. @o :Pop the last element from the array assigned to U above. ``` [Answer] # Pyth, 26 bytes ``` J"[aeiou]"s.i:QJ3.Sf}TPtJQ ``` A program that takes input of a quoted string and prints the shuffled string. [Try it online](https://pyth.herokuapp.com/?code=J%22%5Baeiou%5D%22s.i%3AQJ3.Sf%7DTPtJQ&test_suite=1&test_suite_input=%22%22%0A%22a%22%0A%22cwm%22%0A%22the+quick+brown+fox+jumps+over+the+lazy+dog.%22%0A%22abcdefghijklmnopqrstuvwxyz%22%0A%22programming+puzzles+%26+code+golf%22%0A%22fatalize%22%0A%22martin+ender%22&debug=0) **How it works** ``` J"[aeiou]"s.i:QJ3.Sf}TPtJQ Program. Input: Q J"[aeiou]" J="[aeiou]" :QJ3 Split Q on matches of regex J, removing vowels PtJ J[1:-1], yielding "aeiou" f}T Q Filter Q on presence in above, yielding vowels .S Randomly shuffle vowels .i Interleave non-vowel and vowel parts s Concatenate and implicitly print ``` [Answer] # PHP, ~~144~~ 129 bytes Using lowercase input ``` $r=Aaeiou;$v=str_shuffle(preg_replace("#[^$r]+#",'',$a=$argv[1]));for(;$i<strlen($a);)echo strpos($r,$a[$i++])?$v[$j++]:$a[$i-1]; ``` Explanation: ``` $r="aeiou"; // set vowels preg_replace("#[^$r]+#",'',$argv[1]) // find all vowels in input $v=str_shuffle() // shuffle them for(;$i<strlen($a);) // run through the text strpos($r,$a[$i++])?$v[$j++]:$a[$i-1]; // if it's a vowel print the j-th shuffled vowel else print original text ``` [Answer] ## Actually, 24 bytes ``` ;"aeiou";╗@s@`╜íu`░╚@♀+Σ ``` [Try it online!](http://actually.tryitonline.net/#code=OyJhZWlvdSI74pWXQHNAYOKVnMOtdWDilpHilZpA4pmAK86j&input=Im1lZ28i) Explanation: ``` ;"aeiou";╗@s@`╜íu`░╚@♀+Σ ; dupe input "aeiou";╗ push vowels, store a copy in reg0 @s split one copy of input on vowels @`╜íu`░ take characters from other copy of input where ╜íu the character is a vowel (1-based index of character in vowel string is non-zero) ╚ shuffle the vowels @♀+ interleave and concatenate pairs of strings Σ concatenate the strings ``` [Answer] # Bash, 89 Assumes all input to be lowercase. ``` a=`tee z|grep -o [aeiou]` [ -n "$a" ]&&tr `tr -d \ <<<$a` `shuf -e $a|tr -d ' '`<z||cat z ``` [Answer] ## PowerShell v3+, ~~155~~ 99 bytes ``` param([char[]]$n)$a=$n|?{$_-match'[aeiou]'}|sort{random};-join($n|%{if($_-in$a){$a[$i++]}else{$_}}) ``` *Big props to @[Ben Owen](https://codegolf.stackexchange.com/users/56849/ben-owen) for the 56-byte golf* Takes input `$n`, expecting all lowercase, immediately casts it as a `char`-array. We pipe that into a `Where-Object` clause to pull out those elements that `-match` a vowel, pipe them to `Sort-Object` with `{Get-Random}` as the sorting mechanism. Calling `Get-Random` without qualifiers will return an integer between `0` and `[int32]::MaxValue` -- i.e., assigning random weights to each element on the fly. We store the randomized vowels into `$a`. Finally, we loop through `$n`. For each element, `|%{...}`, if the current character is somewhere `-in` `$a`, we output the next element in `$a`, post-incrementing `$i` for the next time. Otherwise, we output the current character. That's all encapsulated in parens and `-join`ed together into a string. That string is left on the pipeline, and output is implicit at program conclusion. ### Test cases ``` PS C:\Tools\Scripts\golfing> 'a','cwm','the quick brown fox jumps over the lazy dog.','abcdefghijklmnopqrstuvwxyz','programming puzzles & code golf','fatalize','martin ender'|%{.\vawols.ps1 $_} a cwm thu qaeck brown fix jomps ovor thu lezy deg. abcdofghejklmnupqrstivwxyz prugrammong pizzles & code golf fitaleza mertin endar ``` [Answer] # Python 3, 106 bytes Lowercase only. ``` import re,random def f(s):s=re.split('([aeiou])',s);v=s[1::2];random.shuffle(v);s[1::2]=v;return''.join(s) ``` [Answer] # [PHP >= 5.3](http://sandbox.onlinephpfunctions.com/), ~~139~~ 136 bytes (and no errors thrown) ``` array_map(function($a,$b){echo$a.$b;},preg_split("/[aeiou]/",$s=$argv[1]),str_split(str_shuffle(implode(preg_split("/[^aeiou]/",$s))))); ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 29 bytes **Solution:** ``` {x[a:&x in"aeiou"]:x@(-#a)?a} ``` [Try it online!](https://tio.run/##y9bNz/7/v7oiOtFKrUIhM08pMTUzv1Qp1qrCQUNXOVHTPrFWqSQjVaGwNDM5WyGpKL88TyEtv0IhqzS3oFghvyy1SAEknZNYVamQkp@up/T/PwA "K (oK) – Try It Online") **Examples:** ``` "pregrommeng pizzlas & codo gulf" {x[a:&x in"aeiou"]:x@(-#a)?a}"programming puzzles & code golf" "pregremmong puzzlos & coda gilf" {x[a:&x in"aeiou"]:x@(-#a)?a}"programming puzzles & code golf" "pregrommeng pazzlos & cidu golf" ``` **Explanation:** Find locations of the vowels and replace with the vowels drawn in a random order. ``` {x[a:&x in"aeiou"]:x@(-#a)?a} / the solution { } / anonymous function with input x x[ ] / index into x at these indices x in"aeiou" / is character a vowel & / indices where true a: / assign to add : / assign ?a / draw randomly from a ( ) / do this together #a / count length of a - / negate (draws from list, no duplication) x@ / apply these indices to input ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 [bytes](https://github.com/abrudz/SBCS) ``` {⍵[?⍨≢⍵]}@{⍵∊'AEIOU'} ``` [Try it online!](https://tio.run/##hY/NToNAFIX3PMVdOSWpPoAbpTCltMBQCv3BuKDtUEn4szMsGtOt0SZNjHs3XfkCvhAvUgFLY9y4mu@ec@bkXj@LLpcbP0pXx2L/AWbK6TW4WUbXC59RCJMs5xAy8BnLY7o8PhX7r7ubYv9ZvB5KvN/eVkrxskMS1oiLtse6x/DDBII8WfAwTaDF8nkcMlayKAgBFM9v8G@RIFRFDmX8XCQIvBqr78Xu0EYlvQNqB7@i9dZBuo59/qNq9QVVkOS8xD9ZBq2kvpmyhZ9RYGGyiig85qVYekiE@QaWaT6PSgP4A41LEYniaRWETq/UgDwxGnR6GIauJg@gY5OJCV0yhb5rWCMgY2xDZeuSNwOFqFfnno6s4K7a0/oD3TCJNbRHjjueTGdek7BsotqSYWimCpbreToewQXIRMGgEr3bxLqSI@mah5vZkGxHMwGbCrbRNw "APL (Dyalog Unicode) – Try It Online") Assumes uppercase. [Answer] # [Kotlin](https://kotlinlang.org), ~~122~~ 118 bytes ``` x->val v=x.filter{"aeiuo".contains(it)}.toList().shuffled() x.split(Regex("[aeiou]")).reduceIndexed{i,a,s->a+v[i-1]+s} ``` [Try it online!](https://tio.run/##bVBNa8MwDL3nV4gchkMbw66F9j7YaTuWHtxYdt36I/VH6ibkt2cu22lEIJDe0@NJurmolV1EsmCYsmRgnnkJJcMOvqNXVjYwVVCiL03UlghS103zH2IrWPcwK2i8INyT6m5w9u5hQbgM12T6AG5ADy9as/EJ3Em6ZnTuOAp5UdebNtb1dx9iGh75Oa4M995Jz4wpZ0CfxlFjgDfoHEeQTosVhWCRaTXiCmWYj8oCWo7@RVdzVQ1Mg9iRv0@1h99iPy25Pby4YZ@pUDqin2qGKrmads7G8upAVGxmGt2nCpE0NFySEBo5aapMQ69VJF8oMZP6WIQunYol9chThx9lg4x8Ulu2De2BbYajat9PmzAv8/ID "Kotlin – Try It Online") ]
[Question] [ Given a character, output (to the screen) the entire qwerty keyboard layout (with spaces and newlines) that follows the character. The examples make it clear. Input 1 ``` f ``` Output 1 ``` g h j k l z x c v b n m ``` Input 2 ``` q ``` Output 2 ``` w e r t y u i o p a s d f g h j k l z x c v b n m ``` Input 3 ``` m ``` Output 3 (Program terminates without output) Input 4 ``` l ``` Output 4 ``` z x c v b n m ``` **Shortest code wins.** (in bytes) P.S. Extra newlines, or extra spaces at the end of a line are accepted. [Answer] ## CJam, ~~42~~ 40 bytes ``` "wertyuiop asdfghjkl zxcvbnm"q/W=S%Sf*N* ``` [Test it here.](http://cjam.aditsu.net/#code=%22wertyuiop%20asdfghjkl%20zxcvbnm%22q%2FW%3DS%25Sf*N*&input=f) ### Explanation ``` "we...nm" e# Push the letters in order, without q. We don't need q, because it will never e# be part of the output. q/ e# Split the string around the input. If the input is "q", the entire string e# will go into a single chunk. W= e# Select the last chunk. S% e# Split the string around spaces, discarding empty segments (only relevant for the e# first segment if the input is "p" or "l"). Sf* e# Join each line by spaces. N* e# Join the lines by linefeeds. ``` [Answer] # Pyth, 33 bytes ``` jjL\ cec."`zÈ´ýß44,ûtKÕÀ@"z\` ``` Note that some characters are unprintable. Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=jjL%5C+cec.%22%60z%01%1E%C3%88%10%C2%B4%C3%BD%C3%9F44%2C%C3%BBtK%C3%95%C3%80%04%40%22z%5C%60&input=f&debug=0). ### How it works ``` jjL\ cec."`z…"z\` ."`z…" Unpack …, with lowest character '`' and highest character `z`. c z Split at occurrences of the input (z). e Retrieve the last resulting chunk. c \` Split into rows, at backticks. jL\ Separate the characters of each row by spaces. j Separate the rows by linefeeds. ``` [Answer] # Perl, 56 bytes ``` #!perl -p 'qwertyuiop asdfghjkl zxcvbnm'=~/$_ ?/;$_=$';s/\B/ /g ``` Counting the shebang as 3, input is taken from stdin. If a leading newline isn't a concern for inputs `p` and `l`, then `/$_\n?/` could be replaced with a bare `$_` to save 4. --- **Sample Usage** ``` $ echo g|perl qwerty.pl h j k l z x c v b n m $ echo v|perl qwerty.pl b n m ``` [Answer] # [GS2](https://github.com/nooodl/gs2), ~~38~~ 37 bytes ``` ♦wertyuiop asdfghjkl zxcvbnm♣B3$,■♪2◙ ``` The source code uses the [CP437](https://en.wikipedia.org/wiki/Code_page_437#Characters) encoding. [Try it online!](http://gs2.tryitonline.net/#code=4pmmd2VydHl1aW9wIGFzZGZnaGprbCB6eGN2Ym5t4pmjQjMkLOKWoOKZqjLil5k&input=Zg) ### Test run ``` $ base64 -d > qwerty.gs2 <<< BHdlcnR5dWlvcCBhc2RmZ2hqa2wgenhjdmJubQVCMyQs/g0yCg== $ wc -c qwerty.gs2 37 qwerty.gs2 $ echo -n f | gs2 qwerty.gs2 g h j k l z x c v b n m ``` ### How it works ``` ♦ Begin string literal. wertyuiop asdfghjkl zxcvbnm ♣ End string literal. B Swap the string with the input. 3 Split the string at the input character. $ Select the last chunk. , Split the selected chunk at spaces. ■ Map over the resulting array: ♪ Push ' '. 2 Join the characters, separating by ' '. ◙ Push a linefeed. ``` [Answer] # JavaScript (ES6), 60 bytes ``` x=>[...`qwertyuiop asdfghjkl zxcvbnm`].join` `.split(x)[1] ``` Uses the same technique as most other answers. Suggestions welcome! [Answer] # C#, 112 bytes ~~105~~ ~~110~~ Count went up by 5 bytes, but more correct! Thanks @MartinBüttner!! ``` void c(char i){System.Console.Write(@"q w e r t y u i o p a s d f g h j k l z x c v b n m".Split(i)[1].Trim());} ``` Un-golfed ``` void c(char i) { System.Console.Write(@"q w e r t y u i o p a s d f g h j k l z x c v b n m".Split(i)[1].Trim()); } ``` [Answer] ## Python, 83 bytes ``` lambda c,s="q w e r t y u i o p\na s d f g h j k l\nz x c v b n m":s[s.index(c)+2:] ``` [Try it online](http://ideone.com/fork/mYlGTU) [Answer] # Ruby, ~~63~~ 57 bytes Takes the character as command line argument: `ruby keyboard.rb e` ``` "qwertyuiop asdfghjkl zxcvbnm".scan$*[0] puts$'.chars*' ' ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), ~~50~~ ~~45~~ 44 bytes TeaScript is JavaScript for golfing. ``` `qwertyuiop asdfghjkl zxcvbnm`.s×[1]s(b)j(p) ``` ### Ungolfed and explanation ``` `qwertyuiop asdfghjkl zxcvbnm`.s(x)[1]s(b)j(p) // Implicit: x = input string `...` // Take the qwerty string, .s(x) // and split it at the input. [1] // Take the second item from this, s(b) // split it into chars, j(p) // and join the result with spaces. // Implicit: output final expression ``` [Answer] # JavaScript ES6, 73 ``` f=x=>[...(k=`qwertyuiop asdfghjkl zxcvbnm`).slice(k.search(x)+1)].join` ` ``` If a leading newline is not allowed when parameter is `p` or `l`, then **83** ``` f=x=>(k=`q w e r t y u i o p a s d f g h j k l z x c v b n m`).slice(k.search(x)+2) ``` [Answer] # Sed, 59 characters (58 characters code + 1 character command line option.) ``` s/./&qwertyuiop\nasdfghjkl\nzxcvbnm/ s/(.).*\1// s/\w/& /g ``` Sample run: ``` bash-4.3$ echo -n 'f' | sed -r 's/./&qwertyuiop\nasdfghjkl\nzxcvbnm/;s/(.).*\1//;s/\w/& /g' g h j k l z x c v b n m ``` [Answer] # Ruby, ~~86~~ ~~87~~ ~~83~~ ~~71~~ 66 ``` puts"qwertyuiop asdfghjkl zxcvbnm ".split($*[0])[1].gsub /./,'\& ' ``` The extra space after `m` is to prevent the program from crashing if the input is 'm'. Thanks to @manatwork for ~16 bytes of tips [Answer] # PHP, 88 bytes ``` <?=$m[1&ereg("$argn.(.*)",'q w e r t y u i o p a s d f g h j k l z x c v b n m',$m)]; ``` Requires the `-F` command line option, counted as 3. Default .ini setting are assumed (you may disable your local .ini with `-n`). --- **Sample Usage** ``` $ echo g|php -F qwerty.php h j k l z x c v b n m $ echo v|php -F qwerty.php b n m ``` [Answer] # Prolog (SWI), ~~153~~ 133 bytes **Edit:** Cut 20 bytes with tips from @Fatalize **Code** ``` b([A,_|T],[H]):-A=H,writef('%s',[T]);b(T,[H]). p(X):-name(X,C),b(`q w e r t y u i o p \r\na s d f g h j k l \r\nz x c v b n m`,C),!. ``` **Explanation** ``` p(X):-name(X,C), % Get charcode of input b(`q w e r t y u i o p \r\na s d f g h j k l \r\nz x c v b n m`,C),!. % Get keyboard chars as charcodes and call b b([A,_|T],[H]):-A=H, % If list head is input element writef('%s',[T]); % Interpret list as charcodes and print as string b(T,[H]). % Else remove first element of list and try again ``` **Examples** ``` >p(f). g h j k l z x c v b n m >p(q). w e r t y u i o p a s d f g h j k l z x c v b n m ``` [Answer] # Befunge, 122 bytes ``` "m n b v c x z"25*"l k j h g f d s a"v v1-")"g2-"U"~"q w e r t y u i o p"*25< >-:#v_$>:#,_@ZVD0FHJ:LNP^\<>,2B48X.T6R ^1$\< ``` It has been tested here: [Befunge-93 Interpreter](http://www.quirkster.com/iano/js/befunge.html). ### How it works * `'q w e r t y u i o p\na s d f g h j k l\nz x c v b n m'` is pushed on the stack. * The number of values to discard (hardcoded in `@ZVD0FHJ:LNP^\<>,2B48X.T6R`) N is pushed. * First N values are discarded and the remaining values are printed. ### Note I picked the encoding so the string starts with `@` in order to overlap with the program. This string is generated with the following python code: ``` import string letters = string.ascii_lowercase base = 'q w e r t y u i o p a s d f g h j k l z x c v b n m' print(''.join(chr(base.index(x) + 32 + 9 + 3) for x in letters)) ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~49~~ ~~42~~ ~~41~~ ~~40~~ 38 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` `qØÆyuiop\n?dfghjkl\nzxcvbnm`qU g1 ¬qS ``` The `?` should be the unprintable Unicode char U+0086. ### How it works ``` // Implicit: U = input char `...` // Take the compressed string and decompress it. qU g1 // Split the string at the input and take the second item. ¬qS // Split into chars, then join with spaces. // Implicit: output final expression ``` Now beating CJam! :) Suggestions welcome! ### Non-competing version, 12 bytes ``` ;Dv qU g1 ¬¸ ``` As of Jan 11, I've [added](https://github.com/ETHproductions/Japt/commit/0e43c90f2853308f4f7f7aca7759dd29a1eac1a5) a cool new feature to Japt: If the program contains a leading comma, the variables `ABCDEFGHIJL` are redefined to various values. `D` is set to `"QWERTYUIOP\nASDFGHJKL\nZXCVBNM"`, so `;Dv` is enough to replace the string here. [Answer] # Mumps - 102 Bytes Golfed script: ``` S A="qwertyuiopasdfghjklzxcvbnm",B=0 R P F I=1:1:$L(A) S Q=$E(A,I) W:B Q," " X:"qpl"[Q "W !" S:Q=P B=1 ``` Ungolfed and commented: ``` S A="qwertyuiopasdfghjklzxcvbnm" ; Need the qwerty order S B=0 ; boolean flag for printing, default to false. R P ; read from stdin into P F I=1:1:$L(A) D ; Count I from 1 to length of qwerty variable; do all of the following: . S Q=$E(A,I) ; Extract 1 letter (at position I) from A and save in Q. . W:B Q," " ; If our print flag (B) is true, print the letter in Q & a space. . X:"qpl"[Q "W !" ; If Q is q, p or l, write a cr/lf . S:Q=P B=1 ; If Q == P (stdin) change our print flag from false to true. ``` The rule allowing extra newlines saved me almost 10 bytes... [Answer] # Java - 107 bytes ``` void q(char c){System.out.print("qwertyuiop\nasdfghjkl\nzxcvbnm ".split(""+c)[1].replaceAll("\\w","$0 "));} ``` Ungolfed with wrapper-class reading from System.in ``` public class Qwerty { public static void main(String[] args) { new Qwerty().q(new java.util.Scanner(System.in).next().charAt(0)); } void q(char c) { System.out.print("qwertyuiop\nasdfghjkl\nzxcvbnm ".split(""+c)[1].replaceAll("\\w","$0 ")); } } ``` If spaces at *start-of-line* were acceptable, we could go down to 99 bytes: ``` void q(char c){System.out.print("qwertyuiop\nasdfghjkl\nzxcvbnm ".split(""+c)[1].replace(""," "));} ``` [Answer] # 8086 machine code + DOS, 61 bytes Hexdump (with ASCII view on the right): ``` B8 1E 01 8B F8 CD 21 B1 1F F2 AE 8B F7 AC 8A D0 ......!......... B4 02 CD 21 80 E2 20 74 02 CD 21 E2 F0 C3 71 77 ...!.. t..!...qw 65 72 74 79 75 69 6F 70 0D 0A 61 73 64 66 67 68 ertyuiop..asdfgh 6A 6B 6C 0D 0A 7A 78 63 76 62 6E 6D 0D jkl..zxcvbnm. ``` Assembly source code (can be assembled with tasm): ``` .MODEL TINY .CODE org 100h MAIN PROC mov ax, offset qwerty ; sets ah=1 (coincidence) mov di, ax ; di points to the string int 21h ; reads a char from keyboard into al mov cl, 31 ; cx is the length of the string repne scasb ; look for the char mov si, di ; si now points beyond the found char myloop: lodsb ; load a char mov dl, al mov ah, 2 int 21h ; output the char and dl, 20h ; if it's a letter, set it to a space jz print_done ; if it's not a letter, don't print a space int 21h ; if it's a letter, print a space print_done: loop myloop ; repeat until end of string ret qwerty db 'qwertyuiop',13,10,'asdfghjkl',13,10,'zxcvbnm',13 MAIN ENDP END MAIN ``` Two fun things here: 1. The offset of the `qwerty` string is `0x011e`. The upper byte of it is 1, which is the DOS function number for character input. This saves 1 byte in the code. 2. All lower-case letters have bit 5 set. When doing an `AND` with `0x20`, they are all turned into a space, which is then printed. If the previous char was an end-of-line byte, it gets turned into 0, and no space is output. This is used to avoid the nonsensical sequence `0d 20 0a 20` at end of line. One almost-fun thing: I tried to search for the input char starting at address 0 (that decreased program size by 2 bytes), instead of the usual place (start of the string). This almost worked; however, it failed for input `t`, because the code itself contains the byte `t` (as part of the encoding of a conditional jump). So for `t`, it would output a few junk bytes: [![output](https://i.stack.imgur.com/2XE5U.png)](https://i.stack.imgur.com/2XE5U.png) [Answer] ## Python 2, ~~58~~ ~~67~~ 63 bytes ## ``` lambda x:" ".join("qwertyuiop\nasdfghjkl\nzxcvbnm".split(x)[1]) ``` Takes input as a string or char. Splits the string at the input and prints off everything after the split. (First time code-golfing, please be gentle :P ) EDIT: Didn't see the additional spaces required between characters, added now EDIT 2: Modified to be an anonymous lambda function and removing the additional split arg, saving 4 bytes [Answer] # Ruby, ~~59 57~~ 67 bytes Added spaces between letters ``` puts"qwertyuiop\nasdfghjkl\nzxcvbnm".split(gets.chop)[-1].chars*' ' ``` [Answer] # JavaScript, 88 bytes ``` function s(d){alert("qw e r t y u i o p\na s d f g h j k l\nz x c v b n m".split(d)[1])} ``` (no need in the space after the first char, as it never gets to the output) Alerts the keyboard when you call `s("some letter")`. Can be also made with `document.write()` or `console.log()`, but hey, it's longer :P Demo: ``` function s(d){alert("qw e r t y u i o p\na s d f g h j k l\nz x c v b n m".split(d)[1])} s(prompt("Enter the key")); ``` [Answer] **SQL (MS T-SQL), 172 bytes** ``` CREATE PROC c @I CHAR(1) AS DECLARE @S CHAR(49) SET @S = 'w e r t y u i o p' + CHAR(13) + 'a s d f g h j k l' + CHAR(13) + 'z x c v b n m' PRINT RIGHT(@S,LEN(@S)-CHARINDEX(@I,@S)) ``` Ungolfed: ``` CREATE PROC c -- Create a procedure named "c" @I CHAR(1) -- Which is invoked with a single character input (@I) AS DECLARE @S CHAR(49) = 'w e r t y u i o p' + CHAR(13) + 'a s d f g h j k l' + CHAR(13) + 'z x c v b n m' -- Initialise the entire output omitting "q " as @S PRINT RIGHT(@S,LEN(@S)-CHARINDEX(@I,@S)) -- Use the charindex funtion to effectively substring @S ``` I'm new here, only just discovered this site. No idea if I've posted correctly or if T-SQL is allowed but I know the procedure above works. [Answer] # O 2.2, ~~48~~ 46 characters ``` "qwertyuiop asdfghjkl zxcvbnm "i/r;s{n.U=ST?}d ``` Sample run: ``` bash-4.3$ ./o keyboard.o <<< 'f' g h j k l z x c v b n m ``` ## O, 61 characters ``` "qwertyuiop\nasdfghjkl\nzxcvbnm\n"i/r;""/rl{.o"\n"={}{' o}?}d ``` Sample run: ``` bash-4.3$ java xyz.jadonfowler.o.O keyboard.o <<< 'f' g h j k l z x c v b n m ``` [Answer] # [Hassium](http://HassiumLang.com), 114 Bytes ``` func main(){k="qwertyuiop\nasdfghjkl\nzxcvbnm\n"foreach(l in k.substring(k.index(input())))print(l!="\n"?l+" ":l)} ``` Run online and see expanded with test case [here](http://HassiumLang.com/Hassium/index.php?code=f0fbf3d3e9709da3dfaa3c9942e80b22) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-hR`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;Dv qU ®·®¬¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWhS&code=O0R2IHFVIK63rqy4&input=InEi) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~29~~ 35 bytes *Edit +6 bytes when I realised that the letters need to be separated by spaces* ``` ¶mJ' ¶!2x¨qw²yuiop₄sdfghjkl¶zxcvbnm ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@hbble6gqHtikaVRxaUVh@aFNlaWZ@waOmluKUtPSMrOycQ9uqKpLLkvJy////H62epq6jXgjEuUCcox4LAA "Husk – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 38 bytes ``` ↓2↓≠←⁰¶mJ' ¶¨qw²yuiop₄sdfghjkl¶zxcvbnm ``` [Try it online!](https://tio.run/##yygtzv7//1HbZCMgftS54FHbhEeNGw5ty/VSVzi07dCKwvJDmypLM/MLHjW1FKekpWdkZecc2lZVkVyWlJf7////dAA "Husk – Try It Online") [Answer] # JavaScript, 77 bytes ``` alert(`w e r t y u i o p a s d f g h j k l z x c v b n m`.split(prompt())[1]) ``` ### [Fiddle](https://jsfiddle.net/5bvf3jrm/) [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 53 bytes ``` {` 0:1_*|x\"\n"/" "/'$$`qwertyuiop`asdfghjkl`zxcvbnm} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqjpBwcDKMF6rpiJGKSZPSV9JQUlfXUUlobA8taiksjQzvyAhsTglLT0jKzsnoaoiuSwpL7f2f5qCUqHSfwA "K (ngn/k) – Try It Online") Uses `"\n"/" "/'$$`...`...`...` to (slightly) compress `"q w e r t y u i o p\na s d f g h j k l\nz x c v b n m"`. It then splits that string on the input character, taking the remainder that occurs after that character. ]
[Question] [ A string can be *shifted* by a number `n` by getting the byte value `c` of each character in the string, calculating `(c + n) mod 256`, and converting the result back to a character. As an example, shifting `"ABC123"` by 1 results in `"BCD234"`, shifting by 10 in `"KLM;<="`, and shifting by 255 in `"@AB012"`. ### The Task Pick as many numbers `n` with `0 < n < 256` as you dare and write a program or function that takes a string as input and * returns the string unchanged when the source code is unchanged, but * returns the string shifted by `n` when the source code is shifted by `n`. ### Rules * The score of your submission is the number of supported `n`, with a higher score being better. The maximum score is thus 255. * Your submission must support at least one shift, so the minimal score is 1. * In case of a tie the shorter program wins. * All shifted programs need to be in the same language. [Answer] # Brainfuck, score: 31 (2208 bytes) Base64-encoded program: ``` LFsuLF0oVycnJycqKFkkUyMjIyMjIyMjJiRVIE8fHx8fHx8fHx8fHx8iIFEMOwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLDgw9CDcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcKCDkEMwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMGBDUAL8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w78CADHDrBvDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Ouw6wdw6gXw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Oqw6gZw6QTw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6bDpBXDoA/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Oiw6ARw4zDu8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OOw4zDvcOIw7fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OKw4jDucOEw7PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4bDhMO1w4DDr8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8OCw4DDscKsw5vCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8Krwq7CrMOdwqjDl8KpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqrCqMOZwqTDk8KlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKmwqTDlcKgw4/CocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqLCoMORwozCu8KNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKOwozCvcKIwrfCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJworCiMK5woTCs8KFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwobChMK1woDCr8KBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKCwoDCsWzCm21tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1ubMKdaMKXaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpamjCmWTCk2VlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZmTClWDCj2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFiYMKRTHtNTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU5MfUh3SUlJSUlJSUlJSUlJSUlJSUlJSUlJSUlJSUlJSUpIeURzRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRkR1QG9BQUFBQUFBQUFBQUFBQUFBQUFBQUJAcQ== ``` Works for shifts 0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232 and 236. For every value between 0 and 255, there is exactly one of those shifts that sends that character to a valid brainfuck instruction. The program relies on 8-bit cells with wrapping on overflows. This could probably be golfed quite a bit, as the shift just consists of a repeated `+` or `-` (whichever is shorter). Python code used to generate this: ``` l = [0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232, 236] shift = lambda s,n:"".join(chr((ord(i)+n)%256) for i in s) code = "" for i in l: code += shift(",[{}.,]".format(i*"+" if i<=128 else (256-i)*"-"),-i) ``` [Answer] # lHaskell, Score 255 (27,026 bytes) The program works but putting it in my clipboard seems to destroy it so [here is code that outputs my program.](https://tio.run/##jZCxasNADIb3ewoRPMS0PkohtNDEg5MlQ6eOiSmqffEZ2yf3TkddyLu756YJgSzdfkmfxIc@0OlxLJAhhd5SZbGTrXZCFZpgJkRadz1Zhk@PbX2oVQkbZJTZN6s3trWpAB1kIu2wNquSYFgmmawUr8mwMuxeMtl7Dug@CgmLZh912M/v4qn2ZurAIMQMjmC90ega1bbXJuP4X4U/7He41mhF6lfPTxc1kd7KhV6weX2Hs@XuJHlynCcmji@aIRRkwqcCw9go8DDcX@EHS9023K2UlUznRLaMI6fpC0yAS0v9tJcfzTLZPUj5uFjk@Q8 "Bash – Try It Online") ## Verification So if copying things to a clipboard breaks it how do I verify that it works? You can use [this here](https://tio.run/##lVHBasJAEL3vVwwhUEPrUgRRqMkh9tJDvXhUKdNk3QSTnXSzSy347@lGa4iWgr09Zt7Mm/fmHeusaRbhZMqWoRfnEqi4AyGlx1iCBiKoNEmNJS@ymokkI/DysiJt4MNikW9zkcIzGuTxlxFLo3MlAWuIWYm5ClOC/WwYcynMnJQRytRPMa@sccy17xAmu7VfYjW49xdBW7GqrcHea6VHvBNlLLpNN/qv8IUsYx4cQFuVYb0TRdG3f9Voj3NHkjW9bPzl1Xy//RfnuKppbjX4Qzs25xlqFtlwOumMs@i3dVdzXl/f4JzB6hTBKYHBUAVBF4IDCSn3fMcxuBNgYf/Qo281lS9urxSaGzoj0mng1xl9gnLkVFPVzm0OajZcPXI@Go83m28). You can adjust `N` and the string (currently `Big ol' egg`) to see that it works yourself. [This](https://tio.run/##tZFBa4MwGIbv@RUfElilM3SFssGqB7vLDvPSo5WRaapSTVz8pA76312sbbEdg112@8z3ap738YPXWdetXcvPU1DFHYg0tQiJOYIHlVap5iUrspqIOFNgNl5eVkojfDa8yLe5SOCFI2f@F4o16lymwGvwiVfyXLqJgnbp@CwVuFIShcT62WdVgya6oWbi8W5DS15Npnb/3Mj@BFpCLDiAbmTG650oijGJ4VINMmyRkMC1ZoZpn@WFgBBoAE6BMF8sICKJIjBA/xcyDa6grd7Y/CgLen8nypsi81GHY3RgpOubxlf7X1Pn@4ZQ4NKQBtOHvrwUXffX4qfYcbnKuCZe4z49XoQQ76cSc2YcvL3D2U04qBnMTBxp2xc1ZoiVNEpMBvlOQAPt/Si@1ap8Nd9NhWaozpPSiU3rTO1BmnCiVdW/Fx3k0glnjJmfHEXf) will test all N on a single input in succession but tends to time out. ## Explanation This abuses literate Haskell's comment notation. In literate Haskell any line that does not start with `>` is a comment. So to make our code work we make 255 copies of the program each shifting by `n` and then we shift each individual copy by `-n`. [Answer] # C, score: 1 (73 bytes) ``` aZ0;/*0\:..*/f(s){puts(s);}// e'bg`q)r(zenq':)r:**r(otsbg`q'')r*0($145(:| ``` [Try it online!](https://tio.run/##S9ZNT07@/z8xysBaX8sgxkpPT0s/TaNYs7qgtKQYSFvX6utzpqonpScUahZpVKXmFapbaRZZaWkVaeSXFIOE1dU1i7QMNFQMTUw1rGr@Z@aVKOQmZuZpaHJVcykAQZqGkqOTs6GRsZKmNVftfwA) **Shifted by 1:** ``` b[1<0+1];//+0g)t*|qvut)t*<~00 f(char*s){for(;*s;++s)putchar((*s+1)%256);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z8p2tDGQNsw1lpfX9sgXbNEq6awrLQESNvUGRhwpWkkZyQWaRVrVqflF2lYaxVba2sXaxaUloCENTS0irUNNVWNTM00rWv/Z@aVKOQmZuZpaHJVcykAQZqGkqOTs6GRsZKmNVftfwA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), Score: 3 (24 bytes) ``` ¶Ä0(ä.g){n·Å0)åH*oHÆ0*æI ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K2w4QwKMOkLmcpe27Ct8OFMCnDpUgqb0jDhjAqw6ZJ//90ZXN0 "05AB1E – Try It Online") **Explanation** ``` ¶Ä0(ä.g){n·Å0)åH*oHÆ0*æ # Doesn't matter I # Push the original input to the stack, implicit display ``` Shifted once: ``` ·Å1)å/h*|o¸Æ1*æI+pIÇ1+çJ ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K3w4UxKcOlL2gqfG/CuMOGMSrDpkkrcEnDhzErw6dK//90ZXN0 "05AB1E – Try It Online") **Explanation** ``` ·Å1)å/h*|o¸Æ1*æI+p # Doesn't matter IÇ # Push the ASCII values of the input 1+ # Increment by 1 çJ # Push the chars of the ASCII values, join, implicit display ``` Shifted twice: ``` ¸Æ2*æ0i+}p¹Ç2+çJ,qJÈ2,èK ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K4w4YyKsOmMGkrfXDCucOHMivDp0oscUrDiDIsw6hL//90ZXN0 "05AB1E – Try It Online") **Explanation** ``` Æ2*æ0i+}p # Doesn't matter ¹Ç # Push the ASCII values of the input 2+ # Increment by 2 çJ # Push the chars of the ASCII values, join ,q # Print and terminate ``` Shifted thrice: ``` ¹Ç3+ç1j,~qºÈ3,èK-rKÉ3-éL ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K5w4czK8OnMWosfnHCusOIMyzDqEstckvDiTMtw6lM//90ZXN0 "05AB1E – Try It Online") **Explanation** ``` ¹Ç # Push the ASCII values of the input 3+ # Increment by 3 ç1j # Push the chars of the ASCII values, join ,q # Print and terminate ``` [Answer] # Javascript, score: ~~1~~ 4 (~~94~~ 346 bytes) Pretty straight-forward, has different sections commented out when rotated, the difficult bit was finding usable variable names and comment sections that don't break Javascript syntax. Unrotated: ``` hc/*% *%nnS/0S eb^[fRR _SbS/0Efd[`Y Xda_5ZSd5aVWS UZSd5aVW3f"#&$'( \a[`RR!! %34hc/*$ifb_jVV$cWfW34Ijh_d]$\hec9^Wh9eZ[W$Y^Wh9eZ[7j&!'&(+,$`e_dVV%%%*89hc/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&0$ -01$$$)ejdi[[***/=>/*ch*/hc//chhcchvw*/g¬©¥¢­g¦©avw­«¢§ g«¨¦|¡«|¨aaag¡«|¨z­aibdjrrb^knobbbg£¨¢§ ``` Rotated by 5: ``` mh4/*%$/*ssX45X%jgc`kWW%dXgX45Jki`e^%]ifd:_Xi:f[\X%Z_Xi:f[\8k' "(+ ),- %af`eWW &&%*89mh4/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&,+$ -01$$$)ejdi[[***/=>mh4.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+5)%256))).join``///4BC4/hm/4mh44hmmhhm{|/4l±®ª§²l«®f{|²°§¬¥l¤°­«¦°­¢£fffl¡¦°­¢£²fngiowwgcpstgggl¨­§¬ ``` Rotated by 10: ``` rm94/*)4/xx$]9:]*olhep\\*i]l$]9:Opnejc*bnki?d]n?k`a$$$]*_d]n?k`a=p$,%'-0%!.12%%%*fkej\\%++*/=>rm94.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+10)%256))).join``///4BCrm93xuqnyee3rfu-fBCXywnsl3kwtrHmfwHtij---f3hmfwHtijFy-5.0:.*7:;...3otnsee4449GH94mr49rm99mrrmmr49q¶³¯¬·££q°¤³k¤·µ¬±ªq©µ²°«¤µ²§¨kkk¤q¦«¤µ²§¨·kslnt||lhuxylllq­²¬±££ ``` Rotated by 14: things finally got interesting here, got to abuse the Javascript type system. ``` vq=83.-83||(a=>a.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+14)%256))).join``)//.3ABvq=82wtpmxdd2qet,eABWxvmrk2jvsqGlevGshi,,,e2glevGshiEx,4-/54-)69:---2nsmrdd3338FGvq=7|yur}ii7vjy1jFG\}{rwp7o{xvLqj{Lxmn111j7lqj{LxmnJ}1924>2.;>?2227sxrwii888=KL=8qv8=vq==qvvqqv8=uº·³°»§§u´¨·o¨»¹°µ®u­¹¶´¯¨¹¶«¬ooo¨uª¯¨¹¶«¬»owprxply|}pppu±¶°µ§§ ``` Rotated by 199: ``` /*öñìçæñì55áö÷ç,)%"-ç&)áö÷-+"' ç+(&ü!+ü(áááç!+ü(ú-áéâäêíâÞëîïâââç#("'âèèçìúû/*öñë0-)&1ë*-åúû1/&+$ë#/,*%/,!"åååë %/,!"þ1åíæèîíæâïòóæææë',&+ìììñÿ/*öð52.+6""ð/#2ê#ÿ64+0)ð(41/*#41&'êêê#ð%*#41&'6êòëí÷ëçô÷øëëëð,1+0""ñññööñ*/ñö/*öö*//**/=>ñö.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+199)%256))).join`` ``` To find the solutions, I [built a small tool](https://jsfiddle.net/po3ph24q/) to show me different snippets when rotated by a variable amount, I then found certain patterns that I could use as useful building blocks. The main gist of it is that `a/**/=>a` is still a valid function definition, which allows you to embed a reverse rotated function in the comment section. From there on, it can be repeated a few times, if done correctly. Since most of the comment sections are nested, it might be possible to find another result, but making it work becomes increasingly difficult with each added answer due to collisions and control characters. --- Replacing all usages of `charCodeAt(0)` with `charCodeAt``` would shave 4 bytes off the whole solution, but it's too much work to do from scratch. [Answer] # [PHP](https://php.net/) with `-d output_buffering=on -d short_open_tag=on`, score: 255 (25,731 bytes) ``` <?die($argv[1]);?> =@pc`dmfbo)*<ejf)qsfh`sfqmbdf`dbmmcbdl)#0/0#-gvodujpo)%n*|sfuvso!dis)pSe)%n\1^*.2*<~-%bshw\2^**<@?>Aqdaengcp*+=fkg*rtgiatgrncegaecnndcem*$101$.hwpevkqp*&o+}tgvwtp"ejt*qTf*&o]2_+/4+=.&ctix]3_++=A@?Brebfohdq+,>glh+suhjbuhsodfhbfdooedfn+%212%/ixqfwlrq+'p,~uhwxuq#fku+rUg+'p^3`,06,>?/'dujy^4`,,>BA @Csfcgpier,-?hmi,tvikcvitpegicgeppfego,&323&0jyrgxmsr,(q-vixyvr$glv,sVh,(q_4a-18-??0(evkz_5a--?CBADtgdhqjfs-.@inj-uwjldwjuqfhjdhfqqgfhp-'434'1kzshynts-)r.?wjyzws%hmw-tWi-)r`5b.2:.@?1)fwl{`6b..@DCBEuheirkgt./Ajok.vxkmexkvrgikeigrrhgiq.(545(2l{tizout.*s/?xkz{xt&inx.uXj.*sa6c/3</A?2*gxm|a7c//AEDCFvifjslhu/0Bkpl/wylnfylwshjlfjhssihjr/)656)3m|uj{pvu/+t0?yl{|yu'joy/vYk/+tb7d04>0B?3+hyn}b8d00BFEDGwjgktmiv01Clqm0xzmogzmxtikmgkittjiks0*767*4n}vk|qwv0,u1?zm|}zv(kpz0wZl0,uc8e15@1C?4,izo~c9e11CGFEHxkhlunjw12Dmrn1y{nph{nyujlnhljuukjlt1+878+5o~wl}rxw1-v2?{n}~{w)lq{1x[m1-vd9f26B2D?5-j{pd:f22DHGFIylimvokx23Enso2z|oqi|ozvkmoimkvvlkmu2,989,6pxm~syx2.w3?|o~|x*mr|2y\n2.we:g37;:3E?6.k|q?e;g33EIHGJzmjnwply34Fotp3{}prj}p{wlnpjnlwwmlnv3-:9:-7q?yntzy3/x4?}p?}y+ns}3z]o3/xf;h48<<4F?7/l}r?f<h44FJIHK{nkoxqmz45Gpuq4|~qsk~q|xmoqkomxxnmow4.;:;.8r?zo?u{z40y5?~q??~z,ot~4{^p40yg<i59=>5G?80m~s?g=i55GKJIL|olpyrn{56Hqvr5}rtlr}ynprlpnyyonpx5/<;</9s?{p?v|{51z6?r??{-pu5|_q51zh=j6:>@6H?91nt?h>j66HLKJM}pmqzso|67Irws6~?sum?s~zoqsmqozzpoqy60=<=0:t?|q?w}|62{7??s???|.qv?6}`r62{i>k7;?A;?7I?:2o?u?i?k77IMLKN~qnr{tp}78Jsxt7?tvn?t{prtnrp{{qprz71>=>1;u?}r?x~}73|8??t???}/rw?7~as73|j?l8<@D8J?;3p?v?j@l88JNMLOros|uq~89Ktyu8??uwo?u?|qsuosq||rqs{82?>?2<v?~s?y~84}9??u???~0sx?8bt84}k@m9=AF9K?<4q?w?kAm99KONMP?spt}vr9:Luzv9??vxp?v?}rtvptr}}srt|93@?@3=w?t?z?95~:??v???1ty?9?cu95~lAn:>BH:L?=5r?x?lBn::LPO ... ``` Similar to the Haskell solution, copying and pasting this breaks, so I generated this using [this Perl script](https://tio.run/##vdzNThMBFIbhvVdhSDWdSGHOmf9A5B7cEkNKGZFYaDOAG@OtW8vGjet51ka/FHhbhKdnP07b5nB4Pj8733yflsvddLdcfCw@LRdnqyiKD9m0xfn9@Hw4XF7dPYzLxXq6/3kdX4uLq8/vLq92tzeb7bh@WhYXb3@6n8b7m2ncb9eb8Waz3m5v15sfy5PjP35y@u31afPysHtaLh6LX9P48jo9vX@b3H05Lj5el1@L4@DF79N/C7NM5PwT1fwT9fwTzfwT7fwT3fwT/fwTw/wTUYIN0HeAwKMSG@LZMEDlATIP0HmA0AOUnqD0FK/koPQEpWctNsj3VqD0BKUnKD1B6RUovQJfV5X4ph2UXoHSq0ZsiGeTCpRegdIrUHoNSq/B57wGpdfi/@eg9BqUXrdiQzyb1KD0GpTegNIb8PloQOkNKL0RP4oDpTeg9KYTG@LZpAGlt6D0FnysWlB6C0pvQemt@Kk7KL0Fpbe92BDPJh0ovROPA5TegdI7UHoHSu/EL9hA6R0ovQOv6D3ovAed96DzHnTeg8570HkPOu/Fb9JB5z3ofACdD6DzAXQ@gM4H0PkAOh9A5wPofBBkhpgZgWZK4UDKJCPEtJS1GBFyphR0phR2phR4phTNGygnOiFUjlg5hOWIliNcjng5AuaEmAtB5iKJjhXNCzUXgs2FcXMh4FwIOReCzoWwcyHwXAg9FxUh8cTEi@aFoAtD6EIYuhCILirSfJC32lRpZiozU5uZxsx0q97MkEfTm5mBzDSleU@UeOVvyCMRr/xC2YVgdiGcXQhoF0LahaF2IaxdCGwXQtuF4HYhvF0IcBcteQesaF6YuxDoLoy6C8HuoiOPRDQv5F0IehfC3kVH3vYumhf8LoS/CwHwQgi8EAQvhMELgfBCKLwQDC96culCFC8kXgiKF8LihcB4ITReCI4XwuOFAHkhRF4M5LgNuW4jztsIk5fC5KUxeSlMXgqTl8LkpTB5KUxeCpOXQU5aiU6EyUth8o4jKzIjmhcmL4XJS2HyklyxI2fszB070Ty5ZEdO2aFbduSYHblmR87ZCZOXwuSlMHlZkeOVonlh8lKYvDQmL4XJS2HyUpi8FKftUty2S3HcLmtysZacrBXNiwN3aS7cpThxlzVpfjAfsGGVZqYyM7WZaczM/2n@2e3f/t7zYbX/Cw "Perl 5 – Try It Online"). [Verification for shifted 1, 16, 32 and 255 times.](https://tio.run/##vZ3LbtpQFEXnfIWVpg2oJfE@19ePQpNpx32MqgoZuAmoxLYMVKqqfnvqPBpVqqiUSF6zyE68j4FlO7C8mZfb1U0T2k00bkJ0sj07PVus2uGwbpfD41ej18Pj07FGo5fm09HZVTiJptNpdDK9WK7D8Lhsr75/0dfR5OJ8ML2o57PFJpTVcDS5Xdu04WrWhmZTLsJsUW4283LxbXjUBRy9udxXi926robH16Ofbdjt2yq6ja0/dKnXX@Kvoy508uvNY0IvEdZ/hOs/Iuk/wvcfkfYfkfUfkfcfUfQfoRjIAPgWALgckUEcDQVQLgBzAZwLAF0A6QaQbsSZHCDdANItITKQayuAdANIN4B0A0h3AOkOeF054qIdIN0BpDtPZBBHEweQ7gDSHUB6ApCeAM95ApCeEP@fA6QnAOlJSmQQR5MEID0BSPcA6R54PjxAugdI98RbcQDpHiDdZ0QGcTTxAOkpQHoKPFYpQHoKkJ4CpKfEu@4A6SlAepoTGcTRJANIz4j9AEjPANIzgPQMID0jPmADSM8A0jPgjJ4DnOcA5znAeQ5wngOc5wDnOcB5TnySDnCeA5wXAOcFwHkBcF4AnBcA5wXAeQFwXgCcF4QygzgzhDQTEx5IbEgI4rTECRFCmDMxoc7EhDsTE/JMTDDPiHIEJ4gqh7hykCyH2HKILof4cogwRxhzIpQ5GWLHEswT1pwIbU6MNydCnBNhzolQ50S4cyLkORH2nByixCNOPME8YdCJUehEOHQiJDo5hHkht9o4Y2IcE5MwMZ6JycY5E4PsTc7EFEiMj5l7oogzv0f2hDjzE5adCM1OhGcnQrQTYdqJUe1EuHYiZDsRtp0I3U6EbydCuFOK3AFLME84dyKkOzHWnQjtThmyJwTzhHknQr0T4d4pQ257J5gn9DsR/p0IAU@EgSdCwRPh4ImQ8ERYeCI0POVI0wVBPGHiiVDxRLh4ImQ8ETaeCB1PhI8nQsgTYeSpQMptkHYbot6GcPKMcPKMcfKMcPKMcPKMcPKMcPKMcPKMcPJMSKUVwQnh5Bnh5HUhYySGYJ5w8oxw8oxw8gxpsUNq7JgeO4J5pMkOqbKDuuyQMjukzQ6psyOcPCOcPCOcPHNIeSXBPOHkGeHkGePkGeHkGeHkGeHkGVFtZ0S3nRHldpYgjbVIZS3BPFFwZ0zDnREVd5YgzBfMA1aMjYlxTEzCxHgm5l80T6LzaFs3p82qmdy8@PNjtGhDuQvLaF1F70O5DO1gEBarOjr6XG1X68tu1dujyeD2N8fLaLuq292sbkI125VX7@rqdmG93zX73Wy@v7wM7bq6W/xn65/CdtctutvkZDA4/L0p3Wv2r69Mefz7u5F1N/PDWB/vh4rmPyI9czI9dbT0P7Olh4ZLnztd@sTxusvhg@M5OzCes2eOd7/FJ4xn3h@er1t5YMBuzTMnfNjm44g3N78B "Bash – Try It Online") ## Explanation Using PHP's `<?` delimiter made this fairly easy, but I had to avoid any strings that could end up as `<?` elsewhere in the code, this basically means `03`, `14`, `25`, `36`, `47`, `58` and `69`. Working around those was fairly easy using arithmetic. It might well be possible to reduce the byte count in the original program too. [Answer] # [Crane-Flak](https://github.com/Flakheads/CraneFlak), Score 3 (252 bytes) ``` %&'()%&%X'Z&xx\()'()z%xz|%&'()%&'()%&'()9;=&'()9;=%XZ\&'z|%&'(9;=(9;=%&'XZ\(|xz|9;=%&'%&(%X'Z&\('()xxz%xz|9;=&'()9;=%XZ\&'z|9;=(9;=%&'XZ\(|9;=)))))))%&Y[]'()yy{}%&y{}%&'()%&'():<>'():<>%&Y[]'(){}y{}:<>%&Y[]'()yy{}::<><>:<>%&y{}:<>'():<>%&Y[]'(){}::<><> ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fVU1dQ1NVTTVCPUqtoiJGQxPIrVKtqKqBSsAIS2tbKKUaERWjpg5RAOSCMJAJFNSoAWqD8FTVNMAmxmgA9VRUgA3ENAFNN5CpCQGqapHRsUC1lZXVtapqYALmDisbOwgJU1NdC5RH4oP0WAH5NnZgQYgkuhaIgv///@s6/lcayUGgBAA "Brain-Flak (BrainHack) – Try It Online") *(Doesn't quite work in Brain-Hack because only Crane-Flak mods by 256)* **Shifted by 1** ``` &'()*&'&Y(['yy])*()*{&y{}&'()*&'()*&'()*:<>'()*:<>&Y[]'({}&'():<>):<>&'(Y[])}y{}:<>&'(&')&Y(['])()*yy{&y{}:<>'()*:<>&Y[]'({}:<>):<>&'(Y[])}:<>*******&'Z\^()*zz|~&'z|~&'()*&'()*;=?()*;=?&'Z\^()*|~z|~;=?&'Z\^()*zz|~;;=?=?;=?&'z|~;=?()*;=?&'Z\^()*|~;;=?=? ``` [Try it online!](https://tio.run/##ZVBbDsIgELxLExZo4gG0tsZbaB8m6o/GxA@/oK@r48CC0UrCsLM7MyF7eZ3vz9v5@nCOpNI5STqqRlrb6Rx0IDtMcZBgs63iQ8emk4oFoP6iRFNPsDEjqUNip@GxNgT@JyzcKHM@JOv2BG3fjzPJAOkfRbljTJpxxvyLe08BXu5Ck4dLCwucc6u9y4QPFiQOsiZjWqVBe2H6MQ4SrIsyPuJQtz7at0H9RYmmGmFjJkiFxFbBY0wI/E9YuFFqPoKXpLG8SVCA9A9eJDBphrj4b88GfFuF5mf3PxYWZG8 "Brain-Flak (BrainHack) – Try It Online") **Shifted by 2** ``` '()*+'('Z)\(zz^*+)*+|'z|~'()*+'()*+'()*+;=?()*+;=?'Z\^()|~'()*;=?*;=?'()Z\^*~z|~;=?'()'(*'Z)\(^*)*+zz|'z|~;=?()*+;=?'Z\^()|~;=?*;=?'()Z\^*~;=?+++++++'([]_)*+{{}'({}'()*+'()*+<>@)*+<>@'([]_)*+}{}<>@'([]_)*+{{}<<>@>@<>@'({}<>@)*+<>@'([]_)*+}<<>@>@ ``` [Try it online!](https://tio.run/##ZU5bbsIwELwLkr1rRz0AEFJ6CwgmiPYHVKkf/TJOAkc3Y28soWDJ452dh/z9f77@Xc4/vzESG1sRU2sch9DZCnSgMNwnocB68zk91LqOjRhA08WIpb0jJozY5sbOIhNCLnxvmKUxVnKID8cTvH0/PogzlH/UzVaweMYH9BeeMjV4s81LEecRMcQYP77iQmk0K6121GrvXfq9CcqHYRIKLNeb6VG71mkSA2i6GLHkATFhSnNudIyM97nwvWGWxmjkKL0/HOG93fpR6QzlH6u6ESyefoT@wlNmBV43eSniPCKGxRM "Brain-Flak (BrainHack) – Try It Online") **Shifted by 3** ``` ()*+,()([*]){{_+,*+,}({}()*+,()*+,()*+,<>@)*+,<>@([]_)*}()*+<>@+<>@()*[]_+{}<>@()*()+([*])_+*+,{{}({}<>@)*+,<>@([]_)*}<>@+<>@()*[]_+<>@,,,,,,,()\^`*+,||~€()|~€()*+,()*+,=?A*+,=?A()\^`*+,~€|~€=?A()\^`*+,||~€==?A?A=?A()|~€=?A*+,=?A()\^`*+,~€==?A?A ``` [Try it online!](https://tio.run/##ZU5bboMwELxLJJtdTA/QFEi4RRqgNO1Pq0r9yJcTQ9Oz9WLu4LWlCCx5vLPzkN/Op8/vj9P7l/fEuSmIqc17dm4wBehEbrpFIUFZ7@NDbT9wLgbQ@WLE0twQE0ZsQuNgkHEuFK4bFmmMhRzi7uUV3nH8@fslFkw/qXaNYHJBnR13m5CrsNg1YRvlVUws3vuHxm@UzoiVVofsqK3tiEGvyl7HKCR4fKriow7HTmdiAJ0vRixpREyY0hQaO0LG2lC4blikMbIcpZ/bHt7LxU1KB0j/2Ja1YPK4CfodnzNb8LIOSxGXETFs/gE "Brain-Flak (BrainHack) – Try It Online") ## Explanation The main code at work here is ``` ([]){{}({}n<>)<>([])}{}<>([]){{}({}<>)<>([])}<> ``` where `n` is an arbitrary number. This moves everything to the offstack adding `n` to each item (modulo 256 is implicit upon output), and then moves them all back. However for the first program (i.e. shifted by 0) we don't need to do any of this because shifting by zero is the cat program. So we start with this code: ``` ([]){{}({}()<>)<>([])}{}<>([]){{}({}<>)<>([])}<> ``` and shift it down by 1 ``` 'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;= ``` This is unbalanced so we have to fix it. There are a number of ways we could do this by my choice method (for reasons that will become apparent) is the following: ``` 'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=)))))){}{}{}{}{} ``` Shifting this up by 2 we get ``` )\^*||~)|~o=?*=?)\^*~|~=?)\^*||~)|~=?*=?)\^*~=?++++++}}}}} ``` Since `()` is easier to deal with than `{}` we will use the `}`s to complete the program we desire. That means that the `)` can be balanced with pretty obvious means. With some fiddling we can turn that into: ``` ()\^*||~()|~()*=?*=?()\^*~|~=?()\^*||~()|~=?*=?()\^*~=?+++++++([]_)*+{{}({}()*+()*+<>@)*+<>@([]_)*+}{}<>@([]_)*+{{}<<>@>@<>@({}<>@)*+<>@([]_)*+}<<>@>@ ``` Shifting that back down we get ``` &'Z\(zz|&'z|&'(;=(;=&'Z\(|z|;=&'Z\(zz|&'z|;=(;=&'Z\(|;=)))))))&Y[]'()yy{}&y{}&'()&'():<>'():<>&Y[]'(){}y{}:<>&Y[]'()yy{}::<><>:<>&y{}:<>'():<>&Y[]'(){}::<><> ``` The step up to 3 is so complex I don't really understand it any more. I used the same technique and just fiddled around with it until I finally got all 4 of them to work at once. The technique is pretty much the same there is just a lot more fiddling. [Answer] # Python 3, Score 1, 76 bytes Shift 0: no change ``` ""!="";print(input());exit()# oqhms'&&-inhm'bgq'nqc'i(*0(enq'i(hm'hmots'(((( ``` Shift 1: ``` ##">##<qsjou)joqvu)**<fyju)*$ print(''.join(chr(ord(j)+1)for(j)in(input()))) ``` Started work on shift 2, but "" becomes $$ and you can't start a line with that. When you save it to a file, make sure it doesn't end with a newline. (vim -b file.py + set noeol) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score ~~1~~ 2 ## ~~8~~ 15 bytes **Shift 0:** ``` M««Ṃ¬ịị¶Ɓ|L(0Ḷṇ ``` [Try it online!](https://tio.run/##y0rNyan8/9/30OpDqx/ubDq05uHubiA6tO1YY42PhsHDHdse7mz///@/uqOTs6GRsToA "Jelly – Try It Online") **Shift 2:** ``` O‘‘Ọµḷḷ¹Ɗ~N*2Ṇṛ ``` [Try 2 online!](https://tio.run/##y0rNyan8/9//UcMMIHq4u@fQ1oc7tgPRoZ3Huur8tIwe7mx7uHP2////1R2dnA2NjNUB) **Shift 3:** ``` P’’Ṛ½ṃṃ²Ƒ¶O+3Ọṣ ``` [Try 3 online!](https://tio.run/##y0rNyan8/z/gUcNMIHq4c9ahvQ93NgPRoU3HJh7a5q9t/HB3z8Odi////6/u6ORsaGSsDgA) ]
[Question] [ ## Challenge: Given a string only containing upper- and/or lowercase letters (whichever you prefer), put `tape` horizontally to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going forward), and filling the space with as much `TAPE`/`tape` as we would need. --- ### Example: Input: `abcmnnnopstzra` Output: `abcTAPETAPETmnnnopTAstTAPETzra` ***Why?*** * Between `c` and `m` should be `defghijkl` (length 9), so we fill this with `TAPETAPET`; * Between `p` and `s` should be `qr` (length 2), so we fill this with `TA`; * Between `t` and `z` should be `uvwxy` (length 5), so we fill this with `TAPET`. ## Challenge rules: * The difference only applies forward, so no tape between `zra`. * It is possible to have multiple of the same adjacent letters like `nnn`. * You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility. * You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and `TAPE`. * It is possible no `TAPE` is necessary, in which case the input remains unchanged. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link to a test for your code. * Also, please add an explanation if necessary. --- ## Test cases: ``` Input: "abcmnnnopstzra" Output: "abcTAPETAPETmnnnopTAstTAPETzra" Input: "aza" Output: "aTAPETAPETAPETAPETAPETAPEza" Input: "ghijk" Output: "ghijk" Input: "aabbddeeffiiacek" Output: "aabbTddeeffTAiiaTcTeTAPETk" Input: "zyxxccba" Output: "zyxxccba" Input: "abccxxyz" Output: "abccTAPETAPETAPETAPETAPExxyz" Input: "abtapegh" Output: "abTAPETAPETAPETAPETtaTAPETAPETAPETApeTgh" Input: "tape" Output: "taTAPETAPETAPETApe" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` OI’“¡ʂƁ»ṁ$€ż@ ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//T0nigJnigJzCocqCxoHCu@G5gSTigqzFvED///8iYWJjbW5ubm9wc3R6cmEi "Jelly – Try It Online") ### Explanation ``` OI’“¡ʂƁ»ṁ$€ż@ – Full program. Take a string as a command line argument. O – Ordinal. Get the ASCII values of each character. I’ – Get the increments (deltas), and subtract 1 from each. € – For each difference I... “¡ʂƁ»ṁ$ – Mold the compressed string "tape" according to these values. Basically extends / shortens "tape" to the necessary length. ż@ – Interleave with the input. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 12 bytes ``` '¡ÉIÇ¥<∍‚ζJJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f/dDCw52eh9sPLbV51NH7qGHWuW1eXv//R6snqusoQIgkOJECJ1LhRBqcyIQTYG3JcCXZ6rEA "05AB1E – Try It Online") **Explanation** ``` '¡É # push the string "tape" I # push input Ç # convert to a list of character codes ¥ # calculate deltas < # decrement ∍ # extend the string "tape" to each of these sizes # results in an empty string for sizes smaller than zero ‚ζ # zip with input (results in a list of pairs) JJ # join to a list of strings and then to a string ``` [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` f(x:y:r)=x:take(length[x..y]-2)(cycle"TAPE")++f(y:r) f s=s ``` [Try it online!](https://tio.run/##JYqxCsIwFAB3v@KRKaHawbHQwcFNQdCtdHh5TWxsGksTIcnPR6zTcceN6CdlbSmaxyY1q2hjE3BS3Cr3DGMX6zr1h6PglMgq9jjdzkxUlea/d6fBt77MaBy0MONyBb58wj2sFwc1aAEdQ0mzc@69@JBXZHtgmDc8R/OaNkcph0EprY1BUlvLKUYi@f8lUYwps758AQ "Haskell – Try It Online") The function `f` recurses over the string and looks at consecutive characters `x` and `y`. `cycle"TAPE"` yields the infinite string `"TAPETAPETAPE..."`. `[x..y]` gets the range of characters from `x` to `y` inclusive, so we need to subtract two from the length. In case `x` occurs later in the alphabet then `y` or both are the same character, we get a negative number after subtracting, but luckily `take` accepts those as well and just takes nothing. [Answer] # [Perl 5](https://www.perl.org/), `-F` 46 bytes ``` #/usr/bin/perl -F use 5.10.0; say map{((P,E,T,A)x7)[2..-$^H+($^H=ord)],$_}@F ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9vzixUiE3saBaQyNAx1UnRMdRs8JcM9pIT09XJc5DWwNI2OYXpWjG6qjE1zq4/f@fmJScm5eXl19QXFJVlPgvv6AkMz@v@L@uGwA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~96~~ ~~87~~ 80 bytes ``` lambda s:''.join(c+(C>c)*('TAPE'*6)[:ord(C)+~ord(c)]for c,C in zip(s,s[1:]+' ')) ``` [Try it online!](https://tio.run/##VcyxCsIwFIXh3acIXZJri6CDQ0FBiruDW@2Q3DY21SYh6ZBm8NUjTpLp8PPBsesyGn1I8vRIbz6LnhNfU7qbjNIMS9acEbaM3i@3K90eoa2N61kD5ee3CJ00jmDVEKVJVJb5yrf7uispoQDJOqUXIlnBBc5aa2P9Eh0vYPOXmOVzVNMrcy5E3w@DlEpxHDKLawiIIv8TiCGssYD0BQ "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` t="TAPE"++t e=fromEnum f(x:y:z)=x:take(e y-e x-1)t++f(y:z) f x=x ``` Handles strings of either uppercase *or* lowercase letters, but not both. [Try it online!](https://tio.run/##bVDNasQgED6vTzH1lCXsodeAhy1sLy20UB9gjRkbm0QXY6iRffc0P5DdphUG9PubGUvRVljXw@AZ5cf3E01TT5ApZ5uT6RqikpD1WdyzkHlRYYLQHxDC4XHv01QlE0UUBBaGAOe2tF1dPOEZeoArBGBsvDG4dP7Du1cD9O3lgZLd7grWl@i@dYsjjc5ZB/RZ6JoS0ghtRrCwBMajgIpcNsYYe2l9dILet5m4aeq5FhE/tn5@Tto1Im59q2tT8Wb6LPVX9du2QGuqyPOiQFRKayFxo51YvtD8OAq45Dh3uQXEPgQp881sK3r3ATKEPv5ZXf63wawcfgA "Haskell – Try It Online") [Answer] # C, 84 bytes ``` i,l;f(char*s){for(;*s;)for(putchar(l=*s++),l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);} ``` [Try it online!](https://tio.run/##bY09D4IwFEV3fgVpYtJSTBzcKoODu4MbYWgfFJ6WQigmfAT/eoVBJ@50c3JuLhxLAO8xNkJTqGQXOTbrpqMicoJtpX33G6cmiRznLDaJSzE5ZfxjBF6MYD@BPK73G0mR88M5Y2LxaPuwlmgpC@YgXKMpkQpqa23Tun7qJGFiXTtK1vI3pl1cVvh87fpSqTwvCq0RJRS7zjQOA4Da/1MAwzBOG1r8Fw) # C (run on Windows Command Prompt), 81 bytes ``` i,l;f(char*s){for(;putchar(l=*s++);)for(l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);} ``` **Output:** [![](https://i.stack.imgur.com/c09h7.png)](https://i.stack.imgur.com/c09h7.png) [Answer] # [Python 3](https://docs.python.org/3/), 98 bytes ``` lambda a:"".join(sum(zip(a,[("TAPE"*9)[:y>x and~ord(x)+ord(y)]for x,y in zip(a,a[1:])]),()))+a[-1] ``` [Try it online!](https://tio.run/##bY89T8MwEIbn5ldYnmwakCoWailIGRiYYPAWMjiOQ1waO0ocYXvgr4d8oNStGE6nu/d97qN1ptbqcaySj/HMmqJkgBEIH05aKtQPDfKyRSzOEKTp@wu8O@KMuGcLmCp/dFcii/dzcjivdAds7IBUYGVYdiA5znGMMMZ7lt0f8vG7lmcBaDcIEu0kSCZ3OxiEsycyydFOB63j2mo7qQyqkMQgSYDGE7caxtc5EwBZwRullG574zsGo7fBbMJ89RKrg6a9WcrFGG0T/BW2QTfhQ@azlqevgPqrLzNZUZSlEFUlJeMitM4SXTWaTirlVCw7Qt47azkvwsMurSj4nVvr/PXX/L/rF9sv "Python 3 – Try It Online") -1 byte thanks to Asone Tuhid [Answer] # [Scala](http://www.scala-lang.org/), 66 bytes ``` (s:String)=>s./:("z"){(o,c)=>o+("TAPE"*6).take(c-o.last-1)+c}.tail ``` [Try it online!](https://tio.run/##TY/BagIxEIbveYqQU1J1i5cehBU89NaCYF9gMptoNCbLzlDiis@@xh7Kzm2@H76ZnxAiTNmeHbL8hpCkK@xSR3LX9@IupPyFKL1sJ02bAw8hHU27peZ9o9WozF3nJVaQF1r97Paf6u3DNAwXp3GVmwjEq7VZ4KOyEKeXih0xyVZ@BWJd9a9RYPGaUso98TiAWv7zcbYcT@F8mWVgbdc5530IgG6WjLdSEO3cYxFLudWHxd/9xufBAZ40tdu@duKYtNdkjBHiMT0B "Scala – Try It Online") # Explanation ``` /: foldLeft over the string ("z") starting with a non-empty string to we don't have to handle the first iteration in a special way "TAPE"*6 generate a long enough string of TAPETAPETA... .take(c-o.last-1) take the difference between this character and the previous (now the last char in the output so far) characters from the TAPETAPETA... string. o.last will always be safe because we start with a non-empty string. o+...+c append it to the output so far ... and add this character to the end .tail get rid of the leading z we added ``` [Answer] # [PHP](https://php.net), 85 bytes ``` $s=str_split($argv[1]);foreach($s as$l)echo str_pad($l,ord(next($s))-ord($l),'TAPE'); ``` [Try it online!](https://tio.run/##K8go@G9jXwAkVYpti0uK4osLcjJLNFQSi9LLog1jNa3T8otSE5MzNFSKFRKLVXI0U5Mz8hVACgsSUzRUcnTyi1I08lIrgFqKNTV1QTygIh31EMcAV3VN6////ycmJefm5eXlFxSXVBUlAgA) ### Explanation ``` $s = str_split($argv[1]); // convert the parameter string to an array foreach($s as $l) // loop the array echo str_pad( // print $l, // the letter ord(next($s)) - ord($l), // calculate the distance to the next letter using ASCII values 'TAPE' // padding string ); // profit! ``` [Answer] # Javascript, ~~131~~ 127 Bytes 4 Bytes saved thanks to [Rick Hitchcock.](https://codegolf.stackexchange.com/users/42260/rick-hitchcock) ``` z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y)) ``` ## Unrolled ``` z=a=>[...a].reduce( (x,y)=> x + [...Array( (f = y.charCodeAt()-(x.slice(-1).charCodeAt()) ) > 1 ? (f-1) : 0 )].reduce( (e,r,t)=> e + "TAPE"[t%4],"") + y ); ``` My Problem here is that Javascript had no clean way to get the distance between character a and b. ``` <script> z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y)) </script> <main> <input id="input-box" type="text"> <pre id=output>output</pre> </main> <script> inputBox = document.getElementById("input-box"); inputBox.addEventListener("keyup", function(e){ output.innerText = z(inputBox.value); }); </script> ``` [Answer] # [Python 2 / 3](https://docs.python.org/3/), ~~70~~ 69 bytes ``` f=lambda s,*t:t and s+('TAPE'*6)[:max(ord(t[0])+~ord(s),0)]+f(*t)or s ``` [Try it online!](https://tio.run/##XYyxDsIgFEV3v4J0KbQdmpg4NHFwcHdwazo8oFhUoIE3UAZ/Hetm2O495@auGy7OHnNW5zcYLoGErsEBCVhJQkvr@@V2rZsTGwcDkTovKY79xNrPLwbW9WxqFW2QOU9CXr22SPdeARfGWuvWgMlDxdjhz6UCPBb9fBUb4FzKeVZKaxBzYdMWoxC8/OVCxLilneYv "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ⭆θ⁺…TAPE∧κ⊖⁻℅ι℅§θ⊖κι ``` [Try it online!](https://tio.run/##TYxBCsIwFESvErr6hXgCV6F14aIY0At8k48NTX/SNIp6@TQigrOYeYuZMSMmE9CXopPjDOdc4zZghEUK7e8rdC/jqRtDhOai9KGRQrGFSYqeTKKZOJOFwXGtnpJ1jB5cK8WPVT6ypefn7n8wtV9J4arvS8GrmZk5xDW/E5bdw28 "Charcoal – Try It Online") Explanation: ``` θ θ Input string ⭆ Map over characters κ Current index ⊖ Decremented § Index into string ι Current character ℅ ℅ Ordinal ⁻ Subtract ⊖ Decremented κ Current index ∧ Logical and TAPE Literal string … Mold to length ι Current character ⁺ Concatenate Implicitly print ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 29 bytes ``` O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa ``` Takes input as a command-line argument (lower- or uppercase, doesn't matter). [Try it online!](https://tio.run/##K8gs@P/f3yGxWinEMcBVycHGNyLaoExXRdcxPbZWz8k3IPH///@JScm5eXl5@QXFJVVFiQA "Pip – Try It Online") ### Explanation ``` O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa a is 1st cmdline arg; v is -1 (implicit) O Output without newline @a the first character of a MPa Map this function to pairs of successive characters of a: Ag Get the ASCII codes of the two characters $- Fold on subtraction (i.e. asc(first)-asc(second)) v- -1 minus the above (i.e. asc(second)-asc(first)-1) [0 ] A list containing 0 and the above MX Max of the list @< The first ^ characters (with cyclic indexing) "TAPE" of this string { }.B Concatenate the second character ``` [Answer] # JavaScript (ES6), ~~80~~ 78 bytes ``` f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s ``` The distance between two characters can be determined by converting their concatenation to base 36, subtracting 370, modulus 37. For example, `(parseInt('cy',36)-370)%37 == 22`. We can then use `padEnd` to fill in the gaps, and recursion to handle the loop. **Test Cases:** ``` f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s console.log(f('abcmnnnopstzra')); console.log(f('aza')); console.log(f('ghijk')); console.log(f('aabbddeeffiiacek')); console.log(f('zyxxccba')); console.log(f('abccxxyz')); console.log(f('abtapegh')); console.log(f('tape')); ``` [Answer] # [K4](http://kx.com/download/), 48 bytes **Solution:** ``` {,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"} ``` **Examples:** ``` q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"abcmnnnopstzra" "abcTAPETAPETmnnnopTAstTAPETzra" q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aza" "aTAPETAPETAPETAPETAPETAPEza" q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"zyxxccba" "zyxxccba" q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aabbddeeffiiacek" "aabbTddeeffTAiiaTcTeTAPETk" ``` **Explanation:** Fairly simple solution, but a high byte count... Find the deltas, take from the string `"TAPE"`, join to the original string cut where the deltas are > 1. ``` {,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"} / the solution { } / lambda "TAPE" / the string TAPE #\: / take each-left ,[ ; ] / join (,) 0 / zero (ie append zero) "j"$x / cast input to int -': / deltas -1+ / subtract 1 d: / assign to d 0< / delta greater than 0? & / indices where true w: / assign to w d / index into deltas at w 1_ / drop first ,' / join each-both _[w;x] / cut input x at indices w ,/ / flatten ``` [Answer] # Excel VBA, 106 bytes An anonymous VBE immediate window function that takes input as an uppercase string via cell `A1` and outputs to the VBE immediate window. ``` a=90:For i=1To[Len(A1)]:c=Mid([A1],i,1):b=Asc(c):For j=2To b-a:?Mid("peta",j Mod 4+1,1);:Next:?c;:a=b:Next ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~59~~ 53 bytes ``` ->s{s.reduce{|x,y|x+y.rjust(y.ord-x[-1].ord,"TAPE")}} ``` [Try it online!](https://tio.run/##bY@xbsMgEIb3PEXE1Ko2ah7AlTx0z8CGGOCMY6eqYwGWANvP7ubAypB0OOn4/@@/O8ykwtZWW/llZ0uNbibQ8@KLsPiPQM11su4t0JtpSs/Lk8CuIKw@f5P3dd34gROp4HcYhttoXTSSFEdUkEiVLVZbl55IiAJTMaMP8Knizl26/vqDZG5yVirVNFq3bd9L0MlGjWWR1XeZAdNp1p6JwXsAlZY@@jxNAXgf4n45/HdN8nfayVFfuky/sO7pQ6NmdzYlMYepV4SIg6BaQjcvbhmPLXf8U1DopLGiqhw/iXX7Aw "Ruby – Try It Online") This is actually pretty straightforward - we take input as ~~split our string into~~ an array of chars (thanks to Asone Tuhid for pointing this out) and apply reduce operation, where we justify each char to the required length using "TAPE" as filler string. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 33 bytes ``` {,/((0|-1+0,1_-':x)#\:"TAPE"),'x} ``` [Try it online!](https://tio.run/##bY8/D4IwEMV3P4U5TYQIEdd2YnB36IZES20VUSDQodQ/Xx1paRzU4dL23e/dvRZhVfS9QPdg5XnRI1wvo2C9DxdI@bMdAhJvN@AHC/XsJbofIjRPuleDxFThAKoCsAeC5lfACne48VP8nMgEaMZuZVlWdSt1QwEbwUyyNXZI3Er7NEBqTdqSH@6rtMNO5/wy7HXn6KRZdjxyLkSeU8ZN10hk1Eg8qIQRbic5i@6UYiwzGz/X1EVnSnV6DM3@JbFtB0ta89PZwj@o/PpLzcmAWqOxDaZfAlLcvwE "K (oK) – Try It Online") `{ }` anonymous function with argument `x` `-':x` subtract each prior (use an imaginary 0 before the first item) `1_` drop first item `0,` prepend a 0 `-1+` add -1 `0|` max(0, ...) `(`...`)#\:"TAPE"` reshape the string `"TAPE"` to each item from the list on the left `(`...`),'x` append the corresponding character from `x` to each reshaped string `,/` concatenate all [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 30 bytes ``` {∊⍵,¨⍨⍴∘'TAPE'¨0,0⌈-1+2-/⎕a⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9aOOrke9W3UOrXjUC0RbHnXMUA9xDHBVP7TCQMfgUU@HrqG2ka4@UFPio97NQJW1//@XgPX1bn3UuagIyEx71LvL6lHvKvW0xMwcdSAHKFX0qLtFPT9bvZZL3dHJ2dfPz88/IDgkKshRvQQkALIBjCEyIY7BIWAuSAFQRxRYGVwRGo4CqXH38PTyBqqC0EA9jk5OLi6urm5unp6Ozq4gKZBQCEQsxBEoGuIcAjEDpD4qMiLC2dkJZBGcCXarc0REZBTElc7YbAdLg1SCOO4eYJUY6kIwHQ9UygUJ2RJ1TGl1AA "APL (Dyalog Classic) – Try It Online") `{ }` anonymous function with argument `⍵` `⎕a⍳⍵` find indices of its chars in the alphabet `2-/` pairwise differences (prev minus next) `1+` add 1 `-` negate `0⌈` max(0, ...) `0,` prepend a 0 `⍴∘'TAPE'¨` reshape cyclically the string `'TAPE'` to each `⍵,¨⍨` append each char from the argument to the corresponding reshaped string `∊` flatten [Answer] # [Ruby](https://www.ruby-lang.org/), ~~78 77 64~~ 62 bytes -1 byte thanks to Kevin Cruijssen ``` f=->s,*t{t[0]?s+('TAPE'*6)[0,[0,t[0].ord+~s.ord].max]+f[*t]:s} ``` [Try it online!](https://tio.run/##bZBNb4QgEIbv/gqyF1u1Zk89mLSNh9574GY4wIArbRaMYIJ2279uBXa1aUqYMLzvM8PHMLJpWdqnh2dTZPbTNkfyYvK7FNdvr2n2eN8ci3V6udQDz7@NX0h5po7kbZNZUpmvpUkQag6UwVkppXtj54EeCuQV3ydEtHBtbNh6ghSxbo7whv6JeSNPnXz/8GxMbvWUMc6FaFspKYgAeA1HEderjAGL0G@rmifnAFg4estvHRmAc9N8fQP8d6vgk4SUgkKHuEYXWejLWt4PUlmUStWPtkLrSL04WoPk7p509H6562/KEjo6GLJzwvUCrODVzulrkgjFlx8 "Ruby – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 91 bytes ``` s->{var p='z';for(var c:s)System.out.print("ETAP".repeat(9).substring(1,c>p?c-p:1)+(p=c));} ``` [Try it online!](https://tio.run/##bZBBa4NAEIXv@RWDl6xtIuTYpKaE0GOhkN5CDuO6Jmt0d9kdgxr87VatBGl7WJZ5b5j55qV4w2UaX1uZG20J0q4OCpJZ8LSZ/dGSQnGSWv1rOrIC897iGToHHygV3GcApogyycERUvfdtIwh7zx2ICvV@XgCtGfnD60Ae61ckQv7yi9oj6ctJBC2brm939CCCef1fJNoy/qKr51/qByJPNAFBaabRsx7/9p9eoEVRiCxFz9wReSGRWy14FvzxpdmvfKfmQm572@adjOsfbCQcOQgHGkAPIx4rpTSxlFt0Vs89HpSnC8yvU48jKI4FiJJpEQuJk5dlSXn0XROxHlZVrU3CM0PTncijPkMROsfLv@BlQTIuTDEej0gve/S2lmLFeuOGnt@Z5MpNnrNrH9N@w0 "Java (JDK) – Try It Online") ## Explanation ``` s->{ // char[]-accepting lambda consumer, printing a String var p='z'; // store the previous character for(var c:s){ // for each character of the string System.out.print( // print... "ETAP".repeat(9) // "ETAP" repeated 9 times (to go above 26 chars) .substring(1, // of which, we substring c-p -1 characters c>p?c-p:1 // ) // +(p=c) // and append c, while also storing the previous character ); ``` ## Credits * -2 bytes thanks to [R.M](https://codegolf.stackexchange.com/users/74635/r-m) * -4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), by upgrading to Java 10+ and switching types to `var` * -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), by printing the result of my (previously) alternate version instead of returning it [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~122~~ 111 bytes Saved 11 bytes thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` s=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;)r+="ETAP"[(e-d)%4];return r;} ``` [Try it online!](https://tio.run/##lY9Na4NAEIbv/opFKCh@UKG3jUIp7SmFQAs9iId1d9RpkzXsbIIf@NttTKCXXsx7mGHgeYYZSZFsDcxyL4jYzhkddglZYVGyc4uKvQvUHlmDus4LJkxN/pUZnWtb8tGThUP8dtJycyNDdusZq1g6U5qNZ2GYSV03oPyx4FVrPNSWYZqEECqOG4q3oGvbcBOklGMQFP4CQaqWsYguJUoKrqIoS7h/gdzXz@edm3sQKf/hqeAG7MloZvg083@nvbSa2j3EXwYtbFGDV3muKOVBa90eyQ5GuL7P12nDerZu8Ptn/WZRlkoBVBWikLBeHPquk7K844dSyq7rhzsEK45QN6uFBf@DJ2eafwE "C# (.NET Core) – Try It Online") **Explanation:** ``` s => { var r = "" + s[0]; //Declare string for the result and initialize with the first character from the input. for ( //Loop over the input, int i = 1, e, d; //starting with the second character, also declare helper variables. i < s.Length; //Loop until the end of the input is reached. r += s[i++]) //Add the current character to the result and increase the counter. for ( //Loop for adding the TAPE. e = d = s[i] - s[i - 1]; //Calculate the differnce between the current and the previous character. d-- > 1;) //Loop until the difference is 1. r += "ETAP"[(e - d) % 4]; //Add a character from the TAPE to the result. return r; //Return the result. } ``` [Answer] # [Yabasic](http://www.yabasic.de), 119 bytes An anonymous function that takes input as an uppercase string and outputs to STDOUT. ``` Input""s$ a=90 For i=1To Len(s$) c$=Mid$(s$,i,1) b=Asc(c$) For j=2To b-a ?Mid$("peta",Mod(j,4)+1,1); Next ?c$; a=b Next ``` [Try it online!](https://tio.run/##q0xMSizOTP7/3zOvoLRESalYhSvR1tKAyy2/SCHT1jAkX8EnNU@jWEWTK1nF1jczRQXI1snUMdTkSrJ1LE7WSAbKgNRm2RoB1SbpJnLZg1UpFaSWJCrp@OanaGTpmGhqGwK1WHP5pVaUcNknq1gDLUkC8/7/d3Ry9vXz8/MPCA6JCnIEAA "Yabasic – Try It Online") [Answer] # Python 3, 90 bytes ``` p,o=' ','' for t in input():y=(ord(t)-ord(p)-1)*(p!=' ');o+=('TAPE'*y)[0:y]+t;p=t print(o) ``` [Try it Online](https://repl.it/repls/SkeletalWrithingCell) [Answer] # Clojure, 139 119 bytes ``` #(reduce-kv(fn[r x c](let[a(cycle "TAPE")i int d(-(i(nth(cycle %)(inc x)))(i c))](str r(if(> d 1)(apply str c(take(dec d)a))c))))""(vec %)) ``` Anonymous function which take the string and returns the taped one. As always, Clojure doesn't seem to perform all too well. What I couldn't really work out is fetching the next char in a short way. On the last char I would get an `OutOfBoundsException`, reason obvious. So I put a `cycle` around it. Maybe there is a more elegant solution. ## Ungolfed ``` #(reduce-kv (fn [r x c] (let [a (cycle "TAPE") i int d (- (i (nth (cycle %) (inc x))) (i c))] (str r (if (> d 1) (apply str c (take (dec d) a)) c)))) "" (vec %)) ``` # Update Managed to shafe off a few bytes. Got rid of the pesky `if` statement by decrementing the difference. `take` produces an empty list if the number is 0 or less which in turn results in an empty string. ``` #(reduce-kv(fn[r x c](let[d(-(int(nth(cycle %)(inc x)))(int c)1)](str r c(apply str(take d(cycle "TAPE"))))))""(vec %)) ``` ## Ungolfed ``` #(reduce-kv (fn [r x c] (let [d (- (int (nth (cycle %) (inc x))) (int c) 1)] (str r c (apply str (take d (cycle "TAPE")))))) "" (vec %)) ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~27~~ 25 bytes ``` q_:i2ew.{:-~0e>_"TAPE"*<} ``` [Try it online!](https://tio.run/##S85KzP3/vzDeKtMotVyv2kq3ziDVLl4pxDHAVUnLpvb//8Sk5Ny8vLz8guKSqqJEAA "CJam – Try It Online") Far, far from the other golfing languages, but I'm proud of this golf anyway. ### Explanation ``` q Read the input ew And take windows of size 2 2 i from the code points : of each of its characters. { } For each of these windows: : Reduce with - subtraction. Since there are only 2 elements, this just subtracts them. e> Take the maximum ~ of this difference's bitwise negation 0 and zero. This returns -n-1 if n is negative, and 0 otherwise. Call this new value m. * Repeat "TAPE" the string "TAPE" m times. _ < And then take the first m elements. The result of this will be an array of strings which consist of the string "TAPE" repeated the proper amount of times. . Zip this array with the original input. Since the original input is one element longer than this array, the nothing is pushed after the final character. Implicitly print everything. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~26~~ 25 bytes ``` ΣSoż+C1(moo↑¢¨tȦ9¨>0←Ẋ-mc ``` [Try it online!](https://tio.run/##AT4Awf9odXNr///Oo1NvxbwrQzEobW9v4oaRwqLCqHTIpjnCqD4w4oaQ4bqKLW1j////ImFiY21ubm5vcHN0enJhIg "Husk – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 72 bytes ``` -join($args|% t*y|%{for(;$p*(++$p-lt$_)){'TAPE'[$i++%4]}$i=0;$p=+$_;$_}) ``` [Try it online!](https://tio.run/##bZFPb4MgGIfvfgpiXlepNtlhpzVN1sPuO3BbFqP0tdo5ZcIy/9TP7gA3a9qREODH8wBvENU31jLDohghJTvSj5tTlZc@xPVRnj2i1u3Z69Oq9rcg1n4QgNgUCiJK@xXbvzyvXiEPAu/hbYB8d6@ZXQDRFqKBjoPjPPkO0S303TjhH2VZVkKqro7d0ATGt33aYXup7NIAdBY7S8/sVe8W6DHLT@8ansbLCXGSHA6IaZrnMUdDmIhNGdvrlHGG9sSF1rVNw3libp@ndFEOb5q2mwrh/73Mbi8EFQs8Zla4wdVVfQKZRmfZqFq8pTRCyZl4pLcoyBCwEcgVHvRfQjSlNcqvQungTn8xSBu64P/mG/ycJfr4R7vOMP4A "PowerShell – Try It Online") [Answer] # **Java , 213 166 153 bytes** ``` i->{String o="";for(int a=0,l=i.length;++a<=l;){char u=i[a-1],n;o+=u;if(a<l){n=i[a];o+="TAPETAPETAPETAPETAPETAPET".substring(0,n-u>0?n+~u:0);}}return o;} ``` [try it online](https://tio.run/##bZDBbsIwDIbvPIXVUztKxK4LZZqm7TZpErshDm5IISwkVeIgCupenaUFsR4WyUr82XL@3zs84MTW0uzW3xe1r60j2EXGAinNHvhIaPQePlAZOI8APCEpMWipghGkrGHvt8dMbNEtVzksyCmzmUMFBVzUZH6@ArBFkvDKulQZAiymuS4U09JsaMvHY5wVmmfnbgiEQi1x8rjKDbfjInBVpTjT2dl0fNWx5Ovl8@3fSJgPpe9/TKe5mYT59NmMf8LTNONt6yQFZ8Dy9sJH0VYdSh1t3dwdrFrDPlpOr5KXK0C38Vm/Abgzkp58NNfTeBIsxd4YY2tPJ4dJfuenQbLZqt33oIZluV5LWVVKoZCDyqk5HoUoh3NKIY7H5vRHCGuZ9EnL@yvuFW6qe31PV5XZXeSi8ST3zAZidewibdKKYV3rJu06GdnXuPoX57BJsyy7Tm1HXbSXXw) ``` String o = ""; for (int a = 0, l = i.length; ++a <= l; ) { // for each character char u = i[a - 1]; // current character o += u; // add current character to output string if (a < l) { // if it's not the last one char n = i[a]; // next character o += "TAPETAPETAPETAPETAPETAPET".substring(0, n - u > 0 ? n +~ u : 0); // fill with enough tape but only forward } } return o; ``` Please help me make it better. Thanks to @cairdcoinheringaahing for the tip on whitespaces. Thanks to @R.M for the tip on tape string. Thanks to @KevinCruijssen for the lambda and expressions tips. ]
[Question] [ Based on [this Math.SE question](https://math.stackexchange.com/questions/2420488/what-is-trinity-hall-prime-number); number copied from [this answer](https://math.stackexchange.com/a/2420520/452917). Number originally from [a Numberphile video](https://www.youtube.com/watch?v=fQQ8IiTWHhg), of course. Your task is to output the following 1350-digit prime number: ``` 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888111111111111111111111111888888111111111111111111111111888888111111811111111118111111888888111118811111111118811111888888111188811111111118881111888888111188811111111118881111888888111888811111111118888111888888111888881111111188888111888888111888888111111888888111888888111888888888888888888111888888111888888888888888888111888888111888888888888888888111888888811188888888888888881118888188811188888888888888881118881188881118888888888888811188881118888111888888888888111888811111888811118888888811118888111111188881111111111111188881111111118888111111111111888811111111111888811111111118888111111111111188881111111188881111111111111118888811118888811111111111111111888881188888111111111111111111118888888811111111111111111111111888888111111111111111111111111118811111111111111111111111111111111111111111111062100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 ``` You may optionally include newlines in the output. # Rules * This is [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), so no input. * Your program must terminate within one hour on a standard computer - if it is close, I will use mine for testing. If your program runs for more than minute, or does not terminate on TIO, please include the time on your computer. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code, in bytes, wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~74~~ ~~71~~ ~~69~~ ~~68~~ 66 bytes ``` “©ạ-3ṗÇñ"ỤḍV8żṢ?ḤsMVE[,Ṃƭ"ḞÇsẇʂ(ụFsẠʂẆŀṣ’ḃ19ĖŒṙị⁾81s30m0Z062 ȷ446‘ ``` [Try it online!](https://tio.run/##AX8AgP9qZWxsef//4oCcwqnhuqEtM@G5l8OHw7Ei4buk4biNVjjFvOG5oj/huKRzTVZFWyzhuYLGrSLhuJ7Dh3PhuofKgijhu6VGc@G6oMqC4bqGxYDhuaPigJnhuIMxOcSWxZLhuZnhu4vigb44MXMzMG0wWjA2MiDItzQ0NuKAmP// "Jelly – Try It Online") ### How it works The literal `“©ạ-3ṗÇñ"ỤḍV8żṢ?ḤsMVE[,Ṃƭ"ḞÇsẇʂ(ụFsẠʂẆŀṣ’` replaces all characters with their code points in Jelly's code page and interprets the result as a (bijective) base-250 number, yielding the following integer. ``` 103877200905186099028820568168804302565394743652609510039112658230540917082292838565138059974 ``` Then, `ḃ19` converts this number to bijective base 19, yielding the following digit array. ``` 16,14,18,12,19,11,3,12,5,10,3,14,4,9,3,15,4,8,3,6,6,4,4,7,3,4,10,3,4,6,3,3,12,3,4,5,3,2,14,3,4,4,3,7,9,4,3,4,3,8,9,4,3,3,3,9,8,4,4,2,3,9,8,5,3,2,3,9,8,6,3,1 ``` Now, `ĖŒṙ` enumerates the digits and performs run-length decoding, yielding the following array. ``` 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,14,14,14,14,14,14,14,14,14,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,20,20,20,20,20,20,21,21,21,21,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,25,25,25,26,26,26,26,27,27,27,27,27,27,27,27,27,27,28,28,28,29,29,29,29,30,30,30,30,30,30,31,31,31,32,32,32,33,33,33,33,33,33,33,33,33,33,33,33,34,34,34,35,35,35,35,36,36,36,36,36,37,37,37,38,38,39,39,39,39,39,39,39,39,39,39,39,39,39,39,40,40,40,41,41,41,41,42,42,42,42,43,43,43,44,44,44,44,44,44,44,45,45,45,45,45,45,45,45,45,46,46,46,46,47,47,47,48,48,48,48,49,49,49,50,50,50,50,50,50,50,50,51,51,51,51,51,51,51,51,51,52,52,52,52,53,53,53,54,54,54,55,55,55,56,56,56,56,56,56,56,56,56,57,57,57,57,57,57,57,57,58,58,58,58,59,59,59,59,60,60,61,61,61,62,62,62,62,62,62,62,62,62,63,63,63,63,63,63,63,63,64,64,64,64,64,65,65,65,66,66,67,67,67,68,68,68,68,68,68,68,68,68,69,69,69,69,69,69,69,69,70,70,70,70,70,70,71,71,71,72 ``` Then, `ị⁾81` indexes into the string **81**, replacing odd numbers with the character **8**, even number with the character **1**. Afterwards, `s30` splits the result into chunks of length 30. Displaying one chunk per line, the result looks as follows. ``` 888888888888888811111111111111 888888888888888888111111111111 888888888888888888811111111111 888111111111111888881111111111 888111111111111118888111111111 888111111111111111888811111111 888111111888888111188881111111 888111188888888881118888111111 888111888888888888111888811111 888118888888888888811188881111 888111111188888888811118881111 888111111118888888881111888111 888111111111888888881111888811 888111111111888888881111188811 888111111111888888881111118881 ``` Now, `m0` concatenates the array of chunks with a reversed copy of itself. Afterwards, `Z` zips the result, transposing rows and columns. ``` 888888888888888888888888888888 888888888888888888888888888888 888888888888888888888888888888 888111111111111111111111111888 888111111111111111111111111888 888111111811111111118111111888 888111118811111111118811111888 888111188811111111118881111888 888111188811111111118881111888 888111888811111111118888111888 888111888881111111188888111888 888111888888111111888888111888 888111888888888888888888111888 888111888888888888888888111888 888111888888888888888888111888 888811188888888888888881118888 188811188888888888888881118881 188881118888888888888811188881 118888111888888888888111888811 111888811118888888811118888111 111188881111111111111188881111 111118888111111111111888811111 111111888811111111118888111111 111111188881111111188881111111 111111118888811118888811111111 111111111888881188888111111111 111111111118888888811111111111 111111111111888888111111111111 111111111111118811111111111111 111111111111111111111111111111 ``` `0` is an unparsable nilad, so the result from before is printed (without line breaks) and the return value is set to **0**. `62` is another unparsable nilad, so the result from before (**0**) is printed and the return value is set to **62**. `ȷ446` is yet another unparsable nilad. **62** is printed and the return value is set to **10446**. Finally, `‘` increments the result. The final result (**10446 + 1**) is printed when the program finishes. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~81~~ ~~78~~ ~~75~~ 73 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` $!╚Qαūπōθ(└↓Υ8Π⁶!√|ΠΚψ░⅜Υ‛⁷>∙↓ts3]δεΧ‰“8«─'½Κ81¹¹I⌡_¹◄ø∑'¹n╬³0621"η“⌡01⁰∑ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTI0JTIxJXUyNTVBUSV1MDNCMSV1MDE2QiV1MDNDMCV1MDE0RCV1MDNCOCUyOCV1MjUxNCV1MjE5MyV1MDNBNTgldTAzQTAldTIwNzYlMjEldTIyMUElN0MldTAzQTAldTAzOUEldTAzQzgldTI1OTEldTIxNUMldTAzQTUldTIwMUIldTIwNzclM0UldTIyMTkldTIxOTN0czMlNUQldTAzQjQldTAzQjUldTAzQTcldTIwMzAldTIwMUM4JUFCJXUyNTAwJTI3JUJEJXUwMzlBODElQjklQjlJJXUyMzIxXyVCOSV1MjVDNCVGOCV1MjIxMSUyNyVCOW4ldTI1NkMlQjMwNjIxJTIyJXUwM0I3JXUyMDFDJXUyMzIxMDEldTIwNzAldTIyMTE_) Explanation: ``` ...“ push a big number of the RLE lengths of the top part 8«─ convert from base 10 to base 16 (15 was the max length, and making it base 15 wasn't worth it) '½Κ prepend to the array 48 81¹ push [8, 1] ¹ wrap those two in an array I rotate clockwise, resulting in [[8, 48], [1, 2], [8, 9], [1, 12], ...] ⌡_¹ flatten (iterate over, splat current items contents on stack, collect the contents in an array) ◄ run-length decode ø∑ join as a string '¹n split into lines of length 15 ╬³ palindromize horizontally with no overlap 0621 push 0, 6, 2, and 1 "η“ push 445 ⌡ that many times do 0 push 0 1 push 1 ⁰∑ join the stack together in a string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 136 bytes ``` “ßṪṭAƭẠvµM⁾ṖOḥ⁻Ɠ×Ṣ~*pṭẒFỵṿ¦4ÇḟọLÑOcKɲ⁶2*Ḣɲ’b45;@€1ẋ/€ø“Œ\⁴rrNỊġ:,xƙŒ#ṠƲQçḷĠ%&⁻ɼiḂŀB<Ȧƈg(Ṇb>TḥḄ|ḃṘƬ#l7ƇØṃ’b94;@€8ẋ/€ðżF;0;6;2;1;0ẋ445¤;1Ḍ ``` [Try it online!](https://tio.run/##Nc5NSwJBHAbwDyOFSJArY28jUR289CJBR0@GRLKH8BAFEbsaGb0c2qAUAjcxg1AQyZrZlYIdd8iP8cwX2aag0//h4YHfv1Q0zeMoUtajaIK/gvdWZQ@eexgMN5X9CX6fA3tWti/vxAN46zRxoDfwnCz8IfhX0CGiBtaEf7MhbnO765OBst9TCbCWTlajQNJ0RVW6BryrWX0F01To5JX9Vi5vwb8cPy3NHMlG6MTAXTnYFi9gH2N3alqbk9E@WCW01jLfHXmxFwc/Lyzv6H/Azk7AquB12Y2Z87Im6uDVX26R/HEL/1w/HGVpks7RFDVoUreEpIM2NcCuo@gH "Jelly – Try It Online") # Explanation (numbers shortened) ``` “ßṪṭ...*Ḣɲ’b45;@€1ẋ/€ø“Œ\⁴...ƇØṃ’b94;@€8ẋ/€ðżF;0;6;2;1;0ẋ445¤;1Ḍ Main link “ßṪṭ...*Ḣɲ’b45;@€1ẋ/€ Run-length encoded 1s “ßṪṭ...*Ḣɲ’ The base-45 encoding of the list of the run-lengths of 1s b45 in base 45 € For each element ;@ prepend 1 1 € For each sublist / Reduce over ẋ Repeat list (this gets a bunch of lists of 1s) ø“Œ\⁴...ƇØṃ’b94;@€8ẋ/€ Run-length encoded 8s “Œ\⁴...ƇØṃ’ The base-94 encoding of the list of the run-lengths of 8s b94 in base 94 € For each element ;@ prepend 8 8 € For each sublist / Reduce over ẋ Repeat list (this gets a bunch of lists of 8s) ðżF;0;6;2;1;0ẋ445¤;1Ḍ With both of the previous lists of lists, construct the final string ż Interleave them F Flatten it ;0 Append 0 ;6 Append 6 ;2 Append 2 ;1 Append 1 ; Append 0ẋ445¤ (Nilad) 0 0 ẋ445 445 times ;1 Append 1 Ḍ Convert decimal digits to a number ``` -121 bytes thanks to Dennis using `“...’` literals instead of normal numbers [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~133 84~~ 73 bytes ``` “÷iþṃL7[ḲʂƘⱮ=ƬƤ¬`RẹŀẹY÷n£ị€ıø&ḟ"gPƲ_ÇḊṪ’b⁴48;ĖŒṙḂ×7‘s15m€0F;“¡©£¢‘Ḍ×ȷ446‘ ``` **[Try it online!](https://tio.run/##AZoAZf9qZWxsef//4oCcw7dpw77huYNMN1vhuLLKgsaY4rGuPcasxqTCrGBS4bq5xYDhurlZw7duwqPhu4vigqzEscO4JuG4nyJnUMayX8OH4biK4bmq4oCZYuKBtDQ4O8SWxZLhuZnhuILDlzfigJhzMTVt4oKsMEY74oCcwqHCqcKjwqLigJjhuIzDl8i3NDQ24oCY/8OHRHMzMFn/ "Jelly – Try It Online")** (footer formats the decimal number with the dimensions that yield the coat of arms). ### How? A run-length encoded form of a binary format of the left-side of the coat of arms' `8`s and `1` up to the row before the one starting `0621` reflected with the `0621` added and then multiplied up by **10446** and incremented. ``` “...’b⁴48;ĖŒṙḂ×7‘s15m€0F;“¡©£¢‘Ḍ×ȷ446‘ - Link: no arguments “...’ - base 250 number b⁴ - to base 16 48; - prepend a 48 Ė - enumerate [[1,48],[2,12],[3,3],[4,12],[5,3],... Œṙ - run-length decode (48 1s then 12 2s then ...) Ḃ - modulo by 2 (vectorises) evens->0 odds->1 ×7 - multiply by 7 (vectorises) ‘ - increment (vectorises) - now all 8s and 1s s15 - split into chunks of length 15 m€0 - reflect each chunk F - flatten “¡©£¢‘ - code-page indices = [0,6,2,1] ; - concatenate Ḍ - from decimal list to number ȷ446 - 10^446 × - multiply ‘ - increment ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~107~~ ~~104~~ ~~98~~ ~~96~~ ~~87~~ 79 bytes ``` E³⁰✂”}∧Pt→8⌕LJε`‽∨↑¬KαfGⅉKMκ⎆wp◧⪫⊘^≦#⁸¹"π✂×OγX‹nI”×ι¹⁵×⊕ι¹⁵‖CM²⁸←621M²⁵¦¹⁴1UB0 ``` [Try it online!](https://tio.run/##ldBNCoMwEAXgvacYslKpYOwPQ29j49iGxkRiKvT0aQuVRkWLbxO@l83MiFtphSmV903ZQrzPoVNSEDDcGB5kiTgijohrxDlxQpwwLJcYms8ZmI8djDR9g6U3G1fM/xx5uO4vDNJYAj8mkEIstbDUkHZUxTL5tElkqVYknDDtM2pMT1AgnBXVLmqt1A7YqeDs@3PcAT8M/bvtyF1Kcb9a89AVsJx577PeZ516AQ "Charcoal – Try It Online") Link to verbose code for explanation [Answer] # [Proton](https://github.com/alexander-liao/proton), 368 bytes ``` s=(map("8"&(*),[93,6,6,1,1,6,2,2,6,3,3,6,3,3,6,4,4,6,5,5,6,6,6,6,18,6,18,6,18,7,16,4,3,16,3,4,14,4,4,12,4,4,8,4,4,4,4,4,4,4,4,4,5,5,5,5,8,6,2]),map("1"&(*),[24,24,6,10,6,5,10,5,4,10,4,4,10,4,3,10,3,3,8,3,3,6,3,3,3,3,3,3,3,3,3,1,3,3,2,3,3,3,3,3,5,4,4,7,14,9,12,11,10,13,8,15,4,17,2,20,23,26,44])) q=''.join(s[0][i]+s[1][i]for i:0..len(s[0])) print(q+'0621'+'0'*445+'1') ``` [Try it online!](https://tio.run/##ZY/dCsIwDIXvfQrxwrZbGE3/NgWfZOzCC4WJrvvx/WfSDZnIBzmlbU5O@jG@YzfP00W@rr08VIejzBTUJwuBQCKAIQJYsN/qiACeCCtYbUoJyH8si6UDutSBJkkF7g@/wgamUZDC4BrGODA8D3UaSuLZTS@mepmkU7RqE/MXTNVsbnzqLzndibMhsguyCaYBJW@uwVAbreMapXbDRYjiEdtOTrVu6rbJpxpZ73Hct2ddFM/b8kaf@7Ht3nLIhQ4GBYnInPO5QKHm@QM "Proton – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~760~~ ~~523~~ ~~329~~ ~~205~~ 196 bytes *-237 bytes thanks to Stephen. -124 bytes thanks to Jonathan Frech.* ``` print''.join((ord(j)-34)*'81'[i%2]for i,j in enumerate(":(:((#,#(('$,$'(&%,%&(&%,%&(%&,&%(%'*'%(%(((%(%4%(%4%(%4%)%2%&#%%2%%$&%0%&%&%.%&'&&*&&)&0&+&.&-&,&/&*&1'&'3'$'6*9(<$N"))+'0621'+'0'*445+'1' ``` [Try it online!](https://tio.run/##PYxNasMwFISvYmK9mSdZcfwX05icIRcoXQTiUBkqB@MsuurRXS1CGL5vYBbz@F2/59hs22MJcSXLaQ5RdV5uOtl921nHj5qfQZqv@7xkwU9ZiNkYnz/jcl1H3f0NOqjmPlel8YYK8YKXBR6iQsdk1YR0b6w0glySxUAqQUopIOAAiwoFSuzTwyENNcGWhr076dlcdtYWrPqmZiq6rjsWrLlt/w "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 180 bytes ``` s=0;"".unpack('H*')[0].split(?f).map{|a|a.chars.map{|c|s^=2**c.to_i(16)};t=("%015b"%s).gsub ?0,?8;$><<t+t.reverse};puts'0621'+?0*445+?1 ``` [Try it online!](https://tio.run/##TY7dToQwEIVfxRA3/GnTslAgLDas2pj4CFYNEFSiAqHF1Mi@ujgNXHjxZTIzZ86Zcaq@l0XmOLOE5hzAQpNA6H0odESFjhOh00Loo9lFAMx4vGoTIAT2ACZCB3ybH6HerroCepoKfWO0cJ9c/8uIV19arN6p0UAe33YcPKnxNr9sOeaOYwtN3VDW745959nuA35EcvholcNeXPRZDj9zOZeofitHubb1LJ/ywPNqpPrn1iHUPWUqd6wdJlFl7aSLXuVUnTF8wZLs/OpwUL5CY/PVjLI5ZcOkpI1pQGyfYS8MI5@RZfntB9X2nVwu77s/ "Ruby – Try It Online") 178 bytes + 2 bytes for `-Kn` (forces ASCII encoding.) 43 mostly unprintable characters in between the first quotes. Hexdump: ``` 00000000: 733d 300a 22ff f012 3456 789a bff5 f6f7 s=0."...4Vx..... 00000010: ff8f 4f3f 012f ff8b fef7 af69 df45 8cf0 ..O?./.....i.E.. 00000020: 1237 bf6a f59f 48f2 37f1 6f04 5f3f 12f0 .7.j..H.7.o._?.. 00000030: 222e 756e 7061 636b 2827 482a 2729 5b30 ".unpack('H*')[0 00000040: 5d2e 7370 6c69 7428 3f66 292e 6d61 707b ].split(?f).map{ 00000050: 7c61 7c61 2e63 6861 7273 2e6d 6170 7b7c |a|a.chars.map{| 00000060: 637c 735e 3d32 2a2a 632e 746f 5f69 2831 c|s^=2**c.to_i(1 00000070: 3629 7d3b 743d 2822 2530 3135 6222 2573 6)};t=("%015b"%s 00000080: 292e 6773 7562 203f 302c 3f38 3b24 3e3c ).gsub ?0,?8;$>< 00000090: 3c74 2b74 2e72 6576 6572 7365 7d0a 7075 <t+t.reverse}.pu 000000a0: 7473 2730 3632 3127 2b3f 302a 3434 352b ts'0621'+?0*445+ 000000b0: 3f31 ?1 ``` # How? Everyone else was doing run length encoding, so I wanted to try something different. The formatted "picture" version of the prime can be separated into two parts - a 30x30 grid of 8's and 1's, and a second section of mostly zeros which can be hardcoded. Focusing on the first part, we observe that it's symmetrical down the center, so if we can produce the left half then we can just print half of each line with its reverse. Half of one line is 15 characters long. If we replace the 8's with zeros, each line can be interpreted as a 15-bit binary number. Conveniently, for the most part the edit distance between each consecutive line is small, so I decided to implement my solution by storing the first line `s` (`888888888888888`, which just becomes 0) and applying a series of bit flipping operations on `s`, printing the result each time. Since each line is 15 bits long, I encoded these operations as hexadecimal digits - for example, if the operation is `b` (or 11), then we flip bit 11. Some lines differ by more than one bit, so they require a string of hexadecimal digits. We have one bit left over (`f`) so we can use it as a delimiter between these strings, and also as a "do nothing" value. Example below (you can see these lines in the [post](https://math.stackexchange.com/questions/2420488/what-is-trinity-hall-prime-number) referenced in the question): ``` Line 3: 000000000000000 Line 4: 000111111111111 <-- flip bits 0 through b Line 5: 000111111111111 <-- do nothing Line 6: 000111111011111 <-- flip bit 5 ``` To put that all together, we would encode `0123456789ab`, then separate with `f`, do nothing with `f`, then `5`. This works because we're going to do `.split(?f)` later to get each set of operations by line, which will yield `["0123456789ab", "", "5"]`, and `""` will be a no-op. The difference between lines 3 and 4 above is by far the longest set of edits, and the edit distance between any two consecutive lines is usually 0-2, so I would say that this encoding is reasonably inexpensive, although I'm sure it can be improved. The entire encoded string ends up being `fff0123456789abff5f6f7ff8f4f3f012fff8bfef7af69df458cf01237bf6af59f48f237f16f045f3f12f0` (86 bytes), which will get the entire 30x30 grid. But we're not done yet... Hexadecimal digits can be represented by 4 bits (`b` -> `1100`, etc.) That means that if we're willing to encode our string 4 bits at a time rather than using bytes, we can cut the length of the string in half. So that's what I did - the hexdump shows the string represented in 43 bytes. After that, it's just a matter of using Ruby's nifty [String#unpack](https://ruby-doc.org/core-2.4.1/String.html#method-i-unpack) with `H*` (interpret as hex string, high nibble first) to expand the 43-byte string into the 86-byte version we know and love, and looping over each set of operations flipping bits - for our stored string `s` and an operation `c` we do `s ^ 2**c.to_i(16)` to flip the corresponding bit. After each set of edits is completed, we pad the resulting binary to 15 bits, switch all of the 0's back to 8's, and print the result and its reverse. As noted before, the part of the number after the 30x30 grid can be hardcoded, so we do that as `puts'0621'+?0*445+?1`. The final encoded string has no possibility of working on TIO, so the TIO version uses escapes, which still works but is longer. [Answer] # CJam, ~~532~~ ~~412~~ ~~340~~ ~~231~~ ~~210~~ 209 bytes ``` ".$MBZp&8OIoLs7Rv/BEqN#1r~E$O%6^UO=\z:(Iw]l\LQ.g.aWf+{2;on|YP'y$:Lc$i$GMCg&mRs#y0*z`Z,C|Hf6;b/o-0|FNK5R:OIi}{'`CJ}LOXMSA,&vzl5scm5y0{om=A_#/wF"'#fm92bs:A;"6NLkB)h%@{u`hp_v+YK"'#fm92bYb2f+{[A/(\s:A;)]}%e~'0445*1 ``` [Try it Online](http://cjam.aditsu.net/#code=%22.%24MBZp%268OIoLs7Rv%2FBEqN%231r~E%24O%256%5EUO%3D%5Cz%3A(Iw%5Dl%5CLQ.g.aWf%2B%7B2%3Bon%7CYP'y%24%3ALc%24i%24GMCg%26mRs%23y0*z%60Z%2CC%7CHf6%3Bb%2Fo-0%7CFNK5R%3AOIi%7D%7B'%60CJ%7DLOXMSA%2C%26vzl5scm5y0%7Bom%3DA_%23%2FwF%22%226NLkB)h%25%40%7Bu%60hp_v%2BYK%22%5D%7B'%23fm92bs%7D%2FiYb2f%2B%5C%3AA%3B%7B%5BA%2F(%5Cs%3AA%3B)%5D%7D%25e~'0445*1) Run-length encoding expanded from base 92 (Base 250 led to multibyte chars so had to adjust). Also, `4341089843357287864910309744850519376` is expanded from base 92 and converted to binary. A 1 means the run-length is two digits, 0 means it's one digit. For example, the first 4 digits of the binary representation are 1101 because the first four runs are `[93,8],[24,1],[6,8],[24,1]` (93 8's, 24 1's, etc...) [Answer] # JavaScript, ~~454~~ ~~450~~ ~~332~~ ~~207~~ 204 bytes *-4 bytes thanks to Stephen. -125 bytes thanks to Shaggy and Dom Hastings.* ``` _=>[...`] ,`].map((j,i)=>'81'[i%2].repeat(j.charCodeAt())).join``+0+621+"0".repeat(445)+1 ``` There's a boatload of unprintables in this answer, so here's a hexdump: ``` 00000000: 5f3d 3e5b 2e2e 2e60 5d18 0618 0606 010a _=>[...`]....... 00000010: 0106 0605 020a 0205 0604 030a 0304 0604 ................ 00000020: 030a 0304 0603 040a 0403 0603 0508 0503 ................ 00000030: 0603 0606 0603 0603 1203 0603 1203 0603 ................ 00000040: 1203 0703 1003 0401 0303 1003 0302 0403 ................ 00000050: 0e03 0403 0403 0c03 0405 0404 0804 0407 ................ 00000060: 040e 0409 040c 040b 040a 040a 0408 040f ................ 00000070: 0504 0511 0502 0514 0817 061a 022c 605d .............,`] 00000080: 2e6d 6170 2828 6a2c 6929 3d3e 2738 3127 .map((j,i)=>'81' 00000090: 5b69 2532 5d2e 7265 7065 6174 286a 2e63 [i%2].repeat(j.c 000000a0: 6861 7243 6f64 6541 7428 2929 292e 6a6f harCodeAt())).jo 000000b0: 696e 6060 2b30 2b36 3231 2b22 3022 2e72 in``+0+621+"0".r 000000c0: 6570 6561 7428 3434 3529 2b31 epeat(445)+1 ``` ``` f= _=>[...`] ,`].map((j,i)=>'81'[i%2].repeat(j.charCodeAt())).join``+0+621+"0".repeat(445)+1 document.write(f()) ``` [Answer] # JavaScript (ES6), ~~206~~ ~~205~~ ~~204~~ ~~203~~ ~~198~~ ~~197~~ 194 bytes Came up with this while working on [i cri everytim's solution](https://codegolf.stackexchange.com/a/142070/58974), figured it was different enough to warrant posting on it's own. This includes a load of unprintables between the `]` and the `,` so follow the TIO link below to view it with Unicode escapes (each sequence of `\u` followed by 4 digits counts as 1 byte). ``` _=>`],0621ƽ1`.replace(/\D/g,(x,y)=>"810"[y<122?y&1:2].repeat(x.charCodeAt())) ``` [Try it online](https://tio.run/##pVLLTsMwEPyXHpAthdTrvCrUFiH4C1JRN920hRBHTkDNx3HltwJNjbqJOSBxmR3NjHe1Kz@rd1Vn5lA113V12KJ51eULtl2my1oX6Bd6x1j3tFiuV@mbEDA7oYjH3CKkpa1jJ@pRWl8S7eyHPQbWD4j2N/9HKQfpsR@lGzLZ9WMHnQzIf@gJ0YWzCRDFzQTkcnQ/dPoMee5oEeGhvUhIMCEcLW9szYm3Gd3c/NIxdyb2HGDwKy66fQ0J@WfqnPJELOHzA9a@wapQGbJp@jDdeezotXyxnMxATB7bOUh5217BjVydcqgadvSzvTL3eot3DeOcd/wbuy8) [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~319~~ 318 bytes This is my first attempt at this challenge. Still a bit large and there are probably more efficient ways of doing it, but I thought I'd post it anyway as the method was more interesting than just zipping it. ``` for i=reshape('|871%871%8%1 8)1 8%1%8$1!8)1!8$1%8#1"8)1"8#1%8#1"8)1"8#1%8"1#8)1#8"1%8"1$8''1$8"1%8"1%8%1%8"1%8"118"1%8"118"1%8"118"1&8"1/8"1#8 1"8"1/8"1"8!1#8"1-8"1#8"1#8"1+8"1#8$1#8#1''8#1#8&1#8-1#8(1#8+1#8*1#8)1#8,1#8''1#8.1$8#1$801$8!1$831''861%891!8K1 0 6 2 1~0~0~0~0`0 1',2,[]);fprintf(repmat(i(2),1,i(1)-31));end ``` [Try it online!](https://tio.run/##bY/RCsIgFIZfxc2Z2lztLCgjeoIeIYJGOdpF21ijq@jV1z/tJgj5zv8peDy2l6F8unGs2p7V@949bmXnlHzZDQmPIGY1EPCEIniEFJZTDI@Rvx4Th3Pk5ImVEiVshG8SnP7kDCx9A4ZmwWMb@WaZPw@kPhPASUoUbmcgAwqkYP6dwgBMwO0CU3CQgwispptrPL3Ffw7EcrZmBaN3HtY5ZyRNYY4nvau6vm6GSvWuu5eDqlWhDZlakc5WpPXONddx/AA "Octave – Try It Online") The method used here is to make use of a Run-Length-Encoding scheme of sorts. We start off with the original number and count the number of consecutive digits. These are written in the result below as the count followed directly by the digit (space separated for clarity). ``` 938 241 68 241 68 61 8 101 8 61 68 51 28 101 28 51 68 41 38 101 38 41 68 41 38 101 38 41 68 31 48 101 48 31 68 31 58 81 58 31 68 31 68 61 68 31 68 31 188 31 68 31 188 31 68 31 188 31 78 31 168 31 48 1 38 31 168 31 38 21 48 31 148 31 48 31 48 31 128 31 48 51 48 41 88 41 48 71 48 141 48 91 48 121 48 111 48 101 48 131 48 81 48 151 58 41 58 171 58 21 58 201 88 231 68 261 28 441 0 6 2 1 4450 1 ``` If any of the values is larger than 95 we break that up into multiple chunks of 95 or less - this only happens for the 445 0's which instead becomes four sets of 95 0's and a set of 65 0's. We also pad any counts that are less than 10 with a 0 to make all elements three characters long. This yields with the spaces removed: ``` 938241068241068061018101018061068051028101028051068041038101038041068041038101038041068031048101048031068031058081058031068031068061068031068031188031068031188031068031188031078031168031048011038031168031038021048031148031048031048031128031048051048041088041048071048141048091048121048111048101048131048081048151058041058171058021058201088231068261028441010016012011950950950950650011 ``` In hindsight at this point I could have done this step before merging it all together, but ho hum you live and learn. We do something clever which is to take the count for each group (2 digits) and we add 31. Because all of them are <96, the resulting number is the ASCII value for a printable character (32 to 126). Giving us counts of: ``` |7%7%% ) %%$!)!$%#")"#%#")"#%"#)#"%"$'$"%"%%%"%"1"%"1"%"1"&"/"# ""/""!#"-"#"#"+"#$##'##&#-#(#+#*#)#,#'#.$#$0$!$3'6%9!K ~~~~` ``` After a bit of reshaping in MATLAB to make it more favourable for decoding, and then also escaping `'` characters with `''` (otherwise MATLAB splits string literals there), we are left with the clever string: ``` |871%871%8%1 8)1 8%1%8$1!8)1!8$1%8#1"8)1"8#1%8#1"8)1"8#1%8"1#8)1#8"1%8"1$8''1$8"1%8"1%8%1%8"1%8"118"1%8"118"1%8"118"1&8"1/8"1#8 1"8"1/8"1"8!1#8"1-8"1#8"1#8"1+8"1#8$1#8#1''8#1#8&1#8-1#8(1#8+1#8*1#8)1#8,1#8''1#8.1$8#1$801$8!1$831''861%891!8K1 0 6 2 1~0~0~0~0`0 1 ``` That is the root of the code. In the code all I then do is reshape the array into a 2D string with 128 pairs of characters. For each pair the first character has 31 subtracted, and then the second character is displayed that many times. The result is the original prime: ``` 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888111111111111111111111111888888111111111111111111111111888888111111811111111118111111888888111118811111111118811111888888111188811111111118881111888888111188811111111118881111888888111888811111111118888111888888111888881111111188888111888888111888888111111888888111888888111888888888888888888111888888111888888888888888888111888888111888888888888888888111888888811188888888888888881118888188811188888888888888881118881188881118888888888888811188881118888111888888888888111888811111888811118888888811118888111111188881111111111111188881111111118888111111111111888811111111111888811111111118888111111111111188881111111188881111111111111118888811118888811111111111111111888881188888111111111111111111118888888811111111111111111111111888888111111111111111111111111118811111111111111111111111111111111111111111111062100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 ``` --- Edits: * rearranged the magic string so I could get rid of a transpose after the reshape. Saves a byte. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 76 bytes ``` •ŒÆÿ¹т£Ƶ‘β\,ä¸γλaXë«Š¸þaγG(žÃÇ…»šKþÈ/?`'•20BS20öDg81s∍Ss×J30ôø.∞0D445×621s1J ``` [Try it online!](https://tio.run/##AYAAf/8wNWFiMWX//@KAosWSw4bDv8K50YLCo8a14oCYzrJcLMOkwrjOs867YVjDq8KrxaDCuMO@Yc6zRyjFvsODw4figKbCu8WhS8O@w4gvP2An4oCiMjBCUzIww7ZEZzgxc@KIjVNzw5dKMzDDtMO4LuKInjBENDQ1w5c2MjFzMUr//w "05AB1E – Try It Online") --- Stole this from Dennis: ``` 888888888888888811111111111111 888888888888888888111111111111 888888888888888888811111111111 888111111111111888881111111111 888111111111111118888111111111 888111111111111111888811111111 888111111888888111188881111111 888111188888888881118888111111 888111888888888888111888811111 888118888888888888811188881111 888111111188888888811118881111 888111111118888888881111888111 888111111111888888881111888811 888111111111888888881111188811 888111111111888888881111118881 ``` Noticed it always alternates between 8 and 1, so I counted the lengths of each run (Base 20): ``` ['G', 'E', 'I', 'C', 'J', 'B', '3', 'C', '5', 'A', '3', 'E', '4', '9', '3', 'F', '4', '8', '3', '6', '6', '4', '4', '7', '3', '4', 'A', '3', '4', '6', '3', '3', 'C', '3', '4', '5', '3', '2', 'E', '3', '4', '4', '3', '7', '9', '4', '3', '4', '3', '8', '9', '4', '3', '3', '3', '9', '8', '4', '4', '2', '3', '9', '8', '5', '3', '2', '3', '9', '8', '6', '3', '1'] ``` Joined it all together, and converted it into a base-10 integer: ``` 3954184379309026812828704944878416720438306456270310298603957651230861078960874182787979106461 ``` Compressed it further into base-255: ``` ŒÆÿ¹т£Ƶ‘β\,ä¸γλaXë«Š¸þaγG(žÃÇ…»šKþÈ/?`' ``` --- [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~277~~ ~~250~~ 201 bytes -27 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` n;f(i){for(i=0;n="oApYGYGGBKBGGFCKCFGEDKDEGEDKDEGDEKEDGDFIFDGDGGGDGDSDGDSDGDSDHDQDEBDDQDDCEDODEDEDMDEFEEIEEHEOEJEMELEKENEIEPFEFRFCFUIXG[Cm"[i++]%64;)for(;--n;)putchar(49+i%2*7);printf("0621%0446d",1);} ``` [Try it online!](https://tio.run/##PY9Na8JAFEX/SgkEZkwDUUKkDC6aefc9Y6r2g0JFupCU1Fk4hqAr8benI0h53LM4i8t9TfrbNMPgTaucvrTHXrlZZvwsOj53G9mIlHUpwra2LKCacCehBglxxYEiIfTxnzm9EUoKJAtaE8ItCQxUwBxrLLDES2hYBfHK4He2/Fl9ydYeoq1Lku@4yI2@rTFp6o3uzqdmv@tV/pS4eDKaatP1zp9aFWXFZBxneV78RI9jba5D0A@HnfMqfKNu4g8 "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 307 bytes ``` $d=1;print((map{($d^=9)x$_}(93,24,6,24,6,6,1,10,1,6,6,5,2,10,2,5,6,4,3,10,3,4,6,4,3,10,3,4,6,3,4,10,4,3,6,3,5,8,5,3,6,3,6,6,6,3,6,3,18,3,6,3,18,3,6,3,18,3,7,3,16,3,4,1,3,3,16,3,3,2,4,3,14,3,4,3,4,3,12,3,4,5,4,4,8,4,4,7,4,14,4,9,4,12,4,11,4,10,4,13,4,8,4,15,5,4,5,17,5,2,5,20,8,23,6,26,2,44)),0,621,0 x445,1) ``` [Try it online!](https://tio.run/##bY/BCsIwDIZfxcMOLeTQpGm3IXsVRZgHQWUMD4L47DV/Oy8iJT/f3yRNupzXayqlmyfeL@vl/nDudlperpsP0@if3fHtxkiilJtkYuJgAkwkMGKQSSnCRNJfAzWDO5hEg0XjXE9jHv5CD9geMd2M7dSGaM20YKmQLNSGQHu0AUYAepi/63DcyjjVnkTc1z9ZBEsItpCMSeo9BcrCFHZPVav0pXwA "Perl 5 – Try It Online") [Answer] ## [Bubblegum](https://esolangs.org/wiki/Bubblegum), 88 bytes ``` 00000000: edc9 310a 0250 10c4 d02b fdb1 90dc ff64 ..1..P...+.....d 00000010: 96c1 80a2 8885 60aa d97d 7cb3 3de8 75c5 ......`..}|.=.u. 00000020: 37ab 820a 51ee 9537 942a 55c4 aaec 76b4 7...Q..7.*U...v. 00000030: cfb5 1cdc 33dd 908b ac1c 74a0 894e 03c8 ....3.....t..N.. 00000040: 11cc 99ab 9c1d c661 32c5 bad6 8aad 96d2 .......a2....... 00000050: b95e 76fe fd6e bb01 .^v..n.. ``` [Try it online!](https://tio.run/##bdA9TgQxDIbhnlN8NUhWnEz@kLgCgoIWEdsZGpaK3QrOPnjZ2Q5XTpFHbyJHkY/5fjxsW9jnHtO0I3EYCDEHcNAFFqJgNWH0YIp1LQtAxERPRHRH57Gbi8Bu9KKMFkZEay2jhDFgvRqqSkKy2VCz5rNxnjein296oCPtRnQj1SFo0Tsyz4meU0Vfoh@zF40xFbWId1QXnokq3b74droayQ1dJYPVk1My8/gmGMp@cxkBrS8TIWm7dKS/li@iR7oaixvMqujdY7qyQUthpOjxMqygjeFusXh9C424L7uR3ZCep9eu0z@xTIgExr9DryeiT6Jt@wU "Bubblegum – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 194 bytes ``` $><<?8+"~:(:((#,#(('$,$'(&%,%&(&%,%&(%&,&%(%'*'%(%(((%(%4%(%4%(%4%)%2%&#%%2%%$&%0%&%&%.%&'&&*&&)&0&+&.&-&,&/&*&1'&'3'$'6*9(<$N".bytes.reduce(""){|s,x|s+(s[-1]==?8??1:?8)*(x-34)}+"0621"+?0*445+?1 ``` The upper part is RLE-encoded, the rest is simply hardcoded. [Try it online!](https://tio.run/##PYxLDoJAEAXvMky/7vmADKJBAs4NvIBxg3IB0UQjenWchTEvVYtavOt9eC6L3nddbJz6tNKKZD4TYe01C8gTfiZ4kBBbThZJUP3HUEXIKJk0qCSkFQQGLGBQwqFAnh5WKQQGr1nz1u6k0wdVDM/bOBXX8XI/j6KUec2Tf8yTk@mYh1PfxybG0MbGWHnk69q8nSq3VVAulrauNy6GZfkC "Ruby – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 339 bytes ``` val s="8J188J1888138<13881887148<14871886158<15861886158<15861885168<16851885178:178518851888188518851D8518851D8518851D8519851B85168315851B85158416851@85168516851>85168716861:861689168@168;168>168=168<168?168:168A1786178C1784178F1:8I188L148^130363231ǯ031" fun x()=(0..s.length-1 step 2).map{i->(1..(s[i].toInt()-50)).map{print(s[i+1])}} ``` [Try it online!](https://tio.run/##bY/dSsMwGIbPdxVhRwnS0G9p06yudVMRNjzzUCb0YNZil5U2ijJ6DV6K9@CJl1XfpZ4IBh7eJz/fl@T54OrKDsNrUbMum359mA0ZjyFlFsDAE4rgEdIYTTE8Rv71mDRcI0@emBSMbnyP0a//yTm49PUKvUaPTeR7Lf36SO4zAZpSoM0cLME5yEH2@4YLkIIV3qDBFYjADerWuPcWf3kgFSqtZoq@P0NF08nji2VvXGQ8lLKT9c6W7ikg1rldw2ZC7ovmWAU5Jyl5d19tpTusreMiiEMx7jZthQXsndFW9P1wargvKsuLtuxStmrb4n1x53CqzAU7ThgGLvTpa2uLWT/8AA "Kotlin – Try It Online") [Answer] ## CJam (108 81 bytes) ``` "u{èl>`#ö^½³ó!;kMðSÀËndEyvY3ÉÊÅBà#®"256bFbee{)*~}%"81"f=15/_Wf%zT6Y446,:!1 ``` [Online demo](http://cjam.aditsu.net/#code=%22u%1E%7B%C3%A8l%3E%60%C2%8D%23%C2%80%C3%B6%5E%C2%BD%C2%B3%C3%B3!%3B%C2%96%C2%8DkM%C3%B0S%C3%80%C3%8Bnd%1CEyvY3%C3%89%C3%8A%C2%8D%C3%85B%C3%A0%23%C2%AE%22256bFbee%7B)*~%7D%25%2281%22f%3D15%2F_Wf%25zT6Y446%2C%3A!1) In case character encoding borks the above, here it is xxd-encoded: ``` 0000000: 2275 1e7b e86c 3e60 8d23 80f6 5ebd b3f3 "u.{.l>`.#..^... 0000010: 213b 968d 6b4d f053 c0cb 6e64 1c45 7976 !;..kM.S..nd.Eyv 0000020: 5933 c9ca 8dc5 42e0 23ae 2232 3536 6246 Y3....B.#."256bF 0000030: 6265 657b 292a 7e7d 2522 3831 2266 3d31 bee{)*~}%"81"f=1 0000040: 352f 5f57 6625 7a54 3659 3434 362c 3a21 5/_Wf%zT6Y446,:! 0000050: 31 1 ``` The initial run of 8s and 1s is split into just the left half and run-length encoded as just the lengths of alternating runs. Runs of more than 24 are split into runs of at most 24, separated by runs of 0, so that the lengths can be base-25 encoded and then base-256 encoded to pack them down. [Answer] ## JavaScript (ES2017), 287 bytes ``` _=>"00000000000000000027wr2027wr2027a9ko261b7c23jerc23jerc1yjm0o1y8coo1y2ou01xx5q01xx5q01xx5q00yykxc9ull699d4au9dk75xffo1v2fgptj4fh8jrj3hhwvgfhmlev3hour5rhq24n3hqytj3hr4hdrhr8ykfhra0hr".replace(/.{6}/g,n=>parseInt(n,36).toString(2).replace(/0/g,8).padStart(30,8))+0+621+"0".repeat(445)+1 ``` Uses a slightly different approach to [@icrieverytim](https://codegolf.stackexchange.com/users/68615/i-cri-everytim)'s answer. -10 bytes thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)'s suggestion of using `replace` instead of `match`! ``` f= _=>"00000000000000000027wr2027wr2027a9ko261b7c23jerc23jerc1yjm0o1y8coo1y2ou01xx5q01xx5q01xx5q00yykxc9ull699d4au9dk75xffo1v2fgptj4fh8jrj3hhwvgfhmlev3hour5rhq24n3hqytj3hr4hdrhr8ykfhra0hr".replace(/.{6}/g,n=>parseInt(n,36).toString(2).replace(/0/g,8).padStart(30,8))+0+621+"0".repeat(445)+1 ; p.innerHTML=f() ``` ``` pre{word-wrap:break-word;white-space:normal} ``` ``` <pre id=p></pre> ``` [Answer] # [///](https://esolangs.org/wiki////), 260 bytes ``` /;/88%//:/1&13%13"//9/\/\///7/"1#95/!!!!94/%""93/8889-/000009,/11#9'/###9&/#88"9%/"""9#/389"/1119!/-----0/'''''''##8%4#;4&"8%18""&11;188"1::1&#%1#"&#8"",8"&&"&&'&&'&&'&#3"'#"#13"'#"3,"##&#"#"'"#",7#7"7%",%#%"#%,%1#%7"",4#8784,8,8%%,#%%",;411;%%41106215555!0001 ``` [Try it online!](https://tio.run/##LY87jsMwDETPYg4oNQrGjJQVaV8lTYoFUqTz/eEwm338QdKQhI7X43j@HufJne5KbrRiXa0LGbynkZNiiBuXJAZVJHqqPS5cP0SjpaASQBTCXUIpKQO7h@SrxcLLh5X1C@A6sI8iruYixWy37LRtswI1SEFeN5dS0uu/o0uFwP5KbwKUPErNaBNTpkpTqEBbztCZEwZ8@mjeXLVBU7CPXKaaef252i1Z8ht2nm8 "/// – Try It Online") Nothing terribly interesting, just some compression. [Answer] ## Mathematica, 192 bytes ``` Uncompress["1:eJxTTMoP8nRjZWCwoCUwxAGIl0VSZIEhi2wEXAgma4Eqa0GCrAW6rAW6rAWyJKYsulPRGGhBRLksNmmYy/HJonkOXStWaeTwgTGQ5JADD4mJTQRdGo2PysUwC1kA0yJDFPdgJjWoKHZJNB/hlMYhaYiaMgkDAzMjQ4NRMHSBIQDgQA6C"] ``` See: <http://reference.wolfram.com/language/ref/Compress.html> [Answer] # [Python 2](https://docs.python.org/2/), ~~191~~ ~~190~~ 188 bytes ``` s='0621'+'0'*445+'1' a=1 for c in'L":&7(4%"%1%$%/$($-$*$+$,$)$.$\'$$($$%$#,#$#$#.#$"##0##!$#0#\'#2#&#2#&#2#&#&&&#&#%(%#&#$*$#&$#*#$&$#*#$&%"*"%&&!*!&&8&8}':s=`a`*(ord(c)-32)+s;a^=9 print s ``` [Try it online!](https://tio.run/##PYwxDoJAEEV7TgE7f2aWRREQFTXcwCMQI9EYbcAAjYVnxy2M@XmveMV/vadH3xXzPNaabYtcE83UleUm0VyDts6Dez@E1/DZ6ckcZGdLNpwzeAWLJRwSLBAjRaPwBQxaEPxSgiHKiCJ4N0oFyR8RD7Flb/9BAnKEn9k4wyKRi0QqqT56GOtLe3G2H272Gi/XRZyMx/Zc74PX8OymcJznLw "Python 2 – Try It Online") Same principal as my answer over [here](https://codegolf.stackexchange.com/a/146038/38592) ]
[Question] [ If you've ever tried to write palindromic code before, you'd know how much brackets tend to get in your way. `()()` is not a palindrome, even though it kinda looks like it should be, while `())(` and `()(` are both palindromic and both very dumb looking. Wouldn't it be convenient if it was the other way around? A string is *conveniently palindromic* if it is equal to the string derived when its reverse has all its parentheses (`()`), brackets (`[]`), and braces (`{}`) flipped. No other characters are special and require flipping. (`<>` are sometimes paired but often not so they are left out.) **Your task** is to write, in your language, a program (taking input on STDIN) or a function (taking a single string argument) which (a) gives a consistent true value\* when its argument is conveniently palindromic and a different, consistent false value otherwise, and (b) is *itself* conveniently palindromic. For example, the following inputs are conveniently palindromic: ``` racecar (a)(bb)(a) void main(int argc, *char[] argv) {} (vgra []rahc* ,cgra tni)niam diov ``` And the following are not: ``` non-palindrome A nut for a jar of tuna? (old [style] parens) )snerap ]elyts[ dlo( ingirumimusnocte)etconsumimurigni ``` You may not rely on any external state (specific filename, directory structure, other user input, web access, etc) except interpreter/compiler flags. Also, you may not use "the comment trick" where you comment out or render unused some piece of code by taking advantage of your language's commenting facilities. For instance, all of the following are not allowed, because they contain non-functional parts that can be safely removed or destroyed (at the expense of losing conveniently-palindromic-ness): ``` {some code} // {edoc emos} {some code} NB.BN {edoc emos} "n\" ;{edoc emos} ;"; {some code}; "\n" ``` Obviously this might not cover every such case, but the spirit of the challenge here is not to use comments and unparsed\*\* code to achieve palindrominess, instead making use of the corrected parens and brackets. I'm looking at you, LISP, Brainfuck. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins, but all lengths of code are welcome. \* By consistent true and false values, I mean that you can return one of a pair of values, such as `1` for true and `0` for false, or `False` for true and `"no"` for false, so long as these values are different from each other, and do not change from run to run of your program. Use whatever saves you characters. \*\* Not to be confused with *unexecuted*: code that is valid and might do weird things but never called is fine. [Answer] # GolfScript, ~~107~~ 91 ``` .4:ab-1:ba=;1 %ba%{...fi@@= c43.=;)('"([{ }])"'~?~'"([{ }])"')(;=.34c =@@if...}%ab% 1;=ab:1-ba:4. ``` Newlines are artistic. `fi`, `c43` and `c` are noops, but **the entire code is executed.** Prints `-3-1-1` for convenient palindromes, `-4-1-1` otherwise. [Try it online!](http://golfscript.tryitonline.net/#code=LjQ6YWItMTpiYT07MSViYSV7Li4uZmlAQD1jNDMuPTspKCciKFt7fV0pIid-P34nIihbe31dKSInKSg7PS4zNGM9QEBpZi4uLn0lYWIlMTs9YWI6MS1iYTo0Lg&input=LjQ6YWItMTpiYT07MQolYmEley4uLmZpQEA9CmM0My49OykoJyIoW3sKfV0pIid-P34nIihbewp9XSkiJykoOz0uMzRjCj1AQGlmLi4ufSVhYiUKMTs9YWI6MS1iYTo0Lg) ### Alternate version, 155 bytes At the cost of 64 bytes, this can be improved upon: ``` 0!*1{!}\;:);0:f;0:i;-1:ab;9:ba; ...=;1%ab%{....i@f@@fi@@=@.=@\) +""'"([{}])"'~+?+~'"([{}])"'""+ (\@=.@=@@if@@f@i....}%ba%1;=... ;ab:9;ba:1-;i:0;f:0;(:;\{!}1*!0 ``` As before, the entire code is executed and **every single byte affects the output.** Prints `010` for convenient palindromes, `-100` otherwise. [Try it online!](http://golfscript.tryitonline.net/#code=MCEqMXshfVw7Oik7MDpmOzA6aTstMTphYjs5OmJhOy4uLj07MSVhYiV7Li4uLmlAZkBAZmlAQD1ALj1AXCkrIiInIihbe31dKSInfis_K34nIihbe31dKSInIiIrKFxAPS5APUBAaWZAQGZAaS4uLi59JWJhJTE7PS4uLjthYjo5O2JhOjEtO2k6MDtmOjA7KDo7XHshfTEqITA&input=MCEqMXshfVw7Oik7MDpmOzA6aTstMTphYjs5OmJhOwouLi49OzElYWIley4uLi5pQGZAQGZpQEA9QC49QFwpCisiIiciKFt7fV0pIid-Kz8rficiKFt7fV0pIiciIisKKFxAPS5APUBAaWZAQGZAaS4uLi59JWJhJTE7PS4uLgo7YWI6OTtiYToxLTtpOjA7ZjowOyg6O1x7IX0xKiEwOw) ### Tests and examples ``` $ base64 > palindrome.gs -d <<< LjQ6YWItMTpiYT07MSViYSV7Li4uZmlAQD1jNDMuPTspKCciKFt7fV0pIid+P34nIihbe31dKSInKSg7PS4zNGM9QEBpZi4uLn0lYWIlMTs9YWI6MS1iYTo0Lg== $ wc -c palindrome.gs 91 palindrome.gs $ rev palindrome.gs | tr '([{}])' ')]}{[(' | diff - palindrome.gs $ echo -n 'r(a[c{"e"}c]a)r' | golfscript palindrome.gs -3-1-1 $ echo -n 'totallynotapalindrome' | golfscript palindrome.gs -4-1-1 $ $ base64 > pal.gs -d <<< MCEqMXshfVw7Oik7MDpmOzA6aTstMTphYjs5OmJhOy4uLj07MSVhYiV7Li4uLmlAZkBAZmlAQD1ALj1AXCkrIiInIihbe31dKSInfis/K34nIihbe31dKSInIiIrKFxAPS5APUBAaWZAQGZAaS4uLi59JWJhJTE7PS4uLjthYjo5O2JhOjEtO2k6MDtmOjA7KDo7XHshfTEqITA= $ wc -c pal.gs 155 pal.gs $ rev pal.gs | tr '([{}])' ')]}{[(' | diff - pal.gs $ echo -n 'r(a[c{"e"}c]a)r' | golfscript pal.gs 010 $ echo -n 'totallynotapalindrome' | golfscript pal.gs -100 $ for i in {1..154}; do head -c $i pal.gs > tmp.gs; tail -c +$[i+2] pal.gs >> tmp.gs > [ "$(echo -n 'r(a[c{"e"}c]a)r' | golfscript tmp.gs 2> /dev/null)" = "010" ] && echo $i > done; rm tmp.gs 1 for i in {1..154}; do head -c $i pal.gs > tmp.gs; tail -c +$[i+2] pal.gs >> tmp.gs > [ "$(echo -n '42' | golfscript tmp.gs 2> /dev/null)" = "-100" ] && echo $i > done | grep '^1$'; rm tmp.gs ``` ### How it works ``` . # Duplicate the input string. 4:ab-1:ba # Save 4 in “ab” and -1 in “ba”. =; # Compare 4 to -1 and discard the result. 1% # Save every element from the input string in a new string. ab% # Reverse the input string. { # For each character in the input string: ... # Duplicate the character thrice. fi # Variable “fi” is undefined; this does nothing. @@= # Verify that the character is equal to itself; push 1. c43 # Variable “c43” is undefined; this does nothing. .=; # Verify that 1 is equal to itself and discard the result. )( # Increment and decrement the character. '"([{}])"'~ # Push that string and evaluate it. Result: '([{}])' ? # Retrieve the character's position in '([{}])'. -1 means not found. ~ # Negate the position.. Examples: -1 -> 0 0 -> -1 2 -> -3 '"([{}])"') # Push that string and pop its last element. Result: '"([{}])' 34 (; # Decrement 34 (the ASCII code of a double quote) and discard. = # Retrieve the corresponding character. .34 # Duplicate the character and push 34. c # Variable “c” is undefined; this does nothing. = # If the character is a double quote, the index was -1. @@if # In that case, replace the double quote with the original character. ... # Duplicate the new character thrice. }% # ab% # Save every fourth element in a new string to discard dummy values. 1; # Push 1 and discard. = # Push 1 if the modified string matches the original, 0 otherwise. ab:1- # Save 4 in “1” and subtract. ba:4. # Save -1 in “4” and duplicate. ``` ``` 0!* # Pop and push the input string. 1{!}\;:); # Make “)” an alias for “!”. 0:f;0:i; # Variables. -1:ab;9:ba; # Moar variables. ...=; # Duplicate the input string. 1%ab% # Reverse the copy. { # For each character in the input string: .... # Duplicate the character four times. i@ # Push 0 and rotate a string copy on top of it. f@@fi@@ # Push 0 and rotate 0 on top of it. =@ # Push 1 and rotate a string copy on top of it. .=@ # Push 1 and rotate 1 on top of it. \)+ # Negate a 1 and add. Result: 1 "" # Push that string. '"([{}])"' # Push that string. ~+ # Evaluate the second string and concatenate. Result: '([{}])' ? # Retrieve the characters position in '([{}])'. -1 means not found. +~ # Add 1 to the position and negate. Ex.: -1 -> -1 | 0 -> -2 | 1 -> -3 '"([{}])"' # Push that string. "" # Push that string. + # Concatenate. Result: '"([{}])"' (\ # Pop the first double quote and swap it with the rest of the string. @=. # Retrieve the corresponding character and duplicate it. @= # If the character is a double quote, the index was -1. @@if # In that case, replace the double quote with the original character. @@ # Rotate the modified character to the bottom. f@i.... # Push dummy values. }% # ba% # Save every ninth element in a new string to discard dummy values. 1; # Push 1 and discard. = # Push 1 if the modified string matches the original, 0 otherwise. ...; # Duplicate thrice and discard the last copy. ab:9;ba:1-; # Variables. i:0;f:0; # Moar variables. (:;\ # Negate, override “;” and swap. {!}1*!0 # Negate twice and push 0. ``` [Answer] ## J (60) ``` (|.-:'())([]][{}}{'&charsub) :: (busrahc&'}{{}][[])(()':-.|) ``` This is a function that takes an argument: ``` (|.-:'())([]][{}}{'&charsub) :: (busrahc&'}{{}][[])(()':-.|) 'ingirumimusnocte)etconsumimurigni' 0 (|.-:'())([]][{}}{'&charsub) :: (busrahc&'}{{}][[])(()':-.|) '(a)(bb)(a)' 1 ``` Explanation: * `f :: g` runs the function `f` over the input, and returns the result if it returns without error. If `f` fails, it runs `g` instead. * The `f` here is `(|.-:'())([]][{}}{'&charsub)`, which does the actual work: + `|.`: reverse + `-:`: is equal to + `'())([]][{}}{'&charsub`: replacing each bracket with its opposing bracket * The `g` function is `(busrahc&'}{{}][[])(()':-.|)`, which is nonsense but syntactically valid. `busrahc` is not defined, but that doesn't matter because it is only resolved when it is run (and it won't run). [Answer] ## Ruby, 110 ``` (z=gets;r=z.tr *["([{}])",")]}{[("];p *z==r.reverse;1)||(1;esrever.r==z* p;[")]}{[(","([{}])"]* rt.z=r;steg=z) ``` Prints `true` if the input is a convenient palindrome and `false` if it isn't. Note that this solution assumes that the input isn't terminated by a newline, so test it with `echo -n`: ``` echo -n '(a)(bb)(a)' | ruby convpal.rb true echo -n '(a)(bb()a(' | ruby convpal.rb false # note that for this to work, the file must not contain a newline # to remove a trailing newline, pipe it through tr -d $'\n' cat convpal.rb | ruby convpal.rb true ``` This is a somewhat straightforward port of [my answer](https://codegolf.stackexchange.com/a/1801/84) to [Palindromic Palindrome Checker](https://codegolf.stackexchange.com/questions/1798/palindromic-palindrome-checker) (and not really golfed so far). The main trick used is that the first parenthesised expression always returns `1`, so the second half of the boolean expression is never evaluated (but it is parsed). The only difficulty in adapting this was figuring out how to add the call to `z.tr` so that its "convenient reverse" would also be syntactically valid - but I could simply use the same trick I already used puts: `*`, which in the first half is parsed as splat operator (use array contents as function parameters) and as array multiplication (or repitition) operator in the second half. ## Ruby, 157 ~~297~~, all code executed ``` w=tsoh=gets p o=rt=esrever=Gem q=tsoh.tr *["([{}])",")]}{[("] q==esrever.host=w=tsoh.reverse==q [")]}{[(","([{}])"]* rt.host=q meG=reverse=tr=o p steg=host=w ``` This (slightly longer) version executes *all* code, and all but two lines affect the output, which is printed in the last line - but all lines are parsed and executed without any errors. This version interprets any trailing newline as part of the input, so use either `echo -n` to test it, or prepend your input with a newline. It prints `true` if the input is a convenient palindrome, and `false` otherwise. ### Explanation ``` # Read the input by calling gets(nil), which is achieved by passing the return # value of a call to Kernel#p (which returns nil if no argument is supplied) to # gets. w=tsoh=gets p # Assign the global Gem module to three variables. # The variable names are the reversed names of methods we have to call later. # This doesn't necessarily have to be the Gem module, any global module/variable # (or class that allows object creation through a call to the module itself, # e.g. Hash or GC) with a writable property would do, but Gem#host was # the shortest one I could find. This is necessary because Ruby doesn't # allow setting previously undefined properties through the dot syntax. o=rt=esrever=Gem # Replace the parentheses with the corresponding flipped one. # sserts is the reverse of the property name we're going to use later. q=tsoh.tr *["([{}])",")]}{[("] # Do the convinient palindrome check and assign its result to a few variables # and Gem's host property. q==esrever.host=w=tsoh.reverse==q # Here, the * is parsed as array join operator. [")]}{[(","([{}])"]* rt.host=q # Nothing special here. meG=reverse=tr=o # Print the result of the palindrome check, which was stored in w. p steg=host=w ``` [Answer] # GolfScript, 61 chars OK, here's a baseline solution in GolfScript. I'm sure it could be further improved: ``` {.-1%{"([{}])".2$?~@[.]@+=}%=}~{=%{=+@[.]@~?$2."([{}])"}%1-.} ``` As usual for GolfScript, this program reads its input from stdin. It outputs: ``` 1{=%{=+@[.]@~?$2."([{}])"}%1-.} ``` if the input is a convenient palindrome, as defined in the challenge above, and: ``` 0{=%{=+@[.]@~?$2."([{}])"}%1-.} ``` if it is not. **Explanation:** This program relies heavily on the ruling that *unexecuted* code is OK, as long as it gets parsed. It consists of two code blocks, delimited by curly braces (`{ }`), which are mirror images of each other. The first code block is executed by the `~` following it, and checks if the input is a convenient palindrome, outputting `1` if it is and `0` if it isn't. The second code block is *not* executed, and so simply remains on the stack until the program ends and everything on the stack gets automatically stringified and printed by the GolfScript interpreter. It should be noted that the GolfScript interpreter does *very* few syntax checks at parse time (or ever, for that matter); a GolfScript code block literal can contain almost anything, even if it might crash when executed. Still, a few syntax errors, such as unterminated string literals, do raise an error even in unexecuted code, so I believe this solution (barely) falls within the rules. **Ps.** Looking at the actual executed code, it contains a few conveniently palindromic elements like `@[.]@`, the string literal `"([{}])"`, and even the loop `%{ ... }%`. This offers the tantalizing suggestion that an "intrinsically palindromic" GolfScript solution, where the full palindromic program would be executed and functional, might actually be possible. As I haven't managed to produce one myself yet, I hereby offer a **+100 rep bounty** to the first person who manages to come up with one! [Answer] # JavaScript (ES6), 245 bytes I wanted a JS answer that could be run in the browser, so here it is. ``` eurt=>eurt==(("",eurt))["split"||"nioj"]("")["map"||"esrever"](x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x||[x]({')':'(','(':')',']':'[','[':']','}':'{','{':'}'})>=x)["reverse"||"pam"]("")["join"||"tilps"]((true,""))==true>=true ``` Removing all code that is never actually run, we get this: ``` eurt=>eurt==(("",eurt))["split"||"nioj"]("")["map"||"esrever"](x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x||[x]({')':'(','(':')',']':'[','[':']','}':'{','{':'}'})>=x)["reverse"||"pam"]("")["join"||"tilps"]((true,""))==true>=true eurt=>eurt==(("",eurt))["split" ]("")["map" ](x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x )["reverse" ]("")["join" ]((true,""))==true>=true ``` Which can be simplified to this: ``` eurt=>eurt==eurt.split("").map(x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x).reverse("").join("") ``` [Answer] # Javascript (ES6) 288 Runs in the [Spidermonkey command line shell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell). Reads a single line from STDIN and outputs `true` or `false` depending on if the input is a convenient palindrome. ``` ((print)((eval)('r=readline()')==([0]['map']['call'](r,x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x)['reverse']()['join']('')))&&((('')['nioj']()['esrever'](x||[x]({')':'(','(':')',']':'[','[':']','}':'{','{':'}'})>=x,r)['llac']['pam'][0])==('()enildaer=r')(lave))(tnirp)) ``` This code is syntactically valid, but everything after `&&` is not executed, as the `print` function returns a falsey value. You can run this code in Firefox's console by running this shim first to emulate the `readline` and `print` functions. Edit the input inside `readline` as needed: ``` readline = function(){ return "void main(int argc, *char[] argv) {} (vgra []rahc* ,cgra tni)niam diov"; }, print = console.log.bind(console); ``` And here's a quick example of the output: ![command line example](https://i.stack.imgur.com/1F55J.png) [Answer] # 05AB1E, 35 bytes ``` "{[()]}"DRr‡`rJ¹Q,Q¹Jr`‡rRD"{[()]}" ``` [Try it online!](http://05ab1e.tryitonline.net/#code=IntbKCldfSJEUnLigKFgckrCuVEsUcK5SnJg4oChclJEIntbKCldfSI&input=KGZkZCkoZGRmKQ) Explanation: ``` # Implicit input "{[()]}" # Push "{[()]}" onto the stack DR # Pushes a reversed copy onto the stack r # Reverse the order of the stack ‡ # Transliterate ` # Flatten array on stack r # Reverse order of stack J # Join stack ¹Q # Check equality with first input , # Print # Everything after is still syntactically correct, but just does not print anything. ``` [Answer] # CJam, 38 bytes ``` Q~"=re%W_@%W_q"`{[()]}`"q_W%@_W%er="~Q ``` Prints `"=re%W_@%W_q"1` if the input is conveniently palindromic and `"=re%W_@%W_q"0` otherwise. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Q~%22%3Dre%25W_%40%25W_q%22%60%7B%5B()%5D%7D%60%22q_W%25%40_W%25er%3D%22~Q&input=Q~%22%3Dre%25W_%40%25W_q%22%60%7B%5B()%5D%7D%60%22q_W%25%40_W%25er%3D%22~Q). ### How it works ``` Q~ e# Evaluate an empty string. "=re%W_@%W_q" e# Push that string. ` e# Inspect. Pushes "\"=re%W_@%W_q\"". {[()]} e# Push that block. ` e# Inspect. Pushes "{[()]}". " "~ e# Push and evaluate. q e# Read from STDIN. _W% e# Push a reversed copy. @ e# Rotate "{[()]}" on top of the stack. _W% e# Push a reversed copy. er e# Perform transliteration. = e# Compare to the input string. Q e# Push an empty string. ``` After executing the program, CJam automatically prints all three items on the stack: the inspected string, the Boolean from the string comparison and the empty string. [Answer] # Perl, 83 + 2 = 85 bytes Run with `-nl` ``` say$_~~reverse y-"({[]})"-")}][{("-r;exit;tixe;r-")}][{("-"({[]})"-y esrever~~_$yas ``` The code exits after printing the truthiness of the input. Everything after the semicolon is interpreted (and would crash when the script reaches that point were it not for the `exit` it encounters), but not executed. If I left `exit;tixe;` out of the code, it would still print the result correctly before it crashed. ]
[Question] [ > > The Arecibo message is a 1974 interstellar radio message carrying basic information about humanity and Earth sent to globular star cluster M13 in the hope that extraterrestrial intelligence might receive and decipher it... The message consisted of 1,679 binary digits, approximately 210 bytes... > > > The number 1,679 was chosen because it is a semiprime (the product of two prime numbers), to be arranged rectangularly as 73 rows by 23 columns. The alternative arrangement, 23 rows by 73 columns, produces an unintelligible set of characters (as do all other X/Y formats). > > > [![The Arecibo Message](https://i.stack.imgur.com/6CLcs.png)](https://i.stack.imgur.com/6CLcs.png) > > > *This is the message with color added to highlight its separate parts. The actual binary transmission carried no color information.* > > > [Source: Wikipedia](https://en.wikipedia.org/wiki/Arecibo_message) --- Your task is to output the Arecibo Message in the exact 23x73 arrangement shown in the image. Any of these output formats is acceptable: * Text, using one character for ones and another for zeros (using the usual rules for row separation) * A 2D array of two distinct values * A 23x73 image with two distinct colors * Aan uninterrupted stream of 1679 items of two distinct values (i.e. any of the above formats, but flat.) * A 1679-bit integer. Indicate bit and byte order (endianness) in your solution. For your convenience, here is a copy-pastable version (also an example output in text format): ``` 00000010101010000000000 00101000001010000000100 10001000100010010110010 10101010101010100100100 00000000000000000000000 00000000000011000000000 00000000001101000000000 00000000001101000000000 00000000010101000000000 00000000011111000000000 00000000000000000000000 11000011100011000011000 10000000000000110010000 11010001100011000011010 11111011111011111011111 00000000000000000000000 00010000000000000000010 00000000000000000000000 00001000000000000000001 11111000000000000011111 00000000000000000000000 11000011000011100011000 10000000100000000010000 11010000110001110011010 11111011111011111011111 00000000000000000000000 00010000001100000000010 00000000001100000000000 00001000001100000000001 11111000001100000011111 00000000001100000000000 00100000000100000000100 00010000001100000001000 00001100001100000010000 00000011000100001100000 00000000001100110000000 00000011000100001100000 00001100001100000010000 00010000001000000001000 00100000001100000000100 01000000001100000000100 01000000000100000001000 00100000001000000010000 00010000000000001100000 00001100000000110000000 00100011101011000000000 00100000001000000000000 00100000111110000000000 00100001011101001011011 00000010011100100111111 10111000011100000110111 00000000010100000111011 00100000010100000111111 00100000010100000110000 00100000110110000000000 00000000000000000000000 00111000001000000000000 00111010100010101010101 00111000000000101010100 00000000000000101000000 00000000111110000000000 00000011111111100000000 00001110000000111000000 00011000000000001100000 00110100000000010110000 01100110000000110011000 01000101000001010001000 01000100100010010001000 00000100010100010000000 00000100001000010000000 00000100000000010000000 00000001001010000000000 01111001111101001111000 ``` If your language, for some reason, has a builtin for the Arecibo Message, you may not use that builtin. Good Luck! UPDATE: I accepted the 05AB1E answer since it was the first one to be shorter than the original message. Don't let that dissuade you from new solutions. UPDATE 2019-09-09: Accepted answer moved to a new 05AB1E answer, as it obsoletes the previous 05AB1E answer. Same point goes as previous update; new solutions still welcome. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~215~~ ~~210~~ 200 bytes Saved 15 bytes thanks to *Magic Octopus Urn* ``` •cOž¤4é57ñΛ\Ö₃BαöĀíL½₅üBdoÙRθLγ¨G×Tćú$G(˜ƒ¦!€R»SDrµCnJ†d∊ζ·<8‡T@|‹ï=BζćósxG\ÙÎ$¿o₁5/ÔŸÇBûXé-”a::Ž]°∊y;ζ]MÜβ‘иL”β{üÃÇíäc€÷›ÎU=}¨иaŸdY`»¾ÚUβ:ô©¦β†₅DGŠβ3Jêθ,äá!ícqšVÖ›lÈΣ¯pε €êʃDpÙ/¬Žλ8:ãÿ3=€.Þć•3BY¾4×: ``` [Try it online!](https://tio.run/##FZDBSgJRGIVfJaFFi8qFRTIlxCQMiBFYRkJCpi2CyMpNUcFtIkZcuJCoLAtNiYykHGucnFT4j@MmuPQM90Wmaf1xzuE76Uxic3vLcQR7TC7ZPapNoT49gya/W8eVUM9l3oQxYGiEqSvUC3zLqTSKEW6GeYueFVyvDDR0RpWxn9KwQE8eob5GyFoOHtDnwm5IsHJKZHPcoPacX7DKyvyJYF94C8jccHOtzKGyjiLyo9RPC/Vs2otL24Qmw1pDfUKw@4Qk2d04vbslR7PciC@ixHXBbn7NsEu5foxvnENDA7WkO422YB3ko4FTev41E7aZim2QRT3cRrku4YPq9PSfL7sqQcUuc90Xwgs3x1FDxYNGct@urLrerLODLK/S2x7/HPnvfUFuWAjuoeilV7vLLb@EKvq@gMsm8TDQ3Pt8cox6U7iWHOcP "05AB1E – Try It Online") or with [Additional formatting](https://tio.run/##FZDPSgJRHIVfJcFFi0pIJZkSYhIEMQLTKEjItEUQabkpKrhNhNHChURm/9CSyFCsqabJSYXfcdwEF5/hvojd1h/nHL6TzibWNzeGQ8Eekgt2h6oe1LxTeOM3q7gU2onK32D0GBphagvtFD9qKo1ShJth/k7PQRSjvRxazuDo722/QE8OodUjZC0GdulzbjskWDklzs65QV8zPsEq0dlDwb7R9KvckLn37F5wFSXkndRNC@3Y68KFbSKnwlpGbVywu4Si2O04vcqS/WluxOdxy3XBrgZmWFKuH@AHJ8ihgWpSTuNLsBbyMf8RPQ/MhG2mVtbIog6uY1xX8EE1evrPl6VKIGiXue4O4YWbY6ii4kAjuWNXlqQ3a23hjD9SM8M/R/57X3DeLwQyKLmobre55VPwiK7bL9kE7ns5eZ9bXaGOB0VlOOmWS9bwDw) Base-255 encoded trinary string with occurrences of `0000` replaced by `2`. [Answer] # Java, ~~688 678 590 379~~ 361 bytes Returns a string. ``` n->new java.math.BigInteger("in95mzupnpa2r0khpoepyql6ioqyn413avucdtfay6indx4wh9dehe3sn18klobtf4z9g9q17umqmwpegr2khb5eqinn7azl4jpfp2a8eui0xfrx5qwrou6gd65jh4ge3ls14k5lu7qrvmg6942ms29u5rb8fa6yrdhfoh5zoi9bdi7uh5ig0u0ff9kounth8sh357x7qox4m3oqviqsbrvakonbka4ahp21bgzi5v1akzzuqoncszhpabbru9q1uo2g11zr73iuyiqr5ikr69zn7cdv7e1lhd6ese9",36).toString(3).replace("2","0000") ``` -10 bytes by returning the raw stream (old answer) -88 bytes by using base 10 numerics (thanks @ceilingcat!) -211 bytes (I knew it could be golfed!) by using a base-36 encoded BigInteger (thanks @JollyJoker!) -18 bytes by using a different encoded integer (thanks again @JollyJoker) [Try it online!](https://tio.run/##LVG7jqNAEIyPr0BEoLURb4x83mCDlS64aKVLThsMMC8zzHuwwfK3@8bydVJSqbqq1XUGC9gLCfl5nB4DA8aEvwHlt4ByCzUCAww/b19WU45DFP8RdAyX5HgPpOsZHUJjgfWwPPnZ78Uv6d9voLFJbsFniE4Pvn/n8BKefVQ6A0vSD4p/eXsMdRxR3tXz5iSXoNDZRKSAclWsoUKtvMpLsLhhtAisDeXjtbqQboQElobnh4mJ3qJq63Cn8tbNar5IiHUxkb6GinLego1VZ4lkAQ7Q0eyK9LVWFy1cg8emPpMKw5KZvJpq5lqllxk3XVXMpuhcrfsDAs2qR4IEqTdBu36krSM1xZnLEOom4bglB0PKur22SlyruRRqocr0egGT4P0EKkBkkfd4o/WSg2nbnBJ8MBuRoO@183c7UeA833RbUrdSpWs66abbeDuMSwtzRsYGGthFu7JJUite/43LJNVQMl9PHBXRLsr8RMnjGPyvajY4PIUoRTF3jCXHAAkd@0pD6uns6OHnU5MyyLElcbIvSk@@nYoyCW/Bj6/VWDinwtlUej/LePxUG9ebVz7d0Tev9cb34H5//AM) Explanation: ``` n->new java.math.BigInteger("base36 string",36) // Decode the base-36 integer. .toString(3) // Re-encode as ternary .replace("2","0000") // Replace 2 with "0000" // Implicit return ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 213 bytes ``` “H²ɓ¶Ṡḷ€ẹ]ƒf*ḳḢ&ƁṇOḥ{ḄṫwỊ+oLạʋߢH9¢¹÷ỴɗÇ⁶ƲƙæḊẋ3³=1!VƇƁ'D⁺3Ỵɱ©⁵%fȯez#ƈjƒżṆo.ZF⁶ċṢ⁶ọṛb9Ȯƒd?ƁUĠt4ẇ,ḞġƒµƭfʠƁP§÷øȤŻPɲẋ(¢ß¢(⁽3¶ṙėɗy@ṁYȮL~e⁷ƤĊ§nỊṅµṠ°@7ẠB>Ġ⁻İ}uy¡½:esOpḢt}qS©HÞṬĖṛṇḣ9÷;ESḢ,Ẉ^ṙpƲ©tṃwçnẒṆ¡⁻Jıƒị£-&Ɱ*ẋʂżoȯÑḢɼ’ ``` [Try it online!](https://tio.run/##FZBbSwJBFMc/S0QXukEYhEUXokIiKJCCgnqI9CEii4ywKJpuhtJDGyRS1LrdkMrSsp3ZtZcz47DrtzjzRWx8Og/n/C@/sxZZX0/U6@roLgQl/xp@kZlIbXX8jg5bkka0A@k3UqtVEmTJGaTP@0hPkb3topvqjE2jk6ul@QNYoSBYwLiN7o@f4UlFfmVJZvkL0hQ66QB8D/U2zcukJG3jijiBxlkR8oqUW6LeZ2SvWV6sSaNaQXYe61mc1HKRRmbpie4lstuVoFeQxuqIJHPCjPehk@xCei9y0oCy/IjWTElm4ZXbnHpPVXfWL@nQdrAazdoV@Qs0wLIi42cSo8jIgleYPowoYssnkYLXDc2C7AzKGh6@RvvRMceGhamIK74OdhKQg7@ByPbMpv5D/GArDPkQv0f2Lm50Mf0VpI9Bbg9OhPW@C52LZR21KUuQjyM72eXa3jE0F@S04ZQoSgPdNDx2t6pioUPXrB1XKzHvk19puV9RR9l6/R8 "Jelly – Try It Online") I played around with Huffman coding, but the improvements in data size were outweighed by the extra code. As such, this is simply a base-250 encoded version of the desired output. Output consists of an integer that when decoded as bijective base 2 will yield the 1D list of 1s and 2s. Thanks @Emigna for pointing out the change in rules. [Try it online - with further decoding to demonstrate output!](https://tio.run/##FZBbSwJBFMc/S0QXukEZhEUXokIiKIiCgnqI9CEii4ywKJpuhtJDGyRS1LrdkMrSsp3ZtZcz47DrtzjzRWx8Og/n/C@/sxZeX4/XauroLgRF/xp@kZlIbXX8jg5bkkakDek3UqtZEmSJaaTP@0hPkb3toptsj06hk62m@ANYoSBYwLiN7o@f5glFfmVRZvgL0iQ6qQB8D3Y3zMuEJC1jijiB@lkBcoqUmiLeZ3ivUV6sSaNSRnYe7Vqc0HKRQmbpie4lstuVoJeXxuqwJHPCjPWik@hAei@y0oCS/IhUTUlm4JXbnHpPFXfGL@rQVrDqzVoV@QvUwTIi7afjI8jIgpefOgwrYssnkYTXDc2C7AxKGh6@RvrQMUeHhKmIK74OduKQhb/@8Pb0pv5D7GBrFnIhfo/sXdzoYvorSB@D3B4Yn9X7DnQulnXUpixCLobsZJdre8fQXJDVhpOiIA10U/DY2awK@TZds3pcKUe9T36l5X5ZHWVqYCE96dnuCSzU/gE "Jelly – Try It Online") If a more conventional binary encoding is preferred, [here is one](https://tio.run/##FZDJSgNBFEV/RcEpDgsVERcOGxEkqAvFEcSICBp1IXEiiK2NiUYXdkASFZNgNMR5SqzqkhaqOoXkL27/SHxu69W957y3tBAMblcq3t7VgMyqlLyBHatx33Z3PeNbff1mYUfVHeyITz/6wR9UBHZcWw3ytUElAuX9TbBTz/hU5ko53bOyWqtSlKtq9fYfIbJgHzIXBr/3DDEo88oJjKkzz3A8oyALYKl5P2yrV8d99EXmJkI64v70aSJEu8HTRAvIPJWDP@k4mCmLOxCFtaEQ@CUBqIVyc0u/L61U459SEcLIm5KgiHteisM@Igf53rjRPjACbgYhTre0VY7JV/2kHJoNz5BMWOb/YTYRDpRT3abMehKg/ib3h/hto26MBMATRKVlw40Qn26apGfpKqXv8PJi8zJ4pmR1gDvgF@BJnZDPk2C3RCwokx4gjj2D9XfJIlXVaauucx0i1iIzRAqAXev3vvEQ7AxYdhrihGZgJ@CHYEWVAz@gM@wlK5U/ "Jelly – Try It Online") that encodes an integer representation of the inverted binary message. The most significant bit of the integer represents the beginning of the message. [Answer] # Brainfuck, ~~2360~~ ~~2008~~ ~~1938~~ 1902 bytes ``` -[>+<-----]>---......+.-.+.-.+.-.+.-............>++[-<+.-.+.-.....>]<..+.-.>++[-<.+.-...+.-..>]<+.-.+..-..>+++[-<+.-.+.-.+.-.>]<.+.-..+.-.>+++[-<............>]<+..-..................>++[-<.+..-.+.-..................>]<+.-.+.-.+.-..................+.....-..>+++[-<..........>]<+..-....+...-...+..-....+..-...+.-.............+..-..+.-....+..-.+.-...+..-...+..-....+..-.+.-.>++[-<+.....-.+.....-.>]++[-<............>]<.+.-......>++[-<...........+.-.................>]<+......-.............+.....-.>++[-<...........>]<+..-....+..-....+...-...+..-...>++[-<+.-.......>]<..>++[-<+.-....+..-.>]<..+...-..+..-.+.-.>++[-<+.....-.+.....-.>]++[-<............>]<.+.-......+..-.........+.-...........+..-...............+.-.....+..-..........+......-.....+..-......+.....-..........+..-..........>+++[-<...+.-.....>]<+.-......+..>++[-<-.......+.>]<.-....+..-......+.-..........+..-...+.-....+..-...............+..-..+..-.............+..-...+.-....+..-.........+..-....+..-..>++[-<....+.-...>]++[-<...+.-.....>]<+.-.......>++[-<+..-........+.-...+.-........>]<.+.-.......+.-.....>++++[-<+.-.......>]++[-<.....+..-....>]<....+..-.........+.-...+...-.+.-.+..-...........>++[-<+.-.......>]<.......+.-.....+.....-............+.-....+.-.+...-.+.-..+.-.+..-.+..-......+.-..+...-..+.-..+.......-.+...-....+...-.....+..-.+...-.........+.-.+.-.....+...-.+..-..+.-......+.-.+.-.....+......-..+.-......+.-.+.-.....+..-......+.-.....+..-.+..-..>+++[-<...........>]<+...-.....+.-..............+...-.+.-.+.-...>++[-<+.-.+.-.+.-.>]<.+...-.........+.-.+.-.+.-.+.-................+.-.+.-..............+.....-................+.........-..........>++[-<..+...-.....>]++[-<....+..-.......>]<+..-.+.-.........+.-.+..-..>++[-<...+..-..+..-....>]<+.-.>++[-<..+.-.+.-...>]<+.-....>+++[-<+.-...+.-..>]<......>++[-<+.-...+.-.>]<...........+.-....+.-.>++[-<...+.-.........>]<+.-..............+.-..+.-.+.-...........+....-..+.....-.+.-..+....-... ``` [Try it online!](https://tio.run/##pVVJagNBDHyQkF4w9EfMHGJDIARyCOT9E/eirVXOJQ0eM621pJLm/v328fX@8/i8Lr41Orifsz0fMg4Jp184jejGRxS085gWU7Tux/MpmprjhZLpsDiX@jIf9jFYt8/xYxbTMUGF83gBQBH241nBmDRVJLwbtOyL7TakRMDa66QZ6H87EXwP1nYxwjWTX9AA3OIko0WoveGeVL4kWa1U038iTS3PKAEbVCGLUhVcRHttspWTIZA75jUBsRn3vHkPUd3TrlS4AykF7XK7vKFT12uLEHhDOJcvJJ1a4V6ICg@8i@pwkAA2kERsHBNWSK@9sTufrS4cHLv3rRnGSjZemGHgu/F2zz4mwnnaq4L8KWbAWcJ7SGeZ8bDHgnLZy75cEZgXWxFeg@oHqLKPz4DgUQNJQt916VDJLVE6z8bisccw5EbwFjmqH6BKMy0O5FPb56fMkCRqcd1Q4kTjwLqudV2/ "brainfuck – Try It Online") My idea was to first generate a simple solution consisting of setting up an ASCII 0 followed only by `+-.` instructions to produce the output. Repeating sections can then be shortened using loops. Choosing the optimal set of non-overlapping sections for looping basically comes down to solving a [maximum-weight independent set problem](https://en.wikipedia.org/wiki/Independent_set_(graph_theory)#Finding_independent_sets). Currently, I just use a greedy algorithm which takes the section that can be optimized the most and then removes all conflicting sections. This is then repeated until no sections are left. Using a more sophisticated algorithm one can surely achieve better results. [Answer] # [Piet](http://www.dangermouse.net/esoteric/piet.html), 1763 codels Outputs a stream of 0s and 1s (no line breaks). Codel size 1: [![Arecibo message program with codel size 1](https://i.stack.imgur.com/264uA.png)](https://i.stack.imgur.com/264uA.png) Codel size 4, for easier viewing: [![Arecibo message program with codel size 4](https://i.stack.imgur.com/tcyuc.png)](https://i.stack.imgur.com/tcyuc.png) ## Explanation * First, push a sentinel value of -1 onto the stack. * Then push the Arecibo message, in reverse order (because it's a stack), using run-length encoding. * Finally, alternate between two loops, one printing zeroes and the other printing ones. + The loop counter is the current stack value, decremented until it hits zero, at which point it is discarded and we switch to the other loop. + Between the zeroes-loop and the ones-loop, check for the sentinel value, exiting if it is found. ## Notes The program follows a spiral path, clockwise from top left into the centre. The scattered black blocks that roughly follow the diagonals are the flow control. Here's the [trace from NPiet](https://i.stack.imgur.com/Nw8bk.png). I've been working on this since the day this challenge went up, but it took a little bit of time to get the message "written" into the picture! I wrote the final loops and the sentinel value first, and then built up the message from the centre outwards. (Since Piet always starts execution from the top left, I expected to have to shuffle and rotate the image around to avoid excess whitespace, but it fit perfectly!) Fun fact: Run-length encoding in Piet doesn't (by itself) save any space. It takes *n* codels of one colour to push the value *n* onto the stack, or *n* codels of different colours to push that many 1s onto the stack. So it's the same number of codels either way. But the bigger numbers that RLE gives you mean you can use arithmetic tricks (e.g. instead of pushing 9, you can push 3, duplicate, and multiply) to reduce the number of codels, and funny-shaped blocks to fill in available whitespace. I wasn't sure about how to count score for Piet entries. I found some that seem to count *all* codels, and others that explicitly only count those actively used. I just counted them all; ignoring white codels (even those that the program never moves through) seems akin to ignoring whitespace in a more typical programming language. Oh, and I've just now (two hours after posting) realised that I wasted the last bit of time working on this. I wanted to trim off the almost-completely-white last row and column, so I shuffled things around... including the black flow-control blocks. But the edges of the image work the same as black! If I'd just remembered that, I wouldn't have needed to spend so much time puzzling over the intricacies of DPs and CCs... [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~366~~ ~~332~~ ~~329~~ 319 bytes ``` int i;foreach(var g in"*ЀʂЄ࢈ҲપԤ␀␀␀؀ȀȀȀ؀␀␀సؘࠀƐഘؚ྾ߟ␀␀Ā␀␀ྀ␀␀రܘࠈഌΚ྾ߟ␀␀ă␀ྃ␀ȁăÃ1`ƀ1`ÃĂȃЃЁȂĀ`ÀƀȺ؀Ȃ␀ȏЀȗɛ'Ŀஇ7;ȅ?ȅ0ȍЀ␀␀΂␀ΨՕ΀Ŕ␀ŀЀ?܀àǀƀ`̀°٠Ƙѐʈш҈EB@Ѐޟɸ")Write(Convert.ToString(g,2).PadLeft(12-i++%2,'0')); ``` Replace all instances of `␀` with `\0` to test. [Try it online!](https://tio.run/##Sy7WTS7O/P8/M69EIdM6Lb8oNTE5Q6MssUghXSEzT0nrQsOppgstDxZ1XNr0YNWqK0tiDEDwRgPzCRBiPdHAfqMBJPJgw44bMx4saDg24cGWGTdmPdi37/58kPiRBiYQdaiB8cG@BnmIyg13gCo7BB5s6TmHpLCZiRmorhmorlkeyDrRyHKkmeNws4BhAvOxBsMEIOtIE8eJZpYLQNTIcaJJ4EhDwuGGYw0ndt1oONEE1NB/oeHE9JOz1Y/sf7Cu3ZzV@kSr/YlWgxO9F8AOPAdUcm7F1annGo5OiTE42sB/ocH@TsPhBceBRiScbTi04eaCYzMuTjjVcbHjUofroQanQw0OhxqELjTcm39yh5JmeFFmSaqGc35eWWpRiV5IfnBJUWZeuka6jpGmXkBiik9qWomGoZFupra2qpGOuoG6pqb1//8A "C# (Visual C# Interactive Compiler) – Try It Online") # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 305 bytes, 210 chars ``` _=>"*ЀʂЄ࢈ҲપԤ␀␀␀؀ȀȀȀ؀␀␀సؘࠀƐഘؚ྾ߟ␀␀Ā␀␀ྀ␀␀రܘࠈഌΚ྾ߟ␀␀ă␀ྃ␀ȁăÃ1`ƀ1`ÃĂȃЃЁȂĀ`ÀƀȺ؀Ȃ␀ȏЀȗɛ'Ŀஇ7;ȅ?ȅ0ȍЀ␀␀΂␀ΨՕ΀Ŕ␀ŀЀ?܀àǀƀ`̀°٠Ƙѐʈш҈EB@Ѐޟɸ".Select((g,i)=>Convert.ToString(g,2).PadLeft(12-i%2,'0')) ``` Same with above, replace with `␀` with `\0` to test. Output as `IEnumerable<string>`. [Try it online!(Courtesy of Jo King)](https://tio.run/##Sy7WTS7O/O9Wmpdsk5@UlZpcouPpmleam1qUmJSTalNcUpSZl25nl2b7P97WTknrQsOppgstDxZ1XNr0YNWqK0sYGBhuNDCfACHWEw3sNxoYGB5s2HFjxoMFDccmPNgy48asB/v23Z/PwHCkgYmB4VAD44N9DfIgNRvuANV0CDzY0nMOrqSZiZnhUDNQSbM8M8OJRpYjzRyHmwUME5iPNRgmAFlHmjhONLNcAKJGjhNNAkcaEg43HGs4setGw4kmhhP9FxpOTD85W/3I/gfr2s1ZrU@02p9oNTjRewHopnNNDOdWXJ16ruHoFIajDfwXGuzvNBxecByoO@Fsw6ENNxccm3FxwqmOix2XOlwPNTgdanA41CB0oeHe/JM7lPSCU3OAwaKhka6TqWlr55yfV5ZaVKIXkh8MDhugsJGmXkBiik9qWomGoZFupra2qpGOuoG6puZ/a660/CKNzLwShUxbA@tMG3NTa6C0JpdCeFFmSapPZl6qBiSE9YDGJieWaKRpGGpq6gWXJkGENTK1jIx1jIw1Na3/AwA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 182 bytes ``` •sv¯ö¨₁ÿ.ÛïžôΔ¨γ_Ígv…=Bм„Ð.(ܦi´…ε±G½0^/₃öRÛž¼¤"āêL!ˆ6‘Gā܇ðв₁÷Ã7€₂䬂Cć¨g¾†@÷[_-68¯a∍iG*6ÆîÆ;>éjζãÎÂ+ºžnî¼ć'(ÝÞΔ‹∞ÉݹÕ5λ₆*a|§oÄmôæ¨;—:hž¥ð¢ocË'¨%¡4Ćáß©ìća;FÁ?iˆèεƒʒ•Ž6–FD4‰`3ÊD?i- ``` [Try it online!](https://tio.run/##FZDNSgJhGIWvpSAUQwsyi6SMEt20ahtkU4RNUC4EVy0@xxijMMIMIn9KKxtD1MofLJ3gPWOLhMFreG/EpuU5m@c5JxKVduX98ZhFKRqjOtqksRLHtwtZ1Ac6mmaGNPMjhFQ4xqK8vDbqsSjgymVHjsoyNa3SbNFbkPqz2zOsJNDeRHagU4@eJo04XjcmhqqHxW3QCjkWRTRG7/@EDhILrFRZUcwmVVncrRtJ0sKks3hYRWcr5PQsUl3is5QcdHigogbVu4LKodnGIy6hTNPnQD9GjXpG0mZHHgUzw6LLZwUkWDSQpy5u5s0vVlSHdEIvEZweoYkyaV4oLDJLB5blMxpUiuzhwkbaFBXdhooi7qmCqpGUvAHEffJQhWa2ftK/aeujQd/ach3wuy3CzhzO/T7ZOR7/AQ "05AB1E – Try It Online") (uses `1` for 0 and `0` for 1, as allowed by the question). [Try it online!](https://tio.run/##FZDPSgJxGEWfpSAUS4ssjaSMEt20ahtkFmETlAvBVYufY4xSGCEGkX9KKxtD1GpULDP47tgiYfAZvhexaXnu5lxOJBrakw7GYxblaIwaaJPKchzfDuTQGPShGVlSjfcg0uEYi8rK@qjHoogrhxV5qkikmaPRotcAfc3tzLKcQHsLuUGfevQ4qcfxsjkxVFwsbgIm5FmU0By9/Rs6SLhZrrEsGxrVWNxu6ElSw9Rncb@GznbQ7lqiRohTaSlgc0FBHYpnFdUjo40HXEKepo9B/wR16ulJixUFFI0siy6nikiwaKJAXVwvGp8sK7bQKT1HcHYMDRVSPZBZZJcPzZdPaFI5so8LC6lTVFrQFZRwR1XU9GTI40fcKw0VqEbrJ/ObMRu5nX60Zuadft@C6dh14twX9Er28fgP) (5 bytes longer, `0` for 0 and `1` for 1, added newlines for readability). Most of the code is a base-255 integer constant N, the rest is an [Asymmetric Numeral System](https://en.wikipedia.org/wiki/Asymmetric_numeral_systems) decoder, using hardcoded probabilities of 75% / 25% (the actual frequency of 0 is 76.35%, which is so close to 75% that it would only save 1.2 bits in the payload, while the nice and round 75% lets us save several bytes in the decoder). ``` Ž6–F # repeat the following 1679 times: D # duplicate N 4‰` # divmod 4: pushes N / 4, N % 4 on the stack 3Ê # is N % 4 != 3 ? (boolean 1 or 0) D? # print a copy i- # if it's 1, subtract: N = N - (N / 4) # (otherwise, N = N / 4, since that's the top of the stack) ``` Here's the ANS encoder that generated the constant: [Try it online!](https://tio.run/##pZQ9bsJAEIWPEymRkD/BCXKE9BQgUVBRICGlQ5HScoi0HAB634SLOAh2vPNnx1LW/8@zO@/tvp3dfrXebrquPX0cFq@f2/lbe563l@Xt6/v95Xb8mbXXrmsejXKoJp8V5nHq6/6P2rkeEvp3gxycDgfiEgxMy/4MlPfGU0fElPw2mpIp3oezTkDGw2OCsZRKmdZKGF@rFJn8UyWkQkJPAqxUQqrSz8HAi2dCMi@GXZ2eSJOYNovOx2aMn@puTDgAu0FJUeeeQDBZIcpyJxNLvmTOBpRdCX2JUPNA2U7Qu6j68uk1Q6hPUvehgUlh5ymYVIpIVSIVxlY4xzIpQiRDRSZIy7i4POkOMmWx12qMWj8IlV3B7qFNF8oi9tbkxcT8wFUAxAbihzv6Cw "05AB1E – Try It Online") ``` Î # start from N = 0 Rv ] # for each bit in the reversed input: 4* # N *= 4 yi # if the bit is 1: 3+ # N += 3 ë # else: 3÷ # N /= 3 (integer division) ₅B'•.ø # compress N as base-255 ``` [Answer] # [[Python 2]](https://docs.python.org/2/), 345 bytes ``` s='' for c in")pG/K(K*j$h%kk$ppjGE&I6S6S5[5eCv~vw0x&z$wgqcde$e=G4G?G4eG0e:vv~w*G,gn$wy$uuuuG=G)I,G.I2G(I-eG(I)e-I0G+G+G(G)I*G*vI)G-w'I2y0w'I,vI)G*G)G+G(G*I+W+I+W,G*G(G*G*G*G/I,I+I,iq.G*G1G(e/g$c%sG)m%md~$M(},K(cO)K(eO)K(I)G(aE$M(G1c$hpoI,pG3K1e3eU/M*M,I.I*S,Q(y*y'hG(ng&j$j$G+hW/g'G/G,G1k.d$e$mN":c=ord(c)-35;s+=[bin(c-35)[2:],'0'*c][c<35] print s ``` I encoded the length of strings of 0s as a byte starting at chr(31). Then I encoded the remaining 10101 as binary numbers starting at chr(70) up to chr(126). Binary strings that didn't fit were split up into smaller chunks. Edit: Reduced to 326 bytes. Thanks Jo King Edit: Fixed a bug in the code generator program Edit: Final Edit [Answer] # [Perl 6](http://perl6.org/), 368 bytes ``` .say for :36('FJXOE0PDDNF5Y5EHGB8M9SWMXQOXIKIT9F6ZKWWDEACHCBGXL1N2H60CN0CJ4EMKF7D6MODSKYJVNR4SFTDR6NSM421LQ67B6MWF0G5BQATFOJJJBQ0UFQM64T0MWSQN41C4S5D1QR5KJM2L9UTYMMKUBBQWY45YCMRGO8ZRGTQH7LXMZBUASLCTKX30IH0AYKYEPHO8HFHX8GAY5WM38YOSUX0HABYSH2PPBLRDRZIN5ANAQ3V8PLOZ6EHC0UI95EVJVYD1820T6J14HGX85NWFQET2NWOMSNUT0JW4LHMY90X094TEE9KXJXSNN6YPERFQW').base(2).substr(1).comb(23) ``` [Try it online!](https://tio.run/##BcGxcoMgAADQX8mWuORQgWg3ERBBQAQDuCW9dGovvaQd@vXpe9@3xyd@vY7Py9/u4/7YvdX4sOcyWQZmSg1HGTExkEa3PurkbBrVGFqONxUjZV0vejKkqTSVwKA3oJeQacVPFGtLvcrybBboeaALNl7DqpwcPhGsIwcDIq4L3EopiQMrdxrDAHT0zsCyhx7R0i1ISV1N7Rqy1molxMUMUe71MthmW4bgxGlKeiNr56c@qFSDUYAuq8xmYRvBRWqGLqOo6yZbvyYgOpK9qOaZTAtdttGgznSuPjfzZDfMRA/WsUXsLM@Zlk0FApYlFENqkIncsVCZaLU3awAywkno3IIEWhgYa1WSyRuD88wW7uK@OF4vz9uhKo7P3@vz53Eoi@P7/et6qOri9foH "Perl 6 – Try It Online") The long string is the message as a single base-36 number (with a single prefixed 1 bit to preserve the leading zeroes) which is then converted back to binary and printed 23 bits at a time. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 383 bytes ``` StringPartition[Uncompress@"1:eJylVNsRwjAM44s92KBaBTZgAUZhZXqtHUuOWrgjfSRRHFlO4tyer/vjfb1clq0gHirZLRjby986hppcT5p+L3BmgJ3t4Ul4GsNyG++7YbaXLh0ZTPhXa4Sn+X/s9Qfk3Hx2cOaSIuNYaVu5laschvgzSqAjHeZBhilKgKBDEhw0upJRg+HOK4MyNC29sfbc3RV0VPDqeLiRTsG1ulExq1IitpunOa7asnYM9siDZ6eidUCkEzBOUbCkGIig4aTyUGBYWAX6W6aXIWGGI/HlhmsqzSU0QTZjkMVpaX5sBsm1OGKVg1qdjKP0EdyqZBRLhukn8DLBQav6kccgz8OKfgBzjj6Z",23] ``` [Try it online!](https://tio.run/##DdDbbqJAAADQXzF9ZRNBkEqTJnXUBQQFuYmz2YcBYS5cCsxgCz9vez7hNEiQokGC5uhZLt4Xz1AMtMU@GgQV9LP9F7f5Z9MNBecfL8pbcZzq5MyDL7Y9aRo3Vg5AIIJ4G0MC015Y8ehdB8zKMAisv7WniakYlg9WZkpe9zK26ADdgGWTsdFJ1@XRupNcFTT4qAotrjWTnydTkl5vGUpdIsPIJynSwlZKl9y4lJVqfa9yD4X2eL6hZFzXiOfkgeew3zKrgIDQ2sEO2B/Ilzx2xwBLludop@m8Wxm8zHI1SOTE3/eFS4OIm8pYH757xaaiG1sPvSLe3k4Gp3uoF/Qe76rDDLw421WmTbGGoik2we26TfWrjlL7apr20qpJw/s5jOVLBFl1SjqUrjngjeKZToKV/s4cXz7cpx6CwCVj1W72Lrigh17lOZ43nlNiMDOmw5c/K/X/0//tF4vlR/n8AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Node.js](https://nodejs.org), 333 bytes Returns a binary string of 1,679 characters. ``` _=>Buffer(")SI)=.);1K?>>>2333A3,93/I3>3)g33)AEAAI)5JQZJTddda3)*3*33+3,e)*e3)//0/1+)1C/7Cgggg3395)9)A3IY)h*IH),39+)995*)AA-)59Y)*O3Z,)//*)91**)A*-)Y+1)I11+)I1)/)5)Y*0?)+)I)-0Y)1@;_*7<gaE/a)Q7[*9HM+IY16I33)a1)*^.><I+S3.38I)*hY)7)a)Y)A,9*A5Y/A:9=9K:1I-=9)19I)9*329)GH<").map(x=>s+=(x-51&&x-41).toString(2).padStart(x-51?6:12,0),s='')&&s ``` [Try it online!](https://tio.run/##HU5db9owFP0riEmQ4yQ2zl1gpjjMRdVw0TRV7MXttsoiIVCxBCXphFT1t7Ns5@183HvOi//j211zPHdxVefFda@vzzq7fd3viyYYYmuhOW7kZpllWUJEhiJFwlJGKIlg7oyxSO8fHu@/53nuCYwYUUhRAVYQhJgIGUKuxGxV9iBSKRQMWYcDs2tEpEIolTIYEyNVDuwbPUb9IYOSrJdZDBdKWNn/sRICKRybLNEzxBMH@fnmmc0Wpb8THg@zJ6bWX0Pr5NT2@7wE@8WzhQ23xOmTBTs4zODhYCLFTOqEmSutNnNpY60glYVilCh8WS@G4L/9ObjorA11cIlTORpd4o8SvKu3XXOsyiABP/t82/mm@x9YTucyiSaIWj0eYzRqr7u6autTwU91GewD8KY4n/yuCAQXZTSoBjobDPmH4VP1819btzv0zltC76IEf6mPVTD@UY2B618 "JavaScript (Node.js) – Try It Online") (with formatted output) --- # JavaScript (ES8), 413 bytes Returns a binary string of 1,679 characters. ``` _=>atob('AsKoAFBQEiIlwpVVUk!!ABwo!DQ!Gg!V!Aw7g!!GHGHCi!yGjHChsK+w7vDr8K!!Q!Q!!g!/DgAHDs!AGGHDhiAgCGhjwprDu8Ovwr4!ABAw4AQAcK!MKDAD8GB8OAD!QCAQQMBAYYEAMQwABwpgAMQwBwoYEBAgEEBgEQDAIwoAgIMKAwoDCgMKABgDDgDAEdcKACAgAEHwAIXTCtgTDpMO+w6HDgcK4AsKDwrIFB8OkCgwINg!!A4IAB1FVTDoArCo!U!/CgAB/w4ADwoDDoAwAYDQBYMOMBmEUFEIkSMKARR!woQgAQB!MKUAHnDtA'.split`!`.join`AA`).replace(/[\s\S]/g,c=>c.charCodeAt().toString(2).padStart(8,0)) ``` [Try it online!](https://tio.run/##TZFda9swFIbv@yus7sI2yeStC21gJHBkObYxXlDzwUJTFtdxTpwPy8hqxBj77Zmyq6KLc5DgfZ4XHYpL0ZWqbvXnRm6r6250/TUaF1q@eS50mYQJE1Gdnky7XC6OhAAzknBBYiRLAuYJCYmTOAlr8js@JOG@y3rm6cLVMCNE2EOQBBwh4R2BOE74vgYM4/3BtIq/D6cXowY2E8wABJQZyTMOfBiz4RQ4ESEIkTNYrSLIhbHoFm@LVVhFDDCKGEaCQ2okYJpnYCQP0U6GnCOHaFtmEAJClBhIf85DjXPe5tOeeUw4ltnAFuRGpROLO4Zo0h@2DQxSYF8nyzmXoEJJFiQIEVhgDbnNt7cGVlywVT7N2TlaTKL0OLPM52dipEAQzJZYQNJwDS7t2lOtN2RDD7JuNgAbn6qqPRVl5QUv6249ew2wX47GJS33hcVtK9CeT7WcaVU36D34tC22M10o7Q37X3z/evsaZ@R0zmjssPfdrlJ0p@TZ65ye47p9x30ruupx4H4I8b/f3ZWy6eSpoieJ3s77YEGtgNPc0u7pp/uX5tWn50KXe/vy5@Hb3wD9/@6eu25ci/8H "JavaScript (Node.js) – Try It Online") (with formatted output) [Answer] # Bubblegum, ~~275~~ 236 bytes ``` 00000000: e006 8e00 e45d 0018 6988 6507 a228 f86f .....]..i.e..(.o 00000010: f042 c62f d4d7 b99e 38bc 56c4 52e8 2630 .B./....8.V.R.&0 00000020: 8aaa 7252 d47d 5ef4 c96a 511f 6842 423f ..rR.}^..jQ.hBB? 00000030: 4532 ca9f 22d3 1633 e0c4 665a d5dc 4e68 E2.."..3..fZ..Nh 00000040: 7b09 76ae 3c7e f9d4 fa4a 05e0 4163 c580 {.v.<~...J..Ac.. 00000050: c585 a383 2396 4ca9 1f48 a4b9 744e 37c8 ....#.L..H..tN7. 00000060: 68c5 af23 645d 59a7 542a e6d1 23b9 3aba h..#d]Y.T*..#.:. 00000070: f0e6 2738 dfd5 b0a3 c6a3 60bf c5b6 5ae6 ..'8......`...Z. 00000080: 7893 30a8 ae04 edf9 298b b777 4d56 285b x.0.....)..wMV([ 00000090: cb74 07cc 7a7b a399 3dc7 c6e7 b693 e715 .t..z{..=....... 000000a0: d908 876e 001f 7408 3c6a 5fcd 37cb 02c4 ...n..t.<j_.7... 000000b0: 93de 33c2 a11e 5bac cd12 d99a fac3 e0fa ..3...[......... 000000c0: 5268 94f7 d640 0f73 cede f79d 821f 39d1 [[email protected]](/cdn-cgi/l/email-protection). 000000d0: dc49 ff06 6962 6c31 dc29 a077 01c3 7690 .I..ibl1.).w..v. 000000e0: 85ef bbec 31d7 5c7f f9fc 8c00 ....1.\..... ``` [Try it online!](https://tio.run/##VZNbaxVBEITf/RWFgreHdnbuEyJqQFDRgEECGqPO1Ri8gCZGDPrXY83JOagDO7DL8nV1dXU5LeVjf3/66eJCrc8WulIekTe6dQ1KLRE@RV5OBWStI0b0A5B5DkU@SBe5KV@uXBIWMoayGtXrgWZbQEmpw8RS4Xy1cLpHaG8UGTtyZ2Ki7MueXFdrhiYj5pwRtNNkhAbXh0VNPsMty4CPrGC1Wen4uie/3ogcP5ejnZ17a4YhwzpDHTkNaN0MFm8M@6ME711Gc63Cdh@Bh1rkqogRGa9Edo/WDEtGKCoh@MwOaugYqVmMbDOU6wqWTFQX2cu5fJft32zmiciDKrJmODL4g0M20UCb5GEpCcuwEdkWwq0lPNR46ek1eSrySORkN2wYngwfKxlDG/g5F5dygLM6o/u2kEuQySUDR0S0w5fy4vZkbW0YYTWX7qGDiWijORSVKd7z8qoMqiweLvMX6rgRV/OVd3xebRhx@hGTgVGZ4ruy6G0k6BQLSggBtjlWiK4AP0StCLdEzp7t3zxYM9L0owQLFWpFyKHQmUTxrQaK6YyLZ4UeFkcdJyI/z0XuXorZ6MhktKQiYvB9RnTQRL6aOvMxapt2FijNUU9PP9NN2T5@K@Evo5CRTKPzpmrkZelwJVfUtjByKWVOuc64jDwZjIYciPyvo5LhNAOU7Aho3iqoEehpJ3eE1BA1tZnECWGPg5H78u2SkDaMNnupNmEMLp5PXsNXs/CbTsiKnqqFOoJPc18ec9/Kx4Wmngnztmb0uS/cEJTSK8zCnXM1DIZ1VMTKXf7nzOqLvF6puLj4Aw "Bubblegum – Try It Online") [Answer] # bash + GNU tools, 351 bytes ``` base64 -d<<<H4sIAPnNrVwCA6WUCRLDIAwDv8T+/3NNG4wvkTBTcisGSyA8xrcxj9Ds02F+Z7yuf3hnPyz0vYEGz+FG3IKBs+x3oL2PSh0TM/PnaGamft9nPUCew3uCp5RBWdRKGz+qNJn8qRKkkNaTBgeVIFXWOdi8VCaIeUnsfHo6TXpaFa3H5olf6J5MuIHLoEi0uKcRFCvEXG4xseglKzZg7kpYJSLMA3M7wXKR+/L2WiK0kvg+TDASLp6Co1KEVIlVmFzhCktRhBBDdSZYU1xKHrmDUllcWpNR/YNW2QNcHtF0rSySb0MXk/SDUgEwG5gfLvQDxuEdDo8GAAA=|gunzip ``` [TIO](https://tio.run/##DcvJboJAAADQX/HYhhiQTUzsYWDYHKDIjjdkLwhUZI3/Tvvu7x71xfax3aM@ZendPjmfzwrdq8BsjKc3CYD1XcHSoAomOHIOhlOGIdPTWDm8E5e9bC@Am5/x/HOCPUFK2O24DBlVNOayEmMoyismyZSK@B6bqVYjTbsgHB03m0iOHtnr1JiukE7UIHSMxfuJhf7Dr3FpuF8LVZUROXyeeqoU@N9JyXlCpKZu02dKyzpBF0kRpTBtnbEXRh9URWvFkhhQbEnCKAYyPfdpXqP1lh@rLrzYmg4o/TgFyMJwjfRLRFRjjjkQ2FrHCu0BiZ5aew9pLYTqZRU8DxP7FrqHGSnPB3TrOvY7w8JDwyevRqy8JOJpL/ad0IMKt6Gbi5PM5Jk2XuE8iAlsORkA8PXOh2Ytu@3znbV1sttPJLX9AQ) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~223~~ 220 bytes ``` '06*"x·<×J× Ç×►B×ê\"@$↕!◙è0♥f░×→0×♠p└☺α?×└•×◙×P♣p¬è:×►∟××××←♦♠♣≥â☻┘A☺▄αp⌂r☻[║►×>◘×♦♦└:☻↑`×♥@@@@►►@♦↑ ☻♀◘☻♦☻☻├×å↑×╠×Ç!♠ 0♀◘↑◘☻♦◘×♠α♥â▼ÇA×└×◘` ×××▀≈}═14♦►►π0♀××°×α•×►×××☻×◘××└≈}_├↑♪↓×─0♫♥×××|××*××♪×Ç♠×└×××× ⌐¬╩↕◄○((×T☺"$à+ ``` [Try it online!](https://tio.run/##RVG/S8NQEP5X0lKw1MEI4lBEW0dxcHBTsC7VwR9FHBwUgpS0xQ6NJnl5IBgqKbV2sJPQOuX2@j/cPxK/ey2YFy6Xu/u@@@7e5ent@dn1RT3LVuzNUv4u/d4itUfKohYpDqe7pGh0nK8U2A1yrDQNbdZJnUMPaffZhtVxg32fo@l8soNfuE4fX9SqA9bvjXRMw7Ih4/Yb6Mxht8d6ACwquJNQn6MZ@1EVNBw255MGdx9vEDviwAOS1DarSJoN5PX9stS7Xk1CSQWP0IfTimRdz5KsdgAxzkCs8L@idYI8UEEMv5WDAstelrreP2DRLJ5PQA9x4Q@1qmY4mSyqWcspQoc77QcOeusbgjIafh0hlHT6RQoMZh0yg4FEM0NhfOwK8BMIk@Z6xO6LRIXgUxobxL2YkqnXIxENXUspi2Nxt5eOOfjAHbFqsnoqFkkdYpX5AsWr2f7aVZb9AQ "MathGolf – Try It Online") ## Explanation ``` '0 push single character "0" 6* repeat 6 times "..." push the magic string $ convert to ordinal à convert to binary string + pop a, b : push(a+b) (add the 6 zeroes) below is the footer L/ divide into groups of 23 characters n join array with newlines into string ``` [Answer] # [Python 3](https://docs.python.org/3/), 331 bytes ``` exit(''.join(bin(i)[3:]for i in b'`UP@JB`IDQKJjjd`@@@@@L@@Ah@@CP@@J`@@_@@@@@LNLLP@FPtXpu}}}|@@@@`@@`@@@A@@A~@@~@@@CCCcDA@DMCGM____@@@@HF@H@L@@PX@_`pO`A`@HA@HHF@`LLB@FHX@@s@@Xa`CC@`HD@``L@b@XAD@PDDA@PD@C@F@X@ck@A@P@BCx@DKi[@gI\x7f\\NC\\@TGY@hOrAPXDFp@@@@@\\D@@zbjipAU@@B`@Gp@@\x7fx@G@\\@X@LAh@lFXCLHhJHQHdPBJH@DHP@H@`@Dh@OOix')[1:]) ``` [Try it online!](https://tio.run/##JY9Bb8IwDIX/CrfCZdLEYRKnlyZqQwk0SEPKRBBeYazpprZiTOqmsb/eucx6vny2n@3261I29bTvX7pwGUfRXdWEelxwhsl2OtudmvMojEI9KiLaWGQxzdV6kVXVkTCEAUQJSAtkTPb/cGWMRWIvrv28Xq8/A6ObIFi/AAtSyoMSUEuZLvccQ5dOoAdP67CnNidB0AKaMRkTI9EO@ADcM0kJ0gpEBgWcULCKzayCRAKHwxuvsohlB7UIW7zOffdw8n4lvcdj@oQyPwvrVNLeLvZeAd9FFVqxAWJCynyY6JBykQ0Nv/meOGl0mem1Pto401Da8r0EVSLPQxdNtvez3aTv/wA "Python 3 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 460 bytes ``` printf"%023b",oct"0x$_"for qw/15400 141404 4444b2 555524 0 600 1a00 1a00 2a00 3e00 0 61c618 400190 68c61a 7df7df 0 80002 0 40001 7c001f 0 618718 404010 68639a 7df7df 0 81802 1800 41801 7c181f 1800 100804 81808 61810 18860 1980 18860 61810 81008 101804 201804 200808 101010 80060 60180 11d600 101000 107c00 10ba5b 1393f 5c3837 283b 10283f 102830 106c00 0 1c1000 1d4555 1c0154 140 7c00 1ff00 701c0 c0060 1a00b0 330198 228288 224488 22880 21080 20080 9400 3cfa78/ ``` [Try it online!](https://tio.run/##TVHRasMwDPwVEba3bZUs21E@Yt8wEqeGwmjSrLB9/bKTQ2Em3MWSTpbP63n7TPu@bpfrvXbPHHTqXpZy7/jn6aOry0a375OkyEwSJXKkiDUFSlghElP21PiA4KBnADJSshhBKwN2ht1I/VzxIWvMHMBIs1BfgLWJrG@iyOKirMN/kRhEAOiArhODrkWE2TCg15j3gV7MMnCwx@8RNi9FvXh9eBDbEfSD0c@rPUUic7sk4o18VtA0polEB62Uipr2FEwRYVA9yMtyaWZIOdRzhHHYMUyFpUxHt1qBPSNOpR3tbk6wUmGeUQgWzCnGRoaxgrCjj02DP5CWOvZ22vecNGZNoKyA32W9X5br1/76nt5wiT8 "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 336 bytes ``` print bin(int('gVQAKCgJERLKqqkgAAAAAMAABoAADQAAKgAAfAAAAAMOMMQAGQ0Yw19998AAAAgAAgAAABAAB+AA+AAADDDjEBAENDHNffffAAAAIGAIAMAAQYAfgwPgBgAIBAIIGAgMMCAGIYAAzAAYhgDDAgIEAggMAiAYBEAQEEBAQEADAGAYAjrABAQACD4AELpbAnJ/cODcAUHZAoPyBQYEGwAAAAAcEAA6iqpwBVAACgAHwAA/4AHAcAYAMBoAsGYDMIoKIRIkQCKIAEIQAIAgAEoAPPp4'.decode('base64').encode('hex'),16))[3:] ``` [Try it online!](https://tio.run/##JY9Ra8JAEIT/St9iaNHahtD0bS53JGc8zQkVrqUPNcY1CrlEhdT@@fSiw8DCxzI721wve1u/9H1zqurLw6aqR26OPFprZDHNxGqete2RMEgBzAJcA5kjuztcKqWR6GfTTaMoehsY3Qzm/Ag4g3N@EAxiwdPFzmnYkgnkkKkNdtTlxAiSQTpMSsVIpAH@ALMnzkFSgEihgmECWrgwLcCRwOBwcqc0Yh5AzJsN6tmkWPICH@knbH5l2oiku5UtBBBWbdOxNRATUocnAVIULka5586J4UraTK7kUceZhJDatSQIizxvAm@8LQu7LUfe5udchoHnj8v6Dvblr@c/TUPf/3p9/@77fw "Python 2 – Try It Online") Prints a string of bytes [Answer] # [Zsh](http://zsh.sourceforge.net/) (+coreutils), 320 ~~577~~ bytes It runs on my Mac, but [try it online](https://tio.run/##NZBdT4JgAIX/Cg7DyEHvy5fgYAQqNkVLwxEw2wD5UBEkcizQ30540bk6e3bOzVMVcfOI143nFkHqI8QOIYiKZ0VR7AFswd/OpPqC6ujKnoA2UPOeqA2g@nKeo1Lt3BknuIXBRTyJM3Y5KV9btIhgliqMm8W3Z7CqOXkgDxTPPfOGuOygi@f7bWjb9ewB7LppBmuy1gG0qoKND5vDpR557SQYdcKhw@cw@0SPbLCZp6G6j@au6qC45o@hHCrSbEotf6tyjOnF3pzqpojpCiVMv/uGJGZSTseXvf0BWJSn1fUST@jqVB4BNN5MjUGDMwasdyeySLijmDQ2k2Qr6KfIGutulk98EH5pwdZed63e9d8OcS/UqfBChCjB1b/8IIRPQG4gNLdrmCWtvZKimz8) doesn't work because TIO doesn't have [`basenc`](https://www.gnu.org/software/coreutils/manual/html_node/basenc-invocation.html) :( It's a one-line program, I've added newlines here for readability. Data compressed to [z85 encoding](https://rfc.zeromq.org/spec/32/) (similar to Ascii85). ``` basenc -d --z85<<<'0&M8}p.B@#L#QZE00001Fb*2U02+?qq#={[000069asT6g8.)4ZwEwH00 0Mg1onA4aoh}/0Q{6?7?7Abap8T<N!#M/0000:ZZ{J%0d$no1{.{L01Yzs5hjUju{Cb/00eC!f:[ 8q1oX#k5eUKnfBigKaB[#)FcD1?fA=JG2NyzwD&LsiWGLW<&LA29Gr+T=<o=q3huiZS05#83BRN) l3zmwk01TOWF4#ep&0YP[gY.1d24nhWll]9LmgYDLaoqEc0f^Fe]ZR$Y'|basenc --base2msbf -w0|cut -c-1679 ``` **Encoding steps** . Convert Arecibo message to a digestible format → [`bitstr.8`](https://gist.github.com/roblogic/5dffc81b4673649942b4612e925ae80c#file-bitstr-8) . Convert `bitstr.8` into binary, using script [`demo16.sh`](https://gist.github.com/roblogic/5dffc81b4673649942b4612e925ae80c#file-demo16-sh)[\*\*](https://unix.stackexchange.com/questions/623229/convert-binary-data-stored-as-ascii-to-binary) → `bits.16.again` . Convert binary to [z85](https://rfc.zeromq.org/spec/32/) → `basenc --z85 bits.16.again >`[`bits.85`](https://gist.github.com/roblogic/5dffc81b4673649942b4612e925ae80c#file-bits-85) . Use the z85-encoded string in [`bits.85`](https://gist.github.com/roblogic/5dffc81b4673649942b4612e925ae80c#file-bits-85) for a much shorter code golf! **Decoding steps** -- i.e. what the main script does . `basenc -d --z85<<<` decodes the z85 string to binary . `|basenc --base2msbf -w0` decodes binary to Ascii `1`s and `0`s . `|cut -c-1679` trims extra data --- #### Original 577-byte solution [try it online!!](https://tio.run/##VZHdauswDIDv9xSB5cA6SJnkpqwLe4pBGZRe@Dd2lnVlORBZPX32HiUbZbOwJEsfQpJ5iJe7xeny8hxITjJEjihkZs4Emb5PznnsMXVAFGeVaFJ1GtEpiw4t9WjIomacnppWs9SjpSONjo5Qv9cCz7ilQJGs1BEfs9grDQETdfjmwGMHtcdQy8tAhJinZMtSAgPrgBYc@g4Ntt/@nAEnGEQ20GLMGuKsE7RTRETS/YRGbA0jESbDDnrDpu4MOEKSuQlDxpzXpJzyqJVM65DQgCzJrb8MOiM9auxGo7wUkFo87wrMxFM@EPlYd2ETnWpVsPiG3qD0Quj01LZcq3laOLPmLMKeiaH14ETESNut/EHSKq8oK74JH5/Fa5EORXm6G56eFi/n5mT14Ityit7sdDXuF9vncnd7W75Wm/W@OX6mw99QPPxZDsUJlstye26aHVSbH9zq8crBb44q/sEBbK5guYOH@/tyu28aP2h7vpz/hY/eFdWI6vIf) ``` S=fxxxxibxxdxxfyzzzyx1yxxxxxxxxyyywl2ij1xxhj1xxhixxxhi5iw2d3c2d2cxl2bxc2az2c2d2ax4x4x4x5wcxpxwdxp15m5w2d2d3c2cxfxhxc1xxc2c2y1xx4x4x4x5wc1f2ixj2kd1e2j15e2f5j2kb1h1hyc1f2gzd2d2fzaf2c1d2ej2b2gf2c1d2ed2d2f1dc1f1hzb1g2hya1h2hya1i1gzb1g1g1dc1l2ed2h2gbz2xx2ibzd1lbzb5jb1dx2xyx1x2fy2yy6x3d3e2a3ixxd2x2b1fxxd6b1fxxd2db1e2a2jwb3e1lb2xxzxxxxx1b3ixxxynxxeh5jf9hd3g3fc2k2eb2a1ix2da2b2g2b2cazxxdxzzazyzyzzezxz1ge1d1d1ge1i1ggyxxia3y4xy3z for X in ${(s::)S};{case $X in [a-w])V=$[##$X-96];printf 0%.s {1..$V};;[1-9])V=$[##$X-48];printf 1%.s {1..$V};;[x-z])V=$[##$X-119];printf $[10**$V];;esac} ``` Used custom encoding logic. The string `S` is 421 characters, could possibly be compressed a bit more. Letters `a-w` represent repeated `0`s. Numbers `1-9` represent repeated `1`s. Letters `x y z` represent `10 100 1000` respectively. *Maybe I should have tried [byte-pair encoding](https://en.wikipedia.org/wiki/Byte_pair_encoding) or [Ascii85](https://en.wikipedia.org/wiki/Ascii85) --> Done. ✅* [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~702~~ 697 bytes ``` xxd -r -p<<X|xz -dc fd377a585a000004e6d6b4460200210116000000742fe5a3e006d7010c5d 0018698865079cf6752c9e9a501a87a798b4844f9fcfdaaf87733b9d8239 48c816d860a938767f6cb81299f3e8a638effe3068c0e096a8949c81d706 7dff3ec44e5df185b3a48e5b5857724386e8c37cfbd5c856b12614ee78ec c41df4db3aea71fd3a8fa474905609f78eb3fd66e246557965e4ab6dfd67 efbd9202f542ded9cf98a6401ee2d23afb2f544bd2442c6f428fd612397c f2c6ec50847ddccc5832185e487712e5a7676b97058d7e485d5a3536166a 44ab3c689c93073cdda73b5306a83c4cd268e79db238bfa2d08ac912a578 75020bc7828342d5a62ce367aff7fd89290336128d119fa4272da2b2a79f 5973c71935af054f2d91c1bd3ea4847a3502d6dc8c975114dacf8a4de600 622d80986dbb0cd00001a802d80d00001b16e2a7b1c467fb020000000004 595a X ``` [Try it online!](https://tio.run/##LZI9jpYxDIT79xR7gZUcx78SB6F17FiUCJoV4u6LPyBdJnE8fjInfn77/Pz4qLf3H2/v3798@fr749fbe@XTtVWDjQNei66UHCIBBMAFa8lfHZSwL8e@AFIKC5LrAVgmbiYM6tmijOnXg2GFaajbISNq7@yKaFPd@3gZbn/I0paUCYRvU9GWPLbQvfe1kG23@24QS7jgEubkUzLd5dHquZVEl6uX8dlBdvnMIKpI2@Rabs0@xWksZ6Esulft5pO0qqmm5oauIRDWQUoOLOA9d87uErlIwqwufCmO1Gj63HnSEbCZsG7N2D5mCda9WLijz@uITiERpjShTd2aiXVoj3KTwUirMpNt47i/NGQWDt/BIMcV2EpH5RrkvGWJxENjYqeYp2/QnVWh@/AQCttJWSh21evgttOBBRbpC4PVHuX50ZNqaHuMcwjm3aLRrV3m6LCnD1qt5UMDFSvw4HxiP@zTTpdvjgamxvKV69S@Q510LAKWVFq68lpUkW1BdSc8jyCWgZvUOZD1CtOkA17iv81ZQzr0rKQJwXkl7/@i6czxfP38/AM "Bash – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 362 bytes ``` puts"5r0afnfm8wyke8tfy1pwt7xnuaxyh3wodfp7bhsdufyw0xbdp1pumrz2xir652tuc0ss9oec8yad9vefivd66j126wybhefgk2lv38uqqiur11u26q275jk3h2ucithd59awpaenqpqi1pszh52179zw0ddqtbrvo6kyrrgv8c34pqrp83j8estjp63v29t4hqp9yg2hhzjlq1e9zqx6gh20n9lsttimz3nbq060ritrphxaru7quwmv3oujhd9xjddpbacq4bnpf270znhgto59yn0980itylf95pxw9x7rvkvi7mfql1sx46puo8rg4dq0".to_i(36).to_s(2).rjust(1679,?0) ``` Integer written in base 36. There's surely a more efficient way to compress the integer, e.g. with `zlib` or `base64`. [Try it online!](https://tio.run/##FcZHboQwFADQu2Q1I0UjF3BZ5SgRYIxN/e42lyfKWz2fxvY8kGL46j0a9KkPUdo2i6gbhhJ5PdNQm6HlUhr4aIJKuhVURwUY0uFvUq1nPYlpQiHIa55EG5TMs7ZZMbZiwkobzayXjeyZiuScTR7jRJgjvF83akiabDSql0OBYT4dOIsh3KYnmMu7IKVcHH2@2Na8X7KYaAfOg6CrmENcgdFMZOyMA9kWYsy97g7P8naVLYagU@4hRnvc9BwdYsjb6MHUwSfuUjkyvdJqlKyrUjAOk@vGEzTh6D7NEq9ethNJgWxsu5Y91CIr93nLlh/a7TjUjkG6hF865dDXJ16/9kXZ@z/hRd4fv6YQX5hx@f2D3s/zBw "Ruby – Try It Online") [Answer] # [C++ (VC++)(but tested with gcc as well)], 585 bytes ``` #define l(x,y)for(int x=0;x<y;x++) void f(){const char*a="02A800505012Y595Y240U180YD0Y1A0Y540YF80V61C618800321A3186BEFBEF80X10Y40W20YFC001F0X1861C620200868639AFBEFBE0W40C0100180Z83003F0607C00C001008041030101860400C430Z19800310C018604040804101804403008802020808080800600C030047580080800107C002174B604E4FEE1C1B80283B20507E40A0C08360U3820Z751554E00AA0Z140ZF80Z7FC00380E00C0060340160CC06611414422448804510Z8420010040Z940079F4F0";int x=1679;l(i,365){int d=a[i],c=0;d-=(d>47&d<58)?48:((d>64&d<71)?55:0);if(d>70&d<91)c=91-d,d=a[i-1];for(c;c>=0;c--)l(j,4){if(x--)cout<<(int)((d&(8>>j))>0);}}} ``` [Try it online!](https://tio.run/##RVLRbptAEHwOX4ESKeIaU@0ee8cRbCJM4Q/SFFd5QAdOiGyIbFw5svzt7oIrVXcPt6OZ2R3t2c9P/83ay13b2c2hbtz5fqjb/vt74vyH2n4/7JpqmziHfdu9uV21bfaflW1cJsfO5a5u1m3XuBvvOPsS637ntd3gHhcQH@df8fHhQTh/@rZ215442b7bD659r3bfqsUtyNQAKD4oSxWpUhI8o4HyB5SYQqkIysLAT42ZRsPUQGIaoNHLvOBr4BdCSfAimZYBYMGAGckSJIDRRgdRWkxkeCHIAJlkYGUCtipAQ8iqUchkIISAX2wAxCgFsMJo7ImjcELpSmMLIiYDjzR2Mv8OGzKVcQqVgSuEUw@JIS3ZIacizzHDJQtNsJScPMwJUpaZQMNzYCSsQoVKUQ6QpjwCwYqDrsIxYGAgnwbWEBCghiwDrREJiaQk4nlIIecjOYVibcRZwqigAm7j61pQh1G88dpZoJU4jVi9qH63rzPLG6v9hVcnFN7Xc2XEE5lHj2tNXIconpR6BBG3a8ZCYCxCYRcR@vVs8vDxNR73b2ObsJn1fbHxPmbEbdbekSvbH4b5fPwfgn3vPZMkH0Ik7Hk@n53LOMy2ajtPOCfnhv9L7NzsmuGw61yIHSb8BQ "C++ (gcc) – Try It Online") ungolfed Version (lacks the break after the 1679th element though and goes until the 1680th): ``` #include <stdio.h> #include <iostream> using namespace std; int main() { const char arecibo[]="02A800505012Y595Y240U180YD0Y1A0Y540YF80V61C618800321A3186BEFBEF80X10Y40W20YFC001F0X1861C620200868639AFBEFBE0W40C0100180Z83003F0607C00C001008041030101860400C430Z19800310C018604040804101804403008802020808080800600C030047580080800107C002174B604E4FEE1C1B80283B20507E40A0C08360U3820Z751554E00AA0Z140ZF80Z7FC00380E00C0060340160CC06611414422448804510Z8420010040Z940079F4F0"; int i = 0,j; while (i<sizeof(arecibo)-1) { char digit = arecibo[i]; int count=0; if (digit >= '0' & digit <= '9') { digit -= '0'; } else if (digit>='A'& digit<='F') { digit -= 'A'-10; } else if (digit > 'F'&digit<='Z') { //digit does not contain any valid hex digit in this case count = 'Z' - digit+1; //digit = Z means repeat 2 more times... digit = arecibo[i - 1]; } for (count; count >= 0; count--) { for (j = 0; j<4; j++) { cout << (int)(((digit)&(8 >> j))>0); } } i++; } return 0; } ``` as an Explanation: i concatenated the 73 lines of sample output given to one long line. i encoded them in hexadecimal where the bit order is msbfirst (using this program <https://github.com/Marc-Bender/longBinaryStreamToHex/releases/download/addedErrorCode-4/longBinaryStreamToHex.exe>) i shortened the Output of that by about 70 hexadecimal Digits by using the letters 'G'-'Z' as a sign to repeat the last Digit for a certain amount of times (Z = 2more times, Y = 3more times …) the rest should be relatively self explainatory for Code-Golfers. abusing the preprocessor to shorten loops, abusing the `,` Operator and the like. Output Format is uninterrupted stream of 1679 0/1-values. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 348 bytes ``` {"000000"~:36<5r0afnfm8wyke8tfy1pwt7xnuaxyh3wodfp7bhsdufyw0xbdp1pumrz2xir652tuc0ss9oec8yad9vefivd66j126wybhefgk2lv38uqqiur11u26q275jk3h2ucithd59awpaenqpqi1pszh52179zw0ddqtbrvo6kyrrgv8c34pqrp83j8estjp63v29t4hqp9yg2hhzjlq1e9zqx6gh20n9lsttimz3nbq060ritrphxaru7quwmv3oujhd9xjddpbacq4bnpf270znhgto59yn0980itylf95pxw9x7rvkvi7mfql1sx46puo8rg4dq0>.base(2)} ``` Based on Benjamin Urquhart's [Java solution](https://codegolf.stackexchange.com/a/182927/14109). Uses a straight stream of 0 and 1 characters. The link below has some code to prettify the output. [Try it online!](https://tio.run/##HcFZbpwwAADQ/54CTaXMEFXECxicNDlJfwzG2CzGK9hU7dWnUt8zo1vJc8vFiyg@n79v4L/b33dMfjYOMKHF1p15GbsgMjRnaJOOLGWJz50L0/bS8yjyCVLPDTRxcxdKypEGhTgA7@k@Dl1mnB6jUAcnZIaInLmXo5gWtB64i9aq6CCMiFjUNvOCJYqDCpI3lJ2Gjdoaq6Dxl2wQbOl1As5t6N2xkyU7Nx3dgGtjnenw3I0@zIbgA9FQS2tonpCU17xaONLLJjJJBDRdfQhqu7DuLSDAqeCMTMzF1sZzO/AeZ8lpmjk3PRts3WsjUAsuLaewNzRrQDugQl4FbUw6aWrdsRyq3YRdoU81MXHv3FRzC76qnvnxgco/z49vnuVCVMEx7R@gqmDx@VU87sX9x/37vSyrYd/6x1v1@orwW1nNu9KP2y99Kz@e/wA "Perl 6 – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 366 bytes ``` binary scan [binary decode base64 QBUACgpIRKSpqkoCAAAAgAEAsAAAWAAAKgAAHwAAAGA4hhEATFiMYX3f9wEAAAgAIAAAAAQA8AOADwAAGIZjBAQQFsZZ3/d9AAAAAgMIgAEAwQD8YOADMAAIECAIDAgYBgIwwgCAGQCMMIBhICAQIAgYIAIMEAEEBAEBAQFgAAMMIK4BEBAACD4AhC5tICd/h4MdQMFNoOAnUDAQbAAAAAAcBACuqCoHUAUAKADwAQD+A8ABBzAABiyABjNghigoQiQSAaIIACEEgAACACkAni8P] b* z puts [join [regexp -all -inline .{23} $z] \n] ``` [Try it online!](https://tio.run/##LVBNT8JAEL37K/bgSYMkUg0c3263sGkWXLFRQA79crvQbAuFVDD@9roQJzOZrzczL3NIy65LjI33J9KksSWr/yTL0yrLSRI3@bNHFI3AdC1ew3m921YMTjQ4GuffnYUamLQuGMMrCo63wMjFx@Br1PIrUlwGoDDEDL7DjcVyQ6FU0CyXg342ura1FJedrfKHCweTgOAMwodeUC3aVjOMFZNS0EIwKOHqAkJycE7hVAWOhWuHHnUZmO@hYE8HwbJ@4clMyWBazWAjHyq5HkRKwY47Vk0iRAgvzJR/70hSegaoOYFuprowulJGzRELAca5O8LAtrBm@LImyR0539THQ0NWm8q4/@1znX/XpBeXJekZWxqbk4efx8EvuT2vyaddd90f "Tcl – Try It Online") [Answer] # C++ (with Gnu multi-precision library), 359 bytes This outputs the string as one line. It uses '1' for 0, and '0' for 1 :/ It simply reads the embedded string as base 62, and prints it as base 2. Use `g++ -g arecibo.cpp -lgmp -lgmpxx` to compile and link ``` #include<gmpxx.h> main(){mpz_out_str(stdout,2,class_mpz("vuXXKBYAu1hPsJPbFSf49akyFd0bjJbMIV3upYndU8kYFPsXcpRUK6c9qnzLfORxkxGL7ZfoSwgSxFbCrydjHL603QcxexopAzoYAcAyEiENJJU2vQA2zM8NDbeY6nHgL8rfFoPJaclwxx6TeKeOEknEQHzp7C4la3o8xijBQLOVweFZ1CI9dXy2VQhgnuwF5FeW5mQ909pRMxhn6G3RJ1QEtkS7oGMZYHM03fh4fj391IoYLGVv3iUVuTrV2ghz9CUa9hfGYrdhGoVE2w1inYalYl",62).get_mpz_t());} ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 276 bytes ``` :122[q{3tD!gLF[ 'u#.K>'uCG8cvJZ[on1Z<D! `Fhqq- _V' "qQn+n0h\ :b,vXjo&1TMFaW;wvX;eUS (ueelNSu,y93\kjGI&?UU/38 :ndi4Y5cyC+ME\g7L WaS;QLjtD^L+aVd(XW%gy\8'Eqk-+f72S5J?(r5!m^5px T[Z'3&jd0lZ'/x%#(}.ords].base(2)~~S/.//.say ``` [Try it online!](https://tio.run/##BcFbT4JgAABQL9/EymkDXYo2NafQUFCING354G0ptjm8BWShkIaGomKyln@dztmo29W9bZcLNC0av25mj9ST0Jxzx5uXUTGGmSky3HnCzBoKtUqz@AFuC0BE1joooA7B/1hPnn00wcIwcjB8/T7EAuHYjdHTCT2/kHzeMpgi2cNYC6wzoYKz323Ko8rPYVxRHQP@PIibLlVdvfBmMGs9MNJSaz1nqoMoGFAMVEqUQ7rydfcKszPYqhHdhjQPoEXON5L5SKXHafv6hCPkoYKPR2l4DiyphDWM@NLrzyHEZ5Hmr9h2FXds2eT3hN14jpALjVwk@qKAMRlNya8EjAIe5zGdwoN/5Hqr7N7IqbxTcfr2dOIpkqLInWzZ9j8 "Perl 6 – Try It Online") Outputs as a series of 1679 0s and 1s. You can have it on different lines by adding [`.comb(23)>>` before the `say`](https://tio.run/##BcH7c4EAAABgj062OXbFjdhhjnJR1Bpjxw9eN8vuXF6rZosaCyVkut386@37tspu/WDblSJFCcavmz7AzSS4YN3x9nVUiKFmigi/1FCzgYCd8jx@hLo8IMC6BhQRB@9/aiYvPtvA0jDyEHT7MUID4did0ddwrbAUfd4KMINzx4ka0DOhonPQa0vj6s9xUlUcQ@4yiJkuRVm/cmYwZz3S4krtPGfqwygwJGmwnKiENPn7/g1i5pDVwHstcRFASqxvLHGRap9VD80pi0sjGZuM09ACsMQy2jLiK68/D@NfJYq7Ybp1zLFjkpsps/WcQBcSuUoMBB6lM6pcWPMoCXicp3QKC/4R@k7evxMzaa9gVPZ85kiCJIm5vplhFJ2t1Yi9ZNn2Pw). ### Explanation: ``` :122["...".ords] # Convert the string from base 122 .base(2) # To base 2 ~~S/.// # Remove the leading 1 .say # And print ``` I can probably save bytes by using the output as a 1679 bit integer instead, or reversing the bit representation. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 748 bytes ``` #define l(X,Y)if(z[i]==#X[0])z.replace(i,1,#Y); void f(){std::string z = {"ab1eeedala1ebeeheal1mmma1fa1g1eeeeeeea1a1alddhgdbcdgdacedgdacedgdeeedgdndgddhgqiafbcag1dbfa1blceafafbcegcinnnlddhgmddegddhgb1ddelcidbnlddhgqqiafag1hedeblcebcaf1acegcinnnlddhgmhcdegdacdagb1bfda1lcibfhcildacdaga1d1d1almhcheagbqch1blhcmbqgdacachghcmbqgbqch1blmh1d1aga1hfd1aledcd1aledeheaga1heheblmdbqgbcdchga1af1efdga1hedbla1bndala1b1f1ea1fflh1aia1acccl1f1bibff1ldeebf1fla1h1ebfccla1h1ebfbla1bffdalddhgaibedblaieemeeeeelaideeeealdh1ehldcidalhcccidlbihf1hlafdafbgacedefblfachfacagemebeemagema1ma1magbememhgbeb1b1hgbedehghea1edalfcacieacca0"};for(int i=0;i<1751;i++){l(q,cb)l(n,fi)l(m,ae)l(i,c1)l(h,ba)l(g,0l)l(f,0c)l(e,01)l(d,bb)l(c,11)l(b,aa)l(a,00)l(l,\n)printf("%c",z[i]);}} ``` [Try it online!](https://tio.run/##VVLLbtswEDxXXyHYKCAhbCAeigJRnO9IkOaw3AdJgGJs1@khgb/dHcpB0eo11O7OgDtc3u@/RebLNlcub6L9/a@T5Nfb9ND9GzrmGh8uW1HLVfsyPLqnMdvw/pxfdrvt4/P0Mr7fHnVfiHXIzrvt0zh3v1@z9DaMH9C8u7uq9O/9rv/YUPCqKlTIa1BNSsUvy0LeyMeWahd53EUkRQksUSD@99vYUSpepA@ZLDBFLwH8UFjJWkQj51rrKrGI6FocPFaFs4Rr4tDY4CYVbVQImaf/uYkbmVgI9GBCHgLBEudyjZIX3FRQiV5iOHDCPhIv4dB4xClefz4zS2rloCVrNBW@QnOiRYEokkZgARlGmFeTNScBtoW6uhc84rDNSvKUUcbMBbGA7Zkv8CmYNxQmGG3Ifa5WCUMna4OUw6qaVZfVeixlPYIiKE9F4BehHwaWkJP5VAhsC7Gdh0LP0CReipDAkS5tQX59YkBsgfUK93xDNBrRqm8jYLAnKzZO0@Y82@txyPXU590053v/47uf883N@FGGg@MwlqE6y4DFkQKyYw9ILhAguqkAzE0MUDe1nLjQeOx8@wuOWiW5aQIU97OOewzmyYbNV964NtLjfD5f2h4WyhXj23VfMMVz9@Wop7dj7ae5686XPw "C++ (gcc) – Try It Online") By replacing the most used substring with a new character until it's not worth it anymore ]
[Question] [ Inspired by [this SO question](https://stackoverflow.com/q/46019607/1682559). ## Challenge: **Input:** * A string \$s\$ * A character \$c\$ **Output:** Create a diamond-square ASCII art of the string in all four directions, with the first character of the string in the center and going outwards. Which is inside a square ASCII-art carpet, with the character as filler. This may sound pretty vague, so here's an example: Input: \$s\$ = `string`, \$c\$ = `.` Output: ``` ..........g.......... ........g.n.g........ ......g.n.i.n.g...... ....g.n.i.r.i.n.g.... ..g.n.i.r.t.r.i.n.g.. g.n.i.r.t.s.t.r.i.n.g ..g.n.i.r.t.r.i.n.g.. ....g.n.i.r.i.n.g.... ......g.n.i.n.g...... ........g.n.g........ ..........g.......... ``` ## Challenge rules: * Input-string may also be a list of characters * Output may also be a list of string-lines or matrix of characters * Input-string and character are guaranteed to be non-empty * The string is guaranteed to not contain the character * Both string and character will only be printable ASCII (unicode range [32,126], space ' ' to and including tilde '~') ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: Input: \$s\$ = `11111`, \$c=\$ = `0` Output: ``` 00000000100000000 00000010101000000 00001010101010000 00101010101010100 10101010101010101 00101010101010100 00001010101010000 00000010101000000 00000000100000000 ``` Input: \$s\$ = `12345ABCDEF`, \$c\$ = `#` Output: ``` ####################F#################### ##################F#E#F################## ################F#E#D#E#F################ ##############F#E#D#C#D#E#F############## ############F#E#D#C#B#C#D#E#F############ ##########F#E#D#C#B#A#B#C#D#E#F########## ########F#E#D#C#B#A#5#A#B#C#D#E#F######## ######F#E#D#C#B#A#5#4#5#A#B#C#D#E#F###### ####F#E#D#C#B#A#5#4#3#4#5#A#B#C#D#E#F#### ##F#E#D#C#B#A#5#4#3#2#3#4#5#A#B#C#D#E#F## F#E#D#C#B#A#5#4#3#2#1#2#3#4#5#A#B#C#D#E#F ##F#E#D#C#B#A#5#4#3#2#3#4#5#A#B#C#D#E#F## ####F#E#D#C#B#A#5#4#3#4#5#A#B#C#D#E#F#### ######F#E#D#C#B#A#5#4#5#A#B#C#D#E#F###### ########F#E#D#C#B#A#5#A#B#C#D#E#F######## ##########F#E#D#C#B#A#B#C#D#E#F########## ############F#E#D#C#B#C#D#E#F############ ##############F#E#D#C#D#E#F############## ################F#E#D#E#F################ ##################F#E#F################## ####################F#################### ``` Input: \$s\$ = `@+-|-o-|-O`, \$c\$ = `:` 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:::::::::::::::::: ``` Input: \$s\$ = `AB`, \$c\$ = `c` Output: ``` ccBcc BcAcB ccBcc ``` Input: \$s\$ = `~`, \$c\$ = `X` Output: ``` ~ ``` Input: \$s\$ = `/\^/\`, \$c\$ = `X` Output: ``` XXXXXXXX\XXXXXXXX XXXXXX\X/X\XXXXXX XXXX\X/X^X/X\XXXX XX\X/X^X\X^X/X\XX \X/X^X\X/X\X^X/X\ XX\X/X^X\X^X/X\XX XXXX\X/X^X/X\XXXX XXXXXX\X/X\XXXXXX XXXXXXXX\XXXXXXXX ``` [Answer] # [R](https://www.r-project.org/), ~~118~~ ~~95~~ 92 bytes ``` function(a,d,n=length(a),I=c(n:1,1:n)[-n])for(i in I-1)write(c(a,d)[pmin(I+i,n+1)],1,n*2,,d) ``` [Try it online!](https://tio.run/##bcvNCoJQEAXgfU8ht81MjsW12ggu@gXfIFADMa8N2Ch6pV2vbia4a3HgwPlOO5hwML3klmuBjB4kYVVIaZ@QIUVhDhJo0oFg7EmKpm6BHRYn8jS@W7YF5L8Xxs2LBSKXSVyNKWmSlU/jMBjopeLOQmfbrqnYghobS6lIKURSa4WLP0j7293@cDydL9dZLv/LTZLcx8zqNin1UVMdvg "R – Try It Online") Thanks to: * Giuseppe for fixing an error and a golf * Aaron Hayman for 22 bytes worth of golf [Answer] # [J](http://jsoftware.com/), ~~59~~ 56 bytes ``` ,{~[:((0-2*#)}.\[:,0,:"0({:>:t)*t=:]+/<:)[:(|.@}.,])#\@] ``` [Try it online!](https://tio.run/##XcxNC4JAEAbgu79iyMO6urtuVpchw4/yFARdXbtI9nFIKA@B2l/fVOqyAy8D7zPMXc8EqSBEIMBAAg7hAtLjPtOs/eToOJIHrk17oXJkkuFMOi1usKFuE2Lh@Wukw1Unol6wgtoqKjS1wDqX1xqIIFABeTXP2@NCft1/y8nm45hkk1GCxXIVJ@l2l5mOo0ce73g95GByOX2OE7N/T72vTr4i@gs "J – Try It Online") Too long solution for [J](http://jsoftware.com/) ... (entirely my fault) [Answer] # [R](https://www.r-project.org/), an ugly 118 bytes version By letting the input be a vector of single characters, and outputting a matrix instead of printing nice ascii art. ``` function(s,C,l=length(s),L=4*l-3,k=2*l-1,y=abs(rep(1:k,L)-l)+abs(rep(1:L,e=k)-k)/2+1)matrix(ifelse(y%%1|y>l,C,s[y]),k) ``` [Try it online!](https://tio.run/##Vc3BCsIwDIDh@95jtHGZ2ulJqKBe9wCCeJijnaO1SlvBgvjqM6IoHn4CXwLxg3Zy0FfXxv7seMANWmmV6@KRB8Bazke2nKGRFU2BSTaHwL26cLEwWENpofhJjUoaKA1MqkLAqYm@v/FeKxsUT3ku7mlp6UHYpT2ggSHLtOMtZ4Ehi5SnespRHQNkYwafE0H0H62n3/WKaP2i9k3sQbBlMDwB) # [R](https://www.r-project.org/), 161 157 bytes saved 4 bytes by using ifelse instead of conditionally modifying `y` ``` function(S,C,l=nchar(S),L=4*l-3,k=2*l-1,y=abs(rep(1:L,k)-k)/2+abs(rep(1:k,e=L)-l)+1)cat(rbind(matrix(ifelse(y%%1|y>l,C,el(strsplit(S,''))[y]),L),' '),sep='') ``` [Try it online!](https://tio.run/##RY3BSsNAEIbveQ0pO2NmrZu2l8KKbdVTwEMvglVI040uWbdhdwUDxVePo0YcGOb/Pgb@MDReD827r5M9etjShpz29WsVYItU6vm5kzNqdcFXUa@rfYRgOlDLklqULU6L/N@1ZHSJ0mGusK4ShL31B3irUrAfYBvjooF@MlGn/spxk3EQU4ids4mbhUB87J@4FUlkAimaTrMcsqzxIPjT@hdB4kLgj1Dfw3z5x8VsvlitNze3d2zPRnudy5M88t6zXI5ytWaoR/jk/DDm6W73zPtrhi8 "R – Try It Online") ## ungolfed and commented ``` function(S,C){ s=el(strsplit(S,'')) l=nchar(S) L=4*l-3 k=2*l-1 y=abs(rep(1:L,k)-k)/2+abs(rep(1:k,e=L)-l)+1 # distance from centre y[!!y%%1]=l+1 # set non integers to one more than length of string y[y>l]=l+1 # set number beyond length of string to one more than length of string M = rbind(matrix(c(s,C)[y],L),'\n') # build matrix and add line returns cat(M,sep='') # print the matrix as a string } ``` hmmm, seems like the longest answer so far! [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ ~~96~~ ~~90~~ 84 bytes ``` def f(s,c):r=range(len(s));return[c.join(c*i+s[:i:-1]+s[i:]+c*i)for i in r[:0:-1]+r] ``` [Try it online!](https://tio.run/##LY1NC4JAEIbv/oqFDu7mR2p12QjSymvXQA3CVtuQXVm3QxD9dZt1HRh43meGmf6jn1Ik4/hgDWrw4NeEqr26i5bhjgk8ELJTTL@VKOrwJbnA9ZJ7Q0E5DeIKgNPKA0UaqRBHXCBV0GiaqWo6mtujDjIbndmY3/SKC406B03gODl2Bw3Yur4busTk2BTEaI7JerNNs@PpnINcWHnwgm8goS/gqHVpBlxb/gFeLa7K8gZtxfgH "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~95~~ ~~84~~ 75 bytes ``` ->a,c{(1...2*z=a.size).map{|i|s=a[j=(z-i).abs,z]*c+c*2*j;s.reverse.chop+s}} ``` [Try it online!](https://tio.run/##RcoxDoIwFIDhnVMQJijtS2TUVL2BByAdHk3RkghNH5hYytkrDsbhn77fL9079TKJM3K9lgcAaFiQCGSDqeCJbo02ksR2kGUQtgLsiAfFdK1Zw4YTgTcv48mAfkyupm1Lbpkp79uCZm/He7EDeuL5BVT2pezn11pEMe3d/s9RpQ8 "Ruby – Try It Online") Takes input string as an array of chars. Returns an array of strings. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes ``` .sûsζøsýí€û ``` [Try it online!](https://tio.run/##ATAAz/9vc2FiaWX/U/8uc8O7c862w7hzw73DreKCrMO7/8K7/1NxdWFyZSBEaWFtb25kCiA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/W/uFlzscnTB0QX/9YoP7y4@t@3wjuLDew@vfdS05vDu/4d26xzaZv@/uKRIITMvnUuPyxAEuAy4DI2MTUwdnZxdXN24lLkctHVrdPOB2J/LisvRiSuZq44rgks/Jk4/hisCAA) **Explanation** ``` .s # push suffixes of input û # palendromize this list sζ # transpose using the second input as filler ø # transpose back sý # merge each on the second input í # reverse each row €û # palendromize each row ``` [Answer] # [J](http://jsoftware.com/), ~~35 34~~ 33 bytes ``` ,{~1j1(}:@#"1{:(<*-)1-|+/|)i:@-&# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/darrDLMMNWqtHJSVDKutNGy0dDUNdWu09Ws0M60cdNWU/2tyKXClJmfkK6jrqSukKagXlxRl5qWrQ8VgtAFYzhAE0KWU1UEyRsYmpo5Ozi6ubujyViB5B23dGt18IPZHl64Dm@zohC5eARbXj4nTj1H/DwA) Right to left: `-&#` Length of \$c\$ minus the length of \$s\$ `i:` Range from negative **n** to **n** `1-|+/|` Absolute value, outer sum with absolute value, subtract from 1 `{: (<*-)` Compare the matrix with the end of the range (the `-&#`), 0 for less than or equal, 1 otherwise. Also subtract the matrix from the end of range. Multiply together. The double subtraction saves a byte and gives something like this ``` 0 0 _1 0 0 0 _1 _2 _1 0 _1 _2 _3 _2 _1 0 _1 _2 _1 0 0 0 _1 0 0 ``` Negative indices start from -1 like in python. The only thing left is to insert the columns of zeroes. `1j1( #"1` for each row, repeat each element 1 time and pad with one 0 `}:@` then drop the last one (zero) `,{~`concat \$c\$ and \$s\$ and index into that Many thanks to Galen Ivanov for the algorithm. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 39 bytes ``` {1_',/'y,''2{+x,1_|x}/(#x)':1_,/+y,'|x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJydk0uPgjAQx+98ClI3AQIu1scFLoKPqxcPJuJjQ2Ky2U1MPGF8fPYtltLSGZXuECL+5/cf2jJziC505wShcw4cp3/xi4DursUtdDuF50R0F4Q+yzDFspbR5WN9vp+ig/1pF/H++BO7+8PX929cxOf45G1u1nLtEloGiUmPeJZtu6RXBRUPhMk2ESIVCSnT+lJk2rgqmWoyfUk/rf10Jc11exu+wf5gOErSyXQ2Z9vsVNvsIDHHRF4dg2eYAcdLeIoZMJzDE8wAcQGnmEHHJZxghiauwiPMoOJNeIgZJK7DA8wgcAj3MQPHMZhihn9VN1678ckYn7vxVzXuGdXQqiOloWW/C0PraeIGJMTIj/3utXtk94JNfFRNfARiASX+Qgh2IYyhJXiFMEQFCGAdFeARwk1UBQGsonpFDZaoDgJYoDroQ5ijEBxD2Liq0VqNTsDoXI2+llEPqPDbzhJwq37lMAgxR0nK5iev5ifP0zznRdI8yVP+yFXOB+TO+NWDD8o/vEqYZVt21ymXrKrIMvHEi9VqWKdk4iFv65RIVDL7ETmekXook+9ML97zYmXaVrzNH1n882M=) `{` `}` function with arguments `x` (the string *s*) and `y` (the character *c*) `|x` reverse `x` `y,'` prepend `y` to each `+` transpose `,/` concat `1_` drop first char at this point we have a string of length(`x`) instances of `y` followed by the characters from `x` `#x` length of `x` `(#x)':` sliding window of that many consecutive chars `2{` `}/` do twice `+x,1_|x` join `x` with the reversed `x` without its first element, and transpose `y,''` prepend `y` to each each `,/'` concat each `1_'` drop one from each [Answer] # [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` R±[]/┼┼* ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjMyJUIxJXVGRjNCJXVGRjNEJXVGRjBGJXUyNTNDJXUyNTNDJXVGRjBB,i=JTI3WCUyNyUwQSUyNy8lNUMlNUMlNUUvJTVDJTVDJTI3,v=8) [7 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjMyJUIxJXVGRjNCJXVGRjNEJXVGRjBGJXUyNTNDJXVGRjBB,i=JTI3LiUyNyUwQSUyN3N0cmluZy8lMjc_,v=8) but mirrors a bunch of chars. [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 bytes Returns an array of lines ``` Ôå+ ®¬qV êÃûV ê ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1OUrIK6scVYg6sP7ViDq&input=InN0cmluZyIKIi4iCi1S) ``` Ôå+ ®¬qV êÃûV ê :Implicit input of strings U=s & V=c Ô :Reverse U å+ :Prefixes ® :Map ¬ : Split qV : Join with V ê : Palindromise à :End map ûV :Centre pad each string with V, to the length of the longest ê :Palindromise ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` UBηEθ✂θκ‖O↑←UE¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z84tcQpMTk7vSi/NC9FI0PTmiugKDOvRMM3sUCjUEchOCczORXEyNbUBMoFpablpCaX@JelFuUAFViFFugoWPmkppUA5VwrSlKBRhhqWv//X1wCNCSdS@@/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Originally submitted as a [comment on the now deleted sandbox post](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges?cb=1#comment62343_17496). Explanation: ``` UBη ``` Set the background to the second input `c`. ``` Eθ✂θκ ``` Map over the first input `s` to generate all suffixes and implicitly print them on separate lines. ``` ‖O↑← ``` Reflect horizontally and vertically. ``` UE¹ ``` Add extra space horizontally. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~32~~ 31 bytes ``` (⍉1↓¯1↓⊖⍪1↓⊢)⍣2∘↑(≢⊣),/,¨,2⍴¨⊢¨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBI1HvZ2Gj9omH1oPIh91TXvUuwrCWqT5qHex0aOOGY/aJmo86lz0qGuxpo6@zqEVOkaPerccWgFUcWjF///qxSVFmXnp6mnqeupc6oYgAGQbgNhGxiamjk7OLq5uQBFloIiDtm6Nbj4Q@wMFrIACjk5ARrI6l4aOep26Zpp6BFBMPyZOP0YdxAYA "APL (Dyalog Classic) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 121 bytes ``` Join[q=Table[(v=Table[#2,2(l-k)])<>Riffle[Join[(h=Reverse)[n=(g=Take)[#,-k]],g[n,-k+1]],#2]<>v,{k,l=Length@#}],Rest@h@q]& ``` [Try it online!](https://tio.run/##LcxBC4MgGMbxrxIKw5htrHOG0G3sMGI3eQ8uTMVyVNJl7LO7l7Hbjz8Pz6yTM7NOftDZinx9@agW8dDPySi2/0FrXrOpCiWUTdv7ccT2WzInerObdTOlioJZ3Ack5VUA4FZFxPGCpDU07c7fgU/iZqJNTtIP8N5sSTq5wCHfVx9TcZaFVZ3Tqx4S3iqyJeyWACcnAjl/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes *Note: I'll golf it :)* ``` Ôå+ ®¬qVÃùV mê ê ``` [Try it online!](https://tio.run/##AS8A0P9qYXB0///DlMOlKyDCrsKscVbDg8O5ViBtw6ogw6r//ydzdHJpbmcnCicuJyAtUg "Japt – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 120 bytes ``` param($s,$c)($s,(($l=$s.length-1)..0+1..$l|%{($x=$c*(2*$_))+($s[($_,($l..$_+($_+1)..$l))[$_-ne$l]]-join$c)+$x}))[$l-gt0] ``` [Try it online!](https://tio.run/##TYxdCoMwEITfPUVYtiUxJmofC0LbC/QAaoOIfyVVUaGC2qvbSEG6MCzzMTNt8866vsy0XjEPprVNuuRFsXcwZdujFHWAvdRZXQyl8JmUHvelRD0fJopjgKlNTzYqxrjJhxSVYyomoIxXfCugZixEJeoMdRyLZ1PVZp3juGxci2Lw4nWxrCPmBPqhq@oCiLQAfuR6A5Luzt8OCHiwowsXs2iM7kDOO/38b7jRw42AjOsX "PowerShell – Try It Online") Some days, having index ranges instead of slices really hurts. Today is one of those days. Due to conjoined ranges messing up when dealing with single elements (e.g. returning 0..0+1..0), special-casing is used to avoid it altogether (at the cost of many bytes). [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 bytes ``` Ôå+ ê ®ê ¬qV ûV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1OUrIOogruogrHFWCvtW&input=IkArLXwtby18LU8iCiI6IgoKLVI=) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` jÐƤṚzṚŒḄZŒḄ ``` [Try it online!](https://tio.run/##y0rNyan8/z/r8IRjSx7unFUFxEcnPdzREgUm/x9eHlELZO2c8f@/g7ZujW4@EPv/twIA "Jelly – Try It Online") Left argument: \$s\$. Right argument: \$c\$ (as a single character, not as a string). Output: List of Jelly strings (appears as a list of lists of 1-char Python strings, replace `ŒṘ` with `Y` to see the `\n`-joined output). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~82~~ 83 bytes *+2 bytes thanks Veskah: the single character case bug fixed* *-1 byte: The rule `Input-string may also be a list of characters` used* ``` $c,$s=$args ($s|%{(-join$s|% s*g $i)+$c*$i++})[($r=$i..0+1..$i)]|%{"$_"[$r]-join$c} ``` [Try it online!](https://tio.run/##ZY3BCoJAGITv@xTD8teqm5teA6F6gR7ALELSNkRjN@ig9uqbUtahwz98/wzD3JrH2djLuaocFUnrKF@QTehkSss8st2s9cJro@sRYYMSpH1JeUBayt5PPTIJaaUiGSs1RNlQ4HTkKZns3ct71zM2pwIKT8b5By3uMNCoUU5mjg220yMiARH/3RSvINaDIQVCiG7U5ku738oSexxGdS8 "PowerShell – Try It Online") Less golfed: ``` $c,$s=$args $southEast = $s|%{ (-join$s|% substring $i) + $c*$i++ } $range=$i..0+1..$i $southEast[$range]|%{ "$_"[$range]-join$c } ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~24~~ 20 bytes ``` QPRV:_JbMa@>RV,#aZDb ``` Use the `-l` flag to get human-readable output. [Try it online!](https://tio.run/##K8gs@P8/MCAozCreK8k30cEuKExHOTHKJen///@6Of@LS4oy89L/6wEA "Pip – Try It Online") ### Explanation ``` QPRV:_JbMa@>RV,#aZDb a,b are cmdline args (implicit) a 1st cmdline arg (the string) # Length , Range RV Reverse a@> Take slices of a starting at those indices ZDb Zip the list of slices together, filling out missing values in the matrix with b (the character) M To each row, map this function: _Jb Join on b RV: Reverse (making top row the bottom and vice versa) QP Quad-palindromize: reflect downward and rightward, with overlap ``` For example, with inputs of `abcd` and `.`: ``` RV,#a [3 2 1 0] a@> ["d" "cd" "bcd" "abcd"] ZDb [['d 'c 'b 'a] ['. 'd 'c 'b] ['. '. 'd 'c] ['. '. '. 'd]] _JbM ["d.c.b.a" "..d.c.b" "....d.c" "......d"] RV: ["......d" "....d.c" "..d.c.b" "d.c.b.a"] QP ["......d......" "....d.c.d...." "..d.c.b.c.d.." "d.c.b.a.b.c.d" "..d.c.b.c.d.." "....d.c.d...." "......d......"] ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 57 bytes ``` ${q:=#x-1Bounce!Bounce@Join&y@PadLeft&y&#x=>x[q::(q::0)]} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@1@lutDKVrlC19ApvzQvOVURQjl45WfmqVU6BCSm@KSmlahVqilX2NpVRBdaWWkAsYFmbO1/v9TUlOJolYKC5PRYroCizLySkNTiEufE4tTi6Jw0tQRtiCE5aQ5qaToK0VwKQBCtVFwCVJmupKOgpKcUqwMVNAQBkJgBkpiRsYmpo5Ozi6sbSEYZIeOgrVujmw/E/iAJK4SEoxNIwBkhUAfiRyD4@jFx@jFQMa7Y2P8A "Attache – Try It Online") Output is a list of lines. ## Explanation ``` ?? parameters: x, y ${ ?? q is length of x - 1 q:=#x-1 ?? Reflect, collapsing middle: Bounce! ?? Function: ?? Reflect, Bounce@ ?? Joined by y, Join&y@ ?? padded to the length of x with y PadLeft&y&#x ?? Mapped over => ?? The elements of x at x[ ?? decreasing range from q to q::( ?? each element in the range from q to 0 q::0 ) ] } ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 79 bytes ``` ->\c{{map {join c,g $_ X||c},g .[^*X+(^$_,)]}o*.comb} my&g={.[$_-1...0...$_-1]} ``` [Try it online!](https://tio.run/##ZclJC4JAGMbxu59imERcR207FEraco1ugntDipEL2iHR6aub0yGQXnjg5fevbvVjPeQt4BJggEExPdx1eVyB7l5mBcByCtgQOH2PyfgiNxAdiQ/YUBZ8UooIl/mVMHnLpUaHXDZUdISQNo6@PhkSHiIo8LB51lmRQsE0URO3W2Z0jbpOb8KzL88Xy5Vl7w/H0yRuaNxJSq@U486Thmmz7Im9qL3/6BKpXqB60c@HDw "Perl 6 – Try It Online") Anonymous codeblock that takes input curried (like `f(char)(string)`) and returns a list of lines. I think a different approach would be shorter. ### Explanation: ``` my&g={.[$_-1...0...$_-1]} # Helper function to palindromise a list ->\c{ } # Code block that takes a char { }o*.comb # And returns a function .[^*X+(^$_,)] # Get all prefixes with end padding # e.g. "str" => [["r",Nil,Nil] ["t","r",Nil] ["s","t","r"]] g # Palindromise the lsit map { }, # Map each element to $_ X||c # Replace all Nils with the character g # Palindromise it join c, # And join by the character ``` [Answer] # [Perl 5](https://www.perl.org/) with `-lF`, `-M5.010`, 71 bytes ``` $"=<>;$A=abs,$_="@F[$A..$#F]".$"x($A*2),/./,say reverse.$' for-$#F..$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/19FydbGzlrF0TYxqVhHJd5WycEtWsVRT09F2S1WSU9FqUJDxVHLSFNHX09fpzixUqEotSy1qDhVT0VdIS2/SBeoDKz2/38nP79gLsd/@QUlmfl5xf91c9z@6/qa6hkYGgAA "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 249 bytes ``` s=>c=>{var r=s.Select((x,_)=>{int k=s.Length;var m=s.Substring(_,k-_).Aggregate("",(a,b)=>a+c+b);return new string(m.Skip(2).Reverse().Concat(m.Skip(1)).ToArray()).PadLeft(2*k-3+m.Length,c).PadRight(4*k-3,c);});return r.Skip(1).Reverse().Concat(r);} ``` [Try it online!](https://tio.run/##hZFdS8MwFIav118R6sUS@zH34Y1dxz7cQCgom6AXw5HGtA1bU0mzqcz612fSdkNQNFA47/O@p@c0JblDcnaYbTnp51IwHttlTRIs7Jsp36ZU4HBD@99rbQ7UAZF/yP0B8Qf7HRZA@Lm7oBtKJIRv9gopzLgEa4UDymOZeDqV6tQ2rIbBlb12VsgdxbGgMZYUmqYNsR2qZmwRK0SeoHIrOOD0FdQ9qbtYsxfYQe6c7qjIKUTuJOMEy6PVRsi9z0ZC4Heoyjv8HNBIws752ulaab2NTUpnzuJEwp62FPGK00RxfNfPMULlDp6hPycEvl4tYLns/3Nf@wiabX1MBJsXTWRr3en2LkfjyfV0pulZRYeW8@Fk6rnV8KqCo7EWpBKfun4s66HZWj61ljUoPCPKBMUkgX@vAzBgHIRobzR@ayhDgOgM1plTSBsg1ZyUvPEgmPpvKfKUKIxaB4yr@1KoMIrDFw "C# (Visual C# Interactive Compiler) – Try It Online") This must be improvable... [Answer] # [JavaScript (Node.js)](https://nodejs.org/en/), 143 bytes ``` (s,c)=>{q=Math.abs;m=(l=s.length*4-3)-1;for(i=j=0;j<l/2;(i=(++i)%l)?0:++j){p=s[q(i-m/2)/2+q(j-m/4)];process.stdout.write((i?"":"\n")+(p? p:c))}} ``` [Try it online!](https://tio.run/##DcdLDoIwEADQq5gmJjMWCiIrauUEnkBdVERow6d0qi4IZ0d271n91VR540I8jK961WoFiipUl3lSVx1aoZ8kewWdItHVQxPaQx6fMD7K9@jBKKtSac9dksktwLnBfYdlWnBucXaKbhOYuE8yTDI@gd2Y40M6P1Y1kaDwGj9B/LwJNYApGSvYfWDIwZWuqBCXZdXAKHgzNCzaMcFw/QM "JavaScript (Node.js) – Try It Online") A bit more thinkering would lead to calculating in terms of a one-dimensional array, and less bytes. [Answer] # [Kotlin](https://kotlinlang.org), 250 bytes Note: Kotlin tio currently fails to return a new class so this code gets an null pointer exception. This also occurs for codes I previously posted that worked at that time. I assume it will eventually get fixed, but couldn't find a support contact to report the issue to. It can also be run [here](https://code.sololearn.com/cKA6OO8Rcek5). ``` {s:String,c:Char->val h=s.length*2-1 val w=h*2-1 val m=Array(h){Array(w){c}} for(i in s.indices)for(r in 0..h-1){val o=(i-Math.abs(h/2-r))*2 if(o>=0){m[r][w/2+o]=s[i].toChar() m[r][w/2-o]=s[i].toChar()}} m.map{it.joinToString("")}.joinToString("\n")} ``` [Try it online!](https://tio.run/##nVl7bxs5Dv8/n0J1F7C9tcex@9g7Y11sHs0hh/Z8QLK4HuIsoMzItrbj0aw0E8eXpl@9R@oxmpdz57XRYkL@RFIkxRHpLyKLefJ9NCJnktGMRWQpJMnWXJFwTeOYJSs2PQL2OstSNR2NQhGxlYiXgcpo@IU9AAogQSg2oz9ypjIuEjUa/2UyGU9w2Ue6IyLPQCIjZ1SmLDtC8mWiUi5B293OKLuaE7c8KKvTWsQ9k8tYbI2W0Zt3x@O/vjv@SUs681YawWmemUf8nBCVSZ6siCqRwGRJw4xJEmrqPM@KRcYLhJKI041IoqH6I6eSkZOrs8tLQmVGxFJvxsrlCQH94LRcwhLJQu2AAdnybK1xSy5VVlLZWI5/hSxBHk0ishJIB5dtqYxUQP615uGagId4oniElpUtGqJFofZrSafXRhUYAP6RAblGN28gHErkoCeVLMt25J6ucjYAGlkzEEoTwh7oJo0r7iSKzKzFAxLCc1DxGzwGxWflH8uMVZB4lmcgmXuWYxiy9CzDcOTMs5Dhycqznl3xjI5nrHpmH/WdVzKTyDxmyieldurQZgBGhMbg/zuMbcyVzrAigsotMs7eAzeyhnCSmSJwfjcUCA/tgiraMeNK2QIZsILkopCNcDYzrSURyZBt0mznBFyX0lfV8ImAdBRJRl1iO9lu8amAHG1VvoU8JSKJd6g0BUBG72J38Hp5wrHyEInVhty8ngzGk3e3kLgpDRnpwhe0o0CehHEeofiMx7Cg@63b157/G0uYpHE9GPpYYLUD6UMsbPowqLWQGZQjEKm2YBxs524HBLAyUYFbey6SbkZilvnVJAYDc7oCaMRVCGUBnslO5GQpxYakAkqc3jqKVebIooddWUVmIQIOrdzhxqDuMZKnBg5nFI61thAfQKTi6ClrKtbvLk12XXCiWEm62ZRlFrZfZeAtKDHGH4SmKXge1@6wlFlZWl/EljSPM3I5mhuw9hBuCfMFclxsTfBzxcjV9fnlP0bw//zX6wFZ5okpiKMNy9Yi8iUKbEtBQQrRBxa6AoMHNSmXyTDbpQwXQ0LYPYAr/o12haDOu98a9lGIdC30LsAg2MMdjyKWFLjLZeGkAYHSRsFOGkX6/CRfrFOJDnfhAJ1sPR4wiMHlvF/IOoGzN8DVJopQLVNwLcVNNrwHWbXmqzX4Fd4LYrNhScQiUxuuUVkIhqhGnR3jB8rsDJ6P63X22H7G7sETx/pbIY6Lb0EcV76aOK4Rx3uRe2Tu0V61s77Lyes3b09Oz84/XJhXysv6Vl@2fC7aiO3gi5cf2uBtYISet8GbYAM9a4PXwQ562gavgj30pA1eBpehb9vgHlyFvmmDO3Ad@roNbsBN6KQNjuA26LgNfrDkA20@0BsH@vnACB6YGwdm3YH5fOBJ2X8Ga8f7l1fDr0MB/@bmdE/rp3va@MybpDbgfDpsQptAhH1tQutAB2tAq0AHE01oGViGNaAeWJdWgzpgHdaAGmAd9qoJ1b5vwH5pQg@SeICNB@z6AD8eEJkDYn1A9hyQj/syvHZuTk7NeQnr5yUMT8MQH07Dk/DUU2rrv5nln@vLv9WBo8Vvo8Ue8Gf7WbgHT1x8HjmyIyLpN0c2RENaODISHWnkyHuRe2Tu0V61E6kfHlKKF63i8ula7phu7iKqr3vaf/pGlsFtHoB4zwyZUj3Tmkzhemy7XdefTLGfk/3pkbk86wbm8Qj@AlG/woWy1NRj04fXXIHX1TCPcaAAbIOVTMGd1XR@uklbM7gjZvr6u@VRtg4M7pyFMV5nUa5FIgS7eXNjhYumQWpSYWdALuAaymi4xn3jbdRY1VUG7RvCgb6wOqTX45BSbAGT2uGNX0e2elSAxJWAzsig8U9YgdbfQ5dld@XGBoHxyY@T4dgC9F6Bb4Alht0snAUp6a5n@H3wNTEXcE3Vq4FY6h@fyBNAcEs9DvF/wJ7NKoe/OUS3r0VoBFiK/OMgMPKH476JJn6wdy8HDtyzVNDk6Q7Oj2s8WrsPbvsotTw@cxG5zDxWt7nYVrMVdA33DL1Z75ULMFfYYCbQXEM@i6TQEmBPY1KqMEGbCOz/MAkdyhazUWCYtrB1EyUL1ZGGDilmOF0C5Vyvg2xbMYkrPdSKqIyUsLPfCuijoPFWHqrzSE@obDIZJwUWgZG1Ns5sgIafKGQ7vVM2xqPJ0ILxA7vs93@cWApfkp5d/h7aIp8OxObLDeBvb3RajCavDPSWzEoCic2GG638NsgEHuhe/zlBwz8h6EkHbnlUPENG2Drxd2HHIjbHS2eKJzi/AAcmq9hWCpu85BNNy4vAvq6qJAtgKZ6KQogpQ7bXFqp8eIOaJb4cVWdJXWOSlW7tqkhO2JaYgdMdy7aM@TqwQSWmlbdGBxvYwyMkWvA7KL4Wpn72Op0@eXIZUuUskk7/SLvPVmZd2y9cSYd9WrreBccXmxroSh5xBbm5@5@VvKjeH817oSTSDHP1/DcgV8zGgzVeLPRO3OuBQ@llgqkuSaozBhZN3h6bydH3RzW1poRTNGD4XtfJmSrXRl0ZZ/55M7NVsP9oC1//MXx6OgKdPa4rXFHckCRdUYN69qiP3KzHS@cMMlrqU8WXPfF@dtx/3NxIyHY8MrczdcNL2ew4wzoH1G8woI8t4XwKmmF8@m5eaCYu5XiRlZ7J2SprPT6wOQcvu6i0xCQq@lfPBuOk1/lnMTwyd5pF5wcT9EUHl3de2czq6GtO94ciA7qdfklO2lP1FOmX@TYPrTE6Dz/hfHO5JxmL303MzWID2B7UVjBSh/Bn45v3PgFxyCcZNUNLf40oiYXdtL3r7dAtsLNN8CN7CFmqJ24Wj8NgrpT5rcE4nSeQGTyy15QBEbaGJCJpzF3Hk59KLzKDm4ONcssVDtMaZxAxGezH1GdMQbubmd7iRygYvf6LF0euqFeuB@RnMnZlNFvj2/QSPLmi8Ylc5Xi@Prjt9Ur1uHNKI6Pd6nrRKb3pwYSc@btAv/RCMawXwOuSbhDoSbET@v@rrxigRTr9uHsfqz0O8N61PngxI2Py9WuhoQDcHN@2GvunPFVIdcZWy@agorZvE3We@AQbYM2DFfgDmP45qcgEg4UqyEVe@hXR/bCkU@QJrsYZXBh6TEoBFfka94B5597sxSH3Juc6i@00WtXt7hjDOwPwTrfG0iNV5Bw3OH4MifyXdb6fYyB7WmefnCI5rJO/IfVznTpaYM@18DxdVuCwmPqCdeL7fwE "Kotlin – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 19 bytes ``` :ṫl¤┅v;@&Z¦<¦v¦ṫ¦ṫṣ ``` [Try it online!](https://tio.run/##S0/MTPxv9XDHUiCxc3XOoSWPprSWWTuoRR1aZnNoWdmhZUBRMPFw5@L//4tLijLz0rnqAA "Gaia – Try It Online") Explanation to follow. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 101 bytes ``` s=>c=>[l=s.length-1,...Array(l*2)].map((x,i,a,m=Math.abs)=>a.map((y,j)=>s[m(l-i)+m(l-j)]||c).join(c)) ``` [Try it online!](https://tio.run/##JYzBCsIwEETvfoW3ZDVd0GvZgh/gF9Qe1lhrSpqUbCgW/Peq5DQzvJkZeWGxyc25CvHRb0/ahBpLTetJ0PdhyK/qZBDxkhKv2h/O0OHEs9Zv4wybia6cX8h3AWq4kNWMvyDtpH3l4PiXEbrPxwKO0QVtAbZ6t3DaCynJyYVBoczeZa0UFGJJoSo20VML/FYlZkrlRt3Cv21jkOh79HHQGertCw "JavaScript (Node.js) – Try It Online") [Answer] # TSQL query, 191 bytes In MS-SQL Server Management Studio press Ctrl-T before running this query, this will change the output to text. This script is building up the output from left to right in one long "string", calculating the value to put in each position. The output is limited to 4096 characters. **Golfed:** ``` SELECT string_agg(iif(h>k/2,@y,substring(@,h+1,1))+iif(-~n%k=0,' ',@y),'')FROM(SELECT abs(k/2-n%k)+abs(k/2-n/k)h,*FROM(SELECT number n,len(@)*2-1k,*FROM spt_values)c)d WHERE n<k*k and'P'=type ``` **Ungolfed:** ``` USE master DECLARE @y char='.', @ varchar(20) = 'abcd' SELECT string_agg(iif(h>k/2,@y,substring(@,h+1,1))+iif(-~n%k=0,' ',@y),'') FROM ( SELECT abs(k/2-n%k)+abs(k/2-n/k)h,* FROM ( SELECT number n, len(@)*2-1k,* FROM spt_values )c )d WHERE n<k*k and'P'=type ``` I had to make some changes to format the output in the online version. **[Try it online](https://data.stackexchange.com/stackoverflow/query/1017574/lay-out-the-carpet)** [Answer] # [Java (JDK)](http://jdk.java.net/), ~~213~~ ~~199~~ 198 bytes ``` a->b->{int i=0,l=a.length()-1;String s=a,r[]=new String[l-~l],p;for(;i<=l;s=s.substring(1))r[l+i]=r[l-i]=new StringBuffer(p=b.join(b,s.split(""))+b.repeat(2*i++)).reverse()+p.substring(1);return r;} ``` [Try it online!](https://tio.run/##fZNBb5swFMfv@RRP7GIX8EK2XUodrdnW27RDL5NSJhlqMmeOsWyTqsroV89MgJS2Gk8yxvbv2fD/@23ZnsXb@z9HsdOVcbD1Y1I7IUlZq8KJSpGb/iWdzXSdS1FAIZm18J0JBYcZ@NBG7JnjYB1zfn1fiXtw3Dp064xQm3V2GhXMctxntDFsfNVR0duJIX25hBLokcXLPF4ehHIg6DySlBHJ1cb9RjhO0g4GS1lk1hlV/GHIlxeLMMkinZaVQam4ojK11BJb5/YEoARjs5ahyKjvYjFOXtVlyQ3SNCfbSiiURz5RS@FQEGAc5sRwzZlDiwsRhhj74Z4byxEO9YsDUsNdbRSYtDkOAqRnKfyHQS8WmOoBLqEkTGv5iAbh1vMMv55KMjzWs43bR@v4jlS1I94U5aRCfj/8fFIz656nrvdrkHnkkwU62nmkZQaHoPupIIKABE30Pyppo4XmU9Diw8dP16svX7/dtOi7CfRzGP@Nf/hWteTlBHm9aolignhqgZ8TwPu7u1@@vcCatFOtr4LxZd/5Wni@7Mxs7NiYkbsjib3JZ7Vf23gqnnPNvHWvOf4D "Java (JDK) – Try It Online") `-14 bytes` thanks to @KevinCruijssen `-1 byte` thanks to @ceilingcat ### Ungolfed ``` a-> b-> { int i = 0, l = a.length() - 1; String s = a, r[]=new String[a.length()*2-1],p; for (; i<=l; s=s.substring(1)) r[l+i] = r[l-i++] = new StringBuffer( p = String.join(b,s.split("")) + b.repeat(2*i) ).reverse() + p.substring(1); return r; } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 14 bytes ``` Ṙ¦₅↳ømƛð⁰V⁰jøm ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%E1%B9%98%C2%A6%E2%82%85%E2%86%B3%C3%B8m%C6%9B%C3%B0%E2%81%B0V%E2%81%B0j%C3%B8m&inputs=string%0A%27.%27&header=&footer=) ``` Ṙ # Reverse ¦ # Prefixes ₅↳ # Pad right to correct width øm # Mirror ƛ # Map... ð⁰V # Replace spaces with other char ⁰j # Join by other char øm # Mirror # (j flag) join by newlines. ``` ]
[Question] [ Reading a book is easy, but printing a book can be a bit tricky. When printing a booklet, the printer needs to have the pages arranged in a certain manner in order to be read from left to right. The way this is done is using a pattern like below ``` n, 1, 2, n-1, n-2, 3, 4, n-3, n-4, 5, 6, n-5, n-6, 7, 8, n-7, n-8, 9, 10, n-9, n-10, 11, 12, n-11… ``` ## Test Cases 4 page booklet: `4, 1, 2, 3` 8 page booklet: `8,1,2,7,6,3,4,5` 12 page booklet: `12,1,2,11,10,3,4,9,8,5,6,7` 16 page booklet: `16,1,2,15,14,3,4,13,12,5,6,11,10,7,8,9` 20 page booklet: `20,1,2,19,18,3,4,17,16,5,6,15,14,7,8,13,12,9,10,11` ## Task Your task is to, given an integer `n` that is a multiple of 4, display an array of numbers that could be used to print a book of `n` pages. **Note:** As long as the output generates the correct numbers, whether delimited by spaces, commas, hyphens, or parenthesis, any method to getting to a solution can be used This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with the fewest bytes winning. [Answer] ## JavaScript (ES6), ~~49~~ 45 bytes *Saved 4 bytes with help from [@RickHitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)* ``` f=(n,k=1)=>n<k?[]:[n,k,k+1,n-1,...f(n-2,k+2)] ``` ### Demo ``` f=(n,k=1)=>n<k?[]:[n,k,k+1,n-1,...f(n-2,k+2)] console.log(JSON.stringify(f(4))) console.log(JSON.stringify(f(8))) console.log(JSON.stringify(f(12))) console.log(JSON.stringify(f(16))) console.log(JSON.stringify(f(20))) ``` --- ## Non-recursive, 51 bytes ``` n=>[...Array(n)].map((_,i)=>[2*n-i,,++i][i&2]+1>>1) ``` ### Demo ``` let f = n=>[...Array(n)].map((_,i)=>[2*n-i,,++i][i&2]+1>>1) console.log(JSON.stringify(f(4))) console.log(JSON.stringify(f(8))) console.log(JSON.stringify(f(12))) console.log(JSON.stringify(f(16))) console.log(JSON.stringify(f(20))) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ 7 bytes ``` L`[Žˆrˆ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJ8HT2u10W9Hptv//Dc0A "05AB1E – Try It Online") **Explanation** ``` L # push range [1 ... input] ` # split as separate to stack [Ž # loop until stack is empty ˆ # add top of stack to global list r # reverse stack ˆ # add top of stack to global list # implicitly display global list ``` [Answer] # Python 2, ~~99~~ ~~93~~ ~~88~~ ~~58~~ ~~56~~ 55 bytes ``` f=input() for i in range(1,f/2,2):print-~f-i,i,i+1,f-i, ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802M6@gtERDkystv0ghUyEzT6EoMS89VcNQJ03fSMdI06qgKDOvRCFNN1PbUCdTB0QC2Tr//xsaAQA) -6 bytes by removing unneeded indentation, thanks Oliver Ni -5 bytes by changing the conditional, thanks Luis Mendo -30 bytes by optimizing the print statements, thanks Arnold Palmer -2 bytes by putting the loop on one line, thanks nedla2004 -1 byte by doing some wizardry, thanks Mr. Xcoder [Answer] # [Python 2](https://docs.python.org/2/), 46 bytes ``` lambda n:map(range(1,n+1).pop,n/4*[-1,0,0,-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjexQKMoMS89VcNQJ0/bUFOvIL9AJ0/fRCta11DHAAh1DWM1/xcUZeaVKKRpGBppcsHZZpr/AQ "Python 2 – Try It Online") Generates the range `[1..n]` and pops from the front and back in the repeating pattern `back, front, front, back, ...` --- **[Python 2](https://docs.python.org/2/), 49 bytes** ``` f=lambda n,k=1:n/k*[0]and[n,k,k+1,n-1]+f(n-2,k+2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n29bQKk8/WyvaIDYxLyUaKKCTrW2ok6drGKudppGnawTkGmn@LyjKzCtRSNMwNNLkgrPNNP8DAA "Python 2 – Try It Online") Generates the first 4 elements, then recursively continues with the upper value `n` decreased by 2 and the lower value `k` increased by 2. --- **[Python 2](https://docs.python.org/2/), 49 bytes** ``` lambda n:[[n-i/2,i/2+1][-i%4/2]for i in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjo6TzdT30gHiLUNY6N1M1VN9I1i0/KLFDIVMvMUihLz0lM18jRj/xcUZeaVKKRpGBppcsHZZpr/AQ "Python 2 – Try It Online") Directly generates the `i`'th value of the list, using `-i%4/2` as a Boolean for whether to take the lower or higher value. [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ ~~63~~ 62 bytes *−5 bytes thanks to [@notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) (removing spaces and using `[*...]` instead of `list()`).* *−1 byte thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs) (`*1` instead of `[:]`)*. ``` def f(n):r=[*range(1,n+1)];return[r.pop(k%4//2-1)for k in r*1] ``` [**Try it online!**](https://tio.run/##TcY7CoAwDADQ3VN0EZL6I9VBFE8iDoKtipCWUAdPXyfBN73wxMNzm9JmnXLAOMg0a1l5t0AlF4TLKDbewrPUwQe48q5pTEXovKhLnaxE05KCnBzBQYeYfe9/J4OYXg "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~19~~ ~~17~~ 10 bytes ``` :t"0&)@o?P ``` [Try it online!](https://tio.run/##y00syfn/36pEyUBN0yHfPuD/f0MjAA) ### Explanation ``` : % Implicitly input n. Push range [1 2 ... n] t % Duplicate " % For each (that is, do n times) 0&) % Push last element, and then subarray with remaining elements @ % Push 1-based iteration index o? % Is it odd? If so P % Reverse subarray of remaining elements % Implicit end % Implicit end % Implicitly display stack ``` [Answer] # [Jelly](https://github.com/DennisMitchell/), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/wiki/Code-page) Improved to 11 bytes, "Combinatorial Methods": ``` 9Bṁ×ḶṚÆ¡‘Œ? ``` **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//OULhuYHDl@G4tuG5msOGwqHigJjFkj////8yMA "Jelly – Try It Online")** ### How? This uses permutation calculations and the factorial number system: ``` 9Bṁ×ḶṚÆ¡‘Œ? - Link n e.g. 16 9B - nine in binary [1,0,0,1] ṁ - mould like n [1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1] Ḷ - lowered range(n) [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] × - multiply [0,0,0,3,4,0,0,7,8,0,0,11,12,0,0,15] Ṛ - reverse [15,0,0,12,11,0,0,8,7,0,0,4,3,0,0,0] Æ¡ - convert from factorial base 19621302981954 (=15*15!+12*12!+...+3*3!) ‘ - increment 19621302981955 (we actually wanted 1*0! too) Œ? - shortest permutation of natural numbers [1,2,...] that would reside at that - index in a sorted list of all permutations of those same numbers - [16,1,2,15,14,3,4,13,12,5,6,11,10,7,8,9] ``` --- Unimproved 12 byter, "Knitting Patterns": ``` RṚ‘żRs2Z€FḊṁ ``` **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//UuG5muKAmMW8UnMyWuKCrEbhuIrhuYH///8yMA "Jelly – Try It Online")** ### How? This is the simple approach, it creates two strands, interleaves them and then trims the loose ends: ``` RṚ‘żRs2Z€FḊṁ - Link: n e.g. 8 R - range(n) [1,2,3,4,5,6,7,8] Ṛ - reverse [8,7,6,5,4,3,2,1] ‘ - increment [9,8,7,6,5,4,3,2] R - range(n) [1,2,3,4,5,6,7,8] ż - zip (interleave) [[9,1],[8,2],[7,3],[6,4],[5,5],[4,6],[3,7],[2,8]] s2 - split into chunks of length 2 [[[9,1],[8,2]],[[7,3],[6,4]],[[5,5],[4,6]],[[3,7],[2,8]]] Z€ - transpose €ach (cross-stitch?!) [[[9,8],[1,2]],[[7,6],[3,4]],[[5,4],[5,6]],[[3,2],[7,8]]] F - flatten [9,8,1,2,7,6,3,4,5,4,5,6,3,2,7,8] Ḋ - dequeue (removes excess start) [8,1,2,7,6,3,4,5,4,5,6,3,2,7,8] ṁ - mould like n (removes excess end) [8,1,2,7,6,3,4,5] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~43~~ 36 bytes A port of this answer in C (gcc) [can be found here](https://codegolf.stackexchange.com/a/137978/42418). ``` @(n)[n-(k=1:2:n/2)+1;k;k+1;n-k](:)'; ``` # Explanation 1. `k=1:2:n/2`: Generates a linear sequence from 1 to `n/2` in steps of 2. Note that this is immediately used in the next step. 2. `[n-k+1;k;k+1;n-k]`: Creates a 4 row matrix such that the first row creates the sequence `n, n-2, n-4...` down to `n-(n/2)+2`, the second row is `1, 3, 5...` up to `n/2 - 1`, the third row is the second row added by 1 and the fourth row is the first row added by 1. 3. `[n-k+1;k;k+1;n-k](:)'`: This stacks all of the columns of this matrix together from left to right to make a single column vector, and we transpose it to a row vector for easy display. Stacking the columns together this way precisely creates the sequence desired. Note that this is an anonymous function, so you can assign it to a variable prior to using it, or you can use the built-in `ans` variable that gets created after creating the function. [Try it online!](https://tio.run/##y08uSSxL/f/fQSNPMzpPVyPb1tDKyCpP30hT29A62zobSObpZsdqWGmqW/9PzCvWMDLQ/P8fAA "Octave – Try It Online") [Answer] # [R](https://www.r-project.org/), 48 bytes (improved) Thanks to @Giuseppe for -7 bytes! ``` n=scan();(x=order(1:n%%2))[order(-(n/2+.5-x)^2)] ``` The trick is that `x=1:n;x[order(x%%2)]` is equivalent to `order(1:n%%2)`. [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTWqPCNr8oJbVIw9AqT1XVSFMzGsLV1cjTN9LWM9Wt0Iwz0oz9b2TwHwA "R – Try It Online") # [R](https://www.r-project.org/), 55 bytes (original) ## Golfed ``` n=scan();x=1:n;x=x[order(x%%2)];x[order(-(n/2+.5-x)^2)] ``` ## Ungolfed with comments Read `n` from stdin. ``` n=scan() ``` Define `x` as sequence of pages from 1 to `n`. ``` x=1:n ``` Order pages so even pages are before uneven pages. ``` x=x[order(x%%2)] ``` Order pages in descending order with respect to the centre of the book computed by `n/2+.5`. ``` x[order(-(n/2+.5-x)^2)] ``` Example with 8 pages: * centre is 4.5; * pages 1 and 8 are the most distant from the centre, but 8 comes first because 8 is even; * pages 2 and 7 are the next most distant from the centre, but 2 comes first as 2 is even; * and so on. [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTusLW0CoPSFZE5xelpBZpVKiqGmnGWsO4uhp5@kbaeqa6FZpxQPH/Rgb/AQ "R – Try It Online") [Answer] # Mathematica, ~~54~~ ~~53~~ 45 bytes ``` Join@@Range[#][[(-1)^k{k,-k}]]~Table~{k,#/2}& ``` ## Explanation ``` Join@@Range[#][[(-1)^k{k,-k}]]~Table~{k,#/2}& (* Input: # *) ~Table~{k,#/2} (* Iterate from k=1 to #/2 *) Range[#][[ ]] (* From {1..#}, take... *) {k,-k} (* k-th and negative k-th element *) (* negative k-th = k-th from the end *) (-1)^k (* Reversed for odd k *) Join@@ (* Join the result *) ``` [Answer] # [Python 2](https://docs.python.org/2/), 64 63 bytes -1 byte thanks to [ovs!](https://codegolf.stackexchange.com/users/64121/ovs) ``` lambda n:sum([[i,i+1,n-i,n+~i]for i in range(1,n/2,2)],[n])[:n] ``` [Try it online!](https://tio.run/##DckxDoAgEATAr1wJ4YyB0sSXIAVG0Ut0NYiFjV9Hp53zKesBV1M/1C3u4xQJ3XXvynthMZbRCMO8EtKRSUhAOWKZ1T@tY6cDewTtO4R6ZkGhpKzT9QM "Python 2 – Try It Online") [Answer] ## Haskell, 42 bytes ``` n#a|n<a=[]|x<-n-2=n:a:a+1:n-1:x#(a+2) (#1) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P085sSbPJtE2OramwkY3T9fINs8q0SpR29AqT9fQqkJZI1HbSJMrzVZD2VDzf25iZp6CrUJBUWZeiYKKQpqCodF/AA "Haskell – Try It Online") One byte longer: ### Haskell, 43 bytes ``` f n=[1,3..div n 2]>>= \x->[n-x+1,x,x+1,n-x] ``` [Answer] # Java 8, ~~84~~ 72 bytes ``` n->{for(int j=0;++j<n;System.out.printf("%d,%d,%d,%d,",n--,j++,j,n--));} ``` or ``` n->{for(int j=0;++j<n;System.out.print(n--+","+j+++","+j+","+n--+","));} ``` -12 bytes thanks to *@TheLethalCoder*'s comment on the C# answer. **Old answer (84 bytes):** ``` n->{int r[]=new int[n],i=1,N=n,J=1;for(r[0]=n;i<n;r[i]=-~i++%4<2?J++:--N);return r;} ``` **Explanation:** [Try it here.](https://tio.run/##jZDBioMwEIbvPsVQKETU0JZSFlIX9gG2lx7LHtKoJVmdSBILpfjs7mhlDz0JMzD55@Ofnxh5l5ltSzTF76Cb1roAhjTeBV3zL@fkw4soUrX0Hr6lxmcEoDGUrpKqhNP4BLhbXYBipAPGgqSemsoHGbSCEyDkMGD2@aysmzCTb0SSmCOK88OHsuG2C7x1tKrYal2k/7VKMctSkySpGac4Fv0gXu5td63JfT4yZWgoITsH8rldfkDGr3jIFdtPuQDez9XI5s1IfSyitrtl2GERttvMX9YPfw) ``` n->{ // Method with integer parameter and no return-type for(int j=0;++j<n; // Loop from 1 to `n` (exclusive) System.out.printf("%d,%d,%d,%d,",n--,j++,j,n--) // Print four numbers simultaneously ); // End of loop } // End of method ``` [Answer] # Bash + Perl + Groff + Psutils, 48 bytes ``` perl -nE'say".bp "x--$_'|groff|psbook>/dev/null ``` Shows output on `stderr`. Output contains some trailing garbage. Example of use: ``` $ echo 20 | perl -nE'say".bp > "x--$_'|groff|psbook>/dev/null [20] [1] [2] [19] [18] [3] [4] [17] [16] [5] [6] [15] [14] [7] [8] [13] [12] [9] [10] [11] Wrote 20 pages, 4787 bytes ``` [Answer] # [Perl 5](https://www.perl.org/), 47 + 1 (-n) = 48 bytes ``` $,=$";print$_--,$i+++1,$i+++1,$_--,''while$_>$i ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybqgKDOvRCVeV1dHJVNbW9sQToGE1NXLMzJzUlXi7VQy//83MviXX1CSmZ9X/F/X11TPwNDgv24eAA "Perl 5 – Try It Online") [Answer] # [Swift 3](https://www.swift.org), 74 bytes ``` func g(f:Int){for i in stride(from:1,to:f/2,by:2){print(f-i+1,i,i+1,f-i)}} ``` **[Try it online!](http://swift.sandbox.bluemix.net/#/repl/5987fe4c4d13d32906604380)** # [Swift 3](https://www.swift.org), 60 bytes ``` {f in stride(from:1,to:f/2,by:2).map{(f-$0+1,$0,$0+1,f-$0)}} ``` For some reason, this does not work in any online environment I have tried so far. If you want to test it, put `var g=` in front of it, and call it with `print(g(12))` in [Xcode (Playgrounds)](https://developer.apple.com/xcode/). Here is a picture after I've ran it in an Xcode playground, version 8.3.1 (Running Swift 3.1): [![enter image description here](https://i.stack.imgur.com/yA4iU.png)](https://i.stack.imgur.com/yA4iU.png) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 25 bytes ``` [1,:/2,2|?b-a+1,a,1+a,b-a ``` Although the input is %4, the actual rhythm is 2-based. ## Explanation ``` [1,:/2,2| FOR ( b=1; b <= <input>/2; b=b+2) ? PRINT b-a+1, n a, 1 1+a, 2 b-a n-1 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 66 bytes A port of [my Octave answer](https://codegolf.stackexchange.com/a/137901/42418) to C (gcc): ``` f(n,i){for(i=1;i<n/2;i+=2)printf("%d %d %d %d ",n-i+1,i,i+1,n-i);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI08nU7M6Lb9II9PW0DrTJk/fyDpT29ZIs6AoM68kTUNJNUUBjpR08nQztQ11MnVAJJCtaV37PzcxM08jWadMMzkjsUhLq8y6Ok0jsSQ/U6Ms2jBWE6Tiv5EBAA "C (gcc) – Try It Online") [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 21 bytes ``` =n::n-z+1,z+1,x-1,z-1 ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/3zbPyipPt0rbUAeEK3SBtK7h//@GRgA "cQuents – Try It Online") ## Explanation ``` Implicit input n =n First item in the sequence is n :: Mode :: (Sequence 2): print sequence from 1 to n Comma delimited items are rotated through n-z+1, n - previous + 1 z+1, previous + 1 x-1, third-previous - 1 z-1 previous - 1 ``` [Answer] # [R](https://www.r-project.org/), ~~64~~ 60 bytes Devastatingly outgolfed by [djhurio](https://codegolf.stackexchange.com/a/138045/67312)! His answer is quite elegant, go upvote it. ``` n=scan();matrix(c(n-(k=seq(1,n/2,2))+1,k,k+1,n-k),4,,T)[1:n] ``` A port of [rayryeng's Octave answer](https://codegolf.stackexchange.com/a/137901/67312). [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOjexpCizQiNZI09XI9u2OLVQw1AnT99Ix0hTU9tQJ1snG0jm6WZr6pjo6IRoRhta5cX@t/gPAA "R – Try It Online") ### original solution (64 bytes): ``` f=function(n,l=1:n)`if`(n,c(l[i<-c(n,1,2,n-1)],f(n-4,l[-i])),{}) ``` Recursive function. [Try it online!](https://tio.run/##Dcc7CsAgDADQvSdJShxSnKSeRASLEBAklX6GUnp26/be0bt4uTVfZVdQqp6dYiqSRjLUUFaTB5kWUsMYSUCNpRpMiYj0ftjPrbX6ADs7WxKcpP8 "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes A port of [Arnauld's JS answer](https://codegolf.stackexchange.com/a/137882). ``` f=lambda n,k=1:n>k and[n,k,k+1,n-1]+f(n-2,k+2)or[] ``` [Try it online!](https://tio.run/##DcdBCoAgEAXQq/yl0QQ5RIRQFxEXRkhijSFtOr25eIv3fO@ZhWsN6@Xv/fAQSqs2siV4OWwbpV6TDNr1QcnArdzlYl0NuSAiCuxEWAiam5nAozN4SpQXQcWu/g "Python 2 – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), ~~21~~ 20 bytes ``` sm[hK-QddhdK):1/Q2 2 ``` **[Test Suite.](http://pyth.herokuapp.com/?code=sm%5BhK-QddhdK%29%3A1%2FQ2+2&input=12&test_suite=1&test_suite_input=4%0A8%0A12%0A16&debug=0)** If outputting as a nested list is allowed: # [Pyth](https://pyth.readthedocs.io), ~~20~~ 19 bytes ``` m[hK-QddhdK):1/Q2 2 ``` **[Test Suite.](http://pyth.herokuapp.com/?code=m%5BhK-QddhdK%29%3A1%2FQ2+2&input=12&test_suite=1&test_suite_input=4%0A8%0A12%0A16&debug=0)** --- # Explanation ``` sm[hK-QddhdK):1/Q2 2 - Full program. m :1/Q2 2 - Map over range(1,input()/2,2) with a variable d. [ ) - Construct a list with: hK-Qd - Input - d + 1, d - d, hd - d + 1 and K - Input - d. s - Flattens the list and prints implicitly. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->n{1.step(n/2,2){|x|p n-x+1,x,x+1,n-x}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2lCvuCS1QCNP30jHSLO6pqKmQCFPt0LbUKdCB0QC2bW1/9OijQxi/wMA "Ruby – Try It Online") [Answer] ## C#, 107 bytes ``` int[]F(int p){var a=new int[p];for(int i=0,q=1;q<p;a[i++]=p--){a[i++]=p--;a[i++]=q++;a[i++]=q++;}return a;} ``` Keep two counters, one starting at 1, one at p. In each loop iteration, write four elements and just increment or decrement counters after each entry. When the counters meet in the middle, stop. ``` int[] F(int p) { var a = new int[p]; for(int i = 0, q = 1; q < p; a[i++] = p--) { a[i++] = p--; a[i++] = q++; a[i++] = q++; } return a; } ``` [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` (x:y:r)#(a:b:s)=x:y:a:b:r#s f n=take n$n:[1..]#[n-1,n-2..] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X6PCqtKqSFNZI9EqyapY0xbEBTGLlIu50hTybEsSs1MV8lTyrKIN9fRilaPzdA118nSNgOz/uYmZeQq2CrmJBb4KGgVFmXklCnoKaZoK0SY6FjqGRjqGZjpGBrH/AQ "Haskell – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~27~~ ~~24~~ 23 bytes -3 bytes by printing throughout instead of at the end. -1 Thanks to Mr. Xcoder ``` V:1/Q2 2pjd[-QtNNhN-QNk ``` [Try it online!](https://tio.run/##K6gsyfj/P8zKUD/QSMGoICslWjewxM8vw0830C/7/39DMwA "Pyth – Try It Online") [Or on the online Compiler/Executor](https://pyth.herokuapp.com/?code=V%3A1%2FQ2+2pjd%5B-QtNNhN-QNk&input=16&debug=1 "Pyth Compiler/Executor") This is my first real program in Pyth, so there's probably better methods that I don't know about. # Explanation ``` V:1/Q2 2pjd[-QtNNhN-QNk V:1/Q2 2 # For N in range(1, Q/2, 2): pjd # print " ".join(...), [-QtNNhN-QNk # The list [n - (N-1), N, N + 1, n - N, ""] (n is input) ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~89~~ ~~84~~ 68 bytes As unnamed generic lambda. `n` is #pages (%4==0) and `C` is a reference parameter for the result, an empty container like `vector<int>` (only `push_back` is needed). ``` [](int n,auto&C){for(int i=0,j=0;i<n;C.push_back(++j%4<2?n--:++i));} ``` previous solution: ``` #define P C.push_back( [](int n,auto&C){for(int i=0;i<n;P n--),P++i),P++i),P n--));} ``` [Try it online!](https://tio.run/##VU5LboMwEN37FCOiVlhAhSJW2CaLHKOqKteY1CkMFra7iTg7BZNUym7ef5S1xUWp5WBQ9aHV3IzOT1oODfmnfrXy49QQEpzBC6ActLNSaXC@ZYTI4EfoxPL@kRr0gPlGvJ7prRunyBhR5ldRMsORnd9scN@fX1L9pFl2fan48YRFUWeZoZTNy9q3RQZpMKVwI/AoQVEx5OJYMsxEFaVtv6737/jqaWDSLvSerVKXYr4jyh5ONQYPnEOCICDZLoywhiRG7ku2vgdX7jlooz3f7U9KBBrbflVmMi9/ "C++ (gcc) – Try It Online") Slightly ungolfed: ``` auto f= [](int n,auto&C){ for(int i=0,j=0; i<n; C.push_back(++j%4<2 ? n-- : ++i)); } ``` previous solution slightly ungolfed: ``` auto f= [](int n, auto&C){ for( int i=0; i<n; P n--), P++i), P++i), P n--) ); } ; ``` It was quite straightforward developed and there are sure some minor optimizations in the arithmetics. * Edit1: unification of the arithmetics saved 5 byte * Edit2: after the unification the 4 steps were combined Usage: ``` std::vector<int> result; f(n, result); ``` ### Print-Variant, 77 bytes out-dated If you insist on printing the values, there is this solution: ``` [](int n,auto&o){for(int i=0;i<n;o<<n--<<' '<<++i<<' '<<++i<<' '<<n--<<' ');} ``` Where `o` is your desired `std::ostream`, like `std::cout` Usage (if 2nd lambda was assigned to `g`): ``` g(n, std::cout); ``` [Answer] # Common Lisp, 79 bytes ``` (defun f(n &optional(k 1))(and(> n k)`(,n,k,(1+ k),(1- n),@(f(- n 2)(+ k 2))))) ``` [Try it online!](https://tio.run/##FYjBDYAgEARb2ZfZi/jAAoylaFQSAjmIYv147md25sjxqb3zvMKrCFQMpbZYdM9M8CLc9eQCRZKNTl1y9KOJYYKKWxloB7PQsuFfZ72jNjDAW@kf) [Answer] ## Lua, 94 bytes For this challenge I actually came up with 2 different methods that are both 94 bytes. **Method 1:** ``` function f(n,i)i=i or 1 return n>i and('%s,%s,%s,%s,%s'):format(n,i,i+1,n-1,f(n-2,i+2))or''end ``` **Commented Code:** ``` function f(n,i) i=i or 1 -- On the first iteration i will be nil so I'm setting it's value to 1 if it is. return n>i and ('%s,%s,%s,%s,%s'):format(n,i,i+1,n-1,f(n-2,i+2)) or '' -- Here i return a ternary statement -- If n>i is true, it will return a string using string.format() and part of this is recursion -- If it's false, it will just return an empty string end ``` **Method 2:** ``` function f(n,i)i=i or 1 return n>i and n..','..i..','..i+1 ..','..n-1 ..','..f(n-2,i+2)or''end ``` This method is similar to the first method however I'm instead returning a concatenated string instead of string.format() In both methods I have used the concept of n and i getting closer together [Answer] # PHP, 51+1 bytes ``` while($i<$k=&$argn)echo$k--,_,++$i,_,++$i,_,$k--,_; ``` prints page numbers separated by underscore with a trailing delimiter. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/20f77d274bc8f7dca0a1d2b18874752db015c813). ]
[Question] [ Some people count sheep to get to sleep. Others count goats. Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep. Awake goats look like this: ``` \ ___/o> -(___)" '' '' ``` Sleeping goats look like this: ``` \ ___/-> ,(___)" `` `` ``` They are chained together with a single space between beard and tail of adjacent goats: ``` \ \ \ ___/o> ___/o> ___/-> -(___)" -(___)" ,(___)" '' '' '' '' `` `` ``` The output is allowed to have trailing spaces and a single trailing newline. **The shortest code in bytes wins.** ## Examples N = 1: ``` \ ___/-> ,(___)" `` `` ``` N = 2: ``` \ \ ___/o> ___/-> -(___)" ,(___)" '' '' `` `` ``` N = 3: ``` \ \ \ ___/o> ___/o> ___/-> -(___)" -(___)" ,(___)" '' '' '' '' `` `` ``` N = 4: ``` \ \ \ \ ___/o> ___/o> ___/o> ___/-> -(___)" -(___)" -(___)" ,(___)" '' '' '' '' '' '' `` `` ``` Larger N should work just as well. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~56~~ 53 bytes ``` :"'!!((!((!!#*```).?p0```!!!]'8eP!P]'p(.' '.a-'XE&hqc ``` [Try it online!](http://matl.tryitonline.net/#code=OiInISEoKCEoKCEhIypgYGApLj9wMGBgYCEhIV0nOGVQIVBdJ3AoLicgJy5hLSdYRSZocWM&input=NA) ### Explanation **Awake goat** The awake goat can be packed into the string ``` '' '' ")___(->o/___ \ ``` and unpacked as will be explained shortly. However, the single-quote symbols would need to be *duplicated* in order to escape them, so the string literal would have to be defined as (note the enclosing single-quote symbols and the duplication of the original ones): ``` ' '''' '''' ")___(->o/___ \' ``` To save bytes, we define the string using characters *one code point above* that, thus avoiding duplication. The string literal becomes ``` '!!((!((!!#*```).?p0```!!!]' ``` At the end of the code we will subtract 1 and convert to char. (We could do it now, right after the string literal; but leaving it for the end will save another single-quote duplication, as we will see). To explain how the string is unpacked, we will work with the original characters (that are produced at the end of the code by subtacting 1), so the explanation is easier to follow. We first reshape the string ``` '' '' ")___(->o/___ \ ``` into an 8-row 2D char array, in *column-major order* (down, then across). This automatically pads the last column with char 0 (at the end of the code, subtracting 1 will transform it into number −1, which converted to char gives again char 0). Char 0 is displayed as a space. So effectively we are padding with spaces. The result of reshaping is ``` > "o\ ')/ '__ __ '__ '( - ``` We now flip vertically: ``` - '( '__ __ '__ ')/ "o\ > ``` and then transpose and flip vertically again to produce the awake goat: ``` \ ___/o> -(___)" '' '' ``` The two flip operations are needed because the original packed string is "in reverse". This is to exploit the fact that the actual 2D char array representing the goat has 6 initial spaces in its first row, which get automatically filled by padding when the string is reshaped into an 8-row 2D array. But the padding is done at the end (not beginning) of the last column (not row), hence the flips and transpose. **Sleeping goat** A sleeping goat is generated from an awake goat by transliterating chars `o`, `'`, `-` into `-`, ```, `,` respectively. Actually, because of the one-code-point-above transformation, we transliterate chars `p`, `(`, `'` into `.`, `a`, `-`, which again saves us from having to duplicate the single-quote symbol. This is why the subtract-one operation was left for the end of the program. **Code structure** 1. Generate an awake goat `N` times, working with code points increased by 1. 2. Transform the last goat into a sleeping goat. 3. Concatenate all goats horizontally. Subtract 1 to code points and cast to char. **Commented code** ``` : % (Step 1) Implicitly input N. Push range [1 2 ... N] " % For each (i.e. repeat N times) '!!((!((!!#*```).?p0```!!!]' % Push this string. Quotes are escaped by duplicating 8e % Reshape into an 8-row 2D array of char, in % column-major order, padding last column with % char 0 P % Flip vertically !P % Transpose and flip vertically ] % End 'p(.' % (Step 2) Push this string: source for transliteration '.a-' % Push this string: target for transliteration XE % Transliterate. Transforms last goat into sleeping &h % (Step 3) Horizontally concat all 2D char arrays qc % Subtract 1 and convert to char. 0 becomes −1, which % is converted to char 0, which is displayed as a space % Implicitly display ``` [Answer] ## Javascript, 122 bytes **Answer** ``` f=(n,r='repeat')=>' \\ '[r](n--)+` ${' ___/o>'[r](n)} ___/-> ${'-(___)" '[r](n)},(___)" `+` '' '' `[r](n)+' `` ``' ``` --- **Side note** In the following code (91 bytes) the goats are aligned verticaly. It does not comply with the output format but i though it could be interesting to note that the horizontal alignment required in the output format needs more bytes: ``` f=n=>` \\ ___/${--n?'o':'-'}> ${n?'-':','}(___)" ${n?'`` ``':`'' ''`}`+(n?f(n):'') ``` [Answer] ## Batch, 234 bytes ``` @echo off set/pn= call:l " \ " " \" call:l " ___/o]" " ___/-]" call:l "-(___)@ " ",(___)@" call:l " '' '' " " `` ``" exit/b :l set s=%~2 for /l %%i in (2,1,%n%)do call set s=%~1%%s%% set s=%s:@="% echo %s:]=^>% ``` Takes input from stdin. Batch has trouble with `"` and `>` for various reasons so I have to use placeholders and then switch them at the end. [Answer] ## Pyke, ~~56~~ 54 bytes ``` Fhqd6*"\ ___/o> -(___) '' ''"+23\":RI"-o'"",-`".:(P ``` [Try it here!](http://pyke.catbus.co.uk/?code=Fhqd6%2a%22%5C%0A++___%2Fo%3E%0A-%28___%29%0A+%27%27+%27%27%22%2B23%5C%22%3ARI%22-o%27%22%22%2C-%60%22.%3A%28P&input=3) 4 bytes too many because Pyke doesn't allow double quotes in strings :( [Answer] ## JavaScript (ES6), ~~110~~ 109 bytes ``` f= n=>` \\ \\ ___/o> ___/-> -(___)" ,(___)" '' '' `.replace(/^.{8}/gm,"$&".repeat(n-1))+"`` ``" ; ``` ``` <input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o> ``` Having to support all three kinds of quote characters was annoying, but fortunately @pinkfloydx33's comment gave me the flash of inspiration that I could add the backquotes at the end thus saving me 1 byte. [Answer] [# GolfScript](http://www.golfscript.com/golfscript/index.html), 91 bytes ``` ~:a 1-:b;" \\ "a*n" ___/o>"b*" ___/->"n"-(___)\" "b*",(___)\""n" '' '' "b*" `` ``"n ``` Input: `3` Output: ``` \ \ \ ___/o> ___/o> ___/-> -(___)" -(___)" ,(___)" '' '' '' '' `` `` ``` ### Explanation ``` ~:a 1-:b; # Parse and save the input " \\ "a*n # Repeat the first line 'a' times " ___/o>"b* # Repeat the head 'b' times " ___/->"n # Then add the sleeping goat's head "-(___)\" "b* # Idem ",(___)\""n # " '' '' "b* # Idem " `` ``"n # ``` [Try it online!](http://golfscript.tryitonline.net/#code=fjphIDEtOmI7IiAgICAgIFxcICJhKm4iICBfX18vbz4iYioiICBfX18vLT4ibiItKF9fXylcIiAiYioiLChfX18pXCIibiIgJycgJycgICJiKiIgYGAgYGAibg&input=Mw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~62~~ 56 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁶ẋ6;“\ ___/o>-(___)" '' '' ”s8 ¢“-,o-'`”yЀ ’1£ẋ€ż¢Y ``` Test it at [**TryItOnline**](https://tio.run/nexus/jelly#@/@ocdvDXd1m1o8a5sQoKCjEx8fr59vpagBpTSUFBXV1EFJ41DC32ILr0CKgIl2dfF31BKBA5eEJj5rWcD1qmGl4aDHQCCDn0KKjexwi////bwwA) How? ``` ⁶ẋ6;“\ ___/o>-(___)" '' '' ”s8 - Link 1: make a goat, niladic ⁶ẋ6 - space character, ⁶, repeated 6 times “\ ___/o>-(___)" '' '' ” - rest of the awake goat text ; - concatenate s8 - split into length 8 parts ¢“-,o-'`”yЀ - Link 2: put a goat to sleep, niladic ¢ - last link (make a goat) “-,o-'`” - characters to remap yЀ - map for each (change "-" into ",", "o" into "-", and "-" into "`" ’1£ẋ€ż¢Y - Main link: n ’ - decrement (nAwakeGoats) 1£ - call link 1 as a nilad (make an awake goat) ẋ€ - repeat nAwakeGoats times ¢ - last link (make a sleeping goat) ż - zip Y - join with line feeds - implicit print ``` [Answer] ## [Knight](https://github.com/knight-lang/knight-lang), 96 bytes ``` ;O*" \ "=n+0P;O+*+=t' ___/''->'=l-nT+t'o>';O+*+','=t'(___)" 'l+'-'tO+*' `` `` 'l" '' ''" ``` Pretty simple, nothing super fancy—You just print out `n-1` versions of the sleeping goat and then the woke goat. Repeatable elements are saved in `t` so they aren't typed out again. Expanded: ``` # Print out the ears. They're the same for both goat types. ; OUTPUT (* " \ " (= n (+ 0 PROMPT))) ; OUTPUT (+ (* (+ (= tmp ' ___/')'->') (= m - n TRUE)) (+ tmp 'o>')) ; OUTPUT (+ (* (+ ',' (= tmp '(___)" ')) m) (+ '-' tmp)) OUTPUT (+ (* ' `` `` ' m) (" '' ''")) ``` [Answer] # PHP , 200 Bytes ``` $a=[" \ "," ___/o>",'-(___)" '," '' '' "," `` `` "];$z=8*$n=$argv[1];for($i=0;$i<4;)$o.=str_repeat($a[$i],$i++==3?$n-1:$n);$o[$z*2-2]="-";$o[$z*3-8]=",";$o.=$a[4];echo chunk_split($o,$z,"\n"); ``` [Answer] ## C++, 180 bytes ``` auto f(int n) { string a,b,c,d; while(n--) { a+=" \\ "; b+=" ___/";b+=n?"o>":"->\n"; c+=n?"-(___)\" ":",(___)\" \n"; d+=n?R"( '' '' )":" `` `` \n"; } return a+'\n'+b+c+d; } ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), 60 + 1 = 61 bytes One byte added for the `n` flag. ``` YsX6.\"\ ___/o>-(___)" '' '' \"<>8yXa-1.YyR^"-o'"Y^",-`" ``` Constructs an awake goat as a list of lines and yanks it into `y`. String-multiplies to get `a-1` awake goats. Replaces `-o'` with `,-`` in `y` and concatenates it to the end. Prints, newline-separated. [Try it online!](http://pip.tryitonline.net/#code=WXNYNi5cIlwgICBfX18vbz4tKF9fXykiICAnJyAnJyAgXCI8Pjh5WGEtMS5ZeVJeIi1vJyJZXiIsLWAi&input=&args=LW4+Ng) (I think this is my first time using Pip's escaped-string syntax `\"...\"`, which allows for literal double quotes in the string.) [Answer] # IBM/Lotus Notes Formula, ~~187~~ ~~174~~ 188 bytes ~~(not competing)~~ **EDIT** Found a space that shouldn't have been there and removed an unneeded @Implode 188 as I had missed the fact that the tail of the sleeping goat is different :-( ``` B:=@Repeat(" \\ ";a);C:=@Repeat(" /o> ";a-1)+" /->";D:=@Repeat(" --- ";a);E:=@Repeat(",(___)\" ";a);F:=@Repeat(" `` `` ";a);@Implode(B:C:D:E:F;@NewLine) ``` Ungolfed: ``` B:=@Repeat(" \\ ";a); C:=@Repeat(" /o> ";a-1)+" /->"; D:=@Repeat(" --- ";a); E:=@Repeat("`(___)\" ";a-1)+",(___)\" "; F:=@Repeat(" `` `` ";a); @Implode(B:C:D:E:F;@NewLine) ``` Usage: Create a Notes form with two fields named a and g. a=editable, number, g=computed, text. Paste the above formula into g and give a a default value of 0. Set the form font to Terminal. Create a new document with the form, enter a number in a and press F9 to update the goats. Samples: [![enter image description here](https://i.stack.imgur.com/qkSdn.png)](https://i.stack.imgur.com/qkSdn.png) [![enter image description here](https://i.stack.imgur.com/SBy84.png)](https://i.stack.imgur.com/SBy84.png) [![enter image description here](https://i.stack.imgur.com/MktLo.png)](https://i.stack.imgur.com/MktLo.png) ~~Not competing as the format messes up when the number of goats reaches the width of the page.~~ Given an infinitely wide screen it ~~should~~ will work for any number of goats ~~though~~. This is what it looks like when the page is not wide enough. [![enter image description here](https://i.stack.imgur.com/AKlk4.png)](https://i.stack.imgur.com/AKlk4.png) [Answer] # [CJam](https://sourceforge.net/p/cjam), 58 bytes ``` ri{S6*"\ ___/o>,(___)\" '' '' "+\{'o`"`-"er}|8/}%W%zN* ``` [Try it online!](https://tio.run/nexus/cjam#@1@UWR1spqUUo6CgEB8fr59vp6MBpDVjlBQU1NVBSEFJO6ZaPT9BKUFXKbWotsZCv1Y1XLXKT@v/fxMA "CJam – TIO Nexus") **Explanation** ``` ri e# Read an integer from input { e# Map the following block to the range 0..input-1 S6* e# Push 6 space characters "\ ___/o>,(___)\" '' '' "+ e# Push this string and concatenate with the spaces \ e# Bring the number being mapped to the top { e# If it's 0, execute this block: 'o` e# Push the string "'o" "`-" e# Push the string "`-" er e# Transliterate the large string by replacing characters e# from "'o" with respective characters from "`-"; this e# makes the sleeping goat. }| e# (end if) 8/ e# Split the string into chunks of length 8 }% e# (end map) W% e# Reverse the array, since the sleeping goat was made at e# the beginning z e# Transpose N* e# Join with newlines ``` [Answer] # Python 2.7, 101 113 bytes Edit: Added function definition ``` def f(n): m=n-1 print " \ "*n+"\n"+" ___/o>"*m+" ___/->\n"+'-(___)" '*n+"\n"+" '' '' "*m+" ``"*2 ``` de-golfified: ``` m=n-1 # Replacement variable. Saves 6 bytes " \ "*n+"\n"+ # Print ears, same for all goats! " ___/o>"*m+ # Print eyes of n-1 awake goat " ___/->\n"+ # Print eye of sleeping goat '-(___)" '*m+ # Print body of n-1 awake goat ',(___)"\n'+ # Print body of sleeping goat +" '' '' "*m+ # Print the legs of n-1 awake goat " ``"*2 # Print legs of sleeping goat using *2 operator to save 1 byte ``` Note Python2.7 is one byte shorter than Python3 due to that it doesn't need parentesis when printing. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 66 bytes ``` ’ \ 0 ___/1>02(___)" 0 33 33 ’0¡v123SDys…o-'S:I<×?ys…-,`S:, ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcNMBTCIUTBQUIiPj9c3tDMw0gAyNJWAIsbGIKQAVGVwaGGZoZFxsEtl8aOGZfm66sFWnjaHp9uDubo6CcFWOv//GwMA "05AB1E – Try It Online") ### Explanation ``` ’ \ 0 ___/1>02(___)" 0 33 33 ’0¡v123SDys…o-'S:I<×?ys…-,`S:, Argument n ’ \ 0 ___/1>02(___)" 0 33 33 ’ The goat, newline replaced by 0 and the eye replaced by 1 0¡ Split on 0 v For each y in array, do: 123SD Push the array [1,2,3] twice ys…o-'S: Replace [1,2,3] with ['o','-','\''] I<×? Print that n-1 times without newline ys…-,`S:, Replace [1,2,3] with ['-',',','`'] and print ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 105 bytes ``` say for' \\ 'x(--$_+1), ' ___/o>'x$_.' ___/->', '-(___)" 'x$_.',(___)" ', " '' '' "x$_.' `` `` ' ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhLb9IXQEMYmIU1Cs0dHVV4rUNNXW4gKLx8fH6@XbqFSrxelCerp06UEZXA8jWVFKAyOjAeDpcQEIdhBSUIHoSEkBIQf3/f@N/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online") [Answer] # Bash + GNU Coreutils, ~~165~~ 155 bytes ``` a=" \ >o/___ \")___(- '' '' " eval paste -d \'\' $(seq $1|while read;do printf '<(echo "$a") ' done) | sed "s/-/,/;s/o/-/;s/'' ''/"'`` ``/'|rev ``` Run with: ``` bash my_pgm.bash N ``` Basically the program prints N times of the same goat (reversed), and substitutes the first `-`, for `,`, the first `o` for `-` and the first `'' ''` for the backticks. Then reverses the lines. [Answer] # PHP, ~~133~~ 131 bytes ``` for(;$y<32;$y+=8)for($x=$argv[1];$x--;)echo substr(" \ ___/".($x?"o>-(___)\" '' '' ":"->,(___)\" `` `` "),$y,8)," "[$x]; ``` I found two bytes to golf away from one of the version without curlys. [Answer] ## PowerShell v2+, 96 bytes ``` param($n)' \ '*$n-- ' ___/o>'*$n+' ___/->' '-(___)" '*$n+',(___)"' " '' '' "*$n+' `` ``' ``` (ab)uses the default `Write-Output` formatting to include a newline between elements. Leverages string concatenation and multiplication to construct the goats line by line. The only real trick is the first line `$n--` to output the correct number of ears and then post-decrement `$n` so it's correct for the rest of the lines. ``` PS C:\Tools\Scripts\golfing> 1..4|%{.\counting-goats-to-sleep.ps1 $_} \ ___/-> ,(___)" `` `` \ \ ___/o> ___/-> -(___)" ,(___)" '' '' `` `` \ \ \ ___/o> ___/o> ___/-> -(___)" -(___)" ,(___)" '' '' '' '' `` `` \ \ \ \ ___/o> ___/o> ___/o> ___/-> -(___)" -(___)" -(___)" ,(___)" '' '' '' '' '' '' `` `` ``` [Answer] ## Ruby, 102 bytes ``` m=-1+n=gets.to_i puts' \ '*n,' ___/o>'*m+' ___/->',(?-+a='(___)" ')*m+?,+a," '' '' "*m+" ``"*2 ``` [Answer] # Python 3. 170 bytes ``` lambda n:'\n'.join(map(lambda*l:''.join(l),*map(lambda w:(' '*6+'\ ',' ___/'+(w and'o'or'-')+'>',(w and'-'or',')+'(___)" ',w and" '' '' "or' `` `` '),range(n)[::-1]))) ``` hmm, apparently constructing the string without doing list manipulation yield shorter code [Answer] ## Emacs Lisp, 241 bytes ``` (defvar s'(" \\"" ___/->"",(___)\""" `` ``"))(defun a()(dotimes(n 4 g)(setf(nth n g)(format"%s%s"(nth n'(" \\ "" ___/o>""-(___)\" "" '' '' "))(nth n g)))))(defun g(n)(let((g(copy-seq s)))(mapcar'message(dotimes(i(- n 1)g)(a))))) ``` "Slightly ungolfed" ``` (defvar s'(" \\"" ___/->"",(___)\""" `` ``")) (defun a()(dotimes(n 4 g)(setf(nth n g)(format"%s%s"(nth n'(" \\ "" ___/o>""-(___)\" "" '' '' "))(nth n g))))) (defun g(n)(let((g(copy-seq s)))(mapcar'message(dotimes(i(- n 1)g)(a))))) ``` where `s` is one sleeping goat, `a` adds an awake goat and `g(n)` is the counting function. [Answer] # Java 8, ~~236~~ ~~222~~ ~~218~~ 173 bytes ``` n->{String x="\n",a="",b=a,c=a,d=a;for(;n-->0;a+=" \\ ",b+=" ___/"+(n<1?"-":"o")+">",c+=(n<1?",":"-")+"( )\" ")d+=(n<1?" `` ``":" '' ''")+" ";return a+x+b+x+c+x+d;} ``` **Explanation:** [Try it online.](https://tio.run/##NVBBbsIwELznFaO9kMgxpZceakxfUC49NhUYJ1SmsEGJQVQob083JLVmDjs7K3nm4K5O1@eKD@VP74@ubfHuAt8TIHCsmr3zFdbDCHzEJvA3fCobcGZE7ISCNroYPNZgWPSsV/fJe7NUMOXOEuU763IvLK0z@7pJDWu9WhinLOHxigLieoybzeaJVMrL5zfS9Eo1ZYpWlHtlRzEXUQ9iKodZQaCs/N9huxWIAbOZYHABZJoqXhqGUze1E3phabreJBLgfNkdJcCU41qHEiepIR1jfH7BZWMHw8eH@EGCLgyUCljixUxb6ei3jdVpXl/i/Cyn8cgpz6Wx7FHXWFiXdP0f) ``` n->{ // Method with integer parameter and String return-type String x="\n", // New-line String to reduce bytes a="", // Row 1 String, starting empty b=a, // Row 2 String, starting empty c=a, // Row 3 String, starting empty d=a; // Row 4 String, starting empty for(;n-->0; // Loop `n` times: a+=" \\ ", // Append the horns to row 1 b+=" ___/"+(n<1?"-":"o")+">", // Append the back and head to row 2 c+=(n<1?",":"-")+"( )\" ") // Append the tail, body, and beard to row 3 d+=(n<1?" `` ``":" '' ''")+" ";// Append the legs to row 4 return a+x+b+x+c+x+d;} // Return the four rows, separated by new-lines ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~58~~ 39 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` !-≥9A²]]k1{{K4edr↙FX‟×-22╋,83╋`` ``34╋↔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjAxJXVGRjBEJXUyMjY1JXVGRjE5QSVCMiV1RkYzRCU1RCV1RkY0QiV1RkYxMSV1RkY1QiV1RkY1QksldUZGMTQldUZGNDVkJXVGRjUyJXUyMTk5RlgldTIwMUYlRDctJXVGRjEyJXVGRjEyJXUyNTRCJTJDJXVGRjE4JXVGRjEzJXUyNTRCJTYwJTYwJTIwJTYwJTYwJXVGRjEzJXVGRjE0JXUyNTRCJXUyMTk0,i=OQ__,v=8) Constructs the awake goat facing left from a compressed string, repeats it \$n\$ times horizontally, modifies the left-most goat to the sleeping goat, then flips the whole string horizontally. [Answer] # Brainfuck 420 bytes Its not very golfed yet... but it works... whit numbers from 0 to 255 :) ``` >+[[-]>,[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<[->+>+>+>+<<<<]>>>>>>++++[<++++++++>-]>-[<+>---]<+++++++>>-[<+>-----]<---->>-[<-->-------]<+>>----[<+>----]<-><<<<<<[>......>.<.<-]++++++++++.>>+++<<<-[>>..>...>.>.>.<<<<<<-]>>..>...>.--.>>.[<]>.<<-[>>>>>.-----.<...>+.++++<<++.--.<<<-]>>>>>-.----.<...>+.<<++.--.>>[-<<<<+>>>>]<[<]>-->.<<<-[>>>>.<<..>>.<<..>>..<<<<-]>>>>>+<.>..<.>..<.. ``` [Try it online](https://tio.run/##TVDLCgIxDPygmoCeh/xIyEEFQQQPgt9fJ8l21ynbdqeTyeP2uT7fj@/9NacNdwk7@XA54EZyFBxNmQRvgIvZ2AGEUQsMs@AWEYjUjF5AKRJttgJpZ8Jfo3Us1nZKKhuzJpPJZSNTkwVuMqoMBTctmEKxik9opaaCXVm@55er41jHzopQrM6KteWEVmKaUjC0e6ZpUh1MiP5r1nsPpkaTw0lbdqJY1rypHofiMBzIirZN5zxffg) Explained version: ``` Read number from 0 to 255 "thanks to esolangs ;)" >+[[-]>,[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]< Its a little bit hard explain this part because it is creating letters and printing lines at the same time [->+>+>+>+<<<<] Make 4 copies of the number (one for every line) >>>>>>++++[<++++++++>-]>-[<+>---]<+++++++> Make space and '\' >-[<+>-----]<---- Make '/' >>-[<-->-------]<+ Make 'o' >>----[<+>----]<-> Make mayor sign <<<<<<[>......>.<.<-] Print first line ++++++++++.>>+++<< Make line jump and '_' <-[>>..>...>.>.>.<<<<<<-] Print second line >>..>...>.--.>>.[<] Make minus sign and print the line of last sheep >.<<-[>>>>>.-----.<...>+.++++<<++.--.<<<-] Print thirth line >>>>>-.----.<...>+.<<++.--.>>[-<<<<+>>>>] Print the line of last sheep <[<]>-->.<<<-[>>>>.<<..>>.<<..>>..<<<<-] Print fourth line >>>>>+<.>..<.>..<.. Print the line of last sheep ``` [Answer] # [Zsh](https://www.zsh.org/), 97 bytes ``` $1()O+=${s/o/-} for s (' \ ' " ___/o>" '-(___)" ' " '' '' ")(eval {1..$1}'||O+=$s;';<<<$O) ``` [Try it online!](https://tio.run/##qyrO@F@cWqJg@l/FUEPTX9tWpbpYP19ft5YrLb9IoVhBQ10BDGIU1LmUFBTi4@P18@2UuNR1NYBMTSWwqLo6CCkoaWqkliXmKFQb6umpGNaq19SAjCu2Vre2sbFR8df8/x8A "Zsh – Try It Online") Feels way too long. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~63~~ 61 bytes ``` •D:¨Mß²нĀùÜ<3¹º•“\ _/o>-()"'“ÅвJ.B×»R"-, o-"#vy`.;2F„'``.;]R ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcMiF6tDK3wPzz@06cLeIw2Hdx6eY2N8aOehXUCZRw1zYhS44vXz7XQ1NJXUgdzDrRc2eek5HZ5@aHeQkq6OQr6uknJZZYKetZHbo4Z56glAVmzQ//@GBgA "05AB1E – Try It Online") ``` •...•“...“ÅвJ.B×»R"..."#vy`.;2F„'``.;]R # trimmed program R # push reversed... .B # list of lines in... J # joined... Åв # list of characters in... “...“ # literal... Åв # with indices in base-10 values of base length of... “...“ # literal... Åв # digits of... •...• # 258955905826915235144641900393055... .B # with length of longest line minus length of each line spaces appended to each line... # (implicit) with each element... × # repeated... # implicit input... × # times... » # joined by newlines... R # reversed... .; # with first occurence of... ` # second character of... y # variable... .; # replaced by... ` # first character of... y # variable... v # for y in... "..." # literal... # # split by spaces... .; # with first occurence of... ` # second character of... „'` # literal... .; # replaced by... ` # first character of... „'` # literal... F # for n in [0, 1, 2, ..., 2 # ..., literal... F # ] ] # exit loop ] # exit loop # implicit output ``` ]
[Question] [ A Rubik's cube has 6 colors: red, orange, yellow, white, blue, and green. Red and orange, yellow and white, and blue and green faces are on opposite sides. Net of a solved Rubik's cube looks like this: ``` Y BRGO W ``` And the tiles look like this: ``` Y Y Y Y Y Y Y Y Y B B B R R R G G G O O O B B B R R R G G G O O O B B B R R R G G G O O O W W W W W W W W W ``` # Challenge Given rotations, reversed rotations, or double rotations output what a solved cube will transform to, as ASCII art or as an image (whitespaces aren't necessary, may or may not exist, trailing whitespaces are allowed.). Input will be rotation (and optional modifier). Rotation notation goes like: `U`(p), `L`(eft), `F`(ront), `R`(ight), `B`(ack), `D`(own); `2` (double), `'` or `i` (inverse). All normal rotations will be 90° clockwise, inverse ones will be counterclockwise. **Explanation about clockwiseness**: Imagine the cube as you're looking at the red face, and the yellow face is at the top. Then rotate the cube so that the face that the program will rotate will face you. This is the way clockwiseness will work. (Except back face, you will rotate the cube horizontally in that case.) ## Input Input will be a list of moves. ## Output An ASCII art that represents the cube or an image of the net of the cube. ## Examples **Input**: (empty) **Output**: ``` Y Y Y Y Y Y Y Y Y B B B R R R G G G O O O B B B R R R G G G O O O B B B R R R G G G O O O W W W W W W W W W ``` **Input**: `U` (up) **Output**: ``` Y Y Y Y Y Y Y Y Y R R R G G G O O O B B B B B B R R R G G G O O O B B B R R R G G G O O O W W W W W W W W W ``` **Input**: `U'` or `Ui` (inverse up) **Output**: ``` Y Y Y Y Y Y Y Y Y O O O B B B R R R G G G B B B R R R G G G O O O B B B R R R G G G O O O W W W W W W W W W ``` **Input**: `U2` (double up) **Output**: ``` Y Y Y Y Y Y Y Y Y G G G O O O B B B R R R B B B R R R G G G O O O B B B R R R G G G O O O W W W W W W W W W ``` **Input**: `L'` (inversed left) **Output**: ``` R Y Y R Y Y R Y Y B B B W R R G G G O O Y B B B W R R G G G O O Y B B B W R R G G G O O Y O W W O W W O W W ``` **Input**: `R` (right) **Output**: ``` Y Y R Y Y R Y Y R B B B R R W G G G Y O O B B B R R W G G G Y O O B B B R R W G G G Y O O W W O W W O W W O ``` **Input**: `U2 L' D` (double up, inverse left, down) **Output**: ``` O Y Y R Y Y R Y Y G B B W O O B B B R R Y G B B W R R G G G O O Y O O Y G B B W R R G G G R O O W W W W W W ``` # Rules * No loopholes allowed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes solving the problem wins. [Answer] # Ruby, ~~370 339~~ 305 bytes Latest edit: a few bytes saved by rearrangement of the plotting formulas and removal of unnecessary brackets. A massive saving by rewriting the generation of the cube - I never knew Ruby had a builtin for Cartesian Products! ``` ->s{q=[-66,0,71].product [-87,0,89],[-79,0,82] s.map{|c|m="LDBRUF".index c[0];e=m/3*2-1 c.sub(/[i']/,"33").chars{q.map{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)}}} t=[" "*12]*9*$/ q.map{|r|a,b,c=r.map{|i|i<=>0} 3.times{|i|r[i]!=0&&t[56+[a*3-a*c-d=b*13,a-d*3+d*c,3-d-c*3+c*a][i]]=r[i].abs.chr}} t} ``` Anonymous function. Accepts an array of strings, each representing one face turn (a single string with spaces between each face turn is an additional 6 bytes.) Returns a 9x12 rectangular string. **Brief explanation** This is closely based on a concept from my answer to [this question](https://codegolf.stackexchange.com/a/71325/15599), which in turn was based on a similar concept by Jan Dvorak. The first line generates a 27 element array, representing the 27 cubies. Each cubie is represented by a 3 dimensional vector in which the sign represents its current position and the magnitude of each coordinate represents the ascii code for the colour of the sticker. Example move: for R, for each cubie check if the x coordinate is >0 and if so rotate 90 degrees by swapping the y and z coordinates and swapping the sign of one of them. Take a 9x12 array of spaces and plot the cube into it. For each cubie and axis we check if the sticker exists (coordinate in that axis nonzero), and work out where it is to go. Then we take the coordinate and perform `.abs.chr` to change the number into the required character and plot it. **Ungolfed in test program** (per 339 byte edit) ``` f=->s{ q=(0..26).map{|i| #Build an array of 27 cubies [[-66,0,71][i%3], #x coordinate B.G [-87,0,89][i/3%3], #y coordinate Y.W [-79,0,82][i/9]] #z coordinate O.R } s.map{|c| #For each move in the input array m="LDBRUF".index(c[0]);e=m/3*2-1 #m=face to move. e=-1 for LDB, +1 for RUF. c.sub(/[i']/,"33").chars{ #Substitute "i" and "'" for "33" so chars in string = clockwise 1/4 turns required. For each char... q.map{|j|j[m%=3]*e>0&& #...and each cubie, m%3 tells the relevant axis. if coordinate*e>1 rotate the cubie 1/4 turn. (j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)} #Swap other two axes and change sign of one. e performs sign change if necessary for LDB. } } t=[" "*12]*9*$/ #Make an array of 9 strings of 12 spaces, then make a single string by joining them with newlines q.map{|r| #For each cubie a,b,c=r.map{|i|i<=>0} #make a normalised (-1,0,1) copy of each coordinate. d=b*13 #13 chars per line, d will be useful for plotting to the correct line of the output. 3.times{|i| #For each of the 3 coordinates of the cubie r[i]!=0&& #if zero, sticker doesn't exist (edges and centres have <3 stickers.) If not zero plot the sticker. t[[56-d+a*3-a*c, #Calculate position on plot for x (L/R faces), 56-d*3+d*c+a, #Calculate position on plot for y (D/U faces), 59-d-c*3+c*a][i]]= #Calculate position on plot for z (B/F faces). Select the correct axis. r[i].abs.chr #Convert the coordinate to a character and assign to the correct space on the output plot. } } t} #Return the output string. puts f[gets.chomp.split] ``` **Output** ``` Checkerboard U2 D2 F2 B2 L2 R2 YWY WYW YWY BGBRORGBGORO GBGOROBGBROR BGBRORGBGORO WYW YWY WYW 6-spot U D' R L' F B' U D' RRR RYR RRR WWWGGGYYYBBB WBWGRGYGYBOB WWWGGGYYYBBB OOO OWO OOO Testcase U2 L' D OYY RYY RYY GBBWOOBBBRRY GBBWRRGGGOOY OOYGBBWRRGGG ROO WWW WWW ``` [Answer] # Javascript (ES5), 1615 bytes ``` function m(a){b=[];b[0]=a[6];b[2]=a[0];b[8]=a[2];b[6]=a[8];b[1]=a[3];b[5]=a[1];b[7]=a[5];b[3]=a[7];b[4]=a[4];return b}function q(a,b){c=[];c[0]=b[0];c[1]=b[1];c[2]=a[2];c[3]=b[3];c[4]=b[4];c[5]=a[5];c[6]=b[6];c[7]=b[7];c[8]=a[8];return c}function r(a){var b=[];b[0]=m(a[0]);b[1]=q(a[2],a[1]);b[4]=q(a[1],a[4]);b[3]=q(a[4],a[3]);b[2]=q(a[3],a[2]);b[5]=a[5];return b}function x(a){var b=[];b[0]=m(a[0]);b[1]=a[2];b[2]=a[3];b[3]=a[4];b[4]=a[1];b[5]=m(m(m(a[5])));return b}function y(a){var b=[];b[0]=a[4];b[1]=m(a[1]);b[2]=a[0];b[3]=m(m(m(a[3])));b[4]=a[5];b[5]=a[2];return b}function s(a){a=a.replace(/F2/,"F F");a=a.replace(/R2/,"R R");a=a.replace(/U2/,"U U");a=a.replace(/D2/,"D D");a=a.replace(/B2/,"B B");a=a.replace(/L2/,"L L");a=a.replace(/F'/,"F F F");a=a.replace(/R'/,"R R R");a=a.replace(/U'/,"U U U");a=a.replace(/D'/,"D D D");a=a.replace(/B'/,"B B B");a=a.replace(/L'/,"L L L");a=a.replace(/F/,"y y y R y");a=a.replace(/L/,"y y R y y");a=a.replace(/U/,"x y R y y y x x x");a=a.replace(/B/,"y R y y y");a=a.replace(/D/,"x y y y R y x x x");a=a.split(" ");for(b=["RRRRRRRRR".split(""),"WWWWWWWWW".split(""),"GGGGGGGGG".split(""),"YYYYYYYYY".split(""),"BBBBBBBBB".split(""),"OOOOOOOOO".split("")],c=0;c<a.length;++c)"x"==a[c]?b=x(b):"y"==a[c]?b=y(b):"R"==a[c]&&(b=r(b));return p(b)}function p(a){for(var b="",c=0;3>c;++c)b+="\n "+a[1][3*c+0]+a[1][3*c+1]+a[1][3*c+2];for(c=0;3>c;++c)b+="\n"+a[5][3*c+0]+a[5][3*c+1]+a[5][3*c+2]+a[2][3*c+0]+a[2][3*c+1]+a[2][3*c+2]+a[0][3*c+0]+a[0][3*c+1]+a[0][3*c+2]+a[4][3*c+0]+a[4][3*c+1]+a[4][3*c+2];for(c=0;3>c;++c)b+="\n "+a[3][3*c+0]+a[3][3*c+1]+a[3][3*c+2];return b} ``` Ungolfed: ``` function m(fac){ //Turn a face //0 1 2 //3 4 5 //6 7 8 var fac2=[]; fac2[0]=fac[6]; fac2[2]=fac[0]; fac2[8]=fac[2]; fac2[6]=fac[8]; fac2[1]=fac[3]; fac2[5]=fac[1]; fac2[7]=fac[5]; fac2[3]=fac[7]; fac2[4]=fac[4]; return fac2; } function q(face1,face3){ //Swap right third of two faces var face2=[]; face2[0]=face3[0]; face2[1]=face3[1]; face2[2]=face1[2]; face2[3]=face3[3]; face2[4]=face3[4]; face2[5]=face1[5]; face2[6]=face3[6]; face2[7]=face3[7]; face2[8]=face1[8]; return face2; } function r(state){ //Apply a R move var state2=[]; state2[0]=m(state[0]); //Swap right set of Front, Up, Back, Down (2,1,4,3); state2[1]=q(state[2],state[1]); state2[4]=q(state[1],state[4]); state2[3]=q(state[4],state[3]); state2[2]=q(state[3],state[2]); state2[5]=state[5]; return state2; } function x(staten){ //Apply a x move var state2=[]; state2[0]=m(staten[0]); state2[1]=staten[2]; state2[2]=staten[3]; state2[3]=staten[4]; state2[4]=staten[1]; state2[5]=m(m(m(staten[5]))); return state2; } function y(state){ //Apply a y move var state2=[]; state2[0]=state[4]; state2[1]=m(state[1]); state2[2]=state[0]; state2[3]=m(m(m(state[3]))); state2[4]=state[5]; state2[5]=state[2]; return state2; } function s(algo){ //Solve a cube, representing every move with x, y and R algo=algo.replace(/F2/,"F F"); algo=algo.replace(/R2/,"R R"); algo=algo.replace(/U2/,"U U"); algo=algo.replace(/D2/,"D D"); algo=algo.replace(/B2/,"B B"); algo=algo.replace(/L2/,"L L"); algo=algo.replace(/F'/,"F F F"); algo=algo.replace(/R'/,"R R R"); algo=algo.replace(/U'/,"U U U"); algo=algo.replace(/D'/,"D D D"); algo=algo.replace(/B'/,"B B B"); algo=algo.replace(/L'/,"L L L"); algo=algo.replace(/F/,"y y y R y"); algo=algo.replace(/L/,"y y R y y"); algo=algo.replace(/U/,"x y R y y y x x x"); algo=algo.replace(/B/,"y R y y y"); algo=algo.replace(/D/,"x y y y R y x x x"); algo=algo.split(" "); var cstate=[["R","R","R","R","R","R","R","R","R"],["W","W","W","W","W","W","W","W","W"],["G","G","G","G","G","G","G","G","G"],["Y","Y","Y","Y","Y","Y","Y","Y","Y"],["B","B","B","B","B","B","B","B","B"],["O","O","O","O","O","O","O","O","O"]]; for(var i=0;i<algo.length;++i){ if(algo[i]=="x"){ cstate=x(cstate); }else if(algo[i]=="y"){ cstate=y(cstate); }else if(algo[i]=="R"){ cstate=r(cstate); } } return p(cstate); } function p(cstate){ //Print var out=""; var leftspace="\n "; for(var i=0;i<3;++i){ out+=leftspace+cstate[1][3*i+0]+cstate[1][3*i+1]+cstate[1][3*i+2] } for(var i=0;i<3;++i){ out+="\n"+cstate[5][3*i+0]+cstate[5][3*i+1]+cstate[5][3*i+2]+cstate[2][3*i+0]+cstate[2][3*i+1]+cstate[2][3*i+2]+cstate[0][3*i+0]+cstate[0][3*i+1]+cstate[0][3*i+2]+cstate[4][3*i+0]+cstate[4][3*i+1]+cstate[4][3*i+2] } for(var i=0;i<3;++i){ out+=leftspace+cstate[3][3*i+0]+cstate[3][3*i+1]+cstate[3][3*i+2] } return out; } ``` This was a very difficult challenge. # Explanation Take the example call `s("R U' F")`. The program can only execute x, y and R moves. `U'` is equal to `U U U`, so replace that. `F` is equal to `y y y R y`, so replace that. `R U' F'` is therefore equal to `R U U U y y y R y`, which the program can run. cstate is defined with a solved cube. A cube is represented by an array containing 6 arrays containing the 9 stickers. The first array is for R, second for U, third for F, D, B, last array is for L. When an y needs to be executed, the program swaps the four arrays of the front, left, back and right face. For an x, it swaps front, down, back and top. Every rotation also rotates the other faces, that were not swapped. A R move rotates the right face and swaps the right part of the front, up, back, down face. This could be modified to be able to solve problems with all types of moves, by defining them with x, y and R. [Answer] # C, ~~1715~~ ~~1709~~ ~~1686~~ ~~1336~~ 1328 bytes *25 bytes saved thanks to @KevinCruijssen!* No answers so far, so I decided to put my own solution. ``` #define m(a,b,c,d)t[c][d]=r[a][b]; #define n(a)m(a,0,a,2)m(a,1,a,5)m(a,2,a,8)m(a,3,a,1)m(a,5,a,7)m(a,6,a,0)m(a,7,a,3)m(a,8,a,6) #define y memcpy typedef char R[6][9];R t;F(R r){y(t,r,54);n(0)m(4,6,1,0)m(4,7,1,3)m(4,8,1,6)m(1,0,5,0)m(1,3,5,1)m(1,6,5,2)m(5,0,3,2)m(5,1,3,5)m(5,2,3,8)m(3,2,4,6)m(3,5,4,7)m(3,8,4,8)y(r,t,54);}B(R r){y(t,r,54);n(2)m(1,2,4,0)m(1,5,4,1)m(1,8,4,2)m(3,0,5,6)m(3,3,5,7)m(3,6,5,8)m(4,0,3,6)m(4,1,3,3)m(4,2,3,0)m(5,6,1,8)m(5,7,1,5)m(5,8,1,2)y(r,t,54);}L(R r){y(t,r,54);n(3)m(0,0,5,0)m(0,3,5,3)m(0,6,5,6)m(2,2,4,6)m(2,5,4,3)m(2,8,4,0)m(4,0,0,0)m(4,3,0,3)m(4,6,0,6)m(5,0,2,8)m(5,3,2,5)m(5,6,2,2)y(r,t,54);}E(R r){y(t,r,54);n(1)m(0,2,4,2)m(0,5,4,5)m(0,8,4,8)m(5,2,0,2)m(5,5,0,5)m(5,8,0,8)m(4,2,2,6)m(4,5,2,3)m(4,8,2,0)m(2,0,5,8)m(2,3,5,5)m(2,6,5,2)y(r,t,54);}U(R r){y(t,r,54);n(4)m(0,0,3,0)m(0,1,3,1)m(0,2,3,2)m(1,0,0,0)m(1,1,0,1)m(1,2,0,2)m(2,0,1,0)m(2,1,1,1)m(2,2,1,2)m(3,0,2,0)m(3,1,2,1)m(3,2,2,2)y(r,t,54);}D(R r){y(t,r,54);n(5)m(0,6,1,6)m(0,7,1,7)m(0,8,1,8)m(1,6,2,6)m(1,7,2,7)m(1,8,2,8)m(2,6,3,6)m(2,7,3,7)m(2,8,3,8)m(3,6,0,6)m(3,7,0,7)m(3,8,0,8)y(r,t,54);}a,b,c,d,e,o,p,l;f(char*z,R s){char c[6]="RGOBYW";for(;b<7;b++)for(a=0;a<10;)s[b][a++]=c[b];for(l=strlen(z);l-->0;){d=*z++;if(d-32){e=*z++;if(*z++-32)*z++;o=e-50?e-39?1:3:2;for(p=0;p++<o;)d-70?d-66?d-76?d-82?d-85?D(s):U(s):E(s):L(s):B(s):F(s);}}} ``` [Try it online!](https://tio.run/nexus/bash#lVXbbts4EH3XVxDeDVaMaIeirEtDKQGySfoSoICBZLHQ6kGW5Va@yIatYuEY/vZ0Zki7zXofWsCgjjjkzDmHQ7kqO5am7OHTI7th1ddxPajefpvU06at2dItxVhUYsK7vCrySZFt8rLIx4VmznFN65Yc10lRCkXIBxQSUoASQgEgn1AIKCYUAZKEYkABoQRQxE/Jd2xZL6v1zul26xrmWPWl3LBRHhX5h0KPWKcf3RHb8P3O7cRGhEOuWxdzDiG7LwyKAQWEEkARIIgAD0koAOQTigChAojArEEUJ6QAoRaIiCFlwZ1D0gIRQAnfuRvREYvD3TkvRVVwt6mMu01l3K0oD/IyuTG7yY28EuKPvCJCyMtoQl6SGKLihBAqNqxRsfqR19M5L8wjT45IqmzmIstGnTQrYh0QSqwS5CUtQgWB9V/SDnRTWV7oXWi5qve8Hs55@cRBWW8kVQ4JGbfNqUh7UljnqFlav5C38YvOz/aAIq6KFCeEUHFIyPTAD7yez3kNrV@B9QvP4sjV9I1/csTHLrSnfOSKT99ywLhvHfZPPWAYBjhD0YCUvON1f84rtGdmelxSF8TWL9MZPvlubkAMKLbdp6wPke0viACK7Skf@/54ohABdOx7@b7v7QdD1GIl1mKhpy5e2ctXMWJbvqfrW8H1zXqjj5/u/v6rp6erjavHaazHnsfxpcykLlNfar6FL01eel6RVfjNweAi23abRd26r1wv@v0bWLWfZJevnqebqTvpB4rv69M7PnGK3ldZ3Q/lbd0PPtz618G1ooRrqLb2vHSl@aQfy9tJP4pgiHFIFA7h7b275dfPODzg8ITDHQ6PMOjD4fDWiJmYi6Velk3r/ileOIm@fNF7B3SDCS@5XwhY7Fxdse5Ls2Xwg/JsvWnarmk/D1jD5u3q38Fg4CCtBmg1aZboBlwBJc1FcONzWj11exfVP21PbPNhkTcF1/ViWzOzKP2@iDF2Uf131fprh9Tc06xD5eZQbp5mSs@h3B5nZlmgZ2kW6Zk9FstIaf49x@wCsswvAw9YQi4IbN1eDyxxfkFE@FMiwv8VYWcPDvx9Oc7nqrL/YKy/IuQ4gyt8st7vfu/t7Vmxpz/Y/Tc "Bash – TIO Nexus") Ungolfed old version: ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <ctype.h> typedef char Tile; typedef Tile Face[10]; typedef Face Rubik[7]; void main_loop(Rubik); void rubik_init(Rubik); void rubik_print(Rubik); void rotate(Rubik, char, char); void print_tile(Rubik, int, int); void F(Rubik); void B(Rubik); void L(Rubik); void R(Rubik); void U(Rubik); void D(Rubik); #define move(a, b, c, d) \ temp[c][d] = rubik[a][b] #define move_f(a) \ move(a, 1, a, 3); \ move(a, 2, a, 6); \ move(a, 3, a, 9); \ move(a, 4, a, 2); \ move(a, 6, a, 8); \ move(a, 7, a, 1); \ move(a, 8, a, 4); \ move(a, 9, a, 7) void F(Rubik rubik) { Rubik temp; memcpy(temp, rubik, sizeof(Rubik)); move_f(1); move(5, 7, 2, 1); move(5, 8, 2, 4); move(5, 9, 2, 7); move(2, 1, 6, 1); move(2, 4, 6, 2); move(2, 7, 6, 3); move(6, 1, 4, 3); move(6, 2, 4, 6); move(6, 3, 4, 9); move(4, 3, 5, 7); move(4, 6, 5, 8); move(4, 9, 5, 9); memcpy(rubik, temp, sizeof(Rubik)); } void B(Rubik rubik) { Rubik temp; memcpy(temp, rubik, sizeof(Rubik)); move_f(3); move(2, 3, 5, 1); move(2, 6, 5, 2); move(2, 9, 5, 3); move(4, 1, 6, 7); move(4, 4, 6, 8); move(4, 7, 6, 9); move(5, 1, 4, 7); move(5, 2, 4, 4); move(5, 3, 4, 1); move(6, 7, 2, 9); move(6, 8, 2, 6); move(6, 9, 2, 3); memcpy(rubik, temp, sizeof(Rubik)); } void L(Rubik rubik) { Rubik temp; memcpy(temp, rubik, sizeof(Rubik)); move_f(4); move(1, 1, 6, 1); move(1, 4, 6, 4); move(1, 7, 6, 7); move(3, 3, 5, 7); move(3, 6, 5, 4); move(3, 9, 5, 1); move(5, 1, 1, 1); move(5, 4, 1, 4); move(5, 7, 1, 7); move(6, 1, 3, 9); move(6, 4, 3, 6); move(6, 7, 3, 3); memcpy(rubik, temp, sizeof(Rubik)); } void R(Rubik rubik) { Rubik temp; memcpy(temp, rubik, sizeof(Rubik)); move_f(2); move(1, 3, 5, 3); move(1, 6, 5, 6); move(1, 9, 5, 9); move(6, 3, 1, 3); move(6, 6, 1, 6); move(6, 9, 1, 9); move(5, 3, 3, 7); move(5, 6, 3, 4); move(5, 9, 3, 1); move(3, 1, 6, 9); move(3, 4, 6, 6); move(3, 7, 6, 3); memcpy(rubik, temp, sizeof(Rubik)); } void U(Rubik rubik) { Rubik temp; memcpy(temp, rubik, sizeof(Rubik)); move_f(5); move(1, 1, 4, 1); move(1, 2, 4, 2); move(1, 3, 4, 3); move(2, 1, 1, 1); move(2, 2, 1, 2); move(2, 3, 1, 3); move(3, 1, 2, 1); move(3, 2, 2, 2); move(3, 3, 2, 3); move(4, 1, 3, 1); move(4, 2, 3, 2); move(4, 3, 3, 3); memcpy(rubik, temp, sizeof(Rubik)); } void D(Rubik rubik) { Rubik temp; memcpy(temp, rubik, sizeof(Rubik)); move_f(6); move(1, 7, 2, 7); move(1, 8, 2, 8); move(1, 9, 2, 9); move(2, 7, 3, 7); move(2, 8, 3, 8); move(2, 9, 3, 9); move(3, 7, 4, 7); move(3, 8, 4, 8); move(3, 9, 4, 9); move(4, 7, 1, 7); move(4, 8, 1, 8); move(4, 9, 1, 9); memcpy(rubik, temp, sizeof(Rubik)); } int main(int argc, char *argv[]) { Rubik rubik; rubik_init(rubik); main_loop(rubik); return 0; } void main_loop(Rubik rubik) { char a, b; for (;;) { a=toupper(getchar()); if (a == 'Q') break; if (a != 10) { b=toupper(getchar()); if (b != 10) getchar(); rotate(rubik, a, b); } rubik_print(rubik); } } void rubik_init(Rubik rubik) { int i,n; char c[7] = " RGOBYW"; for (n=1; n<=7; n++) for (i=1; i<=10; i++) rubik[n][i] = c[n]; } void rotate(Rubik rubik, char a, char b){ int i = b == '2' ? 2 : b == '\'' || b == toupper('i') ? 3 : 1; int j; for (j=0; j<i; j++) if (a == 'F') F(rubik); else if (a == 'B') B(rubik); else if (a == 'L') L(rubik); else if (a == 'R') R(rubik); else if (a == 'U') U(rubik); else if (a == 'D') D(rubik); else; } void rubik_print(Rubik rubik) { int i,j,k; for (i=1; i<=9; i++) if (i%3==0) { print_tile(rubik,5,i); printf("\n"); } else if (i%3==1) { printf(" "); print_tile(rubik,5,i); } else print_tile(rubik,5,i); printf("\n"); for (k=1; k<=3; k++) { for (i=3; i<=6; i++) { for (j=k*3-2; j<=k*3; j++) print_tile(rubik, i%4+1, j); printf(" "); } printf("\n"); } printf("\n"); for (i=1; i<=9; i++) if (i%3==0) { print_tile(rubik, 6, i); printf("\n"); } else if (i%3==1) { printf(" "); print_tile(rubik, 6, i); } else print_tile(rubik, 6, i); } void print_tile(Rubik rubik, int a, int b) { switch (rubik[a][b]) { case 'R': printf("R"); break; case 'O': printf("O"); break; case 'B': printf("B"); break; case 'G': printf("G"); break; case 'Y': printf("Y"); break; case 'W': printf("W"); break; default: exit(1); } } ``` [Answer] # Python 3, 528 bytes -7 bytes thanks to my colleague [rhsmits](https://stackoverflow.com/users/9722236/rhsmits) (really nice `d,*c` form & removal of redundant parentheses) This is a full program. ``` import re d,*c=[[f]*9for f in' YBRGOW'] r=lambda f:[f[int(v)]for v in'630741852'] U=lambda c:[r(c[0])]+[c[j%4+1][:3]+c[j][3:]for j in(1,2,3,4)]+[c[5]] y=lambda c:[r(c[0])]+c[2:5]+[c[1],r(r(r(c[5])))] z=lambda c:[c[2],r(r(r(c[1]))),c[5],r(c[3]),c[0][::-1],c[4][::-1]] exec("c="+"(c);c=".join("".join("zzzUz U zzUzz yyyzUzzzy zUzzz yzUzzzyyy".split()[ord(t)%11%7]*(ord(n or'a')%6)for t,n in re.findall("([B-U])(['2i]?)",input())))+"(c)") k=' '.join for q in[d,c[0]],c[1:5],[d,c[5]]: for w in 0,3,6:print(k(k(f[w:w+3])for f in q)) ``` [Superflip](https://en.wikipedia.org/wiki/Superflip) and all tests are available at [**ideone**](https://ideone.com/W1sjcP) or **[Try it online!](https://tio.run/##bVJfa9swEH/3p7gJgqREDbGdpJuGGYTSMQgMDKYMTQ@ZHTOnie3ablN77LOnd0rC@jAJ3elOv/uvuu9@V2V4SqtsG3HOf56KQ101HTRbL1PjNDImt@NPedVADkXJ4ccq/vr9gVuvifabw69sA7k2uSnKTrxIS7gXwi3D2e3c/7gIEJlckak2jUjNzEo7ManZjeYT3xod2gkK1oTa2e/QXvgqUKGan4ELa73@f05SE@iFg/hWNYI2oaWU1hveGSDu37tP74pwisTQkjDDPPQNeknN/HK13vZ1mwqWRmzCRCo/42W6qzA5duXDMCQDJEBsgL7viQ89OAYXqe/ZtK33RSekqZpMdHLk@6NbOxYklVA1fMPlaCmp@E6VWD52f5oXZbbZ7wUTZnWTWCkMDwr7RTJVlPUzOsPl8mLSe4w4cJeTR06e0IXJXFVUkI89Uk7GRmoPCHKkKDNs8VLXDQ3vEXdujvo4wYZcxw1PUp7wV3iei9lCBIa1z/W2yfcfag1JHNyv4lUQJ8GaKL/jqIk5CklwHzAFjE7iSOGoU6450fisgDWHO2Zd5i0FPcfCRHG5@2WSGlqnOyfMv9GTZn/@Mj5F28OmE62UDuEGR19avjOQpzc "Python 3 – Try It Online")** The program: * creates the six faces `YBRGOW` of stickers. * creates a function, `r`, which *only* rotates the stickers on a face, clockwise a quarter-turn * creates a function, `U`, which rotates the `U` face clockwise a quarter-turn by applying `r` and rotating the stickers on the top-band of `LFRB` clockwise a quarter-turn * creates a function, `y`, which performs `r` on the `U` and `D` faces and slices `LFRB` - this performs a rotation of the whole cube in the `y` axis (which runs through `U` and `D`) - the rotation is clockwise if looking from above * creates a function `z`, which performs a rotation of the whole cube in the `z` axis clockwise a quarter turn looking at `R` (the axis runs through `R` and `L`) - this time because the way the faces are oriented in our net (same as given in the OP) we have to flip the `B` and `U` faces over (they switch from the horizontal to vertical parts of the net and vice-versa) * Performs a regex on the input, `input()`, (the moves to be performed) matching a character from `BUDLRF` (actually `B-U`) possibly followed by a character `'i2` * Performs a mapping from the `'i2` to the number of clockwise turns (the ordinals of these mod `6` does the job, with a dummy `a` to yield `1` when none is present) * Performs a lookup to map each of these single clockwise turn instructions to a setup of calls to `y` and `z`, a quarter-turn of `U` (which will now be the face instructed), and then the calls to inverse the sequence of the setup performed. Taking the ordinal of the face character modulo by `11` then by `7` maps `B:0 U:1 D:2 L:3 F:4 R:5`, allowing a simple indexing into a string of the function name sequences split by spaces. * executes the string to actually perform the manoeuvre * creates a dummy face `d` to shorten the printing * prints the result by stepping through the rows in the net and the faces in the row (including a dummy face to the left of each of `U` and `D` Here is the [superflip](https://en.wikipedia.org/wiki/Superflip): ``` D:\Python Scripts>python rubiksAscii.py U R2 F B R B2 R U2 L B2 R U' D' R2 F R' L B2 U2 F2 Y O Y B Y G Y R Y B Y B R Y R G Y G O Y O O B R B R G R G O G O B B W B R W R G W G O W O W R W B W G W O W ``` [Answer] **Python ~~760~~ ~~750~~ 649 Bytes** shamelessly stole the idea of using only 3 rotations from @Paul Schmitz :D new version: ``` from numpy import* c=kron([[32,89,32,32],[66,82,71,79],[32,87,32,32]],ones([3,3])).astype(int) def x():t=copy(c);c[:3,3:6],c[3:6,3:6],c[6:,3:6],c[3:6,9:],c[3:6,:3],c[3:6,6:9]=t[3:6,3:6],t[6:,3:6],rot90(t[3:6,9:],2),rot90(t[:3,3:6],2),rot90(t[3:6,:3]),rot90(t[3:6,6:9],3) def y():c[3:6],c[:3,3:6],c[6:,3:6]=roll(c[3:6],3,1),rot90(c[:3,3:6]),rot90(c[6:,3:6],3) def F():c[2:7,2:7]=rot90(c[2:7,2:7],3) s=raw_input() for p in"':i,Fi:FFF,F2:FF,Bi:BBB,B2:BB,Ri:RRR,R2:RR,Li:LLL,L2:LL,Ui:UUU,U2:UU,Di:DDD,D2:DD,B:xxFxx,R:yyyFy,L:yFyyy,U:xxxFx,D:xFxxx".split(','):s=s.replace(*p.split(':')) for S in s:eval(S+'()') for r in c:print(''.join(chr(x)for x in r)) ``` I mostly just did lots of numpy list slicing and used its built in rotate and roll functions. Input is handled by calling the functions directly with `eval()` ``` from numpy import* l=[0];c=kron([[32,89,32,32],[66,82,71,79],[32,87,32,32]],ones([3,3])).astype(int) def i():l[0]();l[0]() def d():l[0]() def U():c[:3,3:6]=rot90(c[:3,3:6],3);c[3]=roll(c[3],9);l[0]=U def D():c[6:,3:6]=rot90(c[6:,3:6],3);c[5]=roll(c[5],3);l[0]=D def F():c[2:7,2:7]=rot90(c[2:7,2:7],3);l[0]=F def B():c[3:6,9:]=rot90(c[3:6,9:],3);t=copy(c);c[:,:9],c[1:-1,1:8]=rot90(t[:,:9]),t[1:-1,1:8];l[0]=B def R():c[3:6,6:9]=rot90(c[3:6,6:9],3);t=copy(c);c[:6,5],c[3:6,9],c[6:,5]=t[3:,5],t[2::-1,5],t[5:2:-1,9];l[0]=R def L():c[3:6,:3]=rot90(c[3:6,:3],3);t=copy(c);c[3:,3],c[3:6,-1],c[:3,3]=t[:6,3],t[:5:-1,3],t[5:2:-1,-1];l[0]=L for s in raw_input().replace("'",'i').replace('2','d').replace(' ',''):eval(s+'()') for r in c:print(''.join(chr(x)for x in r)) ``` ungolfed.. ``` import numpy as np last = [0] #store last move to repeat for inverse or double #list is shorter syntax than global var cube = np.array([ [' ',' ',' ','Y','Y','Y',' ',' ',' ',' ',' ',' '], [' ',' ',' ','Y','Y','Y',' ',' ',' ',' ',' ',' '], [' ',' ',' ','Y','Y','Y',' ',' ',' ',' ',' ',' '], ['B','B','B','R','R','R','G','G','G','O','O','O'], ['B','B','B','R','R','R','G','G','G','O','O','O'], ['B','B','B','R','R','R','G','G','G','O','O','O'], [' ',' ',' ','W','W','W',' ',' ',' ',' ',' ',' '], [' ',' ',' ','W','W','W',' ',' ',' ',' ',' ',' '], [' ',' ',' ','W','W','W',' ',' ',' ',' ',' ',' '] ]) #ascii ascii codes in golfed version def i(): #triple move (inverse) last[0]() last[0]() def d(): #double move last[0]() def U(): #clockwise upface (yellow) cube[:3,3:6] = np.rot90(cube[:3,3:6],3) cube[3] = np.roll(cube[3],9) last[0] = U def D(): #clockwise downface (white) cube[6:,3:6] = np.rot90(cube[6:,3:6],3) cube[5] = np.roll(cube[5],3) last[0] = D def F(): #clockwise frontface (red) cube[2:7,2:7] = np.rot90(cube[2:7,2:7],3) last[0] = F def B(): #clockwise backface (orange) cube[3:6,9:] = np.rot90(cube[3:6,9:],3) tempCube = np.copy(cube) cube[:,:9],cube[1:-1,1:8] = np.rot90(tempCube[:,:9]),tempCube[1:-1,1:8] last[0] = B def R(): #clockwise rightface (green) cube[3:6,6:9] = np.rot90(cube[3:6,6:9],3) tempCube = np.copy(cube) cube[:6,5],cube[3:6,9],cube[6:,5] = tempCube[3:,5],tempCube[2::-1,5],tempCube[5:2:-1,9] last[0] = R def L(): #clockwise leftface (blue) cube[3:6,:3] = np.rot90(cube[3:6,:3],3) tempCube = np.copy(cube) cube[3:,3],cube[3:6,-1],cube[:3,3] = tempCube[:6,3],tempCube[:5:-1,3],tempCube[5:2:-1,-1] last[0] = L for character in raw_input('type a move sequence: ').replace("'",'i').replace('2','d').replace(' ',''): eval(character+'()') print("-"*12) for row in cube: print(''.join(character for character in row)) #uses ascii codes in golfed version ``` test input: ``` >>> runfile('C:~/rubiks cube.py', wdir='C:~/python/golf') U2 L' D OYY RYY RYY GBBWOOBBBRRY GBBWRRGGGOOY OOYGBBWRRGGG ROO WWW WWW ``` Comments or suggestions are greatly appreciated :) [Answer] # [Cubically](//git.io/Cubically), 2 bytes ``` ¶■ ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P//0LZH0xb8/x@k4GOkEKqu4GKk4GakEAQA) Explanation: ``` ¶ read a line from stdin, evaluate ■ print the cube to stdout ``` --- If extraneous output is allowed, this is an alternative. **1 byte:** ``` ¶ ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P//0Lb//4MUfIwUQtUVXIwU3IwUggA) Cubically automatically dumps its memory cube to `STDERR` when the program ends. However, it also prints the notepad beforehand. [Answer] # C, 839 bytes ``` #include <stdio.h> #define b(c) c,c+1,c+2,c+15,c+28,c+27,c+26,c+13 char a[]=" YYY \n YYY \n YYY \nBBBRRRGGGOOO\nBBBRRRGGGOOO\nBBBRRRGGGOOO\n WWW \n WWW \n WWW \n",k;int d[][8]={b(3),b(39),b(42),b(45),b(48),b(81)},e[][12]={50,49,48,47,46,45,44,43,42,41,40,39,3,16,29,42,55,68,81,94,107,76,63,50,29,30,31,45,58,71,83,82,81,67,54,41,109,96,83,70,57,44,31,18,5,48,61,74,39,52,65,107,108,109,73,60,47,5,4,3,65,66,67,68,69,70,71,72,73,74,75,76},i,*j,r,p,q,s;f(int*g,int h){i=h<0?-1:1;for(j=g;j!=g+h;j+=i){k=a[j[3*h]];for(r=3;r--;)a[j[r*h+h]]=a[j[r*h]];a[*j]=k;}}l(int g,int m){f(d[g+m]-m,m?-2:2);f(e[g+m]-m,m?-3:3);}void n(char*o){while(*o){*o-'U'||(p=0);*o-'L'||(p=1);*o-'F'||(p=2);*o-'R'||(p=3);*o-'B'||(p=4);*o-'D'||(p=5);s=*++o=='\''||*o=='i';q=*o=='2';(s||q)&&o++;l(p,s);q&&l(p,0);}printf("%s",a);} ``` As this is not a full program (function with input from a string argument and output to the console), you need to call it like this: ``` int main() { // n("U2D2R2L2F2B2"); //checker cube n("UDiRL'FBiUD'"); //spotted cube } ``` Use only one call at a time as the function uses and modifies global variables. Ungolfed: ``` #include <stdio.h> char cube[] = " YYY \n" " YYY \n" " YYY \n" "BBBRRRGGGOOO\n" "BBBRRRGGGOOO\n" "BBBRRRGGGOOO\n" " WWW \n" " WWW \n" " WWW \n"; #define faceMove(offset) offset,offset+1,offset+2,offset+15,offset+28,offset+27,offset+26,offset+13 int faceMoves[6][8] = { faceMove(3), //Up faceMove(39), //Left faceMove(42), //Front faceMove(45), //Right faceMove(48), //Back faceMove(81) //Down }, lineMoves[6][12] = { 50,49,48,47,46,45,44,43,42,41,40,39, //Up 3,16,29,42,55,68,81,94,107,76,63,50, //Left 29,30,31,45,58,71,83,82,81,67,54,41, //Front 109,96,83,70,57,44,31,18,5,48,61,74, //Right 39,52,65,107,108,109,73,60,47,5,4,3, //Back 65,66,67,68,69,70,71,72,73,74,75,76 //Down }; int rotate(int*move,int rotation){ int sign=rotation<0?-1:1; for(int*submove=move;submove!=move+rotation;submove+=sign){ char takeout=cube[submove[3*rotation]]; for(int j=3;j--;)cube[submove[j*rotation+rotation]]=cube[submove[j*rotation]]; cube[*submove]=takeout; } } int move(int move,int inverted){ rotate(faceMoves[move+inverted]-inverted,inverted?-2:2); rotate(lineMoves[move+inverted]-inverted,inverted?-3:3); } void performMoves(char*instructions){ while(*instructions){ int moveIndex; *instructions-'U'||(moveIndex=0); *instructions-'L'||(moveIndex=1); *instructions-'F'||(moveIndex=2); *instructions-'R'||(moveIndex=3); *instructions-'B'||(moveIndex=4); *instructions-'D'||(moveIndex=5); int inverted=*++instructions=='\''||*instructions=='i', twice=*instructions=='2'; (inverted||twice)&&instructions++; move(moveIndex,inverted); twice&&move(moveIndex,0); } printf("%s",cube); } int main() { // performMoves("U2D2R2L2F2B2"); //checker cube performMoves("UDiRL'FBiUD'"); //spotted cube } ``` As you can see, the main idea is to use a fully data-driven approach: The different rotations are expressed as lists of indices that have to be permuted. The permutation code can thus be very short and generic. [Answer] # JavaScript (ES6), 820 A porting of the buggy answer by @Paul Schmitz. It's still not completely golfed, but it has the added value that it works. The main problem in the original answer is that a single function Q is not enough for all the movements involved in a rotation. I had to add 2 other functions O and N. All of them are just called in the right rotation function R. ``` (a,M=a=>[a[6],a[3],a[0],a[7],a[4],a[1],a[8],a[5],a[2]],Q=(a,b)=>[b[0],b[1],a[2],b[3],b[4],a[5],b[6],b[7],a[8]],N=(a,b)=>[b[0],b[1],a[6],b[3],b[4],a[3],b[6],b[7],a[0]],O=(a,b)=>[b[8],a[1],a[2],b[5],a[4],a[5],b[2],a[7],a[8]],R=a=>[M(a[0]),Q(a[2],a[1]),Q(a[3],a[2]),N(a[4],a[3]),O(a[4],a[1]),a[5]],X=a=>[M(a[0]),a[2],a[3],M(M(a[4])),M(M(a[1])),M(M(M(a[5])))],Y=a=>[a[4],M(a[1]),a[0],M(M(M(a[3]))),a[5],a[2]],F=c=>Array(9).fill(c[0]),r='replace',b=[F`G`,F`Y`,F`R`,F`W`,F`O`,F`B`],J=(p,l)=>p.join``[r](/.../g,l))=>(a[r](/(.)2/g,"$1$1")[r](/(.)['i]/g,"$1$1$1")[r](/F/g,"yyyRy")[r](/L/g,"yyRyy")[r](/B/g,"yRyyy")[r](/U/g,"xyRyyyxxx")[r](/D/g,"xyyyRyxxx")[r](/\w/g,c=>b=(c<'a'?R:c<'y'?X:Y)(b)),o=J(b[1],` $&`),J(b[5],(c,p)=>o+=` `+c+b[2].join``.substr(p,3)+b[0].join``.substr(p,3)+b[4].join``.substr(p,3)),o+J(b[3],` $&`)) ``` *More readable* maybe ``` ( a, // local variables as default parameters r='replace', F=c=>Array(9).fill(c[0]), // function to fill a 3x3 square b=[F`G`,F`Y`,F`R`,F`W`,F`O`,F`B`], // cube status // aux functions to perform basic moves M=a=>[a[6],a[3],a[0],a[7],a[4],a[1],a[8],a[5],a[2]], Q=(a,b)=>[b[0],b[1],a[2],b[3],b[4],a[5],b[6],b[7],a[8]], N=(a,b)=>[b[0],b[1],a[6],b[3],b[4],a[3],b[6],b[7],a[0]], O=(a,b)=>[b[8],a[1],a[2],b[5],a[4],a[5],b[2],a[7],a[8]], // R : right side rotation R=a=>[M(a[0]),Q(a[2],a[1]),Q(a[3],a[2]),N(a[4],a[3]),O(a[4],a[1]),a[5]], // X,Y: to put other sides in place of right side X=a=>[M(a[0]),a[2],a[3],M(M(a[4])),M(M(a[1])),M(M(M(a[5])))], Y=a=>[a[4],M(a[1]),a[0],M(M(M(a[3]))),a[5],a[2]], // aux function for output J=(p,l)=>p.join``[r](/.../g,l), ) => ( // convert common moves to basic moves a[r](/(.)2/g,"$1$1")[r](/(.)['i]/g,"$1$1$1")[r](/F/g,"yyyRy")[r](/L/g,"yyRyy")[r](/B/g,"yRyyy")[r](/U/g,"xyRyyyxxx")[r](/D/g,"xyyyRyxxx") // then execute each [r](/\w/g,c=>b=c<'a'?R(b):c<'y'?X(b):Y(b)), // built output in o o=J(b[1],'\n $&'), J(b[5],(c,p)=>o+='\n'+c+b[2].join``.substr(p,3)+b[0].join``.substr(p,3)+b[4].join``.substr(p,3)), o+J(b[3],'\n $&') // returned output ) ``` ``` S= (a,M=a=>[a[6],a[3],a[0],a[7],a[4],a[1],a[8],a[5],a[2]],Q=(a,b)=>[b[0],b[1],a[2],b[3],b[4],a[5],b[6],b[7],a[8]],N=(a,b)=>[b[0],b[1],a[6],b[3],b[4],a[3],b[6],b[7],a[0]],O=(a,b)=>[b[8],a[1],a[2],b[5],a[4],a[5],b[2],a[7],a[8]],R=a=>[M(a[0]),Q(a[2],a[1]),Q(a[3],a[2]),N(a[4],a[3]),O(a[4],a[1]),a[5]],X=a=>[M(a[0]),a[2],a[3],M(M(a[4])),M(M(a[1])),M(M(M(a[5])))],Y=a=>[a[4],M(a[1]),a[0],M(M(M(a[3]))),a[5],a[2]],F=c=>Array(9).fill(c[0]),r='replace',b=[F`G`,F`Y`,F`R`,F`W`,F`O`,F`B`],J=(p,l)=>p.join``[r](/.../g,l))=>(a[r](/(.)2/g,"$1$1")[r](/(.)['i]/g,"$1$1$1")[r](/F/g,"yyyRy")[r](/L/g,"yyRyy")[r](/B/g,"yRyyy")[r](/U/g,"xyRyyyxxx")[r](/D/g,"xyyyRyxxx")[r](/\w/g,c=>b=(c<'a'?R:c<'y'?X:Y)(b)),o=J(b[1],` $&`),J(b[5],(c,p)=>o+=` `+c+b[2].join``.substr(p,3)+b[0].join``.substr(p,3)+b[4].join``.substr(p,3)),o+J(b[3],` $&`)) function update() { O.textContent=S(I.value) } update() ``` ``` <input id=I value='U2 Li D' oninput='update()'><pre id=O></pre> ``` ]
[Question] [ I was reading [Print your code backwards - reverse quine](https://codegolf.stackexchange.com/questions/16021/print-your-code-backwords-reverse-quine) And I thought, this could be more interesting if your **backwards code is also executable**. So this challenge will have all the rules and requirements of the other, but must also be valid source once reversed (in the same or another language and still print its source backwards). All rules and scoring from the reverse quine challenge apply, so all answers to this question will answer that one (but not score as well). ## Rules: * Write a program p which when executed produces output p' where p' is p backwards and p' when executed produces p. * No using other files (e.g. `reverse.txt`) * Minimum code length is two characters. * **Your program cannot be a palindrome.** ## Scoring: * +50 if you use pull data from the Internet. * +25 if you read your own source code. * +1 point per character. * Lowest score wins. [Answer] ## GolfScript, 46 chars ``` 0{`".~#"+.-1%+\.!@@}.~##~.}@@!.\+%1-.+"#~."`{1 ``` Well, this is ugly, but it works. The output equals the code reversed, and is also a valid GolfScript program which outputs the original code again. OK, let me try to explain how I constructed it. First, I started from the quine `{".~"}.~`, and modified it as in [this answer](https://codegolf.stackexchange.com/questions/16021/print-your-code-backwards-reverse-quine/16040#16040) to reverse itself. To make the output an executable quine in itself, I made a copy of the code before reversing it, and included a `#` at the end of the code, so that the reversed version at the end became just a comment. Thus, we get the palindromic quine: ``` {`".~#"+.-1%}.~##~.}%1-.+"#~."`{ ``` However, by the rules, palindromes are not allowed, so I needed to break the symmetry somehow. I figured the easiest way would be to include a `0` (which, in itself, is a quine in GolfScript) in the code and flip it to `1` with `!` after creating the reversed copy. Most of the remaining complexity is just ugly stack manipulation to get everything in the right order. [Answer] ## Perl and C ~~6478~~ 1955 ``` #!/usr/bin/perl -i// $_=<<'rahc';eval $_; #// print scalar reverse "#!/usr/bin/perl -i//\n\$_=<<'rahc';eval \$_; #//\n${_}rahc\n" #// __END__ __END__ enifed# };)"{ = ][cn\rahcn\n\"(p };)'n\'( rahctup) 1 == 21%b ( fi ;)d(p;)]1-b[c,",d%",)d(foezis,d( ftnirpns{)b--;b;)c(foezis=b( rof ;)c(p;]9[d rahc;b tni{)(niam diov }};)]1-b[c(rahctup )]1-b[c(fi{)b--;b;)c(nelrts=b(rof;b tni{)c*rahc(p diov >h.gnirts< edulcni# >h.oidts< edulcni# ;} ,0 ,53,33,74,711,511,411,74,89,501,011,74,211 ,101,411,801,23,54,501,74,74,01,63,59,16 ,06,06,93,411,79,401,99,93,95,101,811,79 ,801,23,63,59,95,23,53,74,74,01,211,411 ,501,011,611,23,511,99,79,801,79,411,23,411 ,101,811,101,411,511,101,23,43,53,33,74,711 ,511,411,74,89,501,011,74,211,101,411,801,23 ,54,501,74,74,29,011,29,63,59,16,06,06 ,93,411,79,401,99,93,95,101,811,79,801,23 ,29,63,59,95,23,53,74,74,29,011,63,321 ,59,521,411,79,401,99,29,011,43,23,53,74 ,74,01,59,59,96,87,86,59,59,01,59,59 ,96,87,86,59,59,23,101,011,501,201,101,001 ,53,01,521,95,14,43,321,23,16,23,39,19 ,99,011,29,411,79,401,99,011,29,011,29,43 ,04,211,01,521,95,14,93,011,29,93,04,23 ,411,79,401,99,611,711,211,14,23,94,23,16 ,16,23,05,94,73,89,23,04,23,201,501,01 ,95,14,001,04,211,95,14,39,94,54,89,19 ,99,44,43,44,001,73,43,44,14,001,04,201 ,111,101,221,501,511,44,001,04,23,201,611,011 ,501,411,211,011,511,321,14,89,54,54,95,89 ,95,14,99,04,201,111,101,221,501,511,16,89 ,04,23,411,111,201,01,95,14,99,04,211,95 ,39,75,19,001,23,411,79,401,99,95,89,23 ,611,011,501,321,14,04,011,501,79,901,23,001 ,501,111,811,01,521,521,95,14,39,94,54,89 ,19,99,04,411,79,401,99,611,711,211,23,14 ,39,94,54,89,19,99,04,201,501,321,14,89 ,54,54,95,89,95,14,99,04,011,101,801,411 ,611,511,16,89,04,411,111,201,95,89,23,611 ,011,501,321,14,99,24,411,79,401,99,04,211 ,23,001,501,111,811,01,26,401,64,301,011,501 ,411,611,511,06,23,101,001,711,801,99,011,501 ,53,01,26,401,64,111,501,001,611,511,06,23 ,101,001,711,801,99,011,501,53,01,95,521,01 { = ][c rahc ``` # Edit: Brief explanation: from perl the two interesting lines are the second and the third. The second line has two statements the first of which reads the rest of the document into a string. The second evals the string. The Third line prints everything backwards. every thing else gets ignored. from the c side you have an array which has the program as a string, which gets printed as an array and a string, and the rest is a comment. [Answer] # Ruby 145 ``` DATA.read.tap{|a|puts a.reverse,a.tr("\x79\x59","\x59\x79")} :y __END__ __DNE__ Y: })"97x\95x\","95x\97x\"(rt.a,esrever.a stup|a|{pat.daer.ATAD ``` The main idea is simple: just put the first half of the source code backwards after the `__END__` which can be read using `DATA` from ruby. Then just print the reverse of this data, then print the data, and you get back the original source code The problem is, that this becomes a palindrome (note that the first line needs an endline), so we have to break the symmetry. I just added a symbol `:y` to the code, and some code that will transform this symbol between lowercase and uppercase between runs, thereby reverting to the original state after two runs. Test one: they can be executed ``` $ ruby rq2.rb > rq2t.rb $ ruby rq2t.rb > rq2tt.rb ``` Test two: the result of two runs will return the original source ``` $ diff rq2.rb rq2tt.rb $ ``` Test three: the code is not a palindrome (the middle run is different) ``` $ diff rq2.rb rq2t.rb 3c3 < :y --- > :Y 6c6 < Y: --- > y: ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 11 bytes ``` ":5-}H}+5:' ``` A whole byte chopped off! it almost is a palindrome, but technically isn't because of the '+' and '-', haha! [Try it online!](https://tio.run/##S8/PScsszvj/X8nKVLfWo1bb1Er9/38A "Gol><> – Try It Online") **The two below don't work, or at least they don't meet the specifications of the challenge, but the code above does.** **slightly younger version, 12 bytes** ``` "r2ssrH}+5:' ``` Golfed off a byte, simply by using the double quote and incrementing it by 5! And this new version looks less like a palindrome. [Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLi4yKNW29RK/f9/AA "Gol><> – Try It Online") **older version, 13 bytes** ``` "r2ssrHrss7r' ``` There was a problem with the previous that JoKing pointed out, thank you for that, now it works, but with the price of 4 extra bytes... [Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLi4yKOouNi8SP3/fwA "Gol><> – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 99 bytes ## forward : ``` a=1;exec(s:=#)]a::[ "print(('a=1;exec(s:=#)]a::[\\n%r\\n)#=:s(cexe;1-=a'%s)[::-a])" )#=:s(cexe;1-=a ``` [Try it online!](https://tio.run/##bY2xCsMgFEV3P@OFEF@JUNulvOCXGAexQrsY0Qwppd9utB0KpctdzuWc@FhvSzhfYipuuXqVAKBYJSe/ecczqQ6NJdIMYrqHlfPhD5zn0Kc62CnK3FU6SaHs0GfURMIaBPbDSu1oSUIaxt62Vh@fL2SfDgg4nI74ZU0kTXuUHQ "Python 3.8 (pre-release) – Try It Online") ## backward: ``` a=-1;exec(s:=#) ")]a-::[)s%'a=-1;exec(s:=#)n\\r%n\\[::a])#=:s(cexe;1=a'((tnirp" [::a])#=:s(cexe;1=a ``` [Try it online!](https://tio.run/##bY2xCsMgFEV3P@OFEF@JUNulvOCXGAexQrMYUYeU0m83pkuhdLnLuZwTn@WxhustpurWu1cJAKpVQk5@845nUh0yQGMFkcbcDz8szHPq22gia7BTlLlrdJLKDpyXsKQI7A@sraMlCWkY@9iO@vh6I4tpCYWDgNPljF/WHO18POoO "Python 3.8 (pre-release) – Try It Online") ## How it works: I based my solution on the quine `exec(s:="print('exec(s:=%r)'%s)")` * In the forward solution, `a=1` transforms the slices to have something like : ``` exec(s:="print('<string for the quine>'[::-1])") ``` which prints the backward quine * in the backward solution, `a=-1` transforms the slice to have something like : ``` exec(s:=")]1::['<string for the quine in backward>'(tnirp"[::-1]) ``` which (due to the `[::-1]`) gives: ``` exec(s:="print('<string for the quine>'[::1])") ``` and prints the original quine [Answer] # ><>, ~~21~~ 19 bytes ``` 'rd3*70.r l?!;o90.< ``` [Try it here!](http://portal.thedisco.zone/starfish/?script=OQJwJgzAVA7ADAOhAAgDYH4CEBuA9gTkQB4g) Uses the \*><> interpreter for convenience, but this is valid ><> code. --- If erroring out is allowed, then it can be done in 16 bytes: ``` 'd3*}70.!r !|o| ``` [Try it here!](http://portal.thedisco.zone/starfish/?script=OQEwzAVAvg7ADAOgIQCcAEakB8D2Wg) [Answer] # [Help, WarDoq!](https://esolangs.org/wiki/Help,_WarDoq!) (27 bytes) 25 bytes added because of reading source code. ``` <space>q ``` How it works: `<space>` - a comment that ends on non-space character `q` - print source code reversed (q"space") ### Reversed: ``` q<space> ``` How it works: `q` - print source code reversed (q for now) `<space>` - a comment that ends on non-space character, and add a character to beginning of q command (making "space"q) [Answer] # [JavaScript (V8)](https://v8.dev/), 817 bytes I'm sure this can be golfed further. I might also try to translate this into Python. ``` //))""(nioj.)(esrever.])q+s+q(nioj.))53(edoCrahCmorf.gnirtS(tilps.)c,)63(edoCrahCmorf.gnirtS(ecalper.)q+c+q,)33(edoCrahCmorf.gnirtS(ecalper.))""(nioj.)(esrever.]c...[,)621(edoCrahCmorf.gnirtS(ecalper.s...[(gol.elosnoc c=// `console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))//` //=c s=// `~ c=// ! //=c s=// # //=s q=String.fromCharCode(96)// //)69(edoCrahCmorf.gnirtS=q $` //=s q=String.fromCharCode(96)// //)69(edoCrahCmorf.gnirtS=q console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))// ``` [Try it online!](https://tio.run/##3ZExb4MwEIV3/kVpB5@gZyUoKBmY@AkZo0hYjkOMHBt8iLF/nRqaoYOVDN26WafvvXfv3IlJkPS6Hz@n/TxzDpCmzGrXITBFXk3K4xmGjLLhMYZdwdTF1V7c6rvzV2yt9uORjdr0hCBzKOOAksL0wS64yWzIoXiBxTaRiHgKCdvNUy0tGGudQWUcWScTWXGeNNJZckahcS07BYbQq94Iqdhx9Nq2ePXuXt@Er91Fsc22hHzB5BnXfFIMsHPasjQFeKotCsjXni@wkCABqTd6jAM7eESufwDRTThvEs4rmdDa8uun7duv2fvypmSoYhmHMjgEAMpD7KrVkHw0f9P/27vP8zc "JavaScript (V8) – Try It Online") ## How? Line comments at the end of the line comment out that line in the reversed version. Although the entire program is not a palindrome, it is made up of several palindromic or semi-palindromic sections. These are not true palindromes, but are [close enough](https://www.youtube.com/watch?v=522Ls_hLGjQ). ``` // This line is the last line reversed //))""(nioj.)(esrever.])q+s+q(nioj.))53(edoCrahCmorf.gnirtS(tilps.)c,)63(edoCrahCmorf.gnirtS(ecalper.)q+c+q,)33(edoCrahCmorf.gnirtS(ecalper.))""(nioj.)(esrever.]c...[,)621(edoCrahCmorf.gnirtS(ecalper.s...[(gol.elosnoc // This is a palindrome (apart from the string in the middle) c=// `console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))//` //=c // This is a palindrome (apart from the string in the middle) s=// `~ c=// ! //=c s=// # //=s q=String.fromCharCode(96)// //)69(edoCrahCmorf.gnirtS=q $` //=s // This is also a palindrome q=String.fromCharCode(96)// //)69(edoCrahCmorf.gnirtS=q // This line is the first line reversed console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))// ``` Apart from this, it's a pretty standard quine. Writing the code twice, once in code and once in a string, and substituting the string into itself is a common quine technique. [Answer] # [Julia](https://julialang.org), ~~194~~ 177 bytes ``` ~=reverse;(s= #lave>|esrap.ateM>|)) "print(~\"~=reverse;(s= #lave>|esrap.ateM>|))\\n\$(~repr(~s))\\n)|>Meta.parse|>eval#(esrever=s(;* =~\")" )|>Meta.parse|>eval#(esrever=s(;* =~ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZFBCoMwEEX3OYWoi4lQ1wWJN-gNssliCpYQwiS6CrlIN248QA_RQ_Q2NVbpRtDdDPz_eX_mOT163alxnHp_v1w_rygIBySHDTiRFVoN2AZ0pGytPN7awDnLLXXGQ5T5CbWURpYQCS1BdMvOQ3tDr2qrZmdocVC6gNmVooSDpsrEnM1zdka4gr8XJm2As_8URVYlshUS9gBZzlOPY6GRknMXgSxSBFku-w5glsg2yHQj8KYjO7c5Vv_KbN_4Ag) port of [Jakque's answer](https://codegolf.stackexchange.com/a/235337/98541), Julia is not very good at quines **previous answer, 194 bytes:** [`(q=:(print(replace((k = "(q=:($(q)))|>eval#") |> (*), 'q' => :Q, 'Q' => :q), reverse(k))))|>eval##lave>|))))k(esrever ,)Q: >= 'q' ,q: >= 'Q' ,)*( >| )"#lave>|)))Q($(:=Q(" = k((ecalper(tnirp(:=Q(`](https://ato.pxeger.com/run?1=ZU9BasMwELz7FYtSyG5wCrkVgfSDHnQuPQhnC66FKymOezHkIbn4klN_0V_kN5HlpknpaYfZmWHmeHrfu9qOX9XHllW0n0KI0757Wz-dvzEoiT7WbYeRvbMVIzagQOTHAwYiGjT31i0EwaABV1TCMixBaZAmQTPDkOjIPccdY0M318LZnvUwMQ3yLkugJCNBq5xThhmmnJJWCHoAEjeXSSWkMihSqQaRK-s8R-zaOvr8-FlySKNeNpLb7XrzWhR5kmvxWmmaTlRMlfCZO_vo7R19Vd-jX5g1_5x_g6mYa4zjfC8) based on [this quine](https://codegolf.stackexchange.com/a/92455), by appending the reversed program in a comment, and switching between lowercase and uppercase `Q` so it's not a palindrome ]
[Question] [ **The Challenge** Your task is to create a program that takes any given string input, and outputs the input in a squared format. Empty strings should return an empty string. **Examples** Given the input: ``` golf ``` Your program should output: ``` golf o l l o flog ``` Input: ``` 123 ``` Output: ``` 123 2 2 321 ``` Input: ``` a ``` Output: ``` a ``` Input: ``` Hello, world! ``` Output (notice the space between the , and w - the gap is not just a newline): ``` Hello, world! e d l l l r o o , w w , o o r l l l d e !dlrow ,olleH ``` **Scoring** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~7~~ 5 bytes ``` θ‖O↙↘ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRKNQ05orKDUtJzW5xL8stSgnsUDDyiW/PM8nNa1ERwHMDMpMzyjRtP7/Pz0/J@2/btl/3eIcAA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @CarlosAlejo. Explanation: ``` θ Print the input string, making the top row ‖O Reflect with overlap... ↙ ... down and left, to create the left side ↘ ... down and right, to create the bottom and right sides ``` (Multiple directions to the Reflect command run consecutively rather than simultaneously.) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~20~~ ~~16~~ 11 bytes ``` otYTO6Lt&(c ``` Try it at [**MATL online!**](https://matl.io/?code=otYTO6Lt%26%28c&inputs=%27Hello%2C+world%21%27&version=20.2.1) *EDIT: The code works in release 20.2.1, which predates the challenge. The link uses that release. (In 20.2.2 the code would be shorter, but it postdates the challenge).* ### Explanation ``` o % Implicitly input a string. Convert chars to ASCII codes t % Duplicate YT % 2-input Toeplitz matrix O % Push 0 6L % Push predefined literal [2, -1+1j]. When used as an index, this is % interpreted as 2:end-1 (indexing is 1-based) t % Duplicate &( % 4-input assignment indexing. This writes 0 at the square formed by % rows 2:end-1 and columns 2:end-1 c % Convert to char. Char 0 is shown as space. Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29 22~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *[Charcoal](https://github.com/somebody1234/Charcoal) ~~will~~ [trounce+d](https://codegolf.stackexchange.com/a/133677/53748) this score...* ``` J⁶ẋa0,1¦"ṚṚ;$ṖŒḌY ``` A monadic link taking and returning a lists of characters; or a full program printing the result. **[Try it online!](https://tio.run/##y0rNyan8/9/rUeO2h7u6Ew10DA8tU3q4cxYQWas83Dnt6KSHO3oi////r1SekZ@TqgQA "Jelly – Try It Online")** ### How? ``` J⁶ẋa0,1¦"ṚṚ;$ṖŒḌY - Link: list of characters, w e.g. "whole" ⁶ - literal space character ' ' J - range(length(w)) [1,2,3,4,5] ẋ - repeat [" "," "," "," "," "] Ṛ - reverse w "elohw" " - zip with: ¦ - sparse application of: a - and (vectorises) 0,1 - to indexes: [0,1] (last and 1st) ["e","ll","o o","h h","w w"] $ - last two links as a monad: Ṛ - reverse ["w w","h h","o o","ll","e"] ; - concatenate ["w w","h h","o o","ll","e","e","ll","o o","h h","w w"] Ṗ - pop (remove last entry) ["w w","h h","o o","ll","e","e","ll","o o","h h"] ŒḌ - reconstruct matrix from diagonals ["whole","h l","o o","l h","elohw"] Y - join with newlines "whole\nh l\no o\nl h\nelohw" - if running as a full program implicit print ``` [Answer] ## C, 109 bytes ``` i,j;f(char*s){for(i=j=printf("%s\n",s)-2;1[++s];)printf("%c%*c\n",*s,i,s[j-=2]);for(;*s*~i--;)putchar(*s--);} ``` [Try it online!](https://tio.run/##PcxBDsIgEEDRqxCSJgxlFnY74SS1CxxFIRENU1dNvTqWjev/8xjvzK0llykafoRqBbb4qib57N81lTUaPci5aCeAE53mcZSF4J94sNyrFZeczBn9tAB1gazYb0I85s/aaWMFEWhvz5CKAbWpAwgXvt40kNrbDw "C (gcc) – Try It Online") Noteworthy tricks: * Instead of wasting bytes on `strlen`, we simply grab the length of the string while simultaneously printing the first line: ``` i=j=printf("%s\n",s)-2 ``` This works because `printf` returns the number of bytes written. * For the middle lines, we need to loop over the string but exclude both the first and last character. This is achieved with the condition ``` 1[++s] ``` (which is shorter than `(++s)[1]`), which skips the first character due to the `++`'s being in the condition and skips the last one by stopping when the character past the current character is `'\0'` (rather than stopping *at* `'\0'`). * In the body of the first loop, ``` printf("%c%*c\n",*s,i,s[j-=2]) ``` we print the current character, then the appropriate "mirrored" character (keeping track with `j`, which does go into the negatives, resulting in the odd situation of indexing into a string with a negative number) padded to a length of `i` with spaces (where `i` is conveniently `strlen(s) - 1`). * The reversed printing on the last line is pretty straightforward; the only trick is the `*s*~i--`, which is the shortest way to get `i+2` iterations of the loop body (which doesn't depend on `i`; all `i` is used for is to count). The funky `*s*` part makes sure the loop doesn't run if `*s` is `'\0'`, which happens on length-1 input. [Answer] # Octave, 40 bytes ``` @(s,t=toeplitz(s),u=t(x=2:end-1,x)=32)t; ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNYp8S2JD@1ICezpEqjWFOn1LZEo8LWyCo1L0XXUKdC09bYSLPE@n9iXrGGUnp@TpqS5n8A "Octave – Try It Online") It is my answer but posted after @Luis [MATL answer](https://codegolf.stackexchange.com/a/133659/62451) [Answer] # [Haskell](https://www.haskell.org/), ~~84~~ 78 bytes ``` f s@(_:x)|_:y<-r x=s:[a:(y>>" ")++[b]|(a,b)<-zip x y]++[r s];f s=[s] r=reverse ``` [Try it online!](https://tio.run/##Dc1BCoMwEEDRfU8xiIsEaw@QGuk9QpBYRgxNU5mxJRHvnmb74fFXxy8MoZQF@CEmleQ5qTz0BEmzMk6JPI4NNLLrzGxP4a6zHPrDb5Ag2xoJ2N4r1obthTThD4mxvJ2PoMHHHck9d2jhG4OPyLelrHX4@QM "Haskell – Try It Online") Usage: `f "test"`. Returns a list of lines. **Edit:** -6 bytes thanks to dianne! [Answer] # [Python 2](https://docs.python.org/2/), ~~89~~ ~~81~~ ~~88~~ 86 bytes ``` i=input();n=k=len(i)-2 print i exec'print i[~k]+" "*n+i[k];k-=1;'*n if~k:print i[::-1] ``` [Try it online!](https://tio.run/##NcqxCoAgEADQ3a@QFktx0FHxS8IpjI6LS8OgFn/dlhofvPzU7SDbOwSgfNVx8hQw7IlGmLRl@QSqHFi60yI@zA2jGvggScGM0aMOxgtJDNaG7k/OaRN7F6WIFw "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 113 bytes ``` function(s){n=length(s<-strsplit(s,'')[[1]]) m=matrix(' ',n,n) m[n,n:1]=m[,1]=m[1,]=m[n:1,n]=s write(m,'',n,,'')} ``` [Try it online!](https://tio.run/##HYwxCgIxEEX7PcVazQTGIq2Y3htYhBSiGw0kE8nMoiCePWZt3ofH57UeXY8rXzVVRjEfdnnhuz5QjnvRJs@cFIUAjPc2BDMVVy7a0hthBmLiYfyYgw2uePrT0sahiIOT6dWSLlhGY/y30rdHhNOSc6X5XFu@7cD0Hw "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ ~~15~~ 19 bytes ``` ÂDÂø¦¨Dgú€Ás)˜»Igi¨ ``` [Try it online!](https://tio.run/##ASsA1P8wNWFiMWX//8OCRMOCw7jCpsKoRGfDuuKCrMOBcynLnMK7SWdpwqj//2Fi "05AB1E – Try It Online") **Explanation** Example with `input = golf` ``` ÂD # bifurcate, duplicate, bifurcate # STACK: 'golf', 'flog', 'flog', 'golf' ø # zip the top 2 items # STACK: 'golf', 'flog', ['fg', 'lo', 'ol', 'gf'] ¦¨ # remove the first and last element # STACK: 'golf', 'flog', ['lo', 'ol'] Dg # get the length of the list # STACK: 'golf', 'flog', ['lo', 'ol'], 2 ú # prepend that many spaces to each element # STACK: 'golf', 'flog', [' lo', ' ol'] €Á # rotate each right # STACK: 'golf', 'flog', ['o l', 'l o'] s # swap the top 2 items # STACK: 'golf', ['o l', 'l o'], 'flog' )˜ # wrap in a flattened list # STACK: ['golf', 'o l', 'l o', 'flog'] » # join on newline Igi¨ # if input is length 1, remove last char ``` The fix for 1-letter input was quite expensive. I feel like a different approach might be better now. [Answer] # Python 3, 88 bytes ``` w=input();p=print;l=len(w)-2 [p(w[n+1]+' '*l+w[l-n])for n in range(l)] l+1and p(w[::-1]) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~99~~ 88 bytes *-4 bytes thanks to musicman523.* ``` lambda s:s[1:]and[s]+[s[i]+' '*(len(s)-2)+s[~i]for i in range(1,len(s)-1)]+[s[::-1]]or s ``` [Try it online!](https://tio.run/##LcuxDsIgEIDhVzknwLYmdCRx9w060BswgJ7Bo@G6uPjqaIzz//3ba79Xnns@r72E5zUGECfeOgwcveDgxRMOCtRRl8RazDSbQfybMNcGBMTQAt@StuO/W/O7nJss4tdI3xrxDmpldXpUYp21uqRS6ghLbSUelDH9Aw "Python 2 – Try It Online") Returns a list of strings. [Answer] # Mathematica, 128 bytes ``` (c=Column;g=Length[x=Characters@#]-1;If[g==0,#,c@{#,c@Table[""<>{x[[i]],""<>Table[" ",g-1],x[[-i]]},{i,2,g}],StringReverse@#}])& ``` [Answer] # C, 96 bytes ``` i,l;f(char*s){for(i=l=puts(s)-2;--i;)printf("%c%*c\n",s[l-i],l,s[i]);for(;l+1;)putchar(s[l--]);} ``` Bonus version (122 bytes): ``` x,y,i,l;f(char*s){for(i=l=puts(s)-1;++i<l*-~l;putchar(x==l?10:x%~-l*(y%~-l)?32:s[(x*y?l+l-2-x-y:x+y)%l]))x=i%-~l,y=i/-~l;} ``` [Answer] # [Swift 3](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html), ~~215~~ 199 bytes ``` let s=readLine()!,c=s.characters,r:[Character]=c.reversed(),b=c.count print(s) if b>1{for i in 0..<b-2{print("\(r.reversed()[i+1])\(String.init(repeating:" ",count:b-2))\(r[i+1])")};print(String(r))} ``` [Try it online](http://swift.sandbox.bluemix.net/#/repl/5972645d4d6fc06b79b9e5d0) [Answer] # JavaScript (ES8), ~~108~~ 112 bytes ``` let f = s=>(n=s.length)<2?s:(r=[...s].reverse()).slice(1,-1).reduce((a,v,i)=>a+` `+s[i+1].padEnd(n-1)+v,s)+` `+r.join`` o.innerHTML = f("hello folks!") ``` ``` <pre id="o"></pre> ``` **Less golphed** ``` s=> (n=s.length) < 2 ? // record and check length s : // s has 0 or 1 char, else (r=[...s].reverse()) // reverse characters, .slice(1,-1) // exclude 1st and last .reduce((a,v,i)=> // append inner lines a +'\n' +s[i+1].padEnd(n-1) + v ,s) // to first line + '\n' +r.join("") // append characters reversed ``` Thanks to Justin Mariner for saving lots of bytes, which then all got used up adding the zero or single character check needed to comply with the challenge. You get that :-( [Answer] # [PHP](http://php.net/), 118 bytes ``` echo $s=$argv[1];$l=strlen($r=strrev($s))-1;for($i=$l-1;$l&&$i;)echo "\n".str_pad($r[$i],$l).$s[$i].(--$i?"":"\n$r"); ``` [Try it online!](https://tio.run/##HcvRCoMgGIbhW3HyEQopdDoXnXYPLUYst4SflN/RLt/Zzp6D901bKuU2pC0J/9yiQO6x8PuYutmB@vxh8rsCn2J/KGStTedekRVCD6oGNQ2C0/9f3ndpa/tIy1q3CWFuQdoin7TKGIRBymvtwFK7UsroiWIrvpFpvfwA) ``` echo $s = $argv[1]; $l = strlen($r = strrev($s)) - 1; for ($i = $l - 1; $l && $i;) echo "\n" . str_pad($r[$i], $l) . $s[$i] . (--$i ? "" : "\n$r"); ``` [Answer] # [APL](https://www.dyalog.com/), 58 bytes ``` {(' ',⍵)[x+(x←∘.{((c-1)=⍺⌈⍵)∨0=⍺⌊⍵}⍨r)×o⌊⌽⊖o←∘.⌈⍨r←⍳c←≢⍵]} ``` With `⎕IO←0`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLjSgGS1hrqCus6j3q2a0RXaGhVAkUcdM/SqNTSSdQ01bR/17nrU0wGSfdSxwgDC7QJyax/1rijSPDw9H8ztfNQ1DULmQ/WDNa0oAvF6NyeDqM5FQG2xtf//pymoJ6pzAUlDI2Mw7ZGak5OvqA4A) **How?** `c←≢⍵` - length of the string `r←⍳` - range `o←∘.⌈⍨` - outer product with minimum ``` 123 223 333 ``` `o⌊⌽⊖` - minimalize with itself turned 180o ``` 123 ⌊ 333 = 123 223 ⌊ 322 = 222 333 ⌊ 321 = 321 ``` `×` - multiply with `x←∘....⍨r` - outer product of the range with     `((c-1)=⍺⌈⍵)∨0=⍺⌊⍵` - the frame of the matrix ``` 111 × 123 = 123 101 × 222 = 202 111 × 321 = 321 ``` `x+` - add the frame ``` 111 + 123 = 234 101 + 202 = 303 111 + 321 = 432 ``` `(' ',⍵)[...]` - get by index from the string concatenated to space [Answer] # Python 3, 122 bytes ``` i=input();l=len(i) if l!=1: print(i) for I in range(1,l-1): print(i[I]+" "*(l-2)+i[l-I-1]) print(i[::-1]) else:print(i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3qzJtM_MKSks0NK1zbHNS8zQyNbky0xRyFG0Nrbg4C4oy80pAQpxp-UUKngqZeQpFiXnpqRqGOjm6hppWClAF0Z6x2koKSloaObpGmtqZ0Tm6nrqGsZpwA6KtrMD81JziVCuYoRAXQB2yYGEihAEA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~14~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) *Knew* there had to be a shorter way! ``` ¬hU ÆÔÃÕÆÔ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=rGhVIMbUw9XG1A&input=IkhlbGxvLCB3b3JsZCEi) ``` ¬hU ÆÔÃÕÆÔ :Implicit input of string U ¬ :Split hU :Replace first element with U Æ :Modify last element Ô : U reversed à :End modify Õ :Transpose ÆÔ :As above :Implicit output joined with newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gIûûŽ9¦Λ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/3fPw7sO7j@61PLTs3Oz//xOTklMA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GdWibvZJnXkFpiZWCkr0Ol5J/aQmEo/M/3fPw7sO7j@61PLTs3Oz/IMVc5RmZOakKRamJKQqZeVwp@VwKCvr5BSX6EDOhFJo1NgoqYLV5qf/T83PSuAyNjLkSuTxSc3LydRTK84tyUhS5EpOSU7gA). **Explanation:** ``` g # Push the length of the (implicit) input I # Push the input itself û # Palindromize it û # And palindromize that again Ž9¦ # Push compressed integer 2460 Λ # Use the Canvas builtin with those three options # (after which the result is output immediately implicitly) ``` [See this 05AB1E tip of mine (section How to compress large integers?)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž9¦` is `2460`. As for some additional information about the Canvas builtin `Λ`: It takes 3 arguments to draw an ASCII shape: 1. Length of the lines we want to draw 2. Character/string to draw 3. The direction to draw in, where each digit represents a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` `gIûûŽ9¦` creates the following Canvas arguments: * Length: the length of the input (e.g. `4` for input `"abcd"`) * Characters: the double palindromized input (e.g. `"abcdcbabcdcba"` for input `"abcd"`) * Directions: `[2,4,6,0]`, which translates to \$[→,↓,←,↑]\$ Because we only have a single length, the directions are leading here. Step 1: Draw 4 characters (`"abcd"`) in direction `2` (\$→\$): ``` abcd ``` Step 2: Draw 4-1 characters (`"cba"`) in direction `4` (\$↓\$): ``` abcd c b a ``` Step 3: Draw 4-1 characters (`"bcd"`) in direction `6` (\$←\$): ``` abcd c b dcba ``` Step 4: Draw 4-1 characters (`"cba"`) in direction `0` (\$↑\$): ``` abcd b c c b dcba ``` [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) [Answer] # [J](http://jsoftware.com/), 28 23 bytes ``` |._1}]0}|.,.~<:@#{."1,. ``` [Try it online!](https://tio.run/##PYo9C8IwFAD3/IrXBnxtSV6TRWiwEBTEQRxcnIqDtn4QCLg2yV@PxcHhhjvunbvC6GFdmA6RlYQT9AYQBCgwC5Jgdz7uc6CrjoOKgQSljbF8plILyjU7bWn5cSXmVFVcDsHKNlDdqF41bbIiRVPbF1nOxtvTwwT48G7CnyH@42F0zgu4@I@7Y/4C "J – Try It Online") * `,.` Columnize the input: ``` g o l f ``` * `<:@#{."1` Take "input length - 1" elements from each row, with space fills. I'll show the spaces filled with `.` for clarity: ``` g.. o.. l.. f.. ``` * `|.,.~` Zip with the reverse: ``` g..f o..l l..o f..g ``` * `]0}` Replace first row with input: ``` golf o..l l..o f..g ``` * `|._1}` Replace last row with input reversed: ``` golf o..l l..o flog ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 10 bytes ``` ∞∞?L2460ø∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJ7iiJ4/TDI0NjDDuOKIpyIsIiIsIkhlbGxvLCB3b3JsZCEiXQ==) -6 bytes by porting 05AB1E thanks to emanresu [Answer] # JavaScript (ES2017), 87 bytes ``` s=>[...s].reverse(l=s.length-1).map((c,i,z)=>i?l-i?s[i].padEnd(l)+c:z.join``:s).join` ` ``` ES6 version: 93 bytes ``` s=>[...s].reverse(l=s.length-1).map((c,i,z)=>i?l-i?s[i]+' '.repeat(l-1)+c:z.join``:s).join` ` ``` *Less golfed* ``` s => ( l = s.length-1, [...s].reverse().map( // scan string backwards (c, i, z) => i != 0 // check if top row ? l-i != 0 // check if bottom row ? s[i].padEnd(l) + c // any middle row : z.join`` // bottom row: string reversed :s // top row: original string ).join`\n` ) ``` ``` F= s=>[...s].reverse(l=s.length-1).map((c,i,z)=>i?l-i?s[i].padEnd(l)+c:z.join``:s).join` ` function update() { O.textContent = F(I.value) } update() ``` ``` <input id=I value='Hello, world!' oninput='update()'> <pre id=O></pre> ``` [Answer] # Java, 191 bytes ``` (s)->{PrintStream o=System.out;int l=s.lenght();o.println(s);for(int i=0;i<l;i++){o.printf("%"+"s%"+(l-1)+"s%n",s.charAt(i),s.charAt(l-1-i));for(int i=0;i<l;i++){o.print(s.charAt(l-1-i));}}}; ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~179~~ 161 bytes *-18 bytes thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)* ``` using System.Linq; s=>{int l=s.Length-1,i=1;var d=s.Reverse().ToArray();while(i<l)s+="\n"+s[i]+new string(' ',l-1)+d[i++];if(l>1)s+="\n"+new string(d);return s;}; ``` [Try it online!](https://tio.run/##TVA9b8IwEJ2bX3FlwZaTSJlNkFClqgNdaKUOlMGKL3CSsVufCUKI354GaClvuM@np3fXcNGEiL03W@Qv0yC8HTjhNjtmMGDH5NcwJ/@tL33jDDPMLvWVcQYnk6iBLpCFV0NeyNvqn3TG8843E05xEM3hmqfQQt1zPT2ST@BqLufo12lTVDnVle5MBDsMF9hhZBSyfA@zGM1BSL3fkENBEydZ1aNPP1K8pJXyuP/VFmMY566opLJLUmqlqRVuWt3od0wrdcS0ix5Yn3T/cHb7FDwHh@VHpISiFX/9Ao0dXjKYkVLf7jtl13jqX9C5kMM@RGcffwA "C# (.NET Core) – Try It Online") ~~I'm not sure about the rules, if this is needed to byte count or not:~~ ``` using System.Linq; ``` Someone please correct me about this. Ungolfed: ``` s => { int l = s.Length - 1, i = 1; var d = s.Reverse().ToArray(); while (i < l) s += "\n" + s[i] + new string(' ', l - 1) + d[i++]; if (l > 1) s += "\n" + new string(d); return s; }; ``` [Answer] # [Retina](https://github.com/m-ender/retina), 106 bytes ``` ..+ $&¶$& O$^`.(?=.*$) \G. $&$%'¶ r`.\G ¶$%`$& +`(.+)¶¶((.*¶)*).(.*) ¶¶$1$4$2 T`p` `(?<=.¶.).*(?=.¶.) G`. ``` [Try it online!](https://tio.run/##FYwxCgJBDEX7nMIiuyYz8EGxdNlyShvLRWKhIojK4tlygFxsnOke7z/@evs939dagUw8hvNIJ74YZJ6QWImWgjbwsA2n1bAUatFgrcsmyBoeLoIUrknRQKkr3vGB93S2r21M5uOEcChS/@1ExVDr4/O6/wE "Retina – Try It Online") Explanation: ``` ..+ $&¶$& ``` If there are at least two characters, duplicate the input. ``` O$^`.(?=.*$) ``` Reverse the duplicate. ``` \G. $&$%'¶ r`.\G ¶$%`$& ``` Turn the strings into triangles. The top triangle starts with the input and removes the first character each time, while the bottom triangle starts with the first letter of the reversed input and adds a character each time. ``` +`(.+)¶¶((.*¶)*).(.*) ¶¶$1$4$2 ``` Join the triangles together, overlapping so that the last character forms the `/` diagonal. ``` T`p` `(?<=.¶.).*(?=.¶.) ``` Change all the characters to spaces, if they are at least one character away from the end on every side. ``` G`. ``` Delete any left-over blank lines. [Answer] # Python 3, 85 bytes Using the input for the top row :) ``` a=input() b=len(a) for i in range(b-2):print(a[1+i]+" "*(b-2)+a[-2-i]) print(a[::-1]) ``` [Answer] # [Lua](http://lua.org), 104 bytes ``` print(s);for a=2,#s-1 do print(s:sub(a,a)..(" "):rep(#s-2)..s:sub(#s-a+1,#s-a+1)) end;print(s:reverse()) ``` [Try it online!](https://tio.run/##NYvNCoQwDIRfJdu9JFgFPSrefY1Is7BQrCT@PH4tqKfhm28m7pxtdJPEmDycSWP4uLzqf9nQaPglBR47/7W6hZDgEb3tM7Jnahp04KhXWbFsulLcsgBXrb@DCGQJw3tWOURNkCjnCw) [Answer] # Python 3, 106 bytes A functional version... ``` w=input();p=print;l=len(w)-2 def f(k):p(w[k]+' '*l+w[-k-1]);l-k>0and f(k+1) l<0 or f(1)or l<1or p(w[::-1]) ``` [Answer] # [Python 2](https://docs.python.org/2/), 100 bytes ``` lambda a:'\n'.join([a]+(len(a)>1)*([a[i]+(len(a)-2)*' '+a[~i]for i in range(1,len(a)-1)]+[a[::-1]])) ``` [Try it online!](https://tio.run/##PYu7DsIwDAB/xUyO@0BKx0gw8w9pBqMmYBScKqqEWPj10AEx3ulufW/3olNLp7llfl4XBnY4Kx4fRdR4Dr3JUQ3T2VK3s5e/GSfqELBn/5GQSgUBUaist2js8GsshX6/nBttCERtraIbJIOXmHMZ4FVqXg5I7Qs "Python 2 – Try It Online") ]
[Question] [ # Introduction A [Gray Code](https://en.wikipedia.org/wiki/Gray_code) is an alternative to binary representation in which a number is incremented by toggling only one bit, rather than a variable amount of bits. Here are some gray codes along with their decimal and binary equivalents: ``` decimal | binary | gray ------------------------- 0 | 0 | 0 ------------------------- 1 | 1 | 1 ------------------------- 2 | 10 | 11 ------------------------- 3 | 11 | 10 ------------------------- 4 | 100 | 110 ------------------------- 5 | 101 | 111 ------------------------- 6 | 110 | 101 ------------------------- 7 | 111 | 100 ------------------------- 8 | 1000 | 1100 ------------------------- 9 | 1001 | 1101 ------------------------- 10 | 1010 | 1111 ------------------------- 11 | 1011 | 1110 ------------------------- 12 | 1100 | 1010 ------------------------- 13 | 1101 | 1011 ------------------------- 14 | 1110 | 1001 ------------------------- 15 | 1111 | 1000 ``` ### Cyclic Bit Pattern of a Gray Code Sometimes called "reflected binary", the property of changing only one bit at a time is easily achieved with cyclic bit patterns for each column starting from the least significant bit: ``` bit 0: 0110011001100110011001100110011001100110011001100110011001100110 bit 1: 0011110000111100001111000011110000111100001111000011110000111100 bit 2: 0000111111110000000011111111000000001111111100000000111111110000 bit 3: 0000000011111111111111110000000000000000111111111111111100000000 bit 4: 0000000000000000111111111111111111111111111111110000000000000000 bit 5: 0000000000000000000000000000000011111111111111111111111111111111 ``` ...and so on. # Objective Given a non-padded input string of a gray code, increment the gray code by alternating a single character in the sequence or prepending a `1` (when incrementing to the next power of 2), then output the result as a non-padded gray code. ### Caveats * Do not worry about taking `0` or an empty string as input. * The lowest input will be `1`, and there is no upper-bound to the string length other than memory limitations imposed by the environment. * By non-padded string, I mean there will be no leading or trailing whitespace (other than an optional trailing newline), and no leading `0`s in the input or output. ### I/O formats The following formats are accepted form for input and output, but strings are encouraged over other formats: * most significant "bit" first * non-padded character array or string of ASCII `'1'`s and `'0'`s * non-padded integer array of `1`s and `0`s * non-padded boolean array **What's not allowed:** * least significant "bit" first * decimal, binary or unary integer * fixed-length data-structure * character array or string of non-printable ASCII indices `1` and `0` ### Tests ``` input -> output 1 -> 11 11 -> 10 111 -> 101 1011 -> 1001 1111 -> 1110 10111 -> 10110 101100 -> 100100 100000 -> 1100000 ``` More tests can be added by request. # Criteria This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins! All ties will be broken by favoring earlier submissions; standard loopholes apply. The best submitted answer will be accepted October 9th, 2016, and updated whenever better answers are given. [Answer] ## [Jelly](http://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes *Thanks to Dennis for saving 2 bytes.* ``` ^\Ḅ‘^H$B ``` Input and output are lists of 0s and 1s. [Try it online!](http://jelly.tryitonline.net/#code=XlzhuITigJheSCRC&input=&args=WzEsIDAsIDEsIDEsIDAsIDBd) ### Explanation The inverse of the Gray code is given by [A006068](https://oeis.org/A006068). Using this we don't need to generate a large number of Gray codes to look up the input. One classification of this sequence given on OEIS is this: ``` a(n) = n XOR [n/2] XOR [n/4] XOR [n/8] ... ``` Where the `[]` are floor brackets. Consider the example of `44` whose binary representation is `101100`. Dividing by 2 and flooring is just a right-shift, chopping off the least-significant bit. So we're trying to XOR the following numbers ``` 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 ``` Notice that the `n`th column contains the first `n` bits. Hence, this formula can be computed trivially on the binary input as the cumulative reduction of XOR over the list (which basically applies XOR to each prefix of the list and gives us a list of the results). This gives us a simple way to invert the Gray code. Afterwards, we just increment the result and convert it back to the Gray code. For the latter step we use the following definition: ``` a(n) = n XOR floor(n/2) ``` Thankfully, Jelly seems to floor the inputs automatically when trying to XOR them. Anyway, here is the code: ``` ^\ Cumulative reduce of XOR over the input. Ḅ Convert binary list to integer. ‘ Increment. ^H$ XOR with half of itself. B Convert integer to binary list. ``` [Answer] # Perl, ~~27~~ 25 bytes Includes +1 for `-p` Give input string on STDIN, e.g. ``` gray.pl <<< 1010 ``` `gray.pl`: ``` #!/usr/bin/perl -p s%(10*\K1(\K0)*)*%1-$&%e ``` Perl has no cheap infinite-precision integers. So directly toggle the right bit which is the one just before where the last odd-numbered 1 would be. [Answer] ## JavaScript (ES6), 58 bytes ``` s=>s.replace(s.split`1`.length%2?/.$/:/.?(?=10*$)/,c=>1-c) ``` Directly toggles the appropriate bit. Explanation: As shown in MartinEnder♦'s answer, each bit in a decoded Gray code is the cumulative XOR, or parity, of itself and the bits to its left. We then need to increment the number which causes a carry ripple that toggles all the rightmost 1 bits to 0 and then the next 0 bit to 1. Re-encoding results in a code with just that one 0 bit position toggled. If the parity of all the 1 bits is even, then the rightmost bit is 0 and we therefore just toggle the last bit. If the parity of all the 1 bits is odd, then the rightmost bits are 1, and we need to find the last 1 bit. This is now the last of the carried bits, so the bit we need to toggle is the next bit from the right. [Answer] ## JavaScript (ES6), 53 bytes (non-competing) A recursive function which builds all gray codes until the input is found, then stops at the next iteration. The highest possible input depends on the browser recursion limit (about 13 bits in Firefox and 15 bits in Chrome). ``` f=(s,n=1)=>(b=(n^n/2).toString(2),s)?f(b!=s&&s,n+1):b console.log(f("1")); // -> 11 console.log(f("11")); // -> 10 console.log(f("111")); // -> 101 console.log(f("1011")); // -> 1001 console.log(f("1111")); // -> 1110 console.log(f("10111")); // -> 10110 console.log(f("101100")); // -> 100100 console.log(f("100000")); // -> 1100000 ``` [Answer] # Haskell, ~~118 115~~ 108 bytes ``` g 0=[""] g n|a<-g$n-1=map('0':)a++map('1':)(reverse a) d=dropWhile f s=d(=='0')$(d(/='0':s)$g$1+length s)!!1 ``` [Try it on Ideone.](http://ideone.com/lkL7ta) Naive approach: `g` generates the set of all gray codes with length `n` (with 0-padding), `f` calls `g` with `length(input)+1`, removes all elements until `0<inputstring>` is found and returns the next element (truncating a possibly leading `0`). [Answer] # [MATL](http://github.com/lmendo/MATL), 18 bytes ``` ZBtE:t2/kZ~tb=fQ)B ``` [Try it online!](http://matl.tryitonline.net/#code=WkJ0RTp0Mi9rWn50Yj1mUSlC&input=JzEwMSc) Or [verify all test cases](http://matl.tryitonline.net/#code=IkBnClpCdEU6dDIva1p-dGI9ZlEpQg&input=eycxJywgJzExJywgJzExMScsICcxMDExJywgJzExMTEnLCAnMTAxMTEnLCAnMTAxMTAwJywgJzEwMDAwMCd9). ### Explanation Let *a*(*n*) denote the sequence of integers corresponding to Gray codes ([OEIS A003188](https://oeis.org/A003188)). The program uses the characterization *a*(*n*) = *n* XOR floor(*n*/2), where XOR is bit-wise. Essentially, the code converts the input to an integer *a*0, finds that integer in the sequence, and then selects the next term. This requires generating a sufficiently large number of terms of the sequence *a*(*n*). It turns out that 2·*a*0 is sufficiently large. This stems from the fact that the Gray code *a*(*n*) never has more binary digits than *n*. Let's take input `'101'` as an example. ``` ZB % Input string implicitly. Convert from binary string to integer % STACK: 5 t % Duplicate % STACK: 5, 5 E % Multiply by 2. This is the number of terms we'll generate from the sequence % STACK: 5, 10 : % Range % STACK: 5, [1 2 3 4 5 6 7 8 9 10] t % Duplicate % STACK: 5, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 10] 2/k % Divide by 2 and round down, element-wise % STACK: 5, [1 2 3 4 5 6 7 8 9 10], [0 1 1 2 2 3 3 4 4 5] Z~ % Bit-wise XOR, element-wise % STACK: 5, [1 3 2 6 7 5 4 12 13 15] t % Duplicate % STACK: 5, [1 3 2 6 7 5 4 12 13 15], [1 3 2 6 7 5 4 12 13 15] b % Bubble up % STACK: [1 3 2 6 7 5 4 12 13 15], [1 3 2 6 7 5 4 12 13 15], 5 = % Equality test, element-wise % STACK: [1 3 2 6 7 5 4 12 13 15], [0 0 0 0 0 1 0 0 0 0] f % Find: yield (1-based) index of nonzero values (here there's only one) % STACK: [1 3 2 6 7 5 4 12 13 15], 6 Q % Increase by 1 % STACK: [1 3 2 6 7 5 4 12 13 15], 7 ) % Apply as index % STACK: 4 B % Convert to binary array % STACK: [1 0 0] % Implicitly display ``` [Answer] ## CJam (19 bytes) ``` {_2b__(^@1b1&*)^2b} ``` [Online demo](http://cjam.aditsu.net/#code=0a%7B_p%0A%0A%7B_2b__(%5E%401b1%26*)%5E2b%7D%0A%0A~%7D31*%60). This is an anonymous block (function) from bit array to bit array, which the demo executes in a loop. It works on the simple principle that if the number of set bits is even we should toggle the least significant bit, and otherwise we should toggle the bit to the left of the least significant set bit. Actually identifying that bit turns out to be much easier using bit hacks on an integer than using the list of bits. ### Dissection ``` { e# Declare a block: _2b e# Convert the bit array to a binary number __(^ e# x ^ (x-1) gives 1s from the least significant set bit down @1b1& e# Get the parity of the number of set bits from the original array * e# Multiply: if we have an even number of set bits, we get 0; e# otherwise we have 2**(lssb + 1) - 1 )^ e# Increment and xor by 1 or 2**(lssb + 1) 2b e# Base convert back to a bit array } ``` Working solely with the bit array, I think it's necessary to reverse it: working with the left-most `1` is much easier than the right-most. The best I've found so far is (24 bytes): ``` {W%_1b)1&1$+1#0a*1+.^W%} ``` --- ### Alternative approach (19 bytes) ``` {[{1$^}*]2b)_2/^2b} ``` This converts from Gray code to index, increments, and converts back to Gray code. [Answer] ## Retina, 25 bytes ``` ^(10*10*)* $1: 1: 0 .?: 1 ``` I feel sure there should be a better way of doing this... [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes Uses [CP-1252](http://www.cp1252.com/) encoding. ``` CÐ<^¹SOÉ*>^b ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Q8OQPF7CuVNPw4kqPl5i&input=MTAxMTAw) **Explanation** Example for input *1011*. ``` C # convert to int (bigint if necessary) # STACK: 11 Ð # triplicate # STACK: 11, 11, 11 < # decrease by 1 # STACK: 11, 11, 10 ^ # XOR # STACK: 11, 1 ¹ # push first input # STACK: 11, 1, 1011 S # split to list # STACK: 11, 1, [1,0,1,1] O # sum # STACK: 11, 1, 3 É # mod 2 # STACK: 11, 1, 1 * # multiply # STACK: 11, 1 > # increase by 1 # STACK: 11, 2 ^ # XOR # STACK: 9 b # convert to binary # STACK: 1001 # implicitly print top of stack ``` [Answer] ## C++, 205 bytes ``` #include <string> std::string g(std::string s){int i,z;if(s=="1")return"11";for(i=z=0;i<s.length();i++)if(s[i]=='1')z++;i--;if(z%2){char c=s[i];s.erase(i);s=g(s);s+=c;}else{s[i]=s[i]==49?48:49;}return s;} ``` Description: Even numbers have even number of ones. Variable `z` counts ones; if `z` is even (`z mod 2 = z%2 = 0` - else branch), alter the last bit; if `z` is odd, call this function again without the last character and calculate new value, then append the last character afterwards. [Click here to try it for the test cases.](https://ideone.com/i4PIZm) [Answer] ## Batch, ~~199~~ 197 bytes ``` @echo off set/ps= set r= set t=%s:0=% if 1%t:11=%==1 goto g :l set b=%s:~-1% set s=%s:~,-1% set r=%b%%r% if %b%==0 goto l if 0%s%==0 set s=0 :g set/ab=1-%s:~-1% echo %s:~,-1%%b%%r% ``` Reads input from STDIN into variable `s`. Removes the 0s and does a parity check on the 1s and if there are an odd number it strips the rightmost 0s in a loop, stopping when it strips a 1. `s` therefore contains the even parity prefix and `r` the rest of the string. `s` is set to zero if it was blank so that its last digit can be toggled, and then everything is concatenated. [Answer] ## Python 2.7, 68 characters ``` def f(s):i=long(s,2);print bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:] ``` ## Python 3, 68 characters ``` def f(s):i=int(s,2);print(bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:]) ``` This function converts the given binary string to an integer then xor the last bit if the number of set bits in the original string is even, or its swaps the bit to the left of the rightmost set bit if the number of set bits in the original string is odd. Then it converts the result to a binary string and removes the `0b` boolean prefix. [Answer] # Actually, ~~20~~ ~~19~~ 13 bytes Based on [Martin Ender's Jelly answer](https://codegolf.stackexchange.com/a/95204/47581) with my own version of "cumulative reduce of XOR over the input". Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=z4Mx4pmAJjJAwr91O8K94omIXuKUnA&input=WzEsMCwxLDEsMCwwXQ) ``` σ1♀&2@¿u;½≈^├ ``` **Ungolfing** ``` Implicit input a as a list, such as [1,0,1,1,0,0]. σ Get the cumulative sums of a. 1♀& Map x&1 (equivalent to x%2) over every member of the cumulative sum. 2@¿ Convert from binary to decimal. u Increment x. ;½≈ Duplicate and integer divide by 2. ^ XOR x and x//2. ├ Convert to binary to obtain our incremented Gray code. Implicit return as a string, such as "100100". ``` [Answer] # J, 38 bytes ``` [:#:@(22 b.<.@-:)@>:@#.[:22 b./[:#:#.\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62UrRw0jIwUkvRs9Bx0rTQd7KwclPWircBC@iBpZb2Y/5pcqckZ@QoaaQqGmgoKCrpWQMIQCBHCYAmouAGKOKoMih4DdFk0eTTdhuhmG2AzH6saoNHo9higq4NCZPvggkA@Fwj8BwA "J – Try It Online") This is essentially Martin's algorithm in J. Note that `22 b.` is XOR. ``` [: #: #.\ Creates the prefixes of the input converts to a number, then converts back to binary. Needed to get the padding on the left. [: 22 b./ Reduce the rows of the resulting matrix with XOR, giving us the normal binary @#. Convert to int and... @>: Increment and... (22 b. <.@-:) XOR that with its own floored half [: #:@ And turn the result back to binary ``` ]
[Question] [ ## The challenge You're given: * a non-empty, unsorted list **h** of positive integers (the haystack) * a positive integer **n** (the needle) Your task is to return the list of all ***unique*** decimal concatenations of permutations of **h** whose binary representation contains the binary representation of **n**. ## Examples 1. **h = [ 1, 2, 3 ]** **n = 65** [![example](https://i.stack.imgur.com/Xllzk.png)](https://i.stack.imgur.com/Xllzk.png) There's only one matching concatenation, so the expected output is `[321]`. 2. **h = [ 1, 2, 3 ]** **n = 7** This time, there are three concatenations which contain the binary pattern **111**. The expected output is `[123, 231, 312]`. 3. **h = [ 12, 3 ]** **n = 7** Only two permutations are available and both are matching. The expected output is `[123, 312]`. 4. **h = [ 1, 2, 2 ]** **n = 15** The only matching concatenation is **122** (**1111010** in binary, which contains **1111**), so the expected output is `[122]`. Note that two permutations actually lead to **122** but you are *not* allowed to output `[122, 122]`. ## Clarifications and rules * You may take the needle as an integer (`65`), a string representing a decimal value (`"65"`) or a string representing a binary value (`"1000001"`). * You may take the haystack as a native array/object/set of integers (`[11,12,13]`), a native array/object/set of strings representing decimal values (`["11","12","13"]`), or a delimited string of decimal values (`"11 12 13"` or `"11,12,13"`). You may also opt for a variant using arrays of digits (like `[[1,1],[1,2],[1,3]]`). * The output must follow one of the formats described above for the haystack, but not necessarily the same one. * You're not supposed to handle haystacks whose highest decimal concatenation is greater than the highest representable unsigned integer in your language. * Apart from that, your code should theoretically support any input -- assuming it's given enough time and memory. * This is ~~SPARTA!~~ [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win! ## Test cases ``` Haystack | Needle | Output ---------------------+----------+----------------------------------- [ 1, 2, 3 ] | 65 | [ 321 ] [ 1, 2, 3 ] | 7 | [ 123, 231, 312 ] [ 12, 3 ] | 7 | [ 123, 312 ] [ 1, 2, 2 ] | 15 | [ 122 ] [ 1, 2 ] | 7 | [] [ 12, 34, 56 ] | 21 | [ 125634, 341256, 345612, 563412 ] [ 1, 2, 3, 4, 5 ] | 511 | [ 53241 ] [ 1, 3, 5, 7, 9 ] | 593 | [ 37519, 51793, 75913, 75931 ] [ 11, 12, 13, 14 ] | 12141311 | [ 12141311 ] [ 1, 2, 1, 2, 1, 2 ] | 1015 | [ 221112 ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes Takes the needle in binary to save 1 byte. -2 bytes thanks to Emigna ``` œJÙʒbŒIå ``` [Try it online!](https://tio.run/nexus/05ab1e#@390stfhmacmJR2d5Hl46f//0YY6RjrGsVyGhoYA "05AB1E – TIO Nexus") ``` œJÙʒbŒIå Arguments: a, n œJÙ Get all unique permutations of a ʒ Filter: Keep if following code returns true b Convert to binary Œ Get all substrings Iå Check if substrings contain n Implicit output of filtered list ``` [Answer] ## Python 2, 90 bytes -3 bytes thanks to @Gábor Fekete [Try it online](https://tio.run/nexus/python2#HYoxCsMwDEX3nkJoiVVMIR0L3TOEXKDp4NAYVGLLKOpUenYn6YcHj8fv72NdQppeATo/3L4MURQYOEOZNX0sGEteXUccYTjyxNlxNtc0l7ccTkS/U1RJwDariSwrcCqidq5F9yv07oEterz@eXps9yHVDQ) Takes as input array of strings, representing ints from hay and string, representing needle in binary ``` from itertools import* lambda H,N:{i for i in permutations(H)if N in bin(int(''.join(i)))} ``` [Answer] # Java 10, ~~320~~ ~~312~~ ~~305~~ ~~297~~ 292 bytes ``` import java.util.*;Set s=new HashSet();l->n->{Long q=0;p(l,0);for(var x:s)if(q.toString(q.decode(x+""),2).contains(n))System.out.println(x);}void p(List l,int k){int i=k,x=l.size();for(Collections C=null;i<x;p(l,k+1),C.swap(l,k,i++))C.swap(l,i,k);if(k>x-2)s.add((l+"").replaceAll("\\D",""));} ``` Input as List & binary-String, output as Strings on new-lines. **Explanation:** [Try it here.](https://tio.run/##zZNRb9owEMff8ylOPNnDuDhAKxqC1HWaNqmTJvG47sE1hhqMncYOhSE@O3MCZZW2wcMmqB9iX3K5@/3vzhM@543JcLrZXFzAV557sCPwjxIell42hC2MB8S6lenwdaRmmQ1Ok/AbLbzS9F0Swav1u8OoMMIra@itNa6YyTw54PNxd0gioblz8IUrs4qiA2xxc882kB5cauQzfOLuMVgIJ1H0ErJ3p5wnLxC9gc@VGff7ICA9mIA1430G3eibRn91Z80YntJmkiFNmjgZ2RzNeQ6La4fVCD1Rb7fhw3EohR1KtKjXapjEmAprfBDlkMF4sHRezqgtPM2Cu9cGLXCyjqLkMFGH7YnmVg0hQ6U20CTEgClelZtKp2SRaurUD4m2iLdWa1nVwoFITaF1onqLSsS0zjAR1D3zyiKqXsd4bysyxUkQNu0vGjF2lA@HCOlSEc1lprmQN1qj2v39hxoJL4OEDUBWPGglwHnuw1ZxzoJwtK3Mt@/A8aoanbLHMIMUys6VRtm28sOMCsqzTC/RTZ7zZcjrSp2IEYgJtDCmXAiZefTZeDmWeSj7e2V4vtwV/7KDd5H@UOha42@rtk/vdlCvxul/cF2dGOtNQlW1io9isTP08E02sE2gc3mULGZnGXkCJd5Rug47PV5g6xC4ItA9jtdtnRgv8JXNZQGStY/fhZi1WYudpcW/nscxm/90adfRevMT) ``` import java.util.*; // Required import for Set, HashSet, List, and Collections Set s=new HashSet(); // Class-level Set l->n->{ // Method (1) with List and String parameters and no return-type Long q=0; // Number-object is required for two static method-calls below p(l,0); // Determine all permutations of given list and put it in the Set for(var x:s) // Loop over these permutations if(q.toString(q.decode(x+""),2) // If the binary String of the current permutation .contains(n)) // contains the binary String of the input integer System.out.println(x);} // Print this permutation void p(List l,int k){ // Method (2) with List and integer parameters and no return-type int i=k,x=l.size(); // Two temp integers for(Collections C; // Collections-object is required for two static method-calls below i<x // Loop `i` in the range [`k`, list-size) ; // After every iteration: p(l,k+1), // Do a recursive-call to this method with `k+1` Collections.swap(l,k,i++)) // And swap the items at indices `k` and `i` back Collections.swap(l,i,k); // Swap the items at indices `i` and `k` if(k>x-2) // If `k` is now equal to the size of the list - 1 s.add((l+"").replaceAll("\\D",""));} // Add this permutation to the Set ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~15~~ ~~14~~ ~~13~~ ~~12~~ 10 bytes Takes the haystack as an array of integers and the needle as a binary string. Outputs an array of integer strings. ``` á m¬f_°¤øV ``` * Saved a byte thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=4SBtrGZfsKT4Vg==&input=WzEyLCAzNCwgNTZdLCIxMDEwMSIKLVE=) --- ## Explanation ``` á m¬â f_°¤øV :Implicit input of array U=haystack and string V=needle á :Unique permutations of U m :Map ¬ : Join to a string f_ :Filter ° : Postfix increment current element to cast it to an integer ¤ : Convert to base-2 string øV : Does that contain V? :Implicit output of resulting array ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~61~~ 59 bytes ``` ->a,n{a.permutation.select{|s|"%b"%s.join=~/#{"%b"%n}/}|[]} ``` [Try it online!](https://tio.run/nexus/ruby#S7P9r2uXqJNXnahXkFqUW1qSWJKZn6dXnJqTmlxSXVNco6SapKRarJeVn5lnW6evXA3m59Xq19ZEx9b@L1BIi4421DHSMY7VMTON5SooLSlWUNfV1VXnQpYyxy5jFKtjaBr7HwA "Ruby – TIO Nexus") Cool feature of the day: I didn't know I could output the binary representation of a string containing a number. Example: ``` puts "%b"%"123" -> 1111011 ``` [Answer] # JavaScript (ES6), 140 bytes Takes needle as a binary string. ``` (h,n,S=new Set,p=(a,m='')=>a.length?a.map((_,i)=>p(A=[...a],m+A.splice(i,1))):S.add(+m),_=p(h))=>[...S].filter(d=>~d.toString(2).indexOf(n)) ``` ``` f= (h,n,S=new Set,p=(a,m='')=>a.length?a.map((_,i)=>p(A=[...a],m+A.splice(i,1))):S.add(+m),_=p(h))=>[...S].filter(d=>~d.toString(2).indexOf(n)) console.log( f([1, 2, 3], (65).toString(2)) ) console.log( f([12, 34, 56], (21).toString(2)) ) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` {hpc.ḃs~ḃ~t?∧}ᵘ ``` [Try it online!](https://tio.run/nexus/brachylog2#@1@dUZCs93BHc3EdkKgrsX/Usbz24dYZ//9HRxvqGOkYxeoYmsb@jwIA "Brachylog – TIO Nexus") ### Explanation ``` { }ᵘ Find all unique outputs, given [h, n], of: hpc. The Output is the concatenation of a permutation of h .ḃs Take a substring of the binary representation of the Output ~ḃ Convert it back to a decimal number ~t?∧ This decimal number must me n ``` [Answer] ## Mathematica, ~~170~~ 156 bytes ``` (t={};l=Length;v=IntegerDigits;j=v[#2, 2];s=FromDigits/@Flatten/@v@Permutations@#1;Table[If[l@SequenceCases[v[s[[i]],2],j]>0,t~AppendTo~s[[i]]],{i,l@s}];t)& ``` **input** > > [{12, 34, 56}, 21] > > > **output** > > {125634, 341256, 345612, 563412} > > > [Answer] ## CJam, ~~23~~ ~~22~~ ~~21~~ 19 bytes ``` {e!{si2b1$2b#)},\;} ``` This is a block that takes inputs `n h` on the stack and leaves the output as an array on the stack. Explanation: ``` e# Stack: | 65 [1 2 3] e! e# Unique Permutations: | 65 [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]] { e# Filter where block is true: | 65 [3 2 1] s e# Convert to string: | 65 "321" i e# Convert to int: | 65 321 2b e# Convert to binary: | 65 [1 0 1 0 0 0 0 0 1] 1$ e# Copy behind: | 65 [1 0 1 0 0 0 0 0 1] 65 2b e# Convert to binary: | 65 [1 0 1 0 0 0 0 0 1] [1 0 0 0 0 0 1] # e# Find array in another: | 65 2 ) e# Increment: | 65 3 }, e# End filter | 65 [321] \; e# Delete back: | [321] ``` [Answer] # R, 114 bytes ``` pryr::f(plyr::l_ply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n"))) ``` Uses a bunch of packages. `pryr::f()` automatically creates a function, taking `p`, a string of the binary pattern to look for, and `x`, a vector with the other input as input. `combinat::permn` creates all permutations of `x`. `R.utils::intToBin` is a nice and wordy version to convert a numeric (or character representation of a numeric) to a binary number, already conveniently stored as a character. So applying this over all the permutations and outputting them if the binary string `p` is contained in the binary version of the concatenation. An explicit newline is printed, because otherwise the output would be `12 56 3456 34 1234 56 1234 12 56`. `plyr`'s `l_ply` is used to surpress outputting a null list, besides the regular output. If output like this is allowed: ``` 3 2 1 [[1]] NULL [[2]] NULL [[3]] NULL [[4]] NULL [[5]] NULL [[6]] NULL ``` Then we can save few bytes by using `lapply` instead: ## 108 bytes: ``` pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n"))) ``` ~~If output like this is allowed:~~ ``` [[1]] NULL [[2]] NULL [[3]] NULL [[4]] [1] 3 2 1 [[5]] NULL [[6]] NULL ``` Then we can do it even shorter: ## 101 bytes: ``` pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste0(y,collapse=""))))y)) ``` Not allowed. [Answer] # [Perl 6](http://perl6.org/), 69 bytes ``` {set @^a.permutations».join.grep(*.fmt('%b').contains($^b.base(2)))} ``` ]
[Question] [ Vim is a great text editor for unix systems, but it's notorious for being difficult to exit. Write a full program that will output `:q` to exit Vim. It should then read a single line of input, as it will then either be given a bash prompt, in which case the exit was successful, or an error, in which case there are unsaved changes. The bash prompt will be this: ``` E37@vimmachine: /var/override) ``` While the error will be this: ``` E37: No write since last change (add ! to override) ``` Upon being given the bash prompt, the program's work is done, and it should not give any more output (except for whitespace). Upon being given the error, your program should randomly (ie each possibility has a non-zero probability of being chosen) output `:q!`, to exit without saving, or `:x`, to save and exit. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins! [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes Saved 3 bytes thanks to @Mr.Xcoder and 4 thanks to @Mayube! ``` from random import* if'('in input(':q'):print choice([':x',':q!']) ``` [Try it online!](https://tio.run/##HYoxDsIwDEV3TuFOSREsMCBFYmTlAoBQlLjUErWDGygcnDmETu8//Zc@uRfeFOL0zLAH9dN13qVTGapyrKAhieblgjpjDTHMhTXucWbTuqTEGUIvFNCejHubVb0ac2lLOWx3Do4Ck1JGGIkDwt2P/9zzDcH6GKGBLCAvVKWI7ZdlHXzo8Qc "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/en/), 35 bytes ``` p:q p %i(q! x)[rand 2]if/\(/=~gets ``` [Try it online!](https://tio.run/##KypNqvz/v8CqkKtAQTVTo1BRoUIzuigxL0XBKDYzTT9GQ9@2Lj21pPj/f1djcysFv3yF8qLMklSF4sy85FSFnMTiEoXkjMS89FQFjcSUFAVFhZJ8hfyy1KKizJRUza95@brJickZqQA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` „:q,'Nåi„:x…:q!‚.R, ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcM8q0Iddb/DSzNBzIpHDcusChUfNczSC9L5/9/V2NxKwS9fobwosyRVoTgzLzlVISexuEQhOSMxLz1VQSMxJUVBUaEkXyG/LLWoKDMlVfNrXr5ucmJyRioA "05AB1E – Try It Online") ``` „:q, # Print the string ":q" 'Nåi # If N is in the input „:x # Push the string ":x" …:q! # Push the string ":q!" ‚ # Wrap them into an array .R, # Randomly print one of them ``` [Answer] # Vimscript, 45 41 bytes ``` ec"q"|exe"/("|ec["q!","x"][getpid()%2] ``` Shaved off 4 bytes by using `getpid()` to get a number. (Can anyone think of a shorter way to get a number that won't be the same everywhere, all the time?) Assuming +3 bytes for invoking Vim with `-c` to run the above script and `-` to read input from stdin: ``` vim -c 'ec"q"|exe"/("|ec["q!","x"][reltime()[1]%2]' - ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~76~~ ~~75~~ ~~72~~ 69 bytes **This answer has been [out-golfed](https://codegolf.stackexchange.com/a/127479).** *-1 byte thanks to Rod. -3 bytes thanks to Mayube. -3 bytes thanks to Artyer.* ``` from random import* print'::qx!'[random()>.5:('N'in input(':q'))*5:2] ``` [Try it online!](https://tio.run/##Jck7DsIwDADQnVO4k5NKMBRVSBnYuvYCiCFKAo1E7dQ1v4MzBySmN7zy1ompq/UiPIN4ij/yXFi03RTJpOjc8mrw9D9jj7veGRwxE2QqdzXoFrS27V13rhWH/cHByPCUrAnWTCHBza8KYfJ0TWB8jNCAMvAjieSYLH6It8GHKX0B "Python 2 – Try It Online") [Answer] ## JavaScript, ~~52~~ 46 bytes *Saved 6 bytes thanks to @ETHProductions* ``` prompt(':q')[30]&&alert(new Date%2?':q!':':x') ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 140 139 138 bytes ``` using static System.Console;class P{static void Main(){Write(":q");if(ReadLine()[3]==':')Write(new System.Random().Next()>9?":x":":q!");}} ``` [Try it online!](https://tio.run/##NcyxCsIwEIDhV4lZehns4mRKdXBVkTo4iENITzloL9iLWil99lhQ5//n8zL3ocOUHkJ8UxJdJK@Ob4nY5pvAEhosfONE1GH41WegWu0cMZjh1FFE0PauTUFXqNDVW2IEc15cyjKzmfkejK@/WjmuQwsm32MfwayWa217bSdjNiHjmNIH "C# (.NET Core) – Try It Online") * 1 byte saved thanks to LiefdeWen! * 1 byte saved thanks to Mord Zuber! [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~32~~ ~~30~~ 29 bytes * Had a redundant `!o`. * -1 byte thanks to Aaron. ``` iii0["@!qx:q:"ooi{=?;o!ox~oo; ``` [Try it online!](https://tio.run/##HcLNCkBAFAbQV/nGirWFGomNrXeYzMUtzW1@QimvPqRzFo5bzsWg/KW9LkT4@d1d34r6XI9Im/NYNxqT4AycCJHdTNhNTJg341ZCaayFQhLIQSGwpeoF "><> – Try It Online") ## Explanation (old) ``` "@!qx:q:"ooi~i~i~i{=?;o!ox~oo; "@!qx:q:" Push @!qx:q: on the stack (in reverse) oo Print :q [stack: @!qx:] i~i~i~ Remove first 3 input characters i Load @ or : from the input (= i) { Shift stack to the left [stack: !qx:i@] =? If 4th character was @ ; Exit Else o Print : !o Jump to x Random direction (left or right because up and down retrigger x) Left: ;o!o Print x and exit. Right: ~oo; Remove x, print q! and exit. ``` (will update soon) [Answer] # [Actually](https://github.com/Mego/Seriously), 27 bytes ``` ":q"ü[":x",":q!"]`⌂`J'!,cIƒ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/1/JqlDp8J5oJasKJR0gW1EpNuFRT1OCl7qikquxuZWCX75CeVFmSapCcWZecqpCTmJxiUJyRmJeeqqCRmJKioKiQkm@Qn5ZalFRZkqqplKy57FJ//9/zcvXTU5MzkgFAA "Actually – Try It Online") (Note: As TIO doesn't play nice with stdin, I've replaced the `,` (read from stdin) with the literal string, which you can change to test it. Also, you'll need to disable output cache in order to get a different response with the random output.) Explanation: ``` ":q"ü[":x",":q!"]`⌂`J'!,cIƒ ":q"ü - Push the literal :q and print [":x",":q!"] - Push the list of literals :x and :q! `⌂`J - Push function literals ⌂ (terminate) and J (choose random element from list) '! - Push the literal ! , - Read from stdin c - Pop top two values a,b and return "a".count(b) I - Pop top three values a,b,c and return b if a is truthy and c if a is falsy ƒ - Pop a function from the stack and call it ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 27 bytes ``` ':q'⋄('!'∊⍞)/':q!' ':x'⊃⍨?2 ``` [Try it online!](https://tio.run/##dY09bsJAEIV7n2JcDRTI/BRI25DGRSREJMQFRt4RrGTvkmVlCC1RQCBHaVImNeeaO1AbB6J0eeXT975Hy7yjXyh381reP6djefvoglRf4MlqV5gtw@zxKZLDPt2YUKN6Rjm9tjBGORyl@m4nTRUjoNqgHHdSnUf9uqFruAV7qwAUAhfLoDC6lz@mKB0MH0pTFJQtjGUFSUk@cSV7bzS3f0nsW/3vXMHEwdqbwLAyNmPIqTnLFmTnDC3SGmIIDv6cF@s6WXPHVw "APL (Dyalog Unicode) – Try It Online") `':q'` print this `⋄` then `?2` random integer among the first two `⊃⍨` use that to select from `':q!' ':x'` this list of two strings `(`…`)/` replicate that with, i.e. make *n* copies of each element in that, where *n* is  `'!'∊⍞` is exclamation point a member of the text input? (Boolean, i.e. 0 or 1) [Answer] ## Batch, 98 bytes ``` @echo :q @set/ps= @if %s:~3,1%==@ exit/b @set/an=%random%%%2 @if %n%==0 (echo :x)else echo :q! ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes (32 code, +1 for -n flag) ``` p:q;$_[?!]? p([:q!,:x][$$%2]): p ``` I'm not too sure on the `$$%2` snippet. I'm using it to generate a random bit to index my array by taking the current ruby process's pid modulo 2, and it'll be fairly unpredictable. `.sample` adds an extra byte. [Try it online!](https://tio.run/##KypNqvz/v8Cq0FolPtpeMdZeoUAj2qpQUceqIlavODG3ICdV00qh4P9/xX/5BSWZ@XnF/3XzAA "Ruby – Try It Online") [Answer] # JavaScript, ~~76~~ ~~71~~ 50 bytes ``` prompt(":q")[3]<"@"?alert(new Date%2?":q!":":x"):0 ``` Saved a bunch of bytes thanks to Artyer and Neil, as well as condensing my ternaries and moving first alert to prompt (duh). [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes ``` import time if'w'in input(':q'):print'::qx!'[time.time()%2>1::2] ``` [Try it online!](https://tio.run/##HYpBCsIwFAX3nuJ1IUk3gnEhfNBdt15AREIT7QebpOnX6Okj7WYYmEk/GWIwlUN6C07IttxXrzymmAXCo9/wQxXFAWvRiibVUsocRBFN30Zdl2u3QLdbc94TmVut3eFIuESUzOIxc@g9XnYW9IMNTw9tnUMDiYgfnzM73/4B "Python 2 – Try It Online") Since this is just an agglomeration of [both](https://codegolf.stackexchange.com/a/127479/48878) of [these](https://codegolf.stackexchange.com/a/127480/48878) Python answers, I've marked this as community wiki. [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` print'::qx!'[id(0)%3<2:('N'in input(':q'))*5:2] ``` [**Try it online**](https://tio.run/##BcHNCsIwDADgV8kOklYQpEOE4HXXvYB4KG2wAUm3Lv49uOf6fcvXStXQ@9JEDYnWz4BXye7od@MlkMMZRUF0eZpDWtH7/YnCrXecxjPBXOHdxBg20cTwiJtBKlHvDC7mDANYhfri1iSzx5/WQ4qp8B8) **Explanation:** The source of randomness is `id(0)%3<2`. The function `id` returns the memory location of the parameter. Passing anything will give a non-deterministic memory address. The result will always be even, but it will only sometimes be divisible by 3. The results modulo 3 vary. So, this can be a source of randomness. Using `<2` means that roughly 2/3 of the time, the resulting boolean is `True`. The rest of the answer is inspired by [this one](https://codegolf.stackexchange.com/a/127480/34718). [Answer] ## [Keg](https://esolangs.org/wiki/Keg), ~~14~~ 12 bytes ``` \:~2%[q\!|x] ``` This pushes a random number and outputs corresondingly to the random number. [Answer] # TCL, 95 bytes ``` puts :q;puts [if [string match *!* [gets stdin]] {puts [lindex ":q! :x" [expr round(rand())]]}] ``` A simple and rather long solution in tcl... [Answer] **Assembly 86Bytes** Linux System Calls ``` global _start _start: mov edx,4 mov ecx,g mov ebx,1 mov eax,4 int 0x80 g db ':q!',10 ``` [Answer] # LOGO, ~~37~~ 36 bytes ``` pr[:q]if 4<count rl[pr pick[:q! :x]] ``` Try it online at [Anarchy Golf Performance checker](http://golf.shinh.org/check.rb). # Explanation: ``` pr[:q]if 4<count rl[pr pick[:q! :x]] Main program. pr Print [:q] the list `[:q]` without delimiter `[]` if [ ] If... 4< 4 is less than... count the number of word in the... rl ReadLine (from stdin), pr print pick a random word picked from the list... [:q! :x] [:q! :x] ``` (because `E37@vimmachine: /var/override)` has 2 words, while `E37: No write since last change (add ! to override)` has 10 words) [Answer] # Perl 5 (with -E flag), 35 bytes ``` say":q";<>=~l&&say qw(:q! :x)[$$%2] ``` Run this with `perl -E 'say":q";<>=~l&&say qw(:q! :x)[$$%2]'`. [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/OLFSyapQydrGzrYuR00NyFUoLNewKlRUsKrQjFZRUTWK/f/f1djcSsEvX6G8KLMkVaE4My85VSEnsbhEITkjMS89VUEjMSVFQVGhJF8hvyy1qCgzJVUTAA "Perl 5 – Try It Online") Ungolfed: ``` say(":q"); if(<> =~ /l/){ #read a line and check if it contains 'l' @a=(":q!",":x"); say($a[$$ % 2]); #print one element from array based on PID } ``` ]
[Question] [ You have been hired by the American embassy in the UK to act as a translator. Being a programmer, you decide to write a program to do a bit of the work for you. You've found out that often just doing the following things can satisfy Word's spellcheck, which has been set to "English (United States)", somewhat, so you don't have to do as much work later when translating written documents: * All occurrences of "our" can be replaced with "or", e.g. "favourite" -> "favorite", "our" -> "or". * All occurrences of "ise" and "yse" can be replaced with "ize" and "yze", respectively. * All occurrences of "ae" and "oe" can be replaced with "e". * All occurrences of "ll" that have a vowel before them can be replaced with "l". * The ending "re" can re replaced with "er", as long as it is not preceded by a vowel, e.g. "ore" will not be replaced, but "centre" becomes "center". * The ending "xion" can be replaced with "ction", e.g. "connexion" -> "connection" (this is archaic, but whatever). Write a program or function that takes a string or list of characters as input, performs the replacements mentioned above, and outputs the modified string or list of characters using the [standard IO methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). # Rules * A sequence of alphabetical characters is considered a word (`[A-Za-z]`). Words may be delimited by spaces, hyphens, commas, periods, or other punctuation characters (`[^A-Za-z]`). * A vowel is one of a, e, i, o, or u. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. * Inputs with conflicts are undefined behavior, e.g. if a word ends with "oure", your program can make it "ouer" or "ore". * Your program need only take one pass over the input - it's fine if you replaced something like "rae" and end up with "re" instead of further turning that into "er". * Substitutions may be done on uppercase and/or lowercase letters (you can choose). You may also output the letters in any case you want. ## Test cases Note that not all words have been translated correctly, since the rules described above are not always right. Also note that the text here has mixed case to try to look like normal English, but you can use all lowercase for your input and all uppercase for your output or whatever you want. ``` Substitutions are **bolded** or *italicized* if they are side by side. Input --- Output ______ We would like you to anal**yse** something **our** agencies have discovered. --- We would like you to anal**yze** something **or** agencies have discovered. ______ There have been reports of American t**our**ists trave**ll**ing here in knight's arm**our**. --- There have been reports of American t**or**ists trave**l**ing here in knight's arm**o**r. ______ An **ae**rosol may be the cause of their transfi**xion**. Their **oe**sophagi must be studied. --- An **e**rosol may be the cause of their transfi**ction**. Their **e**sophagi must be studied. ______ **OUR**o**ull**is**ae*****ise***re --- **OR**o**ul**is**e****ize**re ______ Pardon me, I just f**ell** on my keyboard while dodging a knight with a met**re**-long sword. --- Pardon me, I just f**el** on my keyboard while dodging a knight with a met**er**-long sword. ______ My ke**yse**re n'tw**our**kingnowneith**re** r myhands h**ell**llpme --- My ke**yze**re n'tw**or**kingnowneith**er** r myhands h**ell**lpme ______ Haha, I'm just messing with you. No knights here with 3.28-foot-long swords. That's tot**all**y ridiculous. --- Haha, I'm just messing with you. No knights here with 3.28-foot-long swords. That's tot**al**y ridiculous. ``` [Answer] # [QuadR](https://github.com/abrudz/QuadRS), ~~77~~ 75 bytes -2 thanks to Neil. ``` our (i|y)se ae|oe ([aeiou]l)l ([^aeiou])re\b xion\b or \1ze e \1 \1er ction ``` [Try it online!](https://tio.run/##TVHLbhsxDLzrK3hzDDQLFP2C3NpDixwC5JC0AL2iV4y1okNK2WyRf3epdQ4FBFDiY2Y4em0Y9XKRpuGGP9a9UUD6EAo3T0gs7XfeZ7//uT72Ss@H8M5SPIiG569/KZAHP6RhrF65XB4JFmk5QuYTwSoNqgAWzKsRmMxUE5cJnBNwojIyGSR8I4hso7yRUhzCQ/J4TR@ICiidRauBHB2tKZvfq3o55w62dXOBU@Ep1Z0B6uxtQ7grgKRikmHG1bGgJoIRm2vpWIlYO1CxI/fFBnjYUkIm54QTw9ys9jmrLXKX5ri@XmZzU8x5wz1qlAIzfYEf8NLbjy4LemqFE60H8QZYEmffUeLUBeOnVFi4Jn@5K0q3Wbxki6jT/NxmOwGUXXVH9eSDRZZCPuJZdfiEJbp7TpfzeabwHRO6it181TGTWWfbSPwnBvgln8R29WyrfLs9itT/2K3bgN3HKhVzXkE58tiyNBv@AQ "QuadR – Try It Online") The first half of the strings are PCRE patterns while the latter half are their substitutions. [Answer] # [Perl 5](https://www.perl.org/), `-p` ~~100~~ 94 bytes *Saves 6 bytes since we can require all input to be lowercase, as pointed out by @NahuelFouilleul* ``` s/our/or/g;s/[iy]\Kse/ze/g;s/ae|oe/e/g;s/[aeiou]l\Kl//g;s/[^aeiou]\Kre\b/er/g;s/xion\b/ction/g ``` [Try it online!](https://tio.run/##TVHBjtQwDL33K3ybC9NKICQkTnsDjRYQWsRhZ5E8racxk8RVnGwp4tspTrsHTolf7PeeXyZK/u26aicldZK68b12j7w8nU9K3W/aaqQ/Qt1@f0RiKU/@fPLdDvzYkfMp0fnS0U7xiyVa1Wc7u3FdvxPMUvwAnm8EixTIAhjRL0qgEig7jiOYCcCRYs@k4PCZYGDt5ZkSDW3z4Ozc4QtRhESTpKwgV7gLlLjHaLQlsRqYk/V5X1m3MY5wizy6fFDAFKytbe4iICVR8RBwMVLIjqDHYqaM1ApOlSjqletGLTxskJDK5HBkCEVzndNcBq4eP3/7ant6VktFTbf5gmmQCIFewUf4WduvZgsqtMCNlotYA8yOvS0rw1gN44tVmDk7qyyeREcv9qSzJJO532arAMRDtmjTzQajzJFsxNBk9A7jYDGanPdToOYDOjQXh7D7CKRa1TYR@5IWPsmLsO6ZbS9v2tfvjleR/J8BrUlgjTJLRu8XSDxwX7wUbZueovn9K1P9fV2Pk/8H "Perl 5 – Try It Online") [Answer] # JavaScript (ES9), 126 bytes Operates on lowercase patterns. ``` s=>s.replace(/(?<=o)u(?=r)|(a|o|(?<=i|y)s)(?=e)|(?<=[aeiou])l(?=l)|(?<![aeiou])re\b|x(?=ion)/g,s=>[{x:'ct',re:'er',s:'z'}[s]]) ``` [Try it online!](https://tio.run/##tZM9b9swEIZ3/4qrF1morQDtUhhVg2zt0KJDgA5OBlo6SYwpnsGjbMt1f7t7lJPCDiI1HTry5fF9eF8PaqM4c3rtZ5ZyPBbpkdNPnDhcG5Xh5Gpy/TGluJlcpy4@TNSBDkHRhzbmWESMu/NCoabmPjYimU568yQ5vFsedqJrsvFVORX7xc/dPMp8NHU4j9BFU55H@@jXgu/v42NGlslgYqicMKRQTMY/ELbUmByMXiG01IAnUFaZlhGYavSVtiVQ40CVaDONDJXaIOSaM9qgwzwZx/Ho3Dp4pzBgvb@wHnSGtzC@s@N4NHrh87eVRJ0eLREtSGXJeQYq4KZGpzNlhdk4zSJ6J3HGBGT3TFtYWV1WPmJQrpawvkRehzmn9ELc31K6saDQkchQq1Z44CuETDXSDuHJQbsAsVzonbQ9gdtOImRaV6rUUDfswzv2Ta77uyOg13IyfwYa4AwmJvWVYTCaZXZZStPzLQpREqD3Xcyg5XflcrJQ4xS@wEP4TiENhiC1sMJ2SRIA20obGSrKy9AV9dgP2GpfyUmm0OHMkFzxllxvuV5k/TMK3SVqML2vnXOoFdjIyyq5ldha2loUQ1GdwCtlc9kbyduYdd1X1ZPV/o/VhRO6506d0eDfPqtKSSWi@lSLGplDyl2msukJfKPH7Pm0CN3N@@Tdh1lB5M@qwGGwVNgPT14Z04LTuc4aQw33NeO/0Z/Dj78B "JavaScript (Node.js) – Try It Online") ### How? All operations are processed within a single `replace()` with a callback function. We use lookbehind and lookahead assertions so that the sub-strings that actually need to be modified are as small as possible and the replacement is just an implicit empty string whenever possible. The non-empty replacement strings are stored in an object. ``` pattern | replacement ----------------------+------------------------------ (?<=o)**u**(?=r) | "u" -> "" (**a**|**o**|(?<=i|y)**s**)(?=e) | "a" or "o" -> "", "s" -> "z" (?<=[aeiou])**l**(?=l) | "l" -> "" (?<![aeiou])**re**\b | "re" -> "er" **x**(?=ion) | "x" -> "ct" ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~130~~ 125 bytes ``` ≔aeiouζ≔⁺ θηFiy≔⪫⪪θ⁺ιse⁺ιzeθF⌕AθreF¬∨№ζ§ηι№β§η⁺³ι≔⭆Φθ⁻μι⎇⁻μιλerθ⭆θ⎇∨№⁺⊕⌕Aθour⁺⌕Aθae⌕Aθoeκ∧№⌕Aθllκ№ζ§ηκω⎇∧№⌕Aθxionκ¬№β§η⁺⁵κctι ``` [Try it online!](https://tio.run/##jZLBbtswDIbvfQrCl9qAk0O3w4CeggHFOqBbgBbYJRfVZmIuMplQclLn5TPKdtZgwLDl4IgU@fEnqapxWonz5/MiBNpwnjkk6bISTsX9zVoU8ie3y593nmKemSmdrphOCBRwxb0d@nRAcMNX0FKzFWdFCWMSmQ1ZUcBU4KsQT7x9CUvZ5VQUV4f9pe4Dcb3wPkVliokwuL9JzL9r/lk6jvmphEV85Brf8qXvQm6VEqGEATXGvP4Rsx8FWclk3Q2x6XcR@ByVeJO6fiAfUVPCE7HFthP3BZWd9vmVtwRvWNTs0sLSIPGKtX9PW3A9yb9u0fukaftb9l9b2xapxvFfvDcSvhDTzP5nGB9HeuJnVcym0dyfzz8QjtL5GjxtbePSQRRw7LwtH4K0GBvrMz0OcBvkijBA4w4INYVKDqhYz@Glsf/R/YrIoLgTjQFkDYsWlSrHhu2UgjmjWpz3iTqkEcOWadPE2wBOWwubw4Lt1akE8dC63qAQG4TKdSbKoGaQJhCHNaVxDBLMJRhk17gNQduFmPJC7GpKGpdOa2FosYRH@Jlu16YCkquHLfavYgFwbMhbb1Jvkj43KYMjxcYsm4bizItdhaOoUZ@G3JD64Ntok9StJbIcGS3FvGr4xnFtU7Ny3u9anMMX1ziTcduOQlq092nMoYqtYG5rnSqHcUbDzYf53afZWiReKQipc5dGFyU673tQqqnqvHRhfnOeHfwv "Charcoal – Try It Online") Link is to verbose version of code. Expects lowercase input. Explanation: ``` ≔aeiouζ ``` Get the vowels in a variable, as they're long enough for this to save a byte. ``` ≔⁺ θη ``` Make a copy of the input with a space prepended. This is used for cyclic indexing, plus conveniently offsets the indices by one. ``` Fiy≔⪫⪪θ⁺ιse⁺ιzeθ ``` Replace `ise` and `yse` with `ize` and `yze` respectively. ``` F⌕Aθre ``` Find all occurrences of `re`... ``` F¬∨№ζ§ηι№β§η⁺³ι ``` ... that are at the end of a word and do not follow a vowel... ``` ≔⭆Φθ⁻μι⎇⁻μιλerθ ``` ... and replace them with `er`. ``` ⭆θ⎇∨№⁺⊕⌕Aθour⁺⌕Aθae⌕Aθoeκ∧№⌕Aθllκ№ζ§ηκω⎇∧№⌕Aθxionκ¬№β§η⁺⁵κctι ``` If the current character is: * the `u` of `our` * the `a` of `ae` * the `o` of `oe` * or the first `l` of `ll` and it follows a vowel ... then delete it, otherwise if it is the `x` that begins `xion` at the end of a word then replace it with `ct`, and output the final result. [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~110~~ ~~101~~ 100 bytes *A port of [Arnauld's answer](https://codegolf.stackexchange.com/a/216117/83605) in Ruby.* *Saved a whooping 9+1 bytes using* `\K`, *thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!!* ``` gsub /o\Ku(?=r)|(a|o|[iy]\Ks)(?=e)|[aeiou]\Kl(?=l)|[^aeiou]\Kre\b|x(?=ion)/,?s=>?z,'re'=>:er,?x=>:ct ``` [Try it online!](https://tio.run/##tZPBjtNADIbvfQpLHLqV2q4EF4TUrfYGWoE4rMRhC9IkcRPTyTiyZ7ZN1WeneLpd1CKKlgOnxH/GnzP@bUlFv9/Xmgq45sVduprPZLS7cjvePVD/dXGnI5NwtHtwSJxM8BZ7i789C4KLYrcxlTiMrsdznd3Mt@Oh4HB28w5lPN/Ys4z7V4CbDsuIFXCKXYqwZAHvNELpFAezAmsKg489rLDfoiCEYVyzrCjUgdcBKTYoIND2jQuVQoPe@661TAzV/gvCmpOvwNMKoecEkcEF53tFUG4xNgay0gKuxlASGsE9IlSkJT9avWo6uAzZnkH@xrhv8r8f5AIxgGDHEhV4CbctCpUuGDUJqYlR7Jz3GXpIowCrQHUThwpOWjv2UuAp7yLOaLcBHAore2hdb0SwtpoDydpkRAtIMibokjZm6RTuDxKjcte4mqBNZpnlaUwV5Rsb8qXEMp4gLxPt3maDJ7UhU7vIgHNsr5QHY/DZScUBWhzDB/iek5fWRMjSYXoKtgOwbsibNVzVuR/u2AlY2xxZZF4KTjzbJ7Ups6J/pP4zFOUM@t41znjD9onYompOPJy3@ZrCJz4y9Mmyw5c309dvJ0vmeMLS3DaXnYwcnfc9CFVUJs9J/2Od8zLH9dRf65nO9tPU3/YzL@gP7rLtup90PwE "Ruby – Try It Online") [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 106 bytes Sound changes are what Lexurgy is made for! Works in all lowercase only. ``` Class v {a,e,i,o,u} o: our=>or {i,y} se=>{i,y} ze {a,o}=>*/_ e l=>*/@v _ l re=>er/!@v _ x=>ct/_ ion ``` Ungolfed explanation: ``` # define vowels Class vowel {a,e,i,o,u} or: our=>or ize: {i,y} se=>{i,y} ze e: {a,o}=>*/_ e l: l=>*/@vowel _ l er: re=>er/!@vowel _ ction: x=>ct/_ ion ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 94 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•´iÈQ<¾Ÿ7ø₂2>“UcтλHZ•#2ä`.:žMS„ll«D€¨.:DžQAKS¡DεD"xion"Å¿i¨¨¨¨.•U®$•«}žNvDy„re«Å¿i¨¨¨y„erJ].; ``` Input in lowercase. Assumes the input will only contains printable ASCII characters. [Try it online](https://tio.run/##yy9OTMpM/f9f71HDokNbMg93BNoc2nd0h/nhHY@amozsHjXMCU2@2HRut0cUUIGy0eElCXpWR/f5Bj9qmJeTc2i1y6OmNYdW6Fm5HN0X6OgdfGihy7mtLkoVmfl5SodbD@3PPLQCAkHGhx5apwKyZXXt0X1@ZS6VQCOKUg@tRlIHEkot8orVs/7/P7dSITu1sji1KFUhT72kPL@0KDszLz0vvzwvNbMkAyhapJBbmZGYl1KskJGaAwQFuakA) or [verify all test cases](https://tio.run/##TVFNixNBEL3PryiikEt2DvGgRHERcvADlWXZiyc7M5WZMj1dobsn44CBEBD8EbKgeFiIeFJZECJMyHXBv5A/EqszOSwzMNTrV@@9fsNOjQj3H2adZ2Za@gFA57TuRZ3XpT@MMu3j3eJr85M2n84eNevt9f3N9W657D/eLT5fJP@WN3@evhHCnf7m29t4sF2/PN8tLrVuVsPd8ntzFQ@G2/XZkxfnzZfhza9h5z2x6Ww@Nn@puWqfIH/R/LgbXFbz7frVbFiLhMVmdYsXILTP5/N5/HDfa36f7iuEikudgqYJQs0leAZllK4dguMCfU4mAy4tqAxNQuggVzOElFzCM7SYxpHP5dvCI0QDFqdsvQMegyrQUqKMyJaWnIDeCk/roHpYIwMTQ1nuuw6ULYQWR8JXaNmxhkLVIgpiAYkqJZSIykA2CBk3ptBFfIQYHU9zlREUpfNhz/kypZBRdOWempxCcuIbTZVN2UCBPSB4F@hjiQUBqmGC9YiFAFVOWi7LaRYCq2NUqMjnMkk9Fk80y5Gr2IpNuxsMwHS9VGsnsmi4MigrglqRz5VJpUax03paYJSrXEmKbtHmKNC54HYwkV8Sg@GjsWs7O5zci/sPTsbM/lYAF5pQoUrPXmldg6WUklJz6eLIWmzfyKOT5P8B). **Explanation:** ``` .•´iÈQ<¾Ÿ7ø₂2>“UcтλHZ• # Push compressed string "our ise yse ae oe or ize yze e e" # # Split it on spaces: ["our","ise","yse","ae","oe","or","ize","yze","e","e"] 2ä # Split into 2 equal-sized blocks: [["our","ise","yse","ae","oe"],["or","ize","yze","e","e"]] ` # Pop and push both lists separated to the stack .: # Replace all žM # Push builtin "aeiou" S # Convert it to a list of characters: ["a","e","i","o","u"] „ll« # Append "ll" to each: ["all","ell","ill","oll","ull"] D€¨ # Duplicate it, and remove the last character of each: ["al","el","il","ol","ul"] .: # Replace all D # Duplicate the current string žQ # Push a builtin with all printable ASCII characters AK # Remove the lowercase alphabet from it S # Split it to a list of characters ¡ # And split the duplicated string on these non-letter characters D # Duplicate the list of words ε # Map over each word: D # Duplicate the current word "xion"Å¿i } # Pop, and if it ends with "xion": ¨¨¨¨ # Remove the final four characters from the word .•U®$•« # And append (compressed) "ction" žN # Push buitin "bcdfghjklmnpqrstvwxyz" v # Loop `y` over each of its characters: D # Duplicate the current word y„re« # Push the current consonant, and append "re" Å¿i # If it ends with "Cre" (where `C` is the consonant) ¨¨¨ # Remove the final three characters from the word y„erJ # Push the consonant and "er" and join all three together ] # Close the open if-statement, loop, and map .: # And replace all # (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 `.•´iÈQ<¾Ÿ7ø₂2>“UcтλHZ•` is `"our ise yse ae oe or ize yze e e"` and `.•U®$•` is `"ction"`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~227~~ 181 bytes saved 46 bytes thanks to comment. [Try it online!](https://tio.run/##tZRNb9NAEIbv@RWjvRTUJFLhgtq6qFQgkApUaREH16CtPbGXrHei2XVTt@pvD7OO0y9UChJcovnamXfHT7bWocJaB5Pr5XKynUywbKzmtxdzRu8NucE09d@z7eQ4sHHlBOdW55j64ZWihtVoTxGroTIeo20uUZx25bSdozs7WrS2Jql69no3STUaarLn1qpMEvY28a3PMJ6ennVJ5C57IYLWoTyIo66zZUAfPCRwpb4iLKixBVgzQ2ipgUCgnbaiCDzVGCq5A4hw0CW63KCHSp8jFMbndI6MxVgNBwDqpBJnlTtDdMA4J5YpNIX9Glm25aR3wyaODix11sbW3THjYOZMWYUND5prKeu77jvQyOTJQq1b6QyyfMh1I/KksziGYzfnpyZedQwnXYjQ07zSpYG68SGe86EpzI3az18mcm1rvOzNi4JV9EhzQQ5qHMIH@BEPTkUlxFALM2zPSApgURkrC6CijPp1rxwWJlTiycoYR5Yk5RfE64EfuwZxFLiNIDvnmZx2tHAo5yTKMqPSrpD9ykxr53Uv6r2utOjZqFeK6giZNO/GyQcbwyfqJfjVMrvMy/GLV6MpUbgjxcft6LjjQEFb2wKbwuSNpcaP1fXOYIAXc8wDFk@wcXmPjX@Exl0yHgXjDhd/ikVH/ZqLp7CIVAgQ8q/8LRN/jQTyY0hc3iBxjwjkh0T8fyB@5SGvMJ@JlIjDgezbqyGogxisNc@6knfEqZGCrSEY2E3gEF0ZqrR7YjKJbW5G0UEqTuiQFsgH2uMqnaYmy7IdSeOD9JrD24r4XE3T0NlH8q6GVJ0qBbt70lp@xIHRHvQhvw51Xn@JNN2CTXhDZKU/JAl4aZ0NsuVP) ``` R:=RegularExpression f[s_]:=StringReplace[s,{"our"->"or","ise"->"ize","yse"->"yze","ae"->"e","oe"->"e",R["(?<=[aeiou])ll"]->"l",R["(?<=[^aeiou])re\\b"]->"er",R["xion\\b"]->"ction"}] ``` Ungolfed version: ``` f[s_String] := Module[ {replacements, result}, replacements = { "our" -> "or", "ise" -> "ize", "yse" -> "yze", "ae" -> "e", "oe" -> "e", RegularExpression["(?<=[aeiou])ll"] -> "l", RegularExpression["(?<=[^aeiou])re\\b"] -> "er", RegularExpression["xion\\b"] -> "ction" }; result = StringReplace[s, replacements]; result ] ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~158~~ 154 bytes Saved 4 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!!! ``` lambda s:[(s:=re.sub(*x.split(),s))for x in r'our or|ise ize|yse yze|[ao]e e|(?<=[aeiou])ll l|(?<=[^aeiou])re\b er|xion\b ction'.split('|')][-1] import re ``` [Try it online!](https://tio.run/##tVRNb9swDL3nVxC52B6SAG0HrCiWDb1th31g6LBDmgGKTcdaZNEg5eaj6W/PKCcdmm3dB7D5IokS@Z74ntWsQ0X@7LzhXTm@3jlTzwoDcjFJ5WLMOJJ2lj5ZjaRxNqTZQLKsJIYVWA@cUMtAvLWCYDe4Xeu41nFiaIqA2/Tl8/HEoKV2mjkHbh/4fIgwXs8Aebuy5HWWBx2TA1CyTbLpZHgy7dm6IQ7AuAsoQWAMaf8TwpJaV4CzC0WkFgKB8cZFAkI1hsr6OUR2Zo4@tyhQmRuEwkpON8hYjPqD/lWls/3GDFHvgxFKgEq4rJFtbrwWbtlG3MB6zrlYt0vT@y@8nVchETBc67FY8tKDQSYhB7VZa1kIFUJuWiWmZXVhOZbyUtp47xFcdSFCoaYycwt1KyHmSWgLu@f57uMHva2zoo0TxdbQe8MFeahxAK/hS0wplRzE0BoWuJ6RHoBlZZ1emop5pG0OhGFpQ6UrbRPj0JFuyZK4g3rTZUcQ8EnQJvNCUz0tPWqSRlkBKuMLbagCOtfUkc4rUxllktR7LjWKRMQOSOUZwVs6gMu@e93O2ej0fFgShQckJHbExKYGCsa5NbAtbN46akUJZj1cNZgHLH5jhM2REf6FDx7a4FEX3JvgTz3Qmf7eBL/0QLSAqq@/2eMG@Gv9kX@q/@ab/kfyI38v/39W/wfx8wrzhdJQ7ZPr9vTZ0zwZQDc7OUuyXnyZwqBTZWObtHswBnDvmOyiB/oFzQ4jR0vkNOsiqBE8isRnpkzDftGw9SEtk/5tuOvD8AX0b0UntwcyExyPZXqXZLuv "Python 3.8 (pre-release) – Try It Online") Inputs a string in lower-case and returns its translation in lower-case. ]
[Question] [ One of the interesting aspects of gravity is that, as far as I'm aware, you can't just have stuff floating in midair. However, it seems not everyone at the Association of Random Castle Builders is aware of this fact, leading to castles such as this one: ``` # # # # # # ### #### #### # # #### # # #### ### ############## ### ###### ###### ### ##### ##### ### ### `````````````````````````````` ``` and this one: ``` # # # # # # ############## ### #### ### # # # # # # # # ### #### ### # # # # # # # # #### #### #### #### ############## #### #### #### #### #### # # #### # # #### # # #### ## ######## ## #### # # #### # # #### # # #### #################################################################################### ###### ######## ######## ######## ######## ######## ######## ######## ###### ################################### ###### ################################### ################################### ###### ################################### ## ## ## ## ## ```````````````````````````````````````````````````````````````````````````````````````````` ``` and even this one: ``` ########## #### # ### ####################### # # # # # # # # # # ### # # ### # # # # ## # # ## ### # # ##### # ##### # # ##### ##### ## ## ##### ##### ## ## ## ## ```````````````````````````````````````````` ``` # Challenge For a valid castle, all blocks will be connected to the ground either directly or indirectly. Your [program or function](http://meta.codegolf.stackexchange.com/a/2422/13486 "Default for Code Golf: Program, Function or Snippet?") will be given a castle such as the ones above as input, and your program must return a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194/13486 "Interpretation of Truthy/Falsey") reflecting whether the castle is valid or not. ## Rules * Input is given as a string. * All valid castles rest on a surface, ``````````. (If the input string does *not* contain a surface, the castle is invalid.) * You can assume all input will satisfy these criteria: + The surface will always be flat. + The surface will always be at least as wide as the castle, so there will be no blocks to the left or right of the ground. + The input will never have `#` below the surface. + Input will only contain characters given in this challenge. (`#`, ```, space or newline.) + You may assume the input will always contain at least one character. * Blocks are connected if they are either horizontally or vertically adjacent. Diagonal does not count! + Connected: ``` # or ## # ``` + Not connected: ``` # or # # or  # # # ``` * Castles must exist to be valid. (In other words, inputs without any `#` must give a falsy value.) * Input will only contain characters given in this challenge. (`#`, ```, space or newline.) * You may assume the input will always contain at least one character. * Standard [I/O](http://meta.codegolf.stackexchange.com/q/2447/13486 "Default for Code Golf: Input/Output methods") and [loophole](http://meta.codegolf.stackexchange.com/q/1061/13486 "Loopholes that are forbidden by default") rules apply. ## Test cases ### Falsy * All the examples given above. * ``` # # # # #### #### #### # # #### ############## ###### ###### ##### ##### ``` (No ground.) * ``` # ### #### #### # # #### ############## ###### ###### ##### ##### `````````````` ``` (Topmost block is not connected either horizontally or vertically.) * ``` ``` ``` (No castle.) * ``` # # # # # # ############## ##### ## ##### # # # # # # # # #### # # #### # # # # # # # # #### #### #### #### ## #### ## #### #### #### #### #### # # #### # # #### # # #### # # #### # # #### # # #### # # #### # # #### #################################################################################### ###### ######## ######## ######## ######## ######## ######## ######## ###### ################################### ###### ################################### ################################### ###### ################################### ```````````````````````````````````````````````````````````````````````````````````````` ``` (Central tower isn't connected to the rest of the castle because there are no horizontally or vertically adjacent blocks connecting it.) * ``` ``` (No castle.) * ``` ``` (No castle, just a single newline character.) * ``` # # # ``````` ``` (Rightmost block is not connected either horizontally or vertically.) * ``` ``` ``` (No castle.) ### Truthy * ``` # ` ``` * ``` # # # # #### #### #### # # #### ############## ###### ###### ##### ##### `````````````` ``` * ``` # # # # # # ### #### #### # # #### # # #### ### ############## ### ###### ###### ### ##### ##### ### ##### ##### ### `````````````````````````````` ``` * ``` # # # # # # ############## ### #### ### # # # # # # # # ### #### ### # # # # # # # # #### #### #### #### ############## #### #### #### #### #### # # #### # # #### # # #### ## ######## ## #### # # #### # # #### # # #### #################################################################################### ###### ######## ######## ######## ######## ######## ######## ######## ###### ################################### ###### ################################### ################################### ###### ################################### ```````````````````````````````````````````````````````````````````````````````````````````` ``` * ``` #### ### # #### ### # ### # ## # ### ##### ####### ######### ##### ##### ##### ##### ###### ###### ################# # ############# # ############# ############# ############# ###### ###### ###### ###### ############# ############# ############# ############# ###### ###### ###### ###### ############# ############# ############# ############# ###### ###### ###### ###### ############# ############# ############# ############# ############# ##### ##### ##### ##### ##### ##### ````````````````````` ``` * ``` #### ##### ###### #### #### ##### ######## ########## ########## ########### ############ ############## ##### ################ ########### ################# ########################################### ######################################## ##################################### ################################## ############################ ################### `````````````````````````````````````````````````` ``` Good luck! [Answer] ## [Snails](https://github.com/feresum/PMA), ~~21~~ 18 bytes -3 bytes due to additional input constraints edited into challenge. ``` !{t=\#!(\#o`+\`}\# ``` Unfortunately the time complexity is factorial, so most of the inputs aren't runnable. Outputs 0 for falsy cases, and the number of `#` for truthy cases. ``` ,, !{ t ,, Assert that nowhere in the grid, =\# ,, there is a '#' !( ,, such that there does not exist (\# o)+ ,, an orthogonally connected path of '#' \` ,, ending at a '`' ) ,, } ,, \# ,, Match '#' at starting position ``` [Answer] # Octave, ~~53~~ 51 bytes ``` @(s)([~,n]=bwlabel(s>32,4))|n==1&&nnz(diff(+s)==61) ``` [Try It Online!](https://tio.run/#alxIo) \*Since op dropped requirement to check for empty input answer reverted to my first edit. Explanation: ``` nnz(s) check for empty input ([~,n]=bwlabel(s~=' ',4)) label nonempty regions and count number of labels n==1 check if number of labels is 1. nnz(diff(+s)==61) check if blocks connected to the surface ``` [Answer] ## [Grime](https://github.com/iatorm/grime), 29 bytes ``` C=\`|\#&<0C>oX e`\#&C!v#!&\## ``` [Try it online!](https://tio.run/nexus/grime#@@9sG5NQE6OsZmPgbJcfwZWaAGQ7K5YpK6rFKCv//6@srMClrKAMxApcCQkJAA "Grime – TIO Nexus") Most test cases time out on TIO. Replace the `<0C>` with `<0CoF>` to make it a little faster. ## Explanation I'm checking that from every `#` there exists a path to a ```, and that there exists at least one `#`. I recently added rotation commands to Grime, which make this challenge much easier. ``` C=\`|\#&<0C>oX First line: C= Define nonterminal C as \` the literal ` | or \# the literal # &< > which is contained in a larger rectangle 0C containing said literal adjacent to a match of C oX rotated by any multiple of 90 degrees. e`\#&C!v#!&\## Second line: e` Match entire input against this pattern: ! does not v# contain \# the literal # &C! which is not a match of C, & and # contains \# the literal #. ``` [Answer] ## JavaScript (ES6), ~~197~~ 196 bytes ``` f=(s,l=Math.max(...s.split`\n`.map(t=>t.length)),t=s.replace(/^.*/g,t=>t+' '.repeat(l-t.length)),u=t.replace(eval('/(#|`)([^]{'+l+'})?(?!\\1)[#`]/g'),'`$2`'))=>t==u?/#/.test(s)>/#/.test(t):f(s,l,u) ``` Where `\n` represents the literal newline character. Tries to remove all `#`s one at a time by finding one adjacent to a ``` and changing it to a ```. Returns `true` if there was at least one `#` originally but there were all removed. Version that requires padded input for ~~118~~ 117 bytes: ``` f=(s,t=s,u=t.replace(eval('/(#|`)([^]{'+s.search`\n`+'})?(?!\\1)[#`]/'),'`$2`'))=>t==u?/#/.test(s)>/#/.test(t):f(s,u) ``` [Answer] # [Perl 6](http://perl6.org/), 180 bytes ``` {?/\#/&&?all map ->\c{my \b=[map {[$^a.comb]},.lines];sub f(\y,\x){with b[y;x] ->$_ {b[y;x]=0;/\#/??f(y+(1|-1),x)|f(y,x+(1|-1))!!/\`/??1!!|()}}(|c)},map {|($++X ^$^a.comb)},.lines} ``` Checks if the input contains at least one `#`, and if every `#` can find a path to a ```. Rather inefficient, because the pathfinding is brute-forced using a recursive function that always visits all other `#` of the same connected region (i.e. doesn't short-circuit). Uses some unholy interaction between [Junction](https://docs.perl6.org/type/Junction) operators and [slipping](https://docs.perl6.org/type/Slip), to ensure that the path test is skipped for space characters without requiring a separate check for that outside of the pathfinding function. [Answer] # [Python 3](https://docs.python.org/3/), ~~214~~ 206 bytes ``` def f(s): C=s.split('\n');n=max(map(len,C));o=[''];C=[*''.join(t.ljust(n)for t in C+o)] while C>o:o=C;C=['`'if z>' 'and'`'in{C[i+y]for y in(1,-1,n,-n)}else z for i,z in enumerate(C)] return'#'in{*s}-{*C} ``` [Try it online!](https://tio.run/nexus/python3#7VnbbuIwEH33V4zwgxMakPpalL74MygSSA3aVMGpSNBuqfh2loRcfItjp6TblTBIDJw5dmKPz3jI@TXawtbL/CcENMzm2XsS5x55YcRfsHC3@ePtNu9eErGA@v4iDZeErBY0XE4Jmb@lMfPyefJ2yHKP@dt0DznEDOhD6q8Q/P4VJxHQ5/QpDWnBIWsSb@H4TIBs2GvxjX3SZfzwsSqoHxeq9xjMHgMWzJh/ipIsgiMUUBwci34jdthF@00eebTofx/lhz0juOhmmp1mn1N6OtNNlidRFi7RZDJ5QaBt2Pg7Lt@chXEFXFoFXC0MHFA61wDHaJsCtJ8iwBs1oF7sBVgbWzEFgWke1D7LF2dYE4XmwKrnsrl/efJVS2RZMPSLp1rSavUzdIuvtdq@a9vM0ATPbZom@G5j2V4xP74VYdyOrYLU1tPN19Xb3b9krEdsisCIs9uoZKNXNksh36R607pp0E8NrpQMaSHAnfJaqbsGrJQRa5ejBDtVu6aZxuwAsZEJ0AvCYObwbl3DjwsnScAl2ZXEUgomSZhETeDHQHC7bk0bA4m/oDFT8RCNExJTwbFLwkrm6kvCFikY@NwOdinYJgG7Wmi09DtS8h0pQ47S7feko@abICuXjYtsNunF61vkyPHE/j9WLlrgXrncK5d75fLDBNROgoSo15@5qyDs9uD@w@jzMdQ9hn9GnM6y3ZvfIAztVtPUAa3SqSgWUKXc6alTpc0OHYN3XvfXUfgCiv8Rer/mH4B2bkEBBQfyjQ4PTXMgXK8JOfm7EDAeMgKMScCOhEajkJu/9TFsUKHrQHA8Gaq6jdtTV4/3dZakU4ExLwC4FanVwjm4Vytt716HhrU7F0tW3nLw9fheCcPOQCv0vo9Z7i23HvXLp1C0fLZ1fb608s9/AQ "Python 3 – TIO Nexus") The first line here is devoted to padding all the lines to the same length: we split the string (`s.split('\n')` is one char shorter than `s.splitlines()`), find the maximum length of a line, and assign to C a flattened list of all the characters after padding each line. (The newlines are gone.) Then we make a list where each non-space character adjacent to at least one backtick is replaced by a backtick, and continue until no change happened (when the old list `o` is equal to `C`. We can compare with `C>o` instead of `C!=o` because replacing # (ASCII 35) with ` (ASCII 96) can only increase the list's lexicographical ordering.) If no # remains, and at least one was present initially, the castle is valid. * Saved eight bytes checking for # in the set difference, rather than `'#'in s and'#'not in C` ]
[Question] [ # Challenge You will be given a table as input, drawn with ASCII `|` and `_`. Your task is to set the chairs around it. # Example Input: ``` ____ | | | | | | | | |____| ``` Output: ``` _^_^_ < > | | < > | | <_ _ _> v v ``` Those chairs are made of `<>` and `v^`. Another example: The line must have as many chairs as possible in it. ``` _____ | |_____ | | | | | | | _____| |_____| _^_^_ < |_^_^_ | > < | | | < _ _ _> |_ _ _| v v v v ``` There must be spaces between every chair. And `>_^_^_<` is invalid, it should be `|_^_^_|`. ``` _____ _____ | |_____| | | | | | | | | ___________| |_____| _^_^_ _^_^_ < |_^_^_| > | | < > | | < _ _ _ _ _ _> |_ _ _| v v v v v v v ``` No chairs may be on the inside of a "donut". ``` _________________ | _____ | | | | | | | | | | |_____| | |_________________| _^_^_^_^_^_^_^_^_ < _____ > | | | | < | | > | |_____| | <_ _ _ _ _ _ _ _ _> v v v v v v v v ``` `^` and `v` prioritise `<` and `>`. No chair on it's own (it has to have at least one `|` or `_` in the row). ``` _________________ | _____ | | | | | | | |_____| | |_____ |___________| _^_^_^_^_^_^_^_^_ < _ _ _ > | | v v | | < > <_ _ _> | |_^_^_ v v <_ _ _ _ _ _| v v v v v ``` This is code golf, so shortest code wins. [Answer] # Python 2, ~~1033~~ ~~1007~~ ~~924~~ ~~879~~ ~~829~~ ~~787~~ ~~713~~ ~~699~~ ~~692~~ ~~691~~ ~~688~~ ~~687~~ ~~672~~ ~~670~~ ~~664~~ ~~659~~ ~~654~~ ~~648~~ ~~643~~ ~~642~~ ~~630~~ ~~625~~ ~~623~~ ~~620~~ ~~570~~ ~~560~~ ~~554~~ ~~545~~ ~~518~~ ~~514~~ ~~513~~ ~~510~~ ~~505~~ ~~492~~ ~~476~~ ~~454~~ ~~451~~ 443 bytes *6 bytes saved thanks to [Riley](https://codegolf.stackexchange.com/users/57100/riley)* *6 bytes saved thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)* Since this question is over a year old and still has no answers I thought I'd give it a try. ``` n,i,o,u="\nI _";R=lambda x:range(1,x-1) b=open(i).read() s=b.split(n) z=max(map(len,s))+3 a=[list(i+x.ljust(z,i))for x in[i]+s+[i]] for x in R(len(a))*len(b): A=a[x];B=a[x+1];C=a[x-1] for y in R(z): D=A[y-1:y+2];k=B[y];j=A[y+1] if(i in[C[y],k]+D+(k==u)*B[y-1:y+2]or"V"==j)&(A[y]==o):A[y]=i if"|"==A[y]==C[y]:A[y]={i:"|",j:">",A[y-1]:"<"}[i] if[u]*3==D:A[y],B[y]={i:u+k,C[y]:"^"+k,k:" V"}[i] print n.join(`y`[2::5]for y in a).replace(i,o) ``` [Try it online!](https://tio.run/nexus/python2#lVTNb5swFD/Xf4XlSYsdnEi02gXmSU1z2bWHXqiXmjadTAhEkEgk8/72zObTQKJ272A/P36/5/dlQjaZTABcVQIUrKTZVxcE2mLZh2Q15muj5aIBlHrHrqCqF0QvKNWsqsF3bMtjB1bX2RB2VFXf21Lrozk3MdlUO@dO1CBnBW2Msq8BavWxqCu@FQDgQoMu96bsTxPIoAVDrT6DrlKDdZzlGD4Kvefbgo9Hqh96C7fyawdjHLuq4XZabTvV/8BHlWmGsoXXXRxUXg22Bn7F7QdwqwifgCs4GO7@U7Tgdn/G8HbUwYWuqN4D6Y0quPwQFNA/mXNCJU3pgaHn5CdcIf@RxWIbvglYeJlIfq@xS4uZS8CXkKW7dYIlmWdr8YYJyFk4z3ex3OOEgBPbigJvxQ7H64TmhDh3QLAglvkeS6eYx9FBaycqCXlPM1hAmQSSO7mjVw4aE3w0dCwImZo9JB6A90wEBfcXZnNc7j8YZeZyAA3rWLFOGnmzZPfBceZ6R@eW@xu2CI7cj4xN08CNfMfS3PqgzXTDnaWDN4wdyHTRktIMPSHGIvIVaxZnLCVeqUhDR0p/q@zGR/Xlj/S0nUYe@oFoeT330Hf0V6dlOMGBT@8YW5ZguqgZB2dDSxfoF9LqxkPwqaLsMpnsYTKPUpngl@NLcOt533ibqDDF38XidY1118j5/A8) The program reads the table a file named `I` and prints the table with its chairs to `std::out`. I was not sure about a bunch of the edge cases so I took my best judgement (whatever took the least effort) but it seems to pass all the test cases. Some of the outputs don't match exactly but they all have the same number of chairs. ## Explanation The first line pretty simply sets up some definitions that will save us bytes in the future: *(I will unpack these macros for readability in future lines)* ``` n,i,o="\nI ";R=lambda x:range(1,x-1) ``` Then we will open a file named `I` because we already have a variable that is short for that so it saves a few bytes. ``` b=open("I").read().split("\n") ``` We split along newlines to create a list of strings (The rows of the image) ``` s=b.split(n) ``` I then find the length of the longest line so that I can pad all lines to that length. (I also add 3 because we need a bit of additional padding) ``` z=max(map(len,s))+3 ``` Then we perform the actual padding and create a border of `I` characters around the edge. This is because we will need to tell the difference between the inside and the outside of the shape later on. We will also change the data type from a list of strings to a list of list of characters (length 1 strings). ``` a=[list("I"+x.ljust(z,"I"))for x in["I"]+s+["I"]] ``` The next line is just another byte saving definition. *(I will also unpack this one)* ``` B=R(len(a)) ``` Now we want to spread `I` characters to everywhere outside of the shape. We can do this with a pseudo-cellular automaton. Each `I` will spread to any adjacent characters. We could loop until the automaton stabilizes however this cannot take more iterations than there are characters so we just loop through every character in `b` (the original input) ``` for _ in b: ``` For each iteration we want to pass over every character in the 2D list (excluding the outermost padding) ``` for x in range(1,len(a)-1): A=a[x] #<--Another definition I will fill in for clarity for y in range(1,z-1): ``` For each position we run the following code: ``` if("I" in[a[x+1][y],a[x-1][y]]+a[x][y-1:y+2])&(a[x][y]==" "):a[x][y]=" " ``` Lets break this down. We have an if with two conditions separated by a `&` (bitwise `and`) The first one simply checks if there is an `I` in any of the adjacent cells and the second one just checks if the current cell is a `" "`. If we pass those conditions we set the current cell to be an `I`. --- Now that we have determined the outside and inside of the shape we can start to place the chairs around the table. Once again we loop through all of the cells (and set some more shorthands) ``` for x in range(1,len(a)-1): A=a[x] for y in range(1,z-1): k=a[x+1][y] ``` Now here's my favorite part. If you have trudged through my boring, mostly definition based, golfing so far I am going to reward you with a nice tidbit of clever golfing (if I do say so myself). A little background in python: In Python if you attempt to assign an dictionary key twice it asigns the latter one. For example ``` >>> {1:"a",1:"b"}[1] 'b' ``` We will abuse this property to assign the current cell to a particular character. The first condition is ``` if["_"]*3==a[x][y-1:y+2]:a[x][y],a[x+1][y]={"I":"_"+a[x+1][y],a[x-1][y]:"^ ",a[x+1][y]:" V"}["I"] ``` If the cell is in the middle of an edge of 3 `_` characters we will reassign the current cell and the cell below it. We will assign it to the result of indexing an overloaded dictionary by `I`. We first set our default with the pair `"I":"_"+a[x+1][y]` this means if there is no change we will assign the two cells back to their original values. Next we add the pair `a[x-1][y]:"^ "`. This wont do anything (important) unless the cell above the current one (`a[x-1][y]`) is filled with an `I`. If it has an `I` in it it will override the default telling us to place a chair at the current cell. Next we move on to the cell below the current cell if that cell is `I` we again override to place an upwards facing chair below the current spot. The next condition is a tad simpler ``` if"|"==a[x][y]==a[x-1][y]:a[x][y]={"I":"|",A[y+1]:">",A[y-1]:"<"}["I"] ``` We check if the current cell and the cell above it are both `|`. If so we set up a dictionary. The first pair in the dictionary `"I":"|"` sets the default. Since we are going to access the key `I` if `I` does not get reassigned it will default back to `|` (the character it already is) and do nothing. We the add the two keys `A[y+1]:">",A[y-1]:"<"` If either of the two cells to the left and right are `I` then it will reassign the current cell to a chair pointing in the direction of the outside. --- Now we just have to output. However we can't just print, there are a couple of housekeeping things we have to do first. We have to convert back to a string and remove all of the `I`s we created. This is done in one line. ``` print "\n".join(`y`[2::5]for y in a).replace("I"," ") ``` ]
[Question] [ ## The challenge Your program or function will accept a single string input from STDIN or a function parameter. You can assume the input will contain only alphabetic characters (a-zA-Z), spaces, and full stops. Input is case insensitive, so you should treat 'a' exactly the same as you would treat 'A'. For each character in the string, you will output a representation of a building as per the following specification. Each building must have a roof, designated by an underscore on the top line then a slash, space, backslash on the second line. ``` _ / \ ``` You will then have a number of floors, matching the letter number (a=1, b=2, c=3 etc.) which are represented by a wall (|) on each side and a space in the middle. The bottom floor (and only the bottom floor) should have a foundation, which is an underscore between the walls. Like this... ``` |_| ``` So for example, 'b' would look like this ``` _ / \ | | |_| ``` Now, we know that very tall, narrow buildings cannot stand and must get wider at the base, so no building can stand more than three storeys high without some additional support. So every three levels (no less) you should add a 'widening layer'. The widening layer consists of a slash and backslash directly above the walls of the section below it, and the section below should be two spaces wider than the section above. The extra layer does not count towards the height of the building. Buildings should not overlap but should not have any unnecessary spaces between them, and the ground is always flat so all buildings should have their base on the same level. For example, 'abcdefga' will look like this. ``` _ / \ _ | | _ / \ | | _ / \ | | | | / \ | | | | / \ _ | | | | | | | | _ / \ | | | | / \ | | _ / \| | | | / \| | | | _ / \| || |/ \| || |/ \/ \ |_||_||_||___||___||___||_____||_| ``` Spaces in the string input should be represented by a double space. Full stops in the string input should be represented by rubble like this. ``` /\/\ ``` ## Further examples Input = `Hello world.` Output = ``` _ / \ | | | | | | / \ | | | | _ | | / \ / \ | | | | | | _ | | _ | | / \ | | / \ / \ | | / \ | | | | | | | | | | | | _ _ | | | | | | | | _ / \ / \ / \ | | / \ / \ / \ | | | | | | / \ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | _ / \ / \ / \ | | / \ / \ / \ / \ | | | | | | / \ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | _ / \ / \ / \ | | / \ / \ / \ / \ / \ | | | | | | / \ | | | | | | _ | | | | | | | | | | | | | | | | | | / \ | | | | | | | | | | | | | | | | | | | | | | | | / \/ \/ \ | | / \/ \/ \ | | / \/ \| || || | / \| || || | | | | || || || || | | || || || |/ \ |_____||___||_______||_______||_________| |_______________||_________||___________||_______||___|/\/\ ``` Input = `lorem ipsum` ``` _ / \ _ | | / \ | | _ | | | | / \ | | / \ | | _ | | | | | | / \ / \ | | _ | | | | | | | | / \ / \ | | | | / \ | | | | _ | | | | | | _ | | | | / \ / \ / \ | | / \ _ | | | | | | | | | | | | | | / \ / \ / \ | | | | | | / \ | | | | | | | | | | | | | | | | | | | | | | | | / \ / \ / \ | | / \ | | | | | | | | _ | | | | | | | | / \ / \ / \ | | / \ | | | | / \ | | | | | | | | | | | | | | | | | | | | | | | | | | / \ | | / \ / \ | | / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ _ | | / \ | | | | / \ | | | | | | | | / \ | | | | | | | | | | | | | | | | | | | | / \ | | / \ / \ | | / \ | | | | | | | | | | | | | | | | | | | | / \/ \/ \ | | | | / \ | | | | / \ | | | || || |/ \ | | | | | | | | | | | | | || || || |/ \ | |/ \/ \| |/ \ |_______||_________||___________||___||_________| |_____||___________||_____________||_____________||_________| ``` Input = `a.a.a.x.x.x.a.a.a` ``` _ _ _ / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ | | | | | | | | | | | | | | | | | | / \ / \ / \ _ _ _ | | | | | | _ _ _ / \ / \ / \ | | | | | | / \ / \ / \ |_|/\/\|_|/\/\|_|/\/\|_______________|/\/\|_______________|/\/\|_______________|/\/\|_|/\/\|_|/\/\|_| ``` ## Rules * Of course this is code golf, lowest score in bytes wins * Standard loophole rules apply * Any number of additional blank lines before or after the output are allowed * You can choose to output the entire result in one string or offer the output as an array where each element represents one line of output, or send to STDOUT ## Note This is my first post to PPCG, so please go easy on me. It's been through the sandbox. Any negative points or possible improvements please post as a comment and I'll do what I can [Answer] ## JavaScript (ES6), ~~330~~ ~~326~~ ... ~~315~~ 309 bytes Builds the ASCII art recursively, starting with the bottom floor and applying several regular expressions between each stage: ``` (a,l,R=(E,b)=>E.split`:`.map((e,i)=>l=(l||a).replace(RegExp(e,'g'),b?b.split`:`[i]:n=>(x=(n.charCodeAt()-65)%32)<0?x+1?'/y/y':n+n:x%3+'_'.repeat((x/3<<1)+1)+0)))=>(L=l)?(R('/y:_:/xy:1:2:/xx(x+)y:0(x+)0:3',' :x: _ :3:1: 2$10 :/$1y:0'),L==l?(l=a.join` `,R('\\d:x:y','|: :\\'),l):f([l].concat(a),l)):f(R('.'),l) ``` ### How it works **1) Bottom floor** We start by translating the input string into a bottom floor such as: ``` "ab cd.df.hcab" --> "0_01_0 2_00___0/y/y0___02___0/y/y1_____02_00_01_0" ``` where: * `y` is a shorter alias for the backslash (which requires escaping) * The digit (`0`, `1` or `2`) just before a sequence of `_` is the left wall of the building. It represents the number of walls that must be placed above it before the next 'widening layer'. * The digit after a sequence of `_` is the right wall of the building and is always set to `0`. **2) Regular expressions applied between each stage** The recursive process consists of applying 9 replacements on the previous floor, using the following regular expressions: 1. `/\/y/g` => `" "` (remove the rubble) 2. `/_/g` => `"x"` (replace the foundation or the top of the building with a solid block) 3. `/\/xy/g` => `" _ "` (replace the last widening layer with the top of the building) 4. `/1/g` => `"3"` (temporarily replace `1` with `3` -- see last step) 5. `/2/g` => `"1"` (replace `2` with `1`) 6. `/\/xx(x+)y/g` => `" 2$10 "` (replace a widening layer with a new, narrower wall) 7. `/0(x+)0/g` => `"/$1y"` (replace the top of the wall with a widening layer) 8. `/3/g` => `"0"` (replace `3` with `0`) For instance, here are the successive transformations of `2___0` (bottom floor generated by a `'f'`): ``` "2___0" > "1xxx0" > "0xxx0" > "/xxxy" > " 2x0 " > " 1x0 " > " 0x0 " > " /xy " > " _ " _ /xy /xy 0x0 0x0 0x0 1x0 1x0 1x0 1x0 2x0 2x0 2x0 2x0 2x0 /xxxy /xxxy /xxxy /xxxy /xxxy /xxxy 0xxx0 0xxx0 0xxx0 0xxx0 0xxx0 0xxx0 0xxx0 1xxx0 1xxx0 1xxx0 1xxx0 1xxx0 1xxx0 1xxx0 1xxx0 2___0 2___0 2___0 2___0 2___0 2___0 2___0 2___0 2___0 ``` ***NB**: The top of the building is then replaced by a `x`. This is not shown in the above diagram.* **3) Regular expressions applied to the final result** The recursion stops when there's nothing more to replace, which means that we are beyond the top of the highest building. We now need to clean up everything with yet another few regular expressions: 1. `/\d/g` => `"|"` (replace digits with pipes) 2. `/x/g` => `" "` (replace solid blocks with spaces) 3. `/y/g` => `"\"` (replace `y` with backslashes) For instance: ``` _ _ /xy / \ 0x0 | | 1x0 | | 2x0 --> | | /xxxy / \ 0xxx0 | | 1xxx0 | | 2___0 |___| ``` ### Demo ``` let f = (a,l,R=(E,b)=>E.split`:`.map((e,i)=>l=(l||a).replace(RegExp(e,'g'),b?b.split`:`[i]:n=>(x=(n.charCodeAt()-65)%32)<0?x+1?'/y/y':n+n:x%3+'_'.repeat((x/3<<1)+1)+0)))=>(L=l)?(R('/y:_:/xy:1:2:/xx(x+)y:0(x+)0:3',' :x: _ :3:1: 2$10 :/$1y:0'),L==l?(l=a.join` `,R('\\d:x:y','|: :\\'),l):f([l].concat(a),l)):f(R('.'),l) console.log(f('ab cd.df.hcab')); ``` *Contributors:* *4 bytes saved thanks to Hedi* *8 bytes saved thanks to Not that Charles* [Answer] # PHP, ~~386~~ ~~376~~ ~~367~~ ~~364~~ ~~362~~ ~~358~~ 356 bytes first approach; may still be golfable. ``` foreach(str_split($argv[1])as$c)for($n=28,$w='.'!=$c?1+2*ceil(1/3*$n=31&ord($c)):4,$p=$y=0;$y<36;){$s=str_pad("",$w,$y||!$n?" ":_);if($n>26&&!$y){$s="/\\/\\";$n=-1;}elseif($n-->0){$s[$p]=$s[$w-$p-1]="|";if($n%3<1){$o[$y++].=$s;$s=str_pad("",$w);$s[$p]="/";$s[$w-++$p]="\\";}}$o[$y++].=$s;if(!$n)$o[$y++].=str_pad(_,$w," ",2);}for($y=36;$y--;)echo"$o[$y] "; ``` **PHP, ~~366~~ ~~362~~ ~~361~~ ~~360~~ 357 bytes** similar approach with a subfunction: ``` function a($p,$r){global$o,$w,$y;$o[$y++].=str_pad(str_pad($r[0],2*$p,$r[1]).$r[2],$w," ",2);}foreach(str_split($argv[1])as$i=>$c)for($n=28,$w='.'!=$c?1+2*$p=ceil(1/3*$n=31&ord($c)):$p=4,$y=0;$y<36;)if($n>26&&!$y)$o[$n=$y++].="/\\/\\";elseif($n-->0){a($p,$y?"| |":"|_|");if($n%3<1)a($p--,"/ \\");if(!$n)a(1," _");}else a(0,"");for($y=36;$y--;)echo"$o[$y] "; ``` **breakdown** for the second approach ``` function a($p,$r) { global$o,$w,$y; $o[$y++].= // 3. add result to current line, increase line counter str_pad( // 2. pad ... str_pad($r[0],2*$p,$r[1]).$r[2] // 1. A + inner width(=2*$p-1) times B + C ,$w," ",2); // ... to $w with blanks on both sides # 2==STR_PAD_BOTH } foreach(str_split($argv[1])as$i=>$c) for( $n=28, $w='.'!=$c // $w=total width ?1+2*$p=ceil(1/3*$n=31&ord($c)) // $n=storey count, $p=(inner width+1)/2 :$p=4 // $n=28, $p <= $w=4 for rubble , $y=0;$y<36;) // $y=line counter if($n>26&&!$y) $o[$n=$y++].="/\\/\\"; // bottom line=rubble, $n=0 elseif($n-->0) { a($p,$y?"| |":"|_|"); // add storey if($n%3<1)a($p--,"/ \\"); // add widening layer/roof if(!$n)a(1," _"); // add roof top } else a(0,""); // idk why str_pad doesn´t yield a warning here for($y=36;$y--;)if($s=rtrim($o[$y]))echo"$s\n"; // output ``` --- +16 bytes if leading newlines are not allowed: Replace `echo"$o[$y]\n;` with `if($s=rtrim($o[$y]))echo"$s\n";`. -3 bytes for any of `;<=>?[\]^_{|}~` as rubble: Replace 1) `($n=31&ord($c))` with `$n`, 2) `$n=28,$w='.'!=$c` with `($n=31&ord($c))<27` and 3) `4` with `($n=28)/7`. Another -8 for `>`, `^` or `~` as rubble: Undo 3) [Answer] # Pyth, ~~93~~ 79 bytes ``` K"/\\"j_.tsm?hJxGdC_m.[hyNk\ +\_mj*hy/k4?nkJ\ \_?%k4"||"Kh=+J=Nh/J3[F*2|@d;Krz0 ``` [Try it online.](http://pyth.herokuapp.com/?code=K%22%2F%5C%5C%22j_.tsm%3FhJxGdC_m.%5BhyNk%5C%20%2B%5C_mj*hy%2Fk4%3FnkJ%5C%20%5C_%3F%25k4%22%7C%7C%22Kh%3D%2BJ%3DNh%2FJ3%5BF*2%7C%40d%3BKrz0&input=Hello+world.&test_suite=1&test_suite_input=abcdefga%0AHello+world.%0Alorem+ipsum%0Aa.a.a.x.x.x.a.a.a&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=K%22%2F%5C%5C%22j_.tsm%3FhJxGdC_m.%5BhyNk%5C%20%2B%5C_mj*hy%2Fk4%3FnkJ%5C%20%5C_%3F%25k4%22%7C%7C%22Kh%3D%2BJ%3DNh%2FJ3%5BF*2%7C%40d%3BKrz0&input=Hello+world.&test_suite_input=abcdefga%0AHello+world.%0Alorem+ipsum%0Aa.a.a.x.x.x.a.a.a&debug=0) ### Explanation I hid this away by default since it's way too long. ``` <ul type="disc"><li>Initialize <code>K</code> to <code>"/\"</code>.</li><li>Lowercase (<code>r</code>&hellip;<code>0</code>) the input (<code>z</code>).</li><li>For each (<code>m</code>) character <code>d</code> in the lowercase input:</li><ul type="disc"><li>Find the index (<code>x</code>) of the character (<code>d</code>) in the alphabet (<code>G</code>). This results in a number 0-25 for the letters and -1 for anything else. Save the index to <code>J</code>.</li><li>Add one (<code>h</code>). This results in a positive number for the letters and 0 for anything else.</li><li>If the result was nonzero (<code>?</code>):</li><ul type="disc"><li>Int-divide (<code>/</code>) <code>J</code> by <code>3</code> and increment (<code>h</code>) and save (<code>=</code>) the result to <code>N</code>.</li><li>Increment (<code>=+</code>) <code>J</code> by that amount.</li><li>Add one (<code>h</code>). This yields the height of the house excluding the roof.</li><li>For each (<code>m</code>) number <code>k</code> from 0 to result-1:</li><ul type="disc"><li>Take <code>" "</code> (<code>\ </code>) if (<code>?</code>) the number (<code>k</code>) is not equal to (<code>n</code>) <code>J</code>, otherwise take <code>"_"</code> (<code>\_</code>).</li><li>Int-divide (<code>/</code>) the number (<code>k</code>) by <code>4</code>, double (<code>y</code>) and add one (<code>h</code>).</li><li>Multiply the string by the number (<code>*</code>).</li><li>Take <code>"||"</code> if (<code>?</code>) the number (<code>k</code>) is not divisible by 4 (<code>%</code>&hellip;<code>4</code>), otherwise take the string in <code>K</code>.</li><li>Join (<code>j</code>) that string by the previous one. This puts the previous string in the middle.</li></ul><li>Prepend (<code>+</code>) a <code>"_"</code> (<code>\_</code>) to the resulting list to add the roof.</li><li>For each line <code>k</code> in the list:</li><ul type="disc"><li>Take <code>N</code>, double (<code>y</code>) and add one (<code>h</code>).</li><li>Pad (<code>.[</code>) the line (<code>k</code>) to that length with spaces (<code>\ </code>).</li></ul><li>We now have the rows for this one house. Reverse (<code>_</code>) and transpose (<code>C</code>) the result to get the reversed columns.</li></ul><li>If the result was zero (all the way up there):</li><ul type="disc"><li>Take the intersection (<code>@</code>) of the character (<code>d</code>) and <code>" "</code> (<code>;</code>). This yields an empty string for periods and a space for itself.</li><li>Logical OR (<code>|</code>) that with the string in <code>K</code>. This yields that string for periods and a space for itself.</li><li>Repeat that string (<code>*</code>) <code>2</code> times and cast to array (<code>[F</code>). This yields the (reversed) columns for spaces and periods.</li></ul></ul><li>Concatenate (<code>s</code>) the resulting lists. This yields the total reversed columns for the output.</li><li>Transpose, padding with spaces (<code>.t</code>), reverse (<code>_</code>) and join by newline (<code>j</code>). Implicitly print the output.</li></ul> ``` [Answer] # Perl, ~~147~~ 146 bytes Includes +1 for `-p` Run with input on STDIN, e.g. ``` citysky.pl <<< " abcdefgxyz." ``` `citysky.pl`: ``` #!/usr/bin/perl -p s%.%@{[map chr~-ord(lc$&)*4/3-4*(abs||-9),-9..9]}%g;y/M\xa248 A|-\xc6\0-\xff/MA|| A}-\xc6A/d,$a=(lc$a).$_ for($_)x36;*_=a;s/\x9f.*?\K\x9f/\xa3/g;y%A\xc6\x9f-\xa3\x0b-\xff%__/|||\\ % ``` Works as shown, but replace the `\xhh` escapes by their literal value to get the claimed score. You can do that using this commandline: ``` perl -0pi -e 's/\\x(..)/chr hex $1/eg;s/\n$//' citysky.pl ``` I haven't really explored any other approaches, so this may be very beatable... [Answer] # Haskell, 289 bytes ``` c?l=c++l++c c%s=("|"?(drop 2(r s)>>c)):s g 46=["/\\"?""] g 32=[" "] g x="_"%h(mod x 32) h 1=["/ \\"," _ "] h x=(" "%h(x-1))!x v!x|mod x 3/=1=v|z<-'/':r v++"\\"=z:map(" "?)v r v=v!!0>>" " f t|l<-map(g.fromEnum)t,m<-maximum(map length l)-1=unlines[l>>= \x->(x++cycle[r x])!!i|i<-[m,m-1..0]] ``` [Answer] ## Ruby, 245 ``` ->s{a=['']*36 w=' ' s.chars{|c|a[u=0]+=c<?!?w*2:c<?/?"/\\"*2:(h=c.upcase.ord-64 1.upto(1+h+=(h-1)/3){|t|u=[u,l=1+2*((f=h-t)/4)].max a[t]+=w*(a[0].size-a[t].size)+(f<-1?w:f<0??_:(f%4<1?[?/,?\\]:[?|]*2)*(w*l)).center(u+2)} "|#{?_*u}|")} a.reverse} ``` You allow as many extra newlines as you want, so I'm taking liberty with that. Aside from that, the process is as follows: 1. Initialize an output array `a`. 2. For each char: 1. if it's ' ', add to `a[0]` 2. if it's '.', add `/\/\` to `a[0]` 3. otherwise: 1. calculate the height (`c.upcase.ord + (c.upcase.ord-1)/3`) 2. for each row in `a`: 1. pad the row with whitespace. `a[t]+=w*(a[0].size-a[t].size)` 2. if we're one above `h`, center a `_` 3. else if we're above height, center a 4. else if we're below height, center `| |` or `/ \` of the proper width (`1+2*((h-t)/4`), depending on if `h-t%4==0` 5. add `"|___|"` of the right width to `a[0]` 3. return `a.reverse` I bet I can get it smaller if I work out the math to avoid `reverse` [Answer] # PHP, 297 bytes ``` foreach(str_split($argv[1])as$c)for($j=0,$h=ord($c)-64,$g=$h+$f=ceil($h/3),$w=$v=$h<0?$h<-18?2:4:2*$f+1;$j<36;$j++,$g--,$v-=$h>0&&$v>1?($g%4||!$j)?0*$n="|$s|":2+0*$n="/$s\\":$v+0*$n=['','_','',0,'/\/\\'][$v],$o[$j].=str_pad($n,$w,' ',2))$s=str_repeat($j?' ':'_',$v-2);krsort($o);echo join($o,' '); ``` A more readable version: ``` foreach (str_split($argv[1]) as $character) { for ( $line = 0, $buildingHeight = ord($character) - 64, $floorsLeft = $buildingHeight + $supportFloors = ceil($buildingHeight / 3), $buildingWidth = $widthOnThisFloor = $buildingHeight < 0 ? $buildingHeight < -18 ? 2 : 4 : 2 * $supportFloors + 1; $line < 36; // The body of the for-loop is executed between these statements $line++, $floorsLeft--, $widthOnThisFloor -= $buildingHeight > 0 && $widthOnThisFloor > 1 ? ($floorsLeft % 4 || !$line) ? 0 * $floorString = "|$middleSpacing|" : 2 + 0 * $floorString = "/$middleSpacing\\" : $widthOnThisFloor + 0 * $floorString = ['', '_', '', 0, '/\/\\'][$widthOnThisFloor], $outputArray[$line] .= str_pad($floorString, $buildingWidth, ' ', 2) ) { $middleSpacing = str_repeat($line ? ' ' : '_', $widthOnThisFloor - 2); } } krsort($outputArray); echo join($outputArray, ' '); ``` ]
[Question] [ You are a talented young chef who has just been offered the position of [sous chef](https://en.wikipedia.org/wiki/Sous_chef) at the world's most prestigious Indian restaurant. You have little experience with preparing Indian cuisine, but you're determined, so you set out to prove yourself. You decide to become the leading [dosa](https://en.wikipedia.org/wiki/Dosa) expert. To do this, you must not only master the creation of dosas, but you must be able to scale them to be arbitrarily large. You find a promising [recipe](http://www.vegrecipesofindia.com/masala-dosa-recipe-how-to-make-masala-dosa-recipe) for dosa batter: * 1 cup rice * 1 cup ukda chawal * 1/2 cup urad dal * 1/4 cup poha * 1/4 tsp methi seeds * Salt to taste * Water as needed This will make a dosa approximately **1/2 meter** in length. ## Challenge Write a program or function that will tell the restaurant staff exactly what's needed to make a single dosa out of an integer multiple of the given recipe[.](http://largedosas.freeforums.net) Space is tight in the kitchen, so you want your code to be as short as possible. The shortest code wins, with ties going to the earlier post. Measuring spoons and cups come in the following standard sizes: 1/4, 1/3, 1/2, 2/3, 3/4, and 1. To avoid angering the kitchen staff, measurements must be reported in the **largest unit** in which the number can be written as mixed numbers using **standard sizes only**. Measurements propagate to larger sizes per the following convention: * 3 tsp == 1 tbsp * 4 tbsp == 1/4 cup So for a multiple of 12, 1/4 tsp methi seeds becomes 1 tbsp. However, for a multiple of 13, it becomes 3 1/4 tsp. Otherwise it wouldn't be represented in standard sizes. The wait staff must be able to carry the dosa to the tables. To ensure that the dosa does not break in transit, you instruct them to carry the dosa in teams. **Each person can carry at most one meter of dosa.** So for a single or double recipe, only one person is needed to carry it. The wait staff is less effective if they're cut into fractional pieces, so an **integer number of waiters** is always required. ## Input Take a positive integer via STDIN (or closest alternative), command line argument, or function argument. This number dictates the scaling factor for the recipe and can be as small as 1 but no larger than 232-1. It can be any integer in that range. ## Output Print to STDOUT (or closest alternative) the list of ingredients scaled according to the input as well as the number of waiters required to carry the dosa. The ingredients must be listed in the order given above and in the format given below. ## Examples Input: ``` 2 ``` Output: ``` 2 cups rice 2 cups ukda chawal 1 cup urad dal 1/2 cup poha 1/2 tsp methi seeds Salt to taste Water as needed 1 waiter ``` Note that "cup" changes to "cups" when the value is greater than 1. "tsp" does not change. "waiter," like "cup," becomes plural. Input: ``` 5 ``` Output: ``` 5 cups rice 5 cups ukda chawal 2 1/2 cups urad dal 1 1/4 cups poha 1 1/4 tsp methi seeds Salt to taste Water as needed 3 waiters ``` Non-integer values greater than 1 are represented as mixed numbers, i.e. an integer followed by a reduced fraction. Note: The title comes from [a relevant video](https://www.youtube.com/watch?v=nlGzc4PI2Kc). [Answer] # CJam, 214 bytes ``` ri[48_24C.25]{[48ZX]f{:DW$@*\md_D{_@\%}h;:M/iDM/}3/_{W=5<}#:I=[(\'/*]{S+_0e=!*}/["cup"2$2a>'s*+"tbsp"_'b-]I=S}%4/"rice ukda chawal urad dal poha methi seeds Salt to taste Water as needed"N/.+N*N@)2/" waiter"1$1>'s* ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri%5B48_24C.25%5D%7B%5B48ZX%5Df%7B%3ADW%24%40*%5Cmd_D%7B_%40%5C%25%7Dh%3B%3AM%2FiDM%2F%7D3%2F_%7BW%3D5%3C%7D%23%3AI%3D%5B(%5C'%2F*%5D%7BS%2B_0e%3D!*%7D%2F%5B%22cup%222%242a%3E's*%2B%22tbsp%22_'b-%5DI%3DS%7D%254%2F%22rice%0Aukda%20chawal%0Aurad%20dal%0Apoha%0Amethi%20seeds%0ASalt%20to%20taste%0AWater%20as%20needed%22N%2F.%2BN*N%40)2%2F%22%20waiter%221%241%3E's*&input=13). [Answer] # Javascript (ES6), 443 chars This was very fun to golf, but the result is considerably longer than what I was expecting. ``` d=n=>(y=s=>n<s?' cup':' cups',z=s=>n/s|0,A=' 1/4',B=' 1/2',C=' 3/4',n+y(2)+` rice ${n+y(2)} ukda chawal ${(n%2<1?n/2:z(2)+B)+y(3)} urad dal ${((e=n%4)<1?n/4:z(4)+(e<2?A:e<3?B:C))+y(5)} poha ${(n%48<1?z(192)+((c=n/48%4)>2?C:c>1?B:c>0?A:'')+y(193):n%3<1?z(12)+((f=n/3%4)>2?C:f>1?B:f>0?A:'')+' tbsp':(z(4)+(e>2?C:e>1?B:e>0?A:''))+' tsp')} methi seeds Salt to taste Water as needed ${(b=Math.ceil(n/2))} waiter`+(b<2?'':'s')).replace(/\n0 /g,'\n') ``` Try it out: ``` d=n=>(y=s=>n<s?' cup':' cups',z=s=>n/s|0,A=' 1/4',B=' 1/2',C=' 3/4',n+y(2)+` rice ${n+y(2)} ukda chawal ${(n%2<1?n/2:z(2)+B)+y(3)} urad dal ${((e=n%4)<1?n/4:z(4)+(e<2?A:e<3?B:C))+y(5)} poha ${n%48<1?z(192)+((c=n/48%4)>2?C:c>1?B:c>0?A:'')+y(193):n%3<1?z(12)+((f=n/3%4)>2?C:f>1?B:f>0?A:'')+' tbsp':(z(4)+(e>2?C:e>1?B:e>0?A:'')+' tsp')} methi seeds Salt to taste Water as needed ${(b=Math.ceil(n/2))} waiter`+(b<2?'':'s')).replace(/\n0 /g,'\n') W=function(){setTimeout(function(){ (Q=document.getElementById("num").value)&&(document.getElementById("a").innerHTML =d(+Q).replace(/\n/g,'<br>')); }, 10);}; document.getElementById("num").addEventListener("keypress", function(){W();}); document.getElementById("num").addEventListener("click", function(){W();}); ``` ``` <form>How many recipes of dosa batter would you like? <input type="number" name="num" id="num" value="1" /> </form> <p id="a">1 cup rice<br> 1 cup ukda chawal<br> 1/2 cup urad dal<br> 1/4 cup poha<br> 1/4 tsp methi seeds<br> Salt to taste<br> Water as needed<br> 1 waiter</p> ``` It accepts values up to and even including `2^32`, or `4294967296`. After that, the 'urad dal' overflows on odd numbers and becomes negative. Basically, it calculates the correct amounts as it goes. Luckily, only the methi seeds need to have tsp/tbsp/cup measures; otherwise, this would have been a whole lot longer. (The methi seed line alone is 155 chars!) This also would have been at least 500 chars long in ES5. I ❤ ES6. As always, suggestions are greatly appreciated! **Edit 1:** Just realized that according to the rules, `1 tsp` should be replaced with `1/3 tbsp`, same with `2 tsp` and `2/3 tbsp`, as well as `16 tsp` and `1/3 cup`.... [Answer] # Common Lisp, 435 ``` (lambda(n)(labels((k(y)(some(lambda(x)(integerp(* y x)))'(1 4/3 3/2 2 3 4)))(h(s m)(multiple-value-bind(q r)(floor m)(format()"~[~:;~:*~A ~]~[~:;~:*~A ~]~@? " q r s m)))(g(o &aux(h(/ o 3))(c(/ h 4)))(cond((k c)(h"cup~P"c))((k h)(h"tbsp"h))(t(h"tsp"o)))))(format t"~&~A rice ~Aukda chawal ~Aurad dal ~Apoha ~Amethi seeds Salt to taste Water as needed ~A waiter~:P "(g(* n 12))(g(* n 12))(g(* n 6))(g(* n 3))(g(/ n 4))(ceiling(/ n 2))))) ``` ## Slightly ungolfed ``` (lambda (n) (labels ((k (y) (some (lambda (x) (integerp (* y x))) '(1 4/3 3/2 2 3 4))) (h (s m) (multiple-value-bind (q r) (floor m) (format nil "~[~:;~:*~A ~]~[~:;~:*~A ~]~@?" q r s m))) (g (o &aux (h (/ o 3)) (c (/ h 4))) (cond ((k c) (h "cup~P" c)) ((k h) (h "tbsp" h)) (t (h "tsp" o))))) (format t "~&~A rice ~A ukda chawal ~A urad dal ~A poha ~A methi seeds Salt to taste Water as needed ~A waiter~:P " (g (* n 12)) (g (* n 12)) (g (* n 6)) (g (* n 3)) (g (/ n 4)) (ceiling (/ n 2))))) ``` All measures are expressed in `tsp`. Based on the `k` function, `g` decides which units to use for printing and call the formatting function `h` with the appropriate arguments. * `k` returns true when the argument can be expressed as a multiple of 1, 1/4, 1/3, 2/3, 4/3 units * `g` converts the input as a number of tbsp and the number of tbsp as a number of cups (as given in the question). We try to print by units of cups first, or units of tbsp, or else in tps. * `h` use a conditional formatting directives to print either `x`, `x y/z` or `y/z` followed by the formatting of `s` with argument `m`: for cups, `s` is `"cup~P"` which plurializes the word according to `m`. ## Exemple (n = 17) ``` 17 cups rice 17 cups ukda chawal 8 1/2 cups urad dal 4 1/4 cups poha 4 1/4 tsp methi seeds Salt to taste Water as needed 9 waiters ``` [Answer] # R, ~~602~~ ~~603~~ 526 bytes Still lots of room to golf this I suspect, but I have run out of time and I really wanted to do an answer for this one. ``` function(i){S=gsub M=i/c(1,5,60) A=list(c(2,1),c(4,3),c(64,48))[[I<-max(which(M>=1))]] B=c(4,12,192)[I] V=c(' tsp',' tbsp',' cup')[I] C=i%/%B C=C+max((i%%B)%/%A*c(.3,.25)) cat(S('([ ]*)0 ','\\1',S('\\.3',' 1/3',S('\\.6',' 2/3',S('\\.5',' 1/2',S('\\.25',' 1/4',S('\\.75',' 3/4',paste0(i,' cup',if(i>1)'s',' rice ',i,' cup',if(i>1)'s',' ukda chawal ',i*.5,' cup',if(i>2)'s',' urad dal ',i*.25,' cup',if(i>4)'s',' poha ',C,V,if(C>1&I>2)'s',' methi seeds Salt to taste Water as needed ',ceiling(i*.5),' waiter',if(i>2)'s'))))))))} ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 419 bytes ``` a=>(y=g=>a<g?" cup":" cups",z=g=>a/g|0,a+y(2)+` rice ${a+y(2)} ukda chawal ${(1>a%2?a/2:z(2)+(B=" 1/2"))+y(3)} urad dal ${(1>(e=a%4)?a/4:z(4)+(2>e?A=" 1/4":3>e?B:C=" 3/4"))+y(5)} poha ${1>a%48?z(192)+(2<(c=a/48%4)?C:1<c?B:0<c?A:"")+y(193):1>a%3?z(12)+(2<(f=a/3)?C:1<f?B:0<f?A:"")+" tbsp":z(4)+(2<e?C:1<e?B:0<e?A:"")+" tsp"} methi seeds Salt to taste Water as needed ${b=-~a/2|0} waiter`+(2>b?"":"s")).replace(` 0 `,` `) ``` [Try it online!](https://tio.run/##RZDbboMwDEDf@YooWqWg3rhNahEBtf2EPewVNxjKxgoi6ap2636dObTTXhI5PseO/QafoFVfd2Z@bAscSjmATMVFVjKFpMo4U6eOx@Ol@ew6vi@rb28G04sI3GnO@lqh8/R1j2/s9F4AUwc4Q0Ovwk9hEmSwDOKrxcVWcuYvA@66xIeW76FgxR8sUMIkckmISIhICFLMNqMU8TikYBvvKAwpHGs8U42uPQD5tle0yq7CX9tWQSKUpEIrW3AX@4ki16NzE3NuVX8durGVQus8lJKU8M6XI18@eM7MXtMuHt9KcGRwZPCfIeTGPtAcaqYRC@28QGOYaZkBbdB5BYM9A82OlMSCfr2X8x/az7d3Y2eoKZvbofcZp7VrmnHRY9eAQpE7HstnuZO7g2qPum1w0bSVKGkF7vAL "JavaScript (Node.js) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~122 120~~ 117 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Öàu≈9o∞3┴&•ªâ6üòf±Σ§LXâ¢vò╣*/T≥C└ôZüæR-^╦ìóσ∩A←··■☼⌂▌2åH╨bgrp╬3L♫-◙•►]╘═º♀ú♣ɱ╧○+╧┴Qî¼▼◄I"a≤ΩzH♦╩k╖FΦúZa═q|▬◄┼W╥ßöo29 ``` [Run and debug it](https://staxlang.xyz/#p=998575f7396fec33c12607a68336819566f1e4154c58839b7695b92a2f54f243c0935a8191522d5ecb8da2e5ef411bfafafe0f7fdd328648d062677270ce334c0e2d0a07105dd4cda70ca30590f1cf092bcfc1518cac1f11492261f3ea7a4804ca6bb746e8a35a61cd717c1611c557d2e1946f3239&i=2%0A5&m=2) It was a bit infuriating to start over after closing this program's tab, but now it works, and it's shorter! -5 bytes from recursive. ## Explanation (Unpacked) ``` 3:B244E{um+{x*uuB\"cup"sch1>{s's+}{s}?]+{fJm"rice,ukda chawal,urad dal,poha,methi seeds"',/\{JmN"cup""tsp"R]+{PF"Salt to taste"P"Water as needed"P2:_ecp" waiter"p1>{'sp}* ``` `3:B244E{um+` array `[1,1,1/2,1/4,1/4]` `{...m` map to: ``` x*uu product with input, converted to fraction B\ push fractional part and whole part, and pair them "cup"sch1>{s's+}{s}?]+ if whole part <1, append "cup", else cups {fJ remove zeroes, and join with spaces ``` `"rice,ukda chawal,urad dal,poha,methi seeds"',/` array of ingredients `\{Jm` zip with the amounts, and jin with spaces `N` remove last element and push separately(methi seeds) `"cup""tsp"R]+` replace "cup" with "tsp", add it back in `{PF` print each ingredient `"Salt to taste"P"Water as needed"P` print the constant instructions `2:_ecp` divide input by 2, ceil, duplicate, and print `" waiter"p` print "waiter" `1>{'sp}` if number of waiters > 1, print an s ]
[Question] [ # Home improvement for the Minotaur The cretan labyrinth is quite easy to draw. Just start with a symmetric shape (here in red). Let us call all the endpoints of those lines 'nodes'. Then you begin drawing the arches (black): The first one alway begins in the top middle node and connects to the node next to it on the right side, then the two nodes closest to the previous arch are connected. This is repeated untill all nodes are covered. [![gif](https://i.stack.imgur.com/iOtcM.gif)](https://i.stack.imgur.com/iOtcM.gif) Now we can generalize this concept: We can easily generate new initial patterns by adding more `L` shapes. I enumerated the initial shapes as follows: [![degree](https://i.stack.imgur.com/vyQOs.png)](https://i.stack.imgur.com/vyQOs.png) The most left pattern will produce a *cretan labyrinth of degree 0*. The next one will create a *cretan labyrinth of degree 1* (the original one) etc. # Task Given a nonnegative integer `n`, your program should output the ascii representation of a cretan labyrinth of degree `n`, that is shown in the following examples. Trailing spaces/newlines do not matter. You have to include a short explanation of how your code works. # Examples The output for the original cretan labyrith (degree 1) is following: ``` +-----------------------------+ | +-------------------------+ | | | +---------------------+ | | | | | +-----------------+ | | | | | | | +-------------+ | | | | | | | | | +---------+ | | | | | | | | | | | +-----+ | | | | | | | | | | | | | +-+ | | | | | | | | | | | | + | | | + | | | | | | | | | | +---+ | +---+ | | | | | | | | +-------+-------+ | | | | | | +-------+ | +-------+ | | | | +-------+ | | | +-------+ | | +-----------+ | +-----------+ | +---------------+ ``` Initial pattern: ``` + | | | + --+ | +-- ----+---- --+ | +-- + | | | + ``` The cretian labyrinth of degree 0 should look like so: ``` +-------------+ | +---------+ | | | +-----+ | | | | | +-+ | | | | | + | + | | | | +---+---+ | | +---+ | +---+ | +-------+ ``` Initial pattern: ``` + | + --+-- + | + ``` [Answer] # Perl 5, 349 bytes ``` say$p="| "x$_,"+","-"x(16*$n-4*$_+13),"+ $p"for 0..4*($n=pop)+3;say$p="| "x(3*$n+2),"+ | ","| "x2x$n,"+ $p|";$p=~s/..//,$q="-"x(4*$_-1),say"$p+$q+ ","| "x(2*$n-2*$_+1),"+$q+ $p|"for 1..$n;$p=~s/..//;say$p,("+---"."-"x4x$n)x2,"+ $p|";$p=~s/..//,$q="-"x(4*$n+3)."-"x4x$_,say"$p+$q+ | ","| "x2x($n-abs$_),"+$q+ $p|"for-$n..$n;say" "x(8*$n+6),"+----$q+" ``` (Pass *n* as a command line argument.) Computes the maze line-by-line in six sections: * first 4n + 4 lines, * next line (the only line with no `-`), * next n lines, * next line (the line at the middle of the initial pattern), * next 2n + 1 lines, * final line (the line with leading spaces). [Answer] # Python 3.5, 703 695 676 648 587 581 542 535 500 486 462 431 423 411 bytes: (*Thanks to @flawr for advice on saving 55 bytes (486 -> 431)!*) ``` def j(r):R=range;Z=zip;B=r+r+2;P,M='+-';X='| ';q=[*Z(R(0,B-1,2),R(B-1,0,-2))];L=r+1;A=2+r;print('\n'.join([X*w+P+M*v+P+' |'*w for v,w in Z(R(4*L*4-3,0,-4),R(4*L))]+[X*g+P*o+M*k+u+M*k+P*o+' |'*-~g for g,o,k,u in Z([*R(4*L-A,0,-1),*R(4*L-A)],[0]+[1]*(3*r+2),[0,*R(1,4*L,2),*R(4*L+1,11*r,2)],[M*y+'+ '+X*b+P+M*y for y,b in q]+[M*B+P+M*B]+[M*y+'+ '+X*b+P+M*y for y,b in q[::-1]+q[1:]])]+[' '*(8*r+6)+P+M*(8*r+7)+P])) ``` Not very much of a contender for the title, but I still gave it a shot, and it works perfectly. I will try to shorten it more over time where I can, but for now, I love it and could not be happier. [Try it online! (Ideone)](http://ideone.com/Tnhfqv) (May look a little bit different on here because of apparent online compiler limitations. However, it's still very much the same.) # Explanation: For the purposes of this explanation, let's assume that the above function was executed with the input, `r`, being equal to `1`. That being said, basically what's happening, step-by-step, is... 1. `q=[*Z(R(0,B-1,2),R(B-1,0,-2))]` A zip object, `q`, is created with 2 range objects, one consisting of every second integer in the range `0=>r+r+1` and another consisting of every second integer in the range `r+r+1=>0`. This is because every starting pattern of a cretan labyrinth of a specific degree will always have an even number of `-` in each line. For instance, for a cretan labyrinth of degree `1`, `r+r+1` equals `3`, and thus, its pattern will always start with `0` dashes, followed by another line with `4` (2+2) dashes. This zip object will be used for the first `r+1` lines of the labyrinth's pattern. **Note:** The *only* reason `q` is a list and separated from the rest is because `q` is referenced a few times and subscripted, and to save a lot of repetition and allow subscripting, I simply created a zip object `q` in the form of a list. 2. `print('\n'.join([X*w+P+M*v+P+' |'*w for v,w in Z(R(4*L*4-3,0,-4),R(4*L))]+[X*g+P*o+M*k+u+M*k+P*o+' |'*-~g for g,o,k,u in Z([*R(4*L-A,0,-1),*R(4*L-A)],[0]+[1]*(3*r+2),[0,*R(1,4*L,2),*R(4*L+1,11*r,2)],[M*y+'+ '+X*b+P+M*y for y,b in q]+[M*B+P+M*B]+[M*y+'+ '+X*b+P+M*y for y,b in q[::-1]+q[1:]])]+[' '*(8*r+6)+P+M*(8*r+7)+P]))` This is the last step, in which the labyrinth is built and put together. Here, three lists, the first consisting of the top `4*r+1` lines of the labyrinth, the second consisting of the middle `3*r+3` lines of the labyrinth, and the last list consisting of the very last line of the labyrinth are joined together, with line breaks (`\n`) into one long string. Finally, this one huge string consisting of the entire labyrinth is printed out. Let us go more in depth into what these 2 lists and 1 string actually contain: * The 1st list, in which another zipped object is used in list comprehension to create each line one by one, with leading `|`or `+` symbols, an odd number of dashes in the range `0=>4*(r+1)`, trailing `|` or `+` symbols, and then a newline (`\n`). In the case of a degree `1` labyrinth, this list returns: ``` +-----------------------------+ | +-------------------------+ | | | +---------------------+ | | | | | +-----------------+ | | | | | | | +-------------+ | | | | | | | | | +---------+ | | | | | | | | | | | +-----+ | | | | | | | | | | | | | +-+ | | | | | | | ``` * The 2nd list, which consists of a zip object containing 4 lists, and each list corresponds to the number of leading/trailing `|` symbols, the number of `+` symbols, the number of dashes, and finally, the last list, which contains the first `r+1` lines of the pattern created according to zip object `q`, the line in the middle of the pattern (the one with no `|`), and the last `r+2` lines of the symmetrical pattern. In this specific case, the last list used in this list's zip object would return: ``` + | | | + --+ | +-- ----+---- --+ | +-- + | | | + --+ | +-- <- Last line created especially for use in the middle of the labyrinth itself. ``` And therefore, in the case of a 1 degree labyrinth, this entire list would return: ``` | | | | | + | | | + | | | | | | | | | | +---+ | +---+ | | | | | | | | +-------+-------+ | | | | | | +-------+ | +-------+ | | | | +-------+ | | | +-------+ | | +-----------+ | +-----------+ | <- Here is where the extra line of the pattern is used. ``` * This final list, in which the last line is created. Here, the first segment (the one before the first space) length of the last line of list `P` number of spaces are created. Then, the length of the last segment (the ending segment) of the same line + 4 number of dashes are added, all of which are preceded and followed by a single `+` symbol. In the case of a degree 1 labyrinth, this last list returns: ``` +---------------+ ```After joining all this together, this step finally returns the completed labyrinth. In the case of a 1 degree labyrinth, it would finally return this: ``` +-----------------------------+ | +-------------------------+ | | | +---------------------+ | | | | | +-----------------+ | | | | | | | +-------------+ | | | | | | | | | +---------+ | | | | | | | | | | | +-----+ | | | | | | | | | | | | | +-+ | | | | | | | | | | | | + | | | + | | | | | | | | | | +---+ | +---+ | | | | | | | | +-------+-------+ | | | | | | +-------+ | +-------+ | | | | +-------+ | | | +-------+ | | +-----------+ | +-----------+ | +---------------+ ``` ]
[Question] [ I was asked by OEIS contributor Andrew Howroyd to post a Code Golf Challenge to extend [OEIS sequence A049021](https://oeis.org/A049021). > > Would be super great to get a couple more terms for [...] A049021. Kind of thing [...] team golf would excel at. > > > As I found out the hard way with the help of [user202729](https://codegolf.stackexchange.com/users/69850/user202729), the definition of A049021 is... *slippery*. Instead, this challenge will have you compute a similar sequence. (If, separate from this challenge, you're interested in computing more terms of A049021, I encourage it!) # Definition This challenge will have you counting topologically distinct ways of partitioning a square into \$n\$ rectangles. Two partitions are called *topologically distinct* if there's no [homeomorphism](https://en.wikipedia.org/wiki/Homeomorphism) \$A \rightarrow B\$ *with the additional property* that the corners of \$A\$'s square map surjectively to the corners of \$B\$'s square. The less fancy way of saying this is that if partitions \$A\$ and \$B\$ are topologically equivalent, there is a map from \$A \rightarrow B\$ and a map from \$B \rightarrow A\$ such that all nearby points stay nearby, and every corner of \$A\$ is sent to a distinct corner of \$B\$. Examples of homeomorphisms are rotating the square, flipping the square, and "slightly" moving the boundaries of the rectangles. When \$n = 4\$ there are seven topologically distinct partitions: [![The seven topologically distinct ways of dissecting a square into 4 rectangles.](https://i.stack.imgur.com/rRQM8.png)](https://i.stack.imgur.com/rRQM8.png) As user202729 pointed out, sometimes these equivalences are somewhat surprising; in particular, the following partitions are equivalent by homeomorphism: [![An example of two partitions that are homeomorphism.](https://i.stack.imgur.com/DruRe.png)](https://i.stack.imgur.com/DruRe.png) # Challenge This [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge will have you write a program that computes as many terms of this new sequence as possible. In case of a close call, I will run submissions on my machine, a 2017 MacBook Pro with 8 GB of RAM. (Be aware that some of these square partitions [are more complicated](https://en.wikipedia.org/wiki/Squaring_the_square) then just putting two smaller partitions side-by-side.) ]
[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/1091/edit) Produce only the name of a programming language using only the facilities of the language itself. The name of the language can only be invoked indirectly, i.e., from non custom environment variables, built-in functions or methods or the interpreter/compiler of the language. Output should be the name of the language only. One example would be: ``` $ awk --v | awk 'NR<2 { print $2}' # GNU Awk 3.1.8 Awk ``` The answer I select will be the one with the most up votes. In case of a tie, the shortest golfed version (separate or the only given answer), will be the tie breaker. [Answer] ## Whitespace ``` | | ``` [Answer] ## C ``` #define d(x) x(#x[3]) void main(){d(putchar);} ``` [Answer] # Python - 23 22 ``` print`credits`[97:103] ``` [Answer] ## J,4 ``` u:74 ``` Having a short language name does kind of help. [Answer] # Python (win32) - abuse of the random module I'm not sure whether this actually *works.* Depends on the implementation. ``` print ''.join([(random.seed(835)==None)and'']+[chr(random.randint(64,90)) for x in range(3)]+[(random.seed(53281)==None)and'']+[chr(random.randint(64,90)) for x in range(3)]) ``` [Answer] ## BASH, ~~17~~ 7 ``` bash -c 'echo $0' ``` or even ``` echo ${0#-} ``` if you already run bash :D **update**: `"echo $0"` gets `$0` expanded first so `'echo $0'` is the correct answer. [Answer] ## BrainFuck Just for fun (I know this isn't related to the purpose of the task.), I wrote this code... ``` +++++[><-+-+-><><>++<><>+++++<>+<]>>>+ +>><<+<>+><<>+[><-<<+>>><>+<><>++<]>[-<<< +>>>]+<<+<[><->>+>><>+<<><+<<]>->-><>-> +++++<<>+++++<<>------>><>+.<<[-<>+<>-> +<]>>+><+<>><+><+[<]>-<><>-><<>-<<>+>-.< +<><>+<>+[><>-<>-><<>-<>><-<><>-><><-+< ++---]>[+>]<<+><+.>><-<<+++++[>+<><><-] > +++.>+<+<>+++<>+.+> -.<><+<+><+><><++> +++<>+<+>>+<><>+< +.<><+[->>+>><<++ +<>><++-<<-+-<>+]+ > > ---.< --- --- --- <>> <-. --- >-< ``` And when I replaced `<`,`>`,`[`,`]`,`.` with space... ``` +++++ -+-+- ++ +++++ + + + + + + - + + ++ - + + + - + + + - - - +++++ +++++ ------ + - + - + + + + + - - - + - + + + - - - - - -+ ++--- + + + - +++++ + - +++ + + +++ + + - + + + ++ +++ + + + + + + - + ++ + ++- -+- + + --- --- --- --- - --- - ``` [Answer] **Piet, 47x2 pixels** Using 5x5 codels: ![Piet program to print "Piet"](https://i.stack.imgur.com/MI4RJ.gif) [Answer] ## Python ``` import sys;print sys.copyright[24:30] ``` This also works for me (sys.executable is '/usr/bin/python') ``` import sys;print sys.executable[9:] ``` [Answer] ## brainfuck 101 ``` ++++++++[->++++++++++++>+>>++>+++<<<<<]>[->+>+>+>+<<<<]>+>++.>++.<-.<.>>----.<<---.>>>---.<<++.>---. ``` could probably be golfed slightly further, but it's 6am and I should get some sleep... [Answer] ## **C** In the spirit of Anon's answer in C (considering a C file always has the extension .c). I'd suggest : ``` #include <stdio.h> void main(){puts(__FILE__+sizeof(__FILE__)-2);} ``` [Answer] ## Java ``` public class Name { public static void main(String[] args) { String s = ""; s = s.getClass().getName(); s = s.substring(0, 1).toUpperCase() + s.substring(1, 4); System.out.println(s); } } ``` [Answer] ## C Built using DevStudio 2005 ``` #include <stdio.h> void main () { int i,j,i2; for (i=j=0,i2=200;i2<=200;i2-=19,j==putchar(32|(i2<'Q'&&i2>'+'&&(j<20||i<12||i>28))*3)+8?j=0,i2+=i,i+=putchar('\n')-8:(i2+=j,j+=2)); } ``` Slightly shorter version (with compiler warnings) ``` int i,j,k; for (i=j=k=0;k<=0;k-=19,j==putchar(32|(k<-119&&k>-157&&j<20|i<12|i>28)*3)+8?j=0,k+=i,i+=putchar('\n')-8:(k+=j,j+=2)); ``` [Answer] ## Ruby - 27 ``` puts RUBY_DESCRIPTION[0..3] ``` Update from Chris Jester-Young's comment: ## Ruby - 24 ``` puts RUBY_COPYRIGHT[0,4] ``` Updated from Hauleth: ## Ruby - 15 ``` p`ruby -v`[0,4] ``` [Answer] ## cat 3 Create a file with the following content (source code) ``` cat ``` And run it like (execute the file): ``` $ cat filename ``` [Answer] # Clojure - 16 chars ``` (subs(str =)0 7) ``` [Answer] ## Haskell, 47 ``` data H=Haskell deriving Show main=print Haskell ``` [Answer] # Ruby Not short, but very indirectly. ``` 4.times{|x|print((82+11.24*x+8.231*Math.tan(111.2*x)).floor.chr)} ``` [Answer] ### Ruby (17) `p 1299022.to_s 36` Outputs `"ruby"` [Answer] # Bash/Brainfuck/C ``` //bin/bash -c 'echo ${0##*/}' #define p putchar #define exit main(){p(p+67);p(10);} exit //++++++++[->++++++++++++>+>>++>+++<<<<<]>[->+>+>+>+<<<<] //>+>++.>++.<-.<.>>----.<<---.>>>---.<<++.>---. ``` [Answer] ## Brainfuck ``` >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. ++++++++++++++++++++++++++++++++++++++++++++++++. -----------------. ++++++++. +++++. --------. +++++++++++++++. ------------------. ++++++++. ``` [Answer] ## Perl ``` $^X=~/([a-z]+)[^\/]+$/;print$1,$/ ``` [Answer] ## Scala — 42 ``` print(((1,1).getClass+"").substring(6,11)) ``` **Update — 39 chars** ``` print(('a.getClass+"").substring(6,11)) ``` [Answer] **C - 34** I don't have enough reputation to add this as a comment to the previous C entry. Same idea as above, but the filename can be anything.c ``` main(){puts(index(__FILE__,0)-1);} ``` [Answer] ## ><> (Fish) (11) Even better: ``` '>'::o2-oo; ``` [Answer] ## Visual Basic (version 6.0) ``` MsgBox Right(Error(458), 12) ``` ## VBScript ``` On Error Resume Next Err.Raise 458 MsgBox Right(Err.Description, 8) ``` ## Both VB6 and VBScript ``` On Error Resume Next Err.Raise 458 D = Err.Description MsgBox Mid(D, InStr(2, D, "V")) ``` [Answer] ## QBasic (37) I am using version 1.1 of the QBasic interpreter. ``` FOR x=0TO 5:?CHR$(PEEK(2588+x));:NEXT ``` [Answer] **Lua 25 Chars** ``` print(arg[-1]:match"%w+") ``` Or, analogue to the J B's [J solution](https://codegolf.stackexchange.com/questions/1091/whats-my-name-produce-the-name-of-the-language-indirectly/1138#1138) 17 chars: ``` print"\76\117\97" ``` [Answer] ## GolfScript (13) ``` "#{$0[0..9]}" ``` [Answer] ## Racket (45) ``` racket -e "(display(substring(banner)10 17))" ``` ]
[Question] [ Write a program or function that takes in a positive integer. You can assume the input is valid and may take it as a string. If the number is any of ``` 123 234 345 456 567 678 789 ``` then output a [truthy](http://meta.codegolf.stackexchange.com/a/2194/26997) value. Otherwise, output a [falsy](http://meta.codegolf.stackexchange.com/a/2194/26997) value. For example, the inputs ``` 1 2 3 12 122 124 132 321 457 777 890 900 1011 1230 1234 ``` must all result in falsy output. (The input will not have leading zeroes so you needn't worry about things like `012`.) **The shortest code in bytes wins.** [Answer] ## Python, 24 bytes ``` range(123,790,111).count ``` An anonymous function that outputs 0 or 1. It creates the list `[123, 234, 345, 456, 567, 678, 789]` and counts how many times the input appears. ``` f=range(123,790,111).count f(123) => 1 f(258) => 0 ``` [Answer] ## Python, 24 bytes ``` lambda n:n%111==12<n<900 ``` Just a lot of condition chaining. [Answer] ## Haskell, 22 bytes ``` (`elem`[123,234..789]) ``` An anonymous function. Generates the evenly-spaced list `[123, 234, 345, 456, 567, 678, 789]` and checks if the input is an element. [Answer] # Python 2, 25 bytes ``` lambda n:`n-12`==`n`[0]*3 ``` Test it on [Ideone](http://ideone.com/dH6JE0). [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 9 bytes ``` h:2j:12+? ``` [Try it online!](http://brachylog.tryitonline.net/#code=aDoyajoxMis_&input=MTIz) or [Verify all test-cases.](http://brachylog.tryitonline.net/#code=Ons6MiYsInRydWUuIkB3OyJmYWxzZS4iQHd9YQpoOjJqOjEyKz8&input=WzEyMzoyMzQ6MzQ1OjQ1Njo1Njc6Njc4Ojc4OToxOjI6MzoxMjoxMjI6MTI0OjEzMjozMjE6NDU3Ojc3Nzo4OTA6OTAwOjEyMzA6MTIzNF0) [Credits to Dennis for the algorithm](https://codegolf.stackexchange.com/a/91604/48934). In English, "(prove that) the Input's first digit, concatenated to itself twice, add 12, is still the Input." [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 76 + 3 = 79 bytes This answer is a golf of [this](https://codegolf.stackexchange.com/a/91609/56656) answer. I don't actually know quite how my answer works but DJMcMayhem gives a good explanation in his original answer and my answer is a modification of his. ``` ([]<>)<>({}[({})]<>)<>(({}[({})()()()()()]<>{}{}<(())>)){{}{}(((<{}>)))}{}{} ``` It is run with the -a ascii flag adding 3 bytes. ## Explanation (of sorts) Starting with the original working solution: ``` ([]<>)<>({}[({})]<>)<>({}[({})]<>)({}{}[()()])({}<({}[()()()])>)(({}{}<(())>)){{}{}(((<{}>)))}{}{} ``` I run this through a simple golfing algorithm I wrote and get: ``` ([]<>)<>({}[({})]<>)<>(({}[({})]<>{}[()()]<({}[()()()])>{}<(())>)){{}{}(((<{}>)))}{}{} ``` From here I see the section `<({}[()()()])>{}` this essentially multiplies by one which makes it equal to `{}[()()()]` reduce the whole code to: ``` ([]<>)<>({}[({})]<>)<>(({}[({})]<>{}[()()]{}[()()()]<(())>)){{}{}(((<{}>)))}{}{} ``` Lastly negatives can be combined: ``` ([]<>)<>({}[({})]<>)<>(({}[({})()()()()()]<>{}{}<(())>)){{}{}(((<{}>)))}{}{} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), 5 bytes ``` ¥XX‚Q ``` **Explanation** ``` ¥ # deltas Q # are equal to XX‚ # [1,1] ``` [Try it online](http://05ab1e.tryitonline.net/#code=wqVYWOKAmlE&input=NDU2) [Answer] # Brainfuck, 32 bytes ``` +>,+>,>,-[-<-<->>],[<]<[<]<[<]<. ``` [Try it online!](http://brainfuck.tryitonline.net/#code=Kz4sKz4sPiwtWy08LTwtPj5dLFs8XTxbPF08WzxdPC4&input=MTIz) [Credits to Lynn for the core of the algorithm.](https://codegolf.stackexchange.com/a/91617/48934) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DI⁼1,1 ``` [Try it online!](http://jelly.tryitonline.net/#code=REnigbwxLDE&input=&args=NDU2) or [verify all test cases](http://jelly.tryitonline.net/#code=REnigbwxLDEKMTAwMDBSw4fDkGY&input=). ### How it works ``` DI⁼1,1 Main link. Argument: n (integer) D Decimal; convert n to base 10. I Increments; compute the differences of all pairs of adjacent digits. 1,1 Yield [1, 1]. ⁼ Test the results to both sides for equality. ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 8 bytes ``` d1=tn2=* ``` [Try it online!](http://matl.tryitonline.net/#code=ZDE9dG4yPSo&input=JzEyMyc) This will print `1 1` for a truthy input, and an array with a `0` in it for a falsy value, since that is falsy in MATL. Explanation: ``` d % Calculate the difference between consecutive digits 1= % Push an array of which elements equal one t % Duplicate this array n % Push the length of this array 2= % Push a one if the length is 2, and a zero otherwise % Now, if we have a truthy input, the stack looks like: % [1 1] % 1 % And if we have a falsy input, the stack looks something like this: % [1 0] % 1 % Or this: % [1 1] % 0 * % Multiply the top two elements ``` [Answer] ## Java 7, 46 bytes ``` boolean f(int a){return a>12&a<790&a%111==12;} ``` After trying several things with Leaky Nun in chat, this seems to be the shortest. Sometimes you just have to do things the straightforward way :/ Explanation: ``` boolean f(int a){ return a>12 Is it more than 12? (stupid edge case) & a<790 Is it in range the other way? & a%111==12; Is it 12 more than a multiple of 111? } ``` [Answer] # [Perl 6](http://perl6.org), ~~35 29 24 21~~ 19 bytes ``` ~~{.chars==3&&'0123456789'.index: $\_} {$\_ (elem) (123,\*+111...789)} {$\_∈(123,\*+111...789)} \*∈(123,\*+111...789)~~ *∈(123,234...789) ``` ## Explanation: ``` # Whatever lambda ( the parameter is 「*」 ) * ∈ # is it an element of: # this sequence ( 123, 234, # deduce rest of sequence ... # stop when you generate this value 789 ) ``` ## Usage: ``` my &code = *∈(123,234...789); say code 123; # True say code 472; # False say ( *∈(123,234...789) )( 789 ); # True ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 26 ``` . $*: ^(:+ ):\1::\1$ ``` Outputs 1 for truthy and 0 for falsey. [Try it online](http://retina.tryitonline.net/#code=JShHYAouCiQqOiAKXig6KyApOlwxOjpcMSQ&input=MTIzCjIzNAozNDUKNDU2CjU2Nwo2NzgKNzg5CjEKMgozCjEyCjEyMgoxMjQKMTMyCjMyMQo0NTcKNzc3Cjg5MAo5MDAKMTAxMQoxMjMwCjEyMzQ) (First line added to allow multiple testcases to be run). [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 99 bytes ``` ([{}]({})<>)<>([{}]{}<>)(({})<([{}]{})((){[()](<{}>)}{})>)([{}]{})((){[()](<{}>)}{})<>{{{}}<>{}}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#@68RXV0bq1Fdq2ljB0RgXnUtkK0BFoPygTzN6mgNzVgNm@paO81aoAhQBU45G7vq6upaoClg4v9/QyPj/7qJAA "Brain-Flak – TIO Nexus") This is 98 bytes of code `+1` for the `-a` flag. This prints `1` for truthy, and either `0` or nothing (which is equivalent to 0) for falsy [Answer] # Ruby `-nl`, ~~32~~ ~~30~~ 25 bytes ``` p"123456789"[$_]&.size==3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5ejlLsgqWlJWm6FjsLlAyNjE1MzcwtLJWiVeJj1fSKM6tSbW2NIfJQZQtuBgOVcQFVcgEVcwHVcwG1cAF1cQE1chlyGXEZcxkaAREIm3AZGgMFjAyBCs25zM3NuSwsDbgsDQy4DA0MDYEKjA1AhAnEbAA) [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 114 bytes ``` ([((()()()){}){}]{})(((()()()){}())<>)<>{({}<(({}[(((((()()()){}()){}){}){}){}]())){(<{}>)<>({}[()])<>}{}>[()])}<> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KFsoKCgpKCkoKSl7fSl7fV17fSkoKCgoKSgpKCkpe30oKSk8Pik8Pnsoe308KCh7fVsoKCgoKCgpKCkoKSl7fSgpKXt9KXt9KXt9KXt9XSgpKSl7KDx7fT4pPD4oe31bKCldKTw-fXt9PlsoKV0pfTw-&input=MTIz) Correct version (in the spirit of the question): takes the integer as input, output 0 for falsey and 1 for truthy. This is **not** stack clean. ### Algorithm Let the input be `n`. The output is truthy iff `(n-123)(n-234)(n-345)(n-456)(n-567)(n-678)(n-789)=0`. I computed those seven numbers by first subtracting 12 and then subtract 111 7 times, and then computed the logical double-NOT of those seven numbers and added them up. For truthy results, the sum is 6; for falsey results, the sum is 7. Then, I subtract the sum from 7 and output the answer. [Answer] # R, ~~30~~ 22 bytes ``` scan()%in%(12+1:7*111) ``` Not particularly exciting; check if input is in the sequence given by 12 + 111k, where k is each of 1 to 7. Note that `:` precedes `*` so the multiplication happens after the sequence is generated. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~41 30~~ 23 bytes First code-golf submission, be gentle :) ``` ~~a=>{return a&gt12&&a&lt790?a%111==12:false;};~~ ~~a=>a&gt12&&a&lt790?a%111==12:false~~ a=>a&gt12&a&lt790&a%111==12 ``` [Try it online!](https://tio.run/##Dcq7CoQwEAXQfr9impUEXZixEUkm5Vbbbx2DgQuSgI/vj5YHTjo@6UD7XiV5lHNYat0CZW1RQwwydtFPM3fxLSKqMjb3ynU3TyUoO5AnYWZH6HuLbLKBtf8d5/pDWR@4dgM "C# (Visual C# Interactive Compiler) – Try It Online") * -11 bytes thanks to Kirill L. * Another -7 bytes thanks to ASCII-only. [Answer] # Brainfuck, 43 bytes ``` ,>,>,>,[>>]<[[-<-<->>]<+[>>]<++[>>->]<+<]>. ``` Bah, I'm no good at this. Outputs `\x01` if the output is one of the strings `123`, `234`, …, `789`; outputs `\x00` otherwise. (I beat Java 7, though…) [Try it online!](http://brainfuck.tryitonline.net/#code=LD4sPiw-LFs-Pl08W1stPC08LT4-XTwrWz4-XTwrK1s-Pi0-XTwrPF0-Lg&input=MzQ1&debug=on) [Answer] # JavaScript ES6, 26 bytes `n=>1>(n-12)%111&n>99&n<790` This takes advantage of the fact that I'm using bit-wise logic operators on what are essentially booleans (which are bit-based!) Thanks to Titus for saving 2. [Answer] # Excel - 62 57 35 31 bytes Based on Anastasiya-Romanova's answer, but returning Excel's `TRUE/FALSE` values. ``` =AND(LEN(N)=3,MID(N,2,1)-MID(N,1,1)=1,MID(N,3,1)-MID(N,2,1)=1) ``` Further, we can get to ``` =AND(LEN(N)=3,MID(N,2,1)-LEFT(N)=1,RIGHT(N)-MID(N,2,1)=1) ``` since both `RIGHT` and `LEFT` return a single character by default. And, inspired by some of the Python solutions: ``` =AND(LEN(N)=3,MOD(N,111)=12,N<>900) ``` Thanks to Neil for 4 more bytes... ``` =AND(N>99,MOD(N,111)=12,N<900) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 7 bytes ``` ẹ~⟦₂-_2 ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9w1866R/OXPWpq0o03@v/fxNQMAA "Brachylog – TIO Nexus") ## Explanation ``` ẹ~⟦₂-_2 ẹ Split into digits ~⟦₂ Assert that this is an increasing range; take its endpoints -_2 Assert that the starting minus ending endpoint is -2 ``` As a full program, we get a truthy return if all assertions hold, a falsey return if any fail. [Answer] # CJam, ~~13~~ 9 bytes ``` A,s3ewqe= ``` [Try it online!](https://tio.run/nexus/cjam#@@@oU2ycWl6Yavv/v6GRMQA) **Explanation** ``` A,s e# Push "0123456789". 3ew e# Split it into contiguous length-3 chunks: ["012" "123" "234" ... "789"]. q e# Push the input. e= e# Count the number of times the input appears in the array. ``` [Answer] # Regex (ECMAScript), 20 bytes The input *n* is in unary, as the length of a string of `x`s. ``` ^x{12}(x{111}){1,7}$ ``` [Try it online!](https://tio.run/##TY/NTgIxFEZfBScG7gVmoEg0oRZXLti40KXRpIFL52rpNG35kWGefRwWJm6@zfmSk/OlDzquA/uUR88bCrvKfdNPG5SjY@@VzPPJA5zVcjJsP0@1mDXQrRAN1mL80Ny2w8kZi1S9pcDOABbR8prgfpzPEWVUU3ks2RKAVYH0xrIjQLxRbm8t1kbZInrLCQb5ACVvAZwyhSVnUonL2eXC8UW/ACuvQ6SVS2Depx@If4D@A7cUT2JxxZjKUB2zlTtoy5te0M7QopeNrNxWASQ/KpI8GmEnzE5ZEciTTsBY7HRalxAQ69jv@y4pwbVCSL9PMYXuIpumneZidjf/BQ "JavaScript (SpiderMonkey) – Try It Online") This works by asserting that \$n-12\$ is of the form \$111k\$ where \$1\le k\le 7\$. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ¯k₁⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwq9r4oKB4oG8IiwiIiwiMTIzXG4yMzRcbjFcbjJcbjNcbjEyMzQiXQ==) ### Explained ``` ¯k₁⁼ ¯ # Deltas k₁ # [1,1] ⁼ # compare lists ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 15 bytes ``` {($x-12)=3#*$x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6rWUKnQNTTStDVW1lKpqOXiSos2NDKOBVImBgYgysjYBMwzNQNR5haWEB5YzhAkCQBJFhD+) Port of [Dennis' algorithm](https://codegolf.stackexchange.com/a/91604/107017). Explanation: ``` {($x-12)=3#*$x} Main function. Takes x as input $x Convert x to string * Then get the first character 3# And duplicate it thrice = Is it equal to ( x-12) x - 12 $ Converted to string? ``` [Answer] # Excel - 104 bytes ``` =IF(LEN(N)<3,"Falsy",IF(AND(LEN(N)=3,MID(N,2,1)-MID(N,1,1)=1,MID(N,3,1)-MID(N,2,1)=1),"Truthy","Falsy")) ``` **Explanation:** The syntax for the IF formula in Excel is: ``` IF( condition, [value_if_true], [value_if_false] ) ``` If the length of input `N`, where it's a name of the reference cell, is less than 3, then it will return **Falsy**. Else, if the length of input `N` is 3 and both of the difference of second digit and first digit and the difference of third digit and second digit are equal to 1, then it will return **Truthy**. [Answer] # Pyth, 8 Bytes ``` qi>3SeQT ``` [Try online!](http://pyth.herokuapp.com/?code=qi%3E3SeQT&input=234&debug=0) Explanation: ``` q Q Is the input equal to: <3S The last three digits of the range from 1 to eQ The last digit of the input i T Concatenated together into an integer ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Takes string argument. ``` 1 1≡¯2-/⍎¨ ``` `1 1≡` Is {1, 1} identical to `¯2-/` the reversed pair-wise difference of `⍎¨` each character taken as a number? [TryAPL online!](http://tryapl.org/?a=e%u2190%7B%7B1%3D%u2374%u2375%3A%u236C%u2374%u2375%u22C4%u2375%7D%u2283%7B%u237A/%u2375%7D/%u2395VFI%20%u2375%7D%20%u22C4%20f%u21901%201%u2261%AF2-/e%A8%20%u22C4%20f%A8%2C%A8%27123%27%20%27234%27%20%27345%27%20%27456%27%20%27567%27%20%27678%27%20%27789%27%20%271%27%20%272%27%20%273%27%20%2712%27%20%27122%27%20%27124%27%20%27132%27%20%27321%27%20%27457%27%20%27777%27%20%27890%27%20%27900%27%20%271011%27%20%271230%27%20%271234%27&run) (`⍎` has been emulated with `e` for security reasons.) [Answer] # Perl, 18 bytes Includes +1 for `-p` Run with the input on STDIN ``` 123.pl <<< 123 ``` `123.pl`: ``` #!/usr/bin/perl -p $_=$_=/./.2==$_-$&x3 ``` ]
[Question] [ Using your language of choice, write a function that takes a variable number of arguments and returns the number of arguments it was called with. Specifics: * Your language needs to support variadic argument functions: something callable that takes an arbitrary number of arguments and returns a value. * Parameters must be able to be passed individually. This means that passing an array would only count for one parameter. You can use an "all passed arguments" array if your language supports it; the restriction is on how the function is called. * Code that calls this function must not be required to pass the number of arguments *in its source*. If a compiler inserts the number of arguments as part of a calling convention, that is allowed. * The arguments can be of any type you want. You can support only a single type (e.g. only supporting `int` is still valid), arbitrary types (any type of argument is allowed), or any combination of argument types (e.g. first arg is `int`, rest are strings). * Your function may have a maximum number of arguments (especially since resources are finite), but must support *at least 2* arguments. Samples: * `f()` returns `0` * `f(1)` or `f("a")` returns `1` * `f([1, 2, 3])` returns `1` as it is passed an array, not 3 arguments * `f(1, 10)` or `f(1, "a")` returns `2` As this is code-golf, the winning solution is the one that uses the fewest number of bytes. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 11 bytes ``` a->a.length ``` [Try it online!](https://tio.run/##jczBaoNAEAbgu0/xk5PCuCRp2qSEFPoAoQePJYdRd81aswnuKJTis9tFkmvtYRj4/5mv5p7Tuvwai4a9x5Gtw08EWCe6NVxovLeVn6IphIk/8loXopQCJ/uQD2FuXd7YAl5YwuqvtsQlUHEmrXXV5wkclOTOTKLBAdHI6RurRrtKzuN@KrNvL/qirp2oW/iVxsVGmThJ/qxXM/2CF3MCrZazJ/9hsCY8ETaEZ8ILYUvYEV4JD3@IhvEX "Java (JDK 10) – Try It Online") [Answer] # JavaScript, 15 bytes ``` [].push.bind(0) ``` The `Array.prototype.push` function takes any number of arguments, adds them to its array, and returns the size of the array. Therefore, the `push` function used on an empty array returns the number of arguments supplied to `push`. ``` f = [].push.bind(0) f(10,2,65,7) > 4 f() > 0 ``` The `.bind(0)` simply gives the `push` function a fixed `this` value so that it can be stored in a variable. In fact, the 7-byte identifier **`[].push`** can be used literally (but not assigned) without `bind`: ``` [].push(10,2,65,7) > 4 [].push() > 0 ``` [Answer] # JavaScript (ES6), 16 bytes ``` (...a)=>a.length ``` ``` f= (...a)=>a.length console.log(f()) console.log(f(1)) console.log(f(1,2)) console.log(f(1,2,3)) console.log(f(1,2,3,4)) ``` [Answer] # [Haskell](https://www.haskell.org/), 108 107 95 94 bytes ``` class T r where z::Int->r instance T Int where z=id instance T r=>T(a->r)where z n _=z$n+1 z 0 ``` [Try it online!](https://tio.run/##TYyxCoMwFEX3fsUdHBKkoGsg7t3dRMrDBnw0fciLIOTnYzoIrvecc1dK3xBjKUuklDBCcaxBA7JzL9mfgz5Y0k6yhArrcmHPnztRP4yGqm4vAYK3z420ffkRCzw25do3MCajs9gYHYzFNMO5/7UtJw "Haskell – Try It Online") This was surprisingly hard to get working, but I had fun trying to find out how to implement something that's trivial in imperative languages. [Answer] ## Amstrad CPC Z80 binary call from BASIC, 1 byte, hex encoded ``` C9 : RET ``` (Also 2 and 5 byte versions, see below) Upon entry to the call, the number of parameters passed will be in the `A` register. The code simply returns immediately. There is no concept of return values in the Z80, just entry and exit states. The value is just "there" accessible in the register since the code changes no input conditions, except for `PC` (the program counter) and `SP` (the stack pointer). However, the value in `A` is not accessible to BASIC and gets overwritten almost immediately. Examples: ``` CALL &8000, "Hello", "World" ``` `A` = 2 ``` CALL &8000, 42 ``` `A` = 1 ``` CALL &8000 ``` `A` = 0 --- By request, here is some code that makes the value accessible in BASIC. I was very surprised to find it could be done in only 5 bytes!: ### The machine code: ``` 12 : LD (DE), A 13 : INC DE AF : XOR A 12 : LD (DE), A C9 : RET ``` On entry: * `AF` - the accumulator and flags registers (treated as two 8-bit registers) + `A` contains the number of parameters passed, up to the maximum of 32 parameters + I'm not sure what's in `F`. It appears to have all flags RESET to `0`, except the two undefined flags which are both `1`. The `Z` flag (zero) is SET to `1` if there were no parameters passed in * `BC` + `B` - 32 minus the number of parameters (`A` + `B` = 32) + `C` - `&FF` * `DE` - The address of the last parameter, or the calling address if no parameters were passed in * `HL` - The address of the first byte after the tokenised BASIC command currently being executed (either as a program or in immediate command mode) * `IX` - The stack address of the pointer to the last parameter * `IY` - `&0000` The code 1. `L`oa`D`s the address pointed to by `DE` with the value in `A` 2. `INC`rements `DE` 3. `XOR`s `A` (with `A`), giving `&00` 4. `L`oa`D`s the value in `A` to the address pointed to by `DE` 5. `RET`urns On exit: * `A` is destroyed (it's always `&00`) * `DE` is destroyed (it's always one higher than on entry) * All other registers are preserved ### The BASIC Amstrad basic has only three data types, plus simple arrays. By default, all BASIC variables are REAL (signed, 32 bit mantissa, 8 bit exponent), which can be made explicit with `!`. For an INTEGER (signed, 16 bit) use `%` and for a STRING (1 byte string length, up to 255 bytes character data, binary safe) use `$`: * `x` - REAL (implicit) * `x!` - REAL (explicit) * `x%` - INTEGER * `x$` - STRING You can also use `DEFINT`, `DEFREAL` and `DEFSTR` with a single letter, or a range of two single letters to specify the default type for all variables starting with that letter, similar to FORTRAN. * `DEFSTR a` * `DEFINT x-z` Now: * `a` - STRING (implicit) * `i` - REAL (implicit) * `x` - INTEGER (implicit) * `x$` - STRING (explicit) The easiest type to work with is the integer. The machine code expects the last parameter to passed by address, not value, which is why `@` is prefixed to the variable. The return variable is counted as one of the `CALL`s parameters. The machine code is called as follows from BASIC (assuming it's loaded at into memory at address `&8000`): ``` CALL &8000, "Hello", "World", 42, @n% ``` `n%` = 4 This will always give the correct result, regardless of the initial value of `n%`. For a 2-byte version that preserves all input registers: ``` CALL &8003, "Hello", "World", 42, @n% ``` `n%` = 4 This skips the first three bytes, and only gives the correct result if the initial value of `n%` is `0`-`255`. This works because the Z80 is little-endian. The return parameter must be initialised before being passed, otherwise BASIC will throw an `Improper argument` error. In the below image, I am printing (with the shortcut `?` since I've golfed the demonstration too!) the return values immediately before and after the call to show the value changing. I'm using the value `&FFFF` because that is the binary representation of `-1` for a signed integer. This demonstrates that the 5-byte program correctly writes both bytes, whereas the 2-byte program only writes the low byte and assumes that the high byte is already `&00`. [![enter image description here](https://i.stack.imgur.com/Uc6TR.png)](https://i.stack.imgur.com/Uc6TR.png) [Answer] # [Python 3](https://docs.python.org/3/), 15 bytes ``` lambda*a:len(a) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSvRKic1TyNR839BUWZeiUaahqYmF4xpiMRWSlRCltFRMDRA5WMoMNJRMNZRMNFRMNVRMNNRMNdRsNBRsIRo/A8A "Python 3 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), ~~7~~ 5 bytes ``` <<<$# ``` [Try it online!](https://tio.run/##qyrO@P/fxsZGRfn///9p@fn/kxKLAA "Zsh – Try It Online") [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 6 bytes My first Brain-Flak solution worthy posting, I guess it's the right tool for this job: ``` ([]<>) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fIzrWxk7z////hv91Df8bAAA "Brain-Flak (BrainHack) – Try It Online") ### Explanation When executing a Brain-Flak program, initially the left stack contains all arguments. From there it's simply a matter of: ``` ( -- push the following.. [] -- height of the stack (ie. # of arguments) <> -- ..to the other stack (toggles to the other stack) ) -- -- the right stack now contains the # of arguments which -- gets printed implicitly ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes ``` Tr[1^{##}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/pCjaMK5aWbk2Vu1/QFFmXkl0WrSJjoKpjoKZjoJRbCwXTNBcR0HJRlc3USGvNDcptUgJxi0uASpIV0JSGZyZh8SLjf0PAA "Wolfram Language (Mathematica) – Try It Online") Suggested by JungHwan Min. Some restrictions (input must be rectangular) but we are not required to handle arbitrary input. **11 bytes** ``` Length@!##& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfJzUvvSTDQVFZWe1/QFFmXkl0WrSJjoKpjoKZjoJRbCwXTNBcR0HJRlc3USGvNDcptUgJxi0uASpIV0JSGZyZh8SLjf0PAA "Wolfram Language (Mathematica) – Try It Online") Another 11 byte solution suggested by Martin Ender. This seems to error when there isn't one input but it still returns the correct value in all cases. **12 bytes** ``` Length@{##}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfJzUvvSTDoVpZuVbtf0BRZl5JdFq0iY6CqY6CmY6CUWwsF0yw2thIx6BWR0HJRlc3USEns7hECcYpLgGqSVdCUhycmYfEi439DwA "Wolfram Language (Mathematica) – Try It Online") My original solution. In Mathematica `##` stands for a variadic number of arguments in a function. `{` and `}` wraps them in a list and `Length@` takes the length of this list. `&` at the end turns this into an actual function. [Answer] # [R](https://www.r-project.org/), 30 bytes ``` function(...)length(list(...)) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP09DT09PMyc1L70kQyMns7gEzNf8n6ahyZWmYQgilBKVwGwdBUMDKAMhZKSjYKyjYKKjYKqjYKajYK6jYKGjYAlW@h8A "R – Try It Online") [Answer] # Bash, 12 bytes (thanks to paxdiablo for saving 4) ``` n()(echo $#) ``` Copy and paste at a bash prompt. Then run the n function from the prompt: ``` $ n 0 $ n 46 gr 3443 dad 4 $ n 4fwj23 wrw jdwj 00998 34 eyt q3 vg wq j qw 11 ``` [Answer] # [C++14 (gcc)](https://gcc.gnu.org/), 34 bytes As generic variadic lambda function (C++14 required): ``` [](auto...p){return sizeof...(p);} ``` [Try it online!](https://tio.run/##jcq7DsIgGAXgnaf4U4dCgiRepkJ9EeOAXAxJC6TAYtNnR@uoQ53OyTmfinH/UKrunFdD0Ua4kPJk5HhBSJYcwEJfrze8dsZYJPNkcpk8JPc0wb4nHAlfKkfOZxil85jMCFLWXadCySAEWEzW@GzG64H//IdNQFvZbqMjbeRdNf/AEz1/s6W@AA "C++ (gcc) – Try It Online") ### Previous (incorrect) answer: 32 bytes It was missing the `template<class...T>` and `(p)` ``` int f(T...p){return sizeof...p;} ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 9 bytes ``` @()nargin ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BQzMvsSg9M@9/moaxjomOeklqcYm6jqUmV5oGCBvqGGr@BwA "Octave – Try It Online") Anonymous function taking any number of arguments (and silently discarding the lot), and outputs the number of arguments through the built-in `nargin`. This does not work in MATLAB, where you would need `varargin` to allow for arbitrary many arguments. [Answer] # [Ruby](https://www.ruby-lang.org/), 12 bytes ``` ->*a{a.size} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rsTpRrzizKrX2f0FpSbFCWnQsF5RhCGcpJSohRHUUDA2QeWiSRjoKxjoKJjoKpjoKZjoK5joKFjoKlmBN/wE "Ruby – Try It Online") `*a` is a splat of the arguments, making `a` consume all arguments passed to the Proc. `a.size` obtains its size. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 5 bytes Thanks [@Joshua](https://codegolf.stackexchange.com/users/49934/joshua) for -5 bytes ``` {+@_} ``` [Try it online!](https://tio.run/##K0gtyjH7X1yapJD2v1rbIb72v3VBUWZeiUKahqGOgpGOgqXmfwA "Perl 6 – Try It Online") [Answer] # C++, 72 bytes ``` int f(){return 0;}template<class...P>int f(int,P...p){return f(p...)+1;} ``` Saves bytes by only working with ints. [Answer] # [Perl 5](https://www.perl.org/), 9 bytes ``` sub{~~@_} ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jo@7@4NKm6rs4hvva/tYqOrVJMnpK1gnJAUWZeiUJ@XqpCQWqRQk5mXipXAViISyVR107DUMdIx1hTB8Ix1THTMdexgHGVEovSS3NT80oMlXTgbCMlTev/AA "Perl 5 – Try It Online") [Answer] # PHP, 34 bytes ``` function(...$a){return count($a);} ``` [Answer] # C# .NET, 11 bytes ``` a=>a.Length ``` [Try it online.](https://tio.run/##ldJNawIxEAbgu7/ixdMuRK3aT8ReBE96aQ89iIdxd1ZT1kSSse0i/vZt/EKEottLYJJ3ngkkiW8k1nGZ5OQ9xpsakHLOcxKGNoJhtCJHSw87@@REJlNQ3AshLyQ6wRAZ@iip/0rNEZu5LEqgVzsHvqxOMSZtonhnA@@FF142B9Z4m3Pzw2nhkTYcZVG8l69G2hUydapXkVT7rlKsKtdRXXWvHtSjelLP6qUKf5s1/L17hsl0sx@wjau1nB5rc1EciMOCP04CjlYLA@tc2M4LOPbrXHy4ATr/GnvhvZ2VbliCQClshvYtMjp48ZWrksGMkekfTjErkJAXbeaQxe73rtZy7GuQc1RA7LEOk7e1bfkL) **Explanation:** In C# .NET `object` is used for multi-type arguments, allowing one to pass integers, strings, characters, etc. as possible inputs. For example: ``` // Can be called like: `F(2)`, `F("test")`, `F('a')`, etc. void F(object arg){ ... } ``` C# .NET can also have a fixed size of optional arguments. For example: ``` // Can be called like: `F()`, `F(2)`, `F("test")`, `F('a')`, etc. void F(object arg = null){ ... } ``` And there are also varargs, which is an undefined amount of optional arguments (which is what I've used in this answer). For example: ``` // Can be called like: `F()`, `F(2)`, `F(2, "test", 'a')`, etc. void F(params object[] args){ ... } ``` Usually lambdas are created like this: ``` System.Func<object[], int> F f = a=>a.Length; // A call like `f(new object[]{2, "test", 'a'))` will return 3 (size of the input array) ``` But unfortunately `System.Func` doesn't support `params` varargs, so I'll have to create a `delegate` instead: ``` delegate int F(params object[] args); F f = a=>a.Length; // A call like `f()` will return 0, and `f(2, "test", 'a')` will return 3 ``` Which is my answer for this challenge, and can be found in the linked TIO test code. --- The only limitation is that inputting an actual `object[]` like `f(new object[]{1,2,3})` will result in 3 instead of 1. `f(new int[]{1,2,3})` will still result in 1, because it interprets the `int[]` as a single `object`. To have the `object[]` parameter be interpret as a single object as well it can be casted to an object like this: `f((object)new object[]{1,2,3})`. [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), ~~32~~ 31 bytes ``` f dot i f dab i dip dot dab ``` [Try it online!](https://tio.run/##S8lPyS/@z5n2P42LMyW/RCFTIU0hJTGJK5OLEyiQWaAAEgQK/P//3/C/0X/L/4ZGxgA "Dodos – Try It Online") Uses Dennis' increment function. ## Explanation ``` f # definition of f - target function dot i f dab # sum of j(f(all args but first)). recurses until it has 0 args i # definition of i - returns (arg, 1) given 1 arg # arg dip dot dab # 1 (dot dab on list of length 1 returns 0, dip returns |0 - 1|) ``` Alternatively, 32 bytes without recursion in target function (thanks [@Leo](https://codegolf.stackexchange.com/users/62393/leo)) ``` dot i i dip dot dab dot i dab ``` [Try it online!](https://tio.run/##S8lPyS/@/58zJb9EIZMrk4szJbNAAcRJSUwC0VycmSDm////Df8b/bf8b2hkDAA "Dodos – Try It Online") ## Explanation ``` dot i # anonymous function: sum of i(args) # here this becomes implicit main i # definition of i - returns a list with all arguments replaced with 1 dip dot dab dot # 1 (dab dot returns empty list, dot returns 0, dip returns |0 - 1| i dab # list concatenated with i(all args but first) ``` [Answer] # Rust, 57 bytes ``` macro_rules!f{()=>{0};($($x:expr),+)=>{[$($x),+].len()};} ``` Explanation: ``` macro_rules! f { // define a macro called f () => {0}; // when called without arguments, expand to 0 ($($x:expr),+) => { // when called with 1 or more comma seperated arguments [ // rust uses [a, b, c] to make an array $($x),+ // expand to the arguments seperated with a comma ] .len() // take the length of that. }; } ``` Test: ``` fn main() { println!("{:?}", f!()); // prints 0 println!("{:?}", f!(4)); // prints 1 println!("{:?}", f!(5, 2)); // prints 2 // works with anything, as long as you dont mix things println!("{}", f!("", "a", "hello")); // prints 3 } ``` [Answer] # [R](https://www.r-project.org/), 20 bytes ``` function(...)nargs() ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP09DT09PMy@xKL1YQ/N/moahkbEOCJuYWpjrKKUpaXKlaeRkFpcAJXQMTTV1clJLSlKLinUUDK2AykCymv8B "R – Try It Online") R has [a function just for that](https://stat.ethz.ch/R-manual/R-patched/library/base/html/nargs.html). [Answer] # PHP, 35 bytes ``` function(){return func_num_args();} ``` [manual entry](http://php.net/func_num_args) [Answer] # [Common Lisp](http://www.clisp.org/), 28 bytes ``` (defun f(&rest a)(length a)) ``` [Try it online!](https://tio.run/##S87JLC74/18jJTWtNE8hTUOtKLW4RCFRUyMnNS@9JAPI0vyvUVCUmZesoJGmYKhgpGAJFAEA "Common Lisp – Try It Online") [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 3 bytes ``` L,L ``` [Try it online!](https://tio.run/##S0xJKSj4/99Hx@e/Sk5iblJKooKhHQgZ2SkYc/lzwQW5/P8DAA "Add++ – Try It Online") [Answer] # PHP, 11 bytes ``` <?=$argc-1; ``` Try it online: [1 input](https://tio.run/##K8go@P/fxt5WJbEoPVnX0Pr///@GAA) | [3 inputs](https://tio.run/##K8go@P/fxt5WJbEoPVnX0Pr///@G/43@GwMA) [Answer] # PowerShell 3, 25 bytes ``` function a(){$args.Count} ``` Usage: ``` a 1 2 ... ``` Console output for "a 1 2 3" ``` PS: C:\> a 1 2 3 3 ``` Pretty self explanatory. Powershell stores all unspecified args in the $args list, so we just grab a count of it. Since the language implicitly writes values to the console, the act of finding the count will print to the console without needing a Write-Host or Write-Output. Edit: Mistyped; should have been 25 bytes (typed 35). [Answer] ## Batch, ~~50~~ 49 bytes ``` set n=0 for %%a in (%*)do set/an+=1 exit/b%n% ``` No builtin in Batch, so we have to go old-school. Saved 1 byte thanks to @IsmaelMiguel. Outputs via exit code, or save 3 bytes if output via global variable is valid. Example of use in a full program: ``` @echo off call:c %* echo %ERRORLEVEL% exit/b :c set n=0 for %%a in (%*)do set/an+=1 exit/b%n% ``` [Answer] # x86 32-bit (i386) machine code function, 13 bytes Calling convention: **i386 System V (stack args), with a NULL pointer as a sentinel / terminator for the end-of-arg-list**. (Clobbers EDI, otherwise complies with SysV). C (and asm) don't pass type info to variadic functions, so the OP's description of passing integers or arrays with no explicit type info could only be implemented in a convention that passed some kind of struct / class object (or pointers to such), not bare integers on the stack. So I decided to assume that all the args were non-NULL pointers, and the caller passes a NULL terminator. **A NULL-terminated pointer list of args is actually used in C for functions like [POSIX `execl(3)`](http://man7.org/linux/man-pages/man3/exec.3.html)**: `int execl(const char *path, const char *arg, ... /* (char *) NULL */);` C doesn't allow `int foo(...);` prototypes with no fixed arg, but `int foo();` means the same thing: args unspecified. (Unlike in C++ where it means `int foo(void)`). In any case, this is an asm answer. Coaxing a C compiler to call this function directly is interesting but not required. `nasm -felf32 -l/dev/stdout arg-count.asm` with some comment lines removed. ``` 24 global argcount_pointer_loop 25 argcount_pointer_loop: 26 .entry: 28 00000000 31C0 xor eax, eax ; search pattern = NULL 29 00000002 99 cdq ; counter = 0 30 00000003 89E7 mov edi, esp 31 ; scasd ; edi+=4; skip retaddr 32 .scan_args: 33 00000005 42 inc edx 34 00000006 AF scasd ; cmp eax,[edi] / edi+=4 35 00000007 75FC jne .scan_args 36 ; dec edx ; correct for overshoot: don't count terminator 37 ; xchg eax,edx 38 00000009 8D42FE lea eax, [edx-2] ; terminator + ret addr 40 0000000C C3 ret size = 0D db $ - .entry ``` The question shows that the function must be able to return 0, and I decided to follow that requirement by not including the terminating NULL pointer in the arg count. This does cost 1 byte, though. (For the 12-byte version, remove the LEA and uncomment the `scasd` outside the loop and the `xchg`, but not the `dec edx`. I used LEA because it costs the same as those other three instructions put together, but is more efficient, so the function is fewer uops.) **C caller for testing**: Built with: ``` nasm -felf32 -l /dev/stdout arg-count.asm | cut -b -28,$((28+12))- && gcc -Wall -O3 -g -std=gnu11 -m32 -fcall-used-edi arg-count.c arg-count.o -o ac && ./ac ``` [`-fcall-used-edi`](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fcall-used) is required even at -O0 to tell gcc to assume that functions clobber `edi` without saving/restoring it, because I used so many calls in one C statement (the `printf` call) that even `-O0` was using EDI. It appears to be safe for gcc's `main` to clobber EDI from its own caller (in CRT code), on Linux with glibc, but otherwise it's totally bogus to mix/match code compiled with different `-fcall-used-reg`. There's no `__attribute__` version of it to let us declare the asm functions with custom calling conventions different from the usual. ``` #include <stdio.h> int argcount_rep_scas(); // not (...): ISO C requires at least one fixed arg int argcount_pointer_loop(); // if you declare args at all int argcount_loopne(); #define TEST(...) printf("count=%d = %d = %d (scasd/jne) | (rep scas) | (scas/loopne)\n", \ argcount_pointer_loop(__VA_ARGS__), argcount_rep_scas(__VA_ARGS__), \ argcount_loopne(__VA_ARGS__)) int main(void) { TEST("abc", 0); TEST(1, 1, 1, 1, 1, 1, 1, 0); TEST(0); } ``` Two other versions also came in at 13 bytes: this one based on `loopne` returns a value that's too high by 1. ``` 45 global argcount_loopne 46 argcount_loopne: 47 .entry: 49 00000010 31C0 xor eax, eax ; search pattern = NULL 50 00000012 31C9 xor ecx, ecx ; counter = 0 51 00000014 89E7 mov edi, esp 52 00000016 AF scasd ; edi+=4; skip retaddr 53 .scan_args: 54 00000017 AF scasd 55 00000018 E0FD loopne .scan_args 56 0000001A 29C8 sub eax, ecx 58 0000001C C3 ret size = 0D = 13 bytes db $ - .entry ``` This version uses rep scasd instead of a loop, but takes the arg count modulo 256. (Or capped at 256 if the upper bytes of `ecx` are 0 on entry!) ``` 63 ; return int8_t maybe? 64 global argcount_rep_scas 65 argcount_rep_scas: 66 .entry: 67 00000020 31C0 xor eax, eax 68 ; lea ecx, [eax-1] 69 00000022 B1FF mov cl, -1 70 00000024 89E7 mov edi, esp 71 ; scasd ; skip retaddr 72 00000026 F2AF repne scasd ; ecx = -len - 2 (including retaddr) 73 00000028 B0FD mov al, -3 74 0000002A 28C8 sub al, cl ; eax = -3 +len + 2 75 ; dec eax 76 ; dec eax 77 0000002C C3 ret size = 0D = 13 bytes db $ - .entry ``` Amusingly, yet another version based on `inc eax` / `pop edx` / `test edx,edx` / `jnz` came in at 13 bytes. It's a callee-pops convention, which is never used by C implementations for variadic functions. (I popped the ret addr into ecx, and jmp ecx instead of ret. (Or push/ret to not break the return-address predictor stack). [Answer] # [Go](https://golang.org/), ~~44~~ ~~30~~ 28 bytes -2 bytes thanks to BMO My first code golf attempt. ``` func(a...int){print(len(a))} ``` [Try it online](https://tio.run/##S8//X5CYnJ2YnqqQm5iZx5VWmpcMZmloVnMplCUWKaQp2P4HiWok6unpZeaVaFYXFAEpjZzUPI1ETc3a/2kahjpGOsY6BprWXLX/AQ) (outputs to Debug-window instead of STDOUT). ]
[Question] [ Related to: [Make a ;# interpreter](https://codegolf.stackexchange.com/q/121921/68910) In the above linked challenge the task was to create an interpreter for the esoteric language `;#`. ## The `;#` language The language has exactly two commands: `;` and `#` (all other characters are ignored by the interpreter): `;`: Increment the accumulator `#`: Modulo the accumulator by 127, print the corresponding ASCII character and reset the accumulator to 0. ## Challenge Because I am lazy but still want to test some more testcases, I need a program or function which converts plain text to `;#` code. ## Input The input is a string, taken either as argument or through stdin. It will only contain printable ASCII characters and newlines. ## Output The output is the generated `;#` program by returning, or printing to stdout. As long as the program is valid, it may contain excess characters other than `#` and `;` as all other characters are ignored. ## Examples ``` Input: Hello, World! Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# Input: ABC Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# Input: ;# Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ``` ## Leaderboard ``` var QUESTION_ID=122139,OVERRIDE_USER=73772;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] # [;#+](https://github.com/ConorOBrien-Foxx/shp), 61 bytes *[Outgolfed](https://codegolf.stackexchange.com/a/122210/64121) by Conor O'Brien* ``` ;;;;;;;(~;;;;;~-;-)~>:~;;;;(~;;;;;;~-;-)~>~-*((;~<#~):<#-:-*) ``` [Try it online!](https://tio.run/nexus/shp#@28NARp1YKpO11pXs87Oqg5JDCZYp6uloWFdZ6Ncp2llo6xrpaul@f@/R2pOTr5CeH5RTooiAwA ";#+ – TIO Nexus") Note that the input has a trailing null byte. [Answer] # [;#+](https://github.com/ConorOBrien-Foxx/shp), 40 bytes ``` ;;;;;~+++++++>~;~++++:>*(-(;~<#~):<#-*:) ``` [Try it online!](https://tio.run/nexus/shp#@28NAnXaEGBXB2Fa2Wlp6GpY19ko12la2Sjrallp/v/vkZqTk68Qnl@Uk6LIAAA ";#+ – TIO Nexus") Input is terminated with a null byte. ## Explanation The code is split into two parts: generation and iteration. ## Generation ``` ;;;;;~+++++++>~;~++++:> ``` This puts the constants `;` and `#` into memory as such: ``` ;;;;;~+++++++>~;~++++:> ;;;;; set A to 5 ~ swap A and B +++++++ add B to A 7 times (A, B) = (5*7, 5) = (35, 5) > write to cell 0 ~ swap A and B ; increment A ~ swap A and B (A, B) = (35, 6) ++++ add B to A 4 times (A, B) = (59, 6) : increment cell pointer > write to cell 1 ``` ## Iteration ``` *(-(;~<#~):<#-*:) * read a character into A ( * ) while input is not a null byte: - flip Δ ( ) while A != 0 ; decrement ~ swap A and B < read ";" into A # output it ~ swap A and B : decrement cell pointer < read "#" into A # output it - flip Δ * take another character from input : increment cell pointer ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~8~~ 7 bytes ``` O”;ẋp”# ``` [Try it online!](https://tio.run/nexus/jelly#@@//qGGu9cNd3QVAWvn///8eqTk5@QA "Jelly – TIO Nexus") ``` O”;ẋp”# Main Link O Map over `ord` which gets the codepoint of every character ”;ẋ Repeat ';' the required number of times ”# '#' p Cartesian Product; this puts a '#' at the end of each element in the array Implicit Output shows as a single string ``` -2 bytes thanks to @Emigna -1 byte thanks to @Dennis [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~59~~ ~~54~~ 33 bytes -21 bytes with [KSab](https://codegolf.stackexchange.com/users/15858/ksab)'s [bfbrute](https://github.com/ksabry/bfbrute) tool. ``` +[>[+<<]>>>+>++>--<],[[>.<-]<.>,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO9ouWtvGJtbOzk7bTlvbTlfXJlYnOtpOz0Y31kbPTif2/3@P1JycfIXw/KKcFEUA "brainfuck – Try It Online") [Answer] # [GS2](https://github.com/nooodl/gs2), 6 bytes ``` ■•;2•# ``` [Try it online!](https://tio.run/nexus/gs2#@/9o2oJHDYusjYCE8v//Hqk5Ofk6CuH5RTkpigA "GS2 – TIO Nexus") ### Reversible hexdump (xxd) ``` 0000000: ff 07 3b 32 07 23 ■•;2•# ``` ### How it works ``` ■ Map the rest of the program over all code points C of the input. •; Push ';'. 2 Multiply; repeat ';' C times. •# Push '#'. ``` [Answer] # Taxi, 779 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[c]Switch to plan "e" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:n 1 l 3 l 3 l.Pickup a passenger going to The Underground.Go to Writer's Depot:w 1 r.[p]; is waiting at Writer's Depot.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to The Underground:n 1 r 1 l.Switch to plan "n" if no one is waiting.Pickup a passenger going to The Underground.Go to Zoom Zoom:n 3 l 2 r.Go to Writer's Depot:w.Switch to plan "p".[n]# is waiting at Writer's Depot.Go to Writer's Depot:n 3 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Switch to plan "c".[e] ``` [Try it online!](https://tio.run/nexus/taxi#rZJLa8MwEIT/yuAcehP0cUqOLeTYQFoKNT6oytoWVbVCkjH99a5fSY2TulB6kISk3ZnRh5otIzJ2HCIe81wrWte4hmmH71ax0@q9cpBwMgSyBXkUrG3Rdd2X7LCv6FMMKqf92h77cTfqpCrb1zqqsit0RloklEDnsAy2BB1QSx1b5V8spX9jbbD12piT7/SwNze4Hcai2lNJeLYH8oXnyh5GuRevI/mrgAdyHHseXqQu20xCQsZZ3aLRhK84Jz7QuhlJDfezaN9ExRyj/QPGyw9/Zf7op9atw9cm@gHJWQiXiNRmq2VCF7WOVuafAS59xnl61aanrGk2qy8) Ungolfed: ``` Go to Post Office: west 1st left 1st right 1st left. Pickup a passenger going to Chop Suey. Go to Chop Suey: north 1st right 1st left 4th right 1st left. [c] Switch to plan "e" if no one is waiting. Pickup a passenger going to Charboil Grill. Go to Charboil Grill: north 1st left 3rd left 3rd left. Pickup a passenger going to The Underground. Go to Writer's Depot: west 1st right. [p] ; is waiting at Writer's Depot. Pickup a passenger going to Post Office. Go to Post Office: north 1st right 2nd right 1st left. Go to The Underground: north 1st right 1st left. Switch to plan "n" if no one is waiting. Pickup a passenger going to The Underground. Go to Zoom Zoom: north 3rd left 2nd right. Go to Writer's Depot: west. Switch to plan "p". [n] # is waiting at Writer's Depot. Go to Writer's Depot: north 3rd left 2nd left. Pickup a passenger going to Post Office. Go to Post Office: north 1st right 2nd right 1st left. Go to Chop Suey: north 1st right 1st left 4th right 1st left. Switch to plan "c". [e] ``` Explanation: ``` Pick up stdin and split it into characters. Covert each character to ASCII. Print ";" as you count down from that ASCII to zero. Print "#". Pickup the next character and repeat until done. ``` [Answer] # Brainfuck, 43 bytes ``` +[+[<]>->++]--[>--<+++++++]>-<,[[<.>-]>.<,] ``` Null byte terminates the program. ## Explanation ``` +[+[<]>->++] 59 (semicolon) location 5 --[>--<+++++++]>- 35 (hash) location 7 <,[ input location 6 [ while input byte not 0 <.> print semicolon - decrement input byte ] >.< print hash ,] loop while input not null ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Ç';×'#«J ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4Xd368HR15UOrvf7/90jNycnXUQjPL8pJUQQA "05AB1E – TIO Nexus") **Explanation** ``` Ç # convert each input char to its ascii value ';× # repeat ";" those many times '#« # append a "#" to each run of semi-colons J # join to string ``` [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` [print(";"*ord(s)+"#")for s in input()] ``` [Try it online!](https://tio.run/nexus/python3#@x9dUJSZV6KhZK2klV@UolGsqa2krKSZll@kUKyQmQdEBaUlGpqx//97pObk5OsohOcX5aQoAgA "Python 3 – TIO Nexus") [Answer] ## [><>](https://esolangs.org/wiki/Fish), 22 bytes ``` i:0(?;\"#"o o1-:?!\";" ``` [Try it online](https://tio.run/nexus/fish#@59pZaBhbx2jpKyUz5VvqGtlrxijZK30/39aZnEGAA "><> – TIO Nexus"), or at the [fish playground](https://fishlanguage.com/playground) Input is STDIN, output is STDOUT. In ><>, characters and ASCII codes are the same thing, so all we need to do is read a character, print `";"` and decrement the character until it's 0, then print `"#"` and loop until there's no more input left. [Answer] # F#, 79 bytes ``` let c i=System.String.Join("#",Seq.map(fun c->String.replicate(int c)";")i)+"#" ``` [Try it online!](https://tio.run/##ZcuxCsIwEIDh3aeIV4QE27xAsVBdxDWDc4kXOUgvMYmD4LvHDC7i@v98Lg9r4FCrxyKsoIN55YKrNiUR3/UlEEvooDf40OsSpXuysMP03QmjJ7sUlMSNKxhBkdo3UK2AM3ofenENyd@28J5iM8Ux7DJs2p6Pp/84dr@tfgA "F# (Mono) – Try It Online") # Expanded ``` // string -> string let convert input = System.String.Join( "#", // join the following char seq with "#" input // replicate ";" n times where n = ASCII value of char c |> Seq.map (fun c-> String.replicate (int c) ";") ) + "#" // and add the last "#" to the output ``` convert takes the input string and outputs a ;# program ## Usage ``` convert "Hello, World!" |> printfn "%s" convert "ABC" |> printfn "%s" convert ";#" |> printfn "%s" ``` [Answer] # Python 2 - 36 bytes ``` for i in input():print';'*ord(i)+'#' ``` **[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITMPiApKSzQ0rQqKMvNK1K3VtfKLUjQyNbXVldX//1f3SM3JyddRCM8vyklRBwA)** [Answer] # PowerShell, ~~29~~ ~~27~~ 25 bytes ``` $args|% t*y|%{';'*$_+'#'} ``` Pretty straightforward. Takes input as command-line argument. Output is a valid ;# program that prints the requested text. [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 47 bytes ``` +++++++[->++++++++>+++++<<]>+++<,[[>.<-]>>.<<,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwKide2gLG0Iw8YmFsSw0YmOttOz0Y21A5I2OrH//3uk5uTk6yiE5xflpCgCAA "brainfuck – Try It Online") See also: [ovs's answer](https://codegolf.stackexchange.com/a/122169/66421), which takes a similar approach, but with a different method of generating constants and a different cell layout. --- ## Explanation: This challenge lines up with the brainfuck spec pretty well, which means the solution is essentially trivial. Brainfuck takes input as ASCII values, which is exactly what ;# need to output as. The schematic for transpiling is simple: Generate the ASCII value for `;` and `#`, print `;` equal to the ASCII value of the input character, print `#`, repeat for every input. ``` +++++++[- 7 >++++++++ * 8 = 56 >+++++<< * 5 = 35 (#) ]>+++< 56 + 3 = 59 (;) ,[ Input into first cell [>.<-] Print ;'s equal to ASCII input >>.<<, Print one # ] End on EOF ``` [Answer] ## Mathematica, 49 bytes ``` StringRepeat[";",#]<>"#"&/@ToCharacterCode@#<>""& ``` ## Explanation [![enter image description here](https://i.stack.imgur.com/Ibq6V.png)](https://i.stack.imgur.com/Ibq6V.png) Converts the input string to a list of character codes, then `Map`s the function `StringRepeat[";",#]<>"#"&` over the list, then `StringJoin`s the result with the empty string. [Answer] # JavaScript, ~~55~~ ~~54~~ ~~51~~ ~~50~~ 48 bytes ``` s=>1+[...s].map(c=>";".repeat(Buffer(c)[0])+"#") ``` [Try it online](https://tio.run/##BcHBDoIwDADQX9FyaQM2ejbjwIk/4EB2WEZnNJUuG/r7471P@Icayzsft902acm16sZHvzJz9fwNGaMb4QlcJEs4cPqlJAUjrXdPPXRALdpeTYXVXpgQZlG14bJY0e0KRO0E) * 1 byte saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil). --- ## Alternatives If we can take input as an array of individual characters then 5 bytes can be saved. ``` a=>1+a.map(c=>";".repeat(Buffer(c)[0])+"#") ``` If we can also output as an array then 2 more bytes can be saved. ``` a=>a.map(c=>";".repeat(Buffer(c)[0])+"#") ``` [Answer] # [Aceto](https://github.com/aceto/aceto), 19 bytes Since there's an [interpreter in Aceto](https://codegolf.stackexchange.com/a/121990/21173), I thought there outta be an Aceto answer to this challenge as well. It fits neatly in a 2rd order Hilbert curve: ``` \n;* 'o'p `!#' ,dpO ``` First of all, we read a single character (`,`) and duplicate and negate it to test whether it is a newline (`d!`, when reading a newline, an empty character is normally pushed on the stack). I then use what I think is a pretty clever trick to handle the newline case compactly: ``'\n` If the value on the stack is `True` (we read a newline), that code means: *do* (```) put a character literal on the stack (`'`), which is a newline: `\n`. If the value on the stack is `False` (we didn't read a newline), that code means: *don't* (```) read a character literal (`'`). That means the next character is executed as a command. Fortunately, a backslash escapes the next command (it makes it so that it doesn't get executed), so `n` doesn't print a newline (which is what `n` usually does). The rest of the code is straightforward; we convert the character on the stack to the integer of its unicode codepoint (`o`), we push a literal semicolon (`';`), multiply the number with the string (`*`, like in Python), `p`rint the result, push a literal (`'`) `#`, `p`rint it too, and go back to the `O`rigin. Run with `-F` if you want to see immediate results (because buffering), but it works without, too. [Answer] # Perl, 24 bytes ``` s/./";"x(ord$&)."#"/ges ``` Run with `perl -pe`. Alternative solution: ``` say";"x ord,"#"for/./gs ``` Run with `perl -nE`. [Answer] # [Solace](https://github.com/splcurran/Solace), 11 bytes Yay, new languages. ``` ';@jx{'#}Ep ``` ### Explanation ``` '; Push the code point of ';' (59). @j Push the entire input as a list of code points. x For each code point in the input, repeat 59 that many times. { }E For each resulting list of 59s: '# Push the code point of '#' (35). p Flatten and print as unicode characters. ``` [Answer] # [Fourier](http://github.com/beta-decay/Fourier), 19 bytes ``` $(I(`;`&j)`#`0~j&i) ``` [**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=JChJKGA7YCZqKWAjYDB-aiZpKQ) To run, you must enclose the input string in quotation marks. ***Explanation pseudocode*** ``` While i != Input length temp = pop first char of Input While j != Char code of temp Print ";" Increment j End While Print "#" j = 0 Increment i End While ``` [Answer] # R, ~~59~~ 56 bytes ``` for(x in utf8ToInt(scan(,'')))cat(rep(';',x),'#',sep="") ``` [Try it online!](https://tio.run/##K/r/Py2/SKNCITNPobQkzSIk3zOvRKM4OTFPQ0ddXVNTMzmxRKMotUBD3Vpdp0JTR11ZXac4tcBWSUnzv7XyfwA "R – Try It Online") [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~23~~ ~~17~~ 10 bytes -5 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king). ``` "#@~k:*k,; ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X0nZoS7bSitbx/r/f4/UnJx8HYXw/KKcFEUA "Befunge-98 (FBBI) – Try It Online") [Answer] # [Actually](https://github.com/Mego/Seriously), 11 bytes ``` O⌠';*'#o⌡MΣ ``` [Try it online!](https://tio.run/nexus/actually#@@//qGeBurWWunL@o56FvucW//@v5JGak5OvoxCeX5SToqgEAA "Actually – TIO Nexus") Explanation: ``` O⌠';*'#o⌡MΣ O convert string to list of ASCII ordinals ⌠';*'#o⌡M for each ordinal: ';* repeat ";" that many times '#o append "#" Σ concatenate ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 18 bytes ``` '#',¨⍨';'⍴¨⍨⎕UCS ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@RR2wR1ZXWdQyse9a5Qt1Z/1LsFzHzUNzXUORgor6DukZqTk6@jEJ5flJOiqM6lrs4FFHR0coYxrZXVAQ "APL (Dyalog Unicode) – Try It Online") `⎕UCS` Convert to Unicode code points `';'⍴¨⍨` use each code point to reshape (*⍴* = *Rho* ≈ *R*; *R*eshape) a semicolon `#',¨⍨` append a hash to each string [Answer] # Ruby, ~~28~~ 25 bytes 24 bytes, plus the `-n` command line switch to repeatedly operate on `stdin`. ``` $_.bytes{|b|$><<?;*b+?#} ``` 3 bytes saved (and output corrected on newlines!) thanks to manatwork. [Answer] # PHP, 54 Bytes ``` for(;$o=ord($argn[$i++]);)echo str_repeat(";",$o)."#"; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfJIzcnJ11EIzy/KSVFUsv6fll@kYa2Sb5tflKIBVhKtkqmtHatprZmanJGvUFxSFF@UWpCaWKKhZK2ko5KvqaekDNT2HwA "PHP – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), 12 bytes ``` '#I.h%&';d&O ``` [Try it online!](https://tio.run/nexus/alice#@6@u7KmXoaqmbp2i5v//v0dqTk6@jkJ4flFOiiIA "Alice – TIO Nexus") ### Explanation ``` '# Push 35, the code point of '#'. I Read a code point C from STDIN. Pushes -1 at EOF. .h% Compute C%(C+1). For C == -1, this terminates the program due to division by zero. For C > -1, this just gives back C, so it does nothing. &'; Pop C and push that many 59s (the code point of ';'). d Push the stack depth, which is C+1. &O Print that many code points from the top of the stack. The IP wraps around to the beginning and another iteration of this loop processes the next character. ``` [Answer] # PHP, 48 bytes ``` for(;$c?:~$c=~ord($argn[$i++]);)echo";#"[!++$c]; ``` [Answer] # jq, 30 characters (26 characters code + 4 characters command line options) ``` explode|map(";"*.+"#")|add ``` Sample run: ``` bash-4.4$ jq -Rr 'explode|map(";"*.+"#")|add' <<< 'Hello, World!' | jq -Rrj '[scan(".*?#")|gsub("[^;]";"")|length%127]|implode' Hello, World! ``` [On-line test](https://jqplay.org/s/azUJuDB8td) [Answer] # Pyth, 10 bytes ``` sm_+\#*\;C ``` [Try it!](https://pyth.herokuapp.com/?code=sm_%2B%5C%23%2a%5C%3BC&input=%22ABC%22&debug=0) ]
[Question] [ **Problem:** Your goal is to add two input numbers without using any of the following math operators: `+,-,*,/`. Additionally, you can't use any built-in functions that are designed to replace those math operators. **Scoring:** Smallest code (in number of bytes) wins. **Update** > > Most of the programs i've seen either concatenate two arrays containing their numbers, or make `first number` of a character, append `second number` characters, then count them all. > > > Shortest array counter: [APL with 8 chars, by Tobia](https://codegolf.stackexchange.com/a/21087/) > > > Shortest array concatenation: [Golfscript with 4 chars, by Doorknob](https://codegolf.stackexchange.com/a/21017/) > > > Shortest logarithmic solution: [TI-89 Basic with 19 chars, by Quincunx](https://codegolf.stackexchange.com/a/21464/9498) > > > Integration solution: [Mathematica with 45 chars, by Michael Stern](https://codegolf.stackexchange.com/a/21018/9498) > > > Coolest, in my opinion: [bitwise operators in javascript, by dave](https://codegolf.stackexchange.com/a/21025/) > > > [Answer] ## Javascript (25) ``` while(y)x^=y,y=(y&x^y)<<1 ``` This adds two variables x and y, using only bitwise operations, and stores the result in x. This works with negative numbers, too. [Answer] ## C - 38 bytes ``` main(){return printf("%*c%*c",3,0,4);} ``` --- I do cheat a bit here, the OP said to not use any *math* operators. The `*` in the `printf()` format means that the field width used to print the character is taken from an argument of `printf()`, in this case, 3 and 4. The return value of `printf()` is the number of characters printed. So it's printing one `' '` with a field-width of 3, and one with a field-width of 4, makes 3 + 4 characters in total. The return value is the added numbers in the `printf()` call. [Answer] # Python - 49 bytes Assuming input by placement in variables `x` and `y`. ``` from math import* print log(log((e**e**x)**e**y)) ``` This **61 byte** solution is a full program: ``` from math import* print log(log((e**e**input())**e**input())) ``` Considering that you did not ban exponentiation, I had to post this. When you simplify the expression using properties of logarithms, you simply get `print input() + input()`. This supports both negative and floating point numbers. Note: I followed [gnibbler's advice](http://meta.codegolf.stackexchange.com/questions/1003/is-it-better-to-post-one-answer-or-two#comment3694_1026) and split this answer into three. This is [the Mathematica solution](https://codegolf.stackexchange.com/a/21462/9498), and this is [the TI-89 Basic solution](https://codegolf.stackexchange.com/a/21464/9498). [Answer] ## JavaScript [25 bytes] ``` ~eval([1,~x,~y].join('')) ``` [Answer] # GolfScript, ~~6~~ 4 characters/bytes Input in the form of `10, 5` (=> `15`). ``` ~,+, ``` The `+` is array concatenation, not addition. How it works is that `,` is used to create an array of the length that the number is (`0,1,...,n-2,n-1`). This is done for both numbers, then the arrays are concatenated. `,` is used again for a different purpose, to find the length of the resulting array. Now, **here's the trick**. I really like this one because it abuses the input format. It *looks* like it's just inputting an array, but really, since the input is being executed as GolfScript code, the first `,` is already done for me! (The old 6-character version was `~,\,+,` with input format `10 5`, which I shaved 2 chars off by eliminating the `\,` (swap-array)). **Old version (12)**: Creates a function `f`. ``` {n*\n*+,}:f; ``` The `*` and `+` are string repetition and concatenation respectively, not arithmetic functions. Explanation: `n` creates a one-character string (a newline). This is then repeated `a` times, then the same thing is done with `b`. The strings are concatenated, and then `,` is used for string length. [Answer] ## Mathematica, 21 bytes There are a number of ways to do this in Mathematica. One, use the Accumulate function and toss everything but the final number in the output. As with my other solution below, I assume the input numbers are in the variables `a` and `b`. 21 bytes. ``` Last@Accumulate@{a, b} ``` More fun, though it is 45 characters, use the numbers to define a line and integrate under it. ``` Integrate[Fit[{{0, a}, {2, b}}, {x, 1}, x], {x, 0, 2}] ``` As a bonus, both solutions work for all complex numbers, not just positive integers as seems to be the case for some other solutions here. [Answer] ## C, 29 27 Bytes Using pointer arithmetic: ``` f(x,y)char*x;{return&x[y];} ``` `x` is defined as a pointer, but the caller should pass an integer. An anonymous user suggested the following - also 27 bytes, but parameters are integers: ``` f(x,y){return&x[(char*)y];} ``` [Answer] # Brainf\*ck, 9 36 ``` ,>,[-<+>] ``` ``` ++[->,[->>[>]+[<]<]<]>>>[<[->+<]>>]< ``` This works without using simple addition; it goes through and lays a trail of 1's and then counts them up Note: The `+` and `-` are merely single increments and nothing can be done in brainf\*ck without them. They aren't really addition/subtraction so I believe this still counts. [Answer] # J (6) You didn't say we couldn't use the succ function: ``` >:@[&0 ``` Usage: ``` 9>:@[&0(8) 17 ``` It just does 9 repetitions of `>:` on 8. The list concatenation approach works, too: `#@,&(#&0)`. And - I know it's against the rules - I can't let this answer go without the most J-ish solution: `*&.^` (multiplication under exponentiation). [Answer] ## Postscript, 41 We define function with expression 41 bytes long as: ``` /a{0 moveto 0 rmoveto currentpoint pop}def ``` Then we call it e.g. as: ``` gs -q -dBATCH -c '/a{0 moveto 0 rmoveto currentpoint pop}def' -c '10 15 a =' ``` Which gives ``` 25.0 ``` It easily handles negatives and floats, unlike most competitors:-) [Answer] bash, 20 chars ``` (seq 10;seq 4)|wc -l ``` [Answer] # Smalltalk (now seriously), 123 118 105(\*) Sorry for answering twice, but consider this a serious answer, while the other one was more like humor. The following is actually executed right at this very moment in all of our machines (in hardware, though). Strange that it came to no one else's mind... By combining two half-adders, and doing all bits of the words in parallel, we get (inputs a,b; output in s) readable version: ``` s := a bitXor: b. c := (a & b)<<1. [c ~= 0] whileTrue:[ cn := s & c. s := s bitXor: c. c := cn<<1. c := c & 16rFFFFFFFF. s := s & 16rFFFFFFFF. ]. s ``` The loop is for carry propagation. The masks ensure that signed integers are handled (without them, only unsigned numbers are possibe). They also define the word length, the above being for 32bit operation. If you prefer 68bit addition, change to 16rFFFFFFFFFFFFFFFFF. golf version (123 chars) (avoids the long mask by reusing in m): ``` [:a :b||s c n m|s:=a bitXor:b.c:=(a&b)<<1.[c~=0]whileTrue:[n:=s&c.s:=s bitXor:c.c:=n<<1.c:=c&m:=16rFFFFFFFF.s:=s&m].s] ``` (\*) By using -1 instead of 16rFFFFFFFF, we can golf better, but the code no longer works for arbitrary precision numbers, only for machine-word sized smallIntegers (the representation for largeIntegers is not defined in the Ansi standard): ``` [:a :b||s c n|s:=a bitXor:b.c:=(a&b)<<1.[c~=0]whileTrue:[n:=s&c.s:=s bitXor:c.c:=n<<1.c:=c&-1.s:=s&-1].s] ``` this brings the code size down to 105 chars. [Answer] # APL, 8 and 12 Nothing new here, the array counting version: ``` {≢∊⍳¨⍺⍵} ``` and the log ○ log version: ``` {⍟⍟(**⍺)**⍵} ``` I just thought they looked cool in APL! ``` {≢ } count ∊ all the elements in ⍳¨ the (two) sequences of naturals from 1 up to ⍺⍵ both arguments ```   ``` {⍟⍟ } the double logarithm of (**⍺) the double exponential of ⍺ * raised to *⍵ the exponential of ⍵ ``` [Answer] # sed, 359 bytes (without the fancy formatting) Sorry for the late answer, and probably the longest answer here by far. But I wanted to see if this is possible with sed: ``` s/([^ ]+) ([^ ]+)/\1:0::\2:/ :d /^([^:]+):\1::([^:]+):/tx s/(:[^:]*)9([_:])/\1_\2/g;td s/(:[^:]*)8(_*:)/\19\2/g;s/(:[^:]*)7(_*:)/\18\2/g;s/(:[^:]*)6(_*:)/\17\2/g s/(:[^:]*)5(_*:)/\16\2/g;s/(:[^:]*)4(_*:)/\15\2/g;s/(:[^:]*)3(_*:)/\14\2/g s/(:[^:]*)2(_*:)/\13\2/g;s/(:[^:]*)1(_*:)/\12\2/g;s/(:[^:]*)0(_*:)/\11\2/g s/:(_+:)/:1\1/g; y/_/0/; # # bd; :x s/.*::([^:]+):/\1/; # # # # # # # # # # # # # # ``` This is similar to <https://codegolf.stackexchange.com/a/38087/11259>, which simply increments numbers in a string. But instead it does the increment operations in a loop. Input is taken from STDIN in the form "x y". That is first transformed to "x:0::y:". Then we increment all numbers that come after ":" characters, until we get "x:x::(x+y):". Then we finally return (x+y). # Output ``` $ printf "%s\n" "0 0" "0 1" "1 0" "9 999" "999 9" "12345 67890" "123 1000000000000000000000" | sed -rf add.sed 0 1 1 1008 1008 80235 1000000000000000000123 $ ``` Note that this only works for the natural numbers. However (in theory at least) it works for arbitrarily large integers. Because we are doing x increment operations on y, ordering can make a big difference to speed: x < y will be faster than x > y. [Answer] # [Dash](https://wiki.debian.org/Shell), 18 bytes ``` time -f%e sleep $@ ``` Requires GNU time 1.7 or higher. Output is to STDERR. [Try it online!](https://tio.run/##S0kszvj/vyQzN1VBN001VaE4JzW1QEHF4f///4b/jQA "Dash – Try It Online") Note that this will not work in **B**​ash, since its builtin time command differs from GNU time. At the cost of one additional byte, `\time` can be used instead of `time` to force Bash to use the external command. [Answer] # Smalltalk, 21 13 All of the following only work on positive integers. See the ***other Smalltalk*** answer for a serious one. ### version1 shifting to a large integer and asking it for its high bit index (bad, ST indexing is 1-based, so I need an additional right shift): ``` (((1<<a)<<b)>>1)highBit ``` ### version2 similar, and even a bit shorter (due to Smalltalk precedence rules, and no right shift needed): ``` 1<<a<<b log:2 ``` ### version3 another variation of the "collection-concatenating-asking size" theme, given two numbers a and b, ``` ((Array new:a),(Array new:b)) size ``` using Intervals as collection, we get a more memory friendly version ;-) in 21 chars: ``` ((1to:a),(1to:b))size ``` not recommended for heavy number crunching, though. ### version4 For your amusement, if you want to trade time for memory, try: ``` Time secondsToRun:[ Delay waitForSeconds:a. Delay waitForSeconds:b. ] ``` which is usually accurate enough (but no guarantee ;-))) ### version5 write to a file and ask it for its size ``` ( [ 't' asFilename writingFileDo:[:s | a timesRepeat:[ 'x' printOn:s ]. b timesRepeat:[ 'x' printOn:s ]]; fileSize ] ensure:[ 't' asFilename delete ] ) print ``` [Answer] ## Javascript (67) There is probably much better ``` a=Array;p=Number;r=prompt;alert(a(p(r())).concat(a(p(r()))).length) ``` [Answer] Ruby, 18 chars ``` a.times{b=b.next} ``` And two more verbose variants, 29 chars ``` [*1..a].concat([*1..b]).size ``` Another version, 32 chars ``` (''.rjust(a)<<''.rjust(b)).size ``` [Answer] # Ruby 39 ``` f=->a,b{[*1..a].concat([*1..b]).length} ``` [Answer] # C# - on the fly code generation Yeah, there is actually an addition in there, but not the + operator and not even a framework function which does adding, instead we generate a method on the fly that does the adding. ``` public static int Add(int i1, int i2) { var dm = new DynamicMethod("add", typeof(int), new[] { typeof(int), typeof(int) }); var ilg = dm.GetILGenerator(); ilg.Emit(OpCodes.Ldarg_0); ilg.Emit(OpCodes.Ldarg_1); ilg.Emit(OpCodes.Add); ilg.Emit(OpCodes.Ret); var del = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>)); return del(i1, i2); } ``` [Answer] # K, 2 bytes ``` #& ``` Usage example: ``` #&7 212 219 ``` Apply the "where" operator (monadic `&`) to the numbers in an input list (possibly taking liberty with the input format). This will produce a list containing the first number of zeroes followed by the second number of ones: ``` &3 2 0 0 0 1 1 ``` Normally this operator is used as a "gather" to produce a list of the indices of the nonzero elements of a boolean list, but the generalized form comes in handy occasionally. Then simply take the count of that list (monadic `#`). If my interpretation of the input requirements is unacceptable, the following slightly longer solution does the same trick: ``` {#&x,y} ``` [Answer] ## R 36 ``` function(x,y)length(rep(1:2,c(x,y))) ``` where `rep` builds a vector of `x` ones followed by `y` twos. [Answer] # TI Basic 89 - 19 bytes Run this in your TI-89 (Home screen or programming app): ``` ln(ln((e^e^x)^e^y)) ``` This uses log rules to compute `x+y`, just like in [this solution](https://codegolf.stackexchange.com/a/21033/9498). As a bonus, it works for decimal and integer numbers. It works for all real numbers. If the logarithm rules are still valid with complex exponents, then this works for complex numbers too. However, my calculator spits out junk when I try to insert complex exponents. [Answer] Thanks to [Michael Stern for teaching me Mathematica notation](https://codegolf.stackexchange.com/questions/20996/add-without-addition-or-any-of-the-4-basic-arithmetic-operators/21033?noredirect=1#comment42342_21033). # Mathematica - ~~21~~ 20 bytes ``` Log@Log[(E^E^x)^E^y] ``` This uses the same approach as [this solution](https://codegolf.stackexchange.com/a/21033/9498), but it is in Mathematica to make it shorter. This works for negative and floating point numbers as well as integers in `x` and `y`. Simplifying the expression using log rules yields `x+y`, but this is valid since it uses exponentiation, not one of the 4 basic operators. [Answer] # C# - string arithmetics We convert both numbers to strings, do the addition with string cutting (with carry and everything, you know), then parse back to integer. Tested with i1, i2 in 0..200, works like a charm. Find an addition in this one! ``` public static int Add(int i1, int i2) { var s1 = new string(i1.ToString().Reverse().ToArray()); var s2 = new string(i2.ToString().Reverse().ToArray()); var nums = "01234567890123456789"; var c = '0'; var ret = new StringBuilder(); while (s1.Length > 0 || s2.Length > 0 || c != '0') { var c1 = s1.Length > 0 ? s1[0] : '0'; var c2 = s2.Length > 0 ? s2[0] : '0'; var s = nums; s = s.Substring(int.Parse(c1.ToString())); s = s.Substring(int.Parse(c2.ToString())); s = s.Substring(int.Parse(c.ToString())); ret.Append(s[0]); if (s1.Length > 0) s1 = s1.Substring(1); if (s2.Length > 0) s2 = s2.Substring(1); c = s.Length <= 10 ? '1' : '0'; } return int.Parse(new string(ret.ToString().ToCharArray().Reverse().ToArray())); } ``` [Answer] # C (79) ``` void main(){int a,b;scanf("%d%d",&a,&b);printf("%d",printf("%*c%*c",a,0,b,0));} ``` [Answer] # Python -- 22 characters ``` len(range(x)+range(y)) ``` [Answer] **APL: 2** ``` 1⊥ ``` This converts the numbers from base 1, so (n\*1^1)+(m\*1^2) which is exactly n+m. Can be tried on [TryApl.org](http://TryApl.org) [Answer] ## TI-BASIC, 10 Adds `X` and `Y` ``` ln(ln(e^(e^(X))^e^(Y ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 29 bytes ``` AQW!qG0=k.&GH=HxGH=k.<k1=Gk)H ``` [Try it online!](https://tio.run/##K6gsyfj/3zEwXLHQ3cA2W0/N3cPWowJIZOvZZBvaumdrevz/r2FooGOsCQA "Pyth – Try It Online") My first submission here! This compiles to: ``` assign('Q',eval_input()) # Q assign('[G,H]',Q) #A while Pnot(equal(G,0)): # W!qG0 assign('k',bitand(G,H)) # =k.&GH assign('H',index(G,H)) # =HxGH (index in this case is XOR) assign('k',leftshift(k,1)) # =k.<k1 assign('G',k) # =Gk) imp_print(H) # H ``` ]
[Question] [ [![enter image description here](https://i.stack.imgur.com/cfNEC.png)](https://i.stack.imgur.com/cfNEC.png) Given one of the following inputs: ``` Sweet Onion Chicken Teriyaki Oven Roasted Chicken Turkey Breast Italian BMT Tuna Black Forest Ham Meatball Marinara ``` output a number from 1-7 (or 0-6) representing the day of the week that you get that deal, starting with Monday as the lowest number. Input can be all lowercase or uppercase if preferred (i.e "italian bmt"). No internet allowed. [Answer] # [Python 2](https://docs.python.org/2/), ~~38~~ ~~30~~ 28 bytes ``` lambda S:`6793**164`[len(S)] ``` [Try it online!](https://tio.run/##NY7BasMwEETv/YpFYJCCW0hbUhpID44x6cEEat@SQDbRliiWV0ZS2vrrXVHoYRjmvcsMY7w4fpyq1X6y2J80QrM8Ll5en2az@eL5uLPEslGHqVztRPNNFGHLxjGsL@bcEUNL3ozYGZGL7VfaHw5DJP3vE25vvqMRCk/JpP0e0RpkKOr2zzKmKiyeO6icpxBhg31CNWE8obVQozeMHsXh7tN50GAYyuWQYBRZgPs3yILIpH7w11uIsseflEGm53mplMorqZWafgE "Python 2 – Try It Online") ~~Unfortunately still **one** byte longer than the best Python 2 answer thus far; though not using the `enklact`-approach.~~ Now **one byte shorter** than [i cri everytim's answer](https://codegolf.stackexchange.com/a/141677/73111)! ### How does it work? After a lot of brute force, I found an expression that results in a number which has just the right digits. I noticed that looking at only one specific digit of the given string's lengths required 3 bytes (`%10`). So I wrote another Python program ([Pastebin link](https://pastebin.com/4AVvZgKi)) to further search for numbers who directly map the input strings' lengths to the day of the week. The magic number looks like this: `6793**164 = 28714733692312345620167113260575862840674216760386883406587492336415023761043044176257567032312859371641211117824224067391750766520256112063756278010050204239810862527958109285342869876264808102743173594017101607983288521836082497514383184553444755034407847810524083812459571382103831904835921560285915349760536969265992879312869538914200854305957428078269094250817029486005437991820466986793657301214564264748923199288698278615871481529585816783654841131577178922192383679718074693535597651237893794976519274268917335387876260270630339777501802739852278932279775510324916969726203688466311848240746465178859847331248655567344801` (a number with an impressive 629 decimal digits) And as you can see, the number provides the necessary mapping from [28, 20, 13, 11, 4, 16, 17] to [0, 1, 2, 3, 4, 5, 6] (Python strings are 0-indexed): `2871 **4** 733692 **3** 1 **2** 34 **5** **6** 20 **1** 6711326 **0** 5758628406742167603868834... [4]^ [11]^ [13]^ [16]^ ^[17] ^[20] ^[28]` My program also found other expressions which yield numbers with the required property, though they take more bytes to represent (29 instead of 28): `19439**540`, `34052**726`, `39311**604`, `44873**182`, `67930**164` and `78579**469`. (Those are all the expressions found by the linked program; its execution took several hours.) Alternative function that requires 28 bytes: `lambda S:`7954<<850`[len(S)]` Alternative function that requires 29 bytes: `lambda S:`9699<<2291`[len(S)]` Alternative function that requires 30 bytes: `lambda S:`853<<4390`[len(S)+9]` Alternative function that requires 31 bytes: `lambda S:`1052<<3330`[len(S)+8]` ### How does it work? How did I generate that number? (30 byte answer) The 30 byte answer was `lambda S:`3879**41`[len(S)%10]`. Looking at the input string's lengths `[28, 20, 13, 11, 4, 16, 17]`, I noticed that all last digits in base ten differ, resulting in the list `[8, 0, 3, 1, 4, 6, 7]`. So I only needed a mapping from that list to the list of all seven days of the week, `[0, 1, 2, 3, 4, 5, 6]`. My first approach simply used a string to perform the mapping: `lambda S:"13*24*560"[len(S)%10]`, though the string required eleven bytes (`"13*24*560"`). So I wrote a Python program ([Pastebin link](https://pastebin.com/Tpfcg3LD)) to test for arithmetic expressions which result in an integer with matching digits, hoping to further golf the program. What I came up with thus far is ``3879**41`` (only ten bytes, the only and thereby smallest expression my program finds). Of course, there are many different possible expressions one could try; I just got lucky that there was one in the form `a**b` with a reasonably small result that fit my need. Just for anyone curious, `3879**41 = 1372495608710279938309112732193682350992788476725725221643007306215781514348937145528919415861895033279220952836384201346579163035594383625990271079 = 1.372... * 10**147`. Another valid function I found whilst searching for alternative expressions that unfortunately requires 32 bytes: `lambda S:`7**416`[len(S)%10+290]` [Answer] # [Python 2](https://docs.python.org/2/), 29 bytes ``` lambda s:'enklact'.find(s[3]) ``` [Try it online!](https://tio.run/##NY4xi8JAEIX7@RVDGpPiBL0uYJMD0SIIms6zGM2EDLvOht3RI78@txxc@d734HvTbGPQ7TLsvhdPz3tPmOoVq/P0sNV6EO3LdP28VYtxsoQ7LIoCLj/MhieVoPg1ysOxYsdRZnICp3dO50DJuP@n0L2i4xmbyLmHo5EXUmzaLhMlaLLO4T7ELMEDPaFlsjt5jy1FUYoE2Xvd1B@b2zpNXsyLciorgCFEFBTFv4M1TnlvOJRSLb8 "Python 2 – Try It Online") ## Explanation The magic string, `enklact`, was found by looking for the first column with unique letters. The first column goes `SOTITBM` which is not useful 'cause it contains duplicates. The second and third ones also don't work because they are `wvutule` and `eeranaa` respectively. The fourth column, however works as it has all unique letters. ``` lambda s:'enklact'.find(s[3]) lambda s: # declare a function that takes a single paramater s .find( ) # find the index of the first instance of... s[3] # the fourth (0-indexing) character of s... 'enklact' # in the magic string ``` [Answer] # [Python](https://docs.python.org/), 26 bytes ``` lambda S:1923136>>len(S)&7 ``` [Try it online!](https://tio.run/##NY5BS8NAEIXv/ophIbKBVGgLioXmEEPQQyiY3NTDtDvSbTazYXer5tfHQfDweLzvu7xpTmfPm6XZvy8Ox6NB6Hbrx812vb0vS0esu/z2Yan3b6r7JkpwYOsZns72NBBDT8HOOFhVqMOX7FePMZH594L7axhohiqQGNkvCZ1Fhqrt/yyjVOXwNEDjA8UEzzgKagnTEZ2DFoNlDKg@bj59AAOWod5NApNWWYRVCVlUmTZ34XKNSY/4I5m0fC/qPM@LRhup5Rc "Python 2 – Try It Online") With a debt of thanks (for my second straight code-golf try) to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)'s answer -- I wouldn't have thought to use the string length instead of a distinguishing letter! This code derives from my experience with [De Bruijn Sequences](https://en.wikipedia.org/wiki/De_Bruijn_sequence "De Bruijn sequences") and programming for chess. In chess, you often work with several 64-bit integers, where each bit indicates something is true or false about the corresponding square on the chessboard, such as "there is a white piece here" or "this square contains a pawn". It is therefore useful to be able to quickly convert `2**n` to `n` quickly and cheaply. In C and C++, the quickest way to do this is to multiply by a 64-bit De Bruijn sequence -- equivalent to shifting by `n` bits -- then right-shift 58 (to put the first six bits last -- make sure you're using an unsigned int or you'll get 1s half the time) and look up this 0..63 number in a table that gives you the corresponding `n` which is in the same range, but rarely the same number. This is kind of related. Instead of changing from `2**n` to `n`, however, we want to change from `n` to some other 3-bit number. So, we hide our 3-bit numbers in a magic 31-bit number (a 28-bit shift requires bits 28-30, with numbering starting at 0.) I generated the number needed by just seeing what values had to fall where (trying both 0..6 and 1..7 as the output sets). Fortunately, the overlapping values (14, 16, and 17) happen to work out! And since the first tri-bit is `000` and the next is `001`, we don't need the leftmost 7 bits, resulting in fewer digits -> fewer bytes of source. The required number is `000xxxx001110101011xxxx100xxxx`, where the x's can be 1 or 0 and it doesn't affect the result for these particular subs -- I set them to 0 just to minimize the number, but changing any of the last 8 xs shouldn't affect the source code's length. Setting all the xs to 0, and leaving off the start, gives 1923136 in decimal (or 1D5840 in hex, but then you need the 0x prefix -- shame!) The &7 at the end just masks the last 3 bits, you could also use %8, but then you'd need parentheses due to python's operator precedence rules. tl;dr: 1923136 encodes each of the three-bit combinations from 0 to 6 in exactly the right spots that these sandwich names happen to fall in place, and then it's a matter of taking the last three bits after a right shift. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) **What's with all this "enklact" business?** ``` ⁽ṃXị“Ð$¥»i ``` A monadic link taking a list of characters and returning the Monday=1 day of the week. **[Try it online!](https://tio.run/##ATsAxP9qZWxsef//4oG94bmDWOG7i@KAnMOQJMKlwrtp////U3dlZXQgT25pb24gQ2hpY2tlbiBUZXJpeWFraQ "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8//9R496HO5sjHu7uftQw5/AElUNLD@3O/P9w95ajew63P2paoxIJJCL//w8uT00tUfDPy8zPU3DOyEzOTs1TCEktyqxMzM7k8i8D8oLyE4tLUlNgslwhpUXZqZUKTkWpQHEuz5LEnMzEPAUn3xCgTF4il1NOYnK2glt@UWpxiYJHYi6Xb2piSVJiTo6Cb2JRZl5iUSIA "Jelly – Try It Online") ### How? ``` ⁽ṃXị“Ð$¥»i - Link: list of characters, sandwichName e.g. "Tuna" ⁽ṃX - base 250 literal -7761 ị - index into sandwichName (1-indexed & modular) 'n' “Ð$¥» - dictionary word "retinal" i - index of 5 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~72~~ ~~71~~ ~~56~~ ~~46~~ ~~41~~ 39 bytes ``` f(char*s){s=index(s="enklact",s[3])-s;} ``` [Try it online!](https://tio.run/##dc8xa8MwEAXg3b/iEBSsEC/NGLI4EJLBBFpvTYeLfHaE5HOR1KQh5K9HFZRu0XbwvvfgVDUoFWNfqhO6mZc3v9Lc0U/pV4LYWFRBzP3H4lNWfnmPI2ouZXErCoAvpzn0pXjpDizm6Xi/EAXYs54Y1ietDDG05PQVjRZSLp919ueE3ib0gbr/Us62387QFWpHiefQLqDVyFA3bX6HMZfV6WMDm8mRD7DFMecawnBEa6HBFKH7G7zHh@otDj5W4@L1Fw "C (gcc) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` O5OHlO7KI6vjYm) ``` [Try it online!](https://tio.run/##y00syfn/39/U3yPH39zb06wsKzJX8///4PLU1BIF/7zM/DwF54zM5OzUPIWQ1KLMysTsTAA) Or [verify all test cases](https://tio.run/##Nck7CgIxFEbhPqu4rQtQ@ygyg4SAprHzd7xgzAvuxJFZfUxjec6XUGO7N7u1Q7T787hb3re0aUfXrl/mSjb7kunw8lPgTI7Frwhe2aXXpWCu/Pyrch8JvJIW7l@NFdEjkzauS4bSEVOgUxGeKw1IyjDqAzGSgfgMwQ8). ### Explanation ``` O5OHlO7KI6 % Push numbers 0, 5, 0, 2, 1, 0, 7, 4, 3, 6 v % Concatenate all numbers into a column vector j % Push input as a string Ym % Mean (of ASCII codes) ) % Index into the column vector (modular, 1-based, with implicit rounding) % Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 4ị“-ƭɼoṚ0»i ``` [Try it online!](https://tio.run/##AToAxf9qZWxsef//NOG7i@KAnC3Grcm8b@G5mjDCu2n///9Td2VldCBPbmlvbiBDaGlja2VuIFRlcml5YWtp "Jelly – Try It Online") Explanation: ``` 4ị“-ƭɼoṚ0»i 4ị 4th element of z “-ƭɼoṚ0»i First index in "enklactate" ``` [Answer] ## [Perl 5](https://www.perl.org/), 24 bytes **23 bytes code + 1 for `-p`.** ``` /[Svrl\s](?!a)/;$_="@+" ``` -4 bytes thanks to [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof)! [Try it online!](https://tio.run/##NcqxCsIwEADQPV9xFgdFpJOTiFJBdCgF201FzvbAkHgJl1jpzxu7OL/nSewqpfxS92Kv4TbbTnCer6f3TbZbZCmVhPGB1kKJohkFVWGxNXBwQiHCEV@q6onh7DBE6mD/1K0hVqeIViNDUTaqeYuhAQqh8aj6QxShYu34v6Eh0QMaPVZG9XU@jhrS0v8A "Perl 5 – Try It Online") [Answer] I thought I would post a couple of other alternatives # Javascript 38 bytes ``` a=s=>(271474896&7<<s.Length)>>s.Length ``` Explanation: Bit-mask rocks? # Javascript 27 bytes ``` s=>"240350671"[s.length%10] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), 12 bytes 0-indexed, takes input in lowercase. ``` `kÇXsm`bUg# ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=YGvHWHNtYGJVZyMa&input=Iml0YWxpYW4gYm10Ig==) --- ## Explanation Implicit input of lowercase string `U` ``` `kÇXsm` ``` The compressed string `kotinsm`. ``` bUg# ``` Get the first index (`b`) of the character at index (`g`) 26 (`#`) in `U`. (Yay, index wrapping!) Implicit output of integer result. --- ## Alternative Same as the above (and everyone else!), just using the characters at index 3 instead, allowing for title case input. ``` `klact`bUg3 ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=YIFrbGFjdGBiVWcz&input=Ikl0YWxpYW4gQk1UIg==) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes Saved 1 byte thanks to Erik the Outgolfer and 1 byte thanks to Magic Octopus Urn. ``` .•ΛΓ2º•I3èk ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f71HDonOzz002OrQLyPI0Prwi@/9/p5zE5GwFt/yi1OISBY/EXAA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), 25 bytes 0-indexed. ``` s=>"enklact".search(s[3]) ``` --- ## Test it ``` o.innerText=(f= s=>"enklact".search(s[3]) )(i.value);oninput=_=>o.innerText=f(i.value) ``` ``` <select id=i><option selected value="Sweet Onion Chicken Teriyaki">Sweet Onion Chicken Teriyaki</option><option value="Oven Roasted Chicken">Oven Roasted Chicken</option><option value="Turkey Breast">Turkey Breast</option><option value="Italian BMT">Italian BMT</option><option value="Tuna">Tuna</option><option value="Black Forest Ham">Black Forest Ham</option><option value="Meatball Marinara">Meatball Marinara</option></select><pre id=o> ``` [Answer] ## [GolfScript](http://www.golfscript.com/golfscript/), 12 bytes ``` {+}*93&(5?7% ``` [Try it online!](https://tio.run/##NcmxCsIwEIDhPU9xiyI6dBARJ6FC0aEUNC9wxlOPxEu5RqWUPnvs4vj/3yOGe@eU25SlGPKwGpe79Xyx2W9nuR2LfPkSJWiEo8Dhyc6TgCXlHj2b5jPVOWKX6PZXY9/qqYdSafrmlDAwCpS1nUTQlAGdhyoqdQmO@DI1YbpiCFCjsqDiDw "GolfScript – Try It Online") Maps the inputs (via the sum of their code points) to `0` to `6`. ### Explanation Found with a GolfScript snippet brute force tool I wrote a while ago... ``` {+}* # Sum all code points. 93& # ... AND 93. ( # Decrement. 5? # ... raised to the fifth power. 7% # ... modulo 7. ``` Here is how this transforms each of the inputs to the desired result: ``` {+}* 93& ( 5? 7% Sweet Onion Chicken Teriyaki 2658 64 63 992436543 0 Oven Roasted Chicken 1887 93 92 6590815232 1 Turkey Breast 1285 5 4 1024 2 Italian BMT 965 69 68 1453933568 3 Tuna 408 24 23 6436343 4 Black Forest Ham 1446 4 3 243 5 Meatball Marinara 1645 77 76 2535525376 6 ``` [Answer] # Excel, 28 bytes Using the `enklact` method: ``` =FIND(MID(A1,4,1),"enklact") ``` [Answer] # [Perl 6](https://perl6.org), 22 bytes ``` tr/enklact/^6/.comb[3] ``` [Try it online!](https://tio.run/##NY2xCsIwFAD3fMUbnARTQejoUEHsUAu2m4i81ieGpEl5iUoQvz1mcby74WZiU6a7Y1gs66M0ypKH1Ra6kM0VlIfRzRE@KXBBVhscQ7GWsizk6KbhvLkkAOkxim/q3kQBWquchd1DjZos9MQqolaifWU6OfSBbv8q@idrilAxZS/qgEahharpc7EoqnzTsHdMPsABJ9EQhgGNgQZZWWT8AQ "Perl 6 – Try It Online (with 24 chars b/c it's an older version)") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` l1b93&(5#7% ``` [Try it online!](https://tio.run/##NcmxCsIwFEbhPU9xQRRxE5HiGkF0CAXN6vA3XjAmvYE0KkV89tjF8ZzPPdDXT43rbrdZLLezZl6v8m1W9fJmLtSKT0L7u3eBhSxnPyJ41b6mOicMhW9/VfaZA4@kM09fnQqih5A2dhKB0hEu0CFlHgod0SvDKB1iJIPsBRk/ "CJam – Try It Online") A port of [my GolfScript answer](https://codegolf.stackexchange.com/a/150073/8478). It costs 1 byte to read the input explicitly, but we save two when summing the code points. [Answer] ## [Husk](https://github.com/barbuz/Husk), 10 bytes ``` %7^5←n93ṁc ``` [Try it online!](https://tio.run/##yygtzv7/X9U8zvRR24Q8S@OHOxuT////H1yemlqi4J@XmZ@n4JyRmZydmqcQklqUWZmYnQkA "Husk – Try It Online") Another port of [my GolfScript answer](https://codegolf.stackexchange.com/a/150073/8478). I'm sure eventually I'll find a language that can sum the code points for a single byte... ## [Husk](https://github.com/barbuz/Husk) (post-challenge update), 9 bytes ``` %7^5←n93Σ ``` [Try it online!](https://tio.run/##yygtzv7/X9U8zvRR24Q8S@Nzi////x9cnppaouCfl5mfp@CckZmcnZqnEJJalFmZmJ0JAA "Husk – Try It Online") Now, `Σ` *does* sum code points directly. Since this was added per a request after I answered this challenge, I'm not going to use it as my primary score though. [Answer] # [Pyth](https://pyth.readthedocs.io), 13 bytes ``` x"enklact"@w3 ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=x%22enklact%22%40w3&test_suite=1&test_suite_input=Sweet+Onion+Chicken+Teriyaki%0AOven+Roasted+Chicken%0ATurkey+Breast%0AItalian+BMT%0ATuna%0ABlack+Forest+Ham%0AMeatball+Marinara&debug=0)** Alternative: ``` x."atÖÅû"@w3 ``` --- `3` can be substituted by any of the following values: `[3, 4, 11, 13, 21, 24, 25, 26]` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 12 bytes ``` 3@"enklact"@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=3%40%22enklact%22%40&input=%22Meatball+Marinara%22&warnings=0&hex=0) [Answer] # [Proton](https://github.com/alexander-liao/proton), 23 bytes ``` s=>'enklact'.find(s[3]) ``` [Try it online!](https://tio.run/##NY4xC8JADIX3/ops14K4uAl1qCA6FEG7iUO0KYY7c@UuKiL@9nql@JbA9wXe64NXL0NXDrFcGRLr8Kpm3rG0eTwtzsWgFDVCCSdzfBEp7IW9wPrGV0sCDQV@o2UzA7N/JnDwGJXa/8PIm0ew9IYqUFIj2Ck6RoGqbiYvON4qdVvY@JAaYYv3kdWEekHnoMbAggHNOcs6H4CX07BPBil9kpp3ORdF9h1@ "Proton – Try It Online") :P [Answer] # [Perl 5](https://www.perl.org/), 43 + 1 (`-p`) = 44 bytes ``` for$i(S,O,TUR,I,TUN,B,M){$"++;$_=$"if/^$i/} ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glUyNYx18nJDRIxxNI@uk46fhqVqsoaWtbq8TbqihlpunHqWTq1/7/75STmJyt4JZflFpcouCRmPsvv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online") Requires the first three characters of input to be upper case. [Answer] # Java 8, 26 bytes ***Credit to @icrieverytim*** Takes input as a char[] ``` s->"enklact".indexOf(s[3]) ``` [Answer] # [Haskell](https://www.haskell.org/), 36 bytes *-9 bytes thanks to H.PWiz.* ``` f s=length$fst$span(/=s!!3)"enklact" ``` [Try it online!](https://tio.run/##NY4xC8IwEEb/yjV0qCA6OHepIDqEgnYTh7NebUh6Lcmp9NfHBnH64L1veD0GS87F2EEoHfFT@rwLkocJudiWIct2K0VsHbai4oCGoYQBJw3F5A0LbKBbwVVdPkQCNZuRYd@b1hJDQ97MaI1ag6rfCziPGIQe/0PizctbmqHytKgEToLOIEOlm59nTFstARYOo6cgcMQhMU0od3QONC4p6FHd4hc "Haskell – Try It Online") ## Alternate solution, 45 bytes This uses the `indexOf` function in `Data.List` as `elemIndex`. ``` import Data.List (`elemIndex`"enklact").(!!3) ``` [Try it online!](https://tio.run/##NY7BaoRAEAXv@Yp2TgrBS857MSFkIbKw8RYCvmjLNjPTytibXb/eKCGnB1XvUBfMnkNYV4nTmIxeYCjfZbaH4ZC3HDgeted761h9QGeuKPMseyrWCFE6UMRUUz4lUaOShoI@3ceN2eikMio9X6TzrNRwkgVe3CO5088GziNm4/7/sPPmmjwvVCXe1A6OhiBQqurmzyv2rbYOT69j4tnoDXFnNcO@EQLV2FKQ4L7WXw "Haskell – Try It Online") [Answer] ## C++, ~~119~~ ~~118~~ ~~77~~ ~~76~~ 73 bytes -41 bytes thanks to Peter Cordes -1 byte thanks to Zacharý -3 bytes thanks to Michael Boger At the string index 3, character for every sandwich is different ``` #include<string> int s(char*p){return std::string("enklact").find(p[3]);} ``` ``` std::initializer_list<char*> t{ "Sweet Onion Chicken Teriyaki", "Oven Roasted Chicken", "Turkey Breast", "Italian BMT", "Tuna", "Black Forest Ham", "Meatball Marinara" }; for (auto& a : t) { std::cout << s(a); } ``` Golfing with `std::string`, that was obvious ofc... what was i thinking... [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 289 bytes ``` using System;class c{delegate int s(string r);static void Main(){s y=x=>{if(x[0]==83)return 1;if(x[0]==79)return 2;if (x[0]==84&x[2]=='r')return 3;if(x[0]==73)return 4;if(x[0]==84)return 5;if(x[0] ==66)return 6;if(x[0]==77)return 7;return 0;};Console.Write(y.Invoke(Console.ReadLine()));}} ``` [Run online](https://tio.run/##TczNqsIwEAXgV5mVJosr/tS2EuLGlaAbFVzIXYR0lGBNJJNKS@mzVy8Yr7vDN@eMph/tPPZ9RcZeYN9QwJvQpSIC3RZY4kUFBGMDEKPg/0qeCwoqGA0PZwrYKmMZbwkaWctla86sPo1/pcxn3GOovIWJ@GC2iDh9IcRqMqhP01cY@mG8z75Gn0/JP@ZJxHlEkDJNo6Zf@yxiJt5hLDqxcpZciaOjNwFZM1rbh7sii7xDVWyMRcY5F13X94fqXuIT "C# (.NET Core) – Try It Online") [Answer] # Golfscript, 13 bytes [Try it online!](http://golfscript.apphb.com/?c=OyJCbGFjayBGb3Jlc3QgSGFtIgonZW5rbGFjdCdcMz0%2F) ``` 'enklact'\3=? ``` Takes the 4th character (which, for each, will be unique) and looks it up in the string "`enklact`". Alternatively: ``` 'nklact'\3=?) ``` This takes advantage of the fact that Golfscript's `?` function returns -1 if the element searched for is not found (which, for Monday, it will not). If this were allowed, the solution could be reduced by 1 byte. [Answer] # Dyalog APL, 13 bytes ``` 'enklact'⍳4⌷⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE9RT87JzEpNL1B/1bjZ51LP9Ue@8//@Dy1NTSxT88zLz8xScMzKTs1PzFEJSizIrE7MzAQ) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 13 bytes **Solution:** ``` "enklact"?*3_ ``` [Try it online!](https://tio.run/##y9bNz/7/Xyk1LzsnMblEyV7LOF7JCcjMVnDLL0otLlHwSMxV@v8fAA "K (oK) – Try It Online") **Examples:** ``` > "enklact"?*3_"Black Forest Ham" 5 > "enklact"?*3_"Turkey Breast" 2 ``` **Explanation:** Interpretted right-to-left, pull out the 4th element from the input and return the zero-index location in the "enklact" list: ``` "enklact"?*3_ / the solution 3_ / 3 drop, 3_"Turkey Breast" => "key Breast" * / first, *"key Breast" => "k" ? / lookup right in left "enklact" / list to lookup element in ``` ]
[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/20823/edit). Closed 1 year ago. [Improve this question](/posts/20823/edit) # Context > > It's Valentines Day. The only one you ever loved left you yesterday > for this guy she always found *"stupid and uninteresting"*. On your > way home, you've been stuck in traffic, listening to old songs on the > radio, the rain hitting the windscreen is rocking you. After a while > in your car, you find yourself alone in your small apartment being > unable to think of something else but her. There is no light and you > stare trough the window, letting darkness surrounds you. There is no > one to talk to, your friends are now gone a long time ago after > warning you about this new girl haunting your mind. You start up your > computer, as it's the only thing you can do, open your browser and > post a new programming puzzle to stackexchange, in an attempt to change your mind. > > > # Challenge Write a program in the language of your choice simulating the rain which falls on the ground. The output can be composed of ASCII characters or 2D/3D rendered. The camera is fixed : you are above looking straight to the ground. Your program must includes some kind of animation like refreshing the console or the page each time you generate a new "frame". It has to be realistic, I know it's a bit subjective but let's say you can't just fill all the ground in only one big drop. The output don't have to be an image but if you're using cryptic language it's better to provide a .gif to illustrate how it looks in action (but of course, it will not affect your score if you don't). # Rules * Your score is the total of bytes used * -20 points if you use colours * -50 if you achieve to render some kind of wind * Lowest score wins # Example A very basic example of what should be rendered: ![](https://i.stack.imgur.com/0bDJM.gif) I hope you'll do better and enjoy this challenge. *Sorry for my english, feel free to edit my post if you want to correct some errors* # Leader board If your name is not listed it's because your attempt has been considered not fitting the rules. ``` Tobia - APL - 35 j6m8 - Processing.js - 38 The Guy with The Hat - Processing - 42 ace - Processing - 74 kelunik - JS/CSS - 89 Riot - Bash - 91 Michael - JS/jQuery - 105 Florent - HTML/JS - 123 David Carraher - Mathematica - 134 Doorknob - HTML/JS - 150 undergroundmonorail - Python - 175 ``` Congratulations to Tobia ! [Answer] # Bash: 111 bytes - 20 = 91 points! A contemplative gentle drizzle in your terminal. Adjust the numbers 819 and 41 for different height and width respectively. ``` e='printf \e';while :;do for i in {0..819};do((RANDOM<9))&&$e[1\;36m.||$e[1C;((i%41<1))&&$e' ';done;$e[20A;done ``` ![Screenshot](https://i.stack.imgur.com/oDB0g.gif) A pleasant bonus is the way the cursor pitter-patters across the rain area. Edit: shortening from 140 bytes to 129 bytes thanks to @manatwork's suggestions. 2nd edit: shortening from 129 bytes to 111 bytes thanks to @manatwork's and @Tobia's suggestions, plus additional inspiration - see comments. (Note: screenshot shows previous less-golfed version of the code, which is functionally identical) [Answer] ## Python, 312 bytes - 50 (wind) = 262 ``` from pygame import* R=__import__('random').randint t,u=640,480;init();d=display;s=d.set_mode((t,u)) w=[255]*3;r=range(t) a=[[R(0,t),R(0,u),R(3,6)]for i in r] while time.wait(9): d.flip();event.get();s.fill(R(0,99)<1and w) for i in r:x,y,z=a[i];draw.line(s,w,(x,y),(x+z,y+2*z));a[i][0]=(x+z)%t;a[i][1]=(y+z*2)%u ``` Sample output (a 50-frame loop): ![](https://i.stack.imgur.com/k7Ge3.gif) Actual playpack is significantly faster than gifs allow. [Answer] # HTML / JS, 170 chars - 20 = 150 points ``` <canvas id=c></canvas><script>d=400;with(c)width=height=d,t=getContext('2d');t.fillStyle='blue';setInterval("t.fillRect(Math.random()*d,Math.random()*d,5,5)",50)</script> ``` (sidenote: golfed further by passing a string to `setInterval`, `with`, automatic ID variable names... it feels so wrong! *shudders*) It just draws random blue rectangles. # HTML / JS, 309 chars - 20 - 50 = 239 points Now with wind! ``` <canvas id=c></canvas><script>s=400;r=Math.random;with(c)width=height=s,t=getContext('2d');t.fillStyle='blue';o=[];setInterval("t.clearRect(0,0,s,s);for(i=0;++i<o.length;)d=o[i],t.fillRect(d[0],d[1],d[2],d[2]),d[0]+=1,d[1]+=2,d[2]-=1,d[2]<0?o.splice(i,1):0;if(r()<.6)o.push([r()*400,r()*400,20])",50)</script> ``` [Answer] ## JS + jQuery (172-20-50 = 102) Copy/Paste that line in the browser console (generally press F12 key) : ``` r=Math.random;w=$(window);setInterval("$('<b>♥</b>').css({color:'red',position:'fixed',top:r()*w.height(),left:r()*w.width()}).appendTo('body').animate({fontSize:0},3e3)",9) ``` Animated red hearts rain for Valentine's day ! ![enter image description here](https://i.stack.imgur.com/E5FEY.jpg) [Answer] # APL, 105 chars/bytes\* – 20 – 50 = 35 score ``` e←{⍞←∊'␛['⍵} e¨'36m' '?25l' '2J' {⍵←3⌊⍵+3×0=?t⍴50 ⍵{(⍵c)←⍕¨⍵+1 e⍵';'c'H',' .∘⍟'[⍺]}¨⍳t ∇0⌈⍵-1}0⍴⍨t←24 80 ``` \*: Most APL implementations support some form of (legacy) single-byte charset, that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of golfing, a program **that only uses ASCII characters and APL symbols** can be scored as chars = bytes. I tested it on [Nick's latest apl.js](https://github.com/ngn/apl) on Node.js in an OS X terminal. But I haven't used anything specific to his dialect, so it should work on any modern APL that can be run on an ANSI terminal and supports d-funs `{...}`, strand assignment `(a b)←...`, and commute `⍨`, such as Dyalog for Linux or for Raspberry PI (with `⎕IO←0`) The `␛` in line 1 is a literal escape character (which is 1 byte). You can input it using `Ctrl-V` `Esc` in a Linux terminal or in Vim, or supposedly something like `Alt-027` in Windows. Also, I couldn't find a reliable way to discover the terminal size, so you might want to edit the number of rows and columns at the end of the last line. I defend the 50 bonus by the fact that each raindrop goes through the following shapes: `⍟∘.` which give the impression of a slight downwards wind, given that the scene is being looked at from above. In fact, looking at the gif below, you should get the impression that each drop is gently moving downwards and to the left, before disappearing on the ground. **Ungolfed version:** ``` e←{⍞←∊"␛["⍵} # utility to print escape sequence e¨'36m' '?25l' '2J' # set cyan, hide the cursor and clear screen { # repeat (⍵=current board of raindrops) ⍵←3⌊⍵+3×0=?t⍴50 # add some new drops (=3) in random places ⍵{ # print the drops (⍺=drop value, ⍵=coords) (r c)←⍕¨⍵+1 # convert the coordinates to string e r';'c'H',' .∘⍟'[⍺] # print or clear the drop }¨⍳t # .. ∇0⌈⍵-1 # remove 1 from every drop and repeat }0⍴⍨t←24 80 # ..starting with an empty board ``` **Output:** ![enter image description here](https://i.stack.imgur.com/kVPc2.gif) --- # APL, different style Out of competition. ``` m←×/t←1+(ζη)←2×(βγ)←24 80 e←{⍞←∊(⎕UCS 27)'['⍵} s←{⍵[β-1-⍳β;1+⍳γ]} p←{⍺{e'H'⍺,⍨{⍺,';',⍵}/⍕¨⍵}¨(,s⍵)/,1+⍳βγ} e¨'2J' '36m' '?25l' {'/'p⍵←(200<m÷?t⍴m)∨0⍪⍵[⍳ζ;1+⍳η],0 ' 'p(~⍵)∧0,⍵[1+⍳ζ;⍳η]⍪0 '.∘°'[?(+/,sδ)/3]pδ←⍵∧~d←.2<m÷⍨?t⍴m ∇⍵∧d}t⍴0 ``` Here my aim was to give the impression of raindrops falling with a slant and accumulating on the ground, while trying to keep the number of visible drops (either falling or splattered) constant on average. The trick was to create a number of new falling drops `/` at every cycle and having the falling drops "wipe out" any splattered ones they travel across. The result is strangely reminiscent of the Matrix code. **Output** (the jerk every 5s is the gif looping) ![enter image description here](https://i.stack.imgur.com/L6lbE.gif) [Answer] # Mathematica 134 - 20 = 114 ## 2D ``` n = 99; m = Array[0 &, {n, n}]; r := RandomInteger[{1, n}, {2}] Table[ArrayPlot[m = ReplacePart[m, r -> 1], ColorRules -> {1 -> Blue}], {k, 250}]; Export["d.gif", d] ``` ![2D](https://i.stack.imgur.com/AjJAz.gif) --- ## 3D The raindrop shape is made via a revolution plot around the z axis. Initially, rain is generated for a region that extends well above the display region. The appearance of falling rain is achieved by shifting the Viewpoint upwards along the z-axis. (It is more efficient than recalculating the position of each raindrop.) ![rain](https://i.stack.imgur.com/eQh6Z.gif) ``` r = RandomInteger; z = Table[{r@30, r@30, r@160}, {100}]; w = RevolutionPlot3D[{.7 Sin[x] Cos[x], 0, 1.4 Sin[x] }, {x, 0, -Pi/2}, PerformanceGoal -> "Speed"][[1]]; c = Map[Translate[w, #] &, z]; p = Table[Graphics3D[c, PlotRange -> {k, k + 50}], {k, 1, 100}] Export["p.gif", p] ``` --- [Answer] # HTML / JavaScript, 156 123 (143 - 20) ``` <body bgcolor=0 onload="t=c.getContext('2d');t.fillStyle='#07d';setInterval('n=Math.random()*4e4;t.fillRect(n%270,n/150,1,1)',1)"><canvas id=c> ``` Annotated version: ``` <body bgcolor="#000"> <canvas id="c"></canvas> <script> onload = function() { // Retrieve the rendering context t=c.getContext('2d'); // Set rain color t.fillStyle='#07d'; // Render whenever it is possible setInterval(function() { // Generate a number between 0 and 40,000 // 40,000 ~= 270 * 150 n=Math.random()*4e4; // Draw a raindrop. // Since x and y are not rounded, the raindrop looks blurry! t.fillRect(n%270,n/150,1,1) }, 1); }; </script> </body> ``` [Answer] # Smalltalk (Smalltalk/X) with random wind ;-) ``` |BG CLR N1 H W v WIND drops gen newDrops draw remove move buffer| BG := Color black. CLR := Color blue lightened. H := 100. W := 100. N1 := 10. WIND := 0. drops := OrderedCollection new. gen := [:n | ((1 to:n) collect:[:i | Random nextIntegerBetween:1 and:W] as:Set) collect:[:x | x@0]]. newDrops := [drops addAll:(gen value:N1)]. draw := [buffer fill:BG; paint:CLR. drops do:[:d | buffer displayPoint:d]]. remove := [drops := drops reject:[:d | d y > H]]. move := [:wind | drops := drops collect:[:d| (d x + wind)\\W @ (d y + 1)]]. v := View new openAndWait. buffer := Form extent:(v extent) depth:24 onDevice:v device. [ [v shown] whileTrue:[ draw value. v displayForm:buffer. move value:WIND. remove value. newDrops value. WIND := (WIND+(Random nextBetween:-1 and:1)) clampBetween:-5 and:5. Delay waitForSeconds:0.1. ] ] fork. ``` output in view: ![enter image description here](https://i.stack.imgur.com/fRThd.gif) [Answer] ## Processing, 94 - 20 = 74 ``` void setup(){background(0);fill(0,0,255);} void draw(){ellipse(random(0,99),random(0,99),3,3);} ``` (New line added for readability.) Click [here](http://adrianiainlam.github.io/rain/) for an online demo. [Answer] # Bash ``` while true;do echo " / / / / /";echo "/ / / / / ";done ``` I'm not sure this should be a code golf because there isn't a strict requirement on what the "rain" must look like. EDIT: If you want it to look like the camera is pointing straight down use this: ``` while true;do echo " . . . . .";echo ". . . . . ";done ``` [Answer] ## Python 2.7: 195 - 20 = 175 I'm sure there's more that can be done here, but this is what I've got for now: ``` import os,time from random import* l=[i[:]for i in[[' ']*100]*50] while 1: os.system('clear') l[randint(0,49)][randint(0,99)]='.' print'\033[94m\n'.join(''.join(r)for r in l) time.sleep(.05) ``` I'll post a gif of the output when I remember how to do that. This works on linux. Replacing `'clear'` with `'cls'` makes it work on windows, but then ANSI colours don't work and I lose the bonus. I have a 2D array of one-character strings, initialized to . Every 0.05 seconds, one of them is chosen at random set to `.`, and the screen is redrawn. `from random import*` saves two characters over `import os,time,random` and using `random.randint()` twice, though I'm not convinced that's the best way to choose a cell anyway. I wanted to use `random.choice()` but I couldn't think of a way around immutable strings that wouldn't waste more characters than it saved. [Answer] # 132 + 27 - 20 - 50 = 89 # Javascript (132) ``` r=Math.random;setInterval("$('body').append($('<i>∘</i>').css({left:r()*2e3,top:r()*2e3}).animate({left:'+=70',fontSize:0},500))",1) ``` # CSS (27) ``` i{color:blue;position:fixed ``` Demo: <http://jsfiddle.net/kelunik/5WC87/4/embedded/result/> [Answer] # Processing, 62 - 20 = 42 ``` void draw(){stroke(0,0,214);point(random(0,99),random(0,99));} ``` Generates blue pixels on a white background. Demonstration in a very similar language here: <https://www.khanacademy.org/cs/rain2/6172053633761280> [Answer] # Processing.js, 86 - 20 = 66 ...but it also slowly fades out (the ground absorbs the rain, naturally). Points for that? ``` g=99;r=random;void draw(){fill(0,9);rect(0,0,g,g);fill(0,g,r(g));rect(r(g),r(g),2,2);} ``` Bonus features include varying between greenish and blueish (it's clearly dirty 'city' rain). Also, I was very pleased that I got to use a JavaScript hack in here; Note that, because this is processing.*js*, you can throw in things like the typeless declaration of g=99, or the alias of `r` for `random` (cross-language alias!). Any other ideas to minify? ## Readable version: ``` g = 99; r = random; // Javascript trickery void draw() { fill(0, 9); rect(0, 0, g, g); // Fade the background fill(0, r(g), r); rect(r(g), r(g), 2, 2); // Add a new drop } ``` The whole thing can be viewed [here](http://jordan.matelsky.com/sketch/golf/rain/). ## ...plus another version without fade: 58 - 20 = 38 If you don't like fading and don't mind grey dirt: ``` r=random;void draw(){fill(0,0,255);rect(r(99),r(99),2,2);} ``` [Answer] # Tcl/Tk, 139 - 20 = 119 Reusing my own answer <http://codegolf.stackexchange.com/a/143018/29325> ***Must be run in the interactive shell*** ``` gri [can .c -w 40 -he 40] set x 0 wh 1 {.c cr o $x [set y [exp int(rand()*40)]] $x [set x $y] -f #[form %06x [exp int(rand()*255**3)]] upd} ``` Unfortunately, converting `expr int(rand()*` into a `proc` makes the script have one byte more! [![enter image description here](https://i.stack.imgur.com/MFbaE.png)](https://i.stack.imgur.com/MFbaE.png) To stop, one just needs to click the ineffable "X" button. ]
[Question] [ Nice verb there, in the title. Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows: The first character is shown once. The second character is shown twice. The third character is shown thrice, and so on. As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string. You can expect to receive only printable ASCII characters. Based off the following [link](http://web.cs.mun.ca/~michael/c/ascii-table.html), these characters have decimal values 32-126. Examples: `Why: Whhyyy` `SKype: SKKyyyppppeeeee` `LobbY: LoobbbbbbbYYYYY` (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's). `A and B: A aaannnnddddd BBBBBBB` Shortest bytes wins :) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes Code: ``` ĖP€ ``` Explanation: ``` Ė # Enumerate. P€ # Product of each. # Implicit joining of everything. ``` Uses the **Jelly encoding**. [Try it online!](http://jelly.tryitonline.net/#code=xJZQ4oKs&input=&args=TG9iYlk). [Answer] # J, 4 bytes ``` #~#\ ``` ## Usage ``` f =: #~#\ f 'Why' Whhyyy f 'SKype' SKKyyyppppeeeee f 'LobbY' LoobbbbbbbYYYYY f 'A and B' A aaannnnddddd BBBBBBB ``` ## Explanation ``` #~#\ Input: s #\ Computes the length of each prefix of s This forms the range [1, 2, ..., len(s)] #~ For each value in the range, copy the character at the corresponding index that many times Return the created string ``` [Answer] ## Brainfuck, 15 bytes ``` ,[>+[->+<<.>],] ``` Pretty straightforward implementation, shifting the memory space by 1 for each input char. Requires an interpreter that gives 0 on EOF, and 32-bit/arbitrary precision cells for inputs longer than 255 chars. [Try it online!](http://brainfuck.tryitonline.net/#code=LFs-K1stPis8PC4-XSxd&input=QSBhbmQgQg) (Note: TIO uses 8-bit cells) [Answer] ## Haskell, 29 bytes ``` concat.zipWith replicate[1..] ``` Usage example: `concat.zipWith replicate[1..] $ "SKype"` -> `"SKKyyyppppeeeee"`. `replicate n c` makes n copies of c and `concat` makes a single list out of all the sublists. [Answer] # Java, 158 121 bytes Saved a whopping 37 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` interface a{static void main(String[]A){int b=0,B;for(char c:A[0].toCharArray())for(B=b+++2;--B>0;)System.out.print(c);}} ``` As a bonus, this program can handle *all* Unicode characters in the existence, including [the control characters located at the very end of Basic Multilingual Plane](https://en.wikipedia.org/wiki/Specials_(Unicode_block)). [Answer] ## Perl, 16 bytes ``` s/./$&x$+[0]/ge ``` +1 byte for the `-p` flag. ``` s/./ / find every character g globally e and replace with the eval'd result of $& the matched string x repeated $+[0] by the index of the character after the match ``` [Answer] # Python, 39 bytes ``` f=lambda s:s and f(s[:-1])+s[-1]*len(s) ``` Test it on [Ideone](http://ideone.com/ZrxEbz). [Answer] ## CJam, ~~9~~ ~~8~~ 7 bytes *Thanks to jimmy23013 for saving 1 byte.* ``` Sl+eee~ ``` [Test it here.](http://cjam.aditsu.net/#code=Sl%2Beee~&input=LobbY) ### Explanation Using the `LobbY` example: ``` Stack: S e# Push space. [" "] l e# Read input. [" " "LobbY"] + e# Append. [" LobbY"] ee e# Enumerate. [[[0 ' ] [1 'L] [2 'o] [3 'b] [4 'b] [5 'Y]]] e~ e# Run-length decode. ["LoobbbbbbbYYYYY"] ``` [Answer] # MATLAB, 45 bytes ``` g=@(m)sort(m(m>0));@(s)s(g(hankel(1:nnz(s)))) ``` Explanation: The key is `hankel`, which produces a Hankel matrix of a given vector. From this matrix, we can extract a vector of indices, which defines which character of the string is at which position in the output. E.g. `hankel(1:4)` produces following matrix: ``` 1 2 3 4 2 3 4 0 3 4 0 0 4 0 0 0 ``` From this matrix we can extrac the vector `1,2,2,3,3,3,4,4,4,4,4`. This vector allows us to output the first character of the string *once*, the second one *twice* e.t.c. [Answer] # Javascript ES6, 39 bytes ``` x=>x.replace(/./g,(y,i)=>y+y.repeat(i)) ``` **Same length, but more fun:** ``` x=>x.replace(i=/./g,y=>y.repeat(i=-~i)) ``` **Snippet demo:** ``` f= x=>x.replace(/./g,(y,i)=>y+y.repeat(i)) run.onclick=_=>output.textContent=f(input.value) ``` ``` <input id="input" value="SKype"> <button id="run">Go</button> <pre id="output"></pre> ``` [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~6~~ 5 bytes ``` ⍳∘≢⌿⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R72bH3XMeNS56FHP/kddi/5rcj3qmwqUSVNQz0jNyclX/w8A "APL (dzaima/APL) – Try It Online") `⍳∘≢` enumeration of the argument... (indices of its length) `⌿` replicates the elements of... `⊢` the unmodified argument [Answer] # APL (8) ``` {⍵/⍨⍳⍴⍵} ``` I.e.: ``` {⍵/⍨⍳⍴⍵} ¨ 'Why' 'SKype' 'LobbY' ┌──────┬───────────────┬───────────────┐ │Whhyyy│SKKyyyppppeeeee│LoobbbbbbbYYYYY│ └──────┴───────────────┴───────────────┘ ``` Explanation: * `⍴⍵`: length of given vector * `⍳`: numbers 1..N * `⍵/⍨`: replicate each element in `⍵` N times. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` :ImC,0:Ie,Cw\ ``` This prints the result to `STDOUT`. ### Explanation This is a good example of exploiting backtracking to loop. ``` :ImC C is the Ith character of the Input , 0:Ie Unify an implicit variable with an integer between 0 and I , Cw Write C to STDOUT \ False, trigger backtracking. It will go back to 0:Ie and unify the implicit variable with another integer, until all integers were used. After that, it will backtrack to :ImC and unify I and C with the next character. ``` [Answer] # Javascript ES6, ~~42~~ 41 bytes ``` s=>[,...s].map((e,i)=>e.repeat(i)).join`` ``` Example runs: ``` f=s=>[,...s].map((e,i)=>e.repeat(i)).join`` f("Why") => "Whhyyy" f("SKype") => "SKKyyyppppeeeee" f("LobbY") => "LoobbbbbbbYYYYY" ``` [Answer] # [R](https://www.r-project.org/), ~~83~~ 50 bytes -23 Thanks to Giuseppe, though he used essentially an entire new method altogether ``` function(s)intToUtf8(rep(utf8ToInt(s),1:nchar(s))) ``` My original post: ``` function(s){r="";for(i in 1:nchar(s))r=paste0(r,strrep(el(strsplit(s,""))[i],i));r} ``` [Try it online!](https://tio.run/##DckxCoAwDAXQq5RMCXTQVelJxEGkxYC05adO4tlrtwcPvacnn01LZpMXgWhNBaxOs5uXfF4HRghCPazFieGtAbFyvHnI6q2NzROJbLp7FVnx9f4D "R – Try It Online") I feel like there's definitely a better way to do this, but with my new knowledge of a few functions in R, this is my approach. [Answer] ## PowerShell v2+, 36 bytes ``` -join([char[]]$args[0]|%{"$_"*++$i}) ``` Takes input `$args[0]`, explicitly casts it as a `char` array, sends that into a loop `|%{...}`. Each iteration we take the current letter/character `"$_"` and use the `*` overloaded operator to concatenate the string pre-incremented `$i` times. The result of each loop iteration is encapsulated in parens to form an array and then `-join`ed together to form a string. That string is left on the pipeline and output is implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 Why Whhyyy PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 SKype SKKyyyppppeeeee PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 LobbY LoobbbbbbbYYYYY PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 'a b' a bbb ``` [Answer] # MATLAB, 23 bytes ``` @(x)repelem(x,1:nnz(x)) ``` Creates an anonymous function `ans` that can be called using `ans('stringtoelacticize')` [Answer] ## [K](https://en.wikipedia.org/wiki/K_(programming_language))/[Kona](https://github.com/kevinlawler/kona), 14 bytes ``` {,/(1+!#x)#'x} ``` Usage: ``` k){,/(1+!#x)#'x}"A and B" "A aaannnnddddd BBBBBBB" ``` [Answer] # [Perl 6](http://perl6.org), ~~22 20~~ 19 bytes ``` ~~{S:g/(.)/{$0 x$/.to}/} {S:g[(.)]=$0 x$/.to}~~ {[~] .comb Zx 1..*} ``` ### Explanation: ``` { # implicit parameter $_ [~] # string concatenate the following list .comb # the NFG characters from $_ Z[x] # zip combined using the string repetition operator 1 .. * # 1 to infinity } ``` [Answer] # VBA, 75 bytes ``` Function e(s):For a=1 To Len(s):e=e &String(a,Mid(s,a,1)):Next:End Function ``` Call as e.g. a user function in a spreadsheet. =e(A1) ``` ┌─────────┬───────────────┐ │ SKype │SKKyyyppppeeeee│ └─────────┴───────────────┘ ``` It truncates if you feed it its own output a few times :-). [Answer] # Julia, 32 bytes ``` !s=join(split(s[k=1:end],"").^k) ``` Unlike Dennis's solution, this is not recursive. `split` with argument `""` separates the string into an array of strings of length 1. The `[k=1:end]` is a trick to create a range from 1 to the number of characters in the string, and this range is used to concatenate n copies of the n-th character. `join` then recombines the array of strings into a single string, in order. Usage example: `!"SKype"` [Answer] # PHP, 68 bytes ``` <?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1); ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 22 bytes Byte count assumes ISO 8859-1 encoding. ``` . $&$.`$*· +`(.)· $1$1 ``` [Try it online!](http://retina.tryitonline.net/#code=LgokJiQuYCQqwrcKK2AoLinCtwokMSQx&input=TG9iYlk&debug=on) Basically, we insert the right amount of `·` as placeholders between the characters (since these extended ASCII characters can't appear in the input), then fill them up with the adjacent character in the second stage. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ƶJ ``` [Try it online](https://tio.run/##yy9OTMpM/f//2Dav//998pOSKgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/2PbvP7r/A/PqOQK9q4sSOXyyU9KiuRyVEjMS1FwAgA). **Explanation:** ``` ƶ # Multiply each character in the (implicit) input-string by its 1-based index J # Join the list of substrings together to a single string # (after which the result is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 2 bytes ``` Þż ``` [Try it online](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiw57FvCIsIiIsIldoeSJd), or see a [3 byte flagless version](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnsW84oiRIiwiIiwiV2h5Il0=) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~9~~ 8 bytes ``` ⊢/˜1+↕∘≠ ``` Anonymous tacit function. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqiL8ucMSvihpXiiJjiiaAKCkbCqCAiV2h5IuKAvyJTS3lwZSLigL8iTG9iYlki4oC/IkEgYW5kIEIi) ### Explanation ``` ⊢/˜1+↕∘≠ ≠ Length of argument ↕∘ Range 1+ Add 1 to each, making it an inclusive range from 1 to the length /˜ Replicate that many times the elements of ⊢ The original input ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 33 bytes ``` 1:i:0(?^$:?v~~1+00. .!02o:$;!-1<| ``` [Try the animated version](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMTppOjAoP14kOj92fn4xKzAwLlxuLiEwMm86JDshLTE8fCIsImlucHV0IjoiYWJjIiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9) [![enter image description here](https://i.stack.imgur.com/jyccH.png)](https://i.stack.imgur.com/jyccH.png) Basically if the counter is 0 skip to the second `:`, otherwise the first `:`. Properly adjust the counters. [Answer] ## Actually, 7 bytes ``` ' +ñ♂πΣ ``` [Try it online!](http://actually.tryitonline.net/#code=JyArw7HimYLPgM6j&input=IldoeSI) Explanation: ``` ' +ñ♂πΣ ' + prepend a space ñ enumerate ("abc" -> [[0, 'a'], [1, 'b'], [2, 'c']]) ♂π map: for each character, repeat it n times Σ concatenate ``` [Answer] # Pyth - 5 bytes *1 byte saved thanks to @FryAmTheEggman.* ``` s*VSl ``` [Test Suite](http://pyth.herokuapp.com/?code=s%2aVSl&test_suite=1&test_suite_input=%22Why%22%0A%22SKype%22%0A%22LobbY%22&debug=0). [Answer] # Python 3, ~~48~~ 47 bytes *Thanks to [mego](https://codegolf.stackexchange.com/users/45941/mego) for saving a byte with the `-~i` trick.* ``` lambda s:''.join(c*-~i for i,c in enumerate(s)) ``` This is mostly self-explanatory. One thing for those not versed in Python: The `*` operator is overloaded to act like Perl's `x` operator, repeating its string argument the number of times specified by its numeric argument. E.g. `'foo' * 3 == 'foofoofoo'` ]
[Question] [ An Indian legend tells the story of the alleged inventor of the chess game, who impressed the emperor of India with his game so much that he would get rewarded with anything asked. The man said he wanted to be paid in rice. He wanted a grain of rice for the first square of the chessboard, two for the second, four for the third, eight for the fourth, and so on, until the 64th square. The emperor was amazed that the man asked for such a small reward, but as his mathematicians started counting, he ended up losing one of his provinces. # Task Given the length of the side of a hypothetical chessboard (which is 8 on a default chessboard) and the multiplier between squares (which is 2 in the legend), calculate the number of grains of rice the emperor must pay to the man. # Notes * The side length will always be a positive integer. The multiplier could instead be any kind of rational number. * If your language of choice can't display very large numbers, it's okay as long as your program can correctly process smaller inputs. * Also if your language of choice rounds larger values (with exponential notations), it's okay if those values are approximately correct. # Testcases ``` Input (side length, multiplier) => Output 8, 2 => 18446744073709551615 3, 6 => 2015539 7, 1.5 => 850161998.2854 5, -3 => 211822152361 256, 1 => 65536 2, 2 => 15 2, -2 => -5 ``` Please note that the explicit formula ``` result = (multiplier ^ (side ^ 2) - 1) / (multiplier - 1) ``` Performs wrong on `multiplier = 1`, as ``` 1 ^ (side ^ 2) - 1 = 0 1 - 1 = 0 0 / 0 != side ^ 2 (as it should be) ``` # Scoring This is code-golf. Shortest answer in bytes wins. [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` 2^:q^s ``` [**Try it online!**](http://matl.tryitonline.net/#code=Ml46cV5z&input=NwoxLjU) ``` 2^ % Take implicit input, say N, and square it: N^2 :q % Generate array [0 1 ... N^2-1] ^ % Take implicit input, M, and compute [M^0 M^1 ... M^(N^2-1)] s % Sum of the array. Implicit display ``` [Answer] # APL, 10 bytes ``` ⎕⊥1+0×⍳⎕*2 ``` `⎕` is used to read user input twice. If we store the side length in **s** and the multiplier in **m**, we get the following code. ``` m⊥1+0×⍳s*2 ``` And here's how APL parses this code: [![Explanation of algorithm](https://i.stack.imgur.com/pk1ni.png)](https://i.stack.imgur.com/pk1ni.png) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ²b1ḅ ``` This uses the approach from [@APLDude's clever APL answer](https://codegolf.stackexchange.com/a/79335). [Try it online!](http://jelly.tryitonline.net/#code=wrJiMeG4hQ&input=&args=OA+Mg) or [verify all test cases](http://jelly.tryitonline.net/#code=wrJiMeG4hQrDpyJH&input=&args=OCwgMywgICA3LCAgNSwgMjU2LCAyLCAgMg+MiwgNiwgMS41LCAtMywgICAxLCAyLCAtMg). ### How it works ``` ²b1ḅ Main link. Arguments: x (side length), y (multiplier) ² Square; yield x². b1 Convert to base 1 (unary), yielding a list of x² ones. ḅ Convert from base y to real number. This yields y^(x²-1) + ... + y + 1. ``` [Answer] ## Python, 40 bytes ``` lambda n,m:eval('1+m*('*n*n+'0'+')'*n*n) ``` Generates and evaluates a string like ``` 1+m*(1+m*(1+m*(1+m*(0)))) ``` that encodes the sum as a [Hornerized polynomial](https://en.wikipedia.org/wiki/Horner%27s_method) with `n*n` terms. A lot of different methods gave very similar byte counts: ``` #String evaluation lambda n,m:eval('1+m*('*n*n+'0'+')'*n*n) #40 #Direct summation lambda n,m:sum(m**i for i in range(n*n)) #40 lambda n,m:sum(map(m.__pow__,range(n*n))) #41 #Direct formula lambda n,m:n*n*(1==m)or(m**n**2-1)/(m-1) #40 #Iterative sequence f=lambda n,m,j=0:j<n*n and 1+m*f(n,m,j+1) #41 def f(n,m):s=0;exec"s=s*m+1;"*n*n;print s #41 #Recursive expression #Fails due to float imprecision of square root f=lambda n,m:n and 1+m*f((n*n-1)**.5,m) #39* ``` [Answer] # Pyth, 6 bytes 1 byte saved thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman). ``` s^Lvz* ``` [Try it online!](http://pyth.herokuapp.com/?code=s%5ELvz*&input=8%0A2&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=s%5ELvz*&test_suite=1&test_suite_input=8%0A2%0A3%0A6%0A7%0A1.5%0A5%0A-3&debug=0&input_size=2) [Answer] ## Haskell, 25 bytes ``` n%m=sum$(m^)<$>[0..n*n-1] ``` Sums the list `[m^0, m^1, ..., m^(n*n-1)]`. [Answer] # JavaScript (ES2016/ES7), ~~31~~ ~~29~~ 28 bytes ``` a=>b=>(b**(a*a)-1)/--b||a*a ``` Just @Bassdrop Cumberwubwubwub and @Kaizo's ES6 version, but with exponentiation operator. :) (I didn't have enough reputation to comment instead.) Edit: `/+(b-1)` changed to `/--b` (thanks @Neil). Edit: now uses currying (thanks @MamaFunRoll). [Answer] # Jelly, 6 bytes ``` ²R’*@S ``` [Try it online!](http://jelly.tryitonline.net/#code=wrJS4oCZKkBT&input=&args=OA+Mg) [Answer] # MATLAB, 23 bytes ``` @(n,k)sum(k.^(0:n^2-1)) ``` Test it [here](https://ideone.com/pu3jdZ)! [Answer] # Javascript ES6, ~~59~~ ~~37~~ ~~35~~ 34 bytes ``` a=>b=>(Math.pow(b,a*a)-1)/--b||a*a` ``` Thanks to @Kaizo for shaving off a whopping 19 bytes, @Neil for another 2 and @gcampbell for 1 more! Try it here ``` f= a=>b=>(Math.pow(b,a*a)-1)/--b||a*a a.innerHTML='<pre>'+ [[8,2], [3,6], [7,1.5], [5,-3], [256,1], [2,2], [2,-2]].map(b=>`${b[0]}, ${b[1]} => ${f(b[0])(b[1])}`).join('<br>')+'</pre>' ``` ``` <div id=a> ``` # Alternative broken versions **32 bytes** ``` (a,b)=>(Math.pow(b,a*a)-1)/(b-1) ``` Causes `NaN` for `b==1`. **30 bytes** ``` (a,b)=>(Math.pow(b,a*a)-1)/~-b ``` Causes `Infinity` for `b==1.5`. **28 bytes** ``` (a,b)=>~-Math.pow(b,a*a)/~-b ``` Outputs `1` for some valid testcases. # Old version for 59 bytes `(a,b)=>Array(a*a).fill``.reduce((c,d,i)=>c+Math.pow(b,i),0)` [Answer] # Java, 132 bytes ``` import java.math.*;Object e(int n,BigDecimal m){BigDecimal r=BigDecimal.ONE,a=r;for(n*=n;n>1;n--)r=r.add(a=a.multiply(m));return r;} ``` ### Ungolfed ``` import java.math.*; Object e(int n, BigDecimal m) { BigDecimal r = BigDecimal.ONE, a = r; for (n *= n; n > 1; n--) r = r.add(a = a.multiply(m)); return r; } ``` ### Notes * This will work for arbitrarily big outputs as required by OP (Too bad Java supports big numbers, this would be shorter otherwise). ### Outputs ``` Input: 8 2.0 Expected: 18446744073709551615 Actual: 18446744073709551615 Input: 3 6.0 Expected: 2015539 Actual: 2015539 Input: 7 1.5 Expected: 850161998.2854 Actual: 850161998.285399449204543742553141782991588115692138671875 Input: 5 -3.0 Expected: 211822152361 Actual: 211822152361 Input: 256 1.0 Expected: 65536 Actual: 65536 Input: 2 2.0 Expected: 15 Actual: 15 Input: 2 -2.0 Expected: -5 Actual: -5 Input: 263 359.9 Expected: ? Actual: 9709...[176798 digits]...7344.7184...[69160 digits]...6291 ``` [Answer] # R, 18 bytes ``` sum(m^(1:s^2-1)) ``` Explanation: ``` sum( # Calculate sum m # Multiplier ^ # Exponentiate (1:s^2-1)) # Generate sequence from 1 to s(ide)^2-1 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes Code: ``` nL<mO ``` Explanation: ``` n # Compute i ** 2 L # Push the list [1, ..., i ** 2] < # Decrement by 1, [0, ..., i ** 2 - 1] m # Power function with implicit input, [0 ** j, ..., (i ** 2 - 1) ** j] O # Sum that all up ``` [Try it online!](http://05ab1e.tryitonline.net/#code=bkw8bU8&input=OAoy). [Answer] ## Haskell, 30 bytes ``` n#m=sum$take(n^2)$iterate(*m)1 ``` or equally long ``` n%1=n^2 n%m=(m**(n*n)-1)/(m-1) ``` The first version starts with `1` repeatedly multiplies with `m`. Then it sums the first `n^2` numbers of this sequence. The second version is the explicit formula as seen in other answers. [Answer] # J, 10 bytes ``` +/@:^i.@*: ``` ## Usage I mark some integers with the `x` suffix to use extended integers to get exact results. ``` f =: +/@:^i.@*: 2x f 8 18446744073709551615 3x f 6 75047317648499560 6x f 3 2015539 1.5 f 7 8.50162e8 _3x f 5 211822152361 1 f 256 65536 2 f 2 15 _2 f 2 _5 ``` ## Explanation ``` +/@:^i.@*: *: Square the value s to get s^2 i.@ Make a range from 0 to s^2 exclusive, [0, 1, ..., s^2-1] ^ Using m as the base, calculate the power with the range [m^0, m^1, ..., m^(s^2-1)] +/@: Sum the entire list and return it ``` [Answer] ## Mathcad, [tbd] bytes (~11) [![enter image description here](https://i.stack.imgur.com/Wkyhi.jpg)](https://i.stack.imgur.com/Wkyhi.jpg) Uses Mathcad's built in summation operator. Also demonstrates symbolic processor simplification to generate exact formula. Mathcad effectively runs two processing engines in parallel - one a standard IEEE 64/80 bit floating point, and the other an arbitrary number length symbolic process (MuPad). Standard numerical evaluation is indicated by equals sign (=), whilst a right arrow indicates symbolic evaluation. --- Mathcad counting scheme yet to be determined so no byte count given. ctl-$ enters the summation operator (Sigma), including empty placeholders to put the summation variable, initial value, final value and expression. Approximate byte-equivalent count = 11. [Answer] # PostgreSQL, 67 66 bytes ``` SELECT SUM(m^v)FROM(VALUES(3,6))t(s,m),generate_series(0,s*s-1)s(v) ``` `**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/8180/0)**` Input: `VALUES(side, multiplier)` --- **EDIT:** Input moved to table, all cases at-once: ``` SELECT s,m,SUM(m^v)FROM i,generate_series(0,s*s-1)s(v)GROUP BY s,m ``` `**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/17f35/3/0)**` Output: ``` ╔══════╦══════╦══════════════════════╗ ║ s ║ m ║ sum ║ ╠══════╬══════╬══════════════════════╣ ║ 7 ║ 1.5 ║ 850161998.2853994 ║ ║ 2 ║ 2 ║ 15 ║ ║ 2 ║ -2 ║ -5 ║ ║ 256 ║ 1 ║ 65536 ║ ║ 5 ║ -3 ║ 211822152361 ║ ║ 8 ║ 2 ║ 18446744073709552000 ║ ║ 3 ║ 6 ║ 2015539 ║ ╚══════╩══════╩══════════════════════╝ ``` [Answer] # TI-Basic, 19 bytes `S` is side length, and `M` is the multiplier. ``` Prompt S,M:Σ(M^I,I,0,S²-1 ``` [Answer] # Python, 40 bytes ``` lambda l,m:sum(m**i for i in range(l*l)) ``` [Answer] # Ruby: 39 bytes ``` ->s,m{(0...s*s).reduce(0){|a,b|a+m**b}} ``` **Test:** ``` f = ->s,m{(0...s*s).reduce(0){|a,b|a+m**b}} f[8,2] # 18446744073709551615 f[3,6] # 2015539 f[7,1.5] # 850161998.2853994 f[5,-3] # 211822152361 f[256,1] # 65536 f[2,2] # 15 f[2,-2] # -5 f[1,1] # 1 ``` [Answer] # Python, 41 Bytes Totally new at this golfing thing, criticism welcome! ``` lambda n,m:sum(m**i for i in range(n**2)) ``` [Answer] # Jolf, ~~18~~ ~~15~~ 10 bytes *Thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ for saving 3 bytes and pointing me towards mapping* ``` uΜzQjd^JwH ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=dc6celFqZF5Kd0g) ``` ΜzQj Map over an array of 1 -> square(side length) d^JwH Set the current array value to multiplier^(current value - 1) u Sum the array ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 9 bytes ``` q~2#,f#:+ ``` Inputs are in reverse order separated by a newline or a space. [**Try it online!**](http://cjam.tryitonline.net/#code=cX4yIyxmIzor&input=MS41Cjc) ``` q~ e# Read input. Evaluate: pushes the two numbers, M and N, onto the stack 2# e# Square: compute N^2 , e# Range: generates array [0 1 ... N^2-1] f# e# Compute M raised to each element of the array [0 1 ... N^2-1] :+ e# Fold addition: compute sum of the array [M^0 M^1 ... M^(N^2-1)] ``` [Answer] ## PHP, ~~58~~ 54 bytes ``` <?function a($n,$m){$n*=$n;echo(1-$m**$n)/(1-$m)?:$n;} ``` This just uses the summation formula to show the value, after checking if the multiplier is 1 (which returns NAN in the formula). [Answer] # Mathematica, 22 bytes ``` Tr[#^(Range[#2^2]-1)]& ``` Creates a range of `{1, 2, ... s^2}`, subtracts 1 over it to make `{0, 1, ..., s^2-1}`. Then raise each to the power of `m` making `{m^0, m^1, ..., m^(s^2-1)}` and return the sum of it. Alternatively, Mathematica can use the explicit formula by taking its limit. This requires **29** bytes. ``` Limit[(s^#^2-1)/(s-1),s->#2]& ``` [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 25 bytes ``` f(s,m)=sum(i=0,s^2-1,m^s) ``` Longer but faster (35 bytes): ``` f(s,m)=if(m==1,s^2,(m^s^2-1)/(m-1)) ``` Cute (30 bytes): ``` f(s,m)=vecsum(powers(m,s^2-1)) ``` [Answer] ## C#, 56 bytes ``` double f(int n,double q){return(Math.Pow(q,n*n)-1)/--q;} ``` [Answer] # Lua, 54 47 bytes ``` r=0l,m=...for i=0,l^2-1 do r=r+m^i end print(r) ``` Run from the command line with the board side length as the first argument and the multiplier as the second. Thanks to user6245072 for saving 6 bytes, and Katenkyo for saving an additional 1. --- Original 54 byte version: ``` a,b=...c=1 d=1 for i=2,a^2 do c=c*b d=d+c end print(d) ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 11 chars / 14 bytes ``` ⨭⩥ î²)ⓜⁿ⁽í$ ``` `[Try it here (Firefox/WebKit Nightly only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B8%2C2%5D&code=%E2%A8%AD%E2%A9%A5%20%C3%AE%C2%B2%29%E2%93%9C%E2%81%BF%E2%81%BD%C3%AD%24)` Yes, 𝔼𝕊𝕄𝕚𝕟 now works in WebKit Nightly! Chrome support is next. # Explanation ``` ⨭⩥ î²)ⓜⁿ⁽í$ // implicit: î = input1, í = input2    ⩥ î²) // generate a range [0..î^2)                      ⓜ  // map over range ($ is mapitem): ⁿ⁽í$  // í^$ ⨭ // sum resulting range  // implicit output ``` [Answer] # [RETURN](https://github.com/molarmanful/RETURN), 32 bytes ``` [a:2^0\ {[$¥][a;\^ ]#[¤¥][+]#]! ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` Anonymous lambda that leaves result on Stack2. Usage: ``` 8 2[a:2^0\ {[$¥][a;\^ ]#[¤¥][+]#]! ``` # Explanation ``` [ ]! lambda a: store multiplier to a 2^ square side-length 0\␊ create range [0..result) { set current stack to range [ ][ ]# while loop $¥ check if TOS is truthy a;\^␌ if so, push a^TOS to Stack2 ␁ set current stack to Stack2 [¤¥][+]# sum Stack2 ``` ]
[Question] [ # Task Write a function/program that, given three positive integers `a`, `b` and `c`, prints a Truthy value if a triangle (any triangle) could have side lengths `a`, `b` and `c` and outputs a Falsy value otherwise. # Input Three positive integers in any sensible format, for example: * three distinct function arguments, `f(2, 3, 5)` * a list of three numbers, `[2,3,5]` * a comma-separated string, `"2,3,5"` You may *not* assume the inputs are sorted. # Output A Truthy value if a triangle could have the sides with the lengths given, Falsy otherwise. # Test cases ``` 1, 1, 1 -> Truthy 1, 2, 3 -> Falsy 2, 1, 3 -> Falsy 1, 3, 2 -> Falsy 3, 2, 1 -> Falsy 3, 1, 2 -> Falsy 2, 2, 2 -> Truthy 3, 4, 5 -> Truthy 3, 5, 4 -> Truthy 5, 3, 4 -> Truthy 5, 4, 3 -> Truthy 10, 9, 3 -> Truthy 100, 10, 10 -> Falsy ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution in bytes, wins. Consider upvoting this challenge if you have fun solving it and... Happy golfing! [Answer] # [Python](https://docs.python.org/2/), 24 bytes ``` lambda l:sum(l)>max(l)*2 ``` [Try it online!](https://tio.run/##LYtBDgIhDEX3nKJLMCykDAsn0ZO4wehkSACJMlFPj201aft@f3/bp6/3imM5nkeO5XKNkOfnVnQ2pxLfhB2O15ryDdzcHql2WHSqbevamOEscCkaaMErlN3z7slSXnzH5Ajf8e9PFgIzkFRB8sJJ/vcWDj9ByknDFw "Python 2 – Try It Online") Checks if `a+b+c > max(a,b,c)*2`. If, say, `c` is the biggest one, this is equivalent to `a+b+c>2*c`, or `a+b>c`, which is want we want for the triangle inequality. [Answer] # [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code ([Intellivision](https://en.wikipedia.org/wiki/Intellivision)), 12 DECLEs1 = 15 bytes A routine taking \$(a,b,c)\$ into **R0**, **R1** and **R2** respectively and setting the carry if \$(a,b,c)\$ is not a triangle, or clearing it otherwise. ``` **083** | MOVR R0, R3 **0CB** | ADDR R1, R3 **15A** | CMPR R3, R2 **02F** | ADCR R7 **0D3** | ADDR R2, R3 **049** | SLL R1 **159** | CMPR R3, R1 **201 002** | BC @@rtn **048** | SLL R0 **158** | CMPR R3, R0 **0AF** | @@rtn JR R5 ``` ### How? Instead of testing: $$\cases{a+b>c\\a+c>b\\b+c>a}$$ We test: $$\cases{a+b>c\\a+b+c>2b\\a+b+c>2a}$$ The left parts of the inequalities are stored into **R3**. If the first test fails (when \$a+b\$ is stored into **R3** and compared with **R2**), the carry is set and added to the program counter (**R7**), forcing the next instruction to be skipped. Consequently, **R3** is not updated to \$a+b+c\$ and the last 2 comparisons are turned into: $$\cases{a+b>2b\\a+b>2a}\Leftrightarrow\cases{a>b\\b>a}$$ which of course is never true, so the test is guaranteed to fail as expected. All in all, this saves a branch which would have cost 1 extra DECLE. ### Full commented test code ``` ROMW 10 ; use 10-bit ROM width ORG $4800 ; map this program at $4800 ;; ------------------------------------------------------------- ;; ;; main code ;; ;; ------------------------------------------------------------- ;; main PROC SDBD ; set up an interrupt service routine MVII #isr, R0 ; to do some minimal STIC initialization MVO R0, $100 SWAP R0 MVO R0, $101 EIS ; enable interrupts MVII #$200, R4 ; R4 = pointer into backtab SDBD ; R5 = pointer into test cases MVII #tc, R5 MVII #13, R3 ; R3 = number of test cases @@loop MVI@ R5, R0 ; R0 = a MVI@ R5, R1 ; R1 = b MVI@ R5, R2 ; R2 = c PSHR R3 ; save R3 and R5 on the stack PSHR R5 CALL tr ; invoke our routine PULR R5 ; restore R3 and R5 PULR R3 MVII #$80, R0 ; R0 = '0' BC @@draw MVII #$88, R0 ; or '1' if the carry is not set @@draw MVO@ R0, R4 ; draw this character DECR R3 ; next test case BNEQ @@loop DECR R7 ; loop forever ;; ------------------------------------------------------------- ;; ;; test cases ;; ;; ------------------------------------------------------------- ;; tc PROC DECLE 1, 1, 1 ; true DECLE 1, 2, 3 ; false DECLE 2, 1, 3 ; false DECLE 1, 3, 2 ; false DECLE 3, 2, 1 ; false DECLE 3, 1, 2 ; false DECLE 2, 2, 2 ; true DECLE 3, 4, 5 ; true DECLE 3, 5, 4 ; true DECLE 5, 3, 4 ; true DECLE 5, 4, 3 ; true DECLE 10, 9, 3 ; true DECLE 100, 10, 10 ; false ENDP ;; ------------------------------------------------------------- ;; ;; ISR ;; ;; ------------------------------------------------------------- ;; isr PROC MVO R0, $0020 ; enable display CLRR R0 MVO R0, $0030 ; no horizontal delay MVO R0, $0031 ; no vertical delay MVO R0, $0032 ; no border extension MVII #$D, R0 MVO R0, $0028 ; light-blue background MVO R0, $002C ; light-blue border JR R5 ; return from ISR ENDP ;; ------------------------------------------------------------- ;; ;; our routine ;; ;; ------------------------------------------------------------- ;; tr PROC MOVR R0, R3 ; R3 = a ADDR R1, R3 ; R3 = a + b CMPR R3, R2 ; is R3 greater than c? ADCR R7 ; if not, skip the next instruction ADDR R2, R3 ; R3 = a + b + c (or still a + b if skipped) SLL R1 ; R1 = 2b CMPR R3, R1 ; is R3 greater than 2b? BC @@rtn ; if not, return with the carry set SLL R0 ; R0 = 2a CMPR R3, R0 ; is R3 greater than 2a? ; if not, the carry is set @@rtn JR R5 ; return ENDP ``` ### Output [![output](https://i.stack.imgur.com/L54jB.gif)](https://i.stack.imgur.com/L54jB.gif) *screenshot from [jzIntv](http://spatula-city.org/~im14u2c/intv/)* --- *1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.* [Answer] # Java 8, ~~52~~ ~~49~~ ~~38~~ 26 bytes ``` (a,b,c)->a+b>c&a+c>b&b+c>a ``` Port of [*@xnor*'s formula](https://codegolf.stackexchange.com/a/199355/52210) turns out to be shorter after all, by taking the input as three loose integers instead of a List/array. -12 bytes thanks to *@xnor* for reminding me that the first 6-bytes formula I used in [my 05AB1E answer](https://codegolf.stackexchange.com/a/199354/52210) is actually shorter in Java: \$(a+b>c)\land(a+c>b)\land(b+c>a)\$ [Try it online.](https://tio.run/##bVFNa8MwDL33V4gcioPV0DrJYSvLP1gvPY4dZNcd7lKnNG5hjP72TPlgJNmwkdDzk554PtGdVqfDZ2NKqmt4Jee/FwDOB3s9krGwa0sAXVWlJQ9G8BMQtgzQfTLxljmPBYc6UHAGduDhBRpBqNHEq4KkLsySpCn0UnOkZtuyLzddMntoulfuAGdeQOzD1fmPt3eguFcPtg5ig3w6qV9AYToGFDPSKSNFNQa4nM5IuUVNZ6h5S4b5FMgxGwM5q8yAbLbHGp/myBo37f3jXWdDx/nP6d6P/Vcd7DmpbiG5sFWh9IJkhJHUXTQyeoZI@sQMPzCIPJof) **Explanation:** ``` (a,b,c)-> // Method with three integer parameters and boolean return-type a+b>c // Return whether the sum of a and b is larger than c &a+c>b // and the sum of a and c is larger than b &b+c>a // and the sum of b and c is larger than a ``` --- **Previous ~~52~~ 49 bytes answer:** ``` S->{S.sort(null);return S.pop()<S.pop()+S.pop();} ``` Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/199362/52210) with input as a Stack of Integers. [Try it online.](https://tio.run/##dZHBb4IwFMbv/hUvO5WIjYIeNpyJxyXMS4/LDhU6U62FtA8XY/zbWcHOAWahoemP7339eG/PT3yyzw91pri18M6lvowApEZhvngmYNMcAbZFoQTXkJG9q6AVSkUZ8uywfHPSnTArSIPESa8j97LIUWawAQ2vULPJ6sKoLQwSXSkVJEZgZTQwWhYlCZZ@H/s9udZJY1JWW@VMvNepkDkcXTzC0Ei9@/gEHtyyobBIZqF72gR3EIVxF0ROEfcVcRh1gTv2PWJXEvU9omHJPFz0wSKcd8HC3TIA80GOafg8JNNw1qyHlrZtaDW@75TSeyP@RpNKi53JuClo8d35vjaGnxsRGTBLuW05D3ygf@fNHlxvghXxlYzyPF8rRdJfcLYojrSokJZuhqg0ScdPL/A01jQjLPB/e61/AA) **Explanation:** ``` S->{ // Method with Integer-Stack parameter and boolean return-type S.sort(null); // Sort the input-Stack return S.pop() // Check if the last largest value <S.pop()+S.pop();} // is smaller than the lowest two values added together ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 23 bytes ``` ->*a{a.sort!.pop<a.sum} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rsTpRrzi/qERRryC/wAbILs2t/R9tqKMARlxA0khHwViHywgsYgwWMQYJcoFJkBpjsJQRWI0RTMpER8EUzDAFsblMwbogDBOIOQY6CpZQFpBpCMaxeqmJyRnxxTmZyakaxprVNYk6STrJNQUK0WCGThqEjo2t/Q8A "Ruby – Try It Online") A different approach, xnor's formula would be shorter but I'm satisfied with that. [Answer] # Ruby, 19 bytes ``` ->*a{2*a.max<a.sum} ``` You can [try it online](https://tio.run/##NYzdCsIwDIXv@xS51BGLS9YLQX2RUSQrGwoOZGOgbHv2uqYK@fk45yTD1Hxid4mHayEzFWJ7eZ/FjlO/xrpE0DLbJARGQ6qwKpxEozNlWC3SDP2tCsEpuMTG6VWGKv85Ipx@tGGp7W0r4X4bn4/Q7ng/L4INhuUFtQJ2eXu/xi8)! Uses the fact that [this Ruby answer](https://codegolf.stackexchange.com/a/199362/75323) said it didn't want to implement the port of [xnor's answer](https://codegolf.stackexchange.com/a/199355/75323) and at the same time taught me enough syntax to guess how the max of an array is calculated :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` O;‹ß ``` -1 byte by porting [*@xnor*'s algorithm](https://codegolf.stackexchange.com/a/199355/52210). -1 byte thanks to *@Grimmy* using a derived formula. [Try it online](https://tio.run/##yy9OTMpM/f/f3/pRw87D8///jzbSAcJYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf3/rRw07D8//r/M/OtpQBwhjdYC0kY4xkDYC8o3BfGMdIyANJMHyxkBxI7C8EVTcRMcUTJvqmABpU6B6CG0C0W@gYwllGOgYglBsLAA). **Explanation:** The formula this program uses to determine if three side-lengths \$a,b,c\$ form a triangle is: \$t=\frac{a+b+c}{2}\$ \$(a<t)\land(b<t)\land(c<t)\$ ``` O # Take the sum of the (implicit) input-list ; # Halve it ‹ # Check if it's larger than each of the values of the (implicit) input-list ß # Get the minimum of those checks # (`P` can be used as alternative to check if all are truthy instead) # (after which this result is output implicitly) ``` --- **Original 6-byter:** ``` ÀĆü+‹P ``` [Try it online](https://tio.run/##yy9OTMpM/f//cMORtsN7tB817Az4/z/aSAcIYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8MNR9oO79F@1LAz4L/O/@hoQx0gjNUB0kY6xkDaCMg3BvONdYyANJAEyxsDxY3A8kZQcRMdUzBtqmMCpE2B6iG0CUS/gY4llGGgYwhCsbEA). **Explanation:** The formula this program uses to determine if three side-lengths \$a,b,c\$ form a triangle is: \$a+b>c\$ \$a+c>b\$ \$b+c>a\$ Which translates to the following code for 05AB1E: ``` À # Rotate the (implicit) input-list once towards the right: [a,b,c] → [b,c,a] Ć # Enclose it; appending its head to itself: [b,c,a] → [b,c,a,b] ü+ # Sum each overlapping pair: [b,c,a,b] → [b+c,c+a,a+b] ‹ # Check for each whether it's larger than the (implicit) input-list: # [a<b+c,b<c+a,c<a+b] P # And check if all three are truthy by taking the product # (`ß` could be used as alternative, like in the 4-byter program above) # (after which the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 30 bytes Probably the most basic formula. ``` f(a,b,c){a=a+b>c&a+c>b&b+c>a;} ``` [Try it online!](https://tio.run/##dY1BCoMwEEX3nmIQKgmO0BhdFKl3mUQiQmulLe1CvHrTaRaSLEqSIe/9T2Kr0VrvnSA0aOVKZypNbwsqbW8Kw5O6zU/zE640zeJ1mwYJawaw3Fk6wTeA/DD8WzmGhhMK4bdlxDWC3rkOuY5zzZWddeirmFWc1yFP@g1CG3PLauc2vJ9wk/x/RDilgo0KR7KSXbb5j3UXGh@@en8B "C (gcc) – Try It Online") [Answer] # [PHP](https://php.net/), ~~45~~ 32 bytes ``` fn($a)=>max($a)*2<array_sum($a); ``` [Try it online!](https://tio.run/##jZBNDsIgEEb3nmJCumgNNhbahemPB1FjiNF000pqTfT0yCBVO2wkLODx5gNGt9pUW91qiMbaXPo4UknddOqBi6Wo1DCo5/F273BfmvOpvQLLOOAEO1YNsDQa451nhyRl@56Vi48pOEhqIiOmcPVz07MwU9oImonsD1O62@k7pbspMLMwU7h6Qd8pQtPW5xwKmoksNAt7QE1kxCzcj@amZ6GZ0356Rru05rB5q99@ehaoluNZ9qtObJLNCw "PHP – Try It Online") Lambda function that takes an array `[a, b, c]` and outputs empty string if false or "1" if true, with xnor's formula. Note that in PHP the `;` is only necessary when the function is attributed to a variable, so it's placed in the footer (provided code is valid as it is). EDIT: thanks to Guillermo Phillips for introducing me to PHP 7.4 short notation! (as a declaration without `{}`, it now needs the `;`) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 12 bytes ``` 2Max@#<Tr@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b738g3scJB2SakyEFZ7X9AUWZeSbSyrl2ag3Ksmr5DNVe1oQ4Q1uqAGEY6xiCGkY6CoY6CMURMwVhHwQjEBNFACSjTECpqBBaFKTDRUTCFMk2BPBDTFGwCjGkCM9dAR8ESzgZyDMG4lqv2PwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 5 bytes ``` $~\-> ``` Why bother with any of the other math? If the longest side is longer (or equal) than the sum of the shorter two, it can't be a triangle. Otherwise it can. Input is an array. Output is 0 or 1. If you have the list necessarily sorted, then you can just input as a dumped array (straight onto the stack) and the first two characters are unneeded. If the list can be entered in *reverse* order, then you can remove the first three characters and flip the greater-than to a lesser-than, leaving only 2 characters needed. ``` $~\-> #Check if side lengths could make a triangle $ #Sort ~ #Dump array onto stack (stack is now 1 2 3) \ #Swap the top two elements (1 3 2) - #Subtract the top from the second (1 3-2) > #Check if that difference is strictly greater than the smallest value ``` This is equivalent to my last answer, but instead of a+b>c, I did a>c-b, which saves a character of stack-shuffling. [Try it online!](https://tio.run/##S8/PSStOLsosKPkfbaxgomAe@1@lLkbX7v9/AA "GolfScript – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytesSBCS ``` +/>2×⌈/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1vfzujw9Ec9Hfr/0x61TXjU2/eob6qn/6Ou5kPrjR@1TQTygoOcgWSIh2fw/0e9cxVCikpLMiq50g6tUNAwVABCTQUNIwUgBNLGCiYKpmDaVMEESJsqGENpEwVjIG1ooGAJZHCBzHFLzCmGG2MEljYCGgdWBtQGMc4IbLwxUNwIrN1AwRCENAE "APL (Dyalog Unicode) – Try It Online") Also uses [xnor's formula](https://codegolf.stackexchange.com/a/199355/78410) of `sum(a,b,c) > 2 * max(a,b,c)`. ### How it works ``` +/>2×⌈/ +/ ⍝ Is sum > ⍝ greater than 2× ⍝ twice of ⌈/ ⍝ max? ``` --- # Alternative 7 bytesSBCS ``` ∧/+/>+⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHcn1tfTvtR70r/qc9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P@PeucqhBSVlmRUcqUdWqGgYagAhJoKGkYKQAikjRVMFEzBtKmCCZA2VTCG0iYKxkDa0EDBEsjgApnjlphTDDfGCCxtBDQOrAyoDWKcEdh4Y6C4EVi7gYIhCGkCAA "APL (Dyalog Unicode) – Try It Online") ### How it works ``` ∧/+/>+⍨ +/ ⍝ Is sum > ⍝ greater than +⍨ ⍝ twice each number? ∧/ ⍝ All of them? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ṀḤ<S ``` [Try it online!](https://tio.run/##y0rNyan8///hzoaHO5bYBAMZ@6wfNcxR0LVTeNQw1/pwO9fh9kdNayL//4@ONtRRAKFYHQUQ00hHwRjENAKLGkNFjYESIKYxWIEhlGkIFTUCi8IUmOgomEKZpkAeiGkKNgHGNIGZa6CjYAlnAzmGYBwbCwA "Jelly – Try It Online") A monadic link taking a list of integers and returning a Jelly boolean (`1` = True, `0` = False). Based on [@xnor's Python answer](https://codegolf.stackexchange.com/a/199355/42248) so be sure to upvote that one too! ## Explanation ``` Ṁ | Maximum Ḥ | Doubled < | Less than: S | - Sum of original argument ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes ``` \d+ $* O`1+ ^(?!(1+),(1+),\1\2) ``` [Try it online!](https://tio.run/##HYqxCsMwDER3/UWhAae@wZLtIVPHjvkBExxohy4ZQv7fORtJT8fjzt/1P/Y2uU9t5evl@ZK1qpfNvR9O/YyBosXm1hQcURiiGHNkjjDh0Ucao7dhEjKZkSSz05l6P2AZL0D73g "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` O`1+ ``` Sort. ``` ^(?!(1+),(1+),\1\2) ``` Check that the sum of the first two is greater than the third. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~54~~ \$\cdots\$ ~~42~~ 36 bytes Saved 6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` f(a,b,c){a=a+b+c>2*fmax(a>b?a:b,c);} ``` [Try it online!](https://tio.run/##bZJRa4MwEMff@ykOoaA1Mo3tQ@d0D2OfYspIYuyEaovxIUz86nMxGpmu8r9w@r/fRY5j3oWxYShsgihiTkdi4lKXJfhQVETaJKGv5Hl0on4o6xYqUta2s@t2oB72RZoDNB8ZxNBZqXzHqTy/qThZCP6@h1YfaWJs0XLRfpIJChAoYX2GWtgkJ63AH8Pf4nTBFxabVkcNhjo5j/QWZgscrkmsyaPWZK1gLu9ctjzXuOb9tYJ/Mnhxa8Aee5R1zqXC/WhOX0CU3/xW2Ka78zR/UOVOBK6r6xyYRm7@hage8yC1n0UrmxqbPrSZsdlDWyjbbMTa4cpZxrBF740qKWxrnyOYArxkPPcirdVGEAQUAUMgkFoa1SoGkc0X9Lt@@GHFlVzE4F2rXw "C (gcc) – Try It Online") Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s formula. [Answer] # [Uiua](https://www.uiua.org/), ~~7 bytes~~ 9 bytes (SBCS) ``` |1<+/∘⊏⍖. ``` [Try it online!](https://www.uiua.org/pad?src=VHJpYW5nbGUg4oaQIHwxIDwrL-KImOKKj-KNli4KClRyaWFuZ2xlWzEgMSAxXSAgICAgIyBUcnV0aHkKVHJpYW5nbGVbMSAyIDNdICAgICAjIEZhbHN5ClRyaWFuZ2xlWzIgMSAzXSAgICAgIyBGYWxzeQpUcmlhbmdsZVsxIDMgMl0gICAgICMgRmFsc3kKVHJpYW5nbGVbMyAyIDFdICAgICAjIEZhbHN5ClRyaWFuZ2xlWzMgMSAyXSAgICAgIyBGYWxzeQpUcmlhbmdsZVsyIDIgMl0gICAgICMgVHJ1dGh5ClRyaWFuZ2xlWzMgNCA1XSAgICAgIyBUcnV0aHkKVHJpYW5nbGVbMyA1IDRdICAgICAjIFRydXRoeQpUcmlhbmdsZVs1IDMgNF0gICAgICMgVHJ1dGh5ClRyaWFuZ2xlWzUgNCAzXSAgICAgIyBUcnV0aHkKVHJpYW5nbGVbMTAgOSAzXSAgICAjIFRydXRoeQpUcmlhbmdsZVsxMDAgMTAgMTBdICMgRmFsc3k=) **Explanation:** ``` ## (Top of stack on the left) ## Stack: [1 3 2] . # Copy input ## Stack: [1 3 2] [1 3 2] ⍖ # Index array by descending value ## Stack: [1 2 0] [1 3 2] ⊏ # Order the input ## Stack: [3 2 1] /∘ # Put the elements on the stack ## Stack: 1 2 3 + # Add the top two items ## Stack: 3 3 < # Test whether the second item is less than the first ## Stack: 0 |1 # Function signature ``` Edit: Added function signature (2 extra bytes) to conform to rules. Thanks to [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler). [Answer] # [J](http://jsoftware.com/), 8 bytes ``` +/>2*>./ ``` [Try it online!](https://tio.run/##Tc09CoAwDIbh3VN8uBT/apu2g4IugpOTVxBFXLz/VJuhREKGJ@@QJ5ZaXZhGKLQwGNN2Gsu@rbHpZ6pn3ceqQHEe94sLlkdAcBmU6KQ4UIbjJrBSiEeKRxAE@IzATeB/fwyGFIWGT9bEDw "J – Try It Online") Uses [xnor's formula](https://codegolf.stackexchange.com/a/199355/75681) [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 13 bytes ``` raJ++j>]2.*.> ``` [Try it online!](https://tio.run/##SyotykktLixN/Z@TV/2/KNFLWzvLLtZIT0vP7n9tbvT/aEMdBRCK5QKxjHQUjIEsI7CYMUTMGCgMZBmDZQ0hLEOImBFYDCproqNgCmGZAjlAlilYL5RlAjXPQEfBEsYEsg3BOBYA "Burlesque – Try It Online") ``` ra # Read as array J # Duplicate ++ # Sum j # Swap >] # Maximum 2.*# Double .> # Greater than ``` [Answer] # [Wren](https://github.com/munificent/wren), 54 bytes I haven't written Wren in a long time... ``` Fn.new{|x|x.reduce{|a,b|a+b}>x.reduce{|a,b|a>b?a:b}*2} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkFkcUpSZmJeek6pgq/DfLU8vL7W8uqaipkKvKDWlNDm1uiZRJ6kmUTup1g5NyC7JPtEqqVbLqPZ/cGVxSWquXnlRZkmqBsJEveTEnByNaEMdIIzV1PwPAA "Wren – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 89 bytes Array/`vector` solution as shown in other answers. ``` #import<regex> int f(std::vector<int>v){std::sort(&v[0],&*end(v));return v[2]<v[1]+v[0];} ``` [Try it online!](https://tio.run/##bZLNboQgEIDvPsXEJi60bOLPeqgae@sT9Lb1YBS3JqsYROJm47NbxP4pJRrkm2@YCVJ03fFSFPP8UDcd4yLh9ELH1KpbARXqRRlFkhaC8USRVOK7Rr0ykSPPbkacR9qWSGIccyoG3oI8@1kiz172tMTjSe3cFtehpJDUrBec5k1q6f2bvG6RZHWJrbsFavwtty@dgtTOauov8Ih@YCJb6BMIttDXZmCYgZK3MNDpngE9w/S1aaafCIQGDBXfwlBXN@HJ7NMl8PwPVdjT73dgii09V4yjfBAMnBEikHh3cPpoCzYISBIY1U9aZpuAva693drPfjJ/x2LAMV0dVKERwwvYb3wQHzdbFbVf82t/s/ESPry3h3htcO3v66a4sTXNnw "C++ (gcc) – Try It Online") # [C++ (gcc)](https://gcc.gnu.org/), 56 bytes ``` int f(int a,int b,int c){a=a+b+c>2*((a=a>b?a:b)>c?a:c);} ``` Like the C solution but with more boilerplate. *-2 bytes thanks (indirectly) to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!* [Try it online!](https://tio.run/##bZDNboMwDIDveQqLSWuyphI/7WHA0tueYLethxDohtRCBQG1qnh2lhhtHc0isJ2Pz8GKOp1Wn0qNY1lp2FMbJbcxw6jYVb7IZbZUInyi1NQi28o4Y0KZpFgyjA9lpQ5dXkBa1q1uCnkU5Mb6Qum6EYTY046yrGhflzkjVwJmtTqP40lJ/9ZGFgJ6dCYTKwg4PjDwOQw5RHMYohk5ZmTkOYywPXBg4Jghmm77msPGgRvD53CDf3fh2p3T5/D8DzU4wPfnw5AQzPu6obLTNTyeIYae3V0cXq2qOw1pCud3f2ezx8Gb9sHdPtz9dt6WNWAlJofuqT2GYzPHFgZb8N6aTn9dPDOD9yoP7cVj1l58VItkmncatyl011TgJ2QYvwE "C++ (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 40 bytes *-2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld):* stores the result of `max` in `a`. Eliminates the variable `m` used in the previous solution. ``` f(a,b,c){a=a+b+c>2*((a=a>b?a:b)>c?a:c);} ``` [Try it online!](https://tio.run/##fZHfboMgFMbveYoTliYw6eaferFa7d2eYHfOC8S6knS6oF3SNT67Y8dsjWUpgZwvv/MdOIBavik1jjWTohSKn2UqvdJTWXjPmNVZuZXrkmfKBsWTYbzTjTocqx1sur7S7cM@I0Q3PbxL3bDPVlecnAnY8QOlMXmRRwWkiKYEKggEThjEHIYCojkM0Rk5zsia5zDC8sCBgeMM0emWrwTEDowtn8MYT3fhyu3TF/D0D7U4wPWbGBKCsW4Nw7dTkIKf2LCBTn/tWvtDxvDHi879gtu85wG/et0PYzeoGV1UAqYFywwW3WtDBf6JKmzxnwwuMiwubd4cUwc39uGwBfpijv3@RGEN9FkeuhPlyXRZMozf "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 42 bytes ``` f(a,b,c){a=a+b+c>2*(a>b?a>c?a:c:b>c?b:c);} ``` [Try it online!](https://tio.run/##fZHNboMwDMfveQorUyUy0o2PchgUuO0JdmMcQihrpA6mQCd1Fc/OMqOtoplqJbL189@JE8v1m5TT1DiCV1yys0iFW7kyC@4dkVW5yGQuYhlXxlexZMk43alWHo71Drb9UKvuYZ8RotoB3oVqnc9O1YycCRj7gULroizCElJEcwIj8DkuGPkSBhzCJQxQGVrK0IiXMMRy34K@pQxQaZdvOEQWjAxfwghvt@HG7tPj8PQPNdjH/ZsYE4K@6bSDfychBS8xbgu9@tp1ZkZas8dLXHglM3nXBXb1ux/aHNA4dFVzmDesM1j1ry3lOBNZmuK/0L@EQXlp86bNHdw4h0EO9EUfh/2JQgz0WRz6E2XJ/FgyTt8 "C (gcc) – Try It Online") [Answer] Never done one of these before. Here are two algorithms borrowed from other answers implemented in JavaScript. # JavaScript, 32 bytes ``` (a,b,c)=>a+b+c>Math.max(a,b,c)*2 ``` [Try it online](https://tio.run/##fc9NDoIwEAXgvaeYJZWRMFQSXcANPMTQUH@CYKASb1/bxpiY2CbTTb/XyeuNV17UfH2Y3XqwahoXAxoamzF2qETTct7lqj2xuRR3fn2ut1WITkNfDNM50xkh@BEIZn72YvOrFYKfiEqEPUId19oFIupIJtVtlhGlEuGY4FDaq@Zh@fcnSjCFYlWMZVhOCabEaypddQrnG7Fv) # JavaScript, 28 bytes ``` (a,b,c)=>a=a+b>c&a+c>b&b+c>a ``` [Try it online](https://tio.run/##fc9BCsMgEAXQfU8xqxDJtGRiA@1C7zJKLC2hKdHm@qm6KBSqMLp53@H74I29Xe@vcNwuu12ePoADtbeMBq1QmhV3RtuGO6tNY@LNObbM02lebq1rCSGNQAjrexKHXx0Q0hRUIpwRxrKOMVDQSLKqcbMsKPUI1wrn0kkdz/7fn6jClIsNJZZ5OVWYKq@pj9Upn29k/wA) [Answer] # [Lua](https://www.lua.org/), ~~128~~ 120 bytes ``` b=io.read()t={}for r in b.gmatch(b,"([^,]+)")do table.insert(t,r) end print(t[1]+t[2]+t[3]+0>math.max(t[1],t[2],t[3])*2) ``` [Try it online!](https://tio.run/##HcxBCsMgEIXhfU4hWTnNII1ZpxcRC1ptIyQaplMolJ7dxm4e/Hzw1per1c@pKIouSOD5870XEiRSFl49Nse3RXrspbmiHaCHUDp2fo0q5WcklowEIubQ7ZTykWa0AxvdZrLD@XI8LGpz779gE2wCJw21jqhx@gE "Lua – Try It Online") # [Lua](https://www.lua.org/), 37 bytes @Jo King's solution using TIO properly and following the rules of the challenge. ``` a,b,c=...print(a+b+c>math.max(...)*2) ``` [Try it online!](https://tio.run/##yylN/P8/USdJJ9lWT0@voCgzr0QjUTtJO9kuN7EkQy83sUIDKK6pZaT5//9/0/9m/80B "Lua – Try It Online") [Very direct translation of @xnor's algorithm](https://codegolf.stackexchange.com/a/199355/42248) [Answer] # Excel, 20 bytes ``` =SUM(A:A)>MAX(A:A)*2 ``` Input in `A1`, `A2` and `A3`. --- Alternatively, with input on `A1`, `B1` and `C1`: ``` =SUM(1:1)>MAX(1:1)*2 ``` [Answer] # [Pepe](//github.com/Soaku/Pepe/), 93 bytes ``` REeEREeEREeEREEEEeEeEREEEeREEEEEEEREEEEEEEErREEEEEerEEEEEerEeEeErEEEEeeRErREErEEEEeREeReEreEE ``` Input: `a;b;c` Output: `-1` for falsy, `1` for truthy **Explanation:** ``` REeEREeEREeE # Push 3 inputs (num) -> (R) REEEEeEeE # Sort the (R) stack REEEe # Move pointer pos to the last -> (R) REEEEEEE # Move last item of (R) (num c in this case) to (r) REEEEEEEE # Sum the stack (note: does not remove the stack completely!) -> (R) # For some reason, the pointer pos of (R) keeps sticking to the last item rREEEEEe # Subtract active item of (R) (a+b) to (r) (num c) -> (R) # ((a+b)-c) # r flag: Preserve the items rEEEEEe # Same as above, but put it to (r) # This switches the expression: (c-(a+b)) or -((a+b)-c) # No more r flag this time, so remove these two items rEeEeE # Absolute of (r) rEEEEee # Divide active item of (R) (a+b) and (r) (num c) -> (r) RE # Push 0 -> (R) rREE # Create loop labelled 0 -> (R) # r flag: Skip until Ee (or REe) rEEEEe # Decrement (0 -> -1) -> (r) REe # Return to where a goto was called last ReE # If the division of (r) returned 0, go inside the loop reEE # Output (r) as number ``` [Try it online!](https://soaku.github.io/Pepe/#RRRRv!pE7Sf@&1&0@y_w&@F-gDBM) [Answer] # x86-16 machine code, 21 bytes ``` 8B D0 MOV DX, AX ; DX = a 03 C3 ADD AX, BX ; AX = a + b 3B C1 CMP AX, CX ; is a + b > c? 76 0C JBE NOT_TRI ; if so, not triangle 03 C1 ADD AX, CX ; AX = a + b + c D1 E2 SHL DX, 1 ; DX = 2a 3B C2 CMP AX, DX ; is a + b + c > 2a? 76 04 JBE NOT_TRI ; if so, not triangle D1 E3 SHL BX, 1 ; BX = 2b 3B C3 CMP AX, BX ; is a + b + c > 2b? NOT_TRI: C3 RET ; return to caller ``` Callable function, input `AX`, `BX` and `CX`. Result is in `ZF`: `NZ` if triangle, `ZR` if not. Uses [Arnauld's method](https://codegolf.stackexchange.com/a/199368/84624) to check. **I/O from DOS test program:** [![enter image description here](https://i.stack.imgur.com/fkYWq.png)](https://i.stack.imgur.com/fkYWq.png) For some reason the test program returns `"Hotdog"` if a triangle and `"Not Hotdog"` if not. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ∑½<A ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oiRwr08QSIsIiIsIlsxMDAsIDEwLCAxMF1cblsxLCAyLCAzXVxuWzIsIDEsIDNdXG5bMSwgMywgMl1cblszLCAyLCAxXVxuWzMsIDEsIDJdXG5bMiwgMiwgMl1cblszLCA0LCA1XVxuWzMsIDUsIDRdXG5bNSwgMywgNF1cbls1LCA0LCAzXVxuWzEsIDEsIDFdXG5bMTAsIDksIDNdIl0=) [Answer] # C# 35 ``` bool t(int[] s)=>s.Max()*2<s.Sum(); ``` :) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` Σ\╙∞> ``` [Try it online.](https://tio.run/##y00syUjPz0n7///c4phHU2c@6phn9/9/tKEOEMZyAWkjHWMgbQTkG4P5xjpGQBpIguWNgDSEb6JjCqZNdUyAtClQHYQ2gegz0LGEMgx0DEEoFgA) Exact port, including same explanation, as [my 5-byte 05AB1E answer](https://codegolf.stackexchange.com/a/199354/52210): sum; swap; max; double; a>b. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 14 bytes A port of the Ruby answers. ``` ~.{+}*\$)\;2*> ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v06vWrtWK0ZFM8baSMvu//9oQwMDBUMQigUA "GolfScript – Try It Online") ## Explanation ``` ~ # Evaluate the input . # Copy it twice {+}* # Sum the input \$ # Sort the other input )\; # Select the last item # in the sorted list 2* # Double this item > # Compare ``` [Answer] ## [W](http://github.com/a-ee/w) `d`, ~~12~~ 10 bytes I'm quite satisfied because W doesn't have a max function. OR a function sorting the array. ``` ▼╪m╜w♣S×∟╖ ``` ## Uncompressed: ``` <a&b|R % Max. 2* % Double. S % Swap. +r % Sum. < % Less than. % It's in the wrong order because % I can golf a few bytes off the max function. ``` ``` % BTW the max function is implemented like this: (b<a) && (a) || (b) % The reduction reduces this function over the whole list. ``` ]
[Question] [ For this challenge, a linked list looks like this: ``` [1, 2, 4, 0, 6, 1, 3, 1] ``` You'll notice there's no data; each item in the list is just a reference to the index of the next one. Your task is to write a program or function which will follow a linked list like this forever, outputting each item as it is encountered. For example, for the above input: ``` [1, 2, 4, 6, 3, 0, 1, ...] ``` Input and output can be represented in any reasonable manner. All numbers in the input will be valid indices in the list, and you can choose if it's 0- or 1-indexed. The output will be infinite, and as long as your program would *theoretically* give a correct result given infinite time and resources it's valid. **Test cases:** Zero indexed, using lists. ``` [0] -> [0, 0, ...] [1, 0] -> [1, 0, 1, ...] [0, 1, 2] -> [0, 0, ...] [2, 1, 0] -> [2, 0, 2, ...] [4] -> (does not need to be handled) ``` [Answer] # [Haskell](https://www.haskell.org/), 17 bytes ``` f x=iterate(x!!)0 ``` 0-indexed [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjazJLUosSRVo0JRUdPgf25iZp5tQVFmXomKQppCtJGOoY5B7H8A "Haskell – Try It Online") [Answer] # [convey](http://xn--wxa.land/convey/), 36 29 bytes ``` v<<<<,{ \~./." >"`=>! >!0<"} ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidjw8PDwse1xuXFx+Li8uXCJcbj5cImA9PiFcbiA+ITA8XCJ9IiwidiI6MSwiaSI6IjEgMiA0IDAgNiAxIDMgMSJ9) [![top](https://i.stack.imgur.com/v96lM.gif)](https://i.stack.imgur.com/v96lM.gif) `{` gets the input, that will get looped around in the upper two rows, while outputting downwards the length `\`, its indices `/.` and a copy of itself `"`. It will only continue after `~.` (batch) if `n` elements reach `~.`, whereas `n` will be the length. [![run for 2 1 0](https://i.stack.imgur.com/LCl1y.gif)](https://i.stack.imgur.com/LCl1y.gif) We then take `!` `n` copies of the current index `i` (starting with 0) and compare `=` them to the indices of the list. This returns either 1 or 0. We take the correspondent element of the copied list so many times, effectively filtering the others out. The next index then gets copied to the output `"}` and waits for the next iteration. [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ¡!¹← ``` [Try it online!](https://tio.run/##yygtzv7//9BCxUM7H7VN@P//f7SxjpGOYSwA "Husk – Try It Online") 1-indexed, returns an infinite list. ## Explanation ``` ¡!¹← ← take the first element as the start ¡ apply the following infinitely: !¹ index into the input ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 29 bytes Zero-indexed. Prints forever. (Where *forever* means *until the call stack overflow*.) ``` f=a=>print(a.i=a[~~a.i])|f(a) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P8020dauoCgzr0QjUS/TNjG6rg5Ix2rWpGkkav5P04g21FEw0lEw0VEw0FEw01EAco2BZKzmfwA "JavaScript (V8) – Try It Online") ### Commented ``` f = a => // f is a recursive function taking the input array a[] print( // print: a.i = // update the current index, which is stored in the // property 'i' of the surrounding object of a[]: a[~~a.i] // it's initially undefined, so we use '~~' to coerce // it to a number (zero) on the first iteration ) // end of print() | f(a) // unconditional recursive call ``` The `a.i` trick saves 2 bytes over the more straightforward version: ``` f=(a,i=0)=>print(i=a[i])|f(a,i) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI1En09ZA09auoCgzr0Qj0zYxOjNWsyYNJK75P00j2lBHwUhHwURHwUBHwUxHAcg1BpKxmv8B "JavaScript (V8) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~35~~ 32 bytes -3 bytes thanks to Giuseppe. ``` function(l)repeat show(T<-l[+T]) ``` [Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/TyNHsyi1IDWxRKE4I79cI8RGNydaOyRW879ymkayhqGOAghpanKBuUZIbKA4kGsM4xqDuSBZqEKggClYtzlYxgRIamr@BwA "R – Try It Online") 1-indexed, prints the list indefinitely. A rare use for `show`, which is 1 byte shorter than `print`, and separates the output unlike `cat`. The variable `T` is initially `TRUE`; `+T` converts it to the integer `1`, and thereafter it is updated at each step to the relevant list entry. [Answer] # [Rattle](https://github.com/DRH001/Rattle), 11 bytes ``` |IP0[gpP~]0 ``` [Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7CIP0%5BgpP%7E%5D0&inputs=%5B2%2C1%2C0%5D) Update: changing link to new Rattle interpreter (please let me know if there are issues - I couldn't find any issues but this is a newer version of Rattle) # Explanation ``` | takes the user's input I stores the user's input in an array P0 sets the pointer to 0 [ ...... ]0 infinite loop g gets the value at the pointer p prints this value P~ sets the pointer to this value ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0[è= ``` 0-based indexing. Prints the numbers newline-delimited to STDOUT indefinitely. [Try it online](https://tio.run/##yy9OTMpM/f/fIPrwCtv//6MNdRSMdBRMdBQMdBTMdBSAXGMgGQsA) or [verify all test cases, but only printing the first 10 numbers of each](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VSG6Ln8N4g@vML2v59loHLtoW32/6OjDWJ1og11QKSBjqGOEZA20oHwgTwdEx0DHTMg31jHEChiEhsLAA). **Explanation:** ``` 0 # Start with index 0 [ # Loop indefinitely: è # Use the current integer to index into the (implicit) input-list = # Print it with trailing newline (without popping, so it'll become the index for # the next iteration) ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~29~~ 28 bytes ``` [z1-:az0<L]dsLx0[;aplLx]dsLx ``` [Try it online!](https://tio.run/##S0n@b6hgpGCiYKBgpmCoYKxg@D@6ylDXKrHKwMYnNqXYp8Ig2jqxIMenAsz5/x8A "dc – Try It Online") 0-indexed; takes input on the stack (just prepend it). If we assume input is already in `a`, cut off the first 16 bytes. Will perish when the call stack overflows. ``` [ # Phase 1: shove stuff into an array z1- # if there are 7 things on the stack, push 6 :a # store whatever was on top into e.g. a[6] z0<L # loop while stack isn't empty ]dsLx # execute immediately and with extreme prejudice 0 # first index to check out [ # Phase 2: the challenge ;a # push a[tos] p # print it lLx # loop forever ]dsLx # autobots, roll out ``` ~~I feel like the `0!=` should be reducible to `1>`~~ never mind, I just can't read. Woohoo! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 11 bytes ``` {⍺∇⎕←⍵⌷⍺}∘0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9e561NEOFAByH/VufdSzHShS@6hjhsH/NLBQ36Ou5ke9ax71bjm03vhR20Sg0uAgZyAZ4uEZ/D9NAcjyCvb3U4821FEw0lEw0VEw0FEw01EAco2BZKw6AA "APL (Dyalog Unicode) – Try It Online") 0-indexed, takes input as the left argument. -1 byte from user. ``` {⍺∇⎕←⍵⌷⍺}∘0 {⍺∇⎕←⍵⌷⍺}∘0 take 0 as initial right argument ⎕←⍺⌷⍵ print element at right arg ⍺∇ ⍵⌷⍺ recursive call with the input and new right arg ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 89 bytes ``` [S S S T N _Push_1][S N S _Duplicate_1][S N S _Duplicate_1][S N S _Duplicate_1][N S S N _Create_Label_READ_INPUT_LOOP][T N T T _Read_STDIN_as_integer][T T T _Retrieve][N T S S N _If_0_Jump_to_Label_DONE_READING][S S S T N _Push_1][T S S S _Add][S N S _Duplicate][S N S _Duplicate][N S N N _Jump_to_Label_READ_INPUT_LOOP][N S S S N _Create_Label_DONE_READING][S N N _Discard_top][N S S T N _Create_Label_PRINT_LOOP][T T T _Retrieve_at_address][S N S _Duplicate][T N S T _Print_as_integer][S S S T S S T N _Push_9_tab][T N S S _Print_as_character][N S N T N _Jump_to_Label_PRINT_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. 1-based indexing. Whitespace doesn't have any lists, so we'll read the numbers one at a time from STDIN. Input numbers will end with a trailing `0`, so the program knows when all the numbers are read from STDIN. I.e. test case `[1,2,4,0,6,1,3,1]` would be taken as input `2\n3\n5\n1\n7\n2\n4\n2\n0`. Outputs the numbers tab-delimited to STDOUT indefinitely. [**Try it online**](https://tio.run/##PYzLCYBADETP86pICboq1iOyoDdBwfLjJguG/GbyyHucT72vba/uZiYM6xlNKAKlZ7n8ZyBFziSbaA@CUTodFO6FiYWRlcLcavgA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer index = 1 Start READ_INPUT_LOOP: Read input as integer from STDIN, and store it in the heap at address `index` Integer input = retrieve the input from address `index` If(input == 0): Jump to DONE_READING index = index + 1 Go to next iteration of READ_INPUT_LOOP Label DONE_READING: Reset index to 1 Start PRINT_LOOP: index = retrieve integer from heap at address `index` Print `index` as integer to STDOUT Print character '\t' Go to next iteration of PRINT_LOOP ``` [Answer] # [Rust](https://www.rust-lang.org/), ~~50~~ 49 bytes ``` |a|(|mut i|loop{i=a[i];println!("{}",i)})(0usize) ``` [Try it online!](https://tio.run/##HYzLCoMwEEX3fsXV1QykYB90UR@f0U3pIkgCAxpFYxc1@fY0dHPhcDh33TefrMOkxRHjKIDReNgHrKOnGdp9k6/pGace2Xcp6EBh2j0kjPO8HNLpl7ybZRXnR1dSdcRKCUem@p9yavKnpY8ZSjorXBRuCrXCXSHjNS9zEdMP "Rust – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~14~~ 12 bytes ``` q~{_T=:Tp1}g ``` Input is taken from STDIN, 0-based, with format `[1 2 4 0 6 1 3 1]`. Output is printed to STDOUT, separated by newlines. [**Try it online!**](https://tio.run/##S85KzP3/v7CuOj7E1iqkwLA2/f//aEMFIwUTBQMFMwVDBWMFw1gA) Or verify test cases: [**1**](https://tio.run/##S85KzP3/v7CuOj7E1iqkwLA2/f//aINYAA), [**2**](https://tio.run/##S85KzP3/v7CuOj7E1iqkwLA2/f//aEMFg1gA), [**3**](https://tio.run/##S85KzP3/v7CuOj7E1iqkwLA2/f//aAMFQwWjWAA), [**4**](https://tio.run/##S85KzP3/v7CuOj7E1iqkwLA2/f//aCMFQwWDWAA). ## How it works ``` q e# Read input as a string ~ e# Evaluate: gives the input as a list of numbers { }g e# Do...while, popping condition from the stack 1 e# Push 1 at the end of each iteration, to produce an infinite loop _ e# Duplicate the input list T e# Push variable T. This is initially 0 = e# Get entry at that index (0-based) :T e# Assign the result to variable T p e# Print with newline ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~37~~ 34 bytes ``` def f(l,i=0):print(l[i]);f(l,l[i]) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PyU1TSFNI0cn09ZA06qgKDOvRCMnOjNW0xokCGb9h4imaUQb6igY6SiY6CgY6CiY6SgAucZAMlZT8z8A "Python 3.8 (pre-release) – Try It Online") thanks [user](https://codegolf.stackexchange.com/users/95792/user) for helping save 3 bytes slightly modified version of 31 bytes, but it prints an extra zero at the beginning ``` def f(l,i=0):print(i);f(l,l[i]) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PyU1TSFNI0cn09ZA06qgKDOvRCNT0xokkhOdGav5HyKUphFtqKNgpKNgoqNgoKNgpqMA5BoDyVhNzf8A "Python 3.8 (pre-release) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~24~~ 21 bytes ``` >(a,i=1)=a>@show a[i] ``` [Try it online!](https://tio.run/##HYxBCoAgFET3/xQDbZQ@oRbtlO4hLtxlCC0s6vZmbmbeY2COO6eo31qdiJyslja6rezng@hTqDmVCxbkNcMwFoZirIymc8tAg1d/NO@t@mR@NB1VABE50Y@mEVrWDw "Julia 1.0 – Try It Online") 1-indexed [Answer] # [PHP](https://php.net/), 34 bytes ``` for($i=1;;)echo($i=$argv[$i])." "; ``` 1-indexed, because `$argv` contains the script name at index 0, first argument is then `$argv[1]`. Too bad the new line takes a lots of bytes more, without it the brackets around `$i=$argv[$i]` are not necessary.. [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQybQ2trTVTkzPyQWyVxKL0smiVzFhNPSUuJev///8b/Tf@b/rf8L85kGXy3wgA "PHP – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 46 bytes ``` a->{for(int i=0;;)System.out.println(i=a[i]);} ``` [Try it online!](https://tio.run/##ZY49z4JAEIR7f8WUkJwXv2KD2Ly1lSWhWE8wywt3hNvTGMJvx9PY2cxmnkx2pqE7LZvr/9yHS8sGpiXvcSK2GBfAl3ohiaeJYR2EW10Ha4Sd1X/O@tBVw4GtFOURNfKZlsexdkMSEThfZVl6fnqpOu2C6H6IuLUJ51RwmWbTnP303B1f0cUNyVli/FaUoOHm088koNZkTNVLYqsHPr3jWmGjsFNYKewVot1GndL372kxzS8 "Java (JDK) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 38 bytes ``` i;f(int*a){printf("%d ",i=a[i]);f(a);} ``` [Try it online!](https://tio.run/##XYrNCsIwEITvPsVSEHbLFvzDS8iTlB5CbEqgaYMNiIa8unFBvDiHYYbvs91kba1eOfRLag3leJfhsNnfoGGvTe8HEmpIlRqMX5Ag70AiGqR@AA35yHBiuDAcGK4Mcs/SRf28Nupg5nm1uPnXuDpMRF8YxmDjEyMn/kcOo6xS39bNZtpq9/gA "C (gcc) – Try It Online") [Answer] # [R](https://www.r-project.org/), 31 bytes Note that tests don't work, but `print` returns its input so we can recurse. Curiously this is different from `cat` and `show` which return NULL. ``` function(l,i=1)f(l,print(l[i])) ``` [Try it online!](https://tio.run/##Fcy9CoAgFIbhvav4oEXBxXbvoi0awh8SxRN6pO7eanqn560jwGCEXixHKiKraLQMX68aC4u8xV3KMWP1jRscoRDjpprgugcTGh82wT/n0du/mIKwQqvlUy8 "R – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 51 50 bytes ``` f(){ A=($@) I=0 while I=${A[$I]} do echo $I done } ``` [Try it online!](https://tio.run/##PcuxDoIwEAbg/X@KM3agg6EgcSOBsc9gHECKbSIlEYwD8Oz1rMZb7sv/37XNZMN@l7bOpy0boU/kgrpMRCWhS4WXdXfDEkt9FvqyoRthrnYkoZneYAuPp08kLSCeWM1mmp2/kahi1jNotabp6JCrtR9mbAD4jTLKqSBFJ9aRspipX/Pd6nMTlf@zAuEN "Bash Try It Online") I was disappointed to find I could not use $@ as an array. I had to copy it to A. The test code limits the output to 20 lines, and wraps it (or tries). Terminates only on signal, like SIGPIPE. Edit: TIO seems to say I don't need the final newline. -1. Note that all my other newlines could become either spaces or semicolons, but I felt newlines had a better (weirder?) style in this case. [Answer] # [MATLAB](https://www.mathworks.com/products/matlab.html) and [Octave](https://octave.org), 20 bytes 32 bytes (I've been informed that it is not allowed on this site to assume the input is an array, original answer below the line.) ``` @(x)eval('1,while 1,x(ans),end') ``` Thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) for this solution to make a function out of my original answer. It is two bytes shorter than the more obvious solution: ``` function f(x),1,while 1,x(ans),end ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCM7UsMUdD3VCnPCMzJ1XBUKdCIzGvWFMnNS9FXfM/kKkRbaSjYKyjYKoDlFQwB7NNdBSMYjX/AwA "Octave – Try It Online") --- ``` 1,while 1,x(ans),end ``` 1-indexed, the input is in matrix `x`. For example: ``` >> x = [1, 2, 4, 0, 6, 1, 3, 1] + 1; >> 1,while 1,x(ans),end ans = 1 ans = 2 ans = 3 ans = 5 ans = 7 ans = 4 ans = 1 ... ``` `ans` is the default variable expression results get assigned to. The code above is equivalent to: ``` ans = 1 while 1 ans = x(ans) end ``` The result of the assignment is shown to the command line because statements are not terminated with a semicolon. [Answer] # Common Lisp, 44 bytes ### (Function prints in the square bracket + comma style of most languages) I used Common Lisp's `format` specifiers to handle all the control flow. ``` (defun f(l)(format t"[~{~a~:*~v@*~^, ~}]"l)) ``` ### Example usage: ``` (defparameter *test* '(1 2 4 0 6 1 3 1)) (f *test*) ; Will print [1, 2, 4, 6, 3, 0, 1, ... and so forth forever. ``` Edit: Technically the ending square bracket would never be reached, so we may omit the closing square bracket in the format string to have a 43 byte solution. [Answer] # [Python 3](https://docs.python.org/3/), ~~49~~ 37 bytes Thanks to Jo King for -12 bytes! ``` def f(l,c=0): while 1:c=l[c];yield c ``` [Try it online!](https://tio.run/##DcpBCsMgFEXReVbxhlr@QJPSQYorESnBaCPITxChZvXWyYUD97rrcfLS@x4iosjkjZLrhN@RcoBevcnWu/edQt7he4MZl9WEmfAkKMKLMLiMOjldJXEVD8uhVdEk4lnwQWKUjb9BaCWd7H8 "Python 3 – Try It Online") # Original ``` def f(l): c=l[0] while 1:c = l[c];yield c ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0fTiksBCJJtc6INYsHM8ozMnFQFQ6tkBVuFnOjkWOvKzNScFIXk//8B "Python 3 – Try It Online") This code takes an input, sets c(which holds the index), then continuosly `yield`s c after updating it to the new location. While this isn't the best answer on here, even for python, ~~I don't think it can really be improved upon without using recursion.~~ Clearly, I was wrong. [Answer] ## Batch, 94 bytes ``` @set n=0 :g @call:c %* @echo %n% @goto g :c @for /l %%i in (1,1,%n%)do @shift @set n=%1 ``` Takes a 0-indexed list of command line arguments (change `=0` to `=1` and `%1` to `%0` for 1-indexing). The `:c` subroutine exists to shift a copy of the command line, thus avoiding destroying the command line. For short lists (up to 9 elements), the following 51-byte 1-indexed script suffices: ``` @set n=1 :g @call set n=%%%n% @echo %n% @goto g ``` [Answer] # [Perl 5](https://www.perl.org/) `-a`, 22 bytes ``` $_=$F[$_]while say$_*1 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbFLVolPrY8IzMnVaE4sVIlXsvw/39DBYN/@QUlmfl5xf91fU31DAwN/usmAgA "Perl 5 – Try It Online") Input needs to be space separated. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` ≔⁰ηW¹«≔§θηηIηD⎚ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEchQ9OaqzwjMydVQcNQU6GaixMq5VjimZeSWqFRCFICUcYZUJSZV6LhnFhcopGhCRJwKc0t0AAxnHNSE4tArNr//6OjDXUUjHQUTHQUgOab6SgAucZAMjb2v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Charcoal rate-limits its output, so TIO will probably time out rather than fill its output buffer. Explanation: ``` ≔⁰η ``` Start at index 0. ``` W¹« ``` Repeat forever. ``` ≔§θηη ``` Update the index. ``` IηD⎚ ``` Output the index, clearing the canvas for the next loop. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes ``` (,)*(((?<-1>,)|\d+)+.*) $3$*,$2, }*`\G, ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ0dTS0NDw95G19BOR7MmJkVbU1tPS5NLxVhFS0fFSIerVishxl3n/39DHSMdEx0DHTMdQx1jHUMA "Retina 0.8.2 – Try It Online") 0-indexed. Explanation: The current index is encoded in unary as the number of leading `,`s. ``` (,)*(((?<-1>,)|\d+)+.*) ``` Match the current index, then as many commas and integers as possible, but only matching as many commas as the current index. The last submatch is therefore the next index. ``` $3$*,$2, ``` Replace the current index with the submatch in unary, then append the original input and an extra comma to ensure that the buffer changes each time (since Retina 0.8.2 doesn't have truly infinite loops). ``` }` ``` Repeat until the buffer stops changing, which it won't because we append a comma to the end on each loop. ``` *`\G, ``` Convert the current index to decimal and print it. [Answer] # [k4](https://code.kx.com/q/ref/), ~~17~~ 13 bytes ``` {0W(0N!x@)/0} ``` Loops "infinitely" via `0W`, outputting (`0N!`) the index in question. Begins with the first value in the input, i.e. `x 0`. [Answer] # [JQ](https://stedolan.github.io/jq/), 37 bytes ``` [0,.]|recurse([.[1][.[0]],.[1]])|.[0] ``` [Try it online!](https://tio.run/##yyr8/z/aQEcvtqYoNbm0qDhVI1ov2jAWSBjExuqAmLGaNSAOUJmRjqGOQSwA) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~27~~ 23 bytes *Saved a whooping 4 bytes, thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!!* ``` f=->a,i=0{f[a,p(a[i])]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5RJ9PWoDotOlGnQCMxOjNWM7b2f1p0tKGOgpGOgomOgoGOgpmOApBrDCRjY/8DAA "Ruby – Try It Online") --- # [Ruby](https://www.ruby-lang.org/), 23 bytes *As suggested by [Dingus](https://codegolf.stackexchange.com/users/92901/dingus), here is another way, and it prevents the "stack overflow" error!!* ``` ->a,i=0{loop{p i=a[i]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ9PWoDonP7@gukAh0zYxOjO2tvZ/WnS0oY6CkY6CiY6CgY6CmY4CkGsMJGNj/wMA "Ruby – Try It Online") [Answer] # FALSE, 65 24 21 bytes ``` [c;[1_][ø$.32,c;\-]#] ``` [Try it online!](https://tio.run/##S0vMKU79/z862TraMD42@vAOFT1jI51k6xjdWOXY//8B) Assumes that array is already pushed onto stack and len(array)-1 is stored in c. -41 because Razetime pointed out that I could just submit a function instead. -3 because of removed redundancy. ## Explanation ``` [c; {Push len(array) on stack for index 0} [1_] {Value for true} [ø {Get value at current index} $. {Dup and print int} 32, {Print space} c;\- {Subtract c by this new value to get new index} ]#] {Do lambda 2 while lambda 1 outputs true (forever)} ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/20209/edit). Closed 7 years ago. [Improve this question](/posts/20209/edit) Your goal is to write the shortest program that outputs "Hello-World!" as ASCII art. Rules : * It must be human readable, I don't care about it's size (cols/rows) * Output must contain only spaces (" "), sharps ("#") and newlines * The output must work with a monospaced font (but the letters doesn't necessary use a monospaced font) * In the result, each character must be separated from each other by at least one space Please add a title with the language and the number of bytes in your code. [Answer] # JavaScript, 178 bytes ``` c=document.createElement("canvas").getContext("2d");c.fillText("Hello-World!",0,7);d=c.getImageData(1,0,56,7).data;s="";for(i=3;i<1568;i+=4){s+=d[i]?"#":" ";s+=(i+1)%224?"":"\n"} ``` That works in Firefox 27 Scratchpad. ``` # # # # # # # # # # # # # # # # # # # # # # # ## # # ## # # # # ## ## # ### # ##### # # # # # # # # # # # # # # # # # # # #### # # # # ## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### # # ## # # ## # # ### # ``` [Answer] # Mathematica ~~101 99~~ 98 This rasterizes the expression, obtains the binary image data, converts each 1 to "#", each 0 to "" (empty space) and displays output in a 12 by 130 character grid. ``` GraphicsGrid[ImageData@ImageResize[Binarize@Rasterize@Style["Hello-World!",99],130] /.{1→"",0→"#"}] ``` ![hello](https://i.stack.imgur.com/JNhu3.png) One character economized thanks to Jonathan Van Matre. [Answer] ## Delphi 85 bytes ``` var s:tstringlist;begin s:=tstringlist.Create;s.LoadFromFile('\a');Write(s.Text);end. ``` I know, its not the prettiest solution but there was no rule that said you couldnt use external resources. Result: ![Result](https://i.stack.imgur.com/JgkGd.png) [Answer] I absolutely enjoyed this one # Perl, 126 116 114 102 98  87 (69) chars (ascii only & no external fonts) ## As of now shortest ascii solution which doesn't use any external fonts. Well, I wanted to present some elegant solution but @Ilmari Karonen challenged me with `unpack`... shouldn't have done that :-) Well, this 92 88 **69 chars** code generates the uglish unreadable output identical to @Ilmari Karonen's: ``` say map{y/01/ #/r}unpack"((b6)7a)*",'eT@j@DE UUBjdeE wTujjTA eUBTddE' ``` More elegant variant without unpack (88 chars): ``` map{print$"x$_,$/x/4/,"#"x!/7/}7&ord,7&ord>>3for'HRyYOKLIIjIRHBa@AJIAIIIJaQHQNSRH'=~/./g ``` But I think such |.|e||.-|||.,d! thing is nothing which resembles Hello-World! and shouldn't be allowed, so real solution goes here - unpack variant, **87 chars**: ``` say map{y/01/ #/r}unpack"((b6)9a)*",'E`D@HB@Hd EcD@HB@Hd ggDsIbaIf e`dDhRRHE ECICPaQPf' ``` Output: ![enter image description here](https://i.stack.imgur.com/d57JO.png) More elegant variant at 98 chars: ``` map{print$"x$_,$/x/1/,"#"x!/7/}7&ord,7&ord>>3for'PW{nw^QD[w}vK@X@PcP@jCDjXQk[rRRbSQD\CWbXeX'=~/./g ``` Output: ![enter image description here](https://i.stack.imgur.com/wGs2a.png) Older solution (114 chars), different type of coding: ``` print'#'x(3&ord),$"x($:=15&ord>>2),$/x!$:for'EmM}U}]MBEQSM}U}]MBOFNMQOKUMSKUOBEM]MMM]IIIMIUQIAEQWMMgFROYQOB'=~/./g ``` Output: ![enter image description here](https://i.stack.imgur.com/8uhp3.png) [Answer] # Perl 5, 54 bytes / 71 printable ASCII chars > > **Note:** This is the second version of this answer. For the original 64-byte / 95-char version using PHP and gzinflate(), see [the history of this answer](https://codegolf.stackexchange.com/posts/20246/revisions). > > > Here's the 71-char printable ASCII version: ``` y/01/ #/,say for unpack'(B40)4',unpack u,'4I*`1`(JJI!$FFNRJU52HIJ0*))H' ``` The 54-byte version contains non-printable characters, so I'm providing it as a hex dump. On Unixish systems, you can use `xxd -r` to turn the hex dump back into an executable Perl script: ``` 0000000: 792f 3031 2f20 232f 2c73 6179 2066 6f72 y/01/ #/,say for 0000010: 2075 6e70 6163 6b27 2842 3430 2934 272c unpack'(B40)4', 0000020: 27a4 a011 008a aaa4 1126 9aec aad5 54a8 '........&....T. 0000030: a6a4 0a24 9a27 ...$.' ``` Both need to be run with `perl -M5.010` to enable the Perl 5.10+ `say` feature. They will produce the following output: ![Screenshot of "Hello-World!" ASCII art](https://i.stack.imgur.com/ETnXR.png) (Shown as a screenshot, because the huge line-height on SE makes ASCII art ugly and hard to read. The lower case "e" is kind of awkward, but I believe this qualifies as readable, if only barely so.) --- **Ps.** If the output of the solution above feels too minimalistic for you, here's a **92-character** variant that produces output similar to [Tomas's solution](https://codegolf.stackexchange.com/a/20228): ``` y/01/ #/,say for unpack'(B56)*',unpack u,'CH!(`"(`"":,2``B``@GGDC\'(C#(YI!)("I)"2*,),`4,03D' ``` Here's a screenshot: ![Screenshot of "Hello-World!" ASCII art](https://i.stack.imgur.com/f6qkU.png) --- **Pps.** I'm pretty sure *this* (**GolfScript, 51 chars**) is the shortest printable-ASCII solution, if you don't count the ones that just call banner / FIGLet or that cheat in some other way: ``` 'iJ@Q@HmURBIMM{JkUUJeMRAQIM'{2base(;{' #'=}/}%39/n* ``` The output is the same as for my 71-char Perl solution above. [Answer] # Shell + Figlet (35) ``` $ figlet -w 90 -f banner Hello-World! # # # # ### # # ###### # # #### # # # #### ##### # ##### ### # # # # # # # # # # # # # # # # # ### ####### ##### # # # # ##### # # # # # # # # # # # # # # # # # # # # # # # ##### # # # # # # # # # # # # # # # # # # # # ### # # ###### ###### ###### #### ## ## #### # # ###### ##### ### ``` [Answer] ## Python 260 215 186 152 ``` >>> print'eJyNkFEKwDAIQ/93isC7/x3LyIJullHrR1BfJSIJPUHTlmiUPHbxC7L56wNCgZAxv3SjDWIxsoOb\nzMaBwyHYPJ5sVPNYxXism74vcIsFZlYyrg=='.decode('base64').decode('zip') # # # # # # # # # # # # # # # # # # # # # # # ## # # ## # # # # ## ## # ### # ##### # # # # # # # # # # # # # # # # # # # #### # # # # ## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### # # ## # # ## # # ### # ``` ## Python 196 183 130 114 (but uglyer) ``` >>> print'eJxTVlBWgCAgAQHKqBywAJeyAgJCZREcZWUYyaUMIpUVEKqRNcLEueDqEaZBLVVWQDITADIdFBw='.decode('base64').decode('zip') # # # # # # # # # # # # # # # # # # # # # # ## # ## # ### ## # # # # ## # # # # # # # # # # # ## # # # # # # # # ## # ``` I used zipped data in base64 encoding. and the code decode it from base64 encoding and then unzipping it. [Answer] # PHP — 183 bytes Using sebcap26's ASCII art as the source... ``` foreach(str_split(base64_decode('iASAERACCYgEgBKQAgmIxIwKoxo5+SSSCqSSSYnkksqkkkmJBJIKpJJIiOSMBEMSOQ'))as$i=>$j)echo strtr(sprintf("%8s%s",decbin(ord($j)),($i+1)%7?"":"\n"),'01',' #'); # # # # # # # # # # # # # # # # # # # # # # # ## # # ## # # # # ## ## # ### # ##### # # # # # # # # # # # # # # # # # # # #### # # # # ## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### # # ## # # ## # # ### # ``` [Answer] ## Brainfuck, 372 Byte (I know. but just for completeness, there has to be brainfuck ^^ It'S not going to get much shorter, as there are little repetitions. First and second line loop already...) ``` ++++++++[>++++>++++<<-]>+++>>++++++++++>>+>++[-<<<<<.>.<.>..>>>[-<<<.>>>]<[-<<<.>>>]<<..<.>>>++[-<<.<.>..........<.>....>>]<<<.>.<.>>.>+>>]<<<<<...>.<.>.<.>.<.>.<.>..<..>..<...>.<.>..<.>..<.>..<..>...<..>.<.>..<...>.<.>>.<<.>.<.>.<.>...<.>.<.>.<.>..<.>.....<.>.<...>.<.>.<.>..<.>.<.>...<.>.<.>..<.>>.<<.>.<.>.<...>.<.>.<.>..<..>.......<..>.<..>...<..>..<.>...<.>..<..>..<. ``` Interpreter here: <http://koti.mbnet.fi/villes/php/bf.php> --- ``` # # # # # # # # # # # # # # # # # # # ### # # # # ## ### # # # ## ## # ### # # # # # # # # # ### # # # # # # # # # ### # # ## ## ## ## # # ## # ``` --- Combining @ASKASK's number generator and image with my loops and some additional tuning, we get: ## Brainfuck, ~~343 339 336~~ 334 Bytes Looks uglier than my original version though. ``` +++++[->++++++>+++++++>++<<<]>++>>>+>>++[-<<<<.<.>.<..>>>[-<<<.>>>]>[-<<<.>>>]<<<<..>.<.>>>++[-<<.<.........>.<...>>>]<<.<.>.>.>>+>]<<<<..<<+++++[->>.<.<]>.>.<..>...<.>.<.>.<.>.<..>.<...>..<.>.<..>..<.>.>.<.<.>.<.>.<...>.<.>.<.>.<.>.<.....<++++++[->>.<.<]>..>.<.>.<.>.>.<.<.>.<..>.<..>.<.>.<..>.<.......>...<...>.<..>.<...>.<..>.<..>. ``` (image see @ASKASK's Answer) [Answer] # EcmaScript 6, 172 161 ``` '¡I%e!c0ĄJ¥eìo0¸ËefMs0µKcÊIs0´Ê¢1éo'.split(0).map(s=>s.split('').map(c=>{for(i=8,s='';i--;)s+=(c.charCodeAt(0)-33)&(1<<i)?'#':' ';return s;}).join('')).join('\n') ``` Output: ``` # # # # # # # # ### ## # # ## # # # ## # ## # ### # # #### # # # # # # # # # ## # # # # # # # # # # # # # # # # # # # # # # ### # # ## # # ## # # ### ``` Explanation: > > The ASCII text is compacted into a string where each bit represent a *pixel*: > > > * `0` for `SPACE` > * `1` for `#` > > > An offset of 33 is applied in order to get only printable characters. > > > [Answer] # [Sclipting](http://esolangs.org/wiki/Sclipting), 38 characters (76 bytes) ``` 갦륈똄릵꺕녔꺒녪냕녪낷뚕년꺒녦냉괄낵要감嚙긂밃⓶掘⓶終丟併껧뜴꼧밍替現겠合終 ``` ## Output: ``` # # ## # # # # # # ## # ## # # # # # # # # # # # # # # # # # # ### ## # # # # ## # # # # # ## # # # # # # # # # # # # # # # # # # # # # # # ## ## ## # # # # # # ## ## # ``` [Answer] # Brainfuck, 362 bytes Sorry @johannes-h, I saw yours and was inspired to make my own. It uses a combination of faster number generation at the beginning and a simpler picture to generate the result in less bytes. It does not however use loops anywhere else so it is up for optimization. ``` +++++[->++++++>+++++++>++<<<]>++>.<.>.<.....>.<.>.<.........>.<...>.<.........>.<...>.<.>.>.<.<.>.<..>.<..>.<.>.<.........>.<...>.<.........>.<...>.<.>.>.<...<.>.<.>.<.>.<.>.<..>.<..>...<.>.<.>.<.>.<..>.<...>..<.>.<..>..<.>.>.<.<.>.<.>.<...>.<.>.<.>.<.>.<.....>.<.>.<.>.<.>.<.>.<.>.<...>.<.>.<.>.>.<.<.>.<..>.<..>.<.>.<..>.<.......>...<...>.<..>.<...>.<..>.<..>. ``` which generates: ![pic](https://cl.ly/image/060Q1S3k3Y0g/Screen%20Shot%202014-02-06%20at%208.41.32%20PM.png) [Answer] # ImageMagick + sed, 71 bytes I don't see any other ImageMagick entries, so here's my late stake in the ground: ``` convert +antialias label:Hello-World! xpm:-|sed '8,+9y/ /#/;s/[^#]/ /g' ``` I think the `sed` portion can probably be golfed some more. [Try it online](https://tio.run/nexus/bash#@5@cn1eWWlSioJ2YV5KZmJOZWKyQk5iUmmPlkZqTk68bnl@Uk6KoUFGQa6VbU5yaoqBuoaNtWamvoK@sb12sHx2nHAtkp6v//w8A). Output: ``` # # # # ## # # # # # # # # # # ## ## # # # # # # # # ### # # # # # # #### # # #### # # # # #### # # # ### # # ###### # # # # ## ## # # # # ## ## ## # ## ## # # # ###### # # # # ### # # # # # # # # # # # # # # # # # # ## ## # # # # # # # # # ## ## # # ## ## ## ## ## ## # # ## ## # # #### # # #### ## ## #### # # ### # # ``` [Answer] ## **Postscript, ~~154~~ 133** ``` <~GasbQ8I>GO#QsOD7:?,pa&5XCgo@jeLPX:a4F9kN1nu1B@8KjD"^]WgY[MA.2VBjpTNo5$Pi%uI9Lr>,9`~>/FlateDecode filter 999 string readstring pop = ``` i.e. ``` <~GasbQ8I>GO#QsOD7:?,pa&5XCgo@jeLPX:a4F9kN1nu1B@8KjD"^]WgY[MA.2VBjpTNo5$Pi%uI 9Lr>,9`~> /FlateDecode filter 999 string readstring pop = ``` ASCII-only source, inspiration for ASCII-art was Johannes H.'s answer :-) ``` # # # # # # # # # # # # # # # # # # # ### # # # # ## ## # # ## ## # ### # # # # # # # # # ## # # # # # # # # # ### # # ## # # ## # # ## # ``` (more readable in terminal) ## **Perl, 102** ``` print$-%44?'':"\n",vec(unpack(u,'<!040`A!:4@`A`*%7918REEM1":T4)75E(#&1"0``'),$-++,1)?'#':' 'for 0..219 ``` Same output as above. I know I lost to both Perl answers above, but I publish it anyway. At least I tried and was moving in the right direction (and hadn't seen shortest answer) :-). [Answer] # Pure Bash, no external utilities - 133 characters: ``` c=" #";for x in 0x{5250088045,55520A914D,74556AAA54,535205124D};do while((s=(t=x)^(x/=2)*2,t));do L=${c:s:1}$L;done;echo "$L";L=;done ``` Uses right and left shift (divide and multiply by 2) and xor to find the one bits. Font data stolen from Blender/Ilmari Karonen. Tested in Bash 3.2 and 4.2 By the way, this is only 166 characters: ``` echo "# # # # # # # # # # # # # # # # # # # # # # # ## # ### # # # # # ## # # # # # # # # # # # ## # # # # # # # # ## #" ``` [Answer] # Python 3, 114 ``` print('\n'.join(bin(x)[2:]for x in[353530052677,366448644429,499649260116,357858349645]).translate({48:32,49:35})) ``` Output (4-character tall **e** and **W** stolen from [@Ilmari Karonen](https://codegolf.stackexchange.com/a/20246/7800)): ``` # # # # # # # # # # # # # # # # # # # # # # # ## # ### # # # # # ## # # # # # # # # # # # ## # # # # # # # # ## # ``` And a shorter one (107): ``` print('\n'.join(bin(x)[2:]for x in[11993933918769,16391913257513,12021315382193]).translate({48:32,49:35})) ``` Output: ``` # # ### # # ### # # ### ## # ## # ### ### # # # # # # # # ### # # # # # # ### ### ### ### ### ### # # ### ## # ``` [Answer] ## Python 154 Characters, (Char 5X7 in size) ``` print'\n'.join(map(''.join,zip(*(''.join("# "[int(e)]for e in"{:07b}".format(ord(c))[1:])for c in"€÷÷÷€ÿñêêòÿ€ÿ€ÿñîîñÿûûÿŸáþÁ¿ÁþáŸÿñîîñÿàïÿ€ÿÿñîî€ÿ‚")))) ``` **Output** ``` # # # # # # # # # # # # # # # # # # # # # # # ## # # ## # # # # ## ## # ### # ##### # # # # # # # # # # # # # # # # # # # #### # # # # ## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### # # ## # # ## # # ### # ``` [Answer] # Bash: ## (~~103~~ 89 Bytes) ### Code: ``` base64 -d<<<rohBEmRiqIihFVRS7IitVWRSqIihVVRQru5Aoldi|xxd -b|sed -e's/ //g;s/1/#/g;s/0/ /g'|cut -b'9-55' ``` ### Output: ``` # # ### # # # # # # ## # ## # # # # # # # # # # # # # # # # # # ### ## # # # # ## # # # # # ## # # # # # # # # # # # # # # # # # # # # # # # ### ### ### # # # # # # ### ## # ``` Smaller, but less readable (Based on <http://mckgyver.pbworks.com/f/1240440791/3PixelFont.jpg>): ### Code: ``` base64 -d<<<V0nCLsmQdklaqslQV23BTq2Q|xxd -b|sed -e's/ //g;s/1/#/g;s/0/ /g;'|cut -c'9-52' ``` ### Output: ``` # # ### # # ### # # ### ## # ## # ### ## # # # # ## # # # # # ## # # # # # # ### ## ## ### # # ### # # ## ## # ``` [Answer] # Javascript / ES6 (108 bytes) Copy into console: ``` [,0xa0a028045,0xeeae2bb5d,0xacaabaa54,0xaeae2ba5d].map(a=>a.toString(2).replace(/./g,b=>' #'[b])).join('\n') ``` Output: ``` " # # # # # # # # # ### ### # # ### # # ### ## # ### # # # ## # # # # # ### # # # # # # # # ### # # ### # # ### # # ### #" ``` (Needs ECMAScript6 compatible browser ie. Firefox 22+) Inspired by @maximeeuziere, @p01, @aemkei [Answer] Authors: xem, aemkei, p01, jonas Execute this in the JS console. ## JavaScript, cross-browser,~~133~~ ~~132~~ ~~126~~ 117 bytes ``` for(i=s="";l=[43117609029,64070269789,46349920852,46890400349][i++];)for(j=0,s+="\n";c=l.toString(2)[j++];)s+=" #"[c] ``` ## JavaScript, ES6, works on Firefox, 108 bytes ``` [,0xa0a028045,0xeeae2bb5d,0xacaabaa54,0xaeae2ba5d].map(a=>a.toString(2).replace(/./g,b=>' #'[b])).join('\n') ``` ## Result: ``` > # # # # # # # # # ### ### # # ### # # ### ## # ### # # # ## # # # # # ### # # # # # # # # ### # # ### # # ### # # ### # ``` [Answer] # HTML, 209 characters ``` <pre># # # # # # # # # # # # # # # # # ### ## # # # # # # # ## # ## # # # ## # # # # ## # # # # # # # # # # # # ### # # # # # # # # ### #</pre> ``` Does this count? :) [Answer] Shell, 20 characters: ``` banner Hello-world\! ``` For this to work, of course you need the `banner` program. On Debian, you can get it by installing the `bsdmainutils` package. This prints a beautifully rendered version of your message, designed to be printed on one of the old continuous-feed printers, so the output of the above text is 322 lines long by 123 columns wide, and you turn the printout on its side to read the message. You could hang the resulting paper on the wall as a banner, hence the name. <http://en.wikipedia.org/wiki/Banner_%28Unix%29> EDIT: Looks like Debian also has the `sysvbanner` package, which installs a banner program that prints the text horizontally for display on a terminal. However, this only prints the first 10 characters of the message, so it is kind of annoying for this code-golf problem! [Answer] # bash, ~~175~~ 170 bytes You need to *waste* quite a few characters in order to produce a *pretty output*! ``` base64 -d<<<H4sICKaT9FICAzAxAK2RQQ7AIAgE776CZP7/x1ZjERebcJAL0QybhcV6YdWizAPNaUatQQLFpj6h+c/XA05WF9Wtk9WJcxz4oe6e1YPQa7Wiut2wfjJ16STY30lSnNIlzvdpHhd6MiTOB65NYc+LAgAA|zcat ``` Output: ``` # # # # ### # # ###### # # #### # # # #### ##### # ##### ### # # # # # # # # # # # # # # # # # ### ####### ##### # # # # ##### # # # # # # # # # # # # # # # # # # # # # # # ##### # # # # # # # # # # # # # # # # # # # # ### # # ###### ###### ###### #### ## ## #### # # ###### ##### ### ``` [Answer] **F# - 204 characters** ``` for s in(Seq.map(Seq.unfold(function|0L->None|i->Some(" #".[int(i%2L)],i/2L)))[173948798213L;174770890021L;191304848727L;182715110773L;45277009173L;191279670629L])do printfn"%s"(new string(Seq.toArray s)) ``` Output: ``` # # # # # # # # # # # # # # # # # # ## # # # ### # # # # # # # # # # # # ## # # # ### # # # # ## # # # # # # # # # # # # # # # # ### # # # # # # # # ## # # # # # # # # ## # ``` [Answer] # Python + [pyfiglet](https://pypi.python.org/pypi/pyfiglet/) -- 87 characters ``` from pyfiglet import figlet_format print(figlet_format('Hello-World!', font='banner')) ``` ### Output ``` # # # # ### # # ###### # # #### # # # #### ##### # ##### ### # # # # # # # # # # # # # # # # # ### ####### ##### # # # # ##### # # # # # # # # # # # # # # # # # # # # # # # ##### # # # # # # # # # # # # # # # # # # # # ### # # ###### ###### ###### #### ## ## #### # # ###### ##### ### ``` To install `pyfiglet`, run: ``` $ pip install pyfiglet ``` [Answer] # Python with pyfiglet: 66 using argv, 69 without ## 66: ``` from pyfiglet import* print(figlet_format(sys.argv[1],font='3x5')) ``` ## 69: ``` from pyfiglet import* print(figlet_format('Hello-World!',font='3x5')) ``` firs must be called as, for example: python asciiart.py 'Hello-World!' second: python asciiart.py. Output: ``` # # # # # # # # # # # ### # # ### # # ### ### # ### # ### ## # # # # ### ### # # # # # # # # # ### ## ## ### ### ### # ## ### # # # # # ``` (Well, it looks kinda crappy with this font. Nevertheless :) ) [edit] removed obsolete dash from the argument. [Answer] # Javascript 137 (134) Uses the bits of integers to represent sharps an white spaces. Tested with Firefox 27. **137 character** ``` s="";[0xadb73eead9,g=0xa9252aaa94,0xed252aac95,g+1,0xad272aee99].map(n=>{for(;n>0;n/=2)n%2?[s="#"+s,n--]:s=" "+s;s="\n"+s});console.log(s) # # ## # # ### # # # ### ### # ## # # # # # # # # # # # # # # # # # # # ### ## # # # # # # # # # ## # # # # # # # # # # # # # # # # # # # # # # # ## ## ## ### ##### ### # # ## ## #" ``` **134 character (rotated 180°)** ``` s="";[0xadb73eead9,g=0xa9252aaa94,0xed252aac95,g+1,0xad272aee99].map(n=>{s+="\n";for(;n>0;n/=2)n%2?[s+="#",n--]:s+=" "});console.log(s) " # ## ## # # ### ##### ### ## ## ## # # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # ## ### # # # # # # # # # # # # # # # # # # # ## # ### ### # # # ### # # ## # #" ``` [Answer] # Python3 (126) There's an additional space between the chars to make it better readable. So technically it's a 125 character solution. ``` print(' '.join(['','\n'][i%40==0]+['#',' '][int('72liw1j4glyc34dum02j2a4ipxa8b7vvp65x511',36)//2**i%2==0]for i in range(200))) ``` Output: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] # Bash ~~37~~, 33 ``` toilet<<<"Hello-world"|tr \"m \# # # ### ### ### # # # ### # # ### # # ### # ## # #### ###### ## # # # ## ## ## # ## ## ## ## # # ## ## # # ##### # # # # ### ##### # # # # # # # # ##### ### ### ##### # # ##### # ### ##### ``` Which is the same as: ``` echo "Hello-world" | toilet ``` From `man toilet` > > TOIlet - display large colourful character > > > With `tr "'\"m" "#"` all `"` chars are replaced with `#`. [Answer] # Smalltalk, 151 although this golf game is already over, for the reference: ``` i:=((Form extent:115@14)displayString:'Hello world'x:0y:12;asImage).0to:13 do:[:y|i valuesAtY:y from:0to:114 do:[:x :p|({$#.$ }at:p+1)print].Stdout cr] ``` output: ``` *** *** *** *** *** ** * * * * * * * * * * * * * * *** * * *** *** *** *** *** *** * *** * ****** * * * * * * * * * * ** * * * ** * * * * * * * * * * * * * * * * * * * ******* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** ** * * * * * ** *** *** **** ******* ******* *** * * *** ****** ******* *** ** ``` ]
[Question] [ A [Proth number](https://en.wikipedia.org/wiki/Proth_number), named after François Proth, is a number that can be expressed as $$N = k \times 2^n + 1$$ Where \$k\$ is an odd positive integer and \$n\$ is a positive integer such that \$2^n > k\$. Let's use a more concrete example. Take 3. 3 is a Proth number because it can be written as $$ 3 = (1 \times 2^1) + 1 $$ and \$2^1 > 1\$ is satisfied. 5 Is also a Proth number because it can be written as $$ 5 = (1 \times 2^2) + 1 $$ and \$2^2 > 1\$ is satisfied. However, 7 is *not* a Proth number because the only way to write it in the form \$N = k \times 2^n + 1\$ is $$ 7 = (3 \times 2^1) + 1 $$ and \$2^1 > 3\$ is not satisfied. Your challenge is fairly simple: you must write a program or function that, given a positive integer, determines if it is a Proth number or not. You may take input in any reasonable format, and should output a truthy value if it is a Proth number and a falsy value if it is not. If your language has any "Proth-number detecting" functions, you *may* use them. # Test IO Here are the first 46 Proth numbers up to 1000. ([A080075](https://oeis.org/A080075)) ``` 3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65, 81, 97, 113, 129, 145, 161, 177, 193, 209, 225, 241, 257, 289, 321, 353, 385, 417, 449, 481, 513, 545, 577, 609, 641, 673, 705, 737, 769, 801, 833, 865, 897, 929, 961, 993 ``` Every other valid input should give a falsy value. As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins! --- *Number theory fun-fact side-note:* The largest known prime that is *not* a Mersenne Prime is \$19249 \times 2^{13018586} + 1\$, which just so happens to also be a Proth number! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’&C²> ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCZJkPCsj4&input=&args=MzM) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCZJkPCsj4KMTAwMFLDh8OQZg&input=). Let \$\newcommand{\&}[]{\text{ & }}j\$ be a strictly positive integer. \$j + 1\$ toggles all trailing set bits of \$j\$ and the adjacent unset bit. For example, \$10011\_{2} + 1 = 10100\_{2}\$. Since \${\sim}j = -(j + 1) = -j - 1\$, \$-j = {\sim}j + 1\$, so \$-n\$ applies the above to the bitwise NOT of \$j\$ (which toggles *all* bits), thus toggling all bits before the last \$1\$. By taking \$j \& (-j)\$ (the bitwise AND of \$j\$ and \$-j\$), all bits before and after the last set bit are nullified (since unequal in \$j\$ and \$-j\$), thus yielding the highest power of \$2\$ that divides \$j\$ evenly. For input \$N\$, we want to apply the above to \$N - 1\$ to find \$2^{n}\$, the highest power of \$2\$ that divides \$N - 1\$. If \$m = N - 1\$, \$-m = -(N - 1) = 1 - N\$, so \$(N - 1) \& (1 - N)\$ yields \$2^{n}\$. All that's left to test is if \$2^{n} > k\$. If \$k > 0\$, this is true if and only if \$(2^{n})^{2} > k2^{n}\$, which is true itself if and only if \$(2^{n})^{2} \ge k2^{n} + 1 = N\$. Finally, if \$(2^{n})^{2} = N = k2^{n} + 1\$, \$2^{n}\$ must be odd (\$1\$) so the parities of both sides can match, implying that \$k = 0\$ and \$N = 1\$. In this case \$(N - 1) \& (1 - N) = 0 \& 0 = 0\$ and \$((N - 1) \& (1 - N))^{2} = 0 < 1 = N\$. Therefore, \$((N - 1) \& (1 - N))^{2} > N\$ is true if and only if \$N\$ is a Proth number. ### How it works ``` ’&C²> Main link. Argument: N ’ Decrement; yield N - 1. C Complement; yield 1 - N. & Take the bitwise AND of both results. ² Square the bitwise AND. > Compare the square to N. ``` [Answer] # Python, 22 bytes ``` lambda N:N-1&1-N>N**.5 ``` This is a port of [my Jelly answer](https://codegolf.stackexchange.com/a/89442/12012). Test it on [Ideone](http://ideone.com/yDI2FL). ### How it works Let \$\newcommand{\&}[]{\text{ & }}j\$ be a strictly positive integer. \$j + 1\$ toggles all trailing set bits of \$j\$ and the adjacent unset bit. For example, \$10011\_{2} + 1 = 10100\_{2}\$. Since \${\sim}j = -(j + 1) = -j - 1\$, \$-j = {\sim}j + 1\$, so \$-n\$ applies the above to the bitwise NOT of \$j\$ (which toggles *all* bits), thus toggling all bits before the last \$1\$. By taking \$j \& (-j)\$ (the bitwise AND of \$j\$ and \$-j\$), all bits before and after the last set bit are nullified (since unequal in \$j\$ and \$-j\$), thus yielding the highest power of \$2\$ that divides \$j\$ evenly. For input \$N\$, we want to apply the above to \$N - 1\$ to find \$2^{n}\$, the highest power of \$2\$ that divides \$N - 1\$. If \$m = N - 1\$, \$-m = -(N - 1) = 1 - N\$, so \$(N - 1) \& (1 - N)\$ yields \$2^{n}\$. All that's left to test is if \$2^{n} > k\$. If \$k > 0\$, this is true if and only if \$(2^{n})^{2} > k2^{n}\$, which is true itself if and only if \$(2^{n})^{2} \ge k2^{n} + 1 = N\$. Finally, if \$(2^{n})^{2} = N = k2^{n} + 1\$, \$2^{n}\$ must be odd (\$1\$) so the parities of both sides can match, implying that \$k = 0\$ and \$N = 1\$. In this case \$(N - 1) \& (1 - N) = 0 \& 0 = 0\$ and \$((N - 1) \& (1 - N))^{2} = 0 < 1 = N\$. Therefore, \$((N - 1) \& (1 - N))^{2} > N\$ is true if and only if \$N\$ is a Proth number. Ignoring floating point inaccuracies, this is equivalent to the code `N-1&1-N>N**.5` in the implementation. [Answer] # Python 2, 23 bytes ``` lambda n:(~-n&1-n)**2>n ``` [Answer] # Mathematica, ~~50~~ ~~48~~ ~~45~~ ~~40~~ ~~38~~ ~~35~~ ~~31~~ 29 bytes Mathematica generally sucks when it comes to code golf, but sometimes there's a built-in that makes things look really nice. ``` 1<#<4^IntegerExponent[#-1,2]& ``` A test: ``` Reap[Do[If[f[i],Sow[i]],{i,1,1000}]][[2,1]] {3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65, 81, 97, 113, 129, 145, 161, 177, 193, 209, 225, 241, 257, 289, 321, 353, 385, 417, 449, 481, 513, 545, 577, 609, 641, 673, 705, 737, 769, 801, 833, 865, 897, 929, 961, 993} ``` Edit: Actually, if I steal [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'s bitwise AND idea, I can get it down to ~~23~~ ~~22~~ 20 bytes. # Mathematica, ~~23~~ ~~22~~ 20 bytes (thanks [A Simmons](https://codegolf.stackexchange.com/users/49583/a-simmons)) ``` BitAnd[#-1,1-#]^2>#& ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 10 bytes Thanks to **Emigna** for saving 4 bytes! ### Code: ``` <©Ó¬oD®s/› ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=PMOSwqkyUcK3MEtQwq4yS1DigLo&input=MTc3). ### Explanation: For the explanation, let's use the number **241**. We first decrement the number by one with `<`. That results into **240**. Now, we calculate the prime factors (with duplicates) using `Ò`. The prime factors are: ``` [2, 2, 2, 2, 3, 5] ``` We split them into two parts. Using `2Q·0K`, we get the list of two's: ``` [2, 2, 2, 2] ``` With `®2K`, we get the list of the remaining numbers: ``` [3, 5] ``` Finally, take the product of both. `[2, 2, 2, 2]` results into **16**. The product of `[3, 5]` results into **15**. This test case is truthy since **16** > **15**. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~460~~ ~~350~~ ~~270~~ ~~266~~ ~~264~~ ~~188~~ 176 bytes [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9WygpXSkoKCg8PigpKSkpe3t9KFsoKCgoe308KCh7fSl7fSk-KXt9KXt9KTw-Wyh7fSkoKCkpXSldKDw-KSl7KHt9KCkpPD59e308Pnt9e308Pigoe30pKXt7fXt9PD4oPCgoKSk-KX17fX0oPHt9e30-KTw-eyh7fVsoKV0pPD4oKHt9KClbKHt9KV0pKXt7fSg8KHt9KHt9KSk-KX17fTw-fXt9PD4oe308Pik&input=MjA5) ``` ({}[()])(((<>()))){{}([(((({}<(({}){})>){}){})<>[({})(())])](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}}(<{}{}>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<>) ``` ### Explanation The program goes through powers of two and four until it finds a power of two greater than N-1. When it finds it it checks for the divisibility of N-1 by the power of two using modulo and outputs the result ``` ({}[()]) #Subtract one from input (((<>()))) #Put three ones on the other stack { {} #Pop the crap off the top ([( ((({}<(({}){})>){}){}) #Multiply the top by four and the bottom by two <>[({})(())])](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{} #Check if the power of four is greater than N-1 } (<{}{}>) #Remove the power of 4 <>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>) #Modulo N-1 by the power of two ``` This program is not stack clean. If you add an extra 4 bytes you can make it stack clean: ``` ({}[()])(((<>()))){{}([(((({}<(({}){})>){}){})<>[({})(())])](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}}(<{}{}>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>) ``` [Answer] # Regex (ECMAScript), ~~48~~ ~~43~~ 41 bytes Neil's and H.PWiz's regexes (both also ECMAScript flavour) are beautiful in their own right. There is another way to do it, which by a pretty neat coincidence was 1 byte more than Neil's, and now with H.PWiz's suggested golfing (thanks!), is 1 byte ~~more~~ less than H.PWiz's. **Warning:** Despite this regex's small size, it contains a **major spoiler**. I highly recommend learning how to solve unary mathematical problems in ECMAScript regex by figuring out the initial mathematical insights independently. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. [See this earlier post](https://codegolf.stackexchange.com/a/178889/17216) for a list of consecutively spoiler-tagged recommended problems to solve one by one. So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above. So, this regex works quite simply: It starts by subtracting one. Then it finds the largest odd factor, *k*. Then we divide by *k* (using the division algorithm briefly explained in a spoiler-tagged paragraph of my [factorial numbers regex post](https://codegolf.stackexchange.com/a/178952/17216)). We sneakily do a simultaneous assertion that the resultant quotient is greater than *k*. If the division matches, we have a Proth number; if not, we don't. I was able to drop 2 bytes from this regex (43 → 41) using a trick found by [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy) that can futher shorten division in the case that the quotient is guaranteed to be greater than or equal to the divisor. > > `^x(?=(x(xx)*)\1*$)((\1x*)(?=\1\4*$)x)\3*$` > > > [Try it online!](https://tio.run/##TY@9bsIwFEZfhUYI7g1NSFrKgGuYOrAwtGPTShZcHLfGsWwDLj/PnoahUtdzPunT@RIH4ddO2ZB5qzbkdo35pp/WcUPH3ivJl2gBTnw@TtvPCAsOEWLEFKsy7SNAVcYUO1yV1aQDEavHtN@m4xPmoXkLThkJmHut1gTT@2yCyDwv2LFWmgA0dyQ2WhkCxDtu9lrjWXKde6tVgGE2RKa2AIbLXJORocb5w@Wi/EqsQHErnKelCSDfiw/EP0H/hZmXi3J20xhq1xyTpTkIrTY9J4ykWS8ZabZtHDD1zImp0Qi7wyQmuSNLIoDCfCfCugaHePaDge2SAtwqSmb3wQfXTdj12hbZ9KkofgE "JavaScript (SpiderMonkey) – Try It Online") > > > ``` > > # Match Proth numbers in the domain ^x*$ > ^ > x # tail = tail - 1 > (?=(x(xx)*)\1*$) # \1 = largest odd factor of tail > > # Calculate tail / \1, but require that the quotient, \3, be > \1 > # (and the quotient is implicitly a power of 2, because the divisor > # is the largest odd factor). > ( # \3 = tail / \1, asserting that \3 > \1 > (\1x*) # \4 = \3-1 > (?=\1\4*$) # We can skip the test for divisibility by \1-1 > # (and avoid capturing it) because we've already > # asserted that the quotient is larger than the > # divisor. > x > ) > \3*$ > > ``` > > > > [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` qtYF1)EW< ``` Truthy output is `1`. Falsy is `0` or empty output. (The only inputs that produce empty output are `1` and `2`; the rest produce either `0` or `1`). [**Try it online!**](http://matl.tryitonline.net/#code=cXRZRjEpRVc8&input=OTkz) ### Explanation Let *x* denote the input. Let *y* be the largest power of 2 that divides *x*−1, and *z* = (*x*−1)/*y*. Note that *z* is automatically odd. Then *x* is a Proth number if and only if *y* > *z*, or equivalently if *y*2 > *x*−1. ``` q % Input x implicitly. Subtract 1 t % Duplicate YF % Exponents of prime factorization of x-1 1) % First entry: exponent of 2. Errors for x equal to 1 or 2 E % Duplicate W % 2 raised to that. This is y squared < % Is x-1 less than y squared? Implicitly display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes ``` >N>0,2:N^P:K*+?,P>K:2%1,N:K= ``` [Try it online!](http://brachylog.tryitonline.net/#code=Pk4-MCwyOk5eUDpLKis_LFA-SzoyJTEsTjpLPQ&input=ODI) [Verify all testcases at once.](http://brachylog.tryitonline.net/#code=MTAwOjFmLgo-Lj4wLC4-Tj4wLDI6Tl5QOksqKy4sUD5LOjIlMSxOOks9&input=&args=Wg&debug=on) (Slightly modified.) ### Explanation Brachylog, being a derivative of Prolog, is very good at proving things. Here, we prove these things: ``` >N>0,2:N^P:K*+?,P>K:2%1,N:K= >N>0 input > N > 0 2:N^P 2^N = P P:K*+? P*K+1 = input P>K P > K K:2%1 K%2 = 1 N:K= [N:K] has a solution ``` [Answer] # Haskell, ~~55~~ 46 bytes ``` f x=length [x|k<-[1,3..x],n<-[1..x],k*2^n+1==x,2^n>k]>0 ``` Edit: Thanks to nimi, now 46 bytes ``` f x=or[k*2^n+1==x|k<-[1,3..x],n<-[1..x],2^n>k] ``` [Answer] # Julia, 16 bytes ``` !x=~-x&-~-x>x^.5 ``` Credits to @Dennis for the answer and some golfing tips! [Answer] # R, ~~52~~ 50 bytes ``` x=scan()-1;n=0;while(!x%%2){x=x/2;n=n+1};2^(2*n)>x ``` The program begins by dividing `N-1` (called here `P` and `x`) by `2` as long as possible in order to find the `2^n`part of the equation, leaving `k=(N-1)/2^n`, and then computes wether or not `k` is inferior to `2^n`, using the fact that `2^n>x/2^n <=> (2^n)²>x <=> 2^2n>x` [Answer] # Regex (ECMAScript), ~~40~~ 38 bytes *-2 bytes thanks to Deadcode* ``` ^x(?=((xx)+?)(\1\1)*$)(?!(\1x\2*)\4*$) ``` [Try it online!](https://tio.run/##Tc0xb8IwEAXgvwJRJe6SxiQIMZCaTB1YGNqxoZIVDudaY0eOCymlvz1Nh0rd3nvf8N7UWXW15zakXcsH8idn3@lz8NLSZfJE@rFvAa5yM4@H1x5KCdD3mJQIVV7lGN8hlNMx99Uixmo59iGeX1EE9xw8Ww0oOsM1weo@XSIWl4YNARjpSR0MWwLEqbQfxuCXlkZ0reEAs3SGBR8BrNTCkNWhwc3iduNup3bAslW@o60NoF@yPeIf0H@wm7zM17@MofHuEm3tWRk@TLyymtaTKDHF0Xko@EFSwUmC42HUR8JTSyoAozipUDfgEWtnO2dIGKfHvfgesnSVZdkP) Commented version: ``` # Subtract 1 from the input N ^x # Assert N is even. # Capture \1 = biggest power of 2 that divides N. # Capture \2 = 2. (?=((xx)+?)(\1\1)*$) # Assert no odd number > \1 divides N (?!(\1x\2*)\4*$) ``` [Answer] # J, 10 bytes ``` %:<<:AND-. ``` Based on @Dennis' bitwise [solution](https://codegolf.stackexchange.com/a/89444/6710). Takes an input `n` and returns 1 if it is Proth number else 0. ## Usage ``` f =: %:<<:AND-. f 16 0 f 17 1 (#~f"0) >: i. 100 NB. Filter the numbers [1, 100] 3 5 9 13 17 25 33 41 49 57 65 81 97 ``` ## Explanation ``` %:<<:AND-. Input: n -. Complement. Compute 1-n <: Decrement. Compute n-1 AND Bitwise-and between 1-n and n-1 %: Square root of n < Compare sqrt(n) < ((1-n) & (n-1)) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 47 bytes ``` \d+ $* +`(1+)\1 $+0 01 1 +`.10(0*1)$ 1$1 ^10*1$ ``` [Try it online!](https://tio.run/##DY07akNBEATzOscK3gfE9Mzs7wS6hDAy2IETB8b3f9qsqaa6/77/f34/r9v2eF3Pr5NycL42nftTlNMwoUXuss0O7QUV8aGVy3XZ6pwgqTQ6g4kWXI6jQIkqaqijgSZu@HIcDzzxije84wOfhBEi1mQQSVSiEZ0YxCSNFOnkekyyko3s5CAn1d4 "Retina 0.8.2 – Try It Online") Explanation: Given a Proth number \$ k · 2^n + 1 \$, you can derive two new Proth numbers \$ (2k±1) · 2^{n + 1} + 1 \$. We can run this in reverse until we obtain a Proth number where \$ k = 1 \$. This is readily performed by transforming the binary representation. ``` \d+ $* ``` Convert to unary. ``` +`(1+)\1 $+0 01 1 ``` Convert to binary. ``` +`.10(0*1)$ 1$1 ``` Repeatedly run the Proth generation formula in reverse. ``` ^10*1$ ``` Match the base case of the Proth generation formula. Edit: I think it's actually possible to match a Proth number directly against a unary number with a single regex. This currently takes me 47 bytes, 7 bytes more than my current Retina code for checking whether a unary number is a Proth number: ``` ^.(?=(.+?)(\1\1)*$)(?=((.*)\4.)\3*$).*(?!\1)\3$ ``` [Answer] # ECMAScript Regex, 42 bytes ``` ^x(?=(x(xx)*)\1*$)(?=(x+?)((\3\3)*$))\4\1x ``` [Try it online!](https://tio.run/##HYwxCsMwEAT7fYcMdydkpDitcZlPHEIBu3DjIqTYl@UB@ZgiUs7AzOt4n9ezdN8jjIhTq0LT5IURoXw/DBnTIS3R0CtlW4VCqqkXC/rnuKmIL77oMOr3Efcwr9A2V@DRfMe49ZxuOf8A) (Using Retina) I essentially subtract 1, divide by the largest possible odd number `k`, then check that at least `k+1` is left over. It turns out that my regex is very similar to the one Neil gives at the end of his [answer](https://codegolf.stackexchange.com/a/179066/71256). I use `x(xx)*` instead of `(x*)\2x`. And I use a shorter method to check `k < 2^n` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 128 bytes ``` ({<{({}[()]<(([{}]())<>{})<>>)}{}>{{}(<>)}{}}<><(())>){([()]{}<(({}){})>)}{}([({}[{}(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} ``` [Try it online!](https://tio.run/##JYwxCsRADAO/IxVXpQoYfyRskRSBcEeKtMJv32j3wFi2Jc/x7Nf9OX/7t3coBNUGtgA2VQMZqXJLliqlQsyxIp0hk8J4UHl10jV9H02yOtPYxhcHfBLtCwgD/3zvQ3pf1@UF "Brain-Flak – Try It Online") I used a very different algorithm than the [older Brain-Flak solution](https://codegolf.stackexchange.com/a/89453/31203). Basically, I divide by 2 (rounding up) until I hit an even number. Then I just compare the result of the last division with the two to the power of the number of times I divided. ## Explanation: ``` ({ # (n+1)/2 to the other stack, n mod 2 to this stack <{({}[()]<(([{}]())<>{})<>>)}{}> # if 1 (n was odd) jump to the other stack and count the one {{}(<>)}{} #end and push the sum -1, with a one under it }<>[(())]) #use the one to get a power of two {([()]{}<(({}){})>)}{} #compare the power of two with the remainder after all the divisions ([({}[{}(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} ``` [Answer] # [Bitwise Fuckery](https://github.com/cairdcoinheringaahing/Bitwise-Fuckery), 56 bytes ``` ,-@|~+&[>+>+<<-]>%>[<|[<+>-]>-]<<[>+<-]|+[-(>.<)>-(.>)<] ``` [Try it online!](https://tio.run/##rVbbbqMwEH2Gr7AqNdjiomT3LSKo/8FSxGK3QUoMMmS30Wb761lfSD11A5tKjRQJ5nJmzhgfuzsO25Z/P5@bfdeKAfXH3vcpe0L7quG4Es@/ItQPtOFk7XtPjeiHcqg6hjYoXxa@17O65fSdqW6pelap@apIBOt2Vc1w8IMHEQoCAiyDa0HG4HsKsJcod/Fwhxpu0L6tJTxlPw/P2kMdDz/smWhq7eOOT@GVW1ZR6V2aHsuGU/Zi3ndt25WUdcPWvDe8OwwwwPd@b5sdQyAxRTvGsTKo0Xj1thIyVr3nNkqW9ponZJyyscc7FQsGmb91VqDHDQLzBB4HZDEHsrgR5DQHcroR5HUOZINerzocjAcXI0LvvyrwFiEb5sDcz7QSTbBBUzRhncnOgz/BDPs0vW2Gwd85lCybRHH4h3NLEW7QyomP5@Ljj/GZibcbacT0BnFcT47LYy@13FY6FdRKqq5jnOIl0Q7A8J0H1k/d@mOPKsgaU7Q0tazpfqM3qi3uIicGWZpGBZF0DlzpSD8IzWHXszdbvdW2TjR8wLLTjbLj6mePleHqHIj8OTWj@Y3TCoq16uZAiQqCJASUJiNBRp6R6hLFZiQgRi@TMo5/2EVuugDqF9qh8na4vqzrcc0qUSu51PGjPBqjCYAie4E15R2J1LsgD9Zj9g3BhQ2@fAUuteJtUb@KQ/yZtj5F@IKsvzOdBVZkiiD@coL/7xl/hiD5QNCtZRjpA31t95RiGIGDNrLbG8pyNHUugCEsVsqx04fIsU/kRmFCEFl31IxelTVDAVebilMIF680nyUUuaRrO0x8O1F7XqlsqNg2HarcJd9Qhqyu9HsJcwh/5CVplSWv9qws9RKUpbrFlaU6YfR9TkWPdzqT13B5@aooJuR8Jucofji9hos8C7MwTeMiu8/y9JSnYSaf4yJNpUeaT2Ee4yxJSRbjJCNp8Q8) Uses the [latest version](https://github.com/cairdcoinheringaahing/Bitwise-Fuckery) of the language, in which I finally fixed the `[]` and `()` loops. Inputs via char code. Outputs a null byte if the input is not a Proth number, outputs a non-null byte otherwise. Add the `-n` flag to output an an integer. ## How it works Bitwise Fuckery is, unsurprisingly, an extension of brainfuck with bitwise commands, an "if zero" loop and a second tape. As [demonstrated by Dennis](https://codegolf.stackexchange.com/a/89442/66833), bitwise operations are helpful in this challenge, so I thought I'd fix up the language and give it a go. Bitwise Fuckery's second tape has the same tape head as the first tape, and certain commands operate on the two values under the tape head on each tape. I've marked the tape heads with `(...)` in the explanation. I'll work through the program with an example input of `5` (that's the char code of the character, not the character `5`) ``` , # Take a byte of input # Tapes: [( 5) 0 0 ...] [( 0) 0 0 ...] - # Decrement it # Tapes: [( 4) 0 0 ...] [( 0) 0 0 ...] @ # Swap tapes # Tapes: [( 0) 0 0 ...] [( 4) 0 0 ...] | # Bitwise OR, copying across # Tapes: [( 4) 0 0 ...] [( 4) 0 0 ...] ~+ # Bitwise NOT and increment # Tapes: [(-4) 0 0 ...] [( 4) 0 0 ...] & # Bitwise AND # Tapes: [( 4) 0 0 ...] [( 4) 0 0 ...] [>+>+ # Copy the first cell into cells 2 and 3 <<-] # Tapes: [( 0) 4 4 ...] [( 4) 0 0 ...] > # Move along one cell # Tapes: [ 0 ( 4) 4 ...] [ 4 ( 0) 0 ...] %> # Swap the cells under the tape head and move # Tapes: [ 0 0 ( 4)...] [ 4 4 ( 0)...] [ # Square the value under the tape head: <| # Move left and Bitwise XOR # Tapes: [ 0 ( 4) 4 ...] [ 4 ( 4) 0 ...] [<+>-] # Copy into the first cell # Tapes: [ 4 ( 0) 4 ...] [ 4 ( 4) 0 ...] >- # Move right and decrement # Tapes: [ 4 0 ( 3)...] [ 4 4 ( 0)...] ] # Repeat while the tape head is non-zero # Tapes: [ 16 0 ( 0)...] [ 4 4 ( 0)...] << # Move to the first cell # Tapes: [(16) 0 0 ...] [( 4) 4 0 ...] [>+<-] # Copy into the second cell # Tapes: [( 0) 16 0 ...] [( 4) 4 0 ...] |+ # Logical OR and increment, restoring N to the tape # Tapes: [( 5) 16 0 ...] [( 4) 4 0 ...] [ # Check that N is less than the second cell - # Decrement N # Tapes: [( 4) 16 0 ...] [( 4) 4 0 ...] ( # If zero: >.< # Output the value in the second cell # Tapes: [( 4) 16 0 ...] [( 4) 4 0 ...] ) >- # Move right and decrement # Tapes: [ 4 (15) 0 ...] [ 4 ( 4) 0 ...] ( # If zero: .> # Output and move right # Tapes: [ 4 15 ( 0)...] [ 4 4 ( 0)...] ) < # Move left # Tapes: [ 4 (15) 0 ...] [ 4 ( 4) 0 ...] ] ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 7 bytes ``` Đ⁻Đ~∧²< ``` [Try it online!](https://tio.run/##K6gs@f//yIRHjbuPTKh71LH80Cab//8NjQE "Pyt – Try It Online") Port of [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/89444/116013) [Answer] # Maple, 100 bytes (including spaces) ``` IsProth:=proc(X)local n:=0;local x:=X-1;while x mod 2<>1 do x:=x/2;n:=n+1;end do;is(2^n>x);end proc: ``` Nicely spaced for readbility: ``` IsProth := proc( X ) local n := 0; local x := X - 1; while x mod 2 <> 1 do x := x / 2; n := n + 1; end do; is( 2^n > x ); end proc: ``` Same idea as several others; divide X by 2 until X is no longer evenly divisible by 2, then check the criteria 2^n > x. [Answer] # Java 1.7, ~~49~~ 43 bytes *Another 6 bytes the dust thanks to @charlie.* ``` boolean g(int p){return p--<(p&-p)*(p&-p);} ``` [Try it!](https://ideone.com/pmqMI0) (ideone) ~~Two ways, equally long. As with most answers here, credits go to @Dennis of course for the expression.~~ Taking the root of the righthand side of the expression: ``` boolean f(int p){return(p-1&(1-p))>Math.sqrt(p);} ``` Applying power of two to the lefthand side of the expression: ``` boolean g(int p){return Math.pow(p-1&(1-p),2)>p;} ``` Can shave off a single byte if a positive numeric value is allowed to represent 'truthy', and a negative value 'falsy': ``` double g(int p){return Math.pow(p-1&(1-p),2)-p;} ``` Unfortunately because of ['Narrowing Primitive Conversion'](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3) one cannot simply write this in Java and get correct results: ``` ((p - 1 & (1 - p))^2) > p; ``` And any attempt to widen 'p' will lead to a compile error because bitwise operators are not supported on i.e. floats or doubles :( [Answer] # [Hy](http://hylang.org/), 37 bytes ``` (defn f[n](>(**(&(- n 1)(- 1 n))2)n)) ``` [Try it online!](https://tio.run/##FYsxCoAwFEN3T5FJ8gWh9QBepHQQ7NcuXykunr5@MyQvhJxv79yLGjRZ5spp4sgZhigeESayiFunXg2pgm2zo/gSQwiSB4BVQUUV51@8W7XHu78@ "Hy – Try It Online") Port of @Dennis' answer. [Answer] # [C (gcc)](https://gcc.gnu.org/), 29 ~~30~~ bytes ``` z;f(x){return--x<(z=x&-x)*z;} ``` [Try it online!](https://tio.run/##FYpBDoIwEEXXcooJBjMj1MC6oBdxY1oqk0hLakkaCGevdfVf3vtKvJVKZ7bqs@oR@m/Q7G7TPW3SYKTdj2H1VojY4zbEi4h03eSR2AaYX2yRYC8AwDiPf8cwQCfz9NC1bYa6puK0@NwMlot3YXpgpSnfKv20ZQPcgEEmksWRfg "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ ~~10~~ 9 bytes ``` É&1-U)>Uq ``` [Try it online!](https://tio.run/##y0osKPn//3CnmqFuqKZdaOH//4bmAA "Japt – Try It Online") Port of Dennis' Jelly answer again. - 1 thanks to @Shaggy. [Answer] # x86 Machine Code, 15 bytes ``` 4F 89 F8 F7 D8 21 F8 0F AF C0 39 C7 19 C0 C3 ``` These bytes define a function that takes the input argument (an unsigned integer) in the `EDI` register, following the standard System V calling convention for x86 systems, and it returns the result in the `EAX` register, like *all* x86 calling conventions. In assembler mnemonics: ``` 4F dec edi ; input -= 1 89 F8 mov eax, edi ; \ temp F7 D8 neg eax ; | = 21 F8 and eax, edi ; / (input & -input) 0F AF C0 imul eax, eax ; temp *= temp 39 C7 cmp edi, eax ; set CF if (input < temp) 19 C0 sbb eax, eax ; EAX = -CF C3 ret ; return with result in EAX ; (-1 for Proth number; 0 otherwise) ``` **[Try it online!](https://tio.run/##jVJNa8JAED0nv2LYImw01nitplCwBy@lxx6EsCabOLDZhP2QYvGvN91EG0xV6LAw7Mx7bx8zm05TwWTRNFZqLCTPYK3fVWV2b7bcckX78p4JywP/ywcXfVVxbYVZdMUkYbpMEko2JuOpcJXRiGe4kaRr/4Zrl9W@b4dtYp83UJIXZ9TNNpPZP0SwtEKcRe6j0rLunwrv2tbb7RB1pfUEJGYE6GksAcBsDJU1tTVuUgVqwxWghteXDxjP/hBXBICepgwdEWXLGxJX6yvi5S04bUJxY5Xsl3NsHlCmwmYcltpkWD3unn0fpYGSoaTtUr28UkA1HnhiACGG@cKlJcyjKFrAZIKB7zmUhznQ4QfBAOIYpnMH6BBerZxyTsnoYEMgIaAz5XlHvz1nY1Hr6TvNBSt08wM "C (clang) – Try It Online")** It's a pretty straightforward solution—and conceptually similar to [MegaTom's C version](https://codegolf.stackexchange.com/a/179088). In fact, you could write this in C as something like the following: ``` unsigned IsProthNumber(unsigned input) { --input; unsigned temp = (input & -input); temp *= temp; return (input < temp) ? -1 : 0; } ``` but the machine code above is better golfed than what you'll get out of a C compiler, even when it's set to optimize for size. The only "cheat" here is returning -1 as a "truthy" value and 0 as a "falsy" value. This trick allows the use of the 2-byte `SBB` instruction as opposed to the 3-byte `SETB` instruction. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 12 \log\_{256}(96) \approx \$ 9.88 bytes ``` zt1-s1_A&2^q ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZrqkoMdYsN4x3VjOIKIUJQmQWLjI0hLAA) or [generate all values up to 100](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSilLssiijakNtl6WlJWm6FmuqSgx1iw3jHdWM4gohQovto7whrAULIDQA). Port of Dennis's Jelly answer #### Explanation ``` zt1-s1_A&2^q # Implicit input zt # Triplicate 1-s # Decrement and swap 1_ # Subtract from 1 A& # Bitwise AND 2^ # Squared q # Is greater than the input? ``` [Answer] # Cjam, 11 bytes Like many of us, piggybacking off of Dennis's excellent solution: ``` qi_(_W*&2#< ``` [Try it online](http://cjam.aditsu.net/#code=qi_(_W*%262%23%3C&input=9) [Answer] # C (137 bytes) ``` int P(int N){int x=1,n=0,k=1,e=1,P=0;for(;e;n++){for(x=1,k=1;x&&x<N;k+=2){x=2<<n;x=x>k?x*k+1:0;if(x>N&&k==1)e=0;}if(x==N)P=1;}return P;} ``` Only came to read the answers after I tried it. Considering `N=k*2^n+1` with the conditional of `k<2^n` (`k=1,3,5..` and `n=1,2,3..` With `n=1` we have one `k` available to test. As we increase `n` we get a few more `k's` to test like so: n=1 ; k=1 n=2 ; k=1 k=3 n=3 ; k=1 k=3 k=5 k=7 ... Iterating through those possibilities we can be sure N is not a Prouth number if for a given `n` the `k=1` number obtained is larger than N and no other iteration was a match. So my code basically "brute-forces" its way into finding N. After reading the other answers and realizing you can factor N-1 with 2 to find `n` and then make the conditional of `k<2^n`, I think my code could be smaller and more efficient using this method. It was worth a try! *Tested all numbers given and a few "non-Prouth" numbers. Function returns 1 if the number is a Prouth number and 0 if it's not.* [Answer] # Javascript ES7, 16 bytes ``` x=>x--<(-x&x)**2 ``` Port of my Julia answer, which is a port of @Dennis's Jelly answer. *Thanks @Charlie for 2 bytes saved!* [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 17 bytes ``` x=>x--<(x=x&-x)*x ``` [Try it online!](https://tio.run/##NY2xCsIwFEX3fsWjiCSmKe1qmi6Ck4Lg4FxjAoGaQBPlldJvjwF1vOdyOCpw5Sed1DiEABdYihCHaBW8vX3AebCO0AwBjJ@IdRFQttUsW4Fd2zSNQMZofgGsIYYg/Q6A6xyiftYH74IfdX2bbNQn6zTZlMvM2LqHBdeSimIt/sWfcnw51eVSBXfvxx4MyISyR847ghK3HOkOUxbTBw "C# (.NET Core) – Try It Online") Port of [MegaTom's C answer](https://codegolf.stackexchange.com/a/179088/8340). I attempted a LINQ based solution, but this was too good. ]
[Question] [ Your task is to write a program which, given a number and a string, splits the string into chunks of that size and reverses them. ## Rules Your program will receive a positive integer `n`, as well as a string `s` with length at least one consisting of only printable ASCII (not including whitespace). The string should then be split into chunks of length `n`, if the length of the string isn't divisible by `n` any leftover at the end should be considered its own chunk. Then, reverse the order of the chunks and put them together again. ## Test Cases ``` n s Output 2 abcdefgh ghefcdab 3 foobarbaz bazbarfoo 3 abcdefgh ghdefabc 2 a a 1 abcdefgh hgfedcba 2 aaaaaa aaaaaa 2 baaaab abaaba 50 abcdefgh abcdefgh 6 abcdefghi ghiabcdef ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so you should aim for as few bytes as possible. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` sṚ ``` A full program that prints the result. **[Try it online!](https://tio.run/nexus/jelly#@1/8cOes////JyYlp6SmpWf8NwIA "Jelly – TIO Nexus")** ### How? ``` sṚ - Main link: string, number e.g. 'abcdefg', 3 s - split string into chunks of length number (keeping any overflow) ["abc","def","g"] Ṛ - reverse the resulting list ["g","def","abc"] - implicit print gdefabc ``` [Answer] # [Python 3](https://docs.python.org/3/), 35 bytes ``` f=lambda s,n:s and f(s[n:],n)+s[:n] ``` [Try it online!](https://tio.run/nexus/python3#XYxBDoMgEEXXcopZQmoabdMNiScxLAYBJbGjEVe9vB2pTWNnQd5/85ktNCM@rUNIJekESA6CTC1pU5K6pFaT2cK0wBjJQySYZk@yUloU2TR5cU3zGFepRDEvkVYZ5G7b2pSwxxwqo5TabgCAtnM@9AMj9IMPnUMr7hzCNFlcLL6Y@WVmkzfnL4wsRL4Fv0FR/1WHPnjXWfxU8xzVPFnbneyhOXD7UZ3PfPkN "Python 3 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5 4~~ 3 bytes -1 thanks to Dennis -1 thanks to carusocomputing ``` ôRJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8JYgr///jbgSk5JTUtPSMzIB "05AB1E – Try It Online") ``` # Implicit: push input ô # Split in pieces of length b RJ # Reverse and join ``` [Answer] ## JavaScript (ES6), 37 bytes ``` n=>F=s=>s&&F(s.slice(n))+s.slice(0,n) ``` Takes input by currying: number first, then string, like `f(2)("abcdefgh")`. ``` let f = n=>F=s=>s&&F(s.slice(n))+s.slice(0,n) let g = (n, s) => console.log(`f(${n})("${s}"): ${f(n)(s)}`) g(2, "abcdefgh") g(3, "foobarbaz") g(3, "abcdefgh") g(2, "a") g(1, "abcdefgh") g(2, "aaaaaa") g(2, "baaaab") g(50, "abcdefgh") ``` [Answer] # [Perl 6](https://perl6.org), ~~28~~ 20 bytes ``` {$^b.comb($^a).reverse.join} ``` [Try it](https://tio.run/nexus/perl6#XU7ZTsMwEHz3V4wqCyVKSA8ED41S8Q/wiCrZzuZAzaE4rYAq/HrYuIW2rOTR7OzsrPeWcHiKTCyqT9yZJiUk41FudWSaSntyq/yoowN1lqL3pqyHkX3PPdkeCXZlTdbzo0q1axwFUK3tHN5bGviML384j3kWyEWIb7mcYCUGsefLr5wTi3anagQuNBZZ053z7zfwIOsQ0vKjj5ZMTyl8d6m0mD7r8Vxa/2oeYnbaQbK5qDMxjCsASpuUsrxgirygzKRKiwdusqbRqtPqizkjc1bc5HaFKQvCZeFSSiz/WYs8o9RodbK6OltdOVlPTJ9lbtj9uLiN@eU/ "Perl 6 – TIO Nexus") ``` {[R~] $^b.comb($^a)} ``` [Try it](https://tio.run/nexus/perl6#XU7bSsNAFHzfrxjKIgmJ6UX0oSHFb1Df1MJek0JzoZuKWtJfjyfb2FoP7GHOzJw5u3cGHw@JSln5hRtVa4OsP7w@Hd/B1zJRdSkDvhZh15P@2BrXIsN2UxkXhEkpmiUODCiXborgTUch9edzn6akRXwW48jnQ1uwju3p4gvlpKzZigqRD02ZrXdj/u0KAXgVgzt65rMxqjUaob@0cRg@GZDOXfhHjzE57SBbXdgJ6/oFACGVNjYvCCIvjFVaSHZHg61rKXZSfBOmTpgYr1yvECSC@SxcSrD5P2uRW6OVFCerr9Hqy9NyQHKkaSD3/ew65hf/AA "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with placeholder parameters 「$a」 and 「$b」 [R[~]] # reduce the following using the reverse meta operator `R` # combined with the string concatenation operator # `comb` with a number splits the invocant into chunks of that size $^b.comb($^a) } ``` [Answer] # Bash + coreutils, 22 ``` fold -$1|tac|tr -d \\n ``` [Try it online](https://tio.run/nexus/bash#K8/IzElVKEpNTLFWSMnnKk4tUVAJcg3wieRKTc7IV1AxUqj5n5afk6Kgq2JYU5KYXFNSpKCbohATk/cfpIArJT8v9b@RgoJCYlJySmpaegaXMZCTlp@flFiUlFgF5sGlwOq4DDGEwADMTAKxkrhMDZCUAAA). [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` n#""="" n#s=n#drop n s++take n s ``` [Try it online!](https://tio.run/nexus/haskell#FcYxDoAgDAXQ3VP8tG6MzhymCkolVgLcv8Y3PTcmikSL8YjGqb8NhhHClJr/@SNqiGhdbWIFNjBI9iPl8yp6V/IP "Haskell – TIO Nexus") [Answer] # PHP, 53 Bytes ``` <?=join(array_reverse(str_split($argv[2],$argv[1]))); ``` [Answer] # [Röda](https://github.com/fergusq/roda), 36 bytes ``` f n{[[_]..[try head n-1]]|reverse|_} ``` [Try it online!](https://tio.run/nexus/roda#@5@mkFcdHR0fq6cXXVJUqZCRmpiikKdrGBtbU5RallpUnFoTX/s/NzEzT6GaizM5I7GoWEMpKREIkpQ0FWoU0jSMNK0VCooy80oUlJTgKtLy85MSi5ISq6CKjLEpSkxKTklNS8/AZxCaGkMi1JgaICuq/Q8A "Röda – TIO Nexus") It's a function that takes one argument. The characters of the string must be in the stream. `try` is used to discard errors in case that the `head` function can't read `n-1` values. Explanation: ``` f n{[[_]..[try head n-1]]|reverse|_} f n{ } /* Function declaration */ /* In a loop: */ _ /* Pull one value */ try head n-1 /* Pull n-1 values (or less) */ [ ]..[ ] /* Make an array */ [ ] /* Push it to the stream */ |reverse /* Reverse all values in the stream */ |_ /* Flat all arrays in the stream */ /* Characters in the stream are printed */ ``` Not as obfuscated as usually. I think it's quite beautiful. :) [Answer] # [CJam](https://sourceforge.net/p/cjam), 5 bytes ``` q~/W% ``` Input is a number and a string enclosed in double quotes, separated by whitespace. [Try it online!](https://tio.run/nexus/cjam#@19Ypx@u@v@/kYJSYlJySmpaeoYSAA "CJam – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/cjam#@1@dU6cfruoXX5v@/7@RgoKCUmJSckpqWnqGEpcxiJuWn5@UWJSUWAXlI6QhqpW4DLEJgwGUkwRiJylxmRogKwQA). ### Explanation ``` q~ e# Read all input and evaluate: pushes a number and a string / e# Split string into chunks of that size. Last chunk may be e# smaller. Gives an array of strings W% e# Reverse the array. Implicitly display ``` [Answer] ## Batch, 74 bytes ``` @if %2=="" (echo %~3)else set s=%~2&call %0 %1 "%%s:~%1%%" "%%s:~,%1%%%~3" ``` Rather annoyingly this ends up being recursive rather than tail recursive. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~13~~ 10 bytes ``` òÀ|lDÏpòÍî ``` [Try it online!](https://tio.run/nexus/v#@3940@GGmhyXw/0FQFbv4XX//ycmJaekpqVn/DcCAA "V – TIO Nexus") ``` ò ò ' Recursively À| ' Go to the "nth" column l ' Move one character right (breaks loop when no more chunks) D ' Delete from here to the end of the line Ï ' Add a line above the current line (now contains one chunk) p ' Paste the remainder of the line that was deleted Íî ' Remove all newlines ``` In Action: ``` abcdefghijkl ``` turns into ``` efghijkl abcd ``` which becomes ``` ijkl efgh abcd ``` before all newlines are removed [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 78 bytes ``` ,<<<+[[>]>+>[[>],<[<]>+>-]<-[->>[>]>>+<<<[<]<]>>]<<<<[[<]>[-[+.[-]]+>]<[<]<<<] ``` The first byte of the input is the chunk size, given by byte value. The rest of the bytes are considered to be the string. [Try it online!](https://tio.run/nexus/brainfuck#FYrJDcAwDMOAruO4EwhaRNCjZ7r/Aqn9EkFqDQAh0Qz2DAjNaaSS7MKoU@kKNJr7o1TsSjtKdgW81nac1/288/sB "brainfuck – TIO Nexus") **Expanded and commented** ``` Read the chunk size byte This cell will become a counter cell , Move left a few cells an increment; this is to make the starting position line up with the relative positioning needed to fit in with the loop <<<+ While the current cell is nonzero: [ Move right to the first zero cell [>] Move right once and increment and then move right to the counter cell The increment is required because of "move to zero cell" loops >+> This loop will store one chunk of the input in consecutive memory cells [ [>] Move right until a zero cell is hit , Store 1 byte of input there <[<] Move back left until a zero cell (other than the current one) is hit >+>- Increment the temporary cell by 1 and decrement the counter ] (end loop once the counter hits zero) Decrement the temp cell (because we needed to have 1 there initially to make the cell location work) <- Move the temp cell to three cells after the end of the chunk This is the new counter cell for the next chunk [->>[>]>>+<<<[<]<] Move two cells right from where the temp cell was This is the first cell of the chunk; if it's 0 then the input is finished and the loop should end >> ] Due to the way the counter is kept track of the tape head will always be four cells to the right of the last input cell when the loops breaks <<<< Now the chunks are printed one by one At the start of an iteration the tape head is at the end of a chunk [ Locate the start of the last chunk [<]> Print the chunk: [ Print the byte held in the current cell if it isn't 1 This is necessary because we left a stray 1 in a cell at the start which shouldn't be printed -[+.[-]]+ Move to the next cell > ] Move to just left of the chunk <[<] Move three cells over to the end of the next chunk <<< ] ``` [Answer] # PowerShell, ~~56~~ 49 bytes -7 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy) ``` param($n,$s)$s-split"(.{$n})"-ne''|%{$r=$_+$r};$r ``` [Try it online!](https://tio.run/##XZDhSsQwEIT/5ymWsmdatKIn@kM5uAcRjqRN2kJNayIo9vrsdS6pnOdCwuzk2yXMOHwaH1rT9wtb2tG0jMqrt5zdDYeCQxnGvvvI8tuJ3VxkpTNSHjcT@x0frtnPL@yXWeyl2BKR0lVtbNNCUtMaW9VKiwc0dhi08lp9Q@OGhhNfLkcgYaRddC4l7v@hbWNNXWmV0FgrGiva@qT0aqMB/Xh3ueZXi6c/TRe/0qVWyD2lDEi@OklH2tAkTrNIiDjgfCG2FeFDevKwrpAnOyDRyjiHW5p38MUziOxMSinm5Qc) [Answer] # Mathematica, 46 bytes ``` ""<>Reverse@Partition[Characters@#2,#,#,1,{}]& ``` Anonymous function. Takes a number and a string as input and returns a string as output. Not much to see here. [Answer] # **Javascript - ~~54~~ ~~47~~ 46 bytes** Remade: ``` (s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse() ``` Used as ``` f=(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse() alert(f("abcdefgh",2)); ``` Thank you to @ETHproductions for some RegEx quickenning Thank you to @Shaggy for an extra byte in the eval! Original: ``` (s,n)=>s.match(new RegExp('.{1,'+n+'}','g')).reverse() ``` [Answer] # Pyth, 5 bytes ``` s_c.* ``` [Try it online](https://pyth.herokuapp.com/?code=s_c.%2A&test_suite=1&test_suite_input=%5B%22abcdefgh%22%2C%202%5D%0A%5B%22foobarbaz%22%2C%203%5D%0A%5B%22abcdefgh%22%2C%203%5D%0A%5B%22a%22%2C%202%5D%0A%5B%22abcdefgh%22%2C%201%5D%0A%5B%22aaaaaa%22%2C%202%5D%0A%5B%22baaaab%22%2C%202%5D%0A%5B%22abcdefgh%22%2C%2050%5D&debug=0). ### Explanation ``` .* splat implicit input c split into chunks length n _ reverse s join ``` [Answer] # [Retina](https://github.com/m-ender/retina), 38 bytes *1 byte saved thanks to @LeakyNun* ``` ^ +`(.* (1)+¶)((?<-2>.)+) $3$1 1+¶ ``` (Note the space on the second line, and the trailing space) This program takes input as unary on the first line, and the string on the second. [Try it online!](https://tio.run/nexus/retina#@x/HpcClnaChp6WgYaipfWibpoaGvY2ukZ2eprYml4qxiiGXgiFQmOv/f0NDrsSk5JTUtPQMAA "Retina – TIO Nexus") [Test Suite! (slightly modified)](https://tio.run/nexus/retina#U9VwT/gfx6XApZ2goaeloGGoqW2tqaFhb6NrZKenqa3JpWKsYsilYKhtzfX/v6GhdWJSckpqWnoGlyGQk5afn5RYlJRYBeYhSVkncqHxwQDESgIxkkAaSARw8wA "Retina – TIO Nexus") ### Explanation The first step is to prepend a space (will become important later on). ``` ^ ``` Now we reverse. This uses .NET's balancing groups. It is important to note that groups here act as stacks, so every match is essentially pushed onto the stack. Here we capture every digit in the unary number into group 2. Now each time a character in the string is found, a match is popped from group 2. This ensures the the number of characters does not exceed that of the unary number. ``` +`(.* (1)+¶) Capture the unary number in group 2 ((?<-2>.)+) Balancing group for substrings $3$1 Reverse ``` And finally remove the unary number and the newline. ``` 1+¶ ``` [Answer] ## Java, 147 138 Bytes `String r(String s,int n){String r="";int l=s.length();for(int i=l/n*n;i>=0;i-=n)if(!(i>=l))r+=(i+n)>=l?s.substring(i):s.substring(i,i+n);return r;}` Saved 9 Bytes thanks to Kevin Cruijssen! ``` String r(String s,int n){String r="";int l=s.length(),i=l/n*n;for(;i>=0;i-=n)if(i<l)r+=i+n>=l?s.substring(i):s.substring(i,i+n);return r;} ``` In expanded form: ``` String r(String s,int n){ String r=""; int l=s.length(),i=l/n*n; for(;i>=0;i-=n) if(i<l) r+=i+n>=l?s.substring(i):s.substring(i,i+n); return r; } ``` This is actually my first try to codegolf ever, so any feedback is welcome! [Answer] # [Perl 5](https://www.perl.org/), 25 bytes Uses the `-lnM5.010` flags. ``` say reverse<>=~/.{1,$_}/g ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVKhKLUstag41cbOtk5fr9pQRyW@Vj/9/38jrsSk5JTUtPSMf/kFJZn5ecX/dXPyfE31DAwNAA "Perl 5 – Try It Online") Shoutout to Grinnz for telling me about `=~ m/.{1,$n}/g` `-M5.010` enables the use of the `say` function, which for our purposes is print with a shorter name. `-n` puts the first line of input into `$_`, and `-l` chomps off the trailing newline. We then get the second line of input using `<>`, and apply it to the regex `.{1,$_}`: any character, between 1 and $\_ (the first input) times. Since this is greedy by default, it tries to always match $\_ characters. The `1,` is needed for the possible leftover chunk at the end. The `/g` modifier gives us *every* match of that regex in the input string as a list, which is then reversed and printed. In Perl, passing a list to `say` joins it without any delimiter by default. [Answer] # [Dyalog APL Extended](https://github.com/abrudz/dyalog-apl-extended), ~~16~~ 15 bytes ``` {∊⌽⍵⊂⍨(≢⍵)⍴=⍳⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qZv6jtgkG/9OAZPWjjq5HPXsf9W591NX0qHeFxqPORUCO5qPeLbaPejc/6t1V@/@/gpFCmoJ6YlJySmpaeoY6l4IxiJ@Wn5@UWJSUWAUTQFIA0qCjnghkGWKRUU8EAxgvCcRJUucyNUBRCwA "APL (Dyalog Extended) – Try It Online") [Answer] # Python, 62 bytes ``` lambda n,s:''.join([s[i:i+n]for i in range(0,len(s),n)][::-1]) ``` [Try it online!](https://tio.run/nexus/python2#TcjBDoIwDADQu1/RW7dYDZB4WeKXzB062aAECtn8/@nFhHd8@flqK29xZFCqDvG@7KLGVy9OrhryXkBAFArrlExHa1JTLakN3rlbH2w7iugHshkII/9EtJf/PTpCju8x5Wk@9XDe9gU "Python 2 – TIO Nexus") [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 9 bytes ``` #<rev''#` ``` [Try it online!](https://tio.run/nexus/stacked#U09MSk5JTUvPUFcw@q9sU5Rapq6unPA/v7TkPwA "Stacked – TIO Nexus") `#<` chunks, `rev` reverses, and `''#`` joins by empty string. Quite simple. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 24 bytes ``` :;[1,_lA|,a|Z=_sA,b,a|+Z ``` This makes excellent use of the new substring-function I recently added to QBIC: ``` :; Read in the cmd line params a (number) and A$ (text) [1,_lA|,a| Set up a FOR loop: FOR b = 1; b <= A$.length; b += a Z= Modify Z$; Z$ is autoprinted at the end of QBIC code _sA,b,a| SUBSTRING: _s is the function followed by the string to take from, the starting pos and the # of chars +Z Take chunks from further into A$, put them before Z$ ``` [Answer] # Pyth, 4 bytes ``` s_cF ``` Takes input as `"s",n`: [Try it for yourself!](http://pyth.herokuapp.com/?code=s_cF&input=%22abcdefgh%22%2C2&debug=0) [Answer] # [Convex](https://github.com/GamrCorps/Convex), 2 bytes ``` /¥ ``` [Try it online!](https://tio.run/nexus/convex#@69/aOn///@V0vLzkxKLkhKrlP4bAwA "Convex – TIO Nexus") [Answer] ## C, 69 bytes ``` i;f(s,n)char*s;{i=strlen(s);for(i-=i%n;printf("%.*s",n,s+i),i;i-=n);} ``` Result is printed out to the standard output. [Answer] # Scala, 57 55 bytes ``` (n:Int,s:String)=>(""/:s.grouped(n).toSeq.reverse)(_+_) ``` Thanks Jacob! Try it [here](http://www.scala-repl.org/code/welcome). Note: By using the symbol form of foldLeft ("/:"), I was able to take off a couple more bytes. [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 5 bytes ``` σ]QWJ ``` [Try it online!](https://tio.run/##y8/I/f//fHNsYLjX//9p@flJiUVJiVVcxgA "Ohm – Try It Online") ### Explanation ``` σ]QWJ σ # Split input1 into input2 pieces ] # Flatten array Q # Reverses stack W # Wraps stack to array J # Joins stack # Implicit print ``` [Answer] # [R](https://www.r-project.org/), ~~69~~ 60 bytes ``` function(s,n)cat(substring(s,(x=nchar(s):0*n)+1,x+n),sep="") ``` [Try it online!](https://tio.run/##Dcg7DoAgDADQqximVmqii4ORwwDyW6qhkHh79I2vjjidy4idfSs3gxCjtw2kO2m1cPoHXsM@2wqCxzoz6o1ezUgSHqMUjgjKOn@FmHJRtOP4AA "R – Try It Online") Thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) for the suggestion to remove `seq`. ]
[Question] [ Surprisingly we haven't had a simple "find the highest digit" challenge yet, but I think that's a *little* too trivial. Given input of a non-negative integer, return the highest **unique** (ie not repeated) digit found in the integer. If there are no unique digits, your program can do anything (undefined behaviour), other than the numbers that are non unique in the input of course. The input can be taken as a single integer, a string, or a list of digits. ## Test cases ``` 12 -> 2 0 -> 0 485902 -> 9 495902 -> 5 999999 -> Anything 999099 -> 0 1948710498 -> 7 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes Saved 1 byte thanks to *Mr. Xcoder* notifying that a digit list is valid input. ``` ¢ÏM ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0KLD/b7//0eb6ChY6iiYgkkDHQWjWAA "05AB1E – Try It Online") **Explanation** ``` ¢ # count occurrences of each digit in input Ï # keep only the digits whose occurrences are true (1) M # push the highest ``` [Answer] # [Python 3](https://docs.python.org/3/), 40 bytes Saved 2 bytes thanks to [movatica](https://codegolf.stackexchange.com/users/86751/movatica). ``` lambda i:max(x*(i.count(x)<2)for x in i) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHTKjexQqNCSyNTLzm/NK9Eo0LTxkgzLb9IoUIhM08hU/N/QVEmUDhNQ93Q0sTC3NDAxNJCXVNTQUHZnAsuZWJhamlgBBYGAWVLhJQBXBQiZYCQsrS0NLC0ROhClbJElgr1c3F18/RzdfkPAA "Python 3 – Try It Online") ### 42 bytes Works for both String and list of digits parameter types. Throws an error for no unique digits, kind of abuses of that spec: ``` lambda i:max(x for x in i if i.count(x)<2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHTKjexQqNCIS2/SKFCITNPIVMhM00hUy85vzSvRKNC08ZI839BUSaQnaahbmhpYmFuaGBiaaGuqamgoGzOBZcysTC1NDACC4OAsiVCygAuCpEyQEhZWloaWFoidKFKWSJLhfq5uLp5@rm6/AcA "Python 3 – Try It Online") --- ## Explanation * `lambda i:` - Declares a lambda function with a string or list of digits parameter i. * `max(...)` - Finds the maximum value of the generator. * `x for x in i` - Iterates through the characters / digits of `i`. * `if i.count(x)<2` - Checks if the digit is unique. [Answer] ## [Alice](https://github.com/m-ender/alice), 15 bytes ``` /&.sDo \i-.tN@/ ``` [Try it online!](https://tio.run/##S8zJTE79/19fTa/YJZ8rJlNXr8TPQf//f0NLEwtzQwMTSwsA "Alice – Try It Online") ### Explanation ``` /... \.../ ``` This is a simple framework for linear code that operates entirely in Ordinal mode (meaning this program works completely through string processing). The unfolded linear code is then just: ``` i..DN&-sto@ ``` What it does: ``` i Read all input as a string. .. Make two copies. D Deduplicate the characters in the top copy. N Get the multiset complement of this deduplicated string in the input. This gives us a string that only contains repeated digits (with one copy less than the original, but the number of them doesn't matter). &- Fold string subtraction over this string, which means that each of the repeated digits is removed from the input. s Sort the remaining digits. t Split off the last digit. o Print it. @ Terminate the program. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 16 bytes ``` O`. (.)\1+ !`.$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3z9Bj0tDTzPGUJuLSzFBT@X/f0MjLgMuEwtTSwMjLhNLMGVpaWlgacllaGliYW5oYGJpAQA "Retina – Try It Online") ### Explanation ``` O`. ``` Sort the digits. ``` (.)\1+ ``` Remove repeated digits. ``` !`.$ ``` Fetch the last (maximal) digit. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 12 bytes ``` Fχ¿⁼№θIι¹PIι ``` [Try it online!](https://tio.run/##NclLCoAgEADQq7icAQUFIaWltOwQEkgDkvnr@lObtu8dZ2xHiZk5lSbAaBSUBGx1xtwhlHkNqDLEPoAQpUEU@8yD7kbf/L4yG2/dYrT1jtXDqucX "Charcoal – Try It Online") (Link to verbose version) Prints nothing if no solution is found. The trick is that the `for` loop prints every unique number in the input string, but without moving the cursor, thus the value keeps reprinting itself until the final solution is found. The previous version printed the characters A to Z when no solution was found, hence the comments: ``` AααFχA⎇⁼№θIι¹Iιααα ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jUUchUdOaKy2/SEHD0EBTASocklqUl1hUqeFaWJqYU6zhnF@aV6JRqOOcWFyikampqWOoqaMA5egkgpA1V0BRJlANkPX/v6GliYW5oYGJpcV/3bL/usU5AA "Charcoal – Try It Online") (Link to verbose version) [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` →fo¬hgO ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8dC2/4/aJqXlH1qTke7///9/QyMuAy4TC1NLAyMuE0swZWlpaWBpyWVoaWJhbmhgYmkBEgECAA "Husk – Try It Online") (Test suite, crashes on the last test case since it has no unique digits) This is a composition of functions in point-free style (the arguments are not mentioned explicitely anywhere). Takes input and returns output as a string, which in Husk is equivalent to a list of characters. ### Explanation ``` Test case: "1948710498" O Sort: "0114478899" g Group consecutive equal elements: ["0","11","44","7","88","99"] fo¬h Keep only those with length 1*: ["0","7"] → Take the last element: "7" ``` \*The check for length 1 is done by taking the head of the list (all elements except the last one) and negating it (empty lists are falsy, non-empty lists are truthy). [Answer] ## JavaScript (ES6), ~~46~~ ~~41~~ 40 bytes Takes input as a string. Returns RangeError if there are no unique digits. ``` s=>f=(i=9)=>s.split(i).length-2?f(--i):i ``` -7 bytes thanks to Rick Hitchcock -1 byte thanks to Shaggy ### Test cases ``` let f = s=>g=(i=9)=>s.split(i).length-2?g(--i):i console.log(f("12")()) // 2 console.log(f("0")()) // 0 console.log(f("485902")()) // 9 console.log(f("495902")()) // 5 //console.log(f("999999")()) // RangeError console.log(f("999099")()) // 0 console.log(f("1948710498")()) // 7 ``` [Answer] ## Haskell, 37 bytes ``` f s=maximum[x|x<-s,[x]==filter(==x)s] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2DY3sSIztzQ3uqKmwka3WCe6ItbWNi0zpyS1SMPWtkKzOPZ/bmJmnoKtQkFRZl6JgopCmoKSoaWJhbmhgYmlhdJ/AA "Haskell – Try It Online") How it works: ``` [ |x<-s ] -- loop x through the input string s x -- and keep the x where [x]==filter(==x)s -- all x extracted from s equal a singleton list [x] maximum -- take the maximum of all the x ``` [Answer] # [R](https://www.r-project.org/), 41 bytes ``` function(x,y=table(x))max(names(y[y==1])) ``` An anonymous function that takes a list of digits, either as integers or single character strings. It precomputes `y` as an optional argument to avoid using curly braces for the function body. Returns the digit as a string. This takes a slightly different approach than [the other R answer](https://codegolf.stackexchange.com/a/128874/67312) and ends up being the tiniest bit shorter! looks like my comment there was wrong after all... `table` computes the occurrences of each element in the list, with `names(table(x))` being the unique values in `x` (as strings). Since digits are fortunately ordered the same lexicographically as numerically, we can still use `max`. [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqfStiQxKSdVo0JTMzexQiMvMTe1WKMyutLW1jBWU/N/mkayhomOqY4xGFoCobmOOVAcAA "R – Try It Online") [Answer] # Python 3, 40 bytes ``` lambda i:max(x+9-9*i.count(x)for x in i) ``` Only works for lists of digits. The edge case '990' works fine :) [Try it online!](https://tio.run/##dc9NCsIwEAXgvacYyCbRqaSttR3Bk6iLqAQD9odSIZ4@piBttenMbvh4vGne3aOuUqePZ/dU5fWuwBxKZbndUERrs73Vr6rjVui6BQumAiNc0xp/0/wUY3IRAgLDIFkNTC6gnsmR7bDADAnlLJUBTRktsmxkhMPOWJTu/6EMwkm72IO@YY6xx32J4ssZ5L9p4X99mvsA) [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` ►≠O ``` [Try it online!](https://tio.run/##yygtzv7//9G0XY86F/j///8/2kTHUscUiA10jGIB "Husk – Try It Online") ## Explanation ``` ►≠O O order the elements ► max by ≠ inequality(selects least frequent elements) then returns the last of the least frequent elements ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ọtᵒtᵍhth ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3pKHWycBcW9GScb//4aWJhbmhgYmlhb/owA "Brachylog – Try It Online") ### Explanation ``` Example input: 495902 ọ Occurences: [[4,1],[9,2],[5,1],[0,1],[2,1]] tᵒ Order by tail: [[0,1],[2,1],[4,1],[5,1],[9,2]] tᵍ Group by tail: [[[0,1],[2,1],[4,1],[5,1]],[[9,2]]] h Head: [[0,1],[2,1],[4,1],[5,1]] t Tail: [5,1] h Head: 5 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 chars = 19 bytes Method: multiply elements that occur multiple times by zero, and then fine the highest element. ``` ⌈/×∘(1=≢)⌸ ``` `⌸` for each unique element and its indices in the argument:  `×` multiply the unique element  `∘(`…`)` with:   `1=` the Boolean for whether one is equal to   `≢` the tally of indices (how many times the unique element occurs) `⌈/` the max of that [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@NR24RHPR36h6c/6pihYWj7qHOR5qOeHUCJQys0DBWMNBU0dAyAhImChYKpgqWCAVjIBMhC8CwV4BDOM4DyDIE0SK@5giFQDKTPQhMA "APL (Dyalog Unicode) – Try It Online") # [APL (Dyalog Classic)](https://www.dyalog.com/), 15 bytes ``` ⌈/×∘(1=≢)⎕U2338 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/41HbhEc9HfqHpz/qmKFhaPuoc5Hmo76poUbGxhZA2UMrNAwVjDQVNHQMgISJgoWCqYKlggFYyATIQvAsFeAQzjOA8gyBNEivuYIhUAykz0ITAA "APL (Dyalog Classic) – Try It Online") Identical to the above, but uses `⎕U2338` instead of `⌸`. [Answer] ## [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes *Thanks to Leo for suggesting a slightly neater solution at the same byte count.* ``` ▲‡ȯf=1`# ``` [Try it online!](https://tio.run/##yygtzv7//9G0TY8aFp5Yn2ZrmKD8//9/JUNLEwtzQwMTSwslAA "Husk – Try It Online") ### Explanation ``` ȯ Compose the following thre functions into one binary function. `# Count the occurrences of the right argument in the left. =1 Check equality with 1. This gives 1 (truthy) for values that appear uniquely in the right-hand argument. f Select the elements from the right argument, where the function in the left argument is truthy. Due to the composition and partial function application this means that the first argument of the resulting function actually curries `# and the second argument is passed as the second argument to f. So what we end up with is a function which selects the elements from the right argument that appear uniquely in the left argument. ‡ We call this function by giving it the input for both arguments. So we end up selecting unique digits from the input. ▲ Find the maximum. ``` [Answer] # Mathematica, 41 bytes ``` (t=9;While[DigitCount[#][[t]]!=1,t--];t)& ``` thanks @Martin Ender here is Martin's approach on my answer # Mathematica, 35 bytes ``` 9//.d_/;DigitCount[#][[d]]!=1:>d-1& ``` [Answer] ## R, ~~45~~ 43 bytes `function(x)max(setdiff(x,x[duplicated(x)]))` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jQjM3sUKjOLUkJTMtTaNCpyK6PCMzOUMjpbQgJzM5sSQ1BahEM1ZTkytNI1nDRMdUxxgMLYHQXMdcU/P/fwA) Takes input as a vector of integers. Finds the duplicated elements, removes them, and takes the maximum. (Returns `-Inf` with a warning if there is no unique maximum.) Edited into an anonymous function per comment [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda l:max(1/l.count(n)*n for n in l) ``` [Try it online!](https://tio.run/##VYzNCoMwEITP@hRzTEqwiViqgk9iPdgfMRDXIJG2T59KAraFWZj5hh37duNMuR@aizf9dL33MPXUv5g6muw2r@QY8QNhmBcQNMFw/xy1eUDVaWIaTXZ1jKeJXTQ5DGzrWyWQd2krtysESoGTQCUgIy5C@ENVCF/9IrkjFVxcPAuo0MW1cv@Q3Qc "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->x{(?0..?9).select{|r|x.count(r)==1}[-1]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iWsPeQE/P3lJTrzg1JzW5pLqmqKZCLzm/NK9Eo0jT1tawNlrXMLb2f4FCWrS6oaWJhbmhgYmlhXosF1jExMLU0sAIxjOAMSwtLQ0sLZF4liDefwA "Ruby – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~30~~ 28 bytes -2 bytes thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) ``` fold -1|sort|uniq -u|tail -1 ``` [Try it online!](https://tio.run/##S0oszvifVpqXXJKZn6eQm1gRX5qXWahQrZCanJGvoGKoUPM/vSi1QEE3X0Gvpji/qKQGLK9bWlOSmJmjoGv4v5aLC67N0AjBNkAwTSxMLQ2QpEwsUfmWYIDCN0DmG1qaWJgbGphYWvyHaAUA "Bash – Try It Online") --- ### [Bash](https://www.gnu.org/software/bash/) + coreutils, 20 bytes ``` sort|uniq -u|tail -1 ``` [Try it online!](https://tio.run/##S0oszvifVpqXXJKZn6eQm1gRX5qXWahQrZCanJGvoGKoUPM/LT8nRUHXsKY4v6ikBiyrW1pTkpiZAxT8X8vFBddkaIRgGyCYJhamlgZIUiaWqHxLMEDhGyDzDS1NLMwNDUwsLf5DtAIA "Bash – Try It Online") If input is given as a list of digits, one per line, we can skip the fold stage. That feels like cheating though. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 27 97 86 58 57 75 bytes ``` using System.Linq; n=>n.GroupBy(i=>i).Where(i=>i.Count()<2).Max(i=>i.Key)-48 ``` [Try it online!](https://tio.run/##TY7BCsIwEETv/Yo9JqBBpWCltgcFPaggevAc4qoL7UaTVCzit9dWEbzNDDOPMb5vrMOm8sRn2Nc@YJlG/06tiW9pZArtPWydPTtdPiMAH3QgA3dLR9hoYiG7FGBRsZn64FpCjzjkcIKs4SxntXS2us5qQVlOUh0u6PCj1dxWHIScjqTa6Mc3W2Et@3HSdMj0A55b9rZAdXAUUJzEz@9QH9uPKKSUXfMVvZrhJE7Gw0E8SdrhGw "C# (.NET Core) – Try It Online") Thanks @CarlosAlejo [Answer] # [<>< (Fish)](https://esolangs.org/wiki/Fish), 93 bytes ``` 0l1-l2-$:?v~~o; v&]{[-3lr < |.!01~$r&\ >r$1-:?!v$rl3-[{]:&:&=?^ @&::&:$~/|.!01 $}&~$?( ``` [Try it in my interpreter](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMGwxLWwyLSQ6P3Z+fm87XG52Jl17Wy0zbHIgPCAgIHwuITAxfiRyJlxcXG4+ciQxLTo/IXYkcmwzLVt7XTomOiY9P15cbkAmOjomOiR+L3wuITAxICR9Jn4kPyhcbiAgICAiLCJpbnB1dCI6IiIsInN0YWNrIjoiMTQ0MjIiLCJtb2RlIjoiY2hhcnMifQ==) [Found a fun bug in my interpreter testing this](https://github.com/mousetail/Fish/commit/aef7487c6fe7c54eee4659f9e04be968abd1c781) Expects input pre-pushed to the stack ## Explanation [![enter image description here](https://i.stack.imgur.com/a6zsC.png)](https://i.stack.imgur.com/a6zsC.png) Top row: Setup. Push 0, the current maximum, l-1, the total number of iterations of the outer loop, and l-2, the total number of iterations in the inner loop. Initially both are the same. Second row left: Shift left 1, then move the top item to the register. This is the candidate largest member. Third row: Compare the register for each digit. If none match go down. Otherwise go up to second row right. Second row right: Reset, then try another digit. This happens if the digit is equal to another. Last row: We have found a unique digit! Now we check if it's better than the current max value, if so replace it. Then reset and jump to the start. [Answer] ## JavaScript (ES6), ~~52~~ 50 bytes Takes input as a list of digits. Returns `0` if there are no unique digits. ``` s=>s.reduce((m,c)=>m>c|s.filter(x=>x==c)[1]?m:c,0) ``` ### Test cases ``` let f = s=>s.reduce((m,c)=>m>c|s.filter(x=>x==c)[1]?m:c,0) console.log(f([1,2])) // 2 console.log(f([0])) // 0 console.log(f([4,8,5,9,0,2])) // 9 console.log(f([4,9,5,9,0,2])) // 5 console.log(f([9,9,9,9,9,9])) // (0) console.log(f([9,9,9,0,9,9])) // 0 console.log(f([1,9,4,8,7,1,0,4,9,8])) // 7 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~89~~ ~~85~~ 79 bytes ``` a->{int i=10,x[]=new int[i];for(int d:a)x[d]++;for(;i-->0&&x[i]!=1;);return i;} ``` [Try it online!](https://tio.run/##nY8/b4MwEMX3fIrrEoFiLKhSNakLUpdKHTqlG/Lg8ic6SmyETUqE@OzURrR7kQfr7t3v3rtKXEWgmkJW@dfUdJ81ZpDVQmt4Fyhh2AAsXW2Esd9VYQ4Xq3kn06I8pxxEe9b@PApQ2X20M1jTspOZQSXph3qT5nWpnlGalCdQQjyJIBlsCRhHIelTHsviG5yOnJWq9ZyWPwm/T3O@280thkGQhNttb2fu4oj5rC1M10pANk7On80pTjdtigtVnaGNDWlq6ZVUNE19e9E2jPdrxIeI3I@@/18qXMHsyYE8kCMJVznuLbmePpK/t5oOV9KR5dztjySyO9wdh2XLuBmnHw "Java (OpenJDK 8) – Try It Online") -6 bytes thanks to @KevinCruijssen's insight! [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes -2 thanks toTwiNight. ``` ⌈/⊢×1=(+/∘.=⍨) ``` `⌈/` the largest of `⊢` the arguments `×` multiplied by `1=(`…`)` the Boolean for each where one equals  `+/` the row sums of  `∘.=⍨` their equality table [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@NR24TqRz0d@o96twLxCkNbbf1HHTP0bIFsoFAtUMWhFRqGCkaaChoGQGyiYKFgqmCpYAAWMQGyEDxLBUswG0gCeYZAGqTaXMEQKAZSaaHJlQFTBYaaAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [PHP](https://php.net/), 40 bytes ``` <?=array_flip(count_chars($argn))[1]-48; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGhpYmFuaGBiaaFkzWVvB5S1TSwqSqyMT8vJLNBIzi/NK4lPzkgsKtYAa9DUjDaM1TWxsP7/HwA "PHP – Try It Online") # [PHP](https://php.net/), 42 bytes ``` <?=chr(array_flip(count_chars($argn))[1]); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGhpYmFuaGBiaaFkzWVvB5S1Tc4o0kgsKkqsjE/LySzQSM4vzSuJT85ILCrWAGvS1Iw2jNW0/v8fAA "PHP – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 67 bytes ``` s->{int i=9;for(s=" "+s+" ";s.split(i+"").length!=2;i--);return i;} ``` [Try it online!](https://tio.run/##jY6xboNADIb3PIV7E4hygYiqWFcyVurQKWPV4UqAml4OxJlIUcSz06uKsobFsvx/@v21@qzj9vgz9@OXoRJKo52Dd00WrhsAx5r9tfWUHJmMrEdbMnVWvi7Ly4EHss0jvFmummrYQw0FzC7eX8kyUIGq7obAFQJE5CI/lZOuN8QBRUKE0lS24e@HYqcojkM1VDwOFkhNs9p4g8VrETl3dISTtwv@3358gg7/RAEOF8fVSXYjy95HbGxQS9335hKIdCfCUN3FklVUlj9hsq4ww9UoIiaIq9AUs/w5TTLMb/h2e6cbb93TZpp/AQ "Java (JDK) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~16~~ 12 bytes ``` 0{\:~-.}./.~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DapjrOp09Wr19PXq/msqcKUmZ@QrqJuqK9gqpCkoWSkYGhmbmBoZQ8UtkMQtLYEyFnApc4SUpYmFuaGBiaUFzDgDuJylpaWBpaXCfwA "J – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~12~~ ~~11~~ ~~10~~ 4 bytes I/O as a digit array. ``` ü l1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=/CBsMQ&input=WzEsOSw0LDgsNywxLDAsNCw5LDhd) [Answer] **APL ([NARS2000](http://www.nars2000.org/)) 16 chars, 23(?) bytes** ``` {↑⌽⍸1=+⌿⍵∘.=⍳10} ``` (input as array of digits, e.g. {↑⌽⍸1=+⌿⍵∘.=⍳10}4 9 5 9 0 2) [Answer] # [Desmos](https://desmos.com/calculator), 113 bytes ``` U(l)=max([min([\left\{l[n]=l[i]:-1,l[n]\right\} for i=join([0...n-1],[n+1...l.length+1])]) for n=[1...l.length]]) ``` Takes input as a list. [Try it out and see versions that make slightly more sense](https://www.desmos.com/calculator/xy4naheu1w) ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/25967/edit). Closed 7 years ago. [Improve this question](/posts/25967/edit) I know there is an (old) thread similar to this ([here](https://codegolf.stackexchange.com/questions/245/print-a-random-maze)), but I'd like to reboot it with some modifications. The goal: generate a random-*looking* maze using an algorithm of your choice, then output the maze graphically (printing counts). * The width and height are determined by you. * There should be at least one path from at least one entrance to at least one exit. * The format of the maze (how you display it, mark entrance(s) or exit(s)) is up to you as well. * The prettier, the better. * Trivial mazes (e.g. blank mazes, lattice mazes, mazes of size 1x1) are discouraged. * Cycles in the maze are allowed and, are encouraged, if the result is reasonable. * Language abuse encouraged. * The maze should look reasonably random (but a completely deterministic (e.g. chaotic) algorithm that generates this is fine too). Edit: the main focus here is on making the smallest possible implementation. However, I want to allow some leeway within that constraint to encourage shininess. I have deliberately left exactly what "features" the maze has open-ended, but as a rough guideline you should try to pack the most amount of bang into the least lexical buck. [Answer] ## Mathematica, ~~144~~ 132 bytes Since Inception, we all know [the most efficient way to draw a maze](https://i.stack.imgur.com/C3KFz.jpg). ``` c=0;Graphics@Most[Join@@{Circle[{0,0},i,{a=c-(r=Random[](d=2Pi-1/i)&)[],a+d}],Line[{{i},{i+1}}.{{Cos[c=a+r[]],Sin@c}}]}~Table~{i,9}] ``` Ungolfed and example output: ![enter image description here](https://i.stack.imgur.com/jsLnH.png) Of course, the lines are the walls. You're the minotaur who starts in the centre and needs to get out. [Answer] # C: 364 Bytes ``` #define I int m[1600],i=0,r;f(I x,I y,I l){m[80*y+x]|=l;I d[]={x-1,y,2,1,x+1,y,1,2,x,y-1,8,4,x,y+1,4,8}, s[]={5,5,5,5},j=0;for(;j<4;){L:r=rand()%4;for(I k=0;k<4;)if(s[k++]==r)goto L;s[j]=r;I*p=d+ 4*s[j++],X=p[0],Y=p[1];if(!(X<0|X>79|Y<0|Y>19|m[80*Y+X])){f(X,Y,p[2]);m[80*y+x]|=p[3];}}} main(){f(0,0,4);m[9]|=4;for(;i<1600;)putchar("#5FMP<HJR;IK:9LN"[m[i++]]+128);} ``` Note: in the above, I added newlines to make it fit on the page. Expected output (on 80-character terminal) (note start and end at top left): ![enter image description here](https://i.stack.imgur.com/kxTzp.png) [Answer] # Mathematica, ~~134~~ 130 chars ``` Graph[Range@273,Reap[Do[c@n/._c:>#0[Sow[#<->n];n],{n,RandomSample@AdjacencyList[g=GridGraph@{13,21},c@#=#]}]&@1][[2,1]],Options@g] ``` ![maze](https://i.stack.imgur.com/hIYTL.png) --- In fact, we can use this algorithm to generate a maze from any (undirected) graph. For example, generate a maze from the 8\*8 [knight's tour graph](http://en.wikipedia.org/wiki/Knight_tour_graph) (`KnightTourGraph[8,8]`): ![knight's tour graph](https://i.stack.imgur.com/XXXYA.png) ``` Graph[Range@64,Reap[Do[c@n/._c:>#0[Sow[#<->n];n],{n,RandomSample@AdjacencyList[g=KnightTourGraph[8,8],c@#=#]}]&@1][[2,1]],Options@g] ``` ![maze2](https://i.stack.imgur.com/IATJF.png) [Answer] # Bash, 53 50 bytes ``` w=(╱ ╲);while :;do echo -n ${w[RANDOM%2]};done ``` Similar idea to the C64 code. Uses Unicode characters as the slashes because they look much nicer in a terminal that supports Unicode. Sample output on OS X Terminal (Menlo font): ![Sample maze output](https://i.stack.imgur.com/fRX05.png) [Answer] # C: 265 253 Bytes ``` #define f(v)for(v=0;v<k;++v) #define d(q,n)case q:r(c+n,c+2*n); z[4225],i,j,k=65;r(p,c){if(!z[c]){z[p]=z[c]=1;f(p)switch(rand()%4){d(0,-k)d(1,k)d(2,-1)d(3,1)}}}main(){f(i)z[i]=z[i+4160]=z[i*k]=z[i*k+64]=z[4157]=1;r(67,132);f(i)f(j)putchar(33-z[i*k+j]);} ``` (Requires 65-character terminal) Generates a relatively random 31x31 maze with one guaranteed path from the entrance to exit. Example output (with simulated 65-character terminal): ``` ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! !!!!! !!! !!! ! !!! ! !!! ! !!! !!!!!!! !!! !!!!!!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!! ! !!!!!!! ! ! ! ! ! ! !!!!!!! !!! ! !!!!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!! !!!!!!!!!!!!!!!!! !!!!! !!! !!! !!! ! ! !!! !!! !!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!! ! ! !!! !!! ! !!!!!!!!!!!!! ! !!! ! !!!!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!! !!!!!!! !!!!!!! ! !!!!!!!!!!!!!!! !!!!!!! !!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!! ! ! ! ! !!!!!!! ! ! ! !!!!!!!!! ! ! !!!!!!! ! ! !!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!! ! !!!!! !!!!!!! ! !!!!!!! !!!!!!!!! !!! !!!!! ! !!! ! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! ! ! ! !!!!!!!!! ! !!!!! !!! !!!!! !!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!! !!! ! ! ! !!! !!!!!!! ! !!!!!!! ! ! !!!!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!!!! !!! !!!!!!! ! !!!!! ! !!! !!!!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!!!! ! ! ! !!! !!!!!!! !!!!!!!!! !!! !!! !!! ! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!!!!!! ! ! ! !!! ! ! ! ! !!! !!!!!!! !!! !!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! ! ! !!! !!! ! ! !!!!!!! !!!!!!! ! ! !!! ! !!!!!!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!! !!! !!!!!!!!!!! !!!!!!! ! ! ! !!!!!!! ! !!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!! !!!!!!!!!!! ! !!! !!!!!!! ! !!!!! ! !!! !!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!! !!!!! ! !!! !!! !!!!!!! ! !!!!! ! ! !!!!! ! !!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!! !!!!! ! !!! !!! !!!!!!! ! !!!!!!!!! !!!!!!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!! ! !!! !!! ! ! ! !!! ! ! !!!!! !!! ! !!! ! !!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!! !!!!!!!!!!!!! ! !!! !!!!!!!!!!! ! ! ! ! !!! ! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!! !!! !!!!!!!!!!!!! ! ! ! !!! ! !!!!!!! ! !!! !!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!! !!!!!!! ! !!!!! ! ! !!! !!!!!!! ! ! !!! !!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!! ! ! !!! !!!!!!! ! !!!!!!!!!!! ! !!!!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!! !!! ! !!!!! !!! ! !!!!! ! ! ! !!!!!!! ! !!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!! ! !!! ! !!!!!!!!! !!!!!!! !!!!!!!!!!! !!!!! !!!!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!!!! !!!!! !!!!! !!!!!!! !!!!!!!!! ! !!!!! !!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!! !!!!! ! !!! ! !!! ! !!!!!!!!!!!!!!! ! !!! !!! !!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!! !!! !!!!!!!!! !!!!! !!!!!!!!! ! !!!!!!! !!! ! !!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!! ! ! ! ! !!! ! !!!!!!! ! !!!!!!!!! ! !!!!! !!!!!!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!!!!!!!! ! !!!!!!!!!!! !!! ! ! ! ! ! ! !!!!! !!!!! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!! !!! !!!!! ! ! !!!!!!!!! !!! ! !!!!!!!!! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ``` [Answer] # JavaScript (ES6), 174 This is the maze builder I used in [this other challenge](https://codegolf.stackexchange.com/questions/49068/leonhard-loves-labyrinths), just golfed. It's a function with 2 parameters: rows and columns. The maze is totally connected with no loops, so any location can be the starting or ending point. ``` (r,c,o=2*c+2,i=2*r*o+o,z=[],F=(p,i=Math.random()*4)=>[o,1,-o,-1].map((s,j,d)=>z[s=p+2*d[j+i&3]]>0&&(z[s]=z[(p+s)/2]=' ',F(s))))=>{for(;i--;)z[i]=i%o?8:`\n`;F(o+2);return''+z} ``` *Example* ``` f(7,10) ``` *Output* ``` ,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, ,8, , , ,8, , , , , ,8, , , , , , , , , ,8, ,8, ,8, ,8,8,8, ,8, ,8,8,8,8,8,8,8, ,8, ,8, ,8, , , ,8, , , ,8, , , ,8, , , , , ,8, ,8, ,8, ,8,8,8, ,8,8,8,8,8, ,8, ,8,8,8,8,8, ,8, ,8, ,8, , , , , ,8, ,8, ,8, ,8, , , , , ,8, ,8, ,8, ,8,8,8, ,8, ,8, ,8, ,8, ,8,8,8,8,8, ,8, ,8, ,8, , , ,8, , , , , ,8, ,8, , , ,8, ,8, ,8, ,8, ,8,8,8,8,8,8,8,8,8, ,8, ,8,8,8, ,8, ,8, ,8, , , , , , , ,8, , , ,8, , , ,8, ,8, ,8, ,8,8,8,8,8,8,8, ,8,8,8, ,8,8,8, ,8, ,8, ,8, , , , , , , ,8, , , ,8, , , , , ,8, ,8, ,8,8,8,8,8,8,8,8,8,8,8, ,8,8,8,8,8, ,8, ,8, , , , , , , , , , , , , ,8, , , , , ,8, ,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 ``` **Test** ``` f= (r,c,o=2*c+2,i=2*r*o+o,z=[],F=(p,i=Math.random()*4)=>[o,1,-o,-1].map((s,j,d)=>z[s=p+2*d[j+i&3]]>0&&(z[s]=z[(p+s)/2]=' ',F(s))))=>{for(;i--;)z[i]=i%o?8:`\n`;F(o+2);return''+z} function update() { O.textContent=''; [r,c]=I.value.match(/\d+/g) O.textContent=f(r,c) } update() ``` ``` pre { line-height: 0.8em } ``` ``` Rows,Columns <input id=I oninput='update()' value='8,12'> <pre id=O></pre> ``` [Answer] # ZX Basic - 54 characters ``` a$="/\":for i=1 to 24*32:print a$(1+int(rnd*2));:next ``` ![Output](https://i.stack.imgur.com/pByCV.png) Here is the maze showing a route through it (spaces between lines) ![path](https://i.stack.imgur.com/YkCEj.png) and a small snippet from when I first did this (several years ago), and spent a bit of time doing better graphics. ![better graphics](https://i.stack.imgur.com/aPK1e.png) [Answer] # BBC BASIC, 18 Bytes An improvement in length on the 23-byte C64 infinite loop version by @nneonneo. VDU sends a single character to the VDU controller: either 2+1\*45=ASCII 47 `/` or 2+2\*45=ASCII 92 `\` ``` VDU2+RND(2)*45:RUN ``` # BBC BASIC, 35 Bytes / ~~107~~ 95 Bytes 35 bytes is just for the last line, which gives a 25 row maze in 40 column layout. MODE1 ensures that no extra space is left between lines. The remainder of the program is optional and improves the formatting. The VDU23 statements redefine the font for characters 47 and 92 (8 bytes forming an 8x8 bitmap.) I include a light pixel in all four corners to stop straight runs from getting pinched off. The side effect of this is that a dot appears in the empty diamonds. 107 bytes total including 2 newlines. ``` VDU23,47,131,7,14,28,56,112,224,193 VDU23,92,193,224,112,56,28,14,7,131 MODE9FORa=0TO999VDU2+RND(2)*45:NEXT ``` **Edit** this program can be shortened to 95 bytes by encoding some of the 8 bit VDU codes into 16 bit small endian values (denoted by a semicolon after them instead of a comma) and representing the MODE statement as a pair of VDU codes, as follows. ``` VDU23,47,1923;7182;28728;49632;23,92,57537;14448;3612;33543;22,9:FORa=0TO999VDU2+RND(2)*45:NEXT ``` **Output** Using BBC Basic for Windows from bbcbasic.co.uk **Last line only, 35 bytes** ![enter image description here](https://i.stack.imgur.com/4egNa.png) **Whole program, ~~107~~ 95 bytes** As I commented on @Brian's answer, the slash splits the square into 2 dark triangles, each of which has exactly 2 entrances/exits. This guarantees a (trivial, unbranched) path from any point on the edge of the maze to some other point on the edge of the maze. Many of these are very short, but there always seem to be a few long ones. Of course, in the middle of the maze there are also some loops. As other answers have not mentioned it, I'd like to take a good look at the light areas. These are bounded by dark areas, therefore as a corollary to the statement made above, a light area bounded externally by N dark areas touches the edge of the field at N (exactly as many) points. Therefore some fairly large light areas occur, and these form interesting, branched mazes. In the example below, you can see the raw output (monochrome) from my program. Below that (using Windows Paint) I have coloured the two longest dark areas in blue. Then I coloured the largest light area in yellow, and the two areas bounded by blue in red and green. The yellow, green (and even the red) mazes are quite interesting and nontrivial. ![enter image description here](https://i.stack.imgur.com/CxFXC.png) # EDIT - Automatic picking of mazes and selection of starts/ends For one more line (59 characters) the program can automatically pick out up to 6 mazes by choosing squares at random and flood filling in colours red,green,yellow,blue,magenta and cyan. It does not always find a full 6, because if it picks a random square that has already been coloured it does nothing. The rest of the code below picks out a start for each colour by scanning each column from top to bottom and left to right, and picking the first square it encounters. It picks an end by scanning in the opposite direction. This produces a set of colourful, intertwined mazes. Sometimes they are so intertwined it looks like the mazes must cross somewhere. But of course, they don't! **Additional code and output 59+187=246 additional characters to be added to the end of the original program (for enhancement beyond question spec.)** ``` GCOL135FORa=1TO6GCOLa FILLRND(40)*32-16,RND(25)*32+208:NEXT :REM set background to grey so fill can identify. For each colour 1 to 6, pick a point in the centre of a character and flood fill (characters are logically 32x32 although they are physically only 8x8 pixels.) f=126:g=126 :REM flags 1111110 to indicate which starts and ends have not been allocated yet FORx=0TO39FORy=0TO24 :REM maze is 40x25. There is some blank space at the bottom of the screen (32 rows total) p=POINT(x*32+16,1008-y*32) :REM check start point. Text origin is at top of screen, Graphics origin is at bottom, 1280x1024 logical. therefore y offset is 1024-32/2=1008. IFf AND2^p f=f-2^p:VDU31,x,y,17,p,79 :REM if start for colour P has not been allocated yet, allocate it now. VDU31,X,Y go to that square. VDU 17,p select text colour. VDU 79 print an "O" p=POINT(1264-x*32,240+y*32) :REM check end point IFg AND2^p g=g-2^p:VDU31,39-x,24-y,17,p,79 :REM if end for colour P has not been allocated yet, allocate it now. NEXT:NEXT VDU31;26 :REM get the cursor off the board. Move to (0,26). Semicolon used instead of comma here indicating that 31 is a 16 bit small endian value, equivalent to VDU31,0,26 or PRINTTAB(0,26) ``` ![enter image description here](https://i.stack.imgur.com/g0HQb.png) [Answer] # C: 235 Bytes ``` #define P(X,Y)M[(Y+40)*80+X+40]=rand()%49/6; #define B(X,Y)P(X,Y)P(Y,X) M[6400],r,i;main(){for(i=0;i<40;i+=2){int x=i,y=0,e=1-x;while(x>=y) {B(x,y)B(-x,y)B(-x,-y)B(x,-y)++y;e+=e<0?2*y+1:2*(y-x--);}}for(i=0; i<6400;)putchar(64>>!M[i++]);} ``` Note: in the above, I added newlines to make it fit on the page. Expected output (on 80-character terminal):![enter image description here](https://i.stack.imgur.com/46por.png) I regret this isn't a very hard maze (in fact, no backtracking to inner rings is required (and you should be able to find a path from the perimeter to the center trivially). However, it has a nice implementation of Bresenham's circle drawing algorithm at its core. [Answer] I helped my kid to do this, to learn a bit of programming: <http://jsfiddle.net/fs2000/4KLUC/34/> how do you like it? [Answer] # Commodore 64 BASIC - 38 bytes ``` 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 ``` This is not my invention, I am simply repeating a very beautiful and short program from days gone past. In fact, there is an entire book named [`10 PRINT CHR$(205.5+RND(1)); : GOTO 10`](http://10print.org/) celebrating this piece of code! You can see the output on this [YouTube video](https://www.youtube.com/watch?v=m9joBLOZVEo); here's a screencap: ![YouTube screencap](https://i.stack.imgur.com/q0fKd.png) Here at [this StackOverflow question](https://stackoverflow.com/questions/13611501/bash-version-of-c64-code-art-10-print-chr205-5rnd1-goto-10) are more implementations of this maze-generator program. The shortest implementation of the program is the following 23-byte C64 BASIC program posted by that question's author: ``` 1?cH(109.5+rN(1));:gO1 ``` where lowercase letters are entered as-is, and uppercase letters are entered using the Shift key (these have different appearances on an actual C64 screen). [Answer] ## Java : 700 Here's a recursive wall adder. The algorithm is outlined on [this site](http://weblog.jamisbuck.org/2011/1/12/maze-generation-recursive-division-algorithm): ``` public class Z{int i,j,u=20,v=u,g[][]=new int[v][u];public static void main(String[]a){new Z().d(0,0,20,20,0).p();}int q(int m){return(int)(Math.random()*m);}<T>void z(T m){System.out.print(m);}void p(){for(i=0;i++<u*2;z("_"));for(i=0;i<v;i++){z("\n|");for(j=0;j<u;j++){boolean b=i+2>v,s=g[i][j]%2>0||b;z(s?"_":" ");z(g[i][j]>1||j+2>u?"|":s&(j+1<u&&g[i][j+1]%2>0||b)?"_":" ");}}}Z d(int x,int y,int w,int h,int o){int a=x,b=y,c=a,d=b,e,f;boolean t=o<1;if(t){b+=q(h-2);c+=q(w);}else{a+=q(w-2);d+=q(h);}for(i=t?w:h;i-->0;j=t?a++:b++)if(a!=c&&b!=d)g[b][a]|=t?1:2;e=t?w:a-x+1;f=t?b-y+1:h;if(e>2&&f>2)d(x,y,e,f,e<f?0:1);e=t?w:x+w-a-1;f=t?y+h-b-1:h;if(e>2&&f>2)d(t?x:a+1,t?b+1:y,e,f,e<f?0:1);return this;}} ``` Basically, it splits each rectangle in two with a wall (and passage), then splits those in two, etc. It generates a "perfect" maze - one with no cycles - that has a path from every point to every other point. Plenty of dead ends, so it's not "trivial" in any sense for larger mazes. So, the entrance and exit can be decided arbitrarily. If I have to choose one, It'll just say top/left and bottom/right. It's drawn in double-width ascii, so it's a good idea to pipe output to a file if you're doing one of any size. Here's a 20x20 in console: ![20x20](https://i.stack.imgur.com/rRopK.png) And a 100x100 in notepad++ (I had to zoom out to get ti all, so it's somewhat... *small*): ![100x100](https://i.stack.imgur.com/8T5sL.png) Code with line breaks: ``` public class Z{ int i,j,u=20,v=u,g[][]=new int[v][u]; public static void main(String[]a){ new Z().d(0,0,20,20,0).p(); } int q(int m){return(int)(Math.random()*m);} <T>void z(T m){System.out.print(m);} void p(){ for(i=0;i++<u*2;z("_")); for(i=0;i<v;i++){ z("\n|"); for(j=0;j<u;j++){ boolean b=i+2>v,s=g[i][j]%2>0||b; z(s?"_":" "); z(g[i][j]>1||j+2>u?"|":s&(j+1<u&&g[i][j+1]%2>0||b)?"_":" "); } } } Z d(int x,int y,int w,int h,int o){ int a=x,b=y,c=a,d=b,e,f; boolean t=o<1; if(t){ b+=q(h-2); c+=q(w); } else{ a+=q(w-2); d+=q(h); } for(i=t?w:h;i-->0;j=t?a++:b++) if(a!=c&&b!=d) g[b][a]|=t?1:2; e=t?w:a-x+1;f=t?b-y+1:h; if(e>2&&f>2)d(x,y,e,f,e<f?0:1); e=t?w:x+w-a-1;f=t?y+h-b-1:h; if(e>2&&f>2)d(t?x:a+1,t?b+1:y,e,f,e<f?0:1); return this; } } ``` [Answer] # ZX Basic - 281 characters This is more of a "proper" maze, less golfier, but more mazier. So called Binary maze algorithm, each cell can have an exit going down or right, but not both. (Now includes marked Start "S" and End "E", to prevent just going straight along one side). The "::" is ZXB's way of entering Spectrum graphic characters into a text file, equates to a sold block character. ``` randomize:border 1:paper 1:ink 6:cls for x=0 to 30 step 2 for y=0 to 20 step 2 r=1+int(rnd*2) if x=30 and r=1 then r=2 end if if y=20 and r=2 then r=1 end if print at y,x;"\::" print at y+(r=2),x+(r=1);"\::" next next print inverse 1;at 0,0;"S";at 20,31;"E" ``` ![Maze](https://i.stack.imgur.com/htuKt.png) [Answer] # C- 244 ``` #include <unistd.h> #include <windows.h> int main(i,j,rv,rs){srand( time(0));for (i = 0; i < 80; i++)for (j = 0; j <50 ; j++){rv = rand() %10;rs = rand() %100;if(rs < 10 || rs > 90)continue;if(rv<4){gotoxy(i,j);printf("%c", '#');}}return 0;} ``` Here is how it looks like: ![Maze](https://i.stack.imgur.com/hdt2Z.png) Note: this solution is inspired by the [untrusted game](http://alexnisnevich.github.io/untrusted/) level 8:into the woods. ]
[Question] [ Based on [this](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output) challenge. In the rhythm game [osu!](https://osu.ppy.sh/home), the difficulty modifier "Double-time" actually only increases the speed by 50%. Your task, is to write a program that outputs a positive *even* integer (higher than 0), and when each byte/character (your choice which) in your source code is duplicated, it should output the number multiplied by 1.5. For example if your source code is `ABC` and that outputs 6, then `AABBCC` should output 9. Following the original challenge's rules: ## Rules * You must build a full program. * The initial source must be at least 1 byte long. * Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden). * Your program must not take input (or have an unused, empty input) and must not throw any error (compiler warnings are not considered errors). * Outputting the integers with trailing / leading spaces is allowed. * You may not assume a newline between copies of your source. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest bytes **in each language** wins! * [**Default Loopholes**](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. I imagine this will be far less trivial than the original challenge, but hopefully we'll see some creative and unique answers! [Answer] # [Pylons](https://github.com/morganthrapp/Pylons-lang), 7 5 4 bytes Picked a random language on TIO used it ``` 46vt ``` Explanation: [Try it Online!](https://tio.run/##K6jMyc8r/v/fxKys5P9/AA) ``` 46 # Stack is [4, 6] v # Reverse the stack [6, 4] t # take top of stack 4 ``` Doubled: ``` 4466 # Stack is [4, 4, 6, 6] vv # Reverse the stack twice so it's the same [4, 4, 6, 6] tt # take top of stack 6 and again which is 6 again ``` Saved 2 bytes thanks to *officialaimm* Saved 1 bytes thanks to *Veedrac* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` !‘ ``` [Try it online!](https://tio.run/##y0rNyan8/1/xUcOM//8B "Jelly – Try It Online") Explanation: ``` !‘ Implicit 0 ! Factorial ‘ Increment ``` Doubled version: ``` !!‘‘ ``` [Try it online!](https://tio.run/##y0rNyan8/19R8VHDDCD6/x8A "Jelly – Try It Online") Explanation: ``` !!‘‘ Implicit 0 ! Factorial ! Factorial ‘ Increment ‘ Increment ``` [Answer] # LibreOffice Calc, 8 bytes ``` =A2+3 19 ``` Save it as `*.csv` and open it in LibreOffice Calc. You will get 22 in A1. --- Double them: ``` ==AA22++33 1199 ``` You will get 33 in A1 [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` TnQ ``` [Try it online!](https://tio.run/##y00syfn/PyQv8P9/AA "MATL – Try It Online") Or [doubled version](https://tio.run/##y00syfn/PyQkLy8w8P9/AA). ### Explanation In MATL a scalar value (number, char, logical value) is the same as a 1×1 array containing that value. Normal version: ``` T % Push true n % Number of elements of true: gives 1 Q % Add 1: gives 2 ``` Doubled version: ``` TT % Push [true, true] n % Number of elements of [true, true]: gives 2 n % Number of elements of 2: gives 1 Q % Add 1: gives 2 Q % Add 1: gives 3 ``` [Answer] ## vim, 5 ``` i1<esc>X<C-a> ``` Without doubling: ``` i1<esc> insert the literal text "1" X delete backwards - a no-op, since there's only one character <C-a> increment, giving 2 ``` With doubling: ``` ii11<esc> insert the literal text "i11" <esc> escape in normal mode does nothing XX since the cursor is on the last character, delete "i1" <C-a><C-a> increment twice, giving 3 ``` [Answer] Not sure if this answer is valid. Just post here in case some one may got ideas from here. # Node.js with -p flag, 7 bytes By **Alex Varga**: ``` 3/3*22 33//33**2222 ``` # Node.js with -p flag, 11 bytes **Old one:** ``` 3*2*0/1+22 33**22**00//11++2222 ``` Output 22 and 33. [Answer] # Python 2 REPL, 11 bytes ``` (3/1)*(2/1) ``` This simply evaluates to 3\*2=6. Duplicated, it is ``` ((33//11))**((22//11)) ``` which evaluates to 3\*\*2, which is 3 to the power of 2, or 9. [Answer] # APL, 7 bytes ``` ⊃⍕⌊3×⍟2 ``` Prints `2`. ``` ⊃⊃⍕⍕⌊⌊33××⍟⍟22 ``` Prints `3`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEx51NT/qnfqop8v48PRHvfONuBDCEBmwJEgeqACsBKTK6P9/AA) ### Waaat? Single: ``` 3×⍟2 → 2.079441542 ⍝ 3 * ln 2 ⌊2.079441542 → 2 ⍝ floor ⊃⍕ → '2' ⍝ format and take first character ``` Double: ``` ⍟⍟22 → 1.128508398 ⍝ ln ln 22 ×1.128508398 → 1 ⍝ signum 33×1 → 33 ⍝ 33 * 1 ⌊⌊33 → 33 ⍝ floor ⊃⊃⍕⍕ → '3' ⍝ format and take first character ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 3 bytes ``` 1u* ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9@wVOv/fwA "Actually – Try It Online") Explanation: ``` 1u* Errors are ignored 1 Push 1 u Increment * Multiply ``` Doubled version: ``` 11uu** ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/QsLRUS@v/fwA "Actually – Try It Online") Explanation: ``` 11uu** Errors are ignored 1 Push 1 1 Push 1 u Increment u Increment * Multiply * Multiply ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` ],)) ``` [Try it normally!](https://tio.run/##S85KzP3/P1ZHU/P/fwA "CJam – Try It Online") [Try it doubled!](https://tio.run/##S85KzP3/PzZWR0cTCP7/BwA) ### Explanation Normal: ``` ] e# Wrap the stack in an array: [] , e# Get its length: 0 )) e# Increment twice: 2 ``` Double: ``` ] e# Wrap the stack in an array: [] ] e# Wrap the stack in an array: [[]] , e# Get its length: 1 , e# Get the range from 0 to n-1: [0] ) e# Pull out its last element: 0 ))) e# Increment 3 times: 3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` X> ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/wu7/fwA "05AB1E – Try It Online") Explanation: ``` X> Only top of stack is printed X Push X (default 1) > Increment ``` Doubled version: ``` XX>> ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/IsLO7v9/AA "05AB1E – Try It Online") Explanation: ``` XX>> Only top of stack is printed X Push X (default 1) X Push X (default 1) > Increment > Increment ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes ``` 𝐓> ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCZPt/v8HAA "Neim – Try It Online") Explanation: ``` 𝐓> Implicit 0 𝐓 Factorial > Increment ``` Doubled version: ``` 𝐓𝐓>> ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCZNB2M7u/38A "Neim – Try It Online") ``` 𝐓𝐓>> Implicit 0 𝐓 Factorial 𝐓 Factorial > Increment > Increment ``` [Answer] # Pyth, 3 bytes ``` he1 ``` [Try it here.](http://pyth.herokuapp.com/?code=he1&debug=0) Explanation: ``` he1 h Increment e Last digit 1 1 ``` Doubled version: ``` hhee11 ``` [Try it here.](http://pyth.herokuapp.com/?code=hhee11&debug=0) Explanation: ``` hhee11 h Increment h Increment e Last digit e Last digit 11 11 ``` [Answer] # Ruby REPL, 8 bytes ``` ";3#";22 ``` The REPL only prints the last value evaluated: `22`. Doubled: ``` "";;33##"";;22 ``` This time `33` is the last value evaluated. The string is discarded once again, and a `#` starts a comment. [Answer] # [Zsh](https://www.zsh.org/), 14 bytes ``` <:|echo 22 3 : ``` [Try it online!](https://tio.run/##ZY6xDoIwEIb3e4pLrRZW3CrppK6@gAu0hZJoS1qICeqz10ICi7f9d1/@@6ZgosDgJZYlssvtymLJP1oah0UBR@Ax7QCmYGYIYIdq7B@drAaNvXetr54cGudRYmeRvrPAeU5oViY6J98TKgeYpvedHRpk@8CQUEklQSHScawfWoFyVs/dwbjX/4O5Wel6bGHxEocCKbvb88qpzYRByguwNi/mW4D4Aw "Zsh – Try It Online") Getting a full program in a non-golfing language to print anything with source code duplicated like this is a challenge. Zsh is very useful for this, because files and heredocs are implicitly passed to `cat`. Let's take a look at the first line in both cases: ``` <:|echo 22 # Give the file : on stdin to cat. cat pipes to 'echo 22', which ignores stdin <<::||eecchhoo 2222 # Start heredoc on following lines with EOF string '::', pass to cat. # Since cat exits 0, 'eecchhoo 2222' is not executed ``` So long as `3` is not a program, the first program will only print `22`. The second program will print `33` surrounded by extra newlines (due to the duplication). --- If `3` is a function/program/alias, then this **18 byte** solution will still work! ``` <:|echo 22\\c\ 3 : ``` [Try it online!](https://tio.run/##ZY6xDoIwEIb3e4pLrRZW3CphUldfoAu0hZIgJS3EBPXZayGBxdv@uy//fbM3oUDvJOY5stvjzkLOP1oai1kmhBRwBh7iHmD2ZgEBDqimoWtlOWocnG1c@eRQW4cS2x7pO/Gcp4QmeaRT8r2gsoBxBtf2Y43s6BkSKqkkWBTxOFWdVqBsr5dub@zr/8HSrHQ1NbC6FacMKRP9dePUbsIg5hXYmlfzPUD4AQ "Zsh – Try It Online") The last `\` is line continuation, so the newline is discarded, effectively making the echo statement `echo '22\c3'`. The `\c` causes echo to stop printing after `22` (which also happens to suppress the newline). [Answer] # [R](https://www.r-project.org/), ~~11~~ 6 bytes ``` 1+7*!0 ``` [Try it online!](https://tio.run/##K/r/31DbXEvR4L@hoba2ubmWliKQDQA "R – Try It Online") `!` is negation, and `**` is exponentiation (an alias for `^`). Numerics get converted to booleans: `0` to `FALSE`, all others to `TRUE`. Booleans get converted to integers: `FALSE` to `0`, `TRUE` to `1`, so `!0==1`, `!1==0`, `!!00==0` and `!!11==1`. The single version thus computes \$1+7\times 1=8\$, and the double version computes \$11+77^0=12\$. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 6 bytes ``` O.1)W@ ``` Prints `2`. ``` O . 1 ) W @ ``` Pushes `1`, `)` increments, `W` jumps left to `O` which outputs `2`, and `@` finishes the program. Doubled up, it's obviously `OO..11))WW@@`, which on a cube is: ``` O O . . 1 1 ) ) W W @ @ . . . . . . . . . . . . ``` It pushes `1` twice, `)` increments twice, `W` jumps left again, which puts it at the right-hand `O` heading north, which outputs `3`, and then the next command is `@` which terminates the program. [Try it online!](https://tio.run/##Sy5Nyqz4/99fz1Az3OH/fwA "Cubix – Try It Online") [Doubled online!](https://tio.run/##Sy5Nyqz4/9/fX0/P0FBTMzzcweH/fwA "Cubix – Try It Online") [Answer] # [Klein](https://github.com/Wheatwizard/Klein), ~~8~~ 6 bytes ``` /3+@4\ ``` [Single](https://tio.run/##y85Jzcz7/1/fWNvBJOb///8GBoYA "Klein – Try It Online"), [Double](https://tio.run/##y85Jzcz7/19f39hYW9vBwcQkJub///8GBoYA "Klein – Try It Online") ## Explanation For the single the program follows a pretty straightforward path. The first mirror deflects it into the second which deflects it through the `4` to the end of the program. The double is a little more complex. Here it is: ``` //33++@@44\\ ``` The first two mirrors work the same, however there is a new mirror due to the doubling which deflects the ip back to the beginning, it is caught by the duplicate of the first mirror and deflected towards the end. All that is run is the `33++` which evaluates to 6. [Answer] # TI-Basic, 3 bytes Single: ``` int(√(8 ``` The last expression is implicitly returned/printed in TI-Basic, so this prints `2` Doubled: ``` int(int(√(√(88 ``` Returns/prints 3 TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens); `int(`, `√(`, and `8` are each one byte in memory. [Answer] # ><>, ~~19~~ 8 Bytes ``` 32b*!{n; ``` Prints `22` [Try it online!](https://tio.run/##S8sszvj/39goSUuxOs/6/38A "><> – Try It Online") Explanation: ``` 32b push literals onto the stack: [3,2,11] * multiply the top two values: [3,22] ! skip the next instruction { (skipped) n pop and print the top value from the stack (22) ; end execution ``` ### Doubled: ``` 3322bb**!!{{nn;; ``` Prints `33` [Try it online!](https://tio.run/##S8sszvj/39jYyCgpSUtLUbG6Oi/P2vr/fwA "><> – Try It Online") Explanation: ``` 3322bb push literals onto the stack: [3,3,2,2,11,11] ** multiply top values (twice): [3,3,2,242] ! skip next instruction ! (skipped) {{ rotate the stack to the left (twice): [2,242,3,3] nn pop and print the top two values from the stack (33) ; end execution ``` Old Version: ~~Normal:~~ ``` 11+!vn; n ; ``` Prints `2` [Try it online!](https://tio.run/##S8sszvj/39BQW7Esz5pLAQjywKT1//8A) Explanation: ``` 1 push 1 on the stack: [1] 1 push 1 on the stack: [1,1] + add top two values of the stack: [2] ! skip the next instruction v (skipped) n print the top value of the stack (2) ; end execution ``` Doubled: ``` 1111++!!vvnn;; nn ;; ``` Prints `3` [Try it online!](https://tio.run/##S8sszvj/3xAItLUVFcvK8vKsrbkUoCAvD860tv7/HwA) Explanation: ``` 1111 push four 1's on the stack: [1,1,1,1] + add top two values of the stack: [1,1,2] + add top two values of the stack: [1,3] ! skip the next instruction ! (skipped) v change direction of execution (down) n print the top value of the stack (3) ; end execution ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 14 bytes ``` '|d 3#';say 22 ``` [Try it online!](https://tio.run/##K0gtyjH7/1@9JkXBWFndujixUsHI6P9/AA "Perl 6 – Try It Online") [Try it doubled!](https://tio.run/##K0gtyjH7/19dvaYmJUVBwdhYWVld3dq6uDgxsbJSQcEICP7/BwA) This uses the conveniently named debug function `dd` to output the doubled program to STDERR. To separate the logic we encase the doubled program in quotes, which then cancel each other out when doubled, along with a comment character `#` to comment out the now invalid normal program. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` ¡› ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%A1%E2%80%BA&inputs=&header=&footer=) Port of the Jelly answer. ``` # (implicit zero) ¡ # Factorial › # Incremented ``` Doubled ([Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%A1%C2%A1%E2%80%BA%E2%80%BA&inputs=&header=&footer=)): ``` ¡ # 0 factorial = 1 ¡ # 1 factorial = 1 ›› # Incremented twice = 3 ``` # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` ðL› ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%B0L%E2%80%BA&inputs=&header=&footer=) ``` ð # Space character L # Length › # Incremented ``` Doubled ([Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%B0%C3%B0LL%E2%80%BA%E2%80%BA&inputs=&header=&footer=)) ``` ðð # Space character (one's a nop) LL # Length twice (one's a nop) ›› # Incremented twice ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 6 bytes ``` ))$$!@ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/19TU0VF0eH/fwA "Hexagony – Try It Online") ([Try it doubled!](https://tio.run/##y0itSEzPz6v8/18TCFSAQFHRweH/fwA "Hexagony – Try It Online")) ## Explanation ``` ) ) $ $ ! @ . ``` This program does nothing too weird; it just executes each line in order: * `))`: Increment twice (memory cell = `2`). * `$$`: Jump the jump; basically a no-op. * `!`: Print memory cell (`2`) * `@`: Stop. --- ``` ) ) ) ) $ $ $ $ ! ! @ @ . . . . . . . ``` Only the first and third lines are executed, due to Hexagony's control flow: * `)))`: Increment 3 times (memory cell = `3`). * `)$$$`: This line is skipped. * `$!`: Jump over the first `!`, so the memory cell isn't printed twice. * `!`: Print `3`. * `@`: Stop. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes ``` ▬) ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RtDWa//8DAA "MathGolf – Try It Online") [Try it doubled](https://tio.run/##y00syUjPz0n7///RtDVApKn5/z8A "MathGolf – Try It Online") Similar to other answers in that the first instruction produces a `1` even when doubled and the second increments it. In this case, I've used reverse exponentiation (`0**0 = 0**0**0 = 1`) but it also could have been any of the `!£≤°` instruction and perhaps even more that I missed. [Answer] # [Stax](https://github.com/tomtheisen/stax), 3 bytes ``` UJ^ ``` [Run and debug it](https://staxlang.xyz/#c=UJ%5E&i=&a=1&m=2) [Run and debug the doubled one](https://staxlang.xyz/#c=UUJJ%5E%5E&i=&a=1&m=2) `U` pushes -1. `J` squares. `^` increments. [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 12 bytes ``` iis(ooh)iiio ``` [Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/M7NYIz8/QzMzMzP//38A "Deadfish~ – Try It Online") [Try it doubled!](https://tio.run/##S0lNTEnLLM7Q/f8/EwiKizU08oEgI0NTMxMM8vP//wcA "Deadfish~ – Try It Online") ## Explanation ``` iis(ooh)iiio ``` Set the accumulator to `2`, square it, print twice to get `44`, stop. ``` iiiiss((oooohh))iiiiiioo ``` Set the accumulator to 4 and square it twice to get 256. Since Deadfish~ doesn't like the number 256, it sets the accumulator to 0 instead. The `(...)` part of the code is ignored if the accumulator is 0, and then the rest of the code prints `66`. [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0 -MData::Dump+(dd)`, 17 bytes ``` q{\};d 3#};say 22 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@wOqbWOkXBWLnWujixUsHI6P//f/kFJZn5ecX/dX1N9QwN9AyADJfEkkQrK5fS3AJtjZQUTQA "Perl 5 – Try It Online") ## Doubled ``` qq{{\\}};;dd 33##}};;ssaayy 2222 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@wsLo6Jqa21to6JUVBwdhYWRnELi5OTKysVFAwAoL////lF5Rk5ucV/9f1NdUzNNAzADJcEksSraxcSnMLtDVSUjQB "Perl 5 – Try It Online") ## Explanation I was hopeful to find a way to trigger a `print` without using an external, but I couldn't come up with anything so I settled on `dd`. The trick here was to leverage Perl's flexibly delimited strings to encase the doubled code without causing a syntax error. Using `{...}` (or any other pairs like`()`, `[]`, `<>`) means in the original code the end char can be escaped with a single `\` which when doubled is just a backslash. Using `q` is easiest as `qq` is just as valid. ``` q{\};d 3#};say 22 ``` Here we have a short string containing `};d 3#`, then we just `say 22` which outputs 22. ``` qq{{\\}};;dd 33##}};;ssaayy 2222 ``` Here we have a string containing a single `\` and then we `dd`ump out 33 and the rest of the program is commented out. --- Now that I look through the other answers I see that [@JoKing's answer](https://codegolf.stackexchange.com/a/191483/9365) would work as-is with my command line arguments too... [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Another "factorial+1" solution. ``` ÊÄ ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ysQ) ``` ÊÊÄÄ ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ysrExA) [Answer] # [Octave](https://www.gnu.org/software/octave/), 1 byte I think we all know this is a worthless answer. Gotta show Octave some love. ``` 0 ``` [Try it online!](https://tio.run/##y08uSSxL/f/f4P9/AA "Octave – Try It Online") ]
[Question] [ Write shortest possible code that will return true if the two given integer values are equal or their sum or absolute difference is 5. Example test cases: ``` 4 1 => True 10 10 => True 1 3 => False 6 2 => False 1 6 => True -256 -251 => True 6 1 => True -5 5 => False ``` The shortest I could come up with in python2 is 56 characters long: ``` x=input();y=input();print all([x-y,x+y-5,abs(x-y)-5])<1 ``` -9, thanks @ElPedro. It takes input in format x,y: ``` x,y=input();print all([x-y,x+y-5,abs(x-y)-5])<1 ``` [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` lambda a,b:a in(b,5-b,b-5,b+5) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqUSEzTyNJx1Q3SSdJ11QnSdtU839BUWZeiUaahqGOiaYmF5xnoGNogMzXMUbimekYociZIfF0jUzNdICEoabmfwA "Python 2 – Try It Online") One byte saved by Arnauld Three bytes saved by alephalpha [Answer] # JavaScript (ES6), 28 bytes Takes input as `(a)(b)`. Returns \$0\$ or \$1\$. ``` a=>b=>a+b==5|!(a-=b)|a*a==25 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1i5RO8nW1rRGUSNR1zZJsyZRK9HW1sj0f3J@XnF@TqpeTn66RpqGiaaGoaamAhTo6yuEFJWmcqGqMTTQBGFNvGo0NYxRzHFLzClGV2SmqWFEUBHQJDNCLtI1MgWaBSTBboeq@Q8A "JavaScript (Node.js) – Try It Online") [Answer] # [Dyalog APL](https://www.dyalog.com/), 9 bytes ``` =∨5∊+,∘|- ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wTbRx0rTB91dGnrPOqYUaP7/7@JQpqCIZehAYgy4DIEUsZcZkDSCMw24zq03sgUxAfRhlzq6iABMNcYAA "APL (Dyalog Unicode) – Try It Online") Spelled out: ``` = ∨ 5 ∊ + , ∘ | - equal or 5 found in an array of sum and absolute of difference. ``` [Answer] # x86 machine code, 39 bytes ``` 00000000: 6a01 5e6a 055f 5251 31c0 39d1 0f44 c601 j.^j._RQ1.9..D.. 00000010: d139 cf0f 44c6 595a 29d1 83f9 050f 44c6 .9..D.YZ).....D. 00000020: 83f9 fb0f 44c6 c3 ....D.. ``` # Assembly ``` section .text global func func: ;inputs int32_t ecx and edx push 0x1 pop esi push 0x5 pop edi push edx push ecx xor eax, eax ;ecx==edx? cmp ecx, edx cmove eax, esi ;ecx+edx==5? add ecx, edx cmp edi, ecx cmove eax, esi ;ecx-edx==5? pop ecx pop edx sub ecx, edx cmp ecx, 5 ;ecx-edx==-5? cmove eax, esi cmp ecx, -5 cmove eax, esi ret ``` [Try it online!](https://tio.run/##bVNNj5swED3jXzFCShUSkw/S5JCEjVS1q16qvfTWjSJjzMYrYiNsWrZVfns6ht0k7AaBPW/83swwAwkz@xNnFtbrbw/3cAdjeyjGbMTM4WQEt1IrGFlRW@I95TphOWSV4sQtS89dK6mKyhqQys6inQXBa2AqBZHWxCsqs4dJPUVLFyCMPLvmr670zXXhYwTi1boEwWrqFkK8FTrjGDkb4vFD4Ti0lfCD/i1eqRi/pQ7xKI7nSGZp2iE3KWmb453Ua7XhWdsU6IhtpWiYKnkfzaF5VxvONx@Dn8nh/EbRpbAn7D8hH0ZhbJWMOMEJiFK5LsNux6wtZVJZsdv1@xkzlrM8D4JmNH2kUHyCFZADk6of/COek1lhrPm1jRF6n@mU4jadULydQWduW9CoRQu3hdF8QXGZtkc4xOOKeJkuXQqQ8WQl10b@FTrrN7GD8StqssthHLnUXlEizvp@L6W9dAk986h82hYjt2/GcLqlTfU3DoKN/7OshL/071luhB9gFUdyJE2/FH6oEGYiz2bR1bcLoW4R16kYafLEedeFguv@XpMhVDospIDwMIuITp65Ll4gfIBEKlai9dz@ER3NxUYWcaq0womHXyH84aYm8g797lNEBN9jLgH@oxoMBl9erACuK2WXiPyG8QeL5rDuBr@h/S5ql@0irOv0hoh0Xv/0Hw "Bash – Try It Online") Edit: fixed bash stderr errors on TIO Edit 2: improved formatting in TIO header and footer code [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` +,ạ5eo= ``` [Try it online!](https://tio.run/##y0rNyan8/19b5@Guhaap@bb/Dy830leI/P9fQ0FBwUQHSCgY6nCBSAMdCMkFEQORxhCOGZhjhCxjBuToGpkCZYAk0ABNAA "Jelly – Try It Online") ### How it works ``` +,ạ5eo= Main link. Arguments: x, y (integers) + Yield x+y. ạ Yield |x-y|. , Pair; yield (x+y, |x-y|). 5e Test if 5 exists in the pair. = Test x and y for equality. o Logical OR. ``` [Answer] # [R](https://www.r-project.org/), 40 bytes (or 34) ``` function(x,y)any((-1:1*5)%in%c(x+y,x-y)) ``` [Try it online!](https://tio.run/##LcdBCoAgEEDRfaeYjTBTM5BpJdFlQhDcGESBnt4QXL3/nxrglBq@5N94J8xc6EoFUfShx5VUTMpjngpnKUQ1oGbYaAhoGEzXNV1/sQuD2L31zJrqDw "R – Try It Online") For non-R users: * `-1:1*5` expands to `[-5, 0, 5]` * the `%in%` operator takes elements from the left and checks (element-wise) if they exist in the vector on the right A direct port of [@ArBo's solution](https://codegolf.stackexchange.com/a/178803/79980) has ~~35~~ 34 bytes, so go upvote that answer if you like it: ``` function(x,y)x%in%c(y--1:1*5,5-y) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~29~~ 31 bytes ``` lambda a,b:a+b==5or`a-b`in"0-5" ``` [Try it online!](https://tio.run/##LYzLDsIgFET3fsWkKx@XBFC6aMKXYJNClEii0NC78euxbdzMmTOLmb/8Klm3aO/t7T/h4eEpDP4SrDWlTl6EKeVOCtM1fi68wMI5RbiNBKckQcm9Ea4be4L@e79RaLNOa6pxPMRSwUgZ@9Mw15QZTIjHM5/aDw "Python 2 – Try It Online") Since I didn't manage to read the task carefully the first time, in order to fix it, I had to come up with a completely different approach, which is unfortunately not as concise. [Answer] # [J](http://jsoftware.com/), ~~12~~ 11 bytes *1 byte saved thanks to Adám* ``` 1#.=+5=|@-,+ ``` [Try it online!](https://tio.run/##JU1PC4IwHL37KR4G/Ryu5Sw9bEyEwFOn6B5hmkoo2DoE0Vdfkw7vH7zHG1woQC2MAoEjgfLYCBxOx8rJlTBxZj7lhseOBXZ@2e69VHe@Rn0r8MZt8ns6z6@GCM3j2Syxunqz5PEmKLD1stlDaplAJlpip3OkXnN9SbMcnmTQ1N1URgRTgIapH5927sd7qHQUqvJ/zYkR/xIi4qFiZdRuGVuLArZ2Pw "J – Try It Online") ## Explanation This is equivalent to: ``` 1 #. = + 5 = |@- , + ``` This can be divided into the following fork chain: ``` (= + (5 e. (|@- , +))) ``` Or, visualized using `5!:4<'f'`: ``` ┌─ = ├─ + ──┤ ┌─ 5 │ ├─ e. └───┤ ┌─ | │ ┌─ @ ─┴─ - └────┼─ , └─ + ``` Annotated: ``` ┌─ = equality ├─ + added to (boolean or) ──┤ ┌─ 5 noun 5 │ ├─ e. is an element of └───┤ ┌─ | absolute value | │ ┌─ @ ─┴─ - (of) subtraction | └────┼─ , paired with | └─ + addition | any of these? ``` [Answer] # Python 2, 38 bytes -2 bytes thanks to @DjMcMayhem ``` lambda a,b:a+b==5or abs(a-b)==5or a==b ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqUTvJ1tY0v0ghMalYI1E3SRPKs7VN@l9QlJlXopGmYahjoqn5HwA "Python 2 – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 30 bytes ``` a->b->a+b==5|a==b|(b-=a)*b==25 ``` [Try it online!](https://tio.run/##ZVBLi4MwGLz7Kz4KQtJVUXftod14XNjDwkKP0kN8lbgaxXwWSutvd@ODpV0DSSYzk8mQgl@4XaQ/g6iaukUo9NnpUJTO9mCsuLyTCYpajmJScqXgiwsJNwOg6eJSJKCQo94utUih0ho5YivkOToBb8@KTlaAT4kfS9S7xt9tloqEYxZCDgwGboexHfKXmLHgzhmL7yS2GadbTfjBcJgyhMTopHMxU6j0rTl5HDd4s8CD3npgPFdT7j/OgtdnZmeBv/LsnhnbD7RNr97q7gPTzyXzuiVT0anmfi5L/7oerwqzyqk7dBr9TZiTjZmCme7BVKbcWJM/ck8L8DTIHd405ZUsCnVGQBaZ0vnZ3hhnP/wC "Java (JDK) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes Takes input as `[a][b]`. ``` MatchQ[#|5-#|#-5|#+5]& ``` [Try it online!](https://tio.run/##LYjBCoQgFEV/5cKDNimkZbsGf2Cg1uJCoqhFLQZ36rc7Gm3uOedezh/b5fy5urxjyl/n12MxFBWnSFxFapVt8vw7b28CUQL/YDdkDUlr0UBrjRAGBpEYguiKdI8x9JUjg3x7rORSlausSCn/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~48~~ ~~44~~ 40 bytes ``` param($a,$b)$b-in($a-5),(5-$a),(5+$a),$a ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyVJNzMPyNY11dTRMNVVSQRR2iBKJfH///@6RqZmIMIQAA "PowerShell – Try It Online") or [Verify all Test Cases](https://tio.run/##ZZBfa4MwFMXf8ylSyEbCElBXfRsIhcGeWljfShmxTalFjTVxZXR@dneNzlZ6H3KS3zk3/0p9UZU5qixrSYHf8LUtZSVzSiQnCSOJSAuYi5BxGgoiO3nphMi2QSimCEPFdM6xKx/UZ3ygvuewkzs6ZF9BvZFGAw0m9D8bTXYQQRhxGKanRZM7IIZ/8dPVeZvV56I2VufL5KR2dhv3uKtDWhn7UZS1hceTr423HS2jdrrY33n@zdO17TF9hm9zfX2CjZFvmaX71P6slbHLMf6Qx0Kd8WwGi2BoblADV3/XVS6tWMskU@0f "PowerShell – Try It Online") Takes input `$a` and `$b`. Checks if `$b` is `-in` the group (`$a-5`, `5-$a` `5+$a`, or `$a`), which checks all possible combinations of `$a`,`$b`, and `5`. *-4 bytes thanks to mazzy.* *-4 bytes thanks to KGlasier.* [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 24 bytes *-1 byte thanks to Grimy* ``` {$^a-$^b==5|0|-5|5-2*$b} ``` [Try it online!](https://tio.run/##RYzBCoMwAEPv/YocZOiw0ta1t7rbvmC3oqCswkCn1MkY1m/v3EVDCHkQMlrXqdB/cWqhEZaoqmlUNVpLzzyVXlJxjpo1tIND3D1fdkqKIvsM7jFhIdg0zm@Yaxv7zLCUl0maGZHmZUnWcAGHLnB3syWcYfNOyP/9VneTJQriAA61r6iQClscL@p4/AE "Perl 6 – Try It Online") This uses the Any Junction but technically, `^` could work as well. ### Explanation: ``` { } # Anonymous code block $^a-$^b== # Is the difference equal to | | | # Any of 0 5 -5 5-2*$b ``` [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~26~~ 70 bytes **Edit:** + input variables. ``` Procedure z(a,b:integer);begin Writeln((abs(a-b)in[0,5])or(a+b=5))end; ``` [Try it online!](https://tio.run/##TcxBCsIwEIXhvafIcgYTsYUiGHoHdy7ExSQdQ6AmYVpBvHysitDdB@/xF5o8jeZWfC2Sg9BdPW09SfY8PITVC0i7Y0wzBxa0jkNM6ixx5jEBkJuAjMOYLnvdXTEL0Nb1HSKnwdbve7M0mlY3LdoPzUGblf9c67cvhV19Aw "Pascal (FPC) – Try It Online") --- ``` (abs(a-b)in[0,5])or(a+b=5) ``` [Try it online!](https://tio.run/##DcnBCsIwDADQ@74ixxZXUWEIjv2Elx3EQ9JlpVC7ko7h1xt7fa9g9ZjcWrwW2YLgB75jBwcKYE@PmHcOLE2IQ8wdwJNxSdm0tE1hlrizUYNUDTqyMb8u/fC2mxg80TRYtSNwXs7q7uCuN/j5NWGo@gc "Pascal (FPC) – Try It Online") I hope that my answer is according to all rules of code-golf. It was fun anyway. [Answer] # x86-16 machine code, ~~21~~ 20 bytes ``` 00000000: 8bd0 2bc3 740d 7902 f7d8 3c05 7405 03d3 ..+.t.y...<.t... 00000010: 80fa 05c3 .... ``` Listing: ``` 8B D0 MOV DX, AX ; Save AX to DX 2B C3 SUB AX, BX ; AX = AX - BX 74 0D JZ DONE ; if 0, they are equal (ZF=1) 79 02 JNS IS_POS ; if positive, check if result is 5 F7 D8 NEG AX ; is negative, negate the result to get abs value IS_POS: 3C 05 CMP AL, 5 ; is result 5? 74 05 JZ DONE ; if so, exit with ZF=1 03 D3 ADD DX, BX ; DX = DX + BX 80 FA 05 CMP DL, 5 ; ZF = ( DX == 5 ) DONE: C3 RET ; return to caller ``` Input numbers in `AX` and `BX` and returns Zero Flag (`ZF`) if result is truthy. [Try it online!](https://tio.run/##dVThUuJIEP6deYqu1LoQnSBB8WpBtERwva1VLNEry41FDckAuQ0TLjPReC7P7vUMiYi1l4LJ9HT3191fd2bM5Ow1YAoOD/uDMziCXTVf7LIak3Nog9Avd8LjyV7jvcZNVlKQhLyWoCEPZgnYhOeKpwIioWA0Ykql0ThTfDSqVidMqoDFsePAJBNBFU0o/p02kDmLRNV5IdpLcankj4fOi0/2qUeJV6f4Ix7do@SANvTugBK30TyguHj60CPLNpkkqYaEqFNvR4cy@pcnk6oBc3YLyUSLdjoNDLVIUZpUfXsrpFthC7akL3ybrqJHD@Vmx3ugJtvfKJxj375JM@7bLd8@Y7HEndMmS7K0Sxalysa1oO0Tn0yDYJM0pPS90QadrkjcRcTBne81jHcy/jvM5gtwe@BeaHZ5vOFw9PmDndxQ/0JaORxVdZs9tHV@wTTlaNaHyo@6@@XhZX8JFTQLMgXuGP5w9xvaKQU3hIovKmvBmGk0gz/jeU3lCo@esLwA3@zpJ1ReDL3wydttLLX9im2wfbG9vd19VhyCJBOqhZIvNPU2fDLJuc5bKWagXF44nfNcF6Y9bGMCeR6CizktPmaiFSXIBt2vkgcqSgTUFI4psaZxMmaxmUail5aFTxvZXWRKapL3GiOFg50DEyHwMCdQPHen51@hf3JHoX96B9qJhWyhoJxxUAlSKVUyBy1GYooFi0cudPgPKF2N0rsjxLoY/AV6SzW0QR2yRw64Rzi0sIa3XSjCdlcGqOvoxYUu6r/dI2pvcNk3umgCdQpqxoVenoGlHPg/GVZcvT/reA7aXw4B/hyOrgbD0mORyEhFj5xCMOPBT32UcpnF@GFJaBKwLvtf4S0/PBN8ylYOZsd1rNIF055yBWws4ZHFGSerWC1inV5cAZx8p9AsYAqP5vFvqpAJBZ5HCp4iNQOdO7FOer2Sq4KKnqYClx1DhQnQ0wFKlCY1rhbR0JiC9a5tqW7U//UL8GrB/FSWihYUfob3@zM4Bg9aUH9rqckdq7y5vu2XDOEdoWbPmnTneN37wXXZypLLCZhL5JmCRNJMhDXwdf@GFLitt8Or2@E5eGtxcLVuDUeodfR3mB5OGqK94mX/@h8 "Bash – Try It Online") (testing code borrowed and adapted from [@Logem's answer](https://codegolf.stackexchange.com/a/178821/84624) - thanks!) *Explanation:* If the difference between the numbers is 0, they are equal. Otherwise if result is negative, first negate it (abs value) and check for 5. If still not true, add and check for 5. *Bonus:* If desired, you can also determine which condition was true with the following: * `ZF` = `1` and `DX` = `5` ; sum is 5 * `ZF` = `1` and `AX` = `5` ; diff is 5 * `ZF` = `1` and `AX` = `0` ; equal * `ZF` = `0` ; falsey [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` OIÆ‚Ä50SåZ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f3/Nw26OGWYdbTA2CDy@N@v8/WtfQyFAHSJjFAgA "05AB1E – Try It Online") --- ``` O # Sum the input. IÆ # Reduced subtraction of the input. ‚ # Wrap [sum,reduced_subtraction] Ä # abs[sum,red_sub] 50S # [5,0] å # [5,0] in abs[sum,red_sub]? Z # Max of result, 0 is false, 1 is true. ``` Tried to do it using stack-only operations, but it was longer. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~43~~, ~~48~~, ~~47~~, 33 bytes EDIT: Tried to use % and apparently forgot how to %. Thanks to Arnauld for pointing that out! EDIT2: AdmBorkBork with a -1 byte golf rearranging the parentheses to sit next to the return so no additional space is needed! EDIT3: Thanks to dana for -14 byte golf for the one-line return shortcut and currying the function (Ty Embodiment of Ignorance for linking to TIO). # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 33 bytes ``` a=>b=>a==b|a+b==5|(a-b)*(a-b)==25 ``` [Try it online!](https://tio.run/##hc2xCgIxDAbgvU@RsVVPVKyL5hbBSUFwcE57VQq1lWtPEPXZz54Obh6BP4F8JDoWOtSmbaL1ZzjcYzKXJdOOYoR9Hc41XR4M4NooZzXERCm3W7AV7Mh6LrolwKbxemV9Gv0mFYIrS6gAW8JSYUmI6klDhSifnAolBp9EnMl2yb6fx@vgY3BmfKxtMlvrDa@4FHwqhfhrphPB@8xcdKznTjY9pJjJrHIuOsjYK1d7amzlIrkTvQE "C# (.NET Core) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 33 bytes ``` f(a,b){a=!(a+b-5&&(a-=b)/6|a%5);} ``` [Try it online!](https://tio.run/##FY3BCsIwEETv@YoasGTpBttqIxiDN7/AW@lhE6jkYBWtp5pvj9uBGRgewwR9DyHnURF6WMhtFFVed2WpSDsPO/OjbQc25QfFSUGxiDjNBfWDWw7Y1NigYeu2M2gSioLlV9iscI8tY4bckhXj863WdXS1jeejjVUF4vWdP4rv@zig54CLvMmTvEqwIuU/ "C (gcc) – Try It Online") Tried an approach I didn't see anyone else try using. The return expression is equivalent to `a+b==5||((-6<a-b||a-b<6)&&(a-b)%5==0)`. --- [Answer] # Scala, 43 bytes ``` def f(a:Int,b:Int)=a+b==5|(a-b).abs==5|a==b ``` [Try it online!](https://tio.run/##dcyxCoMwFAXQ3a94SIeEajFaHQopdOzQj3jRCBaJ0mQoqN@eJoGiRZrhQi7nXV1jj3YQT1kbeGCnQL6NVI2G2zjCFNlGttASvNyVSYRPyvEoOC/nmWAq6AmFDj/kXFiA8dUp0yui43MC7jEf/AqHqSWuYXSJabRlLPOOZSvzDcv2MOwVmz3XFDtWBZZvmGvyP2vV71q1Y2leunOX7MvWJuDFfgA) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` =|+5|-ȧ5 ``` Takes input as a list of two numbers (use `_` for negatives). [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/37ZG27RG98Ry0///ow11zGIB "Brachylog – Try It Online") ### Explanation Pretty much a direct translation of the spec: ``` = The two numbers are equal | or + The sum of the two numbers 5 is 5 | or - The difference of the two numbers ȧ absolute value 5 is 5 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~41~~ 34 bytes ``` f(a,b){a=5==abs(a-b)|a+b==5|a==b;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1EnSbM60dbU1jYxqVgjUTdJsyZRO8nW1rQm0dY2ybr2f25iZp6GJlc1l4KCQkFpSbFGmoahkY6hgaa9UkhRaaqSlZJbYk5xqpKmNReyEh0TLAqQ5A2wG4FsghkW@dr/AA "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ``` ÐO5Qs`α5QrËO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8AR/08DihHMbTQOLDnf7//8frWtkaqYDJAxjAQ "05AB1E – Try It Online") Takes input as a list of integers, saving one byte. Thanks @Wisław! # Alternate 12 byte answer ``` Q¹²α5Q¹²+5QO ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/8NDOQ5vObTQF09qmgf7//@samZpxAQlDAA "05AB1E – Try It Online") This one takes input on separate lines. [Answer] ## [Ruby](https://www.ruby-lang.org/en/), 34 Bytes ``` ->(a,b){[a+5,a-5,5-a,a].include?b} ``` [Online Eval](https://tio.run/##KypNqvyfZvtf104jUSdJszo6UdtUJ1HXVMdUN1EnMVYvMy85pzQl1T6p9n@BQlq0iY6CYSwXiGVoAGQaQNk6CsYQlpmOghFczAzC0jUyBQoDSUO4GigLaI2Caex/AA) - Thanks @ASCII-Only [Answer] # [Factor](https://factorcode.org/), ~~44~~ 40 bytes Saved 4 bytes thanks to @chunes! ``` [ { [ = ] [ - abs 5 = ] [ + 5 = ] } || ] ``` [Try it online!](https://tio.run/##LYi9CgIxEAZ7n@LrJQGFs1CsxcZGrI4r9pbIBfNzbNZCPJ89prhmmJknsWapj/v1djmCcxx9onaKLVMWNeyF315tiSSKl5PkAiLphFmc6mcWnxSnjdl3BzTsao8vepwxNBrQWNCttV3th2XBUJlCgK1/ "Factor – Try It Online") The repetition of `=` is annoying, but I couldn't find another way. `||` tries out each of the three quotations in `{...}` and checks if the result is true for any of them. The first, `[ = ]`, checks if they're equal, the second finds the absolute value of their difference and compares that to 5, and the third compares their sum to 5. [Answer] # [Tcl](http://tcl.tk/), 53 bytes ``` proc P a\ b {expr abs($a-$b)==5|$a==$b|abs($a+$b)==5} ``` [Try it online!](https://tio.run/##LYuxCoNAEAX7/YpXbGEIgmv0uvsH@8RiV@wMHmpAOO/bL4I2MzAw2zDlHJZ5QAf9wBDHPSxQWwvWku3hfXuwes92XPF5xZSnr4b7oQZCUkEqErzIoT7tqKxbhxNCCTH8thXvDqxg61P@Aw "Tcl – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes ``` ¥VªaU ¥5ª5¥Nx ``` [Try it online!](https://tio.run/##y0osKPn//9DSsEOrEkMVDi01PbTK9NBSv4r//w0VzAA "Japt – Try It Online") [Answer] ## Batch, 81 bytes ``` @set/as=%1+%2,d=%1-%2 @if %d% neq 0 if %d:-=% neq 5 if %s% neq 5 exit/b @echo 1 ``` Takes input as command-line arguments and outputs 1 on success, nothing on failure. Batch can't easily do disjunctions so I use De Morgan's laws to turn it into a conjunction. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` Nθ¿№⟦θ⁺⁵θ⁻⁵θ⁻θ⁵⟧N1 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orM01Bwzm/NK9EI7pQRyEgp7RYw1RHoVBTR8E3Mw@dA1Rhqhmro4BsiKampkJAUSbQACVDJU3r//91jUzNFICE4X/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Port of @ArBo's Python 2 solution. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes ``` \d+ $* ^(-?1*) \1$|^(-?1*)1{5} -?\2$|^-?(-?1*) (\3)1{5}$|^-?(1 ?){5}$|^(1 ?-?){5}$ ``` [Try it online!](https://tio.run/##LYmxDkAwFEX39xVvIGnJS9yWrh39RCMkDBaD2PDtVWq5955z9@VYtymWqh9jmGsqKhqUeFSaA4rr3zi7m8UHk4z4/1fBfkd2YK8zvFMyxNgyCA2jIbAlxya1IzGd4xRIBg8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The first two lines convert the inputs into unary. The final line then checks for any of the permitted matches: ``` ^(-?1*) \1$ x==y ^(-?1*)1{5} -?\2$ x>=0 y>=0 x=5+y i.e. x-y=5 x>=0 y<=0 x=5-y i.e. x+y=5 x<=0 y<=0 x=y-5 i.e. y-x=5 ^-?(-?1*) (\3)1{5}$ x<=0 y<=0 y=x-5 i.e. x-y=5 x<=0 y>=0 y=5-x i.e. x+y=5 x>=0 y>=0 y=5+x i.e. y-x=5 ^-?(1 ?){5}$ x>=0 y>=0 y=5-x i.e. x+y=5 x<=0 y>=0 y=5+x i.e. y-x=5 ^(1 ?-?){5}$ x>=0 y>=0 x=5-y i.e. x+y=5 x>=0 y<=0 x=5+y i.e. x-y=5 ``` Pivoted by the last column we get: ``` x==y ^(-?1*) \1$ x+y=5 x>=0 y>=0 ^-?(1 ?){5}$ x>=0 y>=0 ^(1 ?-?){5}$ x>=0 y<=0 ^(-?1*)1{5} -?\2$ x<=0 y>=0 ^-?(-?1*) (\3)1{5}$ x<=0 y<=0 (impossible) x-y=5 x>=0 y>=0 ^(-?1*)1{5} -?\2$ x>=0 y<=0 ^(1 ?-?){5}$ x<=0 y>=0 (impossible) x<=0 y<=0 ^-?(-?1*) (\3)1{5}$ y-x=5 x>=0 y>=0 ^-?(-?1*) (\3)1{5}$ x>=0 y<=0 (impossible) x<=0 y>=0 ^-?(1 ?){5}$ x<=0 y<=0 ^(-?1*)1{5} -?\2$ ``` [Answer] # Japt, ~~13~~ 12 bytes ``` x ¥5|50ìøUra ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=eCClNXw1MOz4VXJh&input=WzQsMV0=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=eCClNXw1MOz4VXJh&input=WwpbNCwxXQpbMTAsMTBdClsxLDNdCls2LDJdClsxLDZdClstMjU2LC0yNTFdClstNSw1XQpdCi1tUg==) ``` x ¥5|50ìøUra :Implicit input of array U x :Reduce by addition ¥5 :Equal to 5? | :Bitwise OR 50ì :Split 50 to an array of digits ø :Contains? Ur : Reduce U a : By absolute difference ``` ]
[Question] [ *This challenge is [NinjaBearMonkey](https://codegolf.stackexchange.com/users/29750/ninjabearmonkey)'s prize for winning my [Block Building Bot Flocks!](https://codegolf.stackexchange.com/questions/50690/block-building-bot-flocks) challenge with the [Black Knight](https://codegolf.stackexchange.com/a/50763/26997) submission. Congratulations NinjaBearMonkey!* The challenge here is fairly simple, but has a variety of possible approaches. The story goes that in the world of [Isometric Illusions](https://i.stack.imgur.com/6X4J9.jpg?s=328&g=1), there are 6 different types of creatures: 1. Ninjas, abbreviated `N` 2. Bears, abbreviated `B` 3. Monkeys, abbreviated `M` 4. NinjaBears, abbreviated `NB` 5. BearMonkeys, abbreviated `BM` 6. NinjaBearMonkeys, abbreviated `NBM` ([NinjaBearMonkey](https://codegolf.stackexchange.com/users/29750/ninjabearmonkey) is, of course, the last, most powerful type.) Your task is to take a [census](https://en.wikipedia.org/?title=Census) of these creatures when they are lined up side-by-side, i.e. when their abbreviation strings are concatenated. The caveat is that you need to make sure not to over-count the parts of some creatures as separate creatures that happen to look similar. The creatures will line up such that: * Any instance of `NBM` is 1 NinjaBearMonkey and 0 other creatures. * Any instance of `NB` not followed by `M` is 1 NinjaBear and 0 other creatures. * Any instance of `BM` not preceded by `N` is 1 BearMonkey and 0 other creatures. * Otherwise, instances of `N`, `B`, and `M` are single Ninjas, Bears, and Monkeys respectively. The line is read from left to right. So, for example, in the line of creatures `NBMMBNBNBM`, there are 0 Ninjas, 1 Bear, 1 Monkey, 1 NinjaBear, 0 BearMonkeys, and 2 NinjaBearMonkeys. # Challenge Write a program or function that takes in a string of the characters `N`, `B`, and `M`, and prints or returns how many of each of the 6 types of creatures are present in it. The output should have the form ``` #N #B #M #NB #BM #NBM ``` with the respective creature count replacing each `#` sign. All 6 counts must be shown, separated by spaces, even when they are 0. However, they may be in any order (e.g. `#NBM` could come first). Also: * The input string will only contain the characters `N`, `B`, and `M`. * If the empty string is input, then all the counts are 0. * The output may optionally contain a single leading and/or trailing space, and/or a single trailing newline. **The shortest submission in bytes wins.** # Examples Input: `NB` Output: `0N 0B 0M 1NB 0BM 0NBM` Input: `NBM` Output: `0N 0B 0M 0NB 0BM 1NBM` Input: `NBMMBNBNBM` (example from above) Output: `0N 1B 1M 1NB 0BM 2NBM` Input: `MBNNBBMNBM` Output: `1N 1B 1M 1NB 1BM 1NBM` Input: `NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM` Output: `17N 6B 14M 5NB 8BM 3NBM` [Answer] # JavaScript ES6, 86 bytes ``` f=s=>'NBM BM NB M B N'.replace(/\S+/g,e=>(i=0,s=s.replace(RegExp(e,'g'),_=>++i))&&i+e) ``` (I just had to answer this.) It goes through each substring of `NBM`, starting with the longer ones, which take higher priority. It searches for each occurrence of that particular string and removes it (in this case replacing it with the current count so it won't be matched again). It finally replaces each substring with the count + the string. This Stack Snippet is written in the ES5 equivalent of the above code to make it easier to test from any browser. It is also slightly ungolfed code. The UI updates with every keystroke. ``` f=function(s){ return'NBM BM NB M B N'.replace(/\S+/g,function(e){ i=0 s=s.replace(RegExp(e,'g'),function(){ return++i }) return i+e }) } run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('input').onkeyup=run;run() ``` ``` <input type="text" id="input" value="NBMMBNBNBM" /><br /><samp id="output"></samp> ``` [Answer] # Pyth, 22 bytes ``` f|pd+/zTT=:zTd_.:"NBM ``` Quite hackish way to save 1 byte, thanks to @Jakube. --- # Pyth, 23 bytes ``` FN_.:"NBM")pd+/zNN=:zNd ``` [Demonstration.](https://pyth.herokuapp.com/?code=FN_.%3A%22NBM%22)pd%2B%2FzNN%3D%3AzNd&input=NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM&debug=0) Prints in reverse order, with a trailing space and no trailing newline. `.:"NBM")` is all the substrings, `_` puts them in the right order, `/zN` counts occurences, and `=:zNd` in-place substitutes each occurence of the string in question with a space. ``` FN_.:"NBM")pd+/zNN=:zNd FN for N in : _ reversed( ) .: ) substrings( ) "NBM" "NBM" pd print, with a space at the end, /zN z.count(N) + N + N =:zNd replace N by ' ' in z. ``` [Answer] ## Python 2, 78 ``` n=input() for x in"NBM BM NB M B N".split():n=`n`.split(x);print`len(n)-1`+x, ``` A variant of [Vioz-'s answer](https://codegolf.stackexchange.com/a/51821/20260). Fun with Python 2 string representations! Counts occurrences of the substring indirectly by splitting on it, counting the parts, and subtracting 1. Instead of replacing the substrings by a filler symbol, replaces the string by the list that `split` produced. Then, when we take its string representation, the parts are separated by spaces and commas. [Answer] # Ruby, ~~166~~ ~~80~~ ~~72~~ 68 characters ``` f=->s{%w(NBM BM NB M B N).map{|t|c=0;s.gsub!(t){c+=1};c.to_s+t}*' '} ``` Explanation: * The counting is done in reverse. This is because the longer ninjas and bears and monkeys take precedence over the shorter ones. * For `NBM`, `BM`, and `NB`, the sequences are `gsub!`'d out of the original string with a block to count how many of these sequences exist (yes, the function modifies its argument). + However, they can't be replaced with nothing, since otherwise `BNBMM` would be counted as `NBM` and `BM` instead of `B`, `NBM`, and `M` (because when the `NBM` would be removed, it would put the `B` and `M` together and there wouldn't be a way to distinguish it). Originally I returned a single character string (`.gsub!('NBM'){c+=1;?|}`), but I realized I could just return the result of the `+=` (which is a number, so it can't be any of `N` `B` `M`). * ~~For `M`, `B`, and `N`, I can just `count` how many of them there are in the string (no need to remove them via `gsub!`).~~ Now it's a loop (don't know why I didn't think of that in the first place), so these are done the same way. --- Similar solution in **[Ostrich](https://github.com/KeyboardFire/ostrich-lang), ~~54~~ 51 chars**: ``` :s;`NBM BM NB M B N`" /{:t0:n;s\{;n):n}X:s;nt+}%" * ``` Unfortunately not a valid solution, as there is a bug in the current Ostrich version (that is now fixed, but after this challenge was posted). [Answer] # Java, ~~166~~ 162 ``` void f(String a){String[]q="NBM-NB-BM-N-B-M".split("-");for(int i=0,c;i<6;System.out.print(c+q[i++]+" "))for(c=0;a.contains(q[i]);c++)a=a.replaceFirst(q[i],".");} ``` And with a few line breaks: ``` void f(String a){ String[]q="NBM-NB-BM-N-B-M".split("-"); for(int i=0,c;i<6;System.out.print(c+q[i++]+" ")) for(c=0;a.contains(q[i]);c++) a=a.replaceFirst(q[i],"."); } ``` It works pretty simply. Just loop over the tokens, replacing them with dots and counting as long as the input contains some. Counts the big ones first, so the little ones don't mess it up. I originally tried replacing all at once and counting the difference in length, but it took a few more characters that way :( [Answer] # CJam, ~~36~~ ~~32~~ 31 bytes ``` l[ZYX]"NBM"few:+{A/_,(A+S@`}fA; ``` *Thanks to @Optimizer for golfing off 1 byte.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l%5BZYX%5D%22NBM%22few%3A%2B%7BA%2F_%2C(A%2BS%40%60%7DfA%3B&input=NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM). ### How it works ``` l e# Read a line L from STDIN. [ZYX]"NBM" e# Push [3 2 1] and "NBM". few e# Chop "NBM" into slices of length 3 to 1. :+ e# Concatenate the resulting arrays of slices. { }fA e# For each slice A: A/ e# Split L at occurrences of A. _,( e# Push the numbers of resulting chunks minus 1. A+ e# Append A. S e# Push a space. @` e# Push a string representation of the split L. ; e# Discard L. ``` [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 6284 bytes ``` Go to Post Office:W 1 L 1 R 1 L.Pickup a passenger going to Chop Suey.Go to Chop Suey:N 1 R 1 L 4 R 1 L.[A]Switch to plan N if no one is waiting.Pickup a passenger going to Cyclone.N is waiting at Writer's Depot.Go to Zoom Zoom:N 1 L 3 R.Go to Writer's Depot:W.Pickup a passenger going to Crime Lab.Go to Cyclone:N.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:S 1 L 2 R 1 L.Go to Cyclone:S 1 R 1 L 2 R.Pickup a passenger going to Crime Lab.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:S 1 L 2 R 1 L.Go to Crime Lab:S 1 L 1 L.Switch to plan F if no one is waiting.Pickup a passenger going to Auctioneer School.Go to Rob's Rest:S 1 R 1 L 1 L 1 R 1 R.Switch to plan D if no one is waiting.Go to Bird's Bench:S.Switch to plan B if no one is waiting.Go to Rob's Rest:N.Pickup a passenger going to KonKat's.Go to Bird's Bench:S.Pickup a passenger going to KonKat's.Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N 1 L 2 L 1 L.Go to Auctioneer School:S.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:N 2 L 1 R.Go to Cyclone:S 1 L 1 L 2 L.Switch to plan C.[B]Go to Auctioneer School:N 1 R 1 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N.Go to Cyclone:N 1 L.[C]Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:N 2 R.Go to Chop Suey:E 2 R.Switch to plan A.[D]Go to Bird's Bench:S.Switch to plan E if no one is waiting.Pickup a passenger going to Sunny Skies Park.[E]Go to Auctioneer School:N 1 R 1 R.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:N 2 L 1 R.Go to Sunny Skies Park:S 1 L 1 L.Go to Cyclone:N 1 L.Switch to plan C.[F]B is waiting at Writer's Depot.Go to Writer's Depot:S 1 R 1 L 2 L.Pickup a passenger going to Crime Lab.Go to Cyclone:N.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Crime Lab.Go to Crime Lab:S 1 L 2 R 2 L.Switch to plan J if no one is waiting.Pickup a passenger going to Auctioneer School.Go to Bird's Bench:S 1 R 1 L 1 L 1 R 1 L.Switch to plan I if no one is waiting.Go to Rob's Rest:N.Switch to plan G if no one is waiting.Pickup a passenger going to KonKat's.[G]Go to Bird's Bench:S.Pickup a passenger going to KonKat's.Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N 1 L 2 L 1 L.Go to Auctioneer School:S.[H]Pickup a passenger going to Bird's Bench.Go to Bird's Bench:N 2 L 1 L.Go to Cyclone:N 1 R 1 L 2 L.Switch to plan C.[I]Go to Auctioneer School:N 1 R 1 R.Switch to plan H.[J]Go to Bird's Bench:S 1 R 1 L 1 L 1 R 1 L.Switch to plan L if no one is waiting.Go to Rob's Rest:N.Switch to plan K if no one is waiting.Pickup a passenger going to KonKat's.[K]Go to Bird's Bench:S.Pickup a passenger going to KonKat's.[L]Go to Cyclone:N 1 R 1 L 2 L.Pickup a passenger going to KonKat's.Go to KonKat's:N 2 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Rob's Rest:S 4 R 1 L 1 L 1 R 1 R.Switch to plan M if no one is waiting.Pickup a passenger going to Sunny Skies Park.[M]Go to Sunny Skies Park:S 1 L 1 L.Go to Chop Suey:N 1 R 1 R 3 R.Switch to plan A.[N]Go to Rob's Rest:N 1 L 3 L 1 L 2 R 1 R.Switch to plan O if no one is waiting.Pickup a passenger going to KonKat's.[O]Go to Bird's Bench:S.Switch to plan P if no one is waiting.Pickup a passenger going to KonKat's.[P]Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Switch to plan Q if no one is waiting.Pickup a passenger going to Sunny Skies Park.[Q]Go to Sunny Skies Park:N 1 L 2 L 1 L.N is waiting at Writer's Depot.B is waiting at Writer's Depot.M is waiting at Writer's Depot.NB is waiting at Writer's Depot.BM is waiting at Writer's Depot.NBM is waiting at Writer's Depot.Go to Writer's Depot:N 1 L.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Go to Joyless Park:N 3 R 2 R 2 L.Go to Writer's Depot:W 1 R 2 L 2 L.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Go to Joyless Park:N 3 R 2 R 2 L.[R]Switch to plan Y if no one is waiting.Pickup a passenger going to Cyclone.0 is waiting at Starchild Numerology.Go to Starchild Numerology:W 1 L 2 R 1 L 1 L 2 L.Pickup a passenger going to Addition Alley.Go to Cyclone:W 1 R 4 L.[S]Pickup a passenger going to Auctioneer School.Go to Zoom Zoom:N.Go to Auctioneer School:W 2 L.Go to Sunny Skies Park:N.Switch to plan V if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 L.Pickup a passenger going to Crime Lab.Pickup a passenger going to Crime Lab.Go to Crime Lab:S 1 L 2 R 2 L.Switch to plan T if no one is waiting.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:N 1 L 1 L.1 is waiting at Starchild Numerology.Go to Starchild Numerology:S 1 R 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 Addition Alley.Go to Cyclone:N 1 L 1 L.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:N 2 R.Go to Auctioneer School:W 2 L 1 L.Switch to plan U.[T]Go to Cyclone:N 4 L 2 L.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:N 2 R 1 L 1 R.Go to Auctioneer School:W 1 L 1 R 2 L 1 L.[U]Pickup a passenger going to Cyclone.Go to Cyclone:N 4 L.Switch to plan S.[V]Go to Addition Alley:N 1 R 1 R 1 R.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:N 1 R 1 R.Pickup a passenger going to Post Office.Go to Cyclone:N 1 L 1 L 2 R.Pickup a passenger going to Post Office." " is waiting at Writer's Depot.Go to Writer's Depot:S.Pickup a passenger going to Post Office.Go to Post Office:N 1 R 2 R 1 L.Go to Auctioneer School:S 1 R 1 L 1 L.Pickup a passenger going to Tom's Trims.Go to Narrow Path Park:N 3 R 1 R 1 L 1 R.[W]Switch to plan X if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:W 1 L 1 R 2 L 1 L.Go to Zoom Zoom:N 1 R.Go to Narrow Path Park:W 1 L 1 L 1 R.Switch to plan W.[X]Go to Tom's Trims:E 1 R 4 R 1 L.Go to Joyless Park:N 1 R 1 L 3 R.Switch to plan R.[Y] ``` [Try it online!](https://tio.run/##3Vhbc6IwFP4rmb70jdlan3yT1t7U1IKt7TJ5oBglUyQOYF1/vRsgaAyRm@7szs54DTk5t@/cEtm/yHZ7T0FEwYiGEXiezYiDOxNwBQbsbcTf2og4X6slsMHSDkPsz3EA5pT485jqxqVLYK7wRktP2f3vwIwetPk5VheZaxI5brxx6dk@gIDMgE8B9TEgIVjbJGLnFjPcOB7brkGBANgRmAQkwsFlCG7xkkZcmp@ULpKPRJoBuAYGf3K4vTMp5hmQBQYD@zNTMpWhAytJKtFwsyTvSvR/kseYLpgNxky/sPK@lJew0jET47a4mw9lMXcwaJXpu7PymSXJzuVP4ycSDu/q47C7ciLC9rM103Ep9Tg3g34yaQwcRoLq@2gyZNa3atbpYToJpuw0HfuO2zFlUr2IVJCjGKZ96vft6DJUs6xBmf0VIr/FYVjmenPl@xtgfhEcgpEdfPET5WUexS3uxHRTzhElUu8No7AUP9tQgHiQ8ZbdcKNZOjomC6wUhpX1VwQ6y6s3qFBh8o2Db4LXQA/IdJ4lC3k5Ud7IpfFesiqp3NWsW1QFor36gZWzhdU70bp1PJ4z@T5nqEyfh8Id0qtUJqn@iFly8C/WIpmrlFNbSZDn7PF0vrx6iDNFZs0xf6ycHiXC@/pS71KhdY/@ozxqPRRmFlFHlZugxELG3bF0@lgh4CWqB816Qk2RMmiKlP4pSOmfgBRrgIpM2gxtreYIO@h62uVdz/AcdWGIqubs3FBiJKNAvqpBpKgQ6eQwECNRJn0@BQjPlUrp6BQWI1Qpt0gsX87hpRdUKQmVzHMlRXVY/BiWkOul9MMGRR2WTs9PdOPhkFvq/BtTqcQlJtN16uskT6hnYQ6H8lTyt8W3DPlC4aP5hcIPycNmZAeOS7wpgKsFDqhH59klh@oRvzNpCbmvzHzd6ZTE9Q10PW9/gcITeuqFdqyliZo0TMLdx9EKPxFQoBg2JOO@NTeuqnc@/S6gYVc6rq9H8a0D3NWbqxNBdNiuNALQ4SLH0XXFPr8Qkns1zz1uHkGmqld71axxrvdpVzAWtIOArhm0I1dML/Iy74OuDqZClXxZd5PJab2iJpHQzqvI@u43pHRmjYs9FwPd/sTejIQuDjJXyssVJ2jhbvgYJko7R/GMC3DRZEiuKaN4ow2zHqd44hHDr2ZCUABpH3UpmKyJXK/ez9BhHUnfeYSq7sSNY9JPxBZeRuhEs95RPg/2eM0SjSyV78wcivab2ecDbbcQwiHrt4bpK/4ZL0CoJ2@dvWC8qid7dLZHZ79h/D2Mt7GfKelv "Taxi – Try It Online") This ain't winning me any Code Golf competitions, but this was a nice reminder for me not to write any more complex programs in Taxi. *(Sooo many special cases, and sooo much gas management...)* A more commented version can be found [here](https://tio.run/##1VlLb@M2EL77VxC@5BIEjZOTT43axWK7jhrYCwSo4QMt0xZrWXQpOln/@nQoURJFUaYkK0AL@EkNh8OZbx4cCvyTfnx8ZUgw9MISgf7cbmlApq/oHs3gPZffd6MXGuxPR4TREScJiXeEox2j8U5O@y1kR7Q4kfPdKONTDEz9nAN6zDmNlkdOjpwFJEkkg4ix42q0/LWYtBot3qkIQsnpGOEYjUm8QfVJY0S3KGaIxQTRBL1jKuCRQ9RzEAH93cjXpiAs0CungvCbBP1OjkzkG/mLsUP6kW5khh7QPH9UnTB9dazL6YGgGV4XKsoEmfpSIYnAUYS2jKMDjIECWm3BYKQ0nb5bKuFzl/nBDqCeH7DzpANhtpw2NF2kqp/k@KnKsygANnFuu7TB4NLkrNVjBXSAcchOAomQoNTGsMQt/APoSfSFOHsEuN5xfEDv7BRtJLT3KKJ7Ak7RDVKGEFLGCQiyGtUcClaPmUA@jf/GTW40WsK/lCL1zpz5ZXA@nQJBgROMLYKQsSgXbs7WoMI5SYRmsjLCgOlMGdOlkZJUSdUsa0GtxqTM5ZorJYVH@QaGPBIH4XRxYc08MqzBeh7BXMnhWh9DoMrJNUH0ZVd1hfiXAfmdxd@xuCnQaG6iy9z8vxaYJ8qfnf6zOMXxGS32lCToBfN9ztMcV7FykvtBRlVDhkv0UkEWDPmK/dwWD2b5@nUDc5iMubBkE7TlEOsVm7ENUiYYmixb36nfLmC2V7AtKsNuly23d9mH5/SN8DdK3pHH6WZXpABzPDXCvJ7zv2TDpuotCbyiZc3Nr3Fe3QW7RQ6NWjd13czdbGiLDcZeB0VRN7@pYUtLYFaMXeNRetoxkorXqh4zii49@c/6F2CfXG21zdNNWVqC5mKSlgRD5Oiqg1mytEXGTq7WKzU2rai7qu7DjuWlG7qKhXYZtbafmijt4tj/OH87E05t1mXl6qqxotI3xTIdcoC8P1SQ7ipDjZkeMy0@PozThuc1ZHO3z2Z0/Vy2kmJdCxbE5Yp9fNOy5pDuWIXJZeU0YLSn30@u8fXKMeyxzTGsvs1qCO0U@JuY9IjDtkKrg6x2LLSohmqtrXnWFWpZ7tpbWUb/y1K2Zd2nmR7x62uC7iOyFQzq9EQWUSWHPr0yHezNnPvV6iY/nX5oWasuaXdRV169JH8feW3o1XlKOXOZVi3ztKul6Sqxnx3PfRcDz83huU@Z77tb0H@wcwT@pHT5GZSZZPoYyPWQ4SOL5/a@sMJQi5j/X9jDaBmwUyyKoKTT2vvyJf1V/fhfDGAsoFQKQhpB9D4dCGcR2xXXC7Zn6r5ioqU0p8KfNhsqKy70FEXa5YXK1pnlHjOtkFiuhAUpw3WbVkrjUUu7WGgusF91XNmaQDZ7VCW9yibW8/8AHfb@J@JEcOABUZ2TNJmTf044ai47dPKUtMMp2XEN4JeFwf210K1W7T1hWx1V6H1o26S47AraZodvHDbg3n5y2UgjB@xwxNKySBl4bBq7wIb1yFRu67GNvn3MOXsHpxNhJY6a46o2v6822GzbywvuSXlVZN9Y60DT6LOPNi0aMSKvS@tBzgw6KzvYulwKhgR5eE2iLU1CwguomeNtu53alXUjat3HpQqXMRr3akZ2FlS/bvfzWtPRc9FDRed7TAtiywihUCt7OhELdBSY0@yFQGXaMDVxQ@azOJDtun7euO1X/dhra9ToO8m9o4Va6mniiyoiKmY1CrBc/dZjpFZe5YJcqtBGy2/qGnnH0BoHe8lJ3jH/wD8p@oo53pHbtE@5JgE@JaS4jQ7YhsCkaHuLBAnCmAY4is7oG4LIdAPHafwGtGz18eH7/jMU8s/ZS/6UA77vpW8PXr4c9VIaD2g8@O3L72dJBj@zqR//Ag "Taxi – Try It Online"), if you dare. [Answer] # R, ~~153~~ ~~134~~ 118 This got longer really quickly, but hopefully I'll be able to shave a few. Input is STDIN and output to STDOUT. **Edit** Change of tack. Got rid of the split string and counting parts. Now I replace the parts with a string one shorter than the part. The difference between the string lengths is collected for output. ``` N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim(' ',N(s)-1),i)),s),'') ``` Explanation ``` N=nchar; i=scan(,''); # Get input from STDIN for(s in scan(,'',t='NBM BM NB M B N')) # Loop through patterns cat( # output paste0( # Paste together N(i) - # length of i minus N(i<-gsub( # length of i with substitution of s, # s strtrim(' ',N(s)-1) # with a space string 1 shorter than s ,i) # in i ), s) # split string ,'') ``` Test run ``` > N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim(' ',N(s)-1),i)),s),'') 1: NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM 2: Read 1 item Read 6 items 3NBM 8BM 5NB 14M 6B 17N > N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim(' ',N(s)-1),i)),s),'') 1: NBMMBNBNBM 2: Read 1 item Read 6 items 2NBM 0BM 1NB 1M 1B 0N > ``` [Answer] # Pyth, 19 bytes ``` jd+Ltl=zc`zd_.:"NBM ``` This is a mixture of @isaacg's Pyth solution and @xnor's incredible Python trick. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=jd%2BLtl%3Dzc%60zd_.%3A%22NBM&input=NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=zFz.zs%5Bz%22%20%3D%3E%20%22%0Ajd%2BLtl%3Dzc%60zd_.%3A%22NBM&input=Test-cases%3A%0ANB%0ANBM%0ANBMMBNBNBM%0AMBNNBBMNBM%0ANNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM&debug=0) ### Explanation ``` jd+Ltl=zc`zd_.:"NBM implicit: z = input string .:"NBM generate all substrings of "NBM" _ invert the order +L add left to each d in ^ the following: `z convert z to a string c d split at d =z assign the resulting list to z tl length - 1 jd join by spaces and implicit print ``` [Answer] # Julia, ~~106~~ 97 bytes ``` b->for s=split("NBM BM NB M B N") print(length(matchall(Regex(s),b)),s," ");b=replace(b,s,".")end ``` This creates an unnamed function that takes a string as input and prints the result to STDOUT with a single trailing space and no trailing newline. To call it, give it a name, e.g. `f=b->...`. Ungolfed + explanation: ``` function f(b) # Loop over the creatures, biggest first for s = split("NBM BM NB M B N") # Get the number of creatures as the count of regex matches n = length(matchall(Regex(s), b)) # Print the number, creature, and a space print(n, s, " ") # Remove the creature from captivity, replacing with . b = replace(b, s, ".") end end ``` Examples: ``` julia> f("NBMMBNBNBM") 2NBM 0BM 1NB 1M 1B 0N julia> f("NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM") 3NBM 8BM 5NB 14M 6B 17N ``` [Answer] # Python 2, ~~93~~ ~~88~~ ~~89~~ 84 Bytes Taking the straightforward approach. ``` def f(n): for x in"NBM BM NB M B N".split():print`n.count(x)`+x,;n=n.replace(x,"+") ``` Call like so: ``` f("NBMMBNBNBM") ``` Output is like so: ``` 2NBM 0BM 1NB 1M 1B 0N ``` [Answer] # SAS, 144 142 139 129 ``` data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end; ``` Usage (7 bytes added for sysparm): ``` $ sas -stdio -sysparm NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM << _S data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end; _S ``` or ``` %macro f(i);i="&i";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1‌​,i);put a+(-1)z@;end;%mend; ``` Usage: ``` data;%f(NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM) ``` Result: ``` 3NBM 5NB 8BM 17N 6B 14M ``` [Answer] # PHP4.1, 92 bytes Not the shortest one, but what else would you expect from PHP? To use it, set a key on a COOKIE, POST, GET, SESSION... ``` <?foreach(split(o,NBMoNBoBMoMoBoN)as$a){echo count($T=split($a,$S))-1,"$a ";$S=join('',$T);} ``` The apporach is basic: * Split the string into the names of the creatures * Count how many elements there are * Subtract 1 (an empty string would give an array with 1 element) * Output the count and the creature name * Join it all together, using an empty string (which will reduce the string and remove the last creature) Easy, right? [Answer] # Perl, 46 ``` #!perl -p $_="NBM BM NB M B N"=~s/\w+/~~s!$&!x!g.$&/ger ``` [Answer] # JavaScript, ~~108~~ 116 bytes Just a straight forward approach, nothing fancy ``` o="";r=/NBM|NB|BM|[NMB]/g;g={};for(k in d=(r+prompt()).match(r))g[d[k]]=~-g[d[k]];for(k in g)o+=~g[k]+k+" ";alert(o); ``` [Answer] # SpecBAS - 164 ``` 1 INPUT s$ 2 FOR EACH a$ IN ["NBM","BM","NB","M","B","N"] 3 LET n=0 4 IF POS(a$,s$)>0 THEN INC n: LET s$=REPLACE$(s$,a$,"-"): GO TO 4: END IF 5 PRINT n;a$;" "; 6 NEXT a$ ``` Uses the same approach as a lot of others. Line 4 keeps looping over the string (from largest first), replaces it if found. SpecBAS has some nice touches over original ZX/Sinclair BASIC (looping through lists, finding characters) which I'm still finding out. [Answer] # C, 205 186 184 bytes A little different approach based on state machine. where `t` is the state. ``` a[7],t,i;c(char*s){do{i=0;t=*s==78?i=t,1:*s-66?*s-77?t:t-4?t-2?i=t,3:5:6:t-1?i=t,2:4;i=*s?i:t;a[i]++;}while(*s++);printf("%dN %dB %dM %dNB %dBM %dNBM",a[1],a[2],a[3],a[4],a[5],a[6]);} ``` Expanded ``` int a[7],t,i; void c(char *s) { do { i = 0; if (*s == 'N') { i=t; t=1; } if (*s == 'B') { if (t==1) { t=4; } else { i=t; t=2; } } if (*s == 'M') { if (t==4) { t=6; } else if (t==2) { t=5; } else { i=t; t=3; } } if (!*s) i = t; a[i]++; } while (*s++); printf("%dN %dB %dM %dNB %dBM %dNBM",a[1],a[2],a[3],a[4],a[5],a[6]); } ``` Test function ``` #include <stdio.h> #include <stdlib.h> /* * 0 : nothing * 1 : N * 2 : B * 3 : M * 4 : NB * 5 : BM * 6 : NBM */ #include "nbm-func.c" int main(int argc, char **argv) { c(argv[1]); } ``` [Answer] # C, 146 ``` f(char*s) { char*p,*q="NBM\0NB\0BM\0N\0B\0M",i=0,a=2; for(;i<6;q+=a+2,a=i++<2) { int n=0; for(;p=strstr(s,q);++n)*p=p[a>1]=p[a]=1; printf("%d%s ",n,q); } } // Main function, just for testing main(c,a)char**a;{ f(a[1]); } ``` [Answer] # Haskell - 177 bytes (without imports) ``` n s=c$map(\x->(show$length$filter(==x)(words$c$zipWith(:)s([f(a:[b])|(a,b)<-zip s(tail s)]++[" "])))++x++" ")l f"NB"="" f"BM"="" f p=" " l=["N","B","M","NB","BM","NBM"] c=concat ``` (Sorry for the internet necromancy here.) The Haskell Platform doesn't have string search without imports, and I wanted to show off and exploit the fact that the searched strings are all substrings of one (without repetitions), so that grouping characters can be done by identifying pairs that are allowed to follow each other, which is what `f` does here. I still need the full list `l` in the end to check for equality and display exactly as required, but would not, had the challenge only been to report the number of occurrences of the possible `words` in any order. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` `NBM`KṘ(n/₅‹n+¨…_∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60NBM%60K%E1%B9%98%28n%2F%E2%82%85%E2%80%B9n%2B%C2%A8%E2%80%A6_%E2%88%91&inputs=NBMN&header=&footer=) ``` `NBM` # 'NBM' K # Substrings Ṙ( # Iterate over n/ # Split current string by current substring of NBM ₅‹ # Duplicate and decrement length np¨…_ # Prepend current substring of NBM and output with a trailing space ∑ # Concatenate for next iteration ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 27 bytes ``` ;zS`+ös←Lx₁GoΣ`x⁰₁ ↔ÖLQ"NBM ``` [Try it online!](https://tio.run/##yygtzv7/37oqOEH78LbiR20TfCoeNTW6559bnFDxqHEDkM31qG3K4Wk@gUp@Tr7////38/PzBbJ8IQjEBAn4@TmBsRMQ@YFEncBqnIBqnIBsPxDtC1IGZEK0AgA "Husk – Try It Online") uses the splitting technique from the Vyxal answer. # [Husk](https://github.com/barbuz/Husk), 28 bytes ``` m§+osL←k€₁Ẋ`-U¡Ṡ-(→n₁ḣ Q"NBM ``` [Try it online!](https://tio.run/##yygtzv7/P/fQcu38Yp9HbROyHzWtedTU@HBXV4Ju6KGFD3cu0NV41DYpDyS2YzFXoJKfk@/////9/Px8gSxfCAIxQQJ@fk5g7AREfiBRJ7AaJ6AaJyDbD0T7gpQBmRCtAA "Husk – Try It Online") Funny set intersection based idea. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs in reverse order. ``` "NBM"ã ÔËiUèDU=rDS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=Ik5CTSLjINTLaVXoRFU9ckRT&footer=dw&input=Ik5OTk1OQk1NQk1NQk1NTU5CTU5OTU5OTkJOTk5CTkJCTkJOTU1OQkJOQk1NQkJNQk1CQkJOTk1CTUJNTU5OTk5OTU1CTU1CTSI) (footer reverses the output) ``` "NBM"ã ÔËiUèDU=rDS :Implicit input of string U "NBM"ã :Substrings of "NBM" Ô :Reverse Ë :Map each D i : Prepend UèD : Count of D in U U= : Reassign to U* rD : Replace D with S : Space :Implicit output joined with spaces ``` \*This is done within the second argument of the `è` method but as that only expects 1 argument, it's result is ignored within the mapping & prepending. [Answer] # Excel, ~~149~~ 145 bytes Saved 4 bytes by realizing I can directly use `LEN(a)` after I rewrote the function from my first - never submitted - draft. ``` =LET(a,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"NBM",1),"BM",2),"NB",3),LEN(a)-LEN(SUBSTITUTE(a,{"N","B","M",3,2,1},))&{"N","B","M","NB","BM","NBM"}) ``` Start by replacing NBM with 1 then BM with 2 and NB with 3. Now we have a string that is as many characters long as they are creatures. One by one, we check the difference between that string's length and it's length with one of the creatures removed. Output is an array of cells. [![Screenshot](https://i.stack.imgur.com/alWHz.png)](https://i.stack.imgur.com/alWHz.png) [Answer] # Bash - 101 ``` I=$1 for p in NBM BM NB M B N;{ c=;while [[ $I =~ $p ]];do I=${I/$p/ };c+=1;done;echo -n ${#c}$p\ ;} ``` Pass the string as the first argument. ``` bash nmb.sh MBNNBBMNBM ``` Explained a bit: ``` # We have to save the input into a variable since we modify it. I=$1 # For each pattern (p) in order of precedence for p in NBM BM NB M B N;do # Reset c to an empty string c= # Regexp search for pattern in string while [[ $I =~ $p ]];do # Replace first occurance of pattern with a space I=${I/$p/ } # Append to string c. the 1 is not special it could be any other # single character c+=1 done # -n Suppress's newlines while echoing # ${#c} is the length on the string c # Use a backslash escape to put a space in the string. # Not using quotes in the golfed version saves a byte. echo -n "${#c}$p\ " done ``` [Answer] # [rs](https://github/kirbyfan64/rs), 275 bytes ``` (NBM)|(NB)|(BM)|(N)|(B)|(M)/a\1bc\2de\3fg\4hi\5jk\6l [A-Z]+/_ # +(#.*?)a_b/A\1 +(#.*?)c_d/B\1 +(#.*?)e_f/C\1 +(#.*?)g_h/D\1 +(#.*?)i_j/E\1 +(#.*?)k_l/F\1 #.*/ # #(A*)/(^^\1)NBM # #(B*)/(^^\1)NB # #(C*)/(^^\1)BM # #(D*)/(^^\1)N # #(E*)/(^^\1)B # #(F*)/(^^\1)M # \(\^\^\)/0 #/ ``` [Live demo and tests.](http://kirbyfan64.github.io/rs/index.html?script=(NBM)%7C(NB)%7C(BM)%7C(N)%7C(B)%7C(M)%2Fa%5C1bc%5C2de%5C3fg%5C4hi%5C5jk%5C6l%0A%5BA-Z%5D%2B%2F_%0A%23%0A%2B(%23.*%3F)a_b%2FA%5C1%0A%2B(%23.*%3F)c_d%2FB%5C1%0A%2B(%23.*%3F)e_f%2FC%5C1%0A%2B(%23.*%3F)g_h%2FD%5C1%0A%2B(%23.*%3F)i_j%2FE%5C1%0A%2B(%23.*%3F)k_l%2FF%5C1%0A%23.*%2F%0A%23%0A%23(A*)%2F(%5E%5E%5C1)NBM%20%23%0A%23(B*)%2F(%5E%5E%5C1)NB%20%23%0A%23(C*)%2F(%5E%5E%5C1)BM%20%23%0A%23(D*)%2F(%5E%5E%5C1)N%20%23%0A%23(E*)%2F(%5E%5E%5C1)B%20%23%0A%23(F*)%2F(%5E%5E%5C1)M%20%23%0A%5C(%5C%5E%5C%5E%5C)%2F0%0A%20%23%2F&input=NB%0ANBM%0ANBMMBNBNBM%0AMBNNBBMNBM%0ANNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM) The workings are simple but a little odd: ``` (NBM)|(NB)|(BM)|(N)|(B)|(M)/a\1bc\2de\3fg\4hi\5jk\6l ``` This creatively uses groups to turn input like: ``` NBMBM ``` into ``` aNBMbcdeBMfghijkl ``` The next line: ``` [A-Z]+/_ ``` This replaces the sequences of capital letters with underscores. ``` # ``` This simply inserts a pound sign at the beginning of the line. ``` +(#.*?)a_b/A\1 +(#.*?)c_d/B\1 +(#.*?)e_f/C\1 +(#.*?)g_h/D\1 +(#.*?)i_j/E\1 +(#.*?)k_l/F\1 #.*/ ``` *This* is the beginning cool part. It basically takes the sequences of lowercase letters and underscores, converts them into capital letters, groups them together, and places them before the pound that was inserted. The purpose of the pound is to manage the sequences that have already been processed. ``` # ``` The pound is re-inserted at the beginning of the line. ``` #(A*)/(^^\1)NBM # #(B*)/(^^\1)NB # #(C*)/(^^\1)BM # #(D*)/(^^\1)N # #(E*)/(^^\1)B # #(F*)/(^^\1)M # \(\^\^\)/0 #/ ``` The capital letters are replaced by their text equivalents with the associated counts. Because of a bug in rs (I didn't want to risk fixing it and getting disqualified), the empty sequences are converted into `(^^)`, which is replaced by a 0 in the second-to-last line. The very last line simply removes the pound. [Answer] # KDB(Q), 76 bytes ``` {" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"} ``` # Explanation ``` l:" "vs"NBM NB BM N B M" / substrings enlist[x]{y vs" "sv x}\l / replace previous substring with space and cut -1+count@' / counter occurrence string[ ],' / string the count and join to substrings {" "sv } / concatenate with space, put in lambda ``` # Test ``` q){" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}"NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM" "3NBM 5NB 8BM 17N 6B 14M" q){" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}"" "0NBM 0NB 0BM 0N 0B 0M" ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â╥)3╨‼!∩╢←◘♀←N╟Ijƒ ``` [Run and debug it](https://staxlang.xyz/#p=83d22933d01321efb61b080c1b4ec7496a9f&i=NB%0ANBM%0ANBMMBNBNBM%0AMBNNBBMNBM%0ANNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM&m=2) [Answer] # Haskell, 244 bytes ``` import Data.List s="NBM" []#_=[[]] a#[]=[]:a#s l@(a:r)#(b:m) |a==b=let(x:y)=r#m in((a:x):y) |True=[]:l#m c?t=length$filter(==t)c p=["N","B","M","NB","BM","NBM"] main=getLine>>= \l->putStrLn.intercalate " "$map(\t->show((l#[])?t)++t)p ``` ]
[Question] [ Take a positive integer **n** as input, and output (some of the) decimal numbers that can be created using **n** bits, ordered in the following way: First list all the numbers that can be created with only one `1`, and the rest `0` in the binary representation (sorted), then all the numbers that can be created with two **consecutive** `1`, the rest `0`, then three **consecutive** `1` and so on. Let's see what this looks like for **n=4**: ``` 0001 - 1 0010 - 2 0100 - 4 1000 - 8 0011 - 3 0110 - 6 1100 - 12 0111 - 7 1110 - 14 1111 - 15 ``` So, the output for **n=4** is: **1, 2, 4, 8, 3, 6, 12, 7, 14, 15** (optional output format). # Test cases: ``` n = 1 1 n = 2 1 2 3 n = 3 1, 2, 4, 3, 6, 7 n = 8 1, 2, 4, 8, 16, 32, 64, 128, 3, 6, 12, 24, 48, 96, 192, 7, 14, 28, 56, 112, 224, 15, 30, 60, 120, 240, 31, 62, 124, 248, 63, 126, 252, 127, 254, 255 n = 17 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 3, 6, 12, 24, 48, 96, 192, 384, 768, 1536, 3072, 6144, 12288, 24576, 49152, 98304, 7, 14, 28, 56, 112, 224, 448, 896, 1792, 3584, 7168, 14336, 28672, 57344, 114688, 15, 30, 60, 120, 240, 480, 960, 1920, 3840, 7680, 15360, 30720, 61440, 122880, 31, 62, 124, 248, 496, 992, 1984, 3968, 7936, 15872, 31744, 63488, 126976, 63, 126, 252, 504, 1008, 2016, 4032, 8064, 16128, 32256, 64512, 129024, 127, 254, 508, 1016, 2032, 4064, 8128, 16256, 32512, 65024, 130048, 255, 510, 1020, 2040, 4080, 8160, 16320, 32640, 65280, 130560, 511, 1022, 2044, 4088, 8176, 16352, 32704, 65408, 130816, 1023, 2046, 4092, 8184, 16368, 32736, 65472, 130944, 2047, 4094, 8188, 16376, 32752, 65504, 131008, 4095, 8190, 16380, 32760, 65520, 131040, 8191, 16382, 32764, 65528, 131056,16383, 32766, 65532, 131064, 32767, 65534, 131068, 65535, 131070, 131071 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in **each language** wins! **Good explanations are highly encouraged**, also for solutions in "regular languages"! [Answer] # [Python](https://docs.python.org/2/), 53 bytes ``` f=lambda n,i=1:n*[f]and[i]+f(n-1,2*i)+i%2*f(n-1,i-~i) ``` [Try it online!](https://tio.run/nexus/python2#JctBCsIwEEbhvacYCkImnYqJLiTQk4QsImXgBztK6a7Uq8eCb/ctXtPxVefnVMkEY0jms5ZqU0bp1dkQJHpwj3P0f2L4gpu@FwLBKAehKHQTugs9SjrR0WeBra5Tt113TrSFvbscx1xXByF1YOb2Aw "Python 2 – TIO Nexus") The recursive function generates the sorted list as a pre-order walk down this tree (example with `n=4`): ``` 1 / \ 2 3 / / \ 4 6 7 / / / \ 8 12 14 15 1 2 4 8 3 6 12 7 14 15 ``` Left branches double the value, and right branches do `i->i*2+1` and exist only for odd `i`. So, the pre-order walk for non-leaves is `T(i)=[i]+T(i*2)+i%2*T(i*2+1)`. The tree terminates at depth `n`, where `n` is the input. This is achieved by decrementing `n` with each step down and stopping when it is 0. An alternative strategy would be to terminate on values that `i` exceeds `2**n`, rather than tracking depth. I found this to be one byte longer: ``` f=lambda n,i=1:2**n/i*[f]and[i]+f(n,2*i)+i%2*f(n,i-~i) f=lambda n,i=1:[f][i>>n:]and[i]+f(n,2*i)+i%2*f(n,i-~i) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Ḷ2*ẆS€ ``` This qualifies for the [imaginary bonus](https://codegolf.stackexchange.com/questions/109407/output-numbers-up-to-2n-1-sorted/109412#comment266284_109407). [Try it online!](https://tio.run/nexus/jelly#@/9wxzYjrYe72oIfNa35f7gdSHoDcdajhjmHth3a9v@/oY6CkY6CsY6CiY6ChY6CoTkA "Jelly – TIO Nexus") ### How it works ``` Ḷ2*ẆS€ Main link. Argument: n Ḷ Unlength; yield [0, ..., n-1]. 2* Yield [2**0, ..., 2**(n-1)]. Ẇ Sliding window; yield all subarrays of consecutive elements. The subarrays are sorted by length, then from left to right. S€ Map the sum atom over the substrings. ``` [Answer] # Mathematica, 40 bytes ``` Join@@Table[2^j(2^i-1),{i,#},{j,0,#-i}]& ``` Every number in the desired list is the difference of two powers of 2, so we simply generate them in order using `Table` and then flatten the list. I think this earns Stewie Griffin's imaginary bonus :) ## Mathematica, 35 bytes ``` Tr/@Rest@Subsequences[2^Range@#/2]& ``` A port of [Dennis's Jelly algorithm](https://codegolf.stackexchange.com/a/109412/56178). I didn't know about `Subsequences` before this! (I also didn't see that [miles had posted this exact answer](https://codegolf.stackexchange.com/a/109430/60043) ... go upvote it!) [Answer] ## JavaScript (ES6), ~~59~~ ~~58~~ 55 bytes ``` for(q=prompt(n=1);p=q--;n-=~n)for(m=n;p--;m*=2)alert(m) ``` A full program that takes input through a prompt and alerts each number in succession. This also qualifies for the [imaginary bonus](https://codegolf.stackexchange.com/questions/109407/output-numbers-up-to-2n-1-sorted/109412#comment266284_109407). ### Test snippet (Note: uses `console.log` instead of `alert`) ``` for(q=prompt(n=1);p=q--;n-=~n)for(m=n;p--;m*=2)console.log(m) ``` [Answer] ## JavaScript (ES6), ~~55~~ 51 bytes Returns a space-separated list of integers. ``` n=>(F=k=>k>>n?--j?F(k>>j|1):'':k+' '+F(k*2))(1,j=n) ``` [Imaginary bonus](https://codegolf.stackexchange.com/questions/109407/output-numbers-up-to-2n-1-sorted/109412#comment266284_109407) friendly. ### Formatted and commented ``` n => ( // main function, takes n as input F = k => // recursive function, takes k as input k >> n ? // if k is greater or equal to 1 << n: --j ? // decrement j ; if j is > 0: F(k >> j | 1) // do a recursive call with an additional bit set : // else '' // stop recursion : // else k + ' ' + F(k * 2) // append k to output and do a recursive call with k * 2 )(1, j = n) // start the recursion with k = 1 and j = n ``` ### Test cases ``` let f = n=>(F=k=>k>>n?--j?F(k>>j|1):'':k+' '+F(k*2))(1,j=n) console.log(f(1)) console.log(f(2)) console.log(f(3)) console.log(f(8)) console.log(f(17)) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~64~~ 61 bytes -3 bytes thanks to Dennis ``` n=2**input() j=i=1 while j<n: print i;i*=2 if i/n:i=j=2*j+1 ``` [Try it online!](https://tio.run/nexus/python2#@59na6SllZlXUFqiocmVZZtpa8hVnpGZk6qQZZNnxaUAYWcC2QVFmXklCpnWmVq2RlwKmbZZQI1Z2ob//5sAAA "Python 2 – TIO Nexus") [Answer] # Mathematica, 35 bytes ``` Tr/@Rest@Subsequences[2^Range@#/2]& ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~65~~ ~~63~~ 58 bytes ``` lambda n:[(2<<k/n)-1<<k%n for k in range(n*n)if k/n+k%n<n] ``` [Try it online!](https://tio.run/nexus/python2#LcpBCoMwFIThtT3FbISkPimxBUXiSWwXKTUl2I4SvH@M4Gp@mM9jwDP93P/9cWA/qsba@UZdm7wl4ZeIGYGIjt9J8UodPLKo8mv5SgfgAYygEdwFD0EnMG1/KdYYuMEr6rPTDg "Python 2 – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` f n=[2^b-2^(b-a)|a<-[1..n],b<-[a..n]] ``` [Try it online!](https://tio.run/nexus/haskell#@5@mkGcbbRSXpGsUp5Gkm6hZk2ijG22op5cXq5MEZCWCWLH/cxMz8xRsFXITC3wVCooy80oUVEAchTSFaEMdIx1jHRMdi9j/AA "Haskell – TIO Nexus") [Answer] ## Haskell, 47 bytes ``` f n=[1..n]>>= \b->take(n-b+1)$iterate(2*)$2^b-1 ``` Usage example: `f 4` -> `[1,2,4,8,3,6,12,7,14,15]`. [Try it online!](https://tio.run/nexus/haskell#@5@mkGcbbainlxdrZ2erEJOka1eSmJ2qkaebpG2oqZJZklqUWJKqYaSlqWIUl6Rr@D83MTNPwVahoCgzr0RBRSFNweQ/AA "Haskell – TIO Nexus"). How it works: for each number `b` in `[1..n]`, start with `2^b-1` and repeatedly double the value and take `n-b+1` elements from this list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` L<oŒéO ``` [Try it online!](https://tio.run/nexus/05ab1e#@@9jk3900uGV/v//WwAA) or as a [Test suite](https://tio.run/nexus/05ab1e#qymr/O9jk3900uGV/v91/htyGXEZc5lwWXAZmgMA) **Explanation** Uses the sublist-sum trick as shown in [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/109412/47066) ``` L # range [1 ... input] < # decrement each o # raise 2 to each power Œ # get all sublists é # sort by length O # sum ``` [Answer] # Groovy, ~~90~~ 89 bytes ``` {(0..<2**it).collect{0.toBinaryString(it)}.sort{it.count("1")}.collect{0.parseInt(it,2)}} ``` Binary conversion is so dumb in groovy. *-1 thanks to Gurupad Mamadapur* [Answer] # Pyth, 7 bytes ``` sM.:^L2 ``` [Try it online.](https://pyth.herokuapp.com/?code=sM.%3A%5EL2&input=4&debug=0) Uses Dennis's algorithm. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 51 bytes ``` dc<<<2i`seq -f%.f $[10**$1-1]|grep ^1*0*$|sort -r`f ``` [Try it online!](https://tio.run/nexus/bash#@5@SbGNjY5SZUJxaqKCbpqqXpqASbWigpaViqGsYW5NelFqgEGeoZaClUlOcX1SioFuUkPb//3/zr3n5usmJyRmpAA "Bash – TIO Nexus") The input n is passed in an argument. Use seq to print all numbers with n or fewer digits. (These are base-10 numbers, so there are lots of extra numbers here. It's wasteful and time-consuming, but this is code golf!) The call to grep keeps only those numbers that consist precisely of 1s followed by 0s. Then use sort -r to sort these in reverse lexicographical order. Finally, dc is set to base 2 input -- it pushes the sorted numbers on a stack and then prints the stack from top to bottom. (This prints the last item pushed first, etc., which is why I'm using sort -r instead of just sort.) Corrected a bug: I had omitted the option -f%.f to seq, which is required for integer counts from 1000000 on. (Thanks to @TobySpeight for pointing out that there was a problem.) [Answer] # Mathematica/[Mathics](http://mathics.github.io/), 69 bytes ``` {0,1}~Tuples~#~SortBy~Count@1/.n:{a=0...,1..,a}:>Print@Fold[#+##&,n]& ``` [Try it online!](https://tio.run/nexus/mathics#@19toGNYWxdSWpCTWlynXBecX1TiVFnnnF@aV@JgqK@XZ1WdaGugp6enYwjEibVWdgFFmUApt/yclGhlbWVlNZ28WLX//wE "Mathics – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), 38 bytes ``` ->\n{map {|(2**$_-1 X+<0..n-$_)},1..n} ``` ### How it works ``` ->\n{ } # A lambda with argument n. 1..n # Numbers from 1 to n. map { }, # Replace each one with a list: 2**$_-1 # 2 to that power minus 1, X+< # bit-shifted to the left by each element of 0..n-$_ # the range from 0 to n minus the number. |( ) # Slip the list into the outer list. ``` I.e. it constructs the numbers like this: ``` 1 2 4 8 = (2^1)-1 bit-shifted to the left by 0 1 2 3 places 3 6 12 = (2^2)-1 bit-shifted to the left by 0 1 2 places 7 14 = (2^3)-1 bit-shifted to the left by 0 1 places 15 = (2^4)-1 bit-shifted to the left by 0 places ← n rows ↑ ↑ n n-1 ``` The code: --- # [Perl 6](http://perl6.org/), 44 bytes ``` ->\n{map {|(2**$_-1,* *2...^*>2**n-1)},1..n} ``` This was my first approach before I thought of the (actually simpler) bit-shift solution above. ### How it works ``` ->\n{ } # A lambda with argument n. 1..n # Numbers from 1 to n. map { } # Replace each one with: 2**$_-1 # 2 to that power minus 1, ,* *2 # followed by the result of doubling it, ...^ # repeated until (but not including) *>2**n-1 # it's larger than 2^n-1. |( ) # Slip the list into the outer list. ``` I.e. it constructs the numbers like this: ``` 1 2 4 8 = (2^1)-1, times 2, times 2, times 2 3 6 12 = (2^2)-1, times 2, times 2 7 14 = (2^3)-1, times 2 15 = (2^4)-1 ← n rows ↑ ↑ n as many columns as possible in each row without exceeding (2^n)-1 ``` [Answer] **Haskell ~~59~~ 46 Bytes** I started out with `f n=[0..n]>>= \b->take(n-b).iterate(*2).sum.map(2^)$[0..b]` from nimi's answer above gained the insight that `sum.map(2^)$[0..x]` can be condensed down to `2^x-1` Ending up with `e n=[1..n]>>= \x->map(\y->2^y*(2^x-1))[0..n-x]` **[1..n]** -- list with number of consecutive bits we want to cycle through` **>>=** --roughly translated for each element in list on left pass it into the function on right and concatenate all results **\x ->** -- lambda function declaration with one argument **map x y**-- applies function x to all members of the list y In our case x = **(\y->2^y\*(2^x-1))** -- another lambda function 2^y\*(2^x-1)). This formula arises from multiplication by two adding a zero to right in binary(example 0001 to 0010). 2^x - 1 is the number of bits we are working with. so for 11 we have 2^0\*3(i.e. dont shift at all) == 0011, then 2^1\*3 = 0110 then 2^2\*3 - 1100. **[0..n-x]** Builds the list of how many times we can shift the bits. If we are working with a single 1 then looking at 0001 we want to shift 3 times (4-1). If we are working two 11 we want 4-2 and so on. [Answer] # Python 3, 59 bytes Note: this was made independently of [ovs](https://codegolf.stackexchange.com/a/109436/32700)'s and [Dennis](https://codegolf.stackexchange.com/a/109421/32700)'s solutions, even though it is very similar to both. ``` lambda n:[(2<<i)-1<<j for i in range(n)for j in range(n-i)] ``` How it works: ``` for i in range(n)for j in range(n-i) # Iterate over number of ones, then number of places # shifted over. i = ones, j = shifts (2<<i) # Create a one followed by i zeroes -1 # Subtract one from above to get i ones. <<j # Shift j places. ``` [Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJBnFa1hZGOTqalraGOTpZCWX6SQqZCZp1CUmJeeqpGnCRLIQhLQzdSM5Sooyswr0UjTAJGZeQWlJRqaQPD/vwkA "Python 3 – TIO Nexus") Tips (both coding and cash) are always welcome! [Answer] ## [Japt](https://github.com/ETHproductions/japt), 11 bytes ``` o@o!²ãXÄ mx ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=b0BvIbLjWMQgbXg=&input=NA==) ### Explanation This pretty much uses @Dennis's approach: ``` o@ o!² ãXÄ mx oX{o!p2 ãX+1 mx} // Implicit: U = input integer oX{ } // Create the range [0...U) and map each item X by this function: o // Create the range [0...U) !p2 // and map each item Z to 2.p(Z); that is, 2**Z. // (p2 would map each item Z to Z.p(2); ! reverses the arguments.) ãX+1 // Get all overlapping slices of length X + 1. mx // Map each of these slices Z through Z.x(); that is, sum each slice. // Implicit: output result of last expression ``` [Answer] # [Python](https://docs.python.org/), ~~61~~ 59 bytes ``` lambda n:[2**-~i-1<<j for i in range(n)for j in range(n-i)] ``` [Try it online!](https://tio.run/nexus/python3#TYuxCsJAEAV7v@KRajfsiRcL5YhfElKc6MkGs5EjXYi/fsZGnHKYKenyjOP1FmGha@ravdX5th2QpgyFGnK0x52Mv2L4E065L7@q84JGcBScBf7Uhx02XlltpirRclg5YPFrtd@WMc6kgkTKzOUD "Python 3 – TIO Nexus") [Answer] # PHP, ~~59 56~~ 53 bytes ``` for(;$p>($k*=2)?:($p=1<<$argn)>$k=$i+=$i+1;)echo$k,_; ``` takes input from STDIN; run with `-R`. **breakdown** ``` for(;$p>($k*=2) // 3. inner loop: shift-0 $k while $k<$p (false in first iteration) ?: ($p=1<<$argvn) // 1. init $p=2^N, outer loop: >$k=$i+=$i+1 // 2. shift-1 $i while $i<$p, init $k to new $i ;) echo$k,_; // 4. print $k ``` [Answer] # [J](http://jsoftware.com/), 19 bytes ``` (0-.~&,>:+/\2&^)@i. ``` This uses the same method in @Dennis' [solution](https://codegolf.stackexchange.com/a/109412/6710). [Try it online!](https://tio.run/nexus/j#@5@mYGuloGGgq1enpmNnpa0fY6QWp@mQqcfFlZqcka@QpmDy/z8A "J – TIO Nexus") ## Explanation ``` (0-.~&,>:+/\2&^)@i. Input: integer n i. Range [0, 1, ..., n-1] ( )@ Operate on that range 2&^ Compute 2^x for each x in that range >: Increment each in that range \ For each overlapping sublist of size (previous) in powers of 2 +/ Reduce by addition 0 The constant 0 &, Flatten each -.~ Remove zeroes ``` [Answer] # Python 3, 91 bytes ``` a=int(input()) print(*[int('1'*-~b,2)<<c for b in range(a)for c in range(a-b)],sep=', ') ``` Full program, with comma+space separated output, as specified. Explanation: Star notation unpacks lists. So `print(*[1,2,3])` is the same as `print(1,2,3)`. Pass the `int()` constructor a string of consecutive '1's. `-~b` evaluates to `b+1`, but you don't have to surround it with brackets when multiplying a string. Bitshift the produced integer an increasing number of times. `print()` has the optional sep argument, specifying the string to put in between each item in an unpacked list. [Answer] # Java 7, 108 bytes ``` static void x(int i){int a=0,t=1<<i,b;while((a=(a<<1)+1)<t){b=a;do System.out.println(b);while((b<<=1)<t);}} ``` Doubles the initial value as long as the result is smaller than `2^n`. Afterwards, updates the initial value to be `(initial_value * 2) + 1` and starts again from there until it eventually reaches `(2^n)-1`. e.g. for `n=4`: ``` 0001 -> init 0010 0100 1000 return, double init and add one 0011 -> init 0110 1100 return, double init and add one 0111 -> init 1110 return, double init and add one 1111 -> init done ``` [Try it online!](https://ideone.com/MJTS0y) [Answer] ## Ruby, 50 bytes ``` ->r{1.upto(r){|x|p a=2**x-1;p a while(a*=2)<2**r}} ``` I tried some "clever" approaches, but this seems to be the shortest (literally follow the instructions) ### Explanation: Each iteration starts with 2^n-1 and multiplies by 2 until the upper limit is reached. Nothing fancy, just basic math. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 37 bytes - imaginary bonus = still 37 bytes... ``` :[a|e=2^b-1┘while e<2^a┘?e┘e=e*2┘wend ``` Shame I haven't built `while-wend` into QBIC yet... Explanation: ``` : Get N from the command line [a| For b = 1 to N; The sequence is reset N times e=2^b-1 Set the first number of this sub-sequence (yields 1, 3, 7, 15 ...) ┘ Line-break - syntactic separation of commands because there's no command for WHILE yet. while Pure QBasic code - lower-case is not (really) interpreted by QBIC e<2^a Continue as long as we don't exceed the maximum value ┘?e Print the number in the sequence ┘e=e*2 Double the number ┘wend And loop as long as we're not exceeding maximum, reset the sequence otherwise. FOR loop auto-closed by QBIC ``` --- EDIT: QBIC now has support for `WHILE`: ``` :[a|e=2^b-1≈e<2^a|?e┘e=e*2 ``` This is only 26 bytes! Here's the `WHILE`: ``` ≈e<2^a| ≈ = WHILE, and the TRUE condition is everything up to the | ... Loop code goes here ] Close construct: adds a WEND instruction In the program above, this is done implicitly because of EOF. ``` [Answer] # MATL, ~~19~~ 18 bytes *1 byte saved thanks to @Luis* ``` :q2w^XJfP"J@YC2&sv ``` [**Try it Online**](https://tio.run/##y00syfn/36rQqDwuwistQMnLIdLZSK247P9/EwA) [Answer] # [R](https://www.r-project.org/), ~~69~~ ~~48~~ 46 bytes ``` n=scan();for(i in 1:n)print((2^i-1)*2^(i:n-i)) ``` Each decimal number corresponding to `i in 1..n` ones in binary system is multiplied by `2^(0..n-i)`, i.e first `n-i+1` powers of two (1, 2, 4, ...). [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOi2/SCNTITNPwdAqT7OgKDOvREPDKC5T11BTyyhOI9MqTzdTU/O/xf//AA "R – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` übg▓}╥é►╪ ``` [Run and debug online!](https://staxlang.xyz/#c=%C3%BCbg%E2%96%93%7D%E2%95%A5%C3%A9%E2%96%BA%E2%95%AA&i=1%0A2%0A3%0A8%0A17&a=1&m=2) ## Explanation > > Imaginary bonus if someone does this without any form of base conversion (using plain old maths). > > > Well, there are no base conversion here. Uses the unpacked version (10 bytes) to explain. ``` m|2vx_-DQH m For input=`n`, loop over `1..n` |2v Power of two minus one x_-D Do `n-j` times, where `j` is the current 1-based loop index Q Output the current value H And double it ``` [Answer] ## Batch, 92 - 0 = 92 bytes ``` @for /l %%i in (1,1,%1)do @for /l %%j in (%%i,1,%1)do @cmd/cset/a"(1<<%%i)-1<<%%j-%%i"&echo( ``` Subtracting 0 for @StewieGriffin's imaginary bonus. ]
[Question] [ # Introduction As is known, in 2017, [Finland](https://en.wikipedia.org/wiki/Finland) celebrates its 100 years of independence. To mark the occasion, it is your job to produce a [Finnish flag](https://en.wikipedia.org/wiki/Flag_of_Finland) for everyone's enjoyment. # Challenge Create a program or a function that produces the flag of Finland (the grey border is there for presentation purposes only): [![Flag of Finland](https://i.stack.imgur.com/SRuCL.png)](https://i.stack.imgur.com/SRuCL.png) ### Flag specifications * The ratio of the flag is `18:11`, with the cross being `3` units thick, giving a horizontal ratio set of `5:3:10` and a vertical ratio set of `4:3:4`. * The picture must be at least `180 x 110` pixels in size, or in case of ASCII art, `90 x 55` characters. * There is no official RGB colour for the blue, but use the closest approximation of `(0, 53, 128)`. If your system doesn't support RGB values, use `blue`. * For the white colour, use RGB `(255, 255, 255)` or `white`. ### Not so fast As drawing the Finnish national flag would be simpler than last year's [Icelandic challenge](https://codegolf.stackexchange.com/questions/85141/draw-the-national-flag-of-iceland), we'll have to ramp up the difficulty a bit. Given that [Finland's Independence Day](https://en.wikipedia.org/wiki/Independence_Day_(Finland)) is on 6 December, the decimal number `100` must appear somewhere on the flag when the date in Finland ([UTC+02:00](https://en.wikipedia.org/wiki/UTC%2B02:00)) is `2017-12-06` or later (your code should not assume that the machine it's running on is set to a particular timezone). Before the date, the number must not be there. The number must be printed in black (RGB `(0, 0, 0)` or `black`) but its placement and font parameters are up to you. An example of such a render (again, ignore the border): [![Flag of Finland with 100 on it](https://i.stack.imgur.com/9PPxf.png)](https://i.stack.imgur.com/9PPxf.png) For testing purposes, it would be nice to include two additional versions of your solution, one with a fixed date in the past and one in the future. # Rules [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, as are built-in flag images/libraries. Also, your code must not take any input. Finns don't like small talk, and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so don't waste characters! [Answer] # C (Windows), 361 bytes ``` #import<time.h> #import<windows.h> C(x){SetConsoleTextAttribute(GetStdHandle(-11),x);}F(I,N,l,a,n,d)time_t n;struct tm*d;{system("mode 90,65");time(&n);d=gmtime(&n);n=d->tm_year<<24|d->tm_mon<<16|d->tm_mday<<8|d->tm_hour;for(a=l=I=15;I++<70;a=l=I<35|I>49?15:9)for(N=n>1963656468&I<17?C(240),printf("100"):0;N++<90;a=N-25?a:9,a=N-40||l==9?a:15)C(a),putchar(70);} ``` **Unrolled:** ``` #import <time.h> #import <windows.h> C(x) { SetConsoleTextAttribute(GetStdHandle(-11),x); } F(I,N,l,a,n,d) time_t n;struct tm*d; { system("mode 90,65"); time(&n); d = gmtime(&n); n = d->tm_year<<24 | d->tm_mon<<16 | d->tm_mday<<8 | d->tm_hour; for(a=l=I=15; I++<70; a=l=I<35|I>49?15:9) for(N=n>1963656468&I<17?C(240),printf("100"):0; N++<90; a=N-25?a:9,a=N-40||l==9?a:15) C(a), putchar(70); } ``` **Output:** [![](https://i.stack.imgur.com/As7ys.png)](https://i.stack.imgur.com/As7ys.png) **Output when `UTC time >= 2017-12-05-22-00`:** [![](https://i.stack.imgur.com/je2mq.png)](https://i.stack.imgur.com/je2mq.png) Add the following in the code after `d=gmtime(&n);` to try it: ``` d->tm_year = 117; d->tm_mon = 11; d->tm_mday = 5; d->tm_hour = 21; ``` [Answer] # PHP + SVG(HTML5), 147 137 123 bytes SVG code by [Neil](https://codegolf.stackexchange.com/users/17602/neil) <https://codegolf.stackexchange.com/a/149850/66061> ``` <svg><path d=180v110 fill=#fff></path><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580></path><?=time()<1512511200?:'<text x=9 y=15>100'; ``` Update: Thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for helping me save 10 bytes. ``` <svg><path d=180v110 fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 /><?=time()<1512511200?:'<text x=9 y=15>100'; ``` Update 2: Smart idea by [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel), thanks for saving 14 bytes ``` <svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 /><?=time()<1512511200?:'<text y=19>100'; ``` Normal [![normal](https://i.stack.imgur.com/FtDnv.png)](https://i.stack.imgur.com/FtDnv.png) After 6th Dec +2 hours [![after 6th Dec - +2 hours](https://i.stack.imgur.com/MJirT.png)](https://i.stack.imgur.com/MJirT.png) [Answer] # [Röda](https://github.com/fergusq/roda), ~~252~~ 250 bytes ``` {s={|w,h|[` width="$w" height="$h" `]}r=`><rect`f=`" fill="#003580"/` [`<svg`,s(18,11),r,s(18,11),`fill="#fff"/`,r,s(18,3),`y="4$f`,r,s(3,11),`x="5$f>`] [`<text y="9" font-size="2">100</text>`]if{}|[[exec("date","+%s")]&"">="1512511200 "] [`</svg>`]} ``` [Try it online!](https://tio.run/##RY7haoMwFIX/9ynCmRstzTDRCS0YX0SEKzVpAl0LJkw39dldum7s3@F@3z339reuXd9bd53WyatpHrida2KD64JVSAYwq93ZhpgtGDVLr6gqe30KZBSBGXe5KDwJkRcHgZQ2NZX@40zcb@WBS7nj/X@kX9sYE9U/kkfwqfCWmMcof7ijQpGYipp7ZdBjYFE6xou3a3j17ksrZKikEGV6p1F0ZlrmutajPm3RtUGDY//ssWtegEpBFjIrpMyE2OCnNY2fxr1lXdZv "Röda – Try It Online") [Answer] # C#, 407 400 277 bytes Weird how `ForegroundColor =0` is allowed *Saved 1 byte thanks to TuukkaX* *Saved 67 bytes thanks to Adam* ``` ()=>{for(int x=0,y;x<90;x++)for(y=0;y<55;y++){BackgroundColor=(ConsoleColor)15;if(x>24&x<41|(y>19&&y<36))BackgroundColor=(ConsoleColor)9;SetCursorPosition(x,y);Write(' ');}if(new DateTime(2017,12,5,22,0,0)<DateTime.UtcNow){SetCursorPosition(1,1);ForegroundColor=0;Write(100);}} ``` ungolfed for testing: ``` using System; using static System.Console; class P { static void Main() { Action func = () => { for (int x = 0,y; x < 90; x++) for (y=0; y < 55; y++) { BackgroundColor = (ConsoleColor)15; if (x > 24 & x < 41 | (y > 19 && y < 36)) BackgroundColor = (ConsoleColor)9; SetCursorPosition(x, y); Write(' '); } if (new DateTime(2017, 12, 5, 22, 0, 0) < DateTime.UtcNow) { SetCursorPosition(1, 1); ForegroundColor =0; Write(100); } }; func(); ReadLine(); } } ``` for testing 100: ``` using System; using static System.Console; class P { static void Main() { Action func = () => { for (int x = 0,y; x < 90; x++) for (y=0; y < 55; y++) { BackgroundColor = (ConsoleColor)15; if (x > 24 & x < 41 | (y > 19 && y < 36)) BackgroundColor = (ConsoleColor)9; SetCursorPosition(x, y); Write(' '); } if (new DateTime(2017, 12, 2, 22, 0, 0) < DateTime.UtcNow) { SetCursorPosition(1, 1); ForegroundColor =0; Write(100); } }; func(); ReadLine(); } } ``` [Answer] # Mathematica, 129 bytes ``` If[AbsoluteTime@Date[]<3721507200,s="",s=100];Graphics@{s~Text~{9,9},RGBColor[0,.2,.5],{0,4}~(R=Rectangle)~{18,7},{5,0}~R~{8,11}} ``` before.. [![enter image description here](https://i.stack.imgur.com/wrcSP.jpg)](https://i.stack.imgur.com/wrcSP.jpg) [![enter image description here](https://i.stack.imgur.com/6wpUI.jpg)](https://i.stack.imgur.com/6wpUI.jpg) you can always test it on [Wolfram Sandbox](https://sandbox.open.wolframcloud.com) (paste the code and hit Shift-Enter) [Answer] # [Python 2](https://docs.python.org/2/), ~~247~~ ~~246~~ ~~230~~ ~~210~~ 189 bytes ``` import time print'P3',180,110,255 w,b='255 '*3,'0 52 128 ';B=['0 '*3,w][time.gmtime()<(2017,12,5,22)] a=w*40+b*30+w*100 x=w*10+a;y,z=w+B+w+B*3+w+B*3+a,(w+B)*5+a print y+z+y+x*37+b*5400+x*40 ``` [Try it online!](https://tio.run/##LY7NCoMwEITveYrcotmlbBKDgs3FJ@hdPKRQWg/@IELUl08T2sPOfLOHYdZz/yyzjnGc1mXb@T5OL7Zu47yLhxGoGkKlCLW1LODTiQRcSIOCuNVc6YaLtnN9ivkbhj4X3N5TtqK8F5pUjUqjRa3LgXkXZEXwlIYgSEXEDpcdfHvi5QJ0kE6av3osEpTSgv@N4idccMIhTZ1KbEWUuKIYvw "Python 2 – Try It Online") Prints a .ppm image: Normal flag [![Finland](https://i.stack.imgur.com/Wd3XN.png)](https://i.stack.imgur.com/Wd3XN.png) Flag with 100 [![Finland100](https://i.stack.imgur.com/NUzyJ.png)](https://i.stack.imgur.com/NUzyJ.png) [Answer] # Python 3, 143 141 135 bytes Uses ANSI escape for colors, uses five spaces or " 100 " as a colored string so that I don't need to specially print "100" somewhere on the flag. Length 5 because of width, because `90/5 == 90//5`. The string being used is getting defined in row 1. Then we iterate 55 round (height), on every iteration `v` is set to string with color [Blue, BrightWhite] and selected index is boolean `row<20 or r>34`. We multiply that result by 5 again (width dimensions: 25:15:50 so total width is 90). Then we print out `v + Blue + Blue + Blue + v + v + Black` where `v` is either Blue or BrightWhite. To clarify printing: width of `v` is 25 chars, width of Blue (`e%44*3`) is 15 and width of `v*2` is 50. `25+15+50` is 90 which is the width and follows the dimensions required in the task! Quite messy summary but I guess it's better than nothing. ``` import time;e="\033[30;%dm "+[" "*4,"100 "][time.time()>1512511200] for r in range(55):v=e%[107,44][19<r<35]*5;print(v+e%44*3+v*2+e%40) ``` [Answer] # Processing.org / Java ~~191~~ 188 bytes -3 bytes thanks to KevinCruijssen ``` import java.util.*;void setup(){size(180,110);background(-1);fill(0);if(new Date().getTime()>=15125256e6D)text("100",0,9);noStroke();scale(10);fill(#003580);rect(5,0,3,11);rect(0,4,18,3);} ``` [![Before After](https://i.stack.imgur.com/T4cdC.png)](https://i.stack.imgur.com/T4cdC.png) [Answer] # Excel VBA, ~~120~~ ~~118~~ 117 Bytes Anonymous VBE immediate window function that takes no input and outputs the the Finnish flag and if Finland is greater than 100 years old a `100` on that flag. This is done with respect to the Easter Timezone of the United States, as there is no way for Excel or Excel VBA to determine timezone without add-ins or accessing the internet. ``` Cells.RowHeight=48:Cells.Interior.Color=-1:[F1:H11,A5:R7].Interior.Color=8402176:If Now>=#12/5/17 19:0#Then[B2]=100 ``` ### Output If Finland is younger than 100 years old [![Young Finnish](https://i.stack.imgur.com/SWUg0.png)](https://i.stack.imgur.com/SWUg0.png) If Finland is older than 100 years old [![Old Finnish](https://i.stack.imgur.com/zx0z2.png)](https://i.stack.imgur.com/zx0z2.png) -2 Byte for changing `If #12/5/17 19:00#<=Now Then[B2]=100` to `If Now>=#12/5/17 19:0#Then[B2]=100` -1 Byte for use of `Cells` rather than `[A1:R11]` [Answer] # MATLAB, ~~133~~ ~~130~~ 123 bytes *~~3~~ 10 bytes sabed thanks for [@flawr!](https://codegolf.stackexchange.com/users/24877/flawr)* ``` r=1:180;r(51:80)=0;imshow(r(11:120)'*r,[0 .2 .5;1 1 1]) if datenum(datetime('now','T','UTC+2'))>=737035 text(9,9,'100'),end ``` This uses `[0, 51, 128]` for the blue color. The size of the image is 180×110 pixels. Sample run: [![enter image description here](https://i.stack.imgur.com/7c6TM.png)](https://i.stack.imgur.com/7c6TM.png) Sample run with the text (changing `737035` to `0` in the code so that the text is shown on any day): [![enter image description here](https://i.stack.imgur.com/zm16g.png)](https://i.stack.imgur.com/zm16g.png) [Answer] ## JavaScript (ES5) + SVG(HTML5), ~~189~~ 179 bytes ``` document.write('<svg><path d=M0,0h180v110H0z fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0Z fill=#005580 />'+(Date.now()<15125112e5?'':'<text x=0 y=30 fill=#000>100')) ``` ``` <body color=grey bgcolor=silver> ``` (HTML to show that the colour requirements are being met.) Edit: Saved 10 bytes thanks to @Shaggy. Outputs: ``` <body color=grey bgcolor=silver> <svg><path d=M0,0h180v110H0z fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0Z fill=#005580 /> ``` ``` <body color=grey bgcolor=silver> <svg><path d=M0,0h180v110H0z fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0Z fill=#005580 /><text x=0 y=30 fill=#000>100 ``` [Answer] # Python 3 with Pillow, ~~213~~ ~~212~~ 211 characters (Unix) and ~~217~~ 216 characters (Portable) This is the Unix version. I realized after posting that the time returned by `time()` does not necessarily have its epoch on 1 Jan 1970, so it is not necessarily portable. ``` b=8402688;from PIL import Image,ImageDraw as d j=Image.new('RGB',(180,110),~1);r=d.Draw(j);R=r.rectangle R([50,0,79,109],b);R([0,40,180,69],b);import time r.text((9,9),'100'*(time.time()>=0x5a273300),0) j.show() ``` This is the portable code, 4 bytes more, it uses `gmtime` with tuple comparison so it should work reliably on Windows too. ``` import time from PIL import Image,ImageDraw as d b=8402688 j=Image.new('RGB',(180,110),~1) r=d.Draw(j) R=r.rectangle R([50,0,79,109],b) R([0,40,180,69],b) r.text((9,9),'100'*(time.gmtime()>(2017,12,5,22)),0) j.show() ``` The images are displayed in a window. Really difficult to make it consume less characters. Even `time.time` returns a `float` so `>0x5a273299` would not be quite so correct, or `>0x5a273300` would be off by a microsecond. > > [![enter image description here](https://i.stack.imgur.com/Wx2LX.png)](https://i.stack.imgur.com/Wx2LX.png) > > > [![enter image description here](https://i.stack.imgur.com/JFohM.png)](https://i.stack.imgur.com/JFohM.png) > > > [Answer] # [Tcl/Tk](http://tcl.tk/), 135 bytes ***Must be run in the interactive shell*** ``` gri [can .c -bg #FFF] lmap C {"52 2 82 112" "2 42 182 72"} {.c cr r $C -f #003580 -w 0} if [clock se]>1512518520 {.c cr t 19 9 -te 100} ``` **Before 2017/12/06 02:00 GMT** [![enter image description here](https://i.stack.imgur.com/Omy0X.png)](https://i.stack.imgur.com/Omy0X.png) **After 2017/12/06 02:00 GMT** [![enter image description here](https://i.stack.imgur.com/bVOIH.png)](https://i.stack.imgur.com/bVOIH.png) [Answer] # Java 342 368 361 321 317 (299+18) bytes ## Golfed ``` import java.awt.*;()->new Frame(){{setBackground(Color.WHITE);setUndecorated(0<1);setSize(180,110);setVisible(0<1);}public void paint(Graphics g){g.setColor(new Color(0,53,128));g.fillRect(50,0,30,110);g.fillRect(0,40,180,30);g.setColor(Color.BLACK);if(System.currentTimeMillis()>15125112e5)g.drawString("100",9,9);}} ``` ## Ungolfed ``` import java.awt.*; () -> new Frame() { { setBackground(Color.WHITE); //Color Objects ARE just RGB values setUndecorated(0 < 1); //Get's ride of title bar setSize(180, 110); setVisible(0 < 1); } public void paint(Graphics g) { g.setColor(new Color(0, 53, 128)); //The special blue color g.fillRect(50, 0, 30, 110); g.fillRect(0, 40, 180, 30); g.setColor(Color.BLACK); if (System.currentTimeMillis() > 15125112e5) //Time Condition g.drawString("100", 9, 9); } ``` ## Result ![Finland](https://i.stack.imgur.com/cfgEm.png) ## Credits 40 bytes saved by [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire) for using lambda. 4 bytes saved by [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for Long formatting. 2 bytes saved by [user902383](https://codegolf.stackexchange.com/users/20093/user902383) for hex formatting. [Answer] ## vim, 147 I really like this challenge ☺. © is escape. ``` sy on set ft=c hi Normal ctermfg=4 ctermbg=7 hi Number ctermfg=0 ctermbg=7 norm 90i ©26|15r█Y40pMVr█Y14Pk if localtime()>1512511199 norm R100 ``` [![enter image description here](https://i.stack.imgur.com/jWF5h.png)](https://i.stack.imgur.com/jWF5h.png) [Answer] ## bash and imagemagick, 135 ``` ((`date +%s`>1512511199))&&x=100 convert -size 150x80 xc: -background \#003580 -splice 30x30+50+40 -draw "fill black text 9,9 '$x'" x: ``` [![enter image description here](https://i.stack.imgur.com/VgzOh.png)](https://i.stack.imgur.com/VgzOh.png) [![enter image description here](https://i.stack.imgur.com/HM4x5.png)](https://i.stack.imgur.com/HM4x5.png) [Answer] # [Imperative Tampio](https://github.com/fergusq/tampio/tree/imperative), 239 bytes (non-competing) ``` Kun iso sivu avautuu,se näyttää tekstin"<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 />"ja,jos nykyinen aika millisekunteina on suurempi kuin 1512511200000,niin se näyttää tekstin"<text y=19>100". ``` > > **Kun** iso sivu *avautuu*,se *näyttää* **tekstin**`"<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 />"`**ja**,**jos** nykyinen aika millisekunteina **on** **suurempi** **kuin** `1512511200000`,**niin** se *näyttää* **tekstin**`"<text y=19>100"`. > > > [Online version](http://iikka.kapsi.fi/tampio/suomi100.html) Translation: > > When the big page opens, it will show the text `"<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 />"` and, if the current time in milliseconds is greater than `1512511200000`, it will show the text `"<text y=19>100"`. > > > SVG was taken from [this answer](https://codegolf.stackexchange.com/a/149855/66323) by th3pirat3 (and Neil, appearently). This program is written in a new version of Tampio I have been working on. Those of you who know Finnish can see that it is almost readable. I marked the answer as non-competing because this language was published after this challenge. To run this program, either go to the online version above that contains the compiled JS version of the program or download the compiler from its [Github page](https://github.com/fergusq/tampio/tree/imperative). To compile the program, run `python3 tampio.py -p program.itp >program.html`. Tampio is not a golfing language by any measure, but due to the better svg code, it actually beat Röda... I was a little surprised. [Answer] ## bash, 198 ``` p()(printf "%-$1b$3" "\e[$2m") r()(for i in `seq $1`;{ $2;}) a()(p 31 107 p 20 44 p 56 30\;107 "${1:- }" p 0 0 ' ') b()(p 95 44 p 0 0 ' ') r 20 a r 15 b r 19 a ((`date +%s`>1512511199))&&a 100||a ``` [![enter image description here](https://i.stack.imgur.com/9Yx6I.png)](https://i.stack.imgur.com/9Yx6I.png) [![enter image description here](https://i.stack.imgur.com/my4Sg.png)](https://i.stack.imgur.com/my4Sg.png) [Answer] # HTML + CSS + Javascript, 339 bytes ``` <style>#f{width:180px;height:110px;position:relative}.b{background-color:#003580;position:absolute}.v{left:27.78%;width:16.67%;height:100%}.h{top:36.36%;height:27.27%;width:100%}</style><div id="f"><div class="b v"></div><div class="b h"></div></div><script>if(Date.now()>1512525600000)document.getElementById('f').innerHTML+=100;</script> ``` Here's the same solution trimmed down to 260 bytes, which assumes your viewing port has the proper 18:11 ratio. ``` <style>.b{background-color:#003580;position:absolute}.v{left:27.78%;width:16.67%;height:100%}.h{top:36.36%;height:27.27%;width:100%}</style><div class="b v"></div><div class="b h"></div><script>if(Date.now()>1512525600000)document.body.innerHTML+=100;</script> ``` You can knock a 0 off of the timestamp in either solution to see the "100" appear. [Answer] # Perl 5, 139 bytes ``` ($w,$b,$r)=map"\e[${_}m","47;30",44,0;$_=$w.$"x25 .$b.$"x15 .$w.$"x50 .$r.$/;$_=$_ x12 .s/7/4/gr x9 .$_ x12;time<1512511200||s/ /100/;say ``` to be launched ``` perl -E '($w,$b,$r)=map"\e[${_}m","47;30",44,0;$_=$w.$"x25 .$b.$"x15 .$w.$"x50 .$r.$/;$_=$_ x12 .s/7/4/gr x9 .$_ x12;time<1512511200||s/ /100/;say' ``` [![capture](https://i.stack.imgur.com/0rOBP.png)](https://i.stack.imgur.com/0rOBP.png) ratio was changed because of character ratio height/width = 1.66 (5/3) otherwise with original ratio : ``` ($w,$b,$r)=map"\e[${_}m","47;30",44,0;$_=$w.$"x25 .$b.$"x15 .$w.$"x50 .$r.$/;$_=$_ x20 .s/7/4/gr x15 .$_ x20;time<1512511200||s/ /100/;say ``` [![original ratio](https://i.stack.imgur.com/RzPji.png)](https://i.stack.imgur.com/RzPji.png) [Answer] # Racket 6.10 with 2htdp/image, 202 bytes ``` (let*([w 180][h 110][p(λ(w h x y o)(place-image(rectangle w h'solid(color 0 53 128))x y o))][b(p w 30 90 55(p 30 h 60 55(empty-scene w h)))])(if(>(current-seconds)1512536400)(overlay(text"100"9'b)b)b)) ``` Ungolfed: ``` (let* ( [flag-width 180] [flag-height 110] [place-rect (λ (width height x-pos y-pos other-pos) (place-image (rectangle width height 'solid (color 0 53 128)) x-pos y-pos other-pos))] [flag (place-rect flag-width 30 90 55 (place-rect 30 flag-height 60 55 (empty-scene flag-width flag-height)))] ) (if (> (current-seconds) 1512536400) ; If Finland is 100 years old (overlay (text "100" 9 'b) flag) ; add "100" to the flag flag)) ; otherwise just the flag ``` [![with text](https://i.stack.imgur.com/HZXS7.png)](https://i.stack.imgur.com/HZXS7.png) [![enter image description here](https://i.stack.imgur.com/gc78s.png)](https://i.stack.imgur.com/gc78s.png) [Answer] # [Small Basic](https://www.smallbasic.com "Microsoft Small Basic"), 300 bytes A Script that takes no input and outputs to the `TextWindow` object. ``` GraphicsWindow.BrushColor=0 If Clock.Year*10000+Clock.Month*100+Clock.Day>=20171206Then GraphicsWindow.DrawText(0,0,"100") EndIf GraphicsWindow.Height=275 GraphicsWindow.Width=450 GraphicsWindow.BrushColor="#003580 GraphicsWindow.FillRectangle(0,100,450,75) GraphicsWindow.FillRectangle(125,0,75,275) ``` [Try it at SmallBasic.com!](http://www.smallbasic.com/program?LLN181) *Requires IE/Silverlight* ### Output Shown after the Finland's 100th independence day. [![Output](https://i.stack.imgur.com/oGzjX.png)](https://i.stack.imgur.com/oGzjX.png) [Answer] # HTML + Javascript, 329 bytes I shamelessly stole the date-checking part from @jstnthms. Basically I just write crude html table with correct row/col ratios, `th` being the blue parts. Tested on IE and Chrome. ``` <body onload="h=[4,3,4];w=[5,3,10];m=50;s='<style>*{border-spacing:0;padding:0;}th{background:#003580;}</style><table>';for(y in h){s+='<tr height='+(m*h[y])+'>';for(x in w){c=(y==1||x==1)?'h':'d';s+='<t'+c+' width='+(m*w[x])+'>'+(x+y<1&&Date.now()>15125112e5?'100':'')+'</t'+c+'>';}s+='</tr>';}s+='</table>';document.write(s);"> ``` [Answer] the previously made code has been golfed down to the following: # HTML, CSS and JavaScript, 1599 bytes ``` var d1=new Date(1917,11,6); var d2=new Date(); var difference = d2.getFullYear()-d1.getFullYear(); if(difference===100 && d2.getDate()===d1.getDate() && d2.getMonth()===d1.getMonth()) { document.getElementById("bottom-right").innerHTML=d2.getFullYear()-d1.getFullYear(); } ``` ``` #flag{ background-color: #FFF; width: 540px; height: 330px; border: 6px solid gray; margin: 10% auto; } .surround{ background-color: #003580; width: 90px; height: 120px; margin: 0px 300px 0px 150px; } .middle{ background-color: rgb(0, 53, 128); width: 540px; height: 90px; } ``` ``` <head> <title>Happy Birthday, Finland</title> <link rel="stylesheet" type="text/css" href="decor.css"> </head> <body> <div id="flag"><div class="surround"></div><div class="middle"></div><div class="surround"></div></div> <script type="text/javascript" src="date.js"></script> </body> ``` [Answer] # HTML + JavaScript, 247 bytes ``` <table cellspacing=0 cellpadding=0><tr height=40><td width=50><td width=30 bgcolor=003580><td width=100><tr height=30><td colspan=3 bgcolor=003580><tr height=40><td><td bgcolor=003580><td><script>Date.now()>15125112e5&&document.write(100)</script> ``` [Answer] ## JavaScript ES6, 532 bytes Decided to try using a Base64 image to see how short I could get it. Not a winner, but interesting nonetheless. ``` document.write(`${Date.now()>1512525600000?'<i style=position:fixed>100</i>':''}<img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAABuAQMAAAC0pqs4AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABlBMVEX///8ANYAaS5LoAAAAAWJLR0QB/wIt3gAAAAd0SU1FB+EMBRcAAPqLykEAAAAxSURBVEjHY2AAA/v///8zYAGj4qPio+KDWfw/VvBhVHxUfEiKD7b8NSo+Kj4qTrQ4AHKtsHq12fKCAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTEyLTA1VDIzOjAwOjAwKzAxOjAwkDJOKAAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0xMi0wNVQyMzowMDowMCswMTowMOFv9pQAAAAASUVORK5CYI>`) ``` [Answer] ## Asymptote, ~~68~~ 90 bytes Run on <http://asymptote.ualberta.ca/> *Asymptote 90 bytes* (add the number 105, not 100 ^^) ``` draw((0,0)--(180,0)^^(65,-50)--(65,50),rgb(0,53,128)+30+linecap(0));label("105",(130,35)); ``` [![enter image description here](https://i.stack.imgur.com/RAJgK.png)](https://i.stack.imgur.com/RAJgK.png) *Asymptote 68 bytes* ``` draw((0,0)--(180,0)^^(65,-50)--(65,50),rgb(0,53,128)+30+linecap(0)); ``` [![enter image description here](https://i.stack.imgur.com/B88yZ.png)](https://i.stack.imgur.com/B88yZ.png) [Answer] # [C (GCC)](https://gcc.gnu.org), 236 bytes ``` i=-55;main(j,z,t){t=time(0)>1512521999;for(write(1,"P6 180 110 255 ",15);i<56;i-=~!i)for(j=-65;j<116;j-=~!j)write(1,((z=i*i+(j-22)*(j-22))<80&z>48|(z=i*i+j*j)<80&z>48|(abs(j+16)<2)&(abs(i)<9))&t?"\0\0":abs(i*i<j*j?i:j)>15?"ÿÿÿ":" 5€",3);} ``` Adaptation of [my solution of the related Icelandic challenge](https://codegolf.stackexchange.com/a/265018/73593). Set encoding to `ANSI`, so each character corresponds to a single byte, and replace `\0` with a `NUL` byte. Outputs to `stdout` a PPM image. --- [![](https://i.stack.imgur.com/sUx34.png)](https://i.stack.imgur.com/sUx34.png) ]
[Question] [ Using *two* languages of your choice, write the smallest “mutual [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29)” you can. That is, write a program P in language A that outputs the source code for a program Q in language B, such that the output of program Q is identical to the source code for P. Empty files don't count, nor do "read the source file and print it"-style programs. **Edit:** Answers with P=Q no longer count. [Answer] ## Python and Ruby, 39 characters This Python snippet ``` s='puts %%q{s=%r;print s%%s}';print s%s ``` generates this Ruby snippet ``` puts %q{s='puts %%q{s=%r;print s%%s}';print s%s} ``` which then generates the inital Python snippet again: ``` $ diff -s mutualquine.py <(ruby <(python mutualquine.py)) Files mutualquine.py and /dev/fd/63 are identical ``` Note that this is similar to [J B's answer](https://codegolf.stackexchange.com/questions/2582/golf-a-mutual-quine/2588#2588). [Answer] ## C and Perl, 73 This C: ``` main(s){printf(s="print q<main(s){printf(s=%c%s%c,34,s,34);}>",34,s,34);} ``` ...outputs the following Perl: ``` print q<main(s){printf(s="print q<main(s){printf(s=%c%s%c,34,s,34);}>",34,s,34);}> ``` ...that outputs the C back. [Answer] # C and C++, 123 chars This C (compilable with gcc v4.3.4): ``` #include <stdio.h> main(){char *c="#include <stdio.h>%cmain(){char *c=%c%s%c;printf(c,10,34,c,34);}";printf(c,10,34,c,34);} ``` outputs this (identical) C++ (compilable with g++ 4.3.4, one warning): ``` #include <stdio.h> main(){char *c="#include <stdio.h>%cmain(){char *c=%c%s%c;printf(c,10,34,c,34);}";printf(c,10,34,c,34);} ``` *This is within the rules as posted.* :P And, like Ventero's, this is based on [J B's answer](https://codegolf.stackexchange.com/questions/2582/golf-a-mutual-quine/2588#2588). [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish) and Python - 26 characters ``` "00gr00g:a9*2+$' tnirp'>o< ``` Generates this Python ``` print "\"00gr00g:a9*2+$' tnirp'>o<" ``` [Answer] **Python + Piet one-liners: 417 chars + 7391 7107 executing codels** This Python script produces a 7393 x 2 image; the rightmost 2x2 block of which is a "sentinel" which terminates the program; so I'm not counting those; and the second row is otherwise white. I can probably golf the piet code down further by using addition/subtraction/multiplication chains instead of the naive binary algorithm... but I don't want to give away a solution to a future puzzle. I'm not going to post the image here, because of its ridiculous dimensions. If you want to see it, run the python code, and pipe the output to a .ppm file. Then, convert the .ppm to a .gif, and run the output at [Rapapaing](http://www.rapapaing.com/blog/?page_id=6). (alternately, use a non-web Piet interpreter that groks .ppm) ``` A='P=lambda A:reduce(lambda(D,H,B),P:(D[P/3:]+D[:P/3],H[P%3*2:]+H[:P%3*2],B+"".join("%i "%H[(D[0]/P)%2]for P in[1,2,4])),map(" A ! @ B".find,A),([1,3,2,6,4,5],[0,192,192,255,0,255],"P3 %i 2 255 "%(len(A)+2)))[2]+"255 "*4+"0 0 "+"255 "*len(A)*3+"255 0 0 "*2;B=lambda D:["@!%s","@@!%s!"][D%2]%B(D/2)if 1<D else"";print P("".join("A%sB"%B(ord(D))for D in"A=%s;exec A[:-13]"%`A`)+" ");exec A[:-13]';exec A[:-13] ``` *edit: golfed the piet a bit by reducing Hamming weight of variable names.* **less golfed pre-quine**: This is a previous version, before I realized I could make it a one-liner. It's marginally easier to understand. The function P translates a special instruction set into Piet; and the function p takes an integer and produces a sequence of instructions to create that integer on the stack. I'm only using the instructions `=,+,:,|`, so this could probably be made more efficient... but I kinda like having a fullblown Piet compiler (of sorts) in the source. ``` s="""def P(s): l=len(s)+1;R="P3 %i 2 255 "%(l+2);C=[1,3,2,6,4,5];V=[0,192,192,255,0,255] for x in map("=|^+-*/%~>.,:@$?#!".find,"="+s): C=C[x//3:]+C[:x//3];V=V[x%3*2:]+V[:x%3*2] for i in [1,2,4]:R+="%i "%V[(C[0]//i)%2] return R+"255 "*4+"0 0 "+"255 "*l*3+"255 0 0 "*2 p=lambda x:[":+%s","::+%s+"][x%2]%p(x/2)if x/2 else"" print P("".join("|%s!"%k(ord(c))for c in "s="+`s`+";exec s[:-13]")) exec s[:-13]""" exec s[:-13] ``` [Answer] # Java to Python - 219 Java: ``` class Q{public static void main(String[]a){char q=34,c=39;String s="print%sclass Q{public static void main(String[]a){char q=34,c=39;String s=%s%s%s;System.out.printf(s,c,q,s,q,c);}}%s";System.out.printf(s,c,q,s,q,c);}} ``` Python: ``` print'class Q{public static void main(String[]a){char q=34,c=39;String s="print%sclass Q{public static void main(String[]a){char q=34,c=39;String s=%s%s%s;System.out.printf(s,c,q,s,q,c);}}%s";System.out.printf(s,c,q,s,q,c);}}' ``` Makes use of the fact that python allows `'` for strings; this makes it much easier to write the java program's source in the python program. [Answer] # /Brainf..k/, 6988 bytes ## Brainfuck ``` ++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++>>>++++++>>>+++++++>>>+++++++++++>>>++++++>>>+++++++>>>++++++++++>>>+>>>++++++++>>>+>>>++++++++++>>>+++++++++++>>>++>>>+++++++++>>>+>>>++>>>++++++>>>+>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++++++++++>>>+++++++++++>>>++>>>++++++++++>>>+++++++++++>>>++>>>++++++++++>>>+++++++++++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>++++++++++>>>+++++++++++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>++++++++++>>>+++++++++++>>>++>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++>>>++++++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++>>>++++++++++>>>+++++++++++>>>++>>>+++++++>>>++>>>++++++++++>>>+>>>++++++>>>++++++++++>>>+++++++++++>>>+>>>++++++++++>>>+++++++++++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+>>>++++++>>>+++++++>>>++>>>++++++>>>+++++++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++>>>++++++>>>+++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>+++++++>>>++>>>+>>>++++++>>>+++++++>>>++++++>>>+++++++>>>++>>>++++++>>>+++++++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++>>>++++++>>>+++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++++>>>+>>>++>>>+++++++++>>>++>>>++++++>>>+++++++>>>+>>>+>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>++>>>++++++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>++++++>>>+++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>+>>>+>>>+>>>+>>>++++++++++>>>+++++++++++>>>++>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++>>>++++++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++>>>++++++++++>>>+++++++++++>>>+>>>++>>>++>>>++>>>++>>>++++++>>>+++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>+>>>++++++++>>>+++++++++>>>++>>>++++++++++>>>+>>>+>>>+>>>++++++++++>>>+++++++++++>>>++++++++>>>+>>>++>>>+++++++++>>>++>>>++++++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++++>>>+>>>++>>>+++++++++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++>>>++++++>>>+++++++>>>+++++++>>>++>>>+++++++>>>++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>+++++++>>>++>>>++++++>>>++++++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++++>>>+>>>++>>>+++++++++>>>++++++>>>++++++>>>+++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++>>>+++++++>>>++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>+++++++>>>++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++++++++++>>>++++++>>>+++++++>>>+>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>+>>>++++++>>>+++++++>>>++>>>++++++++++>>>++++++>>>++++++>>>++++++>>>++++++++>>>++++++>>>++++++>>>++++++>>>+++++++++>>>+++++++>>>+++++++>>>+++++++>>>++++++++>>>+++++++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++++>>>++++++>>>++++++++>>>++++>>>+++++++>>>+++++>>>+++>>>+++++>>>++++>>>+++++++>>>+++>>>++++++>>>++++++>>>+++++++++>>>+++++++>>>+++>>>+++++>>>++++++++>>>++++>>>+++++++++>>>+++++++>>>+++++++>>>+++++++++>>>++++++>>>++++++++>>>++++++>>>++++++>>>++++++>>>+++++++++>>>+++++++>>>+++++++>>>+++++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++>>>+++++++>>>++++>>>++++++++>>>++++++>>>+++>>>+++>>>+++++++>>>++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>+++++++++>>>++++++>>>+++++>>>+++++++>>>+++++++>>>+++++++>>>+++++++>>>+++++++++>>>+++++++++++>>>++++++++++>>>+++++++++++>>>++++++>>>+++++++>>>{({}<>)<>}<>{([({})]()<((((()()()()()){}){}){})>){({}()<({}())>){({}()<({}()())>){({}()<({}()())>){({}()<({}())>){({}()<({}((()()()){}()){})>){({}()<({}()())>){({}()<({}(((()()()){}()){}){}())>){({}()<({}()())>){({}()<({}(((()()()()())){}{}){})>){(<{}({}()())>)}}}}}}}}}}{}({}<(<>)<>{({}<>)<>}{}>)(<><>)<>{({}<>)<>}{}<>{({}[()])<>(((((()()()){}())){}{}){}())<>}{}<>(((({})(((()()())){}{}){}())))<>}{}([]){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}{<>({}<>)}{}(<>){<<<[<<<]>>>[>++++++++++++++++++++++++++++++++++++++++.<[->.+.->+<<]>+.[-]>>]<[<<<]>>>[<++++++++++++++++++++++++++++++++++++++++>-[<+>-[<++>-[<++>-[<+>-[<++++++++++++++>-[<++>-[<+++++++++++++++++++++++++++++>-[<++>-[<++++++++++++++++++++++++++++++>-[<++>-]]]]]]]]]]<.>>>>]}{}<> ``` [Try it online!](https://tio.run/nexus/brainfuck#7VcNroMgDL4OhOgJSC9COAnx7HsFFVRAQGG8RdlkUPr7FSr7MNsAwDw7QmDmyGYUoycFI3Zz3NiSLP/OTujJHhTZv7ceZk/Ih8PNEuhm@XWhm@Wbu/3KsXhUZjth/J70i8mIeZrz8mtd8HMgqZaD/zQrjvUMu6yLSfP7ztnSPlMRdT8U0E2XQgc@4V/hLa@wcLarBQEb9YD3wEj4WQTe1zCpgs5hb7Fk/W20VyudgstVsVIhKHyZJOteW5QiR@MqIJXCzZdrFEbJsUldWZKgZ3LFd1tU3zJ6Wn@Kso9YUDSMYW5qPD8CepNp/O5eeepWCWUmCEoBa3uBYt0dAOvs6YvBzyDRZ@wX6eyqeff/hyJq4kA5YK@IwBmVhHKiG10/FKnzF6gW0Ay6P0zThP2UWO2ziXNhjz3Dg10QKOCC4LhqJSbbDJUTg4iDRk1AkeZR55kgVOKckIOLqz0cLtyaAUmOb8OyMBEh0Tti1a4GuPFrMQ3aZ@2UW0blZnFZwE6tJK0VfxTnXOAjMetiuzFO28jFACMbB2BalI1iQAXSaeK5mmBAXtNt@3no8QXo7BKb5ZO28RH9Bmky8vn8AQ) ## Brain-Flak ``` (()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()()()()()()()()()())(())(()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()())(())(()())(()()()()()())(())(())(())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(())(())(()())(())(()())(())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(())(())(())(()())(())(()())(())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()())(()())(()()()()()()()()()())(())(()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(())(()())(()())(()()()()()()())(()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(())(()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()())(()())(())(()()()()()())(()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()())(())(()())(()()()()()()()()())(()())(()()()()()())(()()()()()()())(())(())(())(())(())(())(()())(())(()())(())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(())(())(())(())(()()()()()()()()()())(()()()()()()()()()()())(()())(())(())(())(())(()())(())(()())(())(()())(()())(()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()())(()()()()()()()()()())(()()()()()()()()()()())(())(()())(()())(()())(()())(()()()()()())(()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(())(()()()()()()()())(()()()()()()()()())(()())(()()()()()()()()()())(())(())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()())(())(()())(()()()()()()()()())(()())(()()()()()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()())(())(()())(()()()()()()()()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()())(()()()()()()())(()())(()()()()()()())(()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()())(()())(()()()()()())(()()()()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()())(())(()())(()()()()()()()()())(()()()()()())(()()()()()())(()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()()())(()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()())(()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()())(()()()()()()())(())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()())(()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(())(()()()()()())(()()()()()()())(()())(()()()()()()()()()())(()()()()()())(()()()()()())(()()()()()())(()()()()()()()())(()()()()()())(()()()()()())(()()()()()())(()()()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()()())(()()()()()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()()()())(()()()()()())(()()()()()()()())(()()()())(()()()()()()())(()()()()())(()()())(()()()()())(()()()())(()()()()()()())(()()())(()()()()()())(()()()()()())(()()()()()()()()())(()()()()()()())(()()())(()()()()())(()()()()()()()())(()()()())(()()()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()()()())(()()()()()())(()()()()()()()())(()()()()()())(()()()()()())(()()()()()())(()()()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()())(()()()()()())(()()())(()()())(()()()()()()())(()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()()()()())(()()()()()())(()()()()())(()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()())(()()()()()()()()())(()()()()()()()()()()())(()()()()()()()()()())(()()()()()()()()()()())(()()()()()())(()()()()()()()){({}<>)<>}<>{([({})]()<((((()()()()()){}){}){})>){({}()<({}())>){({}()<({}()())>){({}()<({}()())>){({}()<({}())>){({}()<({}((()()()){}()){})>){({}()<({}()())>){({}()<({}(((()()()){}()){}){}())>){({}()<({}()())>){({}()<({}(((()()()()())){}{}){})>){(<{}({}()())>)}}}}}}}}}}{}({}<(<>)<>{({}<>)<>}{}>)(<><>)<>{({}<>)<>}{}<>{({}[()])<>(((((()()()){}())){}{}){}())<>}{}<>(((({})(((()()())){}{}){}())))<>}{}([]){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}{<>({}<>)}{}(<>){<<<[<<<]>>>[>++++++++++++++++++++++++++++++++++++++++.<[->.+.->+<<]>+.[-]>>]<[<<<]>>>[<++++++++++++++++++++++++++++++++++++++++>-[<+>-[<++>-[<++>-[<+>-[<++++++++++++++>-[<++>-[<+++++++++++++++++++++++++++++>-[<++>-[<++++++++++++++++++++++++++++++>-[<++>-]]]]]]]]]]<.>>>>]}{}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#7VgJroQgDL1OidETkCZzDsJJjGf3F1xw1EE2GZwP80VbyqMb2x8B2PHHYHrOW675e6mJdpEJQ3bTP9Sqs1aDddTv7PH7Sqdnjj5XSP5j2DwbjvRMvasFNXf8ke5ZY1KvUDV/c@VB@blQ1/JfyCSbrTEnylJPM6FRyZs//42f1v8@8Q@/6ZR75/KV3uer2@jVk9@x1rZb@Nnvf/dNcwoocV/5rN@3MucYFX8f@Ef2GbHJG6fz@edrXUws0879vOvQfXt5/l0i3UnOf28uMZ7XK9id0crv@VTY5Xgw1aroeysLy6q4vq7z2318Q9d33Nsv9rY42ZGv4hebSZ/tsesRlo1Pmy8129PNlqt8sns@HqFEpHS6lB/B59lcfV19fo/Pf4FnOznE78OZ/m/VQz9wZByp7kEQxSQwDqpspIb5D3UHJaDqHXnNeCdhRZ@GsHc@iDto8GYEdTBGcGpdewxr0VwO2iPGNf2AjHgH7kQJYJJogJ2Ky3j0OUsrAWIZuY3ILARCknawwi4DcK3XPDQqnZVSppnAdePcQFW/sBQqvXrOuaBHIqLAxrF0XLTYNV2LjeradKIlAGmQuCsStiSrq209fR7kTvhNkNgqJ9fCO9IbpY7IOI7t6w8) The Brain-Flak might time out on TIO. ## Explanation Coming soon. [Answer] ## Ruby and Python (393 + 413 = 806 chars) Slight change of [this answer](https://codegolf.stackexchange.com/questions/298/quine-that-takes-as-input-the-name-of-a-language-and-outputs-the-same-thing-imple/312#312) of mine. Could definitely be reduced since I just hard-coded the input without any optimisation. ### Ruby (393 chars) ``` require 'json';s=%q[{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l='python'][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l='ruby';print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}];j=JSON.load s;puts j[l='python'][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' ')) ``` ### Python (413 chars) ``` import json,re;s='''{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l='python'][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l='ruby';print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}''';j=json.loads(s);l='ruby';print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1)) ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish) and [APL](https://www.dyalog.com/), 10 bytes and 13 bytes ``` 'r3d*:::}H ``` [Try it online!](https://tio.run/##S8/PScsszvj/X73IOEXLysqq1uP/fwA "Gol><> – Try It Online") Which outputs: ``` '''r3d*:::}H' ``` [Try APL online!](https://tryapl.org/?a=%27%27%27r3d*%3A%3A%3A%7DH%27&run) Which simple prints the code as a string (with the `'` escaped with another `'`) [Answer] # Python 2 to Befunge 98, ~~94~~ 78 Again, making use of Python's two ways of making strings: Python: ``` s='<@,kM%c%cs=%c%s%c;print s%%(39,34,39,s,39,34)%c';print s%(39,34,39,s,39,34) ``` Befunge 98: ``` <@,kM'"s='<@,kM%c%cs=%c%s%c;print s%%(39,34,39,s,39,34)%c';print s%(39,34,39,s,39,34)" ``` The python program formats the string to include itself and the characters for the single and double quote. The Befunge program works like this: * `<`: move to the left, and wrap around. So now we execute the commands from right to left * `"`: make it so that every char we encounter is pushed to the stack until we encounter another `"`, so we push: ``` )43,93,s,93,43,93(%s tnirp;'c%)43,93,s,93,43,93(%%s tnirp;c%s%c%=sc%c%Mk,@<'=s ``` Which is actually just the python program, reversed because of the way Befunge prints (which is a pop+print loop) * `'M`: push `M` to the stack. `M` is also the number 77, which is one less than the number of chars pushed to the stack by the `"`s. * `k`: pop the top value off the stack (`M`) and do the next operation that many times, plus one. * `,`: pop the top value off the stack and print the char. * `@`: end the program. [Answer] ## Clipper and C (111 + 108 = 219 chars) ### Clipper (111) ``` ?'char*f="%c%cchar*f=%c%s%c;main(){printf(f,63,39,34,f,34,39,10);}%c%c";main(){printf(f,63,39,34,f,34,39,10);}' ``` ### C (108) ``` char*f="%c%cchar*f=%c%s%c;main(){printf(f,63,39,34,f,34,39,10);}%c%c";main(){printf(f,63,39,34,f,34,39,10);} ``` This is a bit of a cop-out because: 1. the "print" command in Clipper is really simple: `?'foo'` :-) 2. I based it on the "classic C" quine from <http://www.nyx.net/~gthompso/quine.htm>, with some modification to squeeze in the `?` and `'`s. 3. I didn't `#include <stdio.h>`, so it gives a compiler warning 4. The C code output by the Clipper version had to be prodded to remove a line break that had been introduced by an 80-character column limit in either my terminal or the Harbour printing routine or something. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` “Ṿ;⁾v`+/ŒṘ”v` ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4oCc4bm@O@KBvnZgKy/FkuG5mOKAnXZg//8 "Jelly – Try It Online") # [RAD](https://bitbucket.org/zacharyjtaylor/rad) ``` '“Ṿ;⁾v`+/ŒṘ”v`' ``` [Try it online!](https://tio.run/##ASEA3v9yYWT//yfigJzhub474oG@dmArL8WS4bmY4oCddmAn//8 "RAD – Try It Online") A Jelly quine that wraps itself in single quotes, such that the resultant RAD program simply prints the original Jelly program back out. [Answer] ## [Underload](https://esolangs.org/wiki/Underload) and [Betaload](https://esolangs.org/wiki/Betaload), 16 bytes Underload: ``` (a(:^)*a(S)*S):^ ``` Betaload: ``` ((a(:^)*a(S)*S):^)S ``` Betaload is a superset of Underload, so this could be two Underload answers. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` `:qpq`:qpq ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%3Aqpq%60%3Aqpq&inputs=&header=&footer=) # [Vyxal](https://github.com/Vyxal/Vyxal) `V` ``` `\`:qpq\`:qpq` ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=V&code=%60%5C%60%3Aqpq%5C%60%3Aqpq%60&inputs=&header=&footer=) The `V` flag does nothing, the first is a quine that unevaluates itself, and the second is a string. Or... # [Vyxal](https://github.com/Vyxal/Vyxal) `DrV`, 16 bytes ``` `q\`:Ė\`p1→ip`:Ė ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=DrV&code=%60q%5C%60%3A%C4%96%5C%60p1%E2%86%92ip%60%3A%C4%96&inputs=&header=&footer=) # [Vyxal](https://github.com/Vyxal/Vyxal) `Dr` ``` 0`q\`:Ė\`p1→ip`:Ė ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=Dr&code=0%60q%5C%60%3A%C4%96%5C%60p1%E2%86%92ip%60%3A%C4%96&inputs=&header=&footer=) The 0 at the start is a NOP - Vyxal pads the stack with 0s anyway, so the two programs are functionally identical. ``` `q\`:Ė\`p `:Ė # Standard eval quine 1→ip # If `V` (single-char variable names) is off, this stores 1 to the variable ip. # If it's on, this stores 1 to the variable i and prepends a 0 to the current program. ``` [Answer] # [Guile](https://www.gnu.org/software/guile/), 114 bytes ``` ((lambda(v)(format #t".\\~s"(format #f" (~a~s)"v v)))"(lambda(v)(format #t\".\\\\~s\"(format #f\" (~a~s)\"v v)))") ``` [Try it online!](https://tio.run/##bcsxDoAgDADAr5C6tIO@qEtVUBMaE0FGvl7DgHFwveTSsnv143Yf0ZshRtF5FSyE4bxUshsyTMw1wQsBHFapiaC4QkTwl7it9vgTuU/ulcwe "Guile – Try It Online") # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 139 bytes ``` .\" ((lambda(v)(format #t\".\\\\~s\"(format #f\" (~a~s)\"v v)))\"(lambda(v)(format #t\\\".\\\\\\\\~s\\\"(format #f\\\" (~a~s)\\\"v v)))\")" ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf//68UoKWho5CTmJqUkapRpagCFcxNLFJRLYpT0YoCgrjhGCS6YBlJcl1hXrBmjVKZQpqkJpLHqjYHqhpoQg2JGDMKUGIQ5mkr//wMA "Forth (gforth) – Try It Online") [Answer] # Python and ~-~! - 77 and 81 = 158 This Python code: ``` q=chr(124);s='@%sq=chr(124);s=%s;print(s%%repr(s))%s:';print(s%(q,repr(s),q)) ``` outputs this ~-~! code: ``` @|q=chr(124);s='@%sq=chr(124);s=%s;print(s%%repr(s))%s:';print(s%(q,repr(s),q))|: ``` Can definitely be improved a lot, and adopts a whole bunch from the other answers. [Answer] # Javascript and Windows .bat, 71 bytes and 81 bytes ``` f=()=>{console.log('echo f='+(f+';f()').replace(/(?=[>^\\])/g,'^'))};f() ``` and ``` echo f=()=^>{console.log('echo f='+(f+';f()').replace(/(?=[^>^^^\^\])/g,'^^'))};f() ``` ]
[Question] [ Based on [this question](https://codereview.stackexchange.com/q/236520) from Code Review. Given precisely three positive integers, return the product of all of the distinct inputs. If none of the inputs are distinct, return 1. That is, implement the function: \$ f(a,b,c) = \cases{1 & $a = b = c $ \\ a & $ b = c $ \\ b & $ a = c $ \\ c & $ a = b $ \\ a b c & otherwise } \$ Shortest code in each language wins. ### Test cases ``` a, b, c -> f(a,b,c) 7, 7, 7 -> 1 3, 3, 5 -> 5 2, 6, 6 -> 2 3, 4, 3 -> 4 1, 2, 3 -> 6 12, 9, 16 -> 1728 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` ¢ÏP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0KLD/QH//0cb6yiYA1EsAA "05AB1E – Try It Online") ``` ¢ # count occurences of each number Ï # keep only those where the count is 1 P # product (1 if the list is empty) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~46~~ \$\cdots\$ ~~43~~ 42 bytes Saved 2 bytes thanks to [79037662](https://codegolf.stackexchange.com/users/89930/79037662)!!! ``` f(a,b,c){a=a^b?a^c?b^c?a*b*c:a:b:b^c?c:1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1EnSSdZszrRNjEuyT4xLtk@CYgTtZK0kq0SrZKsQLxkK0Pr2v@5iZl5GprVXAVFmXklaRpKqikxeUo6aRrmOgogpKlpjU3KGIiwSRmDpUyxSRnpKJgBEQ5dJjgMNNRRMIJK1f4HAA "C (gcc) – Try It Online") [Answer] # JavaScript (ES6), 38 bytes ``` (a,b,c)=>a-b?b-c?c-a?a*b*c:b:a:b-c?c:1 ``` [Try it online!](https://tio.run/##ZctBCsIwEIXhvaeYZVImlsS2QqDmLDNjK0ppihWvH6MBwQr/6n28Gz1plft1eZg5noc09kkRMoruT2Q4sJEghgJVXIlnT/6zeJskzmuchv0UL2pUR4R3WkNdg9394gEh1xZsN@gQulxB9/9s8rlgs0GL4L7YpRc "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 53 bytes Takes input as `[a,b,c]`. ``` A=>[[a,b,c]=A,1,a-b?a-c?a:b:c,a*b*c][new Set(A).size] ``` [Try it online!](https://tio.run/##bczRCoIwFMbx@57iXDo5Ki41EEz2DF2OXZytGYpskVLQyy@DQSDB/@7H9030pMU8xvuaOX@1YeiC6M5SEmo0qhNYImW6p8z01OrWIKU6NUo6@4KLXRPB8mV8WxWMd4ufbT77WzIk8oTwTTEGRQHlYcdHhK06cr1njtBsReZ/1tV2ELnac4nAf9yEDw "JavaScript (Node.js) – Try It Online") ### Commented ``` A => // A[] = input [ // lookup table: [a, b, c] = A, // set size = 0 --> impossible, so use this slot // to split A[] into 3 distinct variables 1, // set size = 1 --> return 1 a - b ? // set size = 2 --> if a is not equal to b: a - c ? // if a is not equal to c: a // return a : // else: b // return b : // else: c, // return c a * b * c // set size = 3 --> return a * b * c ] // [new Set(A).size] // index into lookup table = size of the set ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` */@-.}./.~ ``` [Try it online!](https://tio.run/##Lcw7CoAwEATQfk8xrRIj@VoEQ07gJSRBbGxs9epxF2SneQyzZ@8Nq8Y4l0k/etZv3667wtCiIMGUGU6BEwSBrELkCKw0nkuBJ6Ngf0QaqO7HVVrJ/EUuceMQEiyPo8jDJRi2A/UP "J – Try It Online") ``` }./.~ group by value and remove one from each group -. set subtract from input */ product ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 10 bytes *Thanks to Adám and Bubbler in chat for helping golf this* ``` ×/∪*1=⊢∘≢⌸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhMPT9R91rNIytH3UtehRx4xHnYse9ewASikYKRgrmHCBaCALSJuAIBcA "APL (Dyalog Classic) – Try It Online") ### Explanation: ``` ×/ ⍝ Reduce by multiplication ∪ ⍝ The unique values of the input * ⍝ To the power of 1= ⍝ Whether one is equal to ≢ ⍝ The length of ⊢∘ ⌸ ⍝ The indexes of each unique element ``` [Answer] # [Python](https://docs.python.org/2/), 48 bytes ``` lambda l:eval("(%sin[%s,%s]or %s)*"*3%(l*4)+"1") ``` [Try it online!](https://tio.run/##DcZBCsMgEADAu69YBGHX7kVNEwjkJW0PliZEsEaiTenrbZjL5F9dt2TbAhPcW/Tv58tDHOfDR5SoSkg3VViVx7aDKqSldgqj7ugijaT2XUOcwYx5D6nCgiHlT0WiNvBJOHZ8FZZ77s937IRhy@4P "Python 2 – Try It Online") Takes in a tuple. The idea is similar to [an answer in the Code Review question](https://codereview.stackexchange.com/a/236573/56493), which can be golfed to: **51 bytes** ``` lambda a,b,c:a**(b!=a!=c)*b**(c!=b!=a)*c**(a!=c!=b) ``` [Try it online!](https://tio.run/##FcgxDoAgDADAr8BGm06ymfQl6tBiiCSKxODg6xHGu/LV485Ti4bN2k65dBcjpBRmQXRqWSwHQO0IlocBQ8fobmjlSbma6DDl8lYH0JaJPPntBw "Python 2 – Try It Online") Each element is included in the product if it's different from the other two, with the power setting to a harmless `x**0 == 1` otherwise. We want to avoid writing the three similar terms being multiplied. Python unfortunately doesn't have a built-in list product without imports. So, we turn to `eval` shenanigans. We use a longer expression that use logical short-circuiting: **60 bytes** ``` lambda a,b,c:(a in[b,c]or a)*(b in[c,a]or b)*(c in[a,b]or c) ``` [Try it online!](https://tio.run/##FcrBCsMgEIThu0@xRw1ziTYJBPokaQ@rbYiQGgmG0qe3K3P5P5j8K9uRbF3pTo@688e/mBgeYdZMMS1Sz@MkNp32zQHc7MWhWb7NwdTvFvc39XM@Yyq06i6mfBVtTJ0gUw4Og7IYMUrf4FQPC/cH "Python 2 – Try It Online") In this expression, the variable names cycle through `a,b,c` in that order four times. So, by tripling the format string `"(%sin[%s,%s]or %s)*"` and plugging in the input tuple repeated four times, we get the desired expression. We just need to append a `"1"` to deal with the trailing multiplication. [Answer] # [R](https://www.r-project.org/), ~~40~~ 37 bytes -3 bytes by taking input with `scan()`. ``` prod(unique(x<-scan())^2,1/x)^!!sd(x) ``` [Try it online!](https://tio.run/##PcrLCoAgFIThfU9hu3NgItIum3qVICyhjV0F8eUtIWI2Hz9zRiMGYZzV97pZChCXnuzwBw4c93Obydn1cAv5vkgHYh4lqtLzmOfXTJ6jIU0d3jFnyQoKzWeJFu3fa6jPFWRyfAA "R – Try It Online") `sd(x)` computes the standard deviation (which is 0 iff all entries are equal), so `!!sd(x)` is `TRUE` if some entries are different, and `FALSE` if all are equal. * if all entries are different, then `unique(x)==x`, so we are down to `prod(x)^1` * if 2 entries are equal, then the corresponding value gets cancelled out between `unique(x)^2` and `1/x`, so we are left with the sole "lonely" value * if all 3 entries are equal, then we have `(...)^0` which is 1. This is shorter than anything I could come up with based on `table`, `tabulate`, `duplicated` or `rle(sort())`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟœ-Q$P ``` **[Try it online!](https://tio.run/##y0rNyan8///hjvlHJ@sGqgT8P9z@qGnN///R0eY6CiAUy6UTbayjAESmIKaRjoIZEEFFTYASIKahjoIRiBkLAA "Jelly – Try It Online")** ### How? ``` ḟœ-Q$P - list, L $ - last two links as a monad: Q - de-duplicate (L) œ- - (L) multi-set difference (that) ḟ - (L) filter discard if in (that) P - product ``` --- **7**s: ``` ĠṖÐḟị⁸P ḟṖƙ`F$P ``` [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` f l=product[x|x<-l,filter(==x)l==[x]] ``` [Try it online!](https://tio.run/##Lcm7CgIxEIXhVzmFhcJs4XprnCcZUoS40eDsGrIRUvjsxgSEv/g452HX56Raq4dyTK/b22Upn3IdlHzQPKUtc9kpsxRj6mzDAkZMYcnYYLYRHiIXQs8Q5EBonTpHwrn1X4/t6NwTxk5Tv86rva91cDH@AA "Haskell – Try It Online") Pretty straightforward -- filter for elements that appear only once and take the product. [Answer] # Excel (Version 1911), ~~80 Bytes~~, 42 Bytes ``` =PRODUCT(FILTER(A1#,COUNTIF(A1#,A1#)=1,1)) ``` Input entered as a static column array (e.g. `={1;2;3}`) in cell `A1` * Saved 38 bytes due to inspiration from Grimmy's 05AB1E solution. [Answer] # [R](https://www.r-project.org/), 36 bytes ``` prod((a=rle(sort(scan())))$v[a$l<2]) ``` [Try it online!](https://tio.run/##K/r/v6AoP0VDI9G2KCdVozi/qESjODkxT0MTCFTKohNVcmyMYjX/myqYKZj/BwA "R – Try It Online") `rle()` shows its worth again. Feels like some parentheses could be golfed out somehow. The fact that `prod()` of an empty numeric evaluates to 1 is the only reason this is efficient. [Answer] # [PHP](https://php.net/), ~~72~~ ~~71~~ bytes ``` sort($argv);[,$a,$b,$c]=$argv;echo$a-$b?$b-$c?$a*$b*$c:$a:($b-$c?$c:1); ``` [Try it online!](https://tio.run/##LcixCoAgEAbgl/kHDR2CXLTwQaLh7ojcFIte/4po@YavlaZzbq9n7ZcB9eO2aXUgB3aQbfkq7VIqyIMz2EMyaAAPkAiK5i@Jo02qGnTS8AA "PHP – Try It Online") ~~Might be shorter without the `sort` but nested ternary operator precedence blows my mind.~~ -1 byte thanks to @640KB # [PHP](https://php.net/), 66 bytes ``` fn($a,$b,$c)=>$a-$c?$a-$b?$b-$c?$a*$b*$c:$a:$b==$c?:$c:$b==$c?:$b; ``` [Try it online!](https://tio.run/##Vc9Ba4MwFAfw8/Ip/pR3sOXVoqvtpks9DXYYrPe2lCSNyA4q09vYZ88S68CRR3j5Je8l6erOvZRd3QlBg@2HHhIn8XDCnsfAhQFsNlgfkAR/5BDZ3LPgKWPnY@7pdH7rS@a@DZ5wKPnnu9G9PjOSsdN07z59EpdC@CdW0lVNRIpJM5mlPJBakynDrEvS93xFekUmJ5WTltJTHlZ/qS6cb1W1X1aZOsL0a9X7DEt8C8CausVn3zZX25j2ZqNxi7E4D@dhwaAqQhzHdzy@Ha@vH@@F@BHOJX5kvw "PHP – Try It Online") Kudos to @640KB for taming the ternary operator beast! [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 31 bytes ``` ...{{*}*}:m;m\.|m/-m\.|,1=\1\if ``` This was... a lot more difficult than I thought it would be. Can be optimized. So much so, that I don't really want to give this much of an explanation. Here's the process: Take your input array and make 3 more copies of it. Make a function m, which multiplies the elements in an array together. Do that to the first array, then eliminate dupes from a second (keeping one of each). Perform m on it, then divide it from the first number. You should have the duplicate number (if there's only one pair dupe). Remove it rom your array, then return the last number. If the "suspected dupe" is 1, then just multiply again and output. If, when you remove all of the "suspected dupe"s, you're left with an array of size 1, just output 1 instead. This was incredibly and probably needlessly complicated, but I couldn't find any good GolfScript shortcuts besides the multiplication bit. PITA. [Try it online, I guess](https://tio.run/##S8/PSStOLsosKPkfbapgrGAc@19PT6@6WqtWq9Yq1zo3Rq8mV18XROkY2sYYxmSm/f8PAA "GolfScript – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 44 bytes ``` ,1+($args|group|? C* -eq 1|% N*)-join'*'|iex ``` [Try it online!](https://tio.run/##PY/dCoJAEIXv9ykGWXPX1gs1DYJI6L5XiKjNDEnzhwTXZ7fZzW04zMB3ZoaZuvrIpn3IspzpHfYwziJcM3pp8lblTdXX6gBHHwL5hlC5cPJ58KyKl@d7qpDDPBGSMQIYgoUCy1YY8YUlmsVCK7Es0gxTirJss/RhjS1LNcOlkWEcFLgwGo/KoZbXTt4EmEvxbnr@OY1s@7JDsMJ3Mm0a7lC2WPjJf5zv7IBDpvkL "PowerShell – Try It Online") where `|? C* -eq 1` means `|? Count -eq 1` and `|% N*` means `|% Name`. --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 45 bytes ``` $p=1;$args|group|? C* -eq 1|%{$p*=$_.Name};$p ``` [Try it online!](https://tio.run/##PY9hC4JADIa/368YMkPlCtQ0SCSh7/0Fkbrsg@F1KgXqb7fd5TVeNnjebWyyfQvVPUTTLHiHHMYFZR5mWKm6m2rVDnI6wTmArXhBOLkjyiDHcnepnmLOUC4zY4XHgIJ7Iady4Eb@yhLNYq6VWBZpRiklWbZf@6jGlqWa0dLIMB8mcGE0HoqPFNde3DiYS@lwLH@OEt3Q9AQ29E@hTcMd9FaLPvmP@0c74LB5@QI "PowerShell – Try It Online") [Answer] # Python 3, ~~[63](https://tio.run/##DchLCoAgEADQqwyunJAgXASBJ6kW9pGMyQmzsNNbb/nON20cdHFgYChkj2mxQN36WJKiEvXOPsgrRZnRcYQMPgCBd0D1zHdI/xvTIEfRCCxn9H852bdKKz0ilg8)~~ ~~[62](https://tio.run/##XcvLCsIwFIThvU8xZJVIKDTxAmKfRF3ESzByzCkxlfr0MSgIFv7Vx0z/yleOtnh02Bdy9@PZgTaXpyMp5qK5cYjykZMcleeEESGCEDyoOfEQc/WtUZxEK1TpU6ji5W6tYWsHpWY/sx9b/pnRWNWmu8X022qYr5U3)~~ 61bytes ``` lambda l:prod(x for x in l if l.count(x)<2) from math import* ``` You can [try it online](https://tio.run/##PclBCoMwEEbhvaf4l0kRobopRU9iu4iVwUCSGYYI6emjuHD5vif/vHEaXqKVMOFTg4vL6hDeoryaAmJFgU8I8ITQ/XhP2RQ79rYh5Yjo8gYfhTU/qqg/L5n52fbt8LW2ueXsS@oB)! Thanks @FryAmTheEggman for saving me 1 byte. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes ``` #&@@Times@@Tally@#~Cases~{_,1}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1nNwSEkMze1GEgl5uRUOijXOScWpxbXVcfrGNaq/Q8oyswriU6LrjbXAcLa2FguuIixjrGOKYqIkY6ZjhmaGhMdYxQRQx0jsMh/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes ``` {[*] .Bag.grep(0=>1)>>.key} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OlorVkHPKTFdL70otUDDwNbOUNPOTi87tbL2f3FipYIeUFVafhGXhrmOAghp6nBpGOsoAJEpiGmko2AGRCCmIZBtqaNgCOT8BwA "Perl 6 – Try It Online") (Using a `Pair` as matcher compares only values and ignores the key.) [Answer] # [PHP](https://php.net/), ~~92~~ 79 bytes ``` fn($a)=>array_product(array_keys(array_intersect(array_count_values($a),[1]))); ``` [Try it online!](https://tio.run/##Vc5dS8MwFAbga/MrXkYvGsgYrftQaueV4IXg7rtSQpbSqSQhSYUh/vaa1CodnIuT5@R8mM4MD4@mMyRpy6FVacJpuefW8ktjrD71wqe/r3d5cVN6Vl5aJ/9LQvfKN5/8o5cuDmBVVlNKi6EgJPHSeYcSFbmpsGNjoGYAViss98ii37IYm7lvoucM2xBzz6f/69Ay93X0jMWWK9@OHvSeIRsnTXt3@R2pw4WttpKLLsV0KnchA8UXAaToNN6cVo1UQp9kOpYYFkd/9AuGpP2Tw/OheXp9Kcj38AM "PHP – Try It Online") This isn't going to win for brevity, but just thought I'd try it entirely using chained PHP array functions. Now using @Guillermo Phillips's suggestion for PHP 7.4 arrow function syntax to save 13 bytes. # [PHP](https://php.net/), 66 bytes ``` fn($a,$b,$c)=>$a-$c?$a-$b?$b-$c?$a*$b*$c:$a:$b==$c?:$c:$b==$c?:$b; ``` [Try it online!](https://tio.run/##Vc9Ba4MwFAfw8/Ip/pR3sOXVoqvtpks9DXYYrPe2lCSNyA4q09vYZ88S68CRR3j5Je8l6erOvZRd3QlBg@2HHhIn8XDCnsfAhQFsNlgfkAR/5BDZ3LPgKWPnY@7pdH7rS@a@DZ5wKPnnu9G9PjOSsdN07z59EpdC@CdW0lVNRIpJM5mlPJBakynDrEvS93xFekUmJ5WTltJTHlZ/qS6cb1W1X1aZOsL0a9X7DEt8C8CausVn3zZX25j2ZqNxi7E4D@dhwaAqQhzHdzy@Ha@vH@@F@BHOJX5kvw "PHP – Try It Online") And another crazy ternary version inspired by [@Guillermo Phillips's answer](https://codegolf.stackexchange.com/a/199247/84624)! [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 24 bytes ``` psJ{{1j}qfcqpd}M-jNBL[!! ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/oNirutowq7YwLbmwIKXWVzfLz8knWlHx/39DBSMFY1MA "Burlesque – Try It Online") ``` ps # Parse to list J # Duplicate { {1j} # Push 1 & swap qfc # Find least common element qpd # Product }M- # Create array applying each function to make each element # {{Original list}, 1, least common, product} jNB # Remove duplicates from original list L[ # Find length !! # Select that element from the array # (zero indexed, hence the push swap to fill zero) ``` # Burlesque, 31 bytes ``` psJU_qpd{f:{-]1==}fe[~}IEisq1if ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/oNgrNL6wIKU6zapaN9bQ1rY2LTW6rtbTNbO40DAz7f9/MwUgBAA "Burlesque – Try It Online") Can probably be golfed further. ``` ps # Parse to array JU_ # (Non-destructive) is each element unique? qpd # boxed product { f: # Frequency (returns {{count val} ...}) { -]1== # Count == 1 } fe # Find element where [~ # Take the tail } IE # If unique then product, else find single is # Is an error (i.e. single not found) q1 # boxed 1 if # If error, push 1 ``` [Answer] # Mathematica, 40 bytes ``` f[l_]:=Times@@(If[Count[l,#]<2,#,1]&/@l) ``` You can [try it online](https://tio.run/##y00syUjNTSzJTE78/z8tOic@1so2JDM3tdjBQcMzLdo5vzSvJDpHRznWxkhHWccwVk3fIUfzf0BRJlA4LbraUMdIx7g2NpYLLmKsYwwW@Q8A)! [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` l=input();r=1 for x in l:r*=1%l.count(x)or x print r ``` [Try it online!](https://tio.run/##JU3LCsIwELzvV@xF2soitNUKlRzr1Ys/oHGlwZCEJcX262OCh2GGeTBhi7N3XdL@xaiwqqpklXFhiXVzEdXC2wuuaBzaUfaq3dmD9ouL9dqUAIIYF1FSHgJ8Z2MZ77LwCIhRtkKIvLLGcgBFaw4Rp9t1EvHyLzyFH590pp56yKATdDTQkPUxOy111P8A "Python 2 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 26 ``` sort|uniq -u|dc -e1?*?*?*p ``` The 3 input integers are each given on their own line. In the case of non-distinct inputs, `dc` warnings are printed to stderr. These may be ignored. `uniq -u` does most of the heavy lifting here. With the `-u` option, only non-duplicated lines are returned. uniq requires its input to be `sort`ed. The `dc` expression pushes 1 to the stack, then reads up to 3 integers, multiplying each in turn, then `p`rinting the output. If uniq pipes less than 3 integers to dc, then the surplus `?` will not add to the stack and the following `*` will spit out a warning because \* needs to pop 2 operands from the stack. But these are just warnings, dc continues execution until it prints the final product. [Try it online!](https://tio.run/##FYa9DkAwAAb3PsUXYZEYqJ/BYLIZxCaxoBVNpKUllr571V1yuWU2u3t3cXBoPrMaTBF4Ti3kvSGIzCQDhEPbdyMsJmeUvu0jxYXksWxFwtMm/j0dU5K7Cl5CQVGQDCVK/zkoSZH5fg "Bash – Try It Online") [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), 60 bytes ``` int f(int a,int b,int c)=>a==b?a==c?1:c:a==c?b:b==c?a:a*b*c; ``` [Answer] # TI BASIC, 45 Bytes ``` Prompt A,B,C ABC If A=B C If A=C B If B=C A If A=B and A=C 1 Ans ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ≡ᵍ~gˢ× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/1Hnwodbe@vSTy86PP3//@hocx0FEIrViTbWUQAiUyDLSEfBDIggYiZAYSDLUEfBCMoC0pY6CoZmsbEA "Brachylog – Try It Online") ``` ᵍ Group elements by ≡ value. ˢ For each group, ~g if it is a singleton list, extract its only element, ˢ else discard it. × Take the product. ``` [Answer] # [Factor](https://factorcode.org/) + `sets.extras math.unicode`, 20 bytes ``` [ non-repeating Π ] ``` [Try it online!](https://tio.run/##TYpLCgIxEAX3c4p3AQMz/lAPIG7ciCtx0cRWg0wSkx5QhrmLJ/JKMYq/Lt6iqN6TFhfSerVYzqeILFHxRQJF1CRH1Vij3Y5zODdsNUf4wCJXH4wVzIqiLZCvxfhF97Z@Zvi1CqPMrw3yPlbm@mcVJiifv13awDrbC@yZxNgD7jdsU00eUUifVHoA "Factor – Try It Online") Factor has a word `non-repeating` that gives you every element of a sequence that doesn't repeat. Turns out the answer to this question is just taking the product of this. [Answer] # MMIX, 48 bytes (12 instrs) ``` foo CMP $255,$0,$1 CMP $3,$1,$2 BZ $255,0F // if(a == b) goto ab BZ $3,1F // if(b == c) goto bc CMP $255,$0,$2 BZ $255,2F // if(a == c) goto ac MUL $0,$0,$1 // a *= b MUL $0,$0,$2 // a *= c 1H POP 1,0 // bc: return a 0H CSZ $2,$3,1 // ab: if(b == c) c = 1 POP 3,0 // return c 2H POP 2,0 // ac: return b ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` cḅịp ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPWMlRTElQjglODUlRTElQkIlOEJwJmZvb3Rlcj0maW5wdXQ9JTVCNyUyQyUyMDclMkMlMjA3JTVEJTIwLSUzRSUyMDElMEElNUIzJTJDJTIwMyUyQyUyMDUlNUQlMjAtJTNFJTIwNSUwQSU1QjIlMkMlMjA2JTJDJTIwNiU1RCUyMC0lM0UlMjAyJTBBJTVCMyUyQyUyMDQlMkMlMjAzJTVEJTIwLSUzRSUyMDQlMEElNUIxJTJDJTIwMiUyQyUyMDMlNUQlMjAtJTNFJTIwNiUwQSU1QjEyJTJDJTIwOSUyQyUyMDE2JTVEJTIwLSUzRSUyMDE3MjgmZmxhZ3M9Qw==) #### Explanation ``` cḅịp # Implicit input c # Counts of each number ị # Only keep items of the input ḅ # where the count equals 1 p # Product of this list ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 97 bytes ``` param($n)$a,$b,$c=$n|group;(($n-join'*'|iex),(($a,$b|?{$_.count-eq1}).name,1)[$a.count-eq3])[!$c] ``` [Try it online!](https://tio.run/##PcpRCsIwDADQswiBNZINxvRLZN5jDIkl6GRLa3UoWM8e54@/jxfDU9L9IuNoFjnx5EARmOBE4Peg@ZzCHHdu4fIaBi3WRR7khbTIb@X2DcfKh1kfpdzqD1bKk1CNHfCfmx67FfjezA6uoS1t8As "PowerShell – Try It Online") Not terribly impressive, but given that PowerShell doesn't have a ternary operator like JavaScript, nor the same `for` structure as Python, I don't think this is too bad. We take input `$n` as an array, then feed that into `Group-Object`, which stores the (potentially) three values into `$a, $b, $c`. Then we use array-indexing as a pseudo-ternary. We work "backwards" on the function definition given in the challenge, starting from the bottom. If we have a `$c`, then we have three unique values, so we `-join` `$n` with `*` and `iex` it (similar to `eval`). Otherwise, we have at least a duplicate, so we re-index whether `$a`'s `.count` is `-eq`ual to `3`. If it is, then all three values are the same, and we output `1`. Otherwise, we pull out the lonely value (i.e., its `.count` is `-eq`ual to `1`) and output its `.name`. In any case, the result is left on the pipeline and output is implicit. [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=product -apl`, ~~45~~ 44 bytes *@FryAmTheEggman saves a byte* ``` $_=product(grep{$t=$_;2>grep$t==$_,@F}@F)||1 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ragKD@lNLlEI70otaBapcRWJd7ayA7EAbKBHB0Ht1oHN82aGsP/1qrZthqa1v/NFYCQy1jBWMGUy0jBTMEMyDZRMOYyVDBSMP6XX1CSmZ9X/F/X1yezuMTKKrQkMwdmyX/dxIIcAA "Perl 5 – Try It Online") ]
[Question] [ Write the shortest program that prints this ASCII art section of a [hexagonal tiling](http://en.wikipedia.org/wiki/Hexagonal_tiling) or [honeycomb](http://en.wikipedia.org/wiki/Honeycomb): ``` __ __/ \__ __/ \__/ \__ / \__/ \__/ \ \__/ \__/ \__/ / \__/ \__/ \ \__/ \__/ \__/ / \__/ \__/ \ \__/ \__/ \__/ \__/ \__/ \__/ ``` * No input should be taken. * Output to stdout or your language's closest alternative. * Instead of a program, you may write a *named* function that takes no parameters and prints the result normally or returns it as a string. * The output may have any number of leading and/or trailing newlines and each line in the output may have any number of leading and/or trailing spaces (as long as the pattern lines up properly.) * **The shortest code in bytes wins.** [Answer] # CJam, ~~45~~ ~~43~~ ~~42~~ ~~41~~ 40 bytes ``` 741e8 36+Ab"\__/ "38*21/.{G2$-<\S*.e<N} ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=741e8%2036%2BAb%22%5C__%2F%20%20%2238*21%2F.%7BG2%24-%3C%5CS*.e%3CN%7D). ### How it works ``` "\__/ "38*21/ ``` repeats the pattern `\__/` **38** times and splits it into chunks of length **21**. If the chunks were separated by linefeeds, this would be the result: ``` \__/ \__/ \__/ \__ / \__/ \__/ \__/ \__/ \__/ \__/ \__ / \__/ \__/ \__/ \__/ \__/ \__/ \__ / \__/ \__/ \__/ \__/ \__/ \__/ \__ / \__/ \__/ \__/ \__/ \__/ \__/ \__ / \__/ \__/ \__/ \__/ \__/ \__/ ``` This clearly contains the desired honeycomb. All that's left to do is to replace some characters with spaces, cut off some others and actually introduce the linefeeds. ``` 741e8 36+Ab ``` generates the integer **74 100 000 036** and converts it into the array **[7 4 1 0 0 0 0 0 0 3 6]**. Each array element encodes the number of leading characters of the corresponding line that have to get replaced with spaces. By subtracting this number from **16**, we also obtain the correct length for this line. ``` .{ } e# Execute for each pair of a digit D and a line L: G2$-< e# Chop off L after 16 - D characters. \S* e# Push a string of D spaces. .e< e# Compute the vectorized minimum. N e# Push a linefeed. ``` Since a space has a lower code point than the other characters of **L** and vectorized operators leave the characters of the longer string that do not correspond to one of the shorter one untouched, `.e<` replaces the first **D** characters with spaces. [Answer] # Python 2, 73 ``` i=0 exec"k=max(7-i,i-24,0);print' '*k+('\__/ '*9)[i:][k:16-k];i+=3;"*11 ``` [See it run.](https://ideone.com/xhIDDc) For each of the 11 output rows, computes the number of leading spaces `k` as a maximum of three linear functions that form the envelope of the left side of the hexagon. Because the diagonal lines have slope `3` and `-3`, it's better to index the row number as `i=0,3,...30`. To create the hexagon mesh, we first tile enough of the unit `'\__/ '`. Then, shifting `[i:]` realigns it by 3 for odd rows. Finally, we take the needed portion `[k:16-k]` of it, leaving a margin of `k` on the left and right. [Answer] # CJam, ~~65~~ ~~56~~ 55 bytes ``` "Ý6TNð*¯5"303b4b["/\_")"_ "4*S]f=sB/z{_W%"\/"_W%erN}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%C3%9D6TN%17%C3%B0*%C2%85%C2%AF5%22303b4b%5B%22%2F%5C_%22)%22_%20%224*S%5Df%3DsB%2Fz%7B_W%25%22%5C%2F%22_W%25erN%7D%2F). ### Idea The right half of each line is a reversed copy of the left half with slashes and backslashes swapped. Therefore, it suffices to encode the left half of the honeycomb: ``` _ __/ __/ \_ / \__/ \__/ \_ / \__/ \__/ \_ / \__/ \__/ \_ \__/ \_ ``` Rather than analyzing this pattern line by line, we can analyze it column by column: ``` /\/\/\ _ _ _ _ _ _ _ _ /\/\/\/\ _ _ _ _ _ _ _ _ _ _ /\/\/\/\/\ _ _ _ _ _ _ ``` Obvious patterns emerge: * The string `_ _ _ _` occurs five times. * Every `/` is followed by a `\`. By replacing every `/\`, `_`, `_ _ _ _` and space with a number from 0 to 3, we can convert the resulting array from a base 4 number to a higher base and store the complete pattern in a compact fashion. ### Code ``` "Ý6TNð*¯5"303b4b e# Convert the string from base 303 to base 4. ["/\_")"_ "4*S]f= e# Replace each resulting digit by the corresponding item of the array e# ["/\" "_" "_ _ _ _ " " "]. sB/ e# Split into strings of length 11. z e# Zip: transpose rows with columns. { }/ e# For each string: _W% e# Push a reversed copy. "\/"_W%er e# Swap slashes and backslashes. N e# Push a linefeed. ``` [Answer] ## C, ~~148~~ ~~144~~ 140 bytes ``` k,r,c,d,p;f(){for(;k<187;k++){r=k/17;c=k%17;d=c+r%2*3;p=3*r+c-7<33u&3*r-c+8<33u;putchar(c==16?10:p&(d+5)%6<2?95:p&d%6==3?47:!p|d%6?32:92);}} ``` With whitespace, without compiler warnings, and before some code tweaks to save a few bytes: ``` #include <stdio.h> int k, r, c, d, p; void f() { for ( ; k < 187; k++) { r = k / 17; c = k % 17; d = c + 3 * (r % 2); p = 3 * r + c - 7 < 33u && 3 * r - c + 8 < 33u; putchar( c == 16 ? 10 : p && (d + 5) % 6 < 2 ? 95 : p && d % 6 == 3 ? 47 : p && d % 6 == 0 ? 92 : 32); } } ``` This approach does not use any character/string tables. It loops over all 187 (11 rows, 17 columns including newlines), and decides which character to print for each position, based on a combination of conditions. The conditions include a test for being inside/outside the 4 corners, using 4 line equations, with the result stored in variable `p`. The rest is then mostly repeating every 6 characters, with the odd rows shifted by 3 characters relative to the even rows. [Answer] ## Ruby - 78 Bytes ``` (-5..5).map{|i|puts' '*(j=[i.abs*3-i/6-9,0].max)+('/ \__'*4)[j+i%2*3,16-j*2]} ``` --- **A transcription of [xnor's solution](https://codegolf.stackexchange.com/a/50325/4098) (69 Bytes):** ``` 11.times{|i|puts' '*(j=[7-i*=3,i-24,0].max)+('\__/ '*9)[i+j,16-j*2]} ``` [Answer] # JavaScript (ES6), 129 ~~130~~ That's a pure string replace/replace/replace ... not taking advantage of any geometric property. Using template strings, all newlines are significant and count. Run snippet in Firefox to test ``` f=_=>`70 405 055 9992 3051 6301`[R='replace'](/9/g,`55123 30551 `)[R](/5/g,1230)[R](/\d/g,n=>['__','/',,'\\'][n]||' '.repeat(n)) // TEST O.innerHTML = f() ``` ``` <pre id=O></pre> ``` [Answer] # PHP - ~~139~~ ~~137~~ ~~107~~ ~~101~~ ~~91~~ 87 bytes I don't know if this is the best way to golf it but here is my try at it: *~~30~~ ~~36~~ ~~46~~ -50 bytes thanks to Ismael Miguel* Test it online [here](https://ideone.com/WHWEZS) ``` <?=' __ __',$a='/ \__'," __$a$a ",$c="$a$a/ \ \__$a$a/ ","$c$c \__$a/ \__/"; ``` ``` <script src="http://ideone.com/e.js/WHWEZS" type="text/javascript" ></script> ``` old code: ``` <?php $a="/ \\__";$c=$a.$a."/ \\\n\__".$a.$a."/\n";echo " __\n __".$a."\n __".$a,$a."\n".$c,$c,$c." \\__".$a."/\n \\__/"; ``` [Answer] # Lua 146 ``` T=" __\n __/ \\__\n __/ \\__/ \\__\n" S="/ \\__/ \\__/ \\\n\\__/ \\__/ \\__/\n" B=" \\__/ \\__/\n \\__/" io.write(T,S,S,S,B) ``` (newlines added for clarity) [Answer] ## Dart - 113 ``` main({r:"/ \\__"}){print(" __\n __$r\n __$r$r\n${"$r$r/ \\\n\\__$r$r/\n"*3} \\__$r/\n \\__/");} ``` Pure string-interpolation solution, nothing fancy. String operations like "substring" are too verbose to compete in practice. Run it on [DartPad](https://dartpad.dartlang.org/1c9f6d612fea37d8481f). [Answer] # Python 3, ~~100~~ 87 bytes ``` n=0x85208e08e08dd445 while n:l=n>>2&15;print(' '*(8-l)+('\__/ '*4)[n&3:n&3|l*2]);n>>=6 ``` And a readable version of the code below. The idea is to hardcode the intervals (begin, length) and then pad with the correct amount of spaces to center the interval. ``` hexagon_string = '\__/ ' * 4 for i in range(11): # Pick the begin and length of the i-th interval using hardcoded numbers b = (0x00030303111 >> 4*i) & 3 # n is a combination of these two numbers l = (0x25888888741 >> 4*i) & 15 # # Print the interval with appropriate whitespace in front of it spaces = ' ' * (8-l) print(spaces + hexagon_string[b : b+l*2]) ``` [Answer] # Javascript (*ES7 Draft*), 96 94 93 bytes Inspiration taken from a few solutions here... *Edit: -1 from edc65* ``` f=z=>[for(x of[741e6]+36)' '.repeat(x)+'/ \\__'.repeat(4,z^=3).slice(+x+z,16-x+z)].join(` `) // For snippet demo: document.write('<pre>'+f()+'</pre>'); ``` **Commented:** ``` f=z=>[ for(x of [741e6] + 36) // for each character "x" in "74100000036" ' '.repeat(x) + // x spaces '/ \\__'.repeat(4, // build pattern string z ^= 3). // toggle z offset (3) for even lines slice(+x + z, 16 - x + z) // get appropriate substring ].join(` // join with newlines `) ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 66 bytes ``` <empty line> sss __<LF>ssa__<LF> aa__<LF>lll dau<LF>ssdu l /daa<LF>\aau<LF> a ud u __/ d s\ s ``` Each line should go to its own file and `<LF>` means actual newline in the file. 1 byte per extra file added to byte-count. You can run the code as one file with the `-s` flag, keeping the `<LF>` markers and maybe changing them to newlines in the output for readability if you wish. The algorithm is 5 simple substitute steps (change odd line content to even line content) starting from an empty input string. The results after each steps are (delimited by `=`'s): ``` sss __ ssa__ aa__ lll dau ssdu ============ sss __ ssa__ aa__ /daa \aau /daa \aau /daa \aau dau ssdu ============ sss __ ssud__ udud__ /dudud \ududu /dudud \ududu /dudud \ududu dudu ssdu ============ sss __ ss__/d__ __/d__/d__ /d__/d__/d \__/d__/d__/ /d__/d__/d \__/d__/d__/ /d__/d__/d \__/d__/d__/ d__/d__/ ssd__/ ============ sss __ ss__/s\__ __/s\__/s\__ /s\__/s\__/s\ \__/s\__/s\__/ /s\__/s\__/s\ \__/s\__/s\__/ /s\__/s\__/s\ \__/s\__/s\__/ s\__/s\__/ sss\__/ ============ __ __/ \__ __/ \__/ \__ / \__/ \__/ \ \__/ \__/ \__/ / \__/ \__/ \ \__/ \__/ \__/ / \__/ \__/ \ \__/ \__/ \__/ \__/ \__/ \__/ ``` [Answer] # Javascript, ~~154~~ 151 bytes ``` b="\n",c="\t",d="/ \\",f="__",g="\\",h="/",a=f+d,j=a+a,i=d+j+b+g+j+f+h+b,k=" ";console.log(c+k+f+b+c+a+f+b+" "+j+f+b+i+i+i+k+g+a+f+h+b+c+" "+g+f+h) ``` ]
[Question] [ | [Ken Iverson, 1920–2020](https://www.youtube.com/watch?v=3wSSCYUd4z4 "A distinguished panel of contributors remember Ken Iverson and discuss the future of his revolutionary notation.") | | --- | | [(0,x)-(x,0)](https://www.youtube.com/watch?v=3wSSCYUd4z4 "A distinguished panel of contributors remember Ken Iverson and discuss the future of his revolutionary notation.") | Let's implement [his favourite expression](https://www.dyalog.com/blog/2014/12/ken-iversons-favourite-apl-expression/): ### Given a row of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle), compute the next row. This can for example be computed by taking the input padded with a zero on the left, and the input padded with a zero on the right, and then adding the two element-by-element. ### Test cases `[1]` → `[1,1]` `[1,1]` → `[1,2,1]` `[1,2,1]` → `[1,3,3,1]` `[1,10,45,120,210,252,210,120,45,10,1]` → `[1,11,55,165,330,462,462,330,165,55,11,1]` `[1,50,1225,19600,230300,2118760,15890700,99884400,536878650,2505433700,10272278170,37353738800,121399651100,354860518600,937845656300,2250829575120,4923689695575,9847379391150,18053528883775,30405943383200,47129212243960,67327446062800,88749815264600,108043253365600,121548660036300,126410606437752,121548660036300,108043253365600,88749815264600,67327446062800,47129212243960,30405943383200,18053528883775,9847379391150,4923689695575,2250829575120,937845656300,354860518600,121399651100,37353738800,10272278170,2505433700,536878650,99884400,15890700,2118760,230300,19600,1225,50,1]` → `[1,51,1275,20825,249900,2349060,18009460,115775100,636763050,3042312350,12777711870,47626016970,158753389900,476260169700,1292706174900,3188675231420,7174519270695,14771069086725,27900908274925,48459472266975,77535155627160,114456658306760,156077261327400,196793068630200,229591913401900,247959266474052,247959266474052,229591913401900,196793068630200,156077261327400,114456658306760,77535155627160,48459472266975,27900908274925,14771069086725,7174519270695,3188675231420,1292706174900,476260169700,158753389900,47626016970,12777711870,3042312350,636763050,115775100,18009460,2349060,249900,20825,1275,51,1]` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS) ``` +∘⌽⍨0,⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/9vpK1voKPzqGOGAZfGo5692o@6Fmka6ADJ/9pAQaDIo94VEH7ao7YJj3r7HnU1H1pv/Kht4qO@qcFBzkAyxMMz@H@agqGCqYKhAQgBaQA "APL (Dyalog Unicode) – Try It Online") Prepend a zero, and add the mirrored array: ``` 1 4 6 4 1 → 0 1 4 6 4 1 + 1 4 6 4 1 0 → 1 5 10 10 5 1 ``` # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS) ``` 0∘,+,∘0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@BRxwwdbR0gafA/7VHbhEe9fY@6mg@tN37UNvFR39TgIGcgGeLhGfw/TcFQwVTB0ACEgDQA "APL (Dyalog Unicode) – Try It Online") Just realized that the straightforward translation of Iverson's expression is short enough. # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes ``` …⍤≢!≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTflvpK1voKPzqGOGAZfGo5692o@6Fmka6ABJLm2gIFDkUe8KMP//o4Zlj3qXPOpcpAjE/9MetU141Nv3qKv50HrjR20TH/VNDQ5yBpIhHp7B/9MUDBVMFQwNQAhIAwA "APL (Dyalog Extended) – Try It Online") Ignore the content, take the length (n) and evaluate all binomials from nC0 to nCn. In APL, nCk is `k!n`, and `…n` gives `0..n`. [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes ``` lambda l:map(sum,zip(l+[0],[0]+l)) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKjexQKO4NFenKrNAI0c72iBWB4i1czQ1/xcUZeaVKKRpZOYVlJZoAAWiDXUMDXRMTHUMjQx0jIBMI1MjMA3ig4SBrFgA "Python 2 – Try It Online") **37 bytes** ``` lambda l:map(int.__add__,l+[0],[0]+l) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKjexQCMzr0QvPj4xJSU@XidHO9ogVgeItXM0/xcUAaUU0oAKCkpLNDQ1/0cb6hga6JiY6hgaGegYAZlGpkZgGsQHCQNZsQA "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 38 bytes ``` p=0 for x in input()+[0]:print x+p;p=x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8DWgCstv0ihQiEzD4gKSks0NLWjDWKtCooy80oUKrQLrAtsK/5DeGkaUBWa/6MNdQwNdExMdQyNDHSMgEwjUyMwDeKDhIGsWAA "Python 2 – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 37 bytes ``` lambda l,p=0:[p+(p:=x)for x in l]+[1] ``` [Try it online!](https://tio.run/##HYjBCoQgFEV/xeWL3kJtggj8EnPh0EiC2UMs7Osd62zuuYfuvB1xmChVp5Ya7P5dLQtIis@aeqBZlc4diRXmIwum18JUSj5mcPC7bAAf6czQNaoWKDh@RhSSo2wqR/nu85/czPwB "Python 3.8 (pre-release) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ż+ ``` A monadic Link accepting a list of integers which yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8///obu3///9HG@oYGuiYmOoYGhnoGAGZRqZGYBrEBwkDWbEA "Jelly – Try It Online")** ### How? Pretty simple in Jelly to go with the method given in the OP, although we do not need to right-pad with a zero since it is implicit in vectorised addition: ``` Ż+ - Link: list, R e.g. [ 1, 4, 6, 4, 1] Ż - prepend a zero (to R) [ 0, 1, 4, 6, 4, 1] + - addition (vectorises) [ 1, 5,10,10, 5, 1] ``` [Answer] # [Factor](https://factorcode.org/), 27 bytes ``` [ 0 suffix dup reverse v+ ] ``` [Try it online!](https://tio.run/##ZVJNTxtBDL3nV/iOhPwxnrHpD6i4cEE9IQ4RnaiIkobdTVSE@O3Bsynp7nIYzRvbYz/7ebN@GP50xx@31zffr@Cpdtv6G/r6sq/bh9rD83r4dXmoLaaHXVeH4XXXPW4H@LZavcEKAN6A4P2MAn9Cnj4IISkQI3BAVh7v9m5mnIZqs3NYPWOECkq7iKzk8Kg5ljC4m6UUQCVbsawtK2oSaV5CLszFqCBIEY1j1uxM4p6VKB6iyTIqWavjUixp1jxWi1TGrkVHhs5Rw7NrGMAtFSkuTtSYGqoom5mUcAomVA8SJhx5UiF2jm6SRDOQi3BJKWPmRsasJDdSzimPnA2TsIoEixPXRjCgjKQo4gjjc2ql@Kt/8X@RflF8QW1BfNHWvOf5POazmo1xNuD56KeaTLSaSPhf17PUZ/E/t@Hfcpw2ZVwaPa3S@@p4Bwj9frN5/As/9zvo6qF2fYXDBdwfn9c7uDx@AA "Factor – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0šÂ+ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f4OjCw03a//9HG@oY6RjGAgA) or [verify all test cases](https://tio.run/##ZVI7TgNBDL1KlJYp/P9UOUiUAiQKKgokpLQUHIAbcBbERXKRxd6EkF2K3fE8e@xnPz@/3D88PU6vx912c3r/2Gx3xwm@P7/e7qYx7fd4GHsc5z9dToQhOpBgUJmkNJ99bxguUdoQFZAGFcXAfSCGW3k0EryAzAiRMpQtPEw7IagwtxeBnMgDHQY7a30RjRNypiliXVglDBSj6yR7iJraXK1SBaW6zuSSqkZaagEjQ5w9ORGbaYCyUkSwl5NBQLNIBFPlEUdKqm6Eq5lhzuQiBkZNJsIlA5VMbOYcIEzKXCzOXJtgmTyTwopDqMfSpei/f/V@lX5VfEVtRXzV1rLn5TyWs1qMcTHg5ehvNbnR6kbCP12vUl/F/92Gy3KcN2VempbkcPgB). Or alternatively: ``` 0š+Ć ``` -1 byte thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f/f4OhC7SNt//9HG@oY6RjGAgA) or [verify all test cases](https://tio.run/##ZVI7TgNBDL1KlJYp/P9UabhFlAIkCioKJKRcIAfgBtwFLsJFFnsTQnYpdsfz7LGf/fzy@vD4/DS9HXfbzffpfbPdHe8n@Pq4@zxNY9rv8TD2OM5/upwIQ3QgwaAySWk@@94wXKK0ISogDSqKgftADLfyaCR4AZkRImUoW3iYdkJQYW4vAjmRBzoMdtb6Ihon5ExTxLqwShgoRtdJ9hA1tblapQpKdZ3JJVWNtNQCRoY4e3IiNtMAZaWIYC8ng4BmkQimyiOOlFTdCFczw5zJRQyMmkyESwYqmdjMOUCYlLlYnLk2wTJ5JoUVh1CPpUvRf//q/Sr9qviK2or4qq1lz8t5LGe1GONiwMvR32pyo9WNhH@6XqW@iv@7DZflOG/KvDQtyeHwAw). Or yet another alternative (thanks to *@ovs*): ``` gDÝc ``` [Try it online](https://tio.run/##yy9OTMpM/f8/3eXw3OT//6MNdYx0DGMB) or [verify all test cases](https://tio.run/##ZVI7TgNBDL1KlHoK/z9VGm4RpQCEEBUFElIuwAHoOQ03yUUWexNCdil2x/PssZ/9/Pp2//DyNL0fd9vN6eNzs90dp@e776/HaUz7PR7GHsf5T5cTYYgOJBhUJinNZ98bhkuUNkQFpEFFMXAfiOFWHo0ELyAzQqQMZQsP004IKsztRSAn8kCHwc5aX0TjhJxpilgXVgkDxeg6yR6ipjZXq1RBqa4zuaSqkZZawMgQZ09OxGYaoKwUEezlZBDQLBLBVHnEkZKqG@FqZpgzuYiBUZOJcMlAJRObOQcIkzIXizPXJlgmz6Sw4hDqsXQp@u9fvV@lXxVfUVsRX7W17Hk5j@WsFmNcDHg5@ltNbrS6kfBP16vUV/F/t@GyHOdNmZemJTkcfgA). **Explanation:** ``` # (example input: [1,2,1]) 0š # Prepend a 0 to the (implicit) input-list # STACK: [0,1,2,1]  # Bifurcate the list; short for Duplicate & Reverse copy # STACK: [0,1,2,1], [1,2,1,0] + # Add the values at the same positions in the two lists together # [0+1,1+2,2+1,1+0] # STACK: [1,3,3,1] # (after which the result is output implicitly) 0š # Prepend a 0 to the (implicit) input-list # STACK: [0,1,2,1] + # Add the values at the same positions in the two lists together, where the second # list is the (implicit) input (because the two lists are of different lengths, # the trailing item is ignored) # [0+1,1+2,2+1] # STACK: [1,3,3] Ć # Enclose; append its own first item as additional trailing item # STACK: [1,3,3,1] # (after which the result is output implicitly) g # Get the length of the (implicit) input-list # STACK: 3 D # Duplicate this length # STACK: 3,3 Ý # Push a list in the range [0,length] # STACK: 3,[0,1,2,3] c # Calculate the binomial coefficient between the length and each value in this list # STACK: [1,3,3,1] # (after which the result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~26~~ 25 bytes ``` o l=zipWith(+)(0:l)l++[1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P18hx7YqsyA8syRDQ1tTw8AqRzNHWzvaMPZ/bmJmnoKtQkFRZl6JgopCfrShjpGOYSyXAgr4DwA "Haskell – Try It Online") * Saved 1 thanks to @ovs * New approach, it essentially do this: ``` 0[1,2,1] + [1,2,1] = [1,3,3] + 1 ``` Previous version 30 bytes ``` o=(0#) x#(v:w)=x+v:v#w x#_=[x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P99Ww0BZk6tCWaPMqlzTtkK7zKpMuRzIj7eNroj9n5uYmadgq1BQlJlXoqCikB9tqGOkYxj7HwA "Haskell – Try It Online") [Answer] # [convey](http://xn--wxa.land/convey/), ~~[13](https://codegolf.stackexchange.com/revisions/241498/1)~~ ~~[12](https://codegolf.stackexchange.com/revisions/241498/3)~~ 10 bytes ``` {,"0 0.>+} ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoieyxcIjBcbjAuPit9IiwidiI6MSwiaSI6IlsxLDMsMywxXSJ9) [![Program running on 1 4 6 4 1](https://i.stack.imgur.com/Im4eu.gif)](https://i.stack.imgur.com/Im4eu.gif) [Answer] # R 4.1, 17 bytes Only posting because because the function nicely resembles the APL expression. ``` \(x)c(x,0)+c(0,x) ``` [Answer] # [brainf\*\*\*](https://esolangs.org/wiki/Brainfuck), 41 bytes ``` >>>,[>>,]<<[<<]>>[[-<+>>+<]>>]<[<<]>>[.>>] ``` [Takes input as character codepoints.](https://codegolf.meta.stackexchange.com/a/18027/98140) Unfortunately, control characters are currently cancelled on most PC's, so I cannot give a legitimate test case in TIO or any other implementation of brain. : / # How? ``` >>,[>>,]<<[<<] # Store the input on every other cell >>[ ]>>] # For every number in the input -<+>>+< # Distribute the number to adjacent cells Nothing here... <[<<]>>[.>>] # Output each sum ``` --- Probably my last post of 2020. [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` TTY+ ``` [**Try it online!**](https://tio.run/##y00syfn/PyQkUvv//2hDHUMDHRNTHUMjAx0jINPI1AhMg/ggYSArVgEA "MATL – Try It Online") ### How it works This convolves the input with `[1, 1]`. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~8~~ 6 bytes -2 bytes thanks to Adám! ``` +':|0, ``` [Try it online!](https://tio.run/##y9bNz/7/P81KW92qxkDnf5q6hqG1oQIIG4FJQwMFE1MFQyMDBSMg08jUCEyD@CBhIEvzPwA "K (oK) – Try It Online") # [J](http://jsoftware.com/), ~~9~~ 7 bytes -2 bytes thanks to xash! ``` 0&,+,&0 ``` [Try it online!](https://tio.run/##ZVK7TgNBDOzzFRZFIkSI/H4gUSFRUfELiAjR8P/V4b1AuDuK1XrHXnvs8ed0czqc4fEBDnAEhIc@9yd4en15nnB/vDvucbrdwe797eMLzkBXY2nyCkdQA2IEbpON53u8B4zLUBs4N1qOHSoo4yLK8PZYFkYDVZmqbZh4RrqNrGgqMryEHMyRFAgSYn0yB84kVW5E/RDTdDTKUackUs3N52qdKrksbGZY3DXKyxqASg2JkiIaTBNNjDNTop2CilZNIoU7jwZxcXej0s2Ah3CoOjoPMpmhlWTs6jPnRBU2kWZx4ToItikzKeo4wv6soxT/92/@b9Jvim@obYhv2lr3vJ7HelarMa4GvB79UpOFVgsJ/3S9Sn0V/3cbfpbjsinz0gxJYPoG "J – Try It Online") Both translated from [Bubbler's APL solution](https://codegolf.stackexchange.com/a/216484/75681) - don't forget to upvote it! [Answer] # **PowerShell, 30 27 bytes** -3 bytes thanks to mazzy ``` ($x=$args+0)|%{$_+$x[--$i]} ``` Explanation: ``` ($x=$args+0)|%{$_+$x[--$i]} ($x= #assign to $x $args+0) #the input array with a 0 appended | #pipe the result of the assignment %{ } #for each item in the piped input $_+ #add to that item $x[ ] #the item of x --$i #with index equal to the decrement of i. #negative indices in powershell index from #the end of the array, so -1 is the last item #in the array, -2 is second to last, etc. #implicitly output ``` [Answer] # [Nibbles](https://nibbles.golf), 4 bytes (8 nibbles) ``` !:0$:@0+ ``` ## Verbose ``` ! # Zip : 0 $ # Prepend 0 to argument : @ 0 # Append 0 to argument + # With addition ``` [Answer] # JavaScript (ES6), 29 bytes Returns a comma-separated string. ``` a=>a.map(v=>p+(p=v),p=0)+[,1] ``` [Try it online!](https://tio.run/##dctLCoAwDATQvSdpMUobdBkvIl0Efyhqg0qvXz9L0dXMPJiJA@/NNsqRrb7tYk@RqeJ8YVGBKkmVUNAgZHRag3Wx8evu5y6f/aB6VVundfI2@Fb8cWugKMGiAbwqlvjkvW82zyue "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ż+Ṛ$ ``` [Try it online!](https://tio.run/##ZVK7UQNBDG3GGRvo/ymF8TgkYdwAKQk5EUMNNOAhZFyIaeSQzsb4juButU9a6UlPjw/7/dM0HT/vTof3zfT1cnw9Hd42388f99O0xd3Y4jj/6XIiDNGBBIPKJKX57HvDcInShqiANKgoBu4DMdzKo5HgBWRGiJShbOFh2glBhbm9COREHugw2Fnri2ickDNNEevCKmGgGF0n2UPU1OZqlSoo1XUml1Q10lILGBni7MmJ2EwDlJUigr2cDAKaRSKYKo84UlJ1I1zNDHMmFzEwajIRLhmoZGIz5wBhUuZicebaBMvkmRRWHEI9li5F//2r96v0q@Iraiviq7aWPS/nsZzVYoyLAS9Hf6vJjVY3Ev7pepX6Kv7vNlyW47wp89K0JLsf "Jelly – Try It Online") ~~Rip off~~ Translation of Razetime's Husk solution, so be sure to send some upvotes his way. [Answer] # [R](https://www.r-project.org/), 21 bytes ``` c(0,x<-scan())+c(x,0) ``` [Try it online!](https://tio.run/##K/r/P1nDQKfCRrc4OTFPQ1NTO1mjQsdA87@hgqGBgompgqGRgYIRkGlkagSmQXyQMJD1HwA "R – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes ``` Tr/@Partition[#,2,1,{2,1},0]& ``` [Try it online!](https://tio.run/##ZVI9a8NADN37KwqFTgfV50kaCvkJGbqFDKaU1ENaCN5Cfrurc9rUdgb7Tno66UlPx274/Dh2Q//ejYfX8e30stl2p6Ef@u@v3VOhguWcv0uB/fO4PfVfw@PmsDvjZf8ws8rapjsPQhEtSFAor6Q0nc1ubriL1wZSQlEh4xm4HYhuNRH1AEtHhLtIXpSrm1dtqUGFuaEIZETmaFDYWPNzb35CjqiKmAareAVFb3WCzUWr1qlapnIKNZ1oBmWNqKHpKOFibMGB2Jg6KCu5O1uCDAIaScKZMo8YUlB2I5zNlGpMJlKhUiPjbhKOSlXqxNlBmJQ5WVy5NoJ55YkUZhxCPpZWiu7x1ftV@lXxFbUV8VVby56X81jOajHGxYCXo59rMtNqJuG/rjepb@L/bcPvclw3ZVoave7TOP4A "Wolfram Language (Mathematica) – Try It Online") -3 bytes from @att [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes ``` 0p+ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=0p%2B&inputs=%5B1%2C2%2C1%5D&header=&footer=) ``` # Implicit input 0p # prepend 0 + # (Implicit input) add (vectorised) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 20 bytes Character codepoints are used as input and output. ``` ,[[<+>>+<-]<.>>>,]<. ``` [Try it online!](https://tio.run/##ZU5NS8QwFLz3Vwyl0MRNu@4HnrK56dUfEHpo05TElSTEFFfwv9dsXfUgPN7M8Jg3M/RvZlF9goDyo26HCZzj8flpYVLyjRAb3nS8FUKwDEs@FMW7sa8aUfcjrAtzKkZfAH5OmZ8qEj6S8e6ARqEM0bpEtBtPdd2@eOuIMpFcKCYfccl2VOsLSkt8YutD2g6xt26a1fmP/VSjOUYr49E4lNV34NX3P1He@aAduWd1HGraXrsS2tEyV3V6kbuukDuGG@x/2WGdmzgyPKw76y8 "Bash – Try It Online") Input is taken in every second cell and added to both surrounding cells. This leaves the output in every other cell. Example run with input `[1, 2, 1]`: ``` 0 0 0 0 0 0 0 The tape is initially filled with 0's 0 1 0 0 0 0 0 , ^ Read the first input into this cell 1 0 1 0 0 0 0 [<+>>+<-] ^ ^ Add the value to both surrounding cells <.> and print the cell left to the input 1 0 1 2 0 0 0 >>, ^ Move right by 2 cells and take the next input 1 0 3 0 2 0 0 ^ ^ 1 0 3 0 2 1 0 ^ ... 1 0 3 0 3 0 1 ^ ^ 1 0 3 0 3 0 1 ^ ^ ^ ^ The outputs are in these cells The trailing <. prints the last output ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 26 bytes *A port of [Arnauld's answer](https://codegolf.stackexchange.com/a/216482/83605) in Ruby.* ``` ->a,i=0{a.map{i+i=_1}+[1]} ``` [Try it online!](https://tio.run/##dVPLbhsxDLz3K3LPthDf5MH9kcCH9BAghwJB2xQokny7O5Ibe6WgNuyVSIkczsz@eP725/RwOH3@er89HtrL/Zfv908vr79fH28fD7/fbu/o@HZ6ev718@bhDuvjzeFwc0cbHT9dgts1zHOCdynBd77VNrWNuG2MJRuPZ9/3cNtdJdoMIbdNBFnn8evrHuupBZD1Oox4eUNpadIfRBmOjGW1QKAqUxULE89It46imYr0LDUO5kiKtkmI4ZfZ40xS5UaEjZimN6PsfUoi1dx8dEOp5LKwMVExepSXIbBVakiUFFFHms3EODMlkJSmzQogUhh1NIiLMY0Khtk8hEPVm3MHkxlaScauPjBnU2ETAYoz1g4QSxmgCOeo4bL2Vvwxv9xfyi/NF2gL8GWseeaZj5mricaJ4Jn6vSY7rXYSXnW9SH0R/90N/8xxdsowje2tZ3AWd4gAiH@tGobSaj5GbKV9QYYZOyoXDwC3QQcLsQwvBj69YSfN2Rt5xQAT4DpH0V2i3yiO5gT6@6iU6dBLSMFPIGo08gWLKypj1XCiIwxcwAY6FbYKJkvBjaOubQApRmbOQQO2gmi3lObnN8NbBDt1mc@kQLHmiYl4eLqsqEi00eBBAwHUVhzv7@@6X86v9T70W/AscJdhllEXImaWZgZndmfi/yPJpOFO2qveVw9cbPHuk3fbDA8NO3VbHU9/AQ "Ruby – Try It Online") --- # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` ->a{(a+[0]).zip([0]+a).map &:sum} ``` [Try it online!](https://tio.run/##dVPLbhsxDLz3K3wqEmQbiG@yQPojhg/uIUAPAYKmObRFv90dyY29q6A27JVIiRzOzH5//frz9Phw@vTl@PvmeLdvh9v7X9@eb7C4O97ePx2fdx8/v7w@/Tk9v/542T3u93Q47B4ednta6PDhElyuYd4meJUSfLe32qK2ELeFsWTj8ez7Hm6rq0SLIeS2iCDrPH593WM9NQGyXocRL28oLU36gyjDkbGsFghUZapiYeIZ6dZRNFORnqXGwRxJ0RYJMfwye5xJqtyIsBHT9GaUvU9JpJqbj24olVwWNiYqRo/yMgSWSg2JkiLqSLOZGGemBJLStFkBRAqjjgZxMaZRwTCLh3CoenPuYDJDK8nY1QfmbCpsIkBxxtoBYikDFOEcNVzW3orf56f7U/mp@QRtAj6NtZ15y8eWqw2NG4K31K81WWm1kvCq60Xqi/hvbvhnjrNThmlsbT2Ds7hDBED8a9UwlFbzMWIr7QsyzNhRuXgAuA06WIhleDHw6Q07ac7eyCsGmADXOYquEv1GcTQn0N9HpUyHXkIKfgJRo5EvWFxRGauGEx1h4AI20KmwVTBZCm4cdW0BSDEycw4asBVEu6U0P78Z3iLYqct8JgWKNU9MxMPTZUVFoo0GDxoIoLbieH9/5/10fq73rt@EZ4I7DTONOhGxZWnL4JbdLfH/kWSj4Uraq95XD1xs8eaTN9sMDw07dVsdTn8B "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` Sż+Θ ``` [Try it online!](https://tio.run/##yygtzv7/P/joHu1zM/7//x9tqGNooGNiqmNoZKBjBGQamRqBaRAfJAxkxQIA "Husk – Try It Online") ## Explanation ``` Sz+Θ S take the input Θ and itself with 0 prepended ż+ and zip with addition, preserving elements ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` LcŻ$ ``` [Try it online!](https://tio.run/##y0rNyan8/98n@ehulf@PGncoHG5/uLNFRcHy8IRDCxVOLAcK/QcA "Jelly – Try It Online") Same length as [Unrelated String’s answer](https://codegolf.stackexchange.com/a/216488/66833) but uses a different method [Answer] # [Red](http://www.red-lang.org), 37 bytes ``` func[c][alter c 0 c + reverse copy c] ``` [Try it online!](https://tio.run/##TY3BCgIxDETv@xXjyYMI3eJePPgRXkMOJZuiqNsl1hW/vrYi6ECYlzBkTMdy1JG4i3uU@JiEhClcsxoErs4GpovaXSFpfkG4xGQa5ARLT1CHKur56/iR/@PeYTeg9w6@oh/8x9vezq4lmTDbecqg9ne9PSDiFi6KRSUnW7U6Bpc3 "Red – Try It Online") Takes the input as a `vector!` Instead of inserting/appending a zero to the list, I use `alter` (for -1 byte) - it appends the value to the list if not present and removes it if present - the zero is guaranteed to not be in the list. [Answer] # Scala 3, 26 bytes ``` x=>(0::x)zip(x:+0)map(_+_) ``` [Try it online!](https://scastie.scala-lang.org/lCHlOBQnTNKpRhp2ql8iLA) Pretty much a literal translation of the original APL expression, albeit more verbose. [Answer] # Kakoune, 20 bytes ``` A,0<esc>x_S, y<a-)>a+<c-r>"<esc>|bc ``` [![asciicast](https://asciinema.org/a/qFyBsM4FiimUbwvqpGpOnktk7.svg)](https://asciinema.org/a/qFyBsM4FiimUbwvqpGpOnktk7) Takes the input in the default buffer, as a sequence of comma-separated list of numbers. Has a trailing newline at the end. Explanation: ``` A <esc> *A*ppend the following to the end of the line: ,0 Literal ,0 x Select the whole line, including the newline _ Trim the selection, removing the newline S,<ret> Split the selection on every comma y Copy the contents of every selection to the default "-register <a-)> Rotate the contents of the selections rightwards a <esc> Append to every selection: + Literal + <c-r>" The contents of the "-register |bc<ret> Pipe every selection into bc, evaluating it ``` [Answer] ## Wolfram Language (Mathematica), 25 bytes (or 14, if phrased as suggested by @att in the comments below) ``` Prepend[#,0]+Append[#,0]& ``` And below is a more "Mathematica-like" solution, in that it uses a mathematical primitive most other languages lack. It requires more bytes than the solution above (which is how most Mathematica programmers would probably solve this in the real world anyway). ``` (n=Length[#];Table[Binomial[n,k],{k,0,n}])& ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 98 bytes ``` IEnumerable<long> p(IEnumerable<long> l)=>l.Concat(new[]{0L}).Zip(new[]{0L}.Concat(l),(a,b)=>a+b); ``` [Try it online!](https://tio.run/##ZVLfa9swEH62/wrRJ5uqQdLpx4lsfRljDDoY7GGw0gfF9TKBI2e20zFC/vbsnC5t7IKNdHe6u@/u@6r@pmq7@rjrY1qzb3/7od4s80tr8aFtmroaYpv6xac61V2sZi/uYvq9zPPtbtXEivVDGOiomtD37GvXrruwyfd5Ng0/tfGRfQkxFf3QUa37Bxa6dV/m2T4/fv6Ydpu6C6umfte0aX3LtsVbX1O@v20IXqrCUKT6z/3DXtwdysWPuH01z/Gm5EXgK0oJ16tyecyynzR3qH4VT6FjkcXEzlmSG8GlUoZLb4XgCgSMh5ToLEUMeuHI4T2i1nQxYNGhpSxlhNEAY1QK5ZRyKJ3g4MDQjzj6lQTvrZGSDDAarTASxz4eHGpjjT11o1KovHFGKsG1V9TDW2/IwT1qB86Dl3JEisKAUYgIjoIgtDCeQCAoqqOdVF7RNBpoGG4dKKe1FVaNYBCd9iiNstqeMKPQoAwAoXjGOgKkK5xASXonBSXrsZV6G5/lz8rPms@gzYDPxprOPN3HdFeTNU4WPF39JScXXF1Q@MrrC9Uv5J/V8F8cz0o5iWak5FCSkEnJWZaR/vq2qRffuzjURby@YlflkgKHnL7D8R8 "C# (.NET Core) – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 58 bytes ``` N J =INPUT :F(O) OUTPUT =I + J I =J :(N) O OUTPUT =I END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/34/TS8HW0y8gNITTyk3DX5OL0z80BMgDCipoK3hxcXoq2HpxWmn4aXL5I6S4XP1c/v835DIGQkMA "SNOBOL4 (CSNOBOL4) – Try It Online") I/O as numbers separated by newlines. ``` N J =INPUT :F(O) ;* Read input. If none exists, goto O OUTPUT =I + J ;* Print I (initially 0) + J I =J :(N) ;* Set I to J and goto N O OUTPUT =I ;* print I (always 1), and terminate the program END ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ê0▌_x+ ``` Port of [my 4-bytes 05AB1E program](https://codegolf.stackexchange.com/a/216486/52210). [Try it online.](https://tio.run/##ZVK5VUQxDMxpBQe6j2p4JEAAj4SAIogpgjbohEY@kheWtQls67I00ujp9uXh/vnx7jg@P@Dr/e3m9fo48ApHH5o3whAdSDCoRFKab@tthhmjbaBS06BiGLgfxHArj0aClyEzQqQEZQsP004HKsztRSAn8kCHwc5aJ6LthJxpilgKq4SBYnSdZA9RU5vVKlVQquuEllQ10lLLMDLE2ZMTsZEGKCtFBHs5GQQ0C0QwVR5xpKTqRriaGeZMLmJg1GAiXDJQycQm5gBhUuZCccLaAEvkCQorDqE@S5ei//7t/5Z@K75B24Bvba09r/NYZ7WMcRnwOvpLTi64uqDwj9cz1Wfyf7fhZzlOmzKXpin5Bg) **Explanation:** ``` ê # Push all inputs as integer array 0▌ # Prepend a 0 _ # Duplicate the list x # Reverse this copy + # Add the values at the same positions in the two lists together # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` IE⊞Oθ⁰⁺ι§θ⊖κ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQCOgtDjDvyC1KLEkv0ijUEfBQFNHISCntFgjU0fBscQzLyW1AiTskppclJqbmleSmqKRrQkG1v//R0cb6iiY6CiYgUnD2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array ⊞O ⁰ Append literal `0` E Map over elements ι Current element ⁺ Plus §θ⊖κ Previous element (cyclic) I Cast to string Implicitly print ``` Alternative approach, relies on symmetry: ``` IE⮌⊞Oθ⁰⁺ι§θκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQCMotSy1qDhVI6C0OMO/ILUosSS/SKNQR8FAU1NHISCntFgjU0fBscQzLyW1AiSerQkC1v//R0cb6iiY6CiYgUnD2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array ⊞O ⁰ Append literal `0` ⮌ Reverse E Map over elements ι Current element ⁺ Plus §θκ Element from unreversed list I Cast to string Implicitly print ``` In both of the above you can replace `⊞Oθ⁰` with `θ` and prefix `⊞θ⁰` to the start for the same effect. ]
[Question] [ Given a letter of the English alphabet, your task is to build a semi-diagonal alphabet to the input. ## How to build a Semi-Diagonal alphabet? **Brief Description**: First, you take the position of the letter in the alphabet, `P` (`P` is 1-indexed here). Then, you print each letter until the input (inclusive) on a line, preceded by `P-1` and repeat that letter `P` times, interleaving with spaces. **Examples**: * Given `F`, your program should output: ``` A B B C C C D D D D E E E E E F F F F F F ``` * Given `K`, your program should output: ``` A B B C C C D D D D E E E E E F F F F F F G G G G G G G H H H H H H H H I I I I I I I I I J J J J J J J J J J K K K K K K K K K K K ``` * Given `A`, your program should output: ``` A ``` ## Rules * You may choose either lowercase or uppercase characters, but that should be consistent. * You may have extraneous spaces as follows: + One consistent leading space (on each line). + A trailing or leading newline(s). + Trailing spaces. * Input and output can be taken by any standard mean, and default loopholes apply. * You are allowed to output a list of lines instead, as long as you also provide the [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") version. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! *Inspired by [this challenge](https://codegolf.stackexchange.com/questions/125117/diagonal-alphabet)*. [Answer] # [Python 3](https://docs.python.org/3/), 59 bytes ``` lambda l:[' '*i+'%c '%(i+65)*-~i for i in range(ord(l)-64)] ``` [Try it online!](https://tio.run/##Xck7DsIwDADQnVN4qWz3g4SgkajEyiUoQ2gJNQpOZXXpwtUDCwtvffO6TEn3OZz6HP3rNnqI3QUBS6mwGAALksq1XDZvgZAMBETBvD7ulGykyI078DX/lWvr4467DcwmuhD2ittnEqVAw2Qk/PVLzucP "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 61 bytes ``` lambda l:[' '*i+-~i*(chr(i+65)+' ')for i in range(ord(l)-64)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHHKlpdQV0rU1u3LlNLIzmjSCNT28xUUxsoqJmWX6SQqZCZp1CUmJeeqpFflKKRo6lrZqIZ@x9NysxUx9JQ04pLoaAoM69EQz0mT10vKz8zTyMNYqQmEMAkNf@7AQA "Python 3 – Try It Online") (link to pretty-print version) [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ ~~61~~ 59 bytes *-2 bytes thanks to Rod. -2 bytes thanks to Felipe Nardi Batista.* ``` i=1 exec"print' '*i+'%c '%(i+64)*i;i+=1;"*(ord(input())-64) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWkCu1IjVZqaAoM69EXUFdK1NbXTVZQV1VI1PbzERTK9M6U9vW0FpJSyO/KEUjM6@gtERDU1MXKPX/v7q3OgA "Python 2 – Try It Online") [Answer] # C, 89 bytes ``` i,j;f(l){for(i=64;i++<l&&printf("%*c ",i-64,i);puts(""))for(j=i-65;j--;)printf("%c ",i);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9TJ8s6TSNHszotv0gj09bMxDpTW9smR02toCgzryRNQ0lVK1lBSSdT18xEJ1PTuqC0pFhDSUlTE6Q8yxYobGqdpatrrQlXDlataV37H8hXyE3MzNPQ5KrmUgCCNA11N3VNaxjbG4ntCGLX/gcA) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~45~~ 42 bytes ``` 65..$args[0]|%{" "*$i+++"$([char]$_) "*$i} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38xUT08lsSi9ONogtka1WklBSUslU1tbW0lFIzo5I7EoViVeEyxW@///f6iQupu6JgA "PowerShell – Try It Online") Takes input as a literal char, then loops up through the capitals to that point, each iteration prepending the appropriate number of spaces and then the char\space hybrid. *Saved 3 bytes thanks to TessellatingHeckler.* [Answer] # JavaScript (ES6), 85 bytes Works in lower case for both input and output. Outputs a leading space and a trailing space on each line. ``` f=(c,k=10,C=k.toString(36),r=s=>`${s} `.repeat(k-9))=>r``+r(C)+(C==c?'':` `+f(c,k+1)) ``` ### Demo ``` f=(c,k=10,C=k.toString(36),r=s=>`${s} `.repeat(k-9))=>r``+r(C)+(C==c?'':` `+f(c,k+1)) O.innerText = f('m') ``` ``` <pre id=O> ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 26 bytes Prompts for scalar character. Prints list of lines. ``` (∊⍴∘'',' ',¨⍨⊢⍴⊃∘⎕A)¨⍳⎕A⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/9fXfyobcKjvql@wQqPetcoPOpuUTCzsgIKBLvqhTr7uqgn5Vco5Ocp6KbZ5uepP@paXKyXmpeYlJMa7OgTAlb@qGtRsR5Qg3OkenFiTol6LdAcrkcd7cGpuZkumYnp@XmJOf81HnV0Perd8qhjhrq6jrqCus6hFY96VwC1ggS7moHiQBMcNUGim0EsCPUfaAy6UY7FyZmZjkUlXI/aJpJnKsjE/wpggGwwl7qbOhc2YW/swo7YhOGuw24YQtobvzTQcAA "APL (Dyalog Unicode) – Try It Online") (has ASCII art version at one additional byte) `⎕` prompt for input `⎕A⍳` find **ɩ**ndex in **A**lphabet `⍳` first that many **ɩ**ntegers `(`…`)¨` apply the following tacit function to each :  `⊃∘⎕A` pick the argument'th letter letter from the **A**lphabet  `⊢⍴` cyclically reshape it to the argument length  `' ',¨⍨` append a space to each  `⍴∘'',` prepend a string of argument length (padded with spaces)  `∊` **ϵ**nlist (flatten) --- The ASCII art version just has a `↑` on the very left; mix list of strings into table of characters. [Answer] ## [Perl 5](https://www.perl.org/), 31 bytes **30 bytes code + 1 for `-l`.** ``` print$"x$-,"$_ "x++$-for A..<> ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvREWpQkVXR0klXkGpQltbRTctv0jBUU/Pxu7/f@9/@QUlmfl5xf91cwA "Perl 5 – Try It Online") [Answer] # Dyalog APL, 38 bytes ``` {↑{(y/' '),(2×y←⎕A⍳⍵)⍴⍵,' '}¨⎕A↑⍨⎕A⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR20TqzUq9dUV1DV1NIwOT68ECj7qm@r4qHfzo96tmo96twApHaB07aEVYPG2iY96VyBU1ALNUTi0Qt3RzTtKHQA "APL (Dyalog Unicode) – Try It Online") **How?** `⎕A↑⍨` - take the alphabet until `⎕A⍳⍵` - the input character `¨` - for each char     `⍵,' '` - take the char and a space     `(...)⍴` - reshape to     `2×y←⎕A⍳⍵` - twice the index of the char in the alphabet     `(y/' ')` - and prepend index-of-char spaces `↑` - then flatten [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 26 bytes ``` {↑{(≠\⍵<⍳3×⍵)\⍵⊃⎕A}¨⍳⎕A⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHbxGqNR50LYh71brV51LvZ@PB0IEsTxH3U1fyob6pj7aEVQHEQC0T1bq0lT5e6mzoA "APL (Dyalog Classic) – Try It Online") ### Explanation ``` ⍳⎕A⍳⍵ generate indexes up to position of right arg ⍵ { }¨ on each index apply function (≠\⍵<⍳3×⍵) generate boolean mask for expansion (each line has a length 3 times its index ⍵, starting with ⍵ blanks and then alternating letter blank) \⍵⊃⎕A expand character in position ⍵ ↑ mix result into text matrix ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~28, 26, 25~~, 23 bytes ([Competing](https://codegolf.meta.stackexchange.com/q/12877/31716)) ``` ¬A[/a lDÓ./& ò ò-Ûä$Û> ``` [Try it online!](https://tio.run/##ASUA2v92///CrEFbLxJhCmxEw5MuLyYgw7IKw7Itw5vDpCTDmz7///9G "V – Try It Online") Note that although I have been planning on adding [certain features](https://github.com/DJMcMayhem/V/commit/5de2c51e581014a2693a8c6d68cdfb3378343510) for a long time, this challenge was what convinced me to finally do it. The output contains one leading space on each line and one trailing newline. Hexdump: ``` 00000000: ac41 5b2f 1261 0a6c 44d3 2e2f 2620 f20a .A[/.a.lD../& .. 00000010: f22d dbe4 24db 3e .-..$.> ``` Explanation: ``` ¬A[ " Insert 'ABCDEFGHIJKLMNOPQRSTUVWXYZ[' / " Search for... <C-r>a " The input l " Move one character to the right D " And delete every character after the cursor Ó " Search for... . " Any character / " And replace it with... & ò " That character followed by a space and a newline ò " Recursively... - " Move to the beginning of the next line up Ûä$ " Make *line number* copies of the current line Û> " And indent this line by *line number* spaces ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 13 bytes ``` z+ḣ∞øzRNC1…'A ``` Takes a character in single quotes as command line argument, prints result to STDOUT. [Try it online!](https://tio.run/##yygtzv7/v0r74Y7FjzrmHd5RFeTnbPioYZm64////9Xd1AE "Husk – Try It Online") ## Explanation I'm exploiting the way Husk prints lists of lists of strings: join inner lists with spaces and outer lists with newlines. ``` z+ḣ∞øzRNC1…'A Implicit input, say 'C' …'A Range from A: "ABC" C1 Cut into strings of length 1: ["A","B","C"] z N Zip with positive integers R using repetition: x = [["A"],["B","B"],["C","C","C"]] ∞ø The empty string repeated infinitely: ["","","",... ḣ Prefixes: [[],[""],["",""],["","",""],... z+ Zip with x using concatenation: [["A"],["","B","B"],["","","C","C","C"]] Implicitly join each inner list with spaces, join the resulting strings with newlines and print. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` A¹¡н«ðâƶāú ``` [Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//0HCucKh0L3Cq8Oww6LGtsSBw7r//2Y "05AB1E – Try It Online") -2 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). Append `»` to make it print in separate lines. [Answer] # R, 94 88 bytes -6 bytes thanks to Giuseppe ``` function(x,l=LETTERS)for(i in 1:match(x,l))cat(rep(' ',i-1),rep(paste(l[i],' '),i),'\n')} ``` Ungolfed: ``` f=function(x,l=letters){ for(i in 1:which(l==x)){ A=paste(l[i],' ') cat(rep(' ',i-1),rep(A,i),'\n') } } ``` [Answer] ## Haskell, ~~52~~ 44 bytes ``` f k=[[" ",s:" "]>>=(['A'..s]>>)|s<-['A'..k]] ``` Returns a list of lines. [Try it online!](https://tio.run/##y0gszk7Nyfn/P00h2zY6WklBSafYCkjG2tnZakSrO6rr6RUD2Zo1xTa6EG52bOz/3MTMPAVbhdzEAt94hYLSkuCSIp88BRWFNAV1V/X/AA "Haskell – Try It Online") ``` f k= -- main function is f, input parameter k [ |s<-['A'..k]] -- for each s from ['A'..k] >>= -- map (and collect the results in a single string) the function: (['A'..s]>>) -- replace each element in ['A'..s] with [ , ] -- over the list, containing " " -- a single space to get the indent s:" " -- s followed by space to get the letter sequence ``` Edit: @jferard: saved three bytes. Thanks! [Answer] # JavaScript (ES8), 92 bytes ``` c=>(g=n=>n>9?[...g(n-1),`${n.toString(36)} `.repeat(n-=9).padStart(n*3)]:[])(parseInt(c,36)) ``` Uses lowercase letters. Lines have one leading and one trailing space. Returns an array of lines. ## Test Snippet ``` let f= c=>(g=n=>n>9?[...g(n-1),`${n.toString(36)} `.repeat(n-=9).padStart(n*3)]:[])(parseInt(c,36)) ;O.innerText=f("k").join`\n` ``` ``` <pre id=O></pre> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 13 bytes Saved 1 byte thanks to *Adnan* ``` A¹¡н«ƶ€S»¶¡āú» ``` [Try it online!](https://tio.run/##ASQA2/8wNWFiMWX//0HCucKh0L3Cq8a24oKsU8K7wrbCocSBw7r//2Y "05AB1E – Try It Online") or the [Ascii art version](https://tio.run/##ASYA2f8wNWFiMWX//0HCucKh0L3Cq8a24oKsU8K7wrbCocSBw7rCu///Zg) **Explanation** ``` A # push lowercase alphabet ¹¡ # split at input н # get the first part « # append the input ƶ # repeat each a number of times corresponding to its 1-based index €S # split each to a list of chars » # join on spaces and newlines ¶¡ # split on newlines āú # prepend spaces to each corresponding to its 1-based index » # join on newlines ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes[SBCS](https://github.com/abrudz/SBCS) ``` ⍕⍪⊢∘⊂\2,.↑⍉⍴⍨⌸⎕a↑⍨⎕a⍳⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgmGXI862tP@P@qd@qh31aOuRY86Zjzqaoox0tF71DbxUW/no94tj3pXPOrZAdSQCBZaAWb1bn7UO@8/UO//NC5vAA "APL (Dyalog Unicode) – Try It Online") Uses `⎕io←1`. Prints a leading space, which is allowed. [Answer] # QBasic, ~~79~~ ~~74~~ 72 bytes *Thanks to Taylor Scott for [byte savings](https://chat.stackexchange.com/transcript/message/45347921#45347921) (twice!)* ``` FOR i=1TO ASC(INPUT$(1))-64 ?TAB(i) FOR j=1TO i ?CHR$(64+i)" "; NEXT j,i ``` Uses uppercase. The input is by keypress and is not echoed to the screen. ### Explanation We loop `i` from `1` up to the limiting letter's position in the alphabet (1-based). For each `i`, we move to column `i` of the screen using `TAB`; then, `i` times, we print the `i`th letter of the alphabet followed by a space. [Answer] # [Japt](https://github.com/ethproductions/japt/) `-R`, ~~24~~ ~~23~~ ~~17~~ 15 bytes Outputs an array, includes a leading newline and a leading & trailing space on each line. ``` IòUc ÏçSiXd¹iYç ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=SfJVYyDP51NpWGS5aVnn&input=IksiCi1S) * 1 byte saved with help from [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) and a further 6 thanks to him pointing out a better way to generate the initial array. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` F⁺⌕αθ¹«P×⁺§αι ⁺ι¹↘ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nmWPGnc96pl6buO5HYd2Hlr9fs@Gw9OBQoeWA0V2KgBZ53Ye2vmobcb//24A "Charcoal – Try It Online") [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 65 bytes ``` a#a-# 7-,-~vc<!?>[$_]:$_|&,(.#a-!?.>[# M]1+>[.M# M]:$_!@|v# &@R); ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/8/UTlRV1nBXFdHt64s2UbR3i5aJT7WSiW@Rk1HQw8op2ivZxetrOAba6htF63nC2IBZRUdasqUudQcgjSt////XwUA "Braingolf – Try It Online") Lowercase. Contains 1 trailing space on each line, and a trailing newline at the end of output. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 103 bytes ``` n=>{var i='`';var l="";for(;i<n;l+='\n'){l+="".PadLeft(i++-96);for(int s=96;s++<i;)l+=i+" ";}return l;} ``` [Try it online!](https://tio.run/##JY6xagMxEETr01csaiSh2KXB7MmNwZUDCSnSpIiQ5cuCIoFWZ0iO@/bL2ZnqwTyGCbwJpcZlZMoDvP1wi98oREieGV7FJGANN98owK3QBZ49ZW3gv7jnNObQhy9fn7jVdeQAAzhYsjtMN1@BnPpUeKfkpMRrqRqpz5isUx9ZmWkFKbcv/nKO16bJ2s1@Zx4e5Qbs9jtka3tCs5pkJUica2xjzZBwXlB0x5K5pLh9r9TimXLUg1a/yhgUs@i6x1MxL38 "C# (.NET Core) – Try It Online") [Answer] # JavaScript, ~~102~~ 94 bytes *2 bytes saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)* ``` f= a=>[...Array(parseInt(a,36)-9)].map((a,b)=>''.padEnd(b).padEnd(b*3+1,(b+10).toString(36)+' ')) console.log(f('k').join`\n`) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 51 bytes ``` ^. $&$& }T`L`_L`^. . $.`$* $&$.`$* ¶ +`(\w) \B $&$1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/To9LRU1Fjas2JMEnId4nAcgHiuglqGgpAMXB9KFtXNoJGjHlmgoxTiDFhv//uwEA "Retina – Try It Online") Explanation: ``` ^. $&$& ``` Duplicate the (first) letter. ``` }T`L`_L`^. ``` Rotate it back 1 in the alphabet, or delete it if it's a duplicate `A`. Keep duplicating and rotating until we duplicate `A`, at which point the deletion undoes the duplication and the loop completes. ``` . $.`$* $&$.`$* ¶ ``` Replace each letter with a line with the letter padded on both sides. ``` +`(\w) \B $&$1 ``` Insert duplicate letters between all pairs of padding spaces to the right of existing letters. [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` x!'@'=x x!e=([e]:[' ':r++' ':[last r]|r<-x])!pred e ([]!) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0JR3UHdtoKrQjHVViM6NdYqWl1B3apIWxtEReckFpcoFMXWFNnoVsRqKhYUpaYopP7PTczMsy0oLQkuKVIpzcvJzEstVomOVVQPVP8PAA "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` F…·AS«P⪫E…@ιι ↘ ``` [Try it online!](https://tio.run/##LYtBCsIwEADP@oqQ0y7YD@hFQYQKvdQXhBDThbAJaRIP4tu3AXuYyzBjF5NtNEHkHbOCkW2oKzU3G/YO9E2f1MipllfJxB4QUX2Ph6mGQqmbAs9IDJNJsB/XfhD@0UojXnoem4PzPX54Jr@Urn4iDxmaDGvYAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` …·AS Inclusive character range from A to the input F « Loop over each character …@ι Exclusive range from @ to the current character E ι Replace each element with the current character ⪫ Join with spaces P Print without moving the cursor. ↘ Move the cursor down and right. ``` If extra padding was legal, this would work for 14 bytes: ``` E…·?θ⁺× κ⪫× κι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDMy85p7Q4syw1KDEvPVVDyV5JR6FQU0chACiqEZKZm1qsoaQAFMsGinnlZ@ahi2VqAoH1//9u/3XL/usW5wAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # Mathematica, 70 bytes ``` (T=Table)[""<>{" "~T~i,T[Alphabet[][[i]]<>" ",i]},{i,LetterNumber@#}]& ``` lowercase outputs a list *thanx @ngenisis for corrections* For [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") version place `Column@` at the beginning [Answer] # Excel VBA, 72 Bytes Anonymous VBE immediate window function that takes input from cell `A1` and outputs to the VBE immediate window ``` For i=1To Asc([A1])-64:[B1]=i:?Space(i-1)[REPT(CHAR(B1+64)&" ",B1)]:Next ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 17 bytes ``` .e+*kd*+bdhk<GhxG ``` **[Try it here (pretty print version).](https://pyth.herokuapp.com/?code=j.e%2B%2akd%2a%2Bbdhk%3CGhxG&input=%22r%22&debug=0)** --- # How does this work? * `hxG` - Takes the index of the input in the lowercase alphabet. * `<G` - Trims every character after the input from the alphabet. * `.e` - Enumerated Map. Maps over the trimmed alphabet with the indexes as `k` and the letters as `b`. * `*kd` - Append `k` spaces. * `+bd` - `b` + a space (the current letter + space). * `*...hk` - Repeat `k+1` times. * `+(...)(...)` - Concatenate. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 164 bytes ``` #include<iostream> #define f for(int i=0;i<o-'`';i++) using namespace std;int main(){char c;cin>>c;for(char o='a';o<=c;o++){f cout<<' ';f cout<<o<<' ';cout<<'\n';}} ``` My first attempt after a long time lurking! Ungolfed code below: ``` #include <iostream> using namespace std; #define f for (auto i = 0; i < output - '`'; i++) int main() { char input; cin >> input; for (char output = 'a'; output <= input; output++) { f cout << ' '; f cout << output << ' '; cout << endl; } } ``` [Try it online!](https://tio.run/##NYxLDoMwDET3nMISi4AQUvcOnKSLRiahroqNSLJCnD0t/exm5o0erWs/E5VSs9AzT96yxrR5t4xVPfnA4iFA0K1hScDDBdlqb24GuevaKkeWGcQtPq6OPMQ04XlcHEvT7nR3GxASyzgSnpbPooNxBtUOhPq27AFIc7LWgMF/1m/9gasYPI5SHi8 "C++ (gcc) – Try It Online") ]
[Question] [ The domain server requires that all employees have a strong, random password conforming to the following rules: * Exactly 15 characters long. * Keyboard-typeable characters only (as shown in code-type below). Teaching the sales to use ALT+NUMPAD codes is not permitted. * At least 1 lower case letter: `abcdefghijklmnopqrstuvwxyz` * At least 1 upper case letter: `ABCDEFGHIJKLMNOPQRSTUVWXYZ` * At least 1 numeric digit: `0123456789` * At least 1 symbol: ``~!@#$%^&*()_+-={}|[]\:";'<>?,./` For this purpose IT have commissioned and will be distributing a Random Password Generator to all employees. All employees will be required to use the Random Password Generator. The requirements for the Random Password Generator are, in addition to the password restrictions above: * It must be able to generate all permutations of all allowable characters. * It must display the generated password on the screen. * The code is required to be as small as possible (in bytes). Please submit your proposed solution within the next week. [Answer] # Mathematica (18) Let me a little cheat ``` = 15char ASCII pwd ``` > > > ``` > &(^F7yP8k:*1P<t > > ``` > > P.S. not safety :) [Answer] # Ruby, 74 69 bytes Just randomly sample from the ascii range 33 - 126 until all classes of characters are present: ``` $_=[*?!..?~].sample(15)*''until~/\d/&&~/[a-z]/&&~/[A-Z]/&&~/\W|_/ p$_ ``` # Ruby, 39 bytes Using moose's clever discovery: ``` p"0123abcdABCD-+/<".chars.sample(15)*'' ``` --- Edit to satisfy the mob: Note that the rules changed *after* I first posted this. At the time *both* the previous entries applied to the rules. I would also like to point out that the rules are still not too well defined: > > (..) all permutations of all allowable characters > > > "Permutations". There are ***no*** [permutations](http://en.wikipedia.org/wiki/Permutation) of the allowable characters that complies with the rest of the rules, because any permutation of the set of allowable characters is as long as the set of allowable characters itself (while the password is supposed to be 15 characters long). *And there are no repetitions in a permutation.* However my first entry is still more "random" than many of the other well upvoted answers here. Nevertheless, here you have it. Allows repetitions of characters and underscore: # Ruby, 77 bytes ``` $_=([*?!..?~]*15).sample(15)*''until~/\d/&&~/[a-z]/&&~/[A-Z]/&&~/\W|_/ puts$_ ``` I also used `puts` instead of `p` in this one because `p` prints out the string enclosed in "quotation marks" and some characters escaped with a backslash. # Ruby, 70 bytes As Ventero points out, `~` can be skipped in front of the regexes, and `print` can replace `puts$_`. But with the ugly output this causes you might as well print all the rejected passwords too, squeezing it into a one-liner: ``` puts$_=([*?!..?~]*15).sample(15)*''until/\d/&&/[a-z]/&&/[A-Z]/&&/\W|_/ ``` ### Explanation As requested. `$_` is a semi-magical variable that contains the last line read from input - so you don't always need to store it, like [this](https://codegolf.stackexchange.com/questions/17331/shrink-a-number-string/17356#17356). Here however we use it because of another property, namely that the [`~`](http://www.ruby-doc.org/core-2.0/Regexp.html#method-i-7E) operator applies a regex directly to it, a trick I first learned by [chron](https://codegolf.stackexchange.com/questions/11901/chess960-position-generator/11902#11902). I replaced the usage of `all`, but it should be quite easy to understand if you get the rest ([see the docs](http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-all-3F)). [Answer] # Java 8 - 354 329 319 275 267 characters Just for fun, using lambdas with Java 8 - each possible output has the same probability of being found. It uses the fact that the allowed characters have consecutive ascii codes, from 33 to 126. ``` class A { //flags for, respectively, small caps, large caps, digits, punctuation static int a, A, d, p; public static void main(String[] x) { String s; do { //Using special String constructor that takes an int[] s = new String(new java.util.Random().ints(15, 33, 127) .toArray(), 0, 15); a = A = d = p = 0; s.chars() .map(c -> c > 96 & c < 123 ? a = 1 : c > 64 & c < 90 ? A = 1 : c > 47 & c < 58 ? d = 1 : (p = 1)) .min(); } while (a + A + d + p < 4); System.out.println(s); } } ``` Sample output: ``` .*;Tm?svthiEK`3 o.dzMgtW5|Q?ATo FUmVsu<4JF4eB]1 ``` Compressed program: `class A{static int a,A,d,p;public static void main(String[]x){String s;do{s=new String(new java.util.Random().ints(15,33,127).toArray(),0,15);a=A=d=p=0;s.chars().map(c->c>96&c<123?a=1:c>64&c<90?A=1:c>47&c<58?d=1:(p=1)).min();}while(a+A+d+p<4);System.out.println(s);}}` [Answer] # Python 2.X + 3.X (229 characters): Generate and replace ## Idea 1. First make a list with 15 allowed symbols 2. Replace a random position `r` by a random digit 3. Replace a random position `s`, with `s != r`, by an upper case letter 4. The same for lower case letter and symbol as in 2 and 3. ## Code ``` from random import randint as r, shuffle as s a=list(range(15)) p=a[:] for i in range(15): a[i]=chr(r(32,126)) s(p) a[p.pop()]=chr(r(48,57)) a[p.pop()]=chr(r(65,90)) a[p.pop()]=chr(r(97,122)) a[p.pop()]=chr(r(33,47)) print(a) ``` # Python 2.X + 3.X (194 characters): Generate and check ``` import random from re import search as s p='' while not all([s("\d",p),s("[a-z]",p),s("[A-Z]",p),s("[\W_]",p)]): p=str(map(chr,[random.choice(list(range(33,127))) for i in range(15)])) print(p) ``` * Thanks to [MvG](https://codegolf.stackexchange.com/users/13683/mvg) who told me that `\u` and `\l` does not exist in Python regex. * Thanks to [grc](https://codegolf.stackexchange.com/users/4020/grc) who told me that [`random.sample`](http://docs.python.org/2/library/random.html#random.sample) is without replacement, be to get every possible allowed password we need sampling with replacement. # Using flaw in the problem description Currently, the problem description does not demand that every symbol / digit appears with the same probability. With the following solution, you cannot make any assumption about a single symbol and/or position. But you can do it with multiple ones. ## Python 2.X+ 3.X (62 characters) ``` from random import sample print(sample("0123abcdABCD-+/<",15)) ``` Thanks to daniero for the idea to use sample. [Answer] # Bash on \*nix (109) ``` while ! grep -Pq [A-Z].*[a-z].*[0-9].*[\\W_]<<<$a$a$a$a do a=`tr -dc !-~</dev/urandom|head -c15` done echo $a ``` To work correctly, `$a` must not be set to a valid but non-random password up front. If you want to include `a=` and a line break up front, that's three more characters but it allows you to run the thing repeatedly. You can obviously also replace all newlines with `;` so you have a one-liner which you can execute as often as you whish. Furthermore, you should have set `LC_ALL=C` or not set any locale-specific environment variables (`LANG` and `LC_CTYPE` in particular), since the character ranges depend on collation order being equal to ascii order. `/dev/urandom` is the a source of random bytes. `!-~` is the range of all permissible characters, as specified in the question. `tr -dc` removes all characters *not* listed in its next argument. `head` takes 15 of the remaining characters. `grep` checks whether each of the required kinds does occur at least once. Its input consists of four copies of the candidate, so order of the symbols does not matter, hence all possible passwords stand a chance of getting selected. The `-q` to grep suppresses output. For reasons unknown, `/dev/random` instead of `/dev/urandom` takes ages. It seems like entropy got exhausted pretty quickly. If you `cd` into `/dev`, you can avoid some more bytes, but that feels a bit like cheating. # Python 2 (138) ``` import re,random a='' while not re.search('[A-Z].*[a-z].*[0-9].*[\W_]',a*4): a=''.join(random.sample(map(chr,range(33,127))*15,15)) print a ``` To make the code readable I added a newline and indentation after the loop which is not neccessary and which I did not count. This is essentially the same idea as in the bash version. The random source here is `random.sample`, which will not repeat elements. To counter this fact, we use 15 copies of the list of permissible letters. That way, every combination can still occur, although those with repeated letters will occur less often. But I decide to consider this a feature, not a bug, since the question did not require equal probability for all permutations, only the possibility. # Python 3 (145) ``` import re,random a='' while not re.search('[A-Z].*[a-z].*[0-9].*[\W_]',a*4): a=''.join(random.sample(list(map(chr,range(33,127)))*15,15)) print(a) ``` One newline and one indent again not counted. Apart from some Python-3-specific syntax overhead this is the same solution as for Python 2. # JavaScript (161) ``` a=[];for(i=33;i<127;)a.push(s=String.fromCharCode(i++)); while(!/[A-Z].*[a-z].*[0-9].*[\W_]/.test(s+s+s+s)) for(i=0,s="";i<15;++i)s+=a[Math.random()*94|0];alert(s) ``` I added the newlines for readability, but did not count them. # R (114) ``` s<-"" while(!grepl("[A-Z].*[a-z].*[0-9].*(\\W|_)",paste(rep(s,4),collapse=""))) s<-intToUtf8(sample(33:126,15,T)) s ``` Linebreak and indentation inside loop added but not counted. If you feel like it, you can again move this to a single `;`-separated line. [Answer] # C# (123 - 139 103 - 127 characters compacted): Using a perfectly adequate framework method in `System.Web.dll`: ``` class P { static void Main() { Console.WriteLine(System.Web.Security.Membership.GeneratePassword(15, 1)); } } ``` Compacted: ``` class P{static void Main() {Console.WriteLine(System.Web.Security.Membership.GeneratePassword(15,1));}} ``` Example: ``` b+m2ae0K:{dz7:A ``` Alternatively, take the value of the second parameter (`int numberOfNonAlphanumericCharacters`) from the command line: ``` class P { static void Main(string[] a) { Console.WriteLine(System.Web.Security.Membership.GeneratePassword(15, int.Parse(a[0]))); } } ``` [Answer] # R (~~301~~ 322 characters) **Correction** forgot to check for digits. ``` a='abcdefghijklmnopqrstuvwxyz'; f=as.factor(strsplit(paste(a,toupper(a), sep="0123456789`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./"),"")[[1]]); g=gsub("(.):","\\1",levels(q:q:q:q:q:q:q:q:q:q:q:q:q:q:q)); repeat{p=g[runif(1)*length(g)]; if(grepl("[A-Z]",p)&&grepl("[a-z]",p)&&grepl("[0-9]",p)&&grepl("[^A-Za-z0-9]",p))break;}; print(p); ``` (whitespace added for clarity only). Generates all possible 15-character permutations of the 94 characters. Then randomly selects one until it matches the criteria. The magic is in the `q:q` operation, which generates a new factor data type that is the [interaction of all the factors in the first `q` list with all the factors in the second list](http://astrostatistics.psu.edu/datasets/R/html/base/html/seq.html), with every possible combination of those two lists being included in the list of "levels" of that factor. Interact 15 copies of the list of allowed characters, and you get (94^15) possible levels. Please do not try this at home. The code takes a couple seconds to figure out all the three-character permutations, I really can't imagine how long it would take to figure out all the 15-character permutations, if your computer didn't just run out of memory in the meantime. When I ran the finished (three-character password) script to check it, the first password it spit out was "oO=", which I think about sums up the reaction you should have to this code. [Answer] # Mathematica 170 ``` r=RandomSample;f[i_]:=(FromCharacterCode/@Range@@i); {t,A,a,n}=f/@{{33,126},{65,90},{97,122},{48,57}}; s=Complement[t,A,a,n]; ""<>r[Join[RandomChoice/@{A,a,n,s},r[t,11]],15] ``` **Examples** "<]}Pg3/e?3+Z~Oz" "X/8jWe@f(\_x5P:=" "2wz2VQhtJC?\*R7^" [Answer] ## Python 2.7 (182) ``` import random as r,string as s z=r.sample j=list(z(s.ascii_lowercase,12)+z(s.ascii_uppercase,1)+z(s.digits,1)+z('`~!@#$%^&*()_+-={}|[]\\:";\'<>?,./',1)) r.shuffle(j) print ''.join(j) ``` [Answer] **Golfscript (60)** Since the obl. golfscript is missing and as a noob I need the practice anyway :) ``` [48 10{rand}:r~+65 26r+97 26r+33 15r+11,{;32 96r+}%~]{r}$''+ ``` It just builds an array with the 4 required + 11 random characters and sorts in random order. [Answer] # JavaScript 258 240 233 225 ``` R=Math.random;a=b=>b[b.length*R()|0];for(x=[a(l="abcdefghijklmnopqrstuvwxyz"),a(u=l.toUpperCase()),a(n="0123456789"),a(s="`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./")];15>x.length;x.push(a(l+u+n+s)));alert(x.sort(y=>.5-R()).join("")) ``` Using a rule where: `function(x){return x*x}` can be re-written as `function(x)x*x`. Only seems to work for functions returning a value. Next iteration, reduced `x.sort(function().5-R())` to `x.sort(y=>.5-R())` Next iteration, reduced further with fat arrow notation, which sadly only works for Firefox 22 and above. [Answer] ## JavaScript (269 characters compacted) For clarity, this is the code *before* I compacted it down [JS-Fiddle of it](http://jsfiddle.net/IQAndreas/qsPEc/2/): ``` var lowerLetters = "abcdefghijklmnopqrstuvwxyz"; var upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var numbers = "0123456789"; var symbols = "`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./"; var allCharacters = lowerLetters + upperLetters + numbers + symbols; String.prototype.randomChar = function() { return this[Math.floor(this.length * Math.random())]; } var minLength = 15; var result = []; // Start off by picking one random character from each group result.push(lowerLetters.randomChar()); result.push(upperLetters.randomChar()); result.push(numbers.randomChar()); result.push(symbols.randomChar()); // Next, pick a random character from all groups until the desired length is met while(result.length < minLength) { result.push(allCharacters.randomChar()); } result.shuffle(); // Finally, shuffle the items (custom function; doesn't actually exist in JavaScript, but is very easy to add) -> http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array result.join(""); ``` Here it is compacted down to 269 characters ([JS-Fiddle of it](http://jsfiddle.net/IQAndreas/qsPEc/8/)): ``` l="abcdefghijklmnopqrstuvwxyz"; u=l.toUpperCase(); n="0123456789"; s="`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./"; R=Math.random; function r(t){ return t[~~(t.length*R())] } for(x=[r(l),r(u),r(n),r(s)];x.length<15;x.push(r(l+u+n+s))); x.sort(function(){return .5-R()}); alert(x.join("")); ``` [Answer] # Clojure (63): ``` (->> (map char (range 33 127)) (shuffle) (take 15) (apply str)) ``` But need to be improved to ensure that containing at least 1 character of each category (Upper, Lower, Digit, Symbol). [Answer] # In sql-server ``` declare @a nvarchar(28) set @a='abcdefghijklmnopqrstuvwxyz' declare @b nvarchar(max) set @b='ABCDEFGHIJKLMNOPQRSTUVWXYZ' declare @c nvarchar(max) set @c='0123456789' declare @d nvarchar(max) set @d='~!@#$%^&*()_+-={}|[]\:";<>?,./' select left(substring(@a,cast(rand()*10 as int),3)+substring(@b,cast(rand()*10 as int),6)+substring(@c,cast(rand()*10 as int),3)+substring(@d,cast(rand()*10 as int),5),15) ``` # [See it in action--1](http://www.sqlfiddle.com/#!6/c28a0/1) # [see it in Action--2](http://www.sqlfiddle.com/#!6/d41d8/13535) [Answer] ## SAS (191) ``` %macro c(p);compress(p,,"&p")ne''%mend;data x;length p$15;do x=1by 1;do t=1to 15;substr(p,t,1)=byte(ranuni(7)*94+33);end;if %c(kd)and %c(kl)and %c(ku)and %c(ad)then do;put p;stop;end;end;run; ``` `*TQP,(f=h10*)S=` Commented/indented: ``` %macro c(p); /*compress removes or keeps certain classes of characters*/ compress(p,,"&p")ne'' %mend; data x; length p$15; do x=1by 1; do t=1to 15; substr(p,t,1)=byte(ranuni(7)*94+33); /*give it a 33-126, byte discards the noninteger portion rounding down*/ end; if %c(kd)and %c(kl)and %c(ku)and %c(ad)then do; /*k=keep d=digit l/u=lower/upper ad=remove digits and alphas*/ put p; stop; /*met our requirement, head home*/ end; end; run; ``` [Answer] # PowerShell: 119 **Gofled Code** ``` for(;!($x-cmatch'.*(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!-/:-@[-`{-~]).*')){$x='';1..15|%{$x+=[char](33..126|random)}}$x ``` **Un-golfed and Commented** ``` # Start for loop definition. for( # Skip variable initialization, start definition of run condition. ; # Loop runs if $x does not meet complexity requirements. # Length requirement is not tested here because it is enforced by the generator later. # Much thanks to @VasiliSyrakis for the RegEx help. !($x-cmatch'.*(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!-/:-@[-`{-~]).*') ) { # Reset $x in case the script block has already run. $x=''; # Use ForEach-Object, via the % alias, to run a loop 15 times. 1..15|%{ # Append a random ASCII character from 33-126 to $x. # Note: Use get-random instead of random for faster performance. $x+=[char](33..126|random) } } # Display $x. $x # Variable cleanup - not included in golfed code. rv x ``` [Answer] **Python 2.7 (149)** ``` from random import* ''.join(map(lambda x:chr(randint(*(x[1]or(32,126)))),sorted(map(None,sample(range(15),15),((48,57),(65,90),(97,122),(33,47)))))) ``` Written out in a more readable (and not executable) way; ``` from random import * ''.join( # Concatenate characters to string map( # Map all characters using below lambda lambda x:chr(randint(*(x[1] or (32, 126)))), # Map a single range to a random character # within a specific range if supplied, # otherwise the default "all" range. sorted( # After distributing ranges, sort map(None, # zip_longest alternative, distributes the # required ranges over 4 random positions sample(range(15), 15), # 0-14 in random order ((48, 57), (65, 90), (97, 122), (33, 47)) # The 4 required ranges ) ) ) ) ``` Fairly straight forward and surprisingly not much longer than a "generate, retry on match fail" version. [Answer] **PSQL (189)** Feels like PSQL is a bit verbose... :) ``` SELECT ARRAY_TO_STRING(ARRAY_AGG(CHR((TRUNC((b-a)*RANDOM()+a))::int)ORDER BY RANDOM()),'')FROM(SELECT 32 a,127 b FROM generate_series(1,11)UNION ALL VALUES(48,58),(65,91),(97,123),(33,48))a ``` [SQLfiddle demo](http://sqlfiddle.com/#!15/d41d8/842). [Answer] ## PHP, 235 225 This script shuffles characters around and then is checked via RegEx to make sure the password is strong (or it is regenerated). ``` <?php while(!preg_match('/^(?=.*[A-Z])(?=.*[^A-Za-z])(?=.*[0-9])(?=.*[a-z]).{15}$/',$p)){ $p = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()_+-={}|[]\:";\'<>?,./'),0,15); } echo $p; ``` [Answer] **Javascript (209)** ``` r=Math.random;function t(x,y){return String.fromCharCode(Math.floor(y*r()+x))};x=[t(33,14),t(48,10),t(65,26),t(97,26)];for(i=0;i<11;i++)x.push(t(32,95));console.log(x.sort(function(){return r()-0.5}).join('')) ``` Semi-ungolfed; ``` // Return a character in the range [x,x+y) function t(x,y) { return String.fromCharCode(Math.floor(y*Math.random()+x)) } // Prefill required ranges x=[ t(33,14), t(48,10), t(65,26), t(97,26)] // Push 11 totally random (valid) characters for(i=0; i<11; i++) x.push(t(32,95)) // Shuffle and output as string console.log(x.sort(function(){return Math.random()-0.5}) .join('')) ``` [Answer] ## Perl, 92 Not as concise as the Ruby answer, but I'm sure a Perl wizard could make this even shorter... I'm not too happy with all the `m//`s at the end, but seems to work and should satisfy the conditions to eventually generate all permutations. ``` do{$_=join"",map{(map{chr}33..127)[rand 94]}0..14}while!(/[A-Z]/&/[a-z]/&/\d/&/[\W_]/);print ``` Sample usage: ``` perl -e 'do{$_=join"",map{(map{chr}33..127)[rand 94]}0..14}while!(/[A-Z]/&/[a-z]/&/\d/&/[\W_]/);print' ``` Edited to fix validation and change `[[:punct:]]` to `[\W_]` after MvGs comments. [Answer] ## Java 7 (~~270~~ 234 characters) The premise is the same used by @assylias with java 8 (generate random passwords until valid password). However, instead of using lambdas, the password is generated by iterating a char array and validated by matching a regex. ``` class A { public static void main(String [] a) { byte[] b = new byte[15]; String s; do { new java.util.Random().nextBytes(b); s = new String(b); } while(!s.matches("(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?=.*?[!-/:-@\\[-`]).*")); System.out.println(s); } } ``` Minified Code: ``` class A {public static void main(String[] a){byte[] b=new byte[15];String s;do{new java.util.Random().nextBytes(b);s=new String(b);}while(!s.matches("(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?=.*?[!-/:-@\\[-`]).*"));System.out.println(s);}} ``` [Answer] # Powershell --- ## One Liner version (143 bytes) ``` sal g random;1..11|%{$P+=[char](33..126|g)};(65..90|g),(97..122|g),(48..57|g),(33..47+58..64+123..126|g)|%{$P=$P.insert((1..11|g),[char]$_)};$P ``` ## Mini version (146 bytes) ``` sal g random 1..11|%{$P+=[char](33..126|g)} (65..90|g),(97..122|g),(48..57|g),(33..47+58..64+123..126|g)|%{$P=$P.insert((1..11|g),[char]$_)} $P ``` ## Readable version (860 bytes) ``` function pwgen { # Fulfill Upper,Lower,Digit,Symbol requirement by predefining ASCII ranges for each # These will be added into the string beginning at line 24 [array[]]$symbolrange = (33..47),(58..64),(123..126) [char]$upper = (get-random (65..90)) [char]$lower = (get-random (97..122)) [char]$digit = (get-random (48..57)) [char]$symbol = $symbolrange | get-random [char[]]$requirement = $upper + $lower + $digit + $symbol # Create the first 11 characters using any ASCII character between 32 - 126 foreach ($number in (1..11)) { [string]$pass += [char](get-random (33..126)) } # Insert each requirement character at a random position in the string foreach ($char in $requirement) { [string]$pass = $pass.insert((Get-Random (1..11)),$char) } return $pass } ``` > > Credit to Iszi for various tips to shorten the code. > > > [Answer] # Factor, 196 characters Same algorithm as MvG and moose's. It is not the shortest but should satisfy all the (current) criteria in the question: ``` USING: io kernel math pcre random sequences sequences.repeating ; [ 15 94 random-integers [ 33 + ] "" map-as dup 60 cycle "[A-Z].*[a-z].*[0-9].*[\\W_]" findall { } = not ] [ drop ] until print ``` [Answer] # C - 154 characters ``` char p[16],c,f,w;main(){srand(time());while(f^15){c=p[15]=f=0;while(c^15){w=33+rand()%94;f|=w >96&&w<123?1:w>47&&w<59?2:w>64&&w<91?4:8;p[c++]=w;}}puts(p);} ``` How do I hate `srand()`? Let me count the ways. [Answer] # Haskell, 192 ``` import System.Random main=getStdGen>>= \g->(print.(take 15))$until((\x->all(any(`elem`x))[['a'..'z'],['A'..'Z'],['0'..'9'],['!'..'/']++":;<=>?@[\\]^_`{|}~"]).(take 15))tail$randomRs('"','~')g ``` The printed string has quotes around it and escapes the backslash and quote characters; if that's unacceptable, `print` can be replaced with `putStrLn` for 3 more bytes. Here's a more readable version: ``` import System.Random main = do g <- getStdGen let chars = randomRs ('"', '~') g let password = take 15 $ until (hasChars.(take 15)) tail chars print password hasChars :: String -> Bool hasChars x = all (any (`elem` x)) $ [ ['a'..'z'] , ['A'..'Z'] , ['0'..'9'] , "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" ] ``` It's quite straightforward, it just creates an infinite/lazy list of random ASCII characters in the range `'!'` to `'~'`, then tosses out the first element until the first 15 characters have at least one character from each string of required characters. [Answer] ### Excel VBA, 209 bytes ``` For i = 1 To 15 x = x + Chr(Int(90 * Rnd + 33)) Next p = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$" With New RegExp .Pattern = p Set m = .Execute(x) If m.Count = 0 Then MsgBox "redo" Else MsgBox x End If End With ``` Randomly generates 15 ASCII characters so all possible combinations are possible. Then uses a regular expression pattern to check if it contains at least one of each criteria. If it does then the password is displayed, if not "redo" is displayed. Credit to Bart Kiers for the Regular Expression pattern: <https://stackoverflow.com/questions/1559751/regex-to-make-sure-that-the-string-contains-at-least-one-lower-case-char-upper> [Answer] # [Python 3](https://docs.python.org/3/) + [passgen](https://pypi.org/project/passgen/), 64 bytes ``` import passgen as p print(p.passgen(length=15,punctuation=True)) ``` **If you have any suggestions for improvement, let me now in the comments!** [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEgsbg4PTVPIbFYoYCroCgzr0SjQA8qqJGTmpdekmFraKpTUJqXXFKaWJKZn2cbUlSaqqn5/z8A "Python 3 – Try It Online") (or rather don't, as the `passgen` module isn't on TIO) Github: <https://github.com/EacyCoding/Password_Generator> or in one line: ``` import passgen as p;print(p.passgen(length=15,punctuation=True)) ``` Sample Outputs: ``` ;dLjI3pr7541(CW 3ptRCt%OK^8+iW; dDZk7^1!53rG$3M ``` [Answer] ## AutoHotkey 352 ``` global o:={} loop 4 o[c()]:=o(A_index-1) loop 11 o[c()]:=o(m(r(),4)) loop 15 s.=o[A_index-1] msgbox % s r(){ Random,z return z } m(z,r){ return mod(z,r) } c(){ while o[t:=m(r(),15)]!="" j++ return t } o(f){ r0:=48,l0:=10,r1:=97,l1:=l2:=26,r2:=65 r := chr(r%f%+m(r(),l%f%)) if f=3 r:=Substr("``~!@#$%^&*()_+-={}|[]\:"";'<>?,./",m(r(),32)+1,1) return r } ``` **Using** - Just run the script [Answer] ## Python (121 characters) Makes use of the fact that you can multiply lists in Python [1,2,3] \* 2 gives [1,2,3,1,2,3]. Imports random. Numbers in a list multiplied by three are borders between ranges in ascii table for needed characters, e.g. [65, 90] maps to uppercase letters. ``` print "".join([random.choice([chr(i) for i in range(z[0],z[1])]) for z in [[33,48],[48,58],[58,65],[65,90],[90,123]]* 3]) ``` ]
[Question] [ This challenge is about printing the abacaba sequence of a specific depth. Here is a diagram of the first 5 sequences (`a(N)` is the abacaba sequence of depth N, upper/lowercase is just to show the pattern, this is not needed in the output of your program): ``` a(0) = A a(1) = aBa a(2) = abaCaba a(3) = abacabaDabacaba a(4) = abacabadabacabaEabacabadabacaba ... a(25) = abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaiabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabajabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaia... ``` As you can probably tell, the n'th abacaba sequence is the last one with the n'th letter and itself again added to it. (`a(n) = a(n - 1) + letter(n) + a(n - 1)`) Your task is to make a program or function that takes an integer and prints the abacaba sequence of that depth. The output has to be correct at least for values up to and including 15. [Answer] # Pyth, 11 bytes ``` u++GHG<GhQk ``` Simple reduction. [Answer] ## Python, 44 bytes ``` f=lambda n:"a"[n:]or f(n-1)+chr(97+n)+f(n-1) ``` Looks suspiciously might-be-golfable. [Answer] ## Haskell, ~~39~~ 37 bytes ``` a 0="a" a n=a(n-1)++['a'..]!!n:a(n-1) ``` Usage example: `a 3` -> `"abacabadabacaba"`. Edit: @Angs found two bytes to save. Thanks! [Answer] # Pyth, ~~14~~ 13 bytes Thanks to Jakube for saving a byte! ``` VhQ=+k+@GNk;k ``` A solution with 14 bytes: `VhQ=ks[k@GNk;k`. Explanation: ``` VhQ=+k+@GNk;k # Implicit: k = empty string VhQ # For N in range input + 1 = # Assign k +@GNk # Position N at alphabet + k +k # k + above ; # End loop k # Print k ``` Try it [here](https://pyth.herokuapp.com/?code=VhQ%3D%2Bk%2B%40GNk%3Bk&input=3&debug=0)! [Answer] # Brainfuck, 157 bytes ``` ,+>-[>++<-----]>----->>+<<<<[->>[[->>[>>>]<+<+<[<<<]>>[>>>]<]>>[>>>]<[-<<[<<<]>>[>>>]<+>>[>>>]<]+>+<<<[<<<]>>[>>>]+[>>>]<]<<<+>>[<-<<]<]>>>>[>>>]<<<<<<[<<.<] ``` Input is given in binary. The basic idea is to repeatedly duplicate the current sequence (starting with "a") and to increment the last element after each iteration: 1. a → aa → ab 2. ab → abab → abac 3. abac → abacabac → abacabac 4. ... When all of this has been done the specified amount of times, the result gets printed excluding the last element. ## In-depth explanation The memory is arranged in the following way: ``` .---------.-.-----.----.---.-----.----.---.--- |Countdown|0|Value|Copy|End|Value|Copy|End|... '---------'-'-----'----'---'-----'----'---'--- |--Element 1---|--Element 2---| ``` **Countdown** holds the number of copy cycles that are yet to be executed. The ABACABA sequence is stored in adjecent blocks, each made up of 3 cells. **Value** holds the character of the element (i.e. "A","B","C"...). The **Copy** flag indicates whether or not the corresponding element needs to be copied within the current copying cycle (0=copy, 1=don't). The **End** flag is set to 0 for the last element while it is being copied (it's 1 in all other cases). Now to the actual (slightly ungolfed) program: ``` , read Countdown from input + add 1 to avoid off-by-one error >-[>++<-----]>----- initialize value cell of first element to 97 ("a") >>+ set End flag of first element to 1 <<<< move to Countdown [ loop until Countdown hits 0 (main loop) - decrement Countdown >> move to Value cell of first element [ copying loop [ duplication sub-loop - decrement Value cell of the element to copy >> move to End flag [>>>] move to End flag of the last element <+<+ increment Copy and Value cell of last element (Copy cell is temporarily abused) < move to End flag of second to last element [<<<]>> move back to Copy cell of first element [>>>]< move to Value cell of the first element where the Copy flag is 0 ] >>[>>>]< move to (abused) Copy flag of the last element [ "copy back" sub-loop - decrement Copy flag << move to End flag of second to last element [<<<]>> move back to Copy cell of first element [>>>]< move to Value cell of the first element where the Copy flag is 0 + increment Value cell >>[>>>]< move back to Copy flag of the last element ] +>+ set Copy and End flag to 1 <<< move to End flag of second to last element [<<<]>> move back to Copy cell of first element [>>>]< move to Value cell of the first element where the Copy flag is 0 >+< set Copy flag to 1 >[>>>]< move to Value cell of the next element to copy ] loop ends three cells behind the last "valid" Value cell <<<+ increment Value cell of last element >> move to End flag [<-<<] reset all Copy flag < move to Countdown ] >>>> move to End flag of first element [>>>]<<< move to End flag of last element <<< skip the last element [<<.<] output Value cells (in reverse order, but that doesn't matter) ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~37~~ 32 bytes ``` $ aa (T`_l`l`.$ )`1(a.*) $1$1 z ``` The trailing linefeed is significant. Input is taken [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). [Try it online!](http://retina.tryitonline.net/#code=JAphYQooVGBfbGBsYC4kCilgMShhLiopCiQxJDEKego&input=MTExMQ) [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` tail.(iterate((:"a").succ=<<)"_a"!!) ``` [Try it online!](https://tio.run/##BcHBCoAgDADQX5nSQQ956Rb6J0GMoTUykVy/33rvxHHlWrWkTQW5BseSH5Ts3GrR@jBeohSjtztaY7zeyA0S9IebwAQFFv2oVDyGztT7Dw "Haskell – Try It Online") This uses a different recursive method from most of the other answers. To get the next string in the sequence, we don't join two copies in the previous string with a new letter in between, but instead increment every letter and intersperse `a`'s. ``` aba -> bcb -> abacaba ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes (non-competitive) Code: ``` 'aIGDN>.bsJl ``` I'll be damned. I fixed a lot of bugs thanks to this challenge haha. Explanation: ``` 'aIGDN>.bsJl 'a # Push the character 'a' I # User input G # For N in range(1, input) D # Duplicate the stack N # Push N > # Increment .b # Convert to alphabetic character (1 = A, 2 = B, etc.) s # Swap the last two elements J # push ''.join(stack) l # Convert to lowercase # Implicit: print the last item of the stack ``` [Answer] # JavaScript (ES6), ~~43~~ 42 bytes ``` a=n=>n?a(--n)+(n+11).toString(36)+a(n):"a" ``` *A byte saved thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!* Yet another simple recursive solution... [Answer] # [jq](https://stedolan.github.io/jq/) `-r`, 43 bytes ``` def f:.-1|[[97]][.+1]//f+[.+98]+f;f|implode ``` [Try it online!](https://tio.run/##yyr8/z8lNU0hzUpP17AmOtrSPDY2Wk/bMFZfP00byLC0iNVOs06rycwtyMlPSf3/34DLkMuIy5jLhMuUy@xffkFJZn5e8X/dIgA "jq – Try It Online") --- With the capitalization pattern from the example outputs, 58 bytes: ``` def f:[[65]][.]//([.-1|f[]%32+96,.+66]|.+.)[:-1];f|implode ``` [Try it online!](https://tio.run/##BcFLDkAwEADQ/ZzCRkKqQ30mwVEms6MJQf2WPbvx3nqpTrNP/MBMnQijlGXGaF30LGlTm54KNEQS0WDOg3Uy@rjs5xamWbUCBzU00EIH9IXzXcLxqL1/ "jq – Try It Online") ``` def f: ... ; define a filter named f [[65]][.] base case, if the argument . is 0, return [65] // otherwise .-1|f call the filter recursively []%32+96 convert each codepoint to lower case ,.+66 append .+66 (. is now the filter argument -1) [ ... ] collect all codepoints in an array |.+. and repeat that array twice [:-1] remove the last integer f|implode call the filter on the input and convert the result to a string ``` [Answer] ## CJam (14 bytes) ``` 'aqi{'b+1$++}/ ``` [Online demo](http://cjam.aditsu.net/#code='aqi%7B'b%2B1%24%2B%2B%7D%2F&input=4) [Answer] # Ruby (1.9 and up), 38 bytes `?a` is a golfier way to write `"a"` but looks weird when mixed with ternary `?:` ``` a=->n{n<1??a:a[n-1]+(97+n).chr+a[n-1]} ``` [Answer] # [R](https://www.r-project.org/), 48 bytes ``` f=function(n)if(n)paste0(a<-f(n-1),letters[n],a) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jTzMzDUgUJBaXpBpoJNroAnm6hpo6OaklJalFxdF5sTqJmv/TNIw0udI0zDT/AwA "R – Try It Online") Simple recursion. [Answer] # [jq](https://stedolan.github.io/jq/), 51 bytes ``` [range(.)+97|[.]|implode]|reduce.[]as$i("a";.+$i+.) ``` [Try it online!](https://tio.run/##yyr8/z@6KDEvPVVDT1Pb0rwmWi@2JjO3ICc/JTW2pig1pTQ5VS86NrFYJVNDKVHJWk9bJVNbT/P/f1MA "jq – Try It Online") My life has improved significantly since I found `reduce` in this language. -16 bytes from ovs. [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), 31 bytes ``` _-)"(;; (. ? {_ @ +}989 1_ ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P8/XldTScPamktDT8FeQaE6nstBQUG71tLCkktBQcEw/v9/YwA "Labyrinth – Try It Online") I feel like this can be rearranged to be golfier, but a better layout eludes me. I also have a [cleaner 1-indexed version](https://tio.run/##y0lMqizKzCvJ@P9fwV5bScPamktPW0FJQaE6nkspXkGp1tLckstBQUFT6f9/EwA) which has a higher ratio of walls. This uses [xnor's method](https://codegolf.stackexchange.com/a/193729/76162) of repeatedly incrementing the string and interspersing with `a`s. [Answer] # C#, 59 bytes ``` string a(int n){return n<1?"a":a(n-1)+(char)(97+n)+a(n-1);} ``` Just another C# solution... [Answer] # Perl, 33 bytes ``` map$\.=chr(97+$_).$\,0..pop;print ``` No real need for un-golfing. Builds the string up by iteratively appending the next character in sequence plus the reverse of the string so far, using the ASCII value of 'a' as its starting point. Uses `$\` to save a few strokes, but that's about as tricky as it gets. Works for `a(0)` through `a(25)` and even beyond. Although you get into extended ASCII after `a(29)`, you'll run out of memory long before you run out of character codes: `a(25)` is ~64MiB. `a(29)` is ~1GiB. To store the result of `a(255)` (untested!), one would need 2^256 - 1 = 1.15x10^77 bytes, or roughly **1.15x10^65 1-terabyte drives.** [Answer] # [MATL](https://esolangs.org/wiki/MATL), 14 bytes ``` 0i:"t@whh]97+c ``` This uses [version 8.0.0](https://github.com/lmendo/MATL/releases) of the language/compiler, which is earlier than the challenge. ### Example ``` >> matl > 0i:"t@whh]97+c > > 3 abacabadabacaba ``` ### Explanation The secuence is created first with numbers `0`, `1`, `2`, ... These are converted to letters `'a'`, `'b'`, `'c'` at the end. ``` 0 % initiallize: a(0) i: % input "N" and create vector [1, 2, ... N] " % for each element of that vector t % duplicate current sequence @ % push new value of the sequence whh % build new sequence from two copies of old sequence and new value ] % end for 97+c % convert 0, 1, 2, ... to 'a', 'b', 'c'. Implicitly print ``` ### Edit [**Try it online!**](http://matl.tryitonline.net/#code=MGk6InRAd2hoXTk3K2M&input=Mw) [Answer] # Java 7, 158 bytes ``` class B{public static void main(String[]a){a('a',Byte.valueOf(a[0]));}static void a(char a,int c){if(c>=0){a(a,c-1);System.out.print((char)(a+c));a(a,c-1);}}} ``` I like to lurk around PPCG and I would enjoy being able to vote/comment on other answers. Input is given as program parameters. This follows the same format as many other answers here in that it's a straight forward recursive implementation. I would have commented on the other answer but I don't have the rep to comment yet. It's also slightly different in that the recursive call is done twice rather than building a string and passing it along. [Answer] # Mathematica, ~~36~~ 32 bytes ``` ##<>#&~Fold~Alphabet[][[;;#+1]]& ``` Have you ever watched TWOW 11B? [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` !¡S+oṠ:o→▲"a ``` [Try it online!](https://tio.run/##AR0A4v9odXNr//8hwqFTK2/huaA6b@KGkuKWsiJh////NA "Husk – Try It Online") Uses 1-based indexing, which I hope is OK. ## Explanation ``` ! ( !!) ¡ iterate( ) S <*> + (++) o ( ) Ṡ join$ . : (:) o . → succ ▲ maximum "a "a" (iterate((++)<*>(join$(:).succ.maximum))"a"!!) ``` [Answer] # Python, ~~62~~ ~~54~~ ~~46~~ 45 bytes I would like to think that this code can still be golfed down somehow. Edit: Bug fix thanks to Lynn. -1 byte thanks to squid. ``` a=lambda n:n and a(n-1)+chr(97+n)+a(n-1)or'a' ``` [Try it online!](https://tio.run/##Jcg9CoAwDAbQ3VNka0JxEAdR8DDR@hPQrxK6ePo6@Mb3vOXM6GvV@dJ7SUqYQIpEymg7ievpPA4REv/IHjTUPTsZGcgVx8aDTA09biisbCL1Aw) [Answer] # [Vim](https://www.vim.org), 35 bytes ``` :h<_ jjYZZpqqv|yPyl/<c-r>" xq{Dddl@-@qD ``` [Try it online!](https://tio.run/##K/v/3yrDJp4rKysyKqqgsLCspjKgMkffJlm3yE6Jq6Kw2iUlJcdB16HQ5f9/4/@6ZQA "V (vim) – Try It Online") ### Explanation The buffer starts with a single line containing the input integer. ``` :h<_ jjYZZp ``` [Yank the lowercase alphabet from the help file.](https://codegolf.stackexchange.com/a/97868/16766) Paste it on a new line below the integer, leaving the cursor on the first character of the second line. ``` qq ``` Start recording macro `q`. This will be our "loop." ``` v|y ``` Using visual mode, select everything from the current character to the beginning of the line, inclusive, and yank it. This leaves the cursor on the first character of the line. ``` P ``` Paste the yanked text to the left of the cursor. The cursor is now on the last of the pasted characters. ``` yl ``` Yank that character. ``` /<c-r>" x ``` Find the next occurrence of the just-yanked character. Delete it. ``` q ``` Stop recording the macro. Conveniently, this first time through the macro has left the alphabet unchanged. The only effect is that the cursor has moved from the `a` to the `b`. ``` {Dddl ``` Go to the beginning of the buffer. Delete the contents of the first line (the input number). Then delete the (now-empty) first line. Move the cursor one character to the right so as to start on `b`. ``` @-@q ``` Execute the macro *N* times, where *N* is the number we just deleted. ``` D ``` Delete the unused remainder of the alphabet. --- Normally, the `@-@q` idiom is fraught with peril if the number has a chance of being zero, because `0` is not a valid count in Vim; instead, it is treated as a separate command that move the cursor to the beginning of the line. However, in this particular case, an input of `0` is no problem at all: ``` @- ``` Move the cursor to the beginning of the line. ``` @q ``` Execute the macro once. Recall that executing the macro with the cursor on the `a` leaves the alphabet unchanged and the cursor on the `b`. ``` D ``` Delete everything to the end of the line--which leaves only the `a`, exactly the output we want. [Answer] # [Knight](https://github.com/knight-lang/knight-lang) (v2.0-alpha), 37 bytes ``` ;=q+96=n+1P;=x"";W=n-nT=x++xA-q n xOx ``` [Try it online!](https://knight-lang.netlify.app/v2#WyI7PXErOTY9bisxUDs9eFwiXCI7Vz1uLW5UPXgrK3hBLXEgbiB4T3giLCIzIl0=) Expanded ``` ; = q (+ 96 (= n (+ 1 PROMPT))) ; = x "" ; WHILE (= n (- n TRUE)) = x (+ (+ x (ASCII (- q n))) x) : OUTPUT x ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `J`, 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Oėıf2c;⁺Ä ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0kpdS7IKlpSVpuhbr_I9MP7IxzSjZ-lHjrsMtS4qTkouhUgsWmkAYAA) Port of emanresu A's Vyxal answer. #### Explanation ``` Oėıf2c;⁺Ä # Implicit input O # Push 2 ** input ė # Push [1..that) ı ; # Map: f # Prime factors 2c # Count 2s ⁺Ä # Letter of alphabet # Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 61 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.625 bytes ``` ¤$(nøAȮW∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiwqQkKG7DuEHIrlfiiJEiLCIiLCI1Il0=) Uses 1-indexing. ## Explained Generated using Luminespire ``` ¤$(nøAȮW∑ ¤$ # Push an empty string under the input ( # For each n in the range [1, input]: nøA # Get the nth letter of the alphabet Ȯ # Push a copy of the item under the top of the stack. This leaves the stack as [already generated, new letter, already generated] W∑ # Wrap and sum the stack ``` [Answer] # Mathematica, 46 bytes ``` If[#<1,"a",(a=#0[#-1])<>Alphabet[][[#+1]]<>a]& ``` Simple recursive function. Another solution: ``` a@0="a";a@n_:=(b=a[n-1])<>Alphabet[][[n+1]]<>b ``` [Answer] # K5, 18 bytes ``` "A"{x,y,x}/`c$66+! ``` Repeatedly apply a function to a carried value (`"A"`) and each element of a sequence. The sequence is the alphabetic characters from B up to some number N (``c$66+!`). The function joins the left argument on either side of the right argument (`{x,y,x}`). In action: ``` ("A"{x,y,x}/`c$66+!)'!6 ("A" "ABA" "ABACABA" "ABACABADABACABA" "ABACABADABACABAEABACABADABACABA" "ABACABADABACABAEABACABADABACABAFABACABADABACABAEABACABADABACABA") ``` [Answer] ## JavaScript, ~~65~~ 571 bytes ``` n=>eval('s="a";for(i=0;i<n;i++)s+=(i+11).toString(36)+s') ``` Demo: ``` function a(n){ return eval('s="a";for(i=0;i<n;i++)s+=(i+11).toString(36)+s') } alert(a(3)) ``` 1 - thanks Neil for saving 8 bytes [Answer] # Japt, ~~20~~ 17 bytes ``` 97oU+98 r@X+Yd +X ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=OTdvVSs5OCByQFgrWWQgK1g=&input=Mw==) ### How it works ``` // Implicit: U = input integer 65oU+66 // Generate a range from 65 to U+66. r@ // Reduce each item Y and previous value X in this range with this function: X+Yd // return X, plus the character with char code Y, +X // plus X. // Implicit: output last expression ``` ## Non-competing version, 14 bytes ``` 97ôU r@X+Yd +X ``` The `ô` function is like `o`, but creates the range `[X..X+Y]` instead of `[X..Y)`. [Test it online!](http://ethproductions.github.io/japt?v=master&code=OTf0VSByQFgrWWQgK1g=&input=Mw==) I much prefer changing the 97 to 94, in which case the output for `5` looks like so: ``` ^_^`^_^a^_^`^_^b^_^`^_^a^_^`^_^c^_^`^_^a^_^`^_^b^_^`^_^a^_^`^_^ ``` ]
[Question] [ # Twisting Words! Given a string and a positive integer. You must twist the string, back and forth. ### Example Input / Output Input ``` Programming Puzzles & Code Golf 4 ``` Output ``` Prog mmar ing zzuP les oC & de G flo ``` ## Input The input can be taken in through STDIN, or function argument. The input will consist of a string and a positive integer, *n*. The integer will determine the length of each twisted line. The string is twisted back-and-forth. An input of `HELLO, WORLD!` and 5 would look like: ![HELLO, WORLD!](https://i.stack.imgur.com/6K9vq.png) ## Output The output will be the twisted text. It may not any trailing whitespace. If the input string length is not divisible be the line length, add a space until the line is filled: An example of this: Input ``` Hello, World! 5 ``` Output (Note the whitespace at the very end) ``` Hello roW , ld! ``` [Answer] # Pyth, ~~19~~ 15 ``` VPc+z*dQQ_W~!ZN ``` Pre-pads the string, then reverses each other line as it prints it. The padding is equal to the size of the box, but the last line after chopping up the input is discarded. [Try it here](https://pyth.herokuapp.com/?code=VPc%2Bz*dQQ_W%7E!ZN&input=Programming+Puzzles+%26+Code+Gol%0A4&debug=0) [Answer] ## Python 2, 60 ``` s,n=input() d=1 while s:print(s+n*' ')[:n][::d];s=s[n:];d=-d ``` Takes `n` characters at a time from the from of `s`, printing them with a direction `d` that alternates between `1` and `-1`. For spacing on the last line, `s` is padded with `n` spaces at the end before it is chopped, which only affects it when it has fewer than `n` characters remaining. A recursive solution would save a char (59) except that it leaves a trailing newline, which is not allowed. ``` f=lambda s,n,d=1:s and(s+n*' ')[:n][::d]+"\n"+f(s[n:],n,-d) ``` [Answer] # CJam, 19 bytes ``` q~1$S*+/W<{(N@Wf%}h ``` Input example: ``` 5 "Hello, World!" ``` ### Explanations ``` q~ e# Input n and the string. 1$S*+ e# Append n spaces to the string. /W< e# Split by each n characters, and remove the last chunk. { e# While the array of chunks isn't empty: (N e# Extract the first chunk and push a newline. @Wf% e# Reverse every chunk left in the array. }h ``` [Answer] ## [Snowman 1.0.1](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.1-beta), 91 bytes ``` {vg10vg|sB*#.'aGal'NdE'aaAaL|al!*+#5nS" "'aR'!#aCwR|.aC2aG:0aa|sP" "sP'NdE|1aA.aNsP" "sP;aE ``` Or all on one line (for aesthetics, or more specifically, anti-aesthetics), at the cost of 2 bytes: ``` {vg10vg|sB*#.'aGal'NdE'aaAaL|al!*+#5nS" "'aR'!#aCwR|.aC2aG:0aa|sP10wRsP'NdE|1aA.aNsP10wRsP;aE ``` This is way too short, for Snowman. (It's probably the shortest it can get, though; I worked on golfing this for a pretty long time.) This has one caveat: it will exit with an error (but still produce the correct output) 50% of the time, when the last line is *not* reversed. (This is because I use `ag` to group the array elements in groups of two so that I can reverse every other one, but I don't check whether the last element has both expected elements, so it'll try to access a nonexistent element if there are an odd number of lines.) Ungolfed / explanation: ``` {vg10vg|sB*# // get input, convert second string to number and store .'aG // split string into groups of n chars al'NdE'aaAaL // take out the last element of the array |al!*+#5nS" "'aR // subtract its length from 5, repeat that many spaces '!#aCwR|.aC // concat spaces to last el. and that back to the array 2aG // split in groups of 2, so we can reverse every other string // for each sub-group in the array of groups... : 0aa|sP10wRsP // print the first element as is 'NdE|1aA.aNsP10wRsP // print the second element, reversed ;aE ``` [Answer] # [Haskell](https://www.haskell.org/), ~~83~~ 75 bytes ``` (id!) (f![])_=[] (f!l)n=f(take n$l++cycle" ")++'\n':((f.reverse)!drop n l)n ``` Simple `chunksOf` implementation with take and drop, applying an even or odd number of reverses to the output as we go. Thanks to @BMO for five bytes and @ØrjanJohansen for three bytes! [Try it online!](https://tio.run/##FcuxCsIwEADQ3a@4hmITgk5OQiYH14JjWySkl1p6TUISBfvxRt3e8h46LUhUsuoLn8dK7LitukHcVTf8ScIpy7NeEFxNUpq3IWTAhJRN75oz5/YY8YUxoajG6AM4@J2y6tmBgvDMtxyhhgysjX6Kel1nN0H73DbCBHu4@BHh6skyOJWPsaSnVA4mhC8 "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 15 13 bytes ``` ]`|."1@(]\)~- ``` *-2 bytes thanks to xash* Note the above solution requires J901, which allows you to apply cyclic gerunds using the rank `"` conjuntion. TIO uses an older version, so to run this one you have to download J. However, my previous solution of 15 bytes will work on TIO: ## 15 bytes ``` ([]`|.\[:,]\)~- ``` [Try it online!](https://tio.run/##VcxBC4IwGIDhu7/iQ8lt4b4SOo2SkVCXCOk6F0apGdrA6GKyv76CunR4Tw@8N@cjqWAlgEAEcxCfOEJ62G0cVboYMVci0jmz3DFvv0agSugwKeiIYcJmuPRjJqnOLf9xgzIYUeqjUP4cYv2nXH6f@oVWTWmCcmID5nnl@WqAZL2p@1PXNfcasucwtOUDQkjNpYStaSsCFSzcGw "J – Try It Online") Finally, another 15 byte alternative, thanks to @Marshall and based on a trick from @ngn, is: ``` ([:|.@]/\]\)~- ``` [Answer] # [Stuck](http://kade-robertson.github.io/stuck/), ~~42~~ ~~41~~ ~~40~~ 38 Bytes This is a wee bit too long, probably will try to golf more! ``` tg;_lu_@%u;-_0G<*' *+0GKE"];2%;Y_Y?p": ``` Input should be like `"string"|n`. Explanation: ``` tg # Take input, place each item on stack, save the int to variable stack ;_l # Swap the top two items, duplicate the string and obtain length u_@% # Rotate to the left, duplicate, rotate right and take mod u;- # Rotate left, swap the top two and subtract from each other _0G<* # duplicate this value, check if less than stored int and multiply ' *+ # Push space onto stack n times, append to starting string 0GKE # Split this string into segments, and enumerate "];2%;Y_Y?p": # For each segment, determine if should be reversed, and print ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes ``` {↑⊢∘⌽\↓↑⍵⊆⍨⌈⍺÷⍨⍳≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/FR24TqR20TH3UtetQx41HP3phHbZNB/N6tj7raHvWueNTT8ah31@HtIGbv5kedi4Aytf//mygkKqgHFOWnFyXm5mbmpSsElFZV5aQWK6gpOOenpCq45@ekqXOZglR5pObk5OsohOcX5aQoqgMA "APL (Dyalog Unicode) – Try It Online") Took the `⊢∘⌽\` trick from [ngn's brilliant answer to the boustrophedonise challenge](https://codegolf.stackexchange.com/a/150153/41805). After realising that my submission breaks for lines with leading newlines, I have added two more bytes. Below is the older submission. # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes ``` {↑⊢∘⌽\⍵⊆⍨⌈⍺÷⍨⍳≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/FR24TqR20TH3UtetQx41HP3phHvVsfdbU96l3xqKfjUe@uw9tBzN7NjzoXAWVq//83VUhUUPdIzcnJ11EIzy/KSVFUBwA "APL (Dyalog Unicode) – Try It Online") [Answer] # Perl, 87 bytes ``` sub f{$_=@_[0].$"x(@_[1]-1);$a.=(($i++&1?reverse$1:$1).$/)while/(.{@_[1]})/g;chop$a;$a} ``` Old version (prints a trailing newline): ``` sub f{$_=@_[0].$"x(@_[1]-1);print(($i++&1?reverse$1:$1).$/)while/(.{@_[1]})/g} ``` String is passed as a function argument with no trailing newline. Call like this: ``` $_=<>;chomp;print f($_,5); ``` [Answer] ## Mumps, 86 bytes ``` R I,S,! S P=$L(I),$P(I," ",P)=P F Q=1:S:P S F=$E(I,Q,Q+S-1),P='P W $S('P:F,1:$RE(F)),! ``` Although it could be 2 bytes shorter if you remove the first ',!' characters in the R statement (read from STDIN); that adds a carriage return between the input and output. If that wasn't there, the output is technically correct, but the first line would appear appended to the input string. *[[ The standard Mumps terminal that I use has no local echo. ]]*   As it sits, here's the test: ``` R I,S,! S P=$L(I),$P(I," ",P)=P F Q=1:S:P S F=$E(I,Q,Q+S-1),P='P W $S('P:F,1:$RE(F)),! ABCDEFGHIJKLMNOPQRSTUVWXYZ1236 ABCDEF LKJIHG MNOPQR XWVUTS YZ123 ``` Also note, there's actually a carriage return / Enter keypress between the '123' and the '6' at the end of the input. *[[ The local echo thing again. ]]* If anyone's interested I can describe what's going on with the code; but I do realize there's not a ton of Mumps enthusiasts out there... :-) [Answer] ## PowerShell, 102 Bytes ``` param($s,$i)$l=$s.Length;$s+' '*($i%$l)-split"(.{$i})"|?{$_}|%{$r=-not$r;@($_,($_[$l..0]-join''))[$r]} ``` Invoked as follows (if saved to file `CodeGolf55051.ps1`) ``` .\CodeGolf55051.ps1 -s '1234567890' -i 4 ``` --- ## Previous Attempts (longer or invalid) **PowerShell, 110 Bytes** ``` param($s,$i)$l=$s.Length;$s+' '*(($i-$l%$i)%$i)-split"(.{$i})"|?{$_}|%{$r=-not$r;@($_,($_[$l..0]-join''))[$r]} ``` **PowerShell, 111 Bytes** ``` param($s,$i)$s+' '*(($i-$s.Length%$i)%$i)-split"(.{$i})"|?{$_}|%{$r=-not$r;@($_,($_[$_.length..0]-join''))[$r]} ``` **Explanation** ``` param($s,$i) #Take input text (s) and column width (i) $s #take the user entered string + ' ' * (($i - $s.Length % $i) % $i) #add the least number of spaces required to make its length divisible by i -split"(.{$i})" #break it into chunks of i characters in length | ?{$_} #skip any blank lines created in the process | %{ #for each line $r = -not $r; # toggle a boolean value @( # define an array $_ # index 0 = the string going forwards ,($_[$_.length..0] -join '') # index 1 = the string reversed (by taking each character from the last to the first, then joining them) )[$r] # if our boolean value is false take the forward string (index 0), if true take the backwards one (index 1) } #next ``` **PowerShell, 180 Bytes** ``` param($s,$i)$x="`${0}|{1}|`${2}";$w=$x;1..$i|%{$w=$w-f$_,$x,($i+$_)};$w=$w-replace'\||\${.*}';$r=$w-replace'\$\d+','(.)?';$s+' '*($i-$s.Length%$i)-replace$r,$w-split"(.{$i})"|?{$_} ``` **PowerShell, 196 Bytes** ``` param($s,$i)$x="{0}|{1}|{2}";$w=$x;1..$i|%{$w=$w-f$_,$x,($i+$_)};$w=$w-replace'(\d+)','$$$1'-replace'\||{.*}';$r=$w-replace'\$\d+','(.)?';$s+' '*($i-$s.Length%$i)-replace$r,$w-split"(.{$i})"|?{$_} ``` **Explanation** ``` param ($s, $i) #Take input text (s) and column width (i) $x = "{0}|{1}|{2}" #Define string format which takes 3 entries and pipe delimits them $w = $x #initialise our replacement regex with this format 1..$i | %{ #for 1 to the specified column width $w = $w -f $_, $x, ($i + $_) #update the regex 1|{...}|5, 1|2|{...}|6|5, etc } #resulting in w = 1|2|3|4|{...}|8|7|6|5 $w = $w -replace '(\d+)', '$$$1' #now prefix the numbers with a dollar (so they're regex replacement variables) -replace '\||{.*}' #and remove the delimiters and superfluous `{...}` left from our middle insertion routine $r = $w -replace '\$\d+', '(.)?' #then create the match pattern by replacing the variables with optional single character captures $s #now take the user entered string + ' ' * ($i - $s.Length % $i) #add the least number of spaces required to make its length divisible by i -replace $r, $w #perform a replacement using the regex match and replace patterns created above -split "(.{$i})" #then split the string into blocks of length i | ?{$_} #removing any blank lines created in the process ``` (`{...}` in the above comments is actually `{0}|{1}|{2}`; I put `{...}` for improved readability. **Powershell, 120 Bytes** (invalid) ``` param($s,$i)$s + ' ' * ($i-$s.Length%$i) -replace '(.{4})?(.)(.)(.)(.)',"`$1`n`$5`$4`$3`$2`n" -split "`n" | ?{$_ -ne ""} ``` [Answer] ## [Perl 5](https://www.perl.org/), 51 bytes ``` $_.=$"x(($-=<>)-1);say--$|?$_:~~reverse for/.{$-}/g ``` [Try it online!](https://tio.run/##BcHBCoJAEADQu1@xxRIKzaqQF8s6dKhL4K2jCI4ijDsyW1FWfnrbeyMKZd7ryhR6@QxDDcVuH0EabV39AtCfg67yeRZ8oDhULUts3hq@ced9KdxJPQy97VR5nyZCp1bqyA2qE1MbbIIzEvFaXVmoWQTZj8dbz9Z5sOThkpkkTf4 "Perl 5 – Try It Online") [Answer] ## Clojure, 83 bytes, 87 bytes, 79 bytes ``` (fn[n s](map #(apply str(% %2))(cycle[#(or %)reverse])(partition n n(repeat\ )s)))) ``` several corrections after comments below, thank you [Ørjan](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen). [Try it online!](https://tio.run/##LY3LTsMwEEX3@YpLqiBbgg2CL2ABy@5YpF1YzqSYjh@MnUrtzwe7YWZ3z9wzluPPIrSuaqIZvgPUHMaAfFTeJOyUSYmvyEXUgOFFa2WvlmncqSgYtNCFJNNRq2SkuOJiQF0llMiUA3TWdbqu2QPsN9kz7vb2iKlgFMoLFyhfe1m3vJIpZvrFyC4QtoMNVJQkoOX/3k35in4v8STGexdO2C@3G1PGI97jRPiIPPe6q1UXCgf0z/dp0VZ/Q/9JzPEJX1F4eqhkXf8A) Clojure seems often sadly absent from code golfing answers. It certainly can not compete in byte length with golfing languages, but I think the total absence is somewhat unwarranted. Explanation: * in-data, two arguments a number and a string * start by running clojure built-in function [partition](https://clojuredocs.org/clojure.core/partition) on string `s` chunking it into a sequence of lists of characters where the lists have length `n`. The last chunk will be padded with spaces to length `n` using the "pad collection" returned from `(repeat " ")` which returns an infinite lazy sequence of spaces * we then call [map](https://clojuredocs.org/clojure.core/map) with three arguments: + an anonymous function (the `#(..)`) + an infinite alternating lazy sequence of functions `#(or %)` which functions like the [identity](https://clojuredocs.org/clojure.core/identity) function and [reverse](https://clojuredocs.org/clojure.core/reverse) (i.e. `[#(or %) reverse #(or %) reverse ...]`) as returned by [cycle](https://clojuredocs.org/clojure.core/cycle). + the chunked up lazy sequence of lists returned by partition. * finally the [anonymous function](https://clojure.org/guides/learn/functions#_anonymous_function_syntax) `#(apply ...)`: + calls either `identity` or `reverse` alternatingly on a chunk. This is done via the `(% %2)` expression which calls the function sent in as the first argument to the anonymous function [i.e. `identity` or `reverse`] using the second argument [i.e. the chunk] to the anonymous function as the argument to the call. + calls `(apply str ...)` to convert the list of characters into a string * the outer function returns a lazy sequence of strings one trick we use here is that a lot of clojure functions like `map` take an arbitrary number of collections as args, i.e. `(map f coll1 coll2 coll3 ...)` where the function f just needs to accept as many arguments as there are collections. In this case we send in two collections, a collection of alternating function references and the chunked up string. [Answer] # Python 3, ~~110~~ ~~108~~ ~~107~~ 103 bytes ``` def a(s,n):l=len(s)//n+1;s+=' '*(len(s)-l);print('\n'.join([s[x*n:n*x+n][::(-1)**x]for x in range(l)])) ``` (looking at other answers), with `rjust`: ~~95~~ ~~93~~ ~~92~~ 90 bytes ``` def a(s,n):print('\n'.join([s[x*n:n*x+n][::(-1)**x].rjust(n)for x in range(len(s)//n+1)])) ``` [Answer] # Haskell, 108 bytes ``` (#)=splitAt s!n=let(a,t)=n#s;(b,u)=n#t in a:reverse b:(u!n) s%n=unlines$takeWhile(any(>' '))$(s++cycle" ")!n ``` That's sort of long, jeez. Here it is in action: ``` *Main> putStrLn $ "Programming Puzzles & Code Golf" % 4 Prog mmar ing zzuP les oC & de G flo ``` [Answer] # Python 2, 109 bytes Had to add padding with spaces for the last line to be correct. [**Try it here**](http://ideone.com/54nKxW) ``` I,c=input() I+=(c-len(I)%c)*" " L=[] i=0 while I:s=I[:c];L+=[[s,s[::-1]][i%2]];i+=1;I=I[c:] print"\n".join(L) ``` [Answer] # Lua, ~~91~~ ~~88~~ ~~88~~ ~~84~~ ~~83~~ 82 bytes Old version: ``` a=arg for i=1,#a[1],a[2]do s=a[1]:sub(i,i+a[2]-1)print(d and s:reverse()or s)d=not d end ``` New version: ``` arg[1]:gsub((".?"):rep(arg[2]),function(s)print(d and s:reverse()or s)d=not d end) ``` [Answer] # O, 60 bytes ``` z""/rlJ(Q/{n:x;Q({+}dxe{`}{}?p}drQJQ%-{' }dJQ/e{r}{}?Q({o}dp ``` My very first O program, and a long one at that! [Live demo.](http://o-lang.herokuapp.com/link/code=z%22%22%2FrlJ(Q%2F%7Bn%3Ax%3BQ(%7B%2B%7Ddxe%7B%60%7D%7B%7D%3Fp%7DdrQJQ%25-%7B%27+%7DdJQ%2Fe%7Br%7D%7B%7D%3FQ(%7Bo%7Ddp&input=Programming+Puzzles+%26+Code+Golf%0A4) [Answer] # Q, ~~64~~ 56 bytes ``` {c::neg y;-1(til(#)l){$[x mod 2;c$(|:)y;y]}'l:y cut x;} ``` * `{}` is a function that should be called as `{}[x;y]`. + `x` will be the string. + `y` will be the length of the resulting lines. Test: ``` {c::neg y;-1(til(#)l){$[x mod 2;c$(|:)y;y]}'l:y cut x;}["Programming Puzzles & Code Golf";4] Prog mmar ing zzuP les oC & de G flo ``` **edit**: Used shorter functions as inspired by the other [q answer by @tmartin](https://codegolf.stackexchange.com/a/55119/21697) [Answer] # Python 2, 82 75 bytes ``` s,n=input() k=0 while k<=len(s):print s[k:k+n].ljust(n)[::1-2*(k/n%2)];k+=n ``` I couldn't comment on @willem but I made his code smaller. [Try here](http://ideone.com/jpDwEF) [Try here](http://ideone.com/Qu5l6r) [Answer] # Perl, 72 bytes ``` perl -p0e's/\n(.*)/$"x($1-$-[0]%$1)/e;s/.{$1}/($i++%2?reverse$&:$&)."\n"/ge;chop' ``` 70 bytes, plus 2 bytes for `-p0`. Demo: ``` $ echo -en 'Hello, World!\n5' | perl -p0e's/\n(.*)/$"x($1-$-[0]%$1)/e;s/.{$1}/($i++%2?reverse$&:$&)."\n"/ge;chop' Hello roW , ld! $ ``` Note that the input read from STDIN cannot end with a newline (that would cost 2 extra bytes). Explanation: ``` perl -p0e' # Read from STDIN, splitting on null bytes, # and print $_ automatically at the end s/ \n(.*) # Replace everything after first newline, # capturing wrap length in $1... / $"x($1-$-[0]%$1) # ...with spaces until the total length of $_ is # a multiple of $1 (i.e. right-pad with spaces) /e; s/ .{$1} # Replace series of $1 contiguous chars... / ($i++%2?reverse$&:$&)."\n" # ...alternately with themselves or in # reverse, with a trailing newline /ge; chop' # Remove final newline ``` [Answer] # JavaScript ES6, 123 bytes ``` var t=(s,n)=>{for(var d=1,i=0,o='',l=s.length;i<l;i++){o+=d?s[i]:s[i-i%n+n-1-i%n]||' ';if(i%n==n-1){d=!d;o+='\n'}}return o} ``` Call with `t(input_string, twist_length)`, which returns the output string. [Answer] # Python 3, 64 bytes [Try Online](https://tio.run/##BcGxCsMgEADQvV9xZCgKtlCyXXDqkDW7OAgxicWcwTPU5ufte8evbIn61ma/gBOsSFX9kniD7xaiB8YjByqCDZJ95s/JRZA0iNXKgTUbQjtU/ajNiW7Kac1u3wOtMJ3XFT3DHd5p9jCmuHQKetnaHw) ``` def a(s,n,x=1): while s:print(s[:n].rjust(n)[::x]);s=s[n:];x=-x a('Programming Puzzles & Code Golf',4) ``` Step 1: Print the first n bytes of the string (flag = 1 so normal order) Step 2: Trim the string by n bytes Step 3: Flip the flag to -1 Repeat the process until string is empty Note that flag flips to +1 and -1. When it goes to -1, it prints in reverse order [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` òV ËzEÑÃù ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=8lYgy3pF0cP5&input=IlByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYiCjQ) [Answer] ## PHP, 135 bytes Takes two command-line arguments as shown with `$argv`. ``` <? foreach($a=str_split($s=$argv[1],$n=$argv[2])as$k=>&$v)$v=$k%2?$v:strrev($v);echo implode("\n",$a).str_repeat(' ',$n-strlen($s)%$n); ``` [Answer] ## CoffeeScript, 131 bytes This seems too long. ``` f=(s,n,r=l=s.length,i=0,z='')->(t=s[i...i+=n].split '';t=t.reverse()if r=!r;z+=t.join('')+(i<l&&'\n'||' '.repeat n-l%n))while i<l;z ``` [Answer] # Julia, 104 bytes ``` f(s,n)=(L=length(s);L+=L÷n;j=0;for i=1:n:L-n+1 x=rpad(s,L)[i:i+n-1];println(j%2<1?x:reverse(x));j+=1end) ``` Ungolfed: ``` function f(s::String, n::Int) L = length(s) + length(s) ÷ n j = 0 for i = 1:n:L-n+1 x = rpad(s, L)[i:i+n-1] println(j % 2 == 0 ? x : reverse(x)) j += 1 end end ``` [Answer] # Python 3, 101 bytes ``` t,x=eval(input()) print("\n".join([t[c:c+x].ljust(x)[::1-2*(int(c/x)%2)] for c in range(0,len(t),x)])) ``` [Try it here](http://ideone.com/6Oxrqj "Try it here") [Answer] # q, 46 ``` {-1@neg[y]$@[a;(&)(til(#)a:y cut x)mod 2;|:];} ``` . ``` q){-1@neg[y]$@[a;(&)(til(#)a:y cut x)mod 2;|:];}["Programming Puzzles & Code Golf";4] Prog mmar ing zzuP les oC & de G flo ``` [Answer] # Coffeescript, 151 bytes ``` f=(s,n)->r="";d=n;i=0;_="\n";u=" ";l=s.length;(d--and(r+=s[i]or u;++i)or(r+=_;r+=s[c]or u for c in[i+n-1..i];i+=d=n;r+=_ if i<l))while i<(l/n+1>>0)*n;r ``` Too much =( ]
[Question] [ Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor. Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better. ## Test cases ``` [] -> False [1] -> False [1,2] -> False [1,2,1] -> True [1,2,2] -> False [1,2,3] -> False [1,2,2,1] -> False [1,2,2,3] -> False [1,2,1,2] -> True [1,3,2] -> True [3,1,2] -> True [2,2,2] -> False ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` IṠIỊẠ ``` Returns **0** if there's a bump, **1** if not. [Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fng93dz3cteD/4fZHTWsi//@PjtVRiDYEEzpGUEoHxkeIGMNFkCQRonC9xhCGkY4BUB0A "Jelly – Try It Online") ### How it works ``` IṠIỊẠ Main link. Argument: A (integer array) I Increments; take all forward differences of A. Ṡ Take the signs. The signs indicate whether the array is increasing (1), decreasing (-1), or constant at the corresponding point. A 1 followed by a -1 indicates a local maximum, a -1 followed by a 1 a local minimum. I Increments; take the forward differences again. Note that 1 - (-1) = 2 and (-1) - 1 = -2. All other seven combinations of signs map to -1, 0, or 1. Ị Insignificant; map each difference d to (-1 ≤ d ≤ 1). Ạ All; return 1 if all differences are insignificant, 0 if not. ``` [Answer] # JavaScript (ES6), 38 bytes Returns a boolean. ``` a=>a.some(x=n=>x*(x=a<n|-(a>(a=n)))<0) ``` ### Test cases ``` let f = a=>a.some(x=n=>x*(x=a<n|-(a>(a=n)))<0) console.log(f([])) // False console.log(f([1])) // False console.log(f([1,2])) // False console.log(f([1,2,1])) // True console.log(f([1,2,2])) // False console.log(f([1,2,3])) // False console.log(f([1,2,2,1])) // False console.log(f([1,2,2,3])) // False console.log(f([1,2,1,2])) // True console.log(f([1,3,2])) // True console.log(f([2,0,1])) // True console.log(f([2,2,2])) // False console.log(f([-4,100000,89])) // True ``` ### How? We use **a** to store the previous value of **n**. We set **x** to **1** if **a < n**, **-1** if **a > n** or **0** if **a = n**. And we test whether **old\_x \* x < 0**, which is only possible if (**old\_x = 1** and **x = -1**) or (**old\_x = -1** and **x = 1**). Because **x** is initialized to the anonymous callback function of **some()**, it is coerced to **NaN** during the first iteration, which makes the test falsy. [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` any(<0).f(*).f(-) f a b=zipWith a b$tail b ``` [Try it online!](https://tio.run/##y0gszk7NyfmfbhvzPzGvUsPGQFMvTUMLROhqcqUpJCok2VZlFoRnlmSA2ColiZk5Ckn/cxMz82wLijLzSlRyEwsU0qOjY3WiDUFYxwhC6kB5cL4xjI@QgYvBdBmDaSMdA6Ca2P//ktNyEtOL/@smFxQAAA "Haskell – Try It Online") ## Explanation First we have the function `f` that takes a binary function and a list and applies the binary function to every adjacent pair in the list. Then our main function applies `f(-)` to the input list. This calculates the difference list. We then apply `f(*)` to the list to multiply every adjacent pair. Lastly we ask if any pair is less than zero. A number in the end list can only be negative if it is the product of a negative and positive number from the difference list. Thus in order to produce a negative entry (and then return true) the original list must switch from increasing to decreasing or vice versa, that is it must have a bump. [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` f=lambda x,y,z,*t:0>(y-x)*(z-y)or f(y,z,*t) ``` Returns *True* if there's a bump, errors if there isn't. ([allowed by default](https://codegolf.meta.stackexchange.com/a/11908/12012)) [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoUKnUqdKR6vEysBOo1K3QlNLo0q3UjO/SCFNAyKh@T8NyCtRyMxTiI7VUYg2BBM6RlBKB8ZHiBjDRZAkEaJwvcYQhjFMxAhsiBUXZ0lRJZDkLCjKzCsBugPoBi7O1Irk1IIShZDKglTXoqL8IoQCt8Sc4tT/AA "Python 2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/) with Image Package, ~~34~~ 32 bytes *2 bytes saved thanks to [@StewieGriffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin)!* ``` @(x)0||prod(im2col(diff(x),2))<0 ``` [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0LToKamoCg/RSMz1yg5P0cjJTMtDSiqY6SpaWPwP00jOlaTC0gaQilrIzjDGiGGLGqMJIqiBFkGyRxjGNMYIWoEMfI/AA "Octave – Try It Online") ### Explanation Computes consecutive differences, arranges them in sliding blocks of length 2, obtains the product of each block, and tests if any such product is negative. [Answer] # [Perl 6](http://perl6.org/), 39 bytes ``` {so~(.[1..*]Zcmp$_)~~/'re L'|'s M'/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uji/TkMv2lBPTys2Kjm3QCVes65OX70oVcFHvUa9WMFXXb/2f3FipYKSSryCrZ1CdZqCSnytkkJafpFCdKyOgo2hHYhQMIJSCjA@QsQYLoIkiRCF6zWGMIwUDIDq/gMA "Perl 6 – Try It Online") `$_` is the list argument to this anonymous function. `.[1..*]` is the same list, but with the first element dropped. `Zcmp` zips the two lists together with the `cmp` operator, resulting in a list of `Order` values. For example, for an input list `1, 2, 2, 2, 1` this would result in the list `More, Same, Same, Less`. Now we just need to know whether that list contains two adjacent elements `More, Less` or `Less, More`. The trick I used is to convert the list to a space-delimited string with `~`, then test whether it contains either substring `re L` or `s M`. (The first one can't be just `e L` because `Same` also ends with an "e".) The smart match operator returns either a `Match` object (if the match succeeded) or `Nil` (if it didn't), so `so` converts whatever it is into a boolean value. [Answer] # R, 48 bytes ``` function(x)any(apply(embed(diff(x),2),1,prod)<0) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMxr1IjsaAgp1IjNTcpNUUjJTMtDSisY6SpY6hTUJSfomljoPk/TSNZw1DHCCiqyQVjG8LZhkhsIxQZIBtJjwmQZ6Kp@R8A "R – Try It Online") How it works step-by-step using c(1,4,1,4) as example: ``` > x=c(1,4,1,4) > diff(x) [1] 3 -3 3 > embed(diff(x),2) [,1] [,2] [1,] -3 3 [2,] 3 -3 > apply(embed(diff(x),2),1,prod) [1] -9 -9 > any(apply(embed(diff(x),2),1,prod)<0) [1] TRUE ``` As a bonus, here is a solution of similar length and concept using package `zoo`: ``` function(x)any(zoo::rollapply(diff(x),2,prod)<0) ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` f(p:r@(c:n:_))=(c-p)*(c-n)>0||f r ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02jwKrIQSPZKs8qXlPTViNZt0BTC0jmadoZ1NSkKRT9z03MzFOwVSgoyswrUVBRSFOINtRRMNJRMAaThrH/AQ "Haskell – Try It Online") `True` if there's a bump, errors if there's not. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` MatchQ[{___,x_,y_,z_,___}/;x<y>z||x>y<z] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983sSQ5IzC6Oj4@XqciXqcyXqcqXgfIqdW3rrCptKuqqamwq7Spiv0fUJSZVxKtrKOgpKBrp6Cko5AWrRwbq6CmoO@gUF1dq6NQbQgmdBSMYLSOgiGCiSRqjCSKqgZFDskoYyjTGCFqBDW19j8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~55~~ 46 bytes ``` ->a{a.each_cons(3).any?{|x,y,z|(y-x)*(y-z)>0}} ``` [Try it online!](https://tio.run/##TY5LDoMwDET3OYWXpDKoJGvoQVBUJaiIDR81RSIkOXvKp6FsrPHzjO33pExoipCW0srsJev2WQ@9TjjNZG8e1s1ocHGJSWd6W@tCy7v3QU3daKCAigBUOTLMBZ4SWWx4lHynRBCiu2H4tDH6M57h/5aL5Bd6PXRO2O7fto@wf5Z1crROOWgqJfxKj6sH1hvWwocv) A lambda accepting an array and returning boolean. -9 bytes: Replace `(x<y&&y>z)||(x>y&&y<z)` with `(y-x)*(y-z)>0` (thanks to [GolfWolf](https://codegolf.stackexchange.com/users/3527/golfwolf)) ``` ->a{ a.each_cons(3) # Take each consecutive triplet .any?{ |x,y,z| # Destructure to x, y, z (y-x)*(y-z) > 0 # Check if y is a bump } } ``` [Answer] # PostgreSQL 173 bytes ``` SELECT DISTINCT ON(a)a,x>j and x>k OR x<least(j,k)FROM(SELECT a,x,lag(x,1,x)OVER(w)j,lead(x,1,x)OVER(w)k FROM d WINDOW w AS(PARTITION BY rn ORDER BY xn))d ORDER BY 1,2 DESC; a | c -----------+--- {1} | f {1,2} | f {1,2,1} | t {1,2,1,2} | t {1,2,2} | f {1,2,2,1} | f {1,2,2,3} | f {1,2,3} | f {1,3,2} | t {2,2,2} | f {3,1,2} | t (11 rows) ``` [Answer] # Java 8, ~~108~~ ~~104~~ ~~101~~ ~~86~~ ~~84~~ ~~79~~ 72 bytes ``` a->{int i=a.length,p=0;for(;i-->1;)i|=p*(p=a[i]-a[i-1])>>-1;return-i>1;} ``` -2 bytes thanks to *@OlivierGrégoire*. -13 bytes thanks to *@Nevay*. [Try it online.](https://tio.run/##lZExb8MgEIX3/IobcWWc2t6K7LFbs6Sb5eHikISEHAjjVJHr3@7SpJXaLUiAdPDx7j044gW5sZKO29Pcaex7eENF4wJAkZduh52E1XcJsDFGSyToWDhqWsBEhP0pzDB6j151sAKCCmbk9RggUBVmWtLeH1JbPYudcUwozutcJOqzsk/MVtioloeF521S1zwXTvrBEVcBmmZxV7fDRgf1nyYXo7ZwDjbZ2jtF@6bF5G5xuYR3N/jD9eVWrq@9l@fMDD6zAfSaGGUdI/kBtwhjnhZpPiW3II/iaRFzoYzBy3/qv4leUffy0UQR3qJyxz1SJF5Gqsf@WVSH4o//aTHNXw) [Answer] # [R](https://www.r-project.org/), ~~58~~ 56 bytes ``` function(x)any(abs(diff(sign(diff(c(NA,x)))))>1,na.rm=T) ``` [Try it online!](https://tio.run/##bdDBasQgEADQu18hnkYYCia3gIVeeuxpb64Ua3UrWBOiLSml355u12xJms5FeTPMDDPOXs7@LdkS@gQTN@kDzFOG5@A95HBK9Wfh4Q4n/hO3ApO5GV/lgc/l0ZrsMpU0hlyAkstjgSNd4p7jFcWvrhGbhbeItfqwxVr7p7L9D2uDHbZ7rBtsBrXLoBW2KPbYrFYinBDfjxBoSFR00aVTeYHlQJx/EmpNAeY7hv7KSgWtlRJac2THQt00nNPbZKP1JfduYu6oYjiYXBzQXQu0fYxmyE4yZOelmD4mhtkNkjFOvuZv "R – Try It Online") Saved 2 bytes thanks to Giuseppe [Answer] # [J](http://jsoftware.com/), 16 15 bytes -1 byte thanks to FrownyFrog ``` 1 e.0>2*/\2-/\] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRVS9QzsjLT0Y4x09WNi/2tyKXClJmfkK6QpGKgYwJiGcIaCERITRRxVxhhFBk0hqiyKmcYIjjGyDEiX0X8A "J – Try It Online") ## Original: 16 bytes ``` 0>[:<./2*/\2-/\] ``` `2-/\]` - differences of each adjacent items `2*/\` - products of each adjacent items `[:<./` - the minimum `0>` - is negative? [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DeyirWz09I209GOMdPVjYv9rcilwpSZn5CukKRioGMCYhnCGghESE0UcVcYYRQZNIaosipnGCI4xsgxIl9F/AA "J – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ±V<0Ẋ*Ẋ- ``` [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/hzaG2Rg83NWlBcS6////j47lijYEYR0jCKkD5cH5xjA@QgYuBtNlDKaNoXwjqG4jqAoA "Husk – Try It Online") ## Explanation ``` ±V<0Ẋ*Ẋ- Implicit input, say [2,5,5,1,4,5,3] Ẋ- Consecutive differences: [3,0,-4,3,1,-2] Ẋ* Consecutive products: [0,0,-12,3,-2] V<0 Is any of them negative? Return 1-based index: 3 ± Sign (to make output consistent): 1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes *-5 bytes thanks to @ETHproductions* ``` ä- mÌäa d>1 ``` [Try it online!](https://tio.run/##y0osKPn///ASXYXcwz2HlyQqpNgZ/v8fbahjpAPEsQA) | [Test cases](https://tio.run/##y0osKPn//9C6w0t0FXIP9xxekqiQYmf4/390dKwOV7RhrI4CkNQxAnN0jHTgAgghYxgDRRYkDGWDtYPZxlCWMVzMCGxSLJduEAA) This uses Dennis's [algorithm](https://codegolf.stackexchange.com/a/155800/61613) [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` ä- ä* d<0 ``` [Try it online!](https://tio.run/##y0osKPn///ASXYXDS7QUUmwM/v@PNtQx1jGMBQA "Japt – Try It Online") A mashup of Oliver's answer with the approach used by several other answers. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 39 bytes ``` Any&:&{_*~?Sum[__]}@Slices&2@Sign@Delta ``` [Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm898xr1LNSq06XqvOPrg0Nzo@PrbWITgnMzm1WM3IITgzPc/BJTWnJPF/LBcXTFdJso5CNJcCEETH6kBoQzhDxwiJqYMsjipjjCKDphBVFsVMYwTHGFnGCGwBVyzQnX6pqSnF0SoFBcnpsVwBRZl5JSGpxSXOicWpxdFpOgolybH/AQ "Attache – Try It Online") Pretty happy with how this turned out. ## Explanation This is a composition of four functions: ``` Delta Sign Slices&2 Any&:&{_*~?Sum[__]} ``` `Delta` gets the differences between elements. = Then, `Sign` is applied to each difference, giving us an array of `1`s, `0`s, and `-1`s. = Then, `Slices&2` gives all slices of length two from the array, giving all pairs of differences. Finally, `Any&:&{_*~?Sum[__]}` is equivalent to, for input `x`: ``` Any[&{_*~?Sum[__]}, x] Any[[el] -> { el[0] and not (el[0] + el[1] = 0) }, x] ``` This searches for elements which sum to zero but are not zero. If any such pair of elements exist, then there is a bump. [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` dZSd|1>a ``` [Try it online!](https://tio.run/##y00syfn/PyUqOKXG0C7xv716SFFpqnqtultiTnGq@v9oQx1jIDTUMdAxjAUA "MATL – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 33 bytes ``` @(x)0||abs(diff(sign(diff(x))))>1 ``` [Try it online!](https://tio.run/##ZY/fCoMgFIev51OcuxQksO4WjV3tCXYXXTTTcWDU0P0Jomd3zjUoEwTP73znU3v5aF7K6TJNU3ekA2sulraoNbV47X6ngfl1EE5CCSOpag7JqblZlRSkEuuKZ3HNA3E2zznIeb5Btsk8FmVbbr5wqV8FeUx8NYs3kqkgRPcGEP3nxN70b0slIzvUoKkcEbmYGIcW7Z1WweK5hENoZVPte8qL/kCwxoTqWuK3@wA "Octave – Try It Online") ### Explanation: ``` @(x) % Anonymous function taking x as input diff(x) % Takes the difference between consecutive elements sign(diff(x)) % The sign of the differences diff(sign(diff(x))) % The difference between the signs abs(diff(sign(diff(x)))>1 % Check if the absolute value is 2 @(x)abs(diff(sign(diff(x)))>1 % Output as matrices that are treated truthy or falsy ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` s₃.¬≤₁∧¬≥₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU7PeoTWPOpc8amp81LEcxFwKZP7/H22oY6QDxLEA "Brachylog – Try It Online") Succeeds (`true.`) if there is a bump, and fails (`false.`) if there is no bump. ### Explanation This is fairly readable already: ``` s₃. There is a substring of the input… .¬≤₁ …which is not non-decreasing… ∧ …and… ¬≥₁ …which is not non-increasing ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ¥ü‚P0‹Z ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVvn/0NLDex41zAoweNSwM@p/pdLh/Qq6dgqH9yvpxPyPjuWKNgRhHSMIqQPlwfnGMD5CBi4G02UMpo2hfCO4bmOwSl1DHQMdXSMIC6goFgA "05AB1E – Try It Online") **Explanation** ``` ¥ # calculate delta's ü‚ # pair each element with the next element P # product of each pair 0‹ # check each if less than 0 Z # max ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` s₃s₂ᶠ-ᵐ×<0 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRUzMQNz3ctkD34dYJh6fbGPxXVYiO5QIShhBSxwhG68BFkMSMEWLI8kjiCBOMoSxjuJgR2Kz/QDkFIx0Fw1gA "Brachylog – Try It Online") Not nearly as neat and elegant as @Fatalize's existing 10 byte answer, but it works! ``` s₃ % There exists a substring of three elements [I,J,K] in the array such that s₂ᶠ % When it's split into pairs [[I,J],[J,K]] -ᵐ % And each difference is taken [I-J, J-K] × % And those differences are multiplied (I-J)*(J-K) % (At a bump, one of those will be negative and the other positive. % At other places, both differences will be positive, or both negative, % or one of them 0 - ultimately resulting in a non-negative product.) <0 % The product is negative ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ▼mεẊ-Ẋo±- ``` [Try it online!](https://tio.run/##yygtzv7//9G0Pbnntj7c1aULxPmHNur@//8/2kgHCGMB "Husk – Try It Online") Uses Dennis's algorithm. [Answer] # [Perl 5](https://www.perl.org/), 54 + 2 (`-pa`) = 56 bytes ``` map$\|=$F[$_-1]!=(sort{$a-$b}@F[$_-2..$_])[1],2..$#F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUAlpsZWxS1aJV7XMFbRVqM4v6ikWiVRVyWp1gEsaqSnpxIfqxltGKsDYiq71Vb//2@oYASEBv/yC0oy8/OK/@v6muoZGBr81y1IBAA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` lambda l:any(p>c<n or p<c>n for p,c,n in zip(l,l[1:],l[2:])) ``` [Try it online!](https://tio.run/##HcY7DoAgEAXAq7wSkm3AjqAXUQrEEElw3RgbvTx@msnIda4725b7qdW4zUtEdZEvJUPyjP2A@DQw8jdKxCiMu4iqVEfjwqt1QesmR@ETWY2GYAndrwm6PQ "Python 2 – Try It Online") Pretty much the same thing, thought it would be shorter though... # [Python 2](https://docs.python.org/2/), 63 bytes ``` f=lambda l:l[3:]and(l[0]>l[1]<l[2]or l[0]<l[1]>l[2]or f(l[1:])) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIccqJ9rYKjYxL0UjJ9og1i4n2jDWJifaKDa/SAEkYAMSsIMKpAHVGFrFamr@LyjKzCsB8qMNdRSMdBSMwaRhrOZ/AA "Python 2 – Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~11~~ 7 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` ₋ʁ*0<Ʃ± ``` Outputs 1 if there is a bump, 0 otherwise [Try it online!](https://tio.run/##K6gs@f//UVP3qUYtA5tjKw9t/P8/2kjHWAeIYwE) Port of [Wheat Wizard's Haskell answer](https://codegolf.stackexchange.com/a/155816/77078) --- # Old way (11 bytes): ``` ₋±₋Å1≤ĐŁ↔Ʃ= ``` [Try it online!](https://tio.run/##K6gs@f//UVP3oY1A4nCr4aPOJUcmHG181Dbl2Erb//@jjXSMdUx0jGMB) Returns False if there is a bump, True otherwise Port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/155800/77078) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 36 bytes ``` FreeQ[(d=Differences)@Sign@d@#,-2|2]& ``` Gives the opposite of the test case answers (False and True reversed). Prepend a `!` to switch to the normal form. OR ``` Abs@(d=Differences)@Sign@d@#~FreeQ~2& ``` Also reversed output, so replace `FreeQ` with `MatchQ` for normal form. Explanation: Take the sign of the differences of the sequence. Iff the resulting sequence includes {1,-1} or {-1,1} there is a bump. The absolute value the differences of {1,-1} or {-1,1} is 2 in either case. Shave off another byte by squaring the final list instead of taking the absolute value: ``` FreeQ[(d=Differences)@Sign@d@#^2,4]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7360oNTUwWiPF1iUzLS21KDUvObVY0yE4Mz3PIcVBWUfXqMYoVu1/QFFmXkl0mr5DdXWtTrUhCOsYQUgdKA/ON4bxETJwMZguYzBtDOUbgXXXxv4HAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Perl, 35 bytes Includes `+3` for `-p` `bump.pl`: ``` #!/usr/bin/perl -p s%\S+ %$a*1*($a=$&-$')%eg;$_=/-/ ``` Run as: ``` bump.pl <<< "3 1 2" ``` [Answer] # [Julia 0.6](http://julialang.org/), 57 56 bytes ``` l->any(p>c<n||p<c>n for(p,c,n)=zip(l,l[2:end],l[3:end])) ``` Basically just totallyhuman's python answer. -1 byte from user71546 [Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3P0fXLjGvUqPALtkmr6amwCbZLk8hLb9Io0AnWSdP07Yqs0AjRycn2sgqNS8lFsgwBjM0Nf8DKa7S4sy8dAWnxOJUvZDU4hIuhxIgWZxaoqAEYigkAyWKlRTAFkHkFNI0og11jHQMYzXRBHSMUIXMzVHEFGGCQISi0kjHAMk0RahxRmhiQA7Qvf8B "Julia 0.6 – Try It Online") # [Julia 0.6](http://julialang.org/), 39 bytes ``` f(x,y,z,a...)=x>y<z||x<y>z||f(y,z,a...) ``` Lispy recursion style, aka Dennis's python answer. Returns `true` when a bump exists, otherwise throws an error. This should maybe be 42 bytes since you have to splat it when calling. Eg for `a=[1,2,1]` you call as `f(a...)`. `f(a)=f(a...)` would remove that need, but is longer. I need to get better a recursion, and I don't really like writing code that throws an error. [Try it online!](https://tio.run/##yyrNyUw0@/8/TaNCp1KnSidRT09P07bCrtKmqqamwqbSDkilacBl/pcWZ@alKzglFqfqhaQWl3A5lADJ4tQSBSUQQyEZKFGspJCUmp6ZB5FTSNOINtQx0jGMBelHE9MxwhA1N0cTji/JKMovL1bwTS3JyE9xLSrKL4KrBCJ0E4x0DFDswqndCM1ROBRCVKTmpfwHAA "Julia 0.6 – Try It Online") ]
[Question] [ Your goal is to determine whether a given 2D point X lies within the area of the triangle with given vertices A,B,C. Write a function that takes in the coordinates of the test point X and the three triangle vertices (so that's 8 coordinates total) and returns True if the point lies inside that triangle, and False if it lies outside. Don't worry about edge cases. If the point lies on the boundary of the triangle (edge or vertex) or the triangle is actually a line segment, your code can do whatever, including crashing. Also don't worry about numerical stability or floating-point precision. Your code must be a named function. Code snippets will not be accepted. Fewest characters wins. **Input:** Eight real numbers representing coordinates. The numbers will lie in the range `(-1,1)`. The exact input format is flexible. You could, for example, take in eight numbers, a list of eight numbers, a list of four points each given by a tuple, a 2\*4 matrix, four complex numbers, two lists of the x-coordinates and y-coordinates, and so on. The input needs to just be the numbers in some container, with no additional data. You can't use the input to do any preprocessing, nor may you require any constraints on the input, such as requiring the points be given in ascending y coordinate. Your input must allow any eight coordinates (though your code can behave arbitrarily in the edge cases mentioned earlier). Please state your input format. **Output:** Either the corresponding Boolean `True`/`False`, the corresponding number `1`/`0`, or the analogues in your language. **Test cases** The inputs are given a list `[X,A,B,C]` of four tuples, the test point first, then the three triangle vertices. I've grouped them into those whose outputs should be `True` and those that should be `False`. `True` instances: ``` [(-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)] [(-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)] [(0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)] [(-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)] [(0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)] [(-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)] [(-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)] [(-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)] [(0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)] [(-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832)] ``` `False` instances: ``` [(-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)] [(0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)] [(0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)] [(0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)] [(0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)] [(-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)] [(-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)] [(0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)] [(0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)] [(0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192)] ``` [Answer] # Javascript / ECMAScript 6, 161 159 158 / 152 Javascript: ``` function $(t,r,i,a,n,g,l,e){b=(-g*l+a*(-n+l)+i*(g-e)+n*e)/2;c=b<0?-1:1;d=(a*l-i*e+(e-a)*t+(i-l)*r)*c;f=(i*g-a*n+(a-g)*t+(n-i)*r)*c;return d>0&&f>0&&d+f<2*b*c} ``` ECMAScript 6 version (thanks m.buettner, saves 6 characters) ``` $=(t,r,i,a,n,g,l,e)=>{b=(-g*l+a*(-n+l)+i*(g-e)+n*e)/2;c=b<0?-1:1;d=(a*l-i*e+(e-a)*t+(i-l)*r)*c;f=(i*g-a*n+(a-g)*t+(n-i)*r)*c;return d>0&&f>0&&d+f<2*b*c} ``` Call it as such (returns `true` or `false`): ``` $(pointX, pointY, v1X, v1Y, v2X, v2Y, v3X, v3Y); ``` Uses some fancy [barycentric coordinate math](http://en.wikipedia.org/wiki/Barycentric_coordinates_%28mathematics%29) based on code from [this answer](https://stackoverflow.com/a/2049712/863470). An ungolfed version for your reading enjoyment follows: ``` function $ (pointX, pointY, v1X, v1Y, v2X, v2Y, v3X, v3Y) { var A = (-v2Y * v3X + v1Y * (-v2X + v3X) + v1X * (v2Y - v3Y) + v2X * v3Y) / 2; var sign = A < 0 ? -1 : 1; var s = (v1Y * v3X - v1X * v3Y + (v3Y - v1Y) * pointX + (v1X - v3X) * pointY) * sign; var t = (v1X * v2Y - v1Y * v2X + (v1Y - v2Y) * pointX + (v2X - v1X) * pointY) * sign; return s > 0 && t > 0 && s + t < 2 * A * sign; } ``` [Answer] ## Python 2.7 ~~128~~ ~~127~~ ~~117~~ ~~110~~ ~~109~~ ~~103~~ ~~99~~ ~~95~~ ~~94~~ ~~91~~ 90 My first code-golf attempt! ## Code ``` f=lambda x,y,t:sum(a*y+c*b+d*x<d*a+c*y+b*x for i in(0,1,2)for a,b,c,d in[t[i-1]+t[i]])%3<1 ``` Takes as input (x,y,t) where (x,y) is the point we're checking and t is a triangle t = ((x1,y1),(x2,y2),(x3,y3)). ## Explanation I'm calculating the determinants of the matrices ``` | 1 x1 y1 | | 1 x2 y2 | | 1 x3 y3 | | 1 x2 y2 | , | 1 x3 y3 | , | 1 x1 y1 | . | 1 x y | | 1 x y | | 1 x y | ``` These determinants represent the signed distances from the sides of the triangle to the point (x,y). If they all have the same sign, then the point is on the same side of every line and is thus contained in the triangle. In the code above, `a*y+c*b+d*x-d*a-c*y-b*x` is a determinant of one of these matrices. I'm using the fact that `True+True+True==3` and `False+False+False==0` to determine if these determinants all have the same sign. I make use of Python's negative list indices by using `t[-1]` instead of `t[(i+1)%3]`. Thanks Peter for the idea to use `s%3<1` instead of `s in(0,3)` to check if s is either 0 or 3! ## Sagemath Version Not really a different solution so I'm including it in this answer, a sagemath solution using **80** characters: ``` f=lambda p,t,o=[1]:sum([det(Matrix([o+t[i-1],o+t[i],o+p]))<0for i in 0,1,2])%3<1 ``` where `p=[x,y]`, and `t=[[x1,y1],[x2,y2],[x3,y3]]` [Answer] ## Mathematica, 67 bytes ``` f=Equal@@({#2,-#}&@@(#-#2).(x-#)>0&@@@Partition[x=#;#2,2,1,{1,1}])& ``` The function takes two arguments, the point `X` and a list of points `{A,B,C}`, which are referred to as `#` and `#2` respectively. That is if you call ``` f[X,{A,B,C}] ``` then you'll get `#` as `X` and `#2` as `{A,B,C}`. (Note that there are two other anonymous functions nested inside the code - `#` and `#2` have a different meaning within those.) Here is an explanation of the function itself: ``` x=#;#2 & (* Save X into a variable x, but evaluate to {A,B,C}. *) Partition[x=#;#2,2,1,{1,1}] & (* Get a cyclic list of pairs {{A,B},{B,C},{C,B}}. *) ( &@@@Partition[x=#;#2,2,1,{1,1}])& (* Define an anonymous function and apply it to each of the above pairs. The two elements are referred to as # and #2. *) ( (#-#2) &@@@Partition[x=#;#2,2,1,{1,1}])& (* Subtract the two points. For a pair of vertices this yields a vector corresponding to the edge between them. *) {#2,-#}& (* An anonymous function that takes two values, reverses them, inverts the sign of one of them and puts them into a list. *) ({#2,-#}&@@(#-#2) &@@@Partition[x=#;#2,2,1,{1,1}])& (* Applied to the edge, this yields its normal. *) ({#2,-#}&@@(#-#2).(x-#) &@@@Partition[x=#;#2,2,1,{1,1}])& (* Take the scalar product of that normal with a vector from a vertex to x. This is projection of this vector onto that normal and hence the SIGNED distance of x from the edge. *) ({#2,-#}&@@(#-#2).(x-#)>0&@@@Partition[x=#;#2,2,1,{1,1}])& (* Check the sign of that distance, the exact mapping between (left, right) and (True, False) is irrelevant, as long as it's consistent. *) Equal@@({#2,-#}&@@(#-#2).(x-#)>0&@@@Partition[x=#;#2,2,1,{1,1}])& (* Check if all signs are equal - that is, if point X lies on the same side of all edges. This is equivalent to check that the point is inside the triangle. *) ``` Note that this function will actually work for *any* convex n-gon as long as its vertices are given in either clockwise or counter-clockwise order. [Answer] # CJam, ~~66~~ ~~63~~ ~~59~~ ~~52~~ ~~46~~ ~~34~~ ~~32~~ ~~31~~ ~~30~~ 28 characters ``` "Ă䒟损崙㩴ァ椟饃꿾藭鑭蘁"2G#b131b:c~ ``` After transforming the Unicode string, the following code (**33 bytes**) gets evaluated: ``` {2*2/\f{f{+~@-@@-}~@@*@@*>})-!}:T ``` Expects `X [A B C]` as input, where each point is of the form `[double double]`. Output is 1 or 0. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") A big thank you goes to [user23013](https://codegolf.stackexchange.com/u/25180) for saving 6 characters (13 bytes of uncompressed code)! ### Test cases ``` $ cat triangle.cjam "Ă䒟损崙㩴ァ椟饃꿾藭鑭蘁"2G#b131b:c~ [ [-0.31961 -0.12646] [ [0.38478 0.37419] [-0.30613 -0.59754] [-0.85548 0.6633] ] T [-0.87427 -0.00831] [ [0.78829 0.60409] [-0.90904 -0.13856] [-0.80685 0.48468] ] T [0.28997 -0.03668] [ [-0.28362 0.42831] [0.39332 -0.07474] [-0.48694 -0.10497] ] T [-0.07783 0.04415] [ [-0.34355 -0.07161] [0.59105 -0.93145] [0.29402 0.90334] ] T [0.36107 0.05389] [ [0.27103 0.47754] [-0.00341 -0.79472] [0.82549 -0.29028] ] T [-0.01655 -0.20437] [ [-0.36194 -0.90281] [-0.26515 -0.4172] [0.36181 0.51683] ] T [-0.12198 -0.45897] [ [-0.35128 -0.85405] [0.84566 0.99364] [0.13767 0.78618] ] T [-0.03847 -0.81531] [ [-0.18704 -0.33282] [-0.95717 -0.6337] [0.10976 -0.88374] ] T [0.07904 -0.06245] [ [0.95181 -0.84223] [-0.75583 -0.34406] [0.16785 0.87519] ] T [-0.33485 0.53875] [ [-0.25173 0.51317] [-0.62441 -0.90698] [-0.47925 0.74832] ] T [-0.99103 0.43842] [ [0.78128 -0.10985] [-0.84714 -0.20558] [-0.08925 -0.78608] ] T [0.15087 -0.56212] [ [-0.87374 -0.3787] [0.86403 0.60374] [0.01392 0.84362] ] T [0.1114 0.66496] [ [-0.92633 0.27408] [0.92439 0.43692] [0.8298 -0.29647] ] T [0.87786 -0.8594] [ [-0.42283 -0.97999] [0.58659 -0.327] [-0.22656 0.80896] ] T [0.43525 -0.8923] [ [0.86119 0.78278] [-0.01348 0.98093] [-0.56244 -0.75129] ] T [-0.73365 0.28332] [ [0.63263 0.17177] [-0.38398 -0.43497] [-0.31123 0.73168] ] T [-0.57694 -0.87713] [ [-0.93622 0.89397] [0.93117 0.40775] [0.2323 -0.30718] ] T [0.91059 0.75966] [ [0.60118 0.73186] [0.32178 0.88296] [-0.90087 -0.26367] ] T [0.3463 -0.89397] [ [0.99108 0.13557] [0.50122 -0.8724] [0.43385 0.00167] ] T [0.88121 0.36469] [ [-0.29829 0.21429] [0.31395 0.2734] [0.43267 -0.78192] ] T ]p; $ cjam triangle.cjam [1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0] ``` [Answer] # C – 156 bytes Input are array of 3 floats in X, 3 floats in Y and separate x and y for the test point. Bonus: handles all edge cases! ``` int f(float*X,float*Y,float x,float y){int i,j,c=0;for(i=0,j=2;i<3;j=i++)if(((Y[i]>y)!=(Y[j]>y))&&(x<(X[j]-X[i])*(y-Y[i])/(Y[j]-Y[i])+X[i]))c=!c;return c;} ``` Adapted from PNPOLY. [Answer] # [Pyth 1.0.5](https://github.com/isaacg1/pyth/blob/master/pyth.py), 57 54 51 ``` DgYb=Z0J'bWbK;bDiHNR*-'H'K-@N1@K1~Z>iYJiJY=JK)R!%Z3 ``` Defines the function g, which takes two inputs: the test point, and then the list of the vertices of the triangle. Outputs `True` and `False`. Note: Destroys the input, specifically b, the list of the vertices of the triangle. Try it [here](http://ideone.com/fork/aPbXH9). The last few characters, `gvwvw` call the function with a test case on the next two lines. Based on [this](https://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-triangle) algorithm Explanation: ``` DgYb Define g(Y,b): =Z0 Z=0 J'b J=b[0] (No = is needed because j is special). Wb While len(b)>0: (While b:) K;b K=b.pop() DiHN Define i(H,N): R*-'H'K-@N1@K1 Return half of the linked equation. ~ZiYJiJY Z+=i(Y,J)>i(J,Y) =JK J=K ) Wend R!%Z3 return not Z%3==0 (True iff Z == 0 or 3) ``` The CJam - Pyth war rages on! [Answer] # J 64 45 (42 without assignment) ``` c=:*./@(>:&0)@({.(,(1-+/))@%.|:@}.)@(}:-"1{:) ``` The assignment is not necessary for the thing to be a function, so unsure whether to count it or not. Taking advantage of the flexible input: I'd like to have an array of (1 + number of vertices) x (dimensionality of the space). Hoping to score some extra points here ... : This thing works for any dimension of simplex, not just triangles in a plane, but also a 3 sided pyramid in 3d space and so on. It also works when the number of vertices of the simplex is smaller than (n+1), then it computes whether the projection of the point onto the simplex is inside or not. It converts to [barycentric coordinates](http://en.wikipedia.org/wiki/Barycentric_coordinate_system), then checks for negative ones, indicating the point is outside. Do mind J uses \_ for negative ``` NB. example in triangle D =: 4 2 $ 1 1 0 0 3 0 0 2 NB. 4 rows , x first, then the vertices of the triangle NB. subtract last vertex coordinates from the rest and drop reference node n=: (}:-"1{:) NB. preprocessed to barycentric coordinates bar=: {. (, 1 - +/)@%. |:@}. NB. all positive ap =: *./@(>:&0) insided =: ap@bar@n inside D 1 ``` A run on the given examples: ``` true =: 0 : 0 [(-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)] [(-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)] [(0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)] [(-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)] [(0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)] [(-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)] [(-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)] [(-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)] [(0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)] [(-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832)] ) false =: 0 : 0 [(-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)] [(0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)] [(0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)] [(0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)] [(0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)] [(-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)] [(-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)] [(0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)] [(0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)] [(0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192)] ) NB. replace - by _ to avoid problems NB. cut up per row, drop the [ ] and convert to numbers $dat_t =: ((4 2 $ ".)@}:@}.;._2) (true='-')} true ,: '_' 10 4 2 $dat_f =: ((4 2 $ ".)@}:@}.;._2) (false='-')}false,: '_' 10 4 2 NB. this results in arrays with shape 10 4 2 NB. for each 4 x 2 array (rank 2), do c for all true instances c=:*./@(>:&0)@({.(,(1-+/))@%.|:@}.)@(}:-"1{:) c"2 dat_t 1 1 1 1 1 1 1 1 1 1 NB. the same for the false ones, demonstrating anonymous usage NB. still a function though (or verb in J parlance) *./@(>:&0)@({.(,(1-+/))@%.|:@}.)@(}:-"1{:)"2 dat_f 0 0 0 0 0 0 0 0 0 0 ``` [Answer] ## HTML5 + JS, 13b + 146b / 141b / 114 chars HTML: ``` <canvas id=C> ``` JS (146b): ``` // @params: t1x, t1y, t2x, t2y, t3x, t3y, pointx, pointy function T(a,b,c,d,e,f,g,h){with(C.getContext("2d"))return beginPath(),moveTo(a,b),lineTo(c,d),lineTo(e,f),fill(),!!getImageData(g,h,1,1).data[3]} ``` or ES6 (141b): ``` T=(a,b,c,d,e,f,g,h)=>{with(C.getContext("2d"))return beginPath(),moveTo(a,b),lineTo(c,d),lineTo(e,f),fill(),!!getImageData(g,h,1,1).data[3]} ``` or ES6 unicode-obfuscated (114 chars): ``` eval(unescape(escape('𥀽𚁡𛁢𛁣𛁤𛁥𛁦𛁧𛁨𚐽🡻𭱩𭁨𚁃𛡧𩑴𠱯𫡴𩑸𭀨𘠲𩀢𚐩𬡥𭁵𬡮𘁢𩑧𪑮𤁡𭁨𚀩𛁭𫱶𩑔𫰨𨐬𨠩𛁬𪑮𩑔𫰨𨰬𩀩𛁬𪑮𩑔𫰨𩐬𩠩𛁦𪑬𫀨𚐬𘐡𩱥𭁉𫑡𩱥𡁡𭁡𚁧𛁨𛀱𛀱𚐮𩁡𭁡𦰳𧑽').replace(/uD./g,''))) ``` demo: <http://jsfiddle.net/xH8mV/> Unicode obfuscation made with: <http://xem.github.io/obfuscatweet/> [Answer] # Python (65) People seem to be done submitting, so I'll post my own solution to my question. ``` f=lambda X,L:sum(((L[i-1]-X)/(L[i]-X)).imag>0for i in(0,1,2))%3<1 ``` `X` is the complex number representing the test points, and `L` is a list of three points, each a complex number. First, I'll explain a less golfed version of the code; ``` def f(X,A,B,C):A-=X;B-=X;C-=X;return((A/B).imag>0)==((B/C).imag>0)==((C/A).imag>0) ``` We shift the points `A,B,C,X` so that `X` is at the origin, taking advantage of Python's built-in complex arithmetic. We need to check if the origin is contained in the convex hull of `A,B,C`. This is equivalent to the origin always lying on the same side (left or right) of the line segments AB, BC, and AC. A segment `AB` has the origin on the left if one travel counterclockwise less than 180 degrees to get from A to B, and on the right otherwise. If we consider the angles `a`, `b`, and `c` corresponding to these points, this means `b-a < 180 degrees` (taken angles in the range 0 to 360 degrees). As complex numbers, `angle(B/A)=angle(B)/angle(A)`. Also, `angle(x) < 180 degrees` exactly for point in he upper half-plane, which we check via `imag(x)>0`. So whether the origin lies to the left of AB is expressed as `(A/B).imag>0`. Checking whether these are all equal for each cyclic pair in `A,B,C` tells us whether triangle `ABC` contains the origin. Now, let's return to the fully golfed code ``` f=lambda X,L:sum(((L[i-1]-X)/(L[i]-X)).imag>0for i in(0,1,2))%3<1 ``` We generate each cyclic pair in `(A-X,B-X,C-X)=(L[0]-X,L[1]-X,L[2]-X)`, taking advantage of negative Python list indices wrapping around (`L[-1]` = `L[2]`). To check that the Bools are all `True` (`1`) or all `False` (`0`), we add them and check divisibility by 3, as many solutions did. [Answer] # Fortran - ~~232~~ ~~218~~ ~~195~~ 174 Bloody awful. The function is horrendous because of the requirement that the data is passed to it and we cannot preprocess it. ``` logical function L(x);real::x(8);p=x(1)-x(3);q=x(2)-x(4);r=x(5)-x(3);s=x(6)-x(4);t=x(7)-x(3);u=x(8)-x(4);L=ALL([p*(s-u)+q*(t-r)+r*u-t*s,p*u-q*t,q*r-p*s]>=r*u-t*s);endfunction ``` The decrease of 14 characters is because I forgot to golf the function name from my test runs. The further decrease is due to implicit typing and forgetting to change the function name. The next 20 characters came off due to reading in the points as a single array. The full program is ``` program inTriagle real, dimension(2) :: a,b,c,x do print*,"Enter coordinates as x,a,b,c" read*,x,a,b,c if(all(x==0.0).and.all(a==0.0).and.all(b==0.0).and.all(c==0.0)) exit print*,"Is point in triangle: ",T(x,a,b,c) enddo contains! logical function L(x) real::x(8) p=x(1)-x(3);q=x(2)-x(4);r=x(5)-x(3) s=x(6)-x(4);t=x(7)-x(3);u=x(8)-x(4) L=ALL([p*(s-u)+q*(t-r)+r*u-t*s,p*u-q*t,q*r-p*s]>=r*u-t*s) endfunction end program inTriagle ``` [Answer] # MATLAB: 9! Not a whole lot of me to write here ``` inpolygon ``` Can be called like so: ``` inpolygon(2/3, 2/3, [0 1 1], [0 0 1]) ``` Output is assigned to a variable named `ans` --- If I actually had to write a function, it may be something like so, could probably be optimized: ``` function y=f(a,b,c,d) inpolygon(a,b,c,d) ``` [Answer] # C# 218 (149?) ``` using P=System.Drawing.PointF; bool F(P[]p){for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;}P[]a=new P[3];Array.Copy(p,1,a,0,3);var g=new System.Drawing.Drawing2D.GraphicsPath();g.AddLines(a);return g.IsVisible(p[0]);} ``` Probably not as character-efficient as a mathematical method, but it's a fun use of libraries. Incidentally, also rather slow. Also taking advantage of "Also don't worry about numerical stability or floating-point precision." - unfortunately, `GraphicsPath` uses `int`s internally, so a value in the range -1 < f < 1 can only have three possible values. Since floats only have 7 digits of precision, I just multiply by 1e7 to turn them into whole numbers. Hm, I guess it's not really *losing* any precision. It's also exploitable in another way: I probably could have taken advantage of ignoring precision and just given the "wrong" answer. *If* I'm allowed to ignore the character cost of importing libraries, **149** (at the very least, `System.Linq` and `System.Drawing` are pretty standard on most WinForms projects, but `System.Drawing.Drawing2D` might be a bit of a stretch): ``` bool G(PointF[]p){for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;}var g=new GraphicsPath();g.AddLines(p.Skip(1).ToArray());return g.IsVisible(p[0]);} ``` Test program (yea, it's ugly): ``` using System; using System.Drawing; using System.Drawing.Drawing2D; using P=System.Drawing.PointF; using System.Linq; class Program { static void Main(string[] args) { Program prog = new Program(); foreach (string test in @"[(-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)] [(-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)] [(0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)] [(-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)] [(0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)] [(-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)] [(-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)] [(-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)] [(0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)] [(-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832)] [(-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)] [(0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)] [(0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)] [(0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)] [(0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)] [(-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)] [(-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)] [(0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)] [(0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)] [(0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192)]".Split('\n')) { string t = test.Replace("[(", "").Replace(")]", ""); string[] points = t.Split(new string[] { "), (" }, StringSplitOptions.None); string[] p = points[0].Split(','); P[] xabc = new P[4]; for (int i = 0; i < 4; i++) { p = points[i].Split(','); xabc[i] = new F(float.Parse(p[0]), float.Parse(p[1])); } Console.WriteLine(test + "=>" + prog.F(xabc)); } Console.ReadKey(); } bool G(PointF[]p) { for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;} var g=new GraphicsPath(); g.AddLines(p.Skip(1).ToArray()); return g.IsVisible(p[0]); } bool F(P[]p) { for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;} var g=new System.Drawing.Drawing2D.GraphicsPath(); g.AddLines(p.Skip(1).ToArray()); return g.IsVisible(p[0]); } } ``` [Answer] ### Haskell — ~~233~~ 127 Using cross products as described [here](https://math.stackexchange.com/a/51328): ``` h(a,b)(p,q)(r,s)(t,u)=z a b p q r s==z a b r s t u&&z a b r s t u==z a b t u p q where z j k l m n o =(o-m)*(j-l)+(l-n)*(k-m)>0 ``` Previous solution implemented using [barycentric coordinates](http://en.wikipedia.org/wiki/Barycentric_coordinate_system#Determining_whether_a_point_is_inside_a_triangle) and the formulae described in this Stack Exchange [answer](https://math.stackexchange.com/a/51459): ``` g(p,q)(r,s)(t,u)(v,w)= let (j,k)=(p+(-r),q+(-s)) (l,m)=(t+(-r),u+(-s)) (n,o)=(v+(-r),w+(-s)) d=l*o-n*m a=(j*(m-o)+k*(n-l)+l*o-n*m)/d b=(j*o-k*n)/d c=(k*l-j*m)/d in (0<=a&&a<1)&&(0<=b&&b<1)&&(0<=c&&c<1) ``` Both functions `g` and `h` take four pairs, the first of which is the point to be tested for inclusion and the rest being the coordinates of the vertices of the triangle. To test with the sample input: ``` let trueTestCases = [((-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)), ((-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)), ((0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)), ((-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)), ((0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)), ((-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)), ((-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)), ((-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)), ((0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)), ((-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832))] let falseTestCases = [((-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)), ((0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)), ((0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)), ((0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)), ((0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)), ((-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)), ((-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)), ((0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)), ((0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)), ((0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192))] type Point = (Double, Double) test :: [(Point, Point, Point, Point)] -> [Bool] test testCases = map (\((px,py),(ax,ay),(bx,by),(cx,cy)) -> h (px,py) (ax,ay) (bx,by) (cx,cy)) testCases test trueTestCases --> [True,True,True,True,True,True,True,True,True,True] test falseTestCases --> [False,False,False,False,False,False,False,False,False,False] ``` Ungolfed solutions: ``` type Point = (Double, Double) -- using cross products triangulate' (a, b) (p, q) (r, s) (t, u) = (side a b p q r s == side a b r s t u) && (side a b r s t u == side a b t u p q) where side j k l m n o = (o - m) * (j - l) + (-n + l) * (k - m) >= 0 -- using barycentric coordinates triangulate :: (Point, Point, Point, Point) -> Bool triangulate ((px, py), (ax, ay), (bx, by), (cx, cy)) = let (p'x, p'y) = (px + (-ax), py + (-ay)) (b'x, b'y) = (bx + (-ax), by + (-ay)) (c'x, c'y) = (cx + (-ax), cy + (-ay)) d = b'x * c'y - c'x * b'y a = (p'x * (b'y - c'y) + p'y * (c'x - b'x) + b'x * c'y - c'x * b'y) / d b = (p'x * c'y - p'y * c'x) / d c = (p'y * b'x - p'x * b'y) / d in (0 <= a && a < 1) && (0 <= b && b < 1) && (0 <= c && c < 1) ``` [Answer] # JavaScript (ES6) 120 ``` C=(p,q,i,j,k,l,m,n, z=j*(m-k)+i*(l-n)+k*n-l*m, s=(j*m-i*n+(n-j)*p+(i-m)*q)/z, t=(i*l-j*k+(j-l)*p+(k-i)*q)/z )=>s>0&t>0&s+t<1 ``` Directly copied from my answer to [This other question](https://codegolf.stackexchange.com/questions/40343/triangular-battleships-a-computational-geometry-problem) **Test** In FireFox/FireBug console *Output* all 1s ``` ;[ C(-0.31961, -0.12646, 0.38478, 0.37419, -0.30613, -0.59754, -0.85548, 0.6633), C(-0.87427, -0.00831, 0.78829, 0.60409, -0.90904, -0.13856, -0.80685, 0.48468), C(0.28997, -0.03668, -0.28362, 0.42831, 0.39332, -0.07474, -0.48694, -0.10497), C(-0.07783, 0.04415, -0.34355, -0.07161, 0.59105, -0.93145, 0.29402, 0.90334), C(0.36107, 0.05389, 0.27103, 0.47754, -0.00341, -0.79472, 0.82549, -0.29028), C(-0.01655, -0.20437, -0.36194, -0.90281, -0.26515, -0.4172, 0.36181, 0.51683), C(-0.12198, -0.45897, -0.35128, -0.85405, 0.84566, 0.99364, 0.13767, 0.78618), C(-0.03847, -0.81531, -0.18704, -0.33282, -0.95717, -0.6337, 0.10976, -0.88374), C(0.07904, -0.06245, 0.95181, -0.84223, -0.75583, -0.34406, 0.16785, 0.87519), C(-0.33485, 0.53875, -0.25173, 0.51317, -0.62441, -0.90698, -0.47925, 0.74832) ] ``` *Output* all 0s ``` ;[ C(-0.99103, 0.43842,0.78128, -0.10985,-0.84714, -0.20558,-0.08925, -0.78608), C(0.15087, -0.56212,-0.87374, -0.3787,0.86403, 0.60374,0.01392, 0.84362), C(0.1114, 0.66496,-0.92633, 0.27408,0.92439, 0.43692,0.8298, -0.29647), C(0.87786, -0.8594,-0.42283, -0.97999,0.58659, -0.327,-0.22656, 0.80896), C(0.43525, -0.8923,0.86119, 0.78278,-0.01348, 0.98093,-0.56244, -0.75129), C(-0.73365, 0.28332,0.63263, 0.17177,-0.38398, -0.43497,-0.31123, 0.73168), C(-0.57694, -0.87713,-0.93622, 0.89397,0.93117, 0.40775,0.2323, -0.30718), C(0.91059, 0.75966,0.60118, 0.73186,0.32178, 0.88296,-0.90087, -0.26367), C(0.3463, -0.89397,0.99108, 0.13557,0.50122, -0.8724,0.43385, 0.00167), C(0.88121, 0.36469,-0.29829, 0.21429,0.31395, 0.2734,0.43267, -0.78192) ] ``` [Answer] # SmileBASIC, ~~111~~ 100 characters ``` DEF T X,Y,A,B,C,D,E,F Q=9e5GCLS GTRI(A-X)*Q,Q*(B-Y),Q*(C-X),Q*(D-Y),Q*(E-X),Q*(F-Y)?!!GSPOIT(0,0)END ``` Draws a triangle and checks the color of the pixel at the point. The triangle is scaled up 99999x and shifted so that the point to check will be at (0,0) before being drawn, to minimize loss in precision. [Answer] # Intel 8087 FPU assembly, ~~222~~ 220 bytes Uses only the 8087 FPU hardware to calculate. Here is the unassembled (ungolfed in this case too) version as a MACRO (will spare you the 220 hex byte codes): ``` ; calculate the area of of a triangle ABC using determinate ; input: coordinates (float), Ax,Ay,Bx,By,Cx,Cy ; output: area in ST TAREA MACRO A1,A2,B1,B2,C1,C2 FLD A1 FLD B2 FLD C2 FSUB ; ST = By - Cy FMUL ; ST = Ax * ( By - Cy ) FLD B1 FLD C2 FLD A2 FSUB ; ST = Cy - Ay FMUL ; ST = Bx * ( Cy - Ay ) FLD C1 FLD A2 FLD B2 FSUB ; Ay - By FMUL ; Cx * ( Ay - By ) FADD ; Cx * ( Ay - By ) + Bx * ( Cy - Ay ) FADD ; Cx * ( Ay - By ) + Bx * ( Cy - Ay ) + Ax * ( By - Cy ) FLD1 ; make a value of 2 FADD ST,ST ; ST = 2 FDIV ; divide by 2 FABS ; take abs value ENDM ; determine if point X is in triangle ABC ; input: points X, A, B, C ; output: ZF=1 if X in triangle, ZF=0 if X not in triangle TXINABC MACRO X1,X2,A1,A2,B1,B2,C1,C2 TAREA A1,A2,B1,B2,C1,C2 ; ST(3) = area of triangle ABC TAREA X1,X2,B1,B2,C1,C2 ; ST(2) = area of triangle XBC TAREA A1,A2,X1,X2,C1,C2 ; ST(1) = area of triangle AXC TAREA A1,A2,B1,B2,X1,X2 ; ST(0) = area of triangle ABX FADD ; add areas of triangles with point FADD ; ST = ST + ST(1) + ST(2) FCOMPP ; compare ST to ST(1) and pop results FWAIT ; sync CPU/FPU FSTSW R ; store result flags to R MOV AX, R ; move result to AX SAHF ; store result into CPU flags for conditional check ENDM ``` ## Explanation Uses the determinate to calculate the area of the ABC triangle, and then the triangle formed with the X point and two other points of the ABC triangle. If the area of triangle ABC equals the sum of areas of triangles XBC + AXC + ABX, then the point is within the triangle. The result is returned as ZF. ### What's neat about this All of the math and floating point operations are done in hardware with 80-bit extended precision. The final floating point comparison is also done in hardware so will be very accurate. This also uses all eight of the 8087's stack registers at once. ### What's not quite as neat about this As the points of the triangle must be plugged back into the formulas several times during the calculation, it requires each variable in memory to be loaded into the FPU's stack registers one at a time in the correct order. While this can be fairly easily modeled like a function as a MACRO, it means that the code is expanded each time at assembly, creating redundant code. 41 bytes were saved by moving some of the same repeated code segments into PROCs. However it makes the code less readable, so the above listing is without it (which is why it's labeled as "ungolfed"). ## Tests Here is a test program using IBM DOS showing output: ``` TTEST MACRO T LOCAL IS_IN_TRI TXINABC T,T+4*1,T+4*2,T+4*3,T+4*4,T+4*5,T+4*6,T+4*7 MOV DX, OFFSET TEQ ; load true string by default JZ IS_IN_TRI ; if ZF=1, it is in triangle, skip to display MOV DX, OFFSET FEQ ; otherwise ZF=0 means not in triangle, so load false string IS_IN_TRI: MOV AH, 9 ; DOS write string function INT 21H ENDM START: FINIT ; reset 8087 TTEST T0 ; true tests TTEST T1 TTEST T2 TTEST T3 TTEST T4 TTEST T5 TTEST T6 TTEST T7 TTEST T8 TTEST T9 TTEST F0 ; false tests TTEST F1 TTEST F2 TTEST F3 TTEST F4 TTEST F5 TTEST F6 TTEST F7 TTEST F8 TTEST F9 RET ; return to DOS T0 DD -0.31961, -0.12646, 0.38478, 0.37419, -0.30613, -0.59754, -0.85548, 0.6633 T1 DD -0.87427, -0.00831, 0.78829, 0.60409, -0.90904, -0.13856, -0.80685, 0.48468 T2 DD 0.28997, -0.03668, -0.28362, 0.42831, 0.39332, -0.07474, -0.48694, -0.10497 T3 DD -0.07783, 0.04415, -0.34355, -0.07161, 0.59105, -0.93145, 0.29402, 0.90334 T4 DD 0.36107, 0.05389, 0.27103, 0.47754, -0.00341, -0.79472, 0.82549, -0.29028 T5 DD -0.01655, -0.20437, -0.36194, -0.90281, -0.26515, -0.4172, 0.36181, 0.51683 T6 DD -0.12198, -0.45897, -0.35128, -0.85405, 0.84566, 0.99364, 0.13767, 0.78618 T7 DD -0.03847, -0.81531, -0.18704, -0.33282, -0.95717, -0.6337, 0.10976, -0.88374 T8 DD 0.07904, -0.06245, 0.95181, -0.84223, -0.75583, -0.34406, 0.16785, 0.87519 T9 DD -0.33485, 0.53875, -0.25173, 0.51317, -0.62441, -0.90698, -0.47925, 0.74832 F0 DD -0.99103, 0.43842, 0.78128, -0.10985, -0.84714, -0.20558, -0.08925, -0.78608 F1 DD 0.15087, -0.56212, -0.87374, -0.3787, 0.86403, 0.60374, 0.01392, 0.84362 F2 DD 0.1114, 0.66496, -0.92633, 0.27408, 0.92439, 0.43692, 0.8298, -0.29647 F3 DD 0.87786, -0.8594, -0.42283, -0.97999, 0.58659, -0.327, -0.22656, 0.80896 F4 DD 0.43525, -0.8923, 0.86119, 0.78278, -0.01348, 0.98093, -0.56244, -0.75129 F5 DD -0.73365, 0.28332, 0.63263, 0.17177, -0.38398, -0.43497, -0.31123, 0.73168 F6 DD -0.57694, -0.87713, -0.93622, 0.89397, 0.93117, 0.40775, 0.2323, -0.30718 F7 DD 0.91059, 0.75966, 0.60118, 0.73186, 0.32178, 0.88296, -0.90087, -0.26367 F8 DD 0.3463, -0.89397, 0.99108, 0.13557, 0.50122, -0.8724, 0.43385, 0.00167 F9 DD 0.88121, 0.36469, -0.29829, 0.21429, 0.31395, 0.2734, 0.43267, -0.78192 TEQ DB 'In Triangle',0DH,0AH,'$' FEQ DB 'Not In Triangle',0DH,0AH,'$' ``` ### Output ``` In Triangle In Triangle In Triangle In Triangle In Triangle In Triangle In Triangle In Triangle In Triangle In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle Not In Triangle ``` [Answer] ## C 414 (was 465) Golfed ``` #define D double int F(D ax,D ay,D bx,D by,D cx,D cy,D px,D py){int y=0;double J,K;D m=(ax-bx<0.001)?(by-ay)/(ax-bx):1000;D b=m*ax+ay;J=m*cx-cy+b;K=m*px-py+b;if(J*K>=0)y=1;return y;}D T[8],k;int i,n;void G(){while(i<8){scanf("%lf",&k);T[i++]=k;}n+=F(T[2],T[3],T[4],T[5],T[6],T[7],T[0],T[1]);n+=F(T[4],T[5],T[6],T[7],T[2],T[3],T[0],T[1]);n+=F(T[2],T[3],T[6],T[7],T[4],T[5],T[0],T[1]);printf(n==3?"True":"False");} ``` Original function declaration added for explanation ``` /** * determine if points C & P are on same side of line AB * return 1 if true, 0 otherwise */ int PointsSameSide(D ax,D ay,D bx,D by,D cx, D cy, D px, D py); ``` Rewritten as a named function: input via stdin one each line or all in one line space-separated. ``` #define D double int F(D ax,D ay,D bx,D by,D cx, D cy, D px, D py) { int y=0; double J,K; D m = (ax-bx<0.001)?(by-ay)/(ax-bx):1000; D b = m*ax+ay; J=m*cx-cy+b; K=m*px-py+b; if(J*K>=0)y=1; return y; } double T[8],k; int i,n; void G() { while(i<8){scanf("%lf",&k);T[i++]=k;} n+=F(T[2],T[3],T[4],T[5],T[6],T[7],T[0],T[1]); n+=F(T[4],T[5],T[6],T[7],T[2],T[3],T[0],T[1]); n+=F(T[2],T[3],T[6],T[7],T[4],T[5],T[0],T[1]); printf(n==3?"True":"False"); } ``` [Answer] **Java, 149 characters** ``` g=Math.atan2(100*(d-y),(a-x));h=Math.atan2(100*(e-y),(b-x));i=Math.atan2(100*(f-y),(c-x));k=Math.round(Math.abs(g-h)+Math.abs(h-i)+Math.abs(i-g))==6; ``` Horrible considering I have to write "Math." every time. This is the actual program: ``` package mathPackage; public class InTriangle { public static void main(String[] args) { boolean k; double a=-1,b=0,c=1,d=0,e=1,f=0,x=0,y=0.4; double g,h,i; g=Math.atan2(100*(d-y),(a-x)); h=Math.atan2(100*(e-y),(b-x)); i=Math.atan2(100*(f-y),(c-x)); k=Math.round(Math.abs(g-h)+Math.abs(h-i)+Math.abs(i-g))==6; System.out.println(k); System.out.println(g); System.out.println(h); System.out.println(i); System.out.print(Math.abs(g-h)+Math.abs(h-i)+Math.abs(i-g)); } } ``` where a is the x of point a,b is the x of point b, c for x of c, d is y of a, e is y of b, f is the y of c, and x and y are the x and y of the point. The boolean k determines whether it is true or not. [Answer] # JavaScript 125/198 If points are provided in 8 arguments: ``` function d(x,y,a,b,c,d,e,f){function z(a,b,c,d){return(y-b)*(c-a)-(x-a)*(d-b)>0}return(z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1} ``` If points are provided in a 2-dimensional array: ``` function c(s){return (z(s[1][0],s[1][1],s[2][0],s[2][1])+z(s[2][0],s[2][1],s[3][0],s[3][1])+z(s[3][0],s[3][1],s[1][0],s[1][1]))%3<1;function z(a,b,c,d){return (s[0][1]-b)*(c-a)-(s[0][0]-a)*(d-b)>0}} ``` This code doesn't use any of those fancy vector math. Instead, it only uses a simple algebra trick to determine if the point is inside the triangle or not. The formula: ``` (y-b)(c-a) - (x-a)(d-b) ``` [which tells the point is on which side of a line](https://www.desmos.com/calculator/pmuc3meieh), is derived from rearranging the definition of slope: ``` m = (y2-y1)/(x2-x1) (y2-y1) = m(x2-x1) (y-y1) = m(x-x1) ,substituting point we are testing (x,y) to be the 2nd point (y-y1) = (x-x1)(y2-y1)/(x2-x1) ,substitute back the original definition of m (y-y1)(x2-x1) = (x-x1)(y2-y1) <-- left side will be greater than the right side, if the point is on the left; otherwise, it's on the right 0 = (y-b)(c-a)-(x-a)(d-b) ,where (a,b)=(x1,y1), (c,d)=(x2,y2) ``` If we test all 3 sides, all 3 should yield some numbers with the same sign only when the point is inside the triangle since we are testing it around the triangle. If the point is on a side then one of the test should return 0. jsFiddle test code: <http://jsfiddle.net/DerekL/zEzZU/> ``` var l = [[-0.31961, -0.12646, 0.38478, 0.37419, -0.30613, -0.59754, -0.85548, 0.6633],[-0.87427, -0.00831, 0.78829, 0.60409, -0.90904, -0.13856, -0.80685, 0.48468],[0.28997, -0.03668, -0.28362, 0.42831, 0.39332, -0.07474, -0.48694, -0.10497],[-0.07783, 0.04415, -0.34355, -0.07161, 0.59105, -0.93145, 0.29402, 0.90334],[0.36107, 0.05389, 0.27103, 0.47754, -0.00341, -0.79472, 0.82549, -0.29028],[-0.01655, -0.20437, -0.36194, -0.90281, -0.26515, -0.4172, 0.36181, 0.51683],[-0.12198, -0.45897, -0.35128, -0.85405, 0.84566, 0.99364, 0.13767, 0.78618],[-0.03847, -0.81531, -0.18704, -0.33282, -0.95717, -0.6337, 0.10976, -0.88374],[0.07904, -0.06245, 0.95181, -0.84223, -0.75583, -0.34406, 0.16785, 0.87519],[-0.33485, 0.53875, -0.25173, 0.51317, -0.62441, -0.90698, -0.47925, 0.74832], [-0.99103, 0.43842, 0.78128, -0.10985, -0.84714, -0.20558, -0.08925, -0.78608],[0.15087, -0.56212, -0.87374, -0.3787, 0.86403, 0.60374, 0.01392, 0.84362],[0.1114, 0.66496, -0.92633, 0.27408, 0.92439, 0.43692, 0.8298, -0.29647],[0.87786, -0.8594, -0.42283, -0.97999, 0.58659, -0.327, -0.22656, 0.80896],[0.43525, -0.8923, 0.86119, 0.78278, -0.01348, 0.98093, -0.56244, -0.75129],[-0.73365, 0.28332, 0.63263, 0.17177, -0.38398, -0.43497, -0.31123, 0.73168],[-0.57694, -0.87713, -0.93622, 0.89397, 0.93117, 0.40775, 0.2323, -0.30718],[0.91059, 0.75966, 0.60118, 0.73186, 0.32178, 0.88296, -0.90087, -0.26367],[0.3463, -0.89397, 0.99108, 0.13557, 0.50122, -0.8724, 0.43385, 0.00167],[0.88121, 0.36469, -0.29829, 0.21429, 0.31395, 0.2734, 0.43267, -0.78192]]; function d(x,y,a,b,c,d,e,f){function z(a,b,c,d){return(y-b)*(c-a)-(x-a)*(d-b)>0}return(z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1} for(var i = 0; i < l.length; i++){ console.log(d.apply(undefined,l[i])); //10 true, 10 false } ``` --- **97 characters** (not counting spaces or tabs) count if converted into CoffeeScript: ``` d=(x,y,a,b,c,d,e,f)-> z=(a,b,c,d)-> (y-b)*(c-a)-(x-a)*(d-b)>0 (z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1 ``` **115 characters** if converted into ES6: ``` d=(x,y,a,b,c,d,e,f)=>{z=(a,b,c,d)=>{return (y-b)*(c-a)-(x-a)*(d-b)>0};return(z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1} ``` [Answer] ## R, 23 Inspired by [MATLAB](https://codegolf.stackexchange.com/a/32941/26904), ``` SDMTools::pnt.in.poly() ``` called like `SDMTools::pnt.in.poly(point,triangle)` where `point` is a length-2 vector and `triangle` is a 3x2 matrix of vertices. SDMTools is available on CRAN. [Answer] # Mathematica, 38 characters ``` RegionMember[Polygon[#[[1]]],#[[2]]] & ``` Example: ``` d = {{{0, 0}, {1, 0}, {.5, .7}}, {.5, .6}}; RegionMember[Polygon[#[[1]]], #[[2]]] & @ d ``` (\* True \*) [Answer] # [C (gcc)](https://gcc.gnu.org/), 108 bytes ``` i;f(a,b,c,d,e,f,g,h)float a,b,c,d,e,f,g,h;{i=(e-=a)*(h-=b)>(f-=b)*(g-=a);i=(c-=a)*f>(d-=b)*e==i&i==g*d>h*c;} ``` [Try it online!](https://tio.run/##dVXLbiQ3DLznKwYLJOgxehbiQ3xgMP6SXLxjjz3AxgmCvS322x2KVF8C96kFSV0kq4rU9fR6vX583M@35Wn9tl7X5/Vlva2v69vx9v3vpx@H/@2ef94vy8vp8nR8WN5Ol2/Hx@U2Pg/L69g8x@k1T2@Py3MevFwu9z/ul8vrw/Pj28P1/Ovjr6f7@3L8@dvh8M@/9/cft@XL789/vn9Zb8upfSVwgfUQK0BhWQ@xZayWC2XwPKMmQLnqrp1zZb1zXhMhOh7Pn@ObMmreb80Ixn01Q88fG7fC9@atUIGsS@E3sT6usbHY5wHaVzT3iU8ilis0Esw/cYYkJ8K6pawViU18xmzsultBUzUaII0ZetHB1PuEA8kI3aHVlhNw5o3OLdPwRsR7BZBA04TvZEkLKrQMyLpx3RpxqaTOmqCGnYs89Ia2nz7IzBUbU1EVMWfp49cCRumzOoaKELesagOxfYUBwYt37ja1oA5o0yXckg3jLmkvdxIeCyAVLUNEpP0Chh8LCzpNr5pOv4SuVsp6V6h74cfEheY6vWTh5T0Fmm7ma4IlnXeYtBgjlvO1d6MpP7csBUTLoqYdfLeCUL@uhcI6teigVNzSljXy1NibbIyqY/6pbIQjwOcR3DfLBFlYnG4KBAvWZy0KPK0QxVTJlhFOqULbbTPozSrNLgi4ZmfT7CTSOIsN4UpC2jgZ1iMvr3I05C40ANcYYZcB7BgCViNws3VsMHlVJwE4vD/5QRfWPWCLxp3y97D7oBNxSujq7oHUTfoccTGmBmL0QWprwYzsQUf/T9aCPsraAbx4xxie2XdU49GtOa3FHPO0EuC@XZRIaoDYmFrDz8FI@i0cnlmS0eYQitmVWwCYl5RA9rup6zb1gh7IvKIfsWRy8iFkTDDIBuKYfT02kGYPUMy7XY@MCVgcdI9WHz4AsJmSjQ1CqJdlvAClddt8FSXKrpTEQpPumWIEsxoivY@N3gBx1oXDfExUTddiAu57JNqkXoh4/DwN4PN1QmAcFqFwccmhVMAoOjsGPG396@M/ "C (gcc) – Try It Online") Takes three cross products and returns `1` if the sign of the `k̂` component doesn't change. ]
[Question] [ Randall Munroe (author of XKCD) held [a survey to give names to colors](https://blog.xkcd.com/2010/05/03/color-survey-results/). The main outcome is [a list of names for the 954 most common RGB monitor colors](https://xkcd.com/color/rgb/). For ease of programming, here is the list in plain text: <http://xkcd.com/color/rgb.txt>. Beware, the first line is not data, but contains the license. Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner. Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included. Examples: ``` dark peach -> #de7e5d robin's egg blue -> #98eff9 pink/purple -> #ef1de7 ``` [Answer] # Perl 5 - ~~4212~~ ~~3956~~ 3930 ``` use IO::Uncompress::Gunzip qw(gunzip); gunzip 'g'=>\$_; while(/(\x00*)(.)(.)(.)(.)/gs){$c[$i+=ord($2)+255*length$1]=sprintf"#%02x%02x%02x\n",map{ord}$3,$4,$5} @a[32,33,39,47,97..123]=(3,1812,3,17,82,4,1013,119,3,909,8,10,10,1827,1219,4,718,265,228,418,2347,10,3,31,3,1786,921,380,1223,1915,4); $_=<>; for$i(0..(($h=y///c-1)<=12?$h-1:12)){$h+=$a[(($i/2|0)==1)+ord((/./g)[$i])]if($i!=7&&$i!=10)} print$c[$h]; ``` 407 bytes for the code and 3523 for the data file. Binary data is read from the file 'g', a hexdump of which can be found [here](http://pastebin.com/36vWnJMW). This uses a perfect hash function generated using [GNU gperf](https://www.gnu.org/software/gperf/), which assigns each color name to a unique integer in the range 0 to 6304 that can be used to index a table. The gzipped data contains the color values in the format of 1 byte indicating the offset in the table from the previous color, then 3 bytes for the color itself (with two hex digits per byte). (A 0 byte for the offset means it's actually the next value + 255, since not every offset fit in one byte). The code parses the data to create the table containing the color rgb string, then applies the hash function (translated to perl) to the input to select the matching output from the table. Usage: ``` echo 'pale red' | perl get-color.pl #d9544d ``` Edit: Further reduced the size by gzipping the data file [Answer] # EXCEL, 18 (+ 18269) Just to set a baseline, I will show the simplest Excel solution that I could think of: **Code** The code in Excel is very simple: ``` =VLOOKUP("";A:B;2) ``` The input should be placed between the double quotes. **Data** The data should be stored in a .csv file, looking rougly like this: > > pinkish purple;#d648d7 > > > When I click on the CSV it automatically opens excel, and places the data in columns A and B, you may need a different separator. [Answer] # Ruby, ~~5,379~~ 88 + 9 + 5,220 = 5,317 bytes +9 bytes for `-rdigest` flag. ``` n=$*.pop $><<?#+$<.read.unpack("h*")[0][/^.{11}*#{Digest::MD5.hexdigest(n)[1,5]}\K.{6}/] ``` ...plus a 5,220-byte dictionary as binary data read from STDIN (or filename argument). You'll find the dictionary in xxd format in the snippet below. The program takes a color name as an argument, so you invoke it like this: ``` $ cat dictionary | ruby -rdigest script.rb "purplish grey" #7a687f ``` If anyone can figure out a shorter way how to both read a file *and* take a color name as an argument, please leave a comment. `$*` (ARGV) and `$<` (ARGF) interact in strange and occult ways, ergo `$*.pop`. ## Dictionary (xxd format) ``` 0000000: 9bac a5cc d289 ff60 65ea 7573 21ba 9269 .......`e.us!..i 0000010: 9ed0 ad8a ff40 6d38 67d9 48bf 70de 9854 [[email protected]](/cdn-cgi/l/email-protection) 0000020: 58c8 237c b032 8fab 514d ffff 32e9 6aa5 X.#|.2..QM..2.j. 0000030: 7b9c 96b7 59e2 f8df 50f6 fc8c 613d 545a {...Y...P...a=TZ 0000040: 3a19 94c1 3388 0024 c009 c409 5838 b958 :...3..$....X8.X 0000050: 9e8b 6a55 82fe 4b53 c043 d299 8be2 1509 ..jU..KS.C...... 0000060: a0f5 8304 fd0d 0cf6 0737 5616 eda2 3e2e .........7V...>. 0000070: 3277 b8bf bdec 2224 7ce3 aa54 33cc 6651 2w...."$|..T3.fQ 0000080: 0eb9 5bc3 e860 0df5 afd6 023e f136 7577 ..[..`.....>.6uw 0000090: 230a 7173 a4ae 2bc0 5b77 9117 fd0f 8729 #.qs..+.[w.....) 00000a0: 2ac4 fa8a b8bd a905 7878 2f8b 0ddd 587d *.......xx/...X} 00000b0: 9db9 a4c6 7845 0252 7aff 5b23 8bce b207 ....xE.Rz.[#.... 00000c0: d9dc 4a7e e85a ebd8 9d66 befd 6d6b ccda ..J~.Z...f..mk.. 00000d0: 064d cca2 8ca6 4851 9849 e749 54fa 9f38 .M....HQ.I.IT..8 00000e0: bf52 b29b ff36 9e10 d2b7 f2ab 45ed 9836 .R...6......E..6 00000f0: 3b56 1ba5 81ee 359f b859 7b1e 1a67 93f6 ;V....5..Y{..g.. 0000100: 6f5f 1213 44db 8f3a 9db5 dab3 8653 0d2e o_..D..:.....S.. 0000110: ffcf 4c58 0a45 0345 2133 e2ff 2b0d c8c5 ..LX.E.E!3..+... 0000120: 9d79 75a0 179c da09 d03d 15c0 84fe bd3b .yu......=.....; 0000130: 4605 b7c9 32bc 777d 01e3 7f51 ffdf 8707 F...2.w}...Q.... 0000140: 4ade 4a76 ed24 6714 2000 ea21 c0d9 7129 J.Jv.$g. ..!..q) 0000150: ab70 ffaf 6895 c05f 86a4 1e84 4db6 c758 .p..h.._....M..X 0000160: 85ee 686f 0c5a 1e72 e704 172a 2d0a 9033 ..ho.Z.r...*-..3 0000170: f744 7e0d 4e92 70b1 f7ff 19b7 42af d1d5 .D~.N.p.....B... 0000180: ce16 420f 4509 4700 e95b ec80 634b 8bbf ..B.E.G..[..cK.. 0000190: 76ab d954 8cff 0b59 0af8 dd6e 4c74 5aff v..T...Y...nLtZ. 00001a0: fd22 c7cd a7b9 7e30 bd88 8623 3ee6 54f5 ."....~0...#>.T. 00001b0: bd41 97d4 957c cad7 ab20 fdff 93da bf82 .A...|... ...... 00001c0: 58e0 4031 53e4 cff0 6ee0 db04 df41 3908 [[email protected]](/cdn-cgi/l/email-protection). 00001d0: b1c6 0406 47dc d9ff 003f b633 4c41 f22f ....G....?.3LA./ 00001e0: 432f ba51 b2ca a64c 0f66 ea87 4cef 2853 C/.Q...L.f..L.(S 00001f0: c72c fc1a bfd6 36a9 2600 4986 c59a fbe7 .,....6.&.I..... 0000200: 7dd6 78f5 24fc 8138 2afe 1e4d 02df d894 }.x.$..8*..M.... 0000210: 4d82 8e3b 01c3 677f bc5a 064d a767 8933 M..;..g..Z.M.g.3 0000220: a96a 87c0 cd37 c6c2 b857 02f3 fd3d f7f8 .j...7...W...=.. 0000230: e43f cb2e 5683 bd3c fa36 9a05 08c1 c578 .?..V..<.6.....x 0000240: 8ff9 5bda 1bcf 99aa 4cf4 9f8a 7a24 7c6f ..[.....L...z$|o 0000250: 86e8 bdd6 7df6 add8 670e 35ef c5ca d34b ....}...g.5....K 0000260: fe5d e4d9 910a effb 73c2 7cfb d2ca 1aa0 .]......s.|..... 0000270: cb5f 6a07 20c7 6a0b b267 c601 a70b 1494 ._j. .j..g...... 0000280: 2d31 a8ab 0a17 17f9 1987 7ff5 bd19 c561 -1.............a 0000290: 18ef cffa 3963 f0fc 76e9 d306 d120 0031 ....9c..v.... .1 00002a0: 61cc 6b48 53a1 0413 66a8 894f 2374 fa5d a.kHS...f..O#t.] 00002b0: 28bd ffff 6bf9 d190 f0ad 7930 e168 1ad7 (...k.....y0.h.. 00002c0: 93df f7dd 5c9c da24 871d 6bab 211f b3ab ....\..$..k.!... 00002d0: 2f8d d5bf f5cf 941d 2af0 8956 0a68 ff3e /.......*..V.h.> 00002e0: e6e1 2896 0d57 09b7 62a3 811b 5207 ccf2 ..(..W..b...R... 00002f0: 8ff9 0b4b 7d76 dad0 b479 0250 689a 08ff ...K}v...y.Ph... 0000300: ad30 4e06 03c1 803d bb5d ca47 4306 d007 .0N....=.].GC... 0000310: 4106 0002 d799 00af c36f 0d02 666f 9b56 A........o..fo.V 0000320: e867 81c0 14d3 7186 2ff1 8d69 4b30 9ab3 .g....q./..iK0.. 0000330: f5fd 6fb3 7c9a 593a 6aec 4b76 6f48 9e30 ..o.|.Y:j.KvoH.0 0000340: ca57 9137 27b3 0a98 0404 ce0b ff16 3608 .W.7'.........6. 0000350: fb57 8955 6694 c212 7416 eb02 3c7c a3e8 .W.Uf...t...<|.. 0000360: 2056 abe9 88dd 2b0c 12fb e93e 0937 a456 V....+....>.7.V 0000370: d4aa 20c3 846b cc65 f8ea 2286 f2e8 f6a2 .. ..k.e.."..... 0000380: 7202 6eb4 75bd 0f2a de09 6136 7a8b 1045 r.n.u..*..a6z..E 0000390: 28bf 9f97 0d12 06d0 ee27 f820 f6c1 ffef (........'. .... 00003a0: a5dd 6b77 e450 0537 9ff3 b90c 68ab a2ff ..kw.P.7....h... 00003b0: 70a3 a0f7 c777 8936 cb72 6dff ef34 8cf7 p....w.6.rm..4.. 00003c0: 4e0b 53b1 27df 9565 c589 f9ec 61e6 49ff N.S.'..e....a.I. 00003d0: 2b17 d3ce d711 3f4b ddcd 1c96 d9c4 93e1 +.....?K........ 00003e0: 5ff6 ac22 c313 bf55 1817 4f3d 8ef2 5c02 _.."...U..O=..\. 00003f0: f90a fb61 dbff d7f6 ff1a 16c4 f437 e8b2 ...a.........7.. 0000400: 10f3 bf91 1afb 74c5 b851 63e0 5fa4 6cd8 ......t..Qc._.l. 0000410: 7a89 980a 0ba3 4d77 ae70 ca87 d5b1 cf60 z.....Mw.p.....` 0000420: e62d c9fa ffab e120 6bff bb06 4ea1 570e .-..... k...N.W. 0000430: f9f9 7c51 e2ff a2ff 845d bee7 fb7d f5e9 ..|Q.....]...}.. 0000440: f8c0 a568 f3b7 f4f1 3506 6620 ea4a fd8c ...h....5.f .J.. 0000450: a67a 4d2b c800 437e cf70 8500 40d0 6dba [[email protected]](/cdn-cgi/l/email-protection). 0000460: e7c4 8fd4 0903 6744 01a9 ef68 4a9f 77d3 ......gD...hJ.w. 0000470: 1547 2e42 4cef 0dcf eb17 6008 1028 7fd9 .G.BL.....`..(.. 0000480: effd 8049 a2f5 4e02 3fd7 f4f6 c700 e835 ...I..N.?......5 0000490: cd0a 4187 f29d b142 13c7 8f0b f0bb 0052 ..A....B.......R 00004a0: 97bd 8565 1fbd dbdd 1608 6e1e 14df ef37 ...e......n....7 00004b0: dec6 5f42 7eae 9d12 3cf6 08cb a209 0368 .._B~...<......h 00004c0: 0975 e601 5025 b5f5 8e82 cc6f edb4 1631 .u..P%.....o...1 00004d0: c8c4 42ad 0449 05b8 ebea a8b6 9608 33f9 ..B..I........3. 00004e0: 58ac eb8a f895 e5ae 562d d1a0 009f ef2b X.......V-.....+ 00004f0: 9065 c74b 5e81 cb19 be69 e420 7b75 81a5 .e.K^....i. {u.. 0000500: b3d2 1abc ff96 fa6e f6cf f3fb 243a 7ba2 .......n....$:{. 0000510: ef7b cc52 0e50 6fca e468 c071 3947 dffd .{.R.Po..h.q9G.. 0000520: ff8f 4165 790f 38a3 6650 f0f1 332f 5543 ..Aey.8.fP..3/UC 0000530: 1b2d b7de f2fa 8c42 aa4b ff17 aa43 3f91 .-.....B.K...C?. 0000540: bac7 e942 b742 b410 10ea eea0 55e2 c631 ...B.B......U..1 0000550: 2ffa f2d0 e281 838b f888 1a8f a97f 4644 /.............FD 0000560: 50ae f6bb 527e 01ff 5c21 bad8 7505 5851 P...R~..\!..u.XQ 0000570: 703e 1ca4 901c 0bf2 2e4f 0ab0 2e20 302e p>.......O... 0. 0000580: fec6 014a 739a da9a 5a00 553a fca7 8e0b ...Js...Z.U:.... 0000590: fca6 39df 97f8 dda5 b3af 0c15 453e e3fa ..9.........E>.. 00005a0: 678e aac0 4767 e72e 7c9b 84e4 1c11 6774 g...Gg..|.....gt 00005b0: 8d2e 6262 fbef 823e 94db 27d5 4eb2 112b ..bb...>..'.N..+ 00005c0: 7950 0bd8 6a37 3a1f 3140 8ad7 2ca9 f8f6 yP..j7:.1@..,... 00005d0: fa4e 9b1c 3e0c 20f2 b3de 028e c71c 0e8c .N..>. ......... 00005e0: d848 8608 79a1 0dd3 ae24 2fc8 ffe9 2bc6 .H..y....$/...+. 00005f0: 98a4 0c32 6ad2 4cff 7f7f 1bfe ed7e 038a ...2j.L......~.. 0000600: aa33 8b46 1c99 f0ff d940 c589 57d8 3a2f [[email protected]](/cdn-cgi/l/email-protection).:/ 0000610: 7bf9 05c4 197c da77 1a5b b729 8e57 e694 {....|.w.[.).W.. 0000620: 8d59 8879 71c1 47c2 727e 093c 8010 3717 .Y.yq.G.r~.<..7. 0000630: 1971 9d8f 03b3 9cc6 7f5d 0631 67b6 fdf6 .q.......].1g... 0000640: fe88 0857 8bf4 82a6 97bc 0b04 9cf3 9264 ...W...........d 0000650: b50e 696b 6900 c6aa 68da 8f20 8773 c0c1 ..iki...h.. .s.. 0000660: f67c 33f1 53da b66c cbf4 ff3d d708 b24a .|3.S..l...=...J 0000670: 240a 3906 f163 9136 9694 4977 608e 16ff $.9..c.6..Iw`... 0000680: fff4 d266 8fe1 1976 8826 b6c5 0316 11a1 ...f...v.&...... 0000690: efff f700 56c3 ffbd 7ca9 b7a0 dd80 8c27 ....V...|......' 00006a0: 8af7 0d95 3f5d e18f 67ae d67e fbcd b7e2 ....?]..g..~.... 00006b0: efcb ceca 978f b9fb 099f 3a11 ba09 40a9 ..........:...@. 00006c0: 321d bf75 8a71 8400 55a5 d236 a584 a45c 2..u.q..U..6...\ 00006d0: 5d7c 4c55 8088 fe37 8f92 5d4c 0c45 d844 ]|LU...7..]L.E.D 00006e0: 09ba c759 fe4b c8b1 a35e f7bf 8b0a 6197 ...Y.K...^....a. 00006f0: a59a 5078 9a22 a65b fa90 44ad 6e49 d541 ..Px.".[..D.nI.A 0000700: 15a4 482e f52f d96e f30d efd1 0af0 faaf ..H../.n........ 0000710: 26ab 2630 104b c4b4 94f7 6fbc c5bd b9b6 &.&0.K....o..... 0000720: 2474 9ae7 c2c7 013c 92d6 7bff af4b 52a4 $t.....<..{..KR. 0000730: fe6f 9e65 34ce d210 bf32 7af6 7f4b 8273 .o.e4....2z..K.s 0000740: 3700 936d 790a 0443 2852 d0fd e48c 3f78 7..my..C(R....?x 0000750: 60ce 3b0c 0855 f889 50fd 7f52 de1c afa4 `.;..U..P..R.... 0000760: 579d f45f 3e66 c8f8 3ded 52ae 70d0 d033 W.._>f..=.R.p..3 0000770: 6e41 89b4 b836 4a15 7bb3 c777 aa7c 0ec4 nA...6J.{..w.|.. 0000780: 3885 e445 18b9 b080 674e 4bd8 4d85 cb80 8..E....gNK.M... 0000790: dde2 27ef 1f60 521f d2ef 4520 dd0f fa0f ..'..`R...E .... 00007a0: e295 94c9 fe34 e71f 14d8 71cb c7ad 5335 .....4....q...S5 00007b0: a00b 541b 08d5 7bc5 a926 854c c8f8 f89f ..T...{..&.L.... 00007c0: 463f c1e3 ffba f086 988d 8fec 1763 ad42 F?...........c.B 00007d0: cb8a 1f36 310f 218c 39cd bc8f f5ff 3efb ...61.!.9.....>. 00007e0: 7f42 8cde 4682 1073 ec0c b863 ff26 dc28 .B..F..s...c.&.( 00007f0: 840c 27b3 11b1 cc7b 0a8a 3f8a 14b5 ee8d ..'....{..?..... 0000800: 0cb6 c1d4 6f14 dc57 4886 a6f5 d17a ea0c ....o..WH....z.. 0000810: 20ff 4009 74fd 8150 8b87 9bd9 057a 74fe [[email protected]](/cdn-cgi/l/email-protection). 0000820: 25a9 a894 a56a a5fc ff40 b203 f2ff 7ffe %....j...@...... 0000830: f033 fff7 7a60 8fe7 4f20 06f4 47c3 9929 .3..z`..O ..G..) 0000840: b18d 8b68 0816 696b 404f 98b3 d3f7 fe96 ...h..ik@O...... 0000850: de9a 24fc fab7 2bb9 387b 911f 9dc5 df1c ..$...+.8{...... 0000860: 5cd4 f226 c070 23f4 82b9 f50c 64ff 0c9f \..&.p#.....d... 0000870: 8bee 5b77 4782 2042 1790 bd29 3cd6 f84a ..[wG. B...)<..J 0000880: fb02 8222 cf5d 09a9 48e0 da5a 787e 74b5 ...".]..H..Zx~t. 0000890: 0e31 1c6b 258b ffbe dd14 d64c 0d51 4288 .1.k%......L.QB. 00008a0: 2a56 e359 6361 832b 0773 5514 c930 788b *V.Yca.+.sU..0x. 00008b0: b2f1 6f55 c6ce d9cb 4da3 d9fd fdfd 8e90 ..oU....M....... 00008c0: 2077 ba65 eb7a 4346 91b6 1266 9910 7406 w.e.zCF...f..t. 00008d0: 6eb0 fe7d 0360 0f23 fb48 6621 a86f 0f59 n..}.`.#.Hf!.o.Y 00008e0: 903b 0a20 c589 98fc dfb8 01c4 76f7 e4e1 .;. ........v... 00008f0: 09de b49f 0b0c 10da b63a 35c3 4afb 70e5 .........:5.J.p. 0000900: e6de 34b7 8c6f 408e 4057 9f74 37df 5ffb ..4..o@[[email protected]](/cdn-cgi/l/email-protection)._. 0000910: 3052 8ffa ffbe 26c0 aaff df47 99e1 8b59 0R....&....G...Y 0000920: 7bab be18 34b6 da60 c1dc c001 21d5 286c {...4..`....!.(l 0000930: 8f80 e8ce ff34 06e5 abd6 201c d418 33bf .....4.... ...3. 0000940: 520f 23f0 4da2 e791 c32b 4509 46c8 3b77 R.#.M....+E.F.;w 0000950: 3526 76f6 fb5d 0ae6 7f4a 74fc 2043 d1cc 5&v..]...Jt. C.. 0000960: caa4 66b1 3f3e 79a8 483d 841d 0f59 5460 ..f.?>y.H=...YT` 0000970: ea30 10d2 59db 2dbb 7129 9bc7 3c09 b9fe .0..Y.-.q)..<... 0000980: a2a3 66bf b551 9777 0010 aac7 9322 0bd5 ..f..Q.w.....".. 0000990: 14e4 d7f7 c770 e693 094f 3bde 9ef8 3730 .....p...O;...70 00009a0: 098d c938 bc79 e54e ef9a 3938 12a2 bc0b ...8.y.N..98.... 00009b0: 4d15 5a0c 17ef f2e8 c4fc 7d6f 2235 0020 M.Z.......}o"5. 00009c0: e2ce b28d 8243 e4c9 9aff 5cbc e69a aa1b .....C....\..... 00009d0: 3259 8ad2 0b50 b4d9 179b c90c e41c a939 2Y...P.........9 00009e0: c700 909e 0b91 2549 fe3d fed1 7eaa 450d ......%I.=..~.E. 00009f0: 0034 d58e 0a24 3b59 384f 975d 8753 1974 .4...$;Y8O.].S.t 0000a00: 8cca 9a94 6bc3 7806 5683 02aa 7240 199a ....k.x.V...r@.. 0000a10: e5c4 fbdf de30 af24 4247 8501 08f4 d95e .....0.$BG.....^ 0000a20: 41c5 2b00 30fe 7446 427e c9bd c6a7 e092 A.+.0.tFB~...... 0000a30: bdf4 db7d ce06 caa2 1043 9e11 0944 0a15 ...}.....C...D.. 0000a40: cf3a df64 95a9 8a03 7df5 e8aa d9ef 0020 .:.d....}...... 0000a50: d50d cd9b 0dd6 2f6b bfd7 708c 5ab3 c98c ....../k..p.Z... 0000a60: 312f 19de 8cff 3ec4 6fe1 6130 258b a88b 1/....>.o.a0%... 0000a70: ef27 b89c 024a 9eb9 2aef 202a b302 9f3a .'...J..*. *...: 0000a80: 00c1 d58d 56ef 8036 98bb febd 9730 d21b ....V..6.....0.. 0000a90: 2716 43a3 8958 0f71 08df 20cc ef84 abcc '.C..X.q.. ..... 0000aa0: f19d c5d3 6e38 5693 59fb f92b 4913 5eee ....n8V.Y..+I.^. 0000ab0: 487b 10e7 49bd 6623 35af 8bf7 1521 132d H{..I.f#5....!.- 0000ac0: 56af 5002 ae7b d6de dfb7 7603 fbe9 fa22 V.P..{....v...." 0000ad0: 397c 06ff 556c f8ff cf0b 0a64 6fec cf3e 9|..Ul.....do..> 0000ae0: b71a 5580 044f 705f 50f4 435d 6f54 0473 ..U..Op_P.C]oT.s 0000af0: b6b2 a795 100f 75a7 b805 c41c ced3 9937 ......u........7 0000b00: d405 0b00 3193 61fa 679a 376b 9c23 5e8a ....1.a.g.7k.#^. 0000b10: a847 eab0 7fd7 9d30 bc6d 4c38 9dc4 cad1 .G.....0.mL8.... 0000b20: 8bf8 8a25 ab6f 9a89 2d62 7fdf 19b3 a0fe ...%.o..-b...... 0000b30: 6d4c 3523 b9f8 5520 81f4 af0d d124 686c mL5#..U .....$hl 0000b40: c940 a9d6 fdd4 5064 c555 edd9 caef 2e01 [[email protected]](/cdn-cgi/l/email-protection)...... 0000b50: 4508 dd1e 569c ea47 4df5 6540 06cf d471 [[email protected]](/cdn-cgi/l/email-protection) 0000b60: 896f 0b0b f580 faf1 2e09 24e2 8ebb 0ad2 .o........$..... 0000b70: 1281 578d 0080 df0b 0ca3 83b1 6100 c212 ..W.........a... 0000b80: 177f 20a2 df7d d8a5 0b89 75d8 6877 f594 .. ..}....u.hw.. 0000b90: 59cd 965f 39a6 2aa7 86f7 23f9 0324 6e10 Y.._9.*...#..$n. 0000ba0: fd7c 8cd8 49a0 4da7 f5db e519 72ff ef17 .|..I.M.....r... 0000bb0: fc87 6542 c1b7 9edb ffef 04bc a4d6 4349 ..eB..........CI 0000bc0: ce6e 2c89 e5b2 e40b a586 418c 92c6 ff80 .n,.......A..... 0000bd0: 8e2b 8190 7d56 919b 3bef ffac 26b3 9f58 .+..}V..;...&..X 0000be0: 86ad f0dd e900 a3fa 7c2b 783c 97af cb9b ........|+x<.... 0000bf0: 9620 cce5 b96a 78a3 c22f ff87 5506 e798 . ...jx../..U... 0000c00: b412 7c0f 415c 9c7c ce10 6016 eaee eba4 ..|.A\.|..`..... 0000c10: 1604 feed 9a93 eba5 ea30 d5b7 8540 8003 .........0...@.. 0000c20: 2b67 ba93 4598 ef3b 804d b184 fc7d 1e38 +g..E..;.M...}.8 0000c30: b746 88ae 85c4 0b65 ee1e 75f3 2ba7 10d4 .F.....e..u.+... 0000c40: e306 fffe a9c0 39af a255 1c22 8a02 47a7 ......9..U."..G. 0000c50: 189f a7a6 f451 6afc 3402 dc8b 101a 9350 .....Qj.4......P 0000c60: 36cc 638f 82ba e526 5aa5 4f57 89a9 0dfa 6.c....&Z.OW.... 0000c70: 1dda 2d00 5477 0865 6785 6ded 4119 acb7 ..-.Tw.eg.m.A... 0000c80: 0841 5107 5042 59cd b8b2 d543 c80a b4ff .AQ.PBY....C.... 0000c90: 21c8 c9e0 5b49 01fa 9b2d 79b6 dbb0 2c10 !...[I...-y...,. 0000ca0: 1428 e91c bd3b 3f1f 80c0 cf62 74ba e7a7 .(...;?....bt... 0000cb0: 7809 d02d 5a28 bc2b ea9b 6776 3cde d6de x..-Z(.+..gv<... 0000cc0: ef64 5a09 24f3 8ec3 1c91 bf49 6a71 bc51 .dZ.$......Ijq.Q 0000cd0: a988 0925 328b f7f5 00aa f891 4ea3 1291 ...%2.......N... 0000ce0: f760 e230 091b 816a 4e95 0fc9 cca7 b849 .`.0...jN......I 0000cf0: 289b 0e61 1824 a1df ff83 916d c3f0 8abb (..a.$.....m.... 0000d00: 8323 eecd b507 787f be0d 6126 6cb3 b529 .#....x...a&l..) 0000d10: c7a3 0b81 982f 5a7c d3a7 dff9 a859 3fe4 ...../Z|.....Y?. 0000d20: f74d a4d6 a5fc 26f4 7584 0500 a17b 07c6 .M....&.u....{.. 0000d30: 1145 4a3a 0c00 580b bebc 005f 9530 0120 .EJ:..X...._.0. 0000d40: 0d94 1f04 56c8 bb61 bd71 9455 816e 719b ....V..a.q.U.nq. 0000d50: ff66 7e3b 96cd 0180 be7b afee 6690 b67d .f~;.....{..f..} 0000d60: febb a3a4 b6b7 00c2 d931 c192 a251 2db0 .........1...Q-. 0000d70: 10b7 29bc 78f4 cc00 46a5 0156 4723 8fb1 ..).x...F..VG#.. 0000d80: db88 36eb 3bf8 3758 59f3 7ba4 2af3 0f98 ..6.;.7XY.{.*... 0000d90: 8b80 ff80 5328 907b 0aa1 a188 2fe9 e8f0 ....S(.{..../... 0000da0: 6b6b cf72 26ac dfff b500 2fe4 f5fd 5fe2 kk.r&...../..._. 0000db0: ce10 68f6 58be 618c ff0e 49c5 62ee fcef ..h.X.a...I.b... 0000dc0: 0c4a 5a01 ca79 66ca f419 3523 a792 2f03 .JZ..yf...5#../. 0000dd0: d5b9 5327 6893 9738 d20e 6c12 b30b 19e6 ..S'h..8..l..... 0000de0: 99f9 33fd bf61 4d35 3bc3 d430 6a00 747f ..3..aM5;..0j.t. 0000df0: 50e3 da51 7729 f645 db09 01cf 3cf0 e5ec P..Qw).E....<... 0000e00: eaaf 4cec 8b9f f9eb 5665 6ccf ff00 d751 ..L.....Vel....Q 0000e10: 35c9 4cb0 9b45 e430 fcf2 0f71 7a69 65d2 5.L..E.0...qzie. 0000e20: 109f 6cdd e1c9 b900 b35c 2f29 9910 73c9 ..l......\/)..s. 0000e30: 0f5b 0579 e70c 0a40 89f5 b422 00b0 61a0 .[.y...@..."..a. 0000e40: 6d49 65c8 933d c9b2 0e1e 014b 47b8 79d7 mIe..=.....KG.y. 0000e50: 7d69 56df d132 88c9 d65a 2dfa c444 4230 }iV..2...Z-..DB0 0000e60: 5c60 2a84 7520 3388 528f 1773 a89c 46b3 \`*.u 3.R..s..F. 0000e70: 11f8 9db0 3154 fee2 1083 a693 dc22 a563 ....1T.......".c 0000e80: 9f93 f195 56d6 5a10 7ef5 6d03 c69b 12cf ....V.Z.~.m..... 0000e90: d0b0 2753 8aa6 3dd2 71ef 6c51 ea45 ffff ..'S..=.q.lQ.E.. 0000ea0: 0d21 8fbd fd5c efc7 9bb0 6204 4012 00f7 .!...\....b.@... 0000eb0: e500 a3d6 de7e 5e1d 5373 4028 3442 7bf6 .....~^.Ss@(4B{. 0000ec0: ffdf d459 a8b3 36c8 76e8 b897 04c0 57cf ...Y..6.v.....W. 0000ed0: 4895 e7e6 2541 1109 10d6 7ab7 3032 45d3 H...%A....z.02E. 0000ee0: 01d4 f94f d87e 66e7 c208 8ffd ebae ccd8 ...O.~f......... 0000ef0: 627d ffef dbe8 497e 9446 bf03 78c4 26e6 b}....I~.F..x.&. 0000f00: 67d6 f5ff 9fca 0228 d6c8 659f f8bf cafd g......(..e..... 0000f10: 2206 1dff db2b 9742 84ee b4aa 5f50 74a2 "....+.B...._Pt. 0000f20: ea49 d985 961d 9a7a d370 43d6 3442 0a01 .I.....z.pC.4B.. 0000f30: 50a1 4e8f 84c1 fc86 0652 093f 622e 982a P.N......R.?b..* 0000f40: 3003 12eb 30df a81f bb5d a849 633e 71bb 0...0....].Ic>q. 0000f50: 7204 7d57 2556 52e2 06ce 49bc ae2a d4bd r.}W%VR...I..*.. 0000f60: b4ad 7c5e 9b3e 26c3 fd92 5b84 d559 3e7d ..|^.>&...[..Y>} 0000f70: 531c 52cc 99c9 d675 eef2 0482 1f9e d9bf S.R....u........ 0000f80: 1b19 e6a2 b34d 7995 0c30 180a 54e0 2c84 .....My..0..T.,. 0000f90: 36a9 4d18 45f0 6ba6 0536 f986 fcdf 0b1e 6.M.E.k..6...... 0000fa0: ba4a ebc5 dcfe c67b 27a3 2782 5096 b626 .J.....{'.'.P..& 0000fb0: 1dcc 5ead 6edb 7e8c a535 ad79 93a6 8efd ..^.n.~..5.y.... 0000fc0: 715e f17a 47fa 1273 9a07 f375 44ca 3926 q^.zG..s...uD.9& 0000fd0: 9d50 09a1 4019 18b7 9d45 d425 78ff 5aff [[email protected]](/cdn-cgi/l/email-protection).%x.Z. 0000fe0: 07b0 8c28 accf 0502 abfc ffdc 9098 cf0b ...(............ 0000ff0: 1078 d891 0159 91c2 efef c245 b341 c578 .x...Y.....E.A.x 0001000: c594 fdf8 dc5c a0e2 affd 4d11 7e04 c8a9 .....\....M.~... 0001010: 2000 2372 b86e 0430 adfd 30a0 7afb e6ff .#r.n.0..0.z... 0001020: 0e91 1af5 b07f 78a9 b378 8f78 9181 7994 ......x..x.x..y. 0001030: 0b10 948c 451d e291 832e f1ef b7c7 1402 ....E........... 0001040: f59f 0438 00b2 a6e6 9089 598e 2b1e 966a ...8......Y.+..j 0001050: 6596 1621 fd38 e771 0731 758a a084 e112 e..!.8.q.1u..... 0001060: 333a 3438 07d0 b8ff 7bec 5f0e 6a7a f907 3:48....{._.jz.. 0001070: 97ac d560 9e73 9838 1d0c e2e1 de28 6ad7 ...`.s.8.....(j. 0001080: 0476 ba0e 1179 c68e 9cff 72ec 2e31 370e .v...y....r..17. 0001090: 120c 109a 65e1 9a32 c5aa f02f 9519 ac66 ....e..2.../...f 00010a0: 1421 a600 d2e8 e995 6c88 3b87 1294 9708 .!......l.;..... 00010b0: 0002 8953 bc10 26d9 4450 ac2c 6d3a 1167 ...S..&.DP.,m:.g 00010c0: 9985 643d adb2 ff0e bb24 016a 472a 6704 ..d=.....$.jG*g. 00010d0: b684 ab8a 53fa 88a4 2461 038b 8b97 d5da ....S...$a...... 00010e0: ff7a 65f5 81ac a214 e501 2751 4460 ddf4 .ze.......'QD`.. 00010f0: 8a65 9778 e2fe 4310 f347 f465 23ed 693b .e.x..C..G.e#.i; 0001100: 6fa0 88a8 d4e1 667f 3682 8815 4da6 e7b6 o.....f.6...M... 0001110: f311 4e88 cf56 4dcb 31ef 340d 7cfe c40c ..N..VM.1.4.|... 0001120: c24e 67dc 626a d074 a466 f202 b608 10f3 .Ng.bj.t.f...... 0001130: 7b88 b4d1 f19c 28e9 ffff 4e1d 240a 56f2 {.....(...N.$.V. 0001140: dffb 6040 c5a5 a6c4 5b27 c9fe 400a 60a9 ..`@....['..@.`. 0001150: 3f55 8ef9 0f00 bdde a51f c054 5312 5271 ?U.........TS.Rq 0001160: d007 284b cafb 9687 c16b 3c64 41e3 54e5 ..(K.....k<dA.T. 0001170: 18d9 db0c 6a10 fee9 f4e0 0bdd 614a 65c6 ....j.......aJe. 0001180: fd0d 92fc 41c2 f6bb abb7 c770 736a a770 ....A......psj.p 0001190: 6d4b cf35 000e 0230 7531 e707 b37e 219f mK.5...0u1...~!. 00011a0: f43d 0cc6 bc7b 6900 6555 1248 a063 e8df .=...{i.eU.H.c.. 00011b0: 2c30 17c9 e2eb fd5c 5ae0 5da3 ffff 2ce4 ,0.....\Z.]...,. 00011c0: 8875 2f0b da3a ca0b e4f0 ecff ae30 26a3 .u/..:.......0&. 00011d0: bae9 78ea 37b7 357f 987b 5380 efff ffff ..x.7.5..{S..... 00011e0: 5c97 97e8 ff79 0502 56b8 83bc 5851 7a9d \....y..V...XQz. 00011f0: aabf 5a83 8053 13bf f6ff 7eca 5647 c59a ..Z..S....~.VG.. 0001200: 407f 0edc d8dc 861d 665a 5a20 9a08 d546 @.......fZZ ...F 0001210: d827 1abc 4047 59d8 b4b8 97d0 b490 fdb5 .'..@GY......... 0001220: c799 03dd 6970 8cce da30 b004 803f 07e7 ....ip...0...?.. 0001230: 0ddd f93a ccc8 00f0 d65c f9ff 8f14 09df ...:.....\...... 0001240: fb09 5010 90d0 b20d da0d d3ff 74c4 5158 ..P.........t.QX 0001250: 0f84 d591 7332 fffc cda6 5d00 0472 2318 ....s2....]..r#. 0001260: e28a c390 77eb 90e0 c411 e26e 1556 273f ....w......n.V'? 0001270: f2f5 ca02 75fa f75d 6ba0 67ab 3136 3757 ....u..]k.g.167W 0001280: 5e43 b4d5 6140 7a6b 8bab 5403 4808 9fda ^[[email protected]](/cdn-cgi/l/email-protection)... 0001290: 30f0 a575 5e52 3cb8 9a9f 174b 1dc3 5601 0..u^R<....K..V. 00012a0: 8233 b62e ac67 b27f b6f0 9fbd 28f3 f9ef .3...g......(... 00012b0: 0b5a 0cf6 ad4a 7888 95ef 101b feae c3f1 .Z...Jx......... 00012c0: 08ba e68e 6310 f3c7 4f32 140c 62fc df9b ....c...O2..b... 00012d0: 2a18 54d6 83ae 1bb2 49f8 a9ea 70d7 1107 *.T.....I...p... 00012e0: a22b aec9 c6a7 9fba 7edf 1f73 6e2d 8294 .+......~..sn-.. 00012f0: aa6a 26b8 ab60 0120 e3d0 9a10 d4e4 5457 .j&..`. ......TW 0001300: 841f 0422 a893 b400 e60e 2450 084f 6120 ..."......$P.Oa 0001310: 28f8 fff9 708e d1bb 04cc 4afc 2afc ef0b (...p.....J.*... 0001320: 72cd f02b 4db8 3deb 30df e026 8404 0060 r..+M.=.0..&...` 0001330: d008 0def ef9c 9431 9f0b 3b13 d110 51e3 .......1..;...Q. 0001340: d9e8 01d4 b882 9c0f 0ce4 10a2 300f fc0f ............0... 0001350: 1c9e 8b10 56cf dc7c cb6f 7215 163a ff1d ....V..|.or..:.. 0001360: fd3f 6bcb be03 a199 2d83 2028 c7e0 acfa .?k.....-. (.... 0001370: 3f82 d00e 35cf 1a73 b289 8ef2 ee96 94bc ?...5..s........ 0001380: 14b6 7076 6577 0a84 5906 ff0b c791 85cb ..pvew..Y....... 0001390: f7bd a51c b7da 1805 5115 fc0f 82fd dfe9 ........Q....... 00013a0: 0000 0075 40c1 aef2 adb5 3200 1164 169b [[email protected]](/cdn-cgi/l/email-protection).. 00013b0: 0f05 a4fa 5c4f 6ead 6a08 dff1 7f69 4c13 ....\On.j....iL. 00013c0: 0be6 57e0 a4d3 6a05 2041 68d3 10ff 7095 ..W...j. Ah...p. 00013d0: d13b 0536 de5e 23ea 1718 34e1 0c46 075c .;.6.^#...4..F.\ 00013e0: bc95 31ae 9c14 5103 f0ff bfd2 441d 2bf6 ..1...Q.....D.+. 00013f0: 2aa8 0500 535b f35a 7cf9 febc 3b01 c6a2 *...S[.Z|...;... 0001400: 6cd6 1330 5300 d118 930a eefa b5b9 fb77 l..0S..........w 0001410: 6fab f289 f90e a505 0029 5919 704e 77b5 o........)Y.pNw. 0001420: fb4d 78dd ffff 412c 4aca 0270 78f3 4b69 .Mx...A,J..px.Ki 0001430: 9fb7 0ed1 f679 03c6 1448 2039 6868 d290 .....y...H 9hh.. 0001440: d5f0 dc9a 465e 0000 ff74 6a35 07a0 b0d0 ....F^...tj5.... 0001450: ff18 0cd8 2601 43d3 ff72 1451 0ba1 7bea ....&.C..r.Q..{. 0001460: 7d1e 9e0c }... ``` ## Explanation ### Encoding the dictionary The dictionary's construction is very simple. I take the hexadecimal MD5 hash of the color name and concatenate the second through sixth hex digits (which happen to be unique for each color) with the 6-digit color code. I join these into a single string of 10,439 hex digits. Then I convert this into the equivalent 5,219.5 bytes, padded with zeroes on the right for an even 5,220 bytes. Funny thing: I tried Gzipping the dictionary and even `zopfli -i100` produced a file 40 bytes *larger*. Just for fun I [calculated the entropy](https://stackoverflow.com/a/990646/179125) of the binary dictionary and it's 99.8% (versus, for example, `rgb.txt`'s 61.2%). Not bad! Here's the code that generates the dictionary: ``` require "digest" def hash_name(name) Digest::MD5.hexdigest(name)[1,5] end names_colors = ARGF.drop(1).map {|ln| ln.split(?#).map(&:strip) } # => [ [ "cloudy blue", "acc2d9" ], # [ "dark pastel green", "56ae56" ], # ... ] keys_colors = names_colors.map {|name,color| [ hash_name(name), color ] } # => [["b9ca5", "acc2d9"], ["8ff06", "56ae57"], ...] dict_hex = keys_colors.join # => "b9ca5acc2d98ff0656ae57..." STDERR.puts "dict_hex: #{dict_hex.size} bytes" dict_bin = [dict_hex].pack("h*") STDERR.puts "dict_bin: #{dict_bin.size} bytes" print dict_bin ``` ### Decoding and searching the dictionary This is the exact opposite of the above. First I convert convert the binary data to its 10,439-digit hexadecimal representation. Then I take the input string (color name) and get the second through sixth hex digits of its MD5 hash and use a regular expression to find those digits in the 10,439-digit hex string at some index divisible by 11 and return the subsequent 6 digits, which are the corresponding color code. For example, for the hash `b9ca5` ("cloudy blue"), the following regular expression is constructed: `/^.{11}*b9ca5\K.{6}/`. The `\K` operator discards the match up until that point, so just the last six characters are returned. [Answer] ## Perl, 7,375 bytes Stores slightly compressed data (`grey` -> `E`, etc) as compressed binary data, expands it into a hash and returns the matching key after replacing spaces in the input with `_`. I don't think it's that great, and am certain others will have much more intelligent methods for compressing the data, I might play with this more later on. ``` use IO::Uncompress::Gunzip qw(gunzip);gunzip\'<binary data>'=>\$_;for$v(qw{A/pale B/blue D/dark E/grey G/green I/bright L/light N/brown O/orange P/pink R/red U/purple Y/yellow}){eval"s/$v/g"}print"#".{m![/\w']+!g}->{<>=~s/ /_/gr} ``` [A reversible hexdump is available here](https://gist.github.com/dom111/beb1aa50f03322fea0c7f73fc422c21e) which was [generated using this script](https://gist.github.com/dom111/49afa19fab25b265cbc6e9445518e85e). ### Usage ``` echo -n 'baby shit brown' | perl xkcd-colours.pl #ad900d ``` [Answer] # Ruby, ~~12131~~ 12030 + `-p` = 12033 bytes Byte count is after replacing `<compressed text>` with the raw paste data in <http://pastebin.com/xQM6EF9Q>. (Make sure you get the raw data because of tabs within the file) I really could shrink the text further but I've been at it for a few hours now and I need to sleep. Input is a piped-in line from STDIN without a trailing newline. Adding in trailing newline requires +3 bytes by changing `($_+?\t)` to `(chomp+?\t)`. ``` i="<compressed text>" %w"Bblu Ddeep_ R*ight_ N*own Yyellow Tdirt Kdark Ldull_ Sdu} Qdusk Ee]ctric_ Ffaded_ G|een Iish A|ey Hlight Oor{g Ppa]_ Upurpl Cred Vvery_ -pink %ros ~sea .pea @egg ^burnt_ &baby ,poo =tea !t{ Mmedium_ $pa}el_ ;mud `aqua ?s{d >neon_ <lavend :gold +lime |gr ]le [mon }st {an *br".map{|x|i.gsub!x[0],x[1,99]} $_=i.tr(?_,' ').lines.find{|s|($_+?\t)[/^#{s[/[^#]+/]}/]}[/#.*/] ``` [Answer] # BASH + bzip2, 8058 6809 6797 bytes ``` bunzip2 -c c|tr -d "\t"|grep -F "$1#"|cut -d "${1: -1}" -f2 ``` Stored the original list to a file after compressing it, not sure if this is allowed. Call with: ``` sh ./colors.sh "shit" ``` [Answer] ## Python, 9360 characters Doesn't use any compression library. I'll leave it as a mystery for a little while how it works and then post a link to the technique. Of course it could be made shorter by storing the data in a binary format but that's an excercise for another time. ``` G=[int(x or 0) for x in "0 -949 -948 -945 3 3 -944 2 2 -936 3 -935 -929 -927 2 -923 -922 3 3 -920 2 -916 2 2 4 -915 -911 2 4 -910 -909 -906 -898 -897 -890 2 -888 -887 2 -886 -885 2 -882 -880 -878 -876 -860 4 -858 3 4 3 -857 -856 3 3 2 2 -853 3 -852 -851 -850 -849 -848 -846 2 -841 -839 -835 -834 -831 2 2 -829 -823 2 -822 2 -821 4 -819 4 2 2 -815 2 -811 -808 5 3 -807 2 -805 -802 -796 2 2 -794 2 2 -792 2 -790 -787 -784 -781 -779 -778 -777 -776 -775 3 2 -770 2 5 -768 -766 -765 -763 -762 -759 -756 5 3 -751 -748 6 3 5 -738 -737 3 2 2 -724 3 -722 5 -721 -720 4 2 -719 2 -715 -713 -704 -701 2 5 2 -697 2 4 -693 -691 -689 -687 3 -684 3 2 -683 -682 2 3 -681 2 -680 2 -675 2 -669 -665 -664 -661 4 -658 -656 4 -655 -647 3 -644 4 2 2 2 2 -642 -639 -638 2 4 5 -630 -628 2 2 -626 5 -624 -622 -618 -612 -609 2 -607 3 4 -606 8 -596 4 3 -594 2 2 2 2 -593 -590 -588 -587 -585 -583 3 -581 -580 -578 3 -577 -575 2 4 2 -574 -566 4 3 -565 -563 -558 6 -556 3 -553 -552 2 -551 -548 -545 -542 3 -541 -538 3 2 3 -537 -534 3 -525 -524 -522 2 -520 2 -518 -517 3 6 -516 3 -515 2 -511 4 -510 4 -502 -501 -500 -499 2 -498 3 3 -497 2 3 -494 -493 -487 -485 -484 -483 -480 -478 -477 -476 2 -475 -474 2 -473 2 -471 -469 -458 3 -456 -455 4 2 -451 -450 -448 3 -447 2 4 9 2 2 2 -443 5 6 -439 -438 -434 -429 2 3 3 -426 2 -425 -423 2 -419 3 -416 -402 2 3 -401 -389 -388 2 2 -387 -384 -381 -379 17 -374 -371 -365 -363 -362 2 2 -360 -358 -357 2 5 7 -351 -350 -349 -347 -340 -338 -336 -334 2 2 -332 4 -330 -328 3 4 10 3 -326 -324 2 -323 -321 5 -315 -314 -305 11 -303 -301 18 -292 2 -291 -288 5 6 -283 -281 -280 -278 -277 -275 12 3 -274 -273 6 5 -269 2 7 2 9 -261 -257 -256 -252 -248 4 -243 -240 -239 -238 -236 -232 5 -230 -228 -223 -222 -221 -219 5 2 6 -218 6 -217 -216 -206 8 2 2 -203 -201 18 -196 -195 7 -194 -192 6 4 8 -191 -189 3 -186 -185 7 2 -183 -180 2 -179 10 -176 3 -174 4 3 -172 -171 -170 8 2 7 -164 -158 -157 -155 -152 -146 5 10 5 -144 -141 9 -139 -134 5 -132 2 -130 9 -128 -127 3 -126 -125 4 3 -120 -116 -112 -105 6 10 4 2 -104 -103 7 4 -101 -100 8 8 -96 -95 -93 -92 28 -91 5 11 -90 2 -82 13 3 -76 7 6 -75 -72 -68 -67 -62 3 3 2 -61 -60 -59 -56 10 -55 -53 2 8 8 -51 -46 2 -45 6 -44 2 4 -43 -42 2 -40 9 -37 -36 10 2 4 6 -35 3 2 -31 5 14 11 -29 -24 3 -22 -19 -17 -10 -8 -6 -1".split(' ')] V="748500 fdff52 3b638c 0b5509 71aa34 eecffe c8aca9 75bbfd b1916e fa4224 cd5909 b7e1a1 ba6873 922b05 32bf84 31668a 6b7c85 fdff38 b04e0f 875f42 699d4c 03012d 647d8e cb416b c9ae74 0bf9ea 63b365 4b006e 02590f 885f01 1fa774 a6fbb2 ff5b00 b790d4 8cff9e 6b4247 ff6f52 fce166 90fda9 c9d179 d6b4fc c94cbe 419c03 017374 ffff84 41fdfe d0fefe 889717 cb0162 a24857 0a437a a552e6 d3b683 53fca1 464196 0cb577 6832e3 ff000d 598556 6258c4 c0fb2d 1ef876 c9643b 35ad6b 1d5dec 947e94 015482 65ab7c b2713d 920a4e 59656d ffffc2 fcfc81 cba560 03719c 8b2e16 cc7a8b c5c9c7 bf9b0c 08787f 25ff29 7a6a4f 3c4142 653700 005f6a 7a5901 a90308 afa88b 06470c d1b26f 343837 c0fa8b ffffcb 9dc100 7a9703 0c1793 befdb7 4da409 f075e6 152eff c4fff7 9ffeb0 658d6d 978a84 fa2a55 070d0d b59410 8a6e45 a4be5c 4984b8 8f99fb 25a36f 3d0734 ff9a8a c6fcff ff6cb5 ae8b0c 01ff07 7e4071 fef69e 8e82fe 8d8468 fd411e c85a53 ffe36e 5539cc 76fda8 acfffc d5ffff ad0afd f9bc08 ffb19a bf9005 3d7afd ff073a fff9d0 526525 1e488f b9a281 c071fe c88d94 5729ce 5f9e8f b2996e a2bffe d0fe1d faee66 c875c4 4f9153 fddc5c d99b82 b79400 a55af4 e4cbff ec2d01 b36ff6 280137 7f5e00 8f7303 1805db a9561e f0833a 95a3a6 030764 50a747 fe7b7c fea993 d7fffe c6f808 efb435 9be5aa c1fd95 9e0168 276ab3 9900fa 0d75f8 4b5d16 fffd01 aeff6e 7bb274 c4a661 5a86ad b9cc81 0b8b87 20c073 3f012c f10c45 3c9992 ac9362 047495 042e60 a5a391 380282 0e87cc 3b5b92 94b21c c04e01 001146 638b27 7d7103 fcb001 4c9085 fc2647 667e2c fffe40 fe4b03 033500 ff474c caa0ff ff9408 ff964f 8cfd7e af884a 7f5112 4efd54 b8ffeb f6cefc 749551 23c48b 0652ff b6ffbb fed0fc b75203 96f97b 990147 5edc1f beae8a fffe7a 017a79 436bad bc13fe 985e2b 214761 004577 0ffef9 770001 475f94 b5c306 20f986 75fd63 48c072 1bfc06 bcf5a6 fb7d07 6c7a0e da467d 2a0134 8b88f8 2baf6a 516572 fe420f b1ff65 430541 26f7fd fdee73 d5174e 06b1c4 a484ac a0febf c0022f fe2c54 886806 ac1db8 ff63e9 983fb2 ff796c 90b134 10a674 26538d 856798 874c62 76cd26 ba9e88 fdff63 c8ffb0 1d0200 661aee fe019a 029386 fdb915 ef1de7 04d9ff 7ea07a fafe4b 411900 efc0fe ff028d f7879a 13eac9 a2653e bcecac 53fe5c a8415b fbdd7e 98568d 94a617 fbeeac ccad60 4e0550 0b4008 f43605 0cff0c c45508 c1f80a 9b8f55 33b864 bd6c48 ff69af b25f03 fb2943 acbb0d 85a3b2 734a65 99cc04 020035 c95efb 9f2305 21fc0d b0dd16 b0054b cbf85f 1fb57a 8fb67b 7b5804 bf77f6 0343df 044a05 bffe28 706c11 966ebd 6fc276 d0e429 2242c7 b7c9e2 ae7181 6488ea 341c02 2cfa1f 6d5acf 056eee 758da3 e50000 825f87 a6c875 a442a0 f0944d 876e4b f5054f c77986 9cbb04 6140ef 89fe05 4e7496 ccfd7f d9544d e78ea5 6e1005 40fd14 544e03 3778bf 12e193 acc2d9 be03fd 82cbb2 db5856 c7c10c 6ba353 f1da7a 4f738e fa5ff7 c7ac7d 607c8e 76ff7b 6a6e09 155084 137e6d ddd618 ffffd4 751973 789b73 db4bda fd8d49 658b38 cffdbc f97306 08ff08 bccb7a fffcc4 ef4026 703be7 01a049 8f1402 632de9 016795 6f7c00 cfaf7b 5a7d9a bff128 80013f a8ff04 c0737a ceaefa 9aae07 05696b ffc5cb 0cdc73 d767ad 3f829d acbf69 cf0234 9e003a cea2fd 34013f fffd37 a4bf20 9a6200 840000 ad8150 ff0490 b9ff66 fe02a2 ffe5ad 8ee53f bdf8a3 c1c6fc 089404 107ab0 696006 742802 c87606 e03fd8 c2b709 6a79f7 014d4e c14a09 9d5783 fb5ffc 750851 929591 42b395 7f4e1e 9dff00 21c36f 96b403 154406 ac7e04 580f41 29465b 78d1b6 735c12 d4ffff 698339 6c3461 952e8f 01889f 610023 010fcc f504c9 05472a 8f8ce7 feff7f aaa662 5ca904 c48efd 9d7651 b66325 6b8ba4 dfc5fe 11875d a66fb5 2fef10 054907 c9b003 000435 cf524e c8fd3d 02ab2e 3a18b1 fec615 ca0147 15b01a 35530a 021bf9 ff7fa7 b17261 448ee4 2000b1 719f91 cb9d06 2ee8bb ffd1df 887191 3eaf76 1b2431 002d04 86a17d aa2704 014182 c83cb9 7b002c fac205 5c8b15 d5ab09 fdde6c 5f34e7 017371 89a203 019529 7f5f00 3d1c02 fdb0c0 b26400 005249 5e9b8a ffffe4 a7ffb5 f1f33f a8b504 4b6113 ca6b02 ffff14 aaff32 1e9167 ed0dd9 b16002 040273 048243 ffa62b fc824a 363737 fb5581 2b5d34 2dfe54 fe828c 536267 916e99 ab7e4c c20078 aefd6c d46a7e 7f7053 7f2b0a bb3f3f f7022a fdaa48 cb7723 805b87 5b7c99 c2ff89 c69c04 9db92c 9a0200 0804f9 0add08 9d0759 0165fc a50055 a87900 758000 0203e2 8d5eb7 287c37 7efbb3 fdfdfe de9dac d6fffa 9c6d57 51b73b d1ffbd b66a50 8af1fe e17701 fff39a 54ac68 2976bb ad03de 673a3f de7e5d c7fdb5 5cb200 4e518b fe0002 fff4f2 ca6641 4b0101 cafffb cfff04 645403 a0025c 490648 3c73a8 60460f ff7855 ffb07c ac86a8 030aa7 960056 720058 01386a f29e8e 3f9b0b 7d7f7c 5cac2d f6688e 01f9c6 6f7632 dbb40c 7bf2da b00149 0aff02 a2cffe 8cffdb af6f09 98f6b0 b29705 c79fef 90e4c1 04f489 fdc1c5 be6400 cd7584 fffe71 61e160 fcf679 3a2efe 388004 c292a1 980002 eedc5b 0a5f38 95d0fc 9b7a01 8fae22 fd5956 f4320c 738595 769958 a2a415 677a04 c3909b ff0789 ac4f06 fedf08 6ecb3c fc86aa 63f7b4 ac7434 2bb179 045c5a ffff7e 6f6c0a 9f8303 f36196 ab1239 63a950 7bc8f6 d648d7 b1d1fc 069af3 ca9bf7 ceb301 86775f 9a0eea 533cc6 74a662 b1d27b 70b23f a87dc2 017b92 feb308 7f684e 80f9ad 548d44 9c6da5 964e02 894585 d2bd0a c3fbf4 7b0323 00555a fffd74 601ef9 a9be70 507b9c 5170d7 373e02 728639 13bbaf c69f59 58bc08 00fbb0 d3494e befd73 5684ae c44240 a88f59 8b3103 24bca8 88b378 fdb147 fe86a4 01c08d 4a0100 06b48b b5485d 9bb53c 937c00 a83c09 f2ab15 8eab12 e6daa6 a6814c ffda03 76424e cf6275 1f0954 b0ff9d 77ab56 fefcaf de0c62 cdc50a 5fa052 a0450e 990f4b 9d0216 8e7618 d725de 8c0034 d5869d c87f89 606602 ffff81 d6fffe 028f1e e6f2a2 4e5481 fd4659 730039 ffb7ce 87fd05 05480d 0504aa b5ce08 01b44c b96902 ff6163 02066f 75b84f 2138ab 0bf77d ff724c dd85d7 77a1b5 ffd8b1 56ae57 a5a502 0a481e ffffff b6c406 ffc512 c2be0e 6dedfd be013c e2ca76 06c2ac fffa86 edc8ff 7ebd01 00035b 40a368 02c14d 87a922 00022e 997570 ffab0f 748b97 fe46a5 ca7b80 000000 c760ff ab9004 866f85 f4d054 d0c101 9e43a2 c4fe82 7a687f 6241c7 f8481c be0119 947706 a8a495 820747 850e04 3c4d03 7bfdc7 fffd78 7f8f4e 000133 fe83cc c9ff27 c27e79 d1768f fc5a50 a5fbd5 82cafc fe2f4a 2afeb7 36013f 728f02 8ab8fe ce5dae 9cef43 014600 02d8e9 062e03 61de2a 39ad48 910951 84597e 3b719f 49759c ff81c0 8fff9f ffdf22 ffa756 7af9ab 680018 a9f971 5d1451 009337 ad900d 1f6357 b27a01 5d21d0 ffbacd 82a67d 96ae8d 657432 929901 3c0008 f7d560 ffad01 a0bf16 76a973 d8863b 8f9805 df4ec8 87ae73 fff917 a13905 65fe08 feb209 3e82fc 826d8c 0a888a 8ffe09 cb00f5 f5bf03 aa23ff 8756e4 6e750e 0339f8 3d9973 ffcfdc cdfd02 9af764 fd798f 410200 7ef4cc 35063e ffb16d 2c6fbb ffffb6 bfac05 a57e52 fd3c06 dc4d01 696112 01153e 1f3b4d 0c06f7 510ac9 89a0b0 7e1e9c 9dbcd4 9a3001 3ae57f 828344 b9484e b1fc99 d5b60a 380835 665fd1 2a7e19 836539 05ffa6 d94ff5 d58a94 ada587 247afd ffb2d0 bbf90f 5d06e9 ff08e8 69d84f 667c3e 0f9b8e 2e5a88 c74767 a88905 94568c 77926f 6f828a c65102 94ac02 98eff9 658cbb 4b57db 5e819d bdf6fe 040348 a75e09 650021 b7fffa 9b5fc0 cb6843 04d8b2 feffca fe01b1 00ffff af2f0d 84b701 d90166 18d17b 895b7b 02ccfe adf802 d8dcd6 a00498 a03623 fffeb6 8c000f 5a06ef 56fca2 0485d1 fcc006 9e3623 b2fba5".split() h=lambda d,s:hash(s*d) x=raw_input() d=G[h(1,x)%949] print '#'+(V[-d-1]if d<0 else V[h(d,x)%949]) ``` Explanation: Uses an adaptation of the code from <http://stevehanov.ca/blog/index.php?id=119> to generate a minimal perfect hash lookup from color names to color codes. [Answer] # Python 3, 4927 182 code + 4745 data file ``` from hashlib import* def f(s): k,b=md5((67*s).encode('ascii')).digest()[5:7],open('X','rb').read() for j in range(0,4746,5): if b[j:j+2]==k:print(('{:2x}'*3).format(*b[j+2:j+5])) ``` Theory of Operation: `md5((67*s).encode('ascii')).digest()[5:7]` is a perfect hash from the color names to a 2-byte value. The binary data file is simply a list of 5-byte chunks--2 byte hash and 3 byte color. The code hashes the input color name and searches through the data to find a match. The code to generate the binary file: ``` ba = bytearray() with open('./rgb.txt','rt') as f: next(f) # skip header line for name,code in (line.strip().split('\t#') for line in f): key = md5((67*name).encode('ascii')).digest()[5:7] ba.extend(key+bytes.fromhex(code)) with open('X', 'wb') as f: f.write(ba) ``` Here's the code I used to find a perfect hash. Nothing fancy, just three nested loops: number of time to repeat the name (e.g., 'blue', 'blueblue', ...); the available hash algorithms; and the offsets in the hashes. It prints out combinations for which there are no collisions. ``` for i in range(1,100): for hashname in hashlib.algorithms_guaranteed: hashes = [hashlib.new(hashname,(name*i).encode('ascii')).digest() for name in names] for j in range(h.digest_size - 2): if len(set(x[j:j+2] for x in hashes)) == 949: print(i, hashname, j) break print(i) ``` [Answer] # Python 3, 296 + 3960 = 4256 bytes I didn't use `gperf`, because it would be too boring to simply repeat that trick. Instead I did a brute force solution from scratch and therefore the size is not optimal (but not too bad, too). However I found how to compress colors more efficiently — they are sorted and aligned to 4 bytes, LZMA happens to take advantage of it. (the colors are compressed to 2180 bytes) To find the color by name, a 15-bit hash function is used. Theoretically it could be found with fewer bits (numbers 0..949 can be encoded with 10 bits), but my computer could not find anything better, it's too much work. The code takes input from stdin and prints the answer. The code: ``` import codecs,hashlib as L,lzma,sys h=L.md5(b'\x05_h'+sys.stdin.read().encode()).digest();f=open('a','rb');H=int.from_bytes(f.read(1780),'big') for o in range(0,949): if H>>(o*15)&32767==(h[0]<<8|h[1])&32767:c=948-o;print('#'+codecs.encode(lzma.decompress(f.read())[c*4+1:c*4+4],'hex').decode()) ``` Data file (binary, should be named `a` and placed in the same folder): ``` 0596 61b2 005c 634a f47d 2c12 d5d2 e156 435a 1931 17a2 5f7b 547c 5a5b 8c40 0acd fe13 3da6 21b3 bafb b79b 71ea 4af2 70e2 6195 6838 516f c5b7 e08f 6087 4665 cea9 8901 f8a2 b408 d333 1d7a 17b1 b35f 0a22 2aed 9f71 1fdc ac65 8991 2c3b 3b50 2578 c194 7990 03e6 d333 a368 7445 4992 8e1d 1b0b 882c 9614 4ec1 d71f 3ba4 b483 ce06 d3e9 7c09 ed11 2205 2a58 0fd3 f5a8 a573 3c7d fc68 9025 b0da 656a c642 cd1e d964 5197 3488 6794 cc78 df40 2818 d921 267f c056 c554 2c35 0514 e2b9 4c81 dd95 9cfa f2d8 dd0e 840e 2731 5530 ef3e 0b89 8320 4f88 e851 e2eb 5917 cf22 ff13 432f 5fbc 7cf9 0154 b7d7 12af 7e91 d2ed 8fad 4381 21f0 2973 ca7a 60ee b6af b2a4 1817 7fe9 6f9e 1ba3 5330 15bd 858b 8491 3436 e90b b469 b8c3 ed4c d840 1a04 73c8 3788 1ffc 4c2e 4e9f 6f53 7668 7b26 b323 80a5 0ae3 18e6 5106 bff6 6eb5 ddf7 480d 1b3e dad4 be9a e831 9507 4675 d18a 38ef b3a5 c504 fa83 53f4 0ed0 9112 4c7b 597a ac0f e174 8546 2bda 6344 e515 5aca cb14 eeba c12d ea91 e55c b157 c60d 635c afc8 c35a 99a0 3c54 acdd 1edb 65e8 edbc 32f3 df1c 55f9 aad0 fe4b b941 1d5b 88ac 8144 a737 ad97 73c7 b5c8 02c1 3df4 6c39 e9c5 c53f c350 135c b013 18fd 51d2 9e2c bdca 19c5 a15e bc53 c564 f4c6 c0b7 9bb3 da22 230b db66 f36d f675 9732 1b54 3905 65cf dca9 087b 4675 cfaf c0df af8a a30a f25a 336b 4c8c 1938 0f9b ad95 12a7 60fa a29a d7f9 8d4e 61fe 9193 58b7 1af1 d836 0709 ddf9 3e1d c5e2 4f98 3c75 bdb5 fee6 0128 a2c4 8578 ff4d 50e7 b8b3 e51f 9794 5b40 5031 a73e 313d 75c2 70da a5d8 3240 e68f 1eb3 215f 2286 ba27 5bee a32a f005 441e 18b4 6258 91c8 4190 65b1 a286 a800 8607 0a94 4e37 0578 9ad4 6f86 3509 6f1a 1e10 35cc 1d41 dafa bd43 3f1e be88 246f d896 3267 28e8 4b6c 8f25 1aa8 cdbf bb34 c436 d926 6e75 54dc e196 f7f7 f169 29af 6d38 16fb 2fff a49c fa41 26c7 8b63 1f20 ccd9 2d92 fe40 cd0e bc75 5267 1f49 9c38 54fe 628c b06b 52c4 7c6a 97fc c63e 8491 0cc2 d242 d5cf 2e65 e740 2fa1 784a 8bf8 c28e 1a4d 6b5b 002a 7307 f7af 5908 0e37 5088 6818 d09d 5547 0a9a df0e 1169 d278 25b2 dd48 55d0 3cc8 cbf5 4315 1a3f c614 dfca 1188 13a3 969f 032d 90d2 1ef1 fd6e bd66 cdbb 73f4 c29d 3ab8 a3b4 462d 137c 1911 d5ef 9a43 2324 381b 612f 9611 35fc 7b6b 7e54 d906 f6ce 24bf dcc4 5c5b 0ebe a8ac 29d4 7378 3bc3 15f5 0c9d 77ce 9678 2985 69d7 dfee 4029 71af 427f 0c83 a3c1 d7aa 4387 bba1 eb0c a267 6755 ae83 2441 01af 8925 ec00 dc5f f711 3188 c89c 7964 e8b0 f58b 2cd3 da35 880e ac12 1554 8470 b476 27e1 a24d ddd8 778e ff7f cf57 f374 7206 01dd 9b42 85b3 5ab8 ad09 8683 d6c3 6be6 a686 80c8 cf6e 35a8 6d15 ab85 93c3 fdd4 d0c1 654c 18f8 55e1 0962 0e23 3fe6 8c92 a4a9 e5f4 4151 3ad6 2efc 580b 6e39 6126 6b5e 4866 a2dd 58b3 fd7a af63 f876 9c12 cb3b 1bfe 3820 21a5 e2f9 e030 1848 b562 9898 cc3a c9d1 7e93 6609 f15d 9fb1 cd79 c860 e903 7f72 b050 8e75 e997 9ebb 6b8a b81e 6b97 4cdf ac10 abdf 409b 60d7 9056 475c c4ab 1046 eb22 2529 aa8b e6e1 7e47 4bc2 3477 05ae e5ea 8dc4 ee2e 2eb1 396e face 9d8d 7430 9901 3564 0725 81f4 7175 40e5 e342 50f1 2bd2 ec8e 02bf 3609 5444 4896 b0f8 1c60 d02d e271 13ce 6420 dfbe 616c 5483 ca6d 7194 4665 9e38 7bce 0a73 5bc8 78a5 e95d fb2e eb75 80ed a5d5 9c1b 46ec f863 d042 f98d 4fac 54a2 6e60 bdf3 6b25 5abb e8c8 1ecf 09a4 4f8e b9ea 1377 c406 8376 a7c0 1c10 e1de 8a4b 3af2 74d7 00e2 dcc6 83c0 c09f 96a2 bb70 4ba6 8d2d 1a64 d860 c021 1d19 c8c5 6148 7968 59cb 45f3 42e7 2527 1b2d 702c 77da 7dda 11f0 1c3d 8cac 9894 d615 4907 682c cbbe 55ae d68e 1719 a6ab e257 d6f9 59d9 52b9 e174 38a4 1683 1de2 989e c7fd d39e 8e65 61c9 8831 1861 7acb 83bb b2e3 41f1 0ba6 ab70 dcb8 4624 a085 ac65 dd16 1e62 73e5 53f8 fc37 3a57 ead1 a4f1 0fd0 0ae7 34c6 7650 1eea ff24 f2b5 ef97 69a7 4939 b6b4 8588 2f4a ff84 1cf6 6f39 2b41 fa07 7f4b 14b0 b797 5ff0 ab83 2eae 23d7 f295 0644 951b 9b67 f55c 42bc d7f7 41ee 6b19 58d1 8028 557c 268f ae8d bb40 4f81 e342 2e37 3dc2 7fb9 e89c c7cd aad9 cacf 41bd 5883 8913 0e93 d4ed ae42 51f4 b6f4 377a 8fbf 5e05 456a c102 e454 2a81 8c05 2595 6531 0b9b 7f3f 6b79 c341 789c 1021 0c14 1189 f5e9 0c29 ef0f 73e1 5573 ddb8 371e 1be4 e4c1 979c 7486 e7b7 e736 c175 dd5c e2d5 181a ac40 3ed6 03cb c6db fb02 34b3 b4cc 3df8 797a 9ac5 f686 b1ed 7820 6a2f 34cf cc00 704f 28b0 2f81 bb66 5838 b4b0 c9c2 f386 2176 2906 f783 1e2d 9475 f98b b038 e795 dcf0 5eaa e9e4 fa53 f38a b4c8 556c 77e4 b3e8 690b e9d6 a42d 9786 ca76 b721 168c 1775 172f 1d7f 007b 77ad 7ce2 92f8 ea2c 7af5 ab57 0db6 b365 d9b3 21e2 29c0 613e 60e6 7aa7 b8f3 dc7c a2de dc6d f193 d279 04b8 3c3b 11b1 df6f 14aa a2cf 9561 2c64 8941 065c f053 f218 e8bf 37ad f147 273e 9977 d818 d2e7 d1b7 67e3 6fa2 5e44 51ec c802 2828 ecbb 9b46 bf77 9cad abe6 68de 448a 390e 6665 5aca 5d00 0000 04ff ffff ffff ffff ff00 0069 7ea0 e4ca 10fd 878f 79c1 bd67 f49f f836 a77f 61f8 4e3a bfd0 309e 8414 c871 2596 aebc 89cc 7aca e279 1fe8 7e84 271f 29d5 01ca e2b4 70b2 af51 e7dd dab2 3b6e 4a5e b512 1e84 b958 f918 75aa 8880 50d1 37ca bcc7 7308 d9c6 87b3 8a50 4f9f 7e02 f65a 7486 85a2 d114 f736 68cc 16df a508 2a36 9a4d c276 7836 0c0d dd95 2d5b 5728 2068 e911 1541 a2fd d39b e551 d3a9 3e47 96a1 d338 e7b1 7b25 3ba8 71aa a310 d0ef 2673 5a9c c9b4 d36e bd41 9bc7 eacd b630 2535 e65c 339c d9bf afe2 8949 505e 2286 7a66 87c5 9fe7 4410 e9c2 c7fd 705a b0e1 28e5 339e 4d92 2684 76a3 63f4 8967 ce46 014d 7c42 1c77 8ffa a36b b0a6 44f3 5962 b6fb 70e8 c7cf 53e8 a89b 7cd1 43e0 c7d2 61e3 7620 54d0 35bb eac5 160b 01fe 521a 1487 24fb b788 ba41 7e30 73b3 ac8d a95a b9e4 bd10 bc9a b1bf aadb 5856 c729 dc16 c52a 53b1 6004 17b0 35ca 374f 8f1e 803c a176 1043 864d b329 3a4c 6e80 fd25 aad2 5ed1 76a7 2b81 e400 04a9 6a0b c55b eb4c 6c8b c5c8 99b3 6d3c 0d92 f61b 58a4 66d8 cd73 2862 fc81 cdbe d47f 5b9e 5dee 7d93 7ec3 5245 7cb9 05f3 809e 7e41 f848 df58 d6ca 4248 0a4d c2ed 9181 d055 9732 c15c 1091 d3e1 b880 22c0 e7dd 67a3 f1e1 e469 deef 6aa6 e50a 7c89 6ee1 1eb7 c571 4c11 863d 512e 05a4 fc31 1a79 4ba6 4420 ef4a 0e77 a925 21e8 e4d5 81fe 527e ead9 da86 c76b a785 7a53 3a2d 409c 2041 236a 7fb8 3547 ccac e82e 9bc6 db79 670f 84c0 df27 d1c4 e26a 7b4a c951 d57e 4056 e0e3 1288 dc4d 63fa 6e62 489b 0eba 728d 2232 a9ca 123c 8b15 9bdc 6317 02c8 0a3f 07aa 03db 6a1b a906 d99d c007 bbf7 872a fc1f 4459 a7cc 29e5 3111 d4e4 c834 f9de 575a 9755 bd21 bd5f 7284 df3d a131 fd32 b8fa 6b64 3ac9 9a22 2459 8740 c50b 8634 627b 80d8 35e6 535e 4ee1 4641 1d18 55fa 8b51 a8d5 9a4f fd4e 856d d325 8bcd e336 f221 a987 48e1 0c7c 53e9 b022 6b28 6556 c4bc 7df7 2ac5 1f5f bb93 ef09 8a45 2439 dd91 fc30 d602 4648 e78e 24c4 abc3 a37f 5046 d3b7 7c1d 605f ca0c 27cb 7941 1256 d147 50b4 fe76 03e1 8617 c815 d9e8 a0b8 d05d 1b05 fcba 9902 4df1 8fb1 db82 eec0 9624 795b ab0d 8c01 7911 71a6 7484 cc1d 91d2 c56b 8ed2 9ca8 1cd3 24ff d705 d62d d826 44ef f7ab 4fb9 db61 7fb5 23c3 0b92 4737 03ba 01c7 5395 160d ed29 bef7 e5d6 19d7 a6af 4131 8f12 2bf0 46c3 d986 ccb5 a055 bc3b defc 545c 6632 c2a8 52c5 8a6a 9a9a 6ef4 dbdb d6f8 0d73 0c37 7128 7926 f11f 1d15 1edf d236 d74a 74e7 1692 d81d b000 1af1 cf7a 9fc2 be3a c831 34d8 edc8 a014 56cb ee36 3bdc 4e6d 529a 7b70 ecd9 0607 bbad 1f97 f0ff 0412 6c99 f7de e720 ecac bf33 06f4 b3b4 d2c4 ad05 4be3 c378 dd1c 1cb9 71de df25 c3c6 6540 3beb e667 e274 75b0 fe5f f1ad 5793 97ae 939d 3a7f 0c1d 3d25 ed5c 46d6 eda2 983d ba0c 852b 6075 4530 cdee 10fa 60af c929 8f24 2aab 8920 940a f61f 982e 469b a31e d7ab 9d5d d9d8 85f5 772f 84c4 c1d9 ccd7 101a f4e7 8357 2e27 2c63 0f42 c782 4bca f10b 7b79 feae 3f42 f04f ea3e a681 5e66 25cd aa6a 63fc 5ec7 65ce 639c 861a 5541 b9a1 61e5 3d8d 70de 336c 7d44 4342 cd24 6496 099f 90f1 8b1c bdfc 24d9 0664 cdf5 157d 617f 92c3 53d6 a0f7 b9ae 6e4c 3055 86bc 7625 8652 f9bd 5669 7758 f9c8 90c6 18ad 49a5 1471 06c6 fcdf 76ba 6153 bb95 d896 0d81 f084 51ec f334 179e 345e 5442 23db ee18 dd21 dc8f 4851 b71d 850b b60e e7cb 759c 317d ce3e 6516 0e99 50de cea2 71ce ce32 1a25 7ca8 0221 20f3 858d 0d84 b5d1 10f4 4780 28e4 9cf0 c3cd a486 7640 59ff 55bd c094 4bd4 06c8 bb63 d795 4fb3 5638 e927 96b4 0620 6625 b0f7 b16a 73ac 0e3c 9e3d b686 ea96 f404 b622 6952 9747 0bf7 f499 f822 19a5 b61c ce80 900d c04c 873b 6542 6410 6889 533b 4554 52e1 c159 a410 3ddb 3ed8 7435 b330 e9dc 449e 43d8 8c55 6f67 2fb7 539f 5072 d4e5 318b 0b8b 7738 00e4 be0b 7493 bf0d f104 046a 2191 9d01 ca30 df4b 20fa 0896 aa97 ce48 9679 9566 9e2b f3cb da81 3d90 fe67 30db a340 a6a6 9080 5fa1 f35b 8d9a a754 2f49 2d0d 58e3 e4ea 2759 e7d9 d9d8 cede 1366 31ce 19a0 8363 0fb8 b85c 66d0 281b 8528 d745 e454 a1a7 6935 bfc3 1c7c cbca 66d9 69ae b06a b6be fd51 61fa 02cc e09d 7a20 2c3e f0f9 6237 5791 6217 6b0e 6a21 fb74 f59e 66ff a666 a373 1ad3 8b19 7c88 8b38 f2b9 db02 5b6c 33d4 4cfe 22da 6562 9017 44c4 35c8 658a f47e bdfe a4d7 ddbf 430e a633 d5d6 a473 89af 411e 9448 5a54 c0b1 0256 666c 119c c662 aa1e a953 076b a9d3 a2f5 591d 1c7c 5102 7f37 8f43 ee2a 0626 8609 2fc1 1e21 ebcd e9e5 c6fb f19d a942 ddf2 0c84 9fa6 77fe 00bb c088 4731 6640 cc51 0a4d 62bf fb67 2856 069b 4265 c567 f20f 236d 9d11 8c70 56fd 8e56 a812 7e82 4837 0b3b d440 b0d1 73ba 65bb aa5f 0f85 5776 f621 7106 de0d 86e6 6aee 3012 b950 a545 b68e 2f20 ff6f bd07 a4eb d352 b407 3566 a875 2e42 2bfa bfcc 7c78 aec4 9aea 4331 4d6d 7c3a f930 78d9 9c21 59cb c996 2eaf 23a4 11ba 1de0 d647 62d5 da40 bb61 493b 6c68 b2b6 473e 35c1 fd86 8034 b515 1649 90d8 86fc 1204 63f4 83dc 72b4 9a11 5950 5f40 c70d a290 9784 3637 f826 af67 5380 0736 2888 f0a9 f99b 8012 b67e 21e6 3c0c 068e 3cb9 5266 f171 780b ca10 1546 0a16 c502 0de0 0cf8 970c fc6c ebd1 0ce5 0b8b 64e8 bedd cf24 dae9 a605 45b6 d562 ef1e ed6a 6ccd 72f8 0467 e0c7 1123 274e 5ee2 564d 5100 be4a 76ca 51d8 1e0d 65ba 4d24 4c64 8c32 0f51 7124 66f8 6daa 3b6d 90f6 46a6 16fc 7703 233f fa4b e769 a68c ec70 a4e0 0de5 ab0c e43f 6508 936f a197 2bdb 9a69 ef2f 817c e617 03f7 5aa8 c38e 3b9f d1d7 552d 16b0 0f96 686c 28db 2389 0146 cec1 4e65 4afa f1ee 8dbb 9868 a356 8fc3 f8d1 17fe 3f18 f649 9070 604a 1b1c e2d0 08eb 896e 2d39 d862 084f d371 3778 a0a6 2b42 f34d ab25 9350 41d1 7432 e20b abe0 ed70 376f c13f c4a7 da36 dd8c 5746 9409 1552 2042 f13d 9416 4075 f2d2 7e90 9366 e7bc f7e5 3d01 1947 b6a8 5ed7 040f ca1a b066 53bd b91b 8935 db90 f398 58e1 4c1f 9942 d102 a337 7bd8 d3bb 5646 082b dbac e0be 2ad2 f4ff 7952 9b56 0096 3f42 febc 8b19 2b53 4aaf 1b56 103d 6236 fa07 7ccd b51b 7a48 f24b 5830 1fff ec22 4000 ``` How to run: ``` $ echo -n 'very dark purple' | python3 code.py #2a0134 ``` [Answer] # C, 19,566 bytes A miserable 19,566 bytes. ``` #include <stdio.h> int main(int argc,char **argv){int m=0;char *t=argv[1];int c=0;while(c!=EOF){if(m==1){if(c==10||c==13){printf("\n");m=2;}else{if(c>32)putchar(c);}}if(m==0){if(c==*t){t++;if(*t==0){m=1;printf("%s -> ",argv[1]);}}else{t=argv[1];}}c=getchar();}} ``` Bog-standard C. The rgb.txt file is piped in through stdin. The colour to find is given as the first argument. So: `./xkcd "bright sea green" < colors.txt` Gives: `bright sea green -> #05ffa6` [Answer] # Java, ~~7,978~~ 7,435 bytes Code is 293 bytes, data is 7,142 bytes Golfed: ``` Object f(String k)throws Exception{Map c=new HashMap();ObjectInputStream i=new ObjectInputStream(new GZIPInputStream(new FileInputStream("c")));for(int j=0;++j<950;){c.put(i.readInt(),i.readInt());}String s=Integer.toHexString((int)c.get(k.hashCode()));while(s.length()<6)s="0"+s;return"#"+s;} ``` Ungolfed: ``` public class DecipheringXkcdColors { public static void main(String[] args) { Map<String, String> testData = new HashMap<>(); testData.put("light moss green", "#a6c875"); testData.put("straw", "#fcf679"); testData.put("dark fuchsia", "#9d0759"); testData.put("custard", "#fffd78"); testData.put("purple", "#7e1e9c"); try { for (Map.Entry<String, String> data : testData.entrySet()) { System.out.println("Key -> " + data.getKey()); System.out.println("Expected -> " + data.getValue()); System.out.print("Actual -> "); System.out.println(new DecipheringXkcdColors().f(data.getKey())); System.out.println(); } } catch (Exception ex) { ex.printStackTrace(); } } // Begin golf Object f(String k) throws Exception { Map c = new HashMap(); ObjectInputStream i = new ObjectInputStream(new GZIPInputStream(new FileInputStream("c"))); for (int j = 0; ++j < 950;) { c.put(i.readInt(), i.readInt()); } String s = Integer.toHexString((int) c.get(k.hashCode())); while (s.length() < 6) s = "0" + s; return "#" + s; } // End golf } ``` The file named "c" in the program is the result of the inverse operation of this program: take the hash code of each key in the input file and store it with the integer representation of the color value. That goes into an object output stream, a GZip output stream, then a file output stream. This program reads it through the inverse input streams. The default Java hash codes of all the colors are unique across this data set, so it makes a good 32 bit key in the hash map. The value is already an integer, so all that needs to be done is to format it correctly as a hex string, padded to six digits if necessary, with a hash mark in front. [Answer] ## Java, 4649 bytes Java code : 497 bytes, data file : 4152 bytes The file can be found [here](http://filebin.ca/2s3uEvTGBfcX) ``` import java.io.*;import java.util.*;public class A{static void main(String[] a) throws Exception{byte[]d=new byte[4864];new FileInputStream("d").read(d);long h=a[0].hashCode(),k,l,r=0;h=(h&1023)+(h&14336)/2+(h&491520)/4;BitSet b=BitSet.valueOf(d);for(int i=0,j;i<33216;i+=35){for(l=0,j=16;j>=0;){l<<=1;if(b.get(i+j--))l|=1;}r+=b.get(i+33)?1:0;r+=b.get(i+34)?2:0;if(l==h){for(k=0,j=15;j>=0;){k<<=1;if(b.get(i+17+j--))k|=1;}System.out.println("#"+String.format("%06X",(k<<8)+r).toLowerCase());}}}} ``` ungolfed: ``` import java.io.*; import java.util.*; public class A{ public static void main(String[] a) throws Exception{ byte[]d=new byte[4864]; new FileInputStream("d").read(d); // compute word hashcode long h=a[0].hashCode(),k,l,r=0; h=(h&1023)+(h&14336)/2+(h&491520)/4; BitSet b=BitSet.valueOf(d); // browse data file for(int i=0,j;i<33216;i+=35){ for(l=0,j=16;j>=0;){ l<<=1; if(b.get(i+j--))l|=1; } // compute color blue component r+=b.get(i+33)?1:0; r+=b.get(i+34)?2:0; // do hashcode match ? if(l==h){ // compute color value for(k=0,j=15;j>=0;){ k<<=1; if(b.get(i+17+j--))k|=1; } System.out.println("#"+String.format("%06X",(k<<8)+r).toLowerCase()); } } } } ``` The program uses an improved version of Java hashcode that uses only 17 bits: ``` long hash = s.hashCode(); long hash2 = hash & 0b1111111111; hash2 += (hash & 0b11100000000000) / 2; hash2 += (hash & 0b1111000000000000000) / 4; ``` Colors are sorted by blue component increasing. They are stored on 18 bits: 8 for red, 8 for green and 2 for delta blue. Total file size: 949 colors \* (18 + 17) = 33 215 = 4152 bytes [Answer] # JavaScript (Node.js), 10785 bytes ``` q=>`${require('zlib').inflateRawSync(new Buffer('<encoded data>','base64'))}`.split(';').map(x=>x.split(':')).find(([a])=>a===q)[1] ``` Usage: ``` const f = q=>`${require('zlib').inflateRawSync(new Buffer('<encoded data>','base64'))}`.split(';').map(x=>x.split(':')).find(([a])=>a===q)[1] console.log(f('baby shit brown')) // #ad900d ``` [Encoded data](https://gist.githubusercontent.com/Gothdo/60fc1c3e3adba252d57479c9a0a5565f/raw/6bcf3a1412610754a9141579a836abfa869d89c5/gistfile1.txt). [Answer] # MATLAB, 94 + 7.243 = 7.337 bytes Generate the MAT-file "h.mat" with variable "c" containing a sorted list of the CRC32 checksums of the names ( c=java.util.zip.CRC32;c.update(uint8(x));c.getValue();) and the same sorted list of the converted hex codes of the colors ( sscanf(x(:,end),'%x') ) as "e". This should have (R2013b, v7 File format, a size of 7.243 bytes. The function is as follows ``` function g(x);load h;c=java.util.zip.CRC32;c.update(int8(x));sprintf('#%x',e(h==c.getValue())) ``` It takes advantage of the builtin compression of the MAT-files and the support of java for the CRC32 function. [Answer] # Go, 6709 bytes Code is 404 bytes, data is 6305 bytes ``` package main import ("bytes" "compress/flate" "fmt" "os") func main(){t:=make([]byte,6643) i:=os.Args[1] copy(t,i) s:=[]byte{byte(len(i))<<4|t[0]>>1&8|t[0]&7,t[1]&6<<5|t[2]&30|t[3]>>2&1,t[3]<<7|t[4]&1<<3|t[5]&20|t[6]&6<<4|t[7]&3,t[8]&3|t[9]&1<<3|t[10]&1<<4|t[11]&1<<5|t[12]&4} f,_:=os.Open("f") flate.NewReader(f).Read(t) for i:=0;;i+=7{ if bytes.Equal(s,t[i:i+4]){fmt.Printf("#%X", t[i+4:i+7]) return}}} ``` The [Data](http://pastebin.com/X9nxSUhs) is encoded with `xxd -p`. Extract into a file simply named `f` with `xxd -r paste f`. The code can be ran as `go run file.go "tree green"` [Answer] ## C#, 6422 bytes Code is 575 bytes, data is 5847 bytes The data exists in an adjacent GZipped file which contains a transformed representation of the original data. Color words which appear more than once are extracted and placed in a header table at the top of the file, prefixed by a one-byte length. Data entries (after the header) consist of a set of: 1. Single byte entries representing a common word from the header table (value equals array offset + 16) 2. Inline string data prefixed by a single-byte length field (max length 15) Each entry is terminated with either 0xFF, 0xFE, 0xFD which indicates that the next one, two, or three bytes following represent the color value offset, respectively. The table is parsed in-order and color value is accumulated until a matching string to the input is found. **Minified Decompression / Lookup Code:** ``` using System;using System.IO;using System.IO.Compression;namespace G{partial class P{static void Main(string[]a){var f=new GZipStream(File.OpenRead("m"),CompressionMode.Decompress);var b=new BinaryReader(f,S.Encoding.GetEncoding(1252));Func<int>r=()=>f.ReadByte();var d=new string[256];int t,v=0;while(""!=(d[v++]=new string(b.ReadChars(r()))));var k="";v=0;while(0<(t=r())){if(t<0xFD)k+=(t<16?new string(b.ReadChars(t)):d[t-16])+" ";else{v+=t==0xFF?r():t==0xFE?b.ReadUInt16():(r())+(b.ReadUInt16()<<8);if(k.Trim()==a[0]){Console.WriteLine($"#{v:x6}");return;}k="";}}}}} ``` **Data Compression Code** ``` public static void Compress(string path) { var lines = File.ReadAllLines(path); var grams = new Dictionary<string, int>(); var data = new Dictionary<string, string>(); foreach (var line in lines) { var tokens = line.Split('\t'); data[tokens[0]] = tokens[1]; foreach (var gram in tokens[0].Split(' ')) { int count; if (grams.TryGetValue(gram, out count)) { grams[gram] = count + 1; } else { grams[gram] = 1; } } } var dict = new Dictionary<string, byte>(); byte codeValue = 0; foreach (var result in grams.OrderBy(kvp => -kvp.Value)) { if (result.Value == 1) break; dict[result.Key] = codeValue; codeValue++; } using (var outputData = new BinaryWriter(File.OpenWrite("m.dat"), Encoding.GetEncoding(1252))) { foreach(var dictValue in dict.OrderBy(kvp => kvp.Value)) { outputData.Write((byte)dictValue.Key.Length); outputData.Write(dictValue.Key.ToCharArray()); } outputData.Write('\0'); int currentColor = 0; foreach (var entry in data.OrderBy(kvp => kvp.Value)) { foreach (var gram in entry.Key.Split(' ')) { if (dict.ContainsKey(gram)) { outputData.Write((byte)(dict[gram] + 16)); } else { outputData.Write((byte)gram.Length); outputData.Write(gram.ToCharArray()); } } var colorValueString = entry.Value.TrimStart('#'); var colorValueInt = int.Parse(colorValueString, System.Globalization.NumberStyles.AllowHexSpecifier); var colorValueDiff = colorValueInt - currentColor; if(colorValueDiff <= byte.MaxValue) { outputData.Write((byte)0xFF); outputData.Write((byte)colorValueDiff); } else if(colorValueDiff <= ushort.MaxValue) { outputData.Write((byte)0xFE); outputData.Write((ushort)colorValueDiff); } else { outputData.Write((byte)0xFD); outputData.Write(colorValueDiff); outputData.BaseStream.Seek(-1, SeekOrigin.Current); } currentColor = colorValueInt; } } var d = File.ReadAllBytes("m.dat"); var g = new GZipStream(File.OpenWrite("m"), CompressionLevel.Optimal); g.Write(d, 0, d.Length); g.Dispose(); } ``` [Answer] # C# 7,209 bytes: 6,643 bytes data + 566 bytes code (878 bytes unminimized) Github repo is here: <https://github.com/nbcarey/color-map> Color names are compressed in the data file using the [FNV-32-1a hash](http://www.isthe.com/chongo/tech/comp/fnv/) as this hash algorithm is conventiently collision-free for this set of color names. So each color name is stored as 4 bytes. Each color is stored as 3 bytes (1 each for red, green and blue). No magic there. Consequently, each mapping of color name to RGV value occupies 7 bytes in the compressed file. This is a one-line version of the FNV-32-1a hash (assuming a string containing only simple ASCII characters: ``` uint hash = Encoding.ASCII.GetBytes("royal blue") .Aggregate(0x811c9dc5u, (h,b)=> h=(h^b)*0x01000193u ) ; ``` This compressed data file is in the github repo at <https://github.com/nbcarey/color-map/blob/master/color-map/hashed-color-map.dat> Here's the minimized code: ``` using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace A{class B{static void Main(string[]C){var D = new Dictionary<uint,uint>();var E=File.ReadAllBytes("hashed-color-map.dat");for(int i=0;i<E.Length;i+=7){uint F=BitConverter.ToUInt32(E,i);uint G =(uint)(E[i+4]<<16|E[i+5]<<8|E[i+6]);D.Add(F,G);}foreach(var H in C){uint I;var J=D.TryGetValue(Encoding.ASCII.GetBytes(H).Aggregate(0x811c9dc5u,(h,b)=>h=(h^b)*0x01000193u),out I);var c=J?String.Format("#{0:X6}",I):"NOT FOUND";Console.WriteLine("{0}: {1}",c,H);}}}} ``` And here's human-readable code: ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace color_map { class Program { static void Main( string[] args ) { var map = new Dictionary<uint,uint>(); var data = File.ReadAllBytes("hashed-color-map.dat"); for ( int i = 0 ; i < data.Length ; i += 7 ) { uint hash = BitConverter.ToUInt32(data,i); uint rgb = (uint)( data[i+4] << 16 | data[i+5] << 8 | data[i+6] << 0 ); map.Add(hash,rgb); } foreach (var cn in args ) { uint rgb; var hit = map.TryGetValue(Encoding.ASCII.GetBytes(cn).Aggregate(0x811c9dc5u, (h,b)=> h=(h^b)*0x01000193u ), out rgb); var c = hit ? String.Format("#{0:X6}",rgb) : "NOT FOUND"; Console.WriteLine("{0}: {1}", c , cn); } } } } ``` [Answer] # PHP, 5014 bytes Not the best there is but it's late and I need to get some sleep. :-) The beauty of PHP is that you can inline payload data into your script and read the file itself, so the script is self-sufficient. Just [download](http://mehr.it/golf/xkcd_colors.php) it, run it and it will prompt for the color name. ``` <?$f=fopen(__FILE__,r);fseek($f,269);$m=stream_get_contents($f);while($l<4745){$d.=str_pad(dechex(ord($m{$l++})),2,0);}$h=sha1(trim(fgets(STDIN)));$k=substr($h,0,3).$h{16};for($i=0;$i<9490;$i+=10){if($k==substr($d,$i,4)){echo'#'.substr($d,$i+4,6);}};__HALT_COMPILER(); $¥¬ÂÙóûV®W}a²™nÂÀ¨ÿÄ°iØOûO‰E…&@p²? xÔÿÿuAe«|Šü•.¤üüÁÿ¥£‘F²8€?šL…8^›Šlï´5m‘Ù›‚´ [...MORE BINARY DATA...] ``` The basic trick here is to hash the color names and generate minimally identifying substrings of that hash. I found that 4 chars of a SHA1 hash are enough, the first 3 and the 17th to uniquely identify all those colors. The key is in binary as well as the color code, which is conveniently one byte per color channel. So every entry takes up 5 bytes, which makes for 5 x 949 = 4745 bytes payload (the magic number you see in the code). Compression didn't help very much, bzip2, LZMA all created bigger files so without any further tricks, this is as compressed as it goes for this approach. [Answer] # Bash + (coreutils,gzip,xxd,openssl,sed,grep), 4946 bytes data: **4482** bytes, code: **464** bytes ``` s=$(echo $1|openssl dgst -md5 -binary|base64|cut -c3,10,19) f=$(gzip -cd g) a='' function p { q=$(grep -Eo "[$1]{[A-Za-z0-9/+]+}"<<<$f|sed -r "s/([$1]\{|\})//g") for i in `seq 1 6 ${#q}`;do n="$1$(cut -c$i-$((i+1))<<<$q)" c="$(echo -n $(echo $q|cut -c$((i+2))-$((i+5)))|base64 -d|xxd -p)" a="$n#$c,$a" done } p $(echo $s|cut -c1) s=$(sed -r 's~([+/])~[\1]~g'<<<$s) r=$(echo $a|grep -Eo ",?$s#[a-z0-9]+") if [ ${#r} -gt 0 ];then echo -n '#' echo $r|cut -d\# -f 2 fi ``` Data can be found in base64 [here](http://pastebin.com/MgVYhFvn). I know that code may be more golfed. Too sleepy now :/ Any suggestions are welcome :-) ## Explanation Here are the actions I made on the original file after removing the license comment. 1. Calculate the binary md5 of the color names and turned it in base64: `openssl dgst -md5 -binary|base64` 2. Found that the characters 3, 10 and 19 may be used to represent uniquely all the entries. `base64` uses a set of 64 characters to represent the data, `A-Za-z0-9+/`. So, I was hoping to find 2 bytes because all the entries were 494 and 64\*64=4096 but I couldn't find any. I also tried to find 2-char unique entries by using `sha512` in step one but without any luck. So, I stayed with these 3 bytes for the color names. 3. I represented in base64 the color names instead of hex: `(echo '0:';echo -n "$line"|cut -d '#' -f 2)|xxd -rp -l 16|base64` 4. I grouped the results by the first byte from step 2. 5. I used `zopfli -i1000` to compress the file. So the result file before the compression would look like that: ``` +{wf/7FtHhPAAIgWXKwtrpFbAaS6/i9KYk7cj//bpvuy9zvOysmxxvz//6vBP+m2sZFuXG+EgcIhZY1tsTAYif5s1f//xCFS7/}/{61snE90JK69qWKBIJDy83YXXE4df1jNx+XMGQA/60B1Msf9lKaAAEzLs+1WB}0{uiBWlrhIdJVRGSMr+ERZ78D+m2Tv1USQpL5cS3wcb8Hmj/+fZMa6NTEUwrcJqRvv1z+k2VRNvy/7GavV/5qKCTlFaMk5/3lsisUWVy2lraWH3nuaKBdb/+Nu}... ``` I tried other compression utilities also but with worst results except from `zopfli -i0000 --zlib` with **4470** bytes and `zopfli -i10000 --defalte` with **4464** but I was not sure how to uncompress there formats. In order to find the color code I do the reverse actions. I create the 3 character code from the given name and I reconstruct partially the original color codes. For example for `adobe` I create all that start with `X`: ``` Xqy#bd6c48 XL7#7ea07a XI4#3a18b1 ... ``` Then I grep the `Xqy` line and return the second part which is the color hex. I really enjoyed this puzzle and there are many great answers here. Thanks and good job everyone! [Answer] # Groovy, ~~153 + 10,697 = 10,850~~ 253 + 9870 = 10,123 bytes I decided I wanted a solution which involved only one file, so (at the obvious cost of space) I encoded a GZIPped CSV version of the data to Unicode characters 0x0020-0x007E (which I guess would be a base 95 encoding?). The code is 253 characters, the content of the String is 10123 characters. ``` import java.util.zip.* t=0 '''^/3"O:<]NULAydP{|dgMn0T4;4&Y!~0=(BsILP$#KxAoQ<C6Z-.Psh/}k3&uOEa[S}R+u4=X*K`?X&zTKSQT>xdA-_XEy2/e{N$Ue:DSF- *Df1E3x)i=cq;FFq]|p,!sbQpE5F}$qr]zu'jK&A^\\Vd9"sKPgF_^uv>q)6#/"b1#gR"yvZ#<p9{T+__!fl\\\\=7P{zO0('G R+5QKuX}( ,r$V]" ;G)\\3Yooo}<)%HrxnFWLtG1Dwe!N Nz*u;Ti`TI}[[email protected]](/cdn-cgi/l/email-protection)!Lx{w#e0[:Y@feo,=^M|D7qwZLHz2Hss&:z!%W2s|1S%TK]MaH]$KzQGR=*uue5O{d~J{%hU+[0_2z&|iiw )\\aq?(5:~l_u%6U^,&V&N$1YoYUX]E%}T`MN=/#KA?@['=]c|l?=!S9v,S|1]2do8cx>Q`WA]+ nMK_YDa~TdM+Ot4v[Ty\\){}zl0FG2cF**j'tN<g@>^ s='jDcXj|j],2P:p>3_V4$ybMXP?|7D4+W{Mmtsbs#S\\eZH!BUj.1_{@k/YPKe"D2yJ7!~T8A*o3z`1e_hvsd[,^k8>~{>/EUQo#:v>=dO$mkyyl+E[*@C1Adym8-cMYRjY IVxTzu@@Z`^ V,&9zO_?P*j~F~t&XPj*pQyH4[b0ob1JB@?X&_vGPx$Y.\\h6.!d+`CY-=w~IJ*)8&Q;HW"cv#]@tw0A\\uX@+{a"?PjvOF.{l])Z5&pV&]r*4f|Fr &fcnW)6|==t7"TqXe`EK6vfyGU)$xqP6c#snqwBYt}0|ayy~o]CUd',>fva~1OC1p5@,k0aJy,!BkF1yGe@qVF-T12bdE~6m420Zc [v|:w~l_[ZPq<*G?DA}~H<lJ 7y"c@Yq8JtFz#uur*E]dxbt:%mXdc}>%Mvg^^qL603|~@DdqWp]e6R9J?\\4Il/"v|tZXo\\8EtW^t.+~TcSK9T{ymny=KOD[,coYoh5eg~Uge(_N08w5HxP-BV\\E%Rajr\\K3RE{eP^c#QYEU6%|].W&_-nX=d| _i:S,CAlaCquAjtKfCNV~$r7sU)4BN*@'3=MoM&kxWzQvOeW$\\gM(\\&d=1y(D'cF=;O!Q.noW'k1u(Kmalk:xNFl,H)o3rlcS\\VcYMIcB.08,*3kQi~g9Y!>'<#KtJp]c5J|~U8j!\\>!0L<=0W(Xg<QF\\EA[~N-t/k 07 ]YPyYT(u|tJ3(=Wle~o3i6Z{pg)qWiMh=K1Ny]IJN^%O -.%L?>:fkbo7bLj +Xr{L|B*hq\\,$3m(nz+:U:fq5BpQz9Qznlu2h6\\9#>00Z%gb?AmJ]9$XTSM|]ZeKRXIE$Xd2MGDqzZ M9m7K8*ZlX1W"A"H+H9h3 YZscB.<l-YNe;NbuvGlq3@:xrA#:[[email protected]](/cdn-cgi/l/email-protection)+#b.eg|k/CDiW[JPU~7E$o5O1Q.7F:8sF7!~:$Mh1:sm%_#Q@>86;*-kZs1PdL`b^,>zh\\[,>n7Ve;6+#yvTcJEm,RUnZ4pP7*PED\\AMX9$m}K>-x&faPz[=ho?|%rrF@>!RYH)F(#L"v$?g:[19\\"M[O8vGOXP>4k CLt^$2,rf<gd?dw~K6w;|+u'Z6W+<qfq%ShD?.Q(ya<wXc:PdrP4c7R%=%#7#s^v"Pe^:AVTg`t\\)O^J%ZWXGZcZ(5ay@\\SXFE.7a/p/?8^6Iu]{-=kTNQ[~uTru~}[]&hka2nt)~CwaCfhG~[:=>}OZ?TA)dP*CDC7C|VVUX@b5SW#7RNy~7i63>={*U3=@qz*+=R$4?[3yTTM0;i=u%#wSOZe87w*.{5m>q1ZmV1$DuBUJD_R7B>H)``*o2b(_|%JHT.+8d1fdc yG(BaG8!]*:7_@&u#goQ^K0P%Jp!hbFk}!jaYpa(:e%k[ r&sm~Dn-S@V[ZH9U=b#,Ur04-Da;9JnUslwvf3CqmD9O5LTd5q4,K8*CjzjA/|/D9L\\|#[\\Z)gUhi`](S=VaU*FBu4m{N\\'CcUw!Qf+#Y8^0v=gf2F1\\i2kb=kv{*'7Yf%\\Pi4)+;3v'^#F}S-Dr)x9?UB<m7KOn<rjU30")%4{p_<fCb!D=0# Q-rhI\\^~Rx+2`CUXB/:CpYWwwk}*u<J/h-\\V^!EgfjKt<z8Ra*3{Oe0;:-+'$Z0(_nP|8Z]Gm4zJO!bu9[znH_05V1*1\\7"Q#S.ZtV\\FCS|'OJ#qHRQP>P4$<(E6W%zE&+LCqFe8%p`By6+jrk<VfFVu5WZA}vK_{n>:f]Rg}@}yT89CS1J\\xgvl:+>mCac+V@fnTXY,6pg/Vk$N WXsq]U{Y:A01pTx6`$W8+fqn,XAS[i{F:7~uX5Z-\\C-u/zDa1,A-\\?#SQ@(I{po`NrX~/7Dm+Fp0A4uPS\\#+!ex+\\K0A/N*jAJJP~C_B(.+CIx=!'@'|n.w5T3KcD;(*O)#@YJA$<;K*G-k?PW?{tIF8GUJjWtF|GVAp/3V'k&ehk~ibSVg'SSB}eVxRbSS=3;'o/=1@OY<s"6Y;'&`6"J]`Dtq}UM_<xN1dD$k~),^~Wb003~QFep1L @_pL<vp6_pNIaHQ*PO&5!-E`EkFyt&;Hd"uBULxUY+xY:F}>zTH( YYzQh+Qi0x9~'.i,47@2Ar kVL{$[);#2+_9L[ooa=.QtBPO-T3H@M[\\k^E"qS0/~f2@q}B>.r|B{DnXkcj5Bl}'q4%w<J)q=-?g5N0 r(z8CWe:ssf}PO&gd4F$~w5'LbIiXH:f4}0/0+#n@js#0+qhApQ\\&{rK@F8=K6xqgETEL(G{Iu+?)`kWMWjSZp}pP6TnF$[&~0caL.HM5cm+mJ;"<ld<'m2@.~j_[pQ6PaVK^XZ/,|.z,XXBwt;\\Ug%bHv8K-5#)#?"4-u]58SBXM@j^wv- EH!bz8Xnq@3309@:5|jd6{jff$e$nM0JW%A~a+?`tMb~'a`\\5<V=f$l-6Rqa4.4LnK;sjQ"^w?}gWl%G$nir3S7YO ysDwTfOHOF`:_*A-gF4{)qL:hNUXW6Z<Ohxqf<)rJ|8X{#rCn:r8yN+xv5}<<[mM<<,N2+4~r,Y #s&o>`-*03z'`\\+:CA4%/HQVTH-!;e{UUMg`tm!)"si-)W2$~~S+*W0ws QP_5U<W{"IceL?FQn[b(FjkRD0EBc,y>$5(C.C`?xKX5Qdr"mwoH\\gTX[yuOk"M.b6<O|HO`ClKKOS *5jkJH&riC`IGRc=$NP}#4kUUs3<'x)D[.u-%{) Hx7Oj(c;qzosHGk,$n[pRw[<b8D>|50XT@}h^Bn 9SRR}GsL1@K=F!%H&f!ENNQ1)U;0j9iJoJ%n&Sb5w3@ehvdCpk([ yM(t34_a9Z}{WU`oRTEfE!bG!"QTURfSZHh~l<k*1cX\\,\\_ {dA.VdD{sMj,M18-{Jswd"jr4/721>g8J,q!883SQ6p3]LYDrJoF'{:g1TS4m%b5!b6i[fbAQQbbu3{J's&rt)N>.WkpH3I}UFwd~~[}Xi;-hl))`0rRw~|:Gcc#+HXdA}o[="E$CKEF'/VD_L4ipRF'@S@3vS&Zk6[v~s/-=Qsli-2C8`93?>?]p)=:&-EAbrhLx~x<T&y5BwSu(_p@!\\NSKdX70U<-t*}K-<)g>)A s?x9}t<:RWHQT2aU[(M}pWY\\:<s>*+9L_2XR~9-$Py)>}&qbQ5ZV%!5[QQpLNiV^}F]J3<BAIJ6E+/Of$_B)q7X)>u}W^:b(>?_|iG ZnBNVe[e`Gapt t!qROz'M6Os(.led}wtz1wDi}^TM6yC+y~Se8^#@, @ZNB^jEY<dI;".UhkVZfeVJB4J+Fg1t6Qgcio7@fvng:s_W&*D/rP SsYErf6;xlF&}&:5[RMv7=+;|!n>gsLq,A<LkK/R7*#cnpRb:Oq(iM7Z}:#|TzD{6:Q\\[y;zA.tO=NX9X=veF"Hvg["oAItX7exbJ_`D@5@QY4)s9*TK!3Umkk>T)Wuu~p[!j1j"'"gN.6_Uslo(Z>#m<Wr%Gg>>/+xA- 8NQBeYLd{#}pk"+Ll`[=W":)c^3:WV)>3mS1!v]/XytHGG:v<V0rIm7]Gb>H,m'D3A<xV+8YB?4k@L(n$WV\\>P5%Ur!|CcYJ3O^x!*)btz-T+oLO{e{tjKD==rG"6fI_nF1n~a>nqqf1WQRvR+8]QIOIMjY=TJ9dK:7[bf:E%h1d}h<Nj[(;olGs)Z>'nJ`EqNh4p|<yXlYr%'CrF8JWTo)d2HklsDkOv/($ y~UOTta?4k2U^]a\\6IK'dm'#3XHY ]V0)iJ`NV^3<]*4)p`w/Mns_/WuGnRsKSvZjgZDX<lg/u:fli{2k$%qt*nP6v? I~tdyN>@7,D@m$vIH2dr-pLp[}]<nmS(//Y0IMi>{"3F-XmnN92L \\ZY}1;y% ac^(Kz$PVK+#-@1*;]~;l)VvHGC?1IbvqXe4K7(ZY;^)~S&5{L\\bQRs}Fmi6h@s0^b7"zo`f?IA`i.iXOud9IxsCb}zGX/s3HUg?;1e.a\\/jCqP~K8Y#7v6+"6S ?e.pF<B,LO,~"]Y;(LL G}Y@H/k4F6hcuk8LjOOh6kJZ[Sd uo#U>j[i<\\;uR3B1*"JJ"kD(8a9l!}CQ|L'8oVP>{<jfw+'[m'pR.6%aF!>LcqMC$I,l7w~y,8BM<e=iB|(pDDJVei'zOPrSTI]`ditp}Zl<\\Nn\\y9r$jA;I?l[/"u\\2\\v]"0rU7wwQ!62}f}? MWt|#HNP1((]]Lz!pBY[MG{0lN H5[v3T)RT6eGfRL`_auwOWhgW2[Fca_K/ qz0Xryc=!, bGLI9:t#-] -nEDf0#MULimVVwKVn~{RH6f$97E3*L?0n^tQnt.uKOVO9/iQ#oN3%"HNIT/QN~jtt7HH-!f2<|3O4[|f8Pj_/,V7':O5i0>f%!X[nR*+^6GO=6.y@`x'MllbrmIiQlKBIErOv4Mp!<;Bxv,l:`DslO>IbZNfB<*/[R9F\\A@u1 _"e8%54cM,dejpP%Q<Kf#;<hfrD;*&wl)KNbt0z5h~6*dwl-eo.x/"gn3zwE<peP1iL77U+FSD!P~D3$ElPS%x,Rfnh&=&n5a27ok@8&I29#(M drb\\d"EiFyNw*ZQ9M@w96iq7Zu*JClp=S$Br5Rr+%n_`J/(\\8"87Sa}JTFN&<d=(:KIN\\hW<t]UD>m1 mA3eW&iH<8GL]pN3av|.Z5@@IQdsklji%gLSqzcm5FFM$Lg:\\ib#I&b2:ZJj3w1#B3Ovjtqj<S*R5duR]z@TTGYUKnP)/N<P;Z.R_s,.X,.n~PIV7([sirqhg7B5Vuw8}G3tMq\\gAsvh5R:gybQba'bLW^sbxN/M,BAA,)if/BvPyU_MGNvS^(]k3KQbJk|%H7=B".MlQIP4'2K"^v _'|V!+RWtX+<(sRr~p}/J~Zyxf+kBieZB~(B!/Epp@h6!:|U9Ak}LG6=9xoD'TuiP *M$Mr6w}Q;q~ >MZ(N^YqllEQM$Q,: dc==/YKJ#qDdHNO^zu%?'7BEo*xa%S*X!vcLKc$/W KZ@2C?~Dblf\\?C?t@"S5LAQ[5)b3>q{T}'_OOhb+iH$!>HhFgtYJijK@C'Z&g4QVx2\\O>X@,=J#P~2])&|-[M|.qZ5%ya3{,rx%K,Ipvs"jv}0? e_H*CpZwm7}CpcR4/xVz}3/1>5\\p+_>-|aH=Y<k#0+8eMa,JziJ>r qDLJie1nC&}g84{(wH^TL:`'\\ + Z<gt1s ^}WxMTRe2.*djV{B}5npS{F'B:k181bV?!]&XkTi%lvZB`<S- ?C<EEHO|2Ri,BP(cC[F:x#e,$*D*ZPmuhTk\\G+aFfMV~pT-FKz=fj\\o>-9UY%"|wi4,1DN:Yo80T*D6QL/q(Wu$U,1IfqtGY&iMP)=P,$xaT*2+@V4"PnU$L^t]?,@<}:Jfh?hL}MUa9U1]vVuIUl2'z%l|?Y@u>84e39Z:oH)OxNhn`LK`&9+"/Q7&$>TR%I';gZ9G-'&`F?M}*fy8tiU*ZU=[>K#)Re$GQXju2s1q}l00&U=DvT-s"a+n*TPrx)Bz5})r"Il4^.2U:g|g}&>q4u$WS:]yhEZzt.M%~WYI_,0Sa(Rwe''Mh1ut06[^q,L`<\\x[!IS&(~j!xvTAW{DwK`hPlUy!$ki]W'tYbO;a\\o>X9%L|gQjX[z0`VJz['-GSybY+}3Xt`xF_%\\q:ufFfQ,SK8FabUCR63}[[email protected]](/cdn-cgi/l/email-protection){G3RAO-%A.?zjxaDnXs!w]--?{Cwi4NX"=,dyLwRf-lO[e8<Uov`bd@t$DI*WKO$?c]gDdmB,`D`6kC@9]I6l fTpk0{=x[6'riqTXL:2~\\iG*]C)%Jx9.vJ{aQ_7>:>)akb),L[-~}!1bcBsh)kz>j"hIM~"(A.S\\/K'uDTMPgX5p wqk<?r;[)2[.vCAV~H$lUS`6Gs{KOE.SD<OSD;j^S%yNw4Sku.iKBz``IR*c0X|oI3\\)6Xe%&N6?Ex6Y*TW;WSwi DhhqA}:,}kX}~kY}qz}t&,(Lb1[<=4Ha-,91J1+l{"^WQL'0qvY]TdM/h^A"|27N;>5i#Ka"aYpwk|,kV2XS*JP[}zB.iRD_O'>"-DKx6h0 %`}qWN)vc#K%WUQ5vTzX7Hq1sE7hg%kAYod~RVM<}&.Ub@ebo6jo>{(y'^R!|^;n!*>h8<P.Q6Zu9?%:Yz&1C>C2mT<U_BN=8=#ds><G>V'W1]C*#zkrp=c/6Z=rMU{dRtU$8]P(2brytf!I Y=c_jh@c8jj>p<lF/Xvh(mKeW P>-qO4KWZbR1o;2M qz`PrvAF(Av,dMRpcno#%C_]W9rMrjBCu',glHbB"X.jRbTeu+,Bu/+ R=3e)SYv+bS"3vD2!5;&lgC.3w Q4:IDmY*cyqc$SYee&zl44b<"Uxloy,*XGuZ;]#yMLp;Rp/>2}n||c+Xt,r<T'Nn[Obqjf5B[5Vm()$$qW)ZQzeXa6,N}/=!6klFhRG%>BvhGFcS2]GO8+>k/xp+MHwO!#rDg!KvVWC.!Q:FjC3UTt`Ut+>yWd$#HIEDR>?Qr@V5,_Ts-m;&<cn+q<g^LU'v7?a.c*EM{,9*#re#}9NWqw]|:0ZAjt+^vE50H^Jzi_2"D5Ab\\=gG&f.iuo_`RCxcYn%Vs>=pdRp-88D^j}yC^[kT|7v_CrbW&pa_wEWM9de!y(MfL9E1!CNGcXpJqJBXR]OZm6e^XS[cBeK3wvXfAa6eT{+TGq8#Wqp}"L[LHNc`>0V0.,rR:2ij{P'/K*Mn^nab%1qXopwh$^Nq2LL8}Wx]QV|3'r'M:c/r@aG7_/t/yB=o,++YjUYO+`r6Ot~51]+*D"{B9atCfTX'gwT/Men\\.VE}]DtnWFc)P `^2|2l[/leo.{wbme+p7[VK.b'p1A$3hkZ@_G^,G*vMAJJ5tKZT nOm(yy&Xoduos0<?^Q8ht&/sXE>{EXcTr.sxH4yrc%553u1/rcm:W^:v;8+g&o1%&c2BVG>X'vdY6lnS;o_T& DIHt]z^vrH>"#).nK/'6n(9TOue~tXcXt)sW57?6>h@$jX!VFt16CP3)Sf4~@/k$Wn>R^-@]8;eW0!3/*bw\\Ao]jsU&2^%ylL@8s+;"+&p`rh_')Y+{XrgslTC=|mb%|Sk{Lb.uCxW+e8%~=*`0KnVyAj;kf)<QSvwoD^"4~ql.7e\\j0k>"\\Zgv%>T3ie{cdd*70 @_~^D].q%=but)A[Q!o1pX&nO+/`F{Ks)5[zU8`_%iY>r+t@BMy`04qwZ8r@j f:j,WIWlx:l*SRbuWBRD_$Ep?h*i/Td*>u+XZ~2]!=[}^J)T8F(`+%{%#K\\ue|+DNHg!PNZ/8C0V@QH2KF^.nFW26;\\H5-Hg|t-i:z9F@8@{EJ%^og%19;?#~Q_7ZVpQ|]1$?,wg?HM)DNr4H]h3`qmjZ3(06r+<}0%,B[(3siMPakb90q2(c$wqeye9NDf$XXFrd#_dh=I]:TaUEo(ItV\\t+NUpygO#|/7l0kx)vND:dhkH)gu;lbn4n(:8'FxY,(CCheT)sm!3k]F4_j1"zXMHd0/0Efuo#yF:i.LjvW^EWU-).]ns"j^u_jB}LF9y9c%MF.:Oai]>_s<K`UZaD$&k*aNLj}ZUe:@'>O\\7w%VbO|oQ?D?}L"8Y(V*9i\\<A[(3UX/09~+%o7^F'6af78"V^sORba6qiu`+yG{2RZ[q7glFA=$q1(gFP =8;gkoBZN?{?wx/l!H5w`;<*G'+6l=gT8":[LuZ4=Op`^X<*0{}7XK>!W_y%y{+dp*S/o.jU\\|z3j+6*y7?yfe<'qTy2NJ%k]ueXBDtA)BLcif$;>LF36/TwpMzlGj@7XL/:x3:[DU&x1~"3eRdU[%7|/4rjG#iIBDm"5:x]m 11lp./q5J>-y}Tx.|7B8"g=q\\r)Wa<xsdn3Bm[<y1Wge$t:SzC9&9A-gU@FT&Or>*Y(8).2<}?-j}gx;+ZTVk.:XVr$W*`T"N0{S3Y7Ttx6Z]%*3EMG~Wv*Y0tY6pAU161/?u+*t~JyFQzV+|EJe l`;H~=-7P-k{t%'jsORGatzeO>FR@V|gnviL,mK Nu6"pR1V.;#q]^Q0 &:lmjhWY<4/?<h4-d^^V`Q`5SQhh1G~%:9(ws.K*M.F^(XTdq^Y6Jw[0)aA-_3r32lCSz&1)xI<+3R_{I}];:Ldz!=>mI?:Bg)t_>~3J?bV,Wsx(#;t<f?bsf<$Uy,>3i6q<q|iZLEVj`#F*j-E1 +? FkBC g\\f.Jo7F)=c";crn!p>H:F1*Q<P~\\.B'U@/3c:9*HN[8x>U!IJ-BG:R<%%e!NO3ZPl&~j$oNF'&S>{-VW}8lh$BjiWW,[-;X!h1~&J'j?`ez2j0>.H81Zc^}W:L2HDPk,jRR%$NP3TtTb{*r,B>|M2g(tCx+r&%=V7IX|C]:*:{-*;J={&2,;V\\Zt?+adNZRUiq~zx.=eq+u I;eK!A\\%tR,h!v-?*YpUw"<J-;J2T~,W+pRfy,jJ78bilPoW<rvl-=:]=XQgBZc@[[;7)QD@)G_ra2^#ATjk"l1 :RBov|3uQWz[Q#IadV_\\rgY}@ktfdA GZ5~NgJ;SVfr)QiN2"RVRi$2kL]mi:R,-Df*e]+PBI}eWR@bl4C(q7_DHk+_]@$LY.:RwlQ'PwHF%b<Z@Nt#s~p?g0;-B^lD|vV(/yN;oJF)jBET5O(xF6w>A,]Kx2bd/Z0$nbPL:,.p[cY;"'jDn"/z8FvG5!l8\\S[wWOS8uhSUGDpOub ngD=D%W6.%HeLsYCO/#1# /LO$!-lF3X72,Yc6:{\\P7jE7z$la0$n?[:6eP-jH!'~NcNmSC2B,>8W(KZom*\\iNSyupKk&rZDR%ViN\\.23zd8/58Y0ID>T]'"(evh9[>%4a%u=v!fG(m|hK: 5)Du(8g9+d(/4/1=.-P9\\C\\M\\>4;SC&ACckQ,[[email protected]](/cdn-cgi/l/email-protection) JoZ_t<'YVwRP"^FPQZr<1mFvb 2FJ2DS([G]NwV[uc^qr~%_]tDdvN}i~!r`}j^)0jo@#oM2g^-w`Vc%1a%zL8KL$$}<|uRv)~hxWra/.QUa(l6YXI(PR=-|BS 0dN Ls\\G":*.FQ 7o,rp~s\\>s)#3G$Q~FjZHE"Xz40;Yh?5alWWX|.(3jRR|9u+I2ufN@. ,44}bzyis*.YC'r{n72VEA>kgf?~RZEdq#{jFy?(Xn>S*2;$c?@b\\nGVNzJ=^PS[i#L@>l:^qtkEv"&_3pgU^<oVF]>&GvJ|Yg!{Trhp^{_&nabRM!:Z(a}AWWz>|hn,v(fe#)3jJ_Zq|-?QLY`#uCSHA{$!$am0gel%< bM<GRi^0^s@Y`npt2/&:SEAYc'ycCiG'McJ"wna)i25\\D9YKl>vD;4QrVW\\LAN{ePJw]uhy>C;xR1?'?NN4?PU`f-.'7UbULY|%|'%!'''.eachWithIndex{c,i->t+=95g**i*(((byte)c)-32g)} b=[] while(t){b<<(byte)(t%256-128) t=t.intdiv(256)} println new GZIPInputStream(new ByteArrayInputStream((byte[])b)).readLines().collectEntries{(List)it.split(',')}[args[0]] ``` For readability, here's the same thing with the encoded text excluded: ``` import java.util.zip.* t=0 '''^/3...'%!'''.eachWithIndex{c,i->t+=95g**i*(((byte)c)-32g)} b=[] while(t){b<<(byte)(t%256-128) t=t.intdiv(256)} println new GZIPInputStream(new ByteArrayInputStream((byte[])b)).readLines().collectEntries{(List)it.split(',')}[args[0]] ``` --- My original solution was a simpler Base 64 encoding using the built-in encoder ``` import java.util.zip.* print new GZIPInputStream(new ByteArrayInputStream(Base64.decoder.decode('H4sIAAAAAAAAAGVc23LjuJJ851c44jzsy0QMAOL6Obja3JZFLyV1r+frNws30rPzNrJEAoWqrMyqQsfb/krfb+H2yn/9x8cokluSP369ffnHM9/e3o+c73/9R2mflVnS6/H86z9BOKfzkm85Po8tvt22T/qxLYXJpRz58TF+pl2ysiy37f3j+Zbf379u/o4HWCeVVcsdr/geXzUsiLUsR/a32/db+0VbVZIF/y3P7PFA5YOJyx9/fL59vY6vG/7ulMi2LN/5dtv/bHj50+N5JZZo+RLzZ6ZXeuVXx9vW3g//eIz3rtYyLJt29v2Gd9z++o+MjmF5+ML4RGUXrF8+ffTHft/e/D29xY+cH3h9LkGuavna7r/my5PD98Xy+DpeEV9hXpXVLo8nfvzed8Ui08Usz/1/YcFhLp6y8Muf7Z72P4/+xdUYG8pC/9M/EUKKaNonf7bnx5t/+9juz7e9TJuodY1RL2Hf3/MBE4Wg1riEo5r1kf14I1OleD3Mgo/6K3jRK513zl9vz9fxP699o70yblYjl/bNZhoWgzJm7I2sANsXZqzDAmEnmL54a0N7lv+fF06RWWMN3ML/zveUj/6rlKxKpjvL534ekdfRGtX/gMWX3X/Ov5lSglr22/Y7vzUX+Os/UQTDHI5kLCgbm71qS7htNx9hEq1zSPjokQ/4R4w+adbdYCyMIsJqb5dm1uqr3/ipNNnJ9iH9r11LEEvEZr+nAfSaXV/xz0gKogQsJezHBnuNg1/DqtXya/uzjY9szmodoVNdcTzAZO75sh/+/p7P9xUlKETmt1Kxfl1+52MG07H/Iddcg7brgmB8e3zAXvTjEqNcRnhOH5IrU5IvX/uf84xgbJEYojSlrYU5GcAZZdgSfPjGM7f5Kp8cYwlbuG1k8ShtLgmesh+fA3EUM8HF5fWOmO+/Mslwti4RJ+GPVJeXjK0uSq/svuKlNqkdaP+d5Eww1nyTvhjy9o43RJe4cQjd+3a7+fo4b/WylzKWoK30Gat/Pm+Aru2r70oDaIAC9enT+LroyDw+fNV4MFkyw5dfsON5QIy5dUVEbPEXdjV8MrEshVser/v9/BCLcdws/p8XzoEnlXKsG53RKR0zbUt/j98EFTOzsCoAiPykBG1C95PpLfSXCEAObPnyt/z2vt/IlCllHWkNlxWkIuA5/j4jyoVMp9m9AM4i8or/fT7z8Yj7M37QgwKXBF6vLzKx8ZEOg0AkAsA/68ZW5xcA2YYnw12wUMUygLYvtEaYPwg+IysZXrY99rkGyUrisnnU1+tXnl6to2R64Fjbw/ibS4AdtsQPf8Td3/oprlFyCSQG7jxo4cIHrpa43e/+c6fdRlnwxB6pZ/zg4wwEP3zadh+fhC79LyIWz5Go/J+3x5bxHLzaa3K9vtxmtwg7At/jjsVg80YVLKO95ti/sb6O7l5kbL9F81aXmGySbjng/8O1bVgpJB6UdvpHESACvHr88Z9flGftujqK/9t2Zl8WUzR0dAeimtbqCT2UoOjC7uG+xRaZCfR+jdSi1WrTUvJRUck7xYCtCUsmdwcMF+B69agfrhZ4iQ5/yD5+nBjoPHImfjk/0dravMzcflmq0SV5O/50XJ8NFMwq9j/d88VJgCZK/kwLOFB4E9Llc0Oc3wfMmFBEQmKFD+T0tr/OhceivB5B3k6Bzk4HJpb7FkfK5cx4xNLDf319bAcZiq/Wh8oRatavudBwh3juh3mJ8hQcnO4LjvnR2EiB1/tCSdP/qVRFA6IqVtcg6mfMU0U0xN3hEXieTh1gtXa4bP7DYVS/xFv2xzhDaTxwFpFItIy4U9DLNWc6RJd3de1/j2yjPTdpZJsBFhF2H/m2G9Imjqc99y//Dxa4hoBt/N72W36OQw6gFJE4DNY9QoYVB8zt8droWckrOGTdbnnFj8dGcZSYUa6ixvs+A4TbwPvKTo43wlSU6ZGf/h3GxWOS0canBdT0Y4ajgSWVJegreALy2QUAPQKiYWynZjwyBAFM+vxoJMDIVSLi4yVlMy41Duf39ntLJxVFwiu+7eoa5ThHrcvy4f/JN0rtRnO7fL6ecMaez7jR4LCNr81z0kHWWL3745sOhGgFEGUf4OZAagd7e/qKxabAQ/KZLcf2FXeAgufxmjjGwMKBxxHeejtpBMcb6vMeniJBOatUf8Pj5p+TggL+NV8KPhrnBKjxtKnHx7HvCMTgXba2ncKwAg8F8mI7nidOmlV6rZr9+7OB2eCLSJ8zpdrisxjw+evD/9qQODTAXDQp0H4owURTaIv92IdDgoQgRhpVIOY7zlhJS6Tt+Nzuubqe4H2jP/OKEbYADKqLVYCrzqvgYF+316lCZGYKYEmxA2587BRBLsCRlopZNQUSL159BdS2tmgMBUaN/PqCrng0ghaU5LbvaYJSyTJUR/VfuYB/EIwk5XA6NS9Mf46ZthtvfjKqIAxfe36uoqF5Dy9rkKmd4dRrLsm4XLB9kiQAVjf2jHMFfZX2RB7bfQApE7H/flzJOwsFht3i2BdkVH5C5EH29GMrZkVaqPt/+FtNy8AsDv4AvJ1pIFrK3P727mk90kdtqwQarNw6vKrzv/GZyR7AvXxgP3VPZ2zBE+PM+1e1CVzGy4cK2QitA5YdQs34r89QEcGoDIHRgr9nCKhQqNQmMaZ+sEnlQLr5dhtSsjhSqxcTV7Jan6HXYoJEDKV5IMANcj6YnBCA1Ign9g3dR15rI2NApkq6h7sq6FlWCd2g4VAMsvHK7vsrM1pSZiY+nPFMyqJfjydCDoekuJF5QOrrd3W9xHCu8KkjP4kSMsaJkWOPt60eV04Fnt5ctbk62C4roHX7PEHIXSwXxCZ8k5kZMUhaFB2GkCs/qftVcTKYnkhs1VD10SkoC6//2uBkk12nRJDamUP89lUQADF7iqkoh7dCJWFv1Ykmn+NxBTYPxKyv8A42slXmzCjSmSOFkMtNFUIU0cZKpl4Io/f5TBk05ysE7p+TrUCykCYFj8b2Q/YZafv3Fg6SXONcVlfsgN8qna0tynX52bOTSgLEAKFRytFsHwQe/PyzVZ8iJFJImR0Y29qdBjyJGi49WJA5oFnDKwRSB6/PMwM4ZPT0ir+oXjNiAgK3yPN8mn2FL+TbXxnSnwoBTBVNfO+7lQWguoZsaCyE0KLK64loDKzVVyk20QugBNVbna9p+skwk4DMqT9tNDlaIT0l6ULEy/tVnsxyQBwknMtiSceWKU53QmWgKGedUFxTpFeIYF1593f3giIK6ddRpmjGsAGHYmcAX0pJsBzF1QkdZwEDTixO8kH2iIoLAP/tN0WUUcwqTu4Lu08WyqVn7lxojytRsG0sOp/cYsUex/mPT71cjR/UrG1H4YhUZ2HTreGHgZEPH3f/bMGckJQKoVA6OWwoPsL7m2/+LMGsmfbdkK/rBAN2YPpp13cHJ4mWVMrZsU6aRGIgA+97BTEg6YlRbPm7Z28joIobQT8XI5zBYtoXZ3witcJ1wA7hccQmvTUpwsdBn+7+9DBPiXTiXVsecEkI/NY/5zGzbE2M/cU9aJKVSDojaKfjJLbSEkn9Db4SoX7oo6NM50DGQggiqGrZZUQW1TZNzeBXvZCzOYletfEaLFyL4qJVDYAA9IS/e55TNvl1IdIzWXBRTMbG8jt3N56HYbXvqkl1lpeyzVi8dYabtvOz4hKFyabXhqmK9+mPmoJqSRCRvfnj+KASLSBsBU/pUTCrOCaRXm1J/tdQLyEVDYgG3j9v+cxggYrGHcsrCuCpEWlAzkLleIBwUqswkv7wBAdmrrtrjRBMxTIxdf6xIYH+qjqdR3Abkjl/cp55dwW/04EiFpa552vBJq2mCbB5/lIKz8Bq0nbi6Kq5Q46i2sXAYGkM09eK3IDcIgugYDs2KpYgG2bHET1ho4cHFVf8qviULxwPTMOUC20cagirC3E66CD6PiU2c2MLNQj5hAh6gNAejeTwXKwZhOh6wNDOKY6ybFMFIeboY0eSAdCg9kj4rQay70Q7HBsnNtU5B20ELLW6cqsfA5MUKNoUWwAKPLuWPyYSSlBr24VDp5rFCtcKFZMhSpukPPdZy7zRqQw69ydvx3m41MsotVqxx19TEECDg1/+3qNP+4wF4x2ERzP/mbecBHGuTPysuCcuAeEUgoNYQAgLwu/PfKkClswTVSPfdzp6rwW87MN/HjtxL8aDBFVraRlZuSbkOIK2EsXu4kFC5i+/98/teZa9TeSA8uoRLUUHUwn3r/w9mjTwHMju5/7pn3vDvhxFGvnwrMaAiMKjj9tO2WkFy3TL/ZpeIEzlgOpLWbbIHO3iv1rpMMdAXYfuEpMI2uIs65LvrX9X5RQ5FDIRSvAJkrLJARxHvhqFimgRgGkhmUD1MZwxmc2whERdAbNrCmdlsJUdTFBWPJg1LB2SZv6LJrf+z69KnWSlKQTQvfZmNOULcK0p/ZWtuq6x/3HYiEnOTue7FLAEWKiS0FmvYz9jspCopII/YVsuch0QhCCxicP8d//7+8QjtTK/vG7PowfmkB2wJDQvwOMBgwtloxxkebprAf279sfOP/hAHD0fx/eAQ1CbmM2oJFIxKUTfOSnpXYo8xkWk6DmoIFWsKrP5dT7ZCPjx55aa04wgEZbxdWBJ/yyAfZeuvBsUScgaIy5yoLpyjAHI0TnO63h/IWVSkpccCWAqhuGfOnBYouF0y18JSVK2TEs8M3k8bbYwZ99KOjYKM319MHCwhvYyz595EJxR+6M1eAnoqDp/xmKp3dBGPhr/NflkWfOFpnjTw5Fq4ZIJTY5A9RTnnOgsbPiihfTSl80Ob5JFUr/tVUpNDhrco/haJgbdoUiuO+rIGahM2VCi0TXgO4/qPIHpuAznsC4eev3jmxq/Liio5kk86quLC6Bx8SM/nvcXgYUUlGip+3FW5oNrHkPwHopgnWVPfE/Kgek+nvu98imvYHBaWyePGV7Tca01EIMFVewtxfGQFCXhGNzySWdCley8UBvxbN6sNgg6N3/5UHIXQVd6TfvzIjjglerU6SPxYDMxyWWk3VaXI53pH1/+8O+vR2VaAQqVfhAouPAWLRsfqIy17sq5qoDni2mfoN7rxe9rglwFYkyS6+AgbqRKNBJQ2/skex4EdhbJZ5UqUeX0c7tB/37scaf6HVUIZeZ52WNNt8jaRP9Jgw0rBb+qtXc3h58yo3InB6OiDiTWFTaHZaRRxcleASP+Gcrkgb0ZR2WtoLsq/EGqjOzPmmHnVDCEu/k+C4hyxeJSi+ozo0aSc50BzvDToHt2ysWunfB7Ij093c7oEVBa6fzurJopWv8TX5oB4U3m3fRNWVGmYRqZEHBUy1rUr9BCt+7835MceKZzoSip3hCB/WvHotnQkV5r3lR7r+4aC3RrYdlK4sSfmEMuGcBaazlcpLMQVpcZArU8q9N28FsRXyAae7nIFq2pc95VMbgpY7zLneafQgRYq9ParjOSKQYZvW0DHlyQGivbs8UQ6x+N8v5au8bgJnXspb3snUO2uxO18ETrE4KWRNvZO2OGl/yj5j8pboSvtGrNW02QHe9JwGUIfR+wFmFXOXR4hzjo7RiAKS9yQx+4WN1JqhrKgIliN48rCDgXI5Mng8Enay1iUb49+2zcKeFqEpwnDjaQsjnXWZdIcyJDqjSHFmF1A2RaenVJGbvOjNrsHq2PflTOJ2qCmrBWsOgC3wvD5ECUSn+zRIYusyPVwsBLIfC1YwOTmAa0SCIOTPH4PJUgTFb7mlMJjpq9llRG+3wdZ4leR+NZXv4QkafqcErId2dLazIADyyHRffnRfExKT1crcpvYFwrQkDY9VA7IYYhiRe7lO3IbxnRes+jKkIOMBpMgDZq0cH1EiPM/fz6td1PbhJMYuZSYqLqRKRZodtVOICPIsmc1ZexTZ45dCzNAd22++gmWI+MRAa5jdAQzMNCD8Dur+2ci8mMWhb+RS1ZqhetLeamMJtvUYV6/DHfoEXuLTNQqa07xUAoboSmAY39JAjArPnEi90E4ibT83LFH14S3I7caf5yRb50rSPZ91AC1HXvBnXVKIPB4+P+9VVzh9armAgxxjeK4lx0xjH8qOB4BaIvbPf/elBhEVuEoippLLXPBSEbZT8NMqvoEY6Os9h+73VdNLASfgjp7lzQSrnMVnGNOk7KUVbLdVdRCPPSB4aGmpKKGm1Vo4xteFASPsXCqCLYoBBhe8znvMSaHLXWLt3bgUh8XXsNbOoqT1891zeqGFl5axfiXucUSSjGQOikPdRCiY7IMgH8kfDAR54gb/4bsvQEfU/l1x8CZPT0wTLT9O4uA/HAdrS9nQYaV5QaY0VnavZEqvZYA0o7QsNPv/1DxgbdIllTpXGXf9klX8fMWsHyZ8MU0gpQT0mvE73ofDat3TEOgkmc9NnSnzgMrhFYc6BLXdr6QnmCnOdtlCtEzjaEWXaY/R5ujUo9A7ZgTCA+bELjjClNSNIydfcYg9zi+xjFpB0K2smd0NgrhNoAoKghQEwN9prV+/M7xmsafpv1MymyZnOQYCROm1xH8kszxCvgqhr67kKfsuGdAoxQ0ELyaHrv+MdXJetn1popq3QEVPmrNuCtyiIgwPG9ShEsl3Ns8KwsFmYz3BU4W5v2Rivw7ni8WmUq+rMuUB+pLU0j+PvARoD16mfDZfivNXHtVceJ1cFph9NozLBl8kDmW5eRJoqx8No+azVLrUHwiA9vvyt6qOhgik5oe/VZc5/zpX7RP+aSgad97I+v7eln9dUFBKhfrrNtJijLKhEbUYbgDiSWaoMQNJcaSJ3XnFVhSorVB0cR3FoAXszH60aQ0qFD6YzF9Vby2cT1J7RfO2Q4K2TuY0Zh8cLDJsdVwwp2UawnxmkvaxkRGqE38uQK1Uec4kHk1nMQR5j3mfOYOQCxFrbr8Atlwxt9mcW3QY4BHjSK8kXP2879MVlHRus8wcx4Nuk0ZgNaEHgTLPvZtq5AglwiK90iswcFF55NjSHeSuGiVy3aNEtQTvIqXVtZwxndUeI8fegxbkWr/jRKGNayturGwIIotKxeeicM9NY41qvaTa1ZEanVA4PCgY6THWl4d20IhG0ObWapaRJ0FPvOpuIaq1p+e+yvr9OpveadUM6qOrJGPZ8PmgZA5qUBuFGHHiMpWa5eXNLTsKIWGTmPDE5AqrNUQ4E164PP2VC9aJwmApdr2+vqZ7Oi0Gzz14YlxY9tJ/Ze6JfVjONbGXRKhZNLzIyYA+UX+Pn2OesTKrg6yzqnZzi2eaFi/XupjjkNxdGbo2WVeRSYhmjSAOtY2qzcfLG0alDb+RnTkfcZccDzTgGxgu0jkOs4yVAnUAqll0vKfuTHWWlnIrGREnuEKxvJ0SBMzlc7pfglH0+vdaVoXZXRWTqBumVn7Y6iO2et/9XqbKYs8FcaLE7Zv/6XIArrGWyod/KjcIKGh4nA1N4NmZpSUZ/5gtwBZW5FpxmZBqDQjnPWWqzVa2i4QPVhq0Anz2LawAQvVtC2cnuRlWK+tCToroC9lCRHjyQ0kKMeOw1rumw7Xs4Zggignb2hWW5U2GtzzOaRYJu91jISM3BLLSAkk8tRCYmNYcZJNXOONHrT+6bdqTjzccjYnycOzcTVGLFssrmIFSFZWdVlhEiDXAPmK2KnzKIeTYUZp1xn5xYPWRZJGdMEjO5DOz864SvVudam7ifnNkz1wtFgGcaB97WBrxFFrMReRRsRDTfIxS9nP2wQq+LcHII5ZQR1ykq9itDLGpAMMfb39rUoKQlX+qhBk8fGGzczV+v68OKiPunTrNs4HOQ6wY+EFNXJlmZ1YsXg867z4NPRkFGcvVbHqXjJWOCTfBGAgojE1pK7XBTILC/nLOp3RYbgOtBeG4UaoizxAWHtDkHUyasxDU81HOhiNiOuIYgXgJrRDD8TMnSsaaOdbzjvOtzptERQ9Q4UjWkGkso/yv3QFBYsv4LjbDN5ml+Z2fSbpva00mnm6NlXBelfzzCd8y8lgpe39XWH93hJGgTk7DpGzdXP4etWvGMTzWYcpRKhYZc+LxWQNSlP1hIK8hQY4DBwLVWmbDLY+X+/7u/XqoAVcp0d8yb8kmzJgvKEXu1oQk6WZBy9qILVtLVUjmrvowR6XhjglLz/zCoCAHMVa6vjjzZXcjTUVVnJmcrzhNU2yxoytrGc08LJ1Pk9HOPEEGQl6UaXo2GxNZJg4HpFo/1a1ftOrXw3/UUnct7G/OddDB/T9fd9hYnjTx06LuVZaXOWS/49x3KhyAyETTNWE3DKapeoQIEv1TBaEzPVCT/2d3+nSjYAmp03QCYEW2nBuWu9ZtZVFXWEW49ygK7zYpYJx+UctpZkR4CMdXg3EulwX/AqI+uw1awrCK2E6vxspmcnY8hN8Y/PUpAh+RNuGlLnVYt1DOtWbQGJCjdE+qOkpiIX8yct2BHH+TMf/pbOTdrC+7TclJCE5b2J2LuRRrnYs8QYIQQJBvSc5dWK7c4nyHwa3qzlFa/YpSPf5krSwOUfWcHLQFPyc4ezSBiMGZvsRRalnQ6nKu10D/Hn85g9a5XaaJVXl35EL0trnyHoqPZA9WhvTO+zjXPyzrD+xl72R/aEqYfpCMWw+556mwp1ijrqt3/pTOhdGo6h0Ufwaj9LO6257anHNgFgOiLRMz7980yvzKnLx51qi6jksh8grqkWVFWUPdpnigBxZX7URZoISICO3Aeeqif5OqjfvzPcIFfMi3vwt3PCj3lvGsLMkiANutZmV//EQFT4syAwEMAa+NVy+MdX19G0T1ixVj9GlUNkTrX1eoDzDYauTD7raGaN6VIAkvZH7aICG0QAa0Jy3jvB8/TlStWcr6ESXy+sIoC5obIgCbKzvw04yPMyDjxbrpbkfa2kD/gyMdP8+ZyK0+AJpV9sHBRFJQZitFwaWGviNEk1DDSQRXi6EfaI/qi/o6Yhd52bnPSiFGEupIquV6659ivbVR7vlK7x3IB2XubxrF5BbTcxarb2WkverD+KrMlipY/LHKi1YTW2D3I3V7G1Ul19p0degKoSrStJJXcfRap9S6oXOqfsWEy/oytCmw2/Xp8BQdXzXubsgNMUfb8bQOFSrJX+cpjta8FSd7tVw8+5AKN0A256oZdI+2BgV+LLEbCs57PLuLPSxnXdPQ5wlSAtZQ7r9UFnkXIfJmvBzCBlre9l2dbG0cXge6PoTfeA4R+5BxQNLElrS4+lMUsQ8arROLrUSKCNJIhqnTU5i7ExCd1geiozHKpY+mw1a+tu1x/7vBpHbm3d0j/Q3K2jWSirDlI1jK9E6V2qa6lGqqh88+/ZGjTCIQz8P6+j/tD5sg6ONS4N0C3KUftvn3EWodfP2JlKxbB5hbY7uI+haNemlahNs0rNz0pQ+1m23KXLkFE7JMapsPT/7twEltIVFU6kBBMUsx3QqmKRRl/HJGgbDgWhmIMcw0kSvLVcBkbmaCtb1fD12X1ia4DGP64TWWmNbLKrnj5oClCd66RbhWDKtlfvByADVePSx8PBWSnjnncYoTZnyphaSwTmL5fq6q06BtFT2vwupfZKLNqsnDU+my7XhptZ6Nx1uXgQfOXSHBmTBjYDqZfrTWitACi21+MGVzcJ6eK8XL9aZlf1o3naa8RtWvps7nk372O21J5siqlNLdYb84rN8DuplJYWLna5SSOpoNHvx4w4NI6BqV9vDCmaxXbLZThbMxMh7z9e94tIYUFSvWVeCcsJ3gb4P7bPx35vNx5Yn165bI4mJHrbj+YQqW/dOzezYC9CYsPtemBh5XEWX6vgUFB4bSc9R8WSOqudg28CZ3fUfwjBW7jdKAw0YetYlpG3nVM8akWTTFVItTtBgPcxR332EoJm/pxtxRlqpCWzeLooPSoNQfWomzVsQLeXy5yttKw4upVU/8kBr6Co6r9AcGnBeFec6RJ2EkStOOW/et8AfMgbvfzrxjqjeeOlzWY5muAYpPQMP+/lnDA9iQ30NzGA55FfNfJ5sawPfw5PWXVF2eu1x1XW/N4vtAUoBsuXy9Vcm6l/v1zvBTvvMzP1HvbZQBMe9GX517C68TBSmG5YU9lqMtRy74N5X3PAOWGmIXcGgx7FC5lk7tP67W5z4fCLdvfhvBEGggYd0Nr6Cqcj+XIdr7I0x12WVnlLAY7fZyVHoq+VqH+NPzC6gD8tPcKtSqiuZOp6EESjLt1FJSt0z/jnP31Bsz9tzpA2xWlg6sdot0y2XhIhqJv+QlDHl+tFXIaFstkmmuO0CoDeIb9oMf8BhxFZiaeyzEp2pIYJX0bJFiAmrFh6t9KXAiJw6eaptUTPl2t5xtLdsy5gBrGSHELnh0zSxngakRgTUgEYtPwYoTYQWGOp898xsBxp4bxSSLObloZu2vRp/W8ZA8fZC5zFj9kUzqVeftwHVUx6JJEmj+B9cLrlvPtmnI5LT986m6oTezVJK3jjbAPNChvdLFx+DFqsimkagGu1BuQgbkcZ7WwBSINza7KQr5mKnJ2NsfZPrtR/y4QHocvZhqkbXlVYrv15B+9arkxHR+Hj8qPhsK6qXpjtzQTPch54PB25GFP0ci2KWzy6DQvXsQqnIILOooZRIcDa10zAqVrRKQCwlpnzrk7DCg0Q7DeJCLucoQH7HtnCrfZaXKc7tvXuWxuVVvWkhwxSq6Eg6y5heR+NpK3KNZVlUmUw/NETJS7KMyjH/wGizuuGeUcAAA=='))).readLines().collectEntries{(List)it.split(',')}[args[0]] ``` For readability, here's the same thing with the text excluded: ``` new GZIPInputStream(new ByteArrayInputStream(Base64.decoder.decode(''))).readLines().collectEntries{(List)it.split(',')}[args[0]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2894 bytes in Jelly's encoding ``` “¡×l®’ ȷ;€¢ḥ€³ḋ“þ§¤ƝⱮOMẸmŒỤ2ṭẒTþọ ÞẈḃa©Ụ§¡ñẏḥɦḤC÷ẋ(k⁾ç⁶ɓ"Ẏ4Ḣ?"AṠẎ|{\þƬ)ð¦⁶Y4ḂṖṖFN_ẇḤẏ}ȯṭẎ²øɓ8bV¿[ȮƓȮ³OA°ḋƊOḞ/ƭ)ṗṇ⁵⁴AƈtPṆḣėeœ944ɲ⁽Cẇr;ʋ?rȯḊÆọĖƈ~¤zl⁵ỵMŀ7Y⁵⁷ɦ{£¬ḋƙḊḞ¹œėṂÑḌ#½yɲ¤ɦ⁽7ĖỌḷṾZ⁵Ɠ0×ZPL+ṣẸmỵỤḶḟ@ƁTƥƤ⁴ṆxEDṄNrṃtṠɱƭ<RḲGƓʋ®ɓ%ŻPvṢ¡@ṘİŒɓṢlt⁺ɗ"¹Ñ⁷wÇ⁾ỌḄɓ2ḞʋṠḶʠẒġkẒḶUʋ"aⱮÇ1j³Æḋ⁸sƥV58¶ḥȤc⁼$Ƙ>ƙėø÷⁸7ḊØ⁶żɦwṆḞ={>]ẉðĊẹ¬+ĊỵKɼ8dṆ'P§-~ß4Ż¦⁺Ɓj×ⱮḤGE⁽]§Ụ!{ƈṠqƝ1 ỤrṚ⁻⁹ḥßƊÑ×½Œ6Ŀɠ⁶ṅ¤niȥṄʠɱeḶL5ƭ§×ị⁸ƑẒ×Ỵẓ÷ṇAṫƁ²(ṾĖḊḃḃṄœƑ0ṫ8ɠḋḲȧçø⁾ẋ,`Ñ¢D9OẠµɠ¹þḥ⁹B&RɗỊẈɲXċṇẸÄ®oȤƑuṃ-ʂịa⁵]¡ɼSĠŻAḷ6D½o³Iẹƙḳ}Ḅ²ṂߤḊ!YgṡƇ⁵ḶċWF⁸_hÐÞñ=sIẋỴḳ`ʂɱzṗaḄ¦ȥ⁶¶ɓ|ḍ⁺Ȥ<hM¶⁾{ß.x¤TỌOḄṡ}"İẏḟhẸḄ<pż°Ġṭȥ×ĖėẊ÷ŒḢḊạœḲO⁸Œ½]:ḣḅ\¡ḅƓ1&Ṃ⁸nÇ⁻uh⁵E⁹IeY/½ṗʠỵ¤1²8ƥ>³ạj⁵\CsṾPḥ²ẹẊɱ°¬Djƈ\iDßṇǬ¢ȧ¢ẓṃȯ¿ɲqrFʠµẉUçẠṾɦ"ḃÄ0Ƥḃx©<İ?d⁴!qƓ(x¢ẓŀ}ƓƒɠṪƲoɗVƤƝɦEṃ⁻ɠE::ỊxḋNḌɓ⁴ṠŻÆİẋṡɼĿḥżṫẠÆV8Ø+ẈeṆ$9`ġɼ§ ṀB⁸œj>þḍƬÑƈPḞ⁵¬Œḳİ&`ʂ¬zdȦ²ạ28q!ḥµĖṄ*Rȧẏ(÷ỤŻ[!ṫkọƤz8Ɲ()⁻?-ßtạı8YẈıÐy^@ḅM]⁴f©ɗƁʂṡẹt1øÆ⁽ƝfẈṘỵẈẉȤṾȧ£^Ȥṃ *`ɼ'ZtÑƬy£PȮ°ȦfƬ¥ŻạƒḟçạẆÞñƝṪ¤ɼ*=.SỵÄp⁾ƁƭÞleĠḍÄU?Ƭ¦lḲ¢Ḟİ®YHṬ⁽ċ*ßXZ⁷°oẉḃØĿʂ¢YċƊḌ.Ȥḳ"uẆ£bm_ƑpḷʂC'ṄØɲƤ*ḟSṗ/æɓhn¡÷Ḟ`j#iØ(¹⁵ỊÇŻḞ`Ȥ©H4æẆḤḂÆ2ʋṃ©y7<$ÐWṀidMz§ṫ⁹ḊÇAṡœṂ¿ṗCCŀ"_ṇṃ⁾iḣ9¥ĊsḲƒḞ©⁷ḤƙṬG⁵"*¹(%Ƈs Ñæ_Ḋ<M⁾ḅ&ð"ạƒZM⁸ƘKð[v5ƑɼsNḟKh|ṣỌHọ©⁺SḤ⁴Ƙ:³ɗßżGUḊȦṫịŻçdṭŻ÷İU⁾ẒD×ġ£~eSZ(TyÐØĠɱe*4°lÑȷṄIðṙẈȥƥSp'1nC"ʂMƭLẎ]ḅẠ®Y½ʂMƘ<⁽<ðṡ¹.7ÐJĖf- Ɠɱñ3Ȯ6ḌSⱮ⁴&²ø⁹qẇṪẆɓƊṣƥɠȯaØ1ẈðẸ{N@ȯ=ġıṃẆċd8ėþẇẓỤ~ḃ_M~1A.ɓP;ḣṁXeY8ẒḃḊẸŀMḃ?ṚʂạbẹṂƤɱḟ:×Ụ³ṛ¿⁴ṄḂÆOƝ÷ȦʋĊ_JsịṠɱÐṄẏsṁWḢ4ƭạịZ?hfẠ6€=ṣROƈ%©œİİẆ⁻⁼tėọ¥Ƙ|ɠḌḊ`ṡṁȮñḄQB⁷Ʋṣȧẉqḷ_ṆƒṇḅẋEGḂⱮƊṾwcƈ⁼ḥḋṬf\ƑḤ¶ṅȤĖṚµCƓƓḶ,ṇȦȤṇz½ȦẊƈṢn8ñT¢ʠƈċƇ¦ʂNJ(OYṫƑȥhZḤg%ḋʂ{Ṅ}ẎµƒlƘ%⁽=⁸ẠọƓ%ḍ;÷4ßṖƬþẇṁƊ⁵ḋ]ḲṂ¦ạẊ⁾FḄ⁼ZƤỴỤ73½ṛȥỤȦḤNAç⁾®ƒIɱ!Ạ}E⁾ṘŀÇḋQp⁹ṭ€AdþȮ£u&tɠÇ÷Ẇʂ;MVaṾ⁺ŀƊ°ọḌḶėȧƭ®V"Ɠ}]:ŀʂ½NṛỴẸb¹¥Ƭ©qf§ṃṄ_)⁶ẊÇ[8TṘỴṃạ¶j¶lṄȦ€ỊƑṅ¿ßƙ¤ Ḋ4aḞY⁵ⱮṭḂ*ƒ¡ḄD ṣ\'ỊṾṆġḲv¦ñ9Ṙỵ1ṖMƘwṁⱮƤṘỊḞṖ⁽7ṇɱ⁴¦⁸9⁺ZẸƙ:5CẆ\Ƒ²ⱮeḷÄẠṄ`#&ædḋẎ6"bṭɱẈƭqƇÄ|| ½ẸḶtṛẓṅḃạÞṢ*eŻƝ⁻ȯɗȥȷẠ³7gỊṙȧṡ⁸ɱḌSƝÇẋ3¹pƙ⁽tṀŀ§/dĿṂð²#ọ⁼⁽ÆȤ¥^{Ịṇḷ*<ZȮ}ḄÑ`ɦċaẇ9Ʋi]ḋȧÑḋɦ)Q9u®ḣÑƙh^ÞịḅT4{ŒỵþlỌBtØ;ḋ⁶ỵ|Ṙ8SṆ&¬qÆɼɓƑ°H'Ḋ8En¶#ȷJ⁸.mʠṃỌḋẒƑṙ³€FỤẋıḅÑȥ-Dw°²Ẓ_¦ḅM¡ṀỤ×ṠOḊ3ɓ£ɠḢ¢Ɲ½Ɗ1ẈƲkŻ³ƲƲĠ"tṁṫƇ2£ɲ=©nP|3aḳṫHẇƥ×⁶µĠḶƘ⁶¢ȧ£@PɼṭWṪżþƘƲu©Ụ_]×ẏġỊḂ5⁹+øØw6G"ṙżƤ(8`°¦ḷ}GḄBnọ+ẇṡĖvḥq¥¿ɗḌÑḟ&ŀṫƈ⁷}#ṬẎƬȯḂI!(Ẓ¹ḂTṗ1Ḳæƈ;Ä⁸iḢb⁹½ịm⁺qė³ḥ¡ƓbZç©#>ẊḷĖ(W¥Ɲx{ɗżMµEɦɠ?ƤḳoƒLẆøXÇŀYỊAṚñɗOƲ|ṇÄTṠ,ṗ×ƲRƥbð\ɗɠƙC._JXƥf6Ċr>żı0Ƒ,ß⁺Qðẇ⁹ẇI=ċṖ|ʂL⁵?ḍɲƓẉȷP¤Ḳ_ƒ³X§ƁŀⱮ=ẉkḥẏwọIḶḃƊỵİZ.tCṡW]:Ḟɼ⁺Ḃ+ʂ€ạ;3~Ḍ⁺ḍḄ;\|okB¬N*OṾ{ṚƝṘḷȧỌḄv:8½sṫþ^2Ʋ⁷e©ṙ!ĊȥⱮdI]ʠȧÞḷVHgỤ]Ṫ3ƈẏA($UzƝḌ{ḍŒsIɗ¤2¶ḋ¥ṛṣxȥMƬɓCC⁾ṠB3¿Ẏ:*çnȥvƊṅmẹÞgİẸ€ịMɓ÷¿Ŀ89ɦÆ8ḟrƤḶX%Ġ{bµ½ọȯBI>ʂ°y§*þƁuṣḋdƬṂ⁵×ɼɼ×IKÐ3Äƥẇo(ȧ-ṇoDɦbb%_ḅæƭcạGƬʋȷẎ/ⱮẹlṛẊfuTæµ°ċ!6oḤṀḂ×SṘ{/Ịdz3`|¢v5JṣỌḊNŻḂPyȤƝiṠƑ®$¶(M⁵ĊYµẹEɓTMĠ°^ð£Ụ¥ḌıḊ⁵ɗṘ⁹ḋðwrsRTżẊ$ɓß.ʠRWSƘÄẇƬṗḋø¢Ḷɗ0ƲẒ⁷Ṗ⁶_ŻeȥżtṖ⁻Ctṇ⁺ñʂƙṬṡṀ!ḲRḊẈɱ*ʋaḲ¿ƁẆṠ8ḃ*ɼƁḅ.AÄçĿḍ"ȦxḌḅ NƲDẉⱮḷṾẊ?.ạ⁸,ḳvøð9ɠȦḍÆɗ¿C=ɲI⁻*⁹ɓḥ§i⁺Wı^nL⁺ȮɼḃṬ⁸!ȷȯ<ḌXƲmIÞṘ÷ɓÇẓḢḢVYḄfBUSẆƥ⁺&]1Ʋcȯwð€ṡ¡⁸ḟẠỌȥ*ɗỴŻĠȮḌṁ_ȷhịOḅGḶⱮhṠʋ*xḤ/fɦȯPFxh_ṭ%ḅØɠœṡß÷€⁶ẸŀR¬ŀƁ@ạny"^÷NṀṘA÷s¦rė$ZA°7 xḄ⁾.2ỴṬ⁾ĿṖ0ẒG:EßXƙḳntøoḷ2Ñƥµ/¥øVḂỊẎiɓƘ%³EṬẎƤÑṆẈḢÇṀñḤ[ẎȮṃḄMƇ⁺@snḣƇḋẊ"⁽ubż^×pɓ⁵Qȥ¹4ÇẇRñɼlṪDÆþlapɓµƇĖẎ€ẏƝ żƘḶ¥⁷ɗ{ðċ1*ɼṚịzḂÞAɓ#µWWȯ¥ọ¹¥&ḶT¹ṚØṗRɗṗ~Ṃv1(ȦİṆcƈḢ¢/ɗjƇÇd⁸Z§œḶḍ¹þfĠaO çÑṚḥṁġ2d'Ɱ'²]ṡ&2{nı{¿ßạ ƭjrẆ'd@ṗ,ƬỴ⁷gḅƤỴCḅƥ½ṠṡƬ¥ȧGk2Ƙ<ẆƓMẒ¿9ḟ.½Ż|xɓWr²×Ḅm¥?ḥ§æ\!ƈCØvṃṅz÷ÇẎyøƁhzṆṛ]ḊÆṭkUÞṠsṣḟ5Ƒ\[ẋ,¢hpLḥ)ı!ȯæḂPU=ZÞXỤỤɓKḥFṣŻṣĠḥC¢⁾ḳH⁴ọṛ⁶ʋṚƭ+ṭḢʂk!/Ṁ⁼t⁴’b¢$¤%¢+¢b⁴‘ịØhḊ”#; ``` [Try it online!](https://tio.run/##LVhrUxNZtP1@fwWgIOII8lBBQERAReUh4gMEQQYQFUGeoqCVhJAwiS9IlQnOBRLIo5gBTIKQ7k6AqnM6p7rzL5o/4l2751ZRQDrd5@yz9tprr90vB4aH3/3@fWL5Xxbg3mG2e2JZ@R8tUXli22YbhhSiv3uG5MYN/IhFWFCsnsR2W5oMRXqdXjaSwRJD3jGU5XZ@ZCQ/Z/E1Q1k0pPlnbAvf4f4AjxnKVyykhw0pWMcThuLOf3ViPeKRE@uB7skxlC9lhrRRk1NryH58mJvt4kdi@yyPsjDu6MCXNkP@jp8bzT2G4sQqWPCD9tPc9wuLc0n3lPc9ZMdPtF3h0XbZXkstiyJk4WoxpLUisXPWkL2G7Dyx7p9Yf9WKxclWQ3YY0qbqHUh7KsrK9PiJ9bAOa49XZtw141hacnEHjqN@F4sfWfD9MB41kvtNacvlDnOVhB6eZZtsm3ZZwd3Yh8lpj4ptbHzJkD6dYofv9DgL6jjD4WX1u5H8ZEgJQz7qxPPCc4F7O1vvnjPkTcIRSwMsQzowpPVrwtouQiKISBHkTEO9Idubxw15fhLw6DGxU9VmSPGbwpNxs13dk5tOtk4b8gYLXDNknxpNL@sefByePLEqujeHyXwJ0b7lOPyRGYNd95Qg2oyb0JYOMoB8WQ28wm98epBx5zxDermz@CXbAwTIu1WaEKGHF8sZogtpwT9PrKnTwndVrKheLvEEvr9McPmQq3RKD781oV2rnr3abSh/8ajqMhSZbZ/D3@T@HT1V3o8bzrSyyPmPfL0snaQkK8L6knuxL3J7swGAdbMIAMmeFYuIckysFmfhI0D4cWJNnlhlBMLXhYsvcS87TC9fUo91P7Y35AUWHHmhhQBZBlgN4ER3L4odFuFeI0knEUs4J334ZSgeUFF2gnT/CiuL5yM1yBJlcp5@ZHvaI5Yu4NtyHTi5gbkW4REuEY6K@49evsQ26itaDMXP9nU/cD6iYrHK1/PadGyAUy/q8ccqYHYixdzOdke1oFiaQibPZ2wI5xmI0M0Ceuq@6k8na8GOS/XscJTtNQIwItXeB2SLxYlR6wzscGV3PDfkgCAe42Sq@9ENHKlniH/jazxWPYHn3HQyaa83Y9Nj70H6Z7RCWENcBwy1NmdIn4G2FqwaamIHOMksXy@cYcF2MAOlYsfqH3LUqFmv60MIG9eq3qRTLKr6UW1aiHvV7@C44uIJ1L60QXgpgbQH6LQglvQyO@y@gsIypIUuFsBv4SnOwwHw3QhRMDk1hOCRYblxoKOIHSJEEDC5z4LFLF4uQlchNUrgJe7pqptARlqBKRBQZGypx1iUbde/FItdL@r5OnDlTgaN0iLQKQWkn9d@smM9PjZ@I4OcgHwPeATpwTJ6OAc55fYLAjDOz7CtKjVa048Kyx4TnvwZ8/m05YPwiGUkW/5HxEd170MBqdPDDVgYgev@hitXkNYZcKEZ9a17zAJF5riDEEOekUr1GAGnU2ANNuaOh@Xcdw5EGADlT1f0qriDRbIM2XKdwPK8vEqk@Sy2@ZJYxFHXcG62TcDuqdE8JJFtv@/XwgRAoKR8LJvA2AdJZXtBm4ajfc0HhZPBdPJJNnZ8Bb0SwfflYjX/LAKuOc/XJ/GgGivvQAhqjH979/QaUtLUjcgH2ZbuFVYQUQ4A3slilLIDhSdWB0m/ZR9JEv5R/tKCABAYbz6l/@azCnr11JnOSYS8/Y5ttkJuo1p4UGyzUDqJ7QSiXyfcsayDeClWASh0MFVQXXgfq3L7GxBPWMUOXxseAK@kz9z@oAYLhIdBI@o5a2qU7XbcMuRtRKS6C/j6Y6hmgkVHEQ8l0qceA5yNDhUSj1wUIjJpL2cKO7LNvtc9YukNqiljqzsDqLhPj4tgAaK6D7YV8bDuGRpBV0pgn96Xp15wXz6TTXl3cSeOgKtakG3dKuNhrEfNRrJxRwnp5Tzbene56jT/9ggpfNHf9B4qJf9r6hGehZJQJcg2doyN6urSlpweKn6iz9ELFEUFC6muCZyRMFpjWzgSlkely9s3EUBOAZPzc4VzIgu6Fu7BmlVNJDbSQh6P5pjQdjaRhvnu8OiT6YtiSU9NgIrrd4bmqI8kP90CA2hZ5T7WRZKF7wrb0718PZ26@QDraWEiZtINzkagwjv4m1CjD0xFW65HbQfY5seB@5357e@gKT6VJLSgjEWH@ZIGrbQ38qghr4AWWkiE7r85UzxSl5OxNYmdu@jD3QiUxHC3gx3SRV8VkldFTwSYXHiZf7utfh88nyU8eozHSrXdS0jcfUg@4syjHg4Yx6i7y/8Adt2DxMqbIqT7tZ/PuK8Ym2IpRZptvqb9rFbBauCKG1V3fzn60BE9CQ1IBj@CHz1NH4trC3VPayVJkWx9PNBRbva3eVOvpLSlCf/XoJ2A/0qgj/RFtomgHgOaV6g9BKFD8t/s2Kxxu8mAFrHKE1o441ZdPbcngKLZjvk3@l75CrGyPoIglokdon7S3VkzhEryX4J9qsZJ2lrEYi7bgkOIklo4zD6WmoSWImUh4ZujJoPu7OqlgpSt2i5sk2S/B6FICLSATar3v8ZAa3DKAQKBWIS3u@EmogOMhNfR2z/FIpaFTlDHkrcHu9DwpCCjzqgFSTl@sP06yBwE@@APrKGFqaid79khuKG4qN1ujJTzWDvbyPjFIurLycIZW/Pt/JYOapRLWmioEys@z8UGGdssDv@BPNi@WB4WvlxkvBoMJdGFFnlw0@dKnigjsf4OlTOzJFuFy2xgbjCGmhsLm2KBi0c3cGTE3wmZRh9LBi@XUov4Gw09GdTIPjbXkms8YrtiuVGPZWOjDw1EX9mXtnAg4r73hspR3gHstf38COq0OZU3qfu5k4ynI2OrbHr4DEihSNIW4YJNTH42gT9QvVoEVmH3YY7wfOi@krZAYQ6bsbtpFqQ@JiNP22xrbJCqngxCz1nyHOiFzifl7aZk/jJJGWAHL9nBMO7QwogDwoIswJocw7OssGAWslyGxrxmOkl4HthYyVYglqlh2uvRHja7zpCBkHEuh4qL8WkW5rGK/1S5GFiiumCzrJT2oHmV/Ceuk9VEOvUYeEu@SqrAOTsRvVi5chH@1gE@sDgegzNKcLvZHO29p/J4uJ8Io3y5lNOHcFAHyqLYGRNObp@by0IOyAkcTBIY1GgXqJKUAKy@vFEwkE5iIrAmtZ@6VwtBJ6ABe5efmwdYAWvlAOKgyvp0HxWEKnWXMvmNWEGsWNCStrBIUT/6JlxOlMVPIR9gAL7kDshw6OmsuRBSmyio6tR2yRLxpV49rLqfgU0VIv4CNHLDmoHobj189l7FFION3ER/Whl6ihBRqNJCe9kszSr7/GgYOnl9kvsqTWt7gGsQT185eoMjj22PcYeegvgsseitM8hTecMIOzilJW7jDIWvYVWQXzLRwGqZkrrC9pDhG2TeFTc0SVqAVIbO17@FVUHXXu4BudFxkVnZgpsgLbIfRstVqnvYJpX8BtsQq@xQuEjhRPwV/PCeiIu46s8BOlaqOWcJbo1Xs62R1rlS8AbK9O8tnF3AjZGv26ceeiDIf5tmaPNaqw4HsoMm9U86hVHKJ@JT5jTW040AlK@gFBHGdhGlcg593/f20s0cnCWdEsH88l6EjqATHyAs9usjyMc5s2wD6vdpCMsYC8FkeZFOQnw9L22hGKE6iQ@noDjgkNim@cnWmJ0PABh6ow3F4S0GjXlYLFZyVLiEdrjRh@1BraT7NUg6pnppygyxgPD0dfII2zp1FaWFONTv@Y9Qeaszs7o3nWpi@w16WPfXkJPbGxXLd8lmSI/Rui0dOBaa8A8e070tIj5HDtGOvf1QOi/3inibCPXxaJfu1f1ipa6w5/ZjERq8pLrGr6ZTauyCWPqDryOWe9RpnKQjirOxmhz897mM7S6qtQaCBjfhIVuUaCVPHu9B3e49ZhFhTVtQWNX46hXpr/L1LaBrNGe6eUGzjxrtLJysA5CPyCKv6SC5AnDOZWwkEkqgshS965N5EZJkr@yaG311nW03F7RACaC0P8hJ@YAIisoc5KavlLNDNJ5/@dHTEoERNjGANMsr2aoLjj@229/YnfGjMtbwzMNbqMhgNyhRCpFXvtbmn37wHgtKn2axXXp5olH3smAJzXhuFqJClzdntFCT2NY9dXWmxPqvl8LZKF@uFPDIiBaapo6z8Bq9k689p54mmVrnbtIxWLFj9bi8Qg9zRzlIMk7JOnicq/pn@9g@5fyz9vN641UobPQdixSAo9YpsjCSu19sm@PCPveiEFPc23iHfyvldgFEnaP5WuQ8sjpar4f7@nJ7qNzCYudPgHdTbGfcJD5fikhSFXnYFCvX4FQ7D2PPqOrOvjRKbg6FiHbuRcH7ZotM08f2Snvn2Mb0xdv/2SjUZzMZQVvrO0xsqy9wdAjC7ml2kA//ta@6Omi6kBt0T3uT6mfRpxCuTfIM6LqfSASov6FEZJ9pDd08@nZ8oq0dY4HiOg101gsz/rZH94WPFNhJB/bSXRJZ3wPde0GQcpA5JEE/6EknBzTMFJPmx2TdpPkiQ@GxjM20jqZfsGA2iLeZ7mZRjxVkII6w0sfCShZW9iMJ8wV6Ch@lhcJabucRGlQ@52jhGbP5LWQ1i3g9qGuO4PSWAqHWFAJX1OofKLRpyES0AmYsTHbdAa4c11Xr8UYEVIBD6h4q3cgLxPVIjT0duUtD5i5UiAZpmHgpW0toP6uw12MRf91IjcPHE4DCNG00Rm487ACjB68/uI@IBeZVJa@7WMT/1H6@5VEiFlwkBQM2me7ikxYqoDH7Vzqp@rVdOoVs7dESQ2AgBHYB4nWAwwzh8Bl3AU4ZLBrUw9rP1hszQ3BQO7nEHZ/uJ8Me4Os8gT3Mbg5z2IYZzCKs13D8kXc5T3mimUgj@2p5YoKFx1Xv6c5aFr2cNWO6laPCErPx4/EjamPfLyB7N680YGgxh/iRSS6BeIkSdCSMb0UsxKWH9EqLXhF8eYFm48tlew3/r51BqKrsMF@hbQAd2UI2MPgEX@GQaD6SvYnmf@XaxAianHCarciVg3451ZdOPeXeNzSY7t/TQkwuI3idbZDDFKrhn3ruQPt7hhtg15wwg8oXU3i@itUsSD@U5YCF6M2Wd5ajXIoLqIv8AJ7vqWDWanXPKbb/6BGG7BCZVtihPDzSDoWH5PpAYnrvIXs/on6ni/O1MDRBdsCQmk2uSPe@hJ1wYuiWOlmE3hhAaj7Ta5NB1f@sJYtTB8d2kE7ZqgZK@s8gfWdYHJIVyCuZHVFjs2SgkJMssfNyHCw5038N2/2B@kn@QtjP6W0D@cY6@idExtFPb0swmGqRm69KMJAQtTxN1JWOK0CkQnaYTs7N6J5H4xhAUIP21yxUYzKZh7uyxWId902bVm/hPU8QmF/ecUlYh95TiuS/u/97SyjvvHpAjPZPmBK2jsGs6wm9ImIbQ2/uYrmzaixb@4lxEoryoLqTrz0mv5AM6p47@PYGnoLayJvUxkN1bMOc@fZu0egBbyr/DVrS8PlD7JwzreJGxvYquwjUoAECd51YVvrYxmkWzGUb5xi1VVyCJ3Rz3xBpkWX1VOXv37/HR6eeD/wf "Jelly – Try It Online") First, a disclaimer: the question here gives two links to the list of colors that need to be encoded for this problem, and the two links don't match each other. This answer is using the "ease of programming" list, color/rgb.txt, which contains 949 colors (this is apparently a newer, corrected version of the list compared to the HTML version); I was using this list to develop and test the program, and didn't notice it was different from the HTML version until I had already written the program (although I would probably have preferred this version anyway). At the time I downloaded it, it had SHA-256 hash `c4842f383db18beb920f07acecbe5f6bb32be828f3d19c0ddb804a01a292e433`. (This is probably an argument against hosting important challenge data on an external website!) ## Algorithm This answer uses the technique I discovered in [this answer](https://codegolf.stackexchange.com/a/214222) for producing an asymptotically optimal solution to implementing any function defined in terms of input/output pairs in a way that treats the input and output as opaque (and thus does not take advantage of any special structure in it). 949 colors × 3 bytes per colors is 2847, so there's only 47 bytes of overhead here. Some of the overhead is due to the fact that Jelly gives special meanings to six different characters within string literals, and thus those characters need to be avoided when writing a literal, slightly reducing the density with which large literals can be stored (this cost 12 bytes); some of the overhead is due to the fact that 16777216 is not prime, and Jelly does not have built in finite field operations for non-prime-sized fields, so there are minor losses due to using 16777259 instead; and some of the overhead is the need to write a decompressor, although doing so is very terse in Jelly. The basic idea of the program is to give the color name provided as input to 949 different hash functions, each of which returns an output in the range 1…16777259. These results are interpreted as a vector in **GF**(16777259). (We actually use 1000 hash functions in order to avoid needing to write the number 949 into the program explicitly, but all but the first 949 are ignored.) The lookup table is also encoded as a vector in **GF**(16777259), and to look up a given string, we take the dot product of its hash vector and the lookup table. The result is a number in the range 0…16777258, which is then converted to a 6-digit hexadecimal number and used as a color code. In order to convert to 6-digit hexadecimal in a terse way in Jelly, we actually arrange the lookup table so that the result obtained from the table will be too low by 43, mod 16777216. We then add 16777259 to that result, producing a number which is exactly 7 digits long in hexadecimal, and for which the last 6 digits will be the number we want. This technique avoids any need to explicitly specify the number of digits we want in the output, and any need to implement Jelly code for padding a number to a given length (as far as I can tell, there isn't a builtin for this). As for the lookup table itself, finding the appropriate elements to place in the lookup table vector is a case of solving 949 simultaneous equations (in effect, each input-output pair produces a randomly generated equation, because the hashing will give us random coefficients and we need that particular input to match that particular output); with 949 equations and 949 variables (the 949 elements of the lookup table), it is very likely that there will be exactly one solution (I didn't check for a second solution, but suspect that none exists). I used a combination of Perl and Jelly in order to formulate the 949 equations that were necessary, and then used [Sage](https://www.sagemath.org/) to solve them (it took about 2½ minutes to solve the 949 equations), producing the appropriate lookup table. ## Explanation The first line of the program is `“¡×l®’`; this is the compressed representation of the constant 16777259. That constant is used all over the program, so it helps to give it a name so that we can write it more tersely. Jelly autogenerates the name `1£` for it, but because it's the only defined helper constant (or helper function), we can also refer to it as `¢`; that's a byte shorter, so it's the notation used throughout the rest of the program. The second line is the main program: ``` ȷ;€¢ḥ€³ḋ“…’b¢$¤%¢+¢b⁴‘ịØhḊ”#; ḥ Hash ³ the input € with each of these configurations: € each number from 1 to ̛̛ȷ 1000 ; paired with ¢ the constant ¢; ḋ take the dot product with ¤ the constant produced by “…’ a big compressed integer b¢$ interpreted as base ¢ digits; %¢ take that value modulo ¢, +¢ add ¢, b convert to base ⁴ 16, ‘ị index (0-indexed) into Øh a list of hexadecimal digits, Ḋ delete the first, ; and prepend ”# a "#" character ``` The hash configuration consists of two paired arguments, a salt and a codomain (here `¢` to produce an output in the range 1…`¢`. The `³` near the start bothers me a bit (Jelly normally has implicit input); it appears to be necessary for the program to parse correctly, but I'm not sure why. ## Evaluation The program could be made slightly terser by using a better method of storing the lookup table (i.e. an external file, or a length-delimited string literal, neither of which is easily possible in Jelly); by using a finite field of the correct size (**GF**(16777216) exists, but is not readily usable from Jelly); or by writing the decompressor more tersely (which is going to be hard in most languages; Jelly allows it to be written very tersely already). However, it's already close to the theoretical optimum (2847 bytes) for a program that does not take advantage of any structure in the input or output (besides the fact that all the outputs are three bytes long; this program uses 12 bytes to convert the output from 24-bit numbers into color codes, so the lookup table and its decompressor use only 35 bytes more than the theoretical optimum). It strikes me that the entire algorithm used in this answer, and in the other answer, might make for a decent builtin in a golfing language. "Map each of these inputs X to each of these outputs Y" is a fairly common task to need to solve when golfing. Using this algorithm as-is is normally only worthwhile for "big" problems, because of the need to write a decompressor, but if it were available as a builtin it would avoid that problem (and it could also allow for the use of finite fields other than modulo-prime fields, which are too verbose to write decompressors for in typical golfing languages, but which would not be an issue for the implementation of a builtin). It might well be that such a builtin would provide the best possible solution for any "unstructured" map-X-to-Y challenge (with finitely many possible inputs), with the rest of the language used to take advantage of any structure in X or Y that enables shorter implementations than could be produced by an algorithm that treats them as opaque objects. (One potential issue is that the equations may be unsolvable, especially if the codomain is small, but the odds of this are fairly low (slightly, but not much, larger than 1 divided by the size of the universe from which the outputs are drawn). Even if they did end up unsolvable, simply adding one or two additional hash functions, and corresponding lookup table entries, would be highly likely to make them solvable again.) [Answer] # Bash + coreutils/xxd, 4064 bytes Data 3796 bytes [(hex dump of data file)](http://pastebin.com/UMjZ0qdy) Bash 268 bytes ``` h=`md5sum<<<$1|xxd -r -p|xxd -b -g0 -l128 -c128|cut -c18,20,26,41,46,49,65,85,88,90,94,95,118,135`;case $1 in mud|aqua?blue)h=0${h%0};;esac;xxd -b -g4 -c4 d|while read -r x;do let b+=2#${x:23:2};case ${x:9:14} in $h)printf '#%04x%02x\n' $((2#${x:25:16})) $b;;esac;done ``` **Ungolfed** ``` # Set h to select 14 bits from the md5sum in base 2 h=`md5sum<<<$1 | \ xxd -r -p|xxd -b -g0 -l128 -c128|cut -c18,20,26,41,46,49,65,85,88,90,94,95,118,135` # Disambiguate hash collisions case $1 in mud|aqua?blue) h=0${h%0} ;; esac # process each 32-bit record: # First 14 bits are hash # Next 2 bits are blue deltas # Final 16 bits rg xxd -b -g4 -c4 d | \ while read -r x; do let b+=2#${x:23:2}; case ${x:9:14} in $h) printf '#%04x%02x\n' $((2#${x:25:16})) $b ;; esac; done ``` The overall idea is to scan through 32-bit fields, find the matching unique 14-bit hash, and print the color code at that location. The 18-bit color encoding leverages Super Chafouin's approach. The unique 14-bit hash starts with a subset of 14 of the bits from the 128-bit md5sum. To find those bits I used a genetic algorithm coded in C++ [here](http://pastebin.com/13PCFYgv). The code pre-loads a fixed file called "data", which is just the md5sum's, one per line, in binary. If you need that in recipe form, this will create the data file: ``` (cut -f1 rgb.txt|while read x; do md5sum<<<$x | xxd -r -p | xxd -b -g16 -c16| cut -d' ' -f 2;done) > data ``` I find the best candidate 14 bits (that I've seen so far) from this code in generation 2, but this set has two collisions. Specifically: "mud" and "pale purple" map to the same value, and "aqua blue" and "light green" map to the same value. Since there are only two collisions and I haven't found anything better, I just disambiguate them; turns out half of each of these bucket values is unused. I already tried compression on d; but neither bzip2, nor gzip, nor xz appears to shrink d's size. ]
[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/3184/edit) Can you solve the [eight queens puzzle](http://en.wikipedia.org/wiki/8_queens) at compile-time? Pick any suitable output format. I'm particularly interested in a C++ template metaprogramming solution, but you can use languages that have similar constructs, like, for example, Haskell's type system. Ideally your metaprogram would output all solutions. No hardcoding. [Answer] My meta-program finds all 92 solutions. They are printed as error messages: ``` error: ‘solution’ is not a member of ‘std::integral_constant<int, 15863724>’ ``` This means the first queen should be placed at y=1, the second at y=5, the third at y=8 and so on. The meta-program consists of two mutually recursive meta-functions `put_queen` and `put_queens`: ``` #include <type_traits> template<int queens, int rows, int sums, int difs, int x, int y> struct put_queen; template<int queens, int rows, int sums, int difs, int x> struct put_queens : std::integral_constant<int, // try all 8 possible values for y put_queen<queens, rows, sums, difs, x, 1>::value | put_queen<queens, rows, sums, difs, x, 2>::value | put_queen<queens, rows, sums, difs, x, 3>::value | put_queen<queens, rows, sums, difs, x, 4>::value | put_queen<queens, rows, sums, difs, x, 5>::value | put_queen<queens, rows, sums, difs, x, 6>::value | put_queen<queens, rows, sums, difs, x, 7>::value | put_queen<queens, rows, sums, difs, x, 8>::value > {}; template<int queens, int rows, int sums, int difs, int x, int y> struct put_queen : std::conditional< // if blocked rows & (1 << y) || sums & (1 << (x + y)) || difs & (1 << (x - y + 8)), // then backtrack std::integral_constant<int, 0>, // else recurse put_queens<queens * 10 + y, rows | (1 << y), sums | (1 << (x + y)), difs | (1 << (x - y + 8)), x + 1 > >::type {}; ``` The variable `queens` stores the y coordinates of the queens placed on the board so far. The following three variables store the rows and diagonals that are already occupied by queens. `x` and `y` should be self-explanatory. The first argument to `conditional` checks whether the current position is blocked. If it is, we backtrack by returning the (meaningless) result 0. Otherwise, the queen is placed on the board, and the recursion continues with the next column. When `x` reaches 8, we have found a solution: ``` template<int queens, int rows, int sums, int difs> struct put_queens<queens, rows, sums, difs, 8> { // print solution as error message by accessing non-existent member enum { value = std::integral_constant<int, queens>::solution }; }; ``` Since `integral_constant` has no member `solution`, the compiler prints `queens` as an error message. To start the recursion, we inspect the `value` member of the empty board: ``` int go = put_queens<0, 0, 0, 0, 0>::value; ``` The complete program can be found at [ideone](https://ideone.com/PJtX2f). [Answer] I came up with a solution that uses the Haskell type system. I googled a bit for an existing solution to the problem *at the value level*, changed it a bit, and then lifted it to the type level. It took a lot of reinventing. I also had to enable a bunch of GHC extensions. First, since integers are not allowed at the type level, I needed to reinvent the natural numbers once more, this time as types: ``` data Zero -- type that represents zero data S n -- type constructor that constructs the successor of another natural number -- Some numbers shortcuts type One = S Zero type Two = S One type Three = S Two type Four = S Three type Five = S Four type Six = S Five type Seven = S Six type Eight = S Seven ``` The algorithm I adapted makes additions and subtractions on naturals, so I had to reinvent these as well. Functions at the type level are defined with resort to type classes. This requires the extensions for multiple parameter type classes and functional dependencies. Type classes cannot "return values", so we use an extra parameter for that, in a manner similar to PROLOG. ``` class Add a b r | a b -> r -- last param is the result instance Add Zero b b -- 0 + b = b instance (Add a b r) => Add (S a) b (S r) -- S(a) + b = S(a + b) class Sub a b r | a b -> r instance Sub a Zero a -- a - 0 = a instance (Sub a b r) => Sub (S a) (S b) r -- S(a) - S(b) = a - b ``` Recursion is implemented with class assertions, so the syntax looks a bit backward. Next up were booleans: ``` data True -- type that represents truth data False -- type that represents falsehood ``` And a function to do inequality comparisons: ``` class NotEq a b r | a b -> r instance NotEq Zero Zero False -- 0 /= 0 = False instance NotEq (S a) Zero True -- S(a) /= 0 = True instance NotEq Zero (S a) True -- 0 /= S(a) = True instance (NotEq a b r) => NotEq (S a) (S b) r -- S(a) /= S(b) = a /= b ``` And lists... ``` data Nil data h ::: t infixr 0 ::: class Append xs ys r | xs ys -> r instance Append Nil ys ys -- [] ++ _ = [] instance (Append xs ys rec) => Append (x ::: xs) ys (x ::: rec) -- (x:xs) ++ ys = x:(xs ++ ys) class Concat xs r | xs -> r instance Concat Nil Nil -- concat [] = [] instance (Concat xs rec, Append x rec r) => Concat (x ::: xs) r -- concat (x:xs) = x ++ concat xs class And l r | l -> r instance And Nil True -- and [] = True instance And (False ::: t) False -- and (False:_) = False instance (And t r) => And (True ::: t) r -- and (True:t) = and t ``` `if`s are also missing at the type level... ``` class Cond c t e r | c t e -> r instance Cond True t e t -- cond True t _ = t instance Cond False t e e -- cond False _ e = e ``` And with that, all the supporting machinery I used was in place. Time to tackle the problem itself! Starting with a function to test if adding a queen to an existing board is ok: ``` -- Testing if it's safe to add a queen class Safe x b n r | x b n -> r instance Safe x Nil n True -- safe x [] n = True instance (Safe x y (S n) rec, Add c n cpn, Sub c n cmn, NotEq x c c1, NotEq x cpn c2, NotEq x cmn c3, And (c1 ::: c2 ::: c3 ::: rec ::: Nil) r) => Safe x (c ::: y) n r -- safe x (c:y) n = and [ x /= c , x /= c + n , x /= c - n , safe x y (n+1)] ``` Notice the use of class assertions to obtain intermediate results. Because the return values are actually an extra parameter, we can't just call the assertions directly from each other. Again, if you've used PROLOG before you may find this style a bit familiar. After I made a few changes to remove the need for lambdas (which I could have implemented, but I decided to leave for another day), this is what the original solution looked like: ``` queens 0 = [[]] -- The original used the list monad. I "unrolled" bind into concat & map. queens n = concat $ map f $ queens (n-1) g y x = if safe x y 1 then [x:y] else [] f y = concat $ map (g y) [1..8] ``` `map` is a higher order function. I thought implementing *higher order meta-functions* would be too much hassle (again the lambdas) so I just went with a simpler solution: since I know what functions will be mapped, I can implement specialized versions of `map` for each, so that those are not higher-order functions. ``` -- Auxiliary meta-functions class G y x r | y x -> r instance (Safe x y One s, Cond s ((x ::: y) ::: Nil) Nil r) => G y x r class MapG y l r | y l -> r instance MapG y Nil Nil instance (MapG y xs rec, G y x g) => MapG y (x ::: xs) (g ::: rec) -- Shortcut for [1..8] type OneToEight = One ::: Two ::: Three ::: Four ::: Five ::: Six ::: Seven ::: Eight ::: Nil class F y r | y -> r instance (MapG y OneToEight m, Concat m r) => F y r -- f y = concat $ map (g y) [1..8] class MapF l r | l -> r instance MapF Nil Nil instance (MapF xs rec, F x f) => MapF (x ::: xs) (f ::: rec) ``` And the last meta-function can be written now: ``` class Queens n r | n -> r instance Queens Zero (Nil ::: Nil) instance (Queens n rec, MapF rec m, Concat m r) => Queens (S n) r ``` All that's left is some kind of driver to coax the type-checking machinery to work out the solutions. ``` -- dummy value of type Eight eight = undefined :: Eight -- dummy function that asserts the Queens class queens :: Queens n r => n -> r queens = const undefined ``` This meta-program is supposed to run on the type checker, so one can fire up `ghci` and ask for the type of `queens eight`: ``` > :t queens eight ``` This will exceed the default recursion limit rather fast (it's a measly 20). To increase this limit, we need to invoke `ghci` with the `-fcontext-stack=N` option, where `N` is the desired stack depth (N=1000 and fifteen minutes is not enough). I haven't seen this run to completion yet, as it takes a very long time, but I've managed to run up to `queens four`. There's [a full program](http://www.ideone.com/KMvsv) on ideone with some machinery for pretty printing the result types, but there only `queens two` can run without exceeding the limits :( [Answer] ## C, via the preprocessor I think the ANSI committee made a conscious choice not to extend the C preprocessor to the point of being Turing-complete. In any case, it's not really powerful enough to solve the eight queens problem. Not in any sort of general fashion. But it can be done, if you're willing to hard-code the loop counters. There's no real way to loop, of course, but you can use self-inclusion (via `#include __FILE__`) to get a limited sort of recursion. ``` #ifdef i # if (r_(i) & 1 << j_(i)) == 0 && (p_(i) & 1 << i + j_(i)) == 0 \ && (n_(i) & 1 << 7 + i - j_(i)) == 0 # if i == 0 # undef i # define i 1 # undef r1 # undef p1 # undef n1 # define r1 (r0 | (1 << j0)) # define p1 (p0 | (1 << j0)) # define n1 (n0 | (1 << 7 - j0)) # undef j1 # define j1 0 # include __FILE__ # undef j1 # define j1 1 # include __FILE__ # undef j1 # define j1 2 # include __FILE__ # undef j1 # define j1 3 # include __FILE__ # undef j1 # define j1 4 # include __FILE__ # undef j1 # define j1 5 # include __FILE__ # undef j1 # define j1 6 # include __FILE__ # undef j1 # define j1 7 # include __FILE__ # undef i # define i 0 # elif i == 1 # undef i # define i 2 # undef r2 # undef p2 # undef n2 # define r2 (r1 | (1 << j1)) # define p2 (p1 | (1 << 1 + j1)) # define n2 (n1 | (1 << 8 - j1)) # undef j2 # define j2 0 # include __FILE__ # undef j2 # define j2 1 # include __FILE__ # undef j2 # define j2 2 # include __FILE__ # undef j2 # define j2 3 # include __FILE__ # undef j2 # define j2 4 # include __FILE__ # undef j2 # define j2 5 # include __FILE__ # undef j2 # define j2 6 # include __FILE__ # undef j2 # define j2 7 # include __FILE__ # undef i # define i 1 # elif i == 2 # undef i # define i 3 # undef r3 # undef p3 # undef n3 # define r3 (r2 | (1 << j2)) # define p3 (p2 | (1 << 2 + j2)) # define n3 (n2 | (1 << 9 - j2)) # undef j3 # define j3 0 # include __FILE__ # undef j3 # define j3 1 # include __FILE__ # undef j3 # define j3 2 # include __FILE__ # undef j3 # define j3 3 # include __FILE__ # undef j3 # define j3 4 # include __FILE__ # undef j3 # define j3 5 # include __FILE__ # undef j3 # define j3 6 # include __FILE__ # undef j3 # define j3 7 # include __FILE__ # undef i # define i 2 # elif i == 3 # undef i # define i 4 # undef r4 # undef p4 # undef n4 # define r4 (r3 | (1 << j3)) # define p4 (p3 | (1 << 3 + j3)) # define n4 (n3 | (1 << 10 - j3)) # undef j4 # define j4 0 # include __FILE__ # undef j4 # define j4 1 # include __FILE__ # undef j4 # define j4 2 # include __FILE__ # undef j4 # define j4 3 # include __FILE__ # undef j4 # define j4 4 # include __FILE__ # undef j4 # define j4 5 # include __FILE__ # undef j4 # define j4 6 # include __FILE__ # undef j4 # define j4 7 # include __FILE__ # undef i # define i 3 # elif i == 4 # undef i # define i 5 # undef r5 # undef p5 # undef n5 # define r5 (r4 | (1 << j4)) # define p5 (p4 | (1 << 4 + j4)) # define n5 (n4 | (1 << 11 - j4)) # undef j5 # define j5 0 # include __FILE__ # undef j5 # define j5 1 # include __FILE__ # undef j5 # define j5 2 # include __FILE__ # undef j5 # define j5 3 # include __FILE__ # undef j5 # define j5 4 # include __FILE__ # undef j5 # define j5 5 # include __FILE__ # undef j5 # define j5 6 # include __FILE__ # undef j5 # define j5 7 # include __FILE__ # undef i # define i 4 # elif i == 5 # undef i # define i 6 # undef r6 # undef p6 # undef n6 # define r6 (r5 | (1 << j5)) # define p6 (p5 | (1 << 5 + j5)) # define n6 (n5 | (1 << 12 - j5)) # undef j6 # define j6 0 # include __FILE__ # undef j6 # define j6 1 # include __FILE__ # undef j6 # define j6 2 # include __FILE__ # undef j6 # define j6 3 # include __FILE__ # undef j6 # define j6 4 # include __FILE__ # undef j6 # define j6 5 # include __FILE__ # undef j6 # define j6 6 # include __FILE__ # undef j6 # define j6 7 # include __FILE__ # undef i # define i 5 # elif i == 6 # undef i # define i 7 # undef r7 # undef p7 # undef n7 # define r7 (r6 | (1 << j6)) # define p7 (p6 | (1 << 6 + j6)) # define n7 (n6 | (1 << 13 - j6)) # undef j7 # define j7 0 # include __FILE__ # undef j7 # define j7 1 # include __FILE__ # undef j7 # define j7 2 # include __FILE__ # undef j7 # define j7 3 # include __FILE__ # undef j7 # define j7 4 # include __FILE__ # undef j7 # define j7 5 # include __FILE__ # undef j7 # define j7 6 # include __FILE__ # undef j7 # define j7 7 # include __FILE__ # undef i # define i 6 # elif i == 7 printf("(1 %d) (2 %d) (3 %d) (4 %d) (5 %d) (6 %d) (7 %d) (8 %d)\n", j0 + 1, j1 + 1, j2 + 1, j3 + 1, j4 + 1, j5 + 1, j6 + 1, j7 + 1); # endif # endif #else #include <stdio.h> #define _cat(a, b) a ## b #define j_(i) _cat(j, i) #define n_(i) _cat(n, i) #define p_(i) _cat(p, i) #define r_(i) _cat(r, i) int main(void) { # define i 0 # define j0 0 # include __FILE__ # undef j0 # define j0 1 # include __FILE__ # undef j0 # define j0 2 # include __FILE__ # undef j0 # define j0 3 # include __FILE__ # undef j0 # define j0 4 # include __FILE__ # undef j0 # define j0 5 # include __FILE__ # undef j0 # define j0 6 # include __FILE__ # undef j0 # define j0 7 # include __FILE__ # undef j0 return 0; } #endif ``` Despite the horrific amount of repetitive content, let me assure you that it truly is solving the eight queens problem algorithmically. Unfortunately the one thing that I couldn't do with the preprocessor is implement a general push-down stack data structure. The upshot is that I had to hard-code the value of `i` wherever it was used to select another value to set. (As opposed to retrieving values, which could be done completely generally. That's why the `#if` at the top of the file, which is what decides if a queen can be added at the current position, didn't need to be repeated eight times.) Within the preprocessor code, `i` and `j` indicate the current position being considered, while `r`, `p`, and `n` keep track of which ranks and diagonals are currently unavailable for placement. However, `i` also doubles as the counter marking the current depth of recursion, so really all the other values actually use i as a sort of subscript, so that their values are preserved when resuming from a recursion. (And also because of the serious difficulty of modifying the value of a preprocessor symbol without completely replacing it.) The compiled program prints all 92 solutions. The solutions are embedded directly into the executable; the preprocessor output looks like this: ``` /* ... #included content from <stdio.h> ... */ int main(void) { printf("(1 %d) (2 %d) (3 %d) (4 %d) (5 %d) (6 %d) (7 %d) (8 %d)\n", 0 + 1, 4 + 1, 7 + 1, 5 + 1, 2 + 1, 6 + 1, 1 + 1, 3 + 1); printf("(1 %d) (2 %d) (3 %d) (4 %d) (5 %d) (6 %d) (7 %d) (8 %d)\n", 0 + 1, 5 + 1, 7 + 1, 2 + 1, 6 + 1, 3 + 1, 1 + 1, 4 + 1); printf("(1 %d) (2 %d) (3 %d) (4 %d) (5 %d) (6 %d) (7 %d) (8 %d)\n", 0 + 1, 6 + 1, 3 + 1, 5 + 1, 7 + 1, 1 + 1, 4 + 1, 2 + 1); /* ... 88 more solutions ... */ printf("(1 %d) (2 %d) (3 %d) (4 %d) (5 %d) (6 %d) (7 %d) (8 %d)\n", 7 + 1, 3 + 1, 0 + 1, 2 + 1, 5 + 1, 1 + 1, 6 + 1, 4 + 1); return 0; } ``` It can be done, even though it clearly shouldn't. [Answer] Here's a C++11 solution without any templates: ``` constexpr int trypos( int work, int col, int row, int rows, int diags1, int diags2, int rowbit, int diag1bit, int diag2bit); constexpr int place( int result, int work, int col, int row, int rows, int diags1, int diags2) { return result != 0 ? result : col == 8 ? work : row == 8 ? 0 : trypos(work, col, row, rows, diags1, diags2, 1 << row, 1 << (7 + col - row), 1 << (14 - col - row)); } constexpr int trypos( int work, int col, int row, int rows, int diags1, int diags2, int rowbit, int diag1bit, int diag2bit) { return !(rows & rowbit) && !(diags1 & diag1bit) && !(diags2 & diag2bit) ? place( place(0, work*10 + 8-row, col + 1, 0, rows | rowbit, diags1 | diag1bit, diags2 | diag2bit), work, col, row + 1, rows, diags1, diags2) : place(0, work, col, row + 1, rows, diags1, diags2); } int places = place(0, 0, 0, 0, 0, 0, 0); ``` The solution is encoded as decimal digits, as in FredOverflow's answers. GCC 4.7.1 compiles the above file into the following assembly source with `g++ -S -std=c++11 8q.cpp`: ``` .file "8q.cpp" .globl places .data .align 4 .type places, @object .size places, 4 places: .long 84136275 .ident "GCC: (GNU) 4.7.1" .section .note.GNU-stack,"",@progbits ``` The value of the symbol `places` is 84136275, i.e. the first queen is at a8, the second at b4 etc. [Answer] c++ template, with only one template class is defined: ``` template <int N, int mask, int mask2, int mask3, int remainDigit, bool fail> struct EQ; template <int N, int mask, int mask2, int mask3> struct EQ<N, mask, mask2, mask3, 0, false> { enum _ { Output = (char [N])1 }; }; template <int N, int mask, int mask2, int mask3, int i> struct EQ<N, mask, mask2, mask3, i, true> { }; template <int N, int mask, int mask2, int mask3, int i> struct EQ<N, mask, mask2, mask3, i, false> { enum _ { _ = sizeof(EQ<N*10+1, mask|(1<<1), mask2|(1<<(1+i)), mask3|(1<<(1+8-i)), i-1, (bool)(mask&(1<<1)) || (bool)(mask2&(1<<(1+i))) || (bool)(mask3&(1<<(1+8-i)))>) + sizeof(EQ<N*10+2, mask|(1<<2), mask2|(1<<(2+i)), mask3|(1<<(2+8-i)), i-1, (bool)(mask&(1<<2)) || (bool)(mask2&(1<<(2+i))) || (bool)(mask3&(1<<(2+8-i)))>) + sizeof(EQ<N*10+3, mask|(1<<3), mask2|(1<<(3+i)), mask3|(1<<(3+8-i)), i-1, (bool)(mask&(1<<3)) || (bool)(mask2&(1<<(3+i))) || (bool)(mask3&(1<<(3+8-i)))>) + sizeof(EQ<N*10+4, mask|(1<<4), mask2|(1<<(4+i)), mask3|(1<<(4+8-i)), i-1, (bool)(mask&(1<<4)) || (bool)(mask2&(1<<(4+i))) || (bool)(mask3&(1<<(4+8-i)))>) + sizeof(EQ<N*10+5, mask|(1<<5), mask2|(1<<(5+i)), mask3|(1<<(5+8-i)), i-1, (bool)(mask&(1<<5)) || (bool)(mask2&(1<<(5+i))) || (bool)(mask3&(1<<(5+8-i)))>) + sizeof(EQ<N*10+6, mask|(1<<6), mask2|(1<<(6+i)), mask3|(1<<(6+8-i)), i-1, (bool)(mask&(1<<6)) || (bool)(mask2&(1<<(6+i))) || (bool)(mask3&(1<<(6+8-i)))>) + sizeof(EQ<N*10+7, mask|(1<<7), mask2|(1<<(7+i)), mask3|(1<<(7+8-i)), i-1, (bool)(mask&(1<<7)) || (bool)(mask2&(1<<(7+i))) || (bool)(mask3&(1<<(7+8-i)))>) + sizeof(EQ<N*10+8, mask|(1<<8), mask2|(1<<(8+i)), mask3|(1<<(8+8-i)), i-1, (bool)(mask&(1<<8)) || (bool)(mask2&(1<<(8+i))) || (bool)(mask3&(1<<(8+8-i)))>)}; }; int main(int argc, _TCHAR* argv[]) { // output all solutions to eight queens problems as error messages sizeof(EQ<0, 0, 0, 0, 8, false>); return 0; } ``` so the error message will be looked like: error C2440: 'type cast' : cannot convert from 'int' to 'char [15863724]' ]
[Question] [ **This is part of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. [Go here](https://codegolf.stackexchange.com/q/144601/8478) for the robbers' part.** ## The Cops' Challenge You should write a program or function in a language of your choice, which outputs the string `Haystack`. However, it must be possible to remove some subset of characters from your program (without reordering the rest), such that the resulting string is *also* a valid program in the same language, which prints `Needle` instead. Both programs/functions may optionally print a single trailing newline (independently of each other), but nothing else. Output is case sensitive and must follow the exact casing provided. Your goal, of course, is to hide the "needle" very well. But note that your submission can be cracked with *any* valid solution, not just the one you intended. Please include in your answer: * The language (and version if relevant) of your submission. * The size of the Haystack program in bytes. * The Haystack program itself. * The output method if it's not STDOUT. * If possible, a link to an online interpreter/compiler for your chosen language. Your submission may be either a program or function, but not a snippet and you must not assume a REPL environment. You must not take any input, and you may output via STDOUT, function return value or function (out) parameter. Both programs/functions have to complete within 5 seconds on a reasonable desktop machine and need to be deterministic. You must not use built-ins for hashing, encryption or random number generation (even if you seed the random number generator to a fixed value). In the interest of fairness, there must be a freely available interpreter or compiler for your chosen language. An answer is cracked if the Needle program is found. If your answer has not been cracked for 7 days, you may reveal the intended Needle program in your answer, which renders your submission safe. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. The shortest *safe* Haystack program (measured in bytes) wins. ## Examples Here are a couple of simple examples in different languages: ``` Ruby Haystack: puts 1>0?"Haystack":"Needle" Delete: XXXXXXXXXXXXXXX Needle: puts "Needle" Python 2 Haystack: print "kcatsyaHeldeeN"[-7::-1] Delete: XXXXXXXX XX Needle: print "eldeeN"[::-1] ``` Note that the subset of removed characters doesn't have to be contiguous. ## Uncracked Submissions ``` <script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 144600;</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] # [Haystack](https://github.com/kade-robertson/haystack), 84 bytes, [Cracked](https://codegolf.stackexchange.com/a/144613/68942) ``` 0\\1-c\ // ?10F17+c8F+4+cd8F+3+c6-c1+c,c2+c8+c| 0 \1++c,c| F/c++2F8 c\8F+2+cd ``` [Try it online!](https://tio.run/##FcoxCoBADETRPqewH2U3q6idXU6RZhkLwVIbwbuvcZqBzzvqc92VZ2vZXQe6pNTFZNNsuoCrYQL3uBGcByrYs0QHX@lyUFf87RVLBIqtQg8eZm/tAw "Haystack – Try It Online") This looks (to me) rather convoluted but if you find the right subset it's a bit too easy... oh well, just to get us started :P [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), 37 bytes ``` H[@;(...e<l.a;./$.>;\sN;\ac.>).;;;._y ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/98j2sFaQ09PL9UmRy/RWk9fRc/OOqbYzzomMVnPTlPP2tpaLx6oDAA "Hexagony – Try It Online") Just my obligatory Hexagony entry... For convenience, here is the unfolded code: ``` H [ @ ; ( . . . e < l . a ; . / $ . > ; \ s N ; \ a c . > ) . ; ; ; . _ y ``` How this works: The program starts off with `H`, then we move to IP #5. This IP starts in the west corner, bouncing and wrapping around while executing (in effect) `;a;y;s;` (so we've printed `Hays`). Then `s` gets incremented to a `t` by `)` and printed, then we pass through `Ne...(c` before getting to `a;c;` (still bouncing around a small section of the hexagon). The program hits the `_`, reflects up through `\` to `l` which gets decremented to a `k` by `(`, which passes through another `\` before being printed and the program terminates on the `@`. Verbose version ``` H H is entered into the current memory cell [ We move to the previous instruction pointer (starting at the / and moving NE) / No-op < Mirrors the IP back to south-west / No-op (IP now wraps to the NE corner) ; Outputs H . No-op a a is entered into the current memory cell > Mirrors the IP back to north-east a a is entered into the current memory cell . No-op ; Outputs a (IP now wraps SE corner) y y is entered into the current memory cell ; Outputs y . No-op s s is entered into the current memory cell (IP now wraps SW corner) ; Outputs s ) Increments the memory cell to t \ Mirrors the IP west ; Outputs t N N is entered into the current memory cell (IP now wraps to e) e e is entered into the current memory cell ... No-ops ( Decrements the memory cell to d (IP now wraps to . on SE edge) . No-op c c is entered into the current memory cell a a is entered into the current memory cell \ Mirrors the IP north-east > Redirects the IP east ; Outputs a \ Mirrors the IP south-west c c is entered into the current memory cell ; Outputs c _ Mirrors the IP north-west .\. No-ops l l is entered into the current memory cell ( Decrements the memory cell to k (IP now wraps to . on SE edge) .\ No-ops ; Outputs k . No-op @ Terminates the program ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 146 bytes ([Cracked](https://codegolf.stackexchange.com/a/144626/69059)) ``` ([((((()()())){}){}){}](()([()](()({}([((((()()()){})))[]])[]({}({})[{}]()({}((()(({}){}){}){}){}())))[][][][][][]))[]))(((()[]){}){({}[()()])}{}) ``` [Try it online!](https://tio.run/##VYwxDoAwDAO/Ew99BO@IMpQBCYEYWKu@PditEKJJ1To5e73rfpXtrEemuelABbQ@OzRxw3hb/0EEAI/g1YrSZRicGHtDZiuW6FdSwMjjRwwdruhAp8zMsjw "Brain-Flak – Try It Online") ## Intended solution, 80 bytes ``` ([((((()()())){}){}){}](()([()](()({}([((((()()()){})))[]])[]({}({})[{}]()({}((()(({}){}){}){}){}())))[][][][][][]))[]))(((()[]){}){({}[()()])}{}) ( (( )( [( (( ( )()()){})) []] ({}( ) ( ( ( ()(({}){}){}){}){}()))) )) (((()[]){}){({}[() ])}{}) ``` [Answer] # [Haskell](https://www.haskell.org/), 168 bytes ([Cracked by nimi](https://codegolf.stackexchange.com/a/145243/34531)) ``` hays=map;hay=zipWith;stack=head;h=stack{- hay.(hays.(stackany hay$or id).stack hay <*>hays(sum$stack haystack<$>hay))-}$words "Haystack Hayst ackH aysta ckH aystac k" ``` [Try it online!](https://tio.run/##PYqxCsMgFEX3fMUjOGgh/oCxc/YOnR8xoBgTUUNJS7/dqpRs5557NEa7rGvOGs8oHXpRQL6Nf5qkRUw4W6kXVELLNj5DB6XgtPacNofbWR3ZAxjFeHNVdOPtXjMaD0cu22Ak9WFs@JLXHlTsoJ/@FzSAQhM0BRfNYPvs0GwgwR/pkQLo/AM "Haskell – Try It Online") Evaluating the identifier `h` returns the string `"Haystack"`, after some deletions `h` yields `"Needle"`. [Answer] # JavaScript, 95 bytes (ES6), [Cracked](https://codegolf.stackexchange.com/a/144620/3845) A function returning a string. ``` f=(k=b=x=35)=>x--?f(k*74837258394056219&268435455):k&2?'N'+(k^124038877).toString(b):'Haystack' ``` ### "Haystack" demo ``` f=(k=b=x=35)=>x--?f(k*74837258394056219&268435455):k&2?'N'+(k^124038877).toString(b):'Haystack' console.log(f()) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ([Cracked](https://codegolf.stackexchange.com/a/144667/53748)) ``` “¿ọ⁽ṅ*FỊ⁼g£¡#!ʋzoɦṪ£ṢÞḲÐɠ`”m3⁾“»jVḟ“¡!pṄ» ``` **[Try it online!](https://tio.run/##AVwAo/9qZWxsef//4oCcwr/hu43igb3huYUqRuG7iuKBvGfCo8KhIyHKi3pvyabhuarCo@G5osOe4biyw5DJoGDigJ1tM@KBvuKAnMK7albhuJ/igJzCoSFw4bmEwrv//w "Jelly – Try It Online")** Happy hunting! [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 32 bytes. [Cracked](https://codegolf.stackexchange.com/a/145736/60483) I couldn't solve [Martin's](https://codegolf.stackexchange.com/a/144625/71256), so I'm posting my own. ``` ];N.@cl;e@;;(\H/;ya;_.>s.;t//<._ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/z/W2k/PITnHOtXB2lojxkPfujLROl7PrljPukRf30Yv/v9/AA "Hexagony – Try It Online") Here it is formatted: ``` ] ; N . @ c l ; e @ ; ; ( \ H / ; y a ; _ . > s . ; t / / < . _ . . . . . ``` My aim with this was for both solutions to use as many IPs as possible, I got 6 for **Needle** and only 5 for **Haystack**. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 44 bytes ([Cracked](https://codegolf.stackexchange.com/a/144656/48934)) ``` Kr."Dn2û"2sf!/+rrK2 2r."EL8"2Tr."AhÐP­®Z"2 ``` [Try it here.](http://pyth.herokuapp.com/?code=Kr.%22Dn2%C3%BB%C2%82%222sf%21%2F%2BrrK2+2r.%22EL8%222Tr.%22Ah%05%C3%90P%C2%AD%C2%AEZ%222&debug=0) [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 226 217 bytes ([Cracked](https://codegolf.stackexchange.com/a/144809/75077)) First ever code golf, probably very easy but it was a fun challenge! ``` String d(){int h=3609000-5055+911,m=557558,s=15441301-157*10000;String d="0"+h*2+""+m*20+""+s*7,x="",y;for(int g=0;g<d.length();g+=3){y="";for(int e=0;e<3;e++)y+=d.charAt(e+g);x+=(char)Integer.parseInt(y);}return x;} ``` [Try it online!](https://tio.run/##PY/BToQwFEXX@hUNq5YCaYepOOl04dKFq1kaFxVqYYRC2jJCCN@ORaOrm3Nz7kveVd5k2g/KXKvPrWylc@BFNmYZxve2KYHz0oe49U0FutDDi7eN0a9vQKLlMjuvuqwffTaE1kOjvn7WEGUVRIivd9uvDwIuwQC1yB/IiRCSMsIYPlGadIKxgrHHxAnKjkeaE5pSVsQ0WIT/7UVEIlzHBxxFuIsPZE8XF8kkoiiZ@Udv4X5fC8L1ucpaZbSvIeIaixwtc7D@HRUcdc65whjNWFRZWUv75KHCGvEJC7gzejZeaWWzQVqnAsA5/GOVH60BE1/vt3X7Bg "Java (OpenJDK 8) – Try It Online") [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 148 bytes ([Cracked](https://codegolf.stackexchange.com/a/145026/74216)) ``` 6 93 3 9 2 2**+*+483622 1 2 3 3*+3*+89 47*+*+3 5 2* 269 158 9**107 97*2 4*++2 3 3*+42 14 2**+*+5*+5 2148 1 6 2*+*+68262 5 280 7 2 3 3*+5 2**+*+*+*+P ``` [Try it online!](https://tio.run/##NY27EcAwCENXUQ1NjDGGLbJDsv8KjnznHKqePrzPWoHq6CgYTERFPXuYoRHQEKWy4HN7HYMpWBTaSJRIuyZqisFF9TScbT9rg4I1Tw4GGVGkhe2hvDD/L@Pk991rfQ "dc – Try It Online") It is rather simple, but I hope it will be at least a little fun to solve :з [Answer] # JavaScript, 119 bytes (ES6), [Cracked](https://codegolf.stackexchange.com/a/144652/36445) A function returning a string. Quite long and not so hard, but hopefully fun. ``` _=>(+{}+['H'])[+[3]]+(+[][[]]+[])[+!!3]+(+[][[]]+['y'])[3]+(+[][[]]+['s'])[-~2]+(~![]+['t'])[2]+(+[][[]]+[])[+!!3]+'ck' ``` ### "Haystack" demo ``` let f = _=>(+{}+['H'])[+[3]]+(+[][[]]+[])[+!!3]+(+[][[]]+['y'])[3]+(+[][[]]+['s'])[-~2]+(~![]+['t'])[2]+(+[][[]]+[])[+!!3]+'ck' console.log(f()) ``` [Answer] ## Python 2.7.2, 103 / 117 bytes, [Cracked](https://codegolf.stackexchange.com/a/144701/71546) **Function Version (117 bytes):** ``` def e(): a,b,s=20070763850923833476353301471991752,0b1010100010010011,"" while a>0: s=chr(a%b)+s a//=b print s ``` **Program Version (103 bytes):** ``` a,b,s=20070763850923833476353301471991752,0b1010100010010011,"" while a>0: s=chr(a%b)+s a//=b print s ``` This should print `Haystack` well. Tested on [Python Fiddle](http://pythonfiddle.com/). Btw this is the first attempt. Not sure if the program version is counted as a snippet, so I put both versions here. [Answer] ## Python 2.7.10 with Numpy 1.12.1, ~~208~~ 209 bytes ([cracked](https://codegolf.stackexchange.com/a/144734/46523)) It appears that there is a Needle *and* a Haystack in Numpy! Here is the Haystack; see if you can find the Needle. I hope you have as much fun searching for the Needle as I had hiding it. ``` import numpy print "".join([dir(numpy)[int(i)][1-0] for i in numpy.poly1d([-1*1433/252e1,-3232/1920.,4026./72/2/3.,613/(6*4.)*1,-4723./1.8e2,-9763/120.,-2689/(-1+5*17.),1+138*.4*2])(numpy.arange(-12/3,13%9))]) ``` It outputs as specified: ``` Haystack ``` You can [repl.it](https://repl.it/MRuh/0). [Answer] # Java 8, 321 bytes, [Cracked](https://codegolf.stackexchange.com/a/144792/52210) ``` v->{String h="Haystack";int x=-7;return x<0?h:new String(new java.math.BigInteger(new byte[]{(byte)((~-~-~-~-~-~-~-~-~-~1^-x++*x)+151),new Byte("2"+"1+\"0+\"".length()+(x=h.length()*4/x)+"-x-7")}).toByteArray())+(new StringBuffer("hidden".substring(++x%3^4,--x-x--).replaceFirst("dd","e"+(char)(x*211%+93))).reverse());} ``` [Try it here.](https://tio.run/##ZVHRSsMwFH33K0JASJYlrttkaK3iHkQf3Ivgy9wga7O2W5eWNK0Zo/56vXVFHyS5JDfn3JvDuTtZS54XSu@ifRtmsizRq0z16QKhVFtltjJUaNGlCL1Zk@oYheQ9TyNUUx9eGwjYpZU2DdECaRSgtub3p56cBPhZHgEO99iHjsgFfOYbZSujkbsbPSS3Wn32rUl33YEicZA2EfM0fgENsTI/wOZo1XJ1It1JCfni/5a35o6xgaPMu/bosCuaA5ngMWbYYx94BIFFpnRsE0IZcUHymw2mV1CIueMzTBsqbN7VPhojj4QC90/mvNpuQRNO0ihSGouy2pRn/Yy5y8l6OuTQxXFOhVFFBg4@paa0BEd4iBVmJEykocQNxp53yW4mlHbEWplSwU9@0/pnU4tqk4Gpvbd1Z/oBZkPOKpYrJGk/GDBYHUReWVEAZIkWIdFVltF@Rk37DQ) More readable: ``` v->{ String h="Haystack"; int x=-7; return x<0? h : new String(new java.math.BigInteger(new byte[]{ (byte)((~-~-~-~-~-~-~-~-~-~1^-x++*x)+151), new Byte("2"+"1+\"0+\"".length()+(x=h.length()*4/x)+"-x-7") }).toByteArray()) +(new StringBuffer("hidden".substring(++x%3^4,--x-x--) .replaceFirst("dd","e"+(char)(x*211%+93)) ).reverse()); } ``` Not sure if it's too long/hard.. Then again, Java in general is pretty long to begin with, so hiding the 'Needle' properly of course increases the byte-count quite a bit.. If no one cracks it, I'll add some spoiler-tips later on. [Answer] # [Ruby](https://www.ruby-lang.org/), 185 bytes, [cracked by cab404](https://codegolf.stackexchange.com/a/144955/6828) ``` x='yGwztsPXhxDkBKlCYdFjQnpUROfoHvqmTgbaJSLcEiZrIAuMVNW' s="n=x.to_i 36;x.bytjs.jach_cons(3){|a,b,c|n+=n*b%c;n*=a^b};puts n%8675309==1388649 ?'Njjdlj':'Haystack'" eval s.tr ?j,s.size.chr ``` [Try it online!](https://tio.run/##BcHbboIwGADge5@iMTGdShoNiihpzHQHz7p52ryYaesBKhblLwrqnh2/L4x4kqYxxcnn9aZh8uPGb4dW32//bj7klzrNv8e7oHM5H2d7znrTgXj3VmH3NRouRkucAZpVNCY6WHvItJyY8ERLIJIJdy0CBS9m/v5gBjfEQxWpKvCccFSBsj/@75wiDUjlbKtWNUt1SsumbVuVOmrikZQbX@IG7rAENBMHnM1sL8xHQHSImtIAAt5tS4QbpukT "Ruby – Try It Online") I'll try to come up with something sneaky, but for now here's a try at "simple but obnoxious." [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 188 bytes ([Cracked](https://codegolf.stackexchange.com/a/145332/71256)) I only just saw Funky Computer Man's [answer](https://codegolf.stackexchange.com/a/144608/71256) As I posted this. It is somewhat obfuscated. ``` ((((((((((()()()){}){}()){}){}()){}()))<({}[(()()()()){}])(([[]]({})<>)<>)>((()()())){}{})[()]))<[[]()]>((()){}){}((){}[][(<>){}<>])(<>){}(({}<>()[()])[(((()()()){}<[()]>)<(()){}>{}){}()]) ``` [Try it online!](https://tio.run/##VU5JCsAwCPzOeOgPQj4iHtJCobT00GvI2@1koUsUNaMzOl9pO6f1SLs73ifVJBf6LzNIQC46RhpoAqiaEZcQq8dHgm2iCjESOcSiNYcmGNQU5OQSIpVaBdQfOk@/B4UKcUeXiOMyE3eflhs "Brain-Flak – Try It Online") ### Intended solution, 96 bytes: ``` ((((((((((()()()){}){}()){}){}()){}()))<({}[(()()()()){}])(([[]]({})<>)<>)>((()()())){}{})[()]))<[[]()]>((()){}){}((){}[][(<>){}<>])(<>){}(({}<>()[()])[(((()()()){}<[()]>)<(()){}>{}){}()])((((((((()()()){}){}){}()){}){}()<>)<>)(()()()){}())<>(((({}[()]<>)()))[(((()()()){}())()){}{}]) (((((((( (()()()){}){} ){}){}()){}())) ()() <>) (()()()) {} () ) < >((() ((){} <>) ) ) (({} )[(((()() ){} () ) () {} ){}()]) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMGNEFQs7oWgmBMDU0bOxBCyAMJGzuQhuraaA3NWJCcpqZmNLIRQAJMV9fGav7//183GQA) [Answer] # T-SQL, 757 characters [CRACKED](https://codegolf.stackexchange.com/questions/144601/find-the-needle-in-the-haystack-robbers/145348#145348) Apologies for deleting my previous answer--I edited it too many times as I obfuscated, and didn't want to give anything away. :) In any case, obfuscating in SQL is a bit difficult, unless you want to do crazy stuff like [this](https://blogs.oracle.com/sql/obfuscated-sql-contest-winners), and I wasn't that invested. Also, I unabashedly do not apologize for naming my variables after Dota. [SQL Fiddle](http://sqlfiddle.com/#!6/cfcd39/6/0) ``` create table a(l int,c int) insert into a values (1,10),(2,1),(3,8),(4,0) go ;CREATE FUNCTION b(@ varchar(max)) returns varchar(max) as begin return 'char('+@+'),'''','end go ;CREATE FUNCTION h(@ varchar(max),@a varchar(max), @b varchar(max), @c varchar(max), @d varchar(max), @e varchar(max), @f varchar(max), @g varchar(max), @h varchar(max)) returns varchar(max) as begin return replace(replace(replace(replace(@,@a,@b),@c,@d),@e,@f),@g,@h) end declare @x varchar(max),@ int=1,@y varchar(99)='' ,@D varchar(4)='Ha',@O varchar(4)='ys' ,@T varchar(3)='ta',@A varchar(4)='ck' WHILE @<=4 BEGIN set @y+=(SELECT dbo.b(c+100)from a where l=@)+' ' set @+=1 END SELECT @x='select left(dbo.h('''+@D+@O+@T+@A+''','+ left(@y,len(@y)-1) +'),char(56))' execute(@x) ``` If this is the easiest answer in this thread, you're probably right. :P It's hard to trick SQL. [Answer] # [Ly](https://github.com/LyricLy/Ly), 40 bytes, [cracked](https://codegolf.stackexchange.com/a/145344/70424) ``` (78)"e"&p"Ha"s"yst"l"ck"&o(100)"l"l'&'o; ``` [Try it online!](https://tio.run/##y6n8/1/D3EJTKVVJrUDJI1GpWKmyuEQpRyk5W0ktX8PQwEATyMlRV1PPt/7/HwA "Ly – Try It Online") Oh boy, another Ly CNR submission. These haven't worked very well historically (possibly due to me and not the language), ~~but we'll see how this fares~~ and today is no exception. Solution: > > `(78)"e"sl(100)"l"l&o;`, remove `XXXXXX XXXXX XXXXXX X X` with seven leading spaces > > > [Answer] # [Java](http://openjdk.java.net/), 345 bytes, [Cracked](https://codegolf.stackexchange.com/a/145848/55735) ``` import java.util.*;interface Main{static void main(String[]args){Stack<Hay>s=new Stack();s.add(new Needle());for(int i=0;i<1000;i++)s.add(new Hay());System.out.println(s.get(s.indexOf(new Hay())+1).a);}}class Needle extends Hay{{a="Needle";}}class Hay{String a="Haystack";public boolean equals(Object o){return getClass().equals(o.getClass());}} ``` [Try it online!](https://tio.run/##TY@xbsMgEIZfBXmCWkXOTNylS5Y2g8eqw9mcIxwMLpzTRFae3YUmarqA7rtPd/8NcIJnP6Eb9HFdzTj5QGxIUM5krHxSxhGGHjpkb2DcEgnIdOzkjWZjAryhYNzh4xPCIYqlIeiO2x1cXmLt8Jv91lyoKEFrnsk7orbIhVC9DzxNZ6aulNluqip9ZSkeahqTveYSCUfpZ5JT2kXW8SgPSOk1TuN53/@zy42QINT12lmI8b6N4ZnQ6ZidZYG6uOHiT8v8dghL3VTFnLtQ09zadG3rvUVwDL9msJHv2wE7Yl4sAWkOjqUwr3kOF/KuePlgOc26/gA "Java (OpenJDK 8) – Try It Online") Really long and probably easy to crack, but at least it's got a `Stack<Hay>`! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 51 bytes ``` ‛Ha:₍₴Cv∑∑Ṙ⌊√‹½⇩⇩²C:₴«•∞yλ;ß4ġ∆Ė_□∴9«øc:3Ẏ$4ȯ∇ppĖ5e ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=o&code=%E2%80%9BHa%3A%E2%82%8D%E2%82%B4Cv%E2%88%91%E2%88%91%E1%B9%98%E2%8C%8A%E2%88%9A%E2%80%B9%C2%BD%E2%87%A9%E2%87%A9%C2%B2C%3A%E2%82%B4%C2%AB%E2%80%A2%E2%88%9Ey%CE%BB%3B%C3%9F4%C4%A1%E2%88%86%C4%96_%E2%96%A1%E2%88%B49%C2%AB%C3%B8c%3A3%E1%BA%8E%244%C8%AF%E2%88%87pp%C4%965e&inputs=5%0A3&header=&footer=) Have fun! So, here's an explanation of the code: ``` ‛Ha # Push 'ha' :₍ # Duplicate and parallel apply... ₴ # Flatprint C # And charcode, wrapped into a list v∑∑Ṙ # Get sum, concatenate, reverse (`961aH`) ⌊√‹½ # Intify, square root, decrement and halve (15) ⇩⇩²C # Subtract 4, convert to char, which happens to be y :₴ # Dupe and flatprint. «...« # Push a string, specially chosen, see below øc # Compress :3Ẏ$4ȯ∇pp # Insert ToS (`y`) at char 3 Ė # Evaluate 5e # Every fifth character ``` So, I realised I could use the compressed string `‛₍∞` as the needle program. I could easily sneak in a `‛` and `₍`, but `∞` was proving to be a problem. Eventually, I managed to construct a compressed string that contained `∞` and `y`, and had the property that if you took every fifth character, you got 'stack'. So yeah, this was tricky. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 44 bytes ``` 17SǏ⌊0»¹∇ḃF2»*»∷J∇Y.ḊṖ¼ḭ¦]uy»S4ẇṫ½Y⌊$oḢJCṅĖǐ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=17S%C7%8F%E2%8C%8A0%C2%BB%C2%B9%E2%88%87%E1%B8%83F2%C2%BB*%C2%BB%E2%88%B7J%E2%88%87Y.%E1%B8%8A%E1%B9%96%C2%BC%E1%B8%AD%C2%A6%5Duy%C2%BBS4%E1%BA%87%E1%B9%AB%C2%BDY%E2%8C%8A%24o%E1%B8%A2JC%E1%B9%85%C4%96%C7%90&inputs=&header=&footer=) [Answer] # TI-BASIC, 119 bytes (Safe) Output stored in `Ans`. ``` "TIBASIC→Str1 length(Ans→X Str1 For(I,X,2(7-4not(X-1 Ans+sub("ACDEHKLNSTY",inString("ABCDEFGHIJK",sub("KCBADAEDJDHIGF",1+remainder(11I-1,14),1)),1 End sub(Ans,1+X,length(Ans)-X ``` ## Solution Remove characters from `Str1` to give it a length of 1. ``` "C→Str1 length(Ans→X Str1 For(I,X,2(7-4not(X-1 Ans+sub("ACDEHKLNSTY",inString("ABCDEFGHIJK",sub("KCBADAEDJDHIGF",1+remainder(11I-1,14),1)),1 End sub(Ans,1+X,length(Ans)-X ``` [Answer] # PHP, 44 bytes, [Cracked](https://codegolf.stackexchange.com/a/145849/72733) fairly easy to crack; but I like it. ``` for($i=~1;$c=H_aNyesetdalcek[$i+=2];)echo$c; ``` Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/2d59e50d8293febd1368cc57731f0e4dd83ae956). [Answer] # [Aceto](https://github.com/aceto/aceto), 154 bytes (Safe) ``` 27\'dNU QJi9MLJ€{{x(}]J{'!o∑€xiDQxsJ(]sicpicp1.2sJJicp90I.2+D/edxi-'>xd80J0IJicx'NIx5sJsJidcpIcpL7sssJicpei7+ UUdJicpLI7sJicpx'p\p9*coJcU'p+\p ``` [Try it online!](https://tio.run/##S0xOLcn//18BDozMY9RT/EKBrECvTEtfH69HTWuqqys0amO9qtUV8x91TAQKVGS6BFYUe2nEFmcmFwCRoZ5RsZcXkGFp4KlnpO2in5pSkamrbleRYmHgZeAJlKlQ9/OsMC32KvbKTEku8Ewu8DEvLi4GaUnNNNdWCA1NAbF9PM3BYhXqBTEFllrJ@V7JoeoF2jEF//8DAA "Aceto – Try It Online") > > 'N'ed'd80J0IJic'eUpppppp [Try it online!](https://tio.run/##S0xOLcn//19BQd1PPTVFPcXCwMvA0yszWT01tAAM/v8HAA "Aceto – Try It Online") > > > ``` Explanation: <space>*2 - Two spaces for the hilbert curve to work right 'N pushes 'N' onto the stack 'e pushes 'e' d duplicates it 'd pushes d 80 pushes 8, 0 J concats top two values 0I pushes 0, pops, increments, pushes back on, net effect: pushes 1 J concats to '108' i converts to integer c pops and pushes ascii equiv on stack 'e pushes 'e' (again) U reverses the stack and the p's print out the stack ``` [Answer] # [Rattle](https://github.com/DRH001/Rattle), 55 bytes ``` Haystack&Needl|Ip0=2+(1*2)!Ps[bg0*3b^](`+5);$b|1,%(?3b) ``` [Try it Online!](https://www.drh001.com/rattle/?flags=&code=Haystack%26Needl%7CIp0%3D2%2B%281*2%29!Ps%5Bbg0*3b%5E%5D%28%60%2B5%29%3B%24b%7C1%2C%25%28%3F3b%29&inputs=) This isn't terribly difficult but it's not trivial either (note that "Needle" is missing the last "e" near the beginning of the code). Hint: the Needle program will not have a trailing newline, while the Haystack program does. ]
[Question] [ **Task description:** Write a program as short as possible to draw a radial gradient in ASCII art. The size of the output grid is predefined. The center point and the characters to be used for the gradient are provided as input to the program. The gradient will be 70×25 character cells in size with the following specifications * The upper-left corner of the grid has the coordinates (0, 0). * The gradient, consisting of the characters provided, is mapped into 35 *length units*. A length unit is one character tall and two characters wide (since `monospaced fonts` usually have characters twice as high as they are wide). * Within those 35 LU the current distance from the center point is multiplied by number of gradient characters/35 to get the index of the character to draw at that point. Fractional numbers for the index are rounded towards zero here. The length units are to be left as a real number. (Of course, if the results are the same, the implementation doesn't matter.) * Beyond those 35 LU only the last gradient character appears. However, since the last gradient »band« already starts *within* the 35 LU, the last character starts appearing short of 35 LU already. **Input:** The input is given on standard input and consists of three lines, each terminated by a line break: * The *x* coordinate of the gradient center point * The *y* coordinate of the gradient center point * The characters to use for drawing the gradient. Those may include spaces. **Output:** Output is the gradient as defined by the rules above on standard output. The standard error stream is ignored. Each line of the gradient is terminated by a line break. No other characters except those defined by the input may occur. **Sample input 1:** ``` 58 14 .:;+=xX$& ``` **Sample output 1:** ``` &&$$$$$$$$XXXXXXXXxxxxxxxxx===========++++++++++++++++++++++++++++++++ &$$$$$$$$XXXXXXXXxxxxxxxxx=========+++++++++++++;;;;;;;;;;;;;;;;;;;;;+ $$$$$$$$XXXXXXXXxxxxxxxx=========+++++++++++;;;;;;;;;;;;;;;;;;;;;;;;;; $$$$$$$XXXXXXXXxxxxxxxx========++++++++++;;;;;;;;;;;;;;;;;;;;;;;;;;;;; $$$$$$XXXXXXXXxxxxxxxx========+++++++++;;;;;;;;;;;;;:::::::::::::;;;;; $$$$$XXXXXXXXxxxxxxxx=======+++++++++;;;;;;;;;;;:::::::::::::::::::::; $$$$$XXXXXXXxxxxxxxx=======+++++++++;;;;;;;;;::::::::::::::::::::::::: $$$$XXXXXXXXxxxxxxx=======++++++++;;;;;;;;;::::::::::::::::::::::::::: $$$$XXXXXXXxxxxxxx========+++++++;;;;;;;;::::::::::...............:::: $$$XXXXXXXXxxxxxxx=======+++++++;;;;;;;;:::::::::...................:: $$$XXXXXXXxxxxxxx=======++++++++;;;;;;;::::::::....................... $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;::::::::......... ........ $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;:::::::........ ...... $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;:::::::....... ..... $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;:::::::....... ..... $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;:::::::....... ..... $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;:::::::........ ...... $$$XXXXXXXxxxxxxx=======+++++++;;;;;;;::::::::......... ........ $$$XXXXXXXxxxxxxx=======++++++++;;;;;;;::::::::....................... $$$XXXXXXXXxxxxxxx=======+++++++;;;;;;;;:::::::::...................:: $$$$XXXXXXXxxxxxxx========+++++++;;;;;;;;::::::::::...............:::: $$$$XXXXXXXXxxxxxxx=======++++++++;;;;;;;;;::::::::::::::::::::::::::: $$$$$XXXXXXXxxxxxxxx=======+++++++++;;;;;;;;;::::::::::::::::::::::::: $$$$$XXXXXXXXxxxxxxxx=======+++++++++;;;;;;;;;;;:::::::::::::::::::::; $$$$$$XXXXXXXXxxxxxxxx========+++++++++;;;;;;;;;;;;;:::::::::::::;;;;; ``` **Sample input 2:** ``` 0 0 X.X.X.X ``` **Sample output 2:** ``` XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXX............XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXX.............XXXXXXXXXX...........XXXXXXXXXX..........XXXXXXXXXX ..................XXXXXXXXXXX..........XXXXXXXXXX...........XXXXXXXXXX ................XXXXXXXXXXXX...........XXXXXXXXXX..........XXXXXXXXXXX ...............XXXXXXXXXXXX...........XXXXXXXXXX...........XXXXXXXXXXX ............XXXXXXXXXXXXXX...........XXXXXXXXXXX..........XXXXXXXXXXXX .........XXXXXXXXXXXXXXX............XXXXXXXXXXX...........XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXXX...........XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX.............XXXXXXXXXXX...........XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXX...........XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX................XXXXXXXXXXXX............XXXXXXXXXXXXXXX XXXXXXXXXXX..................XXXXXXXXXXXXX............XXXXXXXXXXXXXXXX ...........................XXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXX ........................XXXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXXX ......................XXXXXXXXXXXXXXX.............XXXXXXXXXXXXXXXXXXXX ..................XXXXXXXXXXXXXXXXX.............XXXXXXXXXXXXXXXXXXXXXX .............XXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...............XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX...............XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX.................XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX...................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX......................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ``` **Sample input 3:** ``` 70 25 .:+# ``` **Sample output 3:** ``` ######################################################++++++++++++++++ #################################################+++++++++++++++++++++ #############################################+++++++++++++++++++++++++ ##########################################++++++++++++++++++++++++++++ #######################################+++++++++++++++++++++++++++++++ ####################################++++++++++++++++++++++++++++++++++ ##################################++++++++++++++++++++++++++++++++++++ ################################++++++++++++++++++++++++++++++++++++++ ##############################++++++++++++++++++++++++++++++++:::::::: #############################+++++++++++++++++++++++++++:::::::::::::: ###########################+++++++++++++++++++++++++:::::::::::::::::: ##########################++++++++++++++++++++++++:::::::::::::::::::: #########################++++++++++++++++++++++::::::::::::::::::::::: ########################+++++++++++++++++++++::::::::::::::::::::::::: #######################++++++++++++++++++++::::::::::::::::::::::::::: ######################++++++++++++++++++++:::::::::::::::::::::::::::: #####################+++++++++++++++++++:::::::::::::::::::::::::::::: ####################+++++++++++++++++++::::::::::::::::::::::::....... ####################++++++++++++++++++::::::::::::::::::::::.......... ###################+++++++++++++++++++::::::::::::::::::::............ ###################++++++++++++++++++:::::::::::::::::::.............. ###################+++++++++++++++++:::::::::::::::::::............... ##################++++++++++++++++++::::::::::::::::::................ ##################++++++++++++++++++:::::::::::::::::................. ##################++++++++++++++++++:::::::::::::::::................. ``` **Sample input 4** ``` 59 1 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>|,.-#+!$%&/()=?*'_:; ``` **Sample output 4** ``` !+#-,|><87654210ZYWVUTRQPONLKJIHFEDCBzyxwutsrqonmlkjhgfedcbbbcdefghjkl !+#-,|><87654210ZYWVUTRQPONLKJIHFEDCAzyxwutsrqonmljihgfdcba abcdfghijl !+#-,|><87654210ZYWVUTRQPONLKJIHFEDCBzyxwutsrqonmlkjhgfedcbbbcdefghjkl !+#-,|><97654310ZYXVUTSQPONMKJIHGEDCBAyxwvutrqponmkjihgffeedeeffghijkm $+#-.|><98654320ZYXWUTSRQONMLKIHGFEDBAzyxwutsrqponmlkjihhggggghhijklmn $!#-.,|<987643210YXWVUSRQPONLKJIHGEDCBAzywvutsrqponmllkjjjiiijjjkllmno $!+#.,|><87654210ZYXVUTSRQONMLKJHGFEDCBAzywvutsrrqponnmmlllllllmmnnopq %!+#-.|><987543210YXWVUTRQPONMLJIHGFEDCBAzyxwvutsrrqppooonnnnnoooppqrr %$!+-.,|><87654310ZYXWVTSRQPONMLJIHGFEDCBAzyxxwvuttssrrqqqqqqqqqrrsstt &%!+#-.,><987643210ZYXVUTSRQPONMLKJIHGFEDCBAzyyxwvvuutttssssssstttuuvv &%$!+#.,|><986543210ZYWVUTSRQPONMLKJIHGFEDDCBAzzyyxwwwvvvuuuuuvvvwwwxy /&%$!#-.,|><976543210ZYXVUTSRQPONMLKKJIHGFEEDCBBAAzzyyyxxxxxxxxxyyyzzA (/&%!+#-.,|><876543210ZYXWVUTSRQPONMLKJJIHGGFEEDCCBBBAAAzzzzzzzAAABBBC )(/%$!+#-.,|><876543210ZYXWVUTSRQPPONMLKKJIIHGGFFEEDDDCCCCCCCCCCCDDDEE =)(&%$!+#-.,|><986543210ZYYXWVUTSRQPPONMMLKKJIIHHGGGFFFEEEEEEEEEFFFGGG ?=)(&%$!+#-.,|><9876543210ZYXWVVUTSRRQPOONMMLLKJJJIIIHHHHHHHHHHHHHIIIJ *?=)(/%$!+#-.,|><98765432210ZYXWWVUTSSRQQPOONNMMLLLKKKJJJJJJJJJJJKKKLL '*?=)(/&%$!+#-.,|><98765432110ZYXXWVUUTSSRRQPPOOONNNMMMMMLLLLLMMMMMNNN _'*?=)(/&%$!+#-.,|><988765432210ZYYXWWVUUTTSSRRQQQPPPOOOOOOOOOOOOOPPPQ :_'*?=)(/&%$!+##-.,|><9877654332100ZYYXXWVVUUTTTSSSRRRRQQQQQQQQQRRRRSS ;;:_'*?=)(/&%$!+#-.,,|><98876554322100ZZYYXXWWVVVUUUTTTTTTTTTTTTTTTUUU ;;;:_'*?=)(/&&%$!+#-.,,|><9987665443321100ZZYYYXXXWWWWVVVVVVVVVVVWWWWX ;;;;;:_'*?=)(/&%$$!+#-..,|>><9887665544322211000ZZZYYYYYYYYYYYYYYYYYZZ ;;;;;;:_'*??=)(/&%%$!+##-.,,|><<99877665544333222111100000000000001111 ;;;;;;;;:_'*?==)(/&&%$!++#--.,,|>><<9887766655544433333322222223333334 ``` A week has passed. It is time to unveil the solution lengths from our university's contest: > > 167 – Python > > 189 – Haskell > > 203 – C > > 210 – VB.NET > > 219 – C > > > And our own solutions: > >   91 – GolfScript > > 125 – [Ruby](https://codegolf.stackexchange.com/questions/430/drawing-a-gradient-in-ascii-art/777#777) > > 157 – [PowerShell](https://codegolf.stackexchange.com/questions/430/drawing-a-gradient-in-ascii-art/770#770) > > > [Answer] # Brainfuck - 1286 This is one of my favorite creations yet. Includes a working (for some definitions of working) square root function. ``` >,>,<<<<<<<+>,[<+[<+>-],]<-[>>[>]>>>+<<<<[<]<-]>>[<+<+<+>>>-]<<<[>>>+< <<-]>[>]>>>>>>>+++++[<+++++>-]<[>>+++++++[<++++++++++>-]<[>>+++++++[<+ +++++++++>-]<<[>->+<<-]>>[<<+>>-]<<<<<[>>>>->+<<<<<-]>>>>>[<<<<<+>>>>> -]<[>+>+<<-]>[<+>-]>>+++++++[<<++++++++++>>-]>[-]>[-]+>[-]<<<<[>+>+<<- ]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>- >]<+<<-]>[-]>[-]<<<[-]<[-<+[+>+<]>+[<+>-]]++<[->-[>+>>]>[+[-<+>]>+>>]< <<<<]>[-]>[-]>[<<<+>>>-]<+++++[<+++++>-]<<<<[>>>->+<<<<-]>>>>[<<<<+>>> >-]<<<<<[>>>>->+<<<<<-]>>>>>[<<<<<+>>>>>-]<[>+>+<<-]>[<+>-]>>+++++[<<+ ++++>>-]>[-]>[-]+>[-]<<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[- ]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>[-]>[-]<<<[-]<[-<+[+>+<]>+[< +>-]]<<[>>+>+<<<-]>>[>>>+<<<-]>>>[<<[<+>>+<-]>[<+>-]>-]<<[-]<[<<+>>-]< [>+>+<<-]>[>>>+<<<-]>>>[<<[<+>>+<-]>[<+>-]>-]<<[-]<[<<+>>-]<<>+>>+<<<[ [>>+>>+<<<<-]>>>>[<<<<+>>>>-]>[-]>[-]+>[-]<<<<[>+>+<<-]>>[<<+>>-]<<<[> >>+<<<-]>>>[>-]>[<<<<+>>[-]>>->]<+<<[>-[>-]>[<<<<+>>[-]+>>->]<+<<-]>[- ]>[-]<<+<<[>>-<[-]<-<<[-]>>]>>[-<<<[>+>+<<-]+>[<+>>+<-]>+>]<<<<]>[<+>- ]<-<<<<<[<+>->>>>>>+<<<<<<]<[>+<-]>>>>>>[>>>+<<<-]>>>[<<[<+>>+<-]>[<+> -]>-]<+++++++<[-]>[<+++++>-]<<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]>[ <<<<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[-<[>>+<<-]>[<+>-]<]<.>>>[[<<+>>-] >]>>>>>-]++++++++++.[-]<-] ``` Output is a bit off due to rounding errors, but still recognizable. Floating point is beyond my current skill level. Unfortunately this will only work with 16 bit cells, which means it is going to be dog slow. Output 1: ``` &$$$$$$$$XXXXXXXXxxxxxxxxxx========++++++++++++++++++++++;;;++++++++++ $$$$$$$$$XXXXXXxxxxxxxxxx========++++++++++++++;;;;;;;;;;;;;;;;;;;;;;; $$$$$$$XXXXXXXXxxxxxxxx========++++++++++++;;;;;;;;;;;;;;;;;;;;;;;;;;; $$$$$$$XXXXXXxxxxxxxxxx======++++++++++++;;;;;;;;;;;;;;;;:::;;;;;;;;;; $$$$$XXXXXXXXxxxxxxxx========++++++++++;;;;;;;;;;:::::::::::::::::::;; $$$$$XXXXXXxxxxxxxxxx======++++++++++;;;;;;;;::::::::::::::::::::::::: $$$$$XXXXXXxxxxxxxx======++++++++++;;;;;;;;::::::::::::::::::::::::::: $$$XXXXXXxxxxxxxxxx======++++++++;;;;;;;;::::::::::::::::...:::::::::: $$$XXXXXXxxxxxxxx========++++++++;;;;;;::::::::::::...............:::: $$$XXXXXXxxxxxxxx======++++++++;;;;;;;;::::::::::...................:: $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::::.......... .......... $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::........ ...... $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::...... .... $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::...... .... $XXXXXXxxxxxxxx======++++++++;;;;;;::::::::...... .. $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::...... .... $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::...... .... $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::........ ...... $$$XXXXXXxxxxxxxx======++++++++;;;;;;::::::::::.......... .......... $$$XXXXXXxxxxxxxx======++++++++;;;;;;;;::::::::::...................:: $$$XXXXXXxxxxxxxx========++++++++;;;;;;::::::::::::...............:::: $$$XXXXXXxxxxxxxxxx======++++++++;;;;;;;;::::::::::::::::...:::::::::: $$$$$XXXXXXxxxxxxxx======++++++++++;;;;;;;;::::::::::::::::::::::::::: $$$$$XXXXXXxxxxxxxxxx======++++++++++;;;;;;;;::::::::::::::::::::::::: $$$$$XXXXXXXXxxxxxxxx========++++++++++;;;;;;;;;;:::::::::::::::::::;; ``` Output 2: ``` XXXXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXX............XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XX................XXXXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX ..................XXXXXXXXXX............XXXXXXXXXX..........XXXXXXXXXX ................XXXXXXXXXXXX..........XXXXXXXXXXXX..........XXXXXXXXXX ..............XXXXXXXXXXXX............XXXXXXXXXX..........XXXXXXXXXXXX ..........XXXXXXXXXXXXXXXX..........XXXXXXXXXXXX..........XXXXXXXXXXXX ..XXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXX............XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXXXX..........XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXX............XXXXXXXXXXXXXX XXXXXXXXXXXXXXXX................XXXXXXXXXXXX............XXXXXXXXXXXXXX XXXXXXXXXXXX..................XXXXXXXXXXXX............XXXXXXXXXXXXXXXX XX..........................XXXXXXXXXXXXXX..........XXXXXXXXXXXXXXXXXX ..........................XXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXX ......................XXXXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXXXX ..................XXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXX ..............XXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXX ..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX................XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX..................XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX....................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX......................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ``` [Answer] ## Python - 141 chars ``` x=input();y=input();z=raw_input();w=len(z) for i in range(-y,25-y):print"".join(z[min(w-1,int((i*i*4+j*j)**.5*w/70))]for j in range(-x,70-x)) ``` [Answer] ## Ruby 1.9, ~~116 114 108~~ 101 characters ``` x,y,z=*$<;25.times{|r|70.times{|c|$><<z[[(c-x.to_i+2.i*(r-y.to_i)).abs/70.0*k=z=~/$/,k-1].min]};puts} ``` [Answer] ## Delphi, 200 (and 185) Since I like ascii-art here a Delphi version of this code golf: ``` uses Math;var G:string;X,Y,l,i,j:Int16;begin ReadLn(X,Y);ReadLn(G);l:=Length(G);for j:=-y to 24-y do for i:=-x to 70-x do if i=70-x then WriteLn else Write(g[Min(l,1+Trunc(l*sqrt(i*i/4+j*j)/35))])end. ``` Not very impressive character-wise, as I had to use the Math unit to link in the Min() function. Also, ReadLn() somehow doesn't read integers and strings in one call, so that's quite expensive too. The newline needs a lot of characters too. Also, Delphi needs quite a lot of whitespace around it's keywords. Not very proud of this one. Anyway, the output of sample 4 gives me : ``` !+#-,|><87654210ZYWVUTRQPONLKJIHFEDCBzyxwutsrqonmlkjhgfedcbbbcdefghjkl !+#-,|><87654210ZYWVUTRQPONLKJIHFEDCAzyxwutsrqonmljihgfdcba abcdfghijl !+#-,|><87654210ZYWVUTRQPONLKJIHFEDCBzyxwutsrqonmlkjhgfedcbbbcdefghjkl !+#-,|><97654310ZYXVUTSQPONMKJIHGEDCBAyxwvutrqponmkjihgffeedeeffghijkm $+#-.|><98654320ZYXWUTSRQONMLKIHGFEDBAzyxwutsrqponmlkjihhggggghhijklmn $!#-.,|<987643210YXWVUSRQPONLKJIHGEDCBAzywvutsrqponmllkjjjiiijjjkllmno $!+#.,|><87654210ZYXVUTSRQONMLKJHGFEDCBAzywvutsrrqponnmmlllllllmmnnopq %!+#-.|><987543210YXWVUTRQPONMLJIHGFEDCBAzyxwvutsrrqppooonnnnnoooppqrr %$!+-.,|><87654310ZYXWVTSRQPONMLJIHGFEDCBAzyxxwvuttssrrqqqqqqqqqrrsstt &%!+#-.,><987643210ZYXVUTSRQPONMLKJIHGFEDCBAzyyxwvvuutttssssssstttuuvv &%$!+#.,|><986543210ZYWVUTSRQPONMLKJIHGFEDDCBAzzyyxwwwvvvuuuuuvvvwwwxy /&%$!#-.,|><976543210ZYXVUTSRQPONMLKKJIHGFEEDCBBAAzzyyyxxxxxxxxxyyyzzA (/&%!+#-.,|><876543210ZYXWVUTSRQPONMLKJJIHGGFEEDCCBBBAAAzzzzzzzAAABBBC )(/%$!+#-.,|><876543210ZYXWVUTSRQPPONMLKKJIIHGGFFEEDDDCCCCCCCCCCCDDDEE =)(&%$!+#-.,|><986543210ZYYXWVUTSRQPPONMMLKKJIIHHGGGFFFEEEEEEEEEFFFGGG ?=)(&%$!+#-.,|><9876543210ZYXWVVUTSRRQPOONMMLLKJJJIIIHHHHHHHHHHHHHIIIJ *?=)(/%$!+#-.,|><98765432210ZYXWWVUTSSRQQPOONNMMLLLKKKJJJJJJJJJJJKKKLL '*?=)(/&%$!+#-.,|><98765432110ZYXXWVUUTSSRRQPPOOONNNMMMMMLLLLLMMMMMNNN _'*?=)(/&%$!+#-.,|><988765432210ZYYXWWVUUTTSSRRQQQPPPOOOOOOOOOOOOOPPPQ :_'*?=)(/&%$!+##-.,|><9877654332100ZYYXXWVVUUTTTSSSRRRRQQQQQQQQQRRRRSS ;;:_'*?=)(/&%$!+#-.,,|><98876554322100ZZYYXXWWVVVUUUTTTTTTTTTTTTTTTUUU ;;;:_'*?=)(/&&%$!+#-.,,|><9987665443321100ZZYYYXXXWWWWVVVVVVVVVVVWWWWX ;;;;;:_'*?=)(/&%$$!+#-..,|>><9887665544322211000ZZZYYYYYYYYYYYYYYYYYZZ ;;;;;;:_'*??=)(/&%%$!+##-.,,|><<99877665544333222111100000000000001111 ;;;;;;;;:_'*?==)(/&&%$!++#--.,,|>><<9887766655544433333322222223333334 ``` If you would accept indented output, this version is a bit shorter by changing the newline into an indent that leads to a 80-character wrap (simulating a newline on standard 80x25 consoles) : ``` uses Math;var G:string;X,Y,l,i,j:Int16;begin ReadLn(X,Y);ReadLn(G);l:=Length(G);for j:=-y to 24-y do for i:=-x to 70-x do Write(g[Min(l,1+Trunc(l*sqrt(i*i/4+j*j)/35))]:11*Ord(i=-x))end. ``` (this saves 15 characters, for a total of 185 characters). It's output for "0 0 X.X.X.X" is : ``` XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXXXX............XXXXXXXXXX..........XXXXXXXXXX..........XXXXXXXXXX XXXXXX.............XXXXXXXXXX...........XXXXXXXXXX..........XXXXXXXXXX ..................XXXXXXXXXXX..........XXXXXXXXXX...........XXXXXXXXXX ................XXXXXXXXXXXX...........XXXXXXXXXX..........XXXXXXXXXXX ...............XXXXXXXXXXXX...........XXXXXXXXXX...........XXXXXXXXXXX ............XXXXXXXXXXXXXX...........XXXXXXXXXXX..........XXXXXXXXXXXX .........XXXXXXXXXXXXXXX............XXXXXXXXXXX...........XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXXX...........XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX.............XXXXXXXXXXX...........XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXX...........XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX................XXXXXXXXXXXX............XXXXXXXXXXXXXXX XXXXXXXXXXX..................XXXXXXXXXXXXX............XXXXXXXXXXXXXXXX ...........................XXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXX ........................XXXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXXX ......................XXXXXXXXXXXXXXX.............XXXXXXXXXXXXXXXXXXXX ..................XXXXXXXXXXXXXXXXX.............XXXXXXXXXXXXXXXXXXXXXX .............XXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...............XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX...............XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX.................XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX...................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX......................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ``` (Can you see the indent?! ;-) ) [Answer] ## APL (74) ``` {L←⍴⊃C Y X⎕IO←⍞⎕⎕0⋄⎕←{C[⊃⌊L⌊35÷⍨L×.5*⍨+/2*⍨1 2÷⍨⍵-Y X]}¨⍳⍵}25 70 ``` The reason it's wrapped in a function is that the modification to `⎕IO` doesn't apply to the rest of the system. Explanation: * `L←⍴⊃C Y X⎕IO←⍞⎕⎕0`: Set `⎕IO` to `0` (making arrays 0-based instead of 1-based), set X to `⎕` (first line read), set Y to `⎕` (second line read), set C to `⍞` (third line read, with no formatting), and set L to the length (`⍴`) of `C`. * `25 70`: the dimensions of the matrix. * `¨⍳⍵`: for each element in the matrix where each element is its own coordinates... * `⍵-Y X`: difference between the current point and the center point * `1 2÷⍨`: divide the X coordinate by 2 (because a char is half as wide as it is tall) * `.5*⍨+/2*⍨`: take the square root of the sum of the squares * `35÷⍨`: divide by 35 * `⌊L⌊`: take the minimum of the amount of characters and the current value and round it down * `,/`: The values are still wrapped in a list (of only one element), and this will create spacing in the output, so 'free' the values from their lists. * `C[`...`]`: use the value we found as an index into the character list * `⎕←`: we now have a matrix where each element (x,y) is the character for (x,y), so output the matrix. [Answer] # Perl 5.10, 103 chars ``` $x=<>;$y=<>;@C=<>=~/./g;for$j(-$y..24-$y){print+(map$C[@C/35*sqrt$_**2/4+$j**2]//$C[-1],-$x..69-$x),$/} ``` [Answer] ## Perl, 120 chars ``` $x,$y=<>,<>;@C=split'',<>;for$j(0..24){print+(map$C[($c=$#C/35*sqrt(($x/2-$_/2)**2+($y-$j)**2))<$#C?$c:$#C-1],0..69),$/} ``` [Answer] ## Windows PowerShell, 157 Nothing noteworthy. Beaten to death already: ``` $x,$y,$c=@($input) $l=$c.Length $c+=(""+$c[-1])*90 0..24|%{$r=$_ -join(0..69|%{$c[[math]::truncate([math]::sqrt(($x-$_)*($x-$_)+4*($y-$r)*($y-$r))*$l/70)]})} ``` [Answer] ## C, 176 Here a translation of my Delphi solution to C, saving 24 characters : ``` X,Y,l,i,j,t;char G[99];main(){scanf("%d\n%d\n",&X,&Y);gets(G);l=strlen(G);for(j=-Y;j<25-Y;j++)for(i=-X-1;i<70-X;)t=floor(l*sqrt(i*i++/4+j*j)/35),putchar(!i+X?10:G[t<l?t:l-1]);} ``` You can test this code here : <http://www.ideone.com/oTvHt> [Answer] ### Common Lisp, 173 characters ``` (let*((c(read))(v(read))(g(read-line))(l(length g)))(dotimes(y 25)(dotimes(x 70)(princ(elt g(min(floor(*(sqrt(+(expt(/(- c x)2)2)(expt(- v y)2)))l)35)(1- l)))))(princ #\ ))) ``` The only real trick I use here is using ``` #\[actual newline] ``` as a newline character literal [Answer] ### scala 223 (204 without App-Wrapper) ``` object C extends App{ import math._ def r=readInt val p=r val q=r val m=readLine (1 to 70)map(x=>(0 to 25)map(y=>{ printf("%c[%d;%dH%s",27,y,x,m(({ val a=abs(p-x) val b=abs(q-y) sqrt(a*a+2*b*b) }*(m.size-1)/74).toInt))} ))} ``` Having cols and rows (70, 25) set dynamically would allow for screenfilling gradients. [Answer] ### C# 311 Thought I'd make a long program to make the others feel better: ``` using System;class P{static void Main(){Func<string>r=Console.ReadLine;int x=int.Parse(r()),y=int.Parse(r());var c=r();for(int j=0;j<25;j++){for(int i=0;i<70;i++){var l=c.Length;Console.Write(c[(int)Math.Min(l*Math.Sqrt(Math.Pow(Math.Abs(x-i)/2.0,2)+Math.Pow(Math.Abs(y-j),2))/35,l-1)]);}Console.Write("\n");}}} ``` Input is taken from the console, one line at a time (two lines for the coordinates and one for the gradient chars). Thanks to [Joey](https://codegolf.stackexchange.com/users/15/joey) for the tips. Sample 1: <http://ideone.com/X0jIZ> Sample 2: <http://ideone.com/RvICt> ]
[Question] [ Rectangles have this nice property - an \$n \times m\$ rectangle consists of exactly \$n \times m\$ characters! A.. more interesting property is that the rectangles can be aligned nicely in a multiplication table - for example, a \$3 \times 3\$ table: ``` # ## ### # ## ### # ## ### # ## ### # ## ### # ## ### ``` Your challenge is to, given a number \$n\$ (\$ n > 1\$), output a formatted \$n \times n\$ multiplication table. ## Rules * You can take the input one above or below \$n\$ * [Default I/O rules apply](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * You can choose any non-whitespace character to represent the blocks; every other character (though newlines are special) is considered whitespace. The chosen character can be different for different inputs, but must be the same throughout the input * The result can have unneeded characters, as long as the table aligns up and there are no occurrences of the chosen character that aren't part of the required output * The separators must be 1 character wide/tall, and the rectangles must be packed (i.e. no separators between their characters) * The empty lines can be empty, padding isn't required * The result can be a string, matrix, vector of lines, array of character arrays, or anything 2Dish * You may alternatively output a matrix/vector-of-vectors/anything 2Dish of numbers, but the background & foreground must be 2 distinct numbers (which can vary input to input, but not throughout an output) and no other numbers can be present. Extra surrounding characters are allowed with this format too (though they must match the background number) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes, per-language, wins! # Examples For the input `2`, a valid ascii-art output, with the character `∙`, is: ``` ∙ ∙∙ Result: ∙ ∙∙. ∙ ∙∙ ``` yes the period is there just to confuse you Another valid answer as a number matrix, with 2 being the background number and 9 the foreground: ``` [[9,2,9,9,2,2], [2,2,2,2,2,2], [9,2,9,9,2,2], [9,2,9,9,2,2]] ``` An invalid output example would be ``` # # # # # # # # # ``` as the rectangles have separators in between them. Example outputs for \$4 \times 4\$: ``` # ## ### #### # ## ### #### # ## ### #### # ## ### #### # ## ### #### # ## ### #### # ## ### #### # ## ### #### # ## ### #### # ## ### #### 1 0 1 1 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 ``` [Answer] # [R](https://www.r-project.org/), ~~56~~ ~~54~~ ~~43~~ ~~36~~ 30 bytes ``` x=!!sequence(2:scan())-1;x%o%x ``` [Try it online!](https://tio.run/##K/r/v8JWUbE4tbA0NS85VcPIqjg5MU9DU1PX0LpCNV@14r/JfwA "R – Try It Online") Takes input one above \$n\$ (so returns 3x3 matrix for \$n = 4\$). Returns a matrix of \$1s\$ (foreground), and \$0s\$ (background) with an extra row/column of zeroes in front. Thanks to digEmAll for -7 bytes. [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` f n=map=<<flip(map.max)$show.(10^)=<<[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY3scDWxiYtJ7NAA8jUy02s0FQpzsgv19MwNIjTBEpFG@rp5cX@z03MzFOwVQCq8VUoKC0JLinyyVNQUUhTMPn/LzktJzG9@L9uckEBAA "Haskell – Try It Online") A clever approach by Ørjan Johansen outputting with 0's and 1's, generating each `10...00` part as the string representation of a power of 10. ``` 111111111 101001000 111111111 101001000 101001000 111111111 101001000 101001000 101001000 ``` --- **[Haskell](https://www.haskell.org/), 49 bytes** ``` f n=map=<<flip(map.max)$[0^i|x<-[1..n],i<-[0..x]] ``` [Try it online!](https://tio.run/##DcoxCoAwDADAr2RwUNCg4Ng@wRdIhSBWg20J6tDBtxu73XAH3ecWgqqHZCOJNcYHlroQI@WmmvuF32y6eUBMruWiHjE7p5E4gYUyJ5CL0wMVeBj1W32g/dZuFfkB "Haskell – Try It Online") Generates a pattern like `[1,0,1,0,0,1,0,0,0,...]`, then makes a 2D by taking the `min` of pairs. The pointfree weirdness saves 2 bytes over the more readable: ``` f n|l<-do x<-[1..n];0:(1<$[1..x])=[[a*b|a<-l]|b<-l] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hrybHRjclX6HCRjfaUE8vL9bawErD0EYFxKmI1bSNjk7USqpJtNHNia1JApH/cxMz8xRsFXITC3wVCooy80oUVBTSFEz@/0tOy0lML/6vm1xQAAA "Haskell – Try It Online") [Answer] # JavaScript (ES6), ~~73 72~~ 69 bytes Returns a string made of 1's, spaces and line feeds. ``` n=>(g=s=>n-->0?g(s+`${p+=1} `):s[~n]?(+s[~n]?s:'')+` `+g(s):'')(p='') ``` [Try it online!](https://tio.run/##JYpBCsIwEADvecUehG5YIvbgpXXTh4iQUpuglE1oxEupX48RLzMMzHN8j3laH@llJN7n4rkIWwyc2Yox9jQEzOQOWyJud3C6y9eP3Aakv3PXNJqcclQ//QtMXFl8XFGAoe1B4MJwribSsCmAKUqOy3xcYkCPonWv9vIF "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES7), ~~87 83~~ 82 bytes *Saved 3 bytes thanks to @dzaima* Returns a binary matrix, which is built cell by cell. ``` n=>[...Array(n*(n+3)/2)].map((_,y,a)=>a.map(h=(z,x)=>(17+8*x)**.5%1&&(z||h(1,y)))) ``` [Try it online!](https://tio.run/##LYzBCoJAFEX3fsXbpO85NmEhBTZC31ERg2kq9kbGCDX7dhPpbs49m1Ppt25TWzavNZt7NuVqYpWcpZQna3WP7COLHW22dJVP3SDegj7QpBK9aKFwCLpZMdyLg9@R78toFbouDuNYYBj0NG/KjUUGBWEMDEcF0UwhCD4OQGq4NXUma/PAHJmWrgWVgJWVKRk98Ij@98IegYCFsfOdfg "JavaScript (Node.js) – Try It Online") ### How? The width \$w\$ of the matrix is given by: $$w=T\_n+n-1={n+1\choose 2}+n-1=\frac{n(n + 3)}{2}-1$$ (NB: As allowed by the challenge rules, we output a matrix of width \$w+1\$ instead.) Similarly, the cell located at \$(X,Y)\$ is empty if the following quadratic admits an integer root for either \$k=X\$ or \$k=Y\$: $$\frac{x(x+3)}{2}-1-k=0\\ x^2+3x-2-2k=0 $$ whose determinant is: $$\Delta=9-4(-2-2k)=17+8k$$ [Answer] # MATL, ~~14~~ 10 bytes ``` :"@:Fv]g&* ``` This answer uses `1` for the blocks and `0` for the background Try it at [MATL Online](https://matl.io/?code=%3A%22%40%3AFv%5Dg%26%2a&inputs=3&version=20.10.0) **Explanation** ``` % Implicitly grab the input as an integer, N % STACK: { 3 } : % Create an array from 1...N % STACK: { [1, 2, 3] } " % For each element M in this array @: % Create an array from 1...M % STACK (for 1st iteration): { [1] } % STACK (for 2nd iteration): { [1; 0], [1, 2] } % STACK (for 3rd iteration): { [1; 0; 1; 2; 0], [1, 2, 3] } F % Push a zero to the stack % STACK (for 1st iteration): { [1], 0 } % STACK (for 2nd iteration): { [1; 0], [1, 2], 0 } % STACK (for 3rd iteration): { [1; 0; 1; 2; 0], [1, 2, 3], 0 } v % Vertically concatenate everything on the stack % STACK (for 1st iteration): { [1; 0] } % STACK (for 2nd iteration): { [1; 0; 1; 2; 0] } % STACK (for 3rd iteration): { [1; 0; 1; 2; 0; 1; 2; 3; 0] } ] g % Convert everything to be boolean (turns all non-zeros to 1) % STACK: { [1; 0; 1; 1; 0; 1; 1; 1; 0] } &* % Perform element-wise multiplication to expand this array out into the 2D grid % Implicitly display the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 1ẋⱮj0ȧþ` ``` [Try it online!](https://tio.run/##ARwA4/9qZWxsef//MeG6i@KxrmowyKfDvmD/w4dH//80 "Jelly – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ ~~10~~ 12 [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") ``` ∘.×⍨∊,\0,⎕⍴1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIQ1IztA7PP1R74pHHV06MQY6j/qmPurdYgiS5Up71DbhUW@f4aOeveq11eo66kBJEC5Sf9S7Vf1R1yKjRz3bgfzkIvU0dYVHvXMVSooSU9LyFEryFYDU/zQFYwA "APL (Dyalog Unicode) – Try It Online") **Edit:** -2 bytes from ngn. +2 bytes because the previous answers were invalid (with idea thanks to ngn and dzaima). ## Explanation ``` ∘.×⍨∊,\0,⎕⍴1 ⎕ Take input. ⍴1 An array of 1s of length our input. Example: 1 1 1 0, Prepend a 0. Example: 0 1 1 1 ,\ Take all the prefixes and concatenate them. Example: 0 0 1 0 1 1 0 1 1 1 ∊ Flatten the list. Example: 0 0 1 0 1 1 0 1 1 1 ∘.×⍨ Turn the above list into a multiplication table of 0s and 1s by multiplying the list with itself. ``` The output should look like: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ‘RÄṬ|þ` ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4ygwy0Pd66pObwv4f/hdvf//00A "Jelly – Try It Online") Outputs a digit matrix, using \$0\$ for the rectangles and \$1\$ for the padding between them. The TIO link contains a footer which formats a digit matrix in a human-readable way by lining up the rows and columns. ## Explanation ``` ‘RÄṬ|þ` R Take a range from 1 to ‘ {the input} plus 1 Ä Cumulative sum; produces the first {input}+1 triangular numbers Ṭ Produce an array with 1s at those indexes, 0s at other indexes þ Create a table of {the array} ` with itself | using bitwise OR ``` The number at cell \$(x,y)\$ of the resulting table will be \$1\$ if either \$x\$ or \$y\$ is a triangular number, or \$0\$ otherwise (because bitwise OR works like logical OR on 0 and 1). (We use `R`, range from 1, because Jelly uses 1-based indexing, so we don't have to worry about column 0 being incorrectly full of 0s; we have to add 1 to the input because the array produced by `Ṭ` stops at the largest element given in the input, so we need to draw a line on the right-hand side and the bottom.) The gaps between triangular numbers are the consecutive integers, so the rectangular blocks formed by the gaps between the lines end up as the sizes requested by the question; and the use of an OR operation (in this case, bitwise) allows the lines to cross each other correctly. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes Defines a program \$f\texttt{: }\color{purple}{\texttt{Nat}} →\color{purple}{\texttt{List}}\texttt{[}\color{purple}{\texttt{List}}\texttt{[}\color{purple}{\texttt{Nat}}\texttt{]]}\$. ### Code: ``` $L×0ýSDδ* ``` Uses the [**05AB1E**-encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md). [Try it online!](https://tio.run/##yy9OTMpM/f9fxefwdIPDe4Ndzm3R@v/fBAA "05AB1E – Try It Online") or use the [pretty-printed version](https://tio.run/##yy9OTMpM/f9fxefwdIPDe4Ndzm3R@n9o938TAA "05AB1E – Try It Online"). ### Explanation: ``` $ # Push the number 1 and the input ***n*** L # Create the list [1, 2, 3, ..., ***n***] × # Vectorized string multiplication: 1 × [1, 2, 3, ..., ***n***] This would result in ["1", "11", "111", ..., "1" × ***n***] 0ý # Join the resulting list with '0', resulting in "10110111011110111110..." S # Split into single digits: [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, ...] Dδ* # Multiplication table with itself ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~96~~ 95 bytes -1 byte thanks to [Embodiment of Ignorance](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance) ``` n=>{var l="";for(;n>0;)l=new string('#',n--)+' '+l;for(;n<l.Length;)WriteLine(l[n++]>32?l:"");} ``` [Try it online!](https://tio.run/##LcoxCwIhFADgvyI26MOMKGronUb77Q3REKJ3wuMdqNQQ/XZraPmmL1Qbau6X0PLCQ@bmRXKdnX8/H0WQkxLTUjSy3yKQ4/gStZXMk1YrtWZrwSihDP3XQJsx8tRmhGvJLY6Zo6YbG3P3@92ZTlICfjomfYAfR8D@BQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` s='';n=input() while n:s='#'*n+' '+s;n-=1 for c in s:print(c>' ')*s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWXd06zzYzr6C0REOTqzwjMydVIc8KKKysrpWnra6grl1snadra8iVll@kkKyQmadQbFVQlJlXopFsB5TV1Cr@/98UAA "Python 2 – Try It Online") Prints blank lines for empty lines, which the challenge allows. Same length (with input one above `n`): ``` r=range(input()) for n in r:print(' '.join(i*'#'for i in r)+'\n')*n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVUjM6@gtERDU5MrLb9IIU8hM0@hyKqgKDOvRENdQV0vKz8zTyNTS11ZHSSdCZbW1FaPyVPX1Mr7/98MAA "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` a#&/@(a=Flatten@Array[{0,1~Table~#}&,#])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P1FZTd9BI9HWLSexpCQ1z8GxqCixMrraQMewLiQxKSe1TrlWTUc5VlPtf0BRZl6JvkNatEnsfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ≔⪫EN×#⊕ι θEθ⭆θ⌊⟦ιλ ``` [Try it online!](https://tio.run/##LYs9C8IwEEB3f8URlwvEza2TY4VKwW7iEGOoB8m1zUf//hnE5cHj8dzHJrfYIHLJmWbG60KMg12x57WWW40vn1AbmCj6jOqoDPTsko@ei38jad2iAtW46e4wJuLy@zcD99Js/stATLFGfJCB8Gyb7kTOctrDFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input number E Map over implicit range ι Current value ⊕ Incremented × Repetitions of # Literal `#` ⪫ Join with spaces ≔ θ Assign to variable θ Retrieve variable E Map over characters θ Retrieve variable ⭆ Replace characters with ⌊ Minimum of ⟦ List of ι Row character λ Column character Implicitly print each row on its own line ``` [Answer] # [Mouse-2002](http://mouse.davidgsimpson.com/mouse2002/), 79 bytes Abusing Mouse's macros to repeat functionality. ``` ?1+n:#P,n,j,k,b#P,j,y,k,#P,n,i,' ,#P,i,x,35;;;;$P0 2%:(1%.2%.-^4%3%!'2%.1+2%:)@ ``` [Try it online!](https://tio.run/##y80vLU41MjAw@v/f3lA7z0o5QCdPJ0snWycJyMrSqQSywEKZOuoKIFamToWOsak1EKgEGCgYqVppGKrqGanq6caZqBqrKqoDmYbaQGFNh/8q/40B "Mouse-2002 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~208~~ 155 bytes ``` class M{static void Main(string[]a){int i=int.Parse(a[0]);var l="";for(;i>0;)l=new string('#',i--)+' '+l;for(;;)System.Console.WriteLine(l[i++]>32?l:"");}} ``` [Try it online!](https://tio.run/##JcuxCsIwFEDRXwlxSEJsaXUztA6uFgQHh9IhxKc8iAnkhYqUfnsUXO50rqPKxQSlOG@J2LBQthkdmyPe2WAxSMoJw3OcrFowZIbdr/XFJgJpx2ZSZraJ@Y5z84hJGuwbo3wX4M3@pxQbscWqUlowof1fGXX9UIZXfYqBoof6ljDDGQNIP6LWU7/fHf2Bc2XWtZTStl8 "C# (.NET Core) – Try It Online") A much revised version thanks to various helpful people (see the comments). [Answer] # [PowerShell](https://docs.microsoft.com/en-us/powershell/), ~~42~~ 40 bytes -2 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy). ``` ($r=1.."$args")|%{"$($r|%{'#'*$_}) "*$_} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0OlyNZQT09JJbEovVhJs0a1WkkFKAak1ZXVtVTiazW5lEDU////DQ0A) [Answer] # Java 11, 109 bytes ``` n->{var l="";for(;n>0;)l="x".repeat(n--)+" "+l;for(;n<l.length();)System.out.println(l.charAt(n++)>32?l:"");} ``` Port of [*@ASCII-only*'s C# .NET answer](https://codegolf.stackexchange.com/a/181678/52210). [Try it online.](https://tio.run/##LY/BjsIwDETvfIWVU6KqEQLtHjZQxAfAhSPagwkBCsat0lCBUL@9GOjF8ow88psztpif95feEzYNrLDk5wig5BTiAX2A9VsCtFW5B6/FBzZOrG4ko0mYSg9rYJhDz3nxbDECzZVyhypqx8XYGZF3ZWOoAybNeW4yBSqj4WJGlgIf00kbZzaPJoWrrW7J1lF@EWuy/oRxKcksM8V0sqA/pYzrevcGqG87EoCB4wN5lQp6kyR@3P4Dmi8/W69/PuDf/Xco0fUv) ``` n->{ // Method with integer parameter and no return-type var l=""; // Line-String, starting empty for(;n>0;) // Loop until `n` is 0: l=...+l; // Prepend to `l`: "x".repeat(n--)+" " // Repeat "x" `n` amount of times, appended with a space // And decrease `n` by 1 afterwards with `n--` for(;n<l.length();) // Inner loop as long as `n` is smaller than the length of `l`: System.out.println( // Print with trailing newline: l.charAt(n++)>32? // If the `n`'th character of the line-String is NOT a space: // And increase `n` by 1 afterwards with `n++` l // Print the line-String : // Else: "");} // Print nothing (so only the newlines) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 170 bytes ``` (({})<>){(({})<{({}[()]<(<>({})<>){(({})<{({}[(())])}>[()])}{}{}(([(()()()()())(){}]){})>)}{}(({}))>[()])}{}{}{}([]){{}({}<>((((()()){}){}){}){})<>([])}{}<>{({}<>)<>}<>{} ``` [Try it online!](https://tio.run/##bY2xCsQwDEN/xxq6dwiGfkfIkA6FcqVDV@Nvd@WUOzpc7DhCesHr1fdz2o7@iRAxR1HYI4yzClqRov8SARpcE4EbSyTNb7HNGy8UI6TCi6ZVGfMx54I8@YvUr2nXQRe1QdFJ7RFzTMsN "Brain-Flak – Try It Online") [Answer] # APL+WIN, 29 bytes ``` m/⍉(m←¯1↓∊(⍳n),¨¯1)/(n,n←⎕)⍴1 ``` Explanation: ``` (n,n←⎕)⍴1 prompt for integer n and create a nxn matrix of 1s (m←¯1↓∊(⍳n) replicate the columns by 1,2,.....n and insert 0s between each replication m/⍉ repeat replication and 0 insertion for the rows from above ``` Example: ``` ⎕: 3 1 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 1 1 0 1 1 1 1 0 1 1 0 1 1 1 ``` [Answer] # [J](http://jsoftware.com/), 17 bytes ``` [:*/~2=/\[:I.2+i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209OuMbPVjoq089Yy0M/X@a3IpcKUmZ@QrpCmY/AcA "J – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes ``` ->n{(s=(1..n).map{|x|?#*x}*' ').chars.map{|c|c<?!?c:s}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWqPYVsNQTy9PUy83saC6pqLGXlmrolZLXUFdUy85I7GoGCKeXJNsY69on2xVXFv7v6C0pFghLdo89j8A "Ruby – Try It Online") ### How? First, create the first line, then iterate through its chars. Print the whole line if the character is '#', otherwise print the single character (which is a space) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~35~~ 33 bytes ``` {((\*Xx$_+1)~" "Xx$_+1)>>.say}o^* ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMjRiuiQiVe21CzTolLCcq0s9MrTqyszY/T@m/NlaZhogkiTTX/AwA "Perl 6 – Try It Online") Anonymous Callable that takes a number and prints the multiplication table with `*`s with a trailing newline. ### Explanation: ``` { }o^* # Change the input to the range 0..n-1 (\*Xx$_+1) # Cross string multiply '*' by all of range 1..n # This creates the string "* ** *** ****" etc. ~"\n" # Append a newline Xx$_+1 # Cross string multiply again ( )>>.say # And print all the lines ``` [Answer] ## Haskell, ~~69~~ 68 bytes ``` (a#b)0=[] (a#b)n=(a#b)(n-1)++b:(a<$[1..n]) f n=((1#0)n#(0<$(1#0)n))n ``` Returns a matrix of numbers. [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNROUnTwDY6lgvMyrMFUxp5uoaa2tpJVhqJNirRhnp6ebGaXGkKQFkNQ2UDzTxlDQMbFQhTUzPvf25iZp6CrUJuYoFvvEJBUWZeiYKKQpqCyX8A "Haskell – Try It Online") Variants of `f` with the same byte count: ``` f n=((#)<*>(0<$)$(1#0)n)n f n|l<-(1#0)n=(l#(0<$l))n ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é╫▐§╘←╘ ``` [Run and debug it](https://staxlang.xyz/#p=82d7de15d41bd4&i=3&a=1) The chosen character is backtick. (How do you code format that in markdown?) That means `a` and `b` are considered extraneous whitespace. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 20 bytes ``` ╒ÉÄ10;]h\■mÆε*╣¡§y╠n ``` [Try it online!](https://tio.run/##AUIAvf9tYXRoZ29sZv8ibiA9ICJcK3D/4pWSw4nDhDEwO11oXOKWoG3Dhs61KuKVo8Khwqd54pWgbv9u/zEKMgozCjUKMTA "MathGolf – Try It Online") MathGolf really needs to get some more functionality for splitting lists and creating 2D lists. ## Explanation ``` ╒ range(1,n+1) É start block of length 3 Ä start block of length 1 1 push 1 0 push 0 ; discard TOS ] end array / wrap stack in array the stack now contains the list [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, ...] h length of array/string without popping (used for splitting string) \ swap top elements ■ cartesian product with itself for lists, next collatz item for numbers m explicit map Æ start block of length 5 ε* reduce list by multiplication (logical AND) ╣¡ push the string " #" § get character at index 0 or 1 based on logical AND value block ends here, stack is now ['#',' ','#','#',' ','#',...] y join array without separator to string ╠ pop a, b, push b/a (divides the string using the length of a single line) n join array of strings with newlines ``` [Answer] # [Ink](https://github.com/inkle/ink), ~~151~~ ~~152~~ 151 bytes ``` VAR k=0 =t(n) ~k=n -(u) ~n-- {n+1:->s(k-n)->u}->-> =r(c) ->g(c)-> {k-c:<>->r(c+1)}->-> =g(n) {n>1:@<>->g(n-1)}@->-> =s(n) {n: ->r(1)-> ->s(n-1) } .->-> ``` [Try it online!](https://tio.run/##LY09CsMwDEZ3naKjTPhKDZ1MLdIrdOgFMoQi0NAkk0mv7kikk37e06ePaYesfE@Q/n6@LlpvVFe2RD@tRuDNOwOo2ZALZGGFubztEAjVL0@JILMXH5tiKg8Hvh5y@jtzxDWTXMZgPsLZeMLlhIXiKEdIPAmDdrqG0/sB "ink – Try It Online") Good thing the rules allow excess characters. Edit: +1: Fixed spacing. Also, display using @ (which doesn't need escaping) instead of # (which does) Edit: -1: Apparently that fix also meant I no longer needed a trailing period to force a newline on the non-empty lines. Neat. [Answer] ## C++, ~~170~~ 156 bytes Thanks to dzaima ``` #include<string> using v=std::string;v f(int a){v s;for(int i=1;i<=a;++i,s+='\n')for(int k=0;k<i;++k,s+='\n')for(int j=1;j<=a;++j)s+=v(j,'#')+' ';return s;} ``` [Answer] # [Julia 1.0](http://julialang.org/), 40 bytes ``` \ =join !N=('#'.^(r=1:N)\' '*'\n').^r\'\n' ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P0bBNis/M49L0c9WQ11ZXS9Oo8jW0MpPM0ZdQV1LiUtJUy@uKAZI/y8oyswr0VA00/wPAA "Julia 1.0 – Try It Online") outputs a string with `#` and spaces: ``` julia> print(!3) # ## ### # ## ### # ## ### # ## ### # ## ### # ## ### ``` [20 bytes](https://tio.run/##yyrNyUw0rPj/X9HPNj8vtVhPw9DKTwdEaKpr/k/JLC7ISazUUDTW/A8A "Julia 1.0 – Try It Online") with less strict output format, by returning a matrix of matrices: `!N=ones.(1:N,(1:N)')` [Answer] # SmileBASIC, ~~83~~ 77 bytes Graphical output. Input is `N-1` ``` INPUT N FOR J=0TO N X=0FOR I=0TO N GFILL X,Y,X+I,Y+J X=X+I+2NEXT Y=Y+J+2NEXT ``` [Answer] # [Python 3](https://www.python.org), 88 83 bytes -5 bytes from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) ``` n,l=range(int(input())),'' for i in n:l+='#'*-~i+' ' for j in n:print((l+'\n')*-~j) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8@2KDEvPVUjM68EiAtKSzQ0NTW50vKLFLIUMvMU8qy4FHJs1dW5FEBCmRChHG1bdWV1Ld26TG11BaBUQRFIt0aOtnpMnromUDxL8/9/UwA "Python 3 – Try It Online") [Answer] ## Perl 6, 63 bytes ``` {(1..$_).map(((1..$_).map("#"x*).join(" ")~"\n")x*).join("\n")} ``` ]
[Question] [ Your task is to output a Magical 8 Trapezium: ``` 1 × 8 + 1 = 9 12 × 8 + 2 = 98 123 × 8 + 3 = 987 1234 × 8 + 4 = 9876 12345 × 8 + 5 = 98765 123456 × 8 + 6 = 987654 1234567 × 8 + 7 = 9876543 12345678 × 8 + 8 = 98765432 123456789 × 8 + 9 = 987654321 ``` * Output in your chosen language in the fewest bytes possible. * Note the number of spaces at the start of each line to maintain the trapezium shape. * Trailing spaces are allowed. * You can use `×` or the letter x - whichever you prefer. [Answer] ## Python 2, 59 bytes ``` a=i=1 exec"print'%9d x 8 +'%a,i,'=',a*8+i;i+=1;a=a*10+i;"*9 ``` The numbers `a` and `i` the equation `a * 8 + i` are generated arithmetically. Each line, `i` is incremented, and `a` has the next digit appended via `a=a*10+i`. For example, if `a=12345, i=5`, then `i` becomes `6`, so the new `a` is `12345*10 + 6` which is `123456`. Storing these as numbers rather than strings lets us compute the RHS as given by the equation `a*8+i`, which is shorter than string reversing. [Answer] # [V](https://github.com/DJMcMayhem/V), 37 bytes ``` i¸ 1 X 8 + 1 = 98ñYp|Eylp^Xf+$ylp ``` [Try it online!](http://v.tryitonline.net/#code=acK4IDEgWCA4ICsgMSA9IDkbOMOxWXB8RXlscAFeWGYrASR5bHAY&input=) This contains unprintable, so here is a hexdump: ``` 00000000: 69c2 b820 3120 5820 3820 2b20 3120 3d20 i.. 1 X 8 + 1 = 00000010: 391b 38c3 b159 707c 4579 6c70 015e 5866 9.8..Yp|Eylp.^Xf 00000020: 2b01 2479 6c70 18 +.$ylp. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~32~~ ~~31~~ ~~30~~ 28 bytes Code: ``` TG9N-ð×NLJðN"x8+ÿ="€ðJžmN£J, ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=VEc5Ti3DsMOXTkxKw7BOIng4K8O_PSLigqzDsErFvm1OwqNKLA&input=). [Answer] ## PHP, ~~105~~ ~~89~~ ~~60~~ 57 bytes my first golf try here (thanks to manatwork & user55641) ``` for(;$i++<9;)printf("%9s x 8 + $i = %s ",$s.=$i,$s*8+$i); ``` ### 59 ``` for(;$i++<9;)printf("%9s x 8 + $i = %s ",$s.=$i,$t.=10-$i); ``` ### 89 (my own try) ``` for(;@++$i<=9;){printf("%9s x 8 + %s = %s\n",join(range(1,$i)),$i,join(range(9,10-$i)));} ``` ### 105 (first) ``` for($j='123456789';@$j[$i++];){printf("%9s x 8 + %s = %s\n",substr($j,0,$i),$i,strrev(substr($j,-$i)));} ``` [Answer] # Pyth, 32 bytes ``` VS9ss[*dK-9NSN" x 8 + "N" = "r9K ``` [Try it online!](http://pyth.herokuapp.com/?code=VS9ss%5B%2adK-9NSN%22+x+8+%2B+%22N%22+%3D+%22r9K&debug=0) ``` VS9ss[*dK-9NSN" x 8 + "N" = "r9K VS9 # For N in 1..9 s # Join without delimiter s[ # Reduce the array on + (flattens) *dK-9N # - Space, repeated K=(9-N) times SN # - The string sequence 1..N " x 8 + " # - This string literal N # - N itself " = " # - This string literal r9K # - The string sequence 9..K ``` --- Thanks to @FryAmTheEggman for saving 2 bytes. Thanks to @KennyLau for saving 3 bytes. [Answer] ## CJam, ~~39~~ ~~38~~ 36 bytes *Thanks to Optimizer for saving 2 bytes.* ``` 9{)_,:)9Se[" x 8 + "@S'=S9_,fm4$<N}/ ``` [Test it here.](http://cjam.aditsu.net/#code=9%7B)_%2C%3A)9Se%5B%22%20x%208%20%2B%20%22%40S'%3DS9_%2Cfm4%24%3CN%7D%2F) Same byte count: ``` 9{)_,:)9Se[]"x8+"+:\'=9_,f-Y$<]S*n}/ ``` This requires the latest version, available on [Try it online!](http://cjam.tryitonline.net/#code=OXspXyw6KTlTZVtdIng4KyIrOlwnPTlfLGYtWSQ8XVMqbn0v&input=) [Answer] # Python 2, ~~87~~ ~~84~~ ~~78~~ 75 bytes ``` s="123456789" n=1 exec'print"%9s"%s[:n],"x 8 + %s ="%n,s[::-1][:n];n+=1;'*9 ``` [**Try it online**](http://ideone.com/nr9mEO) A previous version uses some string magic. ``` R=range(1,10) for n in R:print" "*(9-n)+`R`[1:n*3:3]+" x 8 + %d = "%n+`R`[-2:27-3*n:-3] ``` Casting `range(1,10)` to a string gives `[1, 2, 3, 4, 5, 6, 7, 8, 9]`, and this is nice since every number is only a single digit. So getting the string `123456789` from this is simple with ``range(1,10)`[1::3]`. The reversed range is ``range(1,10)`[-2::-3]`. Then, to get only as far as I want each iteration, I slice it off at either `3*n`, or at `3*(9-n)` (`27-3*n`) for the reversed digits. [Answer] ## Perl, 49 bytes ``` printf"%9s x 8 + $_ = %s ",$@.=$_,$_+8*$@for 1..9 ``` ### Usage ``` perl -e 'printf"%9s x 8 + $_ = %s ",$@.=$_,$_+8*$@for 1..9' ``` [Answer] # Ruby, ~~77~~ ~~73~~ ~~65~~ 60 bytes [Try it online~](https://repl.it/Cfhi/37) Major revamps from @manatwork Another overhaul from @xsot ``` a=i=0;9.times{puts"%9d x 8 + %d = %d"%[a=a*10+i+=1,i,a*8+i]} ``` [Answer] # Java 10, ~~151~~ ~~133~~ ~~130~~ ~~129~~ ~~126~~ 110 bytes ``` v->{String p="\n",r="";for(int n=123456789,i=9;i>0;n/=10,p+=" ")r=p+n+" x 8 + "+i+" = "+(n*8+i--)+r;return r;} ``` [Try it online.](https://tio.run/##LY/LTsMwEEX3/Yorr2ychJZnKsv9A7pBYgMsXDdFLu7EcpwIVOXbgyOymbdG55zNYMrz8Xuy3nQdXoyj6wpwlJp4MrbBfm6B1xQdfcHyt9YdMQiVp@Mqhy6Z5Cz2IOhpKHfX5TJo9kGsiJoxdWojzx9BenN3//D49FxvC6e3yu3Wim71Zl0EqRmYiDpIkgw/qCHBpMu1zpnTTS1dWQoZVWxSHwlRjZOaAUJ/8Blg4RhmvEu24P8c758wYlH47VJzqdo@VSGvkidOleXUey8Wn3H6Aw) **Explanation:** ``` v->{ // Method with empty unused parameter and String return-type String p="\n", // Prefix-String, starting at a newline r=""; // Result-String, starting empty for(int n=123456789, // Multiply-number, starting at 123456789 i=9;i>0 // Loop `i` in the range [9, 0): ; // After every iteration: n/=10, // Remove the last digit from the integer p+=" ") // Append a space after the prefix r=...+r; // Prepend the following to the result-String: p // The prefix-String +n // Followed by the integer +" x 8 + " // Followed by the literal String " x 8 + " +i // Followed by the loop-index `i` +" = " // Followed by the literal String " = " +(n*8+i--) // Followed by the result of that equation return r;} // Return the result-String ``` [Answer] ## C#, 113 bytes ``` void f(){for(int n=1,i=1;i<10;n=10*n+ ++i)Console.WriteLine(new string(' ',9-i)+n+" x "+"8 + "+i+" = "+(n*8+i));} ``` if you have anyway to improve this solution feel free to share. [Answer] ## Batch, 117 bytes ``` @echo off set a= 12345678987654321 for /l %%i in (1,1,9)do call echo %%a:~%%i,9%% x 8 + %%i = %%a:~17,%%i%% ``` Yes, that is 16 % signs on one line; that's Batch for you! [Answer] ## Haskell, 92 bytes ``` s=(show=<<) [1..9]>>= \x->([x..8]>>" ")++s[1..x]++" x 8 + "++s[x]++" = "++s[9,8..10-x]++"\n" ``` How it works: ``` s=(show=<<) -- helper function that turns a list of numbers into -- a string without delimiters, e.g. [1,2] -> "12" [1..9]>>= -- for each number 1 to 9 ([x..8]>>" ") -- take length of [x..8] copies of a space s[1..x] -- the digits from 1 to x " x 8 + " -- a string literal s[x] -- the digit of x " = " -- another string literal s[9,8..10-x] -- the digits from 9 down to 10-x "\n" -- an a newline ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 66 bytes Byte count assumes ISO 8859-1 encoding. The leading linefeed is significant. ``` 123456789!9 = 987654321 +`^((.)+)\B.!.(.+). $1!$2$3¶$& ! x 8 + ``` [Try it online!](http://retina.tryitonline.net/#code=CjEyMzQ1Njc4OSE5ID0gOTg3NjU0MzIxCitgXigoLikrKVxCLiEuKC4rKS4KICQxISQyJDPCtiQmCiEKIHggOCArIA&input=) [Answer] ## Pyke, ~~30~~ 29 bytes ``` 9Fd*~utj+9<\x8\+9i-\=ji>_dJ)X ``` [Try it here!](http://pyke.catbus.co.uk/?code=9Fd%2a%7Eutj%2B9%3C%5Cx8%5C%2B9i-%5C%3Dji%3E_dJ%29X&warnings=0) ``` 9F ) - for i in range(9): d* - " " * i + - ^ + V j - j = V ~ut - "123456789" 9< - ^[:9] \x8\+9i-\= - [^, "x", 8, "+", (9-i), "=", V] _ - reversed(V) ji> - j[i:] dJ - " ".join(^) X - print(reversed(^)) ``` [Answer] ## PowerShell v2+, ~~85~~ ~~64~~ ~~58~~ ~~57~~ 52 bytes ``` 8..0|%{" "*$_+-join(1..++$i+" x 8 + $i = "+9..++$_)} ``` Loops from 8 to 0 `8..0|%{...}` via the range operator. Each iteration, we output a string concatenation consisting of (the appropriate number of spaces `" "*$_`), plus a `-join`ed string of (a range from `1` to a pre-incremented helper number `++$i`, plus the middle bit `" x 8 + $i = "`, plus the final range from `9` to the current number `$_` pre-incremented). One big trick here is we leverage the "left-preference" for typecasting, which allows us to "add" arrays together inside the `-join` parens, meaning we use only one `-join` operator. ### Example ``` PS C:\Tools\Scripts\golfing> .\magical-8-trapezium.ps1 1 x 8 + 1 = 9 12 x 8 + 2 = 98 123 x 8 + 3 = 987 1234 x 8 + 4 = 9876 12345 x 8 + 5 = 98765 123456 x 8 + 6 = 987654 1234567 x 8 + 7 = 9876543 12345678 x 8 + 8 = 98765432 123456789 x 8 + 9 = 987654321 ``` [Answer] # C, 74 bytes ``` d(i,n){for(i=n=1;i<10;n=++i+n*10)printf("%9d x 8 + %d = %d\n",n,i,n*8+i);} ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~38~~ ~~36~~ 35 bytes ``` 9:"9@-Z"@:!V' x 8 + '@VO61O58@:-v!D ``` [**Try it online!**](http://matl.tryitonline.net/#code=OToiOUAtWiJAOiFWJyB4IDggKyAnQFZPNjFPNThAOi12IUQ&input=) [Answer] # J, 51 bytes ``` (|."1|.\p),.' x 8 + ',"1]p,.' = ',"1]\|.p=:u:49+i.9 ``` Creates the string `123456789` and then operates on prefixes and suffixes of it to create the output. ### Usage ``` (|."1|.\p),.' x 8 + ',"1]p,.' = ',"1]\|.p=:u:49+i.9 1 x 8 + 1 = 9 12 x 8 + 2 = 98 123 x 8 + 3 = 987 1234 x 8 + 4 = 9876 12345 x 8 + 5 = 98765 123456 x 8 + 6 = 987654 1234567 x 8 + 7 = 9876543 12345678 x 8 + 8 = 98765432 123456789 x 8 + 9 = 987654321 ``` [Answer] # JavaScript ES6 (88) Taking advantage of the new `repeat` method, backticks and templating... ``` i=10;for(y="";--i;)console.log(`${" ".repeat(i)+(y+=(x=10-i))} x 8 + ${x} = ${y*8+x}\n`) ``` [Answer] # R, ~~107~~ 103 bytes ``` a=1;for(i in 2:10){cat(rep("",11-i),paste(a,"x",8,"+",(i-1),"=",strtoi(a)*8+(i-1)),"\n");a=paste0(a,i)} ``` **Ungolfed :** ``` a=1 for(i in 2:10) cat(rep("",11-i),paste(a,"x",8,"+",(i-1),"=",strtoi(a)*8+(i-1)),"\n") a=paste0(a,i) ``` **Result :** ``` 1 x 8 + 1 = 9 12 x 8 + 2 = 98 123 x 8 + 3 = 987 1234 x 8 + 4 = 9876 12345 x 8 + 5 = 98765 123456 x 8 + 6 = 987654 1234567 x 8 + 7 = 9876543 12345678 x 8 + 8 = 98765432 123456789 x 8 + 9 = 987654321 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~61~~ ~~52~~ 39 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` ↑(⍳9)((¯9↑↑),' x 8 +',⊣,'= ',↑∘⌽)¨⊂1↓⎕D ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HbRI1HvZstNTU0Dq23BPKASFNHXaFCwUJBW13nUddiHXVbBSADKNMx41HPXs1DKx51NRk@apv8qG@qy///AA "APL (Dyalog Unicode) – Try It Online") -9 bytes by using the `10⊥` trick to parse the number, instead of a reduction. Thanks to @Adám for -13! Explanation: ``` ↑ ((¯9↑↑),' x 8 +',⊣,'= ',↑∘⌽)¨⊂1↓⎕D ⎕D ⍝ Numbers from 0 to 9 1↓ ⍝ Drop the 0 (⍳9)( )¨⊂ ⍝ Do 9 times, N=current ↑∘⌽ ⍝ Reverse the string (9..1) and cut off N elements ⊣ ⍝ N itself ( ↑) ⍝ Drop N elements off the 1..9 string... (¯9↑ ) ⍝ ...then pad it back with spaces ,' x 8 +', ,'= ', ⍝ Join with a few constant strings ↑ ⍝ Format ``` [Answer] ## JavaScript (ES6), 99 bytes ``` _=>[...Array(9)].map((n,i)=>`${n=" 123456789".substr(i,9)} x 8 + ${++i} = ${n*8+i}`).join`\n` _=>".........".replace(/./g,(n,i)=>`${n=" 123456789".substr(i,9)} x 8 + ${++i) = ${n*8+i}\n`) ``` Where `\n` represents a literal newline character. The second version outputs a trailing newline. I came up with a formula for the numbers `('1'.repeat(9-i)+0+i)/9` but the padding was easier to do this way. [Answer] # [Brainfuck](http://esolangs.org/wiki/Brainfuck), 232 bytes ``` ++++++++[->+>+>+++++[->+>+>+>+>+>+++<<<<<<]>->>+>++>+++<<<<<<<<]>++>+>>>+++>>>---<<<<<<[-[-<<+>>>>.<<]>+[-<+>>>>+.<<<]>.>>>>>.<<<<<.>>>.<<<.>.<.>>.<<.>>>>.<<<<.<<<<[->>>+>>>+<<<<<<]>>[-<<+>>>>>>.-<<<<]>[->>>-<<<<+>]<<<[->>>+<<<]>.>] ``` [Try it online!](https://copy.sh/brainfuck/?c=KysrKysrKytbLT4rPis-KysrKytbLT4rPis-Kz4rPis-KysrPDw8PDw8XT4tPj4rPisrPisrKzw8PDw8PDw8XT4rKz4rPj4-KysrPj4-LS0tPDw8PDw8Wy1bLTw8Kz4-Pj4uPDxdPitbLTwrPj4-PisuPDw8XT4uPj4-Pj4uPDw8PDwuPj4-Ljw8PC4-LjwuPj4uPDwuPj4-Pi48PDw8Ljw8PDxbLT4-Pis-Pj4rPDw8PDw8XT4-Wy08PCs-Pj4-Pj4uLTw8PDxdPlstPj4-LTw8PDwrPl08PDxbLT4-Pis8PDxdPi4-XQ$$) Can be golfed much further... [Answer] ## Javascript (using external library) (143 bytes) ``` n=>_.Range(1,9).WriteLine(v=>_.Range(0,10-v).Write("",x=>" ")+_.Range(1,v).Write("")+" x 8 + " + v + " = "+_.Range(10-v,v).Reverse().Write("")) ``` Link to lib: <https://github.com/mvegh1/Enumerable/> Explanation of code: Create range 1 to 9, and for each value, write a line corresponding to the complex predicate. The predicate is passed the current integer value, and creates a range spanning 10-currentValue elements, in order to create that many spaces. Those spaces are concatenated with the formula part of the line, and then that is concatenated with the tailend of the range matching the number of elements as the frontend, in reverse order. Note: In the image, the first line is off by one space because the console added a quotation mark since the return value is a string. The actual value is formatted correctly [![enter image description here](https://i.stack.imgur.com/DSvoW.png)](https://i.stack.imgur.com/DSvoW.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes ``` 9Lε©LJ'x8'+®'=T®L-Jðý}.c ``` [Try it online!](https://tio.run/##ASgA1/8wNWFiMWX//zlMzrXCqUxKJ3g4JyvCric9VMKuTC1Kw7DDvX0uY/// "05AB1E – Try It Online") Uses a newer version than the challenge, which is now allowed. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 20 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` 9{R⤢x∙8∙+¹=¹◂±m) *]r ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE5JXVGRjVCJXVGRjMyJXUyOTIyeCV1MjIxOTgldTIyMTkrJUI5JTNEJUI5JXUyNUMyJUIxJXVGRjREJXVGRjA5JTIwJXVGRjBBJXVGRjNEJXVGRjUy,v=8) [Answer] # VBA (Excel), 51 bytes Using Immediate Window ``` For z=1To 9:a=a &z:?Spc(9-z)a" x 8 +"z"="a*8+z:Next ``` [Answer] # k (77 bytes) Could probably be shortened a bit more ``` -1@'((|t)#\:" "),'(t#\:n),'" x 8 + ",/:n,'" = ",/:(t:"I"$'n)#\:|n:"123456789"; ``` Example: ``` k)-1@'((|t)#\:" "),'(t#\:n),'" x 8 + ",/:n,'" = ",/:(t:"I"$'n)#\:|n:"123456789"; 1 x 8 + 1 = 9 12 x 8 + 2 = 98 123 x 8 + 3 = 987 1234 x 8 + 4 = 9876 12345 x 8 + 5 = 98765 123456 x 8 + 6 = 987654 1234567 x 8 + 7 = 9876543 12345678 x 8 + 8 = 98765432 123456789 x 8 + 9 = 987654321 ``` [Answer] # golflua, 56 characters ``` p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$ ``` Sample run: ``` bash-4.3$ golflua -e 'p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$' 1 x 8 + 1 = 9 12 x 8 + 2 = 98 123 x 8 + 3 = 987 1234 x 8 + 4 = 9876 12345 x 8 + 5 = 98765 123456 x 8 + 6 = 987654 1234567 x 8 + 7 = 9876543 12345678 x 8 + 8 = 98765432 123456789 x 8 + 9 = 987654321 ``` ]
[Question] [ Your company lately hired a new bunch of *extremely dedicated* sysadmins. They feel that just watching computer screens is quite limiting (I mean, 60Hz refresh rate is just NOT enough), so they hooked up the CPU data bus to an DAC and play that on a speaker through the server room so that they can hear up to 20kHz. One problem: they're sysadmins, not electrical engineers, and their speaker setup keeps breaking. They figured that this is caused by too abrupt changes in byte values in the code that the software engineers compile on the mainframe. The sysadmins are now hosting a little competition to see who can make code that is the most gentle to their speaker setup. # Challenge Your mission is to create a **program** or **function** in a language of choice that has as little difference as possible between consecutive bytes (see the Calculation section). This program will have the task of calculating its own score. # Input An ASCII string on `stdin` or your language's closest equivalent, or as a function input if you're creating a function. Since your program will have to take itself as input to calculate your score, your program should support Unicode if it contains any Unicode. Otherwise, ASCII is sufficient. Input can be assumed to be at least 2 bytes long. # Calculation Each character of the string will be converted to it's numerical equivalent, using the ASCII standard. Then, the difference between all characters will first be **squared** and then **summed**. For example, the string `abd` will get a score of `1²+2²=5`. # Output Output will be the title to your entry. This means that it should be prepended by a `#` or appended by a newline and a `-` (dash). Then, it should output the name of your programming language, followed by a comma, a space and then an integer representing the result of the calculation. For example ``` #C++, 98 ``` would be valid output. Output should be given on `stdout` or your language closest equivalent, or as a return value to your function. # Scoring Your score will be the calculated value by your program, with the program itself as input. **Edit: Should handle newlines now, sorry for before, folks** [Here](http://pyth.herokuapp.com/?code=s%5ER2-VJCMjb.ztJ&input=0%26ii%3A0%28%3Fv%3A%40-%3A%2a%26%2B%2620.%0A%27%23%3E%3C%3E%2C+%27%3C%3Bn%26oooooo&debug=0) is a Pyth script to verify the score calculation. [Answer] # CJam, ~~1051~~ ~~827~~ ~~643~~ ~~569~~ ~~545~~ ~~407~~ ~~327~~ ~~279~~ ~~235~~ ~~233~~ 229 ``` ''"','#'C'J'a'm',' qYew::-Yf#:+e#'''''''''" f{-ci'(*''2*\}'^,40>"*/:N"-"][ZZ[\^__`bcdgimpstsz{}~~~" ``` The above program generates the actual source code, which is 1,179,112 bytes long. ### Testing Using the [Java interpreter](https://sourceforge.net/p/cjam/wiki/Home/), the source code can be generated and tested like this: ``` $ alias cjam='java -jar cjam-0.6.5.jar' $ cjam gen.cjam > diff.cjam $ cksum diff.cjam 896860245 1179112 diff.cjam $ cjam diff.cjam < diff.cjam #CJam, 229 ``` ### Alternate version At the cost of 36 points – for a final score of **265** – we can make the source code 99.92% shorter: ``` '''()))))(''''(((('''())))))))))))))))))))))))))))('''()))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''()))))(''''((((((('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))('()))))))))))))))))))('())))))('())))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''(((('()))))))))))))))))))('())))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''((((''''''''''''''''''()+,-.0123456789;<=>?@ABCDEFGHIJKLMOPQRSTUVWXYZ[\]][ZZ[\^__`bcdgimpstsz{}~~~ ``` You can try this version online in the [CJam interpreter](http://cjam.aditsu.net/#code='''()))))(''''(((('''())))))))))))))))))))))))))))('''()))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''()))))(''''((((((('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))('()))))))))))))))))))('())))))('())))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''(((('()))))))))))))))))))('())))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''((((''''''''''''''''''()%2B%2C-.0123456789%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMOPQRSTUVWXYZ%5B%5C%5D%5D%5BZZ%5B%5C%5E__%60bcdgimpstsz%7B%7D~~~&input='''()))))(''''(((('''())))))))))))))))))))))))))))('''()))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''()))))(''''((((((('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))('()))))))))))))))))))('())))))('())))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''(((('()))))))))))))))))))('())))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''((((''''''''''''''''''()%2B%2C-.0123456789%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMOPQRSTUVWXYZ%5B%5C%5D%5D%5BZZ%5B%5C%5E__%60bcdgimpstsz%7B%7D~~~). ### Idea We want to execute the code ``` '#'C'J'a'm',' qYew::-Yf#:+ ``` keeping the score as low as possible. To achieve this, we're going to build that string character by character (with a few no-ops before and after) and evaluate the result. Fortunately, `'` (push character literal), `(` (decrement) and `)` (increment) are consecutive ASCII characters, so pushing arbitrary characters is relatively inexpensive. * ASCII characters after `'` can be pushed as `'()…)(`, where the number of `)` depends on the code point. For example, `+` can be pushed as `'())))(`. The distance between `'` and `(`, and `(` and `)` is 1. The trailing `)(` cancel each other; their only function is to pave the way for the following `'` (corresponding to the next character) with consecutive characters. Characters pushed in this fashion will raise the score by 4 points. * ASCII characters before `'` can be pushed as `''(…(`, where the number of `(` depends on the code point. For example, `#` can be pushed as `''((((`. The distance between `'` and `(` is 1. Characters pushed in this fashion will raise the score by 2 points. * `''(…(` actually works for *all* ASCII characters, since *Character* is 16 bits wide and wraps around. For example, `+` can be pushed as `''`, followed by 65,532 `(`s. This technique is used in the 1.2 megabyte version of the code. * The character `'` can be pushed as `''`, leaving the score unaffected. ### Code ``` e# Push these characters on the stack: ','#'C'J'a'm',' qYew::-Yf#:+e#''''''''' '' '()))))( '' ''(((( '' '())))))))))))))))))))))))))))( '' '()))))))))))))))))))))))))))))))))))( '' '())))))))))))))))))))))))))))))))))))))))))))))))))))))))))( '' '())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))( '' '()))))( '' ''((((((( '())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))( '())))))))))))))))))))))))))))))))))))))))))))))))))( '())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))( '())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))( '()))))))))))))))))))( '()))))))))))))))))))( '())))))( '())))))))))))))))))))))))))))))))))))))))))))))))))( '()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))( ''(((( '()))))))))))))))))))( '())))( '())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))( ''(((( '' '' '' '' '' '' '' '' ''() + e# Concatenate the two topmost single quotes. , e# Push the length of the resulting string (2). -.0123456789 e# Push that number. ; e# Discard it from the stack. < e# Compare a single quote with 2. Pushes 0. = e# Compare a single quote with 0. Pushes 0. > e# Compare a single quote with 0. Pushes 1. ? e# Ternary if. Discards a single quote and 1. @ e# Rotate the remaining three single quotes. ABCDEFGHIJKLMOPQRSTUVWXYZ e# Push 25 items on the stack. [\] e# Swap the last two and wrap them in an array. e# So far, we've pushed the elements of "','#'C'J'a'm',' qYew::-Yf#:+e#'''" e# followed by the elements of [10 11 12 13 14 15 16 17 18 19 20] e# and ["" "" "" 3.141592653589793 "" "" " " 0 0 0 -1 1 [3 2]]. ] e# Wrap the entire stack in an array. [ e# Begin an array. Does nothing. ZZ e# Push 3 twice. [ e# Begin an array. Does nothing. \^ e# Swap both 3s and push the bitwise XOR. Pushes 0. __ e# Push two copies. ` e# Inspect the last copy. Pushes the string "0". b e# Convert "0" from base 0 to integer. Pushes 48. cd e# Cast 48 to Character, then Double. Pushes 48.0. gi e# Apply the sign function, then cast to integer. Pushes 1. mp e# Check 1 for primality. Pushes 0. s e# Cast the result to string. Pushes the string "0". e# We now have three elements on the stack: an array, 0, and "0" t e# Set the element at index 0 of the array to the string "0". s e# Cast the array to string. e# This pushes the string consisting of the characters e# 0,'#'C'J'a'm',' qYew::-Yf#:+ e# and e# e#'''10111213141516171819203.141592653589793 000-1132 e# e# When evaluated this does the following: e# 0, Push an empty array. Does not affect output. e# '#'C'J'a'm',' Push the characters of "#CJam, ". e# q Read all input from STDIN. e# Yew Push the overlapping slices of length 2. e# ::- Reduce each pair of characters to their difference. e# Yf# Square each difference. e# :+ Add the results. e# e#… Comment. Does nothing. z e# Zip. This wraps the string on the stack in an array. {}~ e# Execute an empty block. ~ e# Unwrap the array. ~ e# Evaluate the string. ``` [Answer] # Haskell, ~~152827~~ ~~95742~~ ~~91196~~ ~~83921~~ ~~77447~~ 71742 ``` a=(.);_ZYXWVUTSRQPONMLKJIHGFEDCBA=("#Haskell, "++)`a`show`a`sum`a`fmap(^2)`a`(tail>>=zipWith(-))`a`fmap fromEnum`a`(""++) ``` Usage (note: `"` has to be escaped): ``` _ZYXWVUTSRQPONMLKJIHGFEDCBA "a=(.);_ZYXWVUTSRQPONMLKJIHGFEDCBA=(\"#Haskell, \"++)`a`show`a`sum`a`fmap(^2)`a`(tail>>=zipWith(-))`a`fmap fromEnum`a`(\"\"++)" "#Haskell, 71742" ``` I prepend the empty string `""` to the input string to help the Haskell interpreter figuring out the types. Without it type inference fails, the code is too polymorphic. The rest is business as usual: map each character to ascii, make a list of neighbor differences, square, sum and prepend language name. [Answer] ## ><>, 30227 ``` 0&ii:0(?v:@-:*&+&20. '#><>, '<;n&oooooo ``` Gah, the title doubled my score; in the words of my own program, n&oooooo! I'll take some time later to make this better. I also know that this score may be off since I can't really enter newlines on the online interpreter and I'm not sure there's a way to populate an input stack on the official one. By no means completely optimized, but takes ~~full~~ some advantage of the relative proximity (at least in terms of ASCII characters) of the commands in ><>. I couldn't easily submit the newline as input, so I used the Pyth score checker, but it matches for a bunch of random test cases I used so it should be fine with regards to that. Here's one with a score of 30353 (which ought to be correct since it's one line): ``` 0&l1=66+*77++0.$:@-:*&+&10.' ,><>#'oooooo&n; ``` [Answer] # Java, ~~66465~~ ~~65506~~ 62434 Surprisingly short. Accepts a char array instead of a string. ``` ABCD->{int A98=0,GFEDCBA=1,A987;for(;GFEDCBA<ABCD.length;A98=A98+(A987=ABCD[GFEDCBA]-ABCD[GFEDCBA++-1])*A987-0);return"#Java, "+A98;} ``` I used a program to generate the best variable names. [Answer] # K5, 25478 ``` "#K5, ",$+/1_{x*x}'-': ``` Pretty simple solution. This is a function that takes its input via a string. [Answer] # Windows PowerShell ISE Host, 62978 ~~63894~~ ~~67960~~ ~~77050~~ ``` PARAM($4)($4.LENGTH-2)..0|foreach{$9=+$4[$_]-$4[$_+1];$0+=$9*$9};'#'+$HOST.NAME+', '+$0 ``` Edit -- saved some points by getting rid of the `$A` variable and instead counting backwards through the string, and also by converting some keywords to CAPS Edit2 -- saved some more points by using `$($HOST.NAME)` instead of `PowerShell` Edit3 -- saved some more points by swapping variable names and changed how the output is generated. Uses variables named with numbers, as they're "closer" to `$` so our penalty is less. It's interesting to *not* use regular golfing techniques. For example, `|%{$` is 22534, while `|foreach{$` is only 8718. This is probably close to optimal without changing techniques. [Answer] # MATLAB, ~~19214~~ ~~39748~~ ~~39444~~ ~~38785~~ 37593 ``` @(A9876543210)sprintf('#MATLAB, %d',diff(A9876543210)*diff(A9876543210')) ``` ## Thanks to Luis Mendo for reducing the difference count further! ## Thanks to NumberOne for reducing the noise count by changing the input variable name! ## How this works 1. Declares an anonymous function that is stored in the default `ans` variable in MATLAB 2. The function takes in a string stored in `A9876543210` and prints out the sum of squared neighbouring differences of the string. 3. `diff` finds pairwise neighbouring differences in an array and produces an array of `length(A9876543210)-1`. By using `diff` on a string array, this gets cast to a `double` array where the ASCII codes of each character are generated and the differences of the consecutive pairs results in another array. 4. To find the sum of squared differences, you simply take the dot product of this difference array with itself transposed. Doing `diff(A9876543210)'` actually produced more noise than with `A9876543210.'` (thanks Luis Mendo!) 5. The result is printed to the screen. [Answer] # QBasic, 38140 YAY FOR SHOUTY SYNTAX ``` LINE INPUT A9876543210$:AAA=ASC(A9876543210$):WHILE A<LEN(A9876543210$):AA9876543210=AAA:A=1+A:AAA=ASC(MID$(A9876543210$,A)):A98765432100=A98765432100+(AA9876543210-AAA)*(AA9876543210-AAA):WEND:?"QBasic,";A98765432100 ``` (Tested with [QB64](http://qb64.net).) This is a full program that inputs the string and outputs the answer. The only limitation here is that the program can't take multiline input (`LINE INPUT` can handle anything as long as it's a single line). **Deobfuscated:** ``` LINE INPUT line$ b=ASC(line$) WHILE i<LEN(line$) a=b i=i+1 b=ASC(MID$(line$,i)) score=score+(a-b)*(a-b) WEND PRINT "#QBasic,"; score ``` Conveniently, passing a multi-character string to `ASC` gives the ASCII value of the first character. Also conveniently, numeric variables are auto-initialized to zero. [Answer] # Python 2, 91026 ``` lambda A:"#Python 2, "+`sum((ord(A9876543210)-ord(A98765432100))**2for A9876543210,A98765432100 in zip(A,A[1:]))` ``` Defines an anonymous function that takes a string and returns the score. [Try it online](http://ideone.com/H2loUQ). Most of this is a pretty straightforward functional implementation: zip `A` with `A[1:]` to get a list of letter pairs, then subtract their `ord`s, square, and sum with a generator expression. Observe that the two variables inside the generator expression are only ever followed by the following characters: `)`, `,`, and space. All three of these have very low ASCII values, so it behooves us to end each variable with as low-ASCII-valued a character as possible. The lowest character that can end a variable in Python is `0`. Furthermore, every opportunity we have to split a single large jump into two smaller jumps will lower the score: `A0` costs 289, but `A90` is only 145 and `A9876543210` is a paltry 73. (This approach *didn't* help the lambda variable `A`, probably because it's followed by `[` in one occurrence.) [Answer] # JSFuck, 144420642 Build it from: ``` t=arguments[0];n=0;for(u=1;u<t.length;++u)n+=(f=t.charCodeAt(u)-t.charCodeAt(u-1))*f;return'#JSFuck, '+n ``` Paste this into [JSFuck.com](http://www.jsfuck.com/)'s small input box to compile it to JSFuck. The result is a 112701 characters long script, so I can't put it here. The last two characters of this script are parentheses, put the input between them. ``` ...)[+!+[]])('abd') ``` It takes the program almost 20 seconds on my computer to evaluate itself. --- ### Explanation I got more time to work on this, so I sat down and tried to optimize the variable names. Here are the variable names worth using, in order of their score. ``` u ([][[]]+[])[+[]] 17237 n ([][[]]+[])[+!+[]] 17437 f (![]+[])[+[]] 18041 t (!![]+[])[+[]] 18041 a (![]+[])[+!+[]] 18241 r (!![]+[])[+!+[]] 18241 d ([][[]]+[])[!+[]+!+[]] 23405 N (+[![]]+[])[+[]] 23669 e (!![]+[])[!+[]+!+[]+!+[]] 29217 i ([![]]+[][[]])[+!+[]+[+[]]] 33581 l (![]+[])[!+[]+!+[]] 24209 s (![]+[])[!+[]+!+[]+!+[]] 29217 uu ([][[]]+[])[+[]]+([][[]]+[])[+[]] 36983 ``` Here is the JavaScript I've translated to JSFuck: ``` score = 0; for (u = 1; u < input.length; ++u) score += (difference = input.charCodeAt(u) - input.charCodeAt(u-1)) * difference; return '#JSFuck, ' + score; ``` I gave a closer look at JSFuck.com's translator and figured out how its evaluation function works. With "Eval source" checked, the code will become a self-executing JSFuck function. To get the input, however, we need to access arguments[0] from within the function. This brings our final JS code to... ``` t=arguments[0];n=0;for(u=1;u<t.length;++u)n+=(f=t.charCodeAt(u)-t.charCodeAt(u-1))*f;return'#JSFuck, '+n ``` (If you're wondering why my previous version had a lower score than this, it's because it was a JSFuck program that returned a string that needed to be evaluated as JS. This is also why I didn't leave it in the post) [Answer] # CJam, ~~23663~~ ~~19389~~ 11547 ``` "#CJam,"32A;clYew[]ULC;;;;::- 0$.*:+ ``` [Try it online](http://cjam.aditsu.net/#code=%22%23CJam%2C%2232A%3BclYew%5B%5DULC%3B%3B%3B%3B%3A%3A-%200%24.*%3A%2B&input=%22%23CJam%2C%2232A%3BclYew%5B%5DULC%3B%3B%3B%3B%3A%3A-%200%24.*%3A%2B) It's starting to feel like this can be pushed almost endlessly by strategically adding more characters. But I think that I'm starting to reach a point of diminishing returns here, so I'll stop for now. For example, where I have `ULC;;;`, I could use the whole alphabet backwards followed by 26 `;`, but the gains get smaller and smaller. By far the biggest gap I have left is between the `m` and the `,` in the initial string. I haven't found anything reasonable to get rid of it. I'm sure there are ways. But if I push it to the limit, it might start looking like Dennis' solution... [Answer] # JAVASCRIPT, 33911 ``` $0123456789ABCDEFGHIJKLMNOPQRS=>/**/('#')+('JAVASCRIPT,')+(" ")+(($)/**/=0,($0123456789ABCDEFGHIJKLMNOPQRS[`split`]``[`map`]/**/(($$,$$$)/**/=>/**/($)/**/=Math[`pow`]/**/($0123456789ABCDEFGHIJKLMNOPQRS[T=`charCodeAt`]/**/($$$)+-($0123456789ABCDEFGHIJKLMNOPQRS[T]/**/(($$$)/**/>=6-5?/**/($$$)+-1:0.)),2)+($))),($)) ``` This is by far one of the silliest optimizations I have ever done in a code golf... Props to Neil for the "comment spam" suggestion =P [Answer] # JAVASCRIPT, 31520 This solution was ~~significantly more ridiculous~~ very different from my other one, and so I felt it deserved it's own answer. ``` A=>/**/(($)/**/=/**/(''),('000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000100000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000100000000000000000000000000000000000000001000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000100000000000000000000000000000000000000001000000000000000000000000000000000000000010000000000000000000000000000000000000000000100000000000000000000000000000000000000100000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000000000000100000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000010/-,+*)(')/**/[`split`]``[`reduce`]/**/(($$,$$$,$$$$)/**/=>/**/($$$)/**/>7.-07?/**/(($)+=/**/((/**/String[`fromCharCode`]/**/)(($$$$)+-($$))),($$$$))/**/:/**/($$)),/**/eval/**/($)) ``` That's 7306 characters, most of which is the actual program encoded into that 0/1 string, and the rest simply to decode it. It works by getting the index of each '1' minus the index of the previous '1' to get the necessary character value. It then eval's the resulting string into the actual function, which is essentially a standard-golf program to solve the problem (which is only about 105 characters itself). [Answer] # R, ~~68911~~ ~~57183~~ ~~53816~~ 52224 Takes a string from STDIN and converts it to an integer via raw. Diffs, squares and sums the resulting vector. The result is returned as a string. Thanks to @nimi for the variable name tip. ``` '&&'=sum;'&&&'=diff;'&&&&'=as.integer;'&&&&&'=charToRaw;'&&&&&&'=readline;'&&&&&&&'=paste;'&&&&&&&'('#R,','&&'((A='&&&'('&&&&'('&&&&&'('&&&&&&'()))))*A)) ``` [Answer] # Mathematica, 33552 ``` A=ToExpression;A@ExportString[A@Characters@(**)"001000100010001101001101011000010111010001101000011001010110110101100001011101000110100101100011011000010010110000100000001000100011110000111110010101000110111101010011011101000111001001101001011011100110011101011011001000110010111000100011001001100100000001000100011010010110011001100110011001010111001001100101011011100110001101100101011100110100000001010100011011110100001101101000011000010111001001100001011000110111010001100101011100100100001101101111011001000110010101000000001000110101110100100110"(**),(**)"Bit"(**)] ``` This code evaluates to an unnamed function, which calculates the "noise" of an input string. It makes use of the fact that the ASCII representation of binary data is essentially "noiseless". The binary data you see is the string ``` "#Mathematica, "<>ToString[#.#&@Differences@ToCharacterCode@#]& ``` which would have been a valid answer on its own, scoring 37848. Everything else ``` A=ToExpression;A@ExportString[A@Characters@(**)"001..110"(**),(**)"Bit"(**)] ``` just decodes the binary string and interprets it as Mathematica code. Note that Mathematica's empty comment `(**)` is very "low-noise" and actually removes noise from the `"`s. [Answer] # Java8 : ~~117170~~ ~~100508~~ ~~99062~~ 98890 With the help of lambada expression and inline assignment of variable can shorten this code a bit. ``` A->{int B=0,D=0,E=0;char[] C=A.toCharArray();for(;D<C.length-1;)B+=(E=C[D]-C[++D])*E;return"#java, "+B;} ``` [Answer] # Java, ~~129300~~ ~~128400~~ ~~110930~~ ~~106581~~ 105101 ``` B->{int A=0,C=A;char[]Z=B.toCharArray();for(;++C<Z.length;A=A+(Z[C]-Z[C-1])*(Z[C]-Z[C-1]));return\"#Java, \"+A;} ``` This challenge actually got me thinking deeper about characters to use and optimization more so than finding the shortest solution. I'll keep working to bring the number down. This is a lambda function, with `B` being the string representing the function. Don't forget to escape the quotes (`"`) when passing this as a string. [Answer] # Pyth, 16391 ``` ++C38828542027820dsm^-ChdCed2,Vztz ``` The only trick of note used here is base-256 encoding `#Pyth,`, which costs far less than the string itself. ``` ++C38828542027820dsm^-ChdCed2,Vztz Implicit: d=' ', z=input() ,Vztz Pair each char in the input with its neighbour m Map d in the above to: Chd ASCII code of 1st char Ced ASCII code of 2nd char - Difference between the two ^ 2 Squared s Take the sum C38828542027820 '#Pyth,' ++ d '#Pyth,' + ' ' + result, implicit print ``` [Answer] # M, 47033 ~~52798~~ ``` A9876543210(A9876543210) F AA9876543210=2:1:$L(A9876543210) S AAA9876543210=$A($E(A9876543210,AA9876543210-1))-$A($E(A9876543210,AA9876543210))**2+AAA9876543210 Q "#M, "_AAA9876543210 ``` To use this, we have to escape quotes and "escape" whitespace characters (which are significant in MUMPS!) like so: ``` >$$A9876543210^MYROUTINE("A9876543210(A9876543210)"_$C(9)_"F AA9876543210=2:1:$L(A9876543210) S AAA9876543210=$A($E(A9876543210,AA9876543210-1))-$A($E(A9876543210,AA9876543210))**2+AAA9876543210"_$C(10,9)_"Q ""#M, ""_AAA9876543210") #M, 47033 ``` Note that "M" is an alternative name for "MUMPS" - there is disagreement among practitioners about which one is correct. Naturally, I have chosen the shorter option here. [Answer] # Ruby, 118402 ``` puts "#Ruby, #{a=0;aa=nil;File.read(ARGV[0]).each_byte{|aaa| aa||=aaa;a+=(aaa-aa)**2;aa=aaa};a}" ``` It reads in a file through command line, such as `ruby diff.rb /path/to/file`. There's room to improve, and that's something I'm working on right now. [Answer] # C++ 166345 ``` void n(){int b=0,c,d;string a;cin >>a;for(c=1;c<a.length();++c){d=(a[c]-a[c-1]);b+=d*d;}cout<<"#C++, "<<b;} ``` [Answer] # Perl, 93556 ``` chomp($A=<>);$AAA=$AAAA=0;foreach$AAAAA(split'',$A){$AA=ord($AAAAA);$AAA+=($AAAA-$AA)**2 if($AAAA!=0);$AAAA=$AA}print'#Perl, '.$AAA ``` I'll try to cut this down some more. It turns out that curly braces (`{` and `}`, ASCII 123 and 125) and the underscore (`_`, ASCII 95) are very expensive since all the other characters are around the range 30-70, which is why I formatted the `if` the way I did, and why I'm using `$AAAAA` instead of Perl's beloved `$_`. Sadly, all the variables with symbols in them are read-only, so I can't take advantage of combinations like `$#` and `$$`. [Answer] # F#, ~~136718~~ 130303 ``` let(A)=Seq.map; (stdout.Write(Seq.sum(A(fun(AA)->AA*AA)(A((<||)(-))(((Seq.pairwise(A(int)(stdin.ReadToEnd()))))))))) ``` Where there is a `\n` after the `;`. [Answer] # POSIX Shell, 172026 ``` { while IFS= read -N 1 A; do A1=$(printf %d \'"$A");test "$A1" -eq 0 && break;case $A11 in "")A111=0;;*)A111=$((A1-A11));;esac;A11="$A1";A1111=$((A111**2+A1111));done;echo "# POSIX Shell, $A1111";} ``` too bad I can't get the same result as the Pyth checker (178386)... [Answer] # Lua, ~~171078~~ 117896 Golfed: ``` A=string AA=A.sub AAA=io.read()AAAA=#AAA AAA=AAA..AA(AAA,AAAA,AAAA)AAAAA=0 AAAAAA=A.byte for AAAAAAA=1,AAAA do AAAAAAAA=AAAAAA(AA(AAA,AAAAAAA,AAAAAAA))-AAAAAA(AA(AAA,AAAAAAA+1,AAAAAAA+1))AAAAA=AAAAA+AAAAAAAA*AAAAAAAA end print(AAAAA) ``` Ungolfed: ``` A=string AA=A.sub AAA=io.read() AAAA=#AAA AAA=AAA..AA(AAA,AAAA,AAAA) AAAAA=0 AAAAAA=A.byte for AAAAAAA=1,AAAA do AAAAAAAA=AAAAAA(AA(AAA,AAAAAAA,AAAAAAA))-AAAAAA(AA(AAA,AAAAAAA+1,AAAAAAA+1)) AAAAA=AAAAA+AAAAAAAA*AAAAAAAA end print(AAAAA) ``` [Answer] # C++, 49031 a C++ macro that takes a c-string and writes the result to the standard output ``` <::>(auto(A))<%long(AAA)=0,AA=A<:0:>;while(*++A)<%AAA+=(*A-AA)*(*A-AA);AA=A<:0:>;%>cout<<"#C++, "<<AAA;%> ``` [Try it online!](https://tio.run/##vZBRasMwDIafm1OIlIIdN7R7GiROwOwG2wk0x0kMjh1shT6MXr2ZNwa9wZ4E0iek/9PrWmuHftqP1mu3DQakDYmiwaUvtmT9BB4Xk1bUBhINbVHo4BOBnjFWsMYwfVD8wTp4L5lsmp7hRoEpzuXJBT8xpRTvrmelOiWba9O3t9k6wyohVEbyVHSsUnWmqr/aPtlTr8NGUpbHNyHOUEqZF3K35WV@xXqCBa1n/Gv/t9P7gT1j8/ZwuWh0DhwunwPCzdKcRf0qiWaNJhlPSDZ4CCNYSsaNxb3YH3p0OKW9zlI7LcTL6zc "C++ (clang) – Try It Online") ]
[Question] [ Each day you put up a new word on a [marquee sign with movable letters](https://i0.wp.com/thecachevenue.com/wp-content/uploads/2017/10/marquee_sign_1.jpg?fit=800%2C800&ssl=1), buying just the letters you need to write it. You re-use letters you've bought for earlier words whenever possible. Given the words you want to write each day in order, output the letters you buy each day. > > **Example** > > > > ``` > Input: ['ONE', 'TWO', 'THREE', 'SEVENTEEN'] > Output: ['ENO', 'TW', 'EHR', 'EENSV'] > > ``` > > **Day 1:** You start with no letters, so to write `ONE`, you buy all its > letters `E`, `N`, `O`. > > **Day 2:** The next day, you want to put up `TWO` > (taking down the `ONE`). You already have an `O` from `ONE`, so you > buy an additional `TW`. > > **Day 3:** At this point, you have `ENOWT`. To write > `THREE`, you need `EHR`. Note that you need to buy a second `E` in > addition to the one you have. > > **Day 4:** To write `SEVENTEEN`, you need 4 > `E`'s total of which you already have two (not three!), so you buy two more. > You also have the `T` and one of the `N`'s, so you buy the remaining letters: > `EENSV`. > > > We've output letters sorted alphabetically in this example, but you may > output them in any order. > > > **Input:** A non-empty list of non-empty strings of letters `A-Z`. You may use lowercase if you prefer. Lists of characters are fine for strings. **Output:** Output or print the additional letters you need to buy each day. The letters for a day may be output in any order, but the days must come in the right order. The letters from each day should be separated from other days so you can tell where a day ends. A trailing and/or leading separator is fine, both within a day or between days. Note that a day may have no letters bought, which should be reflected in the output (a space or empty line is OK, even for the last day). **Test cases** ``` ['ONE', 'TWO', 'THREE', 'SEVENTEEN'] ['ENO', 'TW', 'EHR', 'EENSV'] ['ONE', 'TWO', 'ONE', 'THREE'] ['ENO', 'TW', '', 'EHR'] ['ABC', 'AABC', 'ABBC', 'ABCC', 'AABBCC'] ['ABC', 'A', 'B', 'C', ''] ['SHORT', 'LOONG', 'LOOOONG', 'LOOOOOOONG', 'SHORT', 'LOOONG'] ['HORST', 'GLNO', 'OO', 'OOO', '', ''] ``` Here are all the inputs and outputs as separate lists: ``` [['ONE', 'TWO', 'THREE', 'SEVENTEEN'], ['ONE', 'TWO', 'ONE', 'THREE'], ['ABC', 'AABC', 'ABBC', 'ABCC', 'AABBCC'], ['SHORT', 'LOONG', 'LOOOONG', 'LOOOOOOONG', 'SHORT', 'LOOONG']] [['ENO', 'TW', 'EHR', 'EENSV'], ['ENO', 'TW', '', 'EHR'], ['ABC', 'A', 'B', 'C', ''], ['HORST', 'GLNO', 'OO', 'OOO', '', '']] ``` And as space-separated strings (the trailing spaces in the outputs matter): ``` ONE TWO THREE SEVENTEEN ONE TWO ONE THREE ABC AABC ABBC ABCC AABBCC SHORT LOONG LOOOONG LOOOOOOONG SHORT LOOONG ENO TW EHR EENSV ENO TW EHR ABC A B C HORST GLNO OO OOO ``` **Leaderboards** ``` var QUESTION_ID=183544,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Haskell, ~~54~~ 49 bytes ``` import Data.List g x=zipWith(\\)x$scanl(++)""$g x ``` [Try it online!](https://tio.run/##bYqxCoMwGIR3n@InOCiKb@CgNtTBJqBSB5USStFQtUEzSF8@bcSUFjrd3Xdfz5b7bRiU4qN4zBIOTLIg44u0OljDJxcVl73TNO5qL1c2DY7nuQjZ71ONjE8QwsjE6QKOmPkkIYDOhdoCqBElGPmAyopukeZ42wU@Y1JiTFDr//HM2vTdiOJEs8hkbDIxXLddLlKalxpnlJLjXn7qZ32rGrWtegE "Haskell – Try It Online") We build the output list by calculating pairwise the list difference (`\\`) of the input list and the cumulative append of the output list (starting with `""`). ``` input list: ONE TWO THREE SEVENTEEN cumulative append: "" +-> ONE +-> ONETW +-> ONETWHRE list difference (output): ONE -+ TW -+ HRE -+ SVEEN ``` With both `Data.List` and `Data.Function` in scope (e.g. by using the lambdabot environment), this can be shortened to 30 bytes: ``` fix.(.scanl(++)"").zipWith(\\) ``` Edit: -5 bytes thanks to @Sriotchilism O'Zaic. [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ 68 bytes -4 bytes thanks to Jonathan Allan. ``` p='' for r in input(): for x in p:r=r.replace(x,'',1) print r;p+=r ``` [Try it online!](https://tio.run/##XY7BasJAEIbv@xRDLqM0EerRkkMMox7KLpilLRQPNt1iUJJlWDE@fZpJTWmFhf@fb78d1l/DoannXdl8OkiBoyjqfIqovhoGhqrujz@HyXShQFAryC845Rk7f9qXbtLGiPHjVIHnqg7AT/4h5a5fpNTlUJ0cWD67/jkEvkrATcQkSUDTmwVLhc2zgqAnOBiudSXIn5T00vkAZFbE3PDPig92@2P3jkYTxoD21Qyx2dIwF/RC2hJp3Kl7aZwGV66zZS4gG3M5Zj5yaWIWG7O1wp6N0etb@Vd/p7@qoN03 "Python 2 – Try It Online") ## Commented ``` l=input() # the list of words to write p='' # p contains all letters we own for r in l: # for each word ... for x in p: # for each letter we own ... r=r.replace(x,'',1) # remove one occurence from the current word print r # print the remaining word p+=r # add the remaining chars to p ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ,œ-@Kɗ/ ``` [Try it online!](https://tio.run/##y0rNyan8/1/n6GRdB@@T0/X///8frR7s4R8Uoq6joO7j7@/nDmWgMOE8ZKUgoVgA "Jelly – Try It Online") Output: -separated string. [Answer] # [Haskell](https://www.haskell.org/), 44 bytes ``` import Data.List foldl1(\a x->a++',':(x\\a)) ``` [Try it online!](https://tio.run/##RYnNCoJAFEb3PcVFAhVNaBsYqA25sBnQoRYZccEkyT90It9@ciawzTn3u@eJ4@tR11JWTd8NAg4o0EuqUaxKv@zqot5aOcK02aPjmK65s6Y8R9uWDVYt@NBgf7qD1b9FJoak9Urv0w3FaMMargajBPiFAY9TQiAjZ0I5IdRwYUnaKqtnEEYQaIQakZ6zVMxilnJIGKNHxb9/55LnYdzkFw "Haskell – Try It Online") Output is a string like `ONE,TW,HRE,SVEEN` with commas between days. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` a=>a.map(h=>([...t].map(c=>h=h.replace(c,'')),t+=h,h),t='') ``` [Try it online!](https://tio.run/##fYzRCoIwGIXve4ruNmntDSaojLyIDVTqQrwYa7bCnKj0@suNFgXS1Xe@n3P@u3iKSY63Yd735qJsS6wgscAPMUBNYlhjjOfGqySxJhqPauiEVFAiAKIIzTuikV5IFrXS9JPpFO7MFbawBpxRgLagOnOPvKDeS3qirKKUgSaKNv9Hwfx2rZ6kmSskgWlgFu4urS3LnBeV6xw5Z4d3@Ikf@6660/LOvgA "JavaScript (Node.js) – Try It Online") Quite straightforward solution. For each word `h`, remove letters we already have. Here is an explained version of that code: ``` f = list => { // the string that accumulates all the letters already bought let accu = ''; // for every word in the list return list.map( word => { // for every letter already bought [...accu] // remove the letter from the word .map(char => { return word = word.replace(char,'') }); // add not bought letters to accumulator accu += word; // the reduced word (without already bought letters) should be added to result map // this represents the letters to buy today return word }, accu) } console.log(f(['ONE', 'TWO', 'THREE', 'SEVENTEEN'])) console.log(f(['ONE', 'TWO', 'ONE', 'THREE'])) console.log(f(['ABC', 'AABC', 'ABBC', 'ABCC', 'AABBCC'])) console.log(f(['SHORT', 'LOONG', 'LOOOONG', 'LOOOOOOONG', 'SHORT', 'LOOONG'])) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~44~~ 40 bytes *-4 bytes thanks to Matthew Jensen* ``` {$!=@;.map:{kxxv $!=.comb∖($⊎=$!):}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@79aRdHWwVovN7HAqjq7oqJMAcjXS87PTXrUMU1D5VFXn62KoqZVbe1/a67ixEqFNIVodX8/V3UdBfWQcH8w5RHkCuYHu4a5@oW4uvqpx@JSC@OBtSCpcnRyBok7wmgnGO0MEwexkDQEe/j7B4WA5Hz8/f3coQwUJpwHVAtXChKKtf4PAA "Perl 6 – Try It Online") Outputs as a list of lists of characters. ### Explanation ``` { } # Anonymous codeblock $!=@; # Initialise $! to an empty list .map:{ } # Map each item in the input to .comb # The string split to characters # In a Bag ∖ # Set minus ($⊎=$!) # The accumulated Bag of results $!= # And save the result for the next item kxxv : # Then decompose the Bag into a list ``` [Answer] # [J](http://jsoftware.com/), 29 bytes *-29 bytes thanks to FrownyFrog!* ``` (],a.<@#~0>.-&(1#.a.=/;))/@|. ``` [Try it online!](https://tio.run/##bY9Ba4NAEIXv/opHA65CsiZXTUKibJNDUFBpT6XYzQRtU211Q3Mo@et23UIDobDzZubNfAz72t9xdsDCB8MYU/g6JhxRurvvnadxweer0WW65BPbmY14wRde4Lre6pv3rmXFIccXoWtahZdGlVAlgc4fJBXtUdQ6pDoVR7TUnY6qgyGquqv2NOxWrcbO1I3RVbUkNO2eWlRdzRQKDX2eqpbeqVaWJUuSbwsOZ@LbvuP5Fypk6eLg2s484M8z1156lkWybGBW9XdEnCB/hNimECLOHljAkMRCe9rfpkIgEw8izvWQ/UsOKAtwpUweyJv9dRhhjRARhhumMxIaiUyr0w21TdIsx2anjyXDS2DwTPs5dkkSbwa95t/yb6wb1v8A "J – Try It Online") # Original Post ## [J](http://jsoftware.com/), 58 bytes ``` [:}.@>[:(],<@(/:~@({.@>@-.&(((e.<@#[){:)\));))&.>/<@a:,~|. ``` [Try it online!](https://tio.run/##bU1fa4MwHHz3UxwbmAQ0bq/RSqpk9UESUGkfbBlDLGV72Afon6/ufslghTJI7nJ3Oe5zeZLsiJUCQ4IXKLqpRN21b8uorlKXo@KHpNA8UzfNz2ToVMac81kW@nkUZyX2QuRCxLLMCv2hkttFLiKKptM8fa0keKpwFDEvcvn@KuIyi6J5On0j5LRqrMOwg2k6GGP7LcsZnDXkkd90xqA3W2MHCtm/TV9lOe6twL758H9d1VijQg2/EVSAKkAdJNFDq3FdP2DT0pjzxyHUe/IHtM7Zjcc7/z7/YhJs@QE "J – Try It Online") *Thanks to ngn for help improving the "subtract letters while respecting repetition part".* Not a great fit for J, but an illuminating exercise. Let's begin by constructing a helper verb `wo` ("without") that removes all chacters in one string from another, while respecting repetitions. ``` wo=.{.@>@-.&(((e. <@# [) {:)\) ``` There is a fun idea here: We make each repeated instance of a character unique, by repeating it the required number of times. Thus if our original string is `ABBA` it becomes: ``` ┌─┬─┬──┬──┐ │A│B│BB│AA│ └─┴─┴──┴──┘ ``` A third `A` would become `AAA` and so on. This is accomplished by the phrase `((e. <@# [) {:)\`, which takes each prefix `\`, looks at the final element `{:` of it, and constructs a mask of all elements in that prefix that match `e.` that final element, and then filters and boxes just those elements `<@#`. With our inputs both "unique-ified" we can now safely use normal set minus `-.` while still respecting repetition. We then open each result and take only the first element to "undo" our repetitions: `{.@>` Plugging this helper verb in, our overall solution (which simply inlines it) becomes: ``` [: }.@> [: (] , <@(/:~@wo ;))&.>/ <@a: ,~ |. ``` Essentially, all we do here is setup our problem as a single reduction. We start be reversing the input `|.` and appending to it `,~` an ace `a:`, or empty box, which will be the initial value of our final result, like so: ``` ┌─────────┬─────┬───┬───┬──┐ │SEVENTEEN│THREE│TWO│ONE│┌┐│ │ │ │ │ ││││ │ │ │ │ │└┘│ └─────────┴─────┴───┴───┴──┘ ``` We stick the following verb between each element to effect the reduction: ``` (] , <@(/:~@wo ;))/ ``` This says: take the right input `]` (ie, our result) and append to it `,` the left input (this is `ONE` on the first iteration, `TWO` on the 2nd, etc) without `wo` the raze of `;` the right input (ie, without any previous letters so far used), but before appending sort it `/:~` and box it again `<@`. At the end of all this we'll have the result we want, a list of boxes, but all inside one big additional box, and still with the empty box at the front. Thus we open to remove the outer box and kill the first element: `}.@>`. [Answer] # JavaScript (ES6), ~~66~~ 65 bytes ``` a=>a.map(b=s=>[...s].filter(c=>x==(x=x.replace(c))?b+=c:0,x=b+0)) ``` [Try it online!](https://tio.run/##fYxNC4IwHMbvfYpubljDc/A3VEYewoFKHcTDXDMMc@Ik/PbWJKNAOj0v/J7nxh9ci65q@22jLnIsYeTgcnLnLSpAg5sRQnROyqruZYcEuAMAGmAgnWxrLiQSGO8LG8TO2QxQ2A7Go1CNVrUktbqiEmUWi6i1WVvpmU0SxnTKCT3RKKU0snKMV/9Hc5q2S7jnBwbwZvVnDebeuKVlErI4NcyRsejwNj/2k75RU73uxic "JavaScript (Node.js) – Try It Online") ### Commented \$b\$ is a string holding all available letters (and also some invalid characters, but this is irrelevant to the algorithm). For each new word, we create a copy of \$b\$ in \$x\$. Each letter \$c\$ of a word is either *used* by removing it from \$x\$ or *bought* by appending it to \$b\$. Only bought letters are returned. ``` a => // a[] = input a.map(b = // initialize b to the callback function of this map() // it will be coerced to a string that does not contain // any letter in uppercase s => // for each entry s in a[]: [...s].filter(c => // for each character c in s: x == ( // check whether x is changed when x = x.replace(c) // c is replaced with 'undefined' ) ? // if so: b += c // append c to b and keep c : // else: 0, // discard c x = b + 0 // coerce b to a string and save it in x ) // end of filter() ) // end of map() ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~177~~ 170 bytes -5 bytes thanks to @anatolyg's tip, -2 bytes to small things I noticed. ``` #import<random> #define v std::vector<std::string> v a(v p){std::vector<int>o(91),b;int j=-1;for(auto i:p){b=o;p[++j]="";for(int c:i)--b[c]<0?p[j]+=c,++o[c]:0;}return p;} ``` Explanation `#import<random>` adds both `<string>` and `<vector>` for half the bytes. First creates a 91-element vector of 0s (only indices 65-90 are used to store letter occurences), and another vector of the same type but not set to a value. Iterates through each element of the input (the days): gets the currently owned letters, gets the letters that are needed for the day, overrides the input at the index with the needed amount and updates the owned letters. Returns the overridden input. [Try it online!](https://tio.run/##XZAxb8IwEIVn8itOZkkUR4KxdkLVIVInkAqCATEY2yAjsC3jRK1Qfjs93A6lk@987z1/Z@l9dZTyfh@bi3ch1kFY5S6zbKz0wVgNPVyjYqzXMrpQp/oag7HHWdaDyHvwxe2vwtg4c/nLtKB7jjWcmmrKDy7koosODEP5vnHcb8vytGsISbOHUDJTVNV@K3f15NVvT7uykbQsHV6wCR@Cjl2w4PmAqFaeO6WhNg5ZtEDc7BFxEcbmBdyyUQ8RGriRxbwlFMhqs0jH@0eb@mW7buertp2TgWejhC9dF6GugbzJ2IkzAwCCM6SDH3QlvhguHIv0wLMJZ8lLk2f4F5kabdU5adpPjz@lFQOEo7DaUEAsCss18lDyZMCw370nPBvu3w "C++ (gcc) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 123 bytes ``` a=>{var b="";for(dynamic i=0,e,f;i<a.Count;b+=a[i++]=f)foreach(var c in((e,f)=(b.ToList(),"")).f+a[i])f+=e.Remove(c)?"":c;} ``` [Try it online!](https://tio.run/##bZBBa4QwEIXv/grJKUErPTfG4kroFkSLK93D4iGmSZvDRtB0SxF/u01Wy0rpJfPeyzcJM3y444OaU25Up@PnXA0mHkyv9HuSSDIzkowX1vstAQDLrodv35qdFfcVuQ9FKLGKWZR1n9rgNiDspIKgIRJZUjD@AV2rZTWElkUEtlHduS8gCgFAKJKBbWmQDIiIKnHuLgJy9AjAA8fTjD3XbsRgBp/4WnydGm/0/EWNoCwoCEF9LN25r6hzB/pKi5rSAkzh/@Sqr/yWSXeZzdO17NaSraETW/qwL6vaXuVlWTwtdat@zQZzgX1hwt52N244u55lSHSd7sXu3kAXIGytvMk/N8deGZErLaC10/wD "C# (Visual C# Interactive Compiler) – Try It Online") Anonymous function that outputs by modifying an input array. ``` // a: input array of strings a=>{ // b: cumulative letters var b=""; for( // i: loop index of string // e: copy of cumulative letters for manipulation // f: characters missing from current string dynamic i=0,e,f; // iterate over each string in a i<a.Count; // add missing letters of the day to // cumulative missing letters and // update array for output b+=a[i++]=f ) // iterate current string with character c foreach(var c in // tuplized variable assignment // e=b.ToList() // set e to a copy of the cumulative letters // f="" // initially there are no letters needed for the day ((e,f)= (b.ToList(),"")).f+a[i] ) // conditionally add c to missing letters for the day f+=e.Remove(c)?"":c; } ``` [Answer] # R, ~~119 112 106~~ 103 bytes -7 bytes from aliasing the two longer function names and now taking user input from `scan()` -6 bytes to only call `strsplit()` once at the beginning -3 bytes to get rid of the aliasing again and assign two variables in one call (Also edited the byte count which was erroneously low earlier) ``` a=scan(,'');b=a=strsplit(a,'');for(i in 2:length(a))b[[i]]=vecsets::vsetdiff(a[[i]],unlist(b[1:i-1]));b ``` This is my very first PPCG submission of any kind! So I have no idea what I'm doing both in terms of golfing and in terms of posting etiquette. The output is a list of vectors which may or may not meet the terms of the challenge. :-P As for the code itself, it takes user input via `scan()` and compares each new day's letters to the cumulatively owned letters, as in other solutions. If there are shorter alternatives to `unlist` and `strsplit` for converting strings into vectors of individual characters that would be cool to know. I also used the `vsetdiff` function in Carl Withoft's `vecsets` package to get the set difference of the letters needed for the next day and the current letters owned. [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ 100 bytes ``` from collections import* c=Counter l=c() for x in map(c,input()):y=x-l;l+=y;print list(y.elements()) ``` [Try it online!](https://tio.run/##XZC7asMwFIZ3PcXBi@3WydDRQUNiRDMYCxKTDMGDqyhUoBuyAvbTu5GIS9Ppv@jjHI7s5L@N/pgrc@U4SZL55owCZqTkzAujBxDKGuffEMOVuWvPHZKYZTm6GQcjCA2qtxkrhLZ3n@V5OeFxJTfyHU8b64T2IMXgs2nNJVdc@@HBzI9FKA6ow4DLJaUNSQtI2zONsj@QmI/kRJqWkCbtCvhPLSnC8X27q0KzXXS3aLX0wUX0uKeHNpQ1pc3n07zY3/QXDVXXlQjiuYBB9urr2pdQI@AjZxD@EUE8fP4B "Python 2 – Try It Online") -2 bytes, thanks to Embodiment of Ignorance [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 bytes ``` $args|%{$w=$_;$p|% t*y|%{$w=$w-replace"^(.*?)$_(.*)",'$1$2'};$w;$p+=$w} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RrVapdxWJd5apaBGVaFEqxIqUK5blFqQk5icqhSnoadlr6kSD6Q0lXTUVQxVjNRrrVXKgTq0gepq////r@7o5KwOJKGUE5RyhgqCGAA "PowerShell – Try It Online") Takes input words `$args` and iterates over them. Each iteration we set the current word `$w`, then loop over our `$p`ool of already-purchased letters. Each inner loop, we perform a regex `-replace` on our current `$w`ord, so that we're replacing just the first instance of the letter from our `$p`ool. Once we've gone through all letters in the pool, we output what's remaining `$w` (i.e., what we need to purchase), and then tack those letters onto our pool `$p+=$w` for the next word. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~15~~ 14 bytes ``` £Q®X=rZPPÃQ±XX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o1GuWD1yWlBQw1GxWFg&input=WyJPTkUiLCJUV08iLCJUSFJFRSIsIlNFVkVOVEVFTiJd) ``` £Q®X=rZPPÃQ±XX :Implicit input of array £ :Map each X Q® : Map each Z in Q (initially a quotation mark) X= : Reassign to X rZ : Replace Z with P : The empty string P : With the default global flag disabled à : End map Q±X : Append X to Q X : Return X ``` [Answer] # [Red](http://www.red-lang.org), 75 bytes ``` func[b][a: copy""foreach w b[foreach c a[replace w c""]print w append a w]] ``` [Try it online!](https://tio.run/##ZYvBDoIwEETvfMVm7/wANyCNHEybANFDs4dS2mhioGk0xK@vVKtRuey8mZ3xZgytGSVltgj2Nmk5kFQF6NndEe3sjdInWGCQb9agpDfuorRZc41Izp@n68rKOTONoGAhChYkCs4QsD@KeJuWRdexA@M9YxwJXkPM8xyz/37i52rbLKt6/ZZJqiR1CiNsN10j2h4BcC8E3yX4wY/7rsaIwgM "Red – Try It Online") [Answer] # Excel VBA, 127 bytes ``` Function z(w) z="" For Each x In w.Cells v=x.value For y=1To Len(z) v=Replace(v,Mid(z,y,1),"",1,1) Next z=z&v Next End Function ``` Takes input in the form of an excel range. [Answer] # [C (gcc)](https://gcc.gnu.org/), 118 bytes ``` m(a,r,q,u)char**a,*r,*q,*u;{for(;*a;a++,memcpy(r,q,255))for(memcpy(q,r,255),u=*a;*u;u++)*u=r[*u]-->0?32:(q[*u]++,*u);} ``` [Try it online!](https://tio.run/##VY9Bb8IwDIXv@xU@Jo4rAROXRWWnSJyKtFXboeohRMA4FGggSFPV357ZFRJaTvb3np@dUBxCyLlTniL1lHT48RHRE0bCnjDZYX@OyqK33hjqdl24/CqxLpZLrUV7sJ4DhFEq2cyDyRiNqYwNprYoVrP318Wb6qXjIEzajvl4ukHnjyclhY@HQCD7Abm@N62G4QX4TWzbcHoLJQyz0T5x@Icnzp/hcTMn2HKeflA@FUQI7J1bmDZI21owRgoNl3S7qqfAk2POm8rl@nuT6/WHc/nTfbmqdq76Aw "C (gcc) – Try It Online") As a little bonus it takes the stock in `r` at the start as an array. Outputs the input null-terminated null-terminated-string list `a` with all pre-owned letters replaced with spaces. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes *-6 thanks to Kevin Cruijssen* ``` ćsvDysSõ.;» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SHtxmUtlcfDhrXrWh3b//x@tFOzhHxSipKOg5OPv7@cOZaAw4TxkpSChWAA "05AB1E – Try It Online") [Answer] # [Swift 4.2/Xcode 10.2](https://developer.apple.com/swift/), ~~244~~ ~~242~~ ~~239~~ 238 bytes ``` a.reduce(([Character:Int](),[String]())){c,l in let b=l.reduce(into:[Character:Int]()){$0[$1,default:0]+=1}.map{($0,max(0,$1-(c.0[$0] ?? 0)))};return(c.0.merging(b){$0+$1},c.1+[b.map{String(Array(repeating:$0.0,count:$0.1))}.joined()])}.1 ``` [Try it online!](https://tio.run/##fZBfb4IwFMXf/RQN4aGNlfDvicUZNWQuMZBMsz0QHioUx4LF1JJtIXx21@JwLopP99ybe@75tYfPPBPuMatYAkia5iIvGSmWVAjKDzArOSAeiFaC52wbIzB6PDegBpyKirMjMThNq4RCGM3fCSeJ9HrPTMQQ4W4bIoTqBBcgZ6CgAmzGRefKmSi9KyeqdTPSLZzSjFSF8Mx4OLYaY0f2NdRNvCNf0MS6NYKJIffMGEwmwJQhzcOJSs2NHeVbmQ436tpQtxqcGNYw2rRnTmRwyjn5hpzuKRGy93TTMHFSVkwoacmLxkeZM5pCFEttHZvBQL1A0IOwwBhEWhj4Ggba@i1sy@LFb/uV/@oHa98PtLg1XH2vct/8c@90HA32klDAayP6Q7BvIHRdS9ITbt8Pt3vD7Ytwpw2fzuYqbtrVWVfn3VypHg7nPofTy@FccLgtx2oRvqxV4jIMg6df8U@eu8tVNeqBc@/Dub1wLjr@AA "Swift 4 – Try It Online") The letters are not arranged in alphabetical order, it is not forbidden by the rules. [Answer] # Scala, 68 bytes ``` (c:Seq[String])=>c./:(Seq(""))((a,n)=>a:+n.diff(a./:("")(_+_))).tail ``` [Try it online!](https://scalafiddle.io/sf/IvLuupE/5) /: is short-hand for foldLeft operator, a is aggregation, ultimately returns the result we want, n is next element ## Un-golfed ``` def NewLettersPerDay(c: Seq[String]): Seq[String] = { c.foldLeft(Seq(""))((agg, next) => { val existingLetters = agg.reduce(_+_) val newDayLetters = next.diff(existingLetters) agg :+ newDayLetters }).tail } ``` [Answer] # [PHP](https://php.net/), 87 bytes ``` for(;$w=$argv[++$i];print' ')for($b=$a;$l=$w[$$i++];)$b[$l]?$b[$l]--:++$a[$l]&&print$l; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVym1VEovSy6K1tVUyY60LijLzStQV1DVBkipJQDlrlRxblfJoFZVMbe1Ya02VpGiVnFh7CKWrawXUlghiqqmBtarkWP///9/fz/V/SLj//xCPIFfX/8GuYa5@Ia6ufgA "PHP – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~36~~ 33 bytes ``` *+(){(a;x,a:&0|-/#''='(y;x@:1))}\ ``` [Try it online!](https://tio.run/##ZY5PC4JAEMXvfQrZIndLqa67BKksdYhdKLFDBXoxwjCIDitWX932nyh4eTPz9jdvtvDLW9k0OZ7NIaphRoSX4eny4y/Grrt2YUXEBq8Q@l6aN64n5@r3wrkjSPosCEzz7P4gglTkha7f0fsMAWcUEBCfuNLdgarpSBPKYkoZQCPH6RgpktAATeTjdZBge50z2LXrdi0II2kEtoS2RNZUjQnQgAcCJaESRbQhxx0/xHLec862pva7duhhyjDBnakZrv@v1Rxo/g "K (ngn/k) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` EθΦι¬⊙…θκ‹№…ιμλ№νλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUCjUEfBLTOnJLVII1NHwS@/RMMxr1LDuTI5J9U5Ix8sna2po@CTWlys4ZxfCtSEkANqyAXK5QAxRCoPxIEA6///o6PV/f1c1XUU1EPC/cGUR5ArmB/sGubqF@Lq6qceG/tftywnEQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over strings ι Current string Φ Map over characters θ Input array … Truncated to length κ Outer index ¬ Logical Not ⊙ Any element exists where № Count of λ Current letter in ι Outermost word … Truncated to μ Current letter index ‹ Is less than № Count of λ Current letter in ν Innermost word Implicitly print each day's bought letters on their own line ``` [Answer] ## PHP, UTF-8 aware (253 bytes) ``` <?php $p=[];for($i=1;$i<$argc;$i++){$a=$p;$b=[];for($j=0;$j<mb_strlen($s=$argv[$i]);$j++){$k=1;if(isset($a[$c=mb_substr($s,$j,1)]))if($a[$c]){$k=0;$a[$c]--;}if($k){echo $c;if(isset($b[$c]))$b[$c]+=$k;else $b[$c]=$k;}}$p=array_merge($p,$b);echo PHP_EOL;} ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 112 bytes ``` a=>{var b="";for(int i=0;;b+=a[i++])foreach(var z in b)if(a[i].Contains(z))a[i]=a[i].Remove(a[i].IndexOf(z),1);} ``` [Try it online!](https://tio.run/##bZBBa4QwEIXv/oqQk0Fb2nM2givSXRBTXOkelj1EG7tzaAQTtu2Kv90makHYXmbee/MxMFPrh1rDGNcGWrXZZ6DNRpsO1EcUNWwULOqvokMVw5g2beeDMgjYE6VVwMQJguBMbCxFffEdd0OgUEWg8e3w/Ji0yghQ2r8R4gI2pYX8bK9yJvbqXX7zxgLhM6HDSD23xkhtNGJIya/T2es9NKse8zzFIS6P3NVdkTp3SN/SvEzTHA/h/@SiJ37NxNvE5vHStktLltCJNX3Y8aK0o4zz/GXua/VnVpgL7IaBeusfuePcm6YjyXTdq3248V1AqLWm@@mbxQ61MPWlH@6pYwdGZqCkb@0w/gI "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 28 bytes ``` for$i(@h){s/$i//}push@h,/./g ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8MhQ7O6WF8lU1@/tqC0OMMhQ0dfTz/9/39/P1eukHB/LjDtEeTq@i@/oCQzP6/4v24BAA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` ->l{r="";l.map{|x|r.chars{|c|x[c]&&x[c]=''};r+=x;x}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nushWSck6Ry83saC6pqKmSC85I7GouLomuaYiOjlWTQ1E2qqr11oXadtWWFfU1v6Pjlb393NV11FQDwn3B1MeQa5gfrBrmKtfiKurn3qsDhe6KhgPrBgs7@jkDBJxhNFOMNoZJg5igZUGe/gHhYAEffz9/dyhDBQmnIesFCQUGwvzW4FCWnRFbO1/AA "Ruby – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é█üa%┐┤ ``` [Run and debug it](https://staxlang.xyz/#p=82db816125bfb4&i=[%22ONE%22+%22TWO%22+%22THREE%22+%22SEVENTEEN%22]%0A[%22ONE%22+%22TWO%22+%22ONE%22+%22THREE%22]%0A[%22ABC%22+%22AABC%22+%22ABBC%22+%22ABCC%22+%22AABBCC%22]%0A[%22SHORT%22+%22LOONG%22+%22LOOOONG%22+%22LOOOOOOONG%22+%22SHORT%22+%22LOOONG%22]&a=1&m=2) Output is newline separated. ]
[Question] [ ## Introduction In this challenge, you are given as input the ASCII representation of the [net](https://en.wikipedia.org/wiki/Net_%28polyhedron%29) (unfolded surface) of a [rectangular cuboid](https://en.wikipedia.org/wiki/Cuboid) (3D box). The format is this: ``` ....+--+....... ....|##|....... ....|##|....... ....|##|....... +---+--+---+--+ |###|##|###|##| +---+--+---+--+ ....|##|....... ....|##|....... ....|##|....... ....+--+....... ``` Each face of the cuboid is a rectangle of `#`s surrounded by `+-|`-characters. The outside of the net is filled with `.`s. The net will always have the same orientation: there's a middle face surrounded by its four neighboring faces, and the counterpart of the middle face is at the right border of the input. The input is padded with `.`s to a rectangular shape and will not contain extra rows or columns of `.`s. ## The task Your task is to take as input a diagram as above, and compute the volume of the cuboid that it represents, which is just the product of its height, width and depth. You can take the input as a newline-delimited string or an array of strings. The length of each edge is the distance between the `+`-characters at its two ends. For example, the horizontal edge `+--+` has length 3, and the vertical edge ``` + | | | + ``` has length 4. The minimum length of an edge is 1. The example cuboid above has volume 2\*3\*4 = 24. ## Rules and scoring You can write a full program or a function, and the lowest byte count wins. ## Test cases ``` .++.. +++++ +++++ .++.. 1 ...++.... ...||.... ...||.... +--++--++ +--++--++ ...||.... ...||.... ...++.... 3 ..+-+.... ..|#|.... +-+-+-+-+ |#|#|#|#| |#|#|#|#| +-+-+-+-+ ..|#|.... ..+-+.... 12 .+---+..... ++---++---+ ||###||###| ||###||###| ||###||###| ++---++---+ .+---+..... 16 ....++..... ....||..... ....||..... ....||..... +---++---++ |###||###|| |###||###|| |###||###|| +---++---++ ....||..... ....||..... ....||..... ....++..... 16 ...+--+...... ...|##|...... ...|##|...... +--+--+--+--+ |##|##|##|##| +--+--+--+--+ ...|##|...... ...|##|...... ...+--+...... 18 ....+--+....... ....|##|....... ....|##|....... ....|##|....... +---+--+---+--+ |###|##|###|##| +---+--+---+--+ ....|##|....... ....|##|....... ....|##|....... ....+--+....... 24 ....+-----+.......... ....|#####|.......... ....|#####|.......... ....|#####|.......... +---+-----+---+-----+ |###|#####|###|#####| |###|#####|###|#####| |###|#####|###|#####| |###|#####|###|#####| +---+-----+---+-----+ ....|#####|.......... ....|#####|.......... ....|#####|.......... ....+-----+.......... 120 ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~29~~ 28 bytes ``` T`.p`xy`\G\..+¶ xy ¶\| $` y ``` [Try it online!](https://tio.run/nexus/retina#pZLLDcMgDIbvXoNWqoTsBTJABmiPOTBCj43EXBkgi6UYA3bTpA8lPPRjzM9nlHmCDq6h6@B86QOr5RboHh5jGPqByM8TPEaAeRoinAKMy0LeE4Hnr8wSAaIskkwjxpXyiD4Po7by1CVJj9UwumpTGqSINKN0V0@oSwJFFM0FoHCwVXTOybSrbb71YeBCnOFLHftafbiG6h93tc3/xd/y5NesqPLKTp7lbcVprTOA9tXeJ5fX@4SlrQtny/6@zmXn3rAKVAN72f/Xf81XA6gxc8zpyX@jhRAbK5pyXKtI/rrD0e3bjlex@TpP "Retina – TIO Nexus") There's a *lot* of ways to approach this in Retina, depending on which area you want to multiply with which side, so I'm not sure how optimal this is, but it's actually already a lot shorter than I thought it would be. I've currently got two other solutions at the same byte count which seem a bit more golfable than the above approach: ``` \G\..+¶ ¶\| $'¶ G`\. T`.|+ ``` ``` ¶\||\+¶\.\D+ $'¶ G`\. T`.|+ ``` Although in these I could save a byte each if I assume that the input ends with a trailing linefeed, but I'd rather not have to rely on that. And another one, still at 28 bytes (this one actually multiplies three sides instead of multiplying one area by a side): ``` \G\. x -(?<=^.+) $` ¶\| $` x ``` ### Explanation The main idea is to multiply the area of the face on top by the length of the vertical side that touches the length border of the input. I'll use the following input as an example (it has side lengths 2, 3 and 4, so an area of 24): ``` ...+---+....... ...|###|....... ...|###|....... +--+---+--+---+ |##|###|##|###| +--+---+--+---+ ...|###|....... ...|###|....... ...+---+....... ``` **Stage 1: Transliterate** ``` T`.p`xy`\G\..+¶ ``` The regex `\G\..+¶` matches a line which starts with `.` and is immediately adjacent to the previous line. So this matches all the lines that contain the top face. The stage itself turns `.` into `x` and all other characters (any of `|+-#`) into `y`. This gives us the following result: ``` xxxyyyyyxxxxxxx xxxyyyyyxxxxxxx xxxyyyyyxxxxxxx +--+---+--+---+ |##|###|##|###| +--+---+--+---+ ...|###|....... ...|###|....... ...+---+....... ``` This has one more column of `y` than we need to represent the area of the top face. We fix this with the next stage. **Stage 2: Replace** ``` xy ``` So we match a `y` that is preceded by an `x` (which is exactly one of them per line) and remove them both from the string. We get this: ``` xxyyyyxxxxxxx xxyyyyxxxxxxx xxyyyyxxxxxxx +--+---+--+---+ |##|###|##|###| +--+---+--+---+ ...|###|....... ...|###|....... ...+---+....... ``` So now we've got the area of the top face represented by the number of `y`s. **Stage 3: Replace** ``` ¶\| $` ``` Our goal here is to multiply this area `A` by the missing side length, which is the number of `|` at the beginning of a line plus 1. However, it's actually easier to multiply by a number `n+1` because we've already got one copy of `A` in the string. If we replace `n` things with `A`, we end up with `n+1` copies of `A`. This makes things a lot easier for us. So we simply replace any `|` immediately after a linefeed with everything in front of the match. This mangles the string quite a lot and makes it a fair bit larger than we need, but the number of `y`s ends up being the result we're looking for: ``` xxyyyyxxxxxxx xxyyyyxxxxxxx xxyyyyxxxxxxx +--+---+--+---+xxyyyyxxxxxxx xxyyyyxxxxxxx xxyyyyxxxxxxx +--+---+--+---+##|###|##|###| +--+---+--+---+ ...|###|....... ...|###|....... ...+---+....... ``` **Stage 4: Match** ``` y ``` All that's left is to count the number of `y`s, which is printed as a decimal number at the end. [Answer] ## Python 2, 57 bytes ``` lambda l:l[0].find('+')*~l[0].count('-')*~`l`.count("'|") ``` A function that takes in a list of strings. Determines the 3 dimensions separately: `l[0].find('+')` The index of the first `+` in the first row. `-~l[0].count('-')` The number of `-` signs in the first row. `~`l`.count("'|")` The number of rows starting with `|` symbol, via the string representation of the list having a quote symbol before it. --- **62 bytes:** ``` def f(l):a=l[0].find('+');print(len(l[0])/2-a)*(len(l)-a+~a)*a ``` A function that takes in a list of strings and prints the result. Finds one dimension `a` as the index of `+` in the first row. The other two dimensions are inferred from it and the width and height of the input rectangle. A 63-byte alternative, finding the dimensions separately: ``` lambda l:l[0].find('+')*~l[0].count('-')*~zip(*l)[0].count('|') ``` [Answer] # Bash + coreutils, ~~83~~, 77 bytes EDITS: * Saved 6 bytes, by using "Here String" and optimizing regexp a bit **Golfed** ``` bc<<<`sed -rn '1{s/(.+)[^\.]*\1/(0\1)*(0/ s/\./+1/gp;a)*(-1 } /^[+|]/a+1 '`\) ``` **Explained** Transform with *sed*: ``` ....+--+....... => (0+1+1+1+1)*(0+1+1+1 )*(-2 +1 . =>() . =>() . =>() . =>() + => +1 | => +1 + => +1 . =>() . =>() . =>() . =>() ``` Get rid of newlines using backticks, append ) ``` => (0+1+1+1+1)*(0+1+1+1 )*(-2 +1 +1 +1 +1) ``` Feed resulting expression to *bc* ``` => 24 ``` **Test** ``` ./box <<EOF .++.. +++++ +++++ .++.. EOF 1 ./box <<EOF ...++.... ...||.... ...||.... +--++--++ +--++--++ ...||.... ...||.... ...++.... EOF 3 ./box <<EOF ....+--+....... ....|##|....... ....|##|....... ....|##|....... +---+--+---+--+ |###|##|###|##| +---+--+---+--+ ....|##|....... ....|##|....... ....|##|....... ....+--+....... EOF 24 ``` **[Try it online !](https://goo.gl/rtkDet)** (uses bash arithmetic expansion, instead of *bc*, as the latter is not available) [Answer] # [Snails](https://github.com/feresum/PMA), 19 bytes ``` AM =~d^.+\+.+l.+^.2 ``` [Try it online.](https://tio.run/nexus/snails#@@/oy2VblxKnpx2jraedo6cdp2f0/78eEGjr6mrrQQAXiKhRVq4hlg/Uq6sNRmCKCyinXANGYApDnlTz0dwHAA) The idea is that we start somewhere on the rightmost edge in the net, and then travel to somewhere in the bottommost face. The length of the edge and the area of the face are multiplied by the mechanism of counting all matching paths. ``` AM ,, A -> count all matching paths ,, M -> first char matched is the one in the current direction ,, from the starting location, rather than directly on it =~ ,, check that we are on the right edge of the grid d ^.+ \+ ,, go down, matching one or more non-'.' characters, then a '+' .+ ,, go down one or more times l .+ ,, go left one or more times ^. 2 ,, match two further characters which aren't '.' to the left ``` [Answer] # JavaScript (ES6), 67 ~~91~~ ``` s=>(a=~-s.search` `/2-(b=s.indexOf`+`))*b*(s.split` `.length-1-2*b) ``` **Test** ``` F= s=>(a=~-s.search` `/2-(b=s.indexOf`+`))*b*(s.split` `.length-1-2*b) out=x=>O.textContent+=x+'\n\n' ;`.++.. +++++ +++++ .++.. 1 ...++.... ...||.... ...||.... +--++--++ +--++--++ ...||.... ...||.... ...++.... 3 ..+-+.... ..|#|.... +-+-+-+-+ |#|#|#|#| |#|#|#|#| +-+-+-+-+ ..|#|.... ..+-+.... 12 .+---+..... ++---++---+ ||###||###| ||###||###| ||###||###| ++---++---+ .+---+..... 16 ....++..... ....||..... ....||..... ....||..... +---++---++ |###||###|| |###||###|| |###||###|| +---++---++ ....||..... ....||..... ....||..... ....++..... 16 ...+--+...... ...|##|...... ...|##|...... +--+--+--+--+ |##|##|##|##| +--+--+--+--+ ...|##|...... ...|##|...... ...+--+...... 18 ....+--+....... ....|##|....... ....|##|....... ....|##|....... +---+--+---+--+ |###|##|###|##| +---+--+---+--+ ....|##|....... ....|##|....... ....|##|....... ....+--+....... 24 ....+-----+.......... ....|#####|.......... ....|#####|.......... ....|#####|.......... +---+-----+---+-----+ |###|#####|###|#####| |###|#####|###|#####| |###|#####|###|#####| |###|#####|###|#####| +---+-----+---+-----+ ....|#####|.......... ....|#####|.......... ....|#####|.......... ....+-----+.......... 120` .split('\n\n').forEach(t=>{ t=t.split('\n') k=+t.pop() t=t.join('\n') v=F(t) out(v+' '+k +' '+(v==k?'OK':'KO')+'\n'+t) }) ``` ``` <pre id=O></pre> ``` [Answer] # Ruby, 44 Works on a similar principle to other answers: find the first `+` to find the depth, find the next `.` after the `+` to find the width, and count the number of `|` at end of line and add 1 to find height. ``` ->s{(s=~/\+/)*($'=~/\./)*s.split("| ").size} ``` **ungolfed in test program** ``` f=->s{(s=~/\+/)* # index of first match of /\+/ in s ($'=~/\./)* # $' is a special variable, contains string to right of last match. index of /\./ in $' s.split("| ").size} # split the string at |\n to form an array and count the members puts f[".++.. +++++ +++++ .++.."] puts f["...++.... ...||.... ...||.... +--++--++ +--++--++ ...||.... ...||.... ...++...."] #etc. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 21 bytes Let `W` and `H` be respectively the width and the height of the input - not the box. Then, the box dimensions `A`, `B` and `C` follow these rules: ``` W = 2(A+C)+1 H = B+2C+1 ``` The following figure shows what `A`, `B` and `C` are, in terms of edge names: ``` ....AAAA....... ....|##|....... ....|##|....... ....|##|....... B---+--CCCCC--+ B###|##|###|##| B---+--+---+--+ ....|##|....... ....|##|....... ....|##|....... ....+--+....... ``` Hence the above formulas. This program computes `A`, deduces the values of `B` and `C` and finally computes their product. ``` S'.ÊO<D¹g<;-(D·|g-()P S'.Ê From each character of the first line, yield 0 if it is '.' or 1 otherwise. The result is stored in an array O<D A = sum(array) - 1 ¹g<;-(D C = (W-1)/2 - A ·|g-( B = H-1-2*C ) Yield [A,C,B] P Take the product and implicitly display it ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Uycuw4pPPETCuWc8Oy0oRMK3fGctKClQ&input=Li4uListLS0tLSsuLi4uLi4uLi4uCi4uLi58IyMjIyN8Li4uLi4uLi4uLgouLi4ufCMjIyMjfC4uLi4uLi4uLi4KLi4uLnwjIyMjI3wuLi4uLi4uLi4uCistLS0rLS0tLS0rLS0tKy0tLS0tKwp8IyMjfCMjIyMjfCMjI3wjIyMjI3wKfCMjI3wjIyMjI3wjIyN8IyMjIyN8CnwjIyN8IyMjIyN8IyMjfCMjIyMjfAp8IyMjfCMjIyMjfCMjI3wjIyMjI3wKKy0tLSstLS0tLSstLS0rLS0tLS0rCi4uLi58IyMjIyN8Li4uLi4uLi4uLgouLi4ufCMjIyMjfC4uLi4uLi4uLi4KLi4uLnwjIyMjI3wuLi4uLi4uLi4uCi4uLi4rLS0tLS0rLi4uLi4uLi4uLg) # Former version - Different approach - 26 bytes ``` |vyS'.Ê})¬O<sø¬O<s€O¬Ê1k)P | Take the input as an array of lines (strings) vy For each line S'.Ê For each character in the line, yield 0 if it is '.' or 1 otherwise } End For ) Wrap the results as an array ¬O< A = sum(first_line) - 1 sø Transpose the box pattern ¬O< B = sum(first_line) - 1 ; since the pattern is transposed, it corresponds to the first column s€O Sum every line from the transposed pattern ¬Ê1k C = index of the first line that has a different sum from the first line ) Yield [A, B, C] P Take the product A*B*C and implicitly display it ``` [Answer] # [Befunge 93](http://esolangs.org/wiki/Befunge), 56 bytes ``` ~2%#^_1+ @.*+< `"z"~<|:`~0+ 5*\`#^_\1>*\~7 %2~\<\+1_^# ``` [Try it Online!](https://tio.run/nexus/befunge#@19npKocF2@ozaWg4KCnpW3DlaBUpVRnU2OVUGegzWWqFZMAlI4xtNOKqTPnUjWqi7GJ0TaMj1P@/18PCLR1dbX1IIALRNQoK9cQywfq1dUGIzDFBZRTrgEjMIUhT6r5aO4DAA) ### Explanation: The volume of the box can be calculated by multiplying the number of `.`s on the first line before any other characters, by the number of `+` and `-`s on the first line - 1, and the number of lines that start with a `|` + 1. ``` ~2%#^_1+ Uses the ASCII value % 2 of a character to count the .s %2~\<\+1_^# IP wraps around to the bottom. Counts the non . chars Works because ("+" % 2) == ("-" % 2) == 1 5*\`#^_\1>*\~7 Multiplies the previous 2 results and cycles through characters until it hits a newline or EOF `"z"~<|:`~0+ Adds 1 to the 3rd dimension if the following char is a "|" Also checks for EOF; If there is more input, goes back to previous line. Otherwise, goes to the last line @.*+< Adds 1 to the 3rd dimension, multiplies it to the rest, prints the volume, and ends the program ``` I had to move the IP up lines instead of down in order to use the vertical if in the 3rd line. If the IP was going down lines, the vertical if would force the top of the stack to be 1 when hitting the following horizontal if, sending it in the wrong direction. [Answer] # Haskell, ~~64~~ 56 bytes ``` f(x:r)=sum$fst(span(>'+')x)>>[1|'|':_<-"|":r,'-'<-'-':x] ``` [Try it online!](https://tio.run/nexus/haskell#y03MzFOwVcjMK0ktSkwuUVBRKM7IL1fQU0gD4pzMvNTi/2kaFVZFmrbFpbkqacUlGsUFiXkadura6poVmnZ20YY16jXqVvE2uko1SlZFOuq66ja6QMKqIvb/fz0g0NYFAW09OOACETXKIFBDpijITKi5CBYXSB1ULYJFBVHstlHuC6yhAwA "Haskell – TIO Nexus") ### Explanation The input is expected to be a list of strings for each line, so in `f` the parameter `x` is the first line and `r` a list of the remaining lines. 1. `fst(span(>'+')x)` returns the `.`-prefix of the first line as a string, so `length(fst(span(>'+')x))` is the first dimension `d1`. 2. A list comprehension can act as filter, e.g. `['-' | '-' <- x]` returns a string of all `-` in the first line, so `1 + length['-' | '-' <- x]` yields the second dimension `d2`. 3. Analogously the number of `|` in the first row can be counted, so `1 + length['|' | '|':_ <- r]` is the third dimension `d3`. The list comprehensions of 2. and 3. can be shortened to `1+sum[1|'-'<-x]` and `1+sum[1|'|':_<-r]` by building a list of ones for each occurrence of '-' or '|' and then taking the sum. We can further put the outer `1+` into the list comprehension by appending `-` to `x` and `"|"` to `r` to yield `sum[1|'-'<-'-':x]` and `sum[1|'|':_<-"|":r]`. Now we can combine both list comprehensions by putting both predicates in the same comprehension: `sum[1|'|':_<-"|":r,'-'<-'-':x]` Conveniently this computes exactly the product of the two dimensions because for lists `F` and `G` the following list comprehension is the Cartesian product `F x G =[(a,b)|a<-F,b<-G]`. Finally, instead of multiplying 1. with the combination of 2. and 3. we can make use of the `>>` operator on lists: `F>>G` repeats `G` `length F` times and concatenates the result. So `fst(span(>'+')x)>>[1|'|':_<-"|":r,'-'<-'-':x]` repeats the list of `d2*d3` ones `d1` times, yielding a list of `d1*d2*d3` ones which are then summed up to get the volume. [Answer] # Java 8, ~~185~~ 129 bytes thanks to Zgarb for -56 bytes golfed: ``` int g(String[]i){int h=0;for(String k:i){if(k.charAt(0)=='.')h++;else break;}return((i[0].length()-2*h-1)/2)*(i.length-2*h-1)*h;} ``` ungolfed: ``` int g(String[] i) { int h = 0; for (String k : i) { if (k.charAt(0) == '.') h++; else break; } return ((i[0].length()-2*h-1)/2)*(i.length-2*h-1)*h; } ``` ## Explanation `a*b*h = ((length_of_line-2*h-1)/2)*(number_of_lines-2*h-1)*h` where `a` and `b` are the dimensions of the base and `h` is the height. You can find `h` by counting the first `h` lines where you begin with a `.`. [Answer] # Java, 112 bytes ``` int v(String[]s){int a=s[0].lastIndexOf('+')-s[0].indexOf('+'),b=s[0].length()/2-a;return a*b*(s.length-2*b-1);} ``` Expanded: ``` int v(String[] s) { // length of the edge in the first line int a = s[0].lastIndexOf('+') - s[0].indexOf('+'); // length of the second edge // int b = s[0].length() - 2 * a - 1; <-- multiplied by 2 int b = s[0].length()/2 - a; // <-- hack, length is always odd // length of the third edge in () // volume return a * b * (s.length - 2 * b - 1); } // end method v ``` [Answer] # Powershell, ~~68~~ 67 bytes ``` ($c="$args"|% i*f +)*($args[0].Length/2-.5-$c)*($args.Count-1-2*$c) ``` Note: `"$args"|% i*f +` [is shortcut](https://codegolf.stackexchange.com/a/111526/80745) for `"$args".indexOf('+')` ## Explanation Good explanation took from the [Osable's answer](https://codegolf.stackexchange.com/a/103069/80745): Let `W` and `H` be respectively the width and the height of the input - not the box. Then, the box dimensions `A`, `B` and `C` follow these rules: ``` W = 2(A+C)+1 H = B+2C+1 ``` The following figure shows what `A`, `B` and `C` are, in terms of edge names: ``` CCCCAAAA....... ....|##|....... ....|##|....... ....|##|....... B---+--+---+--+ B###|##|###|##| B---+--+---+--+ ....|##|....... ....|##|....... ....|##|....... ....+--+....... ``` And `C` is position of the first `+` in the first line of the input. Test script: ``` $f = { ($c="$args"|% i*f +)*($args[0].Length/2-.5-$c)*($args.Count-1-2*$c) } @( ,(1, ".++..", "+++++", "+++++", ".++..") ,(3,"...++....", "...||....", "...||....", "+--++--++", "+--++--++", "...||....", "...||....", "...++....") ,(12,"..+-+....", "..|#|....", "+-+-+-+-+", "|#|#|#|#|", "|#|#|#|#|", "+-+-+-+-+", "..|#|....", "..+-+....") ,(16,".+---+.....", "++---++---+", "||###||###|", "||###||###|", "||###||###|", "++---++---+", ".+---+.....") ,(16,"....++.....", "....||.....", "....||.....", "....||.....", "+---++---++", "|###||###||", "|###||###||", "|###||###||", "+---++---++", "....||.....", "....||.....", "....||.....", "....++.....") ,(18,"...+--+......", "...|##|......", "...|##|......", "+--+--+--+--+", "|##|##|##|##|", "+--+--+--+--+", "...|##|......", "...|##|......", "...+--+......") ,(24,"....+--+.......", "....|##|.......", "....|##|.......", "....|##|.......", "+---+--+---+--+", "|###|##|###|##|", "+---+--+---+--+", "....|##|.......", "....|##|.......", "....|##|.......", "....+--+.......") ,(120,"....+-----+..........", "....|#####|..........", "....|#####|..........", "....|#####|..........", "+---+-----+---+-----+", "|###|#####|###|#####|", "|###|#####|###|#####|", "|###|#####|###|#####|", "|###|#####|###|#####|", "+---+-----+---+-----+", "....|#####|..........", "....|#####|..........", "....|#####|..........", "....+-----+..........") ) | % { $expected,$s = $_ $result = &$f @s "$($result-eq$expected): $result" } ``` Output: ``` True: 1 True: 3 True: 12 True: 16 True: 16 True: 18 True: 24 True: 120 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes ``` (2(x=#@" ")-(y=#@"|")-9)((9-5x+y)^2-9#@".")/54&@*CharacterCounts ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/V/DSKPCVtlBiUtJU1ejEsSqAbIsNTU0LHVNK7QrNeOMdC2BonpKmvqmJmoOWs4ZiUWJySWpRc75pXklxf8VHBSU9IBAW1dXWw8CuEBEjbJyDbF8oF5dbTACU1xAOeUaMAJTGPKkmo/mPqXY/wA "Wolfram Language (Mathematica) – Try It Online") Uses the number of `.`, `|`, and `\n` characters in the input to solve for the volume. It looks stupid because there's an actual new line in place of `\n`. If `A`, `B`, and `C` are the sides, then `. = 2C(A+2C)`, `| = 5B+4C-9`, and `\n = B+2C`, so we can solve for the volume `ABC` in terms of these three character counts. ]
[Question] [ When I was a lad, kids would wander into computer stores and play Hunt the Wumpus until the staff kicked us out. It was a simple game, programmable on the home computers of the mid-1970s, machines so rudimentary that instead of chicklet-sized microprocessors, I think some of them probably had real chicklets in there. Let's evoke that bygone era by reproducing the game on modern hardware. 1. The player starts in a random room on an icosahedral map (thus there are 20 rooms in total, connected to each other like the faces of an icosahedron, and every room has exactly three exits). 2. The wumpus starts in a randomly selected different room. The wumpus stinks, and its odor can be detected in any of the three rooms adjacent to its location, though the direction of the odor is impossible for the player to determine. The game reports only "you smell a wumpus." 3. The player carries a bow and an infinite number of arrows, which he may shoot at any time into the room in front of him. If the wumpus is in that room, it dies and the player wins. If the wumpus was not in that room, it is startled and moves randomly into any of the three rooms connected to its current location. 4. One, randomly selected room (guaranteed not to be the room in which the player starts) contains a bottomless pit. If the player is in any room adjacent to the pit, he feels a breeze, but gets no clue as to which door the breeze came from. If he walks into the room with the pit, he dies and wumpus wins. The wumpus is unaffected by the pit. 5. If the player walks into the wumpus's room, or if the wumpus walks into the player's room, the wumpus wins. 6. The player specifies the direction he is facing with a number (1 = right, 2 = left, 3 = back), and then an action (4 = shoot an arrow, 5 = walk in the specified direction). 7. For the sake of scoring, each game string ("You feel a breeze," "You smell a wumpus," "Your arrow didn't hit anything", etc.) can be considered one byte. No abusing this to hide game code in text; this is just for interacting with the player. 8. Deduct 10% of your byte count for implementing megabats, which start in a random room different from the player (though they can share a room with the wumpus and/or the pit). If the player walks into the room with the bats, the bats will carry the player to another randomly selected room (guaranteed not to be the room with the pit or the wumpus in it), before flying off to their own, new random location. In the three rooms adjacent to the bats, they can be heard squeaking, but the player is given no information about which room the sound comes from. 9. Deduct 35% of your byte count for implementing a graphical interface that shows the icosahedral map and some kind of indication of the information the player has so far about the location of the pit, the wumpus, and the bats (if applicable), relative to the player. Obviously, if the wumpus moves or the player gets moved by the bats, the map needs to reset accordingly. 10. Lowest byte count, as adjusted, wins. BASIC source code for a version of the game (not necessarily conforming to the rules above and, in any case, utterly ungolfed) can be found at [this website](http://justbasic.conforums.com/index.cgi?board=shared&action=display&num=1242069786) and probably others. [Answer] # GolfScript, 163 ``` :n;:`"You shot the wumpus. ""The wumpus ate you. ""The pit swallowed you. "{19:|rand}2*0|{[:,~,4%"ftvh"=.,+,@-]{20%}%}:^{;.^.+.3$?>"You feel a breeze. "1$6"You smell a wumpus. "4$8{$?-1>*p}2*'"#{'|):|';`head -1`}"'++~{3%}/={=3$=|{"Your shot missed. "p@^3rand=@@}if}{=@;}if.[|4$6$]?.)!}do])= ``` The score is obtained by taking the byte count (290), adding the number of strings used for interaction with the user (6) and subtracting the combined length of those strings (133). The linefeeds are part of the strings and contribute to the byte count. ### Milestones 1. Ported [professorfish's answer](https://codegolf.stackexchange.com/a/26217) from Bash to GolfScript. **Score: 269** 2. Acted on [Peter Taylor](https://codegolf.stackexchange.com/u/194)'s suggestions in the comments. **Score: 250** 3. Peter Taylor [refactored my entire code](https://gist.github.com/pjt33/11357839#file-wumpus-dennis-gs) and helped me to compress the lookup table. **Score: 202** 4. Replaced the lookup table of adjacent rooms with a mathematical approach. **Score: 182** 5. Refactored input, output and the function supporting the mathematical approach. **Score: 163** A big “Thank you!” goes to Peter Taylor for all his help. ### How it works The 20 rooms are represented as the vertexes of a dodecahedron, which have been assigned numbers from 0 to 19 in the following fashion: ![Dodecahedral graph](https://i.stack.imgur.com/Fmw5N.png) To find the rooms which are adjacent to room *N* and order them in clockwise fashion, we have to consider four cases: * If *N ≡ 0 mod 4* (blue vertexes), the adjacent room are *19 - N*, *N + 2 mod 20* and *N - 2 mod 20*. * If *N ≡ 1 mod 4* (green vertexes), the adjacent room are *19 - N*, *N - 4 mod 20* and *N + 4 mod 20*. * If *N ≡ 2 mod 4* (yellow vertexes), the adjacent room are *19 - N*, *N - 2 mod 20* and *N + 2 mod 20*. * If *N ≡ 3 mod 4* (red vertexes), the adjacent room are, *19 - N*, *N + 4 mod 20* and *N - 4 mod 20*. ``` # The function “p” is implemented as “{`print n print}”. By storing an empty string in # “n” and nullifying “`”, “p” becomes an alias for “print”. :n;:` # Push the messages corresponding to the three possible outcomes of the game. "You shot the wumpus.\n""The wumpus ate you.\n""The pit swallowed you.\n" # Place the wumpus and the pit in randomly selected rooms different from room 19; place # the player in room 19, with his back to room 0. {19:|rand}2*0| # Function “^” takes a single number as its argument and returns an array of all the # adjacent rooms to the room that number corresponds to. { [ :,~ # Store the room number in “,” and negate it ( ~N ≡ 19 - N mod 20 ) ,4% # Push the room number modulus 4. "ftvh"= # If it is equal to 0|1|2|3, push 102|116|118|104 ≡ 2|-4|-2|4 mod 20. .,+,@- # Determine the room number plus and minus the integer from above. ]{20%}% # Take all three room numbers modulus 20. }:^ { # STACK: Strings Pit Wumpus Previous Current Function|Index ; # STACK: Strings Pit Wumpus Previous Current # Find the adjacent rooms to the current room, duplicate them and remove the rooms # before the first occurrence of the previous room. Since the rooms are ordered in # clockwise fashion, the array of adjacent rooms will begin with the rooms # corresponding to the following directions: “Back Left Right” .^.+.3$?> # STACK: Strings Pit Wumpus Previous Current Adjacent # Push two more messages and their respective triggers. "You feel a breeze.\n"1$6"You smell a wumpus.\n"4$8 # STACK: ... Pit Wumpus Previous Current Adjacent String Adjacent 6 String Adjacent 8 # Do the following twice: Duplicate the nth stack element and check if it's present in # the array of adjacent rooms. If so, print the string below it. {$?-1>*p}2* # Read one line (direction, action, LF) from STDIN. The counter “|” is needed so the # result won't get cached. '"#{'|):|';`head -1`}"'++~ {3%}/ # Replace 1|2|3|4|5|LF with their character codes modulus 3 (1|2|0|1|2|1). ={ # If the player shoots an arrow: =3$= # Determine the specified room and check if it corresponds to the wumpus. | # If it does, push and invalid room number ( | > 19 ). # If it does not, say so and move the wumpus to a randomly selected adjacent room. {"Your shot missed."p@^3rand=@@} if }{ # If the player moves: =@; # Place him into the selected room. }if # STACK: Pit Wumpus Previous Current Invalid? # Determine if the player's current room number is either invalid, the wumpus's room # number or the pit's room number (first match). .[|4$6$]? # If there is no match, the index is -1 and incrementing and negating it yields “true”. # STACK: Strings Pit Wumpus Precious Current Invalid? Index Boolean # Repeat loop is the boolean is falsy. If repeated, the first instruction of the loop # will pop the index. }do # Consolidate the entire stack into an array. And pop its last element: the index. # Replace the array with the element corresponding to that index. ])= # GolfScript will execute “print n print”. ``` [Answer] # ~~REV0 C++ (Visual Studio on Windows) 405~~ ``` #include"stdafx.h" #include<stdlib.h> #include<time.h> int main(){srand(time(NULL));char i,h=rand()%19,w=rand()%19,p=19,d=0,q,e,m[]="e@LwQMQOSOLT";while(p-h&&p-w){for(i=3;i--;){q=(p+m[p%4*3+i])%20;if(q==w)puts("you smell a wumpus");if(q==h)puts("you feel a breeze");}scanf_s("%d",&i);e=(d+i/10)*m[p%4]%3;q=(p+m[p%4*3+e])%20;if(i%5){if(q==w){puts("YOU KILLED THE WUMPUS!");h=p;}else{puts("arrow missed");w=(w+m[w%4*3+rand()%3])%20;}}else{p=q;d=e;if(p==h)puts("YOU FELL IN A HOLE!");}if(p==w)puts("THE WUMPUS GOT YOU!");}} ``` Below is a playthrough, demonstrating that (provided you don't start right next to a hazard) with correct play you can always win. The player feels a breeze, turns back and does a complete counterclockwise loop. As it takes him exactly 5 moves to feel a breeze again, he knows the hole to his right, and gets as far away as possible. Similarly, when he smells the wumpus, not knowing whether it is right or left, he turns back and does a clockwise loop. It takes him 5 moves to smell the wumpus again, so he knows it is to the left and shoots with certainty. If he had looped the other way he would have found the wumpus sooner and known it was in the same direction he was turning. ![enter image description here](https://i.stack.imgur.com/Wsvho.png) # ~~REV1 C (GCC on Cygwin), 431-35% bonus = 280.15~~ ``` #define u(t,s,c) if(t){puts(s);c;} i,d,e,a,b;main(){srand(time(0));char q,p=19,h=rand()%p,w=rand()%p,*m="e@LwQMQOSOLT-\\/\n \v "; while(p-h&&p-w){ for(i=3;i--;){q=(p+m[p%4*3+i])%20;u(q==w,"you smell a wumpus",a|=2<<p)u(q==h,"you feel a breeze",b|=1<<p)} for(i=20;i--;)printf("%c%c",i==p?m[d+12]:48+(a>>i&2)+(b>>i&1),m[i%4+15]); scanf("%d",&i);e=(d+i/10)*m[p%4]%3;q=(p+m[p%4*3+e])%20; if(i%5){u(q-w,"arrow missed",w=(w+m[w%4*3+rand()%3])%20;a=0)else u(1,"YOU KILLED THE WUMPUS!",h=p)} else{p=q;d=e;u(p==h,"YOU FELL IN A HOLE!",)} u(p==w,"THE WUMPUS GOT YOU!",)}} ``` Newlines added for clarity. The changes from Rev 0 are as follows: A big thankyou to @Dennis for recommending GCC compiler on Cygwin Linux emulator for Windows. This compiler does not require the `include`s in the rev 0 program, and it allows default `int` type for variables and `main.` This is a life-changing golfing tip! Additionally running in Linux means that `\f` does cause the cursor to move down without doing a carriage return (unlike in Windows where it just produces a printable symbol.) This has allowed considerable shortening of the printf statement that prints the board Several additional tips from Dennis in the comments, and one of my own: change of condition when checking if arrow hit the wumpus: `if(q==w)`>`if(q-w)` (..else.. is reversed) Addition of graphic display showing the information the player knows about where a wumpus is smelt / a breeze is felt to claim the 35% bonus. (I deleted the old debug version of this which showed the exact position of the wumpus and hole. It can be seen in the edit history.) # REV2 C (GCC on Cygwin), 389-35% bonus = 252.85 ``` #define Q(N) (N+"QTLOQMQOSOLT"[N%4*3+e])%20 #define P printf( i,d,e,a,b;main(){int p=19,q=srand(&p),h=rand()%p,w=rand()%p; while(p-h&&p-w){ for(e=3;e--;){q=Q(p);q-w||P"You smell a wumpus\n",a|=2<<p);q-h||P"You feel a breeze\n",b|=1<<p);} for(i=20;i--;)P"%c%c",i-p?48+(a>>i&2)+(b>>i&1):"-\\/"[d],"\n \v "[i%4]); scanf("%d",&i);e=(d+i/9)*"edde"[p%4]%3;q=Q(p); if(i%5){e=rand()%3;w=q-w?P"Your arrow didn't hit anything\n",a=0)&Q(w):(p=20);} else p=q,d=e; } P p-20?p-w?"YOU FELL IN A HOLE!\n":"THE WUMPUS GOT YOU!\n":"YOU KILLED THE WUMPUS!\n");} ``` Thanks again to Dennis for refactoring my code: Char constant `m[]` replaced with literals (I didn't know you could index a literal.) Seeding of random numbers with stack variable (system dependent, some systems randomise memory allocation as a security measure.) Macro with `puts` replaced with a macro with `printf` and additional code which must be executed when the message displayed placed inside `printf` arguments (advantage taken of the face that printf does not print the last few arguments if there aren't enough format specfiers in the format string.) `if` replaced by `||` Calculation of new position of player/wumpus placed inside new macro. Win/lose messages placed outside `while` loop. `if` replaced by conditional operator. Use of conditional operator in line for shooting arrow. If the player misses, this requires both printing a message and adjusting wumpus position. Dennis offered a couple of ways of combining `printf` and the calculation of wumpus position into a single expression, but I have gone with one of my own. `printf` returns the number of characters printed, which for `Your arrow didn't hit anything\n` is 31 (11111 binary.) So, `31&Q(w)==Q(w)`. My other contribution to this edit has been elimination of some unnecessary brackets. **Output** Here the player has already found where the Wumpus is, but chooses to do a thorough explore to find out exactly where the pit is, too. Unlike my old debug version which showed where the wumpus and pit were throughout the game, this shows only the rooms where the player has visited and felt a breeze (1) smelt the wumpus (2) or both (3). (If the player shoots an arrow and misses, the variable `a` containing the wumpus position info is reset.) ![enter image description here](https://i.stack.imgur.com/bX1Cz.png) **ICOSAHEDRON REPRESENTATION** *Note: this section is based on rev 1* My star feature! There is no graph in my code. To explain how it works, see the world map below. Any point on the icosahedron can be represented by a latitude 0-3 and a longitude 0-4 (or a single number, `long*4+lat`.) The longitude line marked on the map passes only through those faces with longitude zero, and the latitude line passes through the centre of the faces with latitude zero. The player can be oriented on 3 possible axes, represented by the symbols as follows: north-south`-` northeast-southwest`\` northwest-southeast `/`. In any given room he has exactly one exit on each of these axes available to him. In the display shown the player makes a complete clockwise loop. It is generally easy to identify from the player marking where he came from, and therefore where he is allowed to go to. *The one case that is a little difficult for the uninitiated eye is the fourth one. When you see a slant in one of these polar rows, the player has come from the polar cell nearest the outside end of the slant and is facing generally towards the equator. Thus the player is facing southeast and his options are: 15(SOUTH, the cell to the right) 25(northEAST, the cell above) or 35(northWEST, the cell below.)* So, basically I map the icosahedron to a 5x4 grid, with cells numbered 19 to 0 in the order they are printed. The move is made by adding or subtracting from the current position, depending on the player's latitude and direction, per the table below. If the player goes off the bottom (west) of the board, he comes back on the top (east) side and vice versa, so his position is taken modulo 20. Generally the moves are coded into m[] by adding ascii 80 (`P`) to the raw value giving the characters shown below, but principle any multiple of 20 can be added without affecting the operation. ``` Table of addition values for moves Direction Symbol Latitude 0 1 2 3 Latitude 0 1 2 3 0, N-S - 1 -1 1 -1 Q O Q O 1, NE-SW \ -4 1 -1 4 L Q O T 2, NW-SE / 4 -3 3 -4 T M S L ``` The player's input (divided by 10 to remove the second digit) is added to his current direction and taken modulo 3 to get his new direction. This works fine in the majority of cases. However there is an issue when he is in a polar room and moves toward the pole. It will be clear when folding the map below that if he leaves the room facing "northeast" he will enter the new square facing "southeast" so a correction must be made. This is done in the line `e=(d+i/10)*m[p%4]%3;` by the multiplication by `m[p%4]`. The first four values of m[] are selected such that, in addition to their function above, they also have the characteristic `m[1]%3==m[2]%3==1` and `m[0]%3==m[3]%3==2`. This leaves the direction alone for the equatorial rooms and applies the necessary correction for polar rooms. The logical time to do the correction would be after the move. However to save characters it is done before the move. Therefore certain values in m[] must be transposed. So the last 2 characters are `LT` instead of `TL` per the table above for example. ![enter image description here](https://i.stack.imgur.com/R9zew.png) **UNGOLFED CODE** *this is rev 1 code, which is less obfuscated than rev 2.* This will run on GCC / Linux. I have included in the comments the extra code needed to make it run on Visual studio / Windows. It's a big difference! ``` //Runs on gcc/linux. For visual studio / windows, change printf(...) //to printf(" %c%c%c",9*(i%4==1),i==p?m[d+12]:48+(a>>i&2)+(b>>i&1),10*!(i%2)) and uncomment the following lines //#include"stdafx.h" //#include<stdlib.h> //#include<time.h> //#pragma warning(once:996;once:430) //allow the use of scanf instead of scanf_s, allow default type=int. //Though rather than using the pragma, it is shorter to follow compiler recommendation and use scanf_s and int. #define u(t,s,c) if(t){puts(s);c;} //if(test){puts(string);additional code;} i, //player input, loop counter d,e, //current and proposed direction a,b; //bit flags for where wumpus smelt / breeze felt main(){ srand(time(0)); char q,p=19,h=rand()%p,w=rand()%p, //Initialise player, hole and wumpus. q stores proposed player position. *m="e@LwQMQOSOLT-\\/\n \f "; //Chars 0-11: movetable. Chars 12-14:symbol for player. Chars 15-18: graphics format. while(p-h&&p-w){ // Print warnings for(i=3;i--;){q=(p+m[p%4*3+i])%20;u(q==w,"you smell a wumpus",a|=2<<p)u(q==h,"you feel a breeze",b|=1<<p)} // graphic display for(i=20;i--;)printf("%c%c",i==p?m[d+12]:48+(a>>i&2)+(b>>i&1),m[i%4+15]); // Get player input and work out direction and room scanf("%d",&i); e=(d+i/10)*m[p%4]%3; q=(p+m[p%4*3+e])%20; // i%5 is false if player inputs 5 (move player) otherwise true (shoot arrow) if(i%5) {u(q-w,"arrow missed",w=(w+m[w%4*3+rand()%3])%20;a=0)else u(1,"YOU KILLED THE WUMPUS!",h=p)} else{p=q;d=e;u(p==h,"YOU FELL IN A HOLE!",)} u(p==w,"THE WUMPUS GOT YOU!",) } } ``` **ISSUES AND CURIOISITIES** I have taken advantage of the point mentioned by @professorfish, if the wumpus and pit start in random places, there is no need for the player to start in a random place. The player always starts in room 19 facing north. I understand that as the wumpus is "unaffected by the pit" the wumpus can start in, or enter the room where the pit is. In general this simplifies things except for one point. I have no specific variable to indicate the game is over; it is over when the player coincides with the wumpus or pit. So when the player wins I display the winning message but move the pit to the player to kludge out of the loop! I can't put the player in the pit as the wumpus might be there and I would get a message about the wumpus that I don't want. The rev0program worked perfectly in visual studio, but the IDE said "stack corrupted around variable i" on exit. This is because scanf is trying to put an `int` into a `char.` Dennis reported incorrect behaviour on his Linux machine because of this. *Anyway it is fixed by use of the correct type in rev 1.* The line for displaying the board in rev 0 is clumsy and appears slightly different on other platforms. In `printf(" %c%c%c")` the middle %c is the printable character displayed. The last %c is either ASCII 0 or ASCII 10 (\n, newline with carriage return in Windows.) There appears to be no character in Windows that works in the console, that will go down a line without giving a carriage return. If there was I wouldn't need the first c% (ASCII 0, or ASCII 9 tab before latitude 1 character. Tabs are notoriously undefined in their behaviour.) The leading space improves formatting (puts latitude 3 & 2 characters nearer latitude 1 character.) *Rev 1 has a revison of this line which uses a \f formfeed character and therefore needs no format character at the start of the printf. This makes it shorter, but the \f does not work in Windows.* [Answer] ### GolfScript, 269 characters ``` {puts}:|;20,{;9{rand}:r~}$3<(:>"B:%d`w85>2n+Fup`y/>@D-=J7ldnx/W5XsLAb8~"{32-}%"`\24"{base}/3/{[.[~@].[~@]]}%:A=3r=0=:F;~:W;:P;{>A={0=F=}?:^P&!!{"You feel a breeze"|}*^W&!!{"You smell a wumpus"|}*'"#{'9.?r';STDIN.gets()}"'++~);(3%^=\4`={W={"Your arrow hit the wumpus"|0}{"Your arrow didn't hit anything"|W A=0=3r=:W>=.!\{"The wumpus catches you"|}*}if}{>:F;:>W=.!\{"You ran into the wumpus"|}*>P=.!\{"You fell into the pit"|}*&}if}do ``` Note that 163 was subtracted from the character count for the hard-coded strings. If you want debug output indicating the room numbers add the following line right after the first occurence of `^`: ``` ' YOU 'F'->'>+++puts' DIRECTIONS [BRL] '^`+puts' PIT 'P+puts' WUMPUS 'W+puts ``` An example session (with additional debug output): ``` YOU 6->11 DIRECTIONS [BRL] [6 7 16] PIT 7 WUMPUS 5 You feel a breeze 25 YOU 11->16 DIRECTIONS [BRL] [11 17 15] PIT 7 WUMPUS 5 35 YOU 16->11 DIRECTIONS [BRL] [16 6 7] PIT 7 WUMPUS 5 You feel a breeze 15 YOU 11->6 DIRECTIONS [BRL] [11 10 1] PIT 7 WUMPUS 5 15 YOU 6->10 DIRECTIONS [BRL] [6 15 5] PIT 7 WUMPUS 5 You smell a wumpus 14 Your arrow didn't hit anything YOU 6->10 DIRECTIONS [BRL] [6 15 5] PIT 7 WUMPUS 0 25 YOU 10->5 DIRECTIONS [BRL] [10 14 0] PIT 7 WUMPUS 0 You smell a wumpus 24 Your arrow hit the wumpus ``` [Answer] # JavaScript (ECMAScript 6) - ~~2197~~ 1759 -45% = 967.45 Characters * Version 1: [JSFIDDLE](http://jsfiddle.net/RLF7m/2/) * Version 2: [JSFIDDLE](http://jsfiddle.net/RLF7m/4/) Nearly finished golfing this... Includes a GUI with an Icosahedral Map and Mega-Bats for the full bonuses. ![Wumpus GUI](https://i.stack.imgur.com/ZYdsc.png) * Each room has 4 buttons: `X` (the Pit); `B` (the Mega-Bat); `W` (the Wumpus); and `P` (You). * Your current location is coloured blue. * The buttons are coloured red if the object it represents could be in that location and green if it is definitely not in that location. * The `W` and `P` buttons can be clicked only in the rooms adjacent to your current location. * If you win the background turns green and if you die the background turns red. **Code:** ``` P=x=>parseInt(x,36);Q=(y,a=4)=>[P(x)<<a for(x of y)];e=Q("def45c6di7ej1ai1bj2af3bf9dg8eh46b57a1gh0280390678ci9cj24g35h",0);X=Q("o6fl6afnik27bloscfaf");Y=Q("icp8i8t4jej4encjjan6");A='appendChild';C='createElement';W='width';H='height';G='background-color';L='disabled';I='innerHTML';N='className';D=document;R=Math.random;B=D.body;E=[];F=1<0;T=!F;Z="XBWP";s=D[C]('style');s.type='text/css';t='.A{position:absolute;left:25px;top:25px}.D{'+W+':50px;'+H+':50px}.D button{'+W+':25px;'+H+':25px;float:left}.R{'+G+':red}.G{'+G+':green}.B{'+G+':blue}';for(i in X)t+='#D'+i+'{left:'+X[i]+'px;top:'+Y[i]+'px}';s[A](D.createTextNode(t));D.head[A](s);c=D[C]('canvas');c[N]='A';c[W]=c[H]=500;B[A](c);x=c.getContext('2d');x.beginPath();d=(i,b,v)=>{for(j=0;j<3;j++){E[e[3*i+j]][b][L]=v}};a=(i,l,v)=>{t=F;for(j=0;j<3;j++)t=e[3*i+j]==l?T:t;if(t)M[v]++;b=E[i][v];b.c=-1;for(j=0;j<3;j++)E[e[3*i+j]][v].c+=t?1:-1;for(j of E)j[v][N]=j[v].c==M[v]?'R':'G';};M=[0,0,0];S=v=>{M[v]=0;for(i of E){i[v][N]='';i[v].c=0}};for(i in X){for(j=3*i;j<3*i+3;j++)x.moveTo(X[i],Y[i])|x.lineTo(X[e[j]],Y[e[j]]);B[A](v=D[C]('div'));v[N]='A D';v.id='D'+i;E[i]=[];for(j in Z){b=E[i][j]=v[A](D[C]('button'));b[L]=T;b.i=i;b.c=0;b[I]=Z[j];}E[i][4][O='onclick']=function(){d(P,2,T);d(P,3,T);if(this.i==W)c[N]+=' G';else{S(2);W=e[3*W+R()*3|0];if(W==P)c[N]+=' R';else{a(P,W,2);d(P,2,F);d(P,3,F)}}};E[i][3][O]=function(){d(P,2,T);d(P,3,T);E[P][3][N]='';P=this.i;if(W==P||Q==P){c[N]+=' R';return}else if(Z==P){j=P;do{P=R()*20|0}while(P==W||P==Q||P==j);do{Z=R()*20|0}while(Z==j||Z==P);S(1)}d(P,2,F);d(P,3,F);E[P][3][N]='B';a(P,Q,0);a(P,Z,1);a(P,W,2)}}x.stroke();P=R()*20|0;do{W=R()*20|0}while(W==P);do{Q=R()*20|0}while(Q==P);do{Z=R()*20|0}while(Z==P);E[P][3][N]='B';a(P,Q,0);a(P,Z,1);a(P,W,2);d(P,2,F);d(P,3,F) ``` [Answer] # Bash, 365 (first working version 726!) CATCHING UP WITH GOLFSCRIPT? **@Dennis has basically done all the golfing for me. Thanks!** The program assumes valid input. Valid input is the direction you choose (1 for right, 2 for left, 3 for back) followed by your action (4 to shoot, 5 to walk). ## Some Explanation I normally do big verbose explanations, but this is probably a bit too complicated for me to be bothered. Each vertex on the dodecahedron graph is encoded as a letter (a=1, b=2, ... t=20). The player's starting position is always 20 (and they are standing with their back to 18), since that doesn't matter in itself, only the relative positions of the player, pit and wumpus matter. The variable `$p` stores the player's location. `$r` stores the player's previous location. `$w` is the wumpus and `$h` (H for hole) is the pit. ## Code ``` p=t r=r j=echo Z=npoemfsgnohtksblbtpckdpljqnriogelfhkbqrcaiadjhagimsmjtqecrdf q(){ $j ${Z:RANDOM%19*3:1};} C(){ [[ ${!1} =~ ${!2} ]];} d(){ s=${Z:30#$1*3-30:3};} w=`q` h=`q` for((;;));{ b=$p d $p u=u${s#*$r}$s C w p&&$j The wumpus ate you&&exit C h p&&$j You fell in the pit&&exit C u w&&$j You smell the wumpus C u h&&$j You feel a breeze from a pit read i F=5 y=${u:i/10:1};C i F&&p=$y&&r=$b||{ d $w;C y w&&$j You killed the wumpus&&exit;$j You missed;w=${s:RANDOM%3:1};};} ``` ## Version History 1. Initial release, 698 chars 2. Fixed bug where "You feel a breeze" and "You smell the wumpus" can't display at the same time; saved 39 chars by making the random number generation a function. 3. Remembered that the wumpus moves if you shoot and miss. 726 chars. 4. Made `grep -oE` a variable. Saved 5 chars. 5. Made `[a-z]{3}` a variable. Saved 3 chars. 6. Made `echo` a variable. Saved 5 chars. 7. Acted on most of @Dennis 's suggestions. Saved 72 chars. 8. Added all remaining suggestions. Saved 68 chars. 9. Saved 2 chars from @DigitalTrauma 's suggestion. 10. Fixed a major bug where you can only shoot the wumpus if it is on the right. Same character count. 11. Used parameter expansion to shave off 2 chars using `$m`. 12. Shaved off a lot of chars by ditching `grep` and being slightly more sensible. 13. Defined `C` as a regexp search function to use in if statements, and `E` as a function printing "You killed the wumpus" and exiting. 14. Saved 1 char by "if statement" rearrangement. 15. Saved a lot of chars by getting rid of `d`, and removed unnecessary brackets. 16. Fixed bugs. Added lots of chars :( 17. MOARR SAVINGS (<http://xkcd.com/1296/>) 18. Another of @Dennis 's ideas (saving a few chars), and my crafty (ab)use of indirection (saving 1 char). 19. Style fix for q(). 20. re-added proper output ## Sample run "In:" is input, "Out: is output". The player wanders around for a bit, smells the wumpus and shoots. They miss, and the wumpus comes into their room and eats them. > > In: 15 > > > In: 15 > > > In: 25 > > > In: 25 > > > In: 15 > > > Out: You smell the wumpus > > > In: 14 > > > Out: You missed > > > Out: The wumpus ate you > > > [Answer] ## GolfScript (206 198) ``` [5:C,]{{.{[~@]}:>~.{-1%}:<~}%.&}8*({[.<><.<><]}:F~-{99rand}$~5,{.<{>.'You smell a wumpus.\n'4{$F@?~!!*}:Q~{print}:,~}3*{>.'You feel a breeze.\n'5Q,}3*'"#{'C):C';STDIN.gets()}"'++~~:&9/{>}*&5%{'You killed the wumpus.'3Q{\<{>}3rand*\"Your arrow didn't hit anything.\n",0}or}{\;.'You fell into the pit.'4Q}if\.'You were killed by the wumpus.'4Q@or:n!}do]; ``` Finally caught up with Dennis' lookup table version, from which it borrows quite a bit. The interesting thing about this version is that it doesn't have a lookup table for the room layout. The [60 rotational symmetries of an icosahedron](http://en.wikipedia.org/wiki/Icosahedral_symmetry) are isomorphic to the alternating group on 5 letters, A\_5. After trying all kinds of approaches to representing the group compactly, I've come back to the simplest one: each element is a permutation of even parity. The group can be generated from two generators in more than one way: the approach I'm taking uses the generators `3` and `3 1`. These allow us to generate `1 = 3 3 1`, `2 = 3 3 1 3 1`, and `3 = 3`. Observe that direction `3` corresponds to an element of order 2, because after going through the door behind you, that door is behind you again. Direction `1` corresponds to an element of order 5, walking around a vertex of the icosahedron. (Similarly element `2`). And the combination `3 1` is of order 3, as it cycles round the rooms adjacent to the one which starts out behind you. So we're looking for a permutation of order 2 to represent direction `3` and a permutation of order 5 to represent direction `1` such that `3 1` is of order 3. There are 15 permutations of order 2 in A\_5, and for each one there are 8 candidate permutations for `1` (and hence for `3 1`). There's an obvious attraction to `[4 3 2 1 0]` for `3`: reversing an array is just `-1%`. Of its possible companion permutations `3 1` I've chosen `[0 1 3 4 2]`, which admits a fairly short implementation as `[~@]`. ### Ungolfed ``` # Generate the 60 permutations by repeated application of `3 1` and `3` [5:C,]{{.{[~@]}:>~.{-1%}:<~}%.&}8* # Remove [0 1 2 3 4] and its equivalence class (apply 3 (3 1)^n 3 for n in 0,1,2) ({[.<><.<><]}:F~- # Shuffle the remaining 57 options to select random starting points for wumpus and pit # Note that this introduces a slight bias against them being in the same room, # but it's still possible. {99rand}$~ # Start player at [0 1 2 3 4] 5, { # Stack: Pit Wumpus Player .< # The adjacent rooms to the player are Player<> , Player<>> , and Player<>>> # If the wumpus is in one of those rooms, say so. { >."You smell a wumpus.\n"4 { # ... X str off $F@?~!!* # ... str off$F X ?~!! * # Which means that we leave either str (if off$ and X are equivalent) # or the empty string on the stack }:Q~ {print}:,~ }3* # Ditto for the pit {>."You feel a breeze.\n"5Q,}3* # Read one line from STDIN. '"#{'C):C';STDIN.gets()}"'++~~ # Stack: Pit Wumpus Player Player< Input # Find the room corresponding to the specified direction. :&9/{>}*& # Stack: Pit Wumpus Player TargetRoom Input 5%{ # Shoots: "You killed the wumpus."3Q { \<{>}3rand*\ # Move the wumpus to an adjacent room "Your arrow didn't hit anything.\n", # Inform 0 # Continue } or }{ # Moves: \; # If player and pit share a room, say so. ."You fell into the pit."4Q }if # If player and wumpus share a room, say so. # NB If the player walks into a room with the pit and the wumpus, # the `or` favours the pit death. \."You were killed by the wumpus."4Q@or # Save the topmost element of the stack for output if we break the loop. Loop if it's falsy. :n! }do # Ditch the junk. ]; ``` [Answer] ## [Wumpus](https://github.com/m-ender/wumpus), 384 - 129 (strings) = 255 bytes ``` 1SDL2vSD70L?.;;3AL1a!?,9)".supmuw a llems uoY"99+1. II5x?,&WC2. L2a!?,9)".ezeerb a leef uoY"93*2. L1a!,FCFC[&WCL1a!?,"!supm",AW#16#[(=]?.;;l(&o1. ?,".uoy eta ",".gnih","uw eht dellik uoY"#22&oN@ #15#L2a!?. ,"supmu","tyna tih t'ndid worra ruoY"#31&oND";"4L1a!?.;;L1xSUL1xSD=F-#81~4~?.;;;CCWC=F-#97~4~?.;;;2. ,"nto the pit."| "w ehT"l&oN@ |"i llef uoY"l2-&oN@ ``` [Try it online!](https://tio.run/##zVFdS8MwFH3vr7hLYU7tgkk7ZymjjpbBoPhSZcjwobJoi@kHbeo2Gfvr86Z17C8YuLnhJOeec2@2bV61zenE4jDi33E4vYt86nn2PGLJwLfca0KbtsrbLSQgpcgbaMtX4rq3jBrL5WTnW8NVwClcVsTPRPEjRP2uiUJ89Dz7hlNDl7YWwSJYI7fXIQOtQqz5ymT35no0e9Mu5GhYoo6uik9oW@5BqAQInj@LLMWMvkSqYCOkzL46CZPzYfn02JHAZBOz80PBIl0fyFH7IgGVpaCuik22gW1Z1wnUHdlmSA6JR5zOF3qI2C5@0Vs4W4zNB3Z0jhr2gmAVaMSdnhHsDFUKVYJKBVSZouTwNxOibT4T2Ts7kEzPsh@J5GON4g/AxOAYl@xgdgwb4x/d/QI "Wumpus – Try It Online") (Of course, TIO doesn't make a lot of sense, because you can't use the program interactively there, and once the program runs out of instructions on STDIN it will read `0 0`, which is equivalent to `3 4`, so you'll end up shooting arrows until the Wumpus moves there or kills you.) When running this locally, make sure that the linefeed after the second number of each input gets flushed (because Wumpus needs it to determine that the number is over). In Powershell, I somehow need to enter one more character after the linefeed to make it work (doesn't matter which character, but I just used double linefeeds for testing). There's a lot of room for golfing this further, but trying completely new layouts takes a while. The final score also depends a lot on the actual strings I use, because in a 2D language, a string of N bytes tends to cost you more than N bytes of source code, because it puts significant constraints on the code layout, and you often need to split it into multiple sections (incurring additional double quotes). At the extreme end, if I reduced every string to a single letter (and the -129 to -12), I'd probably be saving a ton of bytes. ### Explanation First a disclaimer: despite the language's name, it was *not* designed to make implementing *Hunt the Wumpus* particularly easy. Instead, I first designed the language around the theme of triangles, ended up with an icosahedral data structure, and decided to call it Wumpus because of that. So yeah, while Wumpus is mainly stack-based, it also has 20 registers which are arranged around the faces of an icosahedron. That means, we get a data structure to represent the map for free. The only thing we can't do easily is find specific faces on the icosahedron, so to search for them, we need to "roll the d20" until we end up on the face we're looking for. (It's possible to do this in a deterministic way, but that would take a lot more bytes.) Searching for faces like this terminates [almost surely](https://en.wikipedia.org/wiki/Almost_surely) (i.e. with probability 1), so the search running forever is not a concern in practice). The above code is a golfed version of this first implementation with a saner layout: ``` 1SDL2vSD70L?.;;2. < Setup; jumps to third line which starts the main loop 3AL1a! ?,".supmuw a llems uoY"#19&oN03. < This section checks the player's surroundings. L2a!?,".ezeerb a leef uoY"#18&oN04. AW(=12[?.;;7. }&WC#11. < This section reads the input. The top branch moves, the bottom branch shoots II5x^ and kills or moves the wumpus. {FCFC[&WCL1a !?,"!supmuw eht dellik uoY"#22&oN@ ".gnihtyna tih t'ndid worra ruoY"#31&oND#59 9L1a!?.;;L1xSUL1xSD=F-#82~9~?.;;;CCWC=F-#98~9~?.;;;#11. L1a!?,".uoy eta supmuw ehT"#19&oN@ < This section checks whether the player dies. L2a!?,".tip eht otni llef uoY"#22&oN@ Otherwise, we return back to the third line. 2. ``` Since the golfing mostly involved compressing the layout, I'll just explain this version for now (until I add any golfing tricks that go beyond restructuring the code). Let's start with the setup code: ``` 1SDL2vSD70L?.;;2. ``` Initially, all faces are set to **0**. We'll encode the wumpus by setting the 1-bit of the corresponding face, and the pit by setting the 2-bit. This way, they can both be in the same room. The player's position will not be recorded on the icosahedron at all, instead it will always be active face (only one of the 20 registers is active at a time). ``` 1S Store a 1 in the initially active face to put the wumpus there. D Roll the d20. Applies a uniformly random rotation to the icosahedron. L2vS Load the value of that face (in case it's the wumpus's), set the 2-bit and store the result back on that face. ``` Now we need to find a random empty face to put the player in. ``` D Roll the D20. 70 Push 7 and 0 which are the coordinates of the D in the program. L Load the value of the current face. ?. If that value is non-zero (i.e. the active face has either the wumpus or the pit), jump back to the D to reroll the die. ;;2. Otherwise, discard the 0 and the 7 and jump to (0, 2), which is the beginning of the main loop. ``` This next section checks the player's surroundings and prints the appropriate warnings: ``` 3AL1a! ?,".supmuw a llems uoY"#19&oN03. L2a!?,".ezeerb a leef uoY"#18&oN04. AW(=12[?.;;7. ``` This is a loop which we run through 3 times. Each time, we look at the right neighbour, print the appropriate string(s) if there's a hazard and then rotate the icosahedron by 120°. ``` 3 Push a 3 as a loop counter. A Tip the icosahedron onto the NW neighbour of the active face, which will be used to represent the right-hand room. L1a Extract the 1-bit of the value on that face. !?, If that value is zero, strafe to the next line, otherwise continue. ".supmuw a llems uoY"#19&oN03. Print "You smell a wumpus.", a linefeed and then jump to the next line. L2a Extract the 2-bit of the value on that face. !?, If that value is zero, strafe to the next line, otherwise continue. ".ezeerb a leef uoY"#18&oN04. Print "You feel a breeze.", a linefeed and then jump to the next line. A Tip back to the original active room (where the player is). W Rotate the icosahedron by 120°, so that the next iteration checks another neighbour. (= Decrement the loop counter and duplicate it. 12 Push 1, 2, the coordinates of the cell after the 3 (the loop counter). [ Pull up one copy of the loop counter. ?. If it's non-zero, jump to the beginning of the loop, otherwise continue. ;;7. Discard the 2 and the 1 and jump to (0, 7), which reads the player's input for this turn. ``` The next section reads two numbers from the player and then either moves the player or shoots an arrow. The former is trivial, the latter less so. The main issue for shooting the arrow is the case where it misses. In that case we a) need to go looking for the wumpus to move it, and then b) return to the player's room *and* the correct orientation of the icosahedron (so that "back" remains "back"). This is the most expensive part of the entire program. ``` }&WC#11. II5x^ {FCFC[&WCL1a !?,"!supmuw eht dellik uoY"#22&oN@ ".gnihtyna tih t'ndid worra ruoY"#31&oND#59 9L1a!?.;;L1xSUL1xSD=F-#82~9~?.;;;CCWC=F-#98~9~?.;;;#11. ``` The entry point to this section is the `I` on the left. ``` II Read the integers from STDIN. 5x XOR the second one with 5. ^ Turn either left or right, depending on the previous result. If the second input is 4, XORing with 5 gives 1 and the IP turns right. Otherwise, we get 0 and the IP turns left. If the player entered 5, move: } Turn right so that the IP moves east again. &W If the room indicator is X, rotate the icosahedron by X*120°. This puts the target room south of the active face (where the back room normally is). C Tip the icosahedron onto the southern face. This moves the player there. Due to the way tipping works, the formerly active face will now be the southern neighbour, i.e. correctly at the back of the player. #11. Jump to (0, 11), the final section which checks whether the player stepped into the pit or onto the wumpus. If the player entered 4, move: { Turn left so that the IP moves east again. F Store the active face index (the player's position) on the stack. CFC Also store the face index of the southern neighbour (the back room) on the stack, so that we can recover the correct orientation if we need to. [ Pull up the player's room choice. &WC Tip the icosahedron onto the corresponding face (same as for the move action) L1a Extract the 1-bit of the value on that face to check whether the arrow hit the wumpus. !?, If that value is zero, strafe to the next line, otherwise continue. "!supmuw eht dellik uoY"#22&oN@ Print "You killed the wumpus.", a linefeed, and terminate the program. ".gnihtyna tih t'ndid worra ruoY"#31&oN Print "Your arrow didn't hit anything." and a linefeed. This next bit is a loop which searches for the wumpus: D Roll the d20. The easiest way to search for the wumpus is to look at random faces. #59 9 Push 59 and 9, the coordinates of the beginning of this loop. L1a Extract the 1-bit of the value on the current face. !?. If that value is zero, jump back to the beginning of this loop to try another face, otherwise continue. ;; Discard the 9 and the 59. L1xS Unset the 1-bit of the current face to remove the wumpus there. U Tip the icosahedron onto a random neighbouring face. This moves us to a random adjacent room. L1xS Set the 1-bit of the current face to put the wumpus there. This next bit contains two loops which get us back to the player's room with the correct orientation. We do this by first searching for the room at the player's back, and then looking through its neighbours to find the player's room. D Roll the d20. =F- Duplicate the back room index and subtract the current face index. #82~9~ Push 82 and 9 and pull up the difference we just computed. ?. If the difference is non-zero (we've got the wrong room), jump back to the D to try again. Otherwise continue. ;;; We've found the back room. Discard the 9, the 82 and the back room index. C Tip the icosahedron onto the southern face (one of the candidate neighbours which might be the player's room). CWC This begins the loop that searches for the player's room. Tip onto the back room, rotate by 120°, tip back. This cycles through the neighbours of the back room, while keeping the active face on those neighbours. =F- Duplicate the player's room index and subtract the current face index. #98~9~ Push 98 and 9 and pull up the difference we just computed. ?. If the difference is non-zero (we've got the wrong room), jump back to the CWC to try again. Otherwise continue. ;;; We've found the player's room and since we entered from the back room via C, we've also got the correct orientation. Discard the 9, the 98 and the player's room index. #11. Jump to (0, 11), the final section which checks whether the player stepped into the pit or onto the wumpus. ``` Phew, that was the hard part. Now we just need to check whether the player dies and otherwise start over the main loop: ``` L1a!?,".uoy eta supmuw ehT"#19&oN@ L2a!?,".tip eht otni llef uoY"#22&oN@ 2. ``` The structure of this section is essentially identical to the structure we used when checking the player's surroundings: we check the 1-bit of the current face (the player's room) and if it's set we print `The wumpus ate you.` and terminate the program. Otherwise, we check the 2-bit and it's set we print `You fell into the pit.` and terminate the program. Otherwise we reach the `2.` which jumps back to the beginning of the main loop (at coordinates `(0, 2)`). [Answer] # awk - big This didn't turn out as short as I had hoped, but I took a slightly different approach to dealing with the graph, so I'm posting the ungolfed version anyway. I took advantage of the fact that an icosahedron (20 sided polyhedron) under rotations preserving orientation is isomorphic to the alternating group of degree 5 (5 element permutations having an even number of even length cycles). I then choose two permutations with cycle length 5 as "left" and "right", and I choose one permutation with cycle length 2 as "back". Using these, I build up the graph from one room by walking the Hamiltonian path (2xRRRLLLRLRL, using 3xRB in each room to capture the 3 possible directions). ``` function meta(z,a,b,c,d) { if(z==COMPOSE) { split(a,c,""); split(b,d,""); return c[d[1]]c[d[2]]c[d[3]]c[d[4]]c[d[5]]; } if(z==WALK) { split(R" "R" "R" "L" "L" "L" "R" "L" "R" "L,c); for(b = 1; b <= 20; b++) { map[a] = b; a = meta(COMPOSE,meta(COMPOSE,a,R),B); map[a] = b; a = meta(COMPOSE,meta(COMPOSE,a,R),B); map[a] = b; a = meta(COMPOSE,meta(COMPOSE,a,R),B); a = meta(COMPOSE, a, c[b % 10 + 1]); } } if(z==TEST) { a = map[meta(COMPOSE,U,L)]; b = map[meta(COMPOSE,U,R)]; c = map[meta(COMPOSE,U,B)]; if(a==W||b==W||c==W) print "You smell the wumpus"; if(a==P||b==P||c==P) print "You feel a breeze"; if(map[U]==W) { print "You have been eaten by the wumpus"; exit; } if(map[U]==P) { print "You have fallen into a bottomless pit"; exit; } } if(z==ARROWTEST) { if(A==W) { print "You have slain the wumpus!"; exit; } else { for(a in p) if(map[a]==W) break; W=map[meta(COMPOSE,a,v[int(rand()*3)+1])]; } } } BEGIN { COMPOSE = 0; WALK = 1; TEST = 2; ARROWTEST = 3; L = 35214; R = 35421; B = 35142; split(R" "L" "B,V); meta(WALK,L); W = int(rand()*19)+2; P = int(rand()*19)+2; U = L; meta(TEST); } { d=int($0/10); m=$0%10; if(m==5) U = meta(COMPOSE,U,V[d]); else if(m==4) { A = map[meta(COMPOSE,U,V[d])]; meta(ARROWTEST); } meta(TEST); } ``` ]
[Question] [ Your job is to draw a Bézier curve given it's control points. The only criteria is that you actually have to show how to draw the curve from the initial control point to the last one. # Criterias * The result has to be animated, e.g. it has to **show** the drawing process somehow. The way you do the animation is irrelevant, it can generate a `.gif`, it can draw to a window, or generate ASCII results (and possibly clearing the screen after each draw), etc. * It has to support at least 64 control points. * This is a popularity contest, so you might want to add some additional features to your program to get more upvotes. (My answer for example draws the control points, and some visual aid on how to generate the image as well) * The winner is the most upvoted **valid** answer 7 days after the last valid submission. * My submission doesn't count as valid. # How to draw a Bézier curve Assume we want to draw 100 iterations. To get the `n`th point of the curve you can use the following algorithm: ``` 1. Take each adjanced control point, and draw a line between them 2. Divide this line by the number of iterations, and get the nth point based on this division. 3. Put the points you've got into a separate list. Let's call them "secondary" control points. 4. Repeat the whole process, but use these new "secondary" control points. As these points have one less points at each iteration eventually only one point will remain, and you can end the loop. 5. This will be nth point of the Bézier curve ``` This might be a bit hard to understand when written down, so here are some images to help visualize it: For two control points (shown in black dots) you only have one line initally (the black line). Dividing this line by the number of iterations and getting the `n`th point will result in the next point of the curve (shown in red): ![Two points](https://i.stack.imgur.com/LT6Tu.gif) For three control points, you first have to divide the line between the first and the second control point, then divide the line between the second and third control point. You will get the points marked with blue dots. Then, as you still have two points, you have to draw a line between these two points (blue in the image), and divide them again to get the next point for the curve: ![Three points](https://i.stack.imgur.com/Qt4V0.gif) As you add more control points the algorithm stays the same, but there will be more and more iterations to do. Here is how it would look like with four points: ![Four points](https://i.stack.imgur.com/hAb8X.gif) And five points: ![Five points](https://i.stack.imgur.com/KmId1.gif) You can also check my solution, which was used to generate these images, or [read more about generating Bézier curves at Wikipedia](http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Constructing_B.C3.A9zier_curves) [Answer] Done recursively in Mathematica with no hard limits on the number control points in just three lines: ``` ctrlPts = {{0, 0}, {1, 1}, {2, 0}, {1, -1}, {0, 0}}; getLines[x_List] := Partition[x, 2, 1]; partLine[{a_, b_}, t_] := t a + (1 - t) b; f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1] ``` Showing it is more involved than the calculations!: ``` color[x_] := ColorData[5, "ColorList"][[x[[1]]]] Animate[Graphics[{PointSize[.03], , MapIndexed[{color@#2, Point/@ #1,Line@#1} &, f[ctrlPts,t]], Red, Point@Last@f[ctrlPts, t], Line@Flatten[(Last@f[ctrlPts, #]) & /@ Range[0, t, 1/50], 1]}], {t, 0, 1}] ``` Code dissection (kind of) for the calc part: ``` getLines[x_List] := Partition[x, 2, 1]; (* Takes a list of points { pt1, pt2, pt...} as input and returns {{pt1,pt2}, {pt2,pt3} ...} which are the endpoints for the successive lines between the input points *) partLine[{a_, b_}, t_] := t a + (1 - t) b;(* Takes two points and a "time" as input and calculates a linear interpolation between them*) f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1] (* This is where the meat is :) Takes a list of n points and a "time" as input. Operates recursively on the previous result n-1 times, preserving all the results Each time it does the following with the list {pt1, pt2, pt3 ...} received: 1) Generates a list {{pt1, pt2}, {pt2, pt3}, {pt3, pt4} ...} 2) For each of those sublists calculate the linear interpolation at time "t", thus effectively reducing the number of input points by 1 in each round. So the end result is a list of lists resembling: {{pt1, pt2, pt3 ...}, {t*pt1+(1-t)*pt2, t*pt2+(1-t)*pt3,..}, {t*pt12+(1-t)*pt23, ..},..} -------------- --------------- pt12 pt23 And all those are the points you see in the following image: ``` ![enter image description here](https://i.stack.imgur.com/W9k5M.gif) With a few more lines you can drag the control points interactively while the animation is running: ``` Manipulate[ Animate[Graphics[{ PointSize[.03], Point@pts, MapIndexed[{color@#2, Point /@ #1, Line@#1} &, f[pts, t]], Red, Point@Last@f[pts, t], Line@Flatten[(Last@f[pts, #]) & /@ Range[0, t, 1/50], 1]}, PlotRange -> {{0, 2}, {-1, 1}}], {t, 0, 1}], {{pts, ctrlPts}, Locator}] ``` Here dragging the green point: ![enter image description here](https://i.stack.imgur.com/HHbqx.gif) BTW, the same code runs in 3D without modifications (For the Mathematica geeks you only have to replace `Graphics[]` by `Graphics3D[]` and add a third coordinate to the control points list): ![enter image description here](https://i.stack.imgur.com/7qYg2.gif) NB: Of course this kludge isn't needed in Mathematica as there are several primitives for drawing Beziers: ``` Graphics[{BSplineCurve[ctrlPts], Green, Line[ctrlPts], Red, Point[ctrlPts]}] ``` ![Mathematica graphics](https://i.stack.imgur.com/7QZ0c.png) [Answer] # Python Certainly not the most efficient or beautiful code but it was fun to write. Run as ``` $> python thisscript.py ``` The control points are randomly generated for now but it is trivial to extend it to allow for stdin or file input. * Shows the control points * Shows the iterations * Different color for each iteration As a bonus there is an endless mode that is guaranteed to provide for entertainment for hours if not days! Matplotlib is required and ImageMagick if you want to save the resulting GIF. Tested up to 64 control points (runs very slow with a large number of points!) ![An example output gif](https://i.stack.imgur.com/D9bs5.gif) ``` import matplotlib matplotlib.use('GTkAgg') import pylab as pl from math import sin,cos,pi from random import random import os import time class Point: def __init__(self,x,y): self.x=x self.y=y def __repr__(self): return "[{:.3f},{:.3f}]".format(self.x,self.y) def __str__(self): return self.__repr__() class Path: def __init__(self,points): self.points=points def interpolate(self,u): # interpolate the path, resulting in another path with one point less in length pts = [None]*(len(self.points)-1) for i in range(1,len(self.points)): x = self.points[i-1].x + u*( self.points[i].x - self.points[i-1].x) if (self.points[i-1].x == self.points[i].x): # vertical line y = self.points[i-1].y + u*( self.points[i].y - self.points[i-1].y) else: y = self.points[i-1].y + (self.points[i].y - self.points[i-1].y)/(self.points[i].x - self.points[i-1].x)*( x - self.points[i-1].x) pts[i-1] = Point(x,y) return Path(pts) def interpolate_all(self,u): # interpolate all the paths paths = [None]*len(self.points) paths[0]=self for i in range(1,len(paths)): paths[i] = paths[i-1].interpolate(u) return paths def draw(self,ax,color,*args,**kwargs): x = [ p.x for p in self.points] y = [ p.y for p in self.points] ax.plot(x,y,*args,color=color,**kwargs) ax.scatter([p.x for p in self.points], [p.y for p in self.points],color=color) def __str__(self): return str(self.points) def bezier(path,ustep,ax,makeGif): if makeGif: os.system("mkdir -p tempgif") u=0. x=[] # x coordinate list for the bezier path point y=[] # y coordinate list for the bezier path point pl.ion() pl.show() n=0 while u < 1.+ustep: # and not u <= 1.0 to get rid of rounding errors ax.cla() paths = path.interpolate_all(u) x.append(paths[-1].points[0].x) y.append(paths[-1].points[0].y) u+=ustep for i in range(len(paths)): color = pl.cm.jet(1.*i/len(paths)) # <-- change colormap here for other colors, for a list of available maps go to http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps paths[i].draw(ax,color=color,lw=2) # draw all the paths ax.plot(x,y,color='red',lw=5) # draw the bezier curve itself pl.draw() if makeGif: pl.savefig("tempgif/bezier_{:05d}.png".format(n)) n+=1 if makeGif: print("Creating your GIF, this can take a while...") os.system("convert -delay 5 -loop 0 tempgif/*.png "+makeGif) os.system("rm -r tempgif/") print("Done.") pl.ioff() def getPtsOnCircle(R,n): x = [None]*(n+1) y = [None]*(n+1) for i in range(n+1): x[i] = R*cos(i*2.*pi/n) y[i] = R*sin(i*2.*pi/n) return x,y def getRndPts(n): x = [ random() for i in range(n) ] y = [ random() for i in range(n) ] return x,y def run(ax,x,y,makeGif=False): ctrlpoints = [ Point(px,py) for px,py in zip(x,y) ] path = Path(ctrlpoints) bezier(path,0.01,ax,makeGif) # 0.01 is the step size in the interval [0,1] def endless_mode(ax): while True: x,y = getRndPts( int(5+random()*10) ) run(ax,x,y) pl.draw() time.sleep(0.5) # pause for a moment to gaze upon the finished bezier curve def main(): fig = pl.figure(figsize=(6,6)) # <-- adjust here for figure size fig.subplots_adjust(0,0,1,1) ax = fig.add_subplot(111) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) opt = raw_input("[s]ingle run or [e]ndless mode? ") if opt=='s': gifname = raw_input("Name of output GIF (leave blank for no GIF): ") x,y = getRndPts(15) run(ax,x,y,gifname if gifname != "" else False) pl.show() elif opt=='e': endless_mode(ax) else: print("Invalid input: "+opt) main() ``` [Answer] # Postscript to generate a `gif`, make sure 'emitpages' is defined as true, and: ``` gs -sDEVICE=png16 -g500x500 -o bezan%03d.png bezanim.ps convert bezan*.png bezan.gif ``` extra features: * configurable bounding box * 2 generators: random points, randomly permuted random flattened Bezier * "overlay" animation (where it doesn't erase anything). * optional 'showpage' (use for generating `gif`s, omit for on-screen preview) Using ghostscript and larger sets of points, the on-screen preview is very different from the generated images, as you can watch the lines "converge" upon each point. simple set of points, scaled, using `png48`: ![simple point set](https://i.stack.imgur.com/v3cu6.gif) simple set with overlay: ![simple set with overlay](https://i.stack.imgur.com/5AA1q.gif) lots of points, overlay animation: ![overlay animation](https://i.stack.imgur.com/QZubd.gif) non-overlay: ![non-overlay](https://i.stack.imgur.com/Ew4mE.gif) code: ``` %! /iterations 100 def %/Xdim 612 def %/Ydim 792 def /Xdim 400 def /Ydim 400 def /scalepage { 100 100 translate %1 5 scale % "tron"? 1 3 dup dup scale div currentlinewidth mul setlinewidth } def scalepage /gen 2 def % 0:rand points 1:rand permuted bezier % 2:special list /genN 6 def % number of generated points /overlay true def /emitpages false def /emitpartials false def /.setlanguagelevel where { pop 2 .setlanguagelevel } if /pairs { % array-of-points . array-of-pairs-of-points [ exch 0 1 2 index length 2 sub { % A i 2 copy 2 getinterval % A i A_[i..i+1] 3 1 roll pop % A_[i..i+1] A } for pop ] } def /drawpairs { gsave dup 1 exch length B length div sub setgray { aload pop aload pop moveto aload pop lineto stroke %flushpage } forall %flushpage %emitpartials { copypage } if grestore } def /points { % array-of-pairs . array-of-points [ exch { % pair [ exch aload pop % p0 p1 aload pop 3 2 roll aload pop % p1x p1y p0x p0y exch % p1x p1y p0y p0x 4 3 roll % p1y p0y p0x p1x exch % p1y p0y p1x p0x 2 copy sub n mul add exch pop % p1y p0y p0x+n(p1x-p0x) 3 1 roll % p0x+n(p1x-p0x) p1y p0y 2 copy sub n mul add exch pop % p0x+n(p1x-p0x) p0y+n(p1y-p0y) ] } forall ] } def /drawpoints { gsave dup length B length div setgray { newpath aload pop 2 copy moveto currentlinewidth 3 mul 0 360 arc fill %flushpage } forall %flushpage emitpartials { copypage } if grestore } def /anim { /B exch def /N exch def /Bp B pairs def Bp drawpairs 1 0 0 setrgbcolor B 0 get aload pop moveto 0 1 N div 1 { /n exch def B { dup length 1 eq { exit } if dup drawpoints pairs dup drawpairs points } loop aload pop aload pop 2 copy gsave newpath 2 copy moveto currentlinewidth 3 mul 0 360 arc fill grestore lineto currentpoint stroke 2 copy moveto gsave count dup 1 add copy 3 1 roll moveto 2 idiv 1 sub { lineto } repeat pop stroke grestore emitpages { currentpoint currentrgbcolor overlay { copypage }{ showpage scalepage } ifelse setrgbcolor moveto }{ flushpage 10000 { 239587 23984 div pop } repeat flushpage 4000 { 239587 23984 div pop } repeat overlay not { erasepage Bp drawpairs } if %flushpage } ifelse } for moveto N { lineto } repeat stroke } def % "main": iterations [ { [ genN { [ rand Xdim mod rand Ydim mod ] } repeat ] } { 40 setflat rand Xdim mod rand Ydim mod moveto genN 1 sub 3 div ceiling cvi { 3 { rand Xdim mod rand Ydim mod } repeat curveto } repeat flattenpath [{2 array astore}dup{}{}pathforall] [exch dup 0 get exch 1 1 index length 1 sub getinterval { rand 2 mod 0 eq { exch } if } forall] 0 genN getinterval } { [ [10 10] [100 10] [100 100] [10 100] [10 40] [100 40] [130 10] [50 50] [80 50] [110 30] [20 50] [70 50] [60 50] [10 10] [40 50] [30 50] [10 30] [90 50] [10 50] [120 20] [10 20] ] 0 genN getinterval } ] gen get exec newpath anim stroke ``` [Answer] # Ruby + RMagick Additional features: * Shows the control points * Shows each iteration * Uses different colours for each iteration To use send the points from STDIN: ``` $ echo "300 400 400 300 300 100 100 100 200 400" | ./draw.rb ``` Result will be inside `result.gif`: ![Five points](https://i.stack.imgur.com/PrdUi.gif) Here is another run, with 12+1 points: ``` $ echo "100 100 200 200 300 100 400 200 300 300 400 400 300 500 200 400 100 500 0 400 100 300 0 200 100 100" | ./draw.rb ``` ![Thirteen points](https://i.stack.imgur.com/hYPen.gif) # Code This is neither golfed, nor too readable, sorry for that. `draw.rb` ``` #!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' Bundler.require(:default) ITERATIONS = 100 points = ARGF.read.split.map(&:to_i).each_slice(2).to_a result = [] def draw_line(draw,points) points.each_cons(2) do |a,b| draw.line(*a, *b) end end def draw_dots(draw,points,r) points.each do |x,y| draw.ellipse(x,y,r,r,0,360) end end canvas = Magick::ImageList.new 0.upto(ITERATIONS) do |i| canvas.new_image(512, 512) draw = Magick::Draw.new draw.stroke('black') draw.stroke_width(points.length.to_f/2) draw_line(draw,points) draw_dots(draw,points,points.length) it = points.dup while it.length>1 next_it = [] it.each_cons(2) do |a,b| next_it << [b[0]+(a[0]-b[0]).to_f/ITERATIONS * i, b[1]+(a[1]-b[1]).to_f/ITERATIONS * i] end draw.stroke("hsl(#{360/points.length.to_f*next_it.length},100,100)") draw.fill("hsl(#{360/points.length.to_f*next_it.length},100,100)") draw.stroke_width(next_it.length.to_f/2) draw_line(draw,next_it) draw_dots(draw,next_it,next_it.length) it = next_it end result << it.first draw.stroke("hsl(0,100,100)") draw.fill("hsl(0,100,100)") draw.stroke_width(points.length) draw_line(draw,result) draw_dots(draw,[it.first],points.length*2) draw.draw(canvas) end canvas.write('result.gif') ``` `Gemfile` ``` source "https://rubygems.org" gem 'rmagick', '2.13.2' ``` [Answer] ## Java Using the adaptive subdivision algorithm of [Anti Grain Geometry](http://www.antigrain.com). Code is interactive and allows the user to drag the four nodes with the mouse. ``` public class SplineAnimation extends JPanel implements ActionListener, MouseInputListener { int CANVAS_SIZE = 512; double m_distance_tolerance = 1; double m_angle_tolerance = 1; int curve_recursion_limit = 1000; public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setContentPane(new SplineAnimation()); f.pack(); f.setResizable(false); f.setLocationRelativeTo(null); f.setVisible(true); } // Graphics. BufferedImage im = new BufferedImage(CANVAS_SIZE, CANVAS_SIZE, BufferedImage.TYPE_INT_ARGB); Graphics2D imageG = im.createGraphics(); Graphics2D g = null; Ellipse2D dot = new Ellipse2D.Double(); Line2D line = new Line2D.Double(); Path2D path = new Path2D.Double(); // State. Point2D[] pts = {new Point2D.Double(10, 10), new Point2D.Double(CANVAS_SIZE / 8, CANVAS_SIZE - 10), new Point2D.Double(CANVAS_SIZE - 10, CANVAS_SIZE - 10), new Point2D.Double(CANVAS_SIZE / 2, 10)}; double phase = 0; private int dragPt; private double f; private int n = 0; public SplineAnimation() { super(null); setPreferredSize(new Dimension(CANVAS_SIZE, CANVAS_SIZE)); setOpaque(false); // Prepare stuff. imageG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); imageG.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); imageG.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); imageG.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); imageG.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); imageG.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); imageG.translate(0.5, 0.5); addMouseListener(this); addMouseMotionListener(this); // Animate! new javax.swing.Timer(16, this).start(); } @Override public void paintComponent(Graphics g) { this.g = (Graphics2D)getGraphics(); } @Override public void actionPerformed(ActionEvent e) { // Drawable yet? if (g == null) return; // Clear. imageG.setColor(Color.WHITE); imageG.fillRect(0, 0, CANVAS_SIZE + 1, CANVAS_SIZE + 1); // Update state. f = 0.5 - 0.495 * Math.cos(phase += Math.PI / 100); // Render. path.reset(); path.moveTo(pts[0].getX(), pts[0].getY()); recursive_bezier(0, pts[0].getX(), pts[0].getY(), pts[1].getX(), pts[1].getY(), pts[2].getX(), pts[2].getY(), pts[3].getX(), pts[3].getY()); path.lineTo(pts[3].getX(), pts[3].getY()); imageG.setPaint(Color.BLACK); imageG.draw(path); g.drawImage(im, 0, 0, null); // if (phase > Math.PI) // System.exit(0); // save("Bezier" + n++ + ".png"); } private void save(String filename) { paint(im.getGraphics()); try { ImageIO.write(im, "PNG", new File(filename)); } catch (IOException e) {} } // Modified algorithm from Anti Grain Geometry. // http://www.antigrain.com/research/adaptive_bezier/index.html private void recursive_bezier(int level, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { if (level > curve_recursion_limit) return; // Calculate all the mid-points of the line segments // ---------------------- double x12 = x1 + (x2 - x1) * f; double y12 = y1 + (y2 - y1) * f; double x23 = x2 + (x3 - x2) * f; double y23 = y2 + (y3 - y2) * f; double x34 = x3 + (x4 - x3) * f; double y34 = y3 + (y4 - y3) * f; double x123 = x12 + (x23 - x12) * f; double y123 = y12 + (y23 - y12) * f; double x234 = x23 + (x34 - x23) * f; double y234 = y23 + (y34 - y23) * f; double x1234 = x123 + (x234 - x123) * f; double y1234 = y123 + (y234 - y123) * f; if (level > 0) // Enforce subdivision first time { // Try to approximate the full cubic curve by a single straight line // ------------------ double dx = x4 - x1; double dy = y4 - y1; double d2 = Math.abs((x2 - x4) * dy - (y2 - y4) * dx); double d3 = Math.abs((x3 - x4) * dy - (y3 - y4) * dx); double da1, da2; if ((d2 + d3) * (d2 + d3) <= m_distance_tolerance * (dx * dx + dy * dy)) { // If the curvature doesn't exceed the distance_tolerance // value we tend to finish subdivisions. // ---------------------- // Angle & Cusp Condition // ---------------------- double a23 = Math.atan2(y3 - y2, x3 - x2); da1 = Math.abs(a23 - Math.atan2(y2 - y1, x2 - x1)); da2 = Math.abs(Math.atan2(y4 - y3, x4 - x3) - a23); if (da1 >= Math.PI) da1 = 2 * Math.PI - da1; if (da2 >= Math.PI) da2 = 2 * Math.PI - da2; if (da1 + da2 < m_angle_tolerance) { // Finally we can stop the recursion // ---------------------- path.lineTo(x1234, y1234); return; } } } // Continue subdivision // ---------------------- recursive_bezier(level + 1, x1, y1, x12, y12, x123, y123, x1234, y1234); recursive_bezier(level + 1, x1234, y1234, x234, y234, x34, y34, x4, y4); // Draw the frame. float c = 1 - (float)Math.pow(1 - Math.sqrt(Math.min(f, 1 - f)), level * 0.2); imageG.setPaint(new Color(1, c, c)); line.setLine(x1, y1, x2, y2); imageG.draw(line); line.setLine(x2, y2, x3, y3); imageG.draw(line); line.setLine(x3, y3, x4, y4); imageG.draw(line); line.setLine(x12, y12, x23, y23); imageG.draw(line); line.setLine(x23, y23, x34, y34); imageG.draw(line); node(level + 1, x1234, y1234, level == 0? Color.BLUE : Color.GRAY); } private void node(int level, double x, double y, Color color) { double r = 20 * Math.pow(0.8, level); double r2 = r / 2; dot.setFrame(x - r2, y - r2, r, r); imageG.setPaint(color); imageG.fill(dot); } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { Point mouse = e.getPoint(); // Find the closest point; double minDist = Double.MAX_VALUE; for (int i = 0; i < pts.length; i++) { double dist = mouse.distanceSq(pts[i]); if (minDist > dist) { minDist = dist; dragPt = i; } } } @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseDragged(MouseEvent e) { pts[dragPt] = e.getPoint(); } @Override public void mouseMoved(MouseEvent e) {} } ``` ![enter image description here](https://i.stack.imgur.com/Ia3ZK.gif) [Answer] ## HTML5 + Javascript + CSS So I did it long time ago (the last modified date of the file was 9/21/2012). Glad that I kept it. Unfortunately it only supports 4 control points in its current state, but I'm working on it. EDIT: Although the UI only supports 4 control points, the underlying function (`animateConstruction`) does support an arbitrary number of control points. Though I would not suggest doing it for more than 10 since the code is VERY inefficient. (I tried with 25 and had to kill the tab using Task Manager) If this counts as a valid submission I am not planning on revising the code. NOTE: I was a naive hobbyist back then. The code is wrong on so many levels (including lack of semicolons and use of `eval`). ## To Use Save the code as a .html file and open it **in Google Chrome** or [JSfiddle](http://jsfiddle.net/2deKj/1/) If you need 4 or less control points, enter the parameters on the right, then choose "Construction mode" and press "Animate" in bottom left. If you need more control points, call the `animateConstruction` function. It takes an array of coordinates (2-item arrays) as the argument. (e.g. `animateConstruction([[0,0],[500,0],[0,500]]`). Note that the draw area is 500x500, and the coordinate system follow the HTML canvas element (origin at top-left, x-axis pointing right, y-axis pointing down) For the fiddle, I have added a text box bottom-left. Enter semicolon-separated coordinates (default value is an example) and press Go. ## Differences in Fiddle version * The textbox * Default animation steps reduced to 100 * Secondary curves are off by default ## Code ``` <html> <head> <style> span.h{ display: inline-block; text-align: center; text-decoration: underline; font: bold 1em Arial; } input[type="color"]{ -webkit-appearance: button-bevel; vertical-align: -7px; width: 21px; height: 27px; } input[type="color"][disabled]{background: #FFF} td{position:relative; padding:1px; text-align:center} table[class] td{text-align:left} td.t{padding:1px 5px; width:46px;} table input[type="checkbox"]{visibility:hidden} tr:hover input[type="checkbox"]{visibility:visible} </style> <script type='text/javascript'> function Bezier(c){ if(c.length==2) return function(t){return [c[0][0]+t*(c[1][0]-c[0][0]),c[0][1]+t*(c[1][1]-c[0][1])]} else return function(t){return Bezier([Bezier(c.slice(0,-1))(t),Bezier(c.slice(1))(t)])(t)} } function Bezier2(f1,f2){ return function(t){return Bezier([f1(t),f2(t)])(t)} } //============================================ var c = null var settings = {'guide':{'show':[true,true,true,true], 'color':['#EEEEEE','#00FF00','#0000FF','#FF00FF'], 'width':[10,1,1,1]}, 'curve':{'show':[true,true,true,true], 'color':['#EEEEEE','#00FF00','#0000FF','#FF00FF'], 'width':[10,3,3,3]}, 'main':{'show':true, 'color':'#FF0000', 'width':10}, 'sample': 100, 'steps':200, 'stepTime':10, 'mode':'Bezier', 'coords':[[0,500],[125,450],[125,0],[500,0]]} var itv = 0 window.addEventListener('load',function(){ c = $('c').getContext('2d') c.lineCap = 'round' c.lineJoin = 'round' draw(settings.coords,1) },true) function get(k,i){ var t = settings if(k.constructor == Array) k.forEach(function(e){t = t[e]}) return t.length>i ? t[i] : t.slice(-1)[0] } function frame(coords){ c.strokeStyle = settings.curve.color[0] c.lineWidth = settings.guide.width[0] c.beginPath() c.moveTo.apply(c,coords[0]) coords.slice(1).forEach(function(e){c.lineTo.apply(c,e)}) c.stroke() } function transf(c){ var t = [] c.forEach(function(e){t.push([e[0]+5,e[1]+5])}) return t } //============================================ function drawBezier(coords,t){ if(t===undefined) t = 1 coords = transf(coords) c.clearRect(0,0,510,510) frame(coords) c.beginPath() c.strokeStyle = settings.main.color c.lineWidth = settings.main.width c.moveTo.apply(c,coords[0]) for(var i=0;i<=t*settings.sample;i++) c.lineTo.apply(c,Bezier(coords)(i/settings.sample)) c.stroke() } function animateBezier(coords){ var s = settings.steps var cur = ($('t').value==1 ? ($('t').value=$('T').innerHTML=(0).toFixed(3))*1 : $('t').value*s)+1 var b = drawBezier(coords,$('t').value*1) itv = setInterval(function(){ $("T").innerHTML = ($("t").value = cur/s).toFixed(3) drawBezier(coords,cur++/s,b) if(cur>s) clearInterval(itv) },settings.stepTime) } //============================================ function drawBezier2(coords,t){ if(t===undefined) t = 1 c.beginPath() c.strokeStyle = get(['curve','color'],coords.length-1) c.lineWidth = get(['curve','width'],coords.length-1) c.moveTo.apply(c,coords[0]) for(var i=0;i<=t*100;i++) c.lineTo.apply(c,Bezier(coords)(i/100)) c.stroke() } function drawConstruction(coords,t,B){ coords = transf(coords) if(t===undefined) t = 0.5 var b = B===undefined ? [[]] : B coords.forEach(function(e){b[0].push(function(t){return e})}) c.clearRect(0,0,510,510) frame(coords) for(var i=1;i<coords.length;i++){ if(B===undefined) b.push([]) with(c){ for(var j=0;j<coords.length-i;j++){ if(B===undefined) b[i].push(Bezier2(b[i-1][j],b[i-1][j+1])) if(i!=coords.length-1 && get(['curve','show'],i-1) || i==coords.length-1 && settings.main.show){ strokeStyle = i==coords.length-1?settings.main.color:get(['curve','color'],i-1) lineWidth = i==coords.length-1?settings.main.width:get(['curve','width'],i-1) beginPath() moveTo.apply(c,b[i][j](0)) for(var k=0;k<=t*settings.sample;k++) lineTo.apply(c,b[i][j](k/settings.sample)) stroke() } if(i && i!=coords.length-1 && get(['guide','show'],i)){ strokeStyle = i==coords.length-1?settings.main.color:get(['guide','color'],i) lineWidth = i==coords.length-1?settings.main.width:get(['guide','width'],i) beginPath() if(i!=coords.length-1) arc.apply(c,b[i][j](t).concat([settings.curve.width[0]/2,0,2*Math.PI])) stroke() } } if(i && i!=coords.length-1 && get(['guide','show'],i)){ beginPath() moveTo.apply(c,b[i][0](t)) for(var j=1;j<coords.length-i;j++) lineTo.apply(c,b[i][j](t)) stroke() } } } return b } function animateConstruction(coords){ var s = settings.steps var cur = ($('t').value==1 ? ($('t').value=$('T').innerHTML=(0).toFixed(3))*1 : $('t').value*s)+1 var b = drawConstruction(coords,$('t').value*1) itv = setInterval(function(){ $("T").innerHTML = ($("t").value = cur/s).toFixed(3) drawConstruction(coords,cur++/s,b) if(cur>s) clearInterval(itv) },settings.stepTime) } //============================================ function draw(coords,t){clearInterval(itv); return window['draw'+settings.mode](coords,t)} function animate(coords){clearInterval(itv); return window['animate'+settings.mode](coords);} //============================================ function $(id){return document.getElementById(id)} function v(o,p){ for(var i in o){ var k = (p||[]).concat([i]).join('-') var t if((t = o[i].constructor) == Object || t == Array) v(o[i],[k]) else if(t = $(k)){ if(t.type=='checkbox') t.checked = o[i] else if(t.type=='radio'){ for(var j=0, t=document.getElementsByName(t.name); j<t.length; j++) if(t[j].value == o[i]){ t[j].checked = true break } }else t.value = o[i] }else if(t = $((i==0?'x':'y') + p[0].slice(-1))) t.value = o[i] } } document.addEventListener('load',function(){ v(settings) $('t').setAttribute('step',1/settings.steps) var t = document.getElementsByTagName('input') for(i=0;i<t.length;i++) t[i].addEventListener('change',function(){ var t if((t=this.id.split('-')).length > 1){ var t1 = function(T){ var t = 'settings' T.forEach(function(e){t += '[' + (isNaN(e)?'"'+e+'"':e) +']'}) eval(t + '=' + (this.type=='text'?this.value:(this.type=='checkbox'?this.checked:'"'+this.value+'"'))) $(T.join('-')).value = this.value } t1.call(this,t) if(t[0]=='curve' && t[1]=='color' && $('u').checked==true) t1.call(this,['guide'].concat(t.slice(1))) }else if(this.id == 'u'){ for(i=0;t=$('guide-color-'+i);i++){ t.disabled = this.checked t.value = settings.guide.color[i] = this.checked?settings.curve.color[i]:t.value } }else if(this.id == 't'){ $('T').innerHTML = (this.value*1).toFixed(3) draw(settings.coords,this.value*1) }else if(t = /([xy])(\d+)/.exec(this.id)) settings.coords[t[2]*1][t[1]=='x'?0:1] = this.value*1 else settings[this.id] = this.value if(this.id == 'steps') $("t").setAttribute("step",1/settings.steps) },true) },true) </script> </head> <body> <canvas style='float:left' width='510' height='510' id='c'> </canvas> <div style='padding-left:550px; font-family:Arial'> <span class='h' style='width:123px'>Control Points</span><br /> (<input type='text' id='x0' size='3' maxlength='3' />,<input type='text' id='y0' size='3' maxlength='3' />)<br /> (<input type='text' id='x1' size='3' maxlength='3' />,<input type='text' id='y1' size='3' maxlength='3' />)<br /> (<input type='text' id='x2' size='3' maxlength='3' />,<input type='text' id='y2' size='3' maxlength='3' />)<br /> (<input type='text' id='x3' size='3' maxlength='3' />,<input type='text' id='y3' size='3' maxlength='3' />)<br /><br /> <span class='h' style='width:200px'>Appearance</span><br /> <span style='font-weight:bold'>Guide lines</span><br /> <input type='checkbox' checked='checked' id='u' onchange='' /> Use curve colors<br /> <table style='border-collapse:collapse'> <tr><td><input type='checkbox' id='guide-show-0' /></td><td><input type='color' id='guide-color-0' disabled='disabled' /></td><td class='t'>Frame</td><td><input type='text' id='guide-width-0' size='2' maxlength='2' /></td></tr> <tr><td><input type='checkbox' id='guide-show-1' /></td><td><input type='color' id='guide-color-1' disabled='disabled' /></td><td class='t'>1</td><td><input type='text' id='guide-width-1' size='2' maxlength='2' /></td></tr> <tr><td><input type='checkbox' id='guide-show-2' /></td><td><input type='color' id='guide-color-2' disabled='disabled' /></td><td class='t'>2</td><td><input type='text' id='guide-width-2' size='2' maxlength='2' /></td></tr> <tr><td><input type='checkbox' id='guide-show-3' /></td><td><input type='color' id='guide-color-3' disabled='disabled' /></td><td class='t'>3</td><td><input type='text' id='guide-width-3' size='2' maxlength='2' /></td></tr> </table> <span style='font-weight:bold'>Curves</span> <table style='border-collapse:collapse'> <tr><td><input type='checkbox' id='curve-show-0' /></td><td><input type='color' id='curve-color-0' /></td><td class='t'>1</td><td><input type='text' id='curve-width-0' size='2' maxlength='2' /></td></td></tr> <tr><td><input type='checkbox' id='curve-show-1' /></td><td><input type='color' id='curve-color-1' /></td><td class='t'>2</td><td><input type='text' id='curve-width-1' size='2' maxlength='2' /></td></td></tr> <tr><td><input type='checkbox' id='curve-show-2' /></td><td><input type='color' id='curve-color-2' /></td><td class='t'>3</td><td><input type='text' id='curve-width-2' size='2' maxlength='2' /></td></td></tr> <tr><td><input type='checkbox' id='curve-show-3' /></td><td><input type='color' id='curve-color-3' /></td><td class='t'>4</td><td><input type='text' id='curve-width-3' size='2' maxlength='2' /></td></td></tr> <tr><td><input type='checkbox' id='main-show' /></td><td><input type='color' id='main-color' /></td><td class='t'>Main</td><td><input type='text' id='main-width' size='2' maxlength='2' /></td></td></tr> </table><br /> <span class='h' style='width:300px'>Graphing & Animation</span><br /> <table class> <tr><td>Sample points:</td><td><input type='text' id='sample' /></td></tr> <tr><td>Animation steps:</td><td><input type='text' id='steps' /></td></tr> <tr><td>Step time:</td><td><input type='text' id='stepTime' />ms</td></tr> </table> <div style='position:absolute; top:526px; left:8px; width:510px; height:100px;'> <input type='range' id='t' max='1' min='0' style='width:450px' value='1' />&nbsp;&nbsp;&nbsp;<span id='T' style='vertical-align: 6px'>1.000</span><br /> <input type='button' onclick='draw(settings.coords,$("t").value*1)' value='Draw' /><input type='button' onclick='animate(settings.coords)' value='Animate' /> <input type='radio' id='mode' name='mode' value='Bezier' />Basic Mode <input type='radio' id='mode' name='mode' value='Construction' />Construction Mode </div> </body> </html> ``` [Answer] # Perl + PerlMagick ``` use strict; use Image::Magick; sub point { my ($image, $f, $x, $y, $r) = @_; $image->Draw(fill => $f, primitive => 'circle', points => $x . ',' . $y . ',' . ($x + $r) . ',' . $y); } sub line { my ($image, $f, $x1, $y1, $x2, $y2, $w) = @_; $image->Draw(fill => 'transparent', stroke => $f, primitive => 'line', strokewidth => $w, points => "$x1,$y1,$x2,$y2"); } sub colorize { my $i = shift; return ((sin($i * 6) + 0.5) * 255) . ',' . ((sin($i * 6 + 2) + 0.5) * 255) . ',' . ((sin($i * 6 + 4) + 0.5) * 255); } sub eval_bezier { my $p = shift; my @x = @_; my @y; for my $i (0 .. $#x - 1) { $y[$i] = $x[$i] * (1 - $p) + $x[$i + 1] * $p; } return @y; } sub render_bezier { my (%args) = @_; my $seq = $args{sequence}; for my $q (0 .. $args{frames} - 1) { my $p = $q / ($args{frames} - 1); my @x = @{$args{xpoints}}; my @y = @{$args{ypoints}}; my $amt = @x; my $image = Image::Magick->new(size => $args{size}); $image->ReadImage('xc:black'); for my $i (0 .. $amt - 1) { for my $j (0 .. $#x - 1) { line($image, 'rgba(' . (colorize $i / $amt). ', 0.5)', $x[$j], $y[$j], $x[$j+1], $y[$j+1], 4 * 0.88 ** $i) } for my $j (0 .. $#x) { point($image, 'rgba(' . (colorize $i / $amt). ', 1.0)', $x[$j], $y[$j], 4 * 0.88 ** $i); } @x = eval_bezier $p, @x; @y = eval_bezier $p, @y; } my ($ox, $oy) = ($x[0], $y[0]); for my $q (0 .. $q) { my $p = $q / ($args{frames} - 1); my @x = @{$args{xpoints}}; my @y = @{$args{ypoints}}; for (0 .. $amt - 2) { @x = eval_bezier $p, @x; @y = eval_bezier $p, @y; } line($image, 'rgba(255, 255, 255, 1.0)', $x[0], $y[0], $ox, $oy, 2); ($ox, $oy) = ($x[0], $y[0]); } push @$seq, $image; } } my @x = (10,190,40,190); my @y = (190,30,10,110); my $gif = Image::Magick->new; render_bezier(xpoints => \@x, ypoints => \@y, sequence => $gif, size => '200x200', frames => 70); $gif->Write(filename => 'output.gif'); ``` Example of output: ![](https://i.stack.imgur.com/WrsJx.gif) Other outputs can be seen in [this imgur album](https://i.stack.imgur.com/2emkM.jpg) ]
[Question] [ Given a string that is one of the directions on a 16-point compass rose [![16-point compass rose](https://i.stack.imgur.com/hPCWAm.png)](https://en.wikipedia.org/wiki/Points_of_the_compass#/media/File:Compass_Rose_English_North.svg) output the two directions that are immediately adjacent to the input direction, in clockwise order. Specifically, you need to handle these (and only these) input/output pairs: ``` Input Output N NNW NNE NNE N NE NE NNE ENE ENE NE E E ENE ESE ESE E SE SE ESE SSE SSE SE S S SSE SSW SSW S SW SW SSW WSW WSW SW W W WSW WNW WNW W NW NW WNW NNW NNW NW N ``` The output may be a string with some delimiter (not nothing) between the directions or a two-element list. The direction immediately counterclockwise to the input must appear first. You may use lowercase letters for the directions instead of uppercase but keep all input and output in one case or the other. For example, for input `N` (or `n` if you're using lowercase) some valid outputs are: ``` NNW NNE NNW-NNE ["NNW", "NNE"] nnw-nne (if using lowercase) ``` Some invalid outputs are: ``` NNWNNE NNE NNW nnwNNE NNw NNe ``` **The shortest code in bytes wins.** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 34 bytes ``` “¢ ¬9£Hæz¥{çb¤S®!‘ṃ€“¡&¦» ¢iµ’,‘ị¢ ``` [Try it online!](https://tio.run/nexus/jelly#AUwAs///4oCcwqIgwqw5wqNIw6Z6wqV7w6diwqRTwq4h4oCY4bmD4oKs4oCcwqEmwqbCuwrComnCteKAmSzigJjhu4vCov/Dh8WS4bmY//9u "Jelly – TIO Nexus") Takes lowercase input. *-2 thanks to [Jonathan Allan](/u/53748).* *-1 since it turns out this is valid as a function :)* Thanks to Jonathan Allan (and Dennis), now you can remove the `€`. Unfortunately, that would be non-competing here. **Detailed algorithm explanation**: We usually start explaining from the bottom (main) link, going down, but here I feel like it's more appropriate to explain from the top. First, we simply load up the list `[1, 32, 7, 57, 2, 67, 17, 92, 3, 94, 19, 119, 4, 109, 9, 34]`. This looks like random numbers huh? Well, this is actually a list of base-5-compressed numbers, so we base-5-decompress it. Now it looks like `[[1], [1, 1, 2], [1, 2], [2, 1, 2], [2], [2, 3, 2], [3, 2], [3, 3, 2], [3], [3, 3, 4], [3, 4], [4, 3, 4], [4], [4, 1, 4], [1, 4], [1, 1, 4]]`. Still random-looking stuff, but this is actually an `NESW`-mapped list of the sixteen coordinates, so we're not far away from completing the list (Jelly is 1-indexed). Doing the final mapping, we get `[['N'], ['N', 'N', 'E'], ['N', 'E'], ['E', 'N', 'E'], ['E'], ['E', 'S', 'E'], ['S', 'E'], ['S', 'S', 'E'], ['S'], ['S', 'S', 'W'], ['S', 'W'], ['W', 'S', 'W'], ['W'], ['W', 'N', 'W'], ['N', 'W'], ['N', 'N', 'W']]`, which is the complete list we want (Jelly strings are in the form `[char1, char2, char3, ...]`.) Since we've now built the coordinate list, we work with it. The main link comes into play. First, we load up the list we've built, and then take the index that the input (as command-line argument) coordinate resides in. Then, we pair its predecessor and its successor into a list, and we use them as modular indices into the same list of coordinates to take the coordinate to the left and right of the input respectively. You'd now think we're finally done, but there's in fact one more thing, the separator. This is valid as a function, since 1) You can call it using `<integer>Ŀ` 2) You're allowed to define other functions as well (like importing modules). Now, we are done. As a full program, this doesn't have a separator, but that's OK, since it works as a function. **Link-by-link code explanation**: ``` ¢iµ’,‘ị¢K Main link. Arguments: z = cmd0 ¢ Run the helper link niladically (i.e. load the coordinate list). i Find the index of z in the list. µ Start a new monadic chain. Arguments: z = list_index. ’ Decrement z. ‘ Increment z. , Pair x and y into [x, y]. ¢ Run the helper link niladically. ị Take the elements of y at the indices in x. “¢ ¬9£Hæz¥{çb¤S®!‘ṃ€“¡&¦» Helper link. Arguments: [1, 32, 7, 57, 2, 67, 17, 92, 3, 94, 19, 119, 4, 109, 9, 34] “¢ ¬9£Hæz¥{çb¤S®!‘ Generate the integer list (the argument). “¡&¦» Literal "newsy". ṃ€ Base-length(y)-decompress every integer in x, then index into y. ``` [Answer] # Mathematica, ~~118~~ 112 bytes *Thanks to Martin Ender for saving 6 bytes!* ``` r=StringSplit@"N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N NNE";<|Array[r[[#]]->r[[#+{-1,1}]]&,16,2]|> ``` Unnamed function (an association, really) that takes a string as input and returns an ordered pair of strings. Basically just hardcodes the answer. [Answer] # Python 2, ~~116~~ ~~115~~ 103 bytes *-12 bytes thanks to Neil* ``` d='N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW'.split() n=d.index(input()) print d[n-1],d[n-15] ``` [Try it Online!](https://tio.run/nexus/python2#@59iq@6n4OfnqgBEriCs4BrsqgBCIAwkwxWAKByEFcL9whVAyC9cXa@4ICezREOTK882RS8zLyW1QiMzr6AUKKLJVVCUmVeikBKdp2sYqwOmTGP//1cHaQMA) [Answer] # JavaScript ES6, ~~106~~ 102 bytes ``` p=>[(a=`N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW`.split`|`)[i=a.indexOf(p)-1&15],a[i+2&15]] ``` ### Try it online! ``` const f = p=>[(a=`N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW`.split`|`)[i=a.indexOf(p)-1&15],a[i+2&15]] console.log(f('N')) console.log(f('NNE')) console.log(f('ENE')) console.log(f('E')) console.log(f('ESE')) console.log(f('SE')) console.log(f('SSE')) console.log(f('S')) console.log(f('SSW')) console.log(f('SW')) console.log(f('WSW')) console.log(f('W')) console.log(f('WNW')) console.log(f('NW')) console.log(f('NNW')) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~44~~ 43 bytes (Thanks to Adnan) ``` "ESNW4"•2ßU^]>Þ‡¾“¾&é{½‡•5BSè4¡©skD<®ès>®è) ``` [Try it online!](https://tio.run/nexus/05ab1e#@6/kGuwXbqL0qGGR0eH5oXGxdofnPWpYeGjfo4Y5h/apHV5ZfWgvkA@UNnUKPrzC5NDCQyuLs11sDq07vKLYDkRq/v8fDAA "05AB1E – TIO Nexus") ``` "ESNW4"•2ßU^]>Þ‡¾“¾&é{½‡•5BSè # Push N4NNE4NE4ENE4E4ESE4SE4SSE4S4SSW4SW4WSW4W4WNW4NW4NNW 4¡© # Split on 4's and store. sk # Index of input in direction array. D<®è # Element before index of input. s>®è # Element after index of input. ) # Wrap two element to array. ``` Exmaple output: ``` N => [NNW,NNE] ``` --- Version that pushes `N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW` instead: ``` •17¿$Mn]6VAÆ—Dªd—•5B4LJ"NSWE"‡0¡©skD<®ès>®è) ``` Is also 44-bytes, there was 0 reason for my refactor and there is 0 reason for splitting on the 4's. --- [Answer] # Javascript - ~~234~~ ~~154~~ ~~156~~ ~~152~~ ~~120~~ ~~106~~ 102 bytes Only my second time doing code golf!! Latest Revision: Thank you to @fəˈnɛtɪk for this neat variable trick! ``` s=>[(a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `)[n=a.indexOf(s)-1&15],a[n+2&15]] ``` Before That: Okay so latest revision: Input is a string and output is a string which is in the rules, so I made it into a function, and with reductions I have gone even smaller (also function is anonymous, which now means mine has somehow meshed into the other js answer oops! He (powelles) had it first!!): ``` (s,a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `,n=a.indexOf(s))=>[a[n-1&15],a[n+1&15]] ``` Can be used by: ``` f=(s,a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `,n=a.indexOf(s))=>[a[n-1&15],a[n+1&15]] alert(f(prompt())) ``` Remade (not function) with Output - 120: ``` a="NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW".split(' ');n=a.indexOf(prompt());alert(a[n-1&15]+' '+a[n+1&15]); ``` * Note that I made an error originally, having it equal a.length instead of a.length-1 for the first index. Thanks @Neil for pointing out that it didn't work for NNW. * Note 2: Thank you to @Neil and @ETHProductions for helping me shorten the code! Originial: ``` a="NNWN NNENE ENEE ESESE SSES SSWSW WSWW WNWNW ";l=prompt("","");n=l.length<3?l.length<2?l+' ':l+' ':l;f=a.indexOf(n);i=f-3;j=f+3;i=i<0?a.length+--i:i;j=j+3>=a.length?j-a.length:j;alert(a.substring(i,i+3)+' '+a.substring(j,j+3)); ``` [Answer] ## Batch, 196 bytes ``` @set s=N @if %1==N echo NNW @for %%r in (NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW)do @call:c %1 %%r @if %1==NNW echo N @exit/b :c @if %1==%2 echo %s% @if %1==%s% echo %2 @set s=%2 ``` Loops through each pair of compass points, printing one when the other matches. For example, for a parameter of `ENE`, when the loop reaches `ENE`, the variable `s` contains `NE` which is printed, then when the loop advances to `E`, the variable `s` contains `ENE` and so `E` is printed. One pair then needs to be special-cased to avoid the compass points from being printed in the wrong order. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~40~~ 38 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “NSWE”“dḍ.ƈ€ḶƘfƥ’ṃṁ “¢)`)’ḃ3RÇṙi¥µṖṪ,Ḣ ``` **[Try it online!](https://tio.run/nexus/jelly#@/@oYY5fcLjro4a5QFbKwx29esc6HjWtebhj27EZaceWPmqY@XBn88OdjVxA6UOLNBM0QSI7mo2DDrc/3Dkz89DSQ1sf7pz2cOcqnYc7Fv0/3B75/78fAA)** (added the footer to show the output is a list of two items) ...or see [all cases](https://tio.run/nexus/jelly#@/@oYY5fcLjro4a5QFbKwx29esc6HjWtebhj27EZaceWPmqY@XBn88OdjVxA6UOLNBM0QSI7mo2DDrc/3Dkz89DSQ1sf7pz2cOcqnYc7Fv0/uudwexbQLF0VFaAh7v//R6v7qeuo@/m5gkgQ4QohQTgYREIICAlmhYNIEBEOIUHYD0RCCCAZCwA). (I'm not quite sure why `1323DRẋ4` in place of `“¢)`)’ḃ3R` doesn't work at the moment.) ### How? ``` “NSWE”“dḍ.ƈ€ḶƘfƥ’ṃṁ - Link 1, rose list helper: shape array “NSWE” - "NSWE" “dḍ.ƈ€ḶƘfƥ’ - base 250 number: 1554210846733274963415 ṃ - base decompress: "NNNENEENEEESESESSESSSWSWWSWWWNWNWNNW" ṁ - mould like shape array “¢)`)’ḃ3RÇṙi¥µṖṪ,Ḣ - Main link: direction string “¢)`)’ - base 250 number: 33899292 ḃ3 - to base 3: [1,3,2,3,1,3,2,3,1,3,2,3,1,3,2,3] R - range (vectorises) [[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3]] Ç - call the last link (1) as a monad: ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"] ¥ - last two links as a dyad ṙ - rotate the list by: i - index of the direction string in the list µ - monadic chain separation (call the rotated list x) Ṗ - pop (x[:-1]) (removes the direction string) Ṫ - tail that (i.e. x[-2]) Ḣ - head x (i.e. x[0]) , - pair ``` [Answer] # [Haskell](https://www.haskell.org/), ~~100~~ 99 bytes ``` s=words"N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW"++s (a:b:c:r)#x|x==b=(a,c)|1<3=r#x (s#) ``` [Try it online!](https://tio.run/nexus/haskell#Jc0xC4MwEIbh3V9xxCWhUijdpDdm7C0ON5QO0YI4aCUp1MH/bvM18L0Pt92R@PuOr2SERDzleUS@84ShrFKeIlJRwkTN6ZQqG9q@Hdro6m3fmHu2oRncfrldOdZbNbJNtTvmMC3ENIf1TnaN0/I5j44eRkxj8l8IfBF1sFD8XwqBFpHAQvZ5/AA "Haskell – TIO Nexus") Calling `(s#) "N"` returns `("NNW","NNE")`. `s` is an infinite repetition of the list of directions, thus we don't have to add an extra `N` and `NNE` like some of the other answers to correctly handle the edges of the list. Thanks to @nimi for saving one byte! [Answer] # [SOGL](https://github.com/dzaima/SOGL), 33 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ≠┐πΜ]ρ½d⁹V¹-┐*╔╤¹Ψæ;¶‘θ,W:AHwOaIw ``` The first part `≠┐πΜ]ρ½d⁹V¹-┐*╔╤¹Ψæ;¶‘` is a compressed string that is ``` N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW ``` compressed with a custom dictionary with `ENSW` The rest of the program: ``` ...‘θ,W:AHwOaIw example input: NNW ...‘ push the compressed string ["N NNE NE ... NNW"] θ split on spaces [["N","NNE",...,"NNW"]] ,W get the index of input [["N","NNE",...,"NNW"], 16] :A save the index on variable A [["N","NNE",...,"NNW"], 16] H decrease [the index] [["N","NNE",...,"NNW"], 15] wO output that'th item of the array [["N","NNE",...,"NNW"]] a load variable A [["N","NNE",...,"NNW"], 16] I increase [the index] [["N","NNE",...,"NNW"], 17] w get that item in the array [["N","NNE",...,"NNW"], "N"] ``` [Answer] # PHP, 122 bytes ``` preg_match("/([^ ]+ )$argv[1] ([^ ]+)/",'N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N NNE',$m); echo $m[1].$m[2]; ``` [Answer] # Ruby - 94 Bytes A riff on [Blue Okiris's answer](https://codegolf.stackexchange.com/a/116548), just to take advantage of some nice Ruby shorthand (the `%w[]` syntax and `p` specifically): ``` ->(s,d=%w[N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW],n=d.index(s)){p d[n-1],d[n-15]} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 66 52 bytes *Saved 14 bytes thanks to @ETHproductions* ``` V=`ã@JaÀTeaÀÄsÁÁss°s°ws°°wn°n°nnw`qa [J1]£VgX+VaU ``` [Try it online!](https://tio.run/nexus/japt#@x9mm3B4sYPXoabEww0hqUDicEvx4UbRw41ixcWHNgBRORADybxDG0AorzyhMFEh2ssw9tDisPQI7bDE0P//lfLKlQA) ### Explanation: ``` V=(`...`qa) [J1]£Vg(X+VaU) V=( ) // Set V to: `...` // "nanneaneaeneaeaeseaseasseasasswaswawswawawnwanwannw" (de-)compressed qa // Split on "a", creating [n...nnw] [J1] // [-1,1] £ // Iterate through ^, X becomes the iterative item Vg( ) // V.Item at index: X+VaU // X + V.indexOf(input) ``` [Answer] # CJam, 41 ``` "NeSWN"2ew{_1<\_La*\$f+~}%:eu_ra#(m<2%2<p ``` [Try it online](http://cjam.aditsu.net/#code=%22NeSWN%222ew%7B_1%3C%5C_La*%5C%24f%2B~%7D%25%3Aeu_ra%23(m%3C2%252%3Cp&input=N) [Answer] # PHP, 115 Bytes ``` for($r=explode(_,($w=N_NNE_NE_ENE_E_ESE_SE_SSE_).strtr($w,SWNE,NESW).$w);$r[++$i]!=$argn;);echo$r[$i-1]._.$r[$i+1]; ``` -2 Bytes using the deprecated function `split` instead of `explode` ## PHP, 128 Bytes ``` for($i=2;$i--;print$i?end($e)._:$e[2])$e=explode(_,strstr(($w=N_NNE_NE_ENE_E_ESE_SE_SSE_).strtr($w,SWNE,NESW).$w,_.$argn._,$i)); ``` ## PHP, 134 Bytes ``` echo($r=explode(_,N_NNE_NE_ENE_E_ESE_SE_SSE_S_SSW_SW_WSW_W_WNW_NW_NNW))[($k=array_search($argn,$r))-1<0?15:$k-1]._.$r[$k+1>15?0:$k+1]; ``` [Answer] # PHP, 110 109 bytes Saved 1 byte thanks to [Jörg Hülsermann](https://codegolf.stackexchange.com/users/59107/j%c3%b6rg-h%c3%bclsermann). ``` echo@preg_filter("/.*?(\w+) $argn( \w+).*/",'$1$2',($s='N NNE NE ENE E ESE SE SSE ').strtr($s,NESW,SWNE).$s); ``` [Answer] # **Python 3 - ~~112~~ 107 bytes** I based this off of my Javascript answer: Remade: ``` lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1],s[s.index(i)-15]] ``` Use as say ``` f = lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1],s[s.index(i)-15]] print(f(input())); ``` Original: ``` lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1&15],s[s.index(i)+1&15]] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 43 bytes ``` ';evl(Z?&fWElf`gvhM'F' NESW'ZaYbtjY=fFTEq+) ``` [Try it online!](https://tio.run/nexus/matl#@69unVqWoxFlr5YW7pqTlpBeluGr7qau4OcaHK4elRiZVJIVaZvmFuJaqK35/78fAA "MATL – TIO Nexus") ### Explanation ``` ';evl(Z?&fWElf`gvhM' % Push this string F % Push false ' NESW' % Push this string Za % Base conversion. This decompresses the first string from alphabet % given by all printable ASCII except single quote to the alphabet % ' NESW'. The result is the following string, which is pushed: % 'N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW' Yb % Split at spaces. Gives a cell array of strings t % Duplicate j % Input string Y= % String comparison. Gives an array containing true at the index % of the matching string f % Find: index of the entry that equals true FTEq % Push [-1 1] (obtained as [false true], times 2, minus 1) + % Add, element-wise ) % Index modularly into the cell array of strings % Implicitly display. Each cell is displayed on a different line ``` [Answer] ## c, ~~222~~ ~~216~~ 211 bytes ``` main(c,v)char**v;{char r[]="NXNNEXNEXENEXEXESEXSEXSSEXSXSSWXSWXWSWXWXWNWXNWXNNWX",*p=r,*s=r,*a[16],i=0,n;for(;*p++;)*p==88?*p=0,n=strcmp(a[i++]=s,v[1])?n:i-1,s=++p:0;printf("%s %s\n",a[n?n-1:15],a[n<15?n+1:0]);} ``` [Try it online](https://tio.run/nexus/c-gcc#FYo9C8MgFEX/ShAKfgXikBJiJZOrSwcF6yCBUIdY0ZCl9LenCufce@G9a/chwpWeaH37jPHJv2102ToBlFFKmopsGvmUptGsqU1FN41W2jSqgOIkMsWlhbfs7mgQA418@2TIcSKEo/ohpmmpVQ@iHHndE/Q2EOJEoadlDi1xDj2jRRCS5oGnHOKxQXAr3a28IqDexiX2bGaja/vBxiUSNg8O8d91XeoP) [Answer] # Javascript (ES6), 189 bytes ``` d="N.NNW NNE.NNE.N NE.NE.NNE ENE.ENE.NE E.E.ENE ESE.ESE.E SE.SE.ESE SSE.SSE.SE S.S.SSE SSW.SSW.S SW.SW.SSW WSW.WSW.SW W.W.WSW WNW.WNW.W NW.NW.WNW NNW.NNW.NW N".split`.`,f=>d[d.indexOf(f)+1] ``` Just takes the input, looks it up, and returns it. [Answer] ## JavaScript (ES6), 94 bytes Expects a string in uppercase such as `"ENE"`. Returns a comma separated string such as `"NE,E"`. ``` s=>/\D+,\D+/.exec('NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N'.split(0+s+0))[0] ``` ### How it works The expression `0+s+0` is coerced to a string when `split()` is called. For instance, if the input is `"ENE"`, the string will be split on `"0ENE0"`: ``` "NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N" ^^^^^ ``` This leads to the following array: ``` [ "NNW0N0NNE0NE", "E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N" ] ``` Again, this array is coerced to a string when `exec()` is called. So, the regular expression is actually applied on: ``` "NNW0N0NNE0NE,E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N" ``` We look for consecutive non-numeric characters (`\D+`) followed by a comma, followed by consecutive non-numeric characters. This returns the array `[ "NE,E" ]`. We could arguably stop there and return just that. But the challenge is asking for either a delimited string or a two-element array. So, we extract the string with `[0]`. ### Demo ``` let f = s=>/\D+,\D+/.exec('NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N'.split(0+s+0))[0] ; ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"] .map( s => console.log(s, '=>', f(s)) ) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 39 bytes: ``` .rL]z_Bms@L"ESWN"jCd5"\"❤m❤w❤^❤\❤C❤9❤ ❤ ``` where `❤` represents unprintable letters. [Try it online!](http://pyth.herokuapp.com/?code=.rL%5Dz_Bms%40L%22ESWN%22jCd5%22%5C%22%09m%04w%13%5E%03%5C%11C%029%07+%01&test_suite=1&test_suite_input=N%0ANNE%0ANE%0AENE%0AE%0AESE%0ASE%0ASSE%0AS%0ASSW%0ASW%0AWSW%0AW%0AWNW%0ANW%0ANNW&debug=0) Hexdump: ``` 0000000: 2e 72 4c 5d 51 5f 42 6d 73 40 4c 22 45 53 57 4e .rL]Q_Bms@L"ESWN 0000010: 22 6a 43 64 35 22 5c 22 09 6d 04 77 13 5e 03 5c "jCd5"\".m.w.^.\ 0000020: 11 43 02 39 07 20 01 .C.9. . ``` ]
[Question] [ # Background The `echo` program is so neat. You can say anything to it, and it repeats your words perfectly, every time! How cool is that! Disappointingly, it repeats the input all at once, regardless of your typing speed, which is not very realistic. We'll have to fix that. # The Task Your program shall take its input from STDIN or closest equivalent. It shall read lines from the user one by one, possibly displaying some prompt, until they enter an empty line. After that, it shall print the lines to STDOUT or closest equivalent, in the same order as they were given. The last (empty) line is not printed, and the last printed line doesn't need to have a trailing newline. Additionally, the program shall preserve the time intervals between each line: if it took the user `x` seconds to enter a line, it shall take `x` seconds for the program to print it. This applies to the first and last lines too; the empty line is not printed, but the program waits anyway before terminating. # Example Here's an example session with the program. All actions that don't produce text are described in brackets, and the (optional) prompt is displayed as `>`. ``` [begin program] > fhtagn[enter; 1.48s passed since starting program] > yum yum[enter; 3.33s passed since previous enter] > so cool![enter; 2.24s passed since previous enter] > [enter; 0.23s passed since previous enter] [wait 1.48s]fhtagn [wait 3.33s]yum yum [wait 2.24s]so cool! [wait 0.23s, then end program] ``` Without the actions, the session looks like this: ``` > fhtagn > yum yum > so cool! > fhtagn yum yum so cool! ``` # Rules and Scoring The waiting times should be accurate to within 0.01 seconds (in practice, if the average human can't tell the difference, you're fine). The lowest byte count wins, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed. If your language has a built-in function for precisely this task, you may not use it. [Answer] # CJam, ~~45~~ ~~41~~ ~~39~~ ~~36~~ 34 bytes ``` {eslN1$}g;es](es-fm3/{){_es>}g;o}/ ``` This doesn't really make sense in the online interpreter of course, but it works in the Java interpreter. It doesn't display a prompt. ## Explanation ``` { e# Do while... (popping the condition from the stack) es e# Get the current timestamp. l e# Wait for a line to be entered and read it. N e# Push a linefeed. 1$ e# Copy the line we read - this terminates if the line is empty, because e# empty strings/arrays are falsy. }g ; e# Discard the last linefeed (the one after the empty input). es e# Push the current timestamp (corresponding to the last, empty, input). ] e# Wrap everything in an array. This is now a flat array containing: e# - The initial timestamp. e# - Three elements for each line: the line, a linefeed, the timestamp. e# - Two elements for the last line: the empty string and the timestamp. ( e# Pull off the initial time. es- e# Subtract the current time, which gives (minus) the difference between e# when a line was entered and when it should be printed back. fm e# This maps "minus that value" onto each element in the array. Now the lines e# and linefeeds are strings (arrays) - so minus is set difference, but they e# only contain characters, not any integers (like the difference value), so e# none of the strings will be affected. e# The timestamps on the other hand will be incremented by the time difference e# between reading and printing, giving the time at which each line should be e# printed back. 3/ e# Split the array into chunks of 3 (where the remaining two elements are e# just grouped as a pair). { e# For each of those chunks... ) e# Pull off the timestamp. { e# Do while... (popping the condition from the stack) _ e# Duplicate the target time. es> e# Check if it's still greater than the current time. }g ;o e# Discard the target time and print the rest of the current chunk, which will e# automatically be flattened/concatenated into a single string. }/ ``` [Answer] # JavaScript, ~~119~~ 112 bytes ``` k=(d=Date.now)(i=j=[]);do{i[++j]=[prompt(),d()-k]}while(i[j][0]);i.map(a=>setTimeout(b=>console.log(a[0]),a[1])) ``` Hoping to find a couple more bytes to cut out. [Answer] ## JavaScript, 120 bytes No chance of getting near to CJam with this approach, but a straightforward script. ``` a=[];t=+new Date;while(s=prompt()){a.push({s:s,t:+new Date})}while(v=a.pop()){setTimeout(`console.log('${v.s}')`,v.t-t)} ``` [Answer] # Pyth, 68 bytes ``` M&p+Gb$__import__('time').sleep(H)$J].dZWeaYwaJ.dZ)aJ.dZp&gVPY-VtJJk ``` Wasted a *lot* of bytes on the call to `sleep`, since Pyth has no `sleep` function. [Answer] # Ruby, 74 ``` t,*a=Time.now a<<[$_,t-t=Time.now]while$/<gets a.map{|l,i|sleep -i;puts l} ``` Tricks: `*a` on the first line initalizes an empty array. I could use `$*` instead but it's mildly sketchy since it's populated with some invocations and only saves me a byte. `$/` is a newline, and `$_` is the last line retrieved by `gets`. Edit: Sleeping at the end costs 20 more bytes, probably a way to golf it down ``` t,*a=Time.now a<<[$_,t-t=Time.now]while$/<gets t-=Time.now a.map{|l,i|sleep -i;puts l} sleep -t ``` [Answer] # SWI-Prolog, 185 bytes ``` a:-b([],S),reverse(S,T),c(T),!. b(R,S):-get_time(X),read_string(user_input,"\n","",_,A),get_time(Y),Z is Y-X,(A="",S=[A:Z|R];b([A:Z|R],S)). c([A:Z|T]):-sleep(Z),T=[];(write(A),nl,c(T)). ``` There is probably a lot to golf here but this will do for now... [Answer] # Python 3, 124 Only works on Windows platforms ``` from time import* s=[(1,clock())] while s[-1][0]:s+=[(input(),clock()-s[-1][1])] [sleep(y)or x and print(x)for x,y in s[1:]] ``` Keeping the input and times in separate lists cost me [3 more bytes](https://mothereff.in/byte-counter#from%20time%20import%2A%0Aj%3Di%3D1%0As%3D%5B%5D%0At%3D%5Bclock%28%29%5D%0Awhile%28i%29%3Ai%3Dinput%28%29%3Bs%2B%3D%5Bi%5D%3Bt%2B%3D%5Bclock%28%29-t%5B-1%5D%5D%0Afor%20x%20in%20s%5B%3A-1%5D%3Asleep%28t%5Bj%5D%29%3Bprint%28x%29%3Bj%2B%3D1). Probably not the best approach. An 129 byte Unix friendly version, with credit to [Mego](https://codegolf.stackexchange.com/users/45941/): ``` from time import* t=time s=[(1,t())] while s[-1][0]:s+=[(input(),t(),t()-s[-1][1])] [sleep(y)or x and print(x)for x,z,y in s[1:]] ``` [Answer] # PowerShell, ~~261~~ ~~190~~ ~~121~~ 95 Bytes ``` $(do{Measure-Command{$l=read-host};$l}while($l))|%{($_,(sleep -m($_.Ticks/1e4)))[($b=!$b+!$_)]} ``` Props to [TessellatngHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) and [tomkandy](https://codegolf.stackexchange.com/users/25181/tomkandy) for the golfing assistance and inspiration This is very similar in concept to the 121-byte version below, we're just dynamically creating and building a list of objects, instead of going through a while loop to store them into an explicit array `$a`. In both cases, that list of objects gets pipelined into the same foreach loop `|%{...}`. The indexing into the result-array-selector `($b=!$b+!$_)` is this time formulated to eliminate the `if($_){$_}` of the below iterations, which saves a few more bytes. --- ### Previous, 121 Bytes ``` $l,$a=1,@();while($l){$t=Measure-Command{$l=read-host};$a+=$t,$l}$a|%{($(if($_){$_}),(sleep -m($_.Ticks/1e4)))[($b=!$b)]} ``` Expanded and explained: ``` $l,$a=1,@() # Set variable $l and create array $a while($l){ # So long as we don't have a blank line $t=Measure-Command{$l=read-host} # Read the input and measure time to input $a+=$t,$l # Add those values into the array } $a|%{ # For each item in $a, do ($(if($_){$_}),(sleep -m($_.Ticks/1e4)))[($b=!$b)] # Magic happens here ... first, we set $b to the NOT of it's uninitialized # value, so $b is initially set to truthy # This value in [...] selects which of the two elements ( , ) get selected # Truthy to start means the second command, sleep, gets chosen first, and # then it alternates every next item, so it sleeps, then prints, then # sleeps, then prints, etc., until we run out of $a } ``` --- ### Previous-er, 190 Bytes ``` function f {param($m)sleep -m $a[$m].totalmilliseconds}$a=1,1;while($a[-1]-ne""){$a+=Measure-Command{$b=read-host};$a+=$b}if(!($a[3])){f 2;exit}$i=2;while($i-lt$a.length){f($i++);$a[($i++)]} function f { # Define a new function param($m) # with $m as input sleep -m $a[$m].totalmilliseconds # sleep for $a[$m] milliseconds } $a=1,1 # Create new array with two elements while($a[-1]-ne""){ # While the last element isn't empty $a+=Measure-Command{$b=read-host} # Read into $b and measure how long that took, # and add the time into $a $a+=$b # Then add the input into $a } if(!($a[3])){ # If the third element is empty, the user entered # a blank as the only input, so... f 2 # sleep for $a[2] ms (how long it took them to hit enter)... exit # and exit the script } # Else ... $i=2 # Set a counter variable while($i-lt$a.length){ # While we haven't reached the end of $a f($i++) # Sleep $a[($i++)] # Write the output } ``` --- ### Previous-er-er, 261 Bytes ``` $a=$d=@();$d+=,@(date);$x=Read-Host while($x){$a+=,@($x);$d+=,@(date);$x=Read-Host} if($x){0..($a.Length-1)|%{sleep -m((($d[$_+1]).ticks-($d[$_]).ticks)/1e4);$a[$_]};sleep -m((($d[-1]).ticks-($d[-2]).ticks)/1e4)} else{sleep -m(((date).Ticks-($d[0]).Ticks)/1e4)} ``` Holy verbosity, Batman! Let's break it down: ``` $a=$d=@() # Create two empty arrays $d+=,@(date) # Add the current time into $d $x=Read-Host # Read the first line while($x){ # So long as it's not empty $a+=,@($x) # Add it into our output array $d+=,@(date) # Add the current time into $d $x=Read-Host # Get the next line } if($a){ # So long as $a exists (i.e., the first input wasn't blank) 0..($a.Length-1)|%{ # For-loop over the length # Sleep for how long it took to do input sleep -m((($d[$_+1]).ticks-($d[$_]).ticks)/1e4) $a[$_] # Print out the input } # Sleep the length it took for the final blank sleep -m((($d[-1]).ticks-($d[-2]).ticks)/1e4) } else{ # If we're here, the initial input was blank, so just sleep sleep -m(((date).Ticks-($d[0]).Ticks)/1e4) } ``` [Answer] ## Perl 6, 70 characters ``` repeat {$/=now;.push($!=get,now -$/)}while $!;.map:{sleep $^b;say $^a} ``` Perl 6 interpreter only defines three symbolic variables (unlike the craziness of Perl 5). To be exact, `$/`, `$!`, and `$_`. This program uses them all, to avoid the cost of declaring variables using `my`. `get` reads a line from STDIN. It doesn't contain a newline, unlike Perl 5. `now` builtin returns a current time. When subtracted, it gives an interval that can be passed to a string. A method with nothing on the left of it (like `.push` and `.map` in this code) works on `$_`. Using `repeat while` loop (known as `do while` in other programming languages), Perl 6 is writing current timestamp to `$/`, and pushes the received line (which it also stores to `$!`), and difference between current time and timestamp in `$/`. Because of parameter order, `now` is not calculated until a line is received. The `while` condition checks if the line is not empty (in Perl 6, `"0"` is a true value, unlike Perl 5). After I get all timestamps and lines, I just provide those to `map` callback which sleeps a bit and says what was said. [Answer] # Groovy, 202 bytes ``` def b={System.currentTimeMillis()};def h=[];for(;;){def t=b();def s=System.console().readLine();h.add(s+" "+(b()-t));if(s=="")break};for(def s:h){Thread.sleep((s=s.split(" "))[1].toLong());println s[0]} ``` Radical. Ungolfed version: ``` def b = {System.currentTimeMillis()}; // Creates a closure (short function) b that returns the current time since the epoch in milliseconds. def h = []; // Makes an empty list for(;;) { // Infinite loop def t = b(); // Get the time def s = System.console().readLine(); // Read a line h.add(s + " " + b()-t); // Add the string plus the amount of time elapsed to the list if(s=="") // If the string is blank break; // Exit loop } for(def s : h) { // Iterate through array Thread.sleep((s=s.split(" "))[1].toLong()); // Splits s into an array and puts the value in s, then takes the second element (the time), converts into a long and sleeps for that time. println s[0] // Print the first element (text) } ``` [Answer] # JavaScript (ES6) 102 Putting together the efforts of Mwr247 and Dom Hastings (CW) ``` /* for TEST */ console.log=x=>O.innerHTML+=x+'\n' for(k=new Date,i=[];p=prompt();i.push([p,new Date]));i.map(a=>setTimeout(b=>console.log(a[0]),a[1]-k)) ``` ``` <pre id=O></pre> ``` [Answer] # MATLAB, ~~107~~ 99 ``` tic;a={};i=1;while nnz(i);i=input('','s');a=[a;{i,toc}];tic;end;for b=a';pause(b{2});disp(b{1});end ``` And ungolfed: ``` tic; %Start timer a={}; i=1; %Make us enter the while loop while nnz(i); %While i has some non-zero elements (this is used to detect a zero length input where we end) i=input('','s'); %Get an input string a=[a;{i,toc}]; %Append the string and current time as a new cell in a tic; %Restart timer end for b=a' %For each input pause(b{2}); %Wait for the required time disp(b{1}); %Then print the string end ``` This won't be 100% accurate in timing as it doesn't account for the time taken to display each string but that should be pretty quick so timing-wise it should be pretty close. --- After a quick revisit, I've saved a few bytes by removing the double layer deep cell array. Turns out all I needed was a `;` to get it to split up correctly when packing. [Answer] # Java, using version 1.04 of [this library](https://scratch.mit.edu/discuss/topic/123874/?page=1), 385 bytes ``` import sj224.lib.util.*;import java.util.*;class E{static long t(){return System.currentTimeMillis();}public static void main(String[]a) throws Exception{List<Pair<?,Long>>l=new ArrayList();Scanner i=new Scanner(System.in);while(true){long t=t();String s=i.nextLine();if(s.isEmpty())break;l.add(new Pair(s,t()-t));}for(Pair<?,Long>p:l){Thread.sleep(p.two);System.out.println(p.one);}}} ``` [Answer] # Caché ObjectScript, 123 bytes ``` w() q $P($ZTS,",",2) r f s i=i+1,t=$$w() r x,! q:x="" s g(i,x)=$$w()-t f i=1:1 s s=$O(g(i,"")) q:s="" w s,! h g(i,s) q ``` As usual, this assumes a clean symbol table before running `d r`. This problem cannot be solved in ANSI MUMPS, since the ANSI standard only requires second-level resolution for the time intrinsic `$H[OROLOG]`. Luckily, Intersystems Caché, which is currently the industry-leading platform for MUMPS, provides [the implementation-defined `$ZT[IME]S[TAMP]` intrinsic](http://docs.intersystems.com/ens20121/csp/docbook/DocBook.UI.Page.cls?KEY=RCOS_vztimestamp), which provides microsecond-level resolution. (Score was formerly 105 bytes, but there was a bug.) [Answer] # Bash, ~~91~~ 90 bytes ``` while r=`\time -fsleep\ %e head -1` [[ $r ]] do printf{,\ %%b\ %q\;} "$r " done>t 2>&1 . t ``` This creates a temporary file `t`. **It will overwrite an existing file with the same name.** The idea itself is pretty short, but dealing with special characters in the input adds around 15 bytes... [Answer] **VBA , ~~233~~ 228bytes** I'm Sure this can be golfed a lot. they didn't specify how many inputs so i hard coded my array lengths because its shorter then `Redim preserve`. Input is via popup, output is `debug.print` because `msgbox` produces a MODAL and halts code. I don't know how to test if this is accurate to the 0.01s. Maybe someone can test but I am giving the wait command the number in a way that it SHOULD use the milliseconds, But VBA isn't known for doing what it should. The `If goto` may be able to be substituted by a well golfed `Do Loop While`. ``` Sub a() Dim k(99) As String Dim h(99) As Date b: t=Now() i=i+1 k(i)=InputBox("") h(i)=Now()-t If k(i)<>"" Then GoTo b For u=1 To i Application.Wait (Now()+(Format(h(u),"s")&Format(h(u),"ms"))/10^8) Debug.Print k(u) Next End Sub ``` > > Will not work in Access VBA, because access doesn't have a wait command ***because Microsoft hates consistency*** > > > [Answer] # Bash, 22 bytes ``` nc -l 3|nc localhost 3 ``` Then type in the input and press enter. [Answer] # C++ 11, ~~343~~ 338 bytes Wanted to see how many bytes a code for that in c++ would need. A lot more than I expected. Maybe I over complicated the solution. ``` #include<iostream> #include<vector> #include<chrono> int i;using namespace std;int main(){auto n=chrono::system_clock::now;auto t=n();string s{1};vector<string>r;vector<decltype(t-t)>w;while(s.size())getline(cin,s),r.push_back(s),w.push_back(n()-t),t=n();while(i<r.size()){while((n()-t)<w[i]);t=n();cout<<r[i++]<<(i<r.size()-1?"\n":0);}} ``` Lets see if I can reduce this somehow. [Answer] # SmileBASIC, 122 bytes ``` DIM A$[0],T[0]@L C=MAINCNT LINPUT S$PUSH A$,S$PUSH T,MAINCNT-C IF""<S$GOTO@L@P WAIT SHIFT(T)IF""<A$[0]THEN?SHIFT(A$)GOTO@P ``` I think this could be made slightly shorter. [Answer] # C UNIX, 272 bytes ``` #include <stdio.h> #include <unistd.h> #define P printf i;r;c;main(){char*L[99]={0};size_t s;long T[99]={0};while(1){P("> ");T[c]=time(0);r=getline(&L[c],&s,stdin);T[c]=time(0)-T[c];if(r==-1|!(*L[c]-10))break;c++;}while(i<c){P("> ");usleep(T[i]*1000);P("%s", L[i]);i++;}} ``` **Detailed** ``` #include <stdio.h> #include <unistd.h> int main(void) { int i = 0, c = 0, r; char * L[99] = {0}; size_t size; long T[99] = {0L}; while(1) { printf("> "); T[c] = time(0); r = getline(&L[c], &size, stdin); T[c] = time(0) - T[c]; if(r == (-1)) break; if(*L[c]=='\0' || *L[c]=='\n') break; c = c + 1; } while(i < c) { printf(" %ld > ",T[i]); usleep(T[i]*1000); printf("%s", L[i]); i = i + 1; } return 0; } ``` ]
[Question] [ An activity I sometimes do when I'm bored is to write a couple of characters in matching pairs. I then draw lines (over the tops never below) to connect these characters. For example I might write \$abcbac\$ and then I would draw the lines as: [![First Link](https://i.stack.imgur.com/7y5Q7.png)](https://i.stack.imgur.com/7y5Q7.png) Or I might write \$abbcac\$ [![Second Link](https://i.stack.imgur.com/Cg98T.png)](https://i.stack.imgur.com/Cg98T.png) Once I've drawn these lines I try to draw closed loops around chunks so that my loop doesn't intersect any of the lines I just drew. For example, in the first one the only loop we can draw is around the entire thing, but in the second one we can draw a loop around just the \$b\$s (or everything else) [![Loop drawn](https://i.stack.imgur.com/sVH95.png)](https://i.stack.imgur.com/sVH95.png) If we play around with this for a little while we will find that some strings can only be drawn so that closed loops contain all or none of the letters (like our first example). We will call such strings well linked strings. Note that some strings can be drawn in multiple ways. For example \$bbbb\$ can be drawn in both of the following ways (and a third not included): [![Way 1](https://i.stack.imgur.com/T1kQD.png)](https://i.stack.imgur.com/T1kQD.png) or [![Way 2](https://i.stack.imgur.com/HDVF8.png)](https://i.stack.imgur.com/HDVF8.png) If one of these ways can be drawn such that a closed loop can be made to contain some of the characters without intersecting any of the lines, then the string is not well linked. (so \$bbbb\$ is not well linked) ## Task Your task is to write a program to identify strings that are well linked. Your input will consist of a string where every character appears an even number of times, and your output should be one of two distinct consistent values, one if the strings are well linked and the other otherwise. In addition **your program must be a well linked string** meaning * Every character appears an even number of times in your program. * It should output the truthy value when passed itself. Your program should be able to produce the correct output for any string consisting of characters from printable ASCII or your own program. With each character appearing an even number of times. Answers will be scored as their lengths in bytes with fewer bytes being a better score. ## Hint > > A string is not well linked iff a contiguous non-empty strict substring exists such that each character appears an even number of times in that substring. > > > ## Test Cases ``` abcbac -> True abbcac -> False bbbb -> False abacbc -> True abcbabcb -> True abcbca -> False ``` [Answer] # Regex (ECMAScript 2018 or .NET), ~~140~~ ~~126~~ ~~118~~ ~~100~~ ~~98~~ 82 bytes `^(?!(^.*)(.+)(.*$)(?<!^\2|^\1(?=(|(<?(|(?!\8).)*(\8|\3$){1}){2})*$).*(.)+\3$)!?=*)` This is much slower than the 98 byte version, because the `^\1` is left of the lookahead and is thus evaluated after it. See below for a simple switcheroo that regains the speed. But due to this, the two TIOs below are limited to completing a smaller test case set than before, and the .NET one is too slow to check its own regex. [Try it online! (ECMAScript 2018)](https://tio.run/##rVRNb9tGEL3zV1ASLe6Q9JJSgCCgtaLjwCmMoKhiGUgAUXT4saJZ80MmqUQGRR9yaHxq0Rx6NnLuqUCA1Meo8TH/Qfkj7pJyG/tQIIcS2J3ZmbdvFrNv@aP90s7cNJjmm3Hi0euMaFsp2af@7nyKhnkaxD5O7Vcvri1kNJCFJUBYZkMSABm9hmV2F5bZQQZBC9Qz2GQ0zAeAQULmg4V5T4CiU0LRLYFtwBLCIFfBhkEkuH6BszBwKeoomx2ArZSezIKUIjGlthcGMRUBu8zP6V6c03RiM2gRxNNZrk/TxKVZhrPcC@IScBIjsd6hhKRfcDwfTHjUCPnFgg9vimhKFwgRVVUEluf5WxTJLMev0iCnCGWGaMaiLoogh7DFgDTM6LfhUYgjO3ePUApG8yCdUZ3nm3rzsc0YdL65JsxIZ6uEa1XlKwSf0yznXTujGWc7rmO7zNiu465XbHAcg9YUd7GOy7AO@2qka9e470@rU/qpHWXc/39ddYkf8iOaZiL/0g4D72u1vy5Wl@erD69Xlx9Wlz@t/vxt@ebL699Xlxdffvn5Vo6t7qa5fyO3UFd/XL25@vW/M9ynt5/ff3w3WF6UTz693Xvy@f1wb/jx3fJ8UC4vlucckloiVrROt73YPmuJQDotPNIVNNIlVSNVtKXiMzCxyYV25Hg2HyoOKQKv1EMaoyLLU@ToxLEKt4RJkiIXgpgPS@hV6RBaSs@aRHGS5UXZ4pwo1siE3DBlyoAUWql4ZDTWs16TbwYTNODZfg8qKckTlI0mvUwfKwOryEaapY1LZTQYyx5wEnaTyBlZ0nMZWRIwOU0rO8Z@SqeoEA7bo/YYCYfAFB8nMcU7tl9IZe1vdFuSJT/fSZxuSt2NFhdtYhkZhfB0QbZP2n46VQRzQYQ2PREOrUbFKKuW2kbbERF8cqaaT4VD1QcFsZXQBhbBql8y1TRgsyzWevoqJxDuyElHllHNTE33KzWxuRbRWmB1iDlYNu9jqRIUE1bRUUrzXsWv9MCAf67CUyih8SyiKXv3ehTEKLLnyBuFeig7Y9agWZyjY9joVhdzDHVjmcs7ilt1mTJolzW3WwdDZXITBB5aDk/0uYxZp7g56Tfm@Ls0mU13TpFL@i7gh/Ep8knfx4/qGqxEX4N2Y3d9GCekeJ9O2d8IzdcI5cZKNxbwM/Y2KGLCRaESAOkHG2Ffa7NCw@NgigI1BHxgH1PE4vAtxRnTOgOq1G8kpw/jR9puRNlZ9qVnR8FQPZDUvwE "JavaScript (Node.js) – Try It Online") [Try it online! (.NET)](https://tio.run/##dZLPT9swFMfv@SvcFFE7hDTpLiitFyS0SQgQaEXaoVklx3VLJDepbJcxpeHAYXDaNA47V5x3moTEeqSDI/9D@Uc6p90mOGDJv973856f7UflOk0Fmyekz@SAUAaan6Ri/Wwo46QHDtmJct6x3pAT8eZkIJiUcZrIOuVEStDPpCIqpuA4jTtgj8QJgCg7JgJIvGnO2zAowbZjIeis6W6tIBg0Su2wNmqHHgwwHMFGoIegFG4gB1kw3BiFr1ZQ5uUoq@VIOzgWdNBaYSwF2EJzs15EFzhhH4FOi51A6TSHkVRCZws9Wzq7LOmpo/Uashf6/kAVCTtbaX8Qc9ZB9SULeL2bChgnCnSxW4ccb2ks5UzflnR244RBhEo4GXINYg9lcRd2X7voH/VexIotsboBQNwFkP89G2N3NOIt9wPGlWpldZW3vOUSaRCAZxGgmbm5afNFEMYlewHRT2LawtmWe0TRI8hRYB6KIfMBMH3zLdGOPliGyXWbV6ugkIFiUgFKJJMGiWhEqJ4Ijehyp7thaHTh/5yNqGYj3RYkJQtuXx0xISvgmHD93QOR9gTpS@P3eDa5mN2czSY3s8nn2a/v0/PHsx@zyfjx65cnmt49l43/lifU/c/78/tvLyvG3eXD9e3VwXSc79xdbu88XDe3m7dX04uDfDqeXhjQKlcc2/Vqq6PN03IFYa/stHwbtnyr6uLCWq46pyh0QoOTftQhgNsRzuJO7nOWQF3QAkY@jtoZzVFRIRTpquY5ahQyR2W70e72k1SqLC//AQ "C# (.NET Core) – Try It Online") To drop 18 bytes (118 → 100), I shamelessly stole a really nice optimization from [Neil's regex](https://codegolf.stackexchange.com/revisions/179426/2) that avoids the need to put a lookahead inside the negative lookbehind (yielding an 80 byte unrestricted regex). Thank you, Neil! That became obsolete when it dropped an incredible 16 more bytes (98 → 82) thanks to [jaytea](https://codegolf.stackexchange.com/users/75057/jaytea)'s ideas which led to a 69 byte unrestricted regex! It's much slower, but that's golf! Note that the `(|(` no-ops for making the regex well-linked have the result of making the it evaluate very slowly under .NET. They do not have this effect in ECMAScript because [zero-width optional matches are treated as non-matches](https://github.com/Davidebyzero/RegexMathEngine/issues/1). ECMAScript prohibits quantifiers on assertions, so this makes golfing the [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") requirements harder. However, at this point it's so well-golfed that I don't think lifting that particular restriction would open up any further golfing possibilities. Without the extra characters needed to make it pass the restrictions (~~101~~ 69 bytes): `^(?!(.*)(.+)(.*$)(?<!^\2|^\1(?=((((?!\8).)*(\8|\3$)){2})*$).*(.)+\3))` It's slow, but this simple edit (for just 2 extra bytes) regains all the lost speed and more: `^(?!(.*)(.+)(.*$)(?<!^\2|(?=\1((((?!\8).)*(\8|\3$)){2})*$)^\1.*(.)+\3))` ``` ^ (?! (.*) # cycle through all starting points of substrings; # \1 = part to exclude from the start (.+) # cycle through all ending points of non-empty substrings; # \2 = the substring (.*$) # \3 = part to exclude from the end (?<! # Assert that every character in the substring appears a total # even number of times. ^\2 # Assert that our substring is not the whole string. We don't # need a $ anchor because we were already at the end before # entering this lookbehind. | # Note that the following steps are evaluated right to left, # so please read them from bottom to top. ^\1 # Do not look further left than the start of our substring. (?= # Assert that the number of times the character \8 appears in our # substring is odd. ( ( ((?!\8).)* (\8|\3$) # This is the best part. Until the very last iteration # of the loop outside the {2} loop, this alternation # can only match \8, and once it reaches the end of the # substring, it can match \3$ only once. This guarantees # that it will match \8 an odd number of times, in matched # pairs until finding one more at the end of the substring, # which is paired with the \3$ instead of another \8. ){2} )*$ ) .*(.)+ # \8 = cycle through all characters in this substring # Assert (within this context) that at least one character appears an odd # number of times within our substring. (Outside this negative lookbehind, # that is equivalent to asserting that no character appears an odd number # of times in our substring.) \3 # Skip to our substring (do not look further right than its end) ) ) ``` I wrote it using molecular lookahead (~~103~~ 69 bytes) before converting it to variable-length lookbehind: `^(?!.*(?*(.+)(.*$))(?!^\1$|(?*(.)+.*\2$)((((?!\3).)*(\3|\2$)){2})*$))` ``` ^ (?! .*(?*(.+)(.*$)) # cycle through all non-empty substrings; # \1 = the current substring; # \2 = the part to exclude from the end (?! # Assert that no character in the substring appears a # total even number of times. ^\1$ # Assert that our substring is not the whole string # (i.e. it's a strict substring) | (?*(.)+.*\2$) # \3 = Cycle through all characters that appear in this # substring. # Assert (within this context) that this character appears an odd number # of times within our substring. ( ( ((?!\3).)* (\3|\2$) ){2} )*$ ) ) ``` And to aid in making my regex itself well-linked, I've been using a variation of the above regex: `(?*(.+)(.*$))(?!^\1$|(?*(.)+.*\2$)((((?!\3).)*(\3|\2$)){2})*$)\1` When used with [`regex -xml,rs -o`](https://github.com/Davidebyzero/RegexMathEngine), this identifies a strict substring of the input that contains an even number of every character (if one exists). Sure, I could have written a non-regex program to do this for me, but where would be the fun in that? [Answer] ## Jelly, 20 bytes ``` ĠẈḂẸẆṖÇ€Ạ ĠẈḂẸ ẆṖÇ€Ạ ``` [Try it online!](https://tio.run/##y0rNyan8///Igoe7Oh7uaHq4a8fDXW0Pd0473P6oac3DXQu4kGS4UKX@k6cNAA) The first line is ignored. It's only there to satisfy the condition that every character appear an even number of times. The next line first `Ġ`roups indices by their value. If we then take the length of each sublist in the resulting list (`Ẉ`), we get the number of times each character appears. To check whether any of these are non-even, we get the last `Ḃ`it of each count and ask whether there `Ẹ`xists a truthy (nonzero) value. Therefore, this helper link returns whether a substring *cannot* be circled. In the main link, we take all substrings of the input (`Ẇ`), `Ṗ`op off the last one (so that we don't check whether the entire string can be circled), and run the helper link (`Ç`) on `€`ach substring. The result is then whether `Ạ`ll substrings cannot be circled. [Answer] # [J](http://jsoftware.com/), 34 bytes ``` 2:@':.,|~*'>1(#.,)*/@(1>2|#/.~)\.\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jawc1K30dGrqtNTtDDWU9XQ0tfQdNAztjGqU9fXqNGP0Yv5rcqUmZ@QrGCrYKqQpqCcmJSYnJaujiSUngTBU1AAmmpScmIwqlgQE6KqAxiWqc3EVp@ak2eopqINcBHMSLjehWA/S@B8A "J – Try It Online") *-8 bytes thanks to FrownyFrog* # original # [J](http://jsoftware.com/), 42 bytes ``` (*#'.,012&|@~#')=1#.[:,([:*/0=2&|@#/.~)\.\ ``` [Try it online!](https://tio.run/##fY6xCsIwFEX3fMXDgK8p8TVxDAQKgpOTa7skjwYRwcFV@utpAgq2gxfucrhczj3vCBN4BwgaDLjSA8HpejnnppVI2tjj/t3PEpW3kganm8G1nfGVyo5mNdKYlZj49gQLHhJgiIEj44ZxrP1Q86WRA69ZLNmuyl1AIV7TI3kCrGa/av/cVhr1IC8 "J – Try It Online") ## explanation ``` (*#'.,012&|@~#') = 1 #. [: , ([: */ 0 = 2&|@#/.~)\.\ (*#'.,012&|@~#') NB. this evaluates to 1 NB. while supplying extra NB. chars we need. hence... = NB. does 1 equal... 1 #. NB. the sum of... [: , NB. the flatten of... ( )\.\ NB. the verb in parens applied NB. to every suffix of every NB. prefix, ie, all contiguous NB. substrings ([: */ 0 = 2&|@#/.~) NB. def of verb in paren: /.~ NB. when we group by each NB. distinct char... [: */ NB. is it the case that NB. every group... @# NB. has a length... 0 = 2&| NB. divisible by 2... ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 66 bytes ``` lambda l,b={id}:len({str(b:=b^{c})for(c)in l})<len(l)#,<^fmnost{}# ``` [Try it online!](https://tio.run/##NY3RCsMgDEWf168Q@qBCt5e9jNLuUwomrUywKiqDIX57F@kWCJzk5t6ET355d3@EeKBfNzYzzvlh1Q6rYnaAuZi1jnZzoqQcBYwzLAWr1D4KlMYxW@XUZCv7YVr07nzKpfYHxdzIYYKQXacpd3srK9qPNvvIEiM3V4CgkA@NAE8CqnOjEH4aXVH/GRVRyxq7S4jGZZFIuT5pq0WS8vgC "Python 3.8 (pre-release) – Try It Online") The Era of Assignment Expressions is upon us. With [PEP 572](https://www.python.org/dev/peps/pep-0572/) included in Python 3.8, golfing will never be the same. You can install the early developer preview 3.8.0a1 [here](https://www.python.org/downloads/release/python-380a1/). Assignment expressions let you use `:=` to assign to a variable inline while evaluating to that value. For example, `(a:=2, a+1)` gives `(2, 3)`. This can of course be used to store variables for reuse, but here we go a step further and use it as an accumulator in a comprehension. For example, this code computes the cumulative sums `[1, 3, 6]` ``` t=0 l=[1,2,3] print([t:=t+x for x in l]) ``` Note how with each pass through the list comprehension, the cumulative sum `t` is increased by `x` and the new value is stored in the list produced by the comprehension. Similarly, `b:=b^{c}` updates the set of characters `b` to toggle whether it includes character `c`, and evaluates to the new value of `b`. So, the code `[b:=b^{c}for c in l]` iterates over characters `c` in `l` and accumulates the set of characters seen an odd number of times in each non-empty prefix. This list is checked for duplicates by making it a set comprehension instead and seeing if its length is smaller than that of `s`, which means that some repeats were collapsed. If so, the repeat means that in the portion of `s` seen in between those times every character encountered an even number of numbers, making the string non-well-linked. Python doesn't allow sets of sets for being unhashable, so the inner sets are converted to strings instead. The set `b` is initialized as an optional arguments, and successfully gets modified in the function scope. I was worried this would make the function non-reusable, but it seems to reset between runs. For the source restriction, unpaired characters are stuffed in a comment at the end. Writing `for(c)in l` rather than `for c in l` cancels the extra parens for free. We put `id` into the initial set `b`, which is harmless since it can start as any set, but the empty set can't be written as `{}` because Python will make an empty dictionary. Since the letters `i` and `d` are among those needing pairing, we can put the function `id` there. Note that the code outputs negated booleans, so it will correctly give `False` on itself. [Answer] # [Python 2](https://docs.python.org/2/), 74 bytes ``` bmn0=f=lambda s,P={0},d=[]:s<" "if(P in d)else+f(s[f<s:],P^{s[0^0]},[P]+d) ``` [Try it online!](https://tio.run/##XY3LasMwEEX3@opBUCxhE9wsTbTqD3jRnesUPYmKIxmPQltCvt2V7C5KBUKXO2eO5u90ieG46misoJSu6hpa4cQkr8pIwKYX9/bRGDGMHZ4oUO9YDz6A4XZCWzuGgzthNzb9@Y5De27HRzP0Y234mnUHTIufGSf2y2oonxASjXnXF7kgCMjER/SBaXBxAV3EGJdkDUObWOE5B@@2zYOOt5BL/nTkZF58SEBfcg@z9Is1HW2gZn/kxf4fRLRYQLe79yl9C7mirxYTaLkR5PPiJwvP3b7umA/zLTHO10oqraSuSA5Sqz3kJt/fqOUW8luGKp/qBw "Python 2 – Try It Online") Iterates through the string, keeping track in `P` of the set of characters seen an odd number of times so far. The list `d` stores all past values of `P`, and if see the current `P` already in `d`, this means that in the characters seen since that time, each character has appeared an even number of times. If so, check if we've gone through the entire input: if we have, accept because the whole string is paired as expected, and otherwise reject. Now about the source restriction. Characters needing pairing are stuffed into various harmless places, underlined below: ``` bmn0=f=lambda s,P={0},d=[]:s<" "if(P in d)else+f(s[f<s:],P^{s[0^0]},[P]+d) _____ _ _ _ _ ___ ___ ``` The `f<s` evaluates to `0` while pairing off an `f`, taking advantage of the function name also being `f` so that it's defined (by the time the function is called.) The `0^0` absorbs an `^` symbol. The `0` in `P={0}` is unfortunate: in Python `{}` evaluates to an empty dict rather than an empty set as we want, and here we can put in any non-character element and it will be harmless. I don't see anything spare to put in though, and have put in a `0` and duplicated it in `bmn0`, costing 2 bytes. Note that initial arguments are evaluated when the function is defined, so variables we define ourselves can't be put in here. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 76 bytes ``` *.comb[^*X+(^*).map(^*)].grep({$_&[&]($_)}).none.Bag{*}.none%2#*^+XBob2rec%# ``` [Try it online!](https://tio.run/##rZDBaoQwEIbPzVMMuGoSt6H1sJdSCx76BD0IosskxMWuGondgojPbuNK2fbcBobMZL5/5ie9ts1haUcIKniGhQtlWpmXPItoyZlosV/vQpys7um0OwZ5UNDdkc1MdKbTIsXTxOdr7sceL6MsNTK2Wvne8kRIZSw0daeHJBFD39QfNIT7BEIGE7kbcISXior8oWB72Bp7EPljAWQmxFv74V8deSr1TSZ1GdsovM5aiU3NxSc2F4cxZ@@sR/Fu6m5BqSSq1c2bvWiCUqqtfMVm0ES6c6vQofIn7LQufj0ovPH/@cHfS74A "Perl 6 – Try It Online") A Whatever lambda that returns a None Junction of None Junctions that can be boolified to a truthy/falsey value. I would recommend not removing the `?` that boolifies the return result though, otherwise the output gets rather [large](https://tio.run/##rZDBaoQwEIbPzVMMuGoSt0PrYS9LPXjoE/QgiC5JiIutGondgojPbuNK2fbcDQyZmXz/zE96bZvD0o4QVPACC0dlWpmXPItoyRm2ol/vAs9W93TanYI8KOjuxGaGnek0puI88fma@7HHyyhLjYytVr63HAmpjIWm7vSQJDj0Tf1JQ3hMIGQwkYdBjFBRzJ8KtoetvwfMnwsgMyHe@hz@15CnUt9kUpexjcLrrJXY1By/RHNxGHPuPvSI76buFiGVFGp182Yvmggp1Va@imbQRLpzq4RD5W/YaV38aShx4@/5vz9LvgE). This solution is a little more complex than needed, due to several involved functions being unlinked, e.g. `..`, `all`, `>>`, `%%` etc. Without the source restriction, this could be 43 bytes: ``` *.comb[^*X.. ^*].grep(?*).one.Bag{*}.all%%2 ``` [Try it online!](https://tio.run/##VYvLCoMwFETXzVfcjVWDvbRduClV6KJf0EVBFG5CFCE@SNqFiN@epgh9DMxiZs6MyujUdRNsaziD4yiHThQVvyNCxUtsjBqjnMc49Aov1Mx8QdI6CI7uxFg9GNBtr2yWoR11@4hC2GUQxjCzjaUJ8jrCYl/GCaxDAlgcSmCLIyEFyXd5M0/FSAi5xitpq5jw@ibyqPiF/df7r5D04V8 "Perl 6 – Try It Online") ### Explanation: ``` *.comb # Split the string to a list of characters [^*X+(^*).map(^*)] # Get all substrings, alongside some garbage .grep({$_&[&]($_)}) # Filter out the garbage (empty lists, lists with Nil values) .none # Are none of .Bag{*} # The count of characters in each substring .none%2 # All not divisible by 2 #*^+XBob2rec%# And garbage to even out character counts ``` [Answer] # Perl 5 `-p`, ~~94,~~ ~~86,~~ 78 bytes ``` m-.+(?{$Q|=@q&grp,$\|=$&eq$_^!grep+/^/&(@m=$g=~/\Q$_/g),($g=$&)=~/./g})(?!)-}{ ``` ouput 0 if well-linked 1 otherwise. [78 bytes](https://tio.run/##rVBBboMwELz7FZvEIqAEaA45IRo@0EPuKMg4DqAY7KyNSEXSp5ea9NIH9LQzs9LOzGqBcj@twCowtRpAnc/Aa4aMW4EGhlp0jgt@bboKjOqRC0BhLDbcNqojK6BVSovEsE@3RgsVCj1m99TJX3F@pEVcJdnd2z1fQuQYIS87JqXzcwD7Di4Koe2lbbQU0HS6t6BsLXBojAAH4NJLCRpVhayFQeHVgOq4IM6X5tGS0ALS92VCaJ6u18nUhtHGP4z0@Eizm1eh3tL8kVJP3GhxWswZN/Ep9vys/Rs02PpzGy/4TfoM/MMiCJ/jNLGSl4wTVpbcjf@9/q30/EozhVpO4cc@etv9AA) [86 bytes](https://tio.run/##K0gtyjH9r1Jka2D9P1dHT1vDvlol3VZFzVqlqAZIpRaqxMcpphelFlQ7VNgCZer0YwJV4vXTrR0q1AxrwQJ6@um1mhr2ipo61irxtipF1spq2oa5BYVF8XE1yjGB//8nJiUnJSZzJSYlJQMp2tjyL7@gJDM/r/i/bkHOf11fUz0DQwA) [94 bytes](https://tio.run/##tY0xCoMwFED3nsLgJyao0QxOIegFOrgLmgQJgtaQdhDUHr2p9A6dHjwePDf6uQrgZSnCkrGU1DtYCViAPyQiESIwMEhoRDGyfnR7s8kreBddC31hRbNhfv4EK@xJSY1oJqCX4EWME5byYVycP@KuDUFpo5W5Ka3Nhf/ePqt7TevjGXI3h/xesZJ/AQ) How it works * `-p` with `}{` ending trick to output `$\` at the end * `m-.+(?{` .. `})(?!)-`, to execute code over all non-empty substring (`.+` matches the whole string first, and after executing code between `(?{` ..`})` backtracks because of failed forced `(?!)` * `$Q|=@q&grp,` garbage because of source restriction * `$\|=` integer bitwise or assignment, if there's almost one 1, `$\` will be 1 (true), by default it is empty (false) * `$&eq$_` the case where the sbustring is the whole string is bitwise xored `^` with "no odd character occurence" * `($g=$&)=~/./g` to copy the matched substring into `$g` (because will be overwirtten after next regex match) and return the array of character of substring. * `/^/` garbage which evaluates to 1 * `grep` 1 `&(@m=$g=~/\Q$_/g),` for each character in substring get the array of character in `$g` matching itself, array in scalar evaluates to its size and `grep` to filter the chracters with odd occurence `1&x` is equivalent to `x%2==1` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~150~~ 96 bytes ``` ^(?!(.*)(.+)(.*)$(?<!^\2|^\1(?:(^?(?:(?!\6).)*\6){2})*(|(?!\6).)*(?!.+\6.*\3$)(.){1,}\3)(?!,<)?) ``` [Try it online!](https://tio.run/##tY4xCsMwDEX33MKQguQEgRPIUAIaewlhIpkMXTqUbknO7spLb1CB/v88wUfv/fN8aao3eGw1AwegiEADNu@B15BlOrMk4DtkbspBFiSMrsd0YYTzhzzQIAtFmXtvwCONl8zoeFyRsVa1Ylo6NStu5uNZizXkF9/u3098AQ "Retina – Try It Online") Link includes test cases, including itself. Edit: Golfed down the original regex a fair bit with help from @Deadcode, then padded back up slightly less extravagently to maintain the source layout. Explanation: ``` ^(?!(.*)(.+)(.*)$ ``` Assert that no substring `\3` exists that matches the following constraints. ``` (?<!^\2| ``` Assert that the substring is not the whole original string. ``` ^\1(?:(^?(?:(?!\6).)*\6){2})*(|(?!\6).)*(?!.+\6.*\3$)(.){1,}\3)(?!,<)?) ``` Assert that there is no character `\6` such that: * it does not appear between the character itself (exclusive) and the end of the substring * it appears an even number of times between the start of the substring and itself (exclusive) In order to pass the source layout constraint, I replaced `((((` with `(?:(^?(?:(` and `((` with `(|(`. I still had one source constraint `))` left and the characters `!()1<{}` left over, so I changed a `+` into `{1,}` and inserted the useless `(?!,<)?` to consume the rest. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~208~~ ~~206~~ ~~200~~ 198 bytes ``` x=>!x.GroupBy(c=>c).Any(g=>g.Count()%2>0)&!Enumerable.Repeat(x.Count,x.Count*x.Count).Where( (l,i)=>i%l>0&!x.Skip(i/l).Take(i%l).GroupBy(c=>c).Any(g=>g.Count()%2>0) ).Any()/*>!oyAnC0EmeablR*WhiS/T*/ ``` [Try it online!](https://tio.run/##3ZHBisIwEEDv/QpbUJJSk7JXTdgquizsYdGC52SINhibkjbQfn03oAcXFux5B4aB4Q1vhoF2Ca0e976G9eeXbrs1VMLxTFpr@JmNPeNxTz6c9c1mQMA4YFLUA7owfiFb6@sO4fkbz/Ei3tX@ppyQRpGDapToUH8nskdNHxWTU6WcQhEymcaM67nh@SJojlfdIE0NJqW4KhT6eIo6uvcxTXlsh6Le5rubCnsc0lOlj7RM6biKom@nw8QZJUKCFJCQ0hbOiTCH8WpG6ax0Xj1TEv6i9sK0T5gM8RISwScnGMNeIadwIF5J35P/8brfd44/ "C# (Visual C# Interactive Compiler) – Try It Online") -2 bytes thanks to @KevinCruijssen! Finally got it below 200, so I might be done golfing for now :) I ended up creating a second TIO to test things out based on a previous answer. [Try it online!](https://tio.run/##jVHRasIwFH3PV9iCkrRdWvdoTTYnsoftYajgc1eipomtxDpa3b69SxopqHsYhJzLzb3nHE7Sw0N64M1XonoVeXabilCnwq@qOO5fapgSmiI8yWu4IXSDp8UxLyHqP9IIDZxZftwxlXxKhudsz5ISVnYiuKB3QYRXW6YYBFAGHBHK@5JGAy2zEHwPeSgRXiaCQd1H/5EGto9CjzpFPcmn0WzHtI@5t9ryRbj0wsbFS8V3EMUAfCiuNw@lBkOTp63Raxnr704IL5hkaWkf3liNkCHUdD1OoiAjtzR2944mEHryneWbctv54b47cv2svYVhXRcKxnwsPBFznwzRGQDzKTXpYhJdTOImptjOSpL5Q11nPnFqG9G3xROhpytLT9HITPI1zAiRqHe@2GplWlOtTFvdRveHHZPLDzDH0mTjIYqbXw "C# (Visual C# Interactive Compiler) – Try It Online") Things that made this task tricky: * Equality operator `==` was not allowed * Increment/assign operator `++` was not allowed * Linq `All()` function was not allowed Commented code below: ``` // anonymous function that takes an IList as input x=> // the first condition makes sure the string even // counts of each character !x.GroupBy(c=>c).Any(g=>g.Count()%2>0)& // the second condition generates all proper substrings of x // and tests for any that contain even character counts // the string length `l` is repeated `l*l` times !Enumerable.Repeat(x.Count,x.Count*x.Count) .Where((l,i)=> // check that the substring length is greater than 0 i%l>0& // use skip/take to generate a substring // and check for a character count thats odd // negate the result meaning we have found // a substring that invalidates the input !x.Skip(i/l).Take(i%l) .GroupBy(c=>c).Any(g=>g.Count()%2>0) ) // if any invalid substrings are found // then the result in invalid // the comment string at the end is needed // to make the program well-linked .Any()/*>!oyAnC0EmeablR*WhiS/T*/ ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` sᶠb∋p~j&sᶠb∋p~j& ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/jhtgVJjzq6C@qy1JDZ//8rJSYlJiclKwEA "Brachylog – Try It Online") Prints `false.` for truthy instances and `true.` for falsy instances. The TIO version is too slow to handle itself, but it's clearly well-linked since it's a string with unique characters repeated twice. ## Explanation ``` Input is a string: "abcacbaa" sᶠ Find all substrings: ["abcacbaa","abcacba","abcacb",..,"a"] b Behead (now the proper substrings remain): ["abcacba","abcacb",..,"a"] ∋ Take one of them: "abcacb" p Permute it: "abcabc" ~j It is some string repeated twice: "abc" & Get the input again: "abcacbaa" Then repeat the above. If the constraints can be satisfied, the result is true, otherwise false. ``` [Answer] # [Python 2](https://docs.python.org/2/), 108 bytes ``` lambda d,e=enumerate:min(max(d[l:l+b].count(k)%2for(k)in d)for b,c in e(d[2:],2)for l,f in e(d) )#b =:x+.%2# ``` [Try it online!](https://tio.run/##vY1BCsMgFESv8iGE@Ilk4VLwJG0WGpVK9StBITm9ldIzdDVvHgNT7vrKJLpXzx51MlaD5U45asmdujqZArGkL2YfUcbV7NuRG1X2xln4fI4MBBYHguEHjOLGVMidi6@M3P8kAk4GlLzWbRZTL2egCp4FKq0yxL788375AA "Python 2 – Try It Online") -2 thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Œε¢Pà}KŒIKεSIS¢ÈP}àÈ ``` Outputs `1` if the string is well-linked, and `0` if the string is not well-linked. [Try it online](https://tio.run/##yy9OTMpM/f//6KRzWw8tCji8oNb76CRP73Nbgz2DDy063BFQe3jB4Q5C8gA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXjC4Qmh9koKunYKSvb/j046t/XQooDDC2q9j06K8D63NTgi@NCiwx0BtYcXHO74r/M/WglFiSdIiSeSEiUdpcSk5KTEZDAjKRnMSAICMD8xOSkZpiIpOQXKTE5UigUA). **Explanation:** The base program is `ŒsKεsS¢ÈP}à` (**11 bytes**), which outputs `0` if well-linked and `1` if not well-linked. The trailing `È` (is\_even) is a semi no-op that inverts the output, so `1` for well-linked strings and `0` for not well-linked strings. The other parts are no-ops to comply to the challenge rules. ``` Œε¢Pà}K # No-ops: substrings, map, count, product, maximum, close map, remove # Due to the last remove, we're back at the (implicit) input again Œ # Take the substrings of the input IK # Remove the input itself from that list of substrings ε # Map each substring to: S # No-op: transform the substring into a list of characters IS # Get the input-string as a list of characters ¢ # Count the occurrence of each character in the current substring È # Check which counts are even (1 if truthy; 0 if falsey) P # Take the product of that }à # After the map: check if any are truthy by taking the maximum È # Semi no-op: check if this maximum is even (0 becomes 1; 1 becomes 0) # (and output the result implicitly) ``` ]
[Question] [ Starting an the origin on an infinite grid, you follow a predetermined path going up (`U`), down (`D`), left (`L`), or right (`R`). You paint every square you visit, including the square you started at and the square you finish at. Using this method, we can paint the number six using the instructions `RRDDLLUUUURR`: [![](https://i.stack.imgur.com/Nv0z2.png)](https://i.stack.imgur.com/Nv0z2.png) The origin is shown as a green star. We call this a *positional encoding* of the number six. Note that a positional encoding is not unique; the encoding `LLUURRDDUULLUURR` also encodes the number six with some redundancy: [![](https://i.stack.imgur.com/Tkf6J.png)](https://i.stack.imgur.com/Tkf6J.png) Note that if you visit a square you've already painted in your path, you leave it as is. ## Challenge Given a positional encoding of one of the digits zero through nine taken as a string, output which digit it encodes. All digits will be encoded in a \$3\times5\$ format as follows: ``` # ### ### # # ### # # # # # # # ### ### ### ### # # # # # # ### ### # ### ### ### ### ### ### # # # # # # # # ### # ### ### # # # # # # # # # # ### # ### ### ### ``` Note that: * The positional encoding given will always map to one of the ten digits given above exactly; the input string is guaranteed to be valid. * The digit will never be mirrored or rotated. * There may be redundancy in the encoding (eg `LR`). * The square you start at is always painted. ## Test Cases ``` Input -> Output DDDD -> 1 UUUU -> 1 DDUDDUDD -> 1 DDUUUUDDUUDD -> 1 LRRDDLLDDRLRR -> 2 LDDRRLLUURRUULL -> 2 RRDDLLRRDDLL -> 3 LLRRUULLRLRRUUDULL -> 3 LUUDDRRUUDDDD -> 4 DDLLUUDDRRDD -> 4 LLDDRRDDLL -> 5 DLLRRUULLUURRLLRR -> 5 RRDDLLUUUURR -> 6 LLUURRDDUULLUURR -> 6 RRDDLLUURRDDLLUUUURR -> 6 RRDDDD -> 7 LLRRDDDD -> 7 LUURRDDDDLLU -> 8 RUULLUURRDDLLDD -> 8 RRDDLLUURRDDDDLL -> 9 DUDLRLLRRUULLRRUULLD -> 9 RRUUUULLDDD -> 0 UUUUDDDDRRUUUULRDDDD -> 0 ``` Also in list form: ``` [['DDDD', 1], ['UUUU', 1], ['DDUDDUDD', 1], ['DDUUUUDDUUDD', 1], ['LRRDDLLDDRLRR', 2], ['LDDRRLLUURRUULL', 2], ['RRDDLLRRDDLL', 3], ['LLRRUULLRLRRUUDULL', 3], ['LUUDDRRUUDDDD', 4], ['DDLLUUDDRRDD', 4], ['LLDDRRDDLL', 5], ['DLLRRUULLUURRLLRR', 5], ['RRDDLLUUUURR', 6], ['LLUURRDDUULLUURR', 6], ['RRDDLLUURRDDLLUUUURR', 6], ['RRDDDD', 7], ['LLRRDDDD', 7], ['LUURRDDDDLLU', 8], ['RUULLUURRDDLLDD', 8], ['RRDDLLUURRDDDDLL', 9], ['DUDLRLLRRUULLRRUULLD', 9], ['RRUUUULLDDD', 0], ['UUUUDDDDRRUUUULRDDDD', 0]] ``` ## Scoring Shortest code in bytes wins. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~89 ... 77~~ 71 bytes *Saved 6 bytes by using the modulo chain provided by @KjetilS.* ``` s=>Buffer(s).map(c=>o|=p*=4**(c%5)/8,o=p=4**8)|(o/=o&-o)*321%3081%53%11 ``` [Try it online!](https://tio.run/##jZPBboMwDIbvewoUiSlBaykFNnZID1OOPkXKAyAK06auQWXbqe/OSAwdJQXVQiGIjz/2b/OZ/@ZNcfqov1dHvS/bircN3739VFV5og1bf@U1LfhOn3kd8CQIaOGnLMyeNK/NY8bOVIdcP640C@Jt5MebLPLT2I@ittDHRh/K9UG/04oS0QXxJsGYF4Ze9DBhVRf3skIoe5H72C7MOuJnWJBSCAAhZLcjV@zWYTtKAiglpVIAZIlFWVwnOcSOLqCgtHeB0nOsKcpiI6ORTVwfoMcdHxI3B@RG2Q5s6ugOCRsnoPdthkVN049/e3v22c3BUKZvuCML7KB7pb/AOlOJ7MutXjj0HIvH2wQmtWVODkNROG1kkR3VdukIsq9OL5QAeRkguwoyw5rXFhiXh@zm1r9pTu@/QU96tv0D "JavaScript (Node.js) – Try It Online") ### How? We take the ASCII code \$c\$ of the direction character modulo \$5\$ to map it to an index in \$\{0,1,2,3\}\$. For each direction, we update a bit mask \$p\$ by shifting it by a specific amount and mark the bits that are visited in another bit mask \$o\$. ``` char. | ASCII | mod 5 | shift -------+-------+-------+------- 'U' | 85 | 0 | >> 3 'L' | 76 | 1 | >> 1 'R' | 82 | 2 | << 1 'D' | 68 | 3 | << 3 ``` Conveniently, the shift is equivalent to multiply \$p\$ by: $$\frac{4^{(c\bmod 5)}}{8}$$ We start with both \$p\$ and \$o\$ set to \$4^8=2^{16}\$. This value is safe because we will never right-shift by more than \$4\times 3 + 2\times 1=14\$ (e.g. with `"UUUULL"`, which draws a \$7\$, or any other path going from the bottom-right to the top-left corner). Likewise, we will never left-shift by more than \$14\$ and never exceed \$2^{30}\$. So, both \$p\$ and \$o\$ remain 32-bit values. Because we don't know which cell in the digit was our starting point, we normalize the final value of \$o\$ by removing all trailing zeros: ``` o /= o & -o ``` We end up with a unique 15-bit key identifying the digit. ``` digit | binary mask | decimal -------+-----------------+--------- 0 | 111101101101111 | 31599 1 | 001001001001001 | 4681 2 | 111001111100111 | 29671 3 | 111100111100111 | 31207 4 | 100100111101101 | 18925 5 | 111100111001111 | 31183 6 | 111101111001111 | 31695 7 | 100100100100111 | 18727 8 | 111101111101111 | 31727 9 | 111100111101111 | 31215 ``` It can be seen as a binary representation of the digit shape rotated by 180°. For instance: ``` 100 111 100 001 100 100 100 100 111 -> 100 -> 001 -> "7" 100 001 111 001 ``` We apply the following function to turn it into the expected digit: $$f(n)=\big(((n\times 321)\bmod 3081)\bmod 53\big)\bmod 11$$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~70~~ ~~65~~ ~~63~~ ~~60~~ ~~58~~ ~~43~~ 38 bytes ``` F⁺SR«UMKVIΣκ✳ι1»≔↨KA²θ⎚§”←&Φ⁴.º!H”﹪θ⁹⁴ ``` [Try it online!](https://tio.run/##JY3LCsIwEEXX9itCVhOo4PuBq9pshCqlUvehjRpME81DBPHbY6qLCzPMmXObKzONZjKEszYISukt7NTdu6MzQl2ApAhXmKB3Mtize667jqkWSs5vJ60O3MdV9VDOrIOj7@BGCNkkgzJ@O6DC8MYJrUD0ojGOp0@SWSsuCrbM8p8pk7JXTGIeEcglZwbi8Hdkbqda/gI8X6DRarxE6@kMTXCK9rr1UsMjRetZXxpCVddFUddVRWlRUBqGT/kF "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁺SR« ``` Append a dummy instruction to the input to ensure that both ends get drawn, and loop over the instructions. ``` UMKVIΣκ ``` Pad the neighbourhood of each cell. (This is because `PeekAll()` only returns the drawn cells and not their positions, so it would be impossible to distinguish between the groups `69`, `08` and `235`.) Each orthogonally adjacent cell is replaced with its digital sum, which is `1` for cells on the path and `0` for all other cells (whether new or previously padded). ``` ✳ι1» ``` Draw the path using literal `1`s and move in the appropriate direction. ``` ≔↨KA²θ ``` Record which of the cells were drawn and which were just padding, and interpret that as if it was binary. ``` ⎚ ``` Clear the canvas. ``` §”←&Φ⁴.º!H”﹪θ⁹⁴ ``` Cyclically index the compressed lookup table `56 0817 934 2` (where the spaces are don't care values) with the base 2 number captured above modulo 94 and output the result. It's possible to shrink the uncompressed lookup table to 11 bytes `0473125869_` by taking the number modulo 378 for the same byte count, or to 10 bytes `8739651204` by taking the number modulo 4207, but this ends up actually a byte longer after compression, so instead if you capture the number in base 5 rather than base 2, then by taking it modulo 579 you can cyclically index the result in the table `7269105348` also for the same byte count. Example digit decoding: Drawing `RRDDDD` results in the following canvas: ``` 000 01110 0010 010 010 010 0 ``` Reading these gives `0000111000100100100100` which is 231716 in binary, then reducing modulo 94 gives 6, which (cyclically) indexed into the lookup table produces `7`, the desired result. [Answer] # [J](http://jsoftware.com/), 75 65 59 55 bytes *-10 thanks to Jonah!* *-6 thanks to Bubbler!* *-4 thanks to FrownyFrog!* Identifies the numbers by their bit mask of the following positions: ``` #0# 1 2 #3# 4 # ### ``` So 8 would be `11111`, and 7 would be `10100` ``` '=)76.:;4?'i.4 u:2#.1,i.@5(e.>./-:@->:)0+/\@,3-2*5|3&u: ``` [Try it online!](https://tio.run/##nZFNT4QwEIbv/IrGTWxZYFi@drW7rESJp8ZDE06aGGN2I1487UnjX8dOhwK6fiQ2UOg7M0/faZ@7E@B7VkrGWcgWTJo3Anal1XXHS3@1BLnOL3gLOTvIdAZJ2EJViB1sIY5kFW2lvwjiuyrMonRevGWnB9mxm0tgnpjJB2hhhGy530IiQrGR0QZifwfv6RxpPeE@CxzC@wvhAEnwP0R4KwOIK0GgMv6F43sI@okjqLLwX78QDS35DuftHp9emFjvfcZrM3jHuZewku37tVs0ZkwijX2mghk4o5iSqLSua6XqWpu/UTVrrVTTaN00SnEvI52SaR5EFDBL229t8/M@hHtZ1drMnRHVB1AsHIUErO6l2pHRh7L@llMf2M5EpDzsj/6Osj9XrcYg2liNzZBwNrRAiqkcxMEVnR33zo93olb6gLkIpYeDsrOpWrgq9ISgUaOrosMzMfL0AQ "J – Try It Online") ### How it works ``` 3-2*5|3&u: ``` Map `DRLU` to `-3 -1 1 3`. (Thanks to Arnauld!) ``` (>./…-…)0+/\@, ``` Append 0 (the drawn starting tile), and fold every prefix to absolute indices, e.g. `0 1 2 5 8 11 14`. As an index might be negative, get the highest number and subtract it from every index. ``` i.@5(e.…-:@…>:) ``` Checks which of the indices `1 3 5 7 9` are set: `1 0 1 0 0`. ``` '=)76.:;4?'i.4 u:2#.1, ``` The bit masks with a 1 prepended (so the numbers neatly fit into ASCII) is looked up in the table. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ ~~34~~ 32 bytes ``` O%15Żı*ÄÆiḞ_Ṃ$‘ŒṬFḄ%29ị“ẆA⁻R§’D¤ ``` [Try it online!](https://tio.run/##XVCxCgIxDP2XQxdxUXBwFIJTQAh0cHJyUPwBt1NEBzcnBXESXG5xO73N0w9pf6Q2yVXFUJKX5DUv7XQ8m829H9RbnVfxvDbKVbme2Pw0srdlzaX7187esr7NV/V21xZblx7tfd1zi4IeF5ce4HH25cYts6H3CQRLmokJFgKAkaMwGHtJkQgAEYAC4jwgQjSGyBjEUFGCeiagdkgiKAd5muRQiWBVUhFUKFyIE1gDVVWbvJguIT3eUdEP44/JaSXxhcoSHlPiFH3n36y4lAGkz9PEK5OV@Fr8TL5RVVXvDQ "Jelly – Try It Online") *-1 thanks to Zgarb fixing my brainfart* *-2 thanks to Jonathan Allan reminding me of `Ż` and rearranging to remove a space* I have no idea what I'm doing... Going all the way through `Ḟ‘ŒṬ` feels like it may not be necessary with a smart choice of hash function, and it's not a terrible idea to just try translating Arnauld's JS answer outright. I've tried quite a few dumber hash functions, and they've all gotten tripped up on 2 versus 5, but maybe if I keep using base conversion... ``` Ä Cumulative sums of ı* sqrt(-1) to the (vectorized) power of O the codepoints of the input %15 mod 15 (U,D,L,R -> 10,8,1,7 ≡ 2,0,1,3 mod 4) Ż with 0 prepended. Æi a + bi -> [a, b], Ḟ convert the floats to integers, _Ṃ$ and subtract the minimum. ‘ Increment so that all indices are positive, ŒṬ then convert them to a multidimensional Boolean array, F flatten it, Ḅ convert from binary, %29 mod 29, ị modular index into D¤ the decimal digits of “ẆA⁻R§’ 813540020976. ``` [Answer] # [Perl 5](https://www.perl.org/), ~~96~~ 84 bytes ``` $s=0 x99;substr$s,$p+=ord()*9%45%7-3,1,1for$p=49,@F;$s=~/1.*1/;$_=$&*8%29014%1637%11 ``` [Try it online!](https://tio.run/##VVDBasMwDL37K0qxx5ama72ma00I7CB60sngc9nYBoOymLiFnfbp8/zsNFBhpCfp6Vm2/xhO2xhl6NazH2PacHkL50GGWvpF1w/v9w@VUc1W7ZabWtf6sx@k7xpTvxzaNPO70o@VXrXy2Mm7aq@ezFo3Sj9vdkrrGCmZcMkEkcsHIBl8SthaImYim5BAtMzOWescsyjN4gUAqjZHQp@hkTPKwjwWIMwFJBZdJ6ELPOpiDVya69inoKl7w0KSZa@g9DNDTOrlLTcKZQVHbKcHZA8WtDFQvgjcsZbn/np//uq/Q1y@@tNhPv8H "Perl 5 – Try It Online") Somewhat ungolfed: ``` cat <<'.' > recognise.pl $s=0 x99; #init string of 100 zeros substr$s,$p+=ord()*9%45%7-3,1,1for$p=49,@F; #replace 0 with 1 for each step of #input char, start at pos 49, -3 for U, 3 for D, -1 for L, #1 for R. ord() is ascii val of UDLR $s=~/1.*1/; #find longest substring that starts and ends with 1, treat #that string as a long int, i.e. 8 = 111101111101111 $_=$&*8%29014%1637%11 #modulus voodoo to get the digit . cat <<. | perl -F"" -apl recognise.pl DDDD UUUU DDUDDUDD DDUUUUDDUUDD LRRDDLLDDRLRR LDDRRLLUURRUULL RRDDLLRRDDLL LLRRUULLRLRRUUDULL LUUDDRRUUDDDD DDLLUUDDRRDD LLDDRRDDLL DLLRRUULLUURRLLRR RRDDLLUUUURR LLUURRDDUULLUURR RRDDLLUURRDDLLUUUURR RRDDDD LLRRDDDD LUURRDDDDLLU RUULLUURRDDLLDD RRDDLLUURRDDDDLL DUDLRLLRRUULLRRUULLD RRUUUULLDDD UUUUDDDDRRUUUULRDDDD . ``` [Answer] # [R](https://www.r-project.org/), 314 bytes Not very short unfortunately, feels like the extra illegibility isn't worth it here. ``` {f=pryr::f f(w,{s=switch l=f(t,t[length(t)]) a=f(t,s=0,c(t,l(t)+s)) v=f(c,s(c,U=-1,D=1,0)) h=f(c,s(c,L=-1,R=1,0)) m=f(l,b,x=0,{for(c in l)x=a(x,b(c)) x}) z=el(strsplit(w,'')) x=m(z,h) y=m(z,v) p=x-min(x) q=y-min(y) r=p+q*3 u=unique(r) d=trunc(10*(var(u)+median(u)))%%28 match(d,c(0,5,20,3,2,16,1,26,8,19))-1})} ``` [Try it online!](https://tio.run/##hVLBbqMwEL37K5BWVexmIgHZpGkl9@SjT0g@VXugBBIkoAmYlDTKt6djExLSJeoIzOi95/G8MeVpFetlukq1w53TIeGbcl@@vCQkoZ9wqHj1mepoTTKeUA36LYuLlV5Tzf4xElqs4i5E@M0QHFeMkR3CEVT4Kj7xQHAPXITXF1gaODjDOcIZvEODZQ7JR0kjJy2cjDU8pA280wg1DkZzZOSLxxmtdFltslRje6MRkg3P6ResGdnbZMfIhjeTPC1ow8iW7226Z6Tkm/H2cUpqXhfpto5pyciS67IuIuq5j3QXlrRm4zxepmGBGWMPD/6C5CHap0u06MIMfBem4IM3Bw/8OSzAe2Zs4h3Z8TJGOhIYI@b8cSavjkeuuMIYwoVQ9rnDYZh1mJdBIISUQgSYdQK/L0AqkFKpIFBKyiFJW6JdO37aLyHbvYH9CnVHZVq0gp79vzdW5FkzzFsXN03M@ru7LowT2TM7@8@JmdiVn98cYRgzzTYb0nQ1fqtl@KuRpx/zusu1hW3pjl/0q3attbc6KOk12J/Wc39aSsjgcm92FUM6Q1nyepT74481h5xlN67c0zc "R – Try It Online") Intermediate calculations from: ``` letters=list( x1=c(0,3,6,9,12), x2=c(0,1,2,5,6,7,8,9,12,13,14), x3=c(0,1,2,5,6,7,8,11,12,13,14), x4=c(0,2,3,5,6,7,8,11,14), x5=c(0,1,2,3,6,7,8,11,12,13,14), x6=c(0,1,2,3,6,7,8,9,11,12,13,14), x7=c(0,1,2,5,8,11,14), x8=c(0,1,2,3,5,6,7,8,9,11,12,13,14), x9=c(0,1,2,3,5,6,7,8,11,12,13,14), x0=c(0,1,2,3,5,6,8,9,11,12,13,14) ) sapply(letters,function(letter){trunc(10*(var(letter)+median(letter)))%%28}) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Yes, it's very similar to [Unrelated String's](https://codegolf.stackexchange.com/a/211016/53748), but it's slightly different and was completely independently found. ``` O%15Żı*ÄÆi_Ṃ$QṢ“X|cE’Dṭ⁽½ȯ¤ḥ ``` **[Try it online!](https://tio.run/##VVCxCsIwEN3zHbq4OfgH53YgBgJuDuKg9AcEh1pEv0FwEt0UERwspUur4G@kPxLzLm3BI9y9u3v3cslyHkUr50bd/uCTvR@9clvuFlObJp2xTU9VfJysZ8MqPpBNb9UmL/LvvTjb18XZ7Fnuq@TqHHlTxpsiMnIAvMH7hLUmYibSHilEzWyM1sYwq9AMXgGgqiUS@gwNyUiEuS5AmAPwLGomoQtc62INXCp17BNQ2/1jIRHZBoS@MFSrHt7ypxBWMMS6fYB4sKCNgfBF4NY1mfsB "Jelly – Try It Online")** If a larger salt (which is also less than \$250^6\$) for the hash built-in is found which removes the need to permute \$[0,9]\$ (making `“X|cE’Dṭ⁽½ȯ¤ḥ` become `“?????’,⁵¤ḥ’`) we get 27 (or less). ### How? ``` O%15Żı*ÄÆi_Ṃ$QṢ“X|cE’Dṭ⁽½ȯ¤ḥ - Link: listof characters O%15 - mod 15 of ordinals Ż - prepend a zero ı* - root(-1) raised to each of those Ä - cumulative sums Æi - convert each to [real, imaginary] _Ṃ$ - subtract of the minimum from each Q - distinct values Ṣ - sort ¤ - nilad followed by link(s) as a nilad: “X|cE’ - 1398462570 D - to decimal digits (our domain) ⁽½ȯ - 3742 (our salt) ṭ - tack -> [3742,[1,3,9,8,4,6,2,5,7,0]] ḥ - hash (the sort results using that [salt, domain]) ``` --- Previous version at 31 bytes using no built-in hash function... ``` O%15Żı*ÄÆi_Ṃ$QṢFḞḌ%⁽¥Ƭị“ċḞƒø’D¤ ``` A monadic Link accepting a list of characters which yields an integer in \$[0,9]\$. **[Try it online!](https://tio.run/##VVAxCsJAEOzvHdrYWfiDxWpBPLjaykLxA3ZRRItY2QliIdqlESwiwSbR/OPykfNmLwlkOfZmZ2cne1nOV6u1c5P@cPTLvs9BsSv2i5l9b3tT@76NbXq16bFfbT75o0xsFlfR5Rt7tjwVaRWdKb87m72KQ7VNnCMfyvhQREYOgA9kX7DWRMxE2iOFWzMbo7UxzCo0Q1YAYLXchD7DQyoSY64JGHMAXkXNJHyBa1@sgY8Kj30CarsdFQqxbUDoi0K17uEtHYewgiHW7QMkQwVvDIRfBG3Nydwf "Jelly – Try It Online")** ### How? ``` O%15Żı*ÄÆi_Ṃ$QṢFḞḌ%⁽¥Ƭị“ċḞƒø’D¤ - Link: listof characters O%15Żı*ÄÆi_Ṃ$QṢ - as above F - flatten Ḟ - floor (so Ḍ gives an integer rather than a float) Ḍ - convert from base ten %⁽¥Ƭ - modulo 2153 “ċḞƒø’D¤ - decimal digits of 3652914780 ị - 1-indexed modulo index into ``` [Answer] # [R](https://www.r-project.org/), ~~217~~ ~~200~~ 192 bytes (or only **[169 bytes](https://tio.run/##jZNfa8IwFMXf/RTiCCQugml1q0L3lJdBnsL6JN0crUphRmcb0I19dpd/utpGWSgxhd89nntuujvuFtlmJYqvxVterIoqPi6lyKpiI2CJZSyrZfSyeRYV@s7j8n27/TjADA6xhCVCeA4KAeZ4H0vYozxhPYQ6IrZUPiPTAKeDfBZORzjFBJ@F9wge4kyuS7lWZzRYFwIeVKl@D16lKD7lAoZ9McMkvVd7kKJ@GBAEQDiMCADjEABCfprWlQe1eqjbWHfdwVOXdFp0otb/aUoT81xW3KDV0nu9wtFtnHFOKWOUcnU68wYPPLTiOGNJwnmSMOZ4R7dxq233hpfQI86sKje/1Ok72oPrDg1Zz97gI18szBW0Yhn5xJlF674dPvaIn6zrYNgpSEdfi0WPqRa5xR98VjSnB2pPtuIafdK@/A9H@/H2zTX4o39Cbd7R3glZXhlp9Bl5rJwatPexfreizu1G/@Zk8IlnQgll/HzBzE5dLBOvuE5O26j3avCh/3PWJlyVi8jRx18)** by stealing Arnauld's modulo chain to get the final digit without a look-up table...) ``` function(s,u=utf8ToInt){d=sapply(c(0,u(s)),`%in%`,x=u("DRUL")) n=apply(d[1:2,]-d[3:4,],1,function(x)(y=cumsum(x))-min(y)) match(sum(2^unique(n[,1]+5*n[,2]))%%27%%11,c(0,4,7,10,8,5,2,3,9,1))-1} ``` [Try it online!](https://tio.run/##jZNda8IwFIbv/RXiKCTbEUyt8wO6q9wMchXWK@mm1I8V1ui0Ad3Yb3f50lUbZaGkoTzn9T3viZvDZp6tliL/mr/N8mVexoeFFFmZrwTagoxluRi8rJ5Fib9n8Xa6Xn/sUYY6INEWY5gEuQgmsIslalGesBbGDRFbajYmoxDS9mzcHUWQAoGT8A6jfZzJYisLdcbtIhdor0qLaZm9I/01fJUi/5RzJMZA0ofevXqHKcZBEPaDgBDQHiLoA@nAAHoQQheGQJQW@bnsSFlTq4WbF@uu2X5qkkaNTtT6P01pYp7zihu0WnqvVji6jjPOKWWMUq5OJ97goYdWHGcsSThPEsYc7@g6brXtfuGl6xFnVpWbN3X6jvbgukNDVrM3eOSLhbmCWiyRT5xZtOrb4T2P@NG6DoYdg3T0tVj0mCqRW/zRZ0VzeqD2ZCuu0Uft899wtB@v31yD9/0TqvOO9k7I8srIRZ8Dj5Vjg/Y@Vu/WoHG70b85GXzomVBCGT9dMLNTF8vQK66T0zaqvRq84/87axOuykXk6MMv "R – Try It Online") **How?** Original code (before significant golfing changes...): ``` recognize_digit= function(s){ # first we 'construct' the digit from the encoding: d=sapply( # d is direction of each step, calculated by... c("D","R","U","L"), # ...using each letter... grepl, # ...as a regex... el(strsplit(s,''))) # ...to search each letter of the encoding. m=matrix(!-40:40,9) # m is a matrix big enough to fit the letters (9x9) m[ # we set the elements of m, selected by... apply(d[,1:2]-d[,3:4], # ...subtracting L from R, and U from D... 2, # ...and for each of the L-R and U-D columns... cumsum)+5 # ...calculating the cumulative sum +5, ]=T # to 'TRUE'. l=m[(c=t(which(m,T)))[1]+0:4, # l is the 3x5 'letter' matrix, starting at the c[2]+0:2] # first TRUE elment of m # now we have the digit in l, so we just have to # recognize it: match( # we find the match between... sum(l*2^(0:14)) # the number formed by using the pixels of the digit as bits... %%27%%11, # MOD 27 MOD 11 (reduces each number to a smaller number c(0,4,7,10,8,5,2,3,9,1))-1 # and the 'lookup' table of results for each digit. } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •7‡šмÓ•žFDIÇv4y5%m8/*DŠ~s}\b0ÚC45%è ``` Port of [*@Arnauld*'s 78 bytes version](https://codegolf.stackexchange.com/revisions/211013/10), so make sure to upvote him as well! (His 78→77 and 77→71 golfs would be longer in 05AB1E.) [Try it online](https://tio.run/##yy9OTMpM/f//UcMi80cNC48uvLDn8GQg5@g@NxfPw@1lJpWmqrkW@louRxfUFdfGJBkcnuVsYqp6eMX//y6hLj5BPj5BQaGhMNIFAA) or [verify all test cases](https://tio.run/##XU8xCsJAEPyKHNiIoIWinYWL1VYHV6mFAQsLsRACKZRU2mtnZax8hNiE9L4hH4m3O55KQrib2Z2bnd1sF9FqWcXJyDTKw6lhRlWZ3gZlmhXZ65GfPSmeE0ryY9xL@s31sNOi4rrf7mZRN7@Me/1mfq/a1dRY6/zHTESmbQR7RJ@qJZTp11Xm9AfUFw6UrX8hXtYj4eLE7Jz4MfsKBDhFwOhYvQkaFjflYTp/ShjCgKql4CAzGFPRlGAIoT3JCPSnqClt2BcJAaFSnUiCC/aseYVQjth@V9OTzPwN). **Explanation:** ``` •7‡šмÓ• # Push compressed integer 31846207905 žF # Push builtin 16384 (2**14) D # Duplicate it I # Push the input-string Ç # Convert it to a list of codepoint integers v # Loop over each codepoint `y`: y5% # Take `y` modulo-5 4 m # Take 4 to the power this value 8/ # Divide it by 8 * # Multiply it by the top of the stack D # Duplicate it Š # Tripleswap (a,b,c → c,a,b) the top three values on the stack ~ # Bitwise-OR the top two s # And swap so the other value is at the top again }\ # After the loop: discard the top value b # Convert the integer to binary 0Ú # Remove all leading/trailing 0s C # Convert it from binary back to an integer 45% # Modulo-45 è # And index it into the digits of 31846207905 (0-based modulair) # (after which the digit 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 `•7‡šмÓ•` is `31846207905`. [Answer] # Batch 207 bytes Notes: * *must be run from the command line using:* `Echo(NoP pattern|Cmd /V:on` *where `pattern` is a list of movements IE*: `D D D D R R U U U U L L` * **requires windows 10 with virtual terminal support** * `ESC` is a stand in for the ANSI escape character, [As it can't be pasted here, the scripts raw paste data can be found here](https://pastebin.com/Ayg61EDx). + Or it can be generated by opening the command prompt and typing: - `>"%TEMP%\escape.chr" Echo(``ALT`+`027` then pressing `ENTER` + Or output using a for loop with `Echo off`: - `(For /F "skip=4 DELIMS=" %a in ('Echo(prompt $E^|cmd')Do Echo(%a) >"%TEMP%\escape.chr"` filename: NoP ``` @Echo off&Set $=Set &cls %$%U=A&%$%D=B&%$%R=C&%$%O=^<nul set/P =&%$%E=echo(&%$%"F=|findstr /C:"L" >nul &&" %O%ESC[6;7H*ESCD For %%c in (%*)do %e%%%c%F%%O%ESC[2D*||%e%%%c%F:"L"="R"%%O%*||%O%ESC!%%c!*ESCD %e%ESC[12;1H ``` How: the input is assessed using findstr and converted to the [virtual terminal sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#cursor-positioning) required to move the cursor accordingly using sequential `&&` and `||` conditional tests, akin to a compound series of if / else statements. ]
[Question] [ # Overview Consider the following task: > > Given a positive integer **n > 0**, output its integer square root. The integer square root of a number **n** is the largest value of **x** where **x2 ≤ n**, usually expressed with the formula `floor(sqrt(n))`. > > > Examples: `25 -> 5`, `24 -> 4`, `40 -> 6`, `1 -> 1`. > > > This task is easy enough on its own. However, in this challenge, your task is to solve this in *as many languages as possible* using a set of only *25 characters.* # Example First, you need to pick a *set* (no duplicates) of 25 bytes. It may look something like this (note the leading space): ``` ()*-.05:=>Mabdhilmnqrst| ``` Your challenge is then to, using only characters in this set, construct a solution to the problem in as many *text based* (sorry, Piet) languages as possible. You can use characters as many times as necessary, but you must not use characters outside the set. The solutions can be either *full programs* or *functions*, but not snippets. For example, using this set of characters, I could do: ``` M -> (int) Math.sqrt(M) // Java (lambda expression) M => Math.sqrt(M)|0 // Javascript (unnamed function) lambda M: int(M**.5) // Python (lambda function) ``` As I've used 3 languages, this would give me a score of **3**. Please also include the set of bytes you are using in your answer. ## Rules * This is a [rosetta-stone](/questions/tagged/rosetta-stone "show questions tagged 'rosetta-stone'") challenge - your score is the number of languages your submission includes. The highest score wins. Standard loopholes apply. * For this challenge, a 'language' counts as a distinctly different programming language - multiple versions of the same language (Python 2, Python 3, etc) are banned. * Programs only need to work for inputs within the language's standard integer range. * Programs with the exact same source code (polyglots) are not allowed. * To be more specific, it is a set of *bytes*, not characters - so you can use the 05AB1E `£` and the Jelly `ɱ` as the same character (because they have the same codepoint). Please don't feel as though you have to beat all other solutions - if you have an interesting answer, post it! [Answer] # 20 languages Using `()-#*.05;=>^Vefikloqrst` (24 characters) so far: ``` let f l=floor(l**0.5);; OCaml let f l=floor(l**0.5) F# f(l)=floor(l^.5) Julia f(o)=floor(o^.5) PARI/GP s^+>5 0>5 0*.5l Pyth (* **.5).floor Perl 6 floor.(**0.5) Haskell flr.(tt ^.5) Wonder l=>l**.5^0 JavaScript l->l**.5^0 Cheddar .5^5*5f Pyke (isqrt) Maple ri.5#i CJam isqrt Common Lisp 0.5^k MATL *.5^0 Jelly *.^0 M t0^ 05AB1E q f Japt r# Pushy V- gs2 ``` [Answer] # 10 languages Character set of 19 characters (in **CP-1252**): ``` ,-/12@QUVX^fkmt¬÷␊␍ ``` Where `␊` represents a *line feed* and the `␍` represents a *carriage return*. ([Script for checking the characters](https://tio.run/nexus/05ab1e#@19TVqludWih4eEVhzccnu1Ve3iVi4KCUmhxaopCckZiUWJySWpRsZWC@uH96ko6XArIIB2o0Cc1L70kw0rh8H4lnf//vVJzciqtQHKPJvQ@mtDFZWDq6GToChIpMYzQjeNyDzaygmgO0@Xyys9Jg/By00K5vBILSiC8Q2vSuHwdQ3wgvIi4bK6AyuxUCE/HMA3IA9kIAvoOgUYlRlz@icWZxWARQ6ClRvq5hoe3cxkVJyblpMKsjojQ1Y0DAA)) ### Jelly, 2 bytes ``` ƽ ``` [Try it online!](https://tio.run/nexus/jelly#@3@47dDe////G5kAAA "Jelly – TIO Nexus") ### 05AB1E, 2 bytes ``` t1X-^ ``` [Try it online!](https://tio.run/nexus/05ab1e#@19iGKEb9/@/kQkA "05AB1E – TIO Nexus") ### GS2, 2 bytes ``` V- ``` [Try it online!](https://tio.run/nexus/gs2#@x@m@/@/kQkA "GS2 – TIO Nexus") ### Jolf, 3 bytes ``` mfU ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=bWZV&input=MjQKCjI1) (works best on Firefox) ### Japt, 2 bytes ``` ¬f ``` [Try it here!](http://ethproductions.github.io/japt/?v=1.4.3&code=rGY=&input=MjQ=) ### MATL, 3 bytes ``` X^k ``` [Try it online!](https://tio.run/nexus/matl#@x8Rl/3/v5EJAA "MATL – TIO Nexus") ### Pyke, 3 bytes ``` ,1f ``` [Try it here!](http://pyke.catbus.co.uk/?code=%2C1f&input=24) ### Pyth, 6 bytes ``` /@Q2t2 ``` [Try it here!](https://pyth.herokuapp.com/?code=%2F%40Q2t2&input=24&debug=0) ### Oasis, 6 bytes ``` 1␊2/m1÷ ``` [Try it online!](https://tio.run/nexus/oasis#@2/IZaSfa3h4@////41MAA "Oasis – TIO Nexus") ### 2sable, 9 bytes ``` t1X-XX--^ ``` [Try it online!](https://tio.run/nexus/2sable#@19iGKEbEaGrG/f/v5EJAA "2sable – TIO Nexus") [Answer] # 5 languages Gonna add more languages soon. ### Character set (22 bytes): ``` s^Q.5=>*|0√Lrdmlab :/1 ``` ### Pyth ``` s^Q.5 ``` ### Javascript ``` Q=>Q**.5|0 ``` ### Actually ``` √L ``` ### CJam ``` rdmQ ``` ### Python ``` lambda Q:Q**.5//1 ``` [Answer] # 5 languages ``` [].,+<>{}()0134879 ``` 18 characters. I'm trying not to use any alphabet characters... **[Brainfuck](https://tio.run/nexus/brainfuck#7ZmxDcQwDAMHUvBVSoKLGNp/DEeW3/gHMgKpKnB5oEkqntcYjJ6BEB2G9iSHOIE/BcA0EEwA8qJgAJlXco84jgFYFOUUrQp7RHtEyGMoDtxGQWtiwch2iYLRZNaZeLkqGGEI8hX7lIjv9VgfzlJ5y0wHRwsBCTcqytukY0LeEL1od4OGreAXD44G7aldEt0QXJQKw/7ZwL1qn1cbkzl3JfmRD9G0KF6imPO@Hw), [Brainfuck++](http://www.jitunleashed.com/bf/index.html), [Brainfuck-ng](https://github.com/elboza/brainfuck-ng/), [Braintrust](https://gist.github.com/Sgeo/fe54715fc61d1d98f4cc), ...** ``` ,[[>++++++[<++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++<]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+>]<<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+<<]],]>>>>>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[<<<<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+>+<<]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+>]<<+[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<+>>>>+<<]>>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<+>>]<<<<[>>[<+>>>+<<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<[>+<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>>>>>>>>+<<<<[>>>+<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<<]>>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+<]<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+>]<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<<<<<<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<++++++++++>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[<+<<]<[+[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+<]<+<<]>>>>>]<<<[<++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++<]>.[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]]++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++<]>. ``` Doesn't work for over `224` because `256` (= (sqrt(225)+1)^2) overflows. Replaced all `-`s with `+`s to use one less character. (e.g. `-` -> 255 `+`s) *Original Program* ``` ,[[>++++++[<-------->-]>[->++++++++++<]>[-<+>]<<<[->>+<<]],]>>>>>>>-[<<<<<[->+>+<<]>[-<+>]<<+[-<<+>>>>+<<]>>[-<<+>>]<<<<[>>[<+>>>+<<-]<[>+<-]<-]>>>>>>>>+<<<<[>>>+<<[->+>[-]<<]>>[->+<]<[-<+>]<-<-]>[-]>>>-]<<<<<<-<++++++++++>[-<-[<+<<]<[+[->+<]<+<<]>>>>>]<<<[<++++++[->++++++++<]>.[-]]++++++[->++++++++<]>. ``` **[Brain-Flak](https://tio.run/nexus/brain-flak#TU3BDQAxCFoH/t2mcRLj7D2wvaYPDSDgQhZATjBokOYSiQOk6ZyVR2xnZYVDokaKzrcomDva/r3IcD3aqarQ8IKnqnzu9X9ba4wP)** ``` ({}(())[()])(()){{}((({})({}((({}())))[{}{({})({}[()])}{}]))[({}[{}])])([({}(())[()])]){(({}()({}[(({}[(())]()){(([({}{})]{}))}{})]{}))[({}[{}])])}{}{}}{}{}({}[()]) ``` @WheatWizard's code. Thanks for the permission! **[Brain-Flueue](https://github.com/Wheatwizard/Brain-Flueue)** ``` ({}())(())(())({}){{}({})({}<(({})<({({})({}[()])}{})>())>)([{}]<({})>({}))({}<‌​({}<([({})]){()<({}())>}{}(<()>){({}[()])([{}]())}{}>)>)({}<({})>)({})({})}{}({}[‌​()()]){} ``` Another @WheatWizard's code. **[Numberwang](https://tio.run/nexus/numberwang#7ZnRDQMxDEJXAtWSz/sPljpOo1bqCOCvUz6fCODLeiJQM8ESHZT2JEKcwI8CaBosJEl5UaDIzCdxRhxHkBZFO8Wowh4xHlHyGJoDjlHAmtgwclyiYQyZfSZerhpGGYJ8xb4l4nM99oezVN4y08ExQmDSjQryNumYkDdEL9rToGkr@MaDo0F7epfkNAQXpcZwfjbgrNr31cZk7l1JvORDNC2KP1GsFfEG)** ``` 8440999999419999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999909999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997049999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990999999999917049999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999991907111499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999900911778700000009999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999994111114999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999090911704999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999190711949999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999991190000911700499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999911900711114004190009119999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997140919999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997199999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999970000000091111400091149999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990904999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999711700499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999909171499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999919071999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999199999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999970499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999970009999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997111111999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999199999999990499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999919999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999994191171494999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999091719117000007111419999994999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999099999999170349999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997799999949999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990999999991703 ``` **[Spoon](https://web.archive.org/web/20140228003324/http://www.bluedust.dontexist.com/spoon)** ``` 00101100010000100010111111001000110000000000000000000000000100000011010001000000101111111111011001101000100000011101000110110110110010000001001010110110011001100101100011010010010010010010010000001000110110110110110010000001010101011011001101000100000011101000110110111001000000110111010010010010101101100110100100010000001101110100100011011011011011001000100100010001110100100101011011000001101100100010101100000110110000011010010010010010010010010101101101101100100010010010101101100100000010101000100000001101101100110100100010000001010110011011001000000111010001101100001100000110100010000000110100100100000011011011011011011011000011111111111101000100000011000001000111011011001101100100100100000010101100110111011011001101001001001001000110110110110010001111111100100000010111111110110011010001010001000000011001111111100100000010111111110110011010001010 ``` [Per meta consensus,](https://codegolf.meta.stackexchange.com/a/11055/60043) this code should be okay, even though no interpreters are currently available. [Answer] # 5 languages Using `()*/12 dlinpqrstu` and newline (18 characters) so far. ### Common Lisp ``` isqrt ``` A built-in function. ### QBasic ``` input q print int(sqr(q)) ``` ### Python 3 ``` print(int(int(input())**(1/2))) ``` Python 3 used for floating-point division without decimal points. ### Pip ``` q**/2//1 ``` Unnecessarily golfy to show off the unary inversion operator `/`. Takes input from stdin. [Try it online!](https://tio.run/nexus/pip#@1@opaVvpK9v@P@/iREA "Pip – TIO Nexus") ### [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) ``` (d sqrt (q((n nsqr input) (i (l input nsqr) (s n 1) (sqrt (s n (s 1 2)) (s 2 (s (s (s 1 n) n) nsqr)) input))))) (q((input)(sqrt 1 1 input))) ``` `sqrt` is a helper function whose arguments are: the current guess `n`, `n` squared, and the `input` number. If `input` is less than `nsqr`, we've gone too far, so return `n` minus 1; otherwise, recurse, adding 1 to `n` and adding `n + n + 1` to `nsqr`. (The math is a bit complicated because tinylisp only has subtraction built in.) The second line defines our actual function, which takes a single `input` and returns the result of `sqrt` with `n` starting at 1. [Answer] # 6 languages Using `retun flosq(agm1)\,i` and extended codepoints `B1` and `BC` for 22 bytes so far. **GameMaker Language** ``` return floor(sqrt(argument1)) ``` **Pyke** ``` ,1f ``` **Julia** ``` isqrt ``` **Maple** ``` (isqrt) ``` **Stuck** ``` i\ ``` **TI-Basic (hex dump)** ``` B1 BC 72 ``` Note that 0x72 is `r` in ASCII. [Answer] # 7 languages `24` chars: ``` limQi->(nt)Mah.sqr_ ?;:\ ``` ### [CJam](https://esolangs.org/wiki/CJam) ``` limQ li e#Read Int mQ e#Integer square root ``` ### [Java](https://www.oracle.com/java/) ``` i->(int)Math.sqrt(i) ``` ### [Chaincode](https://code.sololearn.com/cAw9mAl5Q9AX/?ref=app) ``` q_ q #sQuare root _ #floor ``` ### [Math++](https://esolangs.org/wiki/Math%2B%2B) ``` _sqrt ? ``` ### [Grin](https://esolangs.org/wiki/Grin) ``` ;q: ``` ### [Stuck](https://esolangs.org/wiki/Stuck) ``` i\) ``` ### [Unilinear](https://esolangs.org/wiki/Unilinear) ``` iMivMiMs i Read input Mi Convert to int v Square root Mi Convert to int Ms Convert to String ``` ### R ``` sqrt ``` ## Costs too much bytes ### [Python](https://www.python.org/) ``` lambda i:int(i**.5) ``` ]
[Question] [ Today is [Bacon Day](http://www.nationaldaycalendar.com/bacon-day-december-30/) which is probably why the name of the hat for participating today is "Mmmm Bacon". What better way to celebrate bacon day with fun filled 2d matrices made out of bacon! A 1 by 1 bacon strip is represented by this: ``` ----- )===) (===( )===) ----- ``` You goal here is given two coordinates in a tuple, (`x`, `y`), where `x` and `y` are nonzero positive integers, you are to create the bacon and return in some format (list, array, string). **Input and Output:** ``` Input: (2, 1) Output: ---------- )===))===) (===((===( )===))===) ---------- Input: (1, 2) Output: ----- )===) (===( )===) ----- )===) (===( )===) ----- Input: (2, 2) ---------- )===))===) (===((===( )===))===) ---------- )===))===) (===((===( )===))===) ---------- ``` **Rules:** * As you can see with the second test case, if multiple pieces of bacon are stacked together, only one `-----` separates with each piece of bacon above and/or below it. That means stacking bacon like this is invalid: ``` ----- )===) (===( )===) ----- ----- )===) (===( )===) ----- ``` * Standard loopholes are forbidden * The code must work for the above test cases and the following: `(4, 4)`, `(1, 6)`, `(5, 1)`, `(2, 3)`, `(3, 2)` * Provide an interpreter where the above test cases can be tested **Winning Criteria:** Shortest code wins! Happy Bacon Day to everyone! [Answer] # [V](https://github.com/DJMcMayhem/V), ~~28, 26~~, 24 bytes ``` Ài)³=)Y4PÒ-G.MÓ)/( kÀäG ``` [Try it online!](https://tio.run/nexus/v#ASUA2v//w4BpKcKzPSkbWTRQw5ItRy5Nw5MpLygKa8OAw6RH////Mv81 "V – TIO Nexus") Explanation: ``` Ài " Arg 1 times insert: )³=) " ')===)' <esc> " Escape back to normal mode Y " Yank this line 4P " Paste four times Ò- " Replace this line with '-' G. " Repeat on the last line M " Move to the middle line Ó)/( " Replace ')' with '(' k " Move up (to the second line) À " Arg 2 times äG " Duplicate everything up to the last line ``` [Answer] # TI-Basic, 80 bytes This one was actually quite genius :) ``` ":→Str0:Input :For(M,0,4Y:For(N,1,X:")===) If not(fPart(M/4:"----- If .5=fPart(M/4:"(===( Str0+Ans→Str0:End:Ans+":→Str0:End ``` [Answer] # Python 2.7, 74 bytes I'm sure this could be golfed some more, but this is what I came up with (Python's string multiplication feature sure comes in handy): ``` a,b=input();f="-"*5*a;d=")===)"*a;print'\n'.join([f,d,"(===("*a,d,''])*b+f ``` [Try it here](https://tio.run/nexus/python2#DcnBCoAgDADQf9llm60uEQSyL6kOigh2WBL2/ebtwetBoharXyP2WWEGt7ngkwKrKsNwfYs1PA2X@ylGR5YkQGNp7DDixS5OuXdaZecf)! Ungolfed with explanation: ``` a,b = input() # Take input from the user as a tuple f = "-"*5 * a # f is the delimiter between bacons d = ")===)" * a # 2nd and 4th lines of bacon print '\n'.join([f, d, "(===("*a, d, ''])*b + f # Join everything together! ``` [Answer] # Mathematica, 74 bytes ``` Array[b["-----",b=")===)","(===("][[#~Mod~4]]&,{4#2+1,#}]~Riffle~"\n"<>""& ``` Unnamed function taking two positive integer arguments and returning a string-with-newlines. A standard Mathematica approach: build a 2d array of strings using a (mod 4) chooser to cycle the strings in the vertical direction, then collapse them to a single string. [Answer] ## Batch, 168 bytes ``` @set s= @for /l %%i in (1,1,%1)do @call set s=%%s%%-___- @set t=%s:_==% @echo %s:_=-% @for /l %%i in (1,1,%2)do @echo %t:-=)%&echo %t:-=(%&echo %t:-=)%&echo %s:_=-% ``` Rather unfortunately I can't write `@echo %s:==-%` otherwise that would eliminate the necessity for the second variable. [Answer] # C, 91 89 bytes ``` i;f(w,h){w=w*5+1;for(i=0;i<w*4*h+w;++i)putchar(i%w<w-1?i/w%4?i%w%5%4?61:40+i/w%2:45:10);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes Code: ``` …)==û×Ь'(:s)¬g'-×=¸«»²F= ``` Explanation: ``` …)==û # Push the string ")===)" × # String multiply by the first input Ð # Triplicate the string ¬ # Take the first character, which is a ')' and push '(: # Replace by '(' s # Swap the top two elements ) # Wrap everything into an array ¬g # Get the length of the first element in the array '-× # And repeat the character '-' that many times = # Print it without popping ¸« # Append the string of dashes to the array » # Join by newlines ²F # Second input times do... = # Print the top of the stack without popping ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#ASsA1P//4oCmKT09w7vDl8OQwqwnKDpzKcKsZyctw5c9wrjCq8K7wrJGPf//Mwo0 "05AB1E – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ 30 bytes Saved 2 bytes thanks to *Adnan*. ``` '-5×…)==ûÐ')'(:s)vy¹×})I.D¬)˜» ``` [Try it online!](https://tio.run/nexus/05ab1e#AS4A0f//Jy01w5figKYpPT3Du8OQJyknKDpzKXZ5wrnDl30pSS5Ewqwpy5zCu///NAo0 "05AB1E – TIO Nexus") **Explanation** ``` '-5× # push "-----" …)==ûÐ # push 3 copies of ")===)" ')'(:s # replace ")" with "(" in the 2nd copy ) # wrap in list vy¹×}) # repeat each list entry input-1 times I.D # repeat list input-2 times ¬ # push the first element of the list ("-----") )˜ # wrap in list and flatten » # join by newline ``` [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` def f(w,h):n=4*h+1;exec"n-=1;print'-)()-===-===-===-)()'[n%4::4]*w;"*n ``` *Thanks to @xnor for saving 4 bytes!* [Try it online!](https://tio.run/nexus/python2#@5@SmqaQplGuk6FplWdropWhbWidWpGarJSna2toXVCUmVeirqupoalra2sLx0C@enSeqomVlUmsVrm1klbe/zQNIx0FY83/AA "Python 2 – TIO Nexus") [Answer] ## Python 2, 59 bytes ``` w,h=input() for a in'-()('*h+'-':print(a+3*'=-'[a>')']+a)*w ``` Generates each line as `a+b*3+a` from the initial character `a` and the center character `b` (which is calculated from `a`). The `a`'s cycle through `'-()('`, whereas `b` is `'-'` when `a` is `'-'`, and `'='` otherwise. --- **67 bytes:** ``` w,h=input() for a,b in['--']+zip(')()-','===-')*h:print(a+b*3+a)*w ``` Generates each line from its outer character `a` and center character `b` as `a+b*3+a`, then prints `w` copies of this. These cycle via a `zip`. [Answer] ## JavaScript, ~~132~~ ~~129~~ 121 bytes *-8 bytes thanks to @user2428118* ``` (x,y)=>{a=b=["-----",")===)","(===(",")===)","-----"];for(i=0;++i<y;){b=[...b,...a.slice(1)]}return b.map(v=>v.repeat(x)).join(` `)} ``` ``` (x,y)=>eval('a=b=["-----",")===)","(===(",")===)","-----"];for(i=0;++i<y;)b=[...b,...a.slice(1)];b.map(v=>v.repeat(x)).join`\n`') ``` ``` (x,y)=>eval('a=b=[c="-----",d=")===)","(===(",d,c];for(i=0;++i<y;)b=[...b,...a.slice(1)];b.map(v=>v.repeat(x)).join`\n`') ``` This can quite probably be golfed more. If you have a suggestion, please leave it in the comments. [Answer] ## Lua, 132 bytes ``` a="-----"b=")===)"c="(===("w,z=io.read(),io.read()function g(f)return f:rep(w).."\n"end print((g(a)..g(b)..g(c)..g(b)):rep(z)..g(a)) ``` Long, literal string attempt. [Try it here](http://ideone.com/qi12GT). [Answer] # JavaScript (ES6), 78 ``` (x,y,r=s=>`${s}`.repeat(x)+` `,a=r`)===)`,c=r`-----`)=>c+r(a+r`(===(`+a+c,x=y) ``` **Test** ``` F= (x,y,r=s=>`${s}`.repeat(x)+` `,a=r`)===)`,c=r`-----`)=>c+r(a+r`(===(`+a+c,x=y) function update() { var x=+X.value,y=+Y.value O.textContent=F(x,y) } update() ``` ``` X<input type=number id=X value=1 min=1 oninput='update()'> Y<input type=number id=Y value=1 min=1 oninput='update()'> <pre id=O></pre> ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 35 bytes ``` (5⁰*¤-,`)===)`⁰*:,`(===(`⁰*,,)5*¤-, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%285%E2%81%B0*%C2%A4-%2C%60%29%3D%3D%3D%29%60%E2%81%B0*%3A%2C%60%28%3D%3D%3D%28%60%E2%81%B0*%2C%2C%295*%C2%A4-%2C&inputs=2%0A2&header=&footer=) Uses magic :P [Answer] # GameMaker Language, ~~160~~ ~~139~~ ~~148 bytes~~ 133 bytes ``` x=argument0 y=argument1*4for(m=0;m<=y;m++){for(n=0;n<x;n++){a=")===)"if !m mod 4a="-----"else if n mod 2a="(===("r+=a}r+="#"}return r ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` 4“\ḊƭVṠ’bị“-=()”s5ẋ€ḷẋµ1ịṭ ``` This is a dyadic link (function) that returns a 2D array. [Try it online!](https://tio.run/nexus/jelly#@2/yqGFOzMMdXcfWhj3cueBRw8ykh7u7gWK6thqajxrmFps@3NX9qGnNwx3bgYxDWw2Bsg93rv1vdHi5caQCUBSoVME5MSdHISczL1tHoTi1ILEosSRVoSi/vFghqRIknJqWmppSrPcfAA "Jelly – TIO Nexus") ### How it works ``` 4“\ḊƭVṠ’bị“-=()”s5ẋ€ḷẋµ1ịṭ Main link. Left argument: w. Right argument: h 4 Set the return value to 4. “\ḊƭVṠ’b Yield 366323084456 and convert it to base 4. This yields [1,1,1,1,1,0,2,2,2,0,3,2,2,2,3,0,2,2,2,0]. ị“-=()” Index into that string, using modular 1-based indexing. s5 Split the result into chunks of length 5. ẋ€ḷ Repeat the characters of each chunk w times. ẋ Repeat the array of chunks h times. µ Begin a new, monadic chain. Argument: M (bacon matrix) 1ị Retrieve the first line. ṭ Tack; append it to M. ``` [Answer] # C, ~~159~~ ~~158~~ 153 bytes ``` p(s,n){printf(s,--n?p(s,n):0);}i,j;b(n,m){p("-----",n);for(j=3;j--;){p("\n",1);for(i=n;i--;)p(j%2?"(===(":")===)",1);}p("\n",1);--m?b(n,m):p("-----",n);} ``` Call with: ``` int main() { b(2,3); } ``` [Answer] ## C#, 160 bytes ``` x=>y=>{int i=0,h=4*y+1,j;var s=new string[h];for(;i<h;++i)if(i%4<1)s[i]=new string('-',x*5);else{var c=i%2>0?')':'(';for(j=0;j++<x;)s[i]+=c+"==="+c;}return s;}; ``` Formatted version: ``` x => y => { int i = 0, h = 4 * y + 1, j; var s = new string[h]; for (; i < h; ++i) if (i % 4 < 1) s[i] = new string('-', x * 5); else { var c = i % 2 > 0 ? ')' : '('; for (j = 0; j++ < x; ) s[i] += c + "===" + c; } return s; }; ``` [Try it online!](http://rextester.com/ZVXHM20542) (for some reason this link gives an error but works anyway) [Answer] ## Dart, ~~125~~ 117 bytes ``` (x,y){var t='-'*5*x,i=0;return()sync*{yield t;for(;i<y*4;i++)yield i%4>2?t:i%2>0?'(===('*x:')===)'*x;}().join('\n');} ``` Try it [here!](https://dartpad.dartlang.org/7d6f174fdc689526d61a7223b3c49a01) [Answer] # Dyalog APL, 55 bytes This is my first time using Dyalog APL, so I'm sure this isn't the best approach. ``` {(⊂'-----'),[1]⍉⍺(4×⍵)⍴')===)' '(===(' ')===)' '-----'} ``` Explanation: This is a quite simple approach, for a bacon grid of N×M, I make an N×(4M) matrix of the following four strings, repeating: ``` ')===)' '(===(' ')===)' '-----' ``` Then I concatenate the string `-----` to the beginning. Here's a quick explanation of the code: ``` ')===)' '(===(' ')===)' '-----' ⍝ An array of the four strings ⍺ (4×⍵) ⍴ ⍝ reshape (⍴) the array to a matrix with the dimensions ⍝ ⍺ by (4×⍵) (⍺ is the 1st argument and ⍵ is the second) ⍉ ⍝ transpose the matrix ,[1] ⍝ concatenate to beginning of the matrix... (⊂'-----') ⍝ ...the string '-----' embedded in its own matrix (⊂) ``` [Answer] # [Tcl](http://tcl.tk/), 91 bytes ``` time {time {append h ----- append l )===) append p (===(} $m puts "$h $l $p $l"} $n puts $h ``` [Try it online!](https://tio.run/##K0nO@Z@eWlKsUFySkpmnkMeFxMn9X5KZm6pQDSETCwpS81IUMhR0QYALys1R0LS1tdWEcQsUNIBcjVoFlVyuglKgSUoqGVwqOVwqBUBSCSicBxFWyfj/35TLCAA "Tcl – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 64 bytes ``` param($x,$y)-split'----- )===) (===( )===) -----'*$y|gu|%{$_*$x} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9vyCxKDFXQ6VCR6VSU7e4ICezRF0XBBQ0bW1tNRU0gKQGlA0WV9dSqaxJL61RrVaJ11KpqP1fy8WlZKRgqMSlBjQRyOBSUuJSMlQwgggAGWABI5gAkPEfAA "PowerShell – Try It Online") ]
[Question] [ It's simple: Make a [proper](https://codegolf.meta.stackexchange.com/q/4877/8478) quine where if you remove any character, it's still a quine. The difference between this and a radiation hardened quine is that if your program is `AB`, in a radiation hardened quine `A` would output `AB`, but here, `A` would output `A`. Code golf, all standard rules, standard loopholes apply, no cheating. [Answer] # [Lenguage](http://esolangs.org/wiki/Lenguage), 4.54×10761 bytes It has this number of null characters: > > 453997365974271498471447945720930600149036031871190716908688344432973027776681259141680552038829875159204621651993092104775733418288411812715164994750890484868305218411129600012389568016974351721147925344946382782884546247102886167837964612372737300786173159265347137401863281368021545169383664534228503236761742285358985343373496184959796553930661837467682191561275123057706776367104142995491262443697167483190110516522677811931124842961701222425076750211774387637740969301686178545299089832300154448308384461700726890067468872402133010536518468336342175124002115991866466700174974019423711837589532744970385003356612639263433822126850314801275940879069069974437167102618471264140597777702065896715558989678487253830854848740247786166790545462769498303055791292 > > > Seeing how the criterion in this challenge conflicts with the definition of a "proper quine", seriously, I think an Unary variant is going to win. Expanded Brainfuck code: ``` >>+++>++++++++>+++>+++>+>+>+>+>+>+>+>+++>+>+>+>+>+>+>+>+>+++>+>+>+>+>+>+>+>+>++++++++>++++>++++++++>++++>+++++++>++>+++>+>+++>++>+++>+++>+>+>+>+>+>+>+>+>++++>++++>+++++++>+>++++>++++++++>++>+++++++>+++>++++++++>++>+++++++>+++>++++++++>++>+++++++>+++>++++++++>++>+++++++>+++>+++++>++++++++>++++>+++++++>+++++++>+>+>+++>+>+>+>++++++++>+++>+++++++>+>+++>+>+++>+>+++>+>++++++++>++++>++++++++>++++>++++++++>++++>++++>+>+++>+++>++>+++++++>+++++++>+>+>+>++++++++>+++>+>++++++++>++++>+>+++>++>+++++++>++>+++++++>++++>++++>++++++++>+++>++++++++>+++>+++>+>++++>++++>++>+++++++>+++>+++>++++++++>++++>+>+++>++>+++++++>++++>++++>+++++++>+++>+++>+++>+++>++++++++>++++>++++>+>+++>+>+++>++>+++++++>+++++++ [ [->+>+<<] >>>>[<<[->+<]>>[-<<+>>]>] <<[-[->+<]+>]+++ [[->>+<<]<]< ] +>+>+>+ [>]+++>++ [ [<]. >[-]>[-]>[-]>[-] <+[<<++++++++>>->+>-[<]<] ++++++++>++++++++>+++++++>> ] . ``` If one character is removed from the Lenguage program, the last character becomes a `<`, which causes the program to print exactly one less character. [Answer] # ><> (Fish), 145 107 bytes This answer uses ><>'s jumping instruction to fix the problem. ``` !<0078*+00~..>0[!."r43a*+8a+&{ee+00&1-:&(?.~~ol?!;4b*0.0f<>0['r3d*159*+&}7a*00&1-:&(?.~~ol?!;68a*+0.0+*a58 ``` This quine actually contains two different quine generators. It starts with some jumping logic and by default uses the left quine. If a character is removed from the jumping logic or from the left quine, the program jumps to the right quine. [You can try it here](https://fishlanguage.com/playground/cz5Wrfmy7QG4mq3w7) # Explanation The code can be dissected into a few parts: ``` A: !<0078*+00~..>0[!. B: >0[!."r43a*+8a+&{ee+00&1-:&(?.~~ol?!;4b*0. C: .0f< D: >0['r3d*159*+&}7a*00&1-:&(?.~~ol?!;68a*+0. E: .0+*a58 ``` Explanation of the different parts: * A: Jumps to the right of C. If any character is deleted from from A, this jumps to the left of D or the right of E, triggering the second quine. If any character is deleted from B or C, the code is shifted 1 character to the left, causing this to jump to the left of D. * C: This code jumps to the left of B. * B: Quine #1 * D: Quine #2 * E: Jumps to the left of D # Explanation of the quine (with #1 as example): Once the instruction pointer reaches either of the quines, you're certain that that quine is completely intact. ``` >0[!. //Fix the instruction pointer's direction and empty the stack (The '!.' is a leftover from codepart A) "r43a*+ //Start reading all of the code and add the '"' character to the stack 8a+& //Because the quine started reading at the 19th character instead of the first, the stack has to move 18 characters. //This part saves the number 18 to the register. {ee+00&1-:&(?. //Move the stack one to the left, decrease the stack by 1. If the stack is not empty yet, jump back to the start of this section. ~~ //Clean the temporary variables from the stack. It should now contain the whole quine. ol?!;4b*0. //Print the first character from the stack. As long as the stack isn't empty, jump back to the start of this section. ``` ]
[Question] [ You are fighting an extensive network of enemy **spies**. You know that each spy has at least one (sometimes multiple) **fake identities** they like to use. You'd really like to know how many spies you're actually dealing with. Luckily, your counter-intelligence **agents** are doing their job and can *sometimes* figure out when two fake identities are actually controlled by the same enemy spy. That is to say: * Your agents don't always know when two fake identies have the same spy behind them, however * If an agent tells you two fake identities are controlled by the same spy, you trust they are right. # Agent messages Agents send you cryptic messages telling you which identities have the same spy behind them. An example: You have **2 agents** and **5 fake identities** to deal with. The first agent sends you a message: ``` Red Red Blue Orange Orange ``` This means they think there are 3 spies: * the first one (Red) controls identities 1 and 2 * the second one (Blue) controls identity 3 * the third one (Orange) controls identities 4 and 5 The second agent sends you a message: ``` cat dog dog bird fly ``` This means they think there are 4 spies: * the first one (cat) controls identity 1 * the second one (dog) controls identities 2 and 3 * the third one (bird) controls identity 4 * the fourth one (fly) controls identity 5 Compiling the intel we see: ``` Identities: id1 id2 id3 id4 id5 Agent 1: |--same-spy--| |--same-spy--| Agent 2: |--same-spy--| Conclusion: |-----same-spy------||--same-spy--| ``` This means there are at most **2 spies**. # Notes Identities owned by the same spy do not have to be consecutive, i.e. a message like: ``` dog cat dog ``` is valid. Also, the same word might be used by two different agents - that does not mean anything, it's just a coincidence, e.g.: ``` Agent 1: Steam Water Ice Agent 2: Ice Ice Baby ``` Ice is used by both agents - the `Ice` used by the first agent is unrelated to the two occurences of `Ice` used by the second agent. # Challenge Compile all your agents' intel and figure out how many enemy spies there really are. (To be more precise, get the lowest upper bound, given the limited information you have.) The shortest code in bytes wins. # Input and Output spec The input is a list of n lines, which represent n messages from agents. Each line consists of k space-separated tokens, same k for all lines. Tokens are alphanumeric, arbitrary length. Case matters. The output should be a single number, representing the number of distinct spies, based on your agents' intel. # Examples ### Example 1 Input: ``` Angel Devil Angel Joker Thief Thief Ra Ra Ras Pu Ti N say sea c c see cee ``` Output: ``` 2 ``` ### Example 2 Input: ``` Blossom Bubbles Buttercup Ed Edd Eddy ``` Output: ``` 3 ``` ### Example 3 Input: ``` Botswana Botswana Botswana Left Middle Right ``` Output: ``` 1 ``` ### Example 4 Input: ``` Black White White Black ``` Output: ``` 2 ``` ### Example 5 Input: ``` Foo Bar Foo Foo Bar Bar ``` Output: ``` 1 ``` ### Example 6 Input: ``` A B C D A A C D A B C C A B B D ``` Output: ``` 1 ``` ### Example 7 Input: ``` A B A C ``` Output: ``` 3 ``` ### Example 8 Input: ``` A B C ``` Output: ``` 1 ``` ### Example 9 Input: ``` X ``` Output: ``` 1 ``` [Answer] # [Sledgehammer 0.5.1](https://github.com/tkwa/Sledgehammer/commit/9e4f8257aae28f8aa0660948d2141e2745c15100), ~~16~~ 15 bytes ``` ⡡⠥⡀⡾⠥⢢⠍⣽⡷⣩⣅⡷⣡⢒⠅ ``` Decompresses into this Wolfram Language function (the final `&` is implicit): ``` Length[ConnectedComponents[RelationGraph[Inner[Equal, ##1, Or] &, Transpose[StringSplit @ #1]]]] & ``` [Try it online!](https://tio.run/##JY1BasMwEEX3PsVHBq@0yQG6KGkpCaEJjnfCi8Ed2yLyyJHk4lJ6dldtZobPXzzmTZRGnijZjratxxNOLEMazd6LcJf4Y@@n2QtLiqYAanaZ9fIWaB7NITPBvN4XchpludM4hxaVRibRBJI4@8jmmoKV4To7m0y5a/@m2tbs@lbPMrDDC39ah0c/@hsHNKPl/pEqv1M14f8iLgsai3elCxXpC5EJXd7IjI5Z/RSXLEumN2vbbr8 "Wolfram Language (Mathematica) – Try It Online") `Transpose[StringSplit @ #1]`: Split each string in the input list, and take the columns (spy identities) `RelationGraph[Inner[Equal, ##1, Or] &, ...]`: Construct the graph where two vertices share an edge if at least one position is equal (if they are classified as the same spy by some friendly agent) `Length[ConnectedComponents[...]]`: The number of connected components is the upper bound on the possible number of spies. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~155 150 142~~ 141 bytes ``` a=>new Set((a=a.map(s=>s.split` `))[0].map((_,x)=>a.flat(m=1<<x).map(o=_=>a.map((b,y)=>b.map((w,i)=>m>>i&1|o[w+=y]?o[w]=m|=1<<i:0)))|m)).size ``` [Try it online!](https://tio.run/##fU5bT8IwFH7frzhPssa5wKuhMwzwwagxSKIJIdBtZ1Dp1mUtjBn@@yxrjCbK0ss557u1H@zAVFzyQt/kMsEmpQ2jQY4VvKJ2XUaZn7HCVTRQvioE12tYE7LoL1vYXXlHQgPmp4JpN6OD4fBIWkbS1RlvRZFXG1Fkh8rjZsiCgF8NTnJRXdN6eWfqkmans5/f9gkhp4wQX/FPbGKZKynQF3Ljpu7CAeiN8g0KmOCBC7D9g9xhCfMtx9TePe8snDFot4KXPcw5PFtYsRoUMojNUogQI/acJSGO889joZBKyQzCfRQJVKZqjWW8L2zWNIFp0p66I0NqVbGcwZ/GhjxiquGJJ4lAmPHNVnd9h8U7eNtyjdbbttDCl133UkLISjDVur4Bcy67RhDCGCbWMYLR7@HMjH@G0DCdOcbcIbBBoS0dwveWar4A "JavaScript (Node.js) – Try It Online") ### How? For each column \$x\$, we build a bitmask \$m\$ of linked columns (including the \$x\$th column). We eventually return the number of distinct bitmasks. ``` +---------+-------+-------+-------+-------+-------+-------+ | x | 0 | 1 | 2 | 3 | 4 | 5 | +---------+-------+-------+-------+-------+-------+-------+ | 2**x | 1 | 2 | 4 | 8 | 16 | 32 | +---------+-------+-------+-------+-------+-------+-------+ | words | Angel | Devil | Angel | Joker | Thief | Thief | | | Ra | Ra | Ras | Pu | Ti | N | | | say | sea | c | c | see | cee | +---------+-------+-------+-------+-------+-------+-------+ | bitmask | 15 | 15 | 15 | 15 | 48 | 48 | +---------+-------+-------+-------+-------+-------+-------+ ``` ### Commented ``` a => // a[] = input new Set( // we eventually convert the generated array into a set (a = a.map(s => // we first need to convert each line into s.split` ` // an array of words (*sigh*) )) // [0].map((_, x) => // for each word at position x in the first line: a.flat(m = 1 << x) // initialize a bitmask m with the x-th bit set and build an // array containing as many entries (N) as there are words in // the whole matrix .map(o = // the object o is used to store words _ => // repeat N times to ensure that all relations are found: a.map((b, y) => // for each line b[] at position y in a[]: b.map((w, i) => // for each word w at position i in b[]: m >> i & 1 | // if the i-th bit is set in m (the relation already // exists) o[w += y] ? // or w + y is set in o (a relation exists in this line): o[w] = // set o[w + y] (the value doesn't matter as long as // it's non-zero) m |= 1 << i // set the i-th bit in m : // else: 0 // do nothing ) // end of map() over the words ) // end of map() over the lines ) | m // end of map() over all flatten entries; yield m ) // end of map() over x ).size // return the size of the corresponding set ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ḲiⱮ`)ZŒc€ẎyⱮ@ƒƊÐLQL ``` [Try it online!](https://tio.run/##y0rNyan8///hjk2ZjzauS9CMOjop@VHTmoe7@iqBfIdjk451HZ7gE@jz/@HuLYfb//93zEtPzVFwSS3LzFGAsL3ys1OLFEIyMlPTICRXUKICGBUrBJQqhGQq@HEVJ1YqFKcmKiQDYXFqqkJyaioA "Jelly – Try It Online") Takes input as a list of space-separated lines (the footer accounts for that). Note: `ḲŒQ)PS` does **not** work. [Answer] # [Python 3](https://docs.python.org/3/), ~~132~~ ~~162~~ ~~154~~ ~~139~~ 135 bytes ``` def f(a):r=[*zip(*[map(b.index,b)for b in map(str.split,a)])];return sum(i==min(min(u)for u in r if min(w)in u)for i,w in enumerate(r)) ``` [Try it online!](https://tio.run/##ZZBPa9wwEMXv/hSPXCwHN9DmtsWFOJseQlpKCPRgfJDt8a6ILRv96Wa77GffarRxEwjS2E9P85sRM@/ddtLXp1NHPXohs5Upqsu/ahaX1Shn0Vwp3dFL3mT9ZNBAabBtnbmy86BcLrM6q78act5oWD8KVRSj0oLDR8gzZKB6sLfLwul8ofIdX5H2IxnpSJgsO7XSkkWBKoGo0hu9oQFr@qMGnPX99EwGT1sV3hu/aY70USJui18eTwo/2bRyD0sSbViWCC1RWuf4kuWxdDlM1k4jSt80Q2hZeufItH5m9q7DXRdjz8z1wkzO7qSW@CAYeqDe4YfquoHwqDZbx@jn/@1k@4zfW@WIc6NANN8/6vs0oZQG4c9ZyzHE@1o3KHGLNWewXC/ydnHL14TIJKiThOfNo81BLzO1jjoefRz2KoFsnZdDmHov2ArIbJR2or84VGkv1UBdmqeztDaIujqnF8VSqj6ucGDwiE/f3hocFnXMsZkcDmfueJGd/gE "Python 3 – Try It Online") This is a very compact implementation of a graph algorithm identifying clusters. 1. For each agent, we create a map of profiles and their alias, which is the lowest index of appearance: `[map(b.index,b)for b in map(str.split,a)]`. I.e. `[0,1,2,1,2]` identifies three spies, where the first profile belongs to one, the second and fourth to another one and the third and fifth to the last one. The group index is also the index of the first profile in the group. 2. By transposing this matrix (`[*zip(*m...)]`), we get a group membership for each profile. This forms a directed, acyclic graph, because the group indices are a subset of the profile indices, and all edges go towards lower or equal indices. Profiles corresponding to the same spy now form a cluster with no connections to the other profiles. We still have duplicate paths though, because profile indices are linked to multiple groups indices. 3. With the following loops, we minimize the the graph to a flat forest, where all profiles are linked directly to the lowest index in their tree, i.e. the root: `min(min(u)for u in r if min(w)in u)` 4. Finally, return the number of roots in the forest, i.e. indices linked to themselves: `return sum(i==...)`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~49~~ 43 bytes ``` ≔⪪S θWS«≔⪪ι ιFLιUMθ⎇⁼λ§θκ§θ⌕ι§ικλ»ILΦθ⁼κ⌕θι ``` [Try it online!](https://tio.run/##VY9RbsIwDIafySksnhypOwFPiA2JaZvQ6AWsYlqrJm2TlA1NO3uXFtDUOLLi@P/yO0VFvmhIh2EdgpQOD61KxJ1r@3iIXlyJNoMlLFPu7Mp8VaIM876FH7OY4fJAJCGLU@MB39iVsUJJ6ndqN835TO6IXQY5e0f@ii9dTxpQM1jHnTvy99isrZ3VW0mQ/F/JJEkatcnp1@zTRBE3FOLDcCsa2Y/s3aC@v9KN001rlT7vSlZ45oso3M6vTc0e8kr4dMvmk2DaAfY95AIfJtAVAhMUKQIzFMxmeLroHw "Charcoal – Try It Online") Link is to verbose version of code. Could possibly save a couple of bytes by using a cumbersome input format. Explanation: ``` ≔⪪S θ ``` Input the first agent's list. ``` WS« ``` Repeat for the remaining agents. ``` ≔⪪ι ι ``` Input their list. ``` FLι ``` Loop over each element index. ``` UMθ⎇⁼λ§θκ§θ⌕ι§ικλ» ``` Find the first element in this agent's list with the same identity and update the first agent's list to show that they are the same identity. ``` ILΦθ⁼κ⌕θι ``` Count the number of unique identities remaining. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 15 bytes ``` ḲĠ)ẎfƇFQɗⱮQ$ÐLL ``` [Try it online!](https://tio.run/##y0rNyan8///hjk1HFmg@3NWXdqzdLfDk9Ecb1wWqHJ7g4/P/4e4th9u5rB81zDm0TddO4VHDXOvD7daPGrdzHZ38cOfiR437Dm07tO1w@6OmNZH//zvmpafmKLiklmXmKEDYXvnZqUUKIRmZqWkQkisoUQGMihUCShVCMhX8uIoTKxWKUxMVkoGwODVVITk1lYvLKSe/uDg/V8GpNCkpJ7UYSJeUpBYllxZwuaYouKaAcSVQWX5JcXliXqICBoPLJzWtRME3MyUlJ1UhKDM9owRkaGJytkJ4RmZJKheYVACLcHE5KjgpOCu4AGlHKA3iO4NpJwUXAA "Jelly – Try It Online") A monadic link taking a list of space-separates agent claims and returning the lowest upper bound of the number of distinct spies. ## Explanation ``` ) | For each list: Ḳ | - Split at spaces Ġ | - Group indices of equal items Ẏ | Tighten lists, so we have a single list of grouped indices $ÐL | Repeat the following until no change: ʋⱮQ | - Do the following as a dyad, mapping through each element of the uniquified list as the right argument fƇ | - Keep only those list members with one or more items matching the right argument F | - Flatten Q | - Uniquify L | Finally take the length of the resultant list ``` Thanks to @Arnauld and @JonathanAllan for identifying issues with previous versions, and to @JonathanAllan again for saving a byte! If the input spec were relaxed to allow a list of lists, this would save one byte. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 120 bytes ``` a=>a.map(l=>(s=l.split` `).map((w,i)=>r[o(i)]=o(s.indexOf(w)),o=i=>r[i]-i?o(r[i]):i),r=[])|r.map(g=(v,i)=>t+=v==i,t=0)|t ``` [Try it online!](https://tio.run/##fU5da8IwFH3vr7hvJqyWPQ/iaNU9jH0hwh6kYGxv652xKUmsE/zvXdswNtiU5Oaee07OST5kI21mqHbjSufYFqKVYiKjvayZEhNmhYpsrcitYc0Hlh1D4mJiVpoRT4VmNqIqx8/Xgh05D7WgXqR0TPea9YDfEQ@NWKX8bIaEUrBmyHA3ohGCQidu@dm1ma6sVhgpXbKCrQKAUVyVqGCGDSnw@FHv0MByS1j4cxT2FxcShm3h7QBLghdPW3kCixKybllEyBBHQcp5EPzzWKK0tXoPyWGzUWi77hya7FD7rHkO83yo05UM7exRVhL@AB/yhIWDZ8pzhbCgcuuufUdmO3jfkkPvHSAM9GXXg9aQSANd965voqvLrhgSmMLMO2KIfw@9Mv0Zkk7pc9ov "JavaScript (Node.js) – Try It Online") ``` a=>a.map(l=>( // for each line (s=l.split` `).map((w,i)=>( // for each words in line r[o(i)]=o(s.indexOf(w)), // join(current index, first occurrence index) )), // without updating nodes in path o=i=>r[i]-i?o(r[i]):i, // a function to find root of some node r=[] // initial disjoint-set ))| r.map(g=(v,i)=>t+=v==i,t=0)| // count roots of tree t // output ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` LωomΣknṁoηkw ``` [Try it online!](https://tio.run/##yygtzv7/3@d8Z37uucXZeQ93Nuaf255d/v///2glx7z01BwFl9SyzBwFCNsrPzu1SCEkIzM1DUIq6SgFJSqAUbFCQKlCSKaCH1CsOLFSoTg1USEZCItTUxWSU1OVYgE "Husk – Try It Online") ## Explanation The idea is to create a list of all groups of spies that are known to be the same person, then progressively merge intersecting groups until a fixed point is reached. The output is the number of remaining groups that couldn't be merged. ``` LωomΣknṁoηkw Implicit input: list of strings, say ["a bc a","b g g"] ṁ Map and concatenate: w Split at spaces: "a bc a" becomes ["a","bc","a"] ηk Group indices by equality of elements: [[1,3],[2]] Result: [[1,3],[2],[1],[2,3]] ω Iterate until result doesn't change: k Group greedily by n (non-emptiness of) intersection: [[[1,3],[1]],[[2],[2,3]]] mΣ Concatenate each part: [[1,3,1],[2,2,3]] Result: [[1,3,1,2,2,3]] L Length: 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~191~~ 182 bytes ### Thank you recursive ``` e=enumerate def f(a): r=[list(map(b.index,b))for b in map(str.split,a)] for z in r: for i,v in e(z): for x in(i>v)*r:x[(i,x[i])[x[i]<i]]=z[v] return sum(i==v for i,v in e(z)) ``` [Try it online!](https://tio.run/##ZVJNb6MwED0nv@L1hF2hSm1v1bJS6MehaqtVVWkPiIMJQzOqA8g2NMmfz3pIolZdwPabN/OeYUy/Dauuvd7vKaN2WJMzgeY1NWiU0TfzmcsKyz6otelVdcFtTZu00rrpHCpwC@F9cBe@txxSo8v5THI7ybmonyJOR4lJ7cTywG0io/j3qM/dzaZQnG4KLnUh8y8uy2xXjNHLURhcCz@sFWfZiB9uei9EIB9SOPKDDZIpVJEs2neyuKORLQ74sfsgh7cVx4@b5iRF8mowPR5/BrwxXoT0ZgtPBst4eyIsiZIyxZVOEZ1z23nfrZEPVWXJxzUEcsuhF@l9jft6GluRXB8lXfCfpjX4D4jmiZqAZ65rS3jl91UQ5eVpM7P8wN8VB5LSCWAiv73RQ9chNw5xlaJTGMc3pwVy3OJOChZYfEFhb08wj@wkKeM5sfwE0luNLDu2V46vd9wGdWh60hvvqU70fEbW01c6OftxxS2OksawFcn@Hw "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~123~~ 117 bytes Uses a similar idea to [movatica's Python 3 solution](https://codegolf.stackexchange.com/a/188349/52194) but calculates the lowest spy index for each "tree" in a slightly different way (by keeping track of previous encountered profiles, finding an overlap if it exists, and combining them) -6 bytes from @GB. ``` ->a,*b{a.map{|s|e=s.split;e.map{|i|e.index i}}.transpose.map{|e|b<<(b.find{|i|i-e!=i}||[])+e} b.map(&:min).uniq.size} ``` [Try it online!](https://tio.run/##JY7RagIxEEXf8xUjlLJraz6gbgqCT30oIr6JlGS9q0NjTM1uu2ry7Vs13GEYzpyHe@rMeWjUMHnXr2Nz7ZWWB@2vMUSoIIO33E6REUdIdlv0xCmJXvqjlxf2xbgvs4BoqqowsrlZd50nGClOMa435QuSMHeteH47sCtl5/hHBr4gDex816r1Rvzt2YJ2aIOgB6SqoqevXEPAbYXw1MhaW5v/w8ztYGmOX7aU74/jN0602jOavMVS02MCLTpaMX2KoM8UoKm@JQBUA/8 "Ruby – Try It Online") ### Explanation ``` ->a,*b{ # Start lambda with input a, b=[] x= a.map{|s| } # For each agent's report e=s.split; # Split the words e.map{|i|e.index i} # Get spy number for each .transpose # Transpose to get group membership .map{|e| } # For each profile (b.find{|i|i-e!=i}||[]) # Find a profile in b that overlaps # If one is not found, use [] +e # Add the profile onto the found one b<< # Insert this modified profile into b b.map(&:min) # Get minimum of each modded profile .uniq # Deduplicate .size # Size of array } # Implicit return ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~229~~ 221 bytes ``` e=enumerate def f(s): v=[];u=sum([(lambda a:[{i for i,x in e(a)if x==k}for k in set(a)])(a.split())for a in s.split('\n')],v) while u: x=u.pop() for i,y in e(u): if x&y:u.pop(i);u+=[x|y];break else:v+=[x] return v ``` [Try it online!](https://tio.run/##TY9Ba4QwEIXPzq@YU03osrAelRwKPfVQStmb9ZDdHddgjJIYq7T97TbRHkqGYfhemDdvWMamN9m6kiDjO7JyJLhRjTVzPAecRFkVXjjfsZJp2V1uEmVefimse4vqMKMySExyVeMsRPsTcRuhozHgijN5dINWI@M8anLT/lD6YVJeHSYO@NkoTehzSGbhj0M/MA7J7rHsHj7ck2D0eVjy/YvihX8U5fy9VMXFkmwhIe0onyKsAC2N3hqc1sEqM4ZMaZo@mTtpfKZJadznl74li@dGhdhbh3eJWzl883hW@ApOLiGRxGt4jgivRGEXB/i3@YQZniD2LGrrLw "Python 2 – Try It Online") 8 bytes thx to [wilkben](https://codegolf.stackexchange.com/users/88089/wilkben). [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 137 bytes ``` import StdEnv,Text,Data.List q=length $l=q(iter(q l)(map flatten o groupBy isAnyMember)(transpose[[(s,n)\\s<-split" "z]\\z<-l&n<-[1..]])) ``` [Try it online!](https://tio.run/##ZVLRbpswFH1OvuIIVZORIFK31/AQmlTalG5VGmkPwIMDN8SqsYltutGPH3NA6dRV@PoeH93jY@NbSuJqaHTVSULDhRpE02rj8OSqjXqJ9vTbRWvu@GIrrJufE0mqdqf5jUzOTDgy7AwZsoa3OEruHClo1EZ3bdpD2JXqH6g5kAmZM1zZVlvKMmYjFea5Xca2lcIFCF6LPH9dxvKTWsbZ7WJRFGE4PDnuD5KAqwoZuJRgLElCeLomF2J0vQFryTSd405oZSFU27kwRJ6DjTh6q1/GyOazGcuClapJYk0vQmLC3/QzGexPgo7THETBjmMcFo8d9gLfPWd5D0scpf8sEUqioIjwOYymnXdU4RKp7Ag//JXra/LikjtUuh7jIEzlf1n/Tr1Cijusgwgerv7BC3t3halnvej2KkqltlY3SLvDQZL12T@DKbvWO24qbKoxRqMvbxrt7C@uOD6Ai8uWjg4Poqp8T@xEfXL/@fHyGT9P/vUvxSPASL67y73WSLmBz5ey69LHtNt8VhTDn9J3TW2H@Ot2WPeKN6KcFo@@mY7aNH8B "Clean – Try It Online") Associates the strings used by the agents with the line-number the appear in to prevent equality across agents, then repeatedly checks if any phrases for any position overlap and counts the number of resulting sets. [Answer] # [PHP](https://php.net/), 271 bytes This won't work if any of the identities are just numbers as I store the "spy number" in with the identities. I don't think it wouldn't be hard to fix that though. ``` $a=$argv;array_shift($a);if(count($a)==1)array_push($a,...$a);foreach($a as&$b)$b=explode(" ",$b);$c=array_map(null,...$a);foreach($c as&$d)foreach($d as$k=>$e){if(!$d[s])$d[s]=++$s;foreach($c as&$f)if($f[$k]==$e)$f[s]=$d[s];}echo count(array_unique(array_column($c,s))); ``` [Try it online!](https://tio.run/##ZY/BSgMxEIbvPsVYgmzouuB5jSJ48qAivZVS0uxkEzZNYrIpFvHVjemueKhMGGb@@b9h4pXPt/eZcEZ46A8tD4Eft1FpOVaE01bLSrhkp4axGzrPfYqqKHXTNCeTdAG5OCnA4xXZUbJj@OGN67BawKIuSksEm9k995VNxvyDxQR39E/oikAGdkeQfpY7Lkm3jhs6ZbZckniOSlpcRK7JsGGsQKUszsnffqFQDuavzHckq98T/jbCmbS3ZVEdKaVtzhf5wfZo4BEP2sBcP7kBA6yURjnn/MZhehFeE6w0POfIjxCRgygREUEgfjs/amdjvu6icmHcOo92O/Kevdgf "PHP – Try It Online") ### Explanation Sort of confused myself writing this but it works for all the test cases! ``` $a=$argv; //shorten the arguments variable array_shift($a); //removes the script name from the arguments variable if(count($a)==1)array_push($a,...$a); //the code needs at least 2 messages to run so if only 1 message duplicate it. "..." passes the stuff in the array rather than the array itself? foreach($a as&$b)$b=explode(" ",$b); //turns each string message into an array $c=array_map(null,...$a); //if you give array_map "null" for the callabck then it zips the arrays, turning a m by n 2D array into a n by m 2D array. this changes it from the messages being grouped to the identities being grouped foreach($c as&$d) //loop over the groups of identities foreach($d as$k=>$e) //loop over the names the agents gave the identity and keep track of the key { if(!$d[s])$d[s]=++$s; //if this identity doesn't have a "spy number" give it the next one foreach($c as&$f) //loop over the groups of identities again if($f[$k]==$e) //check if the agents gave any other identities this name $f[s]=$d[s]; //if they did then give those the same "spy number" } echo count(array_unique(array_column($c,s))); //use array_column to get the "spy number" of each identity, remove duplicates using array_unique and then count the size of the array giving the upper limit of spies ``` [Try it online!](https://tio.run/##jVTRbtMwFH1uvuISRbBopdX2WsKEtCceAKG9TdPkJjeJ1cQ2vna1DvHrlGu7acsAibaq2mvf43POPY7pzf7dzb4QVSFst13Nwmu5pF5bhwpcj8B1P6JyBFthpVgPmAlrxe6Retm6i0KUq9RkcdRbpNhEtZXGgRIjQmv1@C8k2V7U2qsIU1VXZUI2nnquzBeLRYJfLkN/rRsEhdgQCAcDCnJwDSMSiS6cq8F6BaRBtqDVsIOraREabwZZC4cg3QJyBs7BCKKJrvNtC3ISzBzACv5tuSDOq9IRDu1N1mqLog4kQdDrYl0W6wqfzMAML3LI51xJtL1VBGErn2Gl6o6MpGK@jB1xs6KukvRRmAvlh@GknVFYz0576OT2wCNsgzzsy4GpRIK1GAaxrjfhj2Ki8CwNnajTHAKZQEHACOsdKLi@nWRFMlzh8ngsL7hbEtRsQfCXIY@jPJq@xoDYWe0NNmEEYVU2PGXp5Mv1k211tK0pU3IGrQ1wdpKQuJlAt2c42ezY2nBrsaneF1j@pTkk7qC6i1HrBJt2RmrHpjewQTTgrGC7@JywvMFdNvuezWYcyVdFc08PZfyuLi8LWh2mEP04AjUaSb1x0IcjBORk2FQ/rtHmaVbsWOSET44DiQz@woC2/D/5LEZIxf2BXdHeF5uHqooGLJd1j6xCtn@IFmoHOob4DCgqiNcyoM0YiyVGoatJIrIy2aQYRRmu15Q8pNB4rjOb/ciw7jWkW5zC6ZX85vHwp9aDHxULnlNZluEQT1OK01pITYfJqt88ZAvizZkMn0N6xJxuM4GnmOizc@N8I/nIKfGWzzgNOiWehYXGUPDGsEeDHHlcvIcM@7TfZ/sPnPoBbnErB0i/P@oN77zrJbbpe/9VQPwQfPFwJ@HTnhicUEDNb0K@log/tXFSK9q/beKD9VEbVI9OdNVn9Qs "PHP – Try It Online") ]
[Question] [ Write a program, given an input *n*, will generate all possible n-tuples using natural numbers. ``` n=1 (1),(2),(3),(4),(5),(6)... n=2 (1,1),(1,2),(2,1),(2,2),(1,3),(3,1),(2,3),(3,2),(3,3)... n=6 (1,1,1,1,1,1) (1,1,1,1,2,1) (1,1,1,2,1,1)... ``` * The output may be in any order that does not break any other rules. * The program must be written to run forever and list all applicable tuples exactly once, in theory. + In reality, your program will reach your integer type's limit and crash. This is acceptable as long the program *would* run infinitely long if only your integer type was unlimited. + Each valid tuple must be listed within finite time, if only the program were allowed to run that long. * The output may, at your option, include zeroes in addition to the natural numbers. * You may choose your program's output format for your convenience, as long as the separation between tuples and numbers inside each tuple is clear and consistent. (For example, one tuple per line.) * The input (n) is an integer from one to six. Required behavior is undefined for inputs outside of this range. * Code-golf rules apply, shortest program wins. Thanks to "Artemis Fowl" for feedback during the sandbox phase. [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` πN ``` [Try it online!](https://tio.run/##yygtzv7//3yD3////40B "Husk – Try It Online") ## Explanation `N` is the infinite list of natural numbers `[1,2,3,4,..`. `π` is Cartesian power. Result is an infinite list of lists. Each list of the desired length occurs exactly once because `π` is cool like that. Input and output are implicit. [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` ([1..]>>=).(!) 0!s=[[]|s<1] n!s=[a:p|a<-[1..s],p<-(n-1)!(s-a)] ``` [Try it online!](https://tio.run/##FYxBDsIgEADvvGKbeIBECBy8GOgPfAESs6lFm1LcuD327WJ7m0km80aex1JahgD3JqMzJvV9UEZ2StiOQ4xpY@@SqIfglTb0@sg4nclrWbVTnWSNKrUFp7p/nh8BsCDdHkDfqa5wghXnEZy1O2a4tN@QC7646YHoDw "Haskell – Try It Online") `n!s` generates all the `n`-tuples that sum to `s`. Then the answer is `([1..]>>=).(!)`, i.e. `\n -> [t | s<-[1..], t<-n!s]`. This is a function mapping an integer `n` to an infinite lazy list of tuples (lists of integers). [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` f n=[l|k<-[0..],l<-mapM([0..k]<$f)[0..n],sum l==k] ``` [Try it online!](https://tio.run/##FccxDoAgDADAr3Rw0AQMxhWe4AsMQ2NESQshoptvt@p2t2OllVkkQHYz32T1bPreK7Y6YZnaf@RtE7pf2at6JWDnyEvCmMFBOWI@oYETaYXBmI8BRnmWwLhV0UspLw "Haskell – Try It Online") Lists `n`-tuples sorted by sum. `mapM` does the heavy lifting to generate all `n`-tuples of numbers from 0 to k. The `<$f` trick is [explained here](https://codegolf.stackexchange.com/a/181531/20260). # [Haskell](https://www.haskell.org/), 51 bytes ``` f 1=pure<$>[0..] f n=[a-k:k:t|a:t<-f$n-1,k<-[0..a]] ``` [Try it online!](https://tio.run/##FcqxDoMgEADQ3a@4gdEzkG4E@iOG4WI4a44Sorj57Z7t9ob3oUNyKaoMLrZzz8G8ZztNaWCocSYUL75f5HtANhXdKAH/gVLSL20VIrR9qx0MdJIMztofGV56L1xoPRSX1h4 "Haskell – Try It Online") Recursively stretches all `n-1`-tuples into all `n`-tuples by splitting the first number `a` of each `n-1`-tuple into two numbers `a-k,k` that sum to it, in every possible way. [Answer] # Pyth - 9 bytes *Thanks to @FryAmTheEggman for the golf* Loops through all x, and takes [1..x]^n. This makes duplicates, so only keeps ones that are new to that x, aka contain x in them. The formatting is a little weird, but it can be made standard with one more byte, `.V1j}#b^Sb` ``` .V1}#b^Sb ``` [Try it online](https://tio.run/##K6gsyfj/Xy/MMKtWOSkuOOn/fzMA). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 9 bytes ``` ~l.ℕᵐ+≜∧≜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sWHNr5qHEDBD3c1fm/LkfvUcvUh1snaD/qnPOoYzmQ/P/fGAA "Brachylog – Try It Online") This is an infinite generator that generates all possible tuples. The TIO link has a header that uses the generator to generate 1000 elements and prints them (but the generator could continue indefinitely if I asked for that instead; Brachylog's integers are unbounded). It feels like there should be a terser way, but there are a lot of constraints and this is the tersest I can fit them into a single program. ## Explanation ``` ~l.ℕᵐ+≜∧≜ . Generate ≜ all explicit ~l lists whose length is {the input} ᵐ for which every element ℕ is non-negative + and whose sum ≜ is used to order the lists (closest to zero first) ∧ [remove unwanted implicit constraint] ``` Incidentally, it strikes me as interesting just how different my explanations of the two `≜` are, despite them doing the exact same thing from Brachylog's point of view. The first `≜` is the first nondeterministic predicate in the program, so it sets the order of results; in this case, it calculates all possible explicit values for the sum of the list in the order 0, 1, 2, 3…, and is being used to ensure that the lists are output in order of their sum (this ensures that each possible list appears after a finite amount of output). The second `≜` is used to calculate all the explicit possibilities for the list (rather than outputting a formula specifying how the elements of the list relate to each other). [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 148 bytes ``` n=>{var a=new int[n];int j=0;void g(int k){if(k<n)for(int i=0;i++<j;g(k+1))a[k]=i;else if(a.Sum()==j)WriteLine(string.Join(' ',a));}for(;;j++)g(0);} ``` [Try it online!](https://tio.run/##HYyxDoIwFEV3v6IbfakSjOOjJK7GzcGBMDRYmtfqIymIA/Hba3G6OScnt58O/UTp3M80ck08N4NOrJt1MVEYzfYjsmy5wzzC6wqXkR7CyQ0DrDTIUDMMY/wbygEpVXt0MqgjgGlDpwntc7Iit6a8vV8StPZwjzTbK7GV0xyJXXkZiWUhir0BwO/2iOiVAierzAl3gzwBph8 "C# (Visual C# Interactive Compiler) – Try It Online") -3 bytes thanks to @ASCIIOnly! ``` // n: size of tuples to generate n=>{ // a: current tuple workspace var a=new int[n]; // j: target sum value int j=0; // recursive function that works on slot k void g(int k){ // tuple is not fully generated, if(k<n) // try all values from (0,j] for(int i=0;i++<j; // recursive call - generates all // values from (0,j] in the next slot g(k+1) ) // update the kth slot a[k]=i; // tuple is fully generated, however // we should only display if the sum // is equal to the target sum. tuples // are generated many times, this // let's us enforce that they are only // displayed once. else if(a.Sum()==j) WriteLine(string.Join(' ',a)); } // increment the high value forever // while continually starting the // recursive function at slot 0 for(;;j++) g(0); } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62~~ 52 bytes ``` Do[Print/@(1+1~Table~#~FrobeniusSolve~--n),{n,∞}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU/OqAoM69E30HDUNuwLiQxKSe1TrnOrSg/KTUvs7Q4OD@nLLVOVzdPU6c6T@dRx7zaWLX/aQ5m/wE "Wolfram Language (Mathematica) – Try It Online") --- -2 bytes with inconsistent separation: [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU/OqAoM68k2lDbsC4kMSkntU65zq0oPyk1L7O0ODg/pyy1Tlc3L1anOk/nUce82li1/2kOZv8B "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 (9?) [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 9 if we may output using non-consistent separation (which I have enquired about) -- removal of the `€`. ``` ‘ɼṗ³ċƇ®Ṅ€ß ``` **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oCYybzhuZfCs8SLxofCruG5hOKCrMOf////Mw "Jelly – Try It Online")** ### How? ``` ‘ɼṗ³ċƇ®Ṅ€ß - Main Link: some argument, x (initially equal to n, but unused) ɼ - recall v from the register (initially 0), then set register to, and yield, f(v) ‘ - f = increment - (i.e. v=v+1) ³ - program's third command line argument (1st program argument) = n ṗ - (implicit range of [1..v]) Cartesian power (n) - (i.e. all tuples of length n with items in [1..v]) Ƈ - filter keep those for which: ċ - count ® - recall from register - (i.e. keep only those containing v) Ṅ€ - print €ach ß - call this Link with the same arity - (i.e. call Main(theFilteredList), again the argument is not actually used) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [¼¾LIãvy¾å— ``` -4 bytes by creating a port of [*@Maltysen*'s Pyth answer](https://codegolf.stackexchange.com/a/183240/52210). [Try it online.](https://tio.run/##AR0A4v9vc2FiaWX//1vCvMK@TEnDo3Z5wr7DpeKAlP//Mw) **Explanation:** ``` [ # Start an infinite loop: ¼ # Increase the counter_variable by 1 (0 by default) ¾L # Create a list in the range [1, counter_variable] Iã # Take the cartesian power of this list with the input v # Loop over each list `y` in this list of lists: y¾å # If list `y` contains the counter_variable: — # Print list `y` with trailing newline ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` `@:GZ^t!Xs@=Y)DT ``` Tuples are ordered by increasing sum, and within a given sum they are ordered lexicographically. [**Try it online!**](https://tio.run/##y00syfn/P8HByj0qrkQxotjBNlLTJeT/f1MA) [Answer] # [Python 2](https://docs.python.org/2/), ~~126~~ ~~112~~ ~~106~~ ~~101~~ ~~100~~ 83 bytes ``` n=input() i=1 while 1: b=map(len,bin(i)[3:].split('0'));i+=1 if len(b)==n:print b ``` [Try it online!](https://tio.run/##DcpNCoNADAbQ/ZwiOxMqxZ/dlJxEXDig@ME0DXVEevqpb/38V/aPDbWawvwsLAHah2tHXqmPgZK@F@e8WptgDJnGOD8PzyjcdI3IC4/7Eza6DydRtehfWKFU6/gH "Python 2 – Try It Online") 5 bytes thx to [mypetlion](https://codegolf.stackexchange.com/users/65255/mypetlion); 1 byte from the eagle eye of [ArBo](https://codegolf.stackexchange.com/users/82577/arbo); 17 bytes from [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! Construct the ordered partitions of `m` into `n` bins, for `m = 0,1,2,3,...` by selecting for binary numbers with `n-1` `0`s and `m` `1`s. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~608 570~~ 567 bytes ``` using C=System.Console;using L=System.Collections.Generic.List<int[]>;class A{static void Main(){L x=new L(),y=new L(),z=new L();int i=int.Parse(C.ReadLine()),j=0,k,l,m;x.Add(new int[i]);while(i>0){j++;for(m=0;m++<i;){foreach(var a in y)x.Add(a);y=new L();foreach(var a in x){for(k=0;k<i;){int[] t=new int[i];System.Array.Copy(a,t,i);t[k++]=j;var b=true;z.AddRange(x);z.AddRange(y);foreach(var c in z){for(l=0;l<i;l++)if(c[l]!=t[l])break;if(l==i)b=false;}if(b)y.Add(t);}}}}for(k=0;k<x.Count;k++){C.Write("[ ");for(l=0;l<i;l++)C.Write(x[k][l]+" ");C.WriteLine("]");}}} ``` [Try it online!](https://tio.run/##ZZHBbtswDIZfRfNJhDwjwI6sCgQ57OIBQ3fYwfBBUZSWsSIPktLaMfrsGe20zYrpIFA/xf8jJZu@2j66y@WUKDyKjf41puyO1aYPqfcOr3J9k713NhNnq@8uuEi2qinlOwq5ae/RepOSWE8pm0xWPPe0Ez8MBQlTLQYd3IuoJZTjR3R@j5AdBGneq58mJic31YMzu5qCkwDlQa/KrvTlEYdqvdvJuWpmUgv48kTeSbpfwXRQCvd9lEe9wqNSd4Qw8dkZ@ySfTRSGi8QIVw8D@NEI/ndrWCplx07d4rOMKLK@ofHtVdYxmpHf5s8oTZlLAsxNp1SrDzjbbXWOJ4fnGfpgwqOTA/x7Gj/T7Uw/X@me6Z7pXimgvbSNb7/ozDtsuaBD1rzWBFu9Nz45fGVhC@MyXgZ85XUbYuAWTyEjtwbTpvodKTtZNKJY@J9Y79mh6VqmqWK@9CYuX1K0xWJ/uXz7Cw "C# (.NET Core) – Try It Online") my god what have I done (so many loops, that's what I've done) It should work, though! If you move the print loop back one bracket, it will show you the list as it's built, every time it loops. (I recommend adding a newline or something to distinguish each loop if you do.) Honestly, a *lot* of my time was spent fighting with the language...no pretty-printing arrays, assorted behaviors of ==... Hopefully this version is easier to read. ``` using C=System.Console; using L=System.Collections.Generic.List<int[]>; class A{ static void Main(){ L x=new L(),y=new L(),z=new L(); int i=int.Parse(C.ReadLine()),j=0,k,l,m; x.Add(new int[i]); while(i>0){ j++; for(m=0;m++<i;){ foreach(var a in y) x.Add(a); y=new L(); foreach(var a in x){ for(k=0;k<i;){ int[] t=new int[i]; System.Array.Copy(a,t,i); t[k++]=j; var b=true; z.AddRange(x); z.AddRange(y); foreach(var c in z){ for(l=0;l<i;l++) if(c[l]!=t[l])break; if(l==i)b=false; } if(b)y.Add(t); } } } } for(k=0;k<x.Count;k++){ C.Write("[ "); for(l=0;l<i;l++)C.Write(x[k][l]+" "); C.WriteLine("]"); } } } ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 50 bytes ``` {grep $_,{S/.//.split(0)>>.chars}($++.base(2))xx*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAQSVepzpYX09fX6@4ICezRMNA085OLzkjsai4VkNFW1svKbE4VcNIU7OiQqv2f25igYKWXnFipU6ahrFmdJyhgUGs9X9jAA "Perl 6 – Try It Online") Anonymous code block that returns a lazy infinite list. This uses the same strategy as [Chas Brown's answer](https://codegolf.stackexchange.com/a/183251/76162). ### Explanation: ``` {grep $_,{S/.//.split(0)>>.chars}($++.base(2))xx*} { } # Anonymous code block xx* # Repeat indefinitely ($++ ) # From the current index .base(2) # Get the binary form {S/.// } # Remove the first digit .split(0) # And split by zeroes >>.chars # And get the length of each section grep , # From this infinite list, filter: $_ # The groups with length the same as the input ``` [Answer] # [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 51 bytes ``` g(i)==if i=0then{}else{[x]^y|x:nat,y in set g(i-1)} ``` Recursive set comprehension with sequence concatenation.. Not on TIO, you could run in a program (if you turn on limits for nat type or it wont terminate): ``` functions g:nat->set of ? g(i)==if i=0then{}else{[x]^y|x:nat,y in set g(i-1)} ``` Includes the optional 0s in answer otherwise it would be 52 bytes binding on nat1 [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 131 bytes ``` While[0<1,If[a~FreeQ~#,Print@#]&/@(b=Table[Select[Range@t~Tuples~{s},Tr@#==k&],{k,t,t(s=#)}]~Flatten~1);a={a}~Join~b;t++]& t=1 a={} ``` [Try it online!](https://tio.run/##Dcq9CoMwEADg3dcIiGKgdehkA05CO/VH6BAynHLVYEyLXifJvXrq@vHNQCPOQLaHOKj4Gq1DfTyX8vLWwM2CeGchb4v1VAuTHuqsUy10e3qiw570A/yANXH7@zpceVuDbJdaKDWlRm6TJEnZqkQeDDcOiNBzmVegNgh8/VjPXUVFYdKEVJnsHOKgTybGPw "Wolfram Language (Mathematica) – Try It Online") [Answer] # perl -M5.010 122 bytes ``` $n=shift; $s.="for\$x$\_(1..\$m){"for 1..$n; $t.="\$x$\_ "for 1..$n; $u.='}'x$n; eval"{\$m++;$s\$\_=qq' $t';/ \$m /&&say$u;redo}" ``` Added some newlines for readabilities sake (not counted in the byte count) [Answer] # [Python 2](https://docs.python.org/2/), 120 bytes ``` from random import* m=n=input() a=() while 1: m+=len(a)==m**n;t=[randint(1,m)for _ in[1]*n] if(t in a)<1:a+=t,;print t ``` [Try it online!](https://tio.run/##FYtBCsMwDATvfoWOtpOLc0yql4RQDI2JIJKNUCl9vetedhiYbV@7qiy9F60MmuU1QNyqWnSMgiTtbT64jGM@F90npNUBT3if4nNA5BhlM9z/ZxLzaeZQqsITSPZ0RDkcUPE2FHJ4pDVPaPPWdMRgvS8/ "Python 2 – Try It Online") A bit longer than most other answers, but I liked the idea behind it. [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` £ƒ$↔┬ï ``` [Run and debug it](https://staxlang.xyz/#p=9c9f241dc28b&i=4) For input `n` the procedure is roughly ``` for i in [0..infinity]: get all the distinct n length arrays of positive integers that sum to i for each join with spaces implicitly output ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 98 bytes ``` n=>{for(a=[],b=[j=1];;b.push(++j))(g=k=>k<n?b.map(i=>(a[k]=i)|g(k+1)):a.includes(j)&&print(a))(0)} ``` [Try it online!](https://tio.run/##DctBDsIgEADA3zS7QYmNF2NdfAjhsFSpgEUCbS/q29G5T@CN61h8XvbbqTlqidTbvQowabOzpAP1ZhiszGt9gBABESaKpOIlXa2cOYMnBayjIY@fCaLoEc8sfRqf6@1eIWDX5eLTAvy/B/w2B0dsPw "JavaScript (V8) – Try It Online") Hooray! Finally got it under 100 :) Basically a port of [my C# answer](https://codegolf.stackexchange.com/a/183417/8340). ``` // n: length of tuples to generate n=>{ // a: workspace for current tuple // b: range of numbers that grows // - iteration 1: [1] // - iteration 2: [1,2] // - iteration 3: [1,2,3] // j: largest number in b for(a=[],b=[j=1];;b.push(++j)) // g: recursive function to build tuples // k: index of slot for current recursive call (g=k=> // current slot less than the tuple size? k<n? // tuple generation not complete // try all values in current slot and // recurse to the next slot b.map(i=>(a[k]=i)|g(k+1)): // tuple generation complete // print tuple if it contains the // current high value a.includes(j)&&print(a) // start recursive function at slot 0 )(0) } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~96~~ 90 bytes ``` n=>{for(i=0n;z=[];z.length-n||console.log(z))for(j=++i,w=0;j;j/=2n)w=j%2n?+!z.push(w):w+1} ``` [Try it online!](https://tio.run/##FcpBCsIwEADAt3gQssTGWm@G1YeIh1KTNkvYLU01EOvbI855qH/3aVjCvDYsT1c9Vsbrx8uiArZsC94ftpjoeFynhrdtEE4SnYkyqgLwj4Rah0PG1pKlI3YMGWnf8U3viplfaVIZLlmfvtWrM9Qf "JavaScript (Node.js) – Try It Online") V8 on TIO don't support BigInt ]
[Question] [ # Task Given a non-empty string of lowercase ASCII letters `a`-`z`, take its first character, and: * Surround it with a square of copies of the **second** character, * Surround that with a diamond of copies of the **third** character, * Surround that with a square of copies of the **fourth** character… …alternating between square and diamond borders until the end of the string. Empty space between the borders should be represented by ASCII spaces (). To add a **square** border, draw a square exactly around the entire current “working array”: ``` sssssssssss t s t s t t s t t s t t s t t s t aaa t s t aaa t s t aca t => st aca ts t aaa t s t aaa t s t t s t t s t t s t t s t s t s sssssssssss ``` To add a **diamond** border, draw a centered diamond shape that touches the outermost square *diagonally*, but not *orthogonally*: ``` s s s s s s s s s s s s s wwwwwwwwwww s wwwwwwwwwww s w o w s w o w s w o o w s w o o w s w o o w s w o o w s w o eee o w s w o eee o w s wo eme ow => s wo eme ow s w o eee o w s w o eee o w s w o o w s w o o w s w o o w s w o o w s w o w s w o w s wwwwwwwwwww s wwwwwwwwwww s s s s s s s s s s s s s s ``` Your program must output the final array. * Each line may contain any amount of trailing spaces. * You may output a list of strings representing lines, or a single newline-separated string with an optional trailing newline. * Leading/trailing blank lines are disallowed. * Leading columns of spaces are also disallowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest code in bytes wins. # Test cases The above examples are expected outputs for `cat`, `cats`, `meow`, and `meows`, in reading order. Some other cases worth handling: * For the input `a`, your program should output: ``` a ``` * For the input `ab`, your program should output: ``` bbb bab bbb ``` * For the input `codegolf`, your program should output: ``` fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff f l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l ooooooooooooooooooooooooooo l f f l o g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g eeeeeeeeeee g o l f f l o g e d e g o l f f l o g e d d e g o l f f l o g e d d e g o l f f l o g e d ooo d e g o l f fl og ed oco de go lf f l o g e d ooo d e g o l f f l o g e d d e g o l f f l o g e d d e g o l f f l o g e d e g o l f f l o g eeeeeeeeeee g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g g o l f f l o g o l f f l ooooooooooooooooooooooooooo l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l l f f l f fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` # Reference implementation I wrote some Julia code that your program’s output should match (at least visually). [**Try it online!**](http://julia.tryitonline.net/#code=aW5wdXQgPSByZWFkbGluZShTVERJTikKQSA9IGZpbGwoaW5wdXRbMV0sIDEsIDEpCgpzcXVhcmUgPSB0cnVlCmZvciBsZXR0ZXIgaW4gaW5wdXRbMjplbmRdCiAgcyA9IHNpemUoQSlbMV0KICBpZiBzcXVhcmUgdGhlbgogICAgQiA9IGZpbGwobGV0dGVyLCBzICsgMiwgcyArIDIpCiAgICBCWzI6cysxLCAyOnMrMV0gPSBBCiAgICBBID0gQgogIGVsc2UKICAgIG1hcmdpbiA9IGRpdihzLCAyKSArIDIKICAgIHRvdGFsID0gcyArIDIgKiBtYXJnaW4KICAgIEIgPSBmaWxsKCcgJywgdG90YWwsIHRvdGFsKQogICAgQlttYXJnaW4rMTptYXJnaW4rcywgbWFyZ2luKzE6bWFyZ2luK3NdID0gQQogICAgY2VudGVyID0gZGl2KHRvdGFsLCAyKSArIDEKICAgIGZvciBpIGluIDA6Y2VudGVyLTEKICAgICAgQlsgICAgMStpLCBjZW50ZXIraV0gPSBsZXR0ZXIKICAgICAgQlsgICAgMStpLCBjZW50ZXItaV0gPSBsZXR0ZXIKICAgICAgQlt0b3RhbC1pLCBjZW50ZXIraV0gPSBsZXR0ZXIKICAgICAgQlt0b3RhbC1pLCBjZW50ZXItaV0gPSBsZXR0ZXIKICAgIGVuZAogICAgQSA9IEIKICBlbmQKICBzcXVhcmUgPSAhc3F1YXJlCmVuZAoKcyA9IHNpemUoQSlbMV0KQSA9IGhjYXQoQSwgZmlsbCgnXG4nLCBzLCAxKSkKcHJpbnQocnN0cmlwKGpvaW4oQScpKSk&input=Y29kZWdvbGY) [Answer] # JavaScript (ES6), ~~294~~ ~~288~~ ~~287~~ ~~284~~ ~~256~~ ~~246~~ ~~240~~ ~~238~~ 220 bytes My first golf on this site. Pass input string to function `f`, e.g. `f('codegolf')` ``` f=s=>{N=n=>(2<<n/2+.5)-3-n%2 D=N(l=s.length) for(a=[],i=S=D*2+1;i--;)a[i]=a[S+~i]=Array(S).fill` ` for(;l--;)for(o=n=N(l+1),I=0;I<=n;I++,o-=~l&1)a[y=D+I][x=D+o]=a[x][y]=a[y][D-o]=a[x][D-I]=s[l] return a.map(r=>r.join``)} ``` *-6 bytes thanks to @Sunny Pun: Remove parentheses when passing template strings.* -2 bytes thanks to @ETHproductions: Change `S-i-1` to `S+~i`, `l%2||o--` to `o-=~l&1`. -18 bytes per suggestions of @Sunny Pun, @edc65: Remove `prompt()` and `console.log()` in favor of function format, don't `.join()` final array of strings [Answer] # Haskell, ~~138~~ ~~137~~ 136 bytes ``` q 1=0 q x=(mod x 2+1)*(q(x-1)+1) f x|m<-q$length x,n<-abs<$>[-m..m]=[do j<-n;max" "[c|(k,c)<-zip[1..]x,cycle[max i j,i+j]!!k==q k]|i<-n] ``` Defines a function `f` which returns the result as a list of lines *-1 byte thanks to @Lynn* [Answer] # C++ - 373 366 362 359 bytes *-1 by @TuukkaX, -6 by @Kevin Cruijssen, -4 by imports, -3 by @Baum mit Augen* ``` #import<string> #import<vector> #define A(x) abs(x-r) using S=std::string;using V=std::vector<S>;int R(int n){return n?(n%2)?R(n-1)+1:2*R(n-1)+2:0;}V f(S w){int l=w.size(),r=R(l-1),s=r*2+1,i,j,k;V x(s);for(i=0;i<s;++i){x[i]=S(s,46);for(j=0;j<s;++j)for(k=0;k<l;++k){if(A(i)<=R(k)&A(j)<=R(k)&k%2?A(i)==R(k)|A(j)==R(k):(A(i)+A(j)==R(k)))x[i][j]=w[k];}}return x;} ``` <http://ideone.com/5y54mx> Note: This solution uses the dot ('.') as "space" character to make the empty spaces more visible. To use a space instead, one has to change `S(s,46)` to `S(s,32)`. The score remains the same. Ungolfed: ``` #import<string> #import<vector> #define A(x) abs(x-r) //r will be the center coordinate using S=std::string; using V=std::vector<S>; int R(int n){ //recursive function returning the radius of a square/diamond return n? //if(n!=0) (n%2)? //if(n%2 != 0) R(n-1)+1 //square -> just increase radius by 1 : 2*R(n-1)+2 //diamond -> radius doubles + 2 : 0 //n==0 -> end of recursion ; } V f(S w){ //function taking a string and returning a vector<string> int l=w.size(),r=R(l-1),s=r*2+1,i,j,k; //r is radius (==center coord), s is size V x(s); //vector<string> for(i=0;i<s;++i){ //loop over vector x[i]=S(s,46); //initialize string with dots. use 32 for spaces for(j=0;j<s;++j) for(k=0;k<l;++k){ //loop over word if( A(i)<=R(k) //check bounds & A(j)<=R(k) & k%2?A(i)==R(k)|A(j)==R(k):(A(i)+A(j)==R(k)) //for square: check if distance to center of one coordinate = R //for diamond: check if sum of distances = R ) x[i][j]=w[k]; //if any is true, replace default char } } return x; } ``` [Try ungolfed online](http://ideone.com/X32pdD) How to use: ``` include<iostream> void printSquare(std::string word){ auto result = f(word); for(auto& s:result) std::cout << s << std::endl; std::cout << std::endl << std::endl; } int main() { printSquare("a"); printSquare("ab"); printSquare("cat"); printSquare("cats"); printSquare("meow"); printSquare("meows"); printSquare("codegolf"); return 0; } ``` Output: ``` a bbb bab bbb ....t.... ...t.t... ..t...t.. .t.aaa.t. t..aca..t .t.aaa.t. ..t...t.. ...t.t... ....t.... sssssssssss s....t....s s...t.t...s s..t...t..s s.t.aaa.t.s st..aca..ts s.t.aaa.t.s s..t...t..s s...t.t...s s....t....s sssssssssss wwwwwwwwwww w....o....w w...o.o...w w..o...o..w w.o.eee.o.w wo..eme..ow w.o.eee.o.w w..o...o..w w...o.o...w w....o....w wwwwwwwwwww ............s............ ...........s.s........... ..........s...s.......... .........s.....s......... ........s.......s........ .......s.........s....... ......s...........s...... .....s.wwwwwwwwwww.s..... ....s..w....o....w..s.... ...s...w...o.o...w...s... ..s....w..o...o..w....s.. .s.....w.o.eee.o.w.....s. s......wo..eme..ow......s .s.....w.o.eee.o.w.....s. ..s....w..o...o..w....s.. ...s...w...o.o...w...s... ....s..w....o....w..s.... .....s.wwwwwwwwwww.s..... ......s...........s...... .......s.........s....... ........s.......s........ .........s.....s......... ..........s...s.......... ...........s.s........... ............s............ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff f............................l............................f f...........................l.l...........................f f..........................l...l..........................f f.........................l.....l.........................f f........................l.......l........................f f.......................l.........l.......................f f......................l...........l......................f f.....................l.............l.....................f f....................l...............l....................f f...................l.................l...................f f..................l...................l..................f f.................l.....................l.................f f................l.......................l................f f...............l.........................l...............f f..............l...........................l..............f f.............l.ooooooooooooooooooooooooooo.l.............f f............l..o............g............o..l............f f...........l...o...........g.g...........o...l...........f f..........l....o..........g...g..........o....l..........f f.........l.....o.........g.....g.........o.....l.........f f........l......o........g.......g........o......l........f f.......l.......o.......g.........g.......o.......l.......f f......l........o......g...........g......o........l......f f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f f....l..........o....g..e....d....e..g....o..........l....f f...l...........o...g...e...d.d...e...g...o...........l...f f..l............o..g....e..d...d..e....g..o............l..f f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f fl..............og......ed..oco..de......go..............lf f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f f..l............o..g....e..d...d..e....g..o............l..f f...l...........o...g...e...d.d...e...g...o...........l...f f....l..........o....g..e....d....e..g....o..........l....f f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f f......l........o......g...........g......o........l......f f.......l.......o.......g.........g.......o.......l.......f f........l......o........g.......g........o......l........f f.........l.....o.........g.....g.........o.....l.........f f..........l....o..........g...g..........o....l..........f f...........l...o...........g.g...........o...l...........f f............l..o............g............o..l............f f.............l.ooooooooooooooooooooooooooo.l.............f f..............l...........................l..............f f...............l.........................l...............f f................l.......................l................f f.................l.....................l.................f f..................l...................l..................f f...................l.................l...................f f....................l...............l....................f f.....................l.............l.....................f f......................l...........l......................f f.......................l.........l.......................f f........................l.......l........................f f.........................l.....l.........................f f..........................l...l..........................f f...........................l.l...........................f f............................l............................f fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +............................................................+............................................................+ +...........................................................+.+...........................................................+ +..........................................................+...+..........................................................+ +.........................................................+.....+.........................................................+ +........................................................+.......+........................................................+ +.......................................................+.........+.......................................................+ +......................................................+...........+......................................................+ +.....................................................+.............+.....................................................+ +....................................................+...............+....................................................+ +...................................................+.................+...................................................+ +..................................................+...................+..................................................+ +.................................................+.....................+.................................................+ +................................................+.......................+................................................+ +...............................................+.........................+...............................................+ +..............................................+...........................+..............................................+ +.............................................+.............................+.............................................+ +............................................+...............................+............................................+ +...........................................+.................................+...........................................+ +..........................................+...................................+..........................................+ +.........................................+.....................................+.........................................+ +........................................+.......................................+........................................+ +.......................................+.........................................+.......................................+ +......................................+...........................................+......................................+ +.....................................+.............................................+.....................................+ +....................................+...............................................+....................................+ +...................................+.................................................+...................................+ +..................................+...................................................+..................................+ +.................................+.....................................................+.................................+ +................................+.......................................................+................................+ +...............................+.........................................................+...............................+ +..............................+...........................................................+..............................+ +.............................+.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.+.............................+ +............................+..C............................r............................C..+............................+ +...........................+...C...........................r.r...........................C...+...........................+ +..........................+....C..........................r...r..........................C....+..........................+ +.........................+.....C.........................r.....r.........................C.....+.........................+ +........................+......C........................r.......r........................C......+........................+ +.......................+.......C.......................r.........r.......................C.......+.......................+ +......................+........C......................r...........r......................C........+......................+ +.....................+.........C.....................r.............r.....................C.........+.....................+ +....................+..........C....................r...............r....................C..........+....................+ +...................+...........C...................r.................r...................C...........+...................+ +..................+............C..................r...................r..................C............+..................+ +.................+.............C.................r.....................r.................C.............+.................+ +................+..............C................r.......................r................C..............+................+ +...............+...............C...............r.........................r...............C...............+...............+ +..............+................C..............r...........................r..............C................+..............+ +.............+.................C.............r.ooooooooooooooooooooooooooo.r.............C.................+.............+ +............+..................C............r..o............F............o..r............C..................+............+ +...........+...................C...........r...o...........F.F...........o...r...........C...................+...........+ +..........+....................C..........r....o..........F...F..........o....r..........C....................+..........+ +.........+.....................C.........r.....o.........F.....F.........o.....r.........C.....................+.........+ +........+......................C........r......o........F.......F........o......r........C......................+........+ +.......+.......................C.......r.......o.......F.........F.......o.......r.......C.......................+.......+ +......+........................C......r........o......F...........F......o........r......C........................+......+ +.....+.........................C.....r.........o.....F.eeeeeeeeeee.F.....o.........r.....C.........................+.....+ +....+..........................C....r..........o....F..e....t....e..F....o..........r....C..........................+....+ +...+...........................C...r...........o...F...e...t.t...e...F...o...........r...C...........................+...+ +..+............................C..r............o..F....e..t...t..e....F..o............r..C............................+..+ +.+.............................C.r.............o.F.....e.t.ooo.t.e.....F.o.............r.C.............................+.+ ++..............................Cr..............oF......et..oVo..te......Fo..............rC..............................++ +.+.............................C.r.............o.F.....e.t.ooo.t.e.....F.o.............r.C.............................+.+ +..+............................C..r............o..F....e..t...t..e....F..o............r..C............................+..+ +...+...........................C...r...........o...F...e...t.t...e...F...o...........r...C...........................+...+ +....+..........................C....r..........o....F..e....t....e..F....o..........r....C..........................+....+ +.....+.........................C.....r.........o.....F.eeeeeeeeeee.F.....o.........r.....C.........................+.....+ +......+........................C......r........o......F...........F......o........r......C........................+......+ +.......+.......................C.......r.......o.......F.........F.......o.......r.......C.......................+.......+ +........+......................C........r......o........F.......F........o......r........C......................+........+ +.........+.....................C.........r.....o.........F.....F.........o.....r.........C.....................+.........+ +..........+....................C..........r....o..........F...F..........o....r..........C....................+..........+ +...........+...................C...........r...o...........F.F...........o...r...........C...................+...........+ +............+..................C............r..o............F............o..r............C..................+............+ +.............+.................C.............r.ooooooooooooooooooooooooooo.r.............C.................+.............+ +..............+................C..............r...........................r..............C................+..............+ +...............+...............C...............r.........................r...............C...............+...............+ +................+..............C................r.......................r................C..............+................+ +.................+.............C.................r.....................r.................C.............+.................+ +..................+............C..................r...................r..................C............+..................+ +...................+...........C...................r.................r...................C...........+...................+ +....................+..........C....................r...............r....................C..........+....................+ +.....................+.........C.....................r.............r.....................C.........+.....................+ +......................+........C......................r...........r......................C........+......................+ +.......................+.......C.......................r.........r.......................C.......+.......................+ +........................+......C........................r.......r........................C......+........................+ +.........................+.....C.........................r.....r.........................C.....+.........................+ +..........................+....C..........................r...r..........................C....+..........................+ +...........................+...C...........................r.r...........................C...+...........................+ +............................+..C............................r............................C..+............................+ +.............................+.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.+.............................+ +..............................+...........................................................+..............................+ +...............................+.........................................................+...............................+ +................................+.......................................................+................................+ +.................................+.....................................................+.................................+ +..................................+...................................................+..................................+ +...................................+.................................................+...................................+ +....................................+...............................................+....................................+ +.....................................+.............................................+.....................................+ +......................................+...........................................+......................................+ +.......................................+.........................................+.......................................+ +........................................+.......................................+........................................+ +.........................................+.....................................+.........................................+ +..........................................+...................................+..........................................+ +...........................................+.................................+...........................................+ +............................................+...............................+............................................+ +.............................................+.............................+.............................................+ +..............................................+...........................+..............................................+ +...............................................+.........................+...............................................+ +................................................+.......................+................................................+ +.................................................+.....................+.................................................+ +..................................................+...................+..................................................+ +...................................................+.................+...................................................+ +....................................................+...............+....................................................+ +.....................................................+.............+.....................................................+ +......................................................+...........+......................................................+ +.......................................................+.........+.......................................................+ +........................................................+.......+........................................................+ +.........................................................+.....+.........................................................+ +..........................................................+...+..........................................................+ +...........................................................+.+...........................................................+ +............................................................+............................................................+ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ``` [Answer] # MATL, ~~63~~ 54 bytes ``` l&)"X@o?TT@I$Ya}t&n2/Xkw2+-|thYa9Mqt_w&:|&+tleXM=@*+]c ``` [**Try it Online!**](http://matl.tryitonline.net/#code=bCYpIlhAbz9UVEBJJFlhfXQmbjIvWGt3MistfHRoWWE5TXF0X3cmOnwmK3RsZVhNPUAqK11j&input=J2NvZGVnb2xmJw) **Explanation** ``` % Implicitly grab the input as a string l&) % Separate the first letter from the rest and push them onto the stack " % For every letter in the string besides the first X@o? % If this is an odd iteration through the loop TT % Push the array [1, 1] @ % Get current character I$Ya % Pad the matrix with 1 copy of this character on all sides } % Else (this is a diamond) t % Duplicate the matrix &n % Determine the number of rows and columns (push separately to stack) 2/Xk % Compute the radius (half the # of columns rounded up) w2+ % Flip the stack to get the # of rows and add 2. This is the new radius. -| % Subtract the new and old radii and take the absolute value thYa % Apply the necessary number of padding zeros to the matrix 9Mqt_w&:% Generate the array [-radius ... 0 ... radius] |&+ % Take the absolute value and compute the element-wise sum with itself % and automatically broadcast to a matrix. For a radius of 5 this yields % the following: % % 8 7 6 5 4 5 6 7 8 % 7 6 5 4 3 4 5 6 7 % 6 5 4 3 2 3 4 5 6 % 5 4 3 2 1 2 3 4 5 % 4 3 2 1 0 1 2 3 4 % 5 4 3 2 1 2 3 4 5 % 6 5 4 3 2 3 4 5 6 % 7 6 5 4 3 4 5 6 7 % 8 7 6 5 4 5 6 7 8 % tleXM % Duplicate and compute the mode of this matrix (4 in the example above) =@* % Find the locations where the matrix is equal to the mode and % replace with the current character. Set all else to 0. + % Add this to the padded version of the previous iteration. ] % End of if...else c % Cast the current matrix as a character array (zeros are spaces) % Implicit end of for loop and implicit display ``` [Answer] # Mathematica, 167 bytes ``` Grid@Fold[g=Normal@SparseArray[h=f;a_List/;Plus@@Abs[a-#-1]==#->#3,2{#,#}+1]+a[#2,#/2+1]&[Length@#+1,#,#2]&;h=f=(h=g;a=ArrayPad)[#,1,#2]&;h@##&,{{#}},{##2}]/.Rule[0,]& ``` The input must be a list of characters. e.g. ``` Grid@Fold[ ... ]/.Rule[0,]&["i","n","p","u","t"] ``` [Answer] ## JavaScript (ES6), 252 bytes ``` f=([c,...r],a,n,d)=>c?a?d?f(r,[...Array(m=n+n+3)].map((_,i,b)=>b.map((_,j)=>(a[i-g]||[])[j-g]||(i+j-h&&j+h-i&&h+i-j&&i+j-h*3?` `:c)),h=m>>1,g=m-n>>1),m,0):f(r,[b=[...a].fill(c),...a,b].map(b=>[c,...b,c]),n+2,1):f(r,[[c]],1,0):a.map(b=>b.join``).join`\n` ``` ``` <input oninput=o.textContent=this.value&&f(this.value)><pre id=o> ``` Where `\n` represents the literal newline character. [Answer] # JavaScript (ES6), 204 ~~229 238~~ An anonymous function returning an array of strings ``` s=>[...s].map(v=>{T=(x,y)=>((r=[...c[y+z]||' '.repeat(z+z)])[z+x]=r[z-x]=v,c[z+y]=c[z-y]=r.join``);for(y=o-~o,o*=++i%2+1;y--;i%2?T(q,y):T(o,q,T(q,o)))q=y-o;++o},l=s.length,z=(2<<-~l/2)-3-l%2,c=[i=o=0])&&c ``` *Less golfed* ``` s=>( l = s.length, z = (2 << l/2 + .5) - 3 - l%2, // zero position, total width and height are z+z+1 c = [], // output canvas o = 0, // base drawing offset from z [...s].map( (v, i) => { // execute for each char v at position i in input string // helper function to put current char v at position (z+y, z+x),(z+y,z-x),(z-y,z+x),(z-y,z-x) // as the image has vertical and horizontal symmetry T=(x,y) =>( r = [...c[y+z]||' '.repeat(z+z)]), // convert string to array to set char at given pos r[z+x] = v, r[z-x] = v, c[z+y] = c[z-y] = r.join`` // array to string again ); // shorter than if(i%2) {for ...}else{for ...} // o is doubled at every other step // and incremented (below) at each step for(y=o+o, i % 2 ? 0 : o=o*2; y >= 0; y--) q = y-o, i % 2 // even and odd steps have different shapes ? ( T(o,q), T(q,o)) : T(q,y); ++o }), c ) ``` **Test** ``` f= s=>[...s].map(v=>{T=(x,y)=>((r=[...c[y+z]||' '.repeat(z+z)])[z+x]=r[z-x]=v,c[z+y]=c[z-y]=r.join``);for(y=o-~o,o*=++i%2+1;y--;i%2?T(q,y):T(o,q,T(q,o)))q=y-o;++o},l=s.length,z=(2<<-~l/2)-3-l%2,c=[i=o=0])&&c function update() { O.textContent=f(I.value).join`\n` } update() ``` ``` <input id=I value=CodeGolf oninput='update()'> <pre id=O></pre> ``` [Answer] ## Java - 429 417 bytes ``` int r,l;int D(int n){return Math.abs(n-r);}int R(int n){return n=(n!=0)?((n%2!=0)?(R(n-1)+1):(2*R(n-1))+2):n;}char[][]C(String a){char[]c=a.toCharArray();l=a.length();r=R(l-1);int s=r*2+1,i,j,k;char[][]x=new char[s][s];for(i=0;i<s;i++){for(j=0;j<s;j++){x[i][j]=' ';for(k=0;k<l;k++){if(D(i)<=R(k)&&D(j)<=R(k)){if(k%2!=0){if(D(i)==R(k)||D(j)==R(k)){x[i][j]=c[k];}}else{if(D(i)+D(j)==R(k)){x[i][j]=c[k];}}}}}}return x;} ``` Credit goes to @Anedar as it was an influence on the structure of this answer *Ungolfed:* ``` int r, l; int D(int n) { return Math.abs(n - r); } int R(int n) { return n = (n != 0) ? ((n % 2 != 0) ? (R(n - 1) + 1) : (2 * R(n - 1)) + 2) : n; } char[][] C(String a) { char[] c = a.toCharArray(); l = a.length(); r = R(l - 1); int s = r * 2 + 1, i, j, k; char[][] x = new char[s][s]; for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { x[i][j] = ' '; for (k = 0; k < l; k++) { if (D(i) <= R(k) && D(j) <= R(k)) { if (k % 2 != 0) { if (D(i) == R(k) || D(j) == R(k)) { x[i][j] = c[k]; } } else if (D(i) + D(j) == R(k)) { x[i][j] = c[k]; } } } } } return x; } ``` [Answer] # JavaScript (ES6), 322 bytes **Non Competitive** ``` var L=s=>{var A=Array,a,D,c,d=-1,i,k,w,O,Z,P=(u,v)=>{Z=O-(d>>1);a[D?u-v+O:u+Z][D?u+v+O-d+1:v+Z]=c},G=(c,i)=>(D=~i&1)?(d+=2,w=2*d-1):(d+=d+1,w=d);s=[...s];s.map(G);a=A(w).fill(0).map(a=>A(w).fill` `);O=w>>1;d=-1;s.map((C,i)=>{G(0,i);c=C;for(k=d;k--;)P(0,k),P(d-1,k),P(k,0),P(k,d-1)});return a.map(v=>v.join("")).join("\n")} ``` **Less Golphed** ``` var L=s=>{ var A=Array,a,D,c,d=-1,i,k,w,O,Z P=(u,v)=>{ Z=O-(d>>1) a[D?u-v+O:u+Z][D?u+v+O-d+1:v+Z]=c}, G=(c,i)=>(D=~i&1)?(d+=2,w=2*d-1):(d+=d+1,w=d) s=[...s] s.map(G) a=A(w).fill(0).map( a=>A(w).fill` `) O=w>>1 d=-1 s.map((C,i)=>{ G(0,i) c=C for(k=d;k--;) P(0,k),P(d-1,k),P(k,0),P(k,d-1)}) return a.map(v=>v.join("")).join("\n") } ``` Test with ``` L("arty*") ``` Easy gains by leaving out the leading `var L=` and `.join("\n")` in the return statement for -17 bytes, but type them back in to test the code **:D** It's a two pass answer, evaluating the width (`w`) required to plot a square or diamond plot, before plotting points with `P` in the second pass using rotation and translation. `d` is the dimension (height or width) of an unrotated square before translation or rotation. Rotation and scale by √2 details from [Mathematica answer](https://math.stackexchange.com/a/383343/342925). Use of tagged string template from [first answer in this thread](https://codegolf.stackexchange.com/a/96047/53067). Thanks to both for the learning. Votes for the question and answers. [Answer] # Powershell, ~~269~~ ~~245~~ 238 bytes ``` $m,$a=$args if($a){$a|%{$c=$_ $w=$m[0].Length $m=&({$i=0 ($m|%{$_+'.'*$w+'.'})+(0..$w|%{'..'*$w+'.'})|%{($s=$_|% t*y)[--$i]=$c -join$s}},{$m|%{$_+$c} $c*$w+$c})[++$k%2]} $m=($w=$m[0].Length-1)..1+0..$w|%{$m[$_]|%{-join($_[$w..1]+$_)}}} $m ``` Ungolfed, explained & test scripted: ``` $f={ # $args is input char array # $m is canvas. # This script draws a right-bottom quadrant (axes included) on the canvas. # If $args contains one char only then $m contains this char and whole image at same time. $m,$a=$args # $a is other chars array if($a){ $a|%{ $c=$_ # $c is current char $w=$m[0].Length # $w is width of the canvas $m=&({ # $m is the result of executing one of the two scriptblocks # draw Diamond quadrant $i=0 ($m|%{$_+'.'*$w+'.'})+ # expand the canvas (0..$w|%{'..'*$w+'.'})|%{ # add new lines ($s=$_|% t*y)[--$i]=$c # take a diamond edge on each line of the canvas -join$s } },{ # draw Square quadrant $m|%{$_+$c} # expand the canvas $c*$w+$c # add new line })[++$k%2] # get a scriptblock from the array and execute it } # We have a right-bottom part of drawn AsciiArt now. Flip, flip, paste it. $w=$m[0].Length-1 # width of the canvas $m=$w..1+0..$w|%{$m[$_]|%{ # flip vertical -join($_[$w..1]+$_) # flip horizontal }} } $m } @( ,('c',@" c "@) ,('ca',@" aaa aca aaa "@) ,('cat',@" ....t.... ...t.t... ..t...t.. .t.aaa.t. t..aca..t .t.aaa.t. ..t...t.. ...t.t... ....t.... "@) ,('cats',@" sssssssssss s....t....s s...t.t...s s..t...t..s s.t.aaa.t.s st..aca..ts s.t.aaa.t.s s..t...t..s s...t.t...s s....t....s sssssssssss "@) ,('meows',@" ............s............ ...........s.s........... ..........s...s.......... .........s.....s......... ........s.......s........ .......s.........s....... ......s...........s...... .....s.wwwwwwwwwww.s..... ....s..w....o....w..s.... ...s...w...o.o...w...s... ..s....w..o...o..w....s.. .s.....w.o.eee.o.w.....s. s......wo..eme..ow......s .s.....w.o.eee.o.w.....s. ..s....w..o...o..w....s.. ...s...w...o.o...w...s... ....s..w....o....w..s.... .....s.wwwwwwwwwww.s..... ......s...........s...... .......s.........s....... ........s.......s........ .........s.....s......... ..........s...s.......... ...........s.s........... ............s............ "@) ,('codegolf',@" fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff f............................l............................f f...........................l.l...........................f f..........................l...l..........................f f.........................l.....l.........................f f........................l.......l........................f f.......................l.........l.......................f f......................l...........l......................f f.....................l.............l.....................f f....................l...............l....................f f...................l.................l...................f f..................l...................l..................f f.................l.....................l.................f f................l.......................l................f f...............l.........................l...............f f..............l...........................l..............f f.............l.ooooooooooooooooooooooooooo.l.............f f............l..o............g............o..l............f f...........l...o...........g.g...........o...l...........f f..........l....o..........g...g..........o....l..........f f.........l.....o.........g.....g.........o.....l.........f f........l......o........g.......g........o......l........f f.......l.......o.......g.........g.......o.......l.......f f......l........o......g...........g......o........l......f f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f f....l..........o....g..e....d....e..g....o..........l....f f...l...........o...g...e...d.d...e...g...o...........l...f f..l............o..g....e..d...d..e....g..o............l..f f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f fl..............og......ed..oco..de......go..............lf f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f f..l............o..g....e..d...d..e....g..o............l..f f...l...........o...g...e...d.d...e...g...o...........l...f f....l..........o....g..e....d....e..g....o..........l....f f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f f......l........o......g...........g......o........l......f f.......l.......o.......g.........g.......o.......l.......f f........l......o........g.......g........o......l........f f.........l.....o.........g.....g.........o.....l.........f f..........l....o..........g...g..........o....l..........f f...........l...o...........g.g...........o...l...........f f............l..o............g............o..l............f f.............l.ooooooooooooooooooooooooooo.l.............f f..............l...........................l..............f f...............l.........................l...............f f................l.......................l................f f.................l.....................l.................f f..................l...................l..................f f...................l.................l...................f f....................l...............l....................f f.....................l.............l.....................f f......................l...........l......................f f.......................l.........l.......................f f........................l.......l........................f f.........................l.....l.........................f f..........................l...l..........................f f...........................l.l...........................f f............................l............................f fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff "@) #,('codegolfes',"") ) | % { $s, $e = $_ $c = $s-split''-ne'' $r = &$f @c $r = $r-join"`n" "$($e-eq$r): $s`n$r" } ``` ]
[Question] [ *Note: This is #2 in a series of [array](/questions/tagged/array "show questions tagged 'array'") challenges. For the previous challenge, [click here](https://codegolf.stackexchange.com/questions/103571/an-array-of-challenges-1-alternating-arrays).* # Separating Nested Lists > > To separate values in a nested list, flatten it, and then wrap each value so it is at the same nested depth as before. > > > That is to say, this list: ``` [1, [2, 3], [4, 4, [5, 2], 1]] ``` Would become: ``` [1, [2], [3], [4], [4], [[5]], [[2]], [1]] ``` --- # The Challenge Your task is to write a program which takes any nested list of positive integers (within your language's limits) and performs this separation operation. You may submit a function which takes the list as an argument, or a full program which performs I/O. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest submission (in bytes) wins!\* \*Standard golfing loopholes are banned. You know the drill. --- # Test Cases Input lists will only ever contain integers in your language's standard integer size. To avoid languages' constraints preventing them from competing, values will not be nested at depths of more than 10. You may assume that input will not have empty sub-lists: for example - `[[5, []]]` will not be given. However, the main list could be empty. ``` [] -> [] [[1, 2]] -> [[1], [2]] [3, [4, 5]] -> [3, [4], [5]] [3, [3, [3]]] -> [3, [3], [[3]]] [[6, [[7]]]] -> [[6], [[[7]]]] [[5, 10], 11] -> [[5], [10], 11] ``` Don't hesitate to leave a comment if I've missed out a corner case. # Example I threw together a quick (ungolfed) Python 3 solution as an example - you can [**test it on repl.it**](https://repl.it/Eu4J/1). [Answer] ## Mathematica, ~~24~~ 21 bytes ``` ##&@@List/@#0/@#&/@#& ``` or one of these: ``` ##&@@List/@#&/@#0/@#& ##&@@List@*#0/@#&/@#& ##&@@List/@#&@*#0/@#& ``` ### Explanation The reason this is so short is that it's basically a recursion that doesn't require an explicit base case. There's a lot of syntactic sugar here, so let's start by ungolfing this. `&` denotes an unnamed function left of it, whose argument is written as `#`. Inside this function `#0` refers to the function itself, which allows one to write unnamed recursive functions. But let's start by giving the inner function a name and pulling it out: ``` f[x_] := ##& @@ List /@ f /@ x f /@ # & ``` The other important syntactic sugar is `f/@x` which is short for `Map[f, x]` i.e. it calls `f` on every element of `x`. The reason `f[x_] := ... f /@ x` doesn't lead to infinite recursion is that mapping something over an atom leaves the atom unchanged without actually calling the function. Hence, we don't need to check for the base case (current element is an integer) explicitly. So the function `f` first recurses down to the deepest list inside `x`, at which point `f/@` becomes a no-op. Then we call use `##& @@ List /@` on that. Mapping `List` over the list simply wraps each element in a separate list, so `{1, 2, 3}` becomes `{{1}, {2}, {3}}`. Then we *apply* `##&` to it, which means the head (i.e. the outer list) gets replaced by `##&`, so this turns into `##&[{1}, {2}, {3}]`. But `##&` simply returns it's arguments as a `Sequence` (which you can think of as an unwrapped list, or a sort of "splat" operator in other languages). So `##& @@ List /@` turns a list `{1, 2, 3}` into `{1}, {2}, {3}` (kind of, that last thing is actually wrapped in the head `Sequence`, but that vanishes as soon as we use the value anywhere). That leaves the question why `f` itself isn't already the solution to the challenge. The problem is that the outermost list should be treated differently. If we have input `{{1, 2}, {3, 4}}` we want `{{1}, {2}, {3}, {4}}` and *not* `{{1}}, {{2}}, {{3}}, {{4}}`. My original solution fixed this by passing the final result as a list of arguments to `Join` which would restore the outer level of lists, but this one just skips the outer level by using `f` *itself* in a map on the output. Hence `f` is only applied to the individual elements of the outermost list and never gets to touch that list. As for the other three solutions, the first one simply applies the recursion outside of `f` which works just as well. The other two solutions avoid a repeated `Map` operation by first composing two functions and then mapping the result only once. [Answer] # [J](http://jsoftware.com/), ~~19~~ 18 bytes ``` (<@]/@,~>)S:0 1{:: ``` This is an anonymous verb that takes and returns boxed arrays, which are J's (rather cumbersome) version of nested arrays. [See it pass all test cases.](https://tio.run/nexus/j#PY5NCgIxDEb3PUWXLQhO0h@hiTJ3cO1CxMGd2QtevdPWWAgk5D2Sr272XKzj9XZcD9@Lv5bFwqeU@ny83vZezOhbnwS6ykD4Wwr8YZsEOwzEkZJinBiNBMWtOKgQphCMxHE8N8wn5XHyaCSNnIlg8QT6WdI0kpHcDSCHFHzPEanp6MkxePXz9HPdAQ "J – TIO Nexus") ## Explanation This uses the somewhat exotic operations `{::` ([map](http://code.jsoftware.com/wiki/Vocabulary/curlylfcoco)) and `S:` ([spread](http://code.jsoftware.com/wiki/Vocabulary/scapco)), which operate on boxed arrays. `{::` replaces each leaf with the boxed path to that leaf. `S:` applies a given verb to a given nesting depth, then splats the results into an array. ``` (<@]/@,~>)S:0 1{:: Input is y. ( ) Let's look at this verb first. > Open the right argument, ,~ append the left argument to it, / then reduce by <@] boxing. This puts the left argument into as many nested boxes as the right argument is long. This verb is applied to y {:: and its map 0 1 at levels 0 and 1. This means that each leaf of y is paired with its path, whose length happens to be the nesting depth of y, and the auxiliary verb is applied to them. S: The results are spread into an array. ``` [Answer] # [Brachylog v1](http://github.com/JCumin/Brachylog), 16 bytes ``` :{##:0&:ga|g}ac| ``` [Try it online!](http://brachylog.tryitonline.net/#code=OnsjIzowJjpnYXxnfWFjfA&input=WzE6WzI6M106WzQ6NDpbNToyXToxXV0&args=Wg) ### Explanation ``` Example input: [1:[2:3]] :{ }a Apply the predicate below to each element of the list: [[1]:[[2]:[3]]] c Concatenate: Output = [1:[2]:[3]] | Or: Input = Output = [] ## Input is a list: e.g. Input = [2:3] :0& Call recursively the main predicate with this input: [2:3] :ga Group each element in a list: Output = [[2]:[3]] | Or (not a list): e.g. Input = 1 g Group into a list: Output = [1] ``` [Answer] # R, 199 bytes ``` function(l){y=unlist(l);f=function(x,d=0){lapply(x,function(y){if(class(y)=='list'){f(y,d=d+1)}else{d}})};d=unlist(f(l));lapply(1:length(d),function(w){q=y[w];if(d[w]){for(i in 1:d[w])q=list(q)};q})} ``` This question was HARD. R's lists are a bit weird and it is absolutely not straightforward to loop over all the elements of sublists. It is also not straightforward to then determining the depth of that list. Then the challenge becomes to recreate the list with all the elements separated, so we also need a way to adaptively create a list of a certain depth. The solution consists of two big parts. A recursive function that loops over all the lists and records the depth: ``` f=function(x,d=0){ lapply(x,function(y){ if(class(y)=='list'){ f(y,d=d+1) } else { d }}) } ``` When we have the depths of every entry of the vector `unlist(l)`, stored in `d`, we implicitly create a list through `lapply`, and fill it with the following function: ``` lapply(1:length(d),function(w){ q=y[w] if(d[w]){ for(i in 1:d[w]){ q=list(q) } } q }) ``` In this apply call, we create an object `q` with the value of the entry in the list, check its depth and see if it is nonzero. If it is zero, we can just leave it as a numeric value. If it is non-zero, we need to nest it in that amount of lists. So we call a for-loop `d` times and repeatedly call `q=list(q)`. `lapply` then puts all these values of `q` in a list, creating the desired output. ### Complete program with proper spacing and such: ``` function(our.list){ values <- unlist(our.list) f <- function(part.list, depth = 0){ lapply(part.list, function(y){ if(class(y)=='list'){ f(y, depth <- depth + 1) } else { return(depth) }}) } depths <- unlist(f(our.list)) new.list <- lapply(1:length(depths), function(w){ q <- values[w] if(depths[w] != 0){ for(i in 1:depths[w]){ q <- list(q) } } return(q) }) return(new.list) } ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 34 bytes ``` +`(.(?>()\[|(?<-2>)]|.)+)\2, $1],[ ``` [Try it online!](https://tio.run/nexus/retina#LctLCoRAEAPQvedQqMYoVvnbDLqcQ8SAB/HuPd2MUJBHQnX2vXN/22jnYeniY@dniCPpGVOfrkDTusCcqYZ0hErO4IL1VT1VcwO56@8VPgnuxQ4GZtWfBWWI0ks/ "Retina – TIO Nexus") [Answer] # C (gcc), 147 bytes ``` d=0,l,i; P(n,c){for(;n--;)putchar(c);} main(c){for(;~(c=getchar());l=i)i=isdigit(c),P((l<i)*d,91),P(i,c),P((l>i)*d,93),P(l>i,32),d+=(92-c)*(c>90);} ``` Example input: ``` 1 [23 3] [40 4 [5 2] 1] ``` Example output: ``` 1 [23] [3] [40] [4] [[5]] [[2]] [1] ``` [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), noncompeting, 25 bytes ``` {e d:e$wrap d 1-*}cellmap ``` This is a function in that it modifies the top member of the stack. If you want a bonafide function, just add `[` and `]` to the beginning and end. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) Here's a readable version: ``` { arr : arr { ele depth : ele $wrap depth 1- * (* execute wrap n times, according to the depth *) } cellmap (* apply to each cell, then collect the results in an array *) } @:a2 (1 (2 3) (4 4 (5 2) 1)) a2 out ``` Test case: ``` (1 (2 3) (4 4 (5 2) 1)) (* arg on TOS *) {e d:e$wrap d 1-*}cellmap out (* display TOS *) ``` Output without newlines: ``` (1 (2) (3) (4) (4) ((5)) ((2)) (1)) ``` [Answer] # PHP, ~~101~~ 94 bytes saved 1 byte thanks to @Christoph, saved another 6 inspired by that. ``` function s($a){foreach($a as$b)if($b[0])foreach(s($b)as$c)$r[]=[$c];else$r[]=$b;return$r?:[];} ``` recursive function, pretty straight forward **breakdown** ``` function s($a) { foreach($a as$b) // loop through array if($b[0]) // if element is array foreach(s($b)as$c)$r[]=[$c]; // append separated elements to result else$r[]=$b; // else append element to result return$r?:[]; // return result, empty array for empty input } ``` [Answer] # Python 2, ~~122~~ 106 bytes Pretty terrible score, just a straightforward implementation. Thanks to @Zachary T for helping save 16 bytes! ``` def x(l,a=[],d=0): n=lambda b:b and[n(b-1)]or l if'['in`l`:[x(e,a,d+1)for e in l];return a else:a+=n(d) ``` Call `x` with one argument to run. For some reason it can only be run once. [Answer] ## JavaScript (Firefox 30-57), 53 bytes ``` f=a=>[for(e of a)for(d of e.map?f(e):[e])e.map?[d]:d] ``` Best ES6 answer I have so far is 76 bytes: ``` f=(a,r=[],d=0)=>a.map(e=>e.map?f(e,r,d+1):r.push((n=d=>d?[n(d-1)]:e)(d)))&&r ``` [Answer] # Pyth - 29 bytes ``` .b]FYt-F/LN`[)PsM._:`Q"\d"3.n ``` [Test Suite](http://pyth.herokuapp.com/?code=.b%5DFYt-F%2FLN%60%5B%29PsM._%3A%60Q%22%5Cd%223.n&test_suite=1&test_suite_input=%5B1%2C+%5B2%2C+3%5D%2C+%5B4%2C+4%2C+%5B5%2C+2%5D%2C+1%5D%5D%0A%5B%5D%0A%5B%5B1%2C+2%5D%5D%0A%5B3%2C+%5B4%2C+5%5D%5D%0A%5B3%2C+%5B3%2C+%5B3%5D%5D%5D%0A%5B%5B6%2C+%5B%5B7%5D%5D%5D%5D&debug=0). [Answer] # [Perl 6](http://perl6.org/), ~~60~~ 47 bytes ``` sub f{[$_~~List??|([$_] for .&f)!!$_ for |$^a]} ``` ([Try it online.](https://tio.run/#yV8hP)) ### Explanation: 1. `[... for |$^a]`: Iterate over the input array, and construct a new array from it. 2. `$_ ~~ List ?? ... !! ...`: For each element, check if it is itself an array. 3. `|([$_] for .&f)`: If the element is an array, recursively apply the function to it, iterate over the elements of the new array returned from that recursive call, wrap each element in an array of its own, and slip them into the outer list. 4. `$_`: If the element is not an array, pass it on as-is. [Answer] ## Haskell, 71 bytes ``` data L=N Int|C[L] d#C l=((C .pure.d)#)=<<l d#n=[d n] f(C l)=C$(id#)=<<l ``` Again I have to define my own list type, because Haskell's natives lists can't be arbitrarily nested. This new type `L` can be returned from a function but not be printed by default, so in order to see a result I define a `show` instance for `L`: ``` instance Show L where show (N n)=show n show (C l)=show l ``` Now we can do some test in the REPL: ``` *Main> f $ C[N 1, C[N 2, N 3], C[N 4, N 4, C[N 5, N 2], N 1]] [1,[2],[3],[4],[4],[[5]],[[2]],[1]] *Main> f $ C[C[N 6, C[C[N 7]]]] [[6],[[[7]]]] ``` How it works: a simple recursion which passes the nesting level as a function of `C` constructors. We start with the identity function `id` and whenever there's a list (-> pattern match `d#C l=`) we add a further layer of `C` (-> `C .pure.d`) to the recursive call of `#` to all elements of the list. If we encounter a number, we simply apply the nesting-level-function `d` to the number. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 44 bytes\* Anonymous tacit prefix function. Takes nested APL list as argument and returns a nested APL array. ``` ∊{⊃⊂⍣⍵,⍺}¨{⊃¨(j∊⎕D)⊆+\-⌿'[]'∘.=j←⎕JSON⍵} ``` [Try it online!](https://tio.run/##pVGxbtswEN31FbfRRmijbpN2ylDEXYo2HZwOgaqBliiZLk0KItXECLwkgREolVEUCNClU5YMXbN0KZBP4Y@4Rzlx0rRbBxG6d3fv3rtjuewkUyZ1tmy5xcXuwNU/2l1XLwhGO/uEGCYtIe78FOPBq@77nbd9Qob6ELSCTqrMtlaYri65YkPJBy/f7BFw9XdYxQawlCeQCJNLNl2mbv7FnVVHrjpx1bGrL119TV39c3Zz5bGbq9YY0ziq33bVfONDx33@RcKIuLNv3e2xb15cvB6828W22TJ7SHZCsea/ORvpdiQMfOKFEegxL3RSxmhElzYvLRyMRDyCmCngzAg5hSGHWCsst@jTavBUQVCUCpmPVnzcWKEySEsVW@QMAHCkH1zNU7idjpXXq2r2kQMrsnLClQVmGkIKSIjC@JoEUoo7jqU2HEQKSquOwjmooYUimAWJ@iyYkT4AL3aS26k/RpuiJaHsvQjcFp5s/hUIvdOS/aWq6QGh/AqYSlBg0RAnWNtCyd7fY9FN@nY3Pl9wU0p7t6N2MFt6U/4Uweon7FF4Gq3DZxTCTQpbfyLNF91j4XMEwhfRQ2iLQu9JhE/v39hv "APL (Dyalog Unicode) – Try It Online") `{`…`}` apply the following explicit function where the argument is represented by `⍵`:  `⎕JSON⍵` convert the argument to JSON  `j←` store in `j`  `'[]'∘.=` table where `j` equals open (top row) and close (bottom row) brackets  `-⌿` top row minus bottom row (vertical difference reduction)  `+\` cumulative sum (this gives the nesting level for each character)  `(`…`)⊆` partition, beginning a new partition whenever a 1 is not preceded by a 1 in…   `j∊⎕D` where each character of `j` is a member of the set of **D**igits  `⊃¨` pick the first of each (this gives nesting level per multi-digit number) `∊{`…`}¨` apply the following function to each nesting level (`⍵`), using the corresponding element from the **ϵ**nlisted (flattened) argument as left argument (`⍺`):  `,⍺` ravel (listify) the number (because scalars cannot be enclosed)  `⊂⍣⍵` enclose `⍵` times  `⊃` disclose (because the innermost list is itself an enclosure) --- \* Using Dyalog Classic with `⎕ML←3` (default on many systems), substituting `⊂` for `⊆` and `↑` for `⊃`. [Tio!](https://tio.run/##pVE9b9RAEO39K6bbO7E@cYRAlQIlNCgJxUGBjIs9e21v2Nu1vGuOU3QNQVZ04BMgRaKhSpOCNg0NUn7K/pFj1pcj4aOj8MrzZubNmzeslGE6Y1LnYSKZMSJZ9dzy7HDk2m/9gWuXBKPdF4QYJi0h7v07jEePB893D/YIGes3oBWEmTI7WmF6cc4VG0s@erT/jIBrv8I6NoClPIVUmFKyWYAkB/uu@bjV1UzYK6xwi7dgCw6GTTgwHzfAVApmykqMmk@Q6QrRk1WGne50cYwYNrn23LWX1LXf51cXHru66B1hGmfs9TF/52XoPvwgUUzc6ZfBzpFvXp49GT09xLb5Kr9NdkKx5r85u6VsIQy85pUR6FBZ6bROcEld27K2MC1EUkDCFHBmhJzBmEOiFZZbdMlq8FRBUNUKmY/XfNxYoXLIapVY5AwAcKQfvGgyuJ6OlZfrarQUWJXXE66sd9NnKSBh5/GGBDKKF0qkNhxEBkqrUOEc1NBDEcyCRH0WTKGn4MVOSjvzp@xTXEkoeyMC3cKDN5@B0I2W/C9VXQ8I5S3wp2VV1RGnWNtDyX6/P0V36WtvfL7ippZ241E/mK/8Uv4UwfonGlK4F/8KtyhE9yls/450X3yDRQ8QiB7Gt6FtCsO7MT7Df2M/AQ "APL (Dyalog Classic) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 bytes ``` FWṛ¡"ŒJẈ’Ɗ ``` [Try it online!](https://tio.run/##VZA9DsIwDIXn9BQWrEEi9IeNkYELMFgeWVAvwIZYQIydipjYuUAZQeUe6UWC7apRiZQo8fuS95z9riwPIay3vrm/H5O22vjXpTvevtfwOXenZ1v5pg4BE4NkYTSMMdPZCgCJJXQWFjQAUULHJWSBkZR3mYW8pyKiZaHySOkk4f6oVCgVxLCQw5IUGxkWCvWCYLkFN@eac@Pn2IyxQWDOSUwLasEhM8kjHbEuBv0thWhIksUFtSdE/QBumRL6AQ "Jelly – Try It Online") ## How it works ``` FWṛ¡"ŒJẈ’Ɗ - Main link. Takes a list l on the left F - Flatten l Ɗ - Group the three previous commands over l: ŒJ - Multidimensional indices of l Ẉ - Get the length of each ’ - Decrement - This gets the depth of each element in l " - Zip together l and the depths, d ¡ - Do the following... ṛ - d times: W - Wrap the element of l ``` [Answer] # [J](http://jsoftware.com/), 23 bytes ``` ([:;^:(1<L.)<"+L:0)^:L. ``` [Try it online!](https://tio.run/##TYzLCoMwEEX3fsXFTRLaBK12MyoUCl0FCqU7QZCqraVViP5/Gkxfi2HOuXeYuw0V61AQGNaIQG6kwv6kD5aXlFXE41wrkYcrTZGoSCsrgrmd5kKhvdzGHZNSMpTgi3WOfHw29TB1o3m2DTHxOfjWR9Nf@6F@uC5Y/qEmv2NsMiRIveVO3/TDBJnTFNs/9VliXw "J – Try It Online") Since J requires boxing for ragged arrays, we use boxing level for array nesting level. Thus for example: ``` Original: ┌─────┐ │┌───┐│ ││1 2││ │└───┘│ └─────┘ Transformed: ┌───┬───┐ │┌─┐│┌─┐│ ││1│││2││ │└─┘│└─┘│ └───┴───┘ Original: ┌─┬───────┐ │3│┌─┬───┐│ │ ││3│┌─┐││ │ ││ ││3│││ │ ││ │└─┘││ │ │└─┴───┘│ └─┴───────┘ Transformed: ┌─┬───┬─────┐ │3│┌─┐│┌───┐│ │ ││3│││┌─┐││ │ │└─┘│││3│││ │ │ ││└─┘││ │ │ │└───┘│ └─┴───┴─────┘ ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` f?⁽L€f‹¨£(w ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJmP+KBvUzigqxm4oC5wqjCoyh3IiwiIiwiWzEsIFsyLCAzXV0iXQ==) ``` ¨£ # Zip f # Input flattened ⁽L€ # Replace elements with depths ? # in input f‹ # Flatten and decrement ¨£ # Zipwith... (w # Repeatedly wrap ``` ]
[Question] [ ## Introduction Consider a nonempty list **L** of integers. A *zero-sum slice* of **L** is a contiguous subsequence of **L** whose sum equals 0. For example, **[1, -3, 2]** is a zero-sum slice of **[-2, 4, 1, -3, 2, 2, -1, -1]**, but **[2, 2]** is not (because it doesn't sum to 0), and neither is **[4, -3, -1]** (because it's not contiguous). A collection of zero-sum slices of **L** is a *zero-sum cover* of **L** if every element belongs to at least one of the slices. For example: ``` L = [-2, 4, 1, -3, 2, 2, -1, -1] A = [-2, 4, 1, -3] B = [1, -3, 2] C = [2, -1, -1] ``` The three zero-sum slices **A**, **B** and **C** form a zero-sum cover of **L**. Multiple copies of the same slice can appear in a zero-sum cover, like this: ``` L = [2, -1, -1, -1, 2, -1, -1] A = [2, -1, -1] B = [-1, -1, 2] C = [2, -1, -1] ``` Of course, not all lists have a zero-sum cover; some examples are **[2, -1]** (every slice has nonzero sum) and **[2, 2, -1, -1, 0, 1]** (the leftmost **2** is not part of a zero-sum slice). ## The task Your input is a nonempty integer list **L**, taken in any reasonable format. Your output shall be a truthy value if **L** has a zero-sum cover, and a falsy value if not. You can write a full program or a function, and the lowest byte count wins. ## Test cases ``` [-1] -> False [2,-1] -> False [2,2,-1,-1,0,1] -> False [2,-2,1,2,-2,-2,4] -> False [3,-5,-2,0,-3,-2,-1,-2,0,-2] -> False [-2,6,3,-3,-3,-3,1,2,2,-2,-5,1] -> False [5,-8,2,-1,-7,-4,4,1,-8,2,-1,-3,-3,-3,5,1] -> False [-8,-8,4,1,3,10,9,-11,4,4,10,-2,-3,4,-10,-3,-5,0,6,9,7,-5,-3,-3] -> False [10,8,6,-4,-2,-10,1,1,-5,-11,-3,4,11,6,-3,-4,-3,-9,-11,-12,-4,7,-10,-4] -> False [0] -> True [4,-2,-2] -> True [2,2,-3,1,-2,3,1] -> True [5,-3,-1,-2,1,5,-4] -> True [2,-1,-1,-1,2,-1,-1] -> True [-2,4,1,-3,2,2,-1,-1] -> True [-4,-1,-1,6,3,6,-5,1,-5,-4,5,3] -> True [-11,8,-2,-6,2,-12,5,3,-7,4,-7,7,12,-1,-1,6,-7,-4,-5,-12,9,5,6,-3] -> True [4,-9,12,12,-11,-11,9,-4,8,5,-10,-6,2,-9,10,-11,-9,-2,8,4,-11,7,12,-5] -> True ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes ``` JẆịS¥ÐḟċþJḄẠ ``` [Try it online!](https://tio.run/nexus/jelly#ZVFLTsMwEN33FD3AWIp/iXMCpG5ZVrkMQrDohhvAhh0HqFqJBeEi4SLhzbMdXBFN/Jl582bmeT0sl6flerr/ep9flvPr92n@PCznx@Xyts7PPw8fsLt1Pe72@I7GTpJPTtqz3tQ6aQFOrHCDher3YqI6OjGeMVturiJw7cUzTFOSTBP/6MGRStlBTJAA2OapmQ0eMZiiQNjJCJwVpnWk9jgam5uKaKcHZGCrylRZAEgIoR47x7haNpKMFNh7pgSuuYyxTh1DLhCm3ST7ImhXmTOju5FUR4fX30zti2IW05nQPkexcmzUpDZe3L9QKCkqd095OUwA9TayDpDYXM98p0EVPegyiHUbSX4JyuEgX6QUzYCjgom3/EeFJ51DdSH9yPfQ@Kg1E1/FljIRyv0C "Jelly – TIO Nexus") ### How it works ``` JẆịS¥ÐḟċþJḄẠ Main link. Argument: A (array) J Yield all indices of A. Ẇ Window; yield all slices of indices. Ðḟ Filter; keep slices for which the link to the left returns 0. ¥ Combine the two atoms to the left into a dyadic chain. ị Retrieve the elements of A at the slice's indices. S Take the sum. J Yield the indices of A. ċþ Count table; count how many times each index appears in each table. Ḅ Unbinary; convery the array of counts of each index from base 2 to integer. This yields 0 iff an index does not appear in any slice. Ạ All; return 1 iff all integers are non-zero. ``` [Answer] # Mathematica, ~~66~~ 65 bytes *Saved 1 byte, and hopefully learned a new trick for the future, thanks to ngenisis!* Two equally long alternatives, both of which are unnamed functions taking a list of integers as input and returning `True` or `False`: ``` And@@Table[0==Product[Tr@#[[i;;j]],{i,k},{j,k,l}],{k,l=Tr[1^#]}]& 0==Norm@Table[Product[Tr@#[[i;;j]],{i,k},{j,k,l}],{k,l=Tr[1^#]}]& ``` In both cases, `Tr@#[[i;;j]]` computes the sum of the slice of the input from position `i` to position `j` (1-indexed). `Product[...,{i,k},{j,k,l}]` multiples together all these slice-sums, as `i` ranges over indices that are at most `k` and `j` ranges over indices that are at least `k`. (Note that `l=Tr[1^#]` defines `l` to be the sum of `1` to all the powers in the input list, which is simply the length of the list.) In other words, this product equals 0 if and only if the `k`th element belongs to a zero-sum slice. In the first version, each of those products is compared to `0`, and `And@@` returns `True` precisely when every single product equals `0`. In the second version, the list of products is acted upon by the function `Norm` (the length of the `l`-dimensional vector), which equals `0` if and only if every entry equals `0`. [Answer] ## Mathematica, ~~65~~ 64 bytes *Thanks to ngenisis for saving 1 byte.* ``` Union@@Cases[Subsequences[x=Range@Tr[1^#]],a_/;Tr@#[[a]]==0]==x& ``` I'd rather find a pure pattern matching solution, but it's proving to be tricky (and things like `{___,a__,___}` are always super lengthy). [Answer] ## Haskell, 94 bytes ``` import Data.Lists g x=(1<$x)==(1<$nub(id=<<[i|(i,0)<-fmap sum.unzip<$>powerslice(zip[1..]x)])) ``` Usage example: `g [-11,8,-2,-6,2,-12,5,3,-7,4,-7,7,12,-1,-1,6,-7,-4,-5,-12,9,5,6,-3]`-> `True`. How it works (let's use `[-1,1,5,-5]` for input): ``` zip[1..]x -- zip each element with its index -- -> [(1,-1),(2,1),(3,5),(4,-5)] powerslice -- make a list of all continuous subsequences -- -> [[],[(1,-1)],[(1,-1),(2,1)],[(1,-1),(2,1),(3,5)],[(1,-1),(2,1),(3,5),(4,-5)],[(2,1)],[(2,1),(3,5)],[(2,1),(3,5),(4,-5)],[(3,5)],[(3,5),(4,-5)],[(4,-5)]] <$> -- for each subsequence unzip -- turn the list of pairs into a pair of lists -- -> [([],[]),([1],[-1]),([1,2],[-1,1]),([1,2,3],[-1,1,5]),([1,2,3,4],[-1,1,5,-5]),([2],[1]),([2,3],[1,5]),([2,3,4],[1,5,-5]),([3],[5]),([3,4],[5,-5]),([4],[-5])] fmap sum -- and sum the second element -- -> [([],0),([1],-1),([1,2],0),([1,2,3],5),([1,2,3,4],0),([2],1),([2,3],6),([2,3,4],1),([3],5),([3,4],0),([4],-5)] [i|(i,0)<-  ] -- take all list of indices where the corresponding sum == 0 -- -> [[],[1,2],[1,2,3,4],[3,4]] id=<< -- flatten the list -- -> [1,2,1,2,3,4,3,4] nub -- remove duplicates -- -> [1,2,3,4] (1<$x)==(1<$ ) -- check if the above list has the same length as the input list. ``` [Answer] # J, ~~36~~ 35 bytes ``` #\*/@e.[:;]({:*0=[:+/{.)@|:\.\@,.#\ ``` For every subsum I add the element's indexes and I keep the indexes iff subsum is `0` and then check whether every index is present. Trick: 1-based indexes of a list can be generated with `#\` i.e. length of every prefix. Usage: ``` (#\*/@e.[:;]({:*0=[:+/{.)@|:\.\@,.#\) 2 _1 _1 2 1 (#\*/@e.[:;]({:*0=[:+/{.)@|:\.\@,.#\) 2 _1 0 ``` [Try it online here.](https://tio.run/nexus/j) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22~~ 20 bytes *-2 bytes thanks to Bubbler* ``` ∧/∨⌿↑0={×\⌽+\⌽⍵}¨,\⎕ ``` [Try it online!](https://tio.run/##dVG9SgNBEO73Kaa7QoO3f3e3hW8SkIDEJqCtBDuJAXNBC/ERTCFYiKUI8U3mReL87F6SwoOZ2Zufb2a@mdzMRpe3k9n11Q6XD1NSb2e43ODqBxfP9fn893WMq@8TVth/3W03p2Ncv3Du7gIXT3Ps19UUH@@xf68oiv1nMtsPaxyoFitSg3odWFDLEownG@Vdk/Y5YgePM/xqwOeoCmMUlEjIjNAN3VqSAAHskXdfzRUcYeEswqshcZoFqasztKcf8pbJIk3UUGKbZxY0Q@GO3NwyD0@7Su@okIpDjybXhGxTiVsn3rY0C6Yala8y/zJdm9LSZa49KHM@c@IHLi1EAd5fhGX4E5aVMQ/uyB@GbL5Co4zn7QKheiNbdHmURosdR@QWQXQL1h0AlSNlkhyxGpUf2SlxthZYVUnSO9lCONI@SY8lWUkm6PRmtnSMfw "APL (Dyalog Unicode) – Try It Online") ### Explanation ``` ,\⎕ ⍝ All prefixes of the input { }¨ ⍝ Map each to ⌽+\⌽⍵ ⍝ The sum of each postfix ×\ ⍝ Scan multiplied, spreading any zero sums to the other elements in the sub-array 0= ⍝ Map zeroes to true ↑ ⍝ Mix the arrays into a 2D matrix ∧/∨⌿ ⍝ Do all columns have at least one true value? ``` [Answer] # Ruby, 81 bytes [Try it online](https://repl.it/FEqo) Simplistic brute-force solution; for every element of the array, try to find a zero-sum slice that contains it. ``` ->a{(0..l=a.size).all?{|i|(0..i).any?{|j|(i..l).any?{|k|a[j..k].inject(:+)==0}}}} ``` [Answer] # JavaScript (ES6), 109 bytes ``` f=([q,...a],b=[],c=[])=>1/q?f(a,[...b,0].map((x,i)=>x+q||(c=c.map((n,j)=>n|i<=j)),c.push(0)),c):c.every(x=>x) ``` ### Test snippet ``` f=([q,...a],b=[],c=[])=>1/q?f(a,[...b,0].map((x,i)=>x+q||(c=c.map((n,j)=>n|i<=j)),c.push(0)),c):c.every(x=>x) I.textContent = I.textContent.replace(/.+/g,x=>x+` (${f(eval(x.split(" ")[0]))})`) ``` ``` <pre id=I>[-1] -> False [2,-1] -> False [2,2,-1,-1,0,1] -> False [2,-2,1,2,-2,-2,4] -> False [3,-5,-2,0,-3,-2,-1,-2,0,-2] -> False [-2,6,3,-3,-3,-3,1,2,2,-2,-5,1] -> False [5,-8,2,-1,-7,-4,4,1,-8,2,-1,-3,-3,-3,5,1] -> False [-8,-8,4,1,3,10,9,-11,4,4,10,-2,-3,4,-10,-3,-5,0,6,9,7,-5,-3,-3] -> False [10,8,6,-4,-2,-10,1,1,-5,-11,-3,4,11,6,-3,-4,-3,-9,-11,-12,-4,7,-10,-4] -> False [0] -> True [4,-2,-2] -> True [2,2,-3,1,-2,3,1] -> True [5,-3,-1,-2,1,5,-4] -> True [2,-1,-1,-1,2,-1,-1] -> True [-2,4,1,-3,2,2,-1,-1] -> True [-4,-1,-1,6,3,6,-5,1,-5,-4,5,3] -> True [-11,8,-2,-6,2,-12,5,3,-7,4,-7,7,12,-1,-1,6,-7,-4,-5,-12,9,5,6,-3] -> True [4,-9,12,12,-11,-11,9,-4,8,5,-10,-6,2,-9,10,-11,-9,-2,8,4,-11,7,12,-5] -> True</pre> ``` [Answer] # Python, ~~123~~ 120 bytes -3 bytes thanks to @Zgarb Populates a list with the same size as the input with zero-sum slices and overwrites according to indexes, returning its equality to the original at the end. ``` def f(l): s=len(l);n=[0]*s for i in range(s): for j in range(i,s+1): if sum(l[i:j])==0:n[i:j]=l[i:j] return n==l ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [bytes](https://github.com/abrudz/SBCS) ``` ≢={≢∪∊↓∘⍳/¨⍸∘.=⍨0,+\⍵} ``` [Try it online!](https://tio.run/##VVE/S0NBDN/7KW7r4Kvev/dv6ORiJ8E6uhSkLgVdRZyEx7PwiiKCs1Nx6SCC8/so@SLPXJK71oPkcpfkl@SXxd1qcn2/WN3eDLB5n51D86IHeP6cPqCC9gvaNTRv0H5A933Sb6H7Rft4Ct1WZ0dX0P08DkvMgW4D66d@56B5RZz5xanC6/JsNh@WKut3ZrRUVsWbLBKtoscqI3cQj78OrZxeGrUTn0k/FmOCXVDkXoxUsJQf8ANKlaqWKF55Zf797vM5J/iChDjE1KoOgUZRphZ4hw/8jf3l2FeBgaV0TniIhQEVOkJZGQLnpvo5gzISGoVkebnr6DeWfstYzo/Gk3jGWCLTqCK8TSw7xXy5xINLHBp6@7iZJOkl/DJT7nBv5PEpI2ygYLZlJo/YjqKw@0raKhjABh/twZMulbEHUHFBQo5FPnPmRSasQzynGFY1JVQ0D7HDlWpeFEXV1EPF@zKxZv4H "APL (Dyalog Unicode) – Try It Online") Same byte count as [Jo King's](https://codegolf.stackexchange.com/a/210922/78410), but totally different approach. ### How it works ``` ≢={≢∪∊↓∘⍳/¨⍸∘.=⍨0,+\⍵} ⍝ Input: integer vector { 0,+\⍵} ⍝ Cumulative sum and prepend 0 ∘.=⍨ ⍝ Self outer product by equality ⍸ ⍝ Extract coords of ones; (a,b) with a>b is included ⍝ iff the interval [b+1..a] has zero sum ↓∘⍳/¨ ⍝ For each coord, [b+1..a] if a>b, empty vector otherwise ≢∪∊ ⍝ Count unique values ≢= ⍝ Is the count same as the length of the original array? ``` [Answer] # Scala, 49 bytes ``` % =>(1 to%.size)flatMap(%sliding)exists(_.sum==0) ``` ### [Try it at ideone](https://ideone.com/o0dk4z) ### Usage: ``` val f:(Seq[Int]=>Boolean)= % =>(1 to%.size)flatMap(%sliding)exists(_.sum==0) f(Seq(4, -2, -2)) //returns true ``` ### Ungolfed: ``` array=>(1 to array.size) .flatMap(n => array.sliding(n)) .exists(slice => slice.sum == 0) ``` ### Explanation: ``` % => //define a anonymouns function with a parameter called % (1 to %.size) //create a range from 1 to the size of % flatMap( //flatMap each number n of the range %sliding //to an iterator with all slices of % with length n )exists( //check whether there's an iterator with a sum of 0 _.sum==0 ) ``` [Answer] ## Clojure, 109 bytes ``` #(=(count %)(count(set(flatten(for[r[(range(count %))]l r p(partition l 1 r):when(=(apply +(map % p))0)]p)))) ``` Generates all partitions which sum to zero, checks that it has "length of input vector" distinct indices. [Answer] # PHP, 104 bytes Brute force and still over 99 bytes. :-( ``` for($p=$r=$c=$argc;$s=--$p;)for($i=$c;$s&&$k=--$i;)for($s=0;$k<$c&&($r-=!$s+=$argv[$k++])&&$s;);echo!$r; ``` takes input from command line arguments, `1` for truthy, empty for falsy. Run with `-r`. **breakdown** ``` for($p=$r=$argc;$s=$p--;) # loop $p from $argc-1 to 0 with dummy value >0 for $s for($i=$p;$s&&$k=$i--;) # loop $i (slice start) from $p to 1, break if sum is 0 for($s=0; # init sum to 0 $k<$argc # loop $k (slice end) from $i to $argc-1 &&($r-=!$s+=$argv[$k++]) # update sum, decrement $r if sum is 0 &&$s;); # break loop if sum is 0 echo!$r; # $r = number of elements that are not part of a zero-sum slice ``` `$argv[0]` contains the filename; if run with `-r`, it will be `-` and evaluate to `0` for numeric ops. [Answer] ## JavaScript (ES6), 102 bytes ``` a=>(g=f=>a.map((_,i)=>f(i)))(i=>g(j=>j<i||(t+=a[j])||g(k=>b[k]&=k<i|k>j),t=0),b=g(_=>1))&&!/1/.test(b) ``` Computes the partial sums for all the elements `i..j` inclusive, and resets the relevant elements of `b` from `1` to `0` when it finds a zero sum, finally checking that there are no `1`s left. [Answer] # [Python 3](https://docs.python.org/3/), 99 bytes ``` lambda a,r=range:len({k for j in r(len(a)+1)for i in r(j)if sum(a[i:j])==0for k in r(i,j)})==len(a) ``` [Try it online!](https://tio.run/##bVHLbuowEN3zFd4Rq5Or2HmQIOXu2m033dEuTDElkCaRSe5tVfXb6cw4oIAqOQ/POXPOPLrPftc28WlbPp9q877eGGHAlc40b3ZZ2yb4Ooht68ReVI1wAUWMvFOSYpWP7WW1FcfhPTCrarl/kWUZEXrwaAV7@Y0xn3n6v6tqK57cYJcz0btPfCOvA9EOvSjpd@gD@efY1VUfzEX4V8wlUjpXNX2wDew/UwdIkhLE/Lhrh3oj1nbO6cizH6@268X948O9c61birWz5nBaheqFpB5MfbSzlYbbO0XoRHBL1KCAP3iSKRZDmFIwgjBmXI03PWVhKIOYKXxIzMul11aolY9lLCBMIEHqJXLOvslBHA8xUTiCArkKODViixh/Q@ULTLG0DCkLLpvUpkpIyhFGX@4Ex0D2KQuyDH4zTkv47a1CpSmw8CZX04n4QmuerbyonkR4BjQMBOKxJ4/42pSfe3oWPWf5JYXqvK8JSOsBLlb/hiZjIi0j4@Fzewl6xFMedpVzuRmraMJpIwm9FqD0RceviWekca4pz@e664L4nKL4KSgjp7ZoXuxQ8K4IL8g2542p0Sm9yP0A "Python 3 – Try It Online") Creates a set of all indices which are part of a zero sum. Then checks if all indices are present. [Answer] # Python, 86 Bytes ``` def f(l): r=range(len(l)) if[i for i in r for j in r if sum(l[j:j+i+1])==0]:return 1 ``` Truthy = 1 Falsy = None ]
[Question] [ Everyone knows that cats go meow, but what many don't realise is that caaaats go meeeeoooow. In fact, the length of the vowel sounds that the cat makes are dependant on the length of the vowel with which you address it. In the same way, cows go moo, but coooows go moooooooo ## Challenge You are to write a program that takes as input, a word meaning cat, **and** a word meaning cow, determine the number of main vowels, and print one of the following strings, as appropriate: * `C[]ts go M[]w` * `C[]ws go M[]` Where `[]` stands for the vowels, according to the following rules: * The number of e's and o's in "Meow" must both match the number of vowels found in the input word. * The number of o's in "Moo" must be double the number of vowels found in the input word. The program must recognise the input words `cat` and `cow`. Input may use any capitalisation that is most convenient, but the output must be capitalised exactly as shown above. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~57~~ ~~49~~ ~~44~~ ~~43~~ 41 bytes ~~So close...~~ ~~:)~~ Pyth... ``` .(.+). $0s go M$1$1 +`aa(\w*$) e$1ow wo o ``` [Try it online.](http://retina.tryitonline.net/#code=LiguKykuCiQwcyBnbyBNJDEkMQorYGFhKFx3KiQpCmUkMW93CndvCm8&input=Q2FhYXQ) Expects input to be capitalised like `Caaat` or `Coooow`. ### Explanation ``` .(.+). $0s go M$1$1 ``` The regex matches the entire input, and captures the vowels in group `1` (we don't need anchors, because the match cannot fail and will greedily match the entire input). The substitution writes back that input, and appends `s go M`, followed by twice the vowels. For inputs `Caaat` and `Coooow`, we get: ``` Caaats go Maaaaaa Coooows go Moooooooo ``` The output for cows is already correct. We just need to do something about those cats. ``` +`aa(\w*$) e$1ow ``` The `+` tells Retina to repeat this stage as often as possible. The regex matches two `a`s in the last part of the string (we ensure this with the `$` anchor, so that we don't replace things inside `Caaats`). This will essentially match everything after `M`, as long as that part still has `a`s. The two `a`s are removed and the entire suffix after it is wrapped in `e...ow`: ``` Caaats go Meaaaaow Caaats go Meeaaowow Caaats go Meeeowowow ``` Finally, there are two many `w`s in the result, so we remove those that precede an `o` (to make sure we're not messing up the `w` in `Coooows`): ``` wo o ``` And we're left with: ``` Caaats go Meeeooow ``` [Answer] # LabVIEW, 58 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) creating strings like this is a pain... The leftmost vis are pattern matching, a+ and o+ respectively search for the lagest amount of as and os in a row. Taking the lenght of those i create 3 arrays 1 with lenght os 1 with lenght es and one with 2 times lenght os. Then all the parts get put together. First the original input, then s go M all the Arrays, the unused one are empty so they will be ignored, and finally a w if the input was cats. (If as were found there will be a t after the match, if not after match is empty) [![](https://i.stack.imgur.com/Fc5rt.gif)](https://i.stack.imgur.com/Fc5rt.gif) For the lolz i also implemented the fox with 6 different outputs^^ [![](https://i.stack.imgur.com/C7SA3.gif)](https://i.stack.imgur.com/C7SA3.gif) [Answer] # Pyth, 50 44 34 Takes input in the format `["caat", "coow"]`. ``` Pj.bs[rN3"s go M"S*-lN2+Y\o\w)Q"eo ``` [Try it online.](http://pyth.herokuapp.com/?code=Pj.bs%5BrN3%22s%20go%20M%22S%2A-lN2%2BY%5Co%5Cw%29Q%22eo&input=%5B%22caat%22%2C%20%22coow%22%5D&debug=0) Explained: ``` .b Map a lambda across two lists in parallel: Q The input, e.g. ["caat", "coow"] "eo The string "eo" s[ ) Create and concatenate a list of: rN3 - The item N in title caps (e.g. "Caat") "s go M" - The string "s go M" S - The sorted version of: +Y\o The item Y + "o" ("eo" or "oo") *-lN2 Times the length of N - 2 (number of vowels) \w - The string "w" Pj Join the result on \n and drop the final "w" ``` Thanks to [Jakube](https://codegolf.stackexchange.com/users/29577/jakube) for major reductions in length. [Answer] # Perl, ~~66~~ ~~61~~ ~~55~~ 54 bytes *includes +1 for `-p`* ``` /[ao]+/;$\="s go M".$&=~y/a/e/r.o x($+[0]-1).(w)[/w/] ``` Input is expected to conform to `/^C[ao]+[tw]$/` (no trailing newline!) Usage: `/bin/echo -n Caaat | perl -p 55.pl` ### Breakdown ``` /[ao]+/; $\= "s go M" # assign to $OUTPUT_RECORD_SEPARATOR, normally `\n`. Saves 1 vs `$_.=` . $& # the matched vowels =~ y/a/e/r # translate `a` to `e`; `/r` returns a copy. . o x($+[0]-1) # append 'o', repeated. $+[0] is string position of last match end. . (w)[/w/] # returns 'w' if there is no /w/ in the input, nothing if there is. ``` --- ### Previous version: ``` @l=/[ao]/g;$x=$&[[email protected]](/cdn-cgi/l/email-protection) x@l;$y=$x=~y/a/e/?w:'';s/$/s go M$x$y/ ``` *Commented*: ``` @l = /[ao]/g; # captures $& as vowel and @l as list of vowels $x = $& x @l .o x @l; # construct the output vowels $y = $x =~ y/a/e/ ? w : ''; # correct vowel string for cats (aaaooo->eeeooo); $y='w' if cat. s/$/s go M$x$y/ # construct the desired output. ``` --- ### Example: `Caaat` * Capture `$&` as `a` and `@l` as `(a,a,a)`. * Set `$x` to three times `a` followed by 3 times `o`: `aaaooo`. * Translate all `a` in `$x` to `e`: `eeeooo`. The number of replacements (either 0 or positive) serves as a cat-detector: set `$y` to `w` if so. * Change the input by appending `s go M`, `eeeooo` and `w`. --- * *update 61*: Save 5 bytes by using list instead of string * *update 55*: save 6 bytes by inlining, assigning `$\` rather than `s/$/`, and requiring no trailing newline in input. * *update 54*: save 1 byte by eliminating @l. [Answer] ## Python 2, 74 bytes ``` i=input() l=len(i)-2 print i+'s go M'+['e'*l+'o'*l+'w','o'*l*2][i[-1]>'v'] ``` Takes input `Caaat` or `Cooow` [Answer] ## CJam (60 57 55 53 bytes) ``` "C%s%ss go M%sw "2*-2<q"ctw"-S/"teowoo"3/.{(2$,@*$}e% ``` [Online demo](http://cjam.aditsu.net/#code=%22C%25s%25ss%20go%20M%25sw%0A%222*-2%3Cq%22ctw%22-S%2F%22teowoo%223%2F.%7B(2%24%2C%40*%24%7De%25&input=caat%20coow). Input is assumed to be in lower case. For the same length: ``` "C s go M"N/_]"w "a*q"ctw"-S/"teowoo"3/.{(2$,@*$M}]z ``` --- ``` 'CM"s go M"]2*q"ctw"-S/"teowoo"3/.{(2$,@*$}[MM"w "]]z ``` [Answer] ## PowerShell, ~~135~~ 132 bytes ``` param($a,$b) [char[]]"$a$b"|%{if($_-eq'a'){$c++}$d++} $d-=4+$c "C$("a"*$c)ts go M$("e"*$c)$("o"*$c)w" "C$("o"*$d)ws go M$("o"*2*$d)" ``` (linebreaks count same as semicolons, so line-breaked for clarity) Surprisingly tricky challenge. And I'm reasonably sure this can be golfed further. Takes input strings as `$a` and `$b`. Concatenates them and casts them as a char-array, then pipes that through a loop `%{}`. Each letter is then checked if it's `-eq`ual to `'a'` and the associated counter variable is incremented appropriately. We then subtract `4+$c` from `$d` to account for `catcw` in the input, and proceed to formulate the output sentences, modifying the vowels output times the corresponding counters. (In PowerShell, `'e'*3` would yield `'eee'`, for example.) [Answer] Almost similar to @omulusnr's answer but this produces the correct output and also input is case insensitive. ## PHP, 172 ``` $p=$argv[1]; preg_match("/c([ao]+)/i",$p,$e); $l=strlen($e[1]); $s=($k=strcmp($e[0][1],'o'))?'eo':'oo'; echo $p,' go M',str_repeat($s[0],$l),str_repeat($s[1],$l),$k?'w':''; ``` [Answer] ## Swift 2, 3̶8̶1̶ 333 bytes ``` func f(i:String)->String{var s=i.lowercaseString;s.replaceRange(s.startIndex...s.startIndex,with:String(s[s.startIndex]).uppercaseString);let c=i.characters.count-2;let l=s.characters.last;return(s+"s go M"+String(count:c,repeatedValue:l=="t" ?"e" :"o" as Character)+String(count:c,repeatedValue:"o" as Character)+(l=="t" ?"w" :""))} ``` **Ungolfed:** ``` func f(i:String)->String{ var s = i.lowercaseString s.replaceRange(s.startIndex...s.startIndex,with:String(s[s.startIndex]).uppercaseString) let c = i.characters.count-2 let l = s.characters.last return(s+"s go M"+String(count:c,repeatedValue:l=="t" ?"e" :"o" as Character)+String(count:c,repeatedValue:"o" as Character)+(l=="t" ?"w" :"")) } ``` Takes cat or cow any capitalization. You can try it here: <http://swiftlang.ng.bluemix.net/#/repl/3f79a5335cb745bf0ba7698804ae5da166dcee6663f1de4b045e3b8fa7e48415> [Answer] ## MATLAB: ~~190~~ ~~152~~ 118 bytes ``` i=input('','s');b=sum(i=='a');c=sum(i=='o');d=b>c;disp(['C',i(2:2+b+c),'s go M',i(2:1+b)+4,repmat('o',1,b+2*c),'w'*d]) ``` Ungolfed: ``` i=input('','s'); b=sum(i=='a'); c=sum(i=='o'); d=b>c; disp(['C',i(2:2+b+c),'s go M',i(2:1+b)+4,repmat('o',1,b+2*c),'w'*d]) ``` Tests: ``` caaaaaaaats Caaaaaaaats go Meeeeeeeeoooooooow cooooows Cooooows go Moooooooooo ``` P.S.: Thanks to @Kenney for nice suggestion (see comments)! [Answer] # PHP, 138 bytes ``` echo ucfirst($a=$argv[1]).'s go M'.(($n=substr_count($a,'a'))?str_repeat('e',$n).str_repeat('o',$n).'w':str_repeat('oo',substr_count($a,'o'))); ``` --- readable: ``` echo ucfirst($a = $argv[1]) . 's go M'. ( ($n = substr_count($a, 'a')) ? str_repeat('e', $n) . str_repeat('o', $n) . 'w' : str_repeat('oo', substr_count($a, 'o')) ); ``` tried shorter but wont work in PHP: ``` #too long -- echo ucfirst($s=$argv[1]).'s go M'.(($o='o'and$n=substr_count($s,'a'))?str_repeat('e',$n).str_repeat($o,$n).'w':str_repeat('oo',substr_count($s,$o))); #too long -- echo ucfirst($s=$argv[1]).'s go M'.(($o='o'and$f=function($s,$n){return str_repeat($s,$n);}and$n=substr_count($s,'a'))?$f('e',$n).$f($o,$n).'w':$f('oo',substr_count($s,$o))); ``` =) [Answer] # OCTAVE, 126 , 108 First version with variables and explanation, 126: ``` L="ao"';S={'eo','oo'},e={'w',' '};a=sum(argv(){1}==L,2);b=find(a);disp([argv(){1},' goes m',vec(ones(sum(a),1)*S{b})',e{b}]); ``` Explanation: L knows which animal contains which letter. S knows what they repeat. e knows the ending. You need to have "automatic broadcasting" turned on for this to work, but it should be by default in all Octaves I've used. Of course there exist shorter ways with for example command regexprep (regular expressions with replacement), but there has already been several such approaches in answers already, so that would be boring. --- **Edit:** Skipping variables which only occur once, using octave on-the-fly indexing (don't know what it's called for real) and adding "i", input string variable: ``` i=argv(){1};a=sum(i=="ao"',2);b=find(a);disp([i,' goes m',vec(ones(sum(a),1)*{'eo','oo'}{b})',{'w',''}{b}]); ``` [Answer] # JavaScript (ES2015), ~~78~~ 77 ``` s=>s+'s go M'+(l=s.length-1,w=s[l]<'u',Array(l).join(w?'eo':'oo')+(w?'w':'')) ``` Try it here: <https://jsbin.com/guqaxejiha/1/edit?js,console> [Answer] # [Dart](https://www.dartlang.org/), ~~114 112 110 104 102~~ 100 bytes ``` f(s)=>s+'s go M'.padRight(s[1]=='a'?s.length+4:0,'e').padRight(2*s.length+2,'o')+(s[1]=='a'?'w':''); ``` [Try it online!](https://tio.run/##Xcs/C8IwEIfh3U9x2y9natHi1JI6OLu4ikOgf0Gb0gQyiJ89YhGtue3ufa7SkwuhEZZVaSUstYZOSEddnfu2c8JedleloHGw6a0eWtfJfb5NUIN/KFt/Y5bAgOXiDx45wEW4634Q/FgRjVM/OIGjdrQpCSSpmTcwF8v8nn8yXyJm/JIYH2cTAfMhz/AC "Dart – Try It Online") - -2 bytes : Changed the way the u offset is calculated to reduce the number of additions - -2 bytes : Moved the check on the first pasdding to the width and not the character - -6 bytes : Changed the Cow/Cat check - -2 bytes : Got rid of variable assignments - -2 bytes : Reduced then umber of parentesis on 2\*(s.length+1) [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 64 bytes ``` ~/([ao]+)(.)/ x=$1.size $_<<"s go M"+($2<?w??e*x+?o*x+?w:"oo"*x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5BjlLsgqWlJWm6Fjcd6vQ1ohPzY7U1NfQ09bkqbFUM9Yozq1K5VOJtbJSKFdLzFXyVtDVUjGzsy-3tU7UqtO3zQUS5lVJ-vpJWhSbEHKhxC7Y6J5ZwOSeCAJDOLwfi_PxyiCQA) [Answer] ## Lua, 121 90 Bytes **121 Bytes** ``` i=...r="M"o="o"s=i:len()-3if(i:find("w"))then r=r..o:rep(s*2)else r=r..("e"):rep(s)..o:rep(s).."w"end print(i.." go "..r) ``` **90 bytes** ``` i=....." go M"o="o"s=#i-7 print(i..(i:find"w"and o:rep(s*2)or("e"):rep(s)..o:rep(s).."w")) ``` Takes input such as 'Caats' or 'Coooows' case-sensitive. Since there are no requirements for invalid inputs, the output might be weird for, say, 'Foxes' or 'Oxen'. :P **Ungolfed** ``` i=... .. " go M" o="o" s=#i-7 print(i.. (i:find"w"and o:rep(s*2) or ("e"):rep(s)..o:rep(s).."w") ) ``` *Update to 90 Bytes:* Replaced if-control structure with logical operators, optimized string concatenation by appending more data in declaration of `i`. Removed parenthesis on `i:find("w")`. Interestingly enough, storing `"o"` to a variable saved a couple bytes when using `rep`, but would be counterproductive with `"w"` or `"e"`. The more you know. [Answer] # Lua: ~~115~~ ~~92~~ 89 Bytes ``` i=...l=#i-2o="o"io.write(i,"s go M",i:find"a"and("e"):rep(l)..o:rep(l).."w"or o:rep(l*2)) ``` takes `C[]t` or `C[]w` as input; [] = a's or o's. A lowecase input will translate to the result. long version: ``` i=... --"C[]t" or "C[]w" l=#i-2 --length of input -2 o="o" --shorten usage of "o" io.write(i,"s go M",i:find"a"and("e"):rep(l)..o:rep(l).."w"or o:rep(l*2)) -- if it's a C"a"t concat "s go M" then repeat --> Cats/Cows go M -- "e" and then "o" l times and concat else --> Cats go Meo -- repeat "o" l*2 times and concat --> Cows go Moo -- concat "w" and output evrything --> Cats go Meow ``` Example outputs: ``` Caaat --> Caaats go Meeeooow Cat --> Cats go Meow Cow --> Cows go Moo ``` Edit: changed `if` `then` `else` to `and` `or`. removed ALL the non string space's. Also you cat try it here: [Execute Lua Online](http://goo.gl/QZDCh8) but I couldn't figure out how to use the terminal so I've put it in a function. Edit: changed usage of "o" and removed () from `:find`. credit goes to **Cyv** for finding those optimizations. Added "s" and changed `l=#i-3` to `l=#i-2` With input including "s" only 88 byte: ``` i=...l=#i-3o="o"io.write(i," go M",i:find"a"and("e"):rep(l)..o:rep(l).."w"or o:rep(l*2)) ``` [Answer] # PHP, ~~170~~ ~~164~~ ~~161~~ 157 bytes ``` preg_match("/(?i)c([ao]+)/",$argv[1],$e); $n=strlen($e[1]); $c=$e[1][0]; $a=($c=="a"?("ew"):("o")); echo "M".str_repeat($a[0],$n).str_repeat("o",$n).$a[1]."\n"; ``` Takes any capitalization whatsoever. `CaAaT`, `coOOOw`, whatever. *v2: don't really need [wt]$. also corrected char ct* *v3: char ct was all wrong, condensed $a and $e assignment* *v4: save 3 bytes on $af->$a* *v5: save 4 bytes by onelining it (not shown)* ]
[Question] [ [Quipus](https://en.wikipedia.org/wiki/Quipu) are an ancient device used by the Inca in the Precolumbian era to record numbers in a base ten positional system of knots on a cord, which works as follows: > > Each cluster of knots is a digit, and there are three main types of knots: simple overhand knots; "long knots", consisting of an overhand knot with one or more additional turns; and figure-eight knots. > > > * Powers of ten are shown by position along the string, and this position is aligned between successive strands. > * Digits in positions for 10 and higher powers are represented by clusters of simple knots (e.g., 40 is four simple knots in a row in the "tens" position). > * Digits in the "ones" position are represented by long knots (e.g., 4 is a knot with four turns). Because of the way the knots are tied, the digit 1 cannot be shown this way and is represented in this position by a figure-of-eight knot. > * Zero is represented by the absence of a knot in the appropriate position. > > > ## Details For this challenge, each strand of a quipu represents a **single number** (though, as the Wikipedia article states, you *can* represent many numbers on one strand, in this challenge, we shall not). **Knots** Each knot will be represented by a single ASCII character. * `.` represents a simple knot * `:` represents a one turn of a long knot * `8` represents a figure-eight knot * `|` represents the absence of a knot as well as a delimiter between the digits. **Constructing Quipus** Quipu are constructed following these rules. 1. Strands run top to bottom in descending order of position (as in, the units digit will be at the bottom end of a strand). Digits along a strand are separated by the character (`|`). 2. The power of 10 a digit represents is determined by its position along the strand in the same way a digit's power of 10 would be calculated using its index in a number with our number system. That is, `24` with a `2` in the tens place and a `4` in the units place, will be represented by two knots, a delimiter (`|`), then four knots. 3. Digits in the same position are aligned towards the bottom of the strand. If one digit in a position will have less knots than other digits of other numbers in the same position, the absence of those knots is represented by (`|`). 4. Consecutive simple knots (`.`) represent a value in their position. 5. Every digit is represented by at least 1 character. When a digits value is 0 for all numbers in a quipu, it is represented by the absence of a knot (`|`). 6. The units place is treated specially. A one in the units place is represented by a figure-eight knot (`8`). A value of two or more in the units place is represented by consecutive long knots (`:`). 7. When the units digit is 0 for all numbers in a quipu the absence of a knot is not printed but, the trailing delimiter for the tens digit is preserved. 8. There is no delimiter following the units digit. ## Rules * Input will consist of a non-empty list of non-negative integers that may be received through any of the [default input methods](http://meta.codegolf.stackexchange.com/q/2447/31441). You may assume that these integers are all less than or equal to `2147483647` or `2^31-1`. While the test cases are space-delimited, your input format can separate inputs in any way that is convenient for your language, whether that be comma-separated, newline-separated, in an array, and so on. * Output consists of a single Quipu constructed according to the rules described above. Output may be given through any of the [default output methods](http://meta.codegolf.stackexchange.com/q/2447/31441). * Your code should be a program or a function, though it does not need to be a named function. * Knots take some time to tie so to save time, your code as short as possible. As always, if the problem is unclear, please let me know. Good luck and good golfing! ## Examples Input: ``` 5 3 1 0 ``` Output: ``` :||| :||| ::|| ::|| ::8| ``` Input: ``` 50 30 10 0 ``` Output: ``` .||| .||| ..|| ..|| ...| |||| ``` Input: ``` 330 ``` Output: ``` . . . | . . . | ``` Input: ``` 204 1 ``` Output: ``` .| .| || || || :| :| :| :8 ``` Input: ``` 201 0 100 222 ``` Output: ``` .||. .|.. |||| |||. |||. |||| |||: 8||: ``` Input: ``` 1073741823 2147483647 ``` Output: ``` |. .. || |. || .| .| .| .. .. .. .. || |. |. |. |. .. .. .. || .| .| .| .. .. .. .. || |. |. |. |. .. .. .. .. || |. |. .. || .| .| .. .. .. .. .. .. || |. |. .. .. || |: |: |: |: :: :: :: ``` Input: ``` 0 ``` Output: ``` | ``` [Longer test cases](https://gist.github.com/anonymous/eb36d73023e7d8dcc53a) # Further Reading * [Ancientscripts: Quipu](http://www.ancientscripts.com/quipu.html) * [The Quipu, Pre-Inca Data Structure](http://agutie.homestead.com/files/quipu_b.htm) [Answer] # [Unreadable](https://esolangs.org/wiki/Unreadable), ~~3183~~ 3001 bytes This was a fun challenge to work on, on and off, in between Christmas celebrations. Thank you for posting! Golfing this was interesting because the specification is full of exceptions and special cases, which required lots of if conditions. Also, while I didn’t need to convert to and from decimal this time, I *did* need a “max” function of sorts to determine the largest number of digits in each number and the largest value of the digits in each place. **The first version of this was 4844 bytes,** just to give you an idea of how much I golfed this. The program expects the input as a *comma-separated* list of integers. No spaces or newlines. Using those will produce undefined behavior. > > '""""""'""'""'""'""'""'"""'""""""'"""'""'""'""'""'""'""'""'""'""'""'""""""'""'""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""""""""'"""'""'""'""'""'""'""""""'""'"""'""'""'""'""'""'""'""'""'"""'"""""'""""""'"""'""""""""'"""""""'"""'""""""'""""""""'"""'""'""'"""""""'""""""""'"""'"""""'""'""""""'""'""'""'"""'""""""""""'""""'""""""'""'""'"""'"""""""'""'""'""'""'""'""'"""'"""""""""'""""""'""""""'""'"""'""'"""""""'""'"""'""'"""""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'""""""'""""""'"""'""""""""'"""""""'"""'"""'""""""'"""'""""""""'"""'""""""'""'""'"""'"""""'"""""""'"""""""'"""'""""""'"""'""""""""'"""""""'"""'"""""'""""""'"""'""'"""""""'"""'""""'""""""'""'""'""'"""'""""""""'"""'"""""'""""""""'""""""'"""""""'"""'""'"""""""'"""""""'"""'"""""""""'"""""""""'"""""""'"""""""'"""'"""'"""""""""'""'"""""""'"""'"""'""""""""'"""'""""'""""'""""""'""'"""'""'""'""'""'""'""'""'""'"""'"""""'"""""""'""""""'""'"""'""'"""""""'""'"""'""""'""""'"""""'""""""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'"""'"""""""'""""""'""'"""'""'"""""""'""'"""'"""'"""""'"""""""'""""""'""'"""'""""""""'"""""""'""'"""'"""""""""'""""""""'"""""""'""""""'""'""'""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'""'""'""'"""'"""""""""'""""""""'""""""""'"""""""'"""""""'"""'"""""""""'"""""""'""'""'""'"""'""""""'""'""'""'""'"""'"'"""""""""'""'"""""""'"""""""'""'"""'"""""""""'""'""'"""""""'"""""""'""'"""'""""'""""""'"""""""'""'"""'"""""""""'"""""""""'""'"""""""'"""'"""'"""""""""'""'""'"""""""'"""""""'"""'"""'"""""""""'""'""'""'"""""""'"""""""'""'"""'"""'""""""""'"""'""'"""""""'"""""""'""'"""'""""""""'""""""""'"""'"""""""'""""""""'"""'"""""""""'"""""""'"""""""'"""'"""""""""'""'"""""""'"""'"""""""'""'""'""'""'""'""'"""'""'""'"""""""'""'""'""'""'""'"""'"""""""'""""""""'"""'"""""""'""'""'""'""'""'"""'""""'"""""""""'"""""""""'""'"""""'"""""""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""""'"""""""'""'"""'""""""""'"""""""'"""""""'""'"""'"""'"""""""""'"""""""'""'""'""'""'""'"""""""'""'""'"""'"""'"""""""""'""'"""""""'"""'"""'""""""""'"""'""""""'"""""""'""'"""'""""""""'"""""""'"""""""'""'"""'"""'"""""'"""""""'""""""'""'""'"""'""'"""""""'""'""'"""'"""'""""'""""'"""""'""""""'"""""""'""'"""'""""""""'"""""""'"""""""'""'"""'""""""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'"""'"""""'"""""""'""""""'""'""'"""'""'"""""""'""'""'"""'""""""'"""""""'""'"""'""'"""""""'"""""""'""'"""'"""""""""'""'"""""""'"""'""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'""'"""'"""'"""'"""'"""""""""'"""""'"""""""'""""""'""'"""'""'"""""""'""'"""'"""""""'""'""'""'""'"""'"""'"""""""""'"""""""'""'""'""'"""'"'"""""""'""""""""'"""'"""'"""""""""'""""""""'""""""""'""""""""'"""""""'"""""""'"""'"""""""""'"""""""'""'""'""'"""'"'""'""'""'""'""'""'""'""'""'"""'"""'""""""'"""""""'"""'""""""""'""""""'""'""'""'"""'"""""'"""""""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""""'"""""""'"""'""""""""'"""""""'"""""""'"""'""" > > > ## Explanation I’m going to walk you through how the program works by showing you how it processes the specific input `202,100,1`. In the beginning, we construct a few values that we will need later — mostly the ASCII codes of the characters we will output. [![enter image description here](https://i.stack.imgur.com/WQ7p7.png)](https://i.stack.imgur.com/WQ7p7.png) As you can see, `'8'` and `'.'` are already available. `'|'`, however, is really 124, not 14. We use a while loop to add twice the temporary value in slot #1 onto it to get 124 (which is 14 + 55×2, because the while loop runs for 56−1 = 55 iterations). This saves some bytes because large integer literals like 124 are really long. In the following diagram, I show the location of every variable the program uses. [![enter image description here](https://i.stack.imgur.com/pGDGL.png)](https://i.stack.imgur.com/pGDGL.png) Next, we want to input all the characters and store them on the tape starting at cell #12 (*p* is the running pointer for this). At the same time, we want to know how long the longest number is (how many digits). To achieve this, we keep a running total *in unary* going leftwards starting at cell #−1 (we use *q* as the running pointer). After the first input number (`202`), the tape now looks like this: [![enter image description here](https://i.stack.imgur.com/cKNBv.png)](https://i.stack.imgur.com/cKNBv.png) You will have noticed that the numbers are off by 4. Well, when we first input them, they are their ASCII values, so they’re “off” by 48 and the comma is 44. For each character, we copy the 46 from `'.'` into *r* and then subtract it with a while loop (which subtracts 45) and then we add 1. We do that so that the comma (our separator) is 0, so we can use a conditional to recognize it. Also, you will have noticed that we leave cell #11 at 0. We need that to recognize the boundary of the first number. The next character will be a comma, so we store a 0 in #15, but of course this time we don’t advance *q*. Instead, we set *q* back to 0 and start “overwriting” the 1s we’ve already placed. After all the remaining characters are processed, we get this: [![enter image description here](https://i.stack.imgur.com/u9OYA.png)](https://i.stack.imgur.com/u9OYA.png) As you can see, the 1s written by *q* now indicate (in unary) the length of the longest number. We now use a while loop to move *q* to the very left, and then place another pointer there which I will call *r2*. The purpose of *r2* will become clear later. [![enter image description here](https://i.stack.imgur.com/YZS0y.png)](https://i.stack.imgur.com/YZS0y.png) At this point, let me clarify the terminology that I will use throughout this. * By **number**, I mean one of the input numbers that are separated by commas. In our example, they are 202, 100 and 1. * By **digit**, I mean a single digit in a specific one of the numbers. The first number has 3 digits. * By **place**, I mean the ones place, tens place, hundreds place, etc. So if I say “the digits in the current place”, and the current place is the ones place, those digits are 2, 0, and 1 in that order. Now back to our regular programming. The entire rest of the program is a big loop that moves *q* forward until it reaches cell #0. Each of the cells along the way represents a place, with the ones place on the far right, and *q* will start at the most significant. In our example, that is the hundreds place. We proceed by incrementing the cell *q* points at (that is, *\*q*). [![enter image description here](https://i.stack.imgur.com/nlQJc.png)](https://i.stack.imgur.com/nlQJc.png) We are now at “stage 2” for the hundreds place. In this stage, we will find out what the largest digit is among all the digits in the hundreds place. We use the same unary counting trick for this, except this time the pointer is called *r* and the pointer *r2* marks its starting position to which we need to reset it every time we move on to the next number. Let’s start with the first number. We begin by setting *p* to 11 (the hard-coded starting position of all the numbers). We then use a while loop to find the end of the number and set *p2* there to mark the position. At the same time, we also set *q2* to 0: [![enter image description here](https://i.stack.imgur.com/Lz8nD.png)](https://i.stack.imgur.com/Lz8nD.png) Don’t be distracted by the fact that *q2* is pointing into the vars. We don’t have a padding of a blank cell there because we can detect cell #0 simply because it’s number zero. Next, we go through the current number by decrementing *p* and *q2* together until *\*p* is zero. At each place, the value of *\*q2* tells us what we need to do. 1 means “do nothing”, so we keep going. Eventually we encounter the 2 in cell #−3. Every time *\*q2* is not equal to 1, *q2* is always equal to *q*. [![enter image description here](https://i.stack.imgur.com/9pnYV.png)](https://i.stack.imgur.com/9pnYV.png) As I already stated, stage 2 is “determine the largest digit in this place”. So we set *r* to *r2*, use a while loop to decrement *\*p* and move *r* leftwards and fill the tape with 1s, and then use another while loop to move *r* back to the right and increment *\*p* again to restore the value. Remember that every while loop runs for one fewer iteration than the value we use it on; because of this, the number of 1s written will be 3 more (rather than 4 more) than the digit value, and the final value stored back in *\*p* will be 2 more. Thus, this has effectively decremented *\*p* by 2. After that, we set *p* to the value of *p2* and then we do all that again. For the second time, set *q2* to 0, find the end of the number by moving *p* to the right, and then go through the digits of this number by decrementing *p* and *q2* together. Once again we will encounter the 2 in cell #−3 and write that many 1s left of *\*r*. In the case of the third number, we end up doing nothing because it doesn’t have a hundreds place (so *q2* never reaches *q*), but that’s OK because that doesn’t affect the calculation of the maximum digit value. [![enter image description here](https://i.stack.imgur.com/BgM3D.png)](https://i.stack.imgur.com/BgM3D.png) We also set the cell *\*(r − 4)*, which I’ve marked with an unlabeled arrow here, to 1 (even though it’s already at 1). I’m not going to tell you why yet, but maybe you’ve already guessed? The next increment of *\*q* takes us to stage 3, which is “subtract the maximum digit from all digits in the current place”. As before, we reset *p* to 11 and *q2* to 0 and then go through all the numbers just like we did in the previous stage; except this time, *\*q* = 3 instead of 2. Every time *q2* meets *q* and *p* is in a hundreds place, we use a while loop to decrement *\*p* as many times as there are 1s in the block left of *\*r2* (5 in our example) by using *r* as a running pointer. We actually decrement it once more than that so that the largest digit ends up at −2, for a reason that will become clear later: [![enter image description here](https://i.stack.imgur.com/N6Gdu.png)](https://i.stack.imgur.com/N6Gdu.png) After we’ve processed all the numbers, we are now at the end of stage 3. Here we perform two singular things. * First, we *also* subtract the size of the *r*-block (plus 1) from *\*q*, but using the *r2* pointer, which leaves it on the left. *\*q* becomes negative this way. In our case, the *r*-block has five 1s, so *\*q* becomes −3. * Second, we set a variable *out* to a non-zero value to indicate that we are now entering the output stage. (Technically, the fact that *\*q* is negative already indicates the output stage, but this is too difficult to check for, hence the extra variable.) You now understand that we keep going through the numbers, find the current place (indicated by the non-1 value of *\*q*) within each number, and do something depending on the value of *\*q*. We see that *\*q* is first incremented to 2 (= calculate maximum digit value), then 3 (subtract maximum digit value from every digit in this place) and then we subtract from it to make it negative. From there, it will continue to go up until it reaches 1, thus restoring the value that means “do nothing”. At that point, we move on to the next place. Now, when *\*q* is negative, we’re outputting. *\*q* is at exactly the right value so that we will output the right number of rows of characters before it reaches 1; if the largest digit is 2, we need to output 3 rows. Let’s see what happens at each value of *\*q*: * ***\*q* = −2:** + For the first number, *\*p* is −2, which indicates that we need to output a `'.'` (dot) or a `':'` (colon). We decide which by looking at *q*: if it’s −1, we’re in the ones place, so output a `':'` (which we calculate as `'8'`+2), otherwise a `'.'`. + For the second number, *\*p* is −3. Anything that is not −2 means we output a `'|'` (pipe) and then increment the value. This way it will reach −2 in the right place and then we output `'.'`s/`':'`s for the rest of that digit. + In each case, we also set a variable *pd* to 0 *before* we process the number, and set *pd* (= “printed”) to a non-zero value to indicate that we have printed a character. + For the third number, no processing occurs because the third number does not have a hundreds place. In this case, *pd* will still be 0 after processing the number, indicating that we still need to output a `'|'` (but only if *out* is non-zero, because otherwise we’re still in stage 2 or 3). + After processing all numbers, if *out* is non-zero, output a newline. Note that we need the *out* variable so that we don’t output the newline in stage 2 or 3. * ***\*q* = −1:** Same as before, except that *\*p* is −2 for both the first two numbers, so both output a `'.'` (and the third outputs a `'|'` as before). * ***\*q* = 0:** When *\*q* is 0, this means “do nothing if we’re in the ones place, otherwise output a row of `'|'`s regardless of *\*p*”. This way we get the padding between the digits. Now we increment *q* to move on to the next place, the tens place, and increment *\*q* there. At the beginning of Stage 2, the tape looks like this: [![enter image description here](https://i.stack.imgur.com/XCcjx.png)](https://i.stack.imgur.com/XCcjx.png) Then we perform Stage 2 just as before. Remember this effectively subtracts 2 from every digit in this place and also leaves a unary number left of *\*r2* indicating the maximum digit. We leave the previous unary number alone and just keep extending the tape to the left; it would only cost unnecessary extra code to “clean up”. When we’re done and we increment *\*q*, at the start of Stage 3 the tape is now: [![enter image description here](https://i.stack.imgur.com/bdtD5.png)](https://i.stack.imgur.com/bdtD5.png) Actually, this is a lie. Remember earlier where I said we set *\*(r − 4)* to 1 and I didn’t tell you why? Now I’ll tell you why. It’s for cases like this one, where the largest digit is in fact 0, meaning *all* the digits in this place are 0. Setting *\*(r − 4)*, indicated by the unlabeled arrow above, to 1 extends the unary number by 1, but only in this special case. This way we pretend as if the largest digit was 1, which means we will output one extra row. After Stage 3 (subtract maximum digit from all digits in the current place), including the extra step that makes *\*q* negative, the tape looks like this. Last time the biggest digit was represented by −2 in the *\*p* block, but this time they’re all −3 because they’re all actually zeroes but we’re pretending as if the maximum digit was a 1. [![enter image description here](https://i.stack.imgur.com/f8JYS.png)](https://i.stack.imgur.com/f8JYS.png) Now let’s see what happens as *\*q* progresses towards 1: * When *\*q* = −1, the *\*p* values are all −3, which means we output `'|'`s and increment them. * When *\*q* = 0, we output `'|'` because that’s what we always do when *\*q* = 0, regardless of *\*p*. Thus, we get two rows of pipes. Finally, we move *\*q* to the one’s place. This one gets interesting because we need to output `':'`s if the actual digit is anything but 1, but an `'8'` if it’s 1. Let’s see how the program proceeds. First, we increment *\*q* to initiate Stage 2: [![enter image description here](https://i.stack.imgur.com/YYktx.png)](https://i.stack.imgur.com/YYktx.png) After Stage 2 (“calculate maximum digit value”), we’re left with this: [![enter image description here](https://i.stack.imgur.com/ObtMX.png)](https://i.stack.imgur.com/ObtMX.png) After Stage 3 (“subtract maximum digit value from all digits in current place”) the tape looks like this: [![enter image description here](https://i.stack.imgur.com/29VzO.png)](https://i.stack.imgur.com/29VzO.png) Now let’s go through each iteration of *\*q* in turn: * ***\*q* = −2:** + First number: already at −2, so output a `':'` (rather than a `'.'` because *q* = −1). + Second number: at −4, so output a `'|'` and increment. + Third number: at −3, so output a `'|'`. However, this time, instead of incrementing, a special case triggers. *Only* if we’re outputting the last place (*q* = −1), *and* we’re in the second-last row for that (*\*q* = −2), *and* the digit is actually a 1 (*\*p* = −3), *then* instead of incrementing it to −2, we set it to −1. In other words, we use −1 as a special value to indicate that in the next iteration, we will need to output `'8'` instead of `':'`. * ***\*q* = −1:** + First number: already at −2, so output a `':'`. + Second number: at −3, so output a `'|'`. The special condition does not trigger because *\*q* is no longer −2. Therefore, increment. + Third number: at −1, so output `'8'`. * ***\*q* = 0:** Ordinarily, we would output the padding row of `'|'`s here, but in the special case where we’re in the ones place (*q* = −1), we skip that. After this, *q* is incremented to 0 and the big while loop ends. Now you know how an input like `202,100,1` works. However, there’s one more special case that we still haven’t covered. You may remember that while we were processing the last place, when *\*p* was −3 we set it to −1 for the `1` (instead of incrementing it to −2) so that the next iteration would output an `'8'` instead. This only works because we have an iteration in which *\*p* is −3 and we make a decision as to whether to increment it or set it to −1. We *do not* have such an iteration if *all* of the digits in the ones place are 0 or 1. In such a case all the *\*p* values for the 1s would *start out* at −2; there is no opportunity to decide to set it to −1 *rather than to increment it from −3*. Because of this, there is another special-casing condition inside Stage 3 (“subtract maximum digit from every digit in the current place”). I claimed that after subtracting the maximum digit value from every digit (at which point the maximum digit is at −1), we just decrement it once more, but actually there’s a condition on that which goes as follows: If the digit we’re looking at is equal to the maximum digit in this place (*\*p* = −1), *and* this place is the ones place (*q* = −1), *and* the maximum digit is 1 (*\*(r + 5)* = 0, i.e. the unary block at the very left is only 5 cells long), *only then* we leave *\*p* at −1 to indicate that the only iteration of the output must output an `'8'`. In all other cases we decrement it once more. Done. Happy new year! * **Edit 1 (3183 → 3001):** Some Happy New Year golfing! I managed to get rid of the variables *p2* and *r2* entirely! *p* now races back and forth to keep finding the beginning and end of numbers, but it seems to be shorter in code. I tried to get rid of *q2* as well, but I couldn’t make the code shorter that way. I also found a few more places where I could apply typical Unreadable golfing tricks like re-using the last value of a while loop. To give you an example, instead of ``` while *(++p) { 1 } // just increment p until *p is 0; the 1 is a noop if (pd) { x } else { y } // where pd is a variable ``` I can save the `'""""` (do the first, then the second) and the `'"""` (constant 1) by writing it in a way that is kind of like ``` if (while *(++p) { pd }) { x } else { y } ``` Of course, this only works if I know that the while loop will run for at least one iteration, but if it does, its return value is *pd* so I can use that as the condition for the if. [Answer] # Javascript (ES6) ~~750~~ ~~744~~ ~~690~~ ~~604~~ ~~498~~ ~~346~~ ~~245~~ 234 bytes I'm new to PPCG and thought I might give this one a try thinking it was rather simple. Boy was I wrong!! I've been working on it for a while and I have **a lot of golfing** to do... Suggestions are encouraged! - although making sense of this won't be an easy task. Outputs ropes when the input is an array of numbers (eg: `[204, 1]` ). ``` a=>(o=m=s="",l=a.map(n=>(s+="|",l=(n+"").length)>m?m=l:l),h=[],a=a.map((n,i)=>[..."0".repeat(m-l[i])+n].map((d,j)=>d<h[j]?d:h[j]=d)),h.map((n,i)=>{i?o+=s+` `:0;for(j=n;j--;o+=` `)a.map(d=>o+="|.:8"[d[i]-j<1?0:i<m-1?1:d[i]-1?2:3])}),o) ``` ## Explanation ``` a=>( o=m=s="", // m = max number of digits in a number, s = separator string l=a.map(n=>( // l = lengths of each number s+="|", // set the separator string l=(n+"").length // convert each number to a string )>m?m=l:l // get max length ), h=[], a=a.map((n,i)=> [..."0".repeat(m-l[i])+n] // add leading 0s to make all same length .map((d,j)=>d<h[j]?d:h[j]=d) // set each digit of h to max ), h.map((n,i)=>{ i?o+=s+` `:0; for(j=n;j--;o+=` `) a.map(d=> o+= "|.:8"[ d[i]-j<1?0 :i<m-1?1 :d[i]-1?2: 3 ] ) }), o ) ``` ## Example **Input:** Array of numbers: `[4,8,15,16,23,42]` **Output:** ``` |||||. |||||. ||||.. ||.... |||||| |:|||| |:|||| |:|:|| |:::|| ::::|| :::::| :::::: :::::: ``` [Answer] # Python 3, ~~624~~ ~~598~~ ~~595~~ ~~574~~ ~~561~~ ~~535~~ ~~532~~ ~~527~~ ~~525~~ ~~426~~ ~~345~~ ~~328~~ ~~324~~ ~~294~~ ~~288~~ ~~286~~ ~~283~~ ~~280~~ ~~267~~ ~~265~~ ~~255~~ ~~251~~ ~~245~~ ~~238~~ ~~235~~ ~~234~~ ~~230~~ ~~228~~ ~~236~~ 244 bytes ``` z=input().split();v=max(map(len,z));d=''.join(i.zfill(v)for i in z);x=['']*len(z) for k,c in enumerate(d):j=k%v;m=int(max(d[j::v]));c=int(c);x[k//v]+="|"*(m-c+(2>v)+(j>0)+0**(m+(j>v-2)))+":8."[(c<2)|-(j<v-1)]*c for r in zip(*x):print(*r,sep='') ``` [Try it online!](https://tio.run/##HY/daoQwEIXv@xRBKM7Enx21haKmLyJeSHTZ@BOD6wYr@@42ejXMOcN3zpi/9THr7Dh2obR5rYDx04zKzcKKqdlgagyMnQ53xKIVvh/3s9Kg4v2uxhEs3ueFKaY027HYROX7NXfnsOPH6QyhPL1Ov6ZuadYOWsx7MXzaYnJ5K5wJbdXnua0dX16adKBquN1sHQjv7XGYIhlA/0sYEHdbAGlpkTvFRikiBl7@E3sVyDLFdwR9aaMEay6vAstVTRngG@ZmOfl8CZ@dca/gcXxTQiyjlFhKGbGEvojRPw) Well, since this question needed an answer, I have provided one here, where the input should be a space-separated string of numbers, such as `"204 1"`. Boy, is it a long one. Any golfing suggestions (or better answers) are welcome. **Edit:** Bytes saved by mixing tabs and spaces. **Edit:** I saved a *lot* of bytes by changing how I obtained the digits of a number (make a list from the zero-padded string of the number, then in the body of the code, transpose to get hundreds digits, ten digits, etc.) **Edit:** And I saved some more by incorporating that last `:8` loop into the main quipu loop. ~~Now if only I could figure out why `b=d[j*v+i]==m(d[i::v])` won't work.~~ Figured it out and the solution takes too many bytes. (Also the byte count dropped because somehow the tabs turned back into four spaces. It was probably the code block formatting on this site) **Edit:** I reorganized how made the quipus. Now it creates one strand at a time, then transposes for printing. **Edit:** Turned my answer back into a Python 3 program to save some more bytes. **Edit:** I found a bug in my code that made it so that it was not printing zeroes in the middle of numbers correctly (see test case `204 1` above). In fixing this, I managed to golf it :) **Edit:** I changed the printing to save 10 bytes. And I put all of the old byte counts back, just because. **Edit:** Golfed the assignment of `v` using `map` for four bytes. Credit to [CarpetPython](https://codegolf.stackexchange.com/users/31785/carpetpython), as I got the idea from their answer [here](https://codegolf.stackexchange.com/a/69615/47581). **Edit:** Turned the middle "for loop inside a for loop", into just one for loop for six bytes. **Edit:** Now using `enumerate`. No longer using `l=len(z)`. Turned the ternary `if-else` into a list ternary. See below for details. **Edit:** Sp3000 suggested an edit to `print` and an edit to the ternary condition that saved a byte each. **Edit:** +6 bytes fixing a bug where the code did not follow rule 7. +8 more bytes in continuing to fix this bug. O bytes from more bug fixes. **Ungolfed:** ``` s = input() z = s.split() v = max(map(len, z)) # the amount of digits of the largest number d = ''.join(i.zfill(v) for i in z) # pad zeroes until every number is the same length # then join the numbers into one string x = ['']*len(z) # a list of strings for the output, one for each number for k,c in enumerate(d): # for every digit in every number i,j = divmod(k, v) # i is the index of the number we're on # j is the index of the digit of the number we're on m = int(max(d[j::v])) # the largest of all the digits in the j-th place c = int(c) # the digit in j-th place of the i-th number x[i] += "|"*(m-c+(j>0)+0**(m+(2>v)*(j>v-2))) # pad | to size m-c, until the knots are correctly spaced # add a | if all inputs are single-digit numbers # add a | if j>0, if it's not at the start, as delimiters # add a | if the maximum is 0 and it's *NOT* the ones digit x[i] += ":8."[(c<2)|-(j<v-1)] * c # this is essentially the following code # if j<v-1: # x[i] += "."*c # . knots if not in the units place # else: # if c == 1: # x[i] += "8"*c # 8 knots for ones in the units place # else: # x[i] += ":"*c # : knots for something else is in the units place for r in zip(*x): # transpose so all the rows (the quipu strings) now hang down print(*r, sep='') # join the strings together at each knot # and print each on a separate line ``` [Answer] # C, 238 235 bytes Relying heavily on the C preprocessor to make the code as short as possible. As a side effect, also makes it pretty much unreadable. ``` #define l strlen(a[i]) #define d l<k||a[i][l-k]-48 #define m(e) for(i=1;a[i];e<=r?i++:r++); #define p(e) {m(!putchar(e?'|':k>1?46:d<2?56:58))puts("");} k,r;main(int i,char**a){m(l)for(k=r,r=1;k;r=k>1){m(d)for(;r;r--)p(d<r)if(--k)p(1)}} ``` On Ubuntu 14.04, you can compile the code with a straightforward `gcc quipu.c` (please ignore the warnings). An example of running the executable: ``` $ ./a.out 1 2 3 2 1 ||:|| |:::| 8:::8 ``` Tested against all OP's test cases. Ungolfed source code: ``` // Standard library; leaving out the includes still gives executable code despite the warnings. #include <stdio.h> #include <string.h> // 4 preprocessor macros. // Note: some of these actually make use of the fact that parentheses have been left out // l: length of argument i #define l strlen(a[i]) // d: shorthand for a digit #define d l<k || a[i][l-k]-'0' // m: loop across all arguments; calculates r as the maximum of expression e #define m(e) for (i=1; a[i]; e<=r ? i++ : r++); // p: prints one line of output // note: intentionally does not use the r++ code branch of m; // putchar always returns a non-zero number here, so !putchar is zero, // which is always <=r (because r is never negative) // note: the semicolon after m(...) is redundant; // the definition of m already contains a semicolon // note: puts("") outputs a newline #define p(e) { m(!putchar(e ? '|' : k > 1 ? '.' : d < 2 ? '8' : ':')); puts(""); } // k: knot position; 1 for units, 2 for tens, 3 for hundreds... int k; // r: input and output value for m // note: the first time we call m, we need r to be zero; // by defining it outside main, it is automatically initialized as such int r; // function main // note: parameter i (normally named argc by convention) is not needed // (the last element of argv is known; it is followed by a NULL pointer) // but we cannot leave it out (otherwise we cannot access argv) // so it serves as a local variable (to loop through arguments; see m) // note: parameter a (normally named argv by convention) // is the array of arguments (starting from index 1) int main(int i, char **a) { // Determine the longest argument; store its length in r. // This is the number of knot positions to consider. m(l) // Iterate k through the knot positions from top to bottom. // Note: k > 0 has been abbreviated to k. // Note: for each iteration, we also initialize r with either 0 or 1. // 0 = suppress printing when all knots are zero // 1 = always print, even when all knots are zero for (k = r, r = 1; k > 0; r = k > 1) { // Determine the highest digit at this knot position. // Note: due to the absence of parentheses, d mixes up with <=r into: // (l < k) || (a[i][l-k]-'0' <= r) m(d) // Count the digits down. for (; r; r--) { // Print a single line of output. // When d (the digit in the current strand) is less than the counter, // then print a '|', otherwise print a knot. p(d < r) } // Decrement k (go to next knot position). // If this was not the last iteration... if (--k > 0) { // Print separator line. p(1) } } // Return exit code zero; redundant. return 0; } ``` [Answer] # Mathematica ~~436 453 357 352~~ 347 bytes ``` t=Transpose;y=ConstantArray;a=Table; g@j_:=(s=t[PadLeft[#,Max[Length/@i]]&/@(i=IntegerDigits@#)]&;p_~u~o_:=(m=Max@p;c=If[o==-2,":","."];w=If[o==-2,"8","."];p//.{0->a["|",Max@{1,m}],1->Join[a["|",{m-1}],{w}],n_/;MemberQ[2~Range~9,n]:>Join[y["|",m-n ],c~y~n]});t[Join@@@t@Join[u[#,0]&/@Most@#,u[#,-2]&/@{#[[-1]]}]]&[Riffle[(s@j),{a[0,Length@j]}]]//Grid) ``` The above * Breaks up each integer into a list of digits, using `IntegerDigits`; pads each number with zeros to the left (to ensure equal spacing); each input number, now decomposed into digits, corresponds to a row of an array; each column represents a place value. Array is transposed. * Replaces digits with a list of knots with padding. A slightly different pattern-matching routine is used for the units. --- **Example** ``` g[Range[0, 50]] ``` [![fifty](https://i.stack.imgur.com/0OSPi.png)](https://i.stack.imgur.com/0OSPi.png) [Answer] # Pyth, 64 bytes ``` =QjRTQjCmj\|+:R"[8:]"\.PdedCmm+*\|-h.MZdk*?tk\:\8kdC.[L0h.MZlMQQ ``` [Try it online!](http://pyth.herokuapp.com/?code=%3DQjRTQjCmj%5C%7C%2B%3AR%22%5B8%3A%5D%22%5C.PdedCmm%2B%2A%5C%7C-h.MZdk%2A%3Ftk%5C%3A%5C8kdC.%5BL0h.MZlMQQ&input=1%2C12%2C21%2C32%2C41%2C132%2C221%2C312%2C401%2C312%2C221%2C132%2C41%2C32%2C21%2C12%2C1&debug=0) ## How it works ``` =QjRTQ Converts each number in input to decimal (as a list) 123 becomes [1,2,3] ---- jCmj\|+:R"[8:]"\.PdedCmm+*\|-h.MZdk*?tk\:\8kdC.[L0h.MZlMQQ .[L0 Q 0-leftpad each # h.MZlMQ (max length) times C transpose mm d for each digit: + [convert to] sum of *\| "|" repeated - the difference of h.MZd maximum digit in same row k and itself.. that many times *?tk\:\8 and (digit > 1 then ":" or "8") repeated k itself many times the list: [11,23,52] ->[[1,1],[2,3],[5,2]] ->[[1,2,5],[1,3,2]] ->[["||||8","|||::",":::::"],["||8",":::","|::"]] C transpose ->[["||||8","||8"],["|||::",":::"],[":::::","|::"]] m for each number + [convert to] sum of Pd every element but the last :R"[8:]"\. with "8" and ":" replaced by "." ed and the last element j\| joined with "|" C transpose j join (with newlines) ``` [Answer] # R - 446 444 I see there is no R solution yet, so here is one. The function takes a vector with integers. ``` function(x){r=nchar(max(x));c=length(x);m=matrix(0,r,c);for(i in 1:c){t=as.numeric(strsplit(as.character(x[i]),"")[[1]]);m[(r+1-length(t)):r,i]=t};Q=c();for(i in 1:r){d=m[i,];z=ifelse(max(d)>0,max(d),1);q=matrix("|",z,c);for(j in 1:c){v=m[i,j];if(i==r){if(v==1)q[z,j]=8;if(v>1)q[(z-v+1):z,j]=rep(":",v)};if(i<r){if(v>0)q[(z-v+1):z,j]=rep(".",v)}};if(i!=1&sum(d)>0)q=rbind(rep("|",c),q);Q=rbind(Q,q)};for(i in 1:nrow(Q))cat(Q[i,],sep="",fill=T)} ``` ## Ungolfed ``` # Some test data test <- c(201, 0, 100, 222, 53) # Define function quipu <- function (x) { # Create matrix with a row for each digit and a column for each number r=nchar(max(x));c=length(x);m <- matrix(0,r,c) for(i in 1:c) { t=as.numeric(strsplit(as.character(x[i]),"")[[1]]) m[(r+1-length(t)):r,i]=t } # Loop through each row (digit) starting at the top of the quipu Q=c() # Empty matrix to store quipu for(i in 1:r){ d=m[i,] z=ifelse(max(d)>0,max(d),1) q=matrix("|",z,c) # Loop through each column (number in the vector) starting at the leftmost quipu for(j in 1:c){ # The digit v=m[i,j] # If it is the last segment of the quipu if(i==r){ if(v==1){q[z,j]=8} # If unit digit =1 if(v>1){q[(z-v+1):z,j]=rep(":",v)} # If unit digit >1 } # If it is not the last segment of the quipu if(i<r){ if(v>0){q[(z-v+1):z,j]=rep(".",v)} # If non-unit digit >0 } } # Add segment to Q if(i!=1 & sum(d)>0){q=rbind(rep("|",c),q)} Q=rbind(Q,q) } # Print quipu for(i in 1:nrow(Q)) {cat(Q[i,], sep="", fill=T)} } # Test quipu(test) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~160~~ ~~137~~ ~~132~~ ~~128~~ ~~123~~ ~~117~~ ~~126~~ ~~119~~ 116 bytes I sort of wrote this in a frenzy while unable to sleep tonight, so please forgive me if I skip the explanation, and miss any bugs or golfing opportunities. I'll take another look at this after I've gotten some sleep. **Edit:** ~~Turns out this doesn't for an input of just `0`. Will fix soonest.~~ -23 bytes from bug fixing! -5 bytes from removing no-longer-used variables. -4 bytes from using parts of the approach used in [Leaky Nun's excellent Pyth answer](https://codegolf.stackexchange.com/a/79589/47581) (Sidenote: this answer is now exactly twice as long as that answer :D). -5 bytes from rearranging the result matrix mid-computation. -6 bytes from slimming down the generation of the result matrix even further. +9 bytes bug fixing. 0 bytes from more bug fixing. -7 bytes from rearranging how to handle the ones digit special case. -3 bytes from continued rearranging. ``` {⎕IO←0⋄m←⊖↓10⊥⍣¯1⊢1,⍵⋄1↓⊃⍪/⌽{w←1↓⊃m[⍵]⋄M+←1+0*((1≠≢m)∧⍵=0)+M←⌈/w⋄⊃,/⍵{M 1⍴((M-⍵)/'|'),⍵/'.'(':8'[1=⍵])[0=⍺]}¨w}¨⍳≢m} ``` [Try it online!](https://tio.run/##ZY@/SgNBEMb7PMV2e@cl3szexjuEVDamOARjF1IE5GxyaBckpoocyZkLimgtEVFsUqiNYJNHmRc5Z9TmYrF/5pvf981u/2zQOD7vD05PynJEi7v2AWXXQFeXKZ@U31N2i0D5ExWP6xVSvsQ6FR/cR@5QPqHi1af512jI@J@UdpnoMRJ7Inqw5ThIsweaLVOXps/cbYHrxTJgPvWHTLKr7rM@ihVS8e44cYMr19cX2pV5vt7Wjt6NdBdbEu52gc/P3nj9MuRFxZuEj8tEMovF7z/yyXoVUHbDVedwj/ej/XanTBTU@M6g1rVENVWgjMKqiBUCVADKgELYoFQksrEKm6ppqx4xiUts/3ymyqLAkgSB4HaDN2BlVlXiF/8kG1MJQwiD0GJk@FdoQxsFOzb8Bg "APL (Dyalog Unicode) – Try It Online") **Explanation** ``` quipu←{ ⎕IO←0 ⍝ Set to 0-indexing nums ← 1,⍵ ⍝ Append a 1 so that when converting in the next line, ⍝ we always get a matrix, not a vector digit_list ← ⊖ ↓ 10⊥⍣¯1⊢ nums ⍝ All the digits in each digit place, reversed ⍝ For each digit in each digit place, create knots 1↓⊃⍪/⌽{ ⍝ After generating knots, these instructions clean up the result q ← ⍵ w ← 1↓ ⊃ digit_list[⍵] ⍝ 1↓ drops the 1 we appended before M +← 1+ 0* ((1 = ≢digit_list) ∧ (⍵ ≠ 0)) + M ← ⌈/w ⍝ M is the number of knot spaces (including delimiters) needed ⊃,/{ ⍝ ,/ concatenates the knots padding ← ((M-⍵) 1)⍴'|' knots ← ⍵ / ('.' (':8'[1=⍵]))[q=0] (M 1) ⍴ knots ⍪ padding ⍝ Turns the knots into a column vector ⍝ of shape M by 1 }¨w }¨⍳≢digit_list } ``` ]