text
stringlengths
180
608k
[Question] [ *This is the robber's thread of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. You can view the cop's thread [here](https://codegolf.stackexchange.com/questions/207558)* A pretty common beginner style question is to print some string, but, there's a catch!, you need to do it without using any of the characters in the string itself! For this challenge we will find out who is the best at printing X without X. There are two threads to this, a cop's thread and a robber's thread. In the cop's thread users will choose a language (which we will call Y) and a string (which we will call X) and write a program in language Y which takes no input and outputs X without using any of the characters in X. The cop will then post both X and Y without revealing the program they have written. Robbers will be select cop answers and write programs in language Y which take no input and output X. They will post these "cracks" as answers in this thread. A crack need only work not be the intended solution. Once a cop's answer is one week old, so long as it has not been cracked, the cop may reveal their program and mark it as "safe". Safe answers can no longer be cracked Robbers will be scored by the total number of successful cracks with more cracks being better. [Answer] # [Python 3](https://docs.python.org/3/), cracks [@nthistle's answer](https://codegolf.stackexchange.com/a/207563/36398) ``` 𝓹𝓻𝓲𝓷𝓽(𝓬𝓱𝓻(97)+𝓬𝓱𝓻(98)+𝓬𝓱𝓻(99)+𝓬𝓱𝓻(100)+𝓬𝓱𝓻(101)+𝓬𝓱𝓻(102)+𝓬𝓱𝓻(103)+𝓬𝓱𝓻(104)+𝓬𝓱𝓻(105)+𝓬𝓱𝓻(106)+𝓬𝓱𝓻(107)+𝓬𝓱𝓻(108)+𝓬𝓱𝓻(109)+𝓬𝓱𝓻(110)+𝓬𝓱𝓻(111)+𝓬𝓱𝓻(112)+𝓬𝓱𝓻(113)+𝓬𝓱𝓻(114)+𝓬𝓱𝓻(115)+𝓬𝓱𝓻(116)+𝓬𝓱𝓻(117)+𝓬𝓱𝓻(118)+𝓬𝓱𝓻(119)+𝓬𝓱𝓻(120)+𝓬𝓱𝓻(121)+𝓬𝓱𝓻(122)+𝓬𝓱𝓻(65)+𝓬𝓱𝓻(66)+𝓬𝓱𝓻(67)+𝓬𝓱𝓻(68)+𝓬𝓱𝓻(69)+𝓬𝓱𝓻(70)+𝓬𝓱𝓻(71)+𝓬𝓱𝓻(72)+𝓬𝓱𝓻(73)+𝓬𝓱𝓻(74)+𝓬𝓱𝓻(75)+𝓬𝓱𝓻(76)+𝓬𝓱𝓻(77)+𝓬𝓱𝓻(78)+𝓬𝓱𝓻(79)+𝓬𝓱𝓻(80)+𝓬𝓱𝓻(81)+𝓬𝓱𝓻(82)+𝓬𝓱𝓻(83)+𝓬𝓱𝓻(84)+𝓬𝓱𝓻(85)+𝓬𝓱𝓻(86)+𝓬𝓱𝓻(87)+𝓬𝓱𝓻(88)+𝓬𝓱𝓻(89)+𝓬𝓱𝓻(90)+𝓬𝓱𝓻(33)+𝓬𝓱𝓻(34)+𝓬𝓱𝓻(35)+𝓬𝓱𝓻(36)+𝓬𝓱𝓻(37)+𝓬𝓱𝓻(38)+𝓬𝓱𝓻(39)+𝓬𝓱𝓻(42)+𝓬𝓱𝓻(44)+𝓬𝓱𝓻(46)+𝓬𝓱𝓻(47)+𝓬𝓱𝓻(58)+𝓬𝓱𝓻(59)+𝓬𝓱𝓻(60)+𝓬𝓱𝓻(61)+𝓬𝓱𝓻(62)+𝓬𝓱𝓻(63)+𝓬𝓱𝓻(64)+𝓬𝓱𝓻(91)+𝓬𝓱𝓻(93)+𝓬𝓱𝓻(94)+𝓬𝓱𝓻(95)+𝓬𝓱𝓻(96)+𝓬𝓱𝓻(123)+𝓬𝓱𝓻(124)+𝓬𝓱𝓻(125)+𝓬𝓱𝓻(126)) ``` [Try it online!](https://tio.run/##ZdMxcsJADIXh6@ChQau1pL0RFaRIk3Okzg3SJA3DMNyJG5il5H@FXDzPWp9l6@Pr83g@@bY9fr6vs26z/mddZt138/I76@91Yzdy2b8HxWAgsMNBEpOkSeKSdElWSUKSlKQkEbOJ2cRsYjYxm5hNzCZmE7OJ2cTcxNzE3GgOcoKaICZoCVKSkiQk6UiOLjm5pDQpTUqT0qS0KC1Ki9KitCgtSovSorQoLUoHpU6H0@F0OB1Oh9PhdHTOo7NtZ5fOLiu7rOwSfNvgdwn5kzmPIGzwGYNHhhzhCIcsa5Olb7L0TZa@xbJs2xM "Python 3 – Try It Online") [Answer] # [Python 3.7](https://docs.python.org/3/), 128 bytes, cracks [jez's answer](https://codegolf.stackexchange.com/a/207661/46076) ``` import sys class A:__class_getitem__=chr class B:__class_getitem__=ord class C:__class_getitem__=sys.stdout.write C[A[B["'"]+1]] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4spgrOSexuFjB0So@HsyKT08tySxJzY2Pt03OKILKOmGRzS9Kgco6Y5EFmqxXXJKSX1qiV14EFONyjnaMdopWUleK1TaMjf3/P5ELCAE "Python 3 – Try It Online") [Answer] # Ruby, cracks [@histocrat's answer](https://codegolf.stackexchange.com/a/207577/81278) ``` send("ev"+("%x"%(5+5))+"l",send("ev"+("%x"%(5+5))+"l",("%d"%(4-3))+("%d"%(4-3))+"2"+("%f"%2)[4-3]+"chr")+"uts \""+send("ev"+("%x"%(5+5))+"l",("%d"%(4-3))+("%d"%(4-3))+"2"+("%f"%2)[4-3]+"chr")+send("ev"+("%x"%(5+5))+"l","60"+("%f"%2)[4-3]+"chr")+("%f"%2)[4-3]+send("ev"+("%x"%(5+5))+"l","36"+("%f"%2)[4-3]+"chr")+("%x"%(5+5))+("%d"%(4-3))+"\"") ``` [Try it online!](https://tio.run/##KypNqvz/vzg1L0VDKbVMSVtDSbVCSVXDVNtUU1NbKUdJB48UUCAFKGCiawwUQOEoGYGVpympGmlGA4VitZWSM4qUgBKlJcUKMUpK2tQ1Fo9pSmYGODShCuIzwtgMtxEIpahOBXpS8/9/AA "Ruby – Try It Online") I'm gonna be honest – about an hour ago, I didn't know Ruby. But I didn't let that stop me! **Explanation:** In general, my approach to these is to get some kind of `eval` construct, and then convert numbers to characters and combine to get any payload (as long as numbers and + allowed, and you can do the former with the language, this works). The immediate problems with this one are that we don't have access to `p`, which is necessary for any(?) kind of printing in ruby (`p`, `puts`, `pp`, ...), we can't use `a`, so `eval` is out, and we can't use `.`, so it's difficult to call any methods or get attributes. For that matter, we're going to have difficulty converting numbers => characters without `Integer.chr` (I found some hacky ways to get it to call without using `.`, including overriding `*` for Integers, but not without using `a` in `class`). In my quest to find reflection tricks that would be useful, I stumbled across the `send` method, although it took a while before I realized you didn't have to invoke it on an object. Now we're at `send("eval","[payload]")`, but still need a way to construct strings. I banged my head on this for a while before I realized that for the `a` restriction at least, I could simply use a format string with hex. `("%x" % 10)` gets us `a`, although we need to change `10` to `5+5` in order to bypass the `1` restriction. Great, now we have `eval`. Unfortunately, `p` is not a hex character. Not a problem, though, since we have `eval`! We can recover `"."` from `("%f"%1)[1]` (changing to `("%f"%2)[4-3]` to bypass `1`), so now we can just send `"112.chr"` to `eval`, and we're golden. From here it's just combining these primitives to get a payload that translates to the string `puts "p<.$a1"`, and we're done! **Edit:** I just realized that I could've also just used `"%c" % ...` to get characters instead of the clunky trick I have for invoking `.chr`. For completeness, here's a much shorter version that uses this: ``` send("ev"+("%c"%97)+"l",("%c"%(56+56))+"uts \""+("%c"%(56+56))+("%c"%60)+("%f"%2)[4-3]+("%c"%36)+("%c"%97)+("%d"%(4-3))+"\"") ``` [Answer] # Befunge-93 (FBBI), cracks [@Ethan Chapman's (new) answer](https://codegolf.stackexchange.com/a/207635/81278) ``` >g::g- :::+:+:+:+:++\::+:+:+:+:+:+\::+::+::+::+::+::++++++\::+::+:+:+:++\: v v +::+:+::+::+::\+++++::+:+::+::+:::\+++::+::+:+:+::\++++::+::+:+:+:: < > +++\:::+:+::+:+::++++\::+:+::+:+::+++\:::+::+:+:+::++++\::+::+:+:+: v v \+++:+::+::+:+::\+++:+::+::+:+::\++::+:+:+:+::\+++::+:+:+:+:::\+++: < > ::+\::+::+:++\::+:+:+:+:+:+\::+\::+:+::++\$pp v v < > v v < v < X >:| Y = ``` [Try it online!](https://tio.run/##tVC7DsMgDNz5Cg/dEFOnWg3f0UpMSAnqEmVppv47RQZjErGVni3Qnfw48PPyXsNsblezeP@K0QbEYAARNYd2DcHMjklgnXtgVzsQilzSUfVBIq1pzzWtAHdlyzDaxN1luzsJuYKbz@7EGe2VRdjh8vbqstDMxRnK3/T@rHrU7rJt0Ed1NgLV2QgMdgZpXDrhoSx@0v1Myt/jJ0wxfgE "Befunge-93 (FBBI) – Try It Online") **A Brief History/Explanation:** I originally started writing this answer when I saw Ethan Chapman's [first Befunge-93 answer](https://codegolf.stackexchange.com/a/207626/81278), but progress was hampered by the fact that I didn't know Befunge. I took a lunch break and by the time I came back, it had already been cracked (in a different way)! My original approach was simply to use `!` to get 1 on the stack (it implicitly reads a 0 off the stack), and then just duplicate (`:`) and add (`+`) that to itself to create whatever numbers I needed. Then, you can take advantage of Befunge's ability to modify the source code to write a `,` into some specific location and then print off the stack as ASCII characters. It was easy enough to write the following snippet that prints off the entire stack, which also only has a single `,` (which means it only requires one self-write). ``` v < (Whee!) , Prints top of stack as ASCII character >:| Duplicates top of stack, then pops, going down if zero, up otherwise @ Terminates ``` Fortunately, this general approach didn't change too much between the two answers. The main difference is that I can no longer use `!` to get a 1 on top of the stack from the empty stack (I also can't use `@` to terminate, but that's not an issue, since we can just use another self-write for that). Some simple process of elimination reveals that `g` (pop `y`, `x`, then push value of ASCII character at location *(x,y)*) is just about the only way to get non-zero values onto the stack now. Since the stack is implicitly zero, the first `g` we hit with an empty stack will simply push the value of character at (0,0). However, unlike some more convenient languages (*cough*, *cough*, [05AB1E](https://github.com/Adriandmen/05AB1E)), we don't have builtin operators to divide by 2 that we might use to reduce this value down to 1. Thus, we need to use our ability to read *again*. The simplest way to do this is have the value at (0,0) be ASCII value *v*, and then put *v-1* at (v,v). At this point, I ran into some problems with a lot of the Befunge-93 interpreters on TIO, since by default they only support a 25x80 program, and will complain about reads outside of this range. I can start with a space, which has ASCII value 32, but that's still out of bounds. Fortunately, the FBBI version works just fine, although I can't start with a space because for some reason it doesn't terminate unless you begin with a direction(?). In any case, I can recover the magic `1` by starting with `>` (value 62) at (0,0), then using `g::` to push 62 onto the stack and duplicate it twice, then using `g` to read (62,62), where I have `=` (value 61), and then finally subtract the top two elements of the stack, 62 and 61, in order to get 1. From here, it's straightforward, if slightly painful. We just need to produce a stack that looks like our target string (in reverse order), followed by our two writes of `,` and `@` (denoted by `X` and `Y` in the original source). While I could just duplicate the 1 several hundreds of times, I decided it was worth the effort to write a more efficient method, which encodes the target value in binary, then produces the binary decomposition on the stack, before summing (it's easy to get `1,4,16,32`, for instance, because I can double with `:+`). This, plus the careful positioning of everything so the writes end up in the correct place, is a lot of work, so I just wrote a Python script that does it for me. ``` from collections import defaultdict # by convention, assume there is a 1 on top of the stack def gen_stack(stack): # goal is to produce stack:list[int] def gen_single(ch): if type(ch) is chr: ch = ord(ch) binary_decomp = [] cur = ch while cur > 0: # I know this is inefficient r = (1 << (cur.bit_length() - 1)) cur -= r binary_decomp.append(r) binary_decomp = binary_decomp[::-1] total = "" value = 1 for c in binary_decomp: total += ":" while value < c: total += ":+" value *= 2 return total + "+" * (len(binary_decomp) - 1) + "\\" return "".join(gen_single(c) for c in stack) # places string segment starting at (i,j) in given direction def place_segment(prog, i, j, segment, direction=(1,0)): for k, c in enumerate(segment): prog[i + k*direction[0], j + k*direction[1]] = c return len(segment) target_string = """,0123456789"~@!""" # [x,y], use implicit grid prog = defaultdict(lambda : ' ') W = 75 offset = 0 offset += place_segment(prog, offset, 0, ">g::g-") # ends at 6,0 excl # store this for 1-recovery prog[62,62] = "=" # now have 1 on stack target_stack = list(map(ord,target_string))[::-1] target_stack.extend([ord(","),2,10]) # write , to 2,10 target_stack.extend([ord("@"),2,12]) # write @ to 2,12 stack_generation = gen_stack(target_stack) stack_generation += "$" # pop the 1 stack_generation += "p" # place the @ stack_generation += "p" # place the , # program flow routing for i in range(8): prog[W,i] = "<" if (i % 2 == 1) else "v" prog[0,i] = "v" if (i % 2 == 1) else ">" # makes it more aesthetically pleasing offset += 1 row = 0 while len(stack_generation) > 0: # zig-zag segment placement until we're out if row % 2 == 0: place_segment(prog, offset, row, stack_generation[:W-offset-1]) stack_generation = stack_generation[W-offset-1:] else: place_segment(prog, W - 2, row, stack_generation[:W-offset-1], (-1,0)) stack_generation = stack_generation[W-offset-1:] row += 1 # first 8 rows were allocated for the stack generation # place the print-stack block place_segment(prog, 0, 9, "v <") place_segment(prog, 0, 10, " X") place_segment(prog, 0, 11, ">:|") place_segment(prog, 0, 12, " Y") # print prog max_y = max(k[1] for k in prog.keys()) max_x = lambda y : max([0, *[k[0] for k in prog.keys() if k[1] == y]]) # just so we don't print tons of extra spaces source = "\n".join("".join(prog[i,j] for i in range(max_x(j)+1)) for j in range(max_y+1)) print(source) # verify for c in target_string: if c in source: print("Failed check for",c) ``` [Answer] # Haskell, cracks Ad Hoc Garf Hunter's [answer](https://codegolf.stackexchange.com/a/207580/78584) Hard version: ``` main=print[p|r<-[[n..m]|m<-[a|a<-['n'..],init[a|a<-['n'..],'|'<a,[a,']','<']<[a,']'..]]<[a],[a,']','<']<[a,']'..]],n<-[a|a<-init=<<[init['n','a'..]],a<'-']],p<-r,p<','||','<p,p<'.'||'.'<p,p<'['||'['<p,p<'|'||'|'<p,p<'<'||'<'<p,p<'-'||'-'<p,p<']'||']'<p,p<'m'||'m'<p,p<'a'||'a'<p,p<'i'||'i'<p,p<'n'||'n'<p,p<'p'||'p'<p,p<'r'||'r'<p,p<'t'||'t'<p,p<'='||'='<p,t<-init=<<[init=<<[init=<<[init=<<[init[t|n<-[a|a<-init=<<[init['n','a'..]],a<'-'],t<-[n..','],[n,t,'.']<[n,t..]]]]]],p<t||t<p,i<-init[a|a<-['n','['..],a<'.'],i<p||p<i] ``` Easy version: ``` main=print[p|r<-[[n..m]|m<-[a|a<-['n'..],init[a|a<-['n'..],'|'<a,[a,']','<']<[a,']'..]]<[a],[a,']','<']<[a,']'..]],n<-[a|a<-init=<<[init['n','a'..]],a<'-']],p<-r,p<','||','<p,p<'.'||'.'<p,p<'['||'['<p,p<'|'||'|'<p,p<'<'||'<'<p,p<'-'||'-'<p,p<']'||']'<p,p<'m'||'m'<p,p<'a'||'a'<p,p<'i'||'i'<p,p<'n'||'n'<p,p<'p'||'p'<p,p<'r'||'r'<p,p<'t'||'t'<p,p<'='||'='<p,t<-init=<<[init=<<[init=<<[init=<<[init[t|n<-[a|a<-init=<<[init['n','a'..]],a<'-'],t<-[n..','],[n,t,'.']<[n,t..]]]]]],p<t||t<p,i<-init[a|a<-['n','['..],a<'.'],i<p||p<i,':'<p||p<':'] ``` Found by lots of trial and error, mostly using ranges, list comprehensions and comparisons as filters. Some used tricks: * We can only ever obtain strings, never single characters (except those that are allowed). List comprehensions work around this: If `s=[c]` and `t=[d]` are single-character strings, then `[[c,d..]|c<-s,d<-t]` is equivalent to `[[c,d..]]` * `init.init[1,2,3]` doesn't work due to precedence. Use `init=<<[init[1,2,3]]` instead * Lexicographic ordering is useful! Things like `[a,'.'..]>[a,'.']` (check if further terms in arithmetic sequence exist) and `[a,'m'..]>[a,'m',']']` (check if next term is greater than ']') are useful checks for narrowing down characters * After we have `' '` and `'~'` we can construct `[' '..'~']`, and filter out the allowed chars using the construct `p<'m'||'m'<p`. However, we can't write `'''`, so `'` has to again be generated using range tricks There are probably some shortcuts using some kind of pattern matching inside the assignment (for example, the `init`s could be elimited by something like `[a,_,_]<-[[...]]` instead of `a<-init=<<[init[...]]`. [Answer] # [Java (JDK)](http://jdk.java.net/), cracks [user's answer](https://codegolf.stackexchange.com/a/207636/96426) ``` class T{public static void main(String... args){if(System.out.printf(""+(char)92+(char)91+(char)59)==null){}}} ``` [Try it online!](https://tio.run/##y0osS9TNSsn@/z85J7G4WCGkuqA0KSczWaG4JLEESJXlZ6Yo5CZm5mkElxRl5qXr6ekpJBalF2tWZ6ZpBFcWl6Tm6uWXlugVACVL0jSUlLQ1kjMSizQtjWAMQyjD1FLT1javNCdHs7q2tvb/fwA "Java (JDK) – Try It Online") This was pretty fun. First, we need a main method without the square brackets, which can be done with the standard main method definition replacing the square brackets with ellipsis, and then to avoid the semicolon we can wrap the print statement into an if conditional so that it executes when the condition is being checked, printing the characters according to their ascii values. [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 1034 bytes, cracks [@RobinRyder's answer](https://codegolf.stackexchange.com/a/209755/92901) ``` Restricted sauce, or, A shortage of ketchup. Othello, also known as Reversi. Ophelia, a satellite of Uranus. Act I: Love's letters lost. Scene I: Cracked pepper. [Enter Othello and Ophelia] Othello: Thou art as sweet as the square root of a cute peaceful fair fine gentle angel! Ophelia: Thou art as cunning as the square root of the product of the factorial of I and the product of a trustworthy rich pony and the square of I! Speak thy deceitful treachery! Othello: Thou art as golden as the square root of twice the square of thou! Ophelia: Thou art as healthy as the product of the square root of a cunning pretty trustworthy good peaceful gentle fine squirrel and I! Speak thy awful truth! Thou art as loving as twice the square of I! Speak thy flirtatious trifles! Othello: Thou art as happy as the square root of a gentle delicious cunning golden honest trustworthy sweet Lord! Ophelia: Thou art as peaceful as the product of twice the square root of I and I! Speak thy glad tidings! [Exeunt] ``` [Try it online!](https://tio.run/##dVO9buMwDN7zFPTUJegDdCsOHQIUKNDeTUUHQqYtIYKoo6i4fvoc7Tg51Ig3S6S@P9Ilx/P5nYpKcEotFKyO9sCyh2conkWxJ@AOjqTO1/y4272ppxh5DxgLwzHxkAALvNOJpITH3Vu2ekCrG5paa9AZ4Y9gqsUAnp3C4Qle@UQPBSKp2kOIXNSKH44STeVfgu5oijLlTGKVz5dkjbDQA6YWFqqvm6inHcBvzxVQdBJVBqL5w8pQ/lYUAmHWSQ@Cq6YsEzrqaoQOg0AXjL2npJGMoafY7K6G1tiuphRSv4E@XWXhtrrbsUOnLAHjdHGYDay6EFRq0cFi9yPYSDxkTuOtdeGYnjem5sO0H2FqbclR0MmFivnxJGOzGUrPsaW0pXsIjlZkao@3c/CEcdKw4K1M3wn9ElsWG/z4w3DP3P6fxzKFeSKGEkQozkmsvONw8V3VNytpkU/XCd2xtcLpYrBt18DV2iV0kcp2hh5zHjcXa5HeWlxuxruaXqL3nOyX@@H9sqmvLG0DsJn1LZw7Ya8dXuUc7oXWR7SVCq2Jmlx@vnxTTfp1Pv8D "Shakespeare Programming Language – Try It Online") Constructing integers was tricky. As Robin noted, addition and subtraction are out. So too are cubing (`the cube of`), division (`the quotient between`), and modulo (`the remainder of the quotient between`). We will have to make do with multiplication, squares, square roots, and factorials. These operations are incompletely documented in the [official docs](http://shakespearelang.sourceforge.net/report/shakespeare/); I actually found the [interpreter source code](https://github.com/TryItOnline/spl/blob/master/grammar.y) to be a more useful reference in this regard. We also need a way to output characters given that the usual `Speak thy mind!` is banned as well. Digging into the interpreter source code, I found that `mind` may be replaced with arbitrary text (a warning is printed to STDERR). There's that problem solved. Now, on to generating the required characters. The required ASCII codes are 109, 77, 98, and 66. The basic idea is to set Othello to each of these values in succession, then print the character via `Speak thy ...` (I took some poetic licence with the `...`s). Ophelia stores some intermediate values for convenience. I think the code is most easily explained through the maths. Here I will use \$p\$ for Ophelia's value and \$t\$ for Othello's. The only other thing to bear in mind is that *positive nouns* (such as `angel` and `pony`) represent \$1\$ and *adjectives* (such as `cute` and `sweet`) preceding a noun multiply it by \$2\$. (SPL has negative and neutral nouns too, but only positive nouns are used here.) ``` Othello: Thou art as sweet as the square root of a cute peaceful fair fine gentle angel! ``` \$p = \left\lfloor\sqrt{2\cdot2\cdot2\cdot2\cdot2\cdot1}\right\rfloor = \left\lfloor\sqrt{32}\right\rfloor = 5\$ ``` Ophelia: Thou art as cunning as the square root of the product of the factorial of I and the product of a trustworthy rich pony and the square of I! ``` \$t = \left\lfloor\sqrt{p!(2\cdot2\cdot1\cdot p^2)}\right\rfloor = \left\lfloor\sqrt{12000}\right\rfloor = 109\$ ``` Othello: Thou art as golden as the square root of twice the square of thou! ``` \$p = \left\lfloor\sqrt{2p^2}\right\rfloor\ = \left\lfloor\sqrt{50}\right\rfloor = 7\$ ``` Ophelia: Thou art as healthy as the product of the square root of a cunning pretty trustworthy good peaceful gentle fine squirrel and I! ``` \$t = \left\lfloor\sqrt{2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot1}\right\rfloor p = \left\lfloor\sqrt{128}\right\rfloor 7 = 77\$ ``` Thou art as loving as twice the square of I! ``` \$t = 2p^2 = 98\$ ``` Othello: Thou art as happy as the square root of a gentle delicious cunning golden honest trustworthy sweet Lord! ``` \$p=\left\lfloor\sqrt{2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot1}\right\rfloor = \left\lfloor\sqrt{128}\right\rfloor = 11\$ ``` Ophelia: Thou art as peaceful as the product of twice the square root of I and I! ``` \$t = 2\left\lfloor\sqrt{p}\right\rfloor p = 2\left\lfloor\sqrt{11}\right\rfloor 11 = 66\$ [Answer] # [C (gcc)](https://gcc.gnu.org/), cracks [Noodle9's answer](https://codegolf.stackexchange.com/a/207629/90181) Output: `#_ep` Since **p**rintf, **p**ut and writ**e** are not allowed I had to use inline assembly to send data to stdout. The string `"\043\137\145\160"` encodes the desired output in octal notation. ``` int main() { long r; asm ("int $0x80" : "=a" (r) : "a" (4), "b"(1), "c"("\043\137\145\160"), "d" (4)); } ``` [Try it online!](https://tio.run/##S9ZNT07@/z8zr0QhNzEzT0OTq5pLAQhy8vPSFYqswezE4lwFDSWQEhWDCgsDJQUrBSXbRCUFjSJNEBPEMtHUUVBKUtIwBNHJShpKMQYmxjGGxuYxhiamMYZmBkogiRSwSk1rrtr//wE "C (gcc) – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), Ethan Chapman's [answer](https://codegolf.stackexchange.com/a/207599/92069) ``` 9`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)0=,_34=\_97=\_99=\_101=\_115=\39= ``` [Try it online!](https://tio.run/##S85KzP3/3zLBSnMgoIGtTryxiW1MvKU5iLAEEoYGhiDS0NQ2xtjS9v9/AA "CJam – Try It Online") [Answer] # [R](https://www.r-project.org/), cracks [Dominic van Essen's challenge](https://codegolf.stackexchange.com/a/207617/86301) The string to print is ``` 0123456789+-*/^!&|%`()$ ``` My (circumvoluted) solution is: ``` "<"=sum a=T<F aa=T<T aaa=T<aa aaaa=T<aaa aaaaa=T<aaaa aaaaaa=T<aaaaa aaaaaaa=T<aaaaaa aaaaaaaa=T<aaaaaaa aaaaaaaaa=T<aaaaaaaa "["=example S=Syntax[,,,T] A=Arithmetic[,,,T] Q=Quotes[,,,T] ">"=strsplit As=A>"" Ss=S>"" Qs=Q>"" "?"=unlist Au=?As Su=?Ss Qu=?Qs "<"=c b=Au<Su b=b<Qu "?"=unique b=?b "?"=sort b=?b n=F:aaaaaaaaa "?"=rm ?"[" ">"=sum r=n<b[{aaaaaaaaa>aaaaaaaaa}>aaaa] r=r<b[aaa] r=r<b[aaaaaa>aaaaaaaa] r=r<b[aaaaaaa>aaaaaaaa] r=r<b[{aaaaaaaaa>aaaaaaaaa}>aaa] r=r<b[aaaaaaa] r=r<b[aaaaaaaa>aaaaaaaaa] r=r<b[aaaaaaaaa>{aaaaaaaaa>aaaaaaaa}] r=r<b[{aaaaaaaaa>aaaaaa}>aaaa] r=r<b[{aaaaaaaaa>aaaaaa}>aaaaa] r=r<b[aaaaaaaaa>aaa] r=r<b[aaaaaaaaa>aaaa] r=r<b[aaaaaaaaa>{aaaaaaaaa>aaaaaaaaa}] "["=write "?"=length r["",?r,,""] ``` [Don't try it online!](https://tio.run/##jVLJboMwEL3PZ8yZL6gYEJfcLXNDHExkNUhAUi9KqirfTsdA2Bqknt4yz@MZy6bvMUayvgVFeXwCFSBnCKhUICMb6cQn8VIvOevZWJzFWnkKsEDSD9XeGg2S5Hfn1KOIoigvIaPM1O7SalefJ0uQ8Fen7SQx4dGdsbemdpBZyhJEkJZkQGFJBMQUyXdNbTniKc0sSAZpQTAIC2H/M1SU@Vh6xioWfjpUf3nNTloN2l6NG1VHpw@1rMA100LKq4wT8WMa6uKq@JlDycyeAy05YTixpevg1v7rH/beHdzJVXpfUcmbns/D@7aLHJTfXHJk/m@eMFD4M3f@Gnp4@kZ3n@4CpkCMUhNFiGXf/wI "R – Try It Online"): it doesn't work on TIO, but it works on my laptop. The key idea relies on ``` unlist(strsplit(example(Syntax, give.lines=T), "")) ``` The function `example` is usually used to execute the "Examples" section of a help file. With the `give.lines=T` argument, you can get the code of those examples; this includes a lot useful characters. In this case, the examples for `Syntax`, `Arithmetic` and `Quotes` combined contain all the necessary characters, plus some extra ones, stored in `b`. Since we are not allowed brackets, calling functions requires redefining the operators `?<>[`, making the code even messier. (Thanks to Giuseppe for pointing out that this was possible with the available characters.) The rest of the code defines constants 1 to 9 (`a` to `aaaaaaaaa`; some of these are not needed in the end but I'm not sure which ones) and extracts the values of `b` in the right order. Slightly commented version: ``` "<"=sum a=T<F # a=1 aa=T<T #aa=2 aaa=T<aa #aaa=3 aaaa=T<aaa #... aaaaa=T<aaaa aaaaaa=T<aaaaa aaaaaaa=T<aaaaaa aaaaaaaa=T<aaaaaaa aaaaaaaaa=T<aaaaaaaa # aaaaaaaaa=9 "["=example S=Syntax[,,,T] # S=example(Syntax, give.lines=T) A=Arithmetic[,,,T] # A=example(Arithmetic, give.lines=T) Q=Quotes[,,,T] # Q=example(Quotes, give.lines=T) ">"=strsplit As=A>"" # As=strsplit(A) Ss=S>"" # Ss=strsplit(S) Qs=Q>"" # Qs=strsplit(Q) "?"=unlist Au=?As # Au=unlist(As) Su=?Ss # Su=unlist(Ss) Qu=?Qs # Qu=unlist(Qs) "<"=c b=Au<Su b=b<Qu # b=c(Au, Su, Qu) "?"=unique b=?b "?"=sort b=?b # b=sort(unique(b)) n=F:aaaaaaaaa # n=0:9 "?"=rm ?"[" ">"=sum r=n<b[{aaaaaaaaa>aaaaaaaaa}>aaaa] # r=c(n, b[9+9+4]) since b[22]=="+" r=r<b[aaa] # r=c(r,b[3]) since b[3]=="-" r=r<b[aaaaaa>aaaaaaaa] # ... r=r<b[aaaaaaa>aaaaaaaa] r=r<b[{aaaaaaaaa>aaaaaaaaa}>aaa] r=r<b[aaaaaaa] r=r<b[aaaaaaaa>aaaaaaaaa] r=r<b[aaaaaaaaa>{aaaaaaaaa>aaaaaaaa}] r=r<b[{aaaaaaaaa>aaaaaa}>aaaa] r=r<b[{aaaaaaaaa>aaaaaa}>aaaaa] r=r<b[aaaaaaaaa>aaa] r=r<b[aaaaaaaaa>aaaa] r=r<b[aaaaaaaaa>{aaaaaaaaa>aaaaaaaaa}] "["=write "?"=length r["",?r,,""] # write(r, file="", ncolumns=length(r), sep="") ``` [Answer] # [JavaScript (Babel)](https://github.com/patrickroberts/xchars-pipeline), cracks [my pronoun is monicareinstate's answer](https://codegolf.stackexchange.com/a/207609/42091) The answer is 74291 bytes using only the characters `[+|>]`, which is unfortunately too large to post here, so I've provided a [GitHub repository](https://github.com/patrickroberts/xchars-pipeline) to verify the [solution](https://github.com/patrickroberts/xchars-pipeline/blob/master/index.js). ``` git clone https://github.com/patrickroberts/xchars-pipeline.git cd xchars-pipeline npm install npx babel-node index.js ``` Output: ``` !"#$%&'()*,-./0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz ``` This output limits us to the printable ASCII characters `+<>?@[]{|}~` [(as Calculuswhiz points out)](https://codegolf.stackexchange.com/q/207558#comment492172_207609), which means the only way to invoke a function is with the [pipeline operator `|>`](https://github.com/tc39/proposal-pipeline-operator). Essentially the pipeline operator allows `f(x)` to be expressed as `x|>f`. Other than that, the restricted source using these characters is very similar to [JSF\*ck](http://www.jsfuck.com/). I compiled the following program using [Xchars.js](https://syllab.fr/projets/experiments/xcharsjs/5chars.pipeline.html) ``` console.log('!"#$%&\'()*,-./0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz') ``` and was able to interpret it using [a Babel plugin](https://babeljs.io/docs/en/babel-plugin-proposal-pipeline-operator). There are two competing proposals for the pipeline operator supported by this plugin, but I opted to use the [F#-style pipeline](https://github.com/valtech-nyc/proposal-fsharp-pipelines) since the output of the Xchars.js compiler is not compatible with the [Smart pipeline](https://github.com/js-choi/proposal-smart-pipelines) and Babel will throw the following error during compilation: ``` SyntaxError: Pipeline is in topic style but does not use topic reference (1:670) ``` [Answer] # JavaScript (Browser), cracks [PkmnQ's answer](https://codegolf.stackexchange.com/a/207574/81278) ``` window.location="javascript:console.log"+String.fromCharCode`40`+String.fromCharCode`34`+String.fromCharCode`40`+String.fromCharCode`92`+String.fromCharCode`92`+String.fromCharCode`41`+String.fromCharCode`34`+String.fromCharCode`41` ``` Paste it in your browser's JS console! (Tested on Chrome). Uses `window.location="javascript:..."` to basically get an eval, and then builds the payload `("(\\)")` by using `String.fromCharCode`, using [template literal syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to call that method (please don't ask me why this exists in JavaScript...). Both of these tricks I got from [this handy StackOverflow post](https://stackoverflow.com/questions/35949554/invoking-a-function-without-parentheses). [Answer] # [Ruby](https://www.ruby-lang.org/), cracks [@histocrat's answer](https://codegolf.stackexchange.com/a/207590/9365), 55 bytes ``` method("\x70rint")["\x70\x3c\x2e\x24%c%d\x73"%[97,3-2]] ``` The approach I took here was to find a way to access the `print` method, using [`method`](https://ruby-doc.org/core-2.7.1/Object.html#method-i-method) seemed sensible, but trying to invoke it was harder than I'd have liked, then I happened to stumble across [the docs for `Proc`](https://ruby-doc.org/core-2.2.0/Proc.html#method-i-5B-5D) which showed the `<method reference>[<args>]` notation which gave me the last piece I needed! [Try it online!](https://tio.run/##KypNqvz/Pze1JCM/RUMppsLcoCgzr0RJMxrMjqkwTo6pMEoFYhPVZNUUoJixkmq0pbmOsa5RbOz//wA "Ruby – Try It Online") [Answer] # J, cracks [@xash's answer](https://codegolf.stackexchange.com/a/207631/81278) ``` (97)1!:2(4) (117)1!:2(4) (46)1!:2(4) ``` [Try it online!](https://tio.run/##y/r/X8PSXNNQ0cpIw0STS8PQEIljYgZj//8PAA "J – Try It Online") Gonna be honest, not entirely sure why this works. I was trying to learn J syntax and playing around with a few things, and I found that you can just send ASCII values to STDOUT and they get automatically converted into characters. Neat! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), cracks [att's answer](https://codegolf.stackexchange.com/a/207595/32372) ``` {69,99,95+9,111,64,68,116,91,48,32,38,32,93,1+9}//("Fr*ara*de"//Names//Tr//(x//Head))//("Prin"~~_//Names//Tr//(x//Head)) ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/7/azFLHEohMtS11DA0NdcxMdMwsgCwzHUtDHRMLHWMjHWMwaWmsY6htWauvr6HkVqSVWJSolZKqpK/vl5ibWqyvH1IElKjQ1/dITUzR1AQpCijKzFOqq4vHoeT/fwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [QBasic 1.1](https://archive.org/details/msdos_qbasic_megapack), cracks [DLosc's answer](https://codegolf.stackexchange.com/a/207790/94694) The string to print is: ``` Cc ``` Thanks to QBasic's complete lack of memory safety, my solution creates an arbitrary two character string, gets its memory address, directly changes the memory into the right ASCII codes, and prints the result: ``` X$ = "aa" A = SADD(X$) POKE A, 67 POKE A + 1, 99 PRINT X$ ``` [Answer] # [Perl 5](https://www.perl.org/) cracks [@Gilles 'SO- stop being evil''s answer](https://codegolf.stackexchange.com/a/207732/9365), 5845 (!) bytes Note: the original program contains `\x18` which is used as `^X` in this answer. ``` ($__=()=())=>($___=()=(_))=>($____=()=(_=>_))=>($_____=()=(_=>_=>_))=>($______=()=(_=>_=>_=>_))=>($_______=()=(_=>_=>_=>_=>_))=>($________=()=(_=>_=>_=>_=>_=>_))=>($_________=()=(_=>_=>_=>_=>_=>_=>_))=>($__________=()=(_=>_=>_=>_=>_=>_=>_=>_))=>($___________=()=(_=>_=>_=>_=>_=>_=>_=>_=>_))=>($_=[]=>/./)=>(($____________=>$_____________=>$______________=>$_______________=>$________________=>$_________________=>$__________________=>$___________________=>$____________________=>$_____________________=>$______________________=>$_______________________=>$________________________=>$_________________________=>$__________________________=>$___________________________=>$____________________________=>$_____________________________=>$______________________________=>$_______________________________=>$________________________________=>$_________________________________=>$__________________________________=>$___________________________________=>$____________________________________=>$_____________________________________)=$&.._)=>($_=$^X=>/...$/=>$_=$&=>/./)=>(($__________________________________________=>$___________________________________________=>$____________________________________________=>$_____________________________________________=>$______________________________________________=>$_______________________________________________=>$________________________________________________=>$_________________________________________________=>$__________________________________________________=>$___________________________________________________=>$____________________________________________________=>$_____________________________________________________=>$______________________________________________________=>$_______________________________________________________=>$________________________________________________________=>$_________________________________________________________=>$__________________________________________________________=>$___________________________________________________________=>$____________________________________________________________=>$_____________________________________________________________=>$______________________________________________________________=>$_______________________________________________________________=>)=$&.._)=>($______________________________________=$__________________________________________&$______________________________________________________________)=>(($______________________________________=>$_______________________________________=>$________________________________________=>$_________________________________________=>)=$______________________________________.._)=>($_________________________________________________________________=$____________________________________________&(!$_________).$_________)=>($__________________________________________________________________=$______________.$__________________________.$_____________________________.$________________.$_________________________________________________________________.$__________________________________________.$___________________________________________________________.$______________________________________.$_________________________________________________.$_______________________________________.$______________________________________________________________.$_________________________________________________________.$__________________________________________.$________________________________________________________)=>($___________________________________________________________________=$______________.$__________________________.$_____________________________.$________________.$_________________________________________________________________.$_____________________________________________________.$______________________________________.$________________________________________.$________________________________________________)=>(&$__________________________________________________________________(&$___________________________________________________________________($______________.$__________.$___________=>$___.$___.$____=>$___.$___.$______=>$___.$__.$_______=>$___.$___.$__=>$___.$___.$________=>$_____.$____=>$___.$___.$_____=>$______.$_________=>$_____.$_____=>$_____.$______=>$_____.$___________=>$______.$____=>$______.$_____=>$______.$______=>$______.$_______=>$______.$__________=>$______.$___________=>$_______.$__=>$_______.$___=>$_______.$____=>$_______.$_____=>$_______.$______=>$_______.$_______=>$_______.$________=>$_______.$_________=>$_______.$__________=>$_______.$___________=>$________.$__=>$________.$_____=>$________.$______=>$________.$_______=>$________.$________=>$________.$_________=>$________.$__________=>$________.$___________=>$_________.$__=>$_________.$___=>$_________.$____=>$_________.$_____=>$_________.$______=>$_________.$_______=>$_________.$________=>$_________.$_________=>$_________.$__________=>$_________.$___________=>$__________.$__=>$__________.$___=>$__________.$____=>$__________.$_____=>$__________.$______=>$__________.$_______=>$__________.$________=>$__________.$_________=>$__________.$__________=>$__________.$___________=>$___________.$__=>$___________.$____=>$___________.$______=>$___________.$________=>$___________.$_________=>$___________.$__________=>$___________.$___________=>$___.$__.$__=>$___.$__.$___=>$___.$__.$____=>$___.$__.$_____=>$___.$__.$______=>$___.$__.$_______=>$___.$__.$________=>$___.$__.$_________=>$___.$__.$__________=>$___.$__.$___________=>$___.$___.$__=>$___.$___.$___=>$___.$___.$____=>$___.$___.$_____=>$___.$___.$______=>$___.$___.$_______=>$___.$___.$________=>$___.$___.$_________=>$___.$___.$__________=>$___.$___.$___________=>$___.$____.$__=>$___.$____.$___=>$___.$____.$____=>$___.$____.$_____=>$___.$____.$______=>$___.$____.$________=>$______.$_________))) ``` [Try it online!](https://tio.run/##3VbLasQwDPyWQgjxxTn16HxHobQ@7a2H0v@HNOku8UMjRbbSHgqloNGMrJGNsp@3r4/ndZ2GGMPktj8Xlj24R/EIH3FYMihhJVzgVarO1WmQJxTMoTSWB6gSN9HD61tYZj/vUaHeOEVIYgoABEEQwyCDcjCL8wkhI6XEnJw8yZ6lT/PnBAVDQ1FxdCQlS0uLLgyj9/HxxIf3l/2Nez/Me4Etxzz5aw7vYbfSm/ntgg5Fj6RL0yfqVPXKunX9QoPSIjVpbWKj2io36@0FtgrFutNpGg4djQ227Fn9NBrm1jLin2HqqG0Tv@gytuuYnhLf@aGYs70Z0o0Xanr5PJr29gZbSpiO04o7DlFLrPMy6P9mzhc92n/1an/1DbY3sl/ReMEdXVIkTsJFF97uW98f/yiQQ4e0YgFR@qBwdY8PTtZQqalDEqM6dVlyDD0XdYLB7CuZfB@kKiQxBQCCIIhhkEHzz3vZOe0NNIe6g@3h/pgG2Q7rFuvx0gEjG8gHNIKdMFY4L7wZ4obaAX6QIegIW2I8caZYV4It6gvZwD1z7bH98Q1yC61cTNnI0yYjm42uOnH51SZKDIMMerZSFYtaXN3s7hZABuXgHK89EBPUBbCBfKCXk/@@d25dvwE "Perl 5 – Try It Online") ## Explanation This is a very restrictive set of characters, but the biggest problem I encountered was trying to get access to the lowercase letters. First the numbers are set up and stored in `$__` (0) to `$___________` which was using lengths of lists to get the scalar numbers. Next target was to set up `A` to `Z`. To do this, [`$_` is set to `[]` which, in scalar context, evaluates to a string like `ARRAY(0x123456789abc)` so `/./` sets `$&` to `A` which is then used in a range with `_` (`$&.._`)](https://tio.run/##K0gtyjH9/18l3jY61pqroCgzr0Qp3kolPiZPyZpLX08fKqaipqcXb/3/PwA) which you can assign to many variables in list context (e.g. `($a, $b, $c) = a..c`, but using long strings of `_`s for the names in this). Next it's necessary to generate the lowercase letters to be able to call functions, this was pretty tricky and I'm using something that might be a little unfair as it can potentially change depending on the implementation. I did look at a few different ideas before settling on this one, I originally hoped to use `__PACKAGE__` which returns `main` and would easily enable producing `a.._`, but I wasn't able to get it to work. With more patience maybe... But knowing that Perl stores the executable the program was invoked with in a special variable `$^X` (`$\x18`), which ends with `perl` on most of my tests on Linux, was a viable (if not entirely portable) solution. This provides access to `e`, via [storing `$^X` in `$_`, matching `/...$/`, which would store `erl` in `$&`, storing this in `$_`, matching again `/./` to store `e` in `$&` then, as was done for the uppercase letters, generating a range from `e` to `_` and storing](https://tio.run/##K0gtyjH9/18l3lYlLsKaq6AoM69EKd5KJT4mT8maS19PT09F35oLJK2GRVYfKqaipqcXb/3/PwA). To get access to `a`, it's necessary to perform another [stringwise operation of `"e"&"y"`] and generate the missing start of the alphabet as was done for the other letters. To be able to call library functions it's necessary to generate `::` (or `'` which functions identically), fortunately [`'` can be generated via a stringwise `AND` operation of `g&"7"`, but it's necessary to concatenate `7` with the empty string to cast to string so `"g"&(!7).7` is used](https://tio.run/##K0gtyjH9/18lPt5WQ9NWI14HCWpacwHF423TrbkKijLzSpSAvJg8JSgPJKWmoQikNPWAhPX//wA). Now we have all the letters and `'` which means we can call `CORE::evalbytes` (or any other functions in the `CORE` library), but we need to be able to generate characters we haven't pre-generated, so `CORE::pack` is used to generate a string by passing in a list of numbers and converting them to characters, that will be `eval`ed producing the desired output. [Answer] # [Ruby](https://www.ruby-lang.org/), [@histocrat's answer](https://codegolf.stackexchange.com/a/207622/9365), 48 bytes ``` STDOUT::write"\x70\x3c\x2e\x24%c%d\x64"%[97,3-2] ``` [Try it online!](https://tio.run/##KypNqvz/PzjExT80xMqqvCizJFUppsLcIKbCODmmwigViE1Uk1VTYirMTJRUoy3NdYx1jWL//wcA "Ruby – Try It Online") I had no idea you could call methods that way, until I read [this answer (thanks @histocrat!)](https://codegolf.stackexchange.com/a/193205/9365) [Answer] # 05AB1E, cracks [@SomoKRoceS's (other) answer](https://codegolf.stackexchange.com/a/207584/81278) ``` žEžwžv;;;++çžEžvžv;žv;;žv;;;;++++çžEžvžv;žv;;+++çžEžvžv;žv;;;;+++çžEžvžv;++çžzžxžwžvžv;žv;;žv;;;;++++++çžEžwžv;;žv;;;+++çžEžvžv;žv;;žv;;;++++çžwžv;;žv;;;žv;;;;+++çžwžv;;;+çžCžBžzžwžv;žv;;žv;;;;++++++çžwžv+çžwžvžv;;;;++çžwžvžv;;;++çžwžvžv;;;žv;;;;+++çžwžvžv;;++çžwžvžv;;žv;;;;+++çžwžvžv;;žv;;;+++çžwžvžv;;žv;;;žv;;;;++++çžwžvžv;++çžwžvžv;žv;;;;+++çJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6D7Xo/vKj@4rs7a21tY@vBzMLwPxwWIQCaAMFjlsYhiiEF7V0X0VEGuwmQzXUY4ko43TNTANyKpRLYf5B8R2PrrPCeyActxWg6TgDLgsqgA6H9NGaKCgcHGoQvEimihakJejBGQ5lsD2@v8fAA "05AB1E – Try It Online") Incidentally, all this approach really needs to function is `ç` (cast top of stack to a character), `J` (join together the entire stack into a string), and some way of producing numbers on the stack. My original idea for the latter (since number literals are now banned) was to use `T` (push 10), then `;` (divide by 2) to get a 1 (although that technically also needs `ï`, cast to int), and then adding that with itself as many times as necessary. However, since the Unicode character values for this program are in the range of ~8000, this would make for very length source code. I made it a bit shorter by using the literals that push powers of two (`žv` through `žH`). Here's the Python script I used to create this: ``` lookup = {65536: "žH", 32768: "žG", 16384: "žF", 8192: "žE", 4096: "žD", 2048: "žC", 1024: "žB", 512: "žA", 256: "žz", 128: "žy", 64: "žx", 32: "žw", 16: "žv", 8: "žv;", 4: "žv;;", 2: "žv;;;", 1: "žv;;;;"} def make_value(target): if target in lookup: return lookup[target] use = max(k for k in lookup if k <= target) return lookup[use] + make_value(target - use) + "+" goal = "•”“’‘Ž…„'\"ഭ0123456789" source = "".join(make_value(ord(c)) + "ç" for c in goal) + "J" print(source) for c in goal: if c in source: print(f"Failed check for '{c}'") ``` [Answer] # Python 2, 39953 bytes, cracks [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/207663/48931) ``` exec(chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))+chr((id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id))+(id(id)-~-id(id)))) ``` [Try it online!](https://tio.run/##7dYxCoAwEATA7yRIGr8UA7FREQtt/Pop@AphwEKmPG6zt11HX5cxop2tptr3lObp/XK5y/eTB0IIIYT8XPKg5AkhhBCHgJEQQgghapYQQgghCpwQQgghjgViiQghhKgaQoggEiK@RkKI2BFCRJwQItCEiCYhQiZkhHgGPAOECL0hESKshAgHsUSEWGFCCCFE@RBCCFFihFg0Qgghas1ICCGEqCxCCCGEKHlCCCGEOB8IIYQQ4lggxAoTQghRRzniAQ "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), cracks [@xash's answer](https://codegolf.stackexchange.com/a/207678/78410) ``` (tolower'TMOUTPUT')apply 117 (tolower'TMOUTPUT')apply 58 (tolower'TMOUTPUT')apply 46 ``` [Try it online!](https://tio.run/##y/r/X6MkPye/PLVIPcTXPzQkIDREXTOxoCCnUsHQ0JwLp6SpBW45E7P//wE "J – Try It Online") Classic [stdlib](https://www.jsoftware.com/docs/help807/user/lib_stdlib.htm) abuse. `tmoutput` is a wrapper for `1!:2&4` which was used in the [previous crack](https://codegolf.stackexchange.com/a/207648/78410). Since it contains `u`, I use the uppercased name, lowered with `tolower` and then eval-applied with `apply`. [Answer] # [R](https://www.r-project.org/), 187 bytes, cracks [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/207675/67312) ``` n=pi*pi d=F:n `!`=ls l=!n i=n*n*pi-pi-pi-T-T `?`=el o=n+pi-T-T t=n+pi-T p=l?o b=l?t k=l?i A=?letters `!`=toupper e=!letters?pi+pi-T `+`=c o=d+p+b+A+e s=l?n*n*n-n-pi-T `!`=get `+`=!s x=o+k ``` [Try it online!](https://tio.run/##LY3RCcMwDET/bwv/RniBgjD56QQZwKQRxcTIInah27tuEhCHOJ3eHb0rW5osYePnQxFd5FyR2SkS66Tj5K9Z/IIYIktGYaXbafcK4xwK1qEN@9CEmUOW1uSoJ7aVj5kcEHa3HSxdv5EivwZ1I6OVZhLUQfi3q1d/RQbhLe2MuoovF9p7/wE "R – Try It Online") Random tricks: * liberal aliasing of functions to the builtin operators to get around `(`. * Uses `ls(9)` to get a list of all builtins in `package:base`, getting around the lack of `apropos()` -- this may not work on non-TIO platforms. * Uses `el` to get around `[` since `el(what,where)==what[where][[1]]` * `get` is used to return a function given a string, in this case `sapply`. * uses `sapply(output list,"cat")` to print, since otherwise we have no way of specifying that `sep=""`. The `x=` is just to suppress the output of `NULL`. * uses `pi` and `T` and arithmetic for indexing, and `n=pi^2` for a close enough approximation to `9`. [Answer] # [Mornington Crescent](https://github.com/padarom/esoterpret), 5015 bytes, cracks [Discrete lizard's answer](https://codegolf.stackexchange.com/a/207731/46076) I've braved the depths of London, and I came out alive ... ``` Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Moorgate Take Northern Line to Finchley Central Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Moorgate Take Northern Line to West Finchley Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Northern Line to Golders Green Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Northern Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Moorgate Take Northern Line to Morden Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Circle Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Metropolitan Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Moorgate Take Northern Line to Kentish Town Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Tottenham Court Road Take Northern Line to Tottenham Court Road Take Central Line to Holland Park Take Central Line to Fairlop Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Tottenham Court Road Take Northern Line to Tottenham Court Road Take Central Line to Holland Park Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Paddington Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Mansion House Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Tottenham Court Road Take Northern Line to Tottenham Court Road Take Central Line to Holland Park Take Central Line to Gants Hill Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Tottenham Court Road Take Northern Line to Tottenham Court Road Take Central Line to Holland Park Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Moorgate Take Metropolitan Line to Moor Park Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Finchley Road Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Preston Road Take Metropolitan Line to West Harrow Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Mornington Crescent ``` [Try it online!](https://tio.run/##7VjBbsIwDL3zFT7ttq@oBJUGE5rQdrZaj0aEGDlGaF/fRStCbFS0BaKVbmc7sf3sF9tZszjjlsruMRPyGTktywWuCJ5ZtCBxMDWOQBmSAiWoQiLs/aheZ8YsS1SqxImRzFI74RzzvHKkxdkTu2PjssLSByQhAEE7ujyE7mE2iGekwhu2RvGbFfvOTuEBpqhmTXJGucHcG3k9IDCsyOehJkNJwAtjfjlAE7Y5iYeJELneA3SbmBvEccKNRvizwugEm7Hkd1A48Zn1Iw2vJlMWg9cmcGhkvKTG7oyQJ3afQuM1voAF72IzZcGq5ApcQ8Jb0aPcdFDdDwoHzZStRZcHFGRVrzFGI5Y39cL2hjp4f@eA9RqTaL2p4WzT1ei8Ce9NyltPvX1Xf6mgJujUQ2qs/Sfh8EkYk2Xt2vURrN2Ho/71@@uHxsOafc3UOERgWo6JX5t6iiK8Gzh6t1gv/tAKW7dy7v/lgu/Vv9yoLD8B "Mornington Crescent – Try It Online") [Answer] # [BBC BASIC II](http://www.mkw.me.uk/beebem/), cracks [Martin Rosenau's challenge](https://codegolf.stackexchange.com/questions/207558/print-x-without-x-cops-thread/207619#207619) The string to print is ``` VP ``` Solution: ``` 10 MODE 7 20 A%=HIMEM 30 ?A%=80 40 A%?1=86 50 GOTO 50 ``` Tested on BeebEm emulator and should work directly on BBC model 'B'. [![enter image description here](https://i.stack.imgur.com/ZxJbr.png)](https://i.stack.imgur.com/ZxJbr.png) How? * [MODE 7](http://beebwiki.mdfs.net/MODE_7) is a low-resolution graphics mode, intended to display 'teletext'. Each character on the display is encoded by a single byte in memory: bytes 1-128 encode the normal ASCII characters, and bytes 129-255 (which we don't need here) encode chunky coloured and/or flashing 2x6 pixel blocks. So all we need to do is to set the first two bytes of the display memory to encode 'PV' * HIMEM is a system variable used to indicate the address of the highest usable RAM memory location +1; the display memory starts here. * `?` stores the specified value at a particular memory location. It's equivalent to `POKE` in other variants of BASIC. In this case, we specify the ASCII value 80, encoding the letter 'P'. * `A%?1` is a shortcut to store the specified value to the memory location +1. We use 86, encoding the letter 'V' * If we exit the program now, the first character will be overwritten by the new command-line prompt (a '>' character), so we just send the program into an endless loop so that the full beauty of the displayed 'PV' characters can remain on the screen for our admiration. * In the example shown, I exited the program by pressing 'Escape' so that I could display a LISTing of the program. [Answer] # [Mornington Crescent](https://github.com/padarom/esoterpret), 15909 bytes, cracks [Discrete lizard's second answer](https://codegolf.stackexchange.com/a/207860/46076) The battle for London is on, and I have been proven as the victor ``` Take Northern Line to King's Cross St. Pancras Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Cannon Street Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Northern Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Northern Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to Westbourne Park Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take District Line to Plaistow Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Bakerloo Line to Stonebridge Park Take Bakerloo Line to Oxford Circus Take Bakerloo Line to Oxford Circus Take Victoria Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take District Line to Parsons Green Take District Line to Cannon Street Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Aldgate Take Circle Line to Euston Square Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Tooting Bec Take Northern Line to Bank Take Circle Line to Bank Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Kennington Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take District Line to Parsons Green Take District Line to Cannon Street Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Baker Street Take Circle Line to Blackfriars Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Barbican Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Paddington Take District Line to Southfields Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take District Line to Parsons Green Take District Line to Cannon Street Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Edgware Road Take Circle Line to Bank Take Circle Line to Wood Lane Take Circle Line to Sloane Square Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Wood Lane Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Colindale Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Mile End Take District Line to Victoria Take District Line to Victoria Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Circle Line to Cannon Street Take Circle Line to King's Cross St. Pancras Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take District Line to Parsons Green Take District Line to Cannon Street Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Aldgate Take Circle Line to Paddington Take Circle Line to Baker Street Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Edgware Road Take Circle Line to Paddington Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Paddington Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Mornington Crescent ``` I realized about 2/3 of the way through writing this program that I was using an inefficient approach and the code was about twice as long as it needed to be, but that doesn't matter since there's no value to short robber answers. [Try it online!](https://tio.run/##7VvNchoxDL7nKXzrKX2HQjM9JLRMN9OcxVqAh400kb1J3z51SEPS0v2jmGWDLsywkrWSLX2SLLhlIUeLwHSeC/ocKTw@XsMKzVeWsEQhc@UITWBzGfk@eDMW9t5k4aOZAuUC/mzN/sPlgcXBhj3DeySTOR9QqnheHjyTx07yAtsRx0DEUXwQxNBi@R7UayB/jqIkPtmQJy5qc0G2gpx0de3eTZhlAQFbELecYLwEiX7w2wvOdvGUjuydD76TuI6q/mH@8K1vFneDPsy4lPhtCrI6TKSdYCgl87e07jFkcckOZAS0qnCmaQHxET@08jWNJI2k9xtJr1Hy17sqCVOw9rlWTbTu2Oxoo88ofkjB/AoSUS7OxNnF25S9xfbt55zFrt9d@vY8XWtkhSyFLIWsdwdZ24UNiGfy5ks8jyqeHnr2/V4ptNi3AxSVbZX6VNhKdLooYxUabb0rQbAHD@wl2vo3qafg1BytOXrQHfXx7uABYGA4AJugnLlmDk92jDDf3QoFRAVExddhlFqXSPR25R501WjXaNdo1/b/tNr/9W1urTkF5Kt53A7xCpsKm9o1nu7t87HoIzOXAykaKRopuPXdsm35aMZlWM4dFtbrtYrGqMaoNlraaD3NUu3iAQTNdwbbbeUNszVXQP9GjazgSOpvRqvzV52/al7URKbz16GU8PX5JNHwdlexdRvMhSMLBeoISBFYO5NTRTdtfvprfoaT9Op@5tqYmxpGZP@X@hobw0SZNUFGnmz@Jh4P9@Vv4r8A "Mornington Crescent – Try It Online") [Answer] ## JavaScript, cracks [PkmnQ's third answer](https://codegolf.stackexchange.com/questions/207558/print-x-without-x-cops-thread/209531#209531) Outputs a string via `console.log`. You can evaluate arbitrary code with only a little extra work. Should work in any sufficiently modern JavaScript implementation; `/_/.prototype.unicode` must be `false` (`true` would work with minor modifications). [Try it online!](https://tio.run/##7VvLTsMwELzzHb2ifFAasRVwgENBgLhU6a@HAKlUWse11zsbF41KUR@JvS/Pzm7t583n5v3@7en143b78vA4DG3Xymo3/o0v2q7rpd1Pj64Zn127//4fedmH706@PzbU7Aznt8pBj11vIsU0TIJgzao5M2GeNiaSYhUOmTykSHQeSbwupJZGsbMxReaC3TxcjbzC4MoOrotj4WSgyyB4IJ1IRBiU6qbQEzAn0YhoRDS6ejQa39/9rmeSz39GPmlpLPYleuPSdX@/o@dgnouRGEIf627W3cQMMl3W3ay7iUZEI7oMXHf3Pwt5@qA/1AmpyvbSkMqSypLKMriYPEhlSWWJRkQjuqwuKqtQd57Xlm3xSqezQPADBAHD2@PnASYoJigmqCve4yChFBXLPev1eM1pNivOBkdzZTd8ghKp5p0ZLUvwsHhH5rXgAqdj2nhBo0GyaCWBYBtgYQkzhdJ4R28Cn/BXLLt4LGDHLA73xNkclpw1DujkuKSoNcYrHRKFpMCXFpGYDXhGZq8SKs2CXuUA0NJXWrs6m6JDwAzZMaiCJSGgxWRqAggngCm/fMbUJ6cyDRSFAnBda7ltOSs2w72a8LfWrKui2ZZJY15D7Yrx6UXUlenN8ciQE@m7NvAS3BSfoxHtS8qXMhEC7RxTvF@9tFBa02UDl3ymJbEodDePAu2yimhumf0dO8cLtkG9@hRVcNoqSqv62qOV83xsOXlNTSavvkh23YFzNrD7BSw6lmqaWnTY62uvm/9240eZCofiJjZuYuMmNm5i4yY2usx3ExsPBvJgIA8GMriYJHgwkAcDiUZEI7qskoOBhV2VI5I7TilyMwxf "JavaScript (Node.js) – Try It Online") The code is too big to include directly. Here's the Python code I used to generate it. ``` #!/usr/bin/env python3 import re payload = '<("MrJock,TVQuizPHDBagsFewLynx.mRjOCKtvqUIZ=phd#bAGSfEWlYNX? 12+34-56*78^90%!\')>' zero = '~~[]' # 0 one = '~[]/~[]' # 1 def plus_one(n): return '~[%s][~~[]]/~[]' % (n,) def unary_integer(n): assert(n >= 0) if n == 0: return zero s = one while n > 1: n = n - 1 s = plus_one(s) return s def integer_string(n): if n <= 9: return '`${' + unary_integer(n) + '}`' else: return ''.join(['${' + unary_integer(int(digit)) + '}' for digit in str(n)]) def integer(n): if n <= 9: return unary_integer(n) else: return '`' + integer_string(n) + '`/~[]/~[]' # Map a character to how it can be inserted in `...` characters = {} def encode_string(s): return ''.join(['`'] + [characters[c] for c in s] + ['`']) def encode_string_literal(m): return encode_string(m.group(1)) def encode_string_literals(code): return re.sub(r'"([^"]*)"', encode_string_literal, code) permitted_characters = (frozenset(''.join(map(chr, range(32, 127)))) .difference(payload)) for c in permitted_characters: characters[c] = c characters['`'] = '\\`' characters['$'] = '\\$' characters['\\'] = '\\\\' for c in range(10): characters[str(c)] = '${' + unary_integer(c) + '}' def add_characters(raw_code, result): encoded_code = encode_string_literals(raw_code) for i in range(len(result)): this_code = '${`${%s}`[%s]}' % (encoded_code, integer(i)) if result[i] not in characters or len(result[i]) > len(this_code): characters[result[i]] = this_code add_characters('[][[]]', 'undefined') add_characters('{}', '[object Object]') add_characters('[]/[]', 'NaN') add_characters('~[]/[]', '-Infinity') add_characters('/$/["unicode"]', 'false') # +'ls' add_characters('``["includes"]``', 'true') # +'r' add_characters('``["fontcolor"]``', '<font color=""></font>') # +'"<=>' add_characters('``["constructor"]', 'function String() { [native code] }') # +'()Sgv' add_characters('~[~[~[]/~[]][~~[]]/~[]][~~[]]/~[~[]/~[]][~~[]]', '1.5') # +'.' eval_prefix = encode_string_literals('[]["find"]["constructor"]`_${') eval_suffix = '}```' def eval_with_function(code): return eval_prefix + encode_string(code) + eval_suffix def octal_string(s): return ''.join('\\%03o' % (ord(c),) for c in s) print(eval_with_function('console.log("%s")' % (octal_string(payload),))) ``` The basic principle is the same as [JSFuck](https://github.com/aemkei/jsfuck#readme): build integers, then build some strings containing interesting characters, extract the characters from the strings, and assemble those characters to get an “eval” gadget. Leverage automatic coercions to integers and strings. Due to the different character set, the details of the building steps are different. A lot of things coerce to 0 when a number is expected, for example `[]`. To get a number, we need to force a coercion to a number, which we can do with the bitwise negation operator `~`, so the easiest integer to build is -1 = `~[]`. Then 0 = `~~[]`. Signed integers are represented with two's complement, so `~x` = `-x-1` and thus `x+1` = `~x/-1`. We actually need to apply this plus-one operation to an expression that has a lower precedence than the `~` operator, so we need to simulate parentheses: plus-one is `~[…][0]/-`. Armed with 0 and plus-one, we can build all integers in unary. As a shortcut, we'll use the decimal representation for numbers above 9. This is our first use of [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), which this character set supports fully. Template literals are string literals written between backticks, with `${…}` to inject expressions. This lets us concatenate strings without `+`. For example a 2-digit integer is ``${digit1}${digit2}`/-1/-1`. When the goal is to inject the integer into a string, we don't need the `/-1/-1` part. Next we build some strings. [JSFuck](https://github.com/aemkei/jsfuck/blob/master/jsfuck.js) provides some inspiration. For example, `{}` stringifies to `[object Object]`. Here we can't use `+` to coerce to a string, but we can use a template literal: for example ``${{}}`` evaluates to the string `[object Object]`. We can extract individual characters from a string as `string[index]`. The normal way to access a property of an object is `object.property`, but `.` is forbidden. Fortunately there's another way which not only permitted, but also allows using a constructed string as the property name: `object["property"]` is equivalent to `object.property`. Looking through built-in types for which we can build a value ([`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) `[]`, [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) `{}`, [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) `[~[]][~~[]]`, [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) ````, [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) `/$/`), the pickings are slim at this point: ``` Array.prototype.concat() Array.prototype.find() Array.prototype.join() RegExp.prototype.unicode String.prototype.concat() ``` Fortunately [`/_/.unicode`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) is `false`, which gives us `l` and `s`, which unlocks the [`String` method `includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes), which gives us `true`. The string representation of a method gives us parentheses, and the exotic but convenient [`fontcolor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fontcolor) provides `"<=>`. At this point we have a variation of the classic [eval gadget from JSFuck](https://github.com/aemkei/jsfuck#functioncode--evaluate-code): first we take a reference to a method such as `[]["find"]`. Its constructor `[]["find"]["constructor"]` is `Function`, and calling `Function` with a string argument evaluates that string as the body of a function. We have the characters of `return`, so we can make the function return the value of any expression that we can spell as a string. There's one more hurdle here: unlike JSFuck, [we don't have parentheses](https://portswigger.net/research/executing-non-alphanumeric-javascript-without-parenthesis). This is where we use another feature of templates: if you put a function just before a template literal, with no punctuation involved except for the template literal, it's called on the interpolated expressions from the template. The arguments have to be strings, but that's good enough for us. To evaluate the string `code` we call `Function` on the code to build the function and call that code with an empty string as an argument: `Function `_${`return ${code}`}` ``` . At this point we can spell `console.log("…")`. We're allowed to use backslashes, so we can put octal escapes in `…` and print an arbitrary string. The backslashes are just a shortcut: without them, we could still build `fromCharCode` as in JSFuck. If we wanted an arbitrary eval gadget, we could do another round of evaluation. [Answer] # [Python 3](https://docs.python.org/3/), 552040 bytes, cracks [M Virts' second answer](https://codegolf.stackexchange.com/a/218085) ``` getattr(__builtins__,str().join(chr(e)for e in((not not...).__sub__((not...).__sub__(not not...)).__sub__((not...).__sub__(not not...)).__sub__((not...)... ``` [Try it online!](https://tio.run/##7dsxjsIwEAXQnlOk9EiRGw5kAQoQhBKUOAWnDxEV3AChV2yx0aum8Mz/q30863Uc9ut66eqh1imVclz6e@2HuZR23j5Evo39kE7XKXVxHqema7Zf0zDWZvvJOUcuZV6Opbw/fn34QBRFURRFURRFURT1o6oVcimKoiiKoiiKoiiKotQ2FEVRFEVRFEVRFCXkUhRFURRFURRFUX8bTCMi@b9xiqIoiqIoiqIoiqL89ZyiKIqiKIqiKIqiKEqlQVEURVEURVEURVHCN0VRFEVRFEVRFEVRqgOKoiiKoiiKoiiKoij1CEVRFOVZpyiKoiiKoiiKoighl6IoiqIoiqIoiqIo1QFFURRFURRFURQlvoqvFEVRFEU5egyPoijKg01RFEVRFEVRFCWOGQtFURRFURRFURRFUeoRY6EoiqIoiqIoihLHKIqiKIqiKIqiKIpSHVAURVEURVEURYljxkJRFEVRFEVRFEVRFKW2oSiKoihrkKIoiqIoiqIoihI5DY@iKIqiKIqiKEocoyiKoiiKoiiKoihRmKIoiqIoiqIoShyjKIqiKIqiKIqiKIpSaVAURVEURVEURYljhkdRFEVRFEVRFEVRFKW2oSiKoihrkKIoiqIoiqIoiqKEXIqiKIqiKIqiKHGMoiiKoiiKoiiKoiiKUttQFEVRlDVIURRFURRFURRFUaIwRVEURVEURVGUOEZRFEVRFEVRFEVRFEWpbSiKoijKsqQoiqIoa5CiKIqiKIqiKEocoyiKoiiKoiiKoiiKotQ2FEVRFGVZUhRFUZRlSVEURVEURVEUJY4ZC0VRFEVRFEVRFEVRlNqGoiiKoixLiqIoirJSDY@iKIqiKIqiKEocoyiKoiiKoiiKoiiKUtsYC0VRFEVZlhRFURRl8VIURVEURVEURYljhkdRFEVRFEVRFEVRFKW2oSiKoijLkqIoiqIo65miKIqiKIqiKEocoyiKoiiKoiiKoiiKotQ2FEVRFGVZUhRFURRliVMURVEURVEURYljFEVRFEVRFEVRFEVRlNqGoiiKoixLiqIoiqKseoqiKIqiKIqiKHGMoiiKoiiKoiiKoiiKUttQFEVRlGVJURRFUZSDgKIoiqIoiqIoShyjKIqiKIqiKIqiKIqi1DYURVEUZVlSFEVRFOVsoCiKoiiKoiiKEseMhaIoiqIoiqIoiqIoSm1DURRFUZYlRVEURVGOC2OhKIqiKIqiKIoSxyiKoiiKoiiKoiiKotQ2ahuKoiiKsiwpiqIoiqIoiqIoYZKiKIqiKIqiKEocoyiKoiiKoiiKoiiKotQ2FEVRFGVZUhRFURRFURRFUSInRVEURVEURVEUJY5RFEVRFEVRFEVRFEWpbSiKoijKsjQWiqIoiqIoiqIoSjClKIqiKIqiKIoSxwyPoiiKoiiKoiiKoihKbUNRFEVRliVFURRFURRFURRFia8URVEURVEURVHiGEVRFEVRFEVRFEVRFKW2oSiKoijLkqIoiqIoiqIoiqKEXIqiKIqiKIqiKHGMoiiKoiiKoiiKoiiKUttQFEVRlGVJURRFURRFURRFUaIwRVEeM48ZRVGePMOjKMrDaCwURVGeT4qiKI8sRVGUp9hTTFEURVEURVEUJY5RFEVRHmyKoijKiqAoiqIsEoqiKMpSMhaKoijKgqMoiqIoa5CiKIqiLEvDoyiKoigrlaIoiqIsXoqiKIqirGeKoiiKssQNj6IoiqKseoqiKIqiHAQURVEURTkbDI@iKIqiKMcFRVEURVFOEIqiKIqiKIcKRVEURVHOGcOjKIqiKMrRQ1EURVEU5TQyPIqiKIqiKAcURVEURVGUM4uiKIqiKMoxZngURVEURVFONoqiKIqiKMphR1EURVEURTn/KIqiKIqiKEciRVEURVEU5ZSkKIqiKIqiHJwURVEURVEU5SylKIqiKIqiHK/GQlEURVEURTlxKYqiKIqiKMohTFEURVEURVHOZYqiKIqiKIqiHNUURVEURVEU5fSmKIqiKIqiKAe6A52iKIqiKIqinPEURVEURVEURTn2KYqiKIqiKIoSCSiKoiiKoiiKEhwoiqIoiqIoihIvDI@iKIqiKIqiKCGEoiiKoiiKoihRxfAoiqIoiqIoihJoKIqiKIqiKIqixB6KoiiKoiiKoijhiKIoiqIoiqIoSoSiKIqiKIqiKIoStAyPoiiKoiiKoihKHKMoiqIoiqIoihLHDI@iKIqiKIqiKEpooyiKoiiKoiiKokQ7iqIoiqIoiqIoSkykKIqiKIqiKIqixFfDoyiKoiiKoiiKoihBnqIoiqIoiqIoiqIoNYThURRFURRFURRFURSlrKAoiqIoiqIoiqIoilK1UBRFURRFURRFURRFUQoZiqIoiqIoiqIoiqIotQ1FURRFURRFURRFURSl3KEoiqIoiqIoiqIoiqJUQBRFURRFURRFURRFUZSiiKIoiqIoiqIoiqIoilInURRFURRFURRFURRFUUonw6MoiqIoiqIoiqIoiqJUUxRFURRFURRFUeIYRVEURVEURVEURVEUpbahKIqiKMpBQFEURVEURVEURVGiMEVRlAfb8CiKov768Y@I3bq@AA "Python 3 – Try It Online") Truncated here because of SE limitations. The TIO link has the full version, or you can see it [as a gist](https://gist.github.com/pxeger/5c3a7455bc28dde592d43e0962aa1812). * `not...` (`...` is a special sentinal value in Python, and it's truthy) gives `False` which is equivalent to `0` * `not not...` gives `True` which is equivalent to `1` * we can't use `+` or `__add__`, so to get an integer we use `0-(-1)-...` or `(not...).__sub__((not...).__sub__(not not...))...` Other than that, it's the same method as Wheat Wizard's crack for the previous one, but a lot longer. I'm pretty sure this isn't an intended crack, since it's so similar. It could be shortened, but this isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The program was generated using this script: ``` def get_int(a): return "(not not...)" + ".__sub__((not...).__sub__(not not...))" * (a - 1) def get_str(s): return "str().join(chr(e)for e in(" + ",".join(get_int(ord(e)) for e in s) + ",))" print("getattr(__builtins__," + get_str("exec") + ")(" + get_str(r"""print(end='\t\n\x0b\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f!"#$%&\'*+-/0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`dkpqvwxyz{|}~\x7f')""") + ")") ``` [Answer] # [International Phonetic Esoteric Language](https://esolangs.org/wiki/International_Phonetic_Esoteric_Language), cracks [@bigyihsuan's answer](https://codegolf.stackexchange.com/a/207571/81278) ``` {32}χu{33}χu{34}χu{35}χu{36}χu{37}χu{38}χu{39}χu{40}χu{41}χu{42}χu{43}χu{44}χu{45}χu{46}χu{65}χu{66}χu{67}χu{68}χu{69}χu{70}χu{71}χu{72}χu{73}χu{74}χu{75}χu{76}χu{77}χu{78}χu{79}χu{80}χu{81}χu{82}χu{83}χu{84}χu{85}χu{86}χu{87}χu{88}χu{89}χu{90}χu{91}χu{92}χu{93}χu{94}χu{95}χu{96}χu ``` To my knowledge, the only way to test this is with the interpreter [here](https://github.com/bigyihsuan/International-Phonetic-Esoteric-Language). [Answer] # [R](https://www.r-project.org/), 209 bytes, cracks Robin Ryder's [answer](https://codegolf.stackexchange.com/a/207586/67312) ``` dput(intToUtf8(c(59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,86,87,88,89,90,91,92,93,94,95,96,97,98,101,103,104,106,107,108,109,113,114,115,118,119,120,121,122,123,124,125,126))) ``` [Try it online!](https://tio.run/##FczHVgJBEIXhh3ExM@fcRXfPTIWjmBNiFjMGRMwCQmPWVx/Lxbf576kaVhOddkzH8Uaa/XovpsnkVG16ZnZufmFxaXlltb7WWN/Y3Nre2d07ODw6Pjlttc7OLy7bV93bu4fHp@eX4ej17f3j8@v75zfJMOoOagmSrLoejGN634vN/r69TjtpqSAH8qAAykEFqAQRiEECUrADe3AA5@ACXIIJzGABK8RBPCRAcghBGCIQhTqohwZoDi2gJZSgDBV4501uCkOGzX9XeG/dW/elseatBWfsJgRje7A92B4oy7Kq@gM "R – Try It Online") Found the right output function `dput` by using `apropos` on the remaining alphabet characters. `dput` also happens to be a key element of an R quine. [Answer] # C, cracks [xibu's answer](https://codegolf.stackexchange.com/a/207637/95792) ``` #include <stdio.h> int main(void) <% if (printf("%c%c", 123, 59)) <% %> %> ``` For some reason, you can use `<%` instead of `{` in C. You can also use `printf` inside an if block to avoid having a single statement with a semicolon. [Try it online!](https://tio.run/#c-gcc) ]
[Question] [ An *uninteresting number* (which I totally didn't make up only for this challenge) is created like this: > > 1. Take a positive integer N > 2. Create a new number O by adding the digits of N at the end of N > 3. The final uninteresting number is O\*N > > > For example for N=12: > > 1. O = 1212 > 2. O\*N = 1212 \* 12 > 3. Final number is 14544 > > > # Input A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input. # Output The corresponding uninteresting number. # Test cases ``` 1 -> 11 2 -> 44 3 -> 99 10 -> 10100 174 -> 30306276 ``` # Scoring Shortest Code in Bytes wins. [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` Ы* ``` **Explained** ``` Ð # triplicate input « # conactenate * # multiply ``` [Try it online](http://05ab1e.tryitonline.net/#code=w5DCqyo&input=MTI) [Answer] ## JavaScript (ES6), 10 bytes ``` _=>(_+_)*_ ``` Needs to be called with the argument as a `String`, not a `Number`. ### Usage: ``` (_=>(_+_)*_)('3') 99 ``` -3 bytes thanks to [@Quill](https://codegolf.stackexchange.com/users/41519/quill)'s suggestion. [Answer] # Java 8, ~~29 26 25~~ 21 Bytes God bless lambda ``` c->new Long(c+""+c)*c ``` ~~c->Long.decode(c+""+c)\*c;~~ [Answer] ## vim, 11 ``` C<C-r>=<C-r>"<C-r>"*<C-r>"<cr> ``` crcrcrcrcr... ``` C change (delete and enter insert mode) until the end of the line <C-r>= insert an expression via the special "expression register" <C-r>" insert the contents of the default register (what we just C'd) <C-r>" ... again * multiplied by <C-r>" the input (again) <cr> insert the result of this expression ``` [Answer] # Pyth, ~~5~~ 4 bytes ``` *s+` ``` Explanation: ``` Q input ` representation, basically str(Q) + Q add Q to its own string form s parse int * Q multiply by input print ``` [Test it here](http://pyth.herokuapp.com/?code=%2As%2A2%60&input=12&test_suite=1&test_suite_input=1%0A2%0A3%0A10%0A174&debug=1). [Answer] # Emacs, 17 bytes `(``\*``SPACE``C-SPACE``C-E``M-Y``SPACE``C-Y``C-Y``)``C-J` ### Explanation * `(``\*``SPACE` adds `(*` at point (before the number); * `C-SPACE``C-E``M-Y` Select and copy the number; * `SPACE` adds a space character at point (after the number); * `C-Y``C-Y` pastes two times the number at point; * `)` adds `)` at the end; * `C-J` interprets the line as a LISP expression and prints its result. ### Exemple Cursor represented by a pipe (`|`) * `|174` * `(``\*``SPACE` `(* |174` * `C-SPACE``C-E``M-Y` `(* 174|` * `SPACE` `(* 174 |` * `C-Y``C-Y` `(* 174 174174|` * `)` `(* 174 174174)|` * `C-J` ### Result ``` (* 174 174174) 30306276| ``` [Answer] # Python 2.7, 21 bytes: ``` lambda f:int(`f`*2)*f ``` Well, this has to be the shortest Python answer I have ever written in the shortest amount of time ever. It's an anonymous lambda function that can be executed by naming it anything you want and then calling it like a normal function wrapped in `print()`. For instance, if your input is `12`, and the function was named `H`, this this would be called like `print(H(12))`. [Try It Online! (Ideone)](http://ideone.com/DPWJQ8) Note that this only works for values up and equal to `9223372036854775807` since any higher value and `repr()` puts a `L` at the end of the integer. Therefore, for values greater than `9223372036854775807`, this **24 byte** version would be the one that works: ``` lambda f:int(str(f)*2)*f ``` [Try This Online! (Ideone)](http://ideone.com/OUZGUo) [Answer] # C#, 19 23 bytes ``` n=>int.Parse(""+n+n)*n; ``` # Without strings, 47 bytes ``` n=>{int i=1;while(i<=n)i*=10;return(i+1)*n*n;}; ``` [Answer] ## Jelly, 4 Bytes ``` ;DḌ× ``` [Try it online](http://jelly.tryitonline.net/#code=O0ThuIzDlw&input=&args=MTc0) ## Explanation ``` ;DḌ× Main link. argument : N D Decimal; Yield the digits of N ; Concatenate N and its digits Ḍ Convert to integer; We get O × Multiply O and N ``` [Answer] # J, 7 bytes ``` *,~&.": ``` ## Explanation ``` *,~&.": Input: n ": Format n as a string ,~&. Reflect and join the string to make "nn" and parse the string to get a number * Multiply that number by n ``` [Answer] # C, ~~70~~ ~~68~~ ~~54~~ ~~53~~ ~~52~~ 44 ``` f(n){return(pow(10,(int)log10(n)+1)*n+n)*n;} ``` Previous version (48 bytes, no math functions), saved 16 bytes thanks to @LeakyNun, 1 byte thanks to @FryAmTheEggman, 4 bytes thanks to @TobySpeight: ``` f(n,d,i){for(i=d=n;d;d/=10)i*=10;return(i+n)*n;} ``` Call `f()` with one argument, the number, and it returns the corresponding uninteresting number. ## Test program ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { while (*++argv) { int n = atoi(*argv); printf("%d -> %d\n", n, f(n)); } return 0; } ``` ## Test results: ``` $ ./84712 1 2 3 4 10 174 1 -> 11 2 -> 44 3 -> 99 4 -> 176 10 -> 10100 174 -> 30306276 ``` [Try it online!](http://ideone.com/Ighcg1) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 7 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⊢×#⍎⍕,⍕ ``` `⍕` string representation `⍕,` prepend string representation `#⍎` make into number (in root namespace) `⊢×` multiply by original number [Answer] ## [Retina](https://github.com/m-ender/retina), ~~27~~ 20 bytes ``` ^ $_$*: $_ : $_$*: : ``` Gets a bit slow for large inputs, because before the last the stage the result is represented in unary. [Try it online!](http://retina.tryitonline.net/#code=JShHYApeCiRfJCo6ICRfCjoKJF8kKjoKOg&input=MQoyCjMKMTAKMTI) (The first line enables a linefeed-separated test suite.) ### Explanation I'll use `2` as an example input (because the unary representations get a bit unwieldy for larger inputs). **Stage 1: Substitution** ``` ^ $_$*: $_ ``` By matching the beginning of the string with `^` we simply prepend some stuff. `$_` refers to the input string itself and `$*:` means we insert that many colons. So we get: ``` :: 22 ``` **Stage 2: Substitution** ``` : $_$*: ``` Now we match every `:` and again replace it with `$_$*:`. Of course, this time `$_` doesn't evaluate to an integer (but to `:: 22` in our example), but `$*` just looks for the first decimal in the string, so this evaluates to the input concatenated to itself (`O` in the challenge specification). We'll end up with `N*O` colons, followed by `O`: ``` :::::::::::::::::::::::::::::::::::::::::::: 22 ``` **Stage 3: Match** ``` : ``` All that's left is counting the `:`s to convert from unary back to decimal, which is exactly what this stage does. [Answer] # [CJam](https://sourceforge.net/p/cjam/wiki/Home/), 8 bytes ``` ri_`_+i* ``` [**Try it online!**](http://cjam.tryitonline.net/#code=cmlfYF8raSo&input=MTI) ``` r e# Read input i e# Convert to integer _ e# Duplicate ` e# Convert to string _ e# Duplicate + e# Concatenate i e# Convert to integer * e# Multiply. Implicitly display ``` [Answer] # Jelly, ~~8~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṘẋ2v× ``` [Try it online!](http://jelly.tryitonline.net/#code=xZLhuZjhuosydsOX&args=MTI) ## Explanation ``` ŒṘẋ2v× - Main link. Left argument: the number to convert × - Multiply v - an evaluation of the left argument ŒṘ - converted to string ẋ - multiplied by 2 - two and the left argument ``` [Answer] # Awk, 13 bytes ``` $0=($0$0)*$0 ``` Set the line to 2 of itself multiplied by itself [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` :?c:?*. ``` ### Explanation ``` :?c Concatenate Input to itself :?*. Output is that concatenation times Input ``` [Answer] # Python, 42 bytes Pure arithmetic approach, without strings! ``` f=lambda n,m=1:m<=n and f(n,m*10)or-~m*n*n ``` [Ideone it!](http://ideone.com/vtE7wa) [Answer] # Matlab / Octave, 20 bytes ``` @(x)eval([x x 42 x]) ``` This is an anonymous function that takes the input as a string. Example use: ``` >> f = @(x)eval([x x 42 x]) f = @(x)eval([x,x,42,x]) >> f('12') ans = 14544 ``` Or [try it online with ideone](http://ideone.com/AmRGvN). ### Explanation The code builds a string by concatenating the input string twice, then the character `*` (that has ASCII code 42), then the string again. The concatenated string is then evaluated. [Answer] ## Lua, 20 Bytes Takes in a command-line argument, and outputs via STDOUT ``` a=...print((a..a)*a) ``` And ungolfed as @LeakyNun asked in the comment :) ``` a=... -- alias for the first argument print( (a..a) -- concatenate a with itself, equivalent to a:rep(2) *a) -- multiply the resulting number by a ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` tVthU* ``` [**Try it online!**](http://matl.tryitonline.net/#code=dFZ0aFUq&input=MTI) ``` tV % Input number implicitly. Duplicate and convert to string th % Duplicate and concatenate the two equal strings U % Convert to number * % Multiply ``` [Answer] ## zsh, 13 bytes ``` <<<$[$1$1*$1] ``` Takes input as a command line argument, outputs to STDOUT. This only works in zsh, but here's **15 bytes in Bash** using `echo` instead of `<<<`: ``` echo $[$1$1*$1] ``` [Answer] ## Perl, 11 bytes ``` $_*=$_ x2 ``` + the `p` and `l` flags. (run with `perl -ple '$_*=$_ x2'`) -2 bytes thanks to pipe. [Answer] ## Excel VBA, 35 Bytes Sub called with number, msgbox returns answer ``` Sub B(a) MsgBox (a & a) * a End Sub ``` **Alternative Excel VBA, 42 Bytes** Number given in formula, returns answer. ``` Function B(a) B = (a & a) * a End Function ``` [Answer] ## Pyke, ~~5~~ 4 bytes ``` `+b* ``` [Try it here!](http://pyke.catbus.co.uk/?code=%60%2Bb%2a&input=12) ``` ` - str(input) + - ^+input (convert to string implicitly) b - int(^) * - ^*input ``` Also 5 bytes with string inputs ``` +bRb* +]mbB ``` [Answer] # PHP, ~~25~~ 24 bytes Short opening tags are useful for surprisingly few golfing challenges, luckily this is one of them. Unfortunately operator precedence is the opposite of the order you need to do them in so lots of brackets are needed. ``` <?=($a=$argv[1])*"$a$a"; ``` edit: I realised that seeing as how I'm using brackets anyway I can effectively skip the concatenation operator by changing the written order of the operations around. [Answer] # dc, ~~11~~ 10 bytes ``` ddZAr^1+** ``` I *knew* that eventually I would find a use for the `Z` command! Operation is fairly simple - count the digits, take 10 raised to that power and add one. This gives a multiplier that concatenates the number with itself. Then just multiply. I/O uses the stack, as usual for dc. ## Full program This is what I used for the tests: ``` #!/usr/bin/dc ? ddZAr^1+** p ``` The two extra commands give us pipeline I/O. ## Tests ``` $ for i in 1 2 3 10 174; do printf '%d -> ' $i; ./84712.dc <<<$i; done 1 -> 11 2 -> 44 3 -> 99 10 -> 10100 174 -> 30306276 ``` Thanks are due to Sir Biden XVII (1 byte). [Answer] # Mumps, 11 bytes ``` R I W I_I*I ``` This is one of those rare golf challenges where the idiosyncrasies of Mumps can come in very handy. First, all variables are strings, and all math equations are strictly evaluated left-to-right (as in: not PEMDAS), so 1+2\*4=12 in Mumps instead of =9 the way PEMDAS would. So, (barely) ungolfed: ``` R I ; Read from stdin to variable I W I_I*I ; Write out I concatenated with I, then multiplied by I. ``` Word of caution - because the flavour of Mumps that I'm using (InterSystems Ensemble) does not echo the carriage return for stdin, the input and output number will appear concatenated. To rectify that / increase readability, you'd need to add two bytes and add a manual CR/LF, thusly: ``` R I W !,I_I*I ``` However, as I didn't see that requirement in the rules of the challenge, I'm pretty sure that I'm good with the shorter code. If I'm mistaken, please feel free to LART me and I'll modify my answer. :-) [Answer] # PowerShell, ~~25~~, 18 bytes Thank you TessellatingHeckler for reminding me how much PS loves the pipeline. New 18 bytes: ``` process{$_*"$_$_"} ``` Old 25 bytes: ``` param($a);[int]"$a$a"*$a ``` Explanation: ``` # new process{$_*"$_$_"} process{ } # runs code block once for each passed item $_* # multiple the first parameter "$_$_" # concatenate as a string for ease # in this case, the order does the typecasting for us # old param($a);[int]"$a$a"*$a param($a) # assigns the first passed parameter to variable $a ; # line terminator [int] # type cast string "$a$a" to int32 "$a$a" # convert $a$a to string for easy concatenation *$a # multiply by $a ``` Testing (save as boring.ps1): ``` # new 12 | .\boring.ps1 14544 174 | .\boring.ps1 30306276 # old .\boring.ps1 12 14544 .\boring.ps1 174 30306276 ``` Definitely not the winning answer, but fun regardless! [Answer] ## Batch, ~~27~~ ~~20~~ 18 bytes ``` @cmd/cset/a%1%1*%1 ``` Edit: Saved 7 bytes thanks to @TessellatingHeckler. Saved a further 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ. ]
[Question] [ # Challenge You must output the current time continuously (until cancelled by an interrupt), once every second, by any of the following means: * It must be in 24-hour or AM/PM format. + If it is the former, it must be spaced out with colons (i.e. 15:47:36). + If it is the latter, it must be spaced out with colons and have the AM/PM following (i.e. 3:47:36 PM) * It may be pulled from the internet. * It may be the system time. * It must output any naturally accessible form of output which supports text that you choose. * Output may have extra information aside of the time in it, but you *must* guarantee one, and only one, output of time per second. * The continuous output must be a second apart - if you choose to wait until the second changes between outputs, that is fine. If you wait a second between each output, that is perfectly acceptable, despite the eventual loss of accuracy. Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8). # Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=65020,OVERRIDE_USER=44713;function answersUrl(e){return"//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"//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;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] # Minecraft 1.8.7, 7 + 8 = 15 [blytes](https://codegolf.meta.stackexchange.com/a/7397/44713) (bytes + blocks) Only one command block involved: ``` xp 1 @p ``` Output goes to the client console like so: [![times](https://i.stack.imgur.com/TYtQk.png)](https://i.stack.imgur.com/TYtQk.png) As part of the normal output. This is the system: [![the system](https://i.stack.imgur.com/VqYkH.png)](https://i.stack.imgur.com/VqYkH.png) `xp` gives a specified amount of experience to a specified player with the syntax `xp <amount> <player>`. I'm pretty sure this is the smallest command that has singular output that I can get, now. [Answer] # JavaScript, 32 bytes ``` setInterval("alert(Date())",1e3) ``` Uses the fact that [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) evaluates code. This is not recommended, but when was that a concern in code golf? `Date()` returns the current time and date in a format like this (may vary per system). ``` Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) ``` [Answer] ## sh (+ watch), 11 bytes Script: ``` watch -n1 . ``` (no trailing newline) Output: ``` Every 1,0s: . (SPACES) Sat Nov 28 19:07:51 2015 ``` The amount of spaces depends on the terminal width. Tested on Debian8 and NetBSD7. [Answer] # [Snap](https://snap.berkeley.edu/snap/#open:http://snap.berkeley.edu/snapsource/tools.xml), ~~8~~ ~~7~~ 6 blocks [![](https://i.stack.imgur.com/XULyY.jpg)](https://i.stack.imgur.com/XULyY.jpg) (source: [cubeupload.com](https://i.cubeupload.com/TpGafK.jpg)) (Yes, I changed it in MS Paint because I was too lazy to make another screenshot. So what? At least it's readable.) click the script to run 24-hour clock. [Answer] ## Python 2, 47 bytes ``` from time import* while[sleep(1)]:print ctime() ``` No online link because ideone times out (huehuehue) before printing anything. Thanks to @xsot for the `while[sleep(1)]` trick and the `ctime` trick. Prints out the current date and time like so: `Fri Nov 27 21:23:02 2015` [Answer] # Javascript ES6, 43 39 bytes ``` setInterval(_=>console.log(Date()),1e3) ``` Works with my current time settings (which have not been changed for some time, thank you), at least. 4 bytes saved by Conor O'Brien. [Answer] # Perl, Command Line, 24 bytes ``` sleep(say)while$_=gmtime ``` This must be run from the command line, as `perl -E'sleep(say)while$_=gmtime'` (on windows, use double quotes instead). The date will be output along with the time, which [seems to be allowed](https://codegolf.stackexchange.com/a/65022). --- ## Perl, 25 bytes ``` sleep print$/.gmtime;do$0 ``` In a scalar context, `gmtime` will return a string similar to `Sat Nov 28 10:23:05 2015`. The result from `print`, always 1, is used as the parameter for `sleep`. `do$0` is used to execute the script again, after the timer has finished. [Answer] # [Arcyóu](https://github.com/nazek42/arcyou), 27 bytes ``` (@ t(pn(zz 1)(p(st %H:%M:%S ``` I had to kludge together two new functions for this challenge, `zz` and `st`. `pn`: Exactly like Lisp's `progn`. `zz`: Direct link to Python's `time.sleep`. `st`: Direct link to Python's `time.strftime`. Normally, quotes would be necessary around the format string, but since there are no spaces, it's parsed as a symbol. The interpreter evaluates undefined symbols as themselves, so we get a string. [Answer] # Bash, ~~51~~ ~~31~~ ~~24~~ ~~21~~ 20 bytes Thanks to @quartata for some very helpful comments. Thank you @Dennis for clarifications and for chopping off even more bytes. Thank you @VoteToClose for clarifying the rules (which apparently I am bad at reading) further reducing the bytes. `date` displays the the full date with a 24 hour clock. `sleep 1` sleeps for a second. `exec $0` loops the script infinitely. ``` date;sleep 1;exec $0 ``` [Answer] # Befunge 98, 53 bytes ``` v v>"EMIT"4(>H.8,':,M.8,':,S:.8,d, >:S- !!k^ ``` Notes: 1. This program does not zero-pad the numbers it prints. 2. This program prints a space and then a backspace character after every number, as the `.` command prints an implicit space at the end. 3. The size of the stack in this program grows every second, and thus it will eventually run out of memory. 4. This program will overwrite the previous time when it prints a new one. To make it print each time on a new line, change the `d` on the first line to an `a` [Answer] ## mIRC 7.49 ~~20~~ 16 Bytes ``` /timer 0 1 $time ``` [Answer] ## AutoHotkey, 50 bytes ``` x::Send,% a!=A_Sec? A_Hour ":" A_Min ":" a:=A_Sec: ``` Notes: 1. Requires you to hold `x` for continuous output. 2. Remove your finger from `x` to interrupt and end the output. 3. Output is in 24-hour format. [Answer] # C (on Linux x64), ~~179~~ ~~177~~ ~~175~~ ~~168~~ 159 bytes ``` #include<time.h> #include<sys/time.h> main(){struct timeval a;char b[9];for(;;){gettimeofday(&a,0);strftime(b,9,"%T",localtime(&a.tv_sec));puts(b);sleep(1);}} ``` Ungolfed: ``` #include <time.h> #include <sys/time.h> main(){ struct timeval a; char b[9]; for(;;){ gettimeofday(&a, 0); strftime(b, 9, "%T",localtime(&a.tv_sec)); puts(b); sleep(1); } } ``` Only tested on, and likely only functions on, linux x64 (x32 might work, but other platforms probably won't). The main difference between this program and the other posted C program is the use of linux-exclusive function calls, which, while terrible practice for real software, saves quite a few bytes...if you ignore all the compiler warnings. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), ~~14~~ ~~8~~ 7 bytes Crossed out 14 is a striked 1? Naw, it will never catch on ;) [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=VGFEI2B-Mg) Click run, do not click on anything else ^\_^ the page is highly... explosive. Yes. Fixed output system with update. ``` TaD#`~2 ``` (I added some constants, and `~1` to `~4` are powers of `10`.) ## Explanation ``` setInterval("alert(Date())",1000); T a D# ` ~2 ``` [Answer] # PHP, 37 bytes ``` <?=date('G:i:s');header('refresh:1'); ``` Outputs the formatted server time and sets the page to refresh every second. Of course, it depends on your internet connection and how fast-repsonding your server is :) [Demo](http://justachat.freevar.com/realtime.php) [![](https://i.stack.imgur.com/sj1oZ.png)](https://i.stack.imgur.com/sj1oZ.png) [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~27 18~~ 16 bytes ``` ':',¨⎕TS⋄→≢⎕DL 1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9JDM39b@6lbrOoRWP@qaGBD/qbnnUNulR5yIgz8VHwRCk5j9IEQA) `⎕TS` Y M D h m s t `':',¨` prepend : to each `⋄` new statement `⎕DL 1` wait a second and return actual waited time; 1.0something seconds `≢` tally the actual waited time, giving 1 `→` go to line (1 = this line) [Answer] ## [Perl 6](http://perl6.org), 29 bytes The *right* way to do this: ``` Supply.interval(1).tap: -> $ { say join ':',.hour,.minute,.whole-second given DateTime.now } await Promise.new; # halt this thread indefinitely ``` ``` 22:21:58 22:21:59 22:22:0 22:22:1 22:22:2 … ``` The golfed version ``` loop {sleep say join ':',now.polymod(1,60,60,24)[3…1]} # 56 bytes ``` ``` 3:59:26 3:59:27 3:59:28 3:59:29 … ``` Since the output doesn't have to be restricted to just the time, I can make it quite a bit shorter. ``` loop {sleep say DateTime.now} # 29 bytes ``` ``` 2015-11-27T22:18:10-06:00 2015-11-27T22:18:11-06:00 2015-11-27T22:18:12-06:00 2015-11-27T22:18:13-06:00 … ``` [Answer] ## R, 38 bytes ``` repeat{Sys.sleep(1);print(Sys.time())} ``` This outputs the current time in the following format: ``` [1] "2015-11-28 07:34:01 CET" ``` [Answer] ## Powershell, 19 bytes ``` for(){date;sleep 1} ``` [Answer] # VBA, 69 Bytes Getting the Time is easy, `now()` Only outputting every 1 second.... MUCH more verbose. This is the "Right" way of waiting 1 second in VBA. ***78 Bytes*** ``` Sub a():Debug.Print Now():Application.Wait Now()+TimeValue("0:0:1"):a:End Sub ``` Or if you want to Cut some Corners and only being right 86% of the time is good enough ***63 Bytes*** *adding one SigFig take you to 95% accurate and a third will get you to 99.36%* ``` Sub a():Debug.Print Now():Application.Wait Now()+1e-5:a:End Sub ``` If you want to get the above method to 100% then you need ***69 Bytes*** `(1/86400)` ``` Sub a():Debug.Print Now():Application.Wait Now()+(1/86400):a:End Sub ``` All of these methods would stumble on a leap second Beacuse they do not wait for 1 second, But wait untill 1 second. At midnight when the clocks fall back an hour this clock will stop for 1 hour and then pick up where it left off. VBA does allow for the Sleep Method but your byte couter is Ruined. ***97 Bytes*** ``` Declare Sub Sleep Lib "kernel32" (ByVal k as Long) Sub a():Debug.Print Now():Sleep(1e3):a:End Sub ``` [Answer] # JavaScript, ~~47~~ ~~38~~ 35 bytes ``` for(p=1;t=Date();p=t)t!=p&&alert(t) ``` ## Explanation Continuously checks if the time has changed then `alert`s if it has. ``` for( p=1; t=Date(); p=t ) t!=p &&alert(t) ``` [Answer] # AppleScript, ~~51~~ 35 bytes ``` repeat log current date delay 1 end ``` Pretty dang obvious. Prints the current date, which contains the time, delays a second, then continues. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 13 chars / 25 bytes ``` Ĥ⇀ôᶁ⬮+⬬),1𝕜) ``` `[Try it here(Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=&code=%C4%A4%E2%87%80%C3%B4%E1%B6%81%E2%AC%AE%2B%E2%AC%AC%29%2C1%F0%9D%95%9C%29)` This is surprisingly readable. [Answer] # Dyalog APL, 36 bytes Not very short this time. ``` {⎕←1↓∊'⊂:⊃,ZI2'⎕FMT 3↑3↓⎕TS⋄∇⎕DL 1}1 ``` This outputs 24-hour time, i.e.: ``` 14:37:44 14:37:45 14:37:46 ... ``` Explanation: * `{`...`}1`: define a function and call it (the argument is ignored, but we need the function in order to call it recursively) + `⎕TS`: a system function that returns the current date and time, in the format *year - month - day - hour - minute - second - millisecond*. (`⎕TS` = **t**ime**s**tamp) + `3↑3↓`: drop the first 3 items (i.e. year - month - day) and then take the first 3 items that are left (hour - minute - second). + `'⊂:⊃,ZI2'⎕FMT`: format each number as a two-digit integer (`I2`) with leading zeroes (`Z`), prefixed by a colon (`⊂:⊃`). (This results in a matrix.) + `∊`: Get all the elements in the matrix, in row order. (This gives a vector, in this case a string.) + `1↓`: drop the first character (which is an extra `:`) + `⎕←`: output it + `⎕DL 1`: then wait one second (`⎕DL` = **d**e**l**ay) + `∇`: call the function recursively [Answer] # QBasic, 18 bytes ``` ?TIME$ SLEEP 1 RUN ``` [Answer] # Haskell, ~~98~~ ~~96~~ 85 bytes ``` import GHC.Conc import Data.Time m@main=getCurrentTime>>=print>>threadDelay(10^6)>>m ``` Alternate version using do notation: ``` main = do time <- getCurrentTime print time threadDelay 1000000 main ``` Gets the current time with `getCurrentTime` from the `Data.Time` library, then pipes it into `print`, waits 1,000,000 microseconds (1 second) and calls itself. Thanks to nimi and Mauris! [Answer] # Batch - 34 ~~40~~ bytes I love built-in variables: ``` :A //Set label A echo %time% //Print the time in 24 hour format timeout 1 //Wait 1 second (thanks DavidPostill) goto A //Jump back to A and repeat ``` There definitely needs to be some `sleep` command in Batch anytime soon. [Answer] ## Python 3, 99 Bytes Apologies if it formats the code weird, doing this from an ipad. (dont ask). I know this code is big considering some of the other answers, but I didn't see a python one yet so I wanted to add it in. ``` import time import datetime while(True): print(datetime.datetime.now().time()) time.sleep(1) ``` [Answer] # Java, ~~300~~ ~~166~~ ~~137~~ ~~125~~ 124 bytes ~~Nearly~~ More than halved thanks to VoteToClose, Paülo Ebermann and janschweizer! ``` interface A{static void main(String[]a)throws Exception{for(;;Thread.sleep(1000))System.out.println(new java.util.Date());}} ``` Ungolfed: ``` interface A { static void main(String[] a) throws Exception { for (;; Thread.sleep(1000)) System.out.println(new java.util.Date()); } } ``` [Answer] ## Perl, 99 81 75 51 40 36 29 27 bytes ``` sleep(print gmtime.$/);do$0 ``` ]
[Question] [ ## Introduction We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! **So given `F_n` your job is to find `n`.** ## Specification ### Input Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence. ### Output The output must be a non-negative integer as well. ### What to do? The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as `F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)` and you're given `F(n)` and must return `n`. ### Potential Corner Cases 0 is a valid in- and output. If given "1" as input you may either output "1" or "2", as you prefer. You may always assume that your input actually is a fibonacci number. You may assume that the input is representable as a 32-bit signed integer. ### Who wins? This is code-golf so the shortest answer in bytes wins! Standard rules apply of course. ## Test-cases ``` 0 -> 0 2 -> 3 3 -> 4 5 -> 5 8 -> 6 13 -> 7 1836311903 -> 46 ``` [Answer] ## Actually, 1 byte ``` f ``` Yes, there's a builtin for this, [since November 16, 2015](https://github.com/Mego/Seriously/commit/239b5cc6b71b22e96e5ced7ac3ba34ee499ae3e3). [Try it online](http://actually.tryitonline.net/#code=Zg&input=OA) --- For fun, without the builtin, it's 9 bytes: ``` ‚ïó1`F‚ïú=`‚ïìi ``` [Try it online!](http://actually.tryitonline.net/#code=4pWXMWBG4pWcPWDilZNp&input=OA) Explanation: ``` ‚ïó1`F‚ïú=`‚ïìi ‚ïó push input to register 0 1`F‚ïú=`‚ïì push list containing first value x (starting with x = 0) where: F fib(x) ‚ïú= is equal to the input i flatten the list ``` [Answer] # Mathematica, 25 bytes ``` InverseFunction@Fibonacci ``` Function. Pretty self-explanatory if you ask me. [Answer] # Python, ~~36~~ ~~34~~ 32 bytes ``` lambda n:len(str(66*n**6))//1.24 ``` ### Previous versions: ``` f=lambda n:len(str(66*n**6))//1.24 f=lambda n:(n*n*7).bit_length()//1.4 ``` ## Explanation The core idea is to invert the formula ``` fibonacci(n) ~ ( (1 + sqrt(5)) / 2)**n / sqrt(5) ``` which tells us that ``` log fibonacci(n) ~ n log((1 + sqrt(5)) / 2) - log(sqrt(5)) ``` to get ``` f(n) ~ (log(n) + log(sqrt(5))) / log((1 + sqrt(5))/2) ``` The golfing optimizations are: * Use `len(str(n))` to compute log base 10 without importing `log` (old version used `.bit_length()` to compute log base 2) * Raise `n` to a power, so that the approximation of the logarithm can distinguish between successive Fibonacci numbers * Multiplying by a constant scales up the values to get them in the correct range Then the divisor was truncated to as little precision as I could manage and the multiplier chosen to give the correct results for all 32-bit fibonacci numbers. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes Code: ``` √ÖFg ``` Explanation: ``` √ÖF # Generate all Fibonacci numbers <= input. g # Get the length of this list. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4VGZw&input=MTgzNjMxMTkwMw). [Answer] # Julia, ~~27~~ ~~26~~ 18 bytes ``` !n=log(3n+.7)√∑.48 ``` This uses the inverse of [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding), with just enough precision for 32-bit integers; it actually works up to **F(153) = 42,230,279,526,998,466,217,810,220,532,898 > 2105**. [Try it online!](http://julia.tryitonline.net/#code=IW49bG9nKDNuKy43KcO3LjQ4Cgpmb3IgbiBpbiAoMCwgMSwgMiwgMywgNSwgOCwgMTMsIDE4MzYzMTE5MDMsIDQyMjMwMjc5NTI2OTk4NDY2MjE3ODEwMjIwNTMyODk4KQogICAgQHByaW50ZigiJTMydSAtPiAlM3VcbiIsIG4sICFuKQplbmQ&input=) ### How it works Binet's formula states the following. ![Binet's formula](https://i.stack.imgur.com/2ONm9.png) Restricting **F** to the set of Fibonacci, the map **n → Fn** has a [right inverse](https://en.wikipedia.org/wiki/Inverse_function#Left_and_right_inverses) **F → nF**. We have that ![right inverse of Binet's formula](https://i.stack.imgur.com/HtjEn.png) and all that is left to do is dealing with the edge case **0**. Since the input is restricted to 32-bit integers, we can use short decimal literals instead of the constants in the formula. * **log φ = 0.481211825059603447… ≈ 0.48** Unfortunately, **0.5** isn't precise enough. * **√5 = 2.2360679774997896964… ≈ 3** That might seem like an awful approximation at first glance, but we're taking logarithms and since **log 3 - log √5 = 0.29389333245105…**, the result before rounding will be off by a small constant factor. * **0.5 ≈ 0.7** Because of the excess from the previous approximation, we could actually omit this term altogether and still get correct results for **F > 0**. However, if **F = 0**, the logarithm will be undefined. **0.7** turned out to be the shortest value that extends our formula to **F = 0**. [Answer] # Jelly, ~~14~~ 11 bytes ``` 5¬Ω√ól√òp+.·∏û¬ª0 ``` [Try it online!](http://jelly.tryitonline.net/#code=NcK9w5dsw5hwKy7huJ7CuzA&input=&args=OA) This is my first ever Jelly answer! This uses the algorithm [from the MATL answer](https://codegolf.stackexchange.com/a/85573/31716). Thanks to Dennis for shaving off 3 bytes! Explanation: ``` l√òp # Log Base phi 5¬Ω # Of the square root of 5 √ó # Times the input + # Plus . # 0.5 ·∏û # Floored ``` This gets the right answer, now we just need to handle the special case of '0'. With '0' as an arg, we get `-infinity`, so we return ``` ¬ª # The maximum of 0 # Zero # And the previous calculated value. ``` [Answer] # JavaScript, ~~54~~ ~~50~~ ~~69~~ ~~50~~ 42 bytes ``` b=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c ``` Surely it isn't going to win, just for fun :) ~~Ok, checking for zero consumes 19 bytes. WTF?~~ Stupid-me. --- Demo! To see the last test case, you have to scroll the console a bit. ``` a=b=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c; console.log('0: '+a(0)); console.log('2: '+a(2)); console.log('3: '+a(3)); console.log('5: '+a(5)); console.log('8: '+a(8)); console.log('13: '+a(13)); console.log('1836311903: '+a(1836311903)); ``` Thanks @edc for shortening by 8 bytes. [Answer] # [Perl 6](http://perl6.org) ~~¬†33 30¬†~~ 27 bytes ``` ~~{first \*==$\_,:k,(0,1,\*+\*...\*>$\_)} {first \*==$\_,:k,(0,1,\*+\*...\*)}~~ {first $_,:k,(0,1,*+*...*)} ``` [Try it](https://tio.run/nexus/perl6#ZZDPboJAEMbvPMUcjIKuZGeBBTSanvoEvRnT4LpUggLKYjXGx@7Z7q6tbdPbb/58M/NN10o4cl9MnU7Ti2zV1HF2Z@jnxWpcVGt5ghncLnlxaBX0XsmkJC4lSIajoe/7Q@96081PSuta3eg6ABRmc6BEEzMUGAoMhYYiQ5GhxBA3hLYcW0wCHiCm9K64lxmjFDkNMUKGSczjwGpTOxrTOKQsDhmmCU8YC5DHtmrXBVHIWJiECcYp45hiRGN7AlJ9oqe9NtusgtGXgxGgTuX14dvSeK5NgwuTUp7dXlE1nfIITI7ZtpNuT54aKZRce@DBRW8Tu2Zcl/B43Y@iv5D745LAQ0LAfyta5Vwd55/qz4MX@lK6/DXCxAQG7/WhbKFrQNU2pTYgt3InKwV1Ds/Fqq4yIQpo5b6TlZCD20dVj0UmNvIT "Perl 6 ‚Äì TIO Nexus") ### Explanation: ``` # lambda with implicit ÔΩ¢$_ÔΩ£ parameter { first # find the first element $_, # where something is equal to the block's argument :k, # return the key rather than the value # of the Fibonacci sequence ( 0, 1, * + * ... * ) # ^--^ first two values # ^---^ lambda used to generate the next in the series # ^-^ generate until # ^ Whatever } ``` ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; # using the safer version that stops generating # values bigger than the input my &fib-index = {first $_,:k,(0,1,*+*...*>$_)} my @tests = ( 0 => 0, 2 => 3, 3 => 4, 5 => 5, 8 => 6, 13 => 7, 1836311903 => 46, 1836311904 => Nil, # this is why the safe version is used here 12200160415121876738 => 93, 19740274219868223167 => 94, 354224848179261915075 => 100, ); plan +@tests + 1; for @tests -> $_ ( :key($input), :value($expected) ) { cmp-ok fib-index($input), &[eqv], $expected, .gist } cmp-ok fib-index((0,1,*+*...*)[1000]), &[eqv], 1000, 'works up to 1000th element of Fibonacci sequence' ``` ``` 1..13 ok 1 - 0 => 0 ok 2 - 2 => 3 ok 3 - 3 => 4 ok 4 - 5 => 5 ok 5 - 8 => 6 ok 6 - 13 => 7 ok 7 - 1836311903 => 46 ok 8 - 1836311904 => Nil ok 9 - 12200160415121876738 => 93 ok 10 - 19740274219868223167 => 94 ok 11 - 354224848179261915075 => 100 ok 12 - works up to 1000th element of Fibonacci sequence ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1+√ꬰ0 ¬¢i ``` [Try it online!](http://jelly.tryitonline.net/#code=MSvDkMKhMArComk&input=&args=MTM) Note that this approach is too inefficient for the last test case. ### How it works ``` ¬¢i Main link. Argument: n ¬¢ Call the helper link niladically (i.e., without arguments). This yields the sequence of the first n positive Fibonacci numbers, i.e., [1, 1, 2, 3, 5, ...]. i Find the first index of n (1-based, 0 if not found). 1+√ꬰ0 Helper link. No arguments. 1 Set the left argument to 1. 0 Yield 0. +√ꬰ Add both arguments, replacing the left argument with the sum and the right argument with the previous value of the left argument. Yield the array of all intermediate values of the left argument. ``` [Answer] ## Pyke, 5 bytes ``` .f.bq ``` [Try it here!](http://pyke.catbus.co.uk/?code=.f.bq&input=8&warnings=0) ``` .f - first number where .b - fib(n) q - ^ == input ``` [Answer] ## Python, 29 bytes ``` g=lambda n:n>.7and-~g(n/1.61) ``` Recursively divides the input by the golden-ratio approximation 1.61 until it's below 0.7, and outputs the number of divisions. For 0, the code outputs `False`, [which equals 0 in Python](http://meta.codegolf.stackexchange.com/q/9064/20260). This can be avoided for 2 bytes ``` g=lambda n:n//.7and 1+g(n/1.61) ``` [Answer] ## JavaScript, 22 bytes ``` n=>Math.log(n)/.48+2|0 ``` [Answer] ## JavaScript (ES6), ~~39~~ 33 bytes ``` f=(n,j=0,k=1)=>n>j?f(n,k,j+k)+1:0 ``` Even with ES7, the inverse Binet formula takes 47 bytes: ``` x=>Math.log(x*5**.5)/Math.log(.5+1.25**.5)+.5|0 x=>Math.log(x*5**.5)/Math.log((1+5**.5)/2)+.5|0 x=>Math.log(x*(p=5**.5))/Math.log((1+p)/2)+.5|0 ``` [Answer] ## Sage, 49 bytes ``` lambda x,s=sqrt(5):x and int(log(x*s,(1+s)/2)+.5) ``` Thanks to TuukkaX for the suggestion about saving `sqrt(5)` as `s` to shave off a few bytes. [Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSVSo0Cm2LS4sKtEw1bSqUEjMS1HIzCvRyMlP16jQKtbRMNQu1tQ30tTWM9Xk5eLlKigCyiqkaaRlJuXnJSYnZ2oYGhhoagIAwWAXHw==&lang=sage). This approach using an inverse of Binet's formula offers several improvements over the previous approach: it's faster (constant-time versus quadratic time), it actually works for larger inputs, and it's shorter! Python users may wonder why I'm using `sqrt(5)` instead of the shorter `5**.5` - it's because `5**.5` is computed with C's `pow` function, and loses precision due to floating point issues. Many mathematical functions (including `sqrt` and `log`) are overloaded in Sage to return an exact, symbolic value, which don't lose precision. [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` t?5X^*17L&YlYo ``` [**Try it online!**](http://matl.tryitonline.net/#code=dD81WF4qMTdMJllsWW8&input=MTgzNjMxMTkwMw) This uses [an inverse of Binet's formula](https://mathoverflow.net/questions/39124/fibonacci-sequence-inversion), and so it's very fast. Let *F* denote the *n*-th Fibonacci number, and *œÜ* the [golden ratio](https://en.wikipedia.org/wiki/Golden_ratio). Then [![enter image description here](https://i.stack.imgur.com/jVhN5.png)](https://i.stack.imgur.com/jVhN5.png) The code uses this formula with two modifications: * Instead of adding 1/2 and then rounding down, the code simply rounds towards the nearest integer, which takes up fewer bytes. * Input *F*=0 needs to be treated as a special case. ### How it's done ``` t % Take input F implicitly. Make a copy ? % If (copy of) F is positive 5X^ % Push sqrt(5) * % Multiply by F 17L % Push phi (predefined literal) &Yl % Two-input logarithm: first input is argument, second is base Yo % Round towards nearest integer % Else the input, which is 0, is left on the stack % End if implicitly % Display implicitly ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 90 bytes *Written in conversation with [flawr](https://codegolf.stackexchange.com/users/24877/flawr) in chat.* ``` F-N-A-B:-F=A;N>0,M is N-1,C is A+B,F-M-B-C. F/N/I:-N=I,F-N-0-1;J is I+1,F/N/J. F/N:-F/N/0. ``` [Try it online!](https://tio.run/##HYxLCoQwEAX3nsK9/ZI0gcEPERIhEMG@hAsRBhx04fGjmV3Bq3q/8/geG657zzlC4BF6ROcHGQ0t9X7VAqapgG8CRSwImFQVtejUQ1yikhnwMBcpNUxlm//Ke/WyUTlzaz@WuTNWi6rWBw "Prolog (SWI) ‚Äì Try It Online") ### Ungolfed Here's a less-golfed version: ``` fib(F,0,F,_). fib(F,N,A,B) :- N>0, M is N-1, C is A+B, fib(F,M,B,C). fibindex(F,N,N) :- fib(F,N,0,1). fibindex(F,N,I) :- J is I+1, fibindex(F,N,J). fibindex(F,N) :- fibindex(F,N,0). ``` The `fib/4` predicate (`F-N-A-B` in the golfed version) takes a number `N` and two accumulators `A` and `B` (which should start at `0` and `1`) and unifies `F` with the `N`th Fibonacci number. If `N` is `0`, `F` is simply the current value of `A`, the smaller accumulator value. Otherwise, count `N` down by one and recurse with new accumulator values `B` and `A+B`. `fibindex/3` (`F/N/I` in the golfed version) takes a Fibonacci number `F` and an index `I` (which should start at `0`) and unifies `N` with the Fibonacci index of `F`. Either `F` is the `I`th Fibonacci number, in which case `N=I` and we're done, or we count `I` up by one and recurse. Note that this approach leads to infinite recursion if given a non-Fibonacci number, but we don't have to handle that case for this challenge. Finally, `fibindex/2` (`F/N`) just calls `fibindex/3` with an initial `I` value of `0`. [Answer] # Regex (.NET), ~~23~~ 19 bytes ``` (\2?(\1)|x$|^x|\b)* ``` [Try it online!](https://tio.run/##RY5BboMwFET3nOILfQk7FBRadRPLaqSue4KQSsb5CZYAIxsESsi2B@gRexHqtovOZkYzize9ncj5mppmRScPji40H3e7jia2T1ZWPr6wsuDLjMv7vJQV36zJ/iF@tW1vGjrFXOBVbkV0to4hQxUyVrIQaOSWC0CTNQRPzz8pTTncIgjCFiSgy9/UoGvyLJmTDSoufkdzZnjlt8mZgbLa@uEeCIWA/wKyzoZ/jekIYlTw9fEJgd3mF2fH3h@KY65VP4yOfK7t2A08/sNqiSo8URKrYFUqUYvovn4D "PowerShell ‚Äì Try It Online") Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the capture count of group `\1`. This is based on [Martin Ender's .NET regex for matching Fibonacci numbers](https://codegolf.stackexchange.com/questions/126373/am-i-a-fibonacci-number/126405#126405). The .NET feature of balanced groups is used to count the number of iterations taken by the loop. * That regex is first initially translated to use `x` as its unary numeral, yielding `^$|^(^x|(?>\2?)(\1))*x$`. * Then the `x$` at the end is moved inside as the extra alternative `|x$`, incrementing the loop count by \$1\$ for all \$n>0\$. This also allows us to remove the `^$|` at the beginning, because `^(^x|(?>\2?)(\1)|x$)*$` will now match \$n=0\$ on its own. (It will also now match numbers that are \$0\$ or \$1\$ less than a Fibonacci number, but we don't care because as specified by the challenge, all inputs will be Fibonacci numbers.) * Then the extra alternative `|\b` is added to increment the loop count again for all \$n>0\$; `\b` cannot match on an input of \$n=0\$ because there is no word character (`[0-9A-Za-z_]`) to form a boundary with the absense of a word character, but it will always match at the end of a string of one or more `x`s. The match is zero-width, so the loop will then be terminated. * Then we remove the `^` and `$` anchors sandwiching the regex, because we don't need to return a non-match for non-Fibonacci numbers. * Then an optimization for speed, moving the `^x` alternative as far to the end as possible, because it only has to match once, and would add a failed match to every subsequent iteration if ordered as the first alternative. * The `\2?` can lose the `(?>`...`)` atomic group around it, because we don't need to determine if a number is Fibonacci or not. Due to the lack of any assertions following the loop, it will simply keep the first match it finds at each iteration, not having any reason to backtrack. **27 byte** version that matches iff the input is a Fibonacci number: ``` ^((?>\2?)(\1)\B|x$|^x|\b)*$ ``` [Try it online!](https://tio.run/##RY9BboMwEEWvYlkjYYcaQboLchO1654AiESJEyw5tmUbgQJse4AesRehpFHV5Zv5evPHml443wqlFnC8cOIihmq306Inh2g5ErJ/Kbd7SsqMlq/TANNxmMoPuoElOjzhN3O1UokTpjnceJqfjRN10xJQSGoEUtsu0BFqDop5q2TADOfyTKBOGtPpwFRA23sg5lAXaTWvAgKaF1KH6neSg2ZK/HF25zim491x5eCS9zo0rfAkGqINaPrY3OjYOxkEa40P89osy/8ZMW3W95TUAmHQ6PvzC8FqSy7OdNavN5KmtqFzwj9KUjzP85Ky7DlNfwA "PowerShell ‚Äì Try It Online") The `\B` prevents numbers \$1\$ less than a Fibonacci number from being matched; in unary, `\B` matches at every place except the beginning and end in a non-zero number (and matches "everywhere" in an input of zero). # Regex `üêá` (PCRE1 / PCRE2 v10.34 or earlier), 20 bytes ``` ^(\2?(\1)|x$|^x)+|^x ``` [Try it online!](https://tio.run/##dVNtb9owEP7Or7hma4mJW0HRpongVlvXaR9YOyEqbQIaGeOEqMGJnGTQt6/7AfuJ@yFjlzihdC8RJOfz3XN3z2OLJDkMhNi8CJWI8rmEfiK0PFqcNMSCa/CS8RQYDK13q9XNrJt/vb39Mlq8Xi3szbU9OT61Jx3ysH75cL0mDr425M84i0IrYV7idNzGU400m4dxUWTXpUMVPPeFMXolX/4dd9IIVQYJmpkntY61LWKVZlA23VrKNOWBJPdYp9cTGAD9PlTewiz9Us0jF7TMcq2g4z42cpWGgZJziGIVmBdX6Upqt6y2vPUEj6I4z@yCo3rhzaJY3EBLELg34Y6zhW0jbJnLQ2VjQAPwScY4RCSVnZDDzpS1XTANmdEgEcyyT3uWi5bDEvOxiH16hv89gv4cIbvHXgZxkVzgB2iU2LtAoUryrEjXElpaurDLEZKSZNpka5nmUWbsgk3fT2VGAYfDLoNsYXbib1JksR53p6YUojIwTMTLJIwk0nIkPCxuEwqfz4bn3vvL0dvBAB7M6mr04Q2FA1PZGHWpNjGYoQ/2npak5s8vJfZtHAujKVgFUNmjBo4tlemwP@/BfjpReNh2ME2dCnhXMWz7SUuz7eMJKmbkrE1nrEMFvUMrLOnts@4r5I5xytmMzhwmaOg4tZh113cEkO2CW7s5UU3iwh3ruFD1b@3P4ef3H4Adctwy5wT7qFQrHiNLik4lV2Y15k5n6uLBXeJAdkqhuW4agHTMp2wn2ShY6yHXUthaUri4GgwoYCJHistfJSKFLnGf9W8Q@m04OKjR9pjR7Xw4vBx6F5ef3o7OPpJt1va4iYJTvFXWeaGL9YQro1T@P7wiob6OfpSni39MVE352ChV7xm5tJTYMdnes@oENx43v4Qf8SDdHEYFFb8B "C++ (gcc) ‚Äì Try It Online") - PCRE1 [Try it online!](https://tio.run/##hVXvbtpIEP/OU0zcu2QXTA@IWkUYJ8oRpERqSUWJrldCrWW9BqvGtux1SdLmax/gHvEe5Ljx7gJOyOksMLOzM7@dP78deJo255yvX/kiCGMBH/qjQcfrX18MvJvh1dj74@pifAkntVdhzKPCF9BLeSY6rxenNb5gGXjpZAoujKzfV6uvs@Piz/v7T@PF29WCrL@Q284ZuW3TH3e//PhyRxv4WtPndpYN9dT10kbbqRySyyyM5@UpO12YoFaw5eme3WktjCWkKEpPZFmSEZ7EuQQVYX0p8pzNBYXvufS7XY4W0OuBUZei0ovYjxzIhCyyGNrO4x5mueaJL2yYJUkEiRuwKC9h1TEGbtJ583bq1ACfMACiiuXNhcHwjBXROERX@6Z/eT46qVOzaUMePogkINvAf9toKvaUUnVK@ZAEznQSPCkkdGGbKC3Ts5QbqAi6YD1LXjlbFnpZt7FFt/UIoiJf6Ey2Rak91oo4D@ex8CFK4rl@sThficxRBVvee5xFEYZhcjcrbxYl/CvUuQ3fktCHus8kw9qVRSpFcF0g5U6dHu4wqMFuNLadaZnOLFkYEwRQAaYTJEIkYpLSZnvqthydgmYHpNy1yFnXclBquKn@sSg56@P3gKK@QMTjjiexqehbws9RUNBVoDBOC1m6q8SwhVDPxGa9ZJIvPJVLfSdrtEzkRSRt3QLHXLKPV58HShMEucBNzBdTmMvFE4N68k1wiV6mE3jZNucv0zASxJDi44fxiKb8NfcwWEJtg/F5MLr2xoPR@6vh@XhwsVEPPo0Hw4tyfahiMr8mkhbdMfggQwKa2ldvg3obu0rq7l41PFwzKbwgS5ZeyqQUWUwyZPnw5t07A1D1wasrxZ3EIm4k96V9A0v2UDCDLQU3EHaFl/ZLPHsOoI@KwmVYBWm2qVMx8kUq/9coE7zI8jCJXzRUxwZmuDC3Zc/cts3tB5RCRcWee/zGAe4ym7kze9ZwuR02Ghveb5r0QAGZWc4hcnQbH2EAD27b0f0KiPWrD3///Atw1DLc0lcKq2oYXj56UuaojMVKryas0Z46OCmWmAbJbTi6O9IA@YRN3YqzZvfTNqkOV6mJAAyZpT47cqBs6kGdJxlpzF4LDg8N/oFrqDsaXY@84fX783H/cjcDVf8q/NxcOZkVooItcGQ/8dmNTRx8pjQvjMDy8UUkpAD8w8u18vG/yItkF4LsUtu/FNpgu6bVqaI38d5th55OBsfv@h8eRGyer5uRsm@e/As "C++ (gcc) ‚Äì Try It Online") - PCRE2 v10.33 Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.) This is a straight port of the .NET version to the `üêá` output format. It needs to be anchored, so that the only variation in how a match can happen is how many iterations the loop takes, not where in the string it starts. The `*` is changed to `+` because with the former, looping for 0 iterations would still be a match, and would result in a 1-indexed return value. Moving the `|\b` alternative to the end as `|^x` is a minor speed optimization, at a zero-byte cost. As an added bonus, we can change this to `|^xx` to return \$1\$ (instead of \$2\$) for an input of \$1\$. For PCRE1, and PCRE2 before v10.35, the atomic group is not needed even with `üêá`-output, because those versions automatically atomicize groups that contain a nested backreference (in this case, `\1`). # Regex `üêá` (Perl / PCRE), 23 bytes ``` ^(\2?+(\1)|^x)+|^x|^xxx ``` [Try it online!](https://tio.run/##HY1NCsIwEIWvEsJQElJqq7ixjkWqW1cuiyEtCoVqS3AR@@PSA3hELxJHYXiPx/fBdGfbLP31wcCmbGjayjQMZilNXO@2x@1mYpfWCjAYh1BiEkKNMeF6jYsldYVgQqJQElYIFQlKyQFy0gR33IGR@JyJbAVWiiwblII8jCf5e9IHQWfr250XN55Cj0nK/puBiTj7vN6MR5CTOBKatN4fdlr7kyjmmRJFIseTk4qCzjnvvw "Perl 5 ‚Äì Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=LY09CsJAEIWvsiyD7LJRE0UQ4xgk2lpZBsMaFALxh0VhNcbSA9jaWGhp7VlsPYmjBob3eHwfzOW2npns-nosdgyMz_JsleiMQd2nid1Bf9zvFWy-MgI0ug5M0XMgRZdw2sVmizpB0A5RmBJWCAkJSskcQtIEt9yClnisi6ADRoogyJWC0HEL-X2yr1TWJl1ueLTkPuzR89lvM9A1zt6nM-M1CEk8ECrieDgaxPF9u5lX28-JiBqBEpEnDxMrFQWdtX96LavsDw "Perl - Attempt This Online") - Perl v5.36+ [Try it online!](https://tio.run/##dVNtb9owEP7Or7hmarGJW0HRpomQVl3XaR9YOyEqbQIaBeOEqMGJ7GTQt6/7AfuJ@yFjlzihdC9RCOfz3XN3z2PzND0MOd@8iiSP87mAfsqVOFqcNPjCV@Cl4ym4MLTerVa3s27@9e7uy2jxZrUgmxsyOT61yaRDH2/W1MYPvuv1hv4ZajFopa6X2h2n8VxGZ/MoKersulQkw5e@KEGv8Jd/x500IplBimbmCaUSRXgidQZl362l0NoPBX3AOr0exwDo96HyFmbpF3IeO6BElisJHeepkUsdhVLMIU5kaD6@1CuhnLLa8s7jfhwneUYKmuqFN4sTfgstTuHBhNv2FraNsGWuH0mCAQ3AJx3jELGQJKWHnanbdsA0ZEaDlLsWOe1ZDlq2m5o/i5LTc/ztUfTnCNk99jJIiuQCP0SjxN4FimSaZ0W6EtBSwoFdjpCUNFMmWwmdx5mxCzaDQIuMAQ6HXYbZwuwk3wTPEjXuTk0pRHXBMJEs0ygWSMsR97A4oQw@nw8vvPdXo7PBAB7N6nr04S2DA1PZGHWpNjWYUQBkTwla8xeUEgcEx8JoBlYBVPaowMeWynTYn/dgX08kHrYdTFOnAt5VDNt@1tJsB3iCihl9t81mbodxdo9WVNLbd7uvkTvXZ747YzPb5Syy7VrMuut7Csh2wS1pTmSTOnDvdhyo@rf25/Dz@w/ADn3cMucE@6hUKx4ji0anFCuzGvt2Z@rgwV3iQEQzaK6bBkCP/am7k2wUrPUQa8GJEgwurwcDBpjoI8XlW4nIoEudF/0bhH4bDg5qtD3X6HYxHF4NvcurT2ej8490m7U9brzgFG@VdVHoYj3jiliL/4dXJNTXMYhzvfjHRNWUT41S9Z6RSwmBHdPtPatOcONp84sHsR/qzWFcUPEb "C++ (gcc) ‚Äì Try It Online") - PCRE1 [Try it online!](https://tio.run/##hVXvbuJGEP/OU0x8arIL5gpEd4owTpQSpES6IyeOqNcjnLWs12CdsS17fZC0@doH6CP2QUrHuws4IVUtMLOzM7@dP78deJo255xv3vgiCGMBn/qjQcfr314NvLvhzdj79eZqfA1ntTdhzKPCF9BLeSY6bxfnNb5gGXjpZAoujKxfVqvvs9Pit4eHL@PF@9WCbL6R@85Fg9y36R/f1rSBL/ys1xv60tSyoZ66XtpoO5VzcpmF8bw8aK8LE9QKtjw/sDuvhbGEFEXpiSxLMsKTOJeggqwvRZ6zuaDwey79bpejBfR6YNSlqPQi9iMHMiGLLIa283SAWa554gsbZkkSQeIGLMpLWHWMgZt03r2fOjXAJwyAqHp5c2EwPGNFNA7RBb/rX1@OzurUbNqQh48iCcgu8J@3moo9pVSdUj4kgQudBE8KCV3YJUrL9CzlBiqCLlgvklfOloVe1n1s0V09gqjIFzqTXVFqT7UizsN5LHyIkniuXyzOVyJzVMGWDx5nUYRhmNzNyptFCf8OdW7DjyT0oe4zybB2ZZFKEVwXSLlTp8d7DGqwG41dZ1qmM0sWxgQBVIDpBIkQiZiktNmeui1Hp6DZASl3LXLRtRyUGm6qfyxKLvr4PaKoLxDxtONJbCr6lvBzFBR0FSiM00KW7ioxbCHUM7FdL5nkC0/lUt/LGi0TeRFJW7fAMffs883XgdIEQS5wE/PFFOZy8cygnvwQXKKX6QTet@35yzSMBDGk@PxpPKIpf8s9DJZQ22B8HYxuvfFg9PFmeDkeXG3Vgy/jwfCqXB@rmMyviaRF9ww@ypCApvbV26Dexq6SuntQDQ/XTAovyJKllzIpRRaTDFk@vPvwwQBUffDqSrGWWMSt5L62b2DJAQpmsKPgFsKu8NJ@jWcvAfRRUbgMqyDNNnUqRr5I5f8aZYIXWR4m8auG6tjADBfmtuyZ27a5/YhSqKjYc0/fOcBdZjN3Zs8aLrfDRmPL@22THikgM8s5RE7u4xMM4NFtO7pfAbF@8uHvP/8CHLUMt/SVwqoahpePnpQ5KmOx0qsJa7SnDk6KJaZBchtO1icaIJ@wqVtx1ux@3ibV4So1EYAhs9RnTw6UTT2o8ywjjdlrwfGxwT9yDXVHo9uRN7z9eDnuX@9noOpfhZ/bKyezQlSwBY7sZz77sYmDz5TmlRFYPr6IhBSA/3m5Vj79F3mR7EKQfWqHl0Ib7Na0OlX0Jt673dDTyeD43fzDg4jN800zUvbNs38B "C++ (gcc) ‚Äì Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=hVXNbttGED4W0FOMGdTelahUkpHAEEULjizABhI5YGQ0jawQ1HIpEaFIglxGshtf8wC99pJLjzn3Wdpjn6TD3ZVEWy5K8Gd2dubbnZlvh79_Z2lU5OXjzhn7PjGaUcoy3mmeGNO_nGc-D8KYw9uBM-y4g6vzoXs9uhy7P1-ejy_gpPYsjFlU-Bx60un54rTGFl4GbjqZgg2O8Wq1-jQ7Ln65vX0_XrxcLcgfhQiaJ39-JDedfoPctOmXj2vawBfe67Wa_fuHPn3saJhQT203bbStyqq5yMJ4Xi6704UJarm3PN2zO62FsYAUReHyLEsywpI4FyC3XF_yPPfmnMKvufC7XYYW0OuBVpei1PPYjyzIuCiyGNrW_R5mOWaJz02YJUkEiR14UV7CymU03KTz4uXUqgFeYQBEZs-dc43haiuicIhK__Xg4sw5qVM9aUIe3vEkINuN_7TRVOwppXKV8iIJ9FUQLCkEdGEbKC3DM6QbyB10wXgUvHQ2DPQybmKDbvMRIHUWKpJtUmr3tSLOw3nMfYiSeK5eXpyveGbJhC1vXeZFEW5Dx65H7ixK2CeoMxM-J6EPdd8THuauTFIpgm0DKWfq9HCHQTV2o7GtTEtXZumFMUEAucF0gkSIeExS2mxP7ZalQlDsgJTZBul3DQulhp2qj0FJf4DPAUV9gYjHHVdgUdG3hJ-jIKGrQGGcFqJ0l4FhCaGe8c146Qm2cGUs9Z2s0DKeF5EwVQksfereXX4YSk0Q5BwnMV4MYS4WDwzqyWfOBHrpSuDp26y_TMOIE02Kd2_HDk3Zc-biZgk1NcaHoXPljofOm8vR2Xh4vlEP34-Ho_NyfCj3pL96Jy26Y_BBhgTUua-eBvnWdpXQ7b1suDj2BHeDLFm6qScEz2KSIctH169fa4CqDx5dwdcCk7iR7KfmNSzZQ8EIthTcQJgVXppP8ewxgFoqCpdhFaTZplbFyOep-F-jjLMiy8MkftJQLhvo5uLZLXNmt01m3qEUSir27OMXFjDbMz17Zs4aNjPDRmPD-02R7iggM8s-RI5u4iPcwJ3dtlS9AmL86MM_X38DbLUeTqkjhVnVDC8v1SlzVMZ8pUYTr9GeWtgplhgGyU04Wh8pgHziTe2Ks2L3wzLJClepiQAeMkveO3KgrPNBrQcRKcxeCw4PNf6BranrOFeOO7p6czYeXOx6oKxfhZ-bIyeyglewObbsBz67tomNT6fmiRZYXj6PuOCAf8BcKe__i7xIds7JLrT9Q6EMtmNa7SpqEs_dtumpYLD9qv_ot2_q-y8 "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+ [Try it online!](https://tio.run/##hVXvbuJGEP/OU0x8arIL5gpcG0UYJ0oJUiLdkRNH1OsRzlrWa7DO2Ja9PkjafO0D9BH7IKXj3QWckKoWmNnZmd/On98OPE2bc843b3wRhLGAj/3RoOP1b68G3t3wZuz9enM1voaz2psw5lHhC@ilPBOdt4vzGl@wDLx0MgUXRtYvq9W32bvit4eHz@PF6WpBNl/JfeeiQe7b9I@va9rAF37W6w19aWrZUE9dL220nco5uczCeF4etNeFCWoFW54f2J3XwlhCiqL0RJYlGeFJnEtQQdaXIs/ZXFD4PZd@t8vRAno9MOpSVHoR@5EDmZBFFkPbeTrALNc88YUNsySJIHEDFuUlrDrGwE06P59OnRrgEwZAVL28uTAYnrEiGofogt/1ry9HZ3VqNm3Iw0eRBGQX@I9bTcWeUqpOKR@SwIVOgieFhC7sEqVlepZyAxVBF6wXyStny0Iv6z626K4eQVTkC53Jrii1p1oR5@E8Fj5ESTzXLxbnK5E5qmDLB4@zKMIwTO5m5c2ihH@DOrfhexL6UPeZZFi7skilCK4LpNyp0@M9BjXYjcauMy3TmSULY4IAKsB0gkSIRExS2mxP3ZajU9DsgJS7FrnoWg5KDTfVPxYlF338HlHUF4j4ruNJbCr6lvBzFBR0FSiM00KW7ioxbCHUM7FdL5nkC0/lUt/LGi0TeRFJW7fAMffs082XgdIEQS5wE/PFFOZy8cygnnwXXKKX6QTet@35yzSMBDGk@PRxPKIpf8s9DJZQ22B8GYxuvfFg9OFmeDkeXG3Vg8/jwfCqXB@rmMyviaRF9ww@ypCApvbV26Dexq6SuntQDQ/XTAovyJKllzIpRRaTDFk@vHv/3gBUffDqSrGWWMSt5L62b2DJAQpmsKPgFsKu8NJ@jWcvAfRRUbgMqyDNNnUqRr5I5f8aZYIXWR4m8auG6tjADBfmtuyZ27a5/YhSqKjYc386dYC7zGbuzJ41XG6HjcaW99smPVJAZpZziJzcxycYwKPbdnS/AmL94MPff/4FOGoZbukrhVU1DC8fPSlzVMZipVcT1mhPHZwUS0yD5DacrE80QD5hU7firNn9vE2qw1VqIgBDZqnPnhwom3pQ51lGGrPXguNjg3/kGuqORrcjb3j74XLcv97PQNW/Cj@3V05mhahgCxzZz3z2YxMHnynNKyOwfHwRCSkA//NyrXz6L/Ii2YUg@9QOL4U22K1pdaroTbx3u6Gnk8Hxu/mHBxGb55tmpOybZ/8C "C++ (gcc) ‚Äì Try It Online") - PCRE2 - every Fibonacci number up to \$F\_{46}\$ in under 20 seconds Instead of atomicizing the whole loop, as `^((?>\2?(\1)|x$|^x|\b))+`, we move all choices out of the loop, so there's only one thing it can do at any iteration. This saves 1 byte. As in the PCRE1 version, we can change `|^x` to `|^xx` to return \$1\$ (instead of \$2\$) for an input of \$1\$. An alternative 23 byte option would be `^(\2?+(\1)|x$|^x)+|^xxx`, but that'd be ever-so-slightly slower due to having an extra choice inside the loop. # Regex (.NET), ~~33~~ 29 bytes ``` (?=(^(x)|\3?(\1)|)*)(?<-1>x)* ``` [Try it online!](https://tio.run/##RY5NboMwEIX3nGKERsIDBQHdxXWJ1HVPkKSSIQ5YAowMFSg/2x6gR@xFqNuqymzm6XuL9w1mVnZsVNuuaMXOqloth82mVzPbBisrBHtjC133jwXbZ3SlkFjxFGfPC4VrsH3wX0w36FYdfeJ4Fin3TsYyZChdxlJkHLVIiQPquFWQ5z8pigguHrjDDgSgTV7lVDVqZMEShCiJ/5b6xPBMl9nqScWNGaebW8g43AHEvXGmre4V@Cjh6@MT3HaX1Na8D@MuPSSt6uupie4s/2fk/ylUAqWzkgJL98pIYMW92/oN "PowerShell ‚Äì Try It Online") Returns its output as the sum of the lengths of the match (group `\0`) and group `\2`. It is done as a sum because for inputs \$n=1,2,3\$ the Fibonacci index is \$n+1\$ and would not fit in a single capture group. Group `\2`, which is `(x)` in this regex, is captured as \$1\$ iff the loop takes at least one iteration, which happens for all \$n>0\$. The loop count itself is also given an extra increment, as in the **23 byte** version above, by the addition of an empty alternative `|` inside the loop. This will result in a zero-width match being taken at the end, regardless of input; it even happens for \$n=0\$, but that doesn't matter, because the `(?<-1>x)*` will not have room to pop its capture, and the return match will be \$0\$ anyway. Note that this regex would actually *not* be made shorter by returning its output as the sum of the lengths of `\0`, `\3`, and `\3`, as the shortest way I can think of to do that takes **34 bytes**: ``` (?=((?>\2?)(\1)|^x)*(x))?(?<-1>x)* ``` [Try it online!](https://tio.run/##RY5BboMwEEX3nMJCI2FDQUB3cR1H6ronSFLJkAlYMhgZKlDSbHuAHrEXoW6rKrOZP28W/w12Rje2aMwKTuwdNrgcN5seZ7qLVioFpXJ7KCWjh4K9vy4spgtjksqntNj6a412D@Gz7QZt8BQyDheR8@BsHQUKymeoRMFBi5xxAjo1SMryJyUJI9eA@IGOCAIue1FT3eJIoyWKQTH@@9RnChd2nZ2eMG3tON18Q8HJHZC0t17X6B5JCIp8fXwS391ljbNvw7jPj5nBvpna5M4e/1lcsvBPohagvJcSUPlVJQJqHtzWbw "PowerShell ‚Äì Try It Online") **38 byte** version that matches iff the input is a Fibonacci number: ``` ^(?=(^(x)|(?>\3?)(\1)|)*x$|$)(?<-1>x)* ``` [Try it online!](https://tio.run/##RY9BboMwEEWvYlkjYUONINmFOETquicgRELUAUuOjYwRKMC2B@gRexEKraIs35/Rm/mN6YVta6HUApZnVlRiyA8HLXpy9pYrSTm5koFOJD1d9ikll5hO1B9gAkrSI4tPA/UX7/yG3829kUp8YprAg0fJzVhRlDUBhaRGIHXTOTpCwUGxtlHSYYYTeSNQhKXptGPKod22EHAosiifVwEBzTOpXf6XJKCZEk@ONw4COm6OOwcbfhSurEVLvMHzQdP/yYOOvZVOsNq0bl4/i5MXI6bN2lRJLRAGjX6@vhGstrCypmva9WaohK5cHbyy3TOjeJ7nJWLxPop@AQ "PowerShell ‚Äì Try It Online") # Regex (Perl / PCRE), 31 bytes ``` ((?=(\2?x))(^x|\4?+(\3)))*(x|^) ``` [Try it online!](https://tio.run/##LYzLisJAEEX3fkUhhamyRWOPbmzLIDhbVy6DIQk@AjFK66LFx9IP8BPnR2JHZnMPBy7ntLHluD5cAa2BW3nM0xJwYLzKdDFfzWeP1vZoCc8S9jBtJpNhDwsJ/aeYykg3VIpvgLlg6i0VzDwyJZibFgAFLnCYszwHaJv0udM52aK6tOOqbXx5aODrvtAP4O/1hqBPhDoqN9Xuskc9CVnRv4y5q9k8kuR3uUiSmigSinXkmGnt7vEoUhT/MHOX3H3Ndf0B "Perl 5 ‚Äì Try It Online") - Perl [Try it online!](https://tio.run/##XY/BasMwDIbvfQoRBJEak7bpBgPX5LTBYKdd59akxm0CSWrcHALrrnuAPeJeJHPYYbCD@PUL6eOXr/20K33tAQMoSFYJ5OCDO5vgfFtZR@kqX5bG1FU7GHvpfNO6oEmz1K@rayogjXWKQ3N280I/uH64kjFPzy@PxrCADUdkBMvF6RIIK7UWeFQbgY1aS8Bmp7YPs2YZwzugVVhFWyk8RjlmCq1cwG@mrhpsTRjEdQhzQFcNlI6pQMsCO5bQnAgbdra@JLpPJMxdROYJfH9@QZJTPGxdT9i9FXvO/tz9npcFy49/jxLLiahUpItyZKbDeNN3ZUZ6y8xLGm8HnqYf "PHP ‚Äì Try It Online") - PCRE Returns its output as the sum of the lengths of groups `\2`, `\5`, and `\5`. The regex saves 3 bytes just by using a possessive quantifier, replacing `(?>\4?)` with `\4?+`. The Fibonacci index minus \$2\$ is built up in `\2` using the expression `(?=(\2?x))`. The first time this is hit, the `\2?` will evaluate to zero because `\2` isn't set yet, and `\2` will be given a value of \$1\$. On every subsequent iteration, it will be incremented. This is done in a lookahead to avoid influencing the running total Fibonacci match, and is safe because at every step, the index will be less than the amount added to the full match. The `(x|^)` at the end serves to let `\5`\$=1\$ in all cases except \$n=0\$. This regex does not work under Java; group `\2` just captures \$1\$ and stays there. This may be due to a bug in Java's regex engine. **33 byte** version that matches iff the input is a Fibonacci number: ``` ^((?=(\2?x))(^x|\4?+(\3)))*(x|^)$ ``` [Try it online!](https://tio.run/##RU7BToNAFLz3KzbNS3dfgRZQEtNlC03q1ZM3KZtqqG6yUgRMMHQ9@gF@oj@CW9T4Di9vJjNvpipqHQ3PbwRqTnp9fNhrAktuoYi3m9vN2kwOx5pBI3werzn2RB0swr6qVdmSaVZOuSGpFk2lVcuoR93m9b5prUW6XuAGWLycRck/61seVyCRn381NnFfpzoOsU/1XbATdvs7biaEjMnqlwAVi1FgL8fB3noZ7WgHCsX7Euol9tDMZmOvsZbtHPCfmqAWlHx9fBK6YAzCRBflY/sE4cpHh0H0hyOL5yFyY4yU1zdbKYecsUSwLEw6RJZ3p@wycVh2gYhz1p1yhGHwvSvfzjc "Perl 5 ‚Äì Try It Online") - Perl [Try it online!](https://tio.run/##XVDBSsNAEL37FUNYyEyTpmm1F7chFxUK4kG9Ne1S47YpJJslSSHS9uoH@In@SJwURejCLjPz3puZtzaz3Sy2mQVRQQTOyIEAbKW3qtI2X6ca3VEwiJXK1nmj0rKwu1xXCSYkk@dR7frg8t1wUW11TzCNNk2NSj3MH@@VIh/GxC25sbzalBWKXRRKkUcbptf48no3fyJJB9htUOSLuqlybTii4XgZRU5iHGJyvX9jhMt@6A/H1Ot1a/PyXaMzdHymS9an5d40vXY2YdGCG/AbLuUVwHmy@c2FmUVnnCPPIx4NeLZcrJs0Q1H5PKz3r9cNuq3rC0O@KIjg0G@5I51mZb@aBHYzltDnIEzgwPfnFzgBoi5s84GiWEyWFIe3f7bOOXn/8PQC5pwGE5In3vl08elIslshxhEmk7glwlV7TG5iD5NrYhW2xxWJrguH05DPDw "PHP ‚Äì Try It Online") - PCRE If the output specification must be simplified to sum only two groups, this would be the shortest way I can think of doing it (**39 bytes**, output is the sum of the lengths of groups `\0` and `\5`): ``` (?=((?=(\2?x))(^x|\4?+(\3)))*(x))?\2?x? ``` [Try it online!](https://tio.run/##HYzLbsJADEX3fIWFLGIzPBIKq8EMSLDtih1poyTiESkENLAIArrsB/CJ/ZEw04Xv1bGtc97actIcb4BWw7085WkJONQOZbpcrBezZ2t3soQXCXuY@sgk6mEhofsppjIe@VaK74C5YOooFcxcZUow1y0ACuqgxpzlZ4jWqy@dztkW1bUdV23tzJGGf3aGQQB/vy8IBkRztQm/@vO@S1blttpfDzhh/UyS1ecySRoyQn7ikamZ6bt@xGOjKP5g5i65lfEX0zRv "Perl 5 ‚Äì Try It Online") - Perl [Try it online!](https://tio.run/##XU9BTsMwELz3FatopawbK00pHMC1fAIJiRNXApZruU2kJLVcH4qAKw/giXwk2OKAxGE1O7s7o1nf@XmrfOcBA0goVgXU4IM76OD8YKyjclUvldadGaK2x9H3gwsttUy0j6tTyaFMtU9DfXD5YIpuiifS@u7@4VZrxmHNkmUyFov9MRAa2XDcyTXHXjYCsN/KzXXGqmLwBmglmkSNxF2CXSXRigX8ZhpNtB1h4KcYckBnIpXnkqNlHEcmoN8T9szZ7li0UyEgd8myLuD78wuKmpJwcBPh@NQ8s4rc6ONrZlfPTDU3f9vEGRMf//4mJmZSknK1F@rMGL2c39tLVVG7SYIlpZHKGzXPPw "PHP ‚Äì Try It Online") - PCRE **42 byte** version that matches iff the input is a Fibonacci number: ``` ^(?=((?=(\2?x))(^x|\4?+(\3)))*(x|^)$)\2?x? ``` [Try it online!](https://tio.run/##RU5dT4MwFH3fr2iWZu0VGGVKYla6smS@@uSbjGYapk0qQ8AE0@GjP8Cf6B/Bgibe5N7cc@7HOVVRm3h4eUe45sia0@PBIBxyB0Wy295tN/3seKopbgTjyYaDRfroENiq1mWL5lk55z1KjWgqo1tKAuI3bw9N606UH0R@BMXruCT/WeZ4WGMFfPzVOMVDnZpkBTY199FeuMr2vJ8hNCnrPwLrREwLrvM8sO6Wko50WIP4CHEdgsXNYjH5mmw5zxH/tYn1kqDvzy9ElpSmnnsXpIGr4FEcS1OUT@0zjtcMgPd9r9TN7U6pIadS0DGzlewAaN6dsyvp0ewSAC5od84BwziTw8CCa@biBw "Perl 5 ‚Äì Try It Online") - Perl [Try it online!](https://tio.run/##XVDBaoNAEL3nKwZZcCZRo2lz2oiXthAoPbS9xWSxdhMDZhU1ICS59gP6if0ROxtaCl2YZWbnvXnzti7qYZHURQ2igRicqQMB1I3eqUbXZZZrdKfBOFGqyMpO5dWh3pe6STElmT5PW9cDl2PLj2qnLcB02nQtKvWwfLxXijyIiEfyYDnaVg2KfRxKUcZbhrf48nq3fCJJJ9hvUZSrtmtKbTgjP1rHsZMahxjcHt@4w89e6PkRWb7u67J61@j4jsdwyfy8OprOchczJq14AN/hWo4ArsrmpxZmEV/7nE0mxNKAV8uHrMsLFI3HYta/zjp0e9cThjxxIIKT3XJPOi8qu5oEdhNJsDUIEzjw9fEJToC/Ng4sR5O/ar4mkhfe5/LvQ5HksMEkRhvpLOmJcNOf09tkgukNEY2xP29IkO0lwxD685DPNw "PHP ‚Äì Try It Online") - PCRE [Answer] # Python, 38 bytes ``` f=lambda n,a=0,b=1:n^a and-~f(n,b,a+b) ``` Test it on [Ideone](http://ideone.com/fAT2fL). [Answer] # C, 62 58 bytes ``` g(c,a,b){return c-a?g(c,b,a+b)+1:0;}f(c){return g(c,0,1);} ``` **Detailed** ``` int g(int c, int a, int b) { if (c == a) { return 0; } else { return g(c, b, a+b) + 1; } } int f(c) { return g(c, 0, 1); } ``` [Answer] # Java 7, 70 bytes ``` int c(int n){int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;} ``` <https://ideone.com/I4rUC5> [Answer] ## TSQL, 143 bytes Input goes in `@n` as in `DECLARE @n INT = 1836311903;` ``` DECLARE @O BIGINT=0;WITH F(R,P,N)AS(SELECT @O,@O,@O+1 UNION ALL SELECT R+1,N,P+N FROM F WHERE N<=@n)SELECT MAX(R)FROM F OPTION(MAXRECURSION 0); ``` [Answer] ## Haskell, 45 bytes ``` f x=round$log(sqrt 5*x+0.9)/log((sqrt 5+1)/2) ``` [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 28 bytes Hexdump: ``` 0000000: 16f8be 766ef7 ae6d80 f90bde b563f0 7ded18 3ceffa ...vn..m.....c.}..<.. 0000015: b1c1bb af9f3f ff .....?. ``` [Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcApzdWIgMQpmd2QgMQphZGQgMQpmd2QgMQphZGQgMQpyd2QgMgpqbnogICAgO2EgYQpmd2QgNAphZGQgMSAgO2EgYSAwIDEKZndkIDIKYWRkIDEgIDthIGEgMCAxIDAgMQpyd2QgNApqbXAKam1wICAgIDthIGEtYiBiIGMgbgpzdWIgMQpqbnogICAgO2EgMCBiIGMgbgpmd2QgMwphZGQgMQpqbXAKc3ViIDEKZndkIDIKYWRkIDEKcndkIDIKam56ICAgIDthIDAgYiBjIDAgMCBuKzEKcndkIDEKam1wCnN1YiAxCmZ3ZCAxCmFkZCAxCmZ3ZCAxCmFkZCAxCnJ3ZCAyCmpueiAgICA7YSAwIGIgMCBjIGMgbisxCnJ3ZCAxCmptcApzdWIgMQpmd2QgMQpzdWIgMQpmd2QgMgphZGQgMQpyd2QgMwpqbnogICAgO2EgMCAwIC1iIGMgYitjIG4rMQpyd2QgMgpqbXAKc3ViIDEKZndkIDIKYWRkIDEKZndkIDEKYWRkIDEKcndkIDMKam56ICAgIDswIDAgYSBhLWIgYyBiK2MgbisxCmZ3ZCAzCmpuegpmd2QgMwpwdXQ&input=NQ&debug=on) (Exponential time because in Sesos copying a number needs exponential time.) Assembly used to generate the binary file: ``` set numin set numout get jmp sub 1 fwd 1 add 1 fwd 1 add 1 rwd 2 jnz ;input input fwd 4 add 1 ;input input 0 1 fwd 2 add 1 ;input input 0 1 0 1 rwd 4 jmp jmp ;input input-curr curr next iterations sub 1 jnz ;input 0 curr next iterations fwd 3 add 1 jmp sub 1 fwd 2 add 1 rwd 2 jnz ;input 0 curr next 0 0 iterations+1 rwd 1 jmp sub 1 fwd 1 add 1 fwd 1 add 1 rwd 2 jnz ;input 0 curr 0 next next iterations+1 rwd 1 jmp sub 1 fwd 1 sub 1 fwd 2 add 1 rwd 3 jnz ;input 0 0 -curr next curr+next iterations+1 rwd 2 jmp sub 1 fwd 2 add 1 fwd 1 add 1 rwd 3 jnz ;0 0 input input-curr next curr+next iterations+1 fwd 3 jnz fwd 3 put ``` [Answer] # Java 8 61 bytes Same as @dainichi answer only made shorter by using Java 8 lambdas. The answer is a valid rvalue expression. ``` n->{int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;} ``` Ungolfed: ``` interface F { int c(int n); } public class Main { public static void main(String[] args) { F f = n->{int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;}; } } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes ``` ‚âú‚àß0;1‚ü®t‚â°+‚ü©‚ű‚Üñ?h ``` [Try it online!](https://tio.run/##AVsApP9icmFjaHlsb2cy/3t3IiAtPiAidz9@4oaw4oKC4bqJfeG1kP/iiZziiKcwOzHin6h04omhK@KfqeKBseKGlj9o//9bMCwyLDMsNSw4LDEzLDE4MzYzMTE5MDNd "Brachylog ‚Äì Try It Online") Takes input through the output variable and outputs through the input variable. ``` ‚âú Label the input variable, trying 0, 1, -1, 2..., 0 then starting with 0 ‚àß (which is not necessarily the input variable) ;1 paired with 1, ‚ü®t‚â° ‚ü© replace the first element of the pair with the last element ‚ü® ‚â°+‚ü© and the last element of the pair with the sum of the elements ‚ű‚Üñ? a number of times equal to the input variable, h such that the first element of the pair is the output variable. ``` I'm not entirely sure why `‚âú` is necessary. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 bytes ``` (+.!‚àò‚åΩ‚ç®‚àò‚ç≥¬®‚Ķ)‚ç≥‚ä¢ ``` Explanation soon (TM) [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9OApIa2nuKjjhmPevY@6l0BYvRuPrTiUcMyTSDjUdcikGqgqjQFU1MuGNMIzjL@DwA "APL (Dyalog Extended) ‚Äì Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~6~~ 4 bytes ``` √ûF·∏ü‚Ä∫ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiw55G4bif4oC6IiwiIiwiMFxuMVxuMVxuMlxuM1xuNVxuOFxuMTNcbjIxXG4zNFxuNTVcbjg5XG4xNDRcbjIzM1xuMzc3XG42MTBcbjk4N1xuMTU5N1xuMjU4NFxuNDE4MVxuNjc2NVxuMTA5NDZcbjE3NzExXG4yODY1N1xuNDYzNjhcbjc1MDI1XG4xMjEzOTNcbjE5NjQxOFxuMzE3ODExXG41MTQyMjlcbjgzMjA0MFxuMTM0NjI2OVxuMjE3ODMwOVxuMzUyNDU3OFxuNTcwMjg4N1xuOTIyNzQ2NVxuMTQ5MzAzNTJcbjI0MTU3ODE3XG4zOTA4ODE2OVxuNjMyNDU5ODZcbjEwMjMzNDE1NVxuMTY1NTgwMTQxXG4yNjc5MTQyOTZcbjQzMzQ5NDQzN1xuNzAxNDA4NzMzIl0=) -2 thanks to Deadcode 1 byte longer than it should be just because Vyxal's "Fibonacci sequence" builtin does not start with 0. [Answer] # [C89 (clang)](http://clang.llvm.org/), 54 bytes ``` a,b,r;g(f){for(a=r=0,b=1;a<f;++r)b+=a,a=b-a;return r;} ``` [Try it online!](https://tio.run/##XY9RT8MgFIWfx6@4ziwp6a2hq6szjP0SX2hLK0mlC6XGZO63VxgmBp@4fJx7zqEt2lGaYV0lNmj5kPX02k82k8IKho0ouTz1PM8tbXIhUYqmkNwqt1gDlt/WR23acekUnGbX6enp/UyINo44NbvMD6ANQjjV10W1jpIr2YSrVfMyOk42cQABg5dTDy7Wv/fZdtdBcYZd92a2eHeJSi8JS7FA3H0Qv@6c3GL6h9Qm@5x095fnE1iIg28B93IMgdGE7BGqlFQIzyk5IBxSckSoU1L6tZd/6FjVVVm@suBYJ3/wpdcf "C (clang) ‚Äì Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` √¥!gM √®<U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9CFnTSDoPFU&input=MTM) ## Original, 9 bytes Can handle larger inputs than the version above. ``` nMgV¬∞)¬©√í√ü ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bk1nVrApqdLf&input=MTgzNjMxMTkwMw) [Answer] # Pyth, 13 bytes ``` J1tf>=Z+~JZZQ ``` [Test suite.](http://pyth.herokuapp.com/?code=J1tf%3E%3DZ%2B~JZZQ&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A5%0A8%0A13%0A1836311903&debug=0) Approximation in Python 2: ``` Z=0;J=1;T=1;Q=input() while not J+Z>Q: temp=J J=Z Z=temp+J T += 1 print(T-1) ``` ### alternative approach, 18 bytes ``` L?<b2bsyMtBtbs.IyG ``` [Test suite.](http://pyth.herokuapp.com/?code=L%3F%3Cb2bsyMtBtbs.IyG&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A5%0A8%0A13%0A1836311903&debug=0) This uses `.I` for inverse. ]
[Question] [ # Binary to decimal converter As far as I can see, we don't have a simple binary to decimal conversion challenge. --- Write a program or function that takes a positive binary integer and outputs its decimal value. You are not allowed to use any builtin base conversion functions. Integer-to-decimal functions (e.g., a function that turns `101010` into `[1, 0, 1, 0, 1, 0]` or `"101010"`) are exempt from this rule and thus allowed. Rules: * The code must support binary numbers up to the highest numeric value your language supports (by default) * You may choose to have leading zeros in the binary representation * The decimal output may not have leading zeros. * Input and output formats are optional, but there can't be any separators between digits. `(1,0,1,0,1,0,1,0)` is not a valid input format, but both `10101010` and `(["10101010"])` are. + You must take the input in the "normal" direction. `1110` is `14` not `7`. Test cases: ``` 1 1 10 2 101010 42 1101111111010101100101110111001110001000110100110011100000111 2016120520371234567 ``` This challenge is related to a few other challenges, for instance [this](https://codegolf.stackexchange.com/questions/68247/convert-a-number-to-hexadecimal), [this](https://codegolf.stackexchange.com/questions/63564/simplify-binary) and [this](https://codegolf.stackexchange.com/questions/69155/base-conversion-with-strings). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 bytes ``` DḤ+¥/ ``` [Try it online!](http://jelly.tryitonline.net/#code=ROG4pCvCpS8&input=&args=MTAxMDEw) ## Explanation [![enter image description here](https://i.stack.imgur.com/rlLYr.png)](https://i.stack.imgur.com/rlLYr.png) ### The cast * `D` is a monad (single argument function): digits, turning `1234` into `[1, 2, 3, 4]`. * `Ḥ` is a monad that doubles its single argument. * `+` is a dyad (two argument function) that adds its left and right arguments. From there, it gets a little tricky. ### Here’s what happens at parse time * `D`, `Ḥ`, and `+` are read. The chain looks like `[D, Ḥ, +]`. * The next two characters are **quicks**, which act like parse-time postfix operators on the links (functions) we've read so far. * When `¥` is read, the last two links get popped and replaced by a link that acts like the dyad formed by composing them. So now the chain looks like `[D, dyad(Ḥ+)]`. * When `/` is read, the last link (which ought to be a dyad) gets popped and replaced by a monad that [folds](https://en.wikipedia.org/wiki/Fold_(higher-order_function)) using this dyad (intuitively: `f/` takes a list, replaces the commas in it with `f`, and evaluates the result.) * The final chain looks like `[D, fold(dyad(Ḥ+))]`, two monads. ### Here's what happens at run time * Input (a number) is implicitly read into the working value (say, `101010`). * `D` is executed, replacing the working value with its digits (`[1,0,1,0,1,0]`). * `fold(dyad(Ḥ+))` is executed, replacing the working value with `1∗0∗1∗0∗1∗0`, where `∗` is the dyad `Ḥ+`. ### So what does `x∗y` evaluate to? * In a dyadic definition, the working value is initially the **left** argument, `x`. * `Ḥ`, the **double** monad, doubles this value. The working value is now `2x`. * `+`, the **plus** dyad, lacks a right argument, so this is a **hook**: a special syntactical pattern where the right argument of this dyad gets injected into `+`. This yields `2x + y` as the final working value, which is returned. ### So the whole expression evaluates to: ``` 1∗0∗1∗0∗1∗0 = 2×(2×(2×(2×(2×1+0)+1)+0)+1)+0 = 32×1 + 16×0 + 8×1 + 4×0 + 2×1 + 1×0 = 42 ``` [Answer] # Python 2, ~~49~~ ~~37~~ ~~31~~ 30 Bytes Now this will take a binary number in a decimal representation, since Python can handle arbitrarily large integers. ``` b=lambda n:n and n%2+2*b(n/10) ``` *thanks to xnor for saving a byte :)* The easiest way to see how this works is by seeing a basic formula for converting binary to decimal: ``` = 101010 = 1*(2^5) + 0*(2^4) + 1*(2^3) + 0*(2^2) + 1*(2^1) + 0*(2^0) = 1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 0*1 = 42 ``` This is a 'standard' way of converting. You can expand the third line like so: ``` = ((((1*2 + 0)*2 + 1)*2 + 0)*2 + 1)*2 + 0 ``` And this is essentially what the recursive method I've made is doing. Alternate solutions I had: ``` b=lambda n:n and n%10+2*b(n/10) b=lambda n:n%10+2*(n and b(n/10)) b=lambda n:0if n<1else n%10+2*b(n/10) b=lambda n:0**(n/10)or n%10+2*b(n/10) b=lambda n,o=0:o*(n<'0')or b(n[1:],2*o+int(n[0])) lambda j:sum(int(b)*2**a for a,b in enumerate(j,1)) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes Code: ``` $¦v·y+ ``` For the explantion, let's take the example **101010**. We start with the number **1** (which is represented by the first digit). After that, we have two cases: * If the digit is a **0**, multiply the number by 2. * If the digit is a **1**, multiply the number by 2 and add 1. So for the **101010** case, the following is calculated: * **1**01010, start with the number **1**. * 1**0**1010, multiply by two, resulting into **2**. * 10**1**010, multiply by two and add one, resulting into **5**. * 101**0**10, multiply by two, resulting into **10**. * 1010**1**0, multiply by two and add one, resulting into **21**. * 10101**0**, multiply by two, resulting into **42**, which is the desired result. Code explanation: ``` $ # Push 1 and input ¦ # Remove the first character v # For each character (starting with the first) · # Multiply the carry number by two y+ # Add the current character (converted automatically to a number) ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=JMKmdsK3eSs&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) [Answer] # Turing Machine Code, 232 bytes (Using, as usual, the morphett.info rule table syntax) While only 40 bytes shorter than the [existing solution](https://codegolf.stackexchange.com/a/102258), that solution uses 12 states whereas this one only uses 4: ``` 0 1 0 l 0 0 0 . r 0 0 . 1 l 0 0 _ I r 1 0 I 2 r 0 0 2 3 r 0 0 3 4 r 0 0 4 5 r 0 0 5 6 r 0 0 6 7 r 0 0 7 8 r 0 0 8 9 r 0 0 9 X l 0 0 X O r 0 0 O I r 0 1 _ _ l 2 1 * * * 0 2 * _ l 3 3 O 0 l 3 3 I 1 l 3 3 . _ l 3 3 _ * * halt 3 * * l 3 ``` ### [Try it online!](http://morphett.info/turing/turing.html?913c655ff9a63a6da93fa5af72de73cc) The interesting computation (ie. base-conversion) actually just takes place in state 0. This state decrements the binary number one-by-one, each time incrementing a decimal counter. Due to naming clashes of the number-bases' alphabets, I make use of `O` and `I` during the conversion. State *1,2,3* only take care of cleaning the tape, converting the symbols `O → 0` and `I → 1` and finally halting the machine. [Answer] ## Haskell, ~~16~~ 111 + 57 = 168 bytes ``` import Data.String instance IsString[Int]where fromString=map((-48+).fromEnum) f::[Int]->Int f=foldl1((+).(2*)) ``` +57 bytes for the compile flags `-XOverloadedStrings`, `-XOverlappingInstances` and `-XFlexibleInstances`. The challenge has some [cumbersome IO format](http://meta.codegolf.stackexchange.com/a/8077/34531), because it heavily depends on how data types are expressed in the source code. My first version (16 bytes), namely ``` foldl1((+).(2*)) ``` takes a list of integers, e.g. `[1,0,1,0,1,0]` and was declared invalid because literal Haskell lists happen to have `,` between the elements. Lists per se are not forbidden. In my new version I use the very same function, now named `f`, but I overload "Quote enclosed character sequences". The function still takes a list of integers as you can see in the type annotation `[Int] -> Int`, but lists with single digit integers can now be written like `"1234"`, e.g. ``` f "101010" ``` which evaluates to `42`. Unlucky Haskell, because the native list format doesn't fit the challenge rules. Btw, `f [1,0,1,0,1,0]` still works. [Answer] ## JavaScript (ES6), ~~33~~ 31 bytes ``` s=>[...s].map(c=>r+=+c+r,r=0)|r ``` Edit: Shorter but less sweet: 2 bytes saved thanks to @ETHproductions. [Answer] # [Labyrinth](http://github.com/mbuettner/labyrinth), 17 15 bytes ``` -+: 8 + 4_,`)/! ``` [Try it online!](http://labyrinth.tryitonline.net/#code=LSs6CjggKwo0XyxgKS8h&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) [![Image of the code](https://i.stack.imgur.com/TVlWV.png)](https://i.stack.imgur.com/TVlWV.png) Labyrinth is a two-dimensional, stack-based language. In labyrinth, code execution follows the path of the code like a maze with spaces acting as walls and beginning at the top-left-most non-space character. The code flow is determined by the sign of the top of the stack. Since the stack has implicit zeroes at the bottom, the first four instructions (`-+:+`) have no effect. ## Loop starting at the `,` * `,` Push the ascii code value of the next input character to the stop of the stack, or push -1 if EOF. * `_48` pushes 48 to the top of the stack * `-` Pop y, pop x, push `x-y`. The previous instructions have the effect of subtracting 48 from the input yielding 0 for "0" and 1 for "1". * `+` Pop y, pop x, push `x+y`. * `:` Duplicate the top of the stack * `+` This and the previous instruction have the effect of multiplying the current value by 2 So the circular part of the code, in effect, multiples the current number by 2 and adds either a 1 or a 0 depending on if the character 1 or 0 was input. ## Tail If the top of the stack is negative (meaning EOF was found), the code will turn left at the junction (going towards the semicolon). * ``` Negate the top of the stack to get 1 * `)` Icrement the top of the stack to get 2 * `/` Pop y, pop x, push x/y (integer division). This has the effect of undoing the last `*2` from the loop. * `!` Output the integer representation of the top of the stack. At this point the program turns around because it hit a dead end and then exits with an error because it tries to divide by zero. Thanks to [@Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for saving me 2 bytes (and teaching me how to better think in Labyrinth). [Answer] # Retina, 15 bytes Converts from binary to unary, then unary to decimal. ``` 1 01 +`10 011 1 ``` [**Try it online**](http://retina.tryitonline.net/#code=MQowMQorYDEwCjAxMQox&input=MTAxMDEw) [Answer] # PHP, 44 bytes ``` for(;""<$c=$argv[1][$i++];)$n+=$n+$c;echo$n; ``` I could have sworn that I´ve seen that question before. But well. Reads the number from left to right, shifts left and adds the current bit. [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), ~~46~~, 28 bytes ``` ([]){{}({}<>({}){})<>([])}<> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KFtdKXt7fSh7fTw-KHt9KXt9KTw-KFtdKX08Pg&input=MSAxIDAgMSAxIDEgMSAxIDEgMSAwIDEgMCAxIDAgMSAxIDAgMCAxIDAgMSAxIDEgMCAxIDEgMSAwIDAgMSAxIDEgMCAwIDAgMSAwIDAgMCAxIDEgMCAxIDAgMCAxIDEgMCAwIDEgMSAxIDAgMCAwIDAgMCAxIDEgMSA) *Many many bytes saved thanks to @Riley!* Since brain-flak can't take binary input, input is a list of '0's and '1's. Explanation: ``` #Push the height of the stack ([]) #While true: { #Pop the height of the stack {} #Push this top number to (the other stack * 2) ({}<>({}){}) #Toggle back on to the main stack <> #Push the new height of the stack ([]) #endwhile } #Toggle back to the other stack, implicitly display. <> ``` [Answer] # Java, ~~84~~ ~~79~~ ~~46~~ 48 bytes * Version 3.1 Changed to `long`/**48** bytes: ``` s->{long x=0;for(char c:s)x=c-48l+x*2;return x;} ``` * Version 3.0 Did some golfing/**46** bytes: ``` s->{int x=0;for(char c:s)x=c-48+x*2;return x;} ``` * Version 2.0 Thanks to @Geobits!/**79** bytes: ``` s->{int i=Math.pow(2,s.length-1),j=0;for(char c:s){j+=c>48?i:0;i/=2;}return j;} ``` * Version 1.0 **84** bytes: ``` s->{for(int i=-1,j=0;++i<s.length;)if(s[i]>48)j+=Math.pow(2,s.length-i+1);return j;} ``` [Answer] # Befunge-98, 12 bytes ``` 2j@.~2%\2*+ ``` [Try it online!](http://befunge-98.tryitonline.net/#code=MmpALn4yJVwyKis&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) Reads one char at a time from input, converts it to 0 or 1 by taking its value modulo 2 (0 is char(48), 1 is char(49)), then uses the usual algorithm of doubling the current value and adding the new digit each time. **Bonus:** This works with any kind of input string, I've been trying for a while now to find any funny input->output combination, but I wasn't able to produce anything (sadly, "answer"=46). Can you? [Answer] # C# 6, ~~85~~ ~~37~~ 36 bytes ``` long b(long n)=>n>0?n%2+2*b(n/10):0; ``` * Thanks to [Kade](https://codegolf.stackexchange.com/users/38417/kade) for saving 41 bytes! * Changing to C# 6 saved another 7 bytes. [Answer] ## Perl, 25 bytes *-3 bytes thanks to @Dom Hastings.* 24 bytes of code + 1 byte for `-p` flag. ``` $\|=$&<<$v++while s/.$// ``` To run it: ``` perl -pe '$\|=$&<<$v++while s/.$//' <<< 101010 ``` **Explanations:** ``` $\|=$&<<$v++ # Note that: we use $\ to store the result # at first $v=0, and each time it's incremented by one # $& contains the current bit (matched with the regex, see bellow) # So this operation sets a $v-th bit of $\ to the value of the $v-th bit of the input while # keep doing this while... s/.$// # ... there is a character at the end of the string, which we remove. # $\ is implicitly printed thanks to -p flag ``` [Answer] ## Javascript (ES7) ~~41~~ ~~40~~ 36 bytes ``` f=([c,...b])=>c?c*2**b.length+f(b):0 ``` takes a string as input Shaved a byte thanks to ETHproductions ``` f=([c,...b])=>c?c*2**b.length+f(b):0 document.write([ f('101010'), f('11010'), f('10111111110'), f('1011110010110'), ].join("<br>")) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 31 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), ~~9~~ ~~7~~ 3.875 bytes ``` fṘTE ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJzPSIsIiIsImbhuZhURSIsIiIsIjEwMSJd) ``` fṘTE ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJzPSIsIiIsImbhuZhURSIsIiIsIjEwMSJd) * -2 thanks to Steffan * -3 chars thanks to lyxal **Explanation:** ``` fṘTE # Implicit input f # Flatten into a list of digits Ṙ # Reverse the list T # Truthy indices E # Two power # Implicit output of sum ``` Old: ``` ṘėRvƒ↲∑ # Implicit input Ṙė # Reverse and enumerate R # Reverse each vƒ # Vecorised reduce over: ↲ # Left bit-shift ∑ # Sum # Implicit output ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes ``` RvNoy*O ``` [Try it online!](http://05ab1e.tryitonline.net/#code=UnZOb3kqTw&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) **Explanation** ``` R # reverse input v O # sum of No # 2^index * # times y # digit ``` [Answer] # Bash + GNU utilities, 29 bytes ``` sed 's/./2*&+/g;s/.*/K&p/'|dc ``` I/O via stdin/stdout. The `sed` expression splits the binary up into each digit and builds a RPN expression for `dc` to evaluate. [Answer] # C, 53 ``` v(char*s){int v=0,c;while(c=*s++)v+=v+c-48;return v;} ``` Same as my javascript answer Test [Ideone](http://ideone.com/eSaKPz) [Answer] # Mathematica, ~~27~~ ~~13~~ 11 bytes ``` Fold[#+##&] ``` Accepts a `List` of bits as input (e.g. `{1, 0, 1, 1, 0}` -- *Mathematica*'s binary representation of the number `22`) [Answer] # [Pushy](https://github.com/FTcode/Pushy), 10 bytes Takes input as a list of 0/1 on the command line: `$ pushy binary.pshy 1,0,1,0,1,0`. ``` L:vK2*;OS# ``` The algorithm really shows the beauty of having a second stack: ``` \ Implicit: Input on stack L: ; \ len(input) times do: v \ Push last number to auxiliary stack K2* \ Double all items OS# \ Output sum of auxiliary stack ``` This method works because the stack will be doubled `stack length - n` times before reaching number `n`, which is then dumped into the second stack for later. Here's what the process looks like for input `101010`: ``` 1: [1,0,1,0,1,0] 2: [] 1: [2,0,2,0,2] 2: [0] 1: [4,0,4,0] 2: [2] 1: [8,0,8] 2: [2,0] 1: [16,0] 2: [2,0,8] 1: [32] 2: [2,0,8,0] 1: [] 2: [2,0,8,0,32] 2 + 8 + 32 -> 42 ``` [Answer] ## R (32-bit), 64 Bytes Input for the function should be given as character. The base functions of R support 32-bit integers. Input: ``` # 32-bit version (base) f=function(x)sum(as.double(el(strsplit(x,"")))*2^(nchar(x):1-1)) f("1") f("10") f("101010") f("1101111111010101100101110111001110001000110100110011100000111") ``` Output: ``` > f("1") [1] 1 > f("10") [1] 2 > f("101010") [1] 42 > f("1101111111010101100101110111001110001000110100110011100000111") [1] 2.016121e+18 ``` ## R (64-bit), 74 Bytes Input for the function should be given as character. The package `bit64` has to be used for 64-bit integers. Input: ``` # 64-bit version (bit64) g=function(x)sum(bit64::as.integer64(el(strsplit(x,"")))*2^(nchar(x):1-1)) g("1") g("10") g("101010") g("1101111111010101100101110111001110001000110100110011100000111") ``` Output: ``` > g("1") integer64 [1] 1 > g("10") integer64 [1] 2 > g("101010") integer64 [1] 42 > g("1101111111010101100101110111001110001000110100110011100000111") integer64 [1] 2016120520371234567 ``` [Answer] # Matlab, 30 Bytes ``` @(x)sum(2.^find(flip(x)-48)/2) ``` The last test case has rounding errors (because of `double`), so if you need full precision: ``` @(x)sum(2.^uint64(find(flip(x)-48))/2,'native') ``` with 47 Bytes. [Answer] ## [Retina](http://github.com/mbuettner/retina), 12 bytes Byte count assumes ISO 8859-1 encoding. ``` +%`\B ¶$`: 1 ``` [Try it online!](http://retina.tryitonline.net/#code=KyVgXEIKwrYkYDoKMQ&input=MTAxMDEw) Alternative solution: ``` +1`\B :$`: 1 ``` ### Explanation This will probably be easier to explain based on my old, less golfed, version and then showing how I shortened it. I used to convert binary to decimal like this: ``` ^ , +`,(.) $`$1, 1 ``` The only sensible way to construct a decimal number in Retina is by counting things (because Retina has a couple of features that let it print a decimal number representing an amount). So really the only possible approach is to convert the binary to unary, and then to count the number of unary digits. The last line does the counting, so the first four convert binary to unary. How do we do that? In general, to convert from a list of bits to an integer, we initialise the result to `0` and then go through the bits from most to least significant, double the value we already have and add the current bit. E.g. if the binary number is `1011`, we'd really compute: ``` (((0 * 2 + 1) * 2 + 0) * 2 + 1) * 2 + 1 = 11 ^ ^ ^ ^ ``` Where I've marked the individual bits for clarity. The trick to doing this in unary is a) that doubling simply means repeating the number and b) since we're counting the `1`s at the end, we don't even need to distinguish between `0`s and `1`s in the process. This will become clearer in a second. What the program does is that it first adds a comma to the beginning as marker for how much of the input we've already processed: ``` ^ , ``` Left of the marker, we'll have the value we're accumulating (which is correctly initialised to the unary representation of zero), and right of the value will be the next bit to process. Now we apply the following substitution in a loop: ``` ,(.) $`$1, ``` Just looking at `,(.)` and `$1,`, this moves the marker one bit to the right each time. But we also insert `$``, which is everything in front of the marker, i.e. the current value, which we're doubling. Here are the individual steps when processing input `1011`, where I've marked the result of inserting `$`` above each line (it's empty for the first step): ``` ,1011 1,011 _ 110,11 ___ 1101101,1 _______ 110110111011011, ``` You'll see that we've retained and doubled the zero along with everything else, but since we're disregarding them at the end, it doesn't matter how often we've doubled them, as long as the number of `1`s is correct. If you count them, there are `11` of them, just what we need. So that leaves the question of how to golf this down to 12 bytes. The most expensive part of the 18-byte version is having to use the marker. The goal is to get rid of that. We really want to double the prefix of every bit, so a first idea might be this: ``` . $`$& ``` The problem is that these substitutions happen simultaneously, so first bit doesn't get *doubled* for each bit, but it just gets copied once each time. For input `1011` we'd get (marking the inserted `$``): ``` _ __ ___ 1101011011 ``` We do still need to process the input recursively so that the doubled first prefix is doubled again by the second and so on. One idea is to insert markers everywhere and repeatedly replace them with the prefix: ``` \B , +%`, ¶$` ``` After replacing each marker with the prefix for the first time, we need to remember where the beginning of the input was, so we insert linefeeds as well and use the `%` option to make sure that the next `$`` only picks up things up the closest linefeed. This does work, but it's still too long (16 bytes when counting `1`s at the end). How about we turn things around? The places where we want to insert markers are identified by `\B` (a position between two digits). Why don't we simply insert prefixes into those positions? This almost works, but the difference is that in the previous solution, we actually removed one marker in each substitution, and that's important to make the process terminate. However, the `\B` aren't character but just positions, so nothing gets removed. We *can* however stop the `\B` from matching by instead inserting a non-digit character into this place. That turns the non-word boundary into a word boundary, which is the equivalent of removing the marker character earlier. And that's what the 12-byte solution does: ``` +%`\B ¶$`: ``` Just for completeness, here are the individual steps of processing `1011`, with an empty line after each step: ``` 1 1:0 10:1 101:1 1 1:0 1 1:0:1 1 1:0 10:1:1 1 1:0 1 1:0:1 1 1:0 1 1:0:1:1 ``` Again, you'll find that the last result contains exactly 11 `1`s. As an exercise for the reader, can you see how this generalises quite easily to other bases (for a few additional bytes per increment in the base)? [Answer] # Elm, ~~60~~ 41 bytes ``` String.foldl(\b a->2*a+Char.toCode b-48)0 ``` -19 bytes thanks to Wheat Wizard and alephalpha You can try it [here](https://elm-lang.org/try). Here's a full test snippet: ``` import Html exposing (text) f : String -> Int f=String.foldl(\b a->2*a+Char.toCode b-48)0 main = text (String.fromInt (f "101010")) ``` [Answer] ## T-SQL, 202 Bytes ``` DECLARE @b varchar(max)='1',@ int=1 declare @l int=LEN(@b)declare @o bigint=CAST(SUBSTRING(@b,@l,1)AS bigint)WHILE @<@l BEGIN SET @o=@o+POWER(CAST(SUBSTRING(@b,@l-@,1)*2AS bigint),@)SET @=@+1 END PRINT @o ``` [Answer] # PHP, 64 bytes ``` foreach(str_split(strrev($argv[1]))as$k=>$v)$t+=$v*2**$k;echo$t; ``` We reverse our binary number, split it into its component digits, and sum them based on position. [Answer] ## PowerShell v2+, 55 bytes ``` param($n)$j=1;$n[$n.length..0]|%{$i+=+"$_"*$j;$j*=2};$i ``` ~~Feels too long ...~~ Can't seem to golf it down any -- tips appreciated. ### Explanation ``` param($n)$j=1;$n[$n.length..0]|%{$i+=+"$_"*$j;$j*=2};$i param($n)$j=1; # Take input $n as string, set $j=1 $n[$n.length..0] # Reverses, also converts to char-array |%{ }; # Loop over that array $i+=+"$_"*$j; # Increment by current value of $j times current digit $j*=2 # Increase $j for next loop iteration $i # Leave $i on pipeline # Implicit output ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 7 bytes ``` PoofqWs ``` [Try it online!](http://matl.tryitonline.net/#code=UG9vZnFXcw&input=JzEwMTAxMCc) ``` P % Implicitly input string. Reverse o % Convert to array of ASCII codes o % Modulo 2: '1' becomes 1, '0' becomes 0 f % Find: push array of 1-based indices of nonzeros q % Subtract 1 from each entry W % 2 raised to each entry s % Sum of array. Implicitly display ``` [Answer] # JavaScript (ES6), 32 bytes ``` f=([...n])=>n+n&&+n.pop()+2*f(n) ``` Recursion saves the day again! Though the parameterization seems a little long... ]
[Question] [ ## Challenge Given a positive integer, determine whether it is a triangular number, and accordingly output one of any two constant, distinct values. ### Definition A [triangular number](https://en.wikipedia.org/wiki/Triangular_number) is a number that can be expressed as the sum of consecutive positive integers, starting at 1. They can also be expressed with the formula \$\frac {n(n + 1)} 2\$, where \$n\$ is some positive integer. ## Test cases Truthy: ``` 1 3 6 10 15 21 55 276 1540 2701 5050 7626 18915 71253 173166 222111 303031 307720 500500 998991 ``` Falsy: ``` 2 4 5 7 8 9 11 16 32 50 290 555 4576 31988 187394 501500 999999 ``` ## Rules * Your entry may be a function or a program. * You may assume that the input is a positive integer under \$10^6\$. * You must pick two constant, distinct outputs to distinguish the two categories. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes in each language wins.** [Answer] # [Haskell](https://www.haskell.org/), 23 bytes EDIT: * -1 byte: @xnor got rid of parentheses with a `$`. An anonymous function taking an `Int` and returning a `Char`. Output is `'1'` for triangular numbers and `'0'` for others. ``` (!!)$show.(10^)=<<[0..] ``` [Try it online!](https://tio.run/nexus/haskell#JY3risJADIX/@xRH6Y@W4pBkOpeA9UVcF8pasbCOS@vi43cjm0BufCfnPkyln8pznIevZ/VbvqcyLu4@/NQfZX8sbbvD/ohd256u1TwOF5Rz416P@bKs177ebptquT1ermb6bPrD4UTOndeV4RHBBA4QRrCabA8d2UB2oEBIUeyW1ZjEEjw4eY4RIsJsH8jy3VISMoVJCKpZlTeCDqZChsJQjvBiCESNNLcumJ1nzdkMklejif/179j8AQ "Haskell – TIO Nexus") * Use as `((!!)$show.(10^)=<<[0..]) 998991`. * Generates the numbers 1, 10, 100, 1000, ..., converts those to strings, and concatenates them. Then indexes into the resulting infinite string ``` "1101001000100001000001000000... ``` [Answer] # [Python](https://docs.python.org/2/), 24 bytes ``` lambda n:(8*n+1)**.5%1>0 ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ6VhoZWnbaippaVnqmpoZ/A/Lb9IIU8hM0@hKDEvPVXDUMfSUlNBWyHa1MAAiIA8C0tLQx1TA0MIDwRirbg4C4oy80oU8nTSNPI0/wMA "Python 2 – TIO Nexus") Outputs `False` for triangular numbers, `True` for the rest. Checks if `8*n+1` is a perfect square. Python's float precision for square roots easily suffices for the challenge limits of `n` up to a million, first giving a false positive on `n=6896076976160002` as found by Deadcode. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly) ``` R+\ċ ``` **[Try it online!](https://tio.run/nexus/jelly#@x@kHXOk@//RPYfbHzWtcf//P9pQx1jHTMfQQMfQVMfIUMcUSOqY6JjqmOtY6hga6hia6Rgb6ZgaxAIA "Jelly – TIO Nexus")** ### How? ``` R+\ċ - Main link: n R - range(n) -> [1,2,3,...,N] \ - cumulative reduce by: + - addition -> [1,3,6,...,T(N)] ċ - count occurrences of right (n) in left -> 1 if triangular, 0 otherwise ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 10 bytes ``` (^1|1\1)+$ ``` Input is in unary. Output is `0` or `1`. [Try it online!](https://tio.run/nexus/retina#FYvLCUMxEAPvU4cDTgyPle31p5dHSCHp3dlchDSMHvlzFdLr5Le@uvUs6RzRGMiQU4VHztjeLYoFMDfmqMHW/jt0nMliI6FBqyFRt8XZ6R73pr3WDw "Retina – TIO Nexus") (As a test suite that does decimal-to-unary conversion for convenience.) ### Explanation This is the most basic exercise in forward-references. Most people are familiar with backreferences in regex, e.g. `(.)\1` to match a repeated character. However, some of the more advanced flavours allow you to use a backreference before or inside the group it's referring to. In that case, it's usually called a forward-reference. This can make sense if the reference is repeated. It might not be well defined on the first iteration, but on subsequent iterations, the later or surrounding group has captured something and can be reused. This is most commonly used to implement recurrent patterns on unary strings. In this case, we try to match the input as the sum of consecutive integers: ``` ( # This is group 1, which we'll repeat 1 or more times. ^1 # Group 1 either matches a single 1 at the beginning of the string. | # or 1\1 # It matches whatever the previous iteration matched, plus another # 1, thereby incrementing our counter. # Note that the first alternative only works on the first iteration # due to the anchor, and the second alternative only works *after* # the first iteration, because only then the reference is valid. )+ $ # Finally, we make sure that we can exactly hit the end of the # string with this process. ``` [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes Checks if (**8x+1**) is a square number. ``` lambda x:(8*x+1)**.5%1==0 ``` [Try it online!](https://tio.run/nexus/python2#XZDNCsJADITvPkUvQltBkmy3uxH6Jl4qUhBURDz07Ws9yH66e5n8TGaSqRqq43Idb6fzWM2HOrfzTpu23cetDoMsj@fl/qqmWpvNF4YC@wJVgGPBBmZkPpEcO2FJSJKIWuqNvOzUSmoR7jQF7dFtZqpcRNb/E6dkQuVVGrF7dke/FdiBBT8FZoyBQ0xTOA1GF1B02uM5u8h7BvWceaYUnBZF/xb7vGZ5Aw "Python 2 – TIO Nexus") [Answer] ## Mathematica, 16 bytes ``` OddQ@Sqrt[1+8#]& ``` Essentially a port of xnor's [Python solution](https://codegolf.stackexchange.com/a/122092/61980). Outputs `True` for triangular numbers, `False` otherwise. [Answer] ## JavaScript (ES6), ~~30~~ 27 bytes *Saved 2 bytes thanks to kamoroso94* ``` f=(n,k)=>n>0?f(n+~k,-~k):!n ``` ### Test cases ``` f=(n,k)=>n>0?f(n+~k,-~k):!n console.log('Testing truthy test cases'); console.log(f(1)) console.log(f(3)) console.log(f(6)) console.log(f(10)) console.log(f(15)) console.log(f(21)) console.log(f(55)) console.log(f(276)) console.log(f(1540)) console.log(f(2701)) console.log(f(5050)) console.log(f(7626)) console.log(f(18915)) console.log(f(71253)) console.log(f(173166)) console.log(f(222111)) console.log(f(303031)) console.log(f(307720)) console.log(f(500500)) console.log(f(998991)) console.log('Testing falsy test cases'); console.log(f(2)) console.log(f(4)) console.log(f(5)) console.log(f(7)) console.log(f(8)) console.log(f(9)) console.log(f(11)) console.log(f(16)) console.log(f(32)) console.log(f(50)) console.log(f(290)) console.log(f(555)) console.log(f(4576)) console.log(f(31988)) console.log(f(187394)) console.log(f(501500)) console.log(f(999999)) ``` ### Non-recursive version (ES7), 19 bytes Port of [Adnan's answer](https://codegolf.stackexchange.com/a/122091/58563). ``` x=>(8*x+1)**.5%1==0 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 40 bytes ``` (([{}](((()))<>))<>){<>({}({}({})))}{}{} ``` [Wheat Wizard](http://chat.stackexchange.com/users/218449) and I had a [duel](https://codegolf.meta.stackexchange.com/q/12423/57100) over this question. When we decided to post our solutions we were tied at 42 bytes, but I found a 2 byte golf of his solution. We decided that would count as the tie breaker (my solution is below). [Try it online!](https://tio.run/nexus/brain-flak#@6@hEV1dG6sBBJqamjZ2YFxtY6dRXQtBQNHaaiD8/9/QAAA "Brain-Flak – TIO Nexus") ### Explanation: ``` # Set up the stacks like this: -input 1 -input 1 1 (([{}](((()))<>))<>) ^ # Output 1 for triangular and 0 for non-triangular {<>({}({}({})))}{}{} ``` For a full explanation please see [Wheat Wizard's answer](https://codegolf.stackexchange.com/a/122226/57100). --- # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 42 bytes ``` (([({})])<>){(({}())<>{}({})){((<>))}{}{}} ``` Outputs `0\n` (literal newline) for truthy, and the empty string for falsy. The idea is to subtract 1 then 2 then 3 all the way up to the input. If you hit 0, then you know this is a triangular number, so you can stop there. [Try it online! (truthy)](https://tio.run/##SypKzMzTTctJzP7/X0MjWqO6VjNW08ZOs1oDyNTQBDKBFFAQJAAU1qytBsLa//9NTQE "Brain-Flak – Try It Online") [Try it online! (falsy)](https://tio.run/##SypKzMzTTctJzP7/X0MjWqO6VjNW08ZOs1oDyNTQBDKBFFAQJAAU1qytBsLa//9NzQA "Brain-Flak – Try It Online") ``` # Push -input on both stacks. One is a counter and the other is a running total (([({})])<>) # Count up from -input to 0 { # Push the new total which is: (counter += 1) + total (popped) + input (not popped) # This effectively adds 1, then 2, then 3 and so on to the running total (({}())<>{}({})) # If not 0 { # Push to 0s and switch stacks to "protect" the other values ((<>)) # End if } # Pop the two 0s, or empty the stack if we hit 0 {}{} # End loop } ``` --- ### Here's a 46 byte solution that I found interesting. ``` {<>(({}())){({}[()]<>{(<({}[()])>)}{}<>)}{}<>} ``` Outputs `0\n` (literal newline) for truthy, the empty string for falsy. The idea is to count down from input by consecutive numbers, 1 at a time. E.g. `input - (1) - (1,1) - (1,1,1)`. Each time we subtract, if we aren't at 0 yet, we leave an extra value on the stack. That way, if we are at 0 and are still subtracting when we pop we remove the last value on the stack. If the input was a triangular number, we will end exactly at 0, and wont pop the 0. [Try it online! truthy](https://tio.run/##SypKzMzTTctJzP7/v9rGTkOjulZDU1OzGkhHa2jG2thVa9hA2Zp2mrXVtTZQsvb/f1MDUwMA "Brain-Flak – Try It Online") [Try it online! falsy](https://tio.run/##SypKzMzTTctJzP7/v9rGTkOjulZDU1OzGkhHa2jG2thVa9hA2Zp2mrXVtTZQsvb/fxNTczMA "Brain-Flak – Try It Online") ``` # Implicit input (call it I) # Until we reach 0, or the stack is empty { # Add 1 to the other stack and push it twice. This is our counter. <>(({}())) # While counter != 0 { # counter -= 1 ({}[()] # if I != 0 <>{ # I -= 1, and push 0 to escape the if (<({}[()])>) # End if } # Pop from the stack with I. This is either the 0 from the if, or I {} # Get ready for next loop End while <>) # End While } # Pop the counter that we were subtracting from {}<> # End Until we reach 0, or the stack is empty. } ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` ri2*_mQ_)*= ``` Outputs `1` for triangular, `0` otherwise. [Try it online!](https://tio.run/nexus/cjam#@1@UaaQVnxsYr6ll@/@/kSEA "CJam – TIO Nexus") ### Explanation Consider input `21`. ``` ri e# Input integer. STACK: 21 2* e# Multiply by 2. STACK: 42 _ e# Duplicate. STACK: 42, 42 mQ e# Integer square root. STACK: 42, 6 _) e# Duplicate, increment. STACK: 42, 6, 7 * e# Multiply. STACK: 42, 42 = e# Equal? STACK: 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ×8‘Ʋ ``` [Try it online!](https://tio.run/nexus/jelly#LY7LDQIxDETvVJECfLCdZB1XQBGr7QVxgBKgCE6UwHayjYQZRD4aa5w38dwf47g899vnPff7cX3hnOdcV5NSpSxSTHG7FIfTqUGzN2WpNLWjjsXpj@TbMO@gLaotcN3djIGK/dMIV5JAoZkj0zY5ldWlNDQQIWWggxAAhpDqBBCWJDlJ6xylWo7Bn6MmUbV/Jte2fQE "Jelly – TIO Nexus") ### Background Let **n** be the input. If **n** is the **k**th triangular number, we have $$ n = \frac{k(k+1)}{2} \iff k^2+k-2n = 0 \iff k = \frac12 (-1 \pm \sqrt{1+8n}), $$ which means there will be a natural solution if and only if **1 + 8n** is an odd, perfect square. Clearly, checking the parity of **1 + 8n** is not required. ### How it works ``` ×8‘Ʋ Main link. Argument: n ×8 Yield 8n. ‘ Increment, yielding 8n + 1. Ʋ Test if the result is a perfect square. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~31~~ 30 bytes ``` "$args"-in(1..1e6|%{($s+=$_)}) ``` [Try it online!](https://tio.run/nexus/powershell#@6@kkliUXqykm5mnYainZ5hqVqNaraFSrG2rEq9Zq/n//39TAwMgAgA "PowerShell – TIO Nexus") Nice and slow brute force method. Make an array of every sum of 1 through 106, and see if the argument is in there. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 42 bytes ``` (([{}](<((())<>)>))<>){<>({}({}({})))}{}{} ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hEV1dG6tho6GhoalpY6dpByarbew0qmshSFNTs7YaCP//NzYDAA "Brain-Flak – TIO Nexus") ## Explanation The goal of this program is to create a state on two stacks and perform constant operation on both stacks until one of them zeros, we can then output depending on which stack we are on. This is similar to programs that determine the sign of a number. These programs put `n` on one stack and `-n` on the other and add one and switch stacks until one of the stacks is zero. If the number was negative in the first place the first stack will hit zero, if the number was positive the other stack will hit zero. Here we create two stacks one that subtracts consecutive numbers from the input and one that just subtracts one. The one that subtracts consecutive numbers will only terminate if the number is triangular, (other wise it will just pass zero and keep going into the negatives). The other one will always terminate for any positive number, but will always do so slower than the first, thus non-triangular numbers will terminate on that stack. So how do we set up stacks so that the same operation subtracts consecutive numbers on one and subtracts one on the other? On each stack we have the input on top so that in can be checked, below that we have the difference and below that we have the difference of the difference. Each time we run we add the "difference of the difference" to the regular "difference" and subtract that from the input. For the stack that checks for triangularity we set our double difference to be `1` so that we get consecutive integers each time we run, for the other stack we set it to `0` so that we never change the difference, that is it always stays 1. Here is how the stack is set up at the beginning, where `n` is the input: ``` -n -n 0 1 1 0 ``` When we finally do terminate we can use these differences to check which stack we are on we pop the top two values and we get `1` for a triangular number and `0` for a non-triangular number. --- ### Annotated code ``` (([{}](<((())<>)>))<>) Set up the stack { While <> Switch stacks ({}({}({}))) Add bottom to second to bottom, add second to bottom to top } End while {}{} Pop the top two values ``` --- Here's a 50 byte solution I like as well. ``` {(({}[()]))}(([[]])<>){({}{}())<>}({}{()<><{}>}{}) ``` [Try it online!](https://tio.run/nexus/brain-flak#FcixCQAwDAPBdaQuTbqQRYwnEZrdUeCL40eAXGCTBqq6eS6VKYOxPxEc@WZyZq@VHg "Brain-Flak – TIO Nexus") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 23 ~~24~~ ~~25~~ bytes ``` I1Wq/)s.;0..s;p-?\.+O@u ``` 0 for truthy and nothing ~~0~~ for falsey. Brutes forces by incrementing counter, adding to cumulative sum and comparing to input. ~~Now to try and fit it on a 2x2x2 cube.~~ Did it! ``` I 1 W q / ) s . ; 0 . . s ; p - ? \ . + O @ u . ``` [Try it online!](https://tio.run/nexus/cubix#@@9pGF6or1msZ22gp1dsXaBrH6On7e9Q@v@/IQA "Cubix – TIO Nexus") * `/` Reflect to to face. * `I10\` get integer input, push 1 (counter), push 0 (sum) and reflect * `+s;p-` loop body. Add sum and counter, drop previous sum, raise input and subtract * `?` Test the result of the subtraction + For 0 result carrying on straight ahead `\.uO@` reflect to bottom face, no-op, U-turn, output and halt. + For positive result turn right onto bottom face and `@` halt + For negative result turn left `;qWs)/su` drop subtraction, put input to bottom, shift left, swap counter and sum, increment counter, reflect, swap sum and counter, U-turn onto main loop body. [Answer] # [R](https://www.r-project.org/), ~~23~~ 19 bytes Similar approach as other answers. Checks to see if `8x+1` is a perfect square. -4 bytes thanks Giuseppe and MickyT. ``` !(8*scan()+1)^.5%%1 ``` [Try it online!](https://tio.run/##JY1LCgJBDET3dQsXAzMKkkp3Op3LCOLehd6ftgYTyI9Xqc9al31ev6/nez9uPB732DYuomGABgacCNXUHt00mA4Whhyu2ywxSY8GZuMYcHdSH0x5tkw3KSQxVM0qwtEhFSYKQjnQXAi8RMqth@waa04ZZCvRxr/@jPUD "R – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` t:Ysm ``` [Try it online!](https://tio.run/nexus/matl#@19iFVmc@/@/oQEA "MATL – TIO Nexus") Explanation: ``` t % Duplicate input : % Range(1, input) Ys % Cumulative sum. This will push the first *n* triangular numbers m % ismember. Pushes true if the input is contained within the array we just pushed ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes **EDIT**: Thanks to @Dennis: Saved a byte because I forgot about the increment operator ``` 8*>t.ï ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fQsuuRO/w@v//zQA "05AB1E – Try It Online") `n` is triangular if `sqrt(8n + 1)` is an integer How it works ``` 8* # multiply implicit input by 8 > # add one t # sqrt .ï # is integer ``` [Answer] # [Perl 6](http://perl6.org/), 17 bytes ``` {$_∈[\+] 1..$_} ``` Just checks whether `$_`, the input to the function, is equal to any of the elements of the triangular addition reduction `(1, 1+2, ..., 1+2+...+$_)`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ≥ℕ⟦+? ``` [Try it online!](https://tio.run/nexus/brachylog2#@/@oc@mjlqmP5i/Ttv//39AUAA "Brachylog – TIO Nexus") ## Explanation ``` ≥ℕ⟦+? ≥ℕ There is a number from 0 to {the input} inclusive ⟦ such that the range from 0 to that number + has a sum ? that equals the input ``` [Answer] # [Alice](https://github.com/m-ender/alice), ~~38~~ 22 bytes *A lot of bytes saved thanks to Martin and Leo* ``` / i \2*.2RE.h*-n/ o @ ``` There is a trailing newline. Outputs `1` for triangular, `0` otherwise. [Try it online!](https://tio.run/nexus/alice#@6@vkKkQY6SlZxTkqpehpZunr5Cv4MD1/7@hKQA) ### Explanation This uses the same approach as my [CJam answer](https://codegolf.stackexchange.com/a/122096/36398), only clumsier. In linearized form, the program becomes ``` i2*.2RE.h*-no@ ``` where the `i` and `o` are actually in ordinal mode. Consider input `21` as an example. ``` i Input integer STACK: 21 2* Multiply by 2 STACK: 42 . Duplicate STACK: 42, 42 2RE Integer square root STACK: 42, 6 . Duplicate STACK: 42, 6, 6 h Increment STACK: 42, 6, 7 * Multiply STACK: 42, 42 - Subtract STACK: 0 n Logical negation STACK: 1 o Output integer STACK: @ End program ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 7 bytes *Saved 3 bytes thanks to @Luke and @ETHproductions* ``` *8Ä ¬v1 ``` [Try it online!](https://tio.run/nexus/japt#@69lcbhF4dCaMsP//w0B) ### Explanation: ``` *8Ä ¬v1 ¬ // Square root of: *8 // Input * 8 Ä // +1 v1 // Return 1 if divisible by 1; Else, return 0 ``` --- ``` õ å+ øU ``` ### Explanation: ``` õ å+ øU õ // Create a range from [1...Input] å+ // Cumulative reduce by addition øU // Does it contain the input? ``` [Try it online!](https://tio.run/##y0osKPn///BWhcNLtRUO7wj9/183N4iLK9pQh8tYh8tMh8vQAIhNdbiMgCKmINocJGhqYgBiGhjqACkdLhOgnA6XuQ6XhQ6XJVAaqNYQqMwYKGVqEAsA) [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 4 bytes ``` ÅTs¢ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cGtI8aFF//@bAQA "05AB1E (legacy) – Try It Online") Explanation: ``` ÅT //push all triangle numbers <= (implicit) input s //push input onto stack ¢ //count occurrences of input in triangle numbers (i.e. 1 if triangle, 0 if not) ``` I'm using 05AB1E (legacy) since it pre-dates this challenge, but it works in current 05AB1E as well [Answer] # [TypeScript](https://www.typescriptlang.org/)’s type system, 91 bytes ``` //@ts-ignore type F<N,A=[],I=N["length"]>=N extends[...infer R,0]?F<R,[1,...R,...A],I>:A[I] ``` [Try it at the TS playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwLAChwE8AHdAAgDEAeAOQBoBBAXgG0BdagSXssYCIAbdRPHAALbswB8nYugAe4AQBNIjAHRrYiAGbpUxAErUADMwD8FA4wCM1NSoO3arNuIBctRm2Y5vuQiQAq6JDgAGzE9GTkjIZGsTHxEjggxCnEAHomOPhExIHBAJzhkdFxpfFxidjJqRlZfrlB4JaGRRQl5R1lRpXVKbXYQA) This is a generic type `F` taking a unary number `N` as a tuple of N zeroes. I never would have expected a challenge like this to be under 100 bytes in TS types, but in this instance it’s quite doable. This is almost definitely ungolfable. This works by creating the string `1101001000100001…`, which contains N ones separated by as many zeroes as there are already added ones, and indexing into this string with N. Explanation of the code: ``` //@ts-ignore - Suppress any type errors on the following line. type F< N, // N is a tuple type of 0s A=[], // A becomes the string, starts as an empty list I=N["length"] // I is the original N which we use to index at the end >= N extends[...infer R,0] // If a 0 fits in N, take the difference R (i.e. decrement) ?F<R, // If that succeeded, recurse with N = R, [1,...R,...A], // A with 1 then R prepended, I> // and I kept as it was. :A[I] // If it failed, N is 0, so index into A with the original number. ``` [Answer] ## Batch, 72 bytes ``` @set/aj=i=0 :l @if %1% gtr %j% set/aj+=i+=1&goto l @if %1==%j% echo 1 ``` Outputs 1 on success, nothing on failure. Works for zero too, although not requested by the question for some reason. [Answer] # JavaScript (ES7), ~~19~~ 18 bytes From [my answer](https://codegolf.stackexchange.com/a/119011/58974) to a [related question](https://codegolf.stackexchange.com/q/118980/58974). Outputs `false` for triangular numbers or `true` for non-triangular, as permitted by the OP. ``` n=>(8*n+1)**.5%1>0 ``` --- ## Try It ``` f= n=>(8*n+1)**.5%1>0 oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] # PHP, 30 Bytes Prints 1 for true and nothing for false ``` <?=fmod(sqrt(8*$argn+1),2)==1; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTOz5rK3@29jb5uWm5@iUVxYVKJhoQWW0zbU1DHStLU1tP7/HwA "PHP – TIO Nexus") [fmod](http://php.net/manual/en/function.fmod.php) # PHP, 37 Bytes Prints 1 for true and nothing for false ``` <?=($x=sqrt($q=2*$argn)^0)*$x+$x==$q; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTOz5rK3@29jb6uhUmFbXFhUoqFSaGukBZbVjDPQ1FKp0AbK2KoUWv//DwA "PHP – TIO Nexus") [Answer] ## Mathematica, 28 bytes ``` !Accumulate@Range@#~FreeQ~#& ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 18 bytes ``` n->issquare(8*n+1) ``` [Try it online!](https://tio.run/nexus/pari-gp#LY5BC8IwDIX/Sthp1Q6adF2bg/sj4mEHBwMpc9ODv36@iC0l6cd7L5npQkftxmXfn@9pu7flVM/sjmldH5@2UjfSui31hbaxT0NzW53zdGVP0dPgiQNe8iQgyWo2mPpgbTAYEvo8iPGips0sCW7OkQdQEWG2wID7qzlLMCesqKpFFVw89aDweyrASABlJEQxNRRqNlujT7ZHZC3FxuaoZg38D7Rzc8cX "Pari/GP – TIO Nexus") --- There is a built-in to test if a number is a polygonal number, but it is one byte longer. # [Pari/GP](http://pari.math.u-bordeaux.fr/), 19 bytes ``` n->ispolygonal(n,3) ``` [Try it online!](https://tio.run/nexus/pari-gp#LY6xCsMwDER/RWSKwQFLjmNraH6kdMiSEgiOabvk69NTqY2R/Lg7aaUbXXWYt3c79vN51GXvq4/uWlrbz77SMFN7bfWDtrNPR2tfnfN0Z0/R0@SJA17yJCDJajaYxmBtMBgS@jyJ8aKmzSwJbs6RJ1ARYbbAgPurOUswJ6yoqkUVXDyNoPB7KsBIAGUkRDE1FGo2W2NMtkdkLcXG5qhmDfwPtPNw1xc "Pari/GP – TIO Nexus") [Answer] # Python - 52 bytes ***Note:*** *I know that the other two Python answers are much shorter, but this is the old-school way, more of a by-hand algorithm* ``` n=input();i=s=0 while s<n:s=(i*i+i)/2;i+=1 print s>n ``` [Answer] # Excel, ~~31~~ 22 bytes 9 bytes saved thanks to Octopus Outputs `TRUE` for triangular numbers. Else `FALSE`. Checks if `8*n+1` is a perfect square. ``` =MOD(SQRT(8*B1+1),1)=0 ``` [Answer] # [Alchemist](https://github.com/bforte/Alchemist), 80 bytes ``` _->In_n+s f+b->f+a f+0b->a 0f+n+a->b 0f+0a+n->n+f 0n+a+s->Out_n 0n+0a+s->Out_"1" ``` [Try it online!](https://tio.run/##PcgxDoAgDEDRnWOwNk3q4tjdySOQohJJtJiA17fi4vb@l2PZtzPXZhaQJw0K1SWIyAmkg7rEUQIFQY6fSECRFZKjPqEiz3cL@hX96QdvNj7larloNVxf "Alchemist – Try It Online") [Test cases](https://tio.run/##TY47C8IwFIVn8ysuIdJKiEaki4/sTjroJpQ0D1rQG23qpP722CIUt@8cOI9KxzoZ3W23mUObgQITrJubFlMp1B5L5JF4Xgnlue5B9qSJ9By5FqoaSGqOQiH3RPYmj0Idnl2Jg5KjpEua@gHiQwsIDQLLo3sAW842YAOZHM6n4/m0Y7kzdQCG8IZFuHcLfTW1uzXxj8aHMzK5tw12Huh0ZQGm8YJ0yFL2@vWtBXwosQFdSkXxBQ) Subtracts increasing numbers from the input until it reaches 0, and checks if the counter is zero. ]
[Question] [ Given an input of a program written in [oOo CODE](http://esolangs.org/wiki/OOo_CODE), output the BF code that it represents. Here is a short description of how oOo CODE works: * First, all non-alphabetic characters are removed (everything not in the range `A-Za-z`). For example, take the program `PROgRam reVERsES giVeN iNPut sEqUENcE` (an example given on the esolangs wiki page that does exactly what you'd expect). After this first step, we now have `PROgRamreVERsESgiVeNiNPutsEqUENcE`. * Next, divide all remaining characters into groups of 3. We now have `PRO,gRa,mre,VER,sES,giV,eNi,NPu,tsE,qUE,NcE`. If there is a trailing group of 1 or 2 characters, discard it. * Convert each group of 3 letters into a BF command based on the following table: ``` ooo > ooO < oOo [ oOO ] Ooo - OoO + OOo . OOO , ``` That is, if the first letter of a group is lowercase, the second is uppercase, and the third is lowercase, it would translate to the command `[`. With our example, this finally becomes the BF program `,[>,]<[.<]+`, which does indeed reverse its input. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Test cases: ``` <empty string> -> <empty string> A -> <empty string> Ab -> <empty string> Abc -> - AbcD -> - AbcDe -> - AbcDef -> -- 1A_b%c*D[]e\\\f! -> -- PROgRamreVERsESgiVeNiNPutsEqUENcE -> ,[>,]<[.<]+ ``` [Answer] # oOo, ~~1569~~ 1515 bytes Had to be done. [Try it here](http://goo.gl/ISjwLB). Golfed: ``` oooooooooOoOoooooooooooooooOoOooooooOOOoOoooooooOoOOoOOoOOoOOoOOoOOoOOoOoOoooOOoOOoOOoOOoOOoOOoOOoOOoOoooOoooOOooOOoOooOoOoOoooooOoooOoooooOOooOooOoOOooOoOoOoooooOoOooooOoOoooooOoOooOoOOoooOoOooooooOoOOoOOoOOoOOoOoOoooOOoOOoOOoOOoOOoOoooOoooOOooOOoOOoOooOoOoOoooooOoooOoooooOOooOooOoOOooOoOoOoooooOoOooooOoOoooooOoOooOoOOoooOoOoooOoOOoOOoOOoOOoOOoOOoOooOoOoOoooooOoooOoooooOOooOooOoOOooOoOoOoooooOoOooooOoOoooooOoOooOoOOoooOoOooooooOoOOoOOoOOoOOoOoOoooOOoOOoOOoOOoOOoOoooOoooOOooOOoOOoOooOoOoOoooooOoooOoooooOOooOooOoOOooOoOoOoooooooooOoOoooOOooOooOoOOooOoOoOooooOooOooOooOooOooOooOooOooOooOooOOoOoooooooooooooooooooooooooooooooooooooooooooOoOoooOOooOooOooOooOoOOoOOooOoOoOooooooooooooOoOoooOOooOooOooOooOoOOoOOooOoOoOooooOooOooOooOooOooOooOooOooOOoOooooooooooooOoOoooooooooooooooooooooooooOoOoooOOooOooOooOooOoOOoOOooOoOoOooooooooooooOoOoooOOooOooOooOooOoOOooOooOooOooOooOooOooOoOoooooOooooooooooooooooOoOOoOOoOOoOOoOOoOoOoooOOoOOoOOoOOoOOoOOoOOoOoooOoooOOooOOoOOoOooOooOooOoOoooooOoooooOoooOOoooooOoooOOooOoOoooooooOoOOoOooOooOOoooOOooOOooooooOOooOoOooooOoOooooOooooOooooOooOOoooooOoooOOooOoOoooooooOoOooOooOOoooOOooOOoooOOooOOooooooOOooOoOooooOoOooooooooooooOoOOoOOoOOoOoOoooOOoOOoOOoOOoOoooOoooOOooOooOooOoOooooooooooOoOOoOOoOOoOOoOoOoooOOoOOoOOoOOoOOoOOoOoooOoooOOooOOoOooOoOooooOoOOoOooOooOOoooooOoooOOooOoOoOoooOOooOOooooooOOooOoOooooOoOooooOoooOOoooooOoooOOooOoOoooooooOoOOoOooOooOOoooOOooOOoooOOooOOoooOOOoOooooooooooooOOooOoOoooOOooOooOooOooOooOOooooOOooooOOoooOOoOOooooooooooooooooooooooooOoOooooooOOOoOO ``` Translated to Brainfuck (with linebreaks for clarity): ``` >>>+>>>>>+>>,[>>++++++++[<++++++++>-]<+<[->-[>]<<]<[->+>[->+<]>+>>+++++[<+++++>- ]<++<[->-[>]<<]<[->+>[->+<]>+>+++++++<[->-[>]<<]<[->+>[->+<]>+>>+++++[<+++++>-]< ++<[->-[>]<<]<[->>[-]<<]<[-<<<<<<<<<<<+>>>>>>>>>>>>>>[-]<<<<]]<[->>>[-]<<<<]]<[- <<<<<<<<<+>>>>+>>>>>>>>[-]<<<<]]<[->>>[-]<<<<]<<<<<<<[>[>>>>>++++++[<+++++++>-]< ++<<<[>[>[<->-]<[>>++<<-]<->]<[>+>[>-<<->-]<[>>+<<-]<-]<->]<[>+>>>>++++[<++++>-] <<<[>>>+++++[<++++++>-]<+<[>++<<->-]<[-]<->]<[>+>[<->-]<[>>++<<-]<-]<-]+>>>>.[-] <<<<<-<-<-]]>>>>>>>>+>>,] ``` Ungolfed with explanation: ``` this progrAm Translates ooo codE tO brainfUCK cOde. i guesS sINcE ThE ExAMpLE tEXt WAs SeLf-doCUmENtINg, I ShOUlD PrOBaBLy Make This SElf-DOcUmeNtInG too. oh, I shoUld menTIon ThaT i WRotE tHe OriginAl BrainFuCk code EnTirElY By haNd. If you waNt TO sEE tHE bRAiNfUck cODe, RUn THiS PrOGrAm wiTh itSElf AS iNPuT! baSiCaLly, thiS proGram seTS up MemOrY As fOlLoWs: the fIrSt thrEe Bytes aRe "ValId" FLags (V0, v1, V2), theN tHErE'S a BArRIeR (A 1) fOLlOweD bY tHree "vaLue" bIts (b0, b1, b2). THe rEst Of THe aRrAy Is basiCaLly juSt ScratcH sPacE. tO Save SpAce, i'm slIdINg THe POiNTeR fOrwaRD bY OnE In EAcH ItEratIon uNTil THe POiNteR hItS the baRrieR, at whiCH poInt ThE ProGrAm Prints out tHe ConvERteD chArACteR. tHe ProgrAm eXteNsiVelY usEs tHe cLevEr "gReaTEr-Than" comparison operator described by dheeraj ram aT hTtp://sTAckOveRflOw.cOm/QUeSTioNs/6168584/BrAinfuck-comparE-2-nUmbeRS. i hAppEn tO reAlLY lIKe tHiS iMplemEntAtiOn bEcaUse It iS boTh cOMpAct and nestablE, wHich is critical for my bf code tO wOrk pROpeRly. I seT up ThE ReQUisItE sTructure, then pErForm A BunCh oF neSteD cOMpaRisOns ThaT loOk rOugHlY like tHis: if(in >= 65 /* capital a */) { if(In <= 90 /* CApITaL Z */) { vI = 1 Bi = 1 } ELsE { iF(in >= 97 /* lOWeRCaSE a */) { IF(iN <= 122 /* LoWErCAsE z */) { vi = 1 } } } } At thE End OF tHEsE coMpaRisOnS, if the V (valid) Bit iS Set, the ProgRAm sTePs the poiNtER rIghTwaRDs. if IT hiTS the barRIer, It Then gOeS into A big sEt of nEstED condiTionALs tHaT test the AcCumUlaTEd vaLUe bITs, anD ConSTruct thE CorReSpondInG character to pRiNT oUT. tHEn It ReseTS bACk TO tHE iNitiAl stATe. fInaLly, It Reads anotheR iNPuT ChARaCTeR aNd goES bACk TO lOOpINg. SO tHere You hAVe iT - An Ooo To BrainFuCK cOnvErtER writtEn in OOo (aNd BrAinfUCk, bY ExtensiON!). siNcE i havE a Few moRe chARacterS to sPAre In This progRaM, HeRe's A coUPle oF StrESs teST paTTernS: 0123456789ABcDefghijklmnopQRstUvWxyzABcdEfgHijKlmNopQRstuvWXyz!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ~}|{`_^]\[@?>=<;:/.-,+*)('&%$#"!zyXWvutSRqPOnmlkjihgfedcbazyxwvutsrqPoNmlkjihGFEdCBa9876543210 ``` Thanks for the interesting challenge! [Answer] ## CJam, ~~36~~ 35 bytes ``` l{el_eu-},'_f<0+3/W<2fb"><[]-+.,"f= ``` [Test it here.](http://cjam.aditsu.net/#code=l%7Bel_eu-%7D%2C'_f%3C0%2B3%2FW%3C2fb%22%3E%3C%5B%5D-%2B.%2C%22f%3D&input=PROgRam%20reVERsES%20giVeN%20iNPut%20sEqUENcEs) ### Explanation ``` l e# Read input. {el_eu-}, e# Discard all characters that don't change in a lower/upper case e# transformation, i.e. non-letters. '_f< e# Compare with '_' to determine case as 0 or 1. 0+ e# Append a zero. 3/ e# Split into chunks of 3. W< e# Discard last chunk. 2fb e# Convert each chunk from base 2. ",.+-][<>"f= e# Select the corresponding character for each chunk. ``` [Answer] # JavaScript (ES6), ~~94~~ ~~93~~ ~~91~~ ~~85~~ ~~84~~ 83 bytes *Saved 1 byte thanks to @dev-null* ``` x=>x.replace(/[a-z]/gi,c=>(a+=c<'a'|0)[2]?b+="><[]-+.,"['0b'+a-(a="")]:0,a=b="")&&b ``` I've tried many variants of this, but this seems to be the shortest. Also works on empty input! ### How it works First, with `x.replace(/[a-z]/gi,c=>`, we find take each letter `c` in the input. We set `a` and `b` to `""` at the other end of the function call, since the function ignores any parameters past the second. `a` will store a binary string for determining which character we are currently making, and `b` will store the result. Now for the confusing part: first, with `(a+=+(c<'a'))`, we append a `0` to `a` if `c` is uppercase; `1` otherwise. This expression returns the new value of `a`, so then we can check if it has reached three chars of length with by checking if the character at index 2 exists:`[2]?`. If not, we simply end the function with `:0`. If `a` is now three chars in length, it is a binary number between `000` and `111`. We can convert this to a decimal number by appending `"0b"` to the beginning, then forcing the engine to parse it as a number with `'0b'+a-0`. However, we still need to reset `a` to the empty string. We can't just do `'0b'+(a="")-0` because that would mean the string parsed is just `0b`. Fortunately, when parsed as a number, the empty string becomes 0, so we can replace the `0` with `(a="")`. Now we have our number, and we can just append the character at that index in `"><[]-+.,"` to `b`. After the replace is done, we use `&&b` to return it from the function. (Well, unless the result of `.replace` is empty, which only happens on empty input and returns the empty string anyway.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ 32 bytes Code: ``` á0«3÷\)vyS).uïJC",.+-][<>"Sr@?)\ ``` Using a very clever trick from Martin Büttner, from [this answer](https://codegolf.stackexchange.com/a/74410/34388). Explanation: ``` á0« # Remove all non-alphabetic characters and append a zero 3÷\ # Split into pieces of 3 and discard the last one )v # Wrap everything into an array and map over it yS).uï # Is uppercase? Converts AbC to [1, 0, 1] JC # Join and convert from binary to int ",.+-][<>" # Push this string S # Split the string r@ # Reverse the stack and get the character from that index ? # Pop and print without a newline )\ # Wrap everything into an array and pop ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w6Ewwqszw7dcKXZ5UykudcOvSkMiLC4rLV1bPD4iU3JAPylc&input=UFJPZ1JhbXJlVkVSc0VTZ2lWZU5pTlB1dHNFcVVFTmNF) Uses **CP-1252** encoding. [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~79~~ ~~75~~ ~~71~~ 70 bytes *Thanks to randomra for saving 1 byte.* ``` i`[^a-z] M!`... m`^ ; +`(.*);(.) $1$1$2; T`l .+ $.& T`d`_><[]\-+., ¶ ``` [Try it online!](http://retina.tryitonline.net/#code=aWBbXmEtel0KCk0hYC4uLgptYF4KOworYCguKik7KC4pCiQxJDEkMjsKVGBsCi4rCiQuJgpUYGRgXz48W11cLSsuLArCtgo&input=UFJPZ1JhbSByZVZFUnNFUyBnaVZlTiBpTlB1dCBzRXFVRU5jRXM) ### Explanation ``` i`[^a-z] ``` We start by removing everything that's not a letter. ``` M!`... ``` This splits the string into chunks of three characters by returning all (non-overlapping) 3-character matches. This automatically discard any incomplete trailing chunk. ``` m`^ ; ``` Prepend a `;` to each line. We'll use this as a marker for the base-2 conversion. Speaking of which, we'll simply treat upper-case letters as `1` and lower-case letters as `0`. ``` +`(.*);(.) $1$1$2; ``` This does a funny base-2 to unary conversion. At each step we simply double the characters left of the `;` and move the `;` one to the right. Why does this work? Remember we'll be interpreting lower case as `0` and upper case as `1`. Whenever we process a letter, we simply double the running total (on the left) so far - double lower-case letters are just `2*0=0`, so they can be completely ignored and upper-case letters represent the binary number so far, so doubling them is what we want. Then we add the current letter to that running total which represents `0` or `1` correspondingly. ``` T`l ``` Remove all lower-case letters/zeroes. ``` .+ $.& ``` Match each line and replace it with the (decimal) number of characters in that line. Due to the `;` this turns the unary number into its decimal equivalent + 1. ``` T`d`_><[]\-+., ``` Transliteration which substitutes 1-8 with the corresponding command. ``` ¶ ``` Remove linefeeds. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~38~~ 32 bytes ``` '><[]-+.,'jt3Y2m)3ZCtAZ)92<!XBQ) ``` [**Try it online!**](http://matl.tryitonline.net/#code=Jz48W10tKy4sJ2p0M1kybSkzWkN0QVopOTI8IVhCUSk&input=UFJPZ1JhbXJlVkVSc0VTZ2lWZU5pTlB1dHNFcVVFTmNF) ``` '><[]-+.,' % push string with BF commands j % read input as a string t % duplicate 3Y2 % predefined literal: string 'A...Za...z' m % true for elements of input string that are letters ) % index into input string to keep only letters 3ZC % 2D array whose columns are non-overlapping slices of length 3. % The last column is padded with zeros if needed tA % duplicate. True for columns that don't contain zeros Z) % keep those columns only. This removes padded column, if any 92< % 1 for upper case letters, 0 for lower case letters in the 2D array ! % transpose so each group of 3 is a row XBQ % convert each row from binary to decimal and add 1 ) % index into string containing the BF commands. Implicitly display ``` [Answer] # Japt, ~~37~~ 36 bytes ``` Uo"%l" f'.³ £",><[]-+."gX®c ¤gJÃn2Ãq ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=VW8iJWwiIGYnLrMgoyIsPjxbXS0rLiJnWK5jIKRnSsNuMsNx&input=IlBST2dSYW0gcmVWRVJzRVMgZ2lWZU4gaU5QdXQgc0VxVUVOY0Ui) ### How it works ``` Uo"%l" f'.³ £ ",><[]-+."gX® c ¤ gJÃ n2Ã q Uo"%l" f'.³ mX{",><[]-+."gXmZ{Zc s2 gJ} n2} q Uo"%l" // Get rid of all non-letter chars in U. f'.³ // Take each set of three chars in U. mX{ } // Map each item X in this group to: XmZ{ } // Map each letter Z in X to: Zc s2 gJ // Take the char code of Z as a binary string, and take the first char. // This maps each character to 1 if it's UC, or 0 if it's lc. n2 // Interpret the result as a binary number. ",><[]-+."g // Get the item at this index in this string. q // Concatenate the result and implicitly output. ``` [Answer] ## JavaScript (ES6), ~~111~~ 95 bytes ``` s=>s.match(/[A-Z]/gi).map(c=>+(c<'a')).join``.match(/.../g).map(g=>'><[]-+.,'['0b'+g|0]).join`` ``` Simply removes non-letters, converts upper case letters into 1s and lower case into 0s, divides into groups of three, ignores a trailing group of 1 or 2, and decodes the groups. Edit: Saved 16 bytes thanks to @dev-null, although the code no longer works when passed the empty string. [Answer] # Pyth, 40 bytes ``` jkm@"><[]-+.,"id2f!%lT3cm?rId0Z1f!rIT2z3 ``` [Try it here!](http://pyth.herokuapp.com/?code=jkm%40%22%3E%3C%5B%5D-%2B.%2C%22id2f!%25lT3cm%3FrId0Z1f!rIT2z3&input=PROgRamreVERsESgiVeNiNPutsEqUENcE&test_suite=1&test_suite_input=A%0AAb%0AAbc%0AAbcD%0AAbcDe%0AAbcDef%0A1A_b%25c*D%5B%5De%5C%5C%5Cf!%0APROgRamreVERsESgiVeNiNPutsEqUENcE&debug=0) Could save 2 bytes if I can output the result as list of characters instead of a string. ## Explanation Filters out all non-letters, converts uppercase to 1 and lowercase to 0, splits into chunks of 3, interprets every chunk as binary number and uses this as index into a string which contains all BF commands. ``` jkm@"><[]-+.,"id2f!%lT3cm?rId0Z1f!rIT2z3 # z = input f z # filter input with T ! # logical not rIT2 # T == swapcase(T), true if T is not a letter m # map filter result with d ?rId0 # if d == toLower(d) Z1 # 0 for lowercase, 1 for uppercase c 3 # Split into chunks of 3, last element is shorter if needed f # filter with T ! # logical not %lT3 # len(t) mod 3 -> keep only elements of length 3 m # map with d id2 # Convert from binary to decimal @"><[]-+.," # Get the resulting BF command jk # Join to a string ``` [Answer] # Jolf, ~~31~~ 34 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=EM6cWmVaY0HPgWkFRXA0cHVwbHQzM2QuIj48W10tKy4sIs6ZSA) Replace `►` with `\x10` and `♣` with `\x05`. Because I implemented the chop function wrong, I gain 3 bytes. :( ``` ►ΜZeZcAAρi♣Epu1pl033d."><[]-+.,"ΙH ρi♣E remove all space in input A pu1 replace all uppercase letters with 1 A pl0 replace all lowercase letters with 0 Zc 3 chop into groups of three Ze 3 keep groups of length three Μ d map ΙH parse element as binary ."><[]-=.," and return a member of that ► join by nothing ``` [Answer] ## Python 3, 91 bytes ``` b=1 for c in input(): b=-~c.isalpha()*b+c.isupper() if b>7:print(end="><[]-+.,"[b-8]);b=1 ``` Hmm... looks a bit long, especially the second line. `b=[b,2*b+(c<'a')][c.isalpha()]` is slightly worse though. [Answer] ## [Hoon](http://github.com/urbit/urbit), 212 bytes ``` =+([v=turn c=curr q=cold k=tape] |=(t/k `k`(v (v `(list k)`(need ((unit (list k)) p:(rose (murn t (c rush alf)) (star (stun [3 3] ;~(pose (q '0' low) (q '1' hig))))))) (c scan bin)) (c snag (rip 3 '><[]-+.,'))))) ``` Ungolfed: ``` |= t/tape ^- tape %+ turn %+ turn ^- (list tape) %- need %- (unit (list tape)) =+ t=(murn t (curr rush alf)) p:(rose t (star (stun [3 3] ;~(pose (cold '0' low) (cold '1' hig))))) (curr scan bin) (curr snag (rip 3 '><[]-+.,')) ``` 1. use ++murn to get rid of all characters in the input that can't be parsed with "alf" (alphabet) 2. parse the list with a combinator that outputs each 3 characters at a time to a list, replacing lowercase with '0' and uppercase with '1' 3. Cast the result to (unit (list tape)) and forcibly unwrap it to get the furthest parsed result, to work with only multiple of threes without crashing 4. Map over the list, parsing each group as if it were binary 5. Use each number in the list as an index into the text '><[]-+.,', and cast the list back out to a tape. Hoon doesn't have proper regular expressions, only a parser combinator library, so it's sadly pretty verbose. ++scan also crashes if the entire input stream isn't parsed, so I have to use ++rose, coerce it into a unit, and unwrap it for the "farthest parse" value. It also makes heavy use for currying and mapping over lists (++turn), so I alias the function names to one letter variables. Hoon is the programming language for Urbit, a clean slate reimplementation project. It's purely functional, statically typed, vaguely lisp-like, and compiles to Nock. Nock is a combinator based VM that runs on top of a binary tree bignum memory model. When you boot Urbit you are dropped into :dojo, the shell and Hoon repl. To run the snippet simply type: ``` %. "PROgRam reVERsES giVeN iNPut sEqUENcE" ``` and then paste the standalone function on the next line. [Answer] ## [Jelly](http://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` =Œs¬Tịµ=Œu;0s3ṖḄ€ị“<[]-+.,> ``` [Try it online!](http://jelly.tryitonline.net/#code=PcWSc8KsVOG7i8K1PcWSdTswczPhuZbhuITigqzhu4vigJw8W10tKy4sPg&input=&args=IjFBX2IlYypEW11lXFxcXFxcZiEi) Note that backslashes need escaping in the input string for the second last test case. ``` Implicit input: string s (list of characters) =Œs Compare with swapcase ¬ Not - this gives 1 for letters, 0 otherwise Tị Take characters at truthy indices µ Start a new monadic chain Input: string s' (list of letters) =Œu Compare with uppercase ;0 Append 0 s3 Split into chunks of length 3 Ṗ Pop last chunk Ḅ€ Apply convert-from-binary to each chunk ị“<[]-+.,> For each number, 1-based index cyclically into the string "<[]-+.,>" ``` [Answer] # Matlab, 98 bytes ``` function t(s);s=s(isletter(s));s=s(1:end-mod(end,3));r='><[]-+.,';r([4 2 1]*reshape(s<92,3,[])+1) ``` 1. Clean 2. Trim 3. reshape into a 3xn Matrix m with UC = 1, lc =0 4. (4 2 1)\*m+1 results in an index list 5. Index to the right chars [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 154 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 19.25 bytes ``` Ǎvæ3ẇ'L3=;vBkTṖ»AǑ»iiṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPSIsIiIsIseNdsOmM+G6hydMMz07dkJrVOG5lsK7QceRwrtpaeG5hSIsIiIsIkFcbkFiXG5BYmNcblxuQWJjRFxuQWJjRGVcbkFiY0RlZlxuMUFfYiVjKkRbXWVcXFxcXFxmIVxuUFJPZ1JhbXJlVkVSc0VTZ2lWZU5pTlB1dHNFcVVFTmNFIl0=) ``` Ǎ # remove non alphabeticals væ # get the case of each char (0 for lower, 1 for upper) 3ẇ # wrapped into chunks of length 3 'L3=; # keep only those of length 3 vB i # converted from binary and indexed into kTṖ»AǑ»i # the 16560th permutation of the BF instruction set ṅ # join by nothing ``` [Answer] # Perl, ~~76~~ ~~73~~ 72 + 1 = 73 bytes ``` $a.=y+A-Z++dfor/[A-Z]/gi;print substr"><[]-+.,",oct"0b$_",1for$a=~/.../g ``` Requires the `-n` flag: ``` $ perl -n oOo.pl <<< 'PROgRamr{}\eVERsESgiVeNiNPutsEqUENcE' ,[>,]<[.<]+ ``` Using the [trick with base-2 conversion](https://codegolf.stackexchange.com/a/74406/48657). How it works: ``` # '-n' auto read first line into `$_` for/[A-Z]/gi; # Iterate over all letters a-z $a.=y/A-Z//d # Count number of uppercase letters (1 or 0) for$a=~/.../g # Split $b into hunks of 3 characters. And # remove any potential trailing characters. substr"><[]-+.,",oct"0b$_",1 # `oct("0b$binary")` will convert binary # to decimal. print ``` [Answer] # Julia, 107 bytes ``` s->"><[]-+.,"[map(j->parse(Int,j,2)+1,[map(i->i<'_'?'1':'0',m)for m=matchall(r"\w{3}",filter(isalpha,s))])] ``` This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable. Ungolfed: ``` function f(s) # Brainfuck commands bf = "><[]-+.," # Filter out non-alphabetic characters from the input chars = filter(isalpha, s) # Get all non-overlapping groups of three characters groups = matchall(r"\w{3}", chars) # Construct binary strings by comparing to _ binary = [map(i -> i < '_' ? '1' : '0', m) for m = groups] # Parse each binary string as an integer and add 1 indices = map(j -> parse(Int, j, 2) + 1, binary) # Return the Brainfuck commands at the indices return bf[indices] end ``` [Answer] ## Lua, 120 Bytes Big use of `string.gsub()` here, one more time could have allowed me to create a one character pointer on this function to gain some bytes. Also, it is my first lua program without any spaces! :D This program takes its input via command-line argument and output a BrainFuck program, one command per line. **Edit: Saved 1 Byte thanks to @Oleg V. Volkov** ``` arg[1]:gsub("[%A]",""):gsub("%l",0):gsub("%u",1):gsub("...",function(c)x=1+tonumber(c,2)print(("><[]-+.,"):sub(x,x))end) ``` ### Ungolf and explanations ``` arg[1]:gsub("[%A]","") -- replace the non-letter character by an empty string -- %A matches all the character not in %a (letters) :gsub("%l",0) -- replace lower case letters by 0s :gsub("%u",1) -- replace upper case letters by 1s :gsub("...",function(c) -- iterate over all groupe of 3 characters x=tonumber(c,2)+1 -- convert the 3-letter group from binary to decimal print(("><[]-+.,") -- output the corresponding brainfuck command :sub(x,x)) end) ``` [Answer] # Python 2, 112 bytes ``` ''.join('><[]-+.,'[int('%d'*3%tuple(map(str.isupper,y)),2)]for y in zip(*[iter(filter(str.isalpha,input()))]*3)) ``` Will try to golf it more. [Answer] # Mathematica, 192 bytes ``` StringJoin[FromDigits[#,2]&/@Partition[ToCharacterCode@#-48,3]&[StringDelete[#,a_/;!LetterQ[a]]~StringReplace~{_?UpperCaseQ->"1",_?LowerCaseQ->"0"}]/.Thread[0~Range~7->Characters@"><[]-+.,"]]& ``` Anonymous function that takes the desired string as an argument. Steps in the (pretty straightforward) algorithm: 1. Clean the string 2. Replace UC->"1", lc->"0" 3. Turn the string into a binary list 4. Partition the list into threes and interpret each chunk as a base-2 number 5. Replace the numbers with their appropriate symbols and join back into a string. [Answer] # Ruby ~~117~~ ~~114~~ ~~113~~ ~~111~~ ~~86~~ 79 Bytes ``` gets.tr(?^+m='a-zA-Z','').tr(m,?0*26+?1).scan(/.../){$><<"><[]-+.,"[$&.to_i 2]} ``` * `tr(?^+m='a-zA-Z','')` sets m to `'a-zA-Z'` and removes non-letters * `.tr(m,?0*26+?1)` converts lowercase to 0, uppercase to 1 * `.scan(/.../)` chunk string into groups of 3 and discard last group if it has less than 3 * `{$><<"><[]-+.,"[$&.t‌​o_i 2]}` convert each binary number to a character [Answer] # Perl 6, 81 bytes This can probably be done better, but this is my go at it ``` {m:g/:i<[a..z]>/;[~] ("><[]-+.,".comb[:2[$_]]for (+(91>$_.ord)for |$/).rotor(3))} ``` **Usage** ``` > my &f = {m:g/:i<[a..z]>/;[~] ("><[]-+.,".comb[:2[$_]]for (+(91>$_.ord)for |$/).rotor(3))} -> ;; $_? is raw { #`(Block|149805328) ... } > f("PROgRamreVERsESgiVeNiNPutsEqUENcE") ,[>,]<[.<]+ ``` **Ungolfed** ``` sub oOo ($_) { m:g/:i<[a..z]>/; # Match all letters and put them in $/ my @digits = ( for |$/ -> $c { # For all $c in $/ +(91>$c.ord) # 1 if $c.ord < 91 else 0 } ); @digits.=rotor(3); # Split the digits into chunks of 3 my @chars = ( for @digits -> @l { "><[]-+.,".comb[:2[@l]] # Take the character from "><[]-+.," # at an index given by converting # @l (a list of 3 binary digits) # from base 2 to base 10 } ); @chars.join # Join the list of chars into a string and return } ``` [Answer] # C++, ~~173~~ 167 bytes Full program, golfed (reads from standard input): ``` #include <cstdio> main(){for(char*a="@[`{>-[.<+],",c,o=0,t=1;(c=getchar())>0;)if(c=c>*a&&c<a[1]?2:c>a[2]&&c<a[3]?1:0){o|=c>1?t:0;t*=2;if(t>4)putchar(a[o+4]),o=0,t=1;}} ``` Somewhat ungolfed: ``` #include <cstdio> main(){ for(char*a="@[`{>-[.<+],",c,o=0,t=1;(c=getchar())>0;) if(c=c>*a&&c<a[1]?2:c>a[2]&&c<a[3]?1:0){ o|=c>1?t:0; t*=2; if(t>4)putchar(a[o+4]),o=0,t=1; } } ``` Note that `@A` ... `Z[` in ASCII, and likewise for ``a` ... `z}`. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 27 bytes ``` r\L ò3 l3 Ëmè\A Íg"><[]-+., ``` Saved 3 bytes thanks to @Shaggy [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVA&code=clxMIPIzIGwzIMtt6FxBIM1nIj48W10tKy4s&input=IlBST2dSYW1yZVZFUnNFU2dpVmVOaU5QdXRzRXFVRU5jRSI) [Answer] ## Pyke, 31 bytes, noncompetitive Pyke is older than the challenge, but I added some features to make it more competitive - chunk function. I used the same trick as [@Martin Büttner](https://codegolf.stackexchange.com/a/74410/32686) used. ``` #~l{)\`Lm<0+3cFb2"><[]-+.,"@)st ``` [Try it here!](http://pyke.catbus.co.uk/?code=%23%7El%7B%29%5C%60Lm%3C0%2B3cFb2%22%3E%3C%5B%5D-%2B.%2C%22%40%29st&input=PROgRamreVERsESgiVeNiNPutsEqUENcE) [Answer] # JavaScript, 148 bytes ``` function a(s){function b(c){return c.charCodeAt()&32}return (l=(s=s.replace(/[^a-z]/gi)).substr(3))?",.+-][<>"[b(s[0])*4+b(s[1])*2+b(s[2])]+a(l):""} ``` [Answer] # TI-BASIC, ~~311~~ 288 bytes What, no TI-BASIC answers? Time for me to fix that! ``` Ans→Str1:" →Str2:" →Str6:"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str4:For(S,1,length(Str1:sub(Str1,S,1:If inString(Str4+"abcdefghijklmnopqrstuvwxyz",Ans:Str2+Ans→Str2:End:sub(Str2,2,length(Str2)-1→Str2:For(B,1,.1+3⁻¹length(Str2:sub(Str2,3B-2,3→Str3:1+sum({4,2,1}seq(0≠inString(Str4,sub(Str3,X,1)),X,1,3→L₁(B:End:For(C,1,.1+dim(L₁:Str6+sub("><[]-+.,",L₁(C),1→Str6:End:sub(Str6,2,length(Str6)-1→Str6 ``` Input is the **oOo** code in `Ans`. Output is the translated **BF** code. **Examples:** ``` "AbcDef AbcDef prgmCDGF18 -- "PROgRam reVERsES giVeN iNPut sEqUENcE PROgRam reVERsES giVeN iNPut sEqUENcE prgmCDGF18 .[>,]<[.<]+ "AbcDe AbcDe prgmCDGF18 - ``` **Un-golfed:** (Newlines and comments added) ``` Ans→Str1 ;store the input in "Str1" " →Str2 ;set "Str2" and "Str6" to a " →Str6 ; space character ; (needed b/c TI-BASIC doesn't ; like concatenating empty ; strings) "ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str4 ;store the uppercase alphabet ; in "Str4" For(S,1,length(Str1 ;loop over the input string sub(Str1,S,1 ;get the current character If inString(Str4+"abcdefghijklmnopqrstuvwxyz",Ans ;if the character is in either ; the uppercase or lowercase ; alphabet Str2+Ans→Str2 ;add it to "Str2", the code ; string End sub(Str2,2,length(Str2)-1→Str2 ;remove the space added earlier For(B,1,.1+3⁻¹length(Str2 ;loop over each 3-char substring ; and skip any extra chars ; (.1 is added to force one ; loop) sub(Str2,3B-2,3→Str3 ;store said substring in "Ans" 1+sum({4,2,1}seq(0≠inString(Str4,sub(Str3,X,1)),X,1,3→L₁(B ;convert to the respective ; index in "><[]-+.," ; (1-indexed) End For(C,1,.1+dim(L₁ ;loop over each index ; (.1 is added to force one ; loop) Str6+sub("><[]-+.,",L₁(C),1→Str6 ;add the char to the translation ; string End sub(Str6,2,length(Str6)-1→Str6 ;remove the added space and ; store the result in "Str6" ; and "Ans" ;implicit print of "Ans" ``` --- **Notes:** * TI-BASIC is a tokenized language. Character count does ***not*** equal byte count. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `J`, 21 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Ị³fæl3=;2ȷḋkŻ8ṗ«@ṅisi ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0kpdS7IKlpSVpuhY3lR7u7jq0Oe3wshxjW2ujE9sf7ujOPrrb4uHO6YdWOzzc2ZpZnLmkOCm5GKp-wU3FgCD_9KDE3KLUMNegYtfg9MywVL9Mv4DSkmLXwlBXv2RXiEoA) Port of emirps's Vyxal answer. #### Explanation ``` Ị³fæl3=;2ȷḋkŻ8ṗ«@ṅisi # Implicit input Ị # Remove non-alphabets ³ # Split into groups of length 3 f # Case of each character in each group æ ; # Filtered by: l # Length 3= # Equals 3 ȷ # To each: 2 ḋ # Convert from binary kŻ # Push "[]<>-+.," 8ṗ # All permutations «@ṅ # Compressed integer 16560 i # Index into permutations si # Index into the above # Implicit output of joined list ``` ]
[Question] [ Given an input string `S`, print `S` followed by a non-empty separator in the following way: * Step 1: `S` has a `1/2` chance of being printed, and a `1/2` chance for the program to terminate. * Step 2: `S` has a `2/3` chance of being printed, and a `1/3` chance for the program to terminate. * Step 3: `S` has a `3/4` chance of being printed, and a `1/4` chance for the program to terminate. * … * Step `n`: `S` has a `n/(n+1)` chance of being printed, and a `1/(n+1)` chance for the program to terminate. ### Notes * The input string will only consist of characters that are acceptable in your language's string type. * Any non-empty separator can be used, as long as it is always the same. It is expected that the separator is printed after the last print of `S` before the program terminates. * The program has a `1/2` chance of terminating before printing anything. * A trailing new line is acceptable. * Your answer must make a genuine attempt at respecting the probabilities described. Obviously, when `n` is big this will be less and less true. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # C#, 94 85 bytes My first answer! ``` using System;s=>{var r=new Random();for(var i=2;r.Next(i++)>0;)Console.Write(s+" ");} ``` Previous attempt (I liked that `goto`): ``` using System;s=>{var i=2;var r=new Random();a:if(r.Next(i++)>0){Console.Write(s+" ");goto a;}} ``` Ungolfed: ``` using System; class P { static void Main() { Action<string> f = s => { var r = new Random(); for (var i = 2; r.Next(i++) > 0;) Console.Write(s + " "); }; f("test"); Console.ReadKey(); } } ``` Note: in C# the `Random.Next(N)` method returns a nonnegative integer in the [0, N-1] range, so we can just check that the number returned is greater than 0. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` WOh=hZQ ``` [Try it online!](http://pyth.herokuapp.com/?code=WOh%3DhZQ&input=%22Hello%2C+world%21%22&debug=0) ## How it works Pseudocode: ``` while rand_int_below(1 + (Z += 1)): print(input) ``` [Answer] # R, ~~47~~ ~~46~~ 43 bytes 43 bytes due to Robin Ryder in the comments. ``` s=scan(,"") while(sample(T<-T+1)-1)print(s) ``` [Try it online!](https://tio.run/##K/r/v9i2ODkxT0NHSUnTujwjMydVozgxtwBIhdjohmgbauoaahYUZeaVaBRr/k/Lz/8PAA "R – Try It Online") ### Explanation ``` s=scan(,"") # Takes input from stdin. T<-T+1 # T is 1 by default, so this # evaluates to 2, and will increment # at each step. sample(T<-T+1) # Take a sample of size 2, i.e. generate # a list of integers from 1 to 2 in random order sample(T<-T+1)-1 # Subtract one from every element of this list. while(sample(T<-T+1)-1)# while() will treat the first value in this list # as a logical value, i.e. FALSE for zero and TRUE # for nonzero values. The other elements of the list # are ignored, triggering a warning. print(s) # print s ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` [NÌL.R#, ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2u9wj49ekLLO//@ZeQWlJQrFJUWZeelf8/J1kxOTM1IB "05AB1E – Try It Online") **Explanation** ``` [ # start loop NÌL # push range [1 ... current_iteration+2] .R # pick a random number # # if true (1), exit loop , # print input ``` [Answer] ## Javascript, ~~60~~ ~~58~~ 54 bytes ``` f=(s,n=1)=>Math.random()<n/++n?console.log(s)+f(s,n):0 ``` Will output string `s`. The seperator which is printed if the program terminates is `NaN` or `0`. ``` f=(s,n=1)=>Math.random()<n/++n?console.log(s)+f(s,n):0 f('test') ``` `Math.random()` returns a value between 0 and 1. If that value is under `n/(n+1)`, then `s` will be pritned. 4 bytes saved thanks to @Neil [Answer] # Java 8, ~~72~~ ~~62~~ 61 bytes ``` s->{for(int n=2;Math.random()<1f/n++;System.out.println(s));} ``` -10 bytes thanks to *@cliffroot*. -1 byte thanks to *@JollyJoker*. Delimiter is a new-line. **Explanation:** [Try it here.](https://tio.run/##LY5BDoIwEEX3nGLCqg0Bo9uKN8CN7oyLsRQpwpTQ0cQQju0ai7L5yfxk3n8NvjB1vaGmfMy6Re@hQEtjBGCJzVChNnBcToCXsyVoceLB0h28VKGdohCeka2GIxDkMPv0MFZuEOEfKN@pArnOBqTSdULut9WGkkSd3p5Nl7knZ33AcUvCS6mmWS3A/nlrA3Dl/na7YLVOX66A8q9EmRbx2XiOV5tp/pBLNerafAE) ``` s->{ // Method with String parameter and no return-type for( // Loop int n=2; // Start `n` on 2 Math.random()<1f/n++; // Continue loop as long as a random decimal (0.0-1.0) // is smaller than 1/`n` (and increase `n` by 1 afterwards) System.out.println(s) // Print the input-String ); // End of loop } // End of method ``` [Answer] # Mathematica, 43 bytes ``` (n=1;While[RandomInteger@n>0,Print@#;n++])& ``` *JungHwan Min saved 1 byte (above) and suggested something better (below)* # Mathematica, 37 bytes ``` For[n=1,RandomInteger@n++>0,Print@#]& ``` [Answer] ## Clojure, ~~61~~ 56 bytes Oh why didn't I go with a `for` in the first place? But actually to be pedantic `doseq` has to be used as `for` is evaluated lazily. ``` #(doseq[n(range):while(>(rand-int(+ n 2))0)](println %)) ``` Original: ``` #(loop[n 2](if(>(rand-int n)0)(do(println %)(recur(inc n))))) ``` [Answer] ## [><>](https://esolangs.org/wiki/Fish), ~~124~~ 112 bytes ``` i:0( ?v &5a ~/ &p0[^ >"\_\^x0!>"0&1+:&p1&:&p2&:&p3&:&p4&:&p0&1+:&p3&:&p4&: =?v[/!}l]:?!;1 {: ?^ > :o>_ {:?!^ ``` [Try it online!](https://tio.run/##S8sszvj/P9PKQEPBvoxLQc00UaFOn0utwCA6TsFOKSY@Jq7CQNFOyUDNUNtKrcBQDUgYgQhjEGECIqBSMAEuW/uyaH3F2pxYK3tFa0OuaisFBQX7OAUFOy6rfLt4hWqgcNz//8WJRSmZealf8/J1kxOTM1IB "><> – Try It Online") (You can also watch it at the [fish playground](https://fishlanguage.com/playground), but due to some bugs you have to add a `}` after the `l` in the fourth line and add a bunch of newlines after the code to make it work properly.) Randomness is tricky in ><>. The only random instruction is `x`, which picks the fish's direction randomly from four choices (left, right, up and down), so turning that into something with probability 1/*n* is not straightforward. The way this code does it is by using ><>'s self-modifying capabilities to build a Tower of Randomness below the code, so at the fourth stage, for example, the code looks like: ``` i:0( ?v &5a ~/ &p0[^ >"\_\^x0!>"0&1+:&p1&:&p2&:&p3&:&p4&:&p0&1+:&p3&:&p4&: =?v[/!}l]:?!;1 {: ?^ > :o>_ {:?!^ >!0x^ \ _\ >!0x^ \ _\ >!0x^ \ _\ >!0x^ \ _\ ``` The fish starts at the bottom of the tower. At each level of the tower, the `x` is trapped between two mirrors, so the fish can only escape by going left or right. Either of these directions sends the fish up to the next level of the tower, but going left also pushes a `0` to the stack. By the time the fish gets to the top of the tower, the stack contains some number of `0`s, and this number follows a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) with *n* trials and *p* = 1/2. If the length of the stack is 0 (which has probability 1/2*n*), the program halts. If the length is 1 (with probability *n*/2*n*), the fish prints the input and a newline and builds another level of the tower. If the length is anything else, the fish discards the stack and goes back to the bottom of the tower. In effect, out of the possibilities that actually do something, *n* of them print the input string and one of them halts the program, giving the required probabilities. [Answer] # [Python 3](https://docs.python.org/3/), 72 69 66 bytes * Saved 3 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan): Import shorthand and start count from 2. * Saved 3 bytes thanks to [L3viathan](https://codegolf.stackexchange.com/users/21173/l3viathan) : Pointed randint() was inclusive and also shortened while condition. ``` from random import* s=input();i=1 while randint(0,i):print(s);i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocRXbZuYVlJZoaFpn2hpylWdk5qSClWTmlWgY6GRqWhUUgZjFQHltW8P//4vTUoCwOOVrXr5ucmJyRioA "Python 3 – Try It Online") [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~19~~ 17 bytes *Dropped `=1`, switched conditionals, saved 2 bytes* ``` {p=p+1~_rp||?;\_X ``` ## Explanation ``` { Infinitely DO p=p+1 Add 1 to p (p starts as 0, so on first loop is set to 1, then 2 etc...) ~ IF _rp|| a random number between 0 and p (implicitly: is anything but 0) ?; THEN print A$ (which gets read from the cmd line) \_X ELSE QUIT END IF and LOOP are auto-added at EOF ``` [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 23 bytes ``` #|V12[R!&@v!r?<1+>1+]|; ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/9fuSbM0Cg6SFHNoUyxyN7GUNvOUDu2xvr///8hxaklX/PydZMTkzNSAQ "Braingolf – Try It Online") Generates random number `x` where `0 <= x < n+1`, terminates if `x` is 0, otherwise increments `n` and loops. Separator is `|` ## Explanation: ``` #|V12[R!&@v!r?<1+>1+]|; Implicit input of commandline args to stack #| Push | V Create stack2 and switch to it 12 Push 1, then 2 [..............] Do-While loop, will run indefinitely unless conditional skips Closing bracket R Return to stack1 !&@ Print entire stack without popping v Switch to stack2 !r Generate random number 0 <= x < n where n is last item on stack ? If last item is greater than 0.. < ..Move first item to end of stack 1+ ..and increment, this is the loop counter number > ..Move back 1+ ..and increment, this is the upper range of the RNG ] ..end loop | Endif ; Suppress implicit output ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 18 bytes ``` /?!\v \iO/>]qhUn$@ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fXjGmjCsm01/fLrYwIzRPxeH//7z8/JSc1OKvefm6yYnJGakA "Alice – Try It Online") ### Explanation ``` / Reflect to SE. Switch to Ordinal. i Read all input as a string and push it to the stack. ! Store the string on the tape. / Reflect to E. Switch to Cardinal. > Ensure that the IP moves east. This begins the main loop. ] Move the tape head to the right. We'll be using the tape head's position as a counter variable. Note that this tape head is independent of the one used in Ordinal mode to point at the input string. q Push the tape head's position to the stack. h Increment it (so that it's 2 initially). U Get a uniformly random number in [0,n). n Logical NOT. Gives 1 with probability 1/n and 0 otherwise. $@ Terminate the program if we got a 1. \ Reflect to NE. Switch to Ordinal. ? Retrieve the input from the tape. O Print it with a trailing linefeed. \ Reflect to E. Switch to Cardinal. v Send the IP south where it runs into the > to start the next loop iteration. ``` [Answer] # [PHP](https://php.net/), 31 bytes ``` for(;rand()%~++$c;)echo$argn._; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerlJlXUFqiZP0/Lb9Iw7ooMS9FQ1O1TltbJdlaMzU5Ix@sSi/e@v//r3n5usmJyRmpAA "PHP – Try It Online") [Answer] ## Perl, 26 bytes **24 bytes code + 2 for `-nl`.** ``` print while rand++$i+1|0 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRKE8IzMnVaEoMS9FW1slU9uwxuD/f4/UnJx8HYXw/KKcFMV/@QUlmfl5xf9183K@5uXrJicmZ6QCAA "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` A²γW‽γ«θ_A⁺γ¹γ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DSEchXdOaqzwjMydVQSMoMS8lP1cjXVNToZqLM6AoM69EoxAoDWUqxSuBOFCtATmlxRrpOgqGmhAzav//L0ktLvmvW/Zftzjna16@bnJickYqAA "Charcoal – Try It Online") Link is to verbose version of code. Uses `_` as the separator. Note: output caching is disabled, so please don't hammer Dennis's server! [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` `G@QYrq]x ``` [Try it online!](https://tio.run/##y00syfn/P8HdITCyqDC24v9/9cSkZPWvefm6yYnJGakA "MATL – Try It Online") ### Explanation ``` ` % Do...while G % Push input @ % Push iteration index k, starting at 1 QYrq % Random integer uniformly distributed in {0, 1, ..., k}. This is the % loop condition. If non-zero (which occurs with probability k/(1+k)) % proceed with next iteration; else exit loop ] % End x % Delete, as there are one too many strings. Implicitly display the stack ``` [Answer] # [Perl 6](https://perl6.org), ~~50 41 38 36~~ 26 bytes ``` {put $_//last for (($,$_),*⊎$_...*).map(*.pick)} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7v7qgtERBJV5fPyexuEQhLb9IQUNDRUclXlNH61FXn0q8np6elqZebmKBhpZeQWZytmbtf7BO9cSk5BT1/1/z8nWTE5MzUgE "Perl 6 – Try It Online") ``` {eager ->{(++$).rand>.5??.put!!last}...*} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7vzo1MT21SEHXrlpDW1tFU68oMS/FTs/U3l6voLREUTEnsbikVk9PT6v2P1iDemJScor6/695@brJickZqQA "Perl 6 – Try It Online") ``` {eager ->{(++$).rand>.5??.put!!0}...0} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7vzo1MT21SEHXrlpDW1tFU68oMS/FTs/U3l6voLREUdGgVk9Pz6D2P1i1emJScor6/695@brJickZqQA "Perl 6 – Try It Online") ``` {eager ->{(++$).rand>.5&&.put}...!*} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7vzo1MT21SEHXrlpDW1tFU68oMS/FTs9UTU2voLSkVk9PT1Gr9j9YrXpiUnKK@v@vefm6yYnJGakA "Perl 6 – Try It Online") ``` .put while (++$/).rand>.5 ``` (with `-n` commandline argument) [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppds/V@voLREoTwjMydVQUNbW0VfU68oMS/FTs/0///EpOSUf/kFJZn5ecX/dfO@5uXrJicmZ6QCAA "Perl 6 – Try It Online") [Answer] ## [Python 3](https://docs.python.org/3/), 55 bytes ``` v=s=input();i=2 while hash(v)%i:print(s);i+=1;v=hash(v) ``` ## Explanation To save having to import random, I've exploited the fact that the hash built-in is randomly seeded each time a python process is fired up (at least in MacOS). Each hash of the last hash should generate a series of pseudo-random integers. If the hash is pseudo-random enough, the modulo with `i` is zero with probability `1/i`. ## Notes I'm a little bothered by the redundant hash, but without a do-while, or in-condition assignment in Python, I'm a little stuck. [Answer] # C# This is same length as the top C# answer, but: ``` using System;s=>{var x=(1<<31)/new Random().Next();for(;++x>0;)Console.Write(s+" ");} ``` Just wanted to point out that some math can produce the correct probability. ``` int.MaxValue/new Random().Next()-1 ``` Is equivalent to ``` (int)(1 / new Random().NextDouble()) - 1; ``` And the function f(x)=1/x-1 is: f(1) = 0 f(1/2) = 1 f(1/3) = 2 f(1/4) = 3 So 1/2 a chance to be rounded down to 0, 1/6 a chance to be rounded down to 1, and 1/(n+1)(n+2) a chance to be rounded down to n. Maybe some other language could capitalize on this. EDIT: Fixed my mistake I thought of something to make it smaller. EDIT EDIT: I am just all kinds of wrong. Pulled the Random out of the loop because if it's evaluated multiple times, it won't work. EDIT EDIT EDIT: I got rid of the variable i. I'm going to stop trying to shrink it now. Nope, lied. Got rid of another byte. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ROM`, 7 bytes ``` {&›¥℅|, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=ROM&code=%7B%26%E2%80%BA%C2%A5%E2%84%85%7C%2C&inputs=Hello&header=&footer=) Explanation: ``` { | # While... &› # ...Increment the register (initially 0)... ¥ # ...Retrieve value n from the register... ℅ # ...Random value from range[0..n]... | # ...Returns true, do: , # Print the input string ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` SαA²βW‽β«⁺α¶A⁺β¹β ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0JLikKDMvXSNR05rLsbg4Mz1Pw0hHIQnIK8/IzElV0AhKzEvJz9VI0tRUqOZSAIIAoPoSDW2NRB0FpZg8JU2gUpAwVLO2RpKOgqEmxIja///T8vOTEov@65b91y3O@ZqXr5ucmJyRCgA "Charcoal – Try It Online") Verbose code included. Respects specs because it uses a random range from `0` to `n`. [Answer] # C, 41 bytes ``` n;f(char*s){for(n=1;rand()%++n;puts(s));} ``` Assumes `rand` is seeded. [Try it online!](https://tio.run/##S9ZNT07@/z/POk0jOSOxSKtYszotv0gjz9bQuigxL0VDU1VbO8@6oLSkWKNYU9O69n9uYmaehmZ1MVi2JDM3VcMAKJ6moeSRmpOTb68EUvM1L183OTE5IxUA) [Answer] # [braingasm](https://github.com/daniero/braingasm), 22 bytes edit: Same byte count, but I realized I could sneak in the new tape `L`imit feature. ``` ,[>,]>L+[+$rzQ>[.>]:>] ``` Uses `0` as separator. Works like this: ``` ,[>,] Read a byte and move to next cell until end of input. > After the loop we're in an empty cell; Leave it empty and move to the next. L Set tape limit here: The tape will then wrap around if we move further. + Increase current cell by one. This cell will be our counter. [ ] Loop until the counter is zero. That won't happen, so it's an infinite loop. + Increase again, so the first time the counter is 2. $r Get a random number, 0 <= r > current cell zQ Quit the program if that random number was 0 > Wrap around to the start of the tape. [.>] Print the input stored on the tape The loop will stop at the blank cell. : Print the blank cell as a number ("0") > Go to the next (last) cell ``` [Answer] # [Python](https://docs.python.org/2/), 54 bytes ``` lambda s:int(1/random()-1)*(s+'|') from random import* ``` [Try it online!](https://tio.run/##JcrBCsIwDADQs/2K3NpMhqvHwf5kIHVbt4JNStKL4G97rorn98qzHkzXFqe5PUK@rwF0TFSdv0iglbPD3mPn9GxfFk0UzvAHSLmw1K7pZLVKot2ayAI3SPQr@@b8MOBoTuWLFaJTbG/ifgnLsX0A "Python 2 – Try It Online") Generated the number of copies as `floor(1/p)-1` with `p` uniformly chosen from the unit interval. The number of copies is `n` when `1/p-1` falls between `n` and `n+1`, which happens when `1/(n+2) < p < 1/(n+1)`. This happens with probability `1/(n+1)-1/(n+2)` or `1/((n+1)*(n+2)`. This is the desired probability of outputting `n` copies: `1/2` prob of 0, `1/6` prob of 1, `1/12` prob of 2,... [Answer] # C++, 97 96 57 bytes Here my first try on codegolf :) ``` #include<iostream> int main(){std::string S;std::cin>>S;int i=1;while(rand()%++i)puts(S.data());} ``` I saved one byte by using `for` ``` #include<iostream> int main(){std::string S;std::cin>>S;for(int i=1;rand()%++i;)puts(S.data());} ``` Saved 39 bytes since nobody seems to count the includes ``` void p(string S){for(int i=1;rand()%++i;)puts(S.data());} ``` ungolfed ``` #include <iostream> int main() { // Create and read string from inputstream std::string S; std::cin >> S; // rand % i: create random int in range [0, i-1] // Zero is seen as false and all positive int as true int i = 1; while (rand() % ++i) puts(S.data()); } ``` [Answer] # F#, 161 bytes Definitely not the best language to golf, but I decided to give it a try (besides, I do not know anything about F#, so any tips on how to improve my answer will be welcome). ``` let f s= let r,z=System.Random(),(<>)0 let p _=printfn"%s"s seq {for i in 2|>Seq.unfold(fun i->Some(i,i+1))do yield r.Next(i)}|>Seq.takeWhile z|>Seq.iter p ``` Execute with: ``` [<EntryPoint>] let main argv = "test" |> f 0 ``` Writes a new line as separator. [Answer] # [Ruby](https://www.ruby-lang.org/), 29+1 = 30 bytes Uses the `-n` flag. ``` i=1;puts$_ while i>rand(i+=1) ``` [Try it online!](https://tio.run/##KypNqvyvrFgEpBR08/5n2hpaF5SWFKvEK5RnZOakKmTaFSXmpWhkatsaav7/75Gak5OvEJ5flJOi@DUvXzc5MTkjFQA "Ruby – Try It Online") [Answer] ## PowerShell, 31 bytes ``` for($i=2;random($i++)){"$args"} ``` `Get-Random $i` outputs an `n` where `0 <= n < $i`, separator is implicit newline. [Answer] # Python, 75 bytes The other Python answer is shorter, but I wanted to try it a different way: ``` from random import* f=lambda d=1,s=input():randint(0,d)and s+'!'+f(d+1)or'' ``` ]
[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/7197/edit). Closed 7 years ago. [Improve this question](/posts/7197/edit) Write a perfectly legal code in a decent language of your choice whose compiling will either crash the compiler or send it into an infinite loop (infinite compile time). **Restrictions:** * Use a standard language that is used in real world. * Use a standard, well-developed compiler (no answers like "I wrote my C compiler that crashes on everything"). * The code must be legal in the language (so most likely you'll have to exploit a compiler or a language bug). * Give your compiler version and options used so that others can replicate it. * Explain why the compiler crashed, if possible. Have fun :) [Answer] My favorite solution for GHC: ``` data Bad a = C (Bad a -> a) xx :: Bad a -> a xx (x@(C x')) = x' x omega :: a omega = xx (C xx) main = omega ``` For GHC 6.12.1 both `ghci Bad.hs` and `ghc Bad.hs` loop infinitely. GHC 7.4.1 loops infinitely when `ghc -O2 Bad.hs` is executed. **Explanation:** `omega` is defined using an infinite recursion (the only way it can inhabit any type). Compiler's inliner sees `xx` as a simple, non-recursive function, so it tries to inline it in the definition of `omega`. It results in `(\x@(C x') -> x' x) (C xx)`. Seeing a pattern match on a constructor the compiler tries to reduce it, getting `xx (C xx)` again and loops. The trick is that `xx` is actually recursive, but the recursion is hidden within the data type. *Note: While writing the puzzle, I forgot I left GHC running in the infinite loop. It took all my memory, crashed Firefox and I barely managed to kill it without hard reset.* [Answer] I'm pretty sure it's been fixed now, but it used to be that you could crash the Java compiler (or, crash Eclipse) by writing ``` class Foo { static double d = 2.2250738585072012e-308; } ``` <http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/> Actually, according to that page, the compiler will just hang, not crash. Still, I thought that was pretty fun. [Answer] This is easy in any [dependently-typed](https://en.wikipedia.org/wiki/Dependent_type) language. Type-checking general dependent types is undecidable since it may require arbitrarily complex computations (Turing-complete). You can simply encode in a dependent type a too-large value. Then the type-checker will use all available memory and crash. For instance, in Coq, [ReyCharles gives the example of `Compute 70000.`](https://codegolf.stackexchange.com/questions/9359/shortest-program-that-throws-stackoverflow-error/9380#9380), which causes the type-checker to construct a giant Peano numeral and crash. In more common languages that support some sort of macro expansion or metaprogramming, you can do something similar. For example, you can use all available memory in C: ``` #include <stdio.h> #define a printf("%s", "Hello, world!\n"); #define b a a a a a a a a a a a a a a a a #define c b b b b b b b b b b b b b b b b #define d c c c c c c c c c c c c c c c c #define e d d d d d d d d d d d d d d d d #define f e e e e e e e e e e e e e e e e // ... #define z y y y y y y y y y y y y y y y y int main() { z } ``` The D programming language allows [compile-time function execution](https://en.wikipedia.org/wiki/Compile_time_function_execution). This can be used to compute something at compile time that is too large to fit in memory. Something similar can be achieved using C++ template metaprogramming. In XML (not a compiled programming language, but an XML processor is analogous to a compiler), expanding entities can make the processor run out of memory: ``` <?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;"> <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;"> ... ]> <lolz>&lol999;</lolz> ``` This is called the [billion laughs attack](https://en.wikipedia.org/wiki/Billion_laughs). [Answer] ### C# Found this on a [stackoverflow question](https://stackoverflow.com/questions/22898325/why-does-the-c-sharp-compiler-go-mad-on-this-nested-linq-query): ``` using System; using System.Linq; public class Test { public static void Main() { Enumerable.Range(0, 1).Sum(a => Enumerable.Range(0, 1).Sum(b => Enumerable.Range(0, 1).Sum(c => Enumerable.Range(0, 1).Sum(d => Enumerable.Range(0, 1).Sum(e => Enumerable.Range(0, 1).Sum(f => Enumerable.Range(0, 1).Count(g => true))))))); } } ``` The compiler eventually will crash. The issue seems related to type inference and/or lambda generation combined with overload resolution. [Answer] # VBA how about if you can crash the IDE by typing in code? in any Microsoft Office application, try this: `ALT`+`F11` to get to the VBA window, then try the following code ``` sub foo() dim v(1 to 3, 1 to 3) redim preserve v(,1 to 5) ``` and behold: ![Excel Death](https://i.stack.imgur.com/ccQv4.jpg) *You can simply type `redim preserve v(,1 to 5)` into the immediate window, and it will crash after you press `ENTER` !* [Answer] ## Perl (15) ``` BEGIN{1while 1} ``` This creates an infinite loop **at compile time**: > > A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed. > > > (from [perlmod](http://p3rl.org/perlmod#BEGIN%2C-UNITCHECK%2C-CHECK%2C-INIT-and-END)) And that's why Perl isn't able to complete parsing the code. This doesn't terminate: ``` $ perl -MO=Deparse -e 'BEGIN{1while 1}' ``` [Answer] ## J This segfaults the J interpreter (at least on Linux): ``` 15!:1[3#2 ``` It tries to read from memory address 2. Interestingly, if you try it with 0 or 1, you get `domain error`. [Answer] **TeX** ``` \def\x{\x}\x ``` TeX is a macro-expansion language. Here we define the expansion of the macro `\x` to be `\x` again, and then we add afterwards an invocation of `\x`. TeX gets stuck endlessly replacing `\x` with `\x`. [Answer] # Scheme ``` (define-syntax s (syntax-rules () ((_ (t) ...) (s (t t) ... (t t) ...)) ((_ (t u) ...) (s (t) ... (u) ...)))) (s (+)) ``` My compiler, Chicken, made the mistake of attempting to expand macros at compile time for "run-time performance" or something. So it payed the price of expanding this one. I've read R5RS. No one said macros had to be expanded at compile time. Essentially what's going on is the macro expands to an expression of infinite size, constantly doubling in size. Well, to be technical, doubling every other expansion. The compiler's fate is sealed. At least on my system, Chicken caps at 2GB, stalls for a long time trying to garbage collect, then crashes after the garbage collector gives up. It does take a while though because of all the computationally expensive hygienic magic occurring. Switching between expressions of the form ``` (s (+) (+) (+) (+) .... ``` and ``` (s (+ +) (+ +) (+ +) (+ +) .... ``` seems to very, very dramatically increase the rate of memory consumption as compared to: ``` (define-syntax s (syntax-rules () ((_ t ...) (s t ... t ...)))) (s +) ``` I suspect Chicken is a pretty hardy compiler that has some ways of avoiding deep analysis of syntactic expressions when it can get away with it, but my final solution forces the pattern matcher to really dive in. [Answer] ### Common Lisp Macros make it easy: ``` (defmacro loop-forever () (loop for x from 0 collecting x)) (defun compile-me () (loop-forever)) ``` Compiling `compile-me` calls `loop-forever`, which exhausts heap memory during its expansion and crashes the compiler. If you just want to make the compiler hang indefinitely, then this definition of `loop-forever` will do it: ``` (defmacro loop-forever () (loop)) ``` This should work using any CL implementation, unless yours is extremely clever and can detect simple infinite loops, but I seriously doubt any do this. Full protection against this is impossible, of course. [Answer] ## D (DMD32 D Compiler v2.067.1, Windows build) ``` enum x = "mixin(x);"; mixin(x); ``` Note that this will send the compiler into an infinite loop *and* crash it. > > Error: out of memory > > > Mechanical snail [suggested](https://codegolf.stackexchange.com/a/9400/46186) that compile-time programming features in D could be abused for this purpose, but the solution is perhaps simpler than the kind of techniques he had in mind. --- For those who aren't familiar with 'string mixins', it's a fairly straightforward macro feature. When the compiler encounters `mixin("asdf")`, it substitutes it with the contents of the string, `asdf`, and tries to compile it again. The solution above will be expanded like: ``` mixin(x); -> mixin("mixin(x);"); -> mixin(x); ``` So unless the compiler tries to detect this expand-to-same case, it'll enter an infinite loop of expansion. [Answer] # Perl This defines operator overloading at compile time, and runs code at compile time which adds the instances of class together. (by the way, normally infinite recursion would eat all the memory, but with overloading, it just crashes) ``` package MyAmazingClass; use 5.010; use overload '+' => sub { my ($first, $second) = @_; return $first + $second; }; sub new { my $self = shift; return bless {}, $self; } # BEGIN runs code at compile time BEGIN { my $instance = MyAmazingClass->new; my $sum = $instance + $instance; say $sum; } ``` Output: ``` fish: Job 1, 'perl' terminated by signal SIGSEGV (Address boundary error) ``` [Answer] # [Simplex v.0.5](http://conorobrien-foxx.github.io/Simplex/), 2 bytes Too bad this isn't a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): ``` 2Q ``` Let me explain. From the docs: > > [`Q`] Adds program source code to outer program, from the beginning (exclusive of ! characters, if the current byte is not zero) If byte is 2, duplicates current command as well. > > > So: ``` 2 ~~ Manhattan adds 2 to the current byte: 10*0 + 2 = 2. Q ~~ Adds program source code to the outer program, with Q ``` The outer program is a neat little feature in Simplex: it is evaluated at the end of the program. So, if we keep track...: ``` P1 P2 P3 P4 ... 2Q->2Q->2Q->2Q->... ``` Eventually, memory will run out and the world will end. [Answer] # **x86 asm** "nasm -v" returns "NASM version 2.11.08 compiled on Feb 21 2015" (I'm running it under win7) The assembler has been running for 1:12:27 so far on an i7, totally saturating one of the cores. The output file is sitting at 0 bytes, memory consumption has been stable at 1,004K - it seems safe to say I've beaten nasm up, rather than just giving it a really, really long task. :) The key to the trick is the repeat value in the macro - 0xFFFFFFFF. Though, I'm not familiar enough with Nasm's internals to know why exactly it's choking on this. I expected to get a ~16GB output an hour ago. ``` %MACRO INVOKE 1-* ; %REP %0 - 1 %REP 0xffffffff %ROTATE -1 PUSH DWORD %1 %ENDREP %ROTATE -1 CALL %1 %ENDMACRO [section .text] bits 32 org 0x10000 EntryPoint: INVOKE dword 666 ret ``` EDIT: Just checked the task manager, Nasm has been running for 7:40:41 and the memory is now up to 1,016K [Answer] ## Clang++ I just came across this fun bug. ``` #include <iostream> #include <string> #include <sstream> #include <fstream> std::stringstream prog; constexpr unsigned c_strlen( char const* str, unsigned count = 0 ) { return ('\0' == str[0]) ? count : c_strlen(str+1, count+1); } template < char t_c, char... tt_c > struct rec_eval { static void eval() { rec_eval<t_c>::eval(); rec_eval < tt_c... > :: eval (); } }; template < char t_c > struct rec_eval < t_c > { static void eval() { switch(t_c) { case '+': prog<<"++t[i];"; break; case '-': prog<<"--t[i];"; break; case '>': prog<<"++i;"; break; case '<': prog<<"--i;"; break; case '[': prog<<"while(t[i]){"; break; case ']': prog<<"}"; break; case '.': prog<<"putc(t[i],stdout);"; break; case ',': prog<<"t[i]=getchar();"; break; } } }; template < char... tt_c > struct exploded_string { static void eval() { rec_eval < tt_c... > :: eval(); } }; template < typename T_StrProvider, unsigned t_len, char... tt_c > struct explode_impl { using result = typename explode_impl < T_StrProvider, t_len-1, T_StrProvider::str()[t_len-1], tt_c... > :: result; }; template < typename T_StrProvider, char... tt_c > struct explode_impl < T_StrProvider, 0, tt_c... > { using result = exploded_string < tt_c... >; }; template < typename T_StrProvider > using explode = typename explode_impl < T_StrProvider, c_strlen(T_StrProvider::str()) > :: result; int main(int argc, char** argv) { if(argc < 2) return 1; prog << "#include <stdio.h>\n#include <stdlib.h>\nint main(){unsigned char* t=calloc("; prog << (1 << sizeof(unsigned short)); prog << ",sizeof(unsigned short));unsigned short i=0;"; struct my_str_provider { constexpr static char const* str() { return "++++[>+++++<-]>+++[[>+>+<<-]>++++++[<+>-]+++++++++[<++++++++++>-]>[<+>-]<-]+++>+++++++++[<+++++++++>-]>++++++[<++++++++>-]<--[>+>+<<-]>>[<<+>>-]<-->>++++[<++++++++>-]++++++++++>+++++++++[>+++++++++++<-]>[[>+>+>+<<<-]>[<+>-]>>[[>+>+<<-]>>[<<+>>-]<[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<<<+>---------->->[-]]]]]]]]]]]<]<<[>>++++++++++++[<++++<++++>>-]<<[.[-]>]<<]>[<++++++[>++++++++<-]>.[-]]<<<<<.<<<<<.[<]>>>>>>>>>.<<<<<..>>>>>>>>.>>>>>>>.[>]>[>+>+<<-]>[<+>-]>[-[[-]+++++++++[<+++++++++++++>-]<--.[-]>]]<<<<<.[<]>>>>>>>>>.>>>>>>>>>.[>]<<.<<<<<.<<<..[<]>>>>>>.[>]<<.[<]>>>>>>>>>.>.[>]<<.[<]>>>>.>>>>>>>>>>>>.>>>.[>]<<.[<]>.[>]<<<<<<.<<<<<<<<<<<..[>]<<<.>.[>]>[>+>+>+<<<-]>[<+>-]>>[[>+>+<<-]>>[<<+>>-]<[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<<<+>---------->->[-]]]]]]]]]]]<]<<[>>++++++++++++[<++++<++++>>-]<<[.[-]>]<<]>[<++++++[>++++++++<-]>.[-]]<<<<<.<<<<<.[<]>>>>>>>>>.<<<<<..>>>>>>>>.>>>>>>>.[>]>[>+>+<<-]>[<+>-]>[-[[-]+++++++++[<+++++++++++++>-]<--.[-]>]]<<<<<.[<]>>>>>>>>>.>>>>>>>>>.[>]<<.<<<<<.<<<..[<]>>>>>>.[>]<<<<.>>>.<<<<.<.<<<<<<<<<<.>>>>>>.[>]<<.[<]>>>>>>>>>.>.>>>>>>>>>.[>]<<.<<<<<<<.[<]>>>>>>>>>.[<]>.>>>>>>>>>.[>]<<.<<<<.<<<<<<<<<<<<<.[>]<<<<<<<<<.[>]<<.[<]>>>>>>>>.[>]<<<<<<.[<]>>>>>..[>]<<.<<<<<<<<<<<<.[<]>>>>.[>]<<.<<<<.[<]>>>>>>.>>>.<<<<<<.>>>>>>>.>>>>>>>>>>.[>]<<<.>.>>>-[>+>+>+<<<-]>[<+>-]>>[[>+>+<<-]>>[<<+>>-]<[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<<<+>---------->->[-]]]]]]]]]]]<]<<[>>++++++++++++[<++++<++++>>-]<<[.[-]>]<<]>[<++++++[>++++++++<-]>.[-]]<<[>+>+<<-]>[<+>-]+>[<->[-]]<[-<<<[<]>>>>>>>>>>.<.[>]<<.[<]>>>>>>>>>>>.<<.<<<.[>]<<<<<<<<<<.[>]>>]<<<<.<<<<<.[<]>>>>>>>>>.<<<<<..>>>>>>>>.>>>>>>>.[>]>[>+>+<<-]>[<+>-]+>[<->-[<+>[-]]]<[++++++++[>+++++++++++++<-]>--.[-]<]<<<<.[<]>>>>>>>>>.>>>>>>>>>.[>]<<.<<<<<.<<<..[<]>>>>>>.[>]<<.[<]>>>>>>>>>.>.[>]<<.[<]>>>>.>>>>>>>>>>>>.>>>.[>]<<.[<]>.[>]<<<<<<.<<<<<<<<<<<..[>]<<<<.>>>..>>]"; } }; auto my_str = explode < my_str_provider >{}; my_str.eval(); prog << "}"; std::ofstream ofs(argv[1]); if(!ofs) return 2; ofs << prog.str() << std::endl; ofs.close(); return 0; } ``` The goal is to translate Brainfuck into C, using template meta-programming to do most of the work. This code works for smaller Brainfuck programs, such as Hello World, but when I tried to run it with 99 Bottles... ``` $ clang++ -std=c++11 -fconstexpr-depth=1000 bf_static.cpp clang: error: unable to execute command: Segmentation fault (core dumped) clang: error: clang frontend command failed due to signal (use -v to see invocation) clang version 3.5.2 (tags/RELEASE_352/final) Target: i386-pc-windows-cygnus Thread model: posix clang: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script. clang: note: diagnostic msg: ******************** PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT: Preprocessed source(s) and associated run script(s) are located at: clang: note: diagnostic msg: /tmp/bf_static-afa982.cpp clang: note: diagnostic msg: /tmp/bf_static-afa982.sh clang: note: diagnostic msg: ******************** ``` It will successfully compile in GCC (after about 2 minutes), but linking it causes another issue... ``` /usr/lib/gcc/i686-pc-cygwin/4.9.3/../../../../i686-pc-cygwin/bin/as: /tmp/cc0W7cJu.o: section .eh_frame$_ZN8rec_eval<giant mangled name removed>: string table overflow at offset 10004228 /tmp/cc3JeiMp.s: Assembler messages: /tmp/cc3JeiMp.s: Fatal error: can't close /tmp/cc0W7cJu.o: File too big ``` Oops. [Answer] **Smalltalk** (Squeak dialect, version 4.x) Very easy, just evaluate this, or accept a method with this literal ``` 1.0e99999999999999999999 ``` It will try to evaluate the power of 10 in Large Integer arithmetic, just for correctly rounding inf Tsss ;) **Edit:** how many 9 are necessary? Since 2^10 is 1024, approximately 10^3, we can roughly approximate 10^n by 2^(10\*n/3). That means that 10^n require 10\*n/3 bits to be represented in binary. We would like to have 10^n not representable. Assuming 32 bit pointers for the object memory, we know that we cannot address more than 2^32 bytes, that is 2^35 bits. So let's reverse the problem: 2^35 is approximately 32 \* 2^30, 32\*10^9. That requires about 11 decimal digits, so with eleven 9, we are sure to generate an error on 32bits Squeak. In 64 bits that would be twenty one 9. We can also exhaust memory with less 9s, the whole addressable space is not necessarily available, but it's deadly slow to test, the Squeak VM is not optimized for such giant arithmetic unlike GMP. [Answer] **PHP 5.3.1** (Segfaults interpreter) ([Bug 50261](https://bugs.php.net/bug.php?id=50261), fixed in 5.3.3) ``` class testClass { function testClass () { echo 'Output string!'; } } class testClass2 extends testClass { function __construct () { call_user_func(array('parent', '__construct')); } } new testClass2; ``` This one was a bit of a problem, because the code above was common in a lot of the code I was working with, making this a fairly widespread issue for us. (If I recall correctly, at one point this was the only way to call parent constructors in PHP.) [Answer] This is my original and concise method to crash GolfScript: ``` {1.}do ``` What this does is set up a forever loop that keeps on pushing 1 onto the stack until memory runs out. In C/C++, I believe that this original piece of code would crash the compiler: ``` #define a bb #define b aa int main(){a} ``` This would get the compiler stuck doubling the amount of a's and turning them into b's and vice versa, so the compiler would pretty soon run out of memory and crash. Another one is for batch on Windows, if completely freezing the computer rather than just the batch script itself counts. You should type in the following: ``` :a start %0 goto a ``` This gets into an infinite loop of making copies of itself, which make copies of themselves and so on. This would most likely eventually crash your computer if you ran this little bit of code. One last one is a VBS bomb. It is another bomb, like the last one, but it instead opens an infinite amount of dialog boxes. ``` set oshell = wscript.createobject("wscript.shell") do oshell.run "wscript " & wscript.scriptname msgbox "blah" loop ``` This continuously creates a copy of itself and opens up a message box in an infinite loop, which the clones do as well. Running these last two programs is not recommended, as they can freeze your computer and cause you to have to hard boot your computer. Note that I came up with all of these programs myself. [Answer] # Common Lisp, 8 bytes Shorter than the other Common Lisp answer :-) ``` #.(loop) ``` Loop while reading your form. The Common Lisp standard has no mention of a portable way to make it crash, so I guess we need to have an implementation-defined way. Still 8 bytes: ``` #.(quit) ; ccl ``` ... or, ``` #.(exit) ; sbcl ``` When you call `(compile-file "crash.lisp")`, the environments mysteriously "crash". Joking apart, I am still trying to find a way to really crash the environment (and shortly), but it is really hard. All I get is a nice interaction with the debugger. [Answer] # Gnu assembler, generating *huge* output files This macro attempts to fill the output file with garbage (usually null bytes) until a 4 GB boundary is reached, adds an int to get past that boundary, and recursively calls itself to keep filling the output with 4 GB chunks of garbage. This will fill your hard drive until it is full, at which point the assembler will likely crash. ``` .macro f n #Define a macro named f, taking argument n. .p2align 32 #Fill file with 0x00's until current address is divisible by 2^32 .long 0 #Add a long after the current address, throwing it off alignment. .if \n #If n > 0, recursively tail-call itself, decrementing n. f "(\n-1)" .endif .endm #End macro definition. f 32 #Expand macro f, with n = 32 (output size 4GB*32 = 128GB) ``` Note that infinite recursion cannot be used, as the assembler will catch that special case and stop expanding the macro. Compilation can be done with `as -o crash.out crash.s` on most Linux distributions. [Answer] # Common Lisp, 29 bytes Implementation: Clozure CL **WARNING:** Be careful when running this code, it may kill processes that you don't want it to! ``` #.(run-program"pkill"'("cl")) ``` This runs the shell command `pkill cl` on compile time, which will kill the Lisp process doing the compiling. Not technically a crash, but it has the same effect. Example usage: ``` $ cat /tmp/t.lisp #.(run-program "pkill" '("cl")) $ ccl -n Welcome to Clozure Common Lisp Version 1.11-dev-r16513-trunk (LinuxX8664)! ? (compile-file "/tmp/t.lisp") #P"/tmp/t.lx64fsl" NIL NIL ? zsh: terminated ccl -n $ ``` [Answer] # Felix This doesn't work anymore, but at one point, this code: ``` include "std/control/pchannels"; fun is_square(v: int) => let s = int$ sqrt$ v.float + 0.5f in s*s == v; fun is_median(v: int) => v % 4 == 0 and (v/4).is_square; struct Message { value: int; }; proc process(c: int, chan: pchannel[Message]) { var i = 0; for var b in (c+1)/2 upto c do for var a in c - b + 1 upto b do if is_median(2*(b*b+c*c)-a*a) or is_median(2*(a*a+c*c)-b*b) or is_median(2*(a*a+b*b)-c*c) do ++i; done; done done write(chan, Message i); }; proc main() { n := int$ System::argv 1; var count = n; chan := #mk_pchannel[Message]; var ntri = 0; for var c in 1 upto n perform spawn_pthread { process(c, chan); }; while count > 0 do let v = chan.read in ntri += v.value; --count; done ntri.println; } main; ``` This would give a big error: ``` inner_bind_expression raised Not_found [BUG] e=(&((main_mf_60270<60270> ())), (value v)) ``` SYSTEM FAILURE bind\_expression' raised Not\_found [BUG] Felix compilation "/media/ryan/stuff/felix/build/release/host/bin/flxg" "-q" "--optimise" "--inline=100" "--output\_dir=/home/ryan/stuff/.felix/text" "--cache\_dir=/home/ryan/stuff/.felix/cache" "-I/media/ryan/stuff/felix/build/release/share/lib" "-I/media/ryan/stuff/felix/build/release/host/lib" "--syntax=@/media/ryan/stuff/felix/build/release/share/lib/grammar/grammar.files" "--automaton=/home/ryan/stuff/.felix/cache/media/ryan/stuff/felix/build/release/share/lib/grammar/grammar.files/syntax.automaton" "--import=plat/flx.flxh" "std" "/home/ryan/golf/itri/sl.flx" failed Error 1 in flx: [strerror\_r] Failed to find text for error number 1 The issue was here: ``` let v = chan.read in ntri += v.value; ``` `let` expected an expression to follow it, but I put a statement instead. So the compiler freaked out a tad. More info at <https://groups.google.com/forum/m/#!topic/felix-language/J3Hs4j6E0gM>. [Answer] # JavaScript ``` while (true === true){ console.log(0); } ``` This sends it into an infinite loop. I used the Codecademy JS compiler and it crashed my browser. [Answer] # Javascript ``` function crash(){ window.location.hash=Math.random(),onhashchange=function(){crash()} } ``` This one crashes web browsers in a seriously effective fashion. **USE AT YOUR OWN RISK!!!** [Answer] # [Hassium](http://HassiumLang.com) File1.has: ``` use "File2.has"; ``` File2.has: ``` use "File1.has"; ``` This causes Hassium to load and begin compiling File2.has, which tells it to load File1.has, which causes it to load File2.has, and so on. [Answer] # LOLCODE 1.2, LOLCODE Common Interpreter/Compiler (lci) I know this isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") but it's extremely short anyways. ``` OBTW ``` This causes Signal 11: ``` Segmentation fault (core dumped) ``` Why? `HAI1.2` denotes the start of the program, and `OBTW` initiates a multiline comment. But the compiler expects a `KTHXBYE` to close the `HAI`, and a `TLDR` to close the multiline comment. Note that this will still work to cause segfault with anything other than `TLDR` after `OBTW`. (By [wikipedia's](https://en.wikipedia.org/wiki/LOLCODE) standards, LOLCODE is a just a Weirdlang, not actually esoteric.) You can grab the interpreter from [git/justinmeza/lci](http://github.com/justinmeza/lci). ]
[Question] [ One of many unique features of the [Malbolge](https://esolangs.org/wiki/Malbolge) programming language is its highly unintuitive `OP` operator, referred to only as "op" in the documentation and source code but popularly known as the "crazy" operator. As described by Ben Olmstead, the creator of the language, in its documentation: "*don't look for pattern, it's not there*." op is a "tritwise" operator -- it operates on corresponding ternary digits of its two arguments. For each trit (ternary bit), the result of op is given by the following lookup table: ``` a op(a,b) 0 1 2 +------- 0 | 1 0 0 b 1 | 1 0 2 2 | 2 2 1 ``` For example, to calculate `op(12345, 54321)`, first write out both numbers in ternary and then look up each pair of trits in the table: ``` 0121221020 (12345_3) op 2202111220 (54321_3) -------------- 2202220211 (54616_3) ``` The last important point is that all values in Malbolge are 10 trits wide, so input values should be padded with zeroes to a width of 10. (For instance, `op(0, 0)` is `1111111111` in ternary.) Your task is to take two integers 0 ≤ `a`, `b` < 59049 as input, and output the integer value of `op(a,b)`. Test cases (in the format `a b op(a,b)`): ``` 0 0 29524 1 2 29525 59048 5 7 36905 2214 0 11355 1131 20650 12345 54321 54616 ``` Here is a [reference implementation](https://tio.run/##hZLtboIwFIb/exVvXExgdhtfVQi6G3H@MOBHzVYMYKIxXDs7rUUZRpac0NNznryn7Uvytk2S@kXI5PuYrjErylRk77vP@igLsZXrFMUuy0tkBwud0ol1K2fYg8sA3bLAHA7DPqZWUa5KkSDJZFF2uUO04EvMiQIucBkihpCWqUfJhE9cVP9JZItoSdGI6K8SCxh8HSTn6DAJKtaBeNPzbkkb4poIdPtKmORRqT1uSjeg6B93hcL@caGOaRsy4uyemAM8QiG7J@YAbShsiFtiDtBA2oFNlsPCXtka0zIDp2U8JvcVIjCekxFnfChH90uMQKac/mzxet0otXxdHnNJggJ2PKhqIUv8rIS0bGPgIafSxhqO0i85ZOpXVG9q2/GTrvLkeZdHTkBX488JfxI5dGfPc4OeIa7PlXeu7/ZAnh@oBwx8T1NV/Qs) (copied directly from the Malbolge source code). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~99~~ ~~98~~ 96 bytes * Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); golfing `19683` to `L'䳣'`. * Saved two bytes; golfing `108609` to `L'𚡁'`. ``` M,a,l,b,o;L(g,e){for(o=b=L'䳣',l=0;o/=2.4;b/=3)M=g/b,g%=b,a=e/b,e%=b,l+=b*(L'𚡁'>>M+6*a+M&3);g=l;} ``` [Try it online!](https://tio.run/##Nc5NToQwGAbgtZyCjEHaoSP9RbH5xgvAbpZuKFMICYKZuJuMiddwZzyCV/IA3gBbwCbN@@ZJ@7X1rq3raSpJRXpiyKgL1BKLz814QiMYKOKf76@Y9ED1mAK/ldqkIHAJbWpIG4EhFVhXra99AmaLivj34/M93u/LJNtWSXkjsG6h15fp@mibbrDhAVXuLYtfTt3w2qBNpI6h32/7OQDmQFGNn4YN8WcLfwMTu5adfWSUPzCWYR08V92A8Dm4OqDQLUrCNXiuuMT/zhbni6vZVU7l/eJqibvZRZZTD5wzuY6bnTGhvLt04zjN1OpcSOdKCs58ZO5jwWX6Aw "C (gcc) – Try It Online") [Answer] # JavaScript (ES7), 56 bytes ``` f=(a,b,k=9)=>~k&&(a%3|b%3<<9|8)**2%82%3+3*f(a/3,b/3,k-1) ``` [Try it online!](https://tio.run/##Zc3RCoIwGAXg@57CG2Uzze3/95sD7V2maZTiIqMr6dVtpRDogcO5@eDczMsM1eN6f8a9PdfT1BTMRGXUFpoXp3cbBMz4OJY@5rkeMx6G4Gfg4x7DhpkEo9K1jSWfKtsPtqsPnb2whnkuIvJ@w7mXJB5oArXbKjkr@CtaKdJCZbOiWR1XAlMtyAkAqWYhVkJKpK9wK5cnkdJGASqnSCEsilQq0@kD "JavaScript (Node.js) – Try It Online") ## How? Given \$a\$ and \$b\$ in \$[0..2]\$, we compute: $$f(a,b)=((a+512b+8)^2 \bmod 82) \bmod 3$$ Leading to: ``` a | b | 512b | a + 512b | + 8 | squared | MOD 82 | MOD 3 ---+---+------+----------+------+---------+--------+------- 0 | 0 | 0 | 0 | 8 | 64 | 64 | 1 a 1 | 0 | 0 | 1 | 9 | 81 | 81 | 0 0 1 2 2 | 0 | 0 | 2 | 10 | 100 | 18 | 0 +------- 0 | 1 | 512 | 512 | 520 | 270400 | 46 | 1 0 | 1 0 0 1 | 1 | 512 | 513 | 521 | 271441 | 21 | 0 --> b 1 | 1 0 2 2 | 1 | 512 | 514 | 522 | 272484 | 80 | 2 2 | 2 2 1 0 | 2 | 1024 | 1024 | 1032 | 1065024 | 8 | 2 1 | 2 | 1024 | 1025 | 1033 | 1067089 | 23 | 2 2 | 2 | 1024 | 1026 | 1034 | 1069156 | 40 | 1 ``` ### Function choice There are several other possible candidate functions of the form: $$f\_{k,c,p,m}(a,b)=((a+kb+c)^p \bmod m) \bmod 3$$ One of the shortest ones being: $$f(a,b)=((a+5b+2)^4 \bmod 25) \bmod 3$$ But the good thing about \$(a+512b+8)\$ is that it can be performed with bitwise operators, thus implicitly discarding the decimal parts of \$a\$ and \$b\$. This is why we can simply divide them by \$3\$ without rounding between each iteration. ### Commented ``` f = (a, b, // given the input integers a and b k = 9) => // and starting with k = 9 ~k && // if k is not equal to -1: ( a % 3 // compute (a mod 3) | b % 3 << 9 // add 512 * (b mod 3) | 8 // add 8 ) ** 2 // square the result % 82 // apply modulo 82 % 3 // apply modulo 3, leading to crazy(a % 3, b % 3) + 3 * f( // add 3 times the result of a recursive call with: a / 3, // a / 3 \__ no rounding required b / 3, // b / 3 / (see 'Function choice') k - 1 // k - 1 ) // end of recursive call ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ### Code: ``` 3Tm+3Bø5+3m5(^3%3β ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/fOCRX29jp8A5TbeNcU404Y1Xjc5v@/482NDI2MdVRMDUxNjKMBQA "05AB1E – Try It Online") ### Algorithm Explanation In order to get the number padded with zeroes, we need to add **59049** to both numbers (because 59049 in ternary is **10000000000**). We do not have to leave out the leading **1** as \$(1, 1) \rightarrow 0\$. We convert the numbers from decimal to ternary and join each pair as each own number. For example, for input **12345** and **54321**, these get mapped to: $$ \begin{array} & 12345 \rightarrow & 1 & 0 & 1 & 2 & 1 & 2 & 2 & 1 & 0 & 2 & 0 \\ 54321 \rightarrow & 1 & 2 & 2 & 0 & 2 & 1 & 1 & 1 & 2 & 2 & 0 \end{array} $$ Which gives the following list of joined integers: $$ 11, 2, 12, 20, 12, 21, 21, 11, 2, 22, 0 $$ These integers need to be mapped by the given lookup table in the OP. The formula we currently use that maps these numbers to their corresponding trits (\$0 \rightarrow 1, 10 \rightarrow 0, \dots\$) is: $$ f(x) = \left((x + 5)^3 \oplus -5\right) \text{ mod }3 $$ Whereas \$\oplus\$ denotes the bitwise **xor** function. Eventually after mapping this function on the list of joined integers, we treat this resulting list as a number represented in base 3 and convert it from base 3 to decimal. ### Code Explanation ``` 3Tm+ # Add 59049 to pad the ternary number with zeroes. 3B # Convert to base 3. ø # Zip the list to get each joined integer. 5+ # Add 5 to each element. 3m # Raise each element to the power of 3. 5(^ # XOR each element with -5. 3% # Modulo each element with 3. 3β # Convert from base 3 to decimal. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~74~~ ~~72~~ 71 bytes ``` f(a,b,i,r){for(r=0,i=59049;i/=3;)r+=(108609>>a/i%3*2+b/i%3*6&3)*i;i=r;} ``` [Try it online!](https://tio.run/##LU5dC8IwDHy2v6IISrtF7Mc6Nkr9Jb50k408OKWIL2O/vaYqhNzlckcynuZxzHkSEQZASHKdHkmkoACD61XTezwH62Wqg9Cqa1V/ucQzHmxl6uGL7dHKCj2G5Lf8fuCNzwKXF4/ACwySrWz3TMQnsT/cOFWgdl32UDwD8HKcfNKzjbGSuUdcxDc3CwVc0YaYBm5@rDzWAXe/yba9crQzuvkbtXUkEOi/YGxDgmusKcqWPw "C (gcc) – Try It Online") ## Breakdown The truth table ``` a op(a,b) 0 1 2 +------- 0 | 1 0 0 b 1 | 1 0 2 2 | 2 2 1 ``` Can be thought of as a 3x3 array, where a is the column, and b is the row. Transforming that into a one-dimensional list gives us 100102221. To save space we avoid lists and strings and make it into a number instead. To do that, we flip the order and transform every trit into a 2-bit number. Glue them together and we have a binary number we can "index" into by shifting to the right by `2 * (b * 3 + a)` and masking: ``` 1 0 0 1 0 2 2 2 1 1 2 2 2 0 1 0 0 1 011010100001000001 ``` Next, we massage the expression using the power of operation precedence to become the abomination above. ~~3^9 = 19683 so that is a good loop limit. Since we multiply the counter by 3 each time, we can write the limit as `2e4` instead. Also we save ourselves the bother of `pow()` or similar.~~ On second thought, let's start at 3^10 and work downwards with a pre-loop divide-and-test. [Answer] # [R](https://www.r-project.org/), ~~64~~ 62 bytes ``` function(a,b,x=3^(9:0))30801%/%x[a%/%x%%3*3+b%/%x%%3+1]%%3%*%x ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0mnwtY4TsPSykBT09jAwsBQVV@1IjoRRKqqGmsZaydBmdqGsUBSVUu14n@ahqGRsYmpjqmJsZGh5n8A "R – Try It Online") *Thanks to [JAD](https://codegolf.stackexchange.com/users/59530/jad) for some ~~black magic~~ golfing tricks and -2 bytes!* `30801`, when converted to a 10-trit ternary integer, is `1120020210` which just adds a trailing zero to the operation table, when read down the columns. Then we convert the ternary digits of `a` and `b` elementwise into an integer and use that as an index into the ternary digits of `30801`. [Answer] # [Haskell](https://www.haskell.org/), 108 bytes ``` 2%2=1 _%2=2 0%_=1 2%1=2 _%_=0 g=take 10.map(`mod`3).iterate(`div`3) (foldr((.(3*)).(+))0.).(.g).zipWith(%).g ``` [Try it online!](https://tio.run/##Dcc7DsMgEEXRnlVQBGkmkUaAa9aREpD4GBls5KAU2Tyhefe83X@OWOucWmijmF2rmRR2WQu1bJcly2b4I3IlqfkOrl3BbUhlxNuPCC6U7/osGUhXDTcAwfZEJHghSlqljPQr/V3GDgIpz@bLafpdzvFIXHE9/w "Haskell – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~41~~ 25 bytes *9 bytes saved thanks to @Adám* ``` 3⊥(b⊤6883)[3⊥⍉⎕⊤⍨3,b←9⍴3] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862gv@Gz/qWqqR9KhriZmFhbFmNIj7qLcTqAgo9Kh3hbFOElCt5aPeLcax/4Ea/iuAQQGXgYIBF4xtpGAIZ5sqmFoamFgg5IwMTRSMzSwNTOFChobGhgpAwhQhZGpibAQUMzI2MQUA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 23 ~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (rearrange `3*⁵¤` to `⁵3*`) ``` ⁵3*+b3Zḅ3ị⁽½Ṡb3¤ḅ3 ``` A monadic link accepting a list of two integers. **[Try it online!](https://tio.run/##y0rNyan8//9R41ZjLe0k46iHO1qNH@7uftS499DehzsXJBkfWgIS@v//v6GRsYmpjoKpibGRIQA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9R41ZjLe0k46iHO1qNH@7uftS499DehzsXJBkfWgIS@n90z@H2R01r3IDY/f//6GgDHQWDWB2FaEMdBSMQbWppYGKho2AKYhubWRqYAsWNDE3ASgyNTYFcIGUI5hoZmwC5pibGRoaxsQA "Jelly – Try It Online"). `⁹*%733%3` is a byte longer than `ị⁽½Ṡb3¤` :( ### How? ``` ⁵3*+b3Zḅ3ị⁽½Ṡb3¤ḅ3 - Link: [a, b] e.g. [11355,1131] ⁵ - literal ten 10 3 - literal three 3 * - exponentiation 59049 + - addition (vectorises) [70404,60180] 3 - literal three 3 b - to base (vectorises) [[1,0,1,2,0,1,2,0,1,2,0],[1,0,0,0,1,1,1,2,2,2,0]] Z - transpose [[1,1],[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2],[0,0]] 3 - literal three 3 ḅ - from base (vectorises) [4,0,3,6,1,4,7,2,5,8,0] ¤ - nilad followed by link(s) as a nilad: ⁽½Ṡ - literal 3706 3706 3 - literal three 3 b - to base [1,2,0,0,2,0,2,1] ị - index into [0,1,0,0,1,0,2,2,2,1,1] 3 - literal three 3 ḅ - from base 20650 ``` --- Also 18: `⁵3*+b3ZḌ19*%74%3ḅ3` (uses a magic-formula after getting the pair-wise trits of converting from base ten then taking 19 to that power, modulo 74, modulo 3 to get the required trits of the output - found using a search in Python) [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ ~~65~~ ~~63~~ 61 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for his formula (-2 bytes). ``` f=lambda a,b,i=9:i+1and(a%3+b%3*5+2)**4%25%3+f(a/3,b/3,i-1)*3 ``` [Try it online!](https://tio.run/##HY3BCsMwDEPv@wpfCknqsTiOx1roxySUssCWltLLvj5zezDyExLafsd7raG1Zfqkb54TJMxYpmEsPaU6m9Rxnzt20gfrXOyCqLGY9GDMeuVO1nFb1l2LkKFUMB7BWwRDCOFUGXx8Icj583Pwon6geEWIRVGFLgwcFSVyIDveALa91AN0DrNtfw "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 37 bytes ``` ((3 3$d 30801){~{@,.)&.(d=.(10$3)&#:) ``` Explanation: ``` ((3 3$d 30801){~{@,.)&.(d=.(10$3)&#:) (d=.(10$3)&#:) convert to 10 trits, and name this function as d &. ... which is done on both args and inverted on the result {@,. make boxed indices: 1 2 3 4 {@,. 5 6 7 8 -> 1 5 ; 2 6 ; 3 7 ; 4 8 {~ index out of a lookup table (3 3$d 30801) reusing the trits conversion function to make the table ``` Ended up being relatively readable, tbh. [Answer] # [Python 2](https://docs.python.org/2/), ~~90~~ 87 bytes ``` f=lambda a,b,A='':f(a/3,b/3,'100102221'[a%3+b%3*3]+A)if a+b else int(A.rjust(10,'1'),3) ``` [Try it online!](https://tio.run/##HY7PDoIwDMbP8hS9mG3S6LoyoyYceA7CYYsSMYgE8ODTz8Kh@frr32/8Lc/P4FJqyz684z1AwIhVqdSt1eHEGCUUWUvWOUeqDnvO454P3OSV6VoIeYRHPz@gGxZdHafXd140WdlRBtmk9jOtJ6UNtbYI1iBoQnCr@qstLgh@zfl8tV7qjopthNgLitCGjgtBX7Aj09yy3TjJw82s@MRospT@ "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` I↨³⮌⭆χ§200211⁺∨﹪÷θX³ι³¦⁴﹪÷ηX³ι³ ``` [Try it online!](https://tio.run/##ZYy9CsIwGEVfJXT6ChHy18lJ69KhWHQUh9AEGwiJJmn07WPEsRcOXDiXOy8yzF7aUqZgXIJexgRHGTVwjC4661DrNVX3GOUTKMHokAan9AcaRgijtMFosmuEc4DRq9V6GFw6mWyUhld1/q3D78y0LUa8Iiqb5bJd/rMv5UYZFx1GneCM3ssu2y8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` χ Predefined variable 10 ⭆ Map over implicit range and join ι ι Current index X³ X³ Power of 3 θ Input `a` η Input `b` ÷ ÷ Integer divide ﹪ ³ ﹪ ³ Modulo by 3 ∨ ¦⁴ Replace zero ternary digit of `a` with 4 ⁺ Add §200211 Index into literal string `200211` ⮌ Reverse ↨³ Convert from base 3 I Cast to string Implicitly print ``` Alternative solution, also 31 bytes: ``` I↨³E↨⁺X³χ賧200211⁺∨ι⁴§↨⁺X³χη³κ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDWEfBN7EAwg7IKS3WCMgvTy0CCRsaaOooFAKxMRA7lnjmpaRWaCgZGRgYGRoq6SiAFfsXaWTqKJggKcBlUAbUoGxNELD@/z/a0MjYxFRHwdTE2Mgw9r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. ``` χ χ Predefined variable 10 X³ X³ Power of 3 i.e. 59049 θ Input `a` η Input `b` ⁺ ⁺ Sum ↨ ³ ↨ ³ Convert to base 3 E Map over elements ι Current ternary digit of `a` ∨ ⁴ Replace zero with 4 § κ Index into ternary digits of `b` ⁺ Add §200211 Index into literal string `200211` ↨³ Convert from base 3 I Cast to string Implicitly print ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é╨¼aûé∟ç⌂zπb![5┬◘«╜‼╞♠ ``` [Run and debug it](https://staxlang.xyz/#p=82d0ac6196821c877f7ae362215b35c208aebd13c606&i=[0,0]%0A[1,2]%0A[59048,5]%0A[36905,2214]%0A[11355,1131]%0A[12345,54321]&a=1&m=2) [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~25~~ 22 bytes ``` 3/(3\10267)@3/+(10#3)\ ``` [Try it online!](https://tio.run/##JcrNCoJQEIbhfVcxUAslwvk5c8wzm@5DBdsYoRiICyXq1k9qmw@ej7e7DI8hxjZIlkhFyD5Pb5KdE8KjpFWcwvtULt8xtDBb8@osadr7s7fZFhvT@nOYSgQ0LpRdvYKAd@gGLdBdQS3fIL5ABWZyhntJogrrkjF6/X8sTkGdMJk6T76OPw "K (ngn/k) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 70 bytes ``` ->a,b,l=10{l>0?6883.digits(3)[8-b%3*3-a%3]*3**(10-l)+f[a/3,b/3,l-1]:0} ``` [Try it online!](https://tio.run/##HUzdCoMgGL3fU@wmKPfZ1E/DBrUHES@U1QgcxKqLUT27sy7OP5zv4n@xbyJtHXgIDWdraNmz0hrL1/Ae5inHwmjqMyRIXYaWICE5ZzQUt964O4JPCJTbB9vjuMzT1RgGzMLFcBCHqJpJDeqwWNVMgRBcnjtHpSAxP5NAqUBJFNza8uPGdeu23nQmfXUmdXv8Aw "Ruby – Try It Online") Decomposes `a` and `b` recursively until we get 10 digits of each. `6883` gives the flattened ternary table (reversed). Reconstructs from ternary to decimal by multiplying by `3**(10-l)`. [Answer] ## Cjam, 31 bytes ``` {{3bA0e[\}2*.{3*+"100102221"=}} ``` [Try it online!](https://tio.run/##S85KzP3/v7raOMnRIDU6ptZIS6/aWEtbydDAwNDAyMjIUMm2tvb/fwA) [Answer] # [J](http://jsoftware.com/), 43 bytes ``` 3#.((3 3$t 6883){~<@,~"0)&(_10{.t=.3&#.inv) ``` It can certainly be golfed further. ## Explanation: ``` &( ) - for both arguments t=.3&#.inv - convert to base 3 (and name the verb t) _10{. - pad left with zeroes ( <@,~"0) - box the zipped pairs (for indexing) (3 3$t 6883) - the lookup table {~ - use the pairs as indeces in the table 3#. - back to decimal ``` [Try it online!](https://tio.run/##LYzBCsIwDIbvfYqwydbCCE3Tjm5Y8E08iEU96GHDy3CvXlu6Q8j3fwn/K8UlIGiYQSduUUoGPq0wes9q28@XYW@06uSV9IZrQO5afL6/KinRIPQxYA8D/GaIixD32@OTq2KeypTZVHSTtj5HVyOPk3blasgev8SumLzpMIZtMc6yofQH "J – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth) ~~26 25~~ 24 bytes *Saved 1 byte, thanks to @ErikTheOutgolfer* *Save another byte, inspired by @JonathanAllan's [answer](https://codegolf.stackexchange.com/a/167700/41020)* ``` im@j3422 3id3Cm.[0Tjd3Q3 ``` Input is a 2 element list `[a,b]`. Try it online [here](https://pyth.herokuapp.com/?code=im%40j3422%203id3Cm.%5B0Tjd3Q3&input=%5B12345%2C54321%5D&debug=0), or verify all test cases [here](https://pyth.herokuapp.com/?code=QE%0Aim%40j3422%203id3Cm.%5B0Tjd3Q3&test_suite=1&test_suite_input=%5B0%2C0%5D%0A29524%0A%5B1%2C2%5D%0A29525%0A%5B59048%2C5%5D%0A7%0A%5B36905%2C%202214%5D%0A0%0A%5B11355%2C1131%5D%0A20650%0A%5B12345%2C54321%5D%0A54616&debug=0&input_size=2). ``` im@j3422 3id3Cm.[0Tjd3Q3 Implicit: Q=eval(input()) m Q Map each element d of the input using: jd3 Convert to base 3 .[0T Pad to length 10 with 0's C Transpose m Map each element d of the above using: j3422 3 The lookup table [1,1,2,0,0,2,0,2] @ Modular index into the above using id3 Convert d to base 10 from base 3 i 3 Convert to base 10 from base 3, implicit print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~24~~ 23 bytes Getting the ball rolling on Japt's run as [language of the month](https://codegolf.meta.stackexchange.com/q/16592/58974) - I fully expect to be outgolfed on this! Takes input in reverse order as an integer array (i.e., `[b,a]`). ``` ms3 ùTA y_n3 g6883ì3Ãì3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bXMzIPlUQSB5X24zIGc2ODgz7DPD7DM&input=WzU0MzIxLDEyMzQ1XQ) ``` ms3 ùTA y_n3 g6883ì3Ãì3 :Implicit input of array U=[b,a] m :Map s3 : Convert to base-3 string ù :Left pad each T : With zero A : To length 10 y :Transpose _ :Map n3 : Convert from base-3 string to decimal g : Index into 6883ì3 : 6883 converted to a base-3 digit array à :End map ì3 :Convert from base-3 digit array to decimal ``` [Answer] # MMIX, 77 bytes (17 instrs + 9 data bytes) ``` 00000000: e303000a f4040010 e3020000 e3050001 ẉ¤¡½ṡ¥¡Ñẉ£¡¡ẉ¦¡¢ 00000010: 25030301 1d000003 fe060006 1d010103 %¤¤¢ø¡¡¤“©¡©ø¢¢¤ 00000020: feff0006 28060606 200606ff 80060406 “”¡©(©©© ©©”⁰©¥© 00000030: 18060506 20020206 28050505 5b03fff5 𩦩 ££©(¦¦¦[¤”ṫ 00000040: f8030000 01010200 00020002 01 ẏ¤¡¡¢¢£¡¡£¡£¢ ``` ``` malop SET $3,10 // i = 10 GETA $4,1F // oparr = {1,1,2,0,0,2,0,2,1} SET $2,0 // r = 0 SET $5,1 // p = 1 0H SUB $3,$3,1 // loop: i-- DIV $0,$0,3 GET $6,rR // x:xr = x /% 3 DIV $1,$1,3 GET $255,rR // y:yr = y /% 3 2ADDU $6,$6,$6 ADD $6,$6,$255 LDB $6,$4,$6 // j = oparr[xr * 3 + yr] MUL $6,$5,$6 // j *= p ADD $2,$2,$6 // r += j 2ADDU $5,$5,$5 // p *= 3 PBNZ $3,0B // if(i) goto loop POP 3,0 // return r 1H BYTE 1,1,2,0,0,2,0,2,1 ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 102 bytes ``` sub t{map{("@_"%3,$_[0]/=3)[0]}0..9}@a=t$_;@b=t<>}{$\=(1,1,2,0,0,2,0,2,1)[(3*pop@a)+pop@b]+$\*3while@a ``` [Try it online!](https://tio.run/##HcXdCoIwAEDh@54iZMGm0/bjLqIWe4GeQEU2GDUwHbroQvbqLYvD4fN2HkRKy8vsw/rUfoWZ6rMDx6BvSHeUHG1EUlWnqLQMoD8rI8PlGlfQSkgxxQyTLfafogby3E9eaVT8MF0B2py/H26wSqdEGa/FTtSc0c/kg5vGJZU3NwZ7t3Mq/Rc "Perl 5 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~75~~ ~~72~~ 60 bytes ``` (d=IntegerDigits)[6883,3][[{1,3}.d[#,3,10]+1]]~FromDigits~3& ``` [Try it online!](https://tio.run/##RYyxCsIwFEV3vyIgiOJTkry82A7ZRHDoF4QMRUvN0Co1W2l/PUZTcLpwzr23q8Oj6ergb3WsmInbu7n2oWmb4exbH947q4sCAZ21owCcjne7BgTB3V44N1@GZ5eLM27iWNmRA@OTY8YwWZJUsGLVd8nkH1KGVHJVAKMsTsB@FHXJKdWlUFnw5UIgJZ5CLE9cE19GQqJKkhTKxZLSQk8xHl6D78MH "Wolfram Language (Mathematica) – Try It Online") un-golfed version: ``` M[{a_, b_}] := FromDigits[{1, 0, 0, 1, 0, 2, 2, 2, 1}[[ IntegerDigits[a, 3, 10] + 3*IntegerDigits[b, 3, 10] + 1 ]], 3]; ``` Both `a` and `b` are converted to ten-trit lists, then used pairwise as a 2D index into a lookup table of numbers `{1, 0, 0, 1, 0, 2, 2, 2, 1}`. The result is again interpreted as a ten-trit list and converted back to integer form. The lookup table is coded as `IntegerDigits[6883,3]`, which is short because we are recycling the `IntegerDigits` symbol. ]
[Question] [ Graham's number \$G\$ is defined in this way: \begin{align\*} u(3,n,1) & = 3^n \\ u(3,1,m) & = 3 \\ u(3,n,m) & = u(3,u(3,n-1,m),m-1) \end{align\*} Then, \begin{align\*} g\_1 & = u(3,3,4) \\ g\_2 & = u(3,3,g\_1) \\ g\_3 & = u(3,3,g\_2) \\ & \vdots \\ G & = u(3,3,g\_{63}) \end{align\*} You are given that \$u(3,3,2)=7625597484987\$ to check your code. Your task is to write a program/function that will output the value of \$G\$ deterministically, given enough integer size and enough time. # References * [Graham's number](https://en.wikipedia.org/wiki/Graham%27s_number) * [Knuth's up-arrow notation](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) * [Conway chained arrow notation](https://en.wikipedia.org/wiki/Conway_chained_arrow_notation) # Leaderboard ``` var QUESTION_ID=83873,OVERRIDE_USER=48934;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+(?:\.\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] # [Binary lambda calculus](https://tromp.github.io/cl/cl.html), 114 bits = 14.25 bytes Hexdump: ``` 00000000: 4457 42b0 2d88 1f9d 740e 5ed0 39ce 80 DWB.-...t.^.9.. ``` Binary: ``` 010001000101011101000010101100000010110110001000000111111001110101110100000011100101111011010000001110011100111010 ``` ### Explanation ``` 01 00 (λx. │ 01 00 (λy. │ │ 01 01 01 110 x │ │ │ │ └─ 10 y │ │ │ └─ 00 (λm. │ │ │ 01 01 01 10 m │ │ │ │ │ └─ 00 (λg. │ │ │ │ │ 00 λn. │ │ │ │ │ 01 01 10 n │ │ │ │ │ │ └─ 110 g │ │ │ │ │ └─ 00 (λz. │ │ │ │ │ 10 z)) │ │ │ │ └─ 00 (λn. │ │ │ │ 00 λf. │ │ │ │ 01 111110 x │ │ │ │ └─ 01 110 (n │ │ │ │ └─ 10 f)) │ │ │ └─ 1110 x) │ │ └─ 10 y) │ └─ 00 (λf. │ 00 λz. │ 01 110 f │ └─ 01 01 1110 (x │ │ └─ 110 f │ └─ 10 z))) └─ 00 (λf. 00 λz. 01 110 f └─ 01 110 (f └─ 01 110 (f └─ 10 z))) ``` This is (λ*x*. (λ*y*. *x* *y* (λ*m*. *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. *x* (*n* *f*)) *x*) *y*) (λ*f*. λ*z*. *f* (*x* *f* *z*))) 3, where all numbers are represented as [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals). Church numerals are the standard lambda calculus representation of natural numbers, and they are well suited to this problem because a Church number is defined by function iteration: *n* *g* is the *n*th iterate of the function *g*. For example, if *g* is the function λ*n*. λ*f*. 3 (*n* *f*) that multiplies 3 by a Church numeral, then λ*n*. *n* *g* 1 is the function that takes 3 to the power of a Church numeral. Iterating this operation *m* times gives *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. 3 (*n* *f*)) *n* = *u*(3, *n*, *m*). (We use multiplication *u*(–, –, 0) rather than exponentiation *u*(–, –, 1) as the base case, because subtracting 1 from a Church numeral is [unpleasant](https://en.wikipedia.org/wiki/Church_encoding#Derivation_of_predecessor_function).) Substitute *n* = 3: *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. 3 (*n* *f*)) 3 = *u*(3, 3, *m*). Iterating that operation 64 times, starting at *m* = 4, gives 64 (λ*m*. *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. 3 (*n* *f*)) 3) 4 = *G*. To optimize this expression, substitute 64 = 4^3 = 3 4: 3 4 (λ*m*. *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. 3 (*n* *f*)) 3) 4 = *G*. Remember 4 = succ 3 = λ*f*. λ*z*. *f* (3 *f* *z*) as a lambda argument: (λ*y*. 3 *y* (λ*m*. *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. 3 (*n* *f*)) 3) *y*) (λ*f*. λ*z*. *f* (3 *f* *z*)) = *G*. Finally, remember 3 = λ*f*. λ*z*. *f* (*f* (*f* *z*)) as a lambda argument: (λ*x*. (λ*y*. *x* *y* (λ*m*. *m* (λ*g*. λ*n*. *n* *g* 1) (λ*n*. λ*f*. *x* (*n* *f*)) *x*) *y*) (λ*f*. λ*z*. *f* (*x* *f* *z*))) 3 = *G*. [Answer] # Haskell, 41 bytes ``` i=((!!).).iterate i(($3).i(`i`1)(*3))4 64 ``` Explanation: `(`i`1)f n` = `i f 1 n` computes the `n`th iterate of the function `f` starting at `1`. In particular, `(`i`1)(*3)n` = 3^*n*, and iterating this construction *m* times gives `i(`i`1)(*3)m n` = *u*(3, *n*, *m*). We can rewrite that as `(($n).i(`i`1)(*3))m` = *u*(3, *n*, *m*), and iterate this construction *k* times to get `i(($3).i(`i`1)(*3))4 k` = *g*\_*k*. [Answer] ## Haskell, 43 bytes ``` q=((!!).).iterate g=q(`q`1)(3*) q(`g`3)4$64 ``` There has be a better way to flip `g` inline. **46 bytes:** ``` i=iterate n%0=3*n n%m=i(%(m-1))1!!n i(3%)4!!64 ``` --- **48 bytes:** ``` n%1=3^n 1%m=3 n%m=(n-1)%m%(m-1) iterate(3%)4!!64 ``` Just writing down the definitions. The base cases are a bit cleaner backed up to 0, though it saves no bytes. Perhaps it will make it easier to write an alternate definition. ``` n%0=3*n 0%m=1 n%m=(n-1)%m%(m-1) z=iterate(3%)2!!1 ``` [Answer] # Pyth, 25 bytes ``` M?H.UgbtH*G]3^3Gug3tG64 4 ``` The first part `M?H.UgbtH*G]3^3G` defines a method `g(G,H) = u(3,G,H+1)`. To test the first part, check that `7625597484987=u(3,3,2)=g(3,1)`: [`g3 1`](http://pyth.herokuapp.com/?code=M%3FH.UgbtH%2aG%5D3%5E3Gg3+1&debug=0). The second part `ug3tG64 4` starts from `r0 = 4` and then compute `rn = u(3,3,r(n-1)) = g(3,r(n-1))` 64 times, outputting the final value (`r` is chosen instead of `g` to avoid confusion). To test this part, start from `r0=2` and then compute `r1`: [`ug3tG1 2`](http://pyth.herokuapp.com/?code=M%3FH.UgbtH%2aG%5D3%5E3Gug3tG1+2&debug=0). [Answer] ## JavaScript (ES7), 63 bytes ``` u=(n,m)=>n>1&m>1?u(u(n-1,m),m-1):3**n g=n=>n?u(3,g(n-1)):4 g(64) ``` [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 30 bytes ``` 0000000: 286997 2449f0 6f5d10 07f83a 06fffa f941bb ee1f33 (i.$I.o]...:....A...3 0000015: 065333 07dd3e 769c7b .S3..>v.{ ``` ### Disassembled ``` set numout add 4 rwd 2 add 64 jmp sub 1 fwd 3 add 3 rwd 1 add 1 jmp sub 1 jmp fwd 1 jmp jmp sub 1 fwd 1 add 1 rwd 1 jnz rwd 1 jmp sub 1 fwd 3 add 1 rwd 3 jnz fwd 3 jmp sub 1 rwd 2 add 1 rwd 1 add 1 fwd 3 jnz rwd 1 sub 1 jnz rwd 1 jmp sub 1 jnz add 1 rwd 1 sub 1 jnz fwd 1 jmp sub 1 rwd 1 add 3 fwd 1 jnz rwd 2 jnz rwd 1 jnz fwd 2 put ``` Or in Brainfuck notation: ``` ++++<<++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [->>>+++<+[-[>[[->+<]<[->>>+<<<]>>>[-<<+<+>>>]<-]<[-]+<-]>[-<+++>]<<]<]>>. ``` ### Testing To compute *u*(3, *n*, *u*(3, *n*, … *u*(3, *n*, *m*) … )) with *k* nested calls to *u*, replace the first three `add` instructions `add 4`, `add 64`, `add 3` with `add m`, `add k`, `add n`, respectively. Because Sesos can’t build numbers faster than in linear time, you’re practically limited to small values like *u*(3, 2, 2) = 27, *u*(3, 5, 1) = 243, and *u*(3, 1, *u*(3, 1, … *u*(3, 1, *m*) … )) = 3. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 57 bytes ``` 4:64:1iw :3{[1:N],3:N^.|t1,3.|hM:1-X,?t:1-:Mr:2&:Xr:2&.}. ``` Expects no Input nor Output and writes the result to `STDOUT`. This will produce a stack overflow at one point. To check that this works for small values (e.g `u(3,3,2)`) you can replace the `4` with the value of `m` and `64` with `1`. ### Explanation This is basically a straightforward implementation of the explained way of computing the number. * Main predicate: ``` 4:64:1i Call Predicate 1 64 times with 4 as initial input (the second call takes the output of the first as input, etc. 64 times). w Write the final output to STDOUT ``` * Predicate 1: ``` :3{...}. Call predicate 2 with input [Input, 3]. Its output is the output of predicate 1. ``` * Predicate 2: ``` [1:N], M = 1 3:N^. Output = 3^N | Or t1, N = 1 3. Output = 3 | Or hM:1-X, X is M - 1 ?t:1-:Mr:2& Unify an implicit variable with u(3,N-1,M) :Xr:2&. Unify Output with u(3,u(3,N-1,M),X) ``` [Answer] # [Caramel](https://github.com/MaiaVictor/caramel), 38 bytes ``` (64 ((f->(f,1)),(n f->(3 (n f))),3) 4) ``` This is syntactic sugar for the lambda calculus expression 64 (λ*m*. *m* (λ*f*. λ*n*. *n* *f* 1) (λ*n*. λ*f*. 3 (*n* *f*)) 3) 4, where all numbers are represented as [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals). [Answer] # Mathematica, 59 bytes ``` n_ ±1:=3^n 1 ±m_:=3 n_ ±m_:=((n-1)±m)±(m-1) Nest[3±#&,4,64] ``` Uses an undefined infix operator `±` which requires only 1 byte when encoded in ISO 8859-1. See @Martin's [post](https://codegolf.stackexchange.com/a/82740/6710) for more info. Mathematica functions support pattern matching for their arguments, such that the two base cases can be defined separately. [Answer] # Prolog (SWIPL), 129 / 137 bytes ``` g(1,R):-u(3,4,R). g(L,R):-M is L-1,g(M,P),u(3,P,R). u(N,1,R):-R is 3**N. u(1,_,3). u(N,M,R):-K is N-1,L is M-1,u(K,M,Y),u(Y,L,R). ``` To output Graham's number, query for `g(64,G).` (if the 8 bytes of this query are to be counted, the length is 137 bytes): ``` ?- g(64, G). ERROR: Out of local stack ``` But as can be expected, this runs out of stack. ## Test ``` ?- u(3, 2, X). X = 7625597484987 ``` Backtracking causes it to run out of stack: ``` ?- u(3, 2, X). X = 7625597484987 ; ERROR: Out of local stack ``` ## Ungolfed The ungolfed version adds the general up-arrow notation, not just for 3, and uses cuts and checks to avoid backtracking and undefined situations. ``` % up-arrow notation u(X, 1, _M, X) :- !. u(X, N, 1, R) :- R is X**N, !. u(X, N, M, R) :- N > 1, M > 1, N1 is N - 1, M1 is M - 1, u(X, N1, M, R1), u(X, R1, M1, R). % graham's number g(1,R) :- u(3, 3, 4, R), !. g(L,R) :- L > 1, L1 is L - 1, g(L1,G1), u(3, G1, R). ``` [Answer] # C, 161 bytes ``` u(int a, int b){if(a==1)return 3;if(b==1)return pow(3,a);return u(u(a-1,b),b-1);} g(int a){if(a==1)return u(3,4);return u(3,g(a-1));} main(){printf("%d",g(64));} ``` EDIT: saved 11 bytes by removing tabs and newlines. EDIT: thx auhmann saved another byte and fixed my program [Answer] # C, ~~114~~ 109 bytes Based on the answer by @thepiercingarrow ([link](https://codegolf.stackexchange.com/a/83999/45611)) I golfed the answer down quite a bit. Most savings are due to the abuse of default typing of arguments when doing K&R style functions and replacement of if statements with ternary operators. Added optional newlines between functions for readability. Improved to 109 thanks to @LeakyNun. ``` u(a,b){return a<2?3:b<2?pow(3,a):u(u(a-1,b),b-1);} g(a){return u(3,a<2?4:g(a-1));} main(){printf("%d",g(64));} ``` [Answer] ## Python, 85 bytes ``` v=lambda n,m:n*m and v(v(n-1,m)-1,m-1)or 3**-~n g=lambda n=63:v(2,n and g(n-1)-1or 3) ``` The `v` function defines the same function as the one found in [Dennis's answer](https://codegolf.stackexchange.com/a/83923/45941): `v(n,m) = u(3,n+1,m+1)`. The `g` function is a zero-indexed version of the traditional iteration: `g(0) = v(2,3), g(n) = v(2,g(n-1))`. Thus, `g(63)` is Graham's number. By setting the default value of the `n` parameter of the `g` function to `63`, the required output can be obtained by calling `g()` (with no parameters), thus meeting our requirements for a function submission which takes no input. Verify the `v(2,1) = u(3,3,2)` and `v(4,0) = u(3,5,1)` test cases online: [Python 2](http://ideone.com/a5lkxi), [Python 3](http://ideone.com/1XQwsQ) [Answer] ## Dyalog APL, 41 bytes ``` u←{1=⍺:3⋄1=⍵:3*⍺⋄(⍵∇⍨⍺-1)∇⍵-1} 3u 3u⍣64⊣4 ``` Test case: ``` 3u 2 7625597484987 ``` [Answer] # Ruby, 64 bytes Borrowing from [Theoretical algorithm to compute Graham's number](https://codegolf.stackexchange.com/questions/20711/theoretical-algorithm-to-compute-grahams-number). ``` def f(a,b=3)b<2?3:a<1?3*b:f(a-1,f(a,b-1))end;a=4;64.times{a=f a};p a ``` Simply put, `f a = u(3,3,a)` and it applies this 64 times. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ’ß’ß’}ð‘3*ða? 4’2çƊ64¡ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8zD82FE7eENjxpmGGsd3pBoz2UCFDA6vPxYl5nJoYV41OmARJfrcx1ernR00sOdMx41rYn8z/XfWEfBVEfB8L8RkAAyAQ "Jelly – Try It Online") I believe this is close to identical to [Dennis' deleted Jelly answer](https://codegolf.stackexchange.com/a/83923/66833) but was developed independently and uses a language feature that wasn't available at the time of his answer. The first line defines a function \$v(n, m) = u(3, n+1, m+1)\$ and the TIO footer demonstrates this for \$u(3, 3, 2)\$, \$u(3, 5, 1)\$ and \$u(3, 1, 5)\$. With our defined \$v\$, we then have the recurrence relation \begin{align\*} g\_1 & = v(2, 3) \\ g\_{i+1} & = v(2, g\_i - 1) \\ G = g\_{64} & = v(2, g\_{63} - 1) \end{align\*} A more standard approach, which defines \$w(n, m) = u(3, n, m)\$ and then uses \begin{align\*} g\_1 & = w(3, 4) \\ g\_{i+1} & = w(3, g\_i) \\ G = g\_{64} & = w(3, g\_{63}) \end{align\*} comes out at 23 bytes: ``` 3*ð’ßṛß’}ð«Ị¥? 4 3ç$64¡ ``` [Try it online!](https://tio.run/##y0rNyan8/99Y6/CGRw0zD89/uHP24flAVu3hDYdWP9zddWipPZeJgvHh5SpmJocW4ld3eLnS0UkPd8541LQm8j/Xf2MdBVMdBcP/RkACyAQA "Jelly – Try It Online") ## How they work ### \$v(n, m)\$ ``` ’ß’ß’}ð‘3*ða? - Helper link, v(n, m). Takes n on left, m on right ? - If: a - n and m are both non-zero ð - Then: ’ - n-1 ß - v(n-1, m) ’ - v(n-1, m)-1 ’} - m-1 ß - v(v(n-1, m)-1, m) ð - Else: ‘ - n+1 3* - 3^(n+1) 4’2çƊ64¡ - Main link. No arguments 4 - Set the return value and left argument to 4 Ɗ - Last 3 links as a monad f(x): ’ - x-1 2ç - v(2, x-1) 64¡ - Starting with x = 4, iterate f(x) 64 times ``` ### \$w(n, m)\$ ``` 3*ð’ßṛß’}ð«Ị¥? - Helper link, w(n, m). Takes n on left, m on right ¥? - If: « - min(n, m) Ị - is insignificant (abs(x) ≤ 1) ð - Then: 3* - 3^n ð - Else: ’ - n-1 ṛ - m ß - w(n-1, m) ’} - m-1 ß - w(w(n-1, m), m-1) 4 3ç$64¡ - Main link. No arguments 4 - Set the return value and left argument to 4 $ - Last two links as a monad g(x): 3ç - w(3, x) 64¡ - Starting with x = 4, iterate g(x) 64 times ``` [Answer] # J, 107 bytes ``` u=:4 :0 if.y=1 do.3^x elseif.x=1 do.3 elseif.1 do.x:(y u~<:x)u<:y end. ) (g=:(3 u 4[[)`(3 u$:@<:)@.(1&<))64 ``` I'm working on converting `u` to an agenda, but for now it'll do. [Answer] # F#, ~~111~~ 108 bytes ### Edit This is using the function below to calulcate Graham's number ``` let rec u=function|b,1->int<|3I**b|1,c->3|b,c->u(u(b-1,c),c-1) and g=function|1->u(3.,4.)|a->u(3.,g (a-1)) g 63 ``` Here's my previous answer which, well, didnt: Pretty straightforward. Just a definition of the `u` function. ``` let rec u=function|a,b,1->a**b|a,1.,c->a|a,b,c->u(a,u(a,b-1.,c),c-1) ``` Usage: ``` u(3.,3.,2) val it : float = 7.625597485e+12 ``` If I assumed 3 as the value for a, I could cut it to 60: ``` let rec u=function|b,1->3.**b|1.,c->3.|b,c->u(u(b-1.,c),c-1) ``` Usage: ``` u(3.,2) val it : float = 7.625597485e+12 ``` [Answer] ## R, ~~154~~ ~~142~~ ~~128~~ ~~126~~ 118 bytes ``` u=function(n,b)return(if(n&!b)1 else if(n)u(n-1,u(n,b-1))else 3*b) g=function(x)return(u(if(x-1)g(x-1)else 4,3)) g(64) ``` I used the Wikipedia definition of this recursive function because for some odd reason the suggested one did not work... or I just suck at R golfing. UPD: shaved off 12+14=26 bytes thanks to a tip from [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun). The prior version used the bulky and less efficient ``` u=function(n,b)if(n==0)return(3*b)else if(n>0&b==0)return(1)else return(u(n-1,u(n,b-1))) g=function(x)if(x==1)return(u(4,3))else return(u(g(x-1),3)) ``` UPD: shaved off 2+6+2 more bytes (again, kudos to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)) owing to an ingenious replacement with “if(x)” instead of “if(x==0)” because x<0 is never fed into the function... right? [Answer] # PHP, 114 bytes ignore the line breaks; they are for readability only. ``` function u($n,$m){return$m>1&$n>1?u(u($n-1,$m),$m-1):3**$n;} function g($x){return u(3,$x>1?g($x-1):4);} echo g(63); ``` It is possible to integrate the second case into the first one: for `n=1`, `3^n` equals `3`. This will save a few bytes on - as far as I can see - all existing answers; saved two bytes on my **previous version, 62+43+11=116 bytes** ``` function u($n,$m){return$m>1?$n>1?u(u($n-1,$m),$m-1):3:3**$n;} ``` PHP´s left associativity of the ternary requires parentheses ... or a specific order of tests. This saved two bytes on the parenthesized expression. --- There is probably an iterative approach, which *may* allow further golfing ... but I can´t take the time for it now. ]
[Question] [ Write a program/function that returns the vote count of its own Stack Exchange answer at the time of its execution. * Your program/function may access this page ([codegolf.stackexchange.com/questions/82609](https://codegolf.stackexchange.com/questions/82609)) off the internet, however: * Your program/function may not accept any user input and * The use of URL shorteners is not allowed * Your program/function may use only its own source as a reference point to its vote count (for example: no referencing strings of text in its contained answer but not in its own source) * Your program/function must output its own vote count and **only** its own vote count (for example: no returning all vote counts on this page) This is code-golf, shortest code wins. [Answer] # jQuery + JavaScript, 85 bytes ``` $.get("//api.stackexchange.com/posts/82610?site=codegolf",d=>alert(d.items[0].score)) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` ### History * -6 bytes because I was using the var `data` instead of `d`. * -3 bytes thanks to @msh210 * -13 bytes thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ * -4 bytes thanks to @user6188402 * -5 bytes thanks to @Suever * -4 bytes thanks to @RobW ### Recommended usage * Run snippet. * Upvote. * Run snippet, and be amazed as the number magically increases. ### Bonus!! Who doesn't like a bonus? ``` $.getJSON("//api.stackexchange.com/posts/" + prompt() + "?site=codegolf",d=>alert(d.items[0].score)); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` Enter the ID into the bonus and it will tell you the score. ~~Even more bonus!! Run this snippet to *automatically* run the program, upvote, and run again! (Requires rep > 15, auth). If it doesn't work, please tell me.~~ [Answer] # JavaScript ES6, 107 bytes ``` fetch`//api.stackexchange.com/posts/82672?site=codegolf`.then(r=>r.json()).then(b=>alert(b.items[0].score)) ``` Real programmers don't use `XMLHttpRequest`. Real programmers use the [Fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API). [Answer] # Bash, ~~80~~ ~~79~~ ~~75~~ 69 bytes ``` w3m api.stackexchange.com/posts/82616?site=codegolf|tr ,: \\t|cut -f20 ``` For scoring purposes, `\t` should be replaced with a TAB character. This requires `w3m`, which should be available by default on most Linux distros. *Thanks to @NoOneIsHere for -2 bytes!* ### How it works `w3m` is a command-line web browser. It queries the URL and (normally) displays its content in a readable format. Here, we just (ab)use it to avoid the call to `zcat` that `curl` would require, since SE serves the API response gzip-compressed. `tr ,: \^I` replaces all commas and colons with tabs, which are `cut`'s default field delimiter. Finally, `cut -f20` removes everything but the twentieth field, which is the vote count. [Answer] # JavaScript ES6, ~~175~~ ~~165~~ ~~160~~ 145 bytes Saved lotsa bytes thanks to Optimizer and Dendrobium! They're all multiples of five! Using plain ol' javascript. Who needs those newfangled libraries? [Real programmers](https://xkcd.com/378/) use `XMLHttpRequest()` ``` with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf"),onload=_=>alert(response.match(/re..([0-9]+)/)[1])) ``` ## Test it out ``` alert=x=>o.innerHTML=x; with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf"),onload=_=>alert(response.match(/re..([0-9]+)/)[1])) ``` ``` *{font-family:Consolas,monospace;} ``` ``` <div id=o></div> ``` [Answer] # [bash](https://www.gnu.org/software/bash/)+[jq](https://stedolan.github.io/jq/), 69 bytes ``` w3m api.stackexchange.com/posts/82615?site=codegolf|jq .items[].score ``` I used `curl` and `zcat` before; `w3m` is inspired by Dennis’s (strikingly similar) answer. It turns out `jq` and `tr`/`cut` have the same byte cost! [Answer] # [Convex](http://github.com/GamrCorps/Convex) 0.5, 63 bytes ``` 0000000: 22 d1 2e 46 91 32 e5 69 5d b2 66 81 12 a4 8d d1 "..F.2.i].f..... 0000010: 27 40 b5 32 47 68 97 2c b9 5c 22 05 16 49 10 31 '@.2Gh.,.\"..I.1 0000020: 44 9e f3 0a 6a 16 b0 68 91 93 35 0b 96 dc 91 0a D...j..h..5..... 0000030: 3c 18 80 22 dc 67 27 3c 2f 32 36 39 3d 37 3e <..".g'</269=7> ``` This retrieves the score from the search page instead of the API, specifically from the query <https://codegolf.stackexchange.com/search?q=inquestion:82714>. Fortunately, `inquestion` also works for answers. ### Verification ``` $ echo $LANG en_US $ cat gen.convex "codegolf.stackexchange.com:80/search?q=inquestion:82714"Ö`"Üg'</269=7>" $ java -jar Convex/out/builds/convex-0.5/convex/convex.jar gen.conv > count.conv $ cksum count.conv 2414634109 63 count.conv $ java -jar Convex/out/builds/convex-0.5/convex/convex.jar count.conv 1 ``` ### How it works ``` "..."Ü e# Use the built-in string compression to push e# "codegolf.stackexchange.com:80/search?q=inquestion:82714". g e# Retrieve the HTML page at that URL. '</ e# Split at occurrences of '<'. 269= e# Select the chunk at index 269. e# This pushes "strong>", followed by the vote count. 7> e# Discard the leading seven characters. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~89~~ ~~87~~ 81 bytes Thanks Python... ``` •1Ö8•D’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ƒËŠˆ.‚‹º.ŒŒ/…é/ÿ/').‚Ø())’.er¡14èžz£þ ``` Uses the **CP-1252** encoding. [Answer] # MATLAB, 103 bytes ``` g=@getfield;g(g(webread('http://api.stackexchange.com/2.2/posts/82611?site=codegolf'),'items'),'score') ``` [Answer] # JavaScript (Node.js + [Unirest](http://unirest.io/nodejs.html)), 123 bytes ``` require("unirest").get("http://api.stackexchange.com/posts/82683?site=codegolf").end(x=>console.log(x.body.items[0].score)) ``` I like this library, because it automatically parses JSON. [Answer] # Julia, ~~128~~ 107 bytes ``` using Requests f()=split(readall(get("http://api.stackexchange.com/posts/82621?site=codegolf")),r":|,")[20] ``` This is a function that takes no input and returns the score of this post as a string. It requires the `Requests` package to be installed. How it works: * `get` makes a GET request to the SE API * `readall` reads the raw bytes in the response and returns a string * `split` splits the string at colons and commas * The 20th element of the resulting array is the score of the post Saved 21 bytes thanks to Dennis! [Answer] # JavaScript (Node.js), 166 Bytes -1 byte because @CᴏɴᴏʀO'Bʀɪᴇɴ taught me how to count ;) -4 bytes thanks to @NoOneIsHere ``` require("http").get("http://api.stackexchange.com/posts/82620?site=codegolf",a=>a.on("data",d=>console.log(JSON.parse(require("zlib").gunzipSync(d)).items[0].score))) ``` This is somewhat embarrassing. Dang you SE for gzipping your API! /s Any improvements are very welcome. [Answer] # PHP, 137 bytes Pretty straight forward. The uncompressing takes a lot of bytes: ``` <?=json_decode(gzinflate(substr(file_get_contents('http://api.stackexchange.com/2.2/posts/82619?site=codegolf'),10)),1)[items][0][score]; ``` --- **Ungolfed** ``` print json_decode( gzinflate( substr( file_get_contents('http://api.stackexchange.com/2.2/posts/82619?site=codegolf'), 10 ) ), 1 ) [items][0][score]; ``` [Answer] # PHP, 121 bytes Without api. ``` <?php preg_match('/t ">(.*)/',file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),$v);echo$v[1]; ``` Gets the whole post and extracts the vote counts with regex. (don't parse HTML with regex!) Ungolfed: ``` <?php preg_match('/t ">(.*)/', file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'), $v); echo $v[1]; ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •2íЕ’¸¸.‚‹º.ŒŒ/„¤/ÿ?€¼=ƒËŠˆ’žYì.w'ŒÂ¡θ',¡нþ ``` No TIO for the entire program, because the `.w` builtin to access the internet doesn't work on TIO. **Explanation:** We start by creating the url, and accessing it: ``` •2íЕ # Push compressed integer 190437 (the id of this answer) ’¸¸.‚‹º.ŒŒ/„¤/ÿ?€¼=ƒËŠˆ’ # Push dictionary string "api.stackexchange.com/posts/ÿ?site=codegolf", # where the `ÿ` is automatically filled with the 190437 žY # Push builtin "https://" ì # And prepend it in front of the string .w # Go to this website, and get all its contents ``` [Try it online (without the `.w`).](https://tio.run/##AUwAs/9vc2FiaWX//@KAojLDrcOQ4oCi4oCZwrjCuC7DguKAmuKAucK6LsWSxZIv4oCewqQvw78/4oKswrw9xpLDi8Wgy4bigJnFvlnDrP//) After that, we extract the score from the JSON: ``` 'ŒÂ '# Push dictionary string "score" ¡ # Split the website content on this θ # Only leave the last item (of the two) ',¡ '# Split this string on "," н # And this time leave the first item (i.e. `":10`) þ # Only leave the digits of this string # (which is output implicitly as result) ``` [Try it online.](https://tio.run/##lVC7TsNAEPwVtAU0Jn6FQCxFFJQICYkSIWs5r51N7Dtzd06IojR8An/AX9BAQUSL@KNwNgmioKGc3ZnZ2VEGb5k2m4P3x/XD29PH84H39vT5sn7dbJbAlioDyfUS1FyShmQJmurGomUlITkKgpPAg8aQTjlzOIrCHbaLmiBx9IKNJU0ZeIBCUG1TjdathgMPaq1yLinlCouWPba2Nonvc89YFNMeV0Wje0JV/gXlV5e9SV2cmlEYnewXo9AZZmzqEhepxKqVn9OM5d6ZbnhiDElHKFlOf/kKlVGhyvzbnu7FGGVB3YE2tPG7D/xp63MofnxWHhihtDvhvivR2BSF5RnbRZp1v4RHg0EcRnHY90Bo6ur5Y1UrJ90Wg9LMXaPbYdteOAz68fF/MqP/rYHVjQdjNGnVhcyxNOTBXaMsphXeQxIHwQ5rqpAlywKSaNhffQE) An equal 10-[bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative for this second part could be: ``` „ŒÂ‚¡ # Push dictionary string "score after" # # Split it on spaces: ["score","after"] ¡ # Split the website content on these Ås # Only leave the middle element þ # Only leave the digits of this string # (which is output implicitly as result) ``` [Try it online.](https://tio.run/##lVDLSgNBEPwVacHTmn0kRrMgHjyKIHgUWdrZzqbN7sw6PauGEBDBH/DoQfBHPCT4I/5InF0fePDisbqrqqvLCF4wrdfvd89vj6v797un5cvm8mX1IKvX9XoO7KgSSM/mYG40WUjnYKluHDo2GtKdKNqLAmiEbMa5x0kSf2M3qwlSTy9YHFnKIQBUimqXWXR@NRoGUFsz5pIyrrBo2RPnaknDkHviUE17XBWN7SlThcc0Pj3pXdbFgezHyd5WsR97w5ylLnGWaaxa@RFds944tA1fipD2hJL19JevMjkVphx/2tOtmqAuqDvQhpaw@yCctj7b6sdnEYAoY/0J/12J4jJUjq/ZzbK8@yXeGQ77cdKPBwEoS109f6xq46VfxaCWG9/o17BtLx5Fg/7ufzJj@KmBxXkAE5Ss6kKOsRQK4KoxDrMKbyHtR9E3tlQha9YFpMlosPgA) [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•2íЕ` is `190437`, `’¸¸.‚‹º.ŒŒ/„¤/ÿ?€¼=ƒËŠˆ’` is `"api.stackexchange.com/posts/ÿ?site=codegolf"`, `'ŒÂ` is `"score"`, and `„ŒÂ‚¡` is `"score after"`. PS/EDIT: I realize that by using the `þ` I assume I will never get a negative score. ;) [Answer] # Google Sheets, 87 bytes ``` =Mid(Index(ImportData("http://api.stackexchange.com/posts/203609?site=codegolf"),7),7,9 ``` Sheets will add the trailing parentheses automatically. `ImportData` will treat the result as a CSV and split the text into columns. `Index(~,10)` pulls the 10th entry from that split result. `Mid(~,12,99)` starts at the 7th character and pulls up to the next 9. So long as the score doesn't get to 10^9, this will work fine. Here's a screenshot showing the three steps: [![Screenshot](https://i.stack.imgur.com/1flG4.png)](https://i.stack.imgur.com/1flG4.png) ]
[Question] [ This challenge was [inspired by a question on Mathematica.SE](https://mathematica.stackexchange.com/q/30405/2305). Say you've got a nested list/array of some arbitrary structure (the lists at each level don't necessarily have the same length). For simplicity, we'll assume that the nodes are non-negative integers or empty arrays. As an example ``` [[[1, 3], 2], [1, 4], 12, [[0, [], 0], [5, [7]]]] ``` Sometimes it's more convenient to flatten that list to perform some manipulation of the nodes, e.g. ``` --> [1, 3, 2, 1, 4, 12, 0, 0, 5, 7] --> [1, 1, 0, 1, 0, 0, 0, 0, 1, 1] ``` But in the end you actually want to preserve the original structure, so you want to turn this back into ``` --> [[[1, 1], 0], [1, 0], 0, [[0, [], 0], [1, [1]]] ``` Your task is to perform that last step. Given a nested list of arbitrary non-negative integers, which represents the desired structure of the result, and a flat list of non-negative integers, which represent the desired values, reshape the flat list into the form of the structured list. You may assume that both lists contain the same number of integers. As usual you don't have to deal with invalid input (e.g. the second list not being flat, the input being syntactically malformed, not having integers as nodes, etc.). You may modify the input arrays in your code. You may write a function or program, taking input via STDIN, command-line argument or function argument, and you may return the result or print it to STDOUT. You may use any convenient list or string format to represent input and output (as long as the format is unambiguous and the input is not preprocessed). Also, the format of both inputs needs to be consistent (so you can't take one input as a string and the other as a list, for instance). You may take the input lists in either order, but please specify the exact input method in your answer. One more restriction: you must not use regular expressions. This is an array manipulation challenge, not a string manipulation challenge. This is code golf, so the shortest answer (in bytes) wins. ## Test Cases ``` Structure Values Result [[[1,3],2],[1,4],12,[[0,0],[5,[7]]]] [1,1,0,1,0,0,0,0,1,1] [[[1,1],0],[1,0],0,[[0,0],[1,[1]]]] [[[0,0],0],[0,0],0,[[0,0],[0,[0]]]] [1,1,0,1,0,0,0,0,1,1] [[[1,1],0],[1,0],0,[[0,0],[1,[1]]]] [] [] [] [[]] [] [[]] [0,1,2,3] [5,1,0,5] [5,1,0,5] [[[[[0]]]]] [123] [[[[[123]]]]] [0,[1,[]],[[]],[2,3],[]] [1,6,1,8] [1,[6,[]],[[]],[1,8],[]] ``` [Answer] # JavaScript, ES6, 44 bytes ``` f=(a,b,i=0)=>a.map(x=>x.map?f(x,b,i):b[i++]) ``` This creates a function `f` which can be called like ``` f([0,[1,[]],[[]],[2,3],[]],[1,6,1,8]) ``` i.e. the nested array and the values array as input arguments. The output of the function is the converted nested array. This question is a very nice question for recursion, that is why the answer is a neat and sweet recursion function. I create a function `f` which converts the first argument using the `map` method. For each element, if the element is an array, it calls `f` again, otherwise, for integers, it gets the ith item and returns that, incrementing the value of `i`. The value of `i` is passed down in each recursive call, so as to maintain the order correct. Array vs. Integer detection is yet again done using the `map` method. For an array variable, `map` is a valid function, while for integer variables, there is no property or function called `map` defined for the variable. This works in a latest Firefox browser (due to ES6). [Answer] # JavaScript, ES6, 41 bytes I was really impressed by [Optimizer's answer](https://codegolf.stackexchange.com/a/43020/30569), it was very cleverly done and I learned a lot. However on looking it over I found a way of shortening it slightly and fixing a small bug: ``` f=(a,b)=>a.map(x=>x.map?f(x,b):b.shift()) ``` I took out the `i` variable and replaced it with a `shift()`. This makes it slightly shorter and fixes the problem with the fact that `i` is passed by value and not by reference, witch caused some numbers from the final array to repeat and some at the end not to be used. Again, Optimizer's answer was really well thought out, better than I could have done, I just fixed it a little. [Answer] # Dyalog APL, 14 characters This is a no-brainer: `(∊a)←b`. Normally, `∊a` means `a` flattened, but when it occurs on the left-hand side of an assignment, it does precisely what this problem is asking for. To comply with the requirement of being a function, it needs a few extra squiggles: `{a←⍺⋄(∊a)←⍵⋄a}` (curly braces for lambda; `⍺` and `⍵` for left and right argument; `⋄` for statement separator). [Test](http://tryapl.org/?a=%5Ddisplay%20%28%281%203%29%202%29%281%204%2912%28%280%u236C0%29%285%28%2C7%29%29%29%20%7Ba%u2190%u237A%u22C4%28%u220Aa%29%u2190%u2375%u22C4%u237A%7D%201%201%200%201%200%200%200%200%201%201&run) on tryapl.org. Note that in APL the empty numeric vector is denoted by `⍬` ("zilde"). One-element vectors are constructed with `(,A)` because `(A)` would mean a scalar. In the output, this thing: ``` ┌⊖┐ │0│ └~┘ ``` represents an empty numeric vector. The `0` in the centre shows the "prototypical element" which is not an element of the array. [Answer] # Python 2, 50 ``` f=lambda s,v:v.pop(0)if s<[]else[f(x,v)for x in s] ``` This was a very beautiful problem. As I kept working on it, I kept realizing that bits of my code were unnecessary, and the logic collapsed into a simple expression. Most of the golfing was in finding the right algorithm. `s` is the structure and `v` is the flat list of list. The idea is to check whether `s` is an integer with `s<[]` (Python 2 treats numbers as smaller than lists). If it is, simply take and return the first element of `v`, removing it from `v`. Otherwise, recurse down onto the sublists of `s`. The `pop` is a piece of imperative magic in very functional-style code. Because all `v` point to the same instance, popping an element from one removes it from `v` in the whole execution tree, so each number in `v` is only used once. The list comprehension `[f(x,v)for x in s]` creates a call tree that is expanded depth-first and left-to-right, causing the elements of `v` to be slotted in the correct order. I wrote this independently of [grc's answer](https://codegolf.stackexchange.com/a/43023/20260), but it turned out to the same up to moving a single `[` (and variable names). The move saves a char due to spacing. The bracket move means handling the node case immediately in the function, rather than as part of the list comprehension, which I hadn't considered. We can save a char for *49* if we stretch the input requirements to take the value from STDIN and the structure as a function argument. This lets us use `map`. ``` v=input() g=lambda s:v.pop(0)if s<[]else map(g,s) ``` [Answer] # Ruby, 39 ``` f=->a,b{a.map{|d|f[d,b]}rescue b.shift} ``` Recurses till the element in the list is an integer. Since calling Integer.map gives an exception, it goes to the rescue portion, which "pops/shift" the 1st element out of the 2nd list. Regex soln... a bit longer: ``` f=->a,b{eval a.to_s.split(/\d+/).zip(b)*''} ``` [Try it with some test cases](http://ideone.com/w3ALgk) [Answer] ## Python, 51 ``` f=lambda a,b:[b.pop(0)if x<[]else f(x,b)for x in a] ``` Example: ``` >>> f([0,[1,[]],[[]],[2,3],[]], [1,6,1,8]) [1, [6, []], [[]], [1, 8], []] ``` [Answer] # CJam, ~~18 16~~ 13 bytes ``` lA,sNerN%l~]z ``` Takes input via STDIN in the same format as the previous CJam answer: ``` [0 [11 []] [[]] [2 3] []] [1 6 1 8] ``` and outputs the result string to STDOUT ``` [1 [6 []] [[]] [1 8] []] ``` I simply treat the first line as string, convert all digit characters to newlines, split on one or more occurrences of newlines, put the second line as an array on stack, wrap in an array and zip together the two arrays (rows). Printing is automatic and as the first row was treated as string, it retains its brackets. **Code expansion** ``` lA,sNerN%l~]z l "Read the first line of input. This is the nested array"; A,s "Get array [0,1,2...9] and convert it to string '012..9'"; Ner "Replace all occurrences of 0,1,2,..9 with new line"; N% "Split on one or more occurrences of new line"; l~ "Read the second line as an array"; ] "Wrap both the splitted string and the second line array"; "in an array"; z "Transpose the array, there by placing the numbers from second"; "input array in the split holes of first input string"; ``` *Thanks to @user23013 for saving 3 bytes.* [Try it online here](http://cjam.aditsu.net/) [Answer] # Mathematica, 41 bytes ``` Function[,m[[i++]],Listable][i=1;m=#2;#]& ``` This is an unnamed function which takes the structure as the first argument and the list of values as the second argument (and returns a list). This is a golfed version of [the accepted answer](https://mathematica.stackexchange.com/a/30412/2305) on the question that inspired this challenge. I'm posting this myself, and will not accept this answer (should it actually remain the shortest, which I doubt). This is in order to prevent any one else from winning the challenge by basically copying the answer. How it works: * We define a `Listable` pure function. Listable functions are automatically applied to the elements of a list argument (recursively) instead of the list itself, so calling `f` on the structured list will basically return a list of the same structure with each integer `i` replaced by `f[i]`. * We store the value list in the global `m` and a counter in `i`. * Each time we call `f` (regardless of the argument) we return the next element of `m`. [Answer] # CJam, ~~43 37 35~~ 33 bytes This one is a direct conversion of my [JS answer](https://codegolf.stackexchange.com/a/43020/31414). A bit long, most of which is taken up by type detection. ``` q~:B;{{_`La`&{F}{;BW):W=}?}%}:F~` ``` Takes the two input arrays on two lines of STDIN like ``` [[[1 3] 2] [1 4] 12 [] [[0 0] [5 [7]]]] [1 1 0 1 0 0 0 0 1 1] ``` and outputs to STDOUT like ``` [[[1 1] 0] [1 0] 0 "" [[0 0] [1 [1]]]] ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # Haskell, ~~113~~ 104 bytes (86 + 18 from datatype declaration) ``` data N=I Int|L[N] L[]!v=(L[],v) L(a:b)!v|(c,w)<-a!v,(L d,u)<-L b!w=(L$c:d,u) _!(n:m)=(I n,m) s#v=fst$s!v ``` Haskell does not have a built-in nested array datatype, so I had to roll my own. For this reason, the program contains only pattern matching and explicit structural recursion. The last test case reads ``` L[I 0,L[I 1,L[]],L[L[]],L[I 2,I 3],L[]]#[1,6,1,8] ``` and evaluates to ``` L[I 1,L[I 6,L[]],L[L[]],L[I 1,I 8],L[]] ``` [Answer] # Rebol - 87 66 60 ``` f: func[a[block!]b][map-each n a[any[attempt[f n b]take b]]] ``` Ungolfed: ``` f: func [a [block!] b] [ map-each n a [ any [ attempt [f n b] take b ] ] ] ``` Example: ``` >> f [0 [1 []] [[]] [2 3] []] [1 6 1 8] == [1 [6 []] [[]] [1 8] []] ``` [Answer] # C#, ~~225 + 13 = 239~~ ~~185 + 35 = 220~~ 172 + 35 = 207 bytes Requires this: ``` using System;using o=System.Object; ``` Accepts `object[]`s as arguments. ``` o[]u(o[]a,o[]b){var c=a;int i=0;Action<o[],o[]>d=null;d=(e, f)=>{for(int j=0;j<e.Length;j++){if(e[j]is int){f[j]=b[i];i++;}else{d((o[])e[j],(o[])f[j]);}}};d(a,c);return c;} ``` Ungolfed code: ``` object[] Unflatten(object[] structure, object[] values) { var c = structure; int i = 0; Action<object[], object[]> recursiveFunc = null; recursiveFunc = (e, f) => { for (int j = 0; j < e.Length; j++) { if (e[j] is int) { f[j] = values[i]; i++; } else { recursiveFunc((object[])e[j], (object[])f[j]); } } }; recursiveFunc(structure, c); return c; } ``` [Answer] # Python 2, 64 bytes ``` def g(N,L):f=lambda N:L.pop(0)if`N`<":"else map(f,N);return f(N) ``` I heard you like lists in lists so I put functions in functions. *Edit: Looking at [grc's answer](https://codegolf.stackexchange.com/a/43023/21487) now I realise that was completely unnecessary. Oh well...* [Answer] ## SWI-Prolog 82 ``` f([],A,[],A):-!. f([H|T],A,[J|U],B):-(is_list(H),!,f(H,A,J,C);A=[J|C]),f(T,C,U,B). ``` Sample run: ``` ?- f([[[1,3],2],[1,4],12,[[0,[],0],[5,[7]]]],[1,1,0,1,0,0,0,0,1,1],R,[]). R = [[[1,1],0],[1,0],0,[[0,[],0],[1,[1]]]]. ``` The last `[]` in the query is for checking for mismatched number of elements, which doesn't seem to be necessary in this question. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsb/h5crHZ30cOeMR01rIv//jzbUMdQxAGMIBPJjdRRwCcOwKVjKFKzSyBiiwQwoZhH7PzoayAYKGcXqABkmsTqGRjrR0UAzgHxTnWjzWCAAqocKgUQhDLgiIMsAqgisEMwCucBIxxiiMxqiACIOtASkBKwuGqwEyAIA "Jelly – Try It Online") Jelly's `mold` builtin does this exactly. Takes input in reversed order (i.e. the flat list first) --- # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ßḢ}ŒḊ?€ ``` [Try it online!](https://tio.run/##y0rNyan8///w/Ic7FtUenfRwR5f9o6Y1/w8vVwJyds4AsiP//4@OjjbUMY7VMYrVATJMYnUMjXSiow10DIB8U51o81gg0FGIhgqBRCEMuCIgywCqCKwQzDLQMdQxAhkL0hkNUQARB1oCUgJWFw1WAmT9B4oa6hiAMQQC@SD1OIRh2BQsZQpWaWQM0WAGFLOIBQA "Jelly – Try It Online") Non-builtin is still pretty short. Takes input in normal order (flat list second) ## How it works ``` ßḢ}ŒḊ?€ - Main link. Takes l on the left and r on the right € - Over each element k in l: ? - If statement: ŒḊ - Condition: Depth. This yields 0 for integers and non-zero for lists ß - Then: Recurse with k on the left and r on the right Ḣ} - Else: Pop and return the first element of r ``` [Answer] # Erlang, ~~116~~ 93 Bytes ``` f(R,F)->put(n,F),[g(X)||X<-R]. g([H|T])->[g(H)|g(T)];g([])->[];g(E)->[H|T]=get(n),put(n,T),H. ``` Uses two impure functions `f` and `g`. `f` manipulates the process dictionary by setting `n` to the flat list and maps each element of the nested list to `g(X)`. `g` then sets `n` to the tail of the flat list every time it encounters a non-list value and returns the head of the flat list. [Answer] # Perl 5, 49 bytes First argument is the template structure, second is the values. ``` sub u{($t,$l)=@_;ref$t?[map{u$_,$l}@$t]:shift@$l} ``` ## Test Program ``` use Test::More; use Test::Deep; sub u{($t,$l)=@_;ref$t?[map{u$_,$l}@$t]:shift@$l} cmp_deeply u([[[1,3],2],[1,4],12,[[0,0],[5,[7]]]],[1,1,0,1,0,0,0,0,1,1]),[[[1,1],0],[1,0],0,[[0,0],[1,[1]]]]; cmp_deeply u([[[0,0],0],[0,0],0,[[0,0],[0,[0]]]],[1,1,0,1,0,0,0,0,1,1]),[[[1,1],0],[1,0],0,[[0,0],[1,[1]]]]; cmp_deeply u([], []), []; cmp_deeply u([[]], []), [[]]; cmp_deeply u([0,1,2,3], [5,1,0,5]), [5,1,0,5]; cmp_deeply u([[[[[0]]]]], [123]), [[[[[123]]]]]; cmp_deeply u([0,[1,[]],[[]],[2,3],[]], [1,6,1,8]), [1,[6,[]],[[]],[1,8],[]]; done_testing; ``` [Answer] # Powershell: 115 the input array is $i, the mapping is $m, output is $o ``` $h={if($_.GetType().IsArray){if($_.c -eq 0){,@()}else{,@($_|%{.$h})}}else{$m[$c++]}};$i|%{$o=@();$c=0}{$o+=,(.$h)} ``` $h is a string containing the recursive function, and you can execute code contained in a string with .$h... And it would be 30 bytes shorter if powershell didn't insist on flattening single value arrays to scalars, and an array with a single null value to null and a handy array structure viewer for verifying results ``` $j={if($_.GetType().IsArray){write-host '(' -n;($_|%{.$j});write-host ')' -n}else{write-host "$_" -n}};write-host '(' -n;$o|%{(.$j)}; write-host ')' -n; ``` ## edit: 149 save as unflatten.ps1: ``` $m=[array]$args[1];$h={if($_.GetType().IsArray){if($_.c -eq 0){,@()}else{,@($_|%{.$h})}}else{$m[$c++]}};$args[0]|%{$o=@();$c=0}{$o+=,(.$h)};echo $o; ``` ### edit: 136, inline output array creation and write-output ``` $m=[array]$args[1];$h={if($_.GetType().IsArray){if($_.c -eq 0){,@()}else{,@($_|%{.$h})}}else{$m[$c++]}};echo(,@($args[0]|%{$c=0}{.$h})) ``` call with .\unflatten.ps1 [input array] [mapping array] the output is written to the pipeline- so run this first: ``` Function View-Array{ Param([Parameter(ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] [array]$o) PROCESS{ $j={if($_.GetType().IsArray){write-host '(' -n;($_|%{.$j});write-host ')' -n}else{write-host "$_" -n}}; write-host '(' -n;$o|%{(.$j)}; write-host ')' -n; } } ``` and run with ``` .\unflatten.ps1 [input array] [mapping array] | View-Array ``` [Answer] ## C#, (40+123)=163 bytes OR (67+81)=148 bytes C# suffers from its static typing and long namespaces here. **Array method** Using statements: ``` using o=System.Object;using System.Linq; ``` Code: ``` o[] u(o[] x,o[] y){int i=0;Func<o[],o[],o[]> f=null;f=(a,b)=>a.Select(e=>e is int?b[i++]:f((o[])e,b)).ToArray();return f(x,y);} ``` **Stack method** (uses the Stack structure instead of arrays) Using statements: ``` using s=System.Collections.Generic.Stack<object>;using System.Linq; ``` Code: ``` System.Func<s,s,s>f=null;f=(a,b)=>new s(a.Select(e=>e is int?b.Pop():f((s)e,b))); ``` First attempts, first code golf here. [Answer] # [R](https://www.r-project.org/), 6 bytes ``` relist ``` [Try it online!](https://tio.run/##K/qfpmCj@78oNSezuOR/cUmRRppGsoahjqGOARhDIJCvqQNSoYEgDHWMNXWMoMKGOiaaOoZGSGoMIGxNHQOoElMIZa4JBlxpGpl5JanpqUUaBshGA6X@AwA "R – Try It Online") `relist` performs the exact operation described here; and has been included since R 2.6.0 (released Oct. 3, 2007). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` • ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigKIiLCIiLCIiXQ==) Same as Jelly [Answer] # [Appleseed](https://github.com/dloscutoff/appleseed), 136 bytes ``` (def M(q((S D)(if S(if(type?(head S)Int)(cons(head D)(M(tail S)(tail D)))(cons(M(head S)D)(M(tail S)(drop(length(flatten(head S)))D))))( ``` Defines a recursive function that takes two lists. [Try it online!](https://tio.run/##VY6xcoMwDIb3PIWy/dogaS9jliwdmHiAnFqLwp3rGKwlT08EhKHSybZ@f79syTlqUQ3zjKAdNRiBlm6MoaPWF9gz6xW9SqCWv5Ixfh6pbIJjDUyG6FfbfmN@A83u@QeF6ZERNf1ajy6KmaadY17MjO0jpZeshJEA1HRmOjH54YOpPrlWUeX9J@HCaxxWUxATQhyKUe1ZrbWl9ztVTCY7Oid/30HoTsjTkBaleT@7zFmmzi8 "Appleseed – Try It Online") ### Ungolfed/commented ``` ; Define mold (def mold ; as a function of two arguments, the nested list representing the structure ; and the flat list containing the data (lambda (shape data) ; If the shape list is nonempty: (if shape ; If its first element is an int: (if (type? (head shape) Int) ; Construct the result list from (cons ; the first element of the data list (head data) ; followed by a recursive call with all but the first element of both lists (mold (tail shape) (tail data))) ; Else, its first element is a list: ; Construct the result list from (cons ; a recursive call with the first element of the shape list (mold (head shape) data) ; followed by a recursive call with (mold ; all but the first element of the shape list (tail shape) ; and all but the first N elements of the data list, where N is the number ; of data elements used in unflattening the head of the shape list (drop (length (flatten (head shape))) data)))) ; Else, the shape list is empty: ; Return the empty list nil))) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ˶Ô?ßDÔ:Vv ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y7bUP99E1DpWdg&input=W1tbMSwzXSwyXSxbMSw0XSwxMixbWzAsMF0sWzUsWzddXV1dIApbMSwxLDAsMSwwLDAsMCwwLDEsMV0KLVE) ]
[Question] [ A positive integer \$k\$ is a **Loeschian number** if * \$k\$ can be expressed as \$i^2 + j^2 + i\times j\$ for \$i\$, \$j\$ integers. For example, the first positive Loeschian numbers are: \$1\$ (\$i=1, j=0\$); \$3\$ (\$i=j=1\$); \$4\$ (\$i=2, j=0\$); \$7\$ (\$i=2, j=1\$); \$9\$ (\$i=-3, j=3\$); ... Note that \$i, j\$ for a given \$k\$ are not unique. For example, \$9\$ can also be generated with \$i=3, j=0\$. Other equivalent characterizations of these numbers are: * \$k\$ can be expressed as \$i^2 + j^2 + i\times j\$ for \$i, j\$ non-negative integers. (For each pair of integers \$i, j\$ there's a pair of non-negative integers that gives the same \$k\$) * There is a set of \$k\$ contiguous hexagons that forms a tesselation on a hexagonal grid so that corresponding cells are the same distance apart (see illustrations for [\$k = 4\$](https://i.stack.imgur.com/keJqMl.png) and for [\$k = 7\$](https://i.stack.imgur.com/Dj0lKl.png)). (Because of this property, these numbers find application in [mobile cellular communication networks](http://www.wirelesscommunication.nl/reference/chaptr04/cellplan/reuse.htm).) * See more characterizations in the [OEIS page](https://oeis.org/A003136) of the sequence. ## The challenge Given a **positive integer**, output a truthy result **if it is a Loeschian number**, or a falsy result otherwise. The program or function should handle (say in less than a minute) inputs up to \$1000\$, or up to data type limitations. Code golf. Shortest wins. ## Test cases The following numbers should output a truthy result: ``` 1, 4, 7, 12, 13, 108, 109, 192, 516, 999 ``` The following numbers should output a falsy result: ``` 2, 5, 10, 42, 101, 102, 128, 150, 501, 1000 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆF‘%3,2ḄȦ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZG4oCYJTMsMuG4hMim&input=&args=OTk5) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZG4oCYJTMsMuG4hMimCsOH4oKs4oKsRw&input=&args=WzEsIDQsIDcsIDEyLCAxMywgMTA4LCAxMDksIDE5MiwgNTE2LCA5OTldLCBbMiwgNSwgMTAsIDQyLCAxMDEsIDEwMiwgMTI4LCAxNTAsIDUwMSwgMTAwMF0). ### Background In [Elementary results on the binary quadratic form *a² + ab + b²*](https://arxiv.org/abs/math/0408107), the author proves the following theorem about Löschian numbers. > > **Theorem 16.** *The necessary and sufficient condition of any non-negative integer to be in the form* a² + ab + b² *is that, in its prime factorization, all primes other than* 3 *that are not in the form* (6k + 1) *have even exponents.* > > > As noted on the relevant [OEIS page](https://oeis.org/A003136), since all integers are are congruent to **0**, **1** or **2** modulo **3**, the number **3** is the only prime that is congruent to **0**, and all numbers of the form **(6k + 1)** are congruent to **1**, the theorem can be stated alternatively as follows. *A non-negative integer* n *is a Löschian number if and only if all prime factors of* n *that are congruent to* 2 *modulo* 3 *have even exponents.* ### How it works ``` ÆF‘%3,2ḄȦ Main link. Argument: n (integer) ÆF Yield the prime factorization of n, as prime-exponent pairs. ‘ Increment all primes and exponents, turning primes of the form 3k - 2 into multiples of 3 and odd exponents into multiples of 2. %3,2 Reduce all incremented primes/exponents modulo 3/2. n is Löschian if and only if this does not result in a [0, 0] pair. Due to Jelly's form of vectorization, this yields [3, 2] if n = 1. Ḅ Unbinary; convert each pair from base 2 to integer. Note that [x, y] = [0, 0] if and only if 2x + y = 0. Ȧ All; return 1 if the result contains no zeroes, 0 otherwise. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~66~~ ~~63~~ ~~45~~ ~~43~~ 36 bytes ``` ^()(\1(?<1>.\1))+(\1(.(?(4).\4)))*$ ``` Despite the title saying Retina, this is just a plain .NET regex which accepts [unary representations](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) of Loeschian numbers. Inputs 999 and 1000 take well under a second. [Try it online!](http://retina.tryitonline.net/#code=JShHYAouKwokKgpeKCkoXDEoPzwxPi5cMSkpKyhcMSguKD8oNCkuXDQpKSkqJA&input=MQoyCjMKNAo1CjYKNwo4CjkKMTAKMTEKMTIKMTMKMTQKMTUKMTYKMTc) (The first line enables a linefeed-separated test suite, and the next two take care of the conversion to unary for convenience.) ### Explanation The solution is based on the classification that the input can be written as `i*i + j*(i + j)` for positive `i` and non-negative `j` (since we don't have to handle input `0`), and that `n*n` is just the sum of the first `n` odd integers. Golfing this was an interesting exercise in forward references. A "forward reference" is when you put a backreference inside the group it refers to. Of course that doesn't work when the group is used the first time, since there is nothing to be backreferenced yet, but if you put this in a loop, then the backreference gets the previous iteration's capture each time. This in turn, let's you build up a larger capture with each iteration. This can be used to craft very compact patterns for things like triangular numbers, squares and Fibonacci numbers. As an example, using the fact that squares are just sums of the first `n` odd integers, we can match a square input like this: ``` (^.|..\1)+$ ``` On the first iteration, `..\1` can't work, because `\1` doesn't have a value yet. So we start with `^.`, capturing a single character into group `1`. On subsequent iterations, `^.` no longer matches due to the anchor, but now `..\1` is valid. It matches two more characters than the previous iteration and updates the capture. This way we match increasing odd numbers, getting a square after each iteration. Now unfortunately, we can't use this technique as is. After matching `i*i`, we need to get `i` as well, so that we can multiply it by `j`. A simple (but long) way to do this is to make use of the fact that matching `i*i` takes `i` iterations, so that we've captured `i` things in group `1`. We could now use [balancing groups](https://stackoverflow.com/a/17004406/1633117) to extract this `i`, but like I said that's expensive. Instead, I figured out a different way to write this "sum of consecutive odd integers" that also yields `i` in a capturing group at the end. Of course the `i`th odd number is just `2i-1`. This gives us a way to increment the forward reference only by 1 on each iteration. That's this part: ``` ^()(\1(?<1>.\1))+ ``` This `()` just pushes an empty capture onto group `1` (initialising `i` to `0`). This is pretty much equivalent to the `^.|` in the simple solution above, but using `|` in this case would be a bit trickier. Then we have the main loop `(\1(?<1>.\1))`. `\1` matches the previous `i`, `(?<1>.\1)` then updates group `1` with `i+1`. In terms of the *new* `i`, we've just matched `2i-1` characters. Exactly what we need. When we're done, we've matched some square `i*i` and group `1` still holds `i` characters. The second part is closer to the simple square matching I showed above. Let's ignore the backreference to `1` for now: ``` (.(?(4).\1))* ``` This is basically the same as `(^.|..\4)*`, except that we can't make use of `^` because we're not at the start of the string. Instead we make use of a conditional, to match the additional `.\1` only when we've already used group `4`. But in effect this is exactly the same. This gives us `j*j`. The only thing that's missing is the `j*i` term. We combine this with the `j*j` by making use of the fact that the `j*j` computation still takes `j` iterations. So for each iteration we also advance the cursor by `i` with `\1`. We just need to make sure not to write that into group `4`, because that would mess with matching consecutive odd numbers. That's how we arrive at the: ``` (\1(.(?(4).\1)))* ``` [Answer] ## CJam (16 15 bytes) ``` {mF{~\3%2=&},!} ``` [Online demo](http://cjam.aditsu.net/#code=%5B1%204%207%20%2012%2013%20%20108%20109%20192%20516%20999%0A%202%205%2010%2042%20101%20102%20128%20150%20501%201000%5D%0A%0A%7BmF%7B~%5C3%252%3D%26%7D%2C!%7D%0A%0A%25%60) This is a block (an "anonymous function") which takes input on the stack and leaves `0` or `1` on the stack. It uses the characterisation that a number is Loeschian iff it has no prime factor equal to 2 mod 3 with odd multiplicity. Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for a one-byte saving. [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` lambda n:0in[(n-3*i*i+0j)**.5%1for i in range(n)] ``` [Try it online!](https://tio.run/##RcmxDkAwFAXQ3Ve8RaIVUqRLE1@CoUJ5wiVNF19fTNZzrjusJ@ro2j7u9hgnSzCK0WUoGsmSc7UJKUudVu70xMQgb7HMGcQQP8JPWgmTEDty7xq6PCMQ4gM "Python 2 – Try It Online") Uses the equivalent quadratic form given on OEIS of `n == 3*i*i+j*j`. Check whether `n-3*i*i` is a perfect square for any `i` by taking its square root and checking if it's an integer, i.e. equals 0 modulo 1. Note that Python computes square roots of perfect squares exactly, without floating point error. The `+0j` makes it a complex number to avoid an error on the square root of a negative. [Answer] # Python 2, 56 bytes ``` lambda n:any(n==i*i%n+i/n*(i/n+i%n)for i in range(2*n*n)) ``` [Answer] ## Haskell, 42 bytes ``` f k=or[k==i*i+j*j+i*j|i<-[0..k],j<-[0..i]] ``` Usage example: `f 501` -> `False`. Tries all combinations of `i` from `0` to `k` and `j` from `0` to `i` . `or` returns `True` if the equality `k==i*i+j*j+i*j` holds for at least one of the combinations. @flawr found a slightly different version with the same byte count: ``` f k|v<-[0..k]=or[(i+j)^2==k+i*j|i<-v,j<-v] ``` [Answer] ## Java 8, 81 bytes ``` k->{for(int i=0,j;i<=k;i++)for(j=0;j<=k;)if(i*i+j*j+i*j++==k)return 1;return 0;}; ``` simple, naïve implementation. coincidentally same code as C# but uses `->` rather than `=>`. [Answer] # [Jellyfish](https://github.com/iatorm/jellyfish), ~~56~~ ~~43~~ ~~41~~ ~~29~~ 28 bytes **2 bytes thanks to Zgarb** ``` p n < +`/ `1* / + &*r&;>i ``` [Try it online!](http://jellyfish.tryitonline.net/#code=cApuICAgIDwKK2AvCmAxKgovCisKJipyJjs-aQ&input=MTM) A fork of [my Jelly answer](https://codegolf.stackexchange.com/a/88733/48934). [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes ``` t:0hU&+HM&*+m ``` [Try it online!](http://matl.tryitonline.net/#code=dDowaFUmK0hNJiorbQ&input=OTk5) Or [verify all test cases](http://matl.tryitonline.net/#code=IkAKdDowaFUmK0hNJiorbQpddiE&input=WzEsIDQsIDcsIDEyLCAxMywgMTA4LCAxMDksIDE5MiwgNTE2LCA5OTksIDIsIDUsIDEwLCA0MiwgMTAxLCAxMDIsIDEyOCwgMTUwLCA1MDEsIDEwMDBd). Outputs `1` or `0`. ### Explanation ``` t: % Implicitly input number k. Duplicate. Generate vector [1 2 ...k] 0h % Concatenate a 0. Gives [1 2 ... k 0] U % Square, element-wise. Gives [1 4 ... k^2 0] &+ % Sum of all pairs from this vector. Gives a (k+1)×(k+1) matrix HM % Push [1 2 ... k 0] again &* % Product of all pairs from this vector. Gives a (k+1)×(k+1) matrix + % Add the two matrices m % True if k is a member of the resulting matrix. Implicitly display ``` [Answer] ## Python, 67 bytes ``` lambda k,r=range:any(i*i+j*j+i*j==k for i in r(k+1)for j in r(k+1)) ``` <https://repl.it/Cj6x> [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ ~~14~~ ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) **1 byte thanks to miles.** ``` ²S+P ‘ṗ2’Ç€i ``` [Try it online!](http://jelly.tryitonline.net/#code=wrJTK1AK4oCY4bmXMuKAmcOH4oKsaQ&input=&args=MTI) [Verify the smaller testcases](http://jelly.tryitonline.net/#code=wrJTK1AK4oCY4bmXMuKAmcOH4oKsaQrDh-KCrOKCrA&input=&args=W1sxLCA0LCA3LCAxMiwgMTNdLFsyLCA1LCAxMCwgNDJdXQ). A word of advice when testing for large numbers (bigger than 50): don't. Truthy is a positive number. Falsey is zero. ### Explanation ``` ‘ṗ2’Ç€i main chain, argument: z ‘ṗ2’ generate all pairs of numbers between 0 and z inclusive Ç€ apply the helper link to each pair i find the index of z in the result ²S+P helper link, argument: [x,y] (a pair of numbers) ² compute [x*x, y*y] S x*x+y*y +P x*x+y*y+x*y ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ḋḅ{h%₃<2|~j}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7oc7WqszVB81NdsY1dRl1T7cOuH/f0tLSwA "Brachylog – Try It Online") ### Explanation Uses the prime factors approach. ``` ḋḅ{h%₃<2|~j}ᵐ ḋ Prime factorization: gives a list like [7, 3, 2, 2] ḅ Analyze into blocks of the same value: [[7], [3], [2, 2]] { }ᵐ This predicate must succeed for each block: h The head (first number in the list, i.e. the prime factor) %₃ mod 3 <2 is less than 2 | Or ~j the list can be considered the result of joining two identical sublists (i.e. its length is even, i.e. that prime factor has an even exponent) ``` [Answer] # C (gcc), 71 69 bytes ``` i,j,r;f(n){for(r=i=n+1;i--;)for(j=n;j--;)r*=n!=i*i+j*j+i*j;return!r;} ``` [Answer] ## VBA, ~~68~~ 67 bytes ``` Function L(N):For a=0To N:For b=0To a:L=L+(N=a^2+a*b+b^2):Next b,a ``` Naive search, starting to slow down slightly for n=1000. Excel recognizes zero return as falsy, all other returns as truthy. Note that investigation of negative *i* and *j* is not needed, since given *i>j>=0* : > > *(-i)2 + (-i)(-j) + (-j)2 = i2 + ij + j2* > > > (the same result as for *i* and *j*) > > *(-i)2 + (-i)j + j2 = i2 - ij + j2* > > > *i2 + i(-j) + (-j)2 = i2 - ij + j2* > > > (if one is negative, it doesn't matter which one), and then > > *(i-j)2 + (i-j)j + j2 = (i2 - 2ij + j2) + (ij - j2) + j2 = i2 - ij + j2* > > > And since both *(i-j)* and *j* are non-negative, any generation of Loeschian numbers involving a negative number can be achieved using non-negative numbers. --- *Saved a byte, `Next:Next` -> `Next b,a` thanks to Taylor Scott.* [Answer] ## C#, ~~84~~ ~~82~~ 81 bytes ``` k=>{for(int i=0,j;i<=k;++i)for(j=0;j<=k;)if(i*i+j*j+i*j++==k)return 1;return 0;}; ``` A naïve solution. 1 = true, 0 = false [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÝãDnOsP+Iå ``` [Try it online](https://tio.run/##yy9OTMpM/f//8NzDi13y/IsDtD0PL/3/39LSEgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3MPL3bJ8y8O0K48vPS/zv9oQx0THXMdQyMdQ2MdQwMLILbUMbQ00jE1NNOxtLTUUQAygYI6JkAVBoZADKSNgMpMDXRMwXwDg1gA). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input] ã # Create all possible pairs by taking the cartesian product on itself D # Duplicate this list of pairs n # Square each inner value in the pairs: [i²,j²] O # Sum each inner pair together: i²+j² s # Swap so the original list of pairs is at the top of the stack again P # Take the product of each inner pair: i*j + # Sum the values in the list at the same positions: i²+j²+i*j Iå # And check if the input-integer is in this list # (after which the result is output implicitly) ``` [Answer] # [Desmos](http://desmos.com/calculator), ~~62~~ 60 bytes ``` f(k)=\prod_{n=0}^k\prod_{m=0}^k\left\{mm+nn+mn=k:0,1\right\} ``` [![](https://i.stack.imgur.com/2IjGA.png)](https://i.stack.imgur.com/2IjGA.png) Outputs \$0\$ for truthy and \$1\$ for falsey [Try It On Desmos!](https://www.desmos.com/calculator/sl7klzxsih) Explanation: The products(\$\prod\$) iterate through \$0\$ through \$k\$ inclusive for both \$m\$ and \$n\$. It then tests if \$m^2+n^2+mn=k\$. If it does, then we know that \$k\$ is a Loeschian number, and we multiply by \$0\$. Else, we multiply by \$1\$. So if we don't encounter any pairs of \$m\$ and \$n\$ that satisfy \$m^2+n^2+mn=k\$, it will keep on multiplying \$1\$, and therefore it will stay at \$1\$ at the end. So the falsey value is \$1\$. But if a pair does satisfy \$m^2+n^2+mn=k\$, then it multiplies by \$0\$, and because \$0\$ times anything is \$0\$, and we are essentially just multiplying over and over again, it is guaranteed that once we multiply by \$0\$, it will stay at \$0\$. Hence, the truthy value is \$0\$. [Answer] # Javascript (using external library - Enumerable) (63 bytes) ``` k=>_.Range(0,k+1).Any(i=>_.Range(0,k+1).Any(j=>i*i+j*j+i*j==k)) ``` Link to library: <https://github.com/mvegh1/Enumerable> Code explanation: Create a range of integers from 0 to k (call this the "i" range), and test if any "i" satisfies a certain predicate. That predicate creates a range from 0 to k (call this the "j" range), and tests if any "j" satisfies a certain predicate. That predicate is the loeschian formula [![enter image description here](https://i.stack.imgur.com/Me2Wu.png)](https://i.stack.imgur.com/Me2Wu.png) [Answer] # [Perl 6](http://perl6.org), ~~52 51~~ 50 bytes ``` ->\k{?first ->(\i,\j){k==i*i+j*j+i*j},(0..k X 0..k)} ->\k{?grep ->(\i,\j){k==i*i+j*j+i*j},(0..k X 0..k)} {?grep ->(\i,\j){$_==i*i+j*j+i*j},(0..$_ X 0..$_)} ``` ### Explanation: ``` { # Turn the following into a Bool # ( Technically not necessary as a list of 1 or more values is truthy ) ? # find all where the code block returns a truthy value grep # pointy block that takes one value (list of 2 values) # and gives each of the values in it a name -> $ ( \i, \j ) { # return true if the definition matches $_ == i*i + j*j + i*j }, # a list of 2 element lists (possible i and j values) ( 0..$_ X 0..$_ ) } ``` ### Test: ``` use v6.c; use Test; my @true = 0, 1, 4, 7, 12, 13, 108, 109, 192, 516, 999; my @false = 2, 5, 10, 42, 101, 102, 128, 150, 501, 1000; plan (@true + @false) * 2; my &is-loeschian = {?grep ->(\i,\j){$_==i*i+j*j+i*j},(0..$_ X 0..$_)} for |(@true X True), |(@false X False) -> ( $input, $expected ) { my ($result,$seconds) = $input.&time-it; is $result, $expected, ~$input; cmp-ok $seconds, &[<], 60, "in $seconds seconds" } sub time-it ( $input ) { my $start = now; my $result = $input.&is-loeschian; my $finish = now; return ( $result, $finish - $start ) } ``` ``` 1..42 ok 1 - 0 ok 2 - in 0.00111763 seconds ok 3 - 1 ok 4 - in 0.00076766 seconds ... ok 19 - 516 ok 20 - in 0.19629727 seconds ok 21 - 999 ok 22 - in 0.1126715 seconds ok 23 - 2 ok 24 - in 0.0013301 seconds ok 25 - 5 ok 26 - in 0.00186610 seconds ... ok 37 - 150 ok 38 - in 0.83877554 seconds ok 39 - 501 ok 40 - in 9.2968558 seconds ok 41 - 1000 ok 42 - in 37.31434146 seconds ``` [Answer] ## PowerShell v2+, ~~63~~ ~~56~~ 55 bytes ``` param($k)(0..$k|%{0..($i=$_)|%{$i*($i+$_)+$_*$_}})-eq$k ``` Takes input `$k`, loops upwards twice (outer loop `$i = 0 to $k`, inner loop `$j = 0 to $i`), each iteration generates the result of `i*i + j*j + i*j` (shortened to `i*(i+j) + j*j`). Those results are encapsulated in parens, and passed as an array to `-eq$k`. This acts as a filter to select only elements that equal the input. Outputs a nonzero (the number back) for truthy, or nothing (empty) for falsey. Processes `1000` in about 15 seconds on my machine. ### Test Cases ``` PS C:\Tools\Scripts\golfing> (1,4,7,12,13,108,109,192,516,999|%{.\loeschian-numbers.ps1 $_})-join',' 1,4,7,12,13,108,109,192,516,999 PS C:\Tools\Scripts\golfing> (2,5,10,42,101,102,128,150,501,1000|%{.\loeschian-numbers.ps1 $_})-join',' PS C:\Tools\Scripts\golfing> ``` [Answer] # Perl, 54 + 1 (`-n` flag) = 55 bytes ``` for$i(0..$_){for$j(0..$_){$i*$i+$j*$j+$i*$j-$_?1:say}} ``` Needs `-n` and `-M5.010` flags to run : ``` perl -nE 'for$i(0..$_){for$j(0..$_){$i*$i+$j*$j+$i*$j-$_?1:say}}' ``` Outputs some stuffs if the number is a Loeschian number, and nothing otherwise. This implementation is quite boring, so here is another one, for 87 bytes, regex-based, just for the eyes : ``` perl -pE '$_=(1 x$_)=~/^(.*)(??{$1x(-1+length$1)})(.*)(??{$2x(-1+length$2)})(??{$1x length$2})$/' ``` Carefull with this one, as the backtracking will use a lot of memory, so don't try to test numbers too big! (especially numbers that aren't Loeschians) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` ⊢∊(∘.(×-⍨2*⍨+)⍨0,⍳) ``` Checks if *k* ∊ (*i* + *j*)² – *ij*, for any 0 ≤ *i*, *j* ≤ *k*.     `⊢` is *k* `∊` a member of     `∘.` all combinations of         `×` *i* times *j*         `-⍨` subtracted from         `2*⍨` the square of         `+` *i* plus *j*     `⍨` for all *i* **and** *j* in     `0,` zero prepended to     `⍳` the integers 1 through *k* 1000 takes 3.3 seconds on my M540 and even less on [TryAPL](http://tryapl.org/?a=f%u2190%u22A2%u220A%28%u2218.%28%D7-%u23682*%u2368+%29%u23680%2C%u2373%29%20%u22C4%20%u2395TS%20%u22C4%20f%20999%20%u22C4%20%u2395TS%20%u22C4%20f%201000%20%u22C4%20%u2395TS&run). [Answer] ## Matlab, ~~53~~ 52 bytes ``` n=input('');[a b]=ndgrid(0:n);find((a+b).^2-a.*b==n) ``` Simple search over all possibilities. Outputs empty array as falsy and a non-empty vector as truthy value. Considering all-zeros matrix as falsy and not-all-zeros matrix as truthy we can get rid of the `find` function resulting in **~~47~~ 46 bytes** solution: ``` n=input('');[a b]=ndgrid(0:n);(a+b).^2-a.*b==n ``` *One byte saved thanks to [@flawr](https://codegolf.stackexchange.com/users/24877/flawr)* [Answer] # C, 66 bytes Call `f()` with the number to test. The function returns the number of solutions it found. ``` q,r;f(n){for(r=q=0;q++<n*n;r+=n==q%n*(q%n+q/n)+q/n*q/n);return r;} ``` [Try it on ideone](http://ideone.com/fDyGD8). [Answer] # Mathematica, 44 bytes ``` MemberQ[(+##)^2-##&@@@0~Range~#~Tuples~2,#]& ``` Unnamed function taking an integer as input and returning `True` or `False`. The command `0~Range~#~Tuples~2` creates all ordered pairs of integers both between `0` and the input `#`. The function `(+##)^2-##&` computes the square of the sum of its arguments minus the product of its arguments; when called on two arguments `i` and `j`, this is exactly `i^2+j^2+ij` as desired. So that function is called on all the tuples, and then `MemberQ[...,#]` checks whether the input is one of the resulting values. [Answer] # ASP, 39 + 4 = 43 bytes ``` o:-k=I*I+J*J+I*J;I=1..k;J=1..k.:-not o. ``` Output: the problem is satisfiable iff k is Loeschian. [Answer Set Programming](https://en.wikipedia.org/wiki/Answer_set_programming) is a logical language, similar to prolog. I use here the [Potassco implementation](https://potassco.org), *clingo*. Input is taken from parameters (`-ck=` is 4 bytes long). Call example: ``` clingo -ck=999 ``` Output sample: ``` SATISFIABLE ``` Tried with 1000: ``` clingo -ck=1000 ``` Output sample: ``` UNSATISFIABLE ``` You can try it in your [browser](https://potassco.org/clingo/run/) ; unfortunately, this method doesn't handle call flags, so you need to add the line `#const k=999` in order to make it work. --- Ungolfed & explained code: ``` v(1..k). % predicate v(X) holds for any X in [1..k] o:- k=I*I+J*J+I*J ; v(I) ; v(J). % o holds if k is Loeschian. :- not o. % discard models where o doesn't holds (make problem unsatisfiable) ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), ~~28~~ 26 bytes ``` D,g,@@,*aaz€b*Fs L,0rd‽gAe ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HwUFHKzGx6lHTmiQtt2IuHx2DopRHDXvTHVP///9v/i@/oCQzP6/4v27mf13d4oLU5My0StucxNyklEQFQwA "Add++ – Try It Online") or [verify the test cases](https://tio.run/##S0xJKSj4/99FJ13HwUFHKzGx6lHTmiQtt2IuHx2DopRHDXvTHVP/l1hFGyqYKJgrGBopGBorGBpYALGlgqGlUSxXmlW0kYIpkK9gApQ0MARiIG0EVGFqEMvF5Vqiw8WZkgkilHTtlIC0Sk5iblJKooKhHUjUn4vLX0kJqC6NgLr/AA) Takes a long time for large inputs. Times out on TIO for the `501` and larger test cases. ## How it works ``` D,g,@@, ; Define a helper function that takes 2 arguments, i and j ; Example: i = 0, j = 2 STACK = [0 2] * ; Multiply STACK = [0] aaz ; Push [i i] and [j j] STACK = [0 [0 0] [2 2]] €b* ; Take their products STACK = [0 [0 4]] Fs ; Flatten and return the sum STACK = [0 0 4 4] ; Returns i*i + i*j + j*j Returns 4 L, ; Main function, takes 1 argument, k ; Example: k = 4 STACK = [4] 0r ; Range from 0 STACK = [[0 1 2 3 4]] d ; Duplicate STACK = [[0 1 2 3 4] [0 1 2 3 4]] ‽ ; Across all pairs... STACK = [[[0 0] [0 1] [0 2] ... [4 2] [4 3] [4 4]]] g ; run the helper function STACK = [[0 1 4 ... 28 37 48]] Ae ; Is k in the array? Returns 1 ``` [Answer] # PHP, 70 bytes ``` for(;$i++<$k=$argv[1];)for($j=$i+1;$j--;)$i*$i+$j*$j+$i*$j-$k?:die(1); ``` takes input from command line argument; exits with `1` for Loeschian number, with `0` else. Run with `-nr`. **breakdown** ``` for(;$i++<$k=$argv[1];) # loop $i from 1 to $k for($j=$i+1;$j--;) # loop $j from $i to 0 $i*$i+$j*$j+$i*$j-$k? # if $i,$j,$k do not satisfy the equation, do nothing :die(1); # else exit with return code 1 # implicit: exit with code 0 ``` --- # revisited, 67 bytes by merging the loops to one: ``` for($b=1+$a=$n=$argv[1];$b--||$b=--$a;)$a*$a+$b*$b+$a*$b-$n||die(1); ``` not tested, though pushed it a little further ... ## 57 bytes: ``` while($a*$a+$b*$b+$a*$b-$argn)$b++<$a||$b=1/($a++<$argn); ``` * takes input from pipe; run with -nR * no output if input is Loeschian, division by zero error if not * not tested either Haven´t been here for a while. I thought I remembered that deliberate errors were forbidden; but I couldn´t find it. What I found instead was a deleted post in the [loopholes thread](https://codegolf.meta.stackexchange.com/questions/1061) that requested to forbid output to STDERR. Could someone refresh my memory? **breakdown** ``` # $a and $b are implicitly initialized with NULL, which increments to 1 while($a*$a+$b*$b+$a*$b-$argn) # while solution not found $b++<$a # inner loop: $b from 1 to $a ||$b=1/($a++<$argn); # outer loop: $a from 0 to $argn(=input) # $a<$argn: 1/true -> 1 # else: 1/false -> division by zero ``` [Answer] # GAP 4.7.9, 75 bytes ``` k->Filtered(Collected(FactorsInt(k)),d->RemInt(d[2],2)+RemInt(d[1],3)=3)=[] ``` Every positive integer \$k\$ has a unique representation as the product of powers of distinct primes, \$p\_1^{e\_1}\dots p\_s^{e\_s}\$. \$k\$ is Loeschian iff no prime \$p\_i\$ occurs to an odd power \$e\_i\$ if \$p\_i=2\$ modulo 3. The above GAP code is for a lambda-expression which returns `true` if `k` is Loeschian and `false` if not. [Try it online!](https://tio.run/##S08s@B9QlJlXouGWmVOSWpSaohFtpKdnYRir8z9b1w4u6Jyfk5OaXAJkuSUml@QXFXsCtWRrauqk6NoFpeaCeCnRRrE6RpracC7QDGNNWyCKjv2vqWn9HwA "GAP – Try It Online") Its algorithm is nice and simple but the long names for some of those GAP functions make for poor golf, unfortunately. [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ô ï d@¶Xx²+X× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9CDvIGRAtlh4sitY1w&input=MTIKLVE) ]
[Question] [ A simple one today. Write the shortest program that draws a "sawtooth alphabet" given a positive integer for the height. You must write the name of your programming language when you come to the letter it starts with. For example, if your language is Python and the input is `1` the output should be: ``` ABCDEFGHIJKLMNOPythonQRSTUVWXYZ ``` If the input is `2` the output should be: ``` B D F H J L N Python R T V X Z A C E G I K M O Q S U W Y ``` If the input is `4` the output should be: ``` D J Python V C E I K O Q U W B F H L N R T X Z A G M S Y ``` **Notes** * `A` always starts at the bottom left. * Input can be via stdin or function call or similar. Output to stdout. * Input above `26` doesn't need to work. * No trailing spaces. [Answer] ## C, 134 ``` n,m,c,p; main(r){ for(scanf("%d",&n),m=--n?n*2:1;n+r--;puts("")) for(c=-1,p=1;c++<25;) p+=(c-n-r)%m*((c-n+r)%m)?1:1-printf("%*c",p,c+65); } ``` Compiles on gcc with a few warnings. Newlines aren't included in the character count. **122 characters** if the input is already stored in `n`. Thanks to [user2992539](https://codegolf.stackexchange.com/users/20442/user2992539), [tolos](https://codegolf.stackexchange.com/users/21677/tolos) and [edc65](https://codegolf.stackexchange.com/users/21348/edc65) for improvements. [Answer] if **n** holds the height: # C + escape codes: 81 ``` x;main(y){for(y=n--;x<26;x++)printf("\033[%d;%dH%c",n?x/n&1?y++:y--:y,x+1,x+65);} ``` # C: 110 ``` x;char a[702]={[0 ...701]=32};main(y){for(y=--n;x<26;a[x*27-1]=10)a[27*(n?x/n&1?y++:y--:y)+x]=x+++65;puts(a);} ``` [Answer] # TI-BASIC - 148 bytes (raw text), 186 bytes (graphic) In response to the OP, the wonderful TI-83 (and newer) comes with a size of 16 x 8 (just using the standard large text) or with a size of 94 x 62 pixels (which with small text is worth about 10 lines). Now, this has a little problem (to which I would like clarification). The size impositions can't be "ignored" by the interpreter; in other words, if we were to try to set the sawtooth height at 20, it would give an error preventing the full execution of the code. I *could* write code that would, in an infinite environment, produce the correct output, except it wouldn't run on the machine. With this being said, I present you the (running) versions of the programs. They all depend on the variable `N` being set to the desired height in lines before running: * Raw text approach ``` :ClrHome :"ABCDEFGHIJKLMNOPQRSTI-BASICUVWXYZ"→Str1 :8→R :For(C,1,16 :If N=1 :Then :0→F :Else :If R<2 or 10-R>N :1→F :If R>7 :-1→F :End :If C≠20 :Then :Output(R,C,sub(Str1,C,1 :Else :Output(R,C,sub(Str1,C,8 :C+7→C :End :R+F→R :End ``` In order to make this work regardless of the terminal, change `For(C,1,16` to `For(C,1,33` and remove the upper bound checking (`R<2 or`). Here is the output with `5→N`: ![enter image description here](https://i.stack.imgur.com/RoNnh.png) * Graphic approach (this may also need `AxisOff` for clarity) ``` :ClrDraw :N*6→N :"ABCDEFGHIJKLMNOPQRSTI-BASICUVWXYZ"→Str1 :57→R :For(C,1,56 :If N=6 :Then :0→F :Else :If R<7 or 64-R>N :6→F :If R>51 :-6→F :End :If C≠20 :Then :If C>50 :Then :Text(R,C,sub(Str1,C-23,1 :Else :Text(R,C,sub(Str1,C,1 :End :Else :Text(R,C,sub(Str1,C,8 :C+30→C :End :R+F→R :End ``` This one works OK, with two minor quirks. The height is still a problem, although the width isn't. However, I didn't space the letters, so in some cases (when the letter starts to rise or decline from the sawtooth), the letters may be chopped off by their successors. To make it work regardless of the terminal, remove the upper bound check (`R<7 or`). Then follows the graph: ![enter image description here](https://i.stack.imgur.com/Fyb7J.png) [Answer] # Pure Bash (no coreutils), 181 bytes ``` m=$1 for l in A Bash {C..Z};{ ((m))||s=++ ((m>$1-2))&&s=-- for((m=$1==1?1:m,m$s,i=0;i<$1;i++));{ ((i-m))&&a[i]+=${l//?/ }||a[i]+=$l } } shopt -s extglob printf %s\\n "${a[@]%%+( )}" ``` ### Output: Piped to `cat -E` just to prove there are no trailing newlines. ``` $ ./sawtooth.sh 1 | cat -E ABashCDEFGHIJKLMNOPQRSTUVWXYZ$ $ ./sawtooth.sh 5 | cat -E E M U$ D F L N T V$ C G K O S W$ Bash H J P R X Z$ A I Q Y$ $ ``` [Answer] # JavaScript (ES6) 231 ~~244~~ **Edit** Bug fix, some reordering and a different way of managing height==1 Moreover, changed to a function as this is allowed by OP, so no prompt() for input No changes to the general algorithm that probably is NOT the best for this challenge ``` F=h=>{for(p=s=[i=z=b=t=''];++p<h;)i=1,z=b=' ',s[p]=t;for(p=--h,k=64;++k<91;)s[p]+=t+String.fromCharCode(k),k-74||(s=s.map((x,q)=>x+(p-q?' ':'avascript'))),p-=i,p<0|p>h?(i=-i,p-=i+i,t=z,b=t+t):t+=b;console.log(s.join('\n'))} ``` **Explained** ``` F=h=>{ // row in s for output must be initialized to ''. In the same step I make other initializations for(p=s=[i=z=b=t='']; ++p < h;) // initialize for height 1, all increment and spacing can be null i=1,z=b=' ',s[p]=t; // the for body is entered only if height > 1, initializing spacing and increment to the right values for(p=--h,k=64;++k<91;) s[p]+=t+String.fromCharCode(k), k-74||(s=s.map((x,q)=>x+(p-q?' ':'avascript'))), // if 'J' modify each line of output adding the name or spacing p-=i,p<0|p>h?(i=-i,p-=i+i,t=z,b=t+t):t+=b; // index bouncing console.log(s.join('\n')) } ``` **Examples** 1 ``` ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ ``` 3 going up ``` C G K O S W B D F H Javascript L N P R T V X Z A E I M Q U Y ``` 4 on top ``` D Javascript P V C E I K O Q U W B F H L N R T X Z A G M S Y ``` 7 going down ``` G S F H R T E I Q U D Javascript P V C K O W B L N X Z A M Y ``` [Answer] **JAVA** **(393)** As always a great language for golfing: ``` public class P{public static void main(String[]a){int h=Integer.valueOf(a[0]);String x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";String[]l=new String[h];Arrays.fill(l,"");int i=h-1;int d=-1;for(char c:x.toCharArray()){for(int n=0;n<l.length;n++){String k=(n==i)?(c=='J')?"Java":c+"":(c=='J')?" ":" ";l[n]+=k;}if(i==0&&d==-1)d=1;if(i==h-1&&d==1)d=-1;if(h>1)i+=d;}for(String s:l){System.out.println(s);}}} ``` [Answer] ## Ruby, 112 bytes ``` o="#{' '*29} "*h 26.times{|i|o[(h-i%(h<2?1:2*h-2)-1).abs*30+i+(i>17?3:0)]=(i+65).chr} puts o.gsub('R ','Ruby') ``` Expects the input to be stored in `h`. Let me know if this needs clarification. [Answer] # J : 75 bytes ``` NB. without IO |:26([:u:65+i.@[)`(($(,|.@}.@}:)@i.)<"1@,.i.@[)`(' '$~,~)}5 2(1!:2)~|.26([:u:65+i.@[)`(($(,|.@}.@}:)@i.)<"1@,.i.@[)`(' '$~,~)}".1!:1[1 ``` Using the wonderful [Amend conjunction](http://www.jsoftware.com/help/dictionary/d530n.htm). As usual the IO is ugly and clunky, not going into details there. The core solution takes 3 gerunds (a sort of noun-ified verb (aka. function)): * a) generating the alphabet * b) generating the indices * c) generating the matrix to make amends to x (a`b`c}) y a) is a pretty trivial lookup in the ascii table c) is even more trivial b) is the interesting one. The morale is that the horizontal indices are supposed to be starting from 0 going to y-1 and back down, repeating this 26 times. Eg. for y == 4: ``` 0 1 2 3 2 1 0 1 2 3 2 1 ... ``` Implementing this gives for b): ``` ($(,|.@}.@}:)@i.) <"1@,. i.@[) NB. is equivalent too (tine0 tine1 tine2) NB. a fork with tines defined as tine0 =: hook0 =: hook0_0 hook0_1 NB. a dyadic hook: x (g h) y -: x g h y hook0_0 =: $ NB. reshape hook0_1 =: (hook1_0 hook1_1)@i. NB. do hook1 after making 0-y hook1_0=: , NB. append to self hook1_1=: |.@}.@}: NB. rotated version of y after beheading and curtailing tine2 =: i.@[ NB. generate 0-x tine1 =: <"1@,. NB. glue together coordinates. ``` And oh yea, handy fact: J's name is ... "J". [Answer] ## R (204) ``` f=function(x) { m=matrix(" ",x,26) i=x d=ifelse(x==1,0,-1) for (j in 1:26) { m[i,j]=LETTERS[j] if (!((i+d) %in% 1:x)) d=-d i=i+d } for (i in 1:x) cat(m[i,],"\n",sep="") } ``` Result ``` > f(1) ABCDEFGHIJKLMNOPQRSTUVWXYZ > f(2) B D F H J L N P R T V X Z A C E G I K M O Q S U W Y > f(3) C G K O S W B D F H J L N P R T V X Z A E I M Q U Y > f(7) G S F H R T E I Q U D J P V C K O W B L N X Z A M Y ``` [Answer] ## J, ~~67 57~~ 61 characters ``` echo@dtb"1@|.@|:@(26&,$(u:65+i.26)#~1 j.26$(0#~1=]),<:#-&0 2) ``` Use as a function: ``` echo@dtb"1@|.@|:@(26&,$(u:65+i.26)#~1 j.26$(0#~1=]),<:#-&0 2) D J P V C E I K O Q U W B F H L N R T X Z A G M S Y ``` --- **Explanation:** this solution uses a different approach than the other J solution. Instead of generating a sawtooth wave *0 1 2 3 2 1 0 1 ...*, I looked at the spacing between consecutive letters. For instance, for *n=4* if you go from the A upwards, wrap over to the second column and reach B, then you find four spaces between A and B. This pattern of spacing between letters is very regular: for *n=4* the pattern is *4 4 4 2 2 2 4 4 4 ...*. So the idea is to first build the flattened (and transposed) array, and then re-shape it and flip it so it look right. The output routine is straightforward (for being J, at least): *dtb* is "delete trailing blanks" and `"1` says "operate on each line". [*dtb*](http://www.jsoftware.com/help/user/lib_strings.htm) and [*echo*](http://www.jsoftware.com/help/user/lib_stdlib.htm) are both provided by the standard library. Thanks to [Zsbán Ambrus](https://codegolf.stackexchange.com/users/6691/zsban-ambrus) for some golfing help. [Answer] ## Javascript - ~~248~~ ~~224~~ 235 ``` z=~~prompt(),y="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");y[9]="Javascript";for(w=[],v=0;v<z;v++)w[v]="\n";v--;for(i=0;i<26;i++){for(j=0;j<z;j++)w[j]+=j-v?i-9?" ":" ":y[i];~~(i/(z-1))%2?v++:v--;}if(z==1)w=y;console.log(w.join("")) ``` [Here](http://jsfiddle.net/58snu/1/) is a link to the jsfiddle, where you can test it. edit: Made a console log for a monospaced font and removed the commas if input==1. [Answer] # Perl 119 ``` $s.=/26/?++$r&&$/:$m-1&&$r-abs$_%(2*$m-2)+1-$m?$"x(1+3*/15/):/15/?Perl:(A..Z)[$_]for(0..26)x($m=<>);print$s=~s/\s+$//rg ``` This program takes input from `STDIN` and prints the result to `STDOUT`. And bonus - a version that is against the rules as it prints trailing spaces, but adds some interaction: ``` #!/usr/bin/perl -p $r=0;$_=join'',map{/26/?++$r&&$/:$m-1&&$r-abs$_%(2*$m-2)+1-$m?$"x(1+3*/15/):/15/?Perl:(A..Z)[$_]}(0..26)x($m=$_) ``` ...and some tests below: ``` 1 ABCDEFGHIJKLMNOPerlQRSTUVWXYZ 2 B D F H J L N Perl R T V X Z A C E G I K M O Q S U W Y 4 D J Perl V C E I K O Q U W B F H L N R T X Z A G M S Y 6 F Perl Z E G O Q Y D H N R X C I M S W B J L T V A K U ``` [Answer] # MetaPost (207) ``` numeric h,d,y;h=5;d=-1;y=1;u=5mm;pair p;string s;for x=1upto26:p:=(x,y)*u;s:=char(x+64);if x=13:s:="MetaPost";elseif x>13:p:=(x+2,y)*u;fi;label.rt(s,p);if(y=h)or(y=1):d:=d*-1;fi;if h=1:d:=0;fi;y:=y+d;endfor; ``` [![enter image description here](https://i.stack.imgur.com/r5UtY.png)](https://i.stack.imgur.com/r5UtY.png) You can try it [here.](http://www.tlhiv.org/mppreview/ "here") [Answer] # Bash (213) (223) ``` read i p=0 d=1 printf '\n%.0s' `seq $i` for l in {A..Z} do (($p==$i-1))&&((p=$p*-1)) (($i==1))&&p=0 (($p!=0))&&echo -en "\033[s\033[${p#-}A" [[ "$l" == "B" ]]&&l="Bash" echo -en $l"\033[s\033[${p#-}B" ((p++)) done ``` Minor tweaks and we're down to 213. The original one had a minor bug. Tested and confirmed to work on bash version 4.2.37. Thanks to @manatwork for pointing out the bug and some tips. [Answer] # Haskell – 432 Bytes (unfortunately...) This turned out to be much harder than I expected to accomplish purely, hence the hefty byte count. I am sure I (or someone) could do better, but I've spent too much time on this as it is. The golfed version is as follows: ``` import Data.Matrix import Data.Vector(toList) r=repeat s h=y h$l(take 26(case h of 1->r 1;_->concat$r$[h,h-1..1]++[2..h-1]))['A'..'Z']$matrix h 32(const ' ')<|>matrix h 1(const '\n') l _[]m=m l(x:i)(r:e)m=l i e$u m(let z=26-length i in if z<9 then z else z+6)x r l _ _ m=m u m c r h=case h of 'H'->t c r"Haskell"m;_->setElem h(r,c)m t _ _[]m=m t c r(x:i)m=t(c+1)r i$setElem x(r,c)m y h m=concat[toList$getRow x m|x<-[1..h]] ``` To run, load the code into `ghci` and execute `putStr $ s Int` where `Int` is your desired height. You could also add ``` import System.Environment main :: IO () main = fmap (s . read . head) getArgs >>= putStr ``` under the `import`s in a text file, compile it with `ghc`, and pass the height as a command line argument. Ungolfed version: ``` import System.Environment import Data.Matrix import Data.Vector (toList) main :: IO () main = fmap (sawtooth . read . head) getArgs >>= putStr type M = Matrix Char sawtooth :: Int -> String sawtooth height = let mat = matrix height 32 (const ' ') <|> matrix height 1 (const '\n') numbers = take 26 (case height of 1 -> repeat 1 _ -> concat $ repeat $ [height,height-1..1]++[2..height-1]) chars = ['A'..'Z'] in toString height $ makeMatrix numbers chars mat makeMatrix :: [Int] -> String -> M -> M makeMatrix [] [] mat = mat makeMatrix (x:xs) (s:ss) mat = makeMatrix xs ss $ updateMatrix mat (let z = 26 - length xs in if z < 9 then z else z + 6) x s makeMatrix _ _ mat = mat updateMatrix :: M -> Int -> Int -> Char -> M updateMatrix mat col row char = case char of 'H' -> insertHaskell col row "Haskell" mat _ -> setElem char (row, col) mat insertHaskell :: Int -> Int -> String -> M -> M insertHaskell _ _ [] mat = mat insertHaskell col row (x:xs) mat = insertHaskell (col+1) row xs $ setElem x (row, col) mat toString ::Int -> M -> String toString height mat = concat [ toList $ getRow x mat | x <- [1..height] ] ``` [Answer] # C#/LINQ: ``` using System; using System.Linq; namespace SawtoothAlphabet { class Program { static void Main(string[] args) { int N = Int32.Parse(args[0]); // eg 4 Console.WriteLine( String.Join(Environment.NewLine, Enumerable.Range(0, N).Select(line => String.Concat(Enumerable.Range(0, 26).Select(i => line == Math.Abs(i % (2 * (N - 1)) - (N - 1)) ? (i == 2) ? "C#" : Char.ConvertFromUtf32(i + 'A') : (i == 2) ? " " : " ") ).TrimEnd()))); } } } ``` Brief explanation: `Enumerable.Range(0, N).Select(...)` causes a string to be generated for each line which is eventually concatenated into a single string with `String.Join(Environment.NewLine, ...)`. For each line we cycle through all 26 characters with `Enumerable.Range(0, 26).Select(...)`, the test at the start of the lambda expression determines whether to generate a character or space while the `i==2` checks for "C" and converts it to either "C#" or two spaces depending on the line. The `String.Concat(...)` converts the resulting `IEnumerable<char>` for each line into a string before passing it to `TrimEnd(...)` to cleanly strip away any trailing whitespace. [Answer] # K, 60 bytes ``` `0:'{+{x!y}.'+(26#{(!x),|1_!x-1}x;(((x-1)#" "),)'`c$65+!26)} ``` Pretty straightforward, and it looks like I just edged out the J solution. :) First, generate an alphabet: ``` `c$65+!26 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ``` And a sawtooth wave of an appropriate length: ``` 26#{(!x),|1_!x-1}5 0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0 1 ``` Pad each letter of the alphabet with leading spaces: ``` (((5-1)#" "),)'"ABC" (" A" " B" " C") ``` Zip the alphabet and the square wave together, and rotate each row: ``` +(0 1 2;(" A";" B";" C")) ((0 " A") (1 " B") (2 " C")) {x!y}.'+(0 1 2;(" A";" B";" C")) (" A" " B " "C ") ``` And the transposition of that is our answer: ``` +{x!y}.'+(0 1 2;(" A";" B";" C")) (" C" " B " "A ") ``` Try it here in [oK](http://johnearnest.github.io/ok/index.html?run=%20%600%3A'%7B%2B%7Bx!y%7D.'%2B(26%23%7B(!x)%2C%7C1_!x-1%7Dx%3B(((x-1)%23%22%20%22)%2C)'%60c%2465%2B!26)%7D5%3B). [Answer] **Javascript (~~204 185 150~~ 145)** ``` h=m=4;d=h>1?-1:0;o=[];for(a=0;a<35;a++){for(r=h;r;r--)o[r]=(o[r]||"")+(r==m?"ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a]:" ");if(a<9||a>17){m+=d;if(m<2||m==h)d=-d}}console.log(o.join("\n")) ``` ## EDIT Saved 13 bytes by not building an array and .join("\n"). Required flipping the for loops. Then, with help from C coding son, made code entirely too clever to save another 12 bytes. Here is the readable version showing the logic change. ``` for (row = height; row; row--) { rowOfNextActiveLetter = 1; direction = height > 1 ? -1 : 0; output = ""; for (a = 0; a < 35; a++) { output += (row == rowOfNextActiveLetter ? "ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a] : ""); if (a < 9 || a > 17) { rowOfNextActiveLetter -= direction; if (rowOfNextActiveLetter < 2 || rowOfNextActiveLetter == height)direction = -direction } } console.log(output) } ``` Golfed (161): ``` for(r=h;r;r--){m=1;d=h>1?-1:0;o="";for(a=0;a<35;a++){o+=(r==m?"ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a]:" ");if(a<9||a>17){m-=d;if(m<2||m==h)d=-d}}console.log(o)} ``` Golfed and obfuscated (149): ``` for(r=h;r;r--,console.log(o))for(m=1,d=h>1?1:0,o="",a=0;a<35;)if(o+=r==m?"ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a]:" ",a<9|a++>17)d=(m+=d)<2|m==h?-d:d ``` Reversed Alphabet and loop (145): ``` for(r=h;r;r--,console.log(o))for(m=d=1,o="",a=35;a;)if(o+=" ZYXWVUTSRQPONMLKtpircsavaJIHGFEDCBA"[r==m?a:0],a<18|a-->26)d=h<2?0:(m+=d)<2|m==h?-d:d ``` [Answer] # PHP (216) (205) New version: ``` $b=array_fill(65,26,' ');$b[80]=' ';$b=array_fill(0,$i,$b);for($j=--$i,$x=64;++$x<91;$i||$j=0){$b[$j][$x]=chr($x);$x==80&&$b[$j][$x]='PHP';$j+=($d=$j<($d?$i:1))*2-1;}echo join("\n",array_map('join',$b)); ``` Old version: ``` $b=array_fill(0,$i,array_fill(0,28,' '));for($j=--$i,$x=-1;++$x<28;$i||$j=0){$q=&$b[$j];$q[$x]=chr($x-($x&16)/8+65);$x==15&&($q[++$x]='H')*$q[++$x]='P';$j+=($d=$j<($d?$i:1))*2-1;}echo join("\n",array_map('join',$b)); ``` expects the variable $i to be the height. [Answer] ## C, 214 169 bytes, no trailing spaces Thank to @edc65 and @tolos for their helpful suggestions. ``` #define C ((c-i+n-65)%z&&(c+i+n-67)%z) n,i,m,c,z;main(){scanf("%d",&n);z=n<2?1:2*n-2;for(;i++<n;){for(m=c=64;c++<90;)m=C?m:c;for(c=64;c++<m;)putchar(C?32:c);puts("");}} ``` [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 79 bytes Not the shortest, and I think there's a chance this isn't valid (as it uses ANSI escape sequences to position the letters...) - happy to remove if this is deemed invalid. ``` //;$_=$/x$_;$|-=++$-<$'?0:($-=1),$\.=$_.($|?".":".[A")x($'>1)for A..O,Perl,Q..Z ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDJmMmYgM2IyNCA1ZjNkIDI0MmYgNzgyNCA1ZjNiIDI0N2MgMmQzZCAgLy87JF89JC94JF87JHwtPVxuMDAwMDAwMTA6IDJiMmIgMjQyZCAzYzI0IDI3M2YgMzAzYSAyODI0IDJkM2QgMzEyOSAgKyskLTwkJz8wOigkLT0xKVxuMDAwMDAwMjA6IDJjMjQgNWMyZSAzZDI0IDVmMmUgMjgyNCA3YzNmIDIyMGMgMjIzYSAgLCRcXC49JF8uKCR8P1wiLlwiOlxuMDAwMDAwMzA6IDIyMWIgNWI0MSAyMjI5IDc4MjggMjQyNyAzZTMxIDI5NjYgNmY3MiAgXCIuW0FcIil4KCQnPjEpZm9yXG4wMDAwMDA0MDogMjA0MSAyZTJlIDRmMmMgNTA2NSA3MjZjIDJjNTEgMmUyZSA1YSAgICAgQS4uTyxQZXJsLFEuLloiLCJoZWFkZXIiOiIkXFw9XCJcXG5cXG5cXG5cIjskfD0wOyQtPTA7IiwiYXJncyI6Ii1wIiwiaW5wdXQiOiIxXG4yXG4zXG40XG41XG42In0=) ## Explanation The initial `//` is purely to store the current value of `$_` in `$'` so `$_` can be used in the body of the loop, saving a variable assignment. Then `$_` is set to `$/` (newline) `$_` times, to move the cursor down the screen. The main body of the program is the `for` loop that iterates over the alphabet, replacing `P` with `Perl` as a bareword. `$|` can be used as a binary toggle when decremented so if the post-incremented `$-` is less than `$'`, subtract nothing, keeping the value the same, otherwise, set `$-` to `1` and decrement that. Next, append to `$\` (which is automatically output after `$_` at the end of the program thanks to `-p`) the current letter (`$_` - implicitly set by the `for` loop) with if `$|` is truthy, form feed (to move the cursor down a line) otherwise `\x1b[A` to move the cursor up one line, `$'>`` times. This last condition is to satisfy the requirement of input` 1` being a straight line and feels the most out of place in the answer... [Answer] # ~~C: ~~142~~ 139 characters~~ ~~Dreadfully long, I expect to be able to shorten it a bit:~~ ``` char a[26][27],i,j,p,d;main(n){for(scanf("%d",&n);i<26;d^=!p^p+2>n,p+=d-(d^n>1),i++)for(j=n;j--;a[j][i]=p^j?32:i+65);while(n)puts(a[--n]);} ``` Slightly more readable: ``` char a[26][27], i, j, p, d; main(n) { for ( scanf("%d", &n); i < 26; d ^= !p ^ p + 2 > n, p += d - (d ^ n > 1), i++ ) for ( j = n; j--; a[j][i] = p ^ j ? 32 : i + 65 ); while (n) puts(a[--n]); } ``` Edit: I missed the "no trailing spaces"-rule, but I will be back. [Answer] # Scala, 246 bytes ``` def f(h:Int)={val a=Seq.fill(h)(Array.fill(32)(' '));var(r,x,d)=(h-1,0,if(h==1)0 else-1);def p(c:Char){a(r)(x)=c;x+=1};for(c<-'A'to'Z'){p(c);if(c==83)"cala"foreach p;r+=d;if(r==0|r==h-1)d*= -1};for(z<-a)println(new String(z)replaceAll(" +$",""))} ``` reformatted and commented: ``` def f(h: Int) = { val a = Seq.fill(h)(Array.fill(32)(' ')); // r - row; x - x coordinate, column; d - direction var (r, x, d) = (h - 1, 0, if(h==1) 0 else -1); def p(c: Char) { // p for "put the character" a(r)(x) = c; x += 1 }; for(c <- 'A' to 'Z') { p(c); if(c == 83) // 83 == 'S' "cala" foreach p; r += d; if(r == 0 | r == h - 1) // | is shorter than || d *= -1 }; for(z <- a) println(new String(z) replaceAll (" +$", "")) // trimming trailing whitespace } ``` Results: ``` scala> f(4) D J P V C E I K O Q U W B F H L N R T X Z A G M Scala Y scala> f(5) E M U D F L N T V C G K O Scala W B H J P R X Z A I Q Y scala> f(1) ABCDEFGHIJKLMNOPQRScalaTUVWXYZ ``` [Answer] ## Python - 137 Input to be stored in i. e.g. `i=8` ``` l=[""]*h;k=j=0;y=h-1;exec'l[y]+=" "*(j-len(l[y]))+chr(k+65)+"ython"*(k==15);j=len(l[y]);y-=1^k/(h-(h>2))%2*-2;k+=1;'*26;print"\n".join(l) ``` [Answer] # Racket Here's a clean functional version: suggestions to shorten it welcome. ``` (define (sawtooth n) (define (ST i d m lns) (if (null? m) lns (let* ([v (first m)] [spc (make-string (string-length v) #\space)] [I (+ i d)]) (ST I (if (or (zero? I) (= (sub1 n) I)) (* d -1) d) (rest m) (for/list ([ln lns] [j n]) (~a ln (if (= i j) v spc))))))) (displayln (string-join (ST (sub1 n) (if (= n 1) 0 -1) (string-split "A B C D E F G H I J K L M N O P Q Racket S T U V W X Y Z") (make-list n "\n"))))) ``` ## Output ``` > (sawtooth 1) ABCDEFGHIJKLMNOPQRacketSTUVWXYZ > (sawtooth 2) B D F H J L N P Racket T V X Z A C E G I K M O Q S U W Y > (sawtooth 8) H V G I U W F J T X E K S Y D L Racket Z C M Q B N P A O ``` [Answer] # JavaScript, 168 bytes ``` f=(n,o=0,a=[...Array(n)])=>o<26?f(n,o+1,a.map((s='',i)=>s+(o-9?String.fromCharCode(65+o):'JavaScript').replace(i*i-(o%(2*n-2)-n+1)**2&&/./g,' '))):a.map(s=>s.trimEnd()) ``` [Try it online!](https://tio.run/##XY5BT8JAEEbv/Iq5yM6020WqVAUXYggXrxyRw6a0ZUk702yJiTH@9rrqzev3kve@i3t3Qxl8f81YTtU41hZZi73Vzh6MMS8huA9kOpJdy3NebOofnM61M53rEQerlPYRDilK9rTZX4PnxtRBuu3ZhW10YrFIhZbqNab2vylFJlR968oKfeIzlBvME85yyjidU5Lk0@nMzBqtQBHR8i81xIaJ9m7HJyQaV5NDruFOw72GhYZCw4OGx6OpJexceUYGu4bPCUApPEhbmVYajO/JXMQzqjeO8tU/HocvWo3f "JavaScript (Node.js) – Try It Online") Returns an array of lines. Ungolfed and explained: ``` f = ( n, // input o = 0, // offset for recursion (current step) a = [...Array(n)] // array containing output lines ) => o < 26 ? // if not at end yet f( // call function again n, // with same input o + 1, // increment offset a.map((s = '', i) => // add next letter to each line of a s + // current line ( o - 9 ? // if letter is not J String.fromCharCode(65 + o) : // current letter 'JavaScript' // else 'JavaScript' ).replace( // replace with spaces if not at a triangular wave point i != Math.abs(o % (2 * n - 2) - n + 1) && /./g, ' ' ) ) ) : a.map(s => s.trimEnd()) // return array with trailing spaces removed ``` [Answer] # [Scala](https://www.scala-lang.org/), 332 bytes Golfed version. [Try it online!](https://tio.run/##TY9bT8MgGIb/CuFigyxt1juT7jOp8zSP03o2XiClK47QBYjp0vS3V0Av5Orj4YX3wXKm2Di2n1@CO7RGonNCVxYVu13/zRRqgJmNJXOaunalXR5YB7g4Wh6fnJ6dry4ur65vbtd39@XD49Pzy@sbjhEFhTFsn9ZSqffSGak3H6ShBGPqzw2S0CRZnCpAfqpbQ/gi6XzLsmEmXqZ9oHqRqFTqSnJhaVTagqyJBpC09wMHmJZTisvwESyUFYj7V347h7D/n0J@xRBGeMgV0XQG2yH3CQkwn0wqCDq0guyPec1IAwuinjaHGZUzqIZobb0f7Xe@zSlNLB2GcRwPfgA) ``` object P extends App{val h=args(0).toInt;val x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";val l=Array.fill[String](h)("");var i=h-1;var d= -1;for(c<-x.toCharArray){for(n<-l.indices){val k=if(n==i){if(c=='S')"Scala"else c.toString}else{if(c=='S')" "else" "};l(n)+=k};if(i==0&&d== -1)d=1;if(i==h-1&&d==1)d= -1;if(h>1)i+=d};for(s<-l){println(s)}} ``` Ungolfed version. [Try it online!](https://tio.run/##dZBLT4QwFIX3/IqbLmZoDGRm50JMcHyNz1F8Gxe1lKFOU0hLDMbMb8e2FIkLV3DP/c69PVdTIkjXVe8fjDawAtY2TOYa0rqG7wDgkwgoIQGi1jqc4biplrLxemt0lB4sDo@OT06XZ@cXl1fXq5vb7O7@4fHp@QV5TBgsVYp8xQUX4jVrFJfrt7DEIULYMQq4YUqIYO7r3NSRLYpKQUhhL4LW7F6URLlR2D3Ot6Vti5jLnFOmh1a/fGMG8cIyifkZe@BUatVpNsWAMnsIBExoBtSs6p/p6W2v/2u2kvciQIPJf0UoMewksAlG1fq59c9gMrFpbVzsYs//Au4qv5BnohEqYd@q3G7Ig36@u4p2VxkS1yZNI2SosWO2Qdd1uz8) ``` object P extends App { val h = args(0).toInt val x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" val l = Array.fill[String](h)("") var i = h - 1 var d = -1 for (c <- x.toCharArray) { for (n <- l.indices) { val k = if (n == i) { if (c == 'S') "Scala" else c.toString } else { if (c == 'S') " " else " " } l(n) += k } if (i == 0 && d == -1) d = 1 if (i == h - 1 && d == 1) d = -1 if (h > 1) i += d } for (s <- l) { println(s) } } ``` ]
[Question] [ # Introduction Turns out, aliens love memes just as much as we do. Every alien race we've encountered so far has their own version of `2spooky4me` (see [the following question](https://codegolf.stackexchange.com/questions/62350/halloween-golf-the-2spooky4me-challenge)) and equivalent, though, with some variation. The inhabitants of planet CUTE1f can't handle a lot of spook, so their preferred spook is `1spooky2me`, while skeletor7 memers love them some spook, so they tend to use `9spooky11me`. # Challenge Translating memes is hard work, so you've been tasked with writing a universal meme translator to help these guys access the memenet correctly. Your program will accept a meme and a transformation to apply to the digit sequences in that meme to make it appropriate for the inhabitants of a different planet. ## Input Your program will receive two string inputs: 1. The input meme (e.g. `2spooky4me`). Matches `[a-zA-Z0-9]+`. 2. The transformation to apply to it (e.g. `+1`, to go from `2spooky4me` to `3spooky5me`). Matches `[+\-*/^]\d+` (you must accept `+`, `-`, `*`, `/`, and `^` as operators, regardless of the native representation in your language). ## Output Your program must return a string output (printed to standard output or equivalent) with the given transformation applied to the digit sequences in the input meme. In a weird turn of events, it also turns out that all races encountered so far prefer integral memes over fractional ones, so these transformations should perform integer arithmetic (e.g. `1spooky1me /2` should result in `0spooky0me`). ## Examples Standard arithmetic operations apply: ``` Input: 2spooky4me +1 Output: 3spooky5me Input: 2spooky4me -1 Output: 1spooky3me Input: 2spooky4me *15 Output: 30spooky60me Input: 10spooky900me /5 Output: 2spooky180me ``` Digit sequences are integral; integer truncation should occur in cases like this: ``` Input: idontunderstandmemes3 /2 Output: idontunderstandmemes1 ``` Your input may not have any digit sequences: ``` Input: notreallyafunnymeme *100 Output: notreallyafunnymeme ``` You must support exponentiation, even if it is not a native operation in your language of choice: ``` Input: 2spooky4me ^3 Output: 8spooky64me ``` There's no limit on string length of number of digit sequences in the string: ``` Input: some1meme2sequences3can4be5really6long7 /2 Output: some0meme1sequences1can2be2really3long3 ``` ## Addendum If your language supports arbitrary-precision integers as a language feature, you must use those. If it does not, you do not need to support arbitrary-precision integers. For example, you must use `Integer` in Haskell instead of `Int` because it's available as part of the language; in `Java`, you are not required to use `BigInteger` because it's a library feature, not a language feature. ``` Input: 2000000000000000000000000000000000000000000000000000000000000000000000000000000‌​000000000000000000000000000000000spooky4me /2 Output: 1000000000000000000000000000000000000000000000000000000000000000000000000000000‌​000000000000000000000000000000000spooky2me ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, and the shortest answer in bytes wins! # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 79809; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # Ruby, ~~50~~ ~~44~~ 43 bytes FGITW answer. Gotta go fast! Thanks to @Neil for saving 6 bytes. Oh right, crossed out 44 is still 44 ``` ->m,t{m.gsub(/\d+/){eval$&+t.sub(?^,'**')}} ``` [Answer] # Perl, ~~36~~ 34 bytes ``` s/\d+/"0|$&$^I"=~s#\^#**#r/gee ``` The source code is **30 bytes** long and it requires the switches `-pi` (**+4 bytes**). It takes the first input from STDIN, the second input as an argument to `-i`. *Thanks to @DenisIbaev for golfing off 2 bytes!* Test it on [Ideone](http://ideone.com/of5mUj). [Answer] # Jolf, ~~15~~ 14 bytes ``` ρi«\d+»dC!6+HI ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=z4FpwqtcZCvCu2RtZiE2K0hJ&input=MnNwb29reTRtZQoKKjE1) ## Explanation ``` ρi«\d+»dC!6+HI ρ «\d+» replace all digits i in the input d (functional replace) !6 eval (using jolf's custom infix eval) +H the number as a string plus I the second input C floor the result (integer truncate) ``` --- Fun to note, I updated Jolf after this challenge, adding some RegExp builtins. This could be ~~12~~ 11 bytes: ``` ρiLRdC!6+HI ``` [Answer] ## PowerShell v2+, ~~139~~ 137 bytes ``` param($a,$b)-join($a-split"(\d+)"|%{if($_-match"\d+"){if($b[0]-ne'^'){[math]::Floor((iex $_$b))}else{"$_*"*$b.Trim('^')+1|iex}}else{$_}}) ``` Ooof ... 47 bytes just to account for `^` since that's not a native operator in PowerShell. Saved 2 bytes thanks to @TessellatingHeckler. Takes input as `$a=<word>`, `$b=<operation>`, like `.\universal-spooky-meme.ps1 2spooky4me ^3`. We `-split` `$a` on digits, enclosing that in parens so we keep the delimiters, and pipe the resultant array through a loop `|%{...}`. If the current piece is a number, we're in the first `if`. We need to check whether the first character of `$b` is `^`. If it's not, we simply concatenate our current piece and `$b` and send it to `iex` (similar to `eval`), then leave that on the pipeline. Otherwise, we need to create an exponentiation string with `"$_*"*$b.Trim('^')+1` and pipe that to `iex`, and leave that on the pipeline. For the given `2spooky4me ^3` example, this will be `2*2*2*1` and `4*4*4*1`, respectively. Otherwise, we just leave the string as-is on the pipeline. All of those results are gathered from the pipeline with the encapsulating parens before being `-join`ed back together into one string. That is the re-left on the pipeline, and output is implicit at program termination. ### Examples ``` PS C:\Tools\Scripts\golfing> .\universal-spooky-meme.ps1 2spooky4me ^5 32spooky1024me PS C:\Tools\Scripts\golfing> .\universal-spooky-meme.ps1 2spooky4me /3 0spooky1me ``` [Answer] ## JavaScript (ES7), ~~58~~ 57 bytes ``` (s,t)=>s.replace(/\d+/g,n=>0|eval(n+t.replace('^','**'))) ``` Edit: Saved 1 byte when I remembered that `replace` also works on literal strings. [Answer] # Pyth, 29 ``` Jws.i:zK"\d+"3m.vs.iJ]+d;:zK1 ``` This works by extracting each number from the meme, and then interleaving (`.i`) it followed by a space and wrapped in a list with the other argument. So if our number is `7` and we had `^20` we would get the list: `["^", "7 ", "20"]`. Flattening and using Pyth's `eval` (`.v`) on this always gives the operation we want. Finally these values are interleaved with the original string split on occurrences of numbers. This could be a byte shorter if both inputs were surrounded by quote characters, or two bytes shorter if only one of them could be quoted. [Try it here](http://pyth.herokuapp.com/?code=Jws.i%3AzK%22%5Cd%2B%223m.vs.iJ%5D%2Bd%3B%3AzK1&input=200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me%0A%2B1&debug=0) or run a [Test Suite](http://pyth.herokuapp.com/?code=Jws.i%3AzK%22%5Cd%2B%223m.vs.iJ%5D%2Bd%3B%3AzK1&test_suite=1&test_suite_input=2spooky4me%0A%2B1%0A2spooky4me%0A-1%0A2spooky4me%0A%2A15%0A10spooky900me%0A%2F5%0Aidontunderstandmemes3%0A%2F2%0Anotreallyafunnymeme%0A%2A100%0A2spooky4me%0A%5E3%0Asome1meme2sequences3can4be5really6long7%0A%2F2&debug=0&input_size=2) [Answer] # Python 2, ~~156~~ ~~89~~ ~~88~~ 87 bytes Inspired by the other answers that use their languages' substitution function with a function handler to process the numeric parts of the long `i`nput string with the `o`perator. Unlucky for Python, the `^` must be replaced by `**`, which costs a whopping 18 bytes. The `.group(0)` call just to access the [match object](https://docs.python.org/3/library/re.html?highlight=re#match-objects)'s string representation does not make things better... Thanks to QPaysTaxes for spotting a spurious space and RootTwo for the unnecessary argument to `.group`! ``` import re lambda i,o:re.sub(r'\d+',lambda p:str(eval(p.group()+o.replace('^','**'))),i) ``` [Answer] # Javascript (ES6) 99 bytes Another example, why we hate to wait for ES7 to get compatibility ``` (a,b)=>a.match(/\d+|\D+/g).map(_=>(d=- -_)?eval(b[0]=="\^"?Math.pow(_,b.slice(1)):d+b)|0:_).join`` ``` Runnable example: ``` f=(a,b)=>a.match(/\d+|\D+/g).map(_=>(d=- -_)?Math.ceil(eval(b[0]=="\^"?Math.pow(_,b.slice(1)):d+b)):_).join`` alert(f(prompt("Enter string!"), prompt("Enter operation!"))); ``` [Answer] # Julia, ~~71~~ ~~59~~ 54 bytes ``` / =÷ x%y=replace(x,r"\d+",t->"big($t)"y|>parse|>eval) ``` The requirement to use `big` if available makes this a lot longer than it could be... [Try it online!](http://julia.tryitonline.net/#code=LyA9w7cKeCV5PXJlcGxhY2UoeCxyIlxkKyIsdC0-ImJpZygkdCkieXw-cGFyc2V8PmV2YWwpCiAKcHJpbnRsbigiMnNwb29reTRtZSIlIisxIikKcHJpbnRsbigiMnNwb29reTRtZSIlIi0xIikKcHJpbnRsbigiMnNwb29reTRtZSIlIioxNSIpCnByaW50bG4oIjEwc3Bvb2t5OTAwbWUiJSIvNSIpCnByaW50bG4oImlkb250dW5kZXJzdGFuZG1lbWVzMyIlIi8yIikKcHJpbnRsbigibm90cmVhbGx5YWZ1bm55bWVtZSIlIioxMDAiKQpwcmludGxuKCIyc3Bvb2t5NG1lIiUiXjMiKQpwcmludGxuKCJzb21lMW1lbWUyc2VxdWVuY2VzM2NhbjRiZTVyZWFsbHk2bG9uZzciJSIvMiIpCnByaW50bG4oIjIwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBzcG9va3k0bWUiJSIvMiIpCnByaW50bG4oIjJiaWc0aW50IiUiKjkyMjMzNzIwMzY4NTQ3NzU4MDciKQ&input=) [Answer] ## Kotlin, ~~416~~ 413 Bytes The lack of an `eval()` in Kotlin really upped that byte count... ``` fun main(a:Array<String>){var r=Regex("\\d+");var i=a[0];var n=a[1].takeLast(a[1].length-1).toInt();when(a[1][0]){'+'->print(r.replace(i,{m->""+(m.value.toInt()+n)}));'*'->print(r.replace(i,{m->""+(m.value.toInt()*n)}));'/'->print(r.replace(i,{m->""+(m.value.toInt()/n)}));'-'->print(r.replace(i,{m->""+(m.value.toInt()-n)}));'^'->print(r.replace(i,{m->""+(Math.pow(m.value.toDouble(),n.toDouble())).toInt()}));}} ``` [Try it Online!](http://try.kotlinlang.org/#/UserProjects/8undins0n2k4hs97jbi4evugbv/9a6ebi5emumiu1bpu3oe22hej1) ### Ungolfed ``` fun main(a: Array<String>) { var r = Regex("""\d+""") var i = a[0] var n = a[1].takeLast(a[1].length - 1).toInt() when (a[1][0]) { '+' -> print(r.replace(i, { m -> "" + (m.value.toInt() + n) })) '*' -> print(r.replace(i, { m -> "" + (m.value.toInt() * n) })) '/' -> print(r.replace(i, { m -> "" + (m.value.toInt() / n) })) '-' -> print(r.replace(i, { m -> "" + (m.value.toInt() - n) })) '^' -> print(r.replace(i, { m -> "" + (Math.pow(m.value.toDouble(), n.toDouble())).toInt() })) } } ``` [Answer] ## PowerShell (v4), ~~124~~ 120 bytes ``` # New 120 byte version: $s,$a=$args;[regex]::Replace($s,'\d+',{($(if($a-ne($a=$a.Trim('^'))){ "$args*"*$a+1}else{"$args$a"})|iex)-replace'\..*'}) # Previous 124 byte version $s,$a=$args;[regex]::Replace($s,'\d+',{if($a[0]-eq'^'){ [math]::pow("$args",$a.Trim('^'))}else{iex "$args$a-replace'\..*'"}}) ``` (the newlines are only here to avoid horizontal scrolling, they work when saved as one line). Comments, and ungolfed version was requested: ``` $meme, $instruction = $args # Scriptblock which processes the numbers # to be replaced. $args is the input number. $replacement = { # Generates a string of the calculation, by: # Removing leading ^ character, if present. # ^3 -> 3, +3 -> +3 # See if it was present, and switch code paths. # (Can be one combined step in the golf) # Switch code paths for "raise to the power of", # or basic arithmetic. $trimmedInstruction = $instruction.Trim('^') $tmp = if ( $instruction -ne $trimmedInstruction ) { # String multiplication, changes # function input "45" and instruction "3" into # "45*45*45*+1". The "3" implicitly casts to [int] # the +1 is there to make the trailing * not crash. "$args*" * $instruction + 1 } else { # Cobble the basic math together as a string # "45" and "+10" becomes # "45+10" "$args$instruction" } # eval() the generated string (e.g. "45+10" or "45*45*45*+1") $tmp = Invoke-Expression $tmp # iex # Use a regex golf to replace trailing .23423 # decimals in case of division with remainder. # Acts as [math]::floor(), harmless on other numbers. $tmp -replace'\..*' } # A regular expression replacement which picks out all # the numbers (\d+) and runs them through the # replacement function. Returns a string which # ends up on stdout [regex]::Replace($meme, '\d+', $replacement) ``` * .Net regex library can do a replace with a scriptblock that executes on the content of the match, and PowerShell casts types strings to numbers, and `iex` is like `eval()` in other languages. It just does `"2spooky" "+3"` -> `eval("2+3")` * Except... it can't handle `^` operator or any other convenient exponentiation like `**`, it can only use the `[math]::Pow()` library call so there's a big block to handle that branch. + The updated version steals an idea from @TimmyD and does string multiplication instead - `"2*" * n` which becomes `"2*2*2*2*"` and then adds `+1` on the end to multiply by one instead of complaining about the trailing `*`. * Except... .Net does Banker's Rounding which rounds to the nearest even number by default, and 3/2 = 2 rather than 3/2 = 1. This challenge calls for truncation, and that means `[math]::Truncate()`. Instead, I save characters by using `-replace` to trim a decimal point and anything after it. Test cases: ``` PS D:\> .\meme.ps1 2spooky4me +1 3spooky5me PS D:\> .\meme.ps1 2spooky4me -1 1spooky3me PS D:\> .\meme.ps1 2spooky4me *15 30spooky60me PS D:\> .\meme.ps1 10spooky900me /5 2spooky180me PS D:\> .\meme.ps1 idontunderstandememes3 /2 idontunderstandememes1 PS D:\> .\meme.ps1 "idontunderstandememes3" "/2" idontunderstandememes1 PS D:\> .\meme.ps1 "notreallyafunnymeme" "*100" notreallyafunnymeme PS D:\> .\meme.ps1 "2spooky4me" "^3" 8spooky64me PS D:\> .\meme.ps1 "some1meme2sequences3can4be5really6long7" "/2" some0meme1sequences1can2be2really3long3 PS D:\> .\meme.ps1 2000000000000000000000000000000000000000000000000000000000000000000000000000000‌​000000000000000000000000000000000spooky4me /2 1E+78‌​0spooky2me ``` NB. In the last test the numbers overflow into type `[BigInteger]` automatically, but they get rendered in scientific notation. Luckily, every known race able to communicate between the stars has enough scientific development to be able to process scientific notation without problem. [Answer] ## Bash + GNU coreutils, 144 Bytes ``` d= u=$1, for((i=0;i<${#u};i++)){ l=${u:i:1} [[ "$l" =~ [0-9] ]]&&d=$d$l||{ [ -z $d ]||echo -n `bc<<<$d$2`&&{ [ $l != , ]&&echo -n $l; };d=; } } ``` This looks at the alteration between digits and non-digits, that's why a random invalid input character (comma) is appended to the input string. This comma is then ignored in the output. The convention of the OP follows exactly the syntax of `bc` which is used here to do the maths. [Answer] # Lua, ~~145~~ 93 bytes ``` r=io.read;m=r()o=r()m=m:gsub("%d",function(n)return loadstring("return..."..o)(n)end)print(m) ``` [Answer] # [Zsh](https://zsh.sourceforge.io/) (builtins only), ~~167~~ 118 bytes ``` a=$1 S=(${(s: :)a//[0-9]/ }) for i (${(s: :)a//[a-z]/ })N+=($[i${2/^/**}]) ((#a<58))&&<<<${(j::)N:^S}||<<<${(j::)S:^N} ``` Crack the input into a numerical array `N` and string array `S`, do operations on `N`, then zip the arrays together again (zip the arrays the other way if the leading character is a letter). [Try it Online.](https://tio.run/##XYxBboMwFET3nMJSUWQTIdskpI1FrsCGZRokN5iGFOwWw4IQn51@mkVFlvPezNzsZSoxGb1eW9WhCl1RirJJHnyOsgP2R2wFEkRSemTh/kSRI15pWigunAxvfy5dw@ZY@WNEcxoE7kQ8jF9kEr8RslolSQKjqxAkFXnm7vd/kIk8dZPzShTZb2O@hm2j0Jovc/iU3wMeA@HsgfaMAaTxspRvIFeF0V2vC9XaTuqiUY2yG0QjUNp0rZJ1Pciy13qY1XzMGDhrGsVnEln10yt9htVZ6u2Hih@bXW305yscTb8) ~~[167 bytes!](https://tio.run/##XY7LboMwEEX3fIWlWMiAItskaZUEV@I78pBo4rRgGLcYFoD4djo07SJZnnvPHU3vPqcbCwavBacbkpOCGNITIOnUKzrE/MzDcPRutsaO0YG53S6QIzmSYABFDxDJ076IUM35QSy3Jz7uzR9myx7RY4wuCqWkTxfmTQSB76coMGZoP4NRv4ZB478rfL@YU1CKLmQknzbeuE@ShA4pJyEfJ/yOxO7LWtOtK00i@cjLJz6GcoOJFPdoKwSGfPMonVfI@dVC08JV167J4FrpSrsV4TFWYJtaZ2XZZbcWoJur@bAQ2DlbaTknsdPfrYYLri4ZrN/15r55KS18vOKh6Qc)~~ (longer than the bash solution! ☹️ ) [Answer] # [Zsh](https://www.zsh.org/), 95 bytes Whole program. Inputs: the meme and transformation as command line arguments. Output: standard output (with a trailing newline). ``` a=$1;repeat $#a c=${a/[^0-9]*}&&(($#c))&&b+=$[$c${2/^/**}] a=${a##<->}||b+=$a[1] a=${a#?};<<<$b ``` [Try it online!](https://tio.run/##XY/dioMwEEbv9ykGDOIPkh/bglTbB3ErjDGyZWtSNL2wrc/uJpRedC/POcMHc59@1v6mpT0bDT1EMUQrVoTvR3VVaIEECLIiD6R1w7LilCxhGEUkkHEchm1akZpI8hC0oUmynAD9aRCU2WF5Pn3Gmr/tcdmXZUnaNf7qQUxXY37nzaAg5Z@c/ePvhG@d4eylCsacpF6dO6PtTXdqnCzqblCDmnKgwiVt7KjwcpnRfadnn/wQY5/bTe4YRZtv5HYHaeGIQSrWPw "Zsh – Try It Online") A 98-byte solution with a non-optimized number/letter test: ``` a=$1;repeat $#a [[ $a = <->* ]]&&b+=$[${a%%[^0-9]*}${2/^/**}] a=${a##<->}||b+=$a[1] a=${a#?};<<<$b ``` Explanation: first here's the code with additional whitespace. ``` a=$1; repeat $#a \ c=${a/[^0-9]*} && (($#c)) && b+=$[$c${2/^/**}] a=${a##<->} || b+=$a[1] a=${a#?}; <<<$b ``` The general idea is to consume the input in `$a` from left to right, one multi-digit integer or one non-digit character at a time. Accumulate the result in `$b`, which is printed out after the loop. `repeat $#a …` repeats the following code `$#a` (initial length of the input) times. The loop body consumes at least one character as long as `$a` is non-empty and does nothing when it runs out, so this works, and it's shorter than naive approaches such as `while (($#a))` or `while [ $a ]`. In the loop body: 1. Set `c` to the initial digit sequence of `$a` (remove everything starting with the first non-digit). `${a/[^0-9]*}` is short for `${a/[^0-9]*/}` and shorter than the more intuitive `${a%%[^0-9]*}`. The assignment always succeeds, so the subsequent `&&` is just like `;` except that it doesn't terminate the `repeat` body. 2. `((#c))` tests whether `c` is non-empty, i.e. if `$a` starts with a digit. 3. If the test above, i.e. if `$a` starts with a digit, append the result of the arithmetic expression `$[…]` (an alternative form of `$((…))`) to `b`. The expression uses the digits in `$c` and the operator-and-number from `$2`. Zsh has the operators `+` `-` `*` `/` as required but exponentiation is `**` instead of `^`. 4. If the test above was false, i.e. if `$a` starts with a non-digit, append the first character of `$a` to `b` and remove the first character from `a`. [Answer] # [Zsh](https://www.zsh.org/) `--extendedglob`, 39 bytes ``` <<<${1//(#m)[0-9]##/$[MATCH${2/\^/**}]} ``` [Try it online!](https://tio.run/##XY6xDoIwFEV3v4IEBsCQtigaEhbj4uLmppggfaCRviItiUj89lripOM5992b91JXU/mBr0DLVjvw1IAceN3Ii8myzBsZIb4rgiON0tx1iXfcbw7bnTfG5HQmYfjO3yaYVU6sWinvw1KAM2e/HP3xKWSJNYx@VUqplST5PTovLN@4RN3bfzqlC@QCBKiFQ2IbodQdFE0zFFWPOEzRNEypzZQUwCYTK3j0gKVtlQUuL5B8O6tGYr22Q@YD "Zsh – Try It Online") [Answer] ## R, 163 bytes As someone who's learning regular expressions and string substitution in R, this proved to be a quite difficult challenge. Especially because matching the numbers is easy but I couldn't find a way to use multiple substitutions with `gsub`. Furthermore, I don't know if `eval(parse(paste0(...` is the most efficient way to switch between operations. Maybe the `switch`-function is better suited here. ``` function(s,o){p=strsplit;y=p(gsub("\\d+","?",s),"?")[[1]];x=na.omit(as.integer(p(s,"[a-zA-Z]+")[[1]]));y[y=="?"]=floor(eval(parse(,,paste0("x",o))));cat(y,sep="")} ``` **Explanation** ``` f=function(s,o){ p=strsplit # alias for stringsplit y=p(gsub("\\d+","?",s),"?")[[1]] # substitute numbers with "?" and split into vector on "?" x=na.omit(as.integer(p(s,"[a-zA-Z]+")[[1]])) # split at alphabetical char, return vector with numbers to be operated on y[y=="?"]=floor(eval(parse(,,paste0("x",o)))) # replace inserted "?" with vector of numbers operated on cat(y,sep="") # print concatenated vector } ``` [Answer] # Javascript (ES6), 85 Bytes ``` x=(s)=>{var a=s.split(" ");return[...a[0]].map(x=>(!isNaN(x))?eval(x+a[1]):x).join``} console.log(x("2spookie5me +1")); ``` Ungolfed: ``` x = (s) => { var a = s.split(" "); return [...a[0]].map(x => (!isNaN(x)) ? eval(x + a[1]) : x).join `` } console.log(x("2spookie5me +1")); ``` [Answer] # Groovy, ~~64~~ 60 Bytes ``` {a,b->a.replaceAll(/\d+/,{Eval.me(it+b.replace("^","**"))})} ``` Replaces all instances of digits with a closure that evaluates the operation on the digit portions of the word passed. If passed an exponent function, it replaces it with the proper notation. Groovy implicitly handles BigInteger/BigDecimal conversion when using `Eval.me()` because parsed strings can potentially be out of the `2^32-1` range. ## Explained `{a,b->...}` - Closure with two arguments. `a.replaceAll(/\d+/,{...})` - Search for all digit sequences in string and replace with a closure. `{Eval.me(it+b.replace("^","**"))}` - More specifically, a closure with each match having the operation appended to it, then evaluated as groovy code. `.replace("^","**")` - Replace the first instance of `^` with the groovy exponent operator `**` in the operation provided. If you want this to work with full equation strings that use exponents, use `replaceAll()` instead for a +3 byte penalty. Fun side-note his is a valid test scenario: `(22348952345238905290858906209862398036spooky409552me, /200*4943^8-23939+((100/203)+600)` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε.γd]``s„^/„m÷‡.VJ ``` Input as a pair of strings. [Try it online](https://tio.run/##yy9OTMpM/f//3Fa9c5tTYhMSih81zIvTBxK5h7c/alioF@b1/3@0kqFBcUF@fnalpYFBbqqSjpK@qVIsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/3Nb9c5tTolNSCh@1DAvTh9I5B7e/qhhoV6Y138lvTCd/9HRSkbFBfn52ZUmualKOkrahkqxOmhiuljEtAxNwYKGBhBRSwMDsLg@RDgzJT@vpDQvJbWouCQxLyU3NTe12BgkbQSWzssvKUpNzMmpTEwrzcurBEmDzTQwwLQpzhgsVpyfm2oIUmhUnFpYmpqXDDQwOTHPJCnVFGKUWU5@Xro5wg4jA6qCRw09jxq6CSpDdjnIIbEA). **Explanation:** ``` ε # Map both strings in the (implicit) input-pair to: .γ # Group it into substrings by: d # Is it a non-negative number ] # Close both the map and inner group-by ` # Pop and push both list or substrings separated to the stack ` # Pop and push the operator and number separated to the stack s # Swap them, so the operator is at the top of the stack „^/„m÷‡ # Transliterate "^" to "m" and "/" to "÷" .V # Evaluate the operator string as 05AB1E command # (the operations are no-ops on the non-number substrings) J # Join the list of substrings back together to a single string # (after which it is output implicitly as result) ``` If the final test case wasn't necessary, it could have been 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (which unfortunately has floating-point precision issues for the final test case): ``` ε.γd]``s'^'m:.VïJ ``` [Try it online](https://tio.run/##yy9OTMpM/f//3Fa9c5tTYhMSitXj1HOt9MIOr/f6/z9aydCguCA/P7vS0sAgN1VJR0nfVCkWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/3Nb9c5tTolNSChWj1PPtdILO7ze67@SXpjO/@hoJaPigvz87EqT3FQlHSVtQ6VYHTQxXSxiWoamYEFDA4iopYEBWFwfIpyZkp9XUpqXklpUXJKYl5KbmptabAySNgJL5@WXFKUm5uRUJqaV5uVVgqTBZhoYYNoUZwwWK87PTTUEKTQqTi0sTc1LBhqYnJhnkpRqCjHKLCc/L90cYYeRAVXBo4aeRw3dBJUhuxzkkFgA). **Explanation:** Mostly the same as above, except for `„^/„m÷‡` being `'^'m:` to only transform the exponent-operator and leave the division-operator as is, and the addition of `ï` to truncate the decimals after the eval. [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 39 Bytes ``` ►x='%d+'§x'%D+'''Rx'%d+'''Rg'y'=y_}R ``` ## Explained ``` ►x='%d+'§x'%D+'''Rx'%d+'''Rg'y'=y_}R ► # Spaceless segment. x= # Assign the top value of the stack '[+*/-]\d+' '$d+'§ }R # Replace everything in the pattern %d+ (all numbers) based on an anonymous function x'%D+'''R # Replace all Non-digits in the modifer with nothing, leaving just the second argument for the operator. x'%d+'''R # Snip all digits, separating our operator from our digits such that digit operator exists in the stack. g'y'= # Grab the function that is represented by the top of the stack (the operator in this case) y # Run it _ # Floor the result. ``` Technically invalid answer, because this language did not exist for it. However, it was not specifically designed for it, nor any particular addition. So I'm running it. Sue me. [Try it Online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%E2%96%BAx%3D%27%25d%2B%27%C2%A7x%27%25D%2B%27%27%27Rx%27%25d%2B%27%27%27Rg%27y%27%3Dy_%7DR&input=2Spooky4Me%20%5E2) [Answer] ## Perl 6, 111 bytes ``` {/(\w+)\s(<[+\-*/^]>)(\d+)/&&my \b=+$2;my \o=(*+b,*-b,* *b,*div b,* **b)[index "+-*/^",$1];$0.subst(/\d+/,o):g} ``` Unfortunately `EVAL` is disabled by default. Also, you have to use `div` for integer division. ]
[Question] [ You're a professional hacker and your boss has just ordered you to help a candidate win an upcoming election. Your task is to alter the voting machines data to boost the candidate's results. Voting machines store voting results as two integers : the number of votes for your candidate (`v1`) and the number of votes for their opponent (`v2`). After weeks of research, you have found a security hole in the system and you can increase the value of `v1` by an integer `x`, and decrease the value of `v2` by the same `x`. But there is a constraint, you have to keep the security hash code constant: * security hash code : `(v1 + v2*2) modulo 7` Also, the value for `x` must be minimal so your changes can go unnoticed. Your program should accept as input `v1` and `v2` ; it should output the optimal value for `x` so `v1>v2`. There are some cases for which you cannot hack the results; you don't have to handle them (this might lead to problems with your boss, but that's another story). **Test cases** ``` 100,123 --> 14 47,23 --> 0 40,80 --> 21 62,62 --> 7 1134,2145 --> 511 ``` [Answer] # Python 2, 30 bytes ``` lambda u,t:max(0,(t-u)/14*7+7) ``` `u` is our votes, `t` is their votes. [Answer] ## Python 2, 30 bytes ``` lambda a,b:max((b-a)/14*7+7,0) ``` [Answer] ## Mathematica, 22 bytes ``` 0//.x_/;2x<=#2-#:>x+7& ``` Pure function with arguments `#` and `#2`. Hits maximum recursion depth if the discrepancy is more than `7*2^16 = 458752`. ## Explanation ``` 0 Starting with 0, //. repeatedly apply the following rule until there is no change: x_ if you see an expression x /; such that 2x<=#2-# 2x <= #2-# (equivalently, #+x <= #2-x) :> then replace it with x+7 x+7 (hash is preserved only by multiples of 7) & End the function definition ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` IH:7‘×7»0 ``` [Try it online!](https://tio.run/nexus/jelly#@@/pYWX@qGHG4enmh3Yb/P//P9rQwEBHwdDIOFZHIdrEXEcBygIKWhiAWGZGOgpmRiCWoaGxCVDe0MQ0FgA "Jelly – TIO Nexus") ### How it works ``` IH:7‘×7»0 Main link. Argument: [v1, v2] I Increments; compute [v2 - v1]. H Halve the result. :7 Perform integer division by 7. ‘ Increment the quotient. ×7 Multiply the result by 7. »0 Take the maximum of the product and 0. ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 13 bytes ``` 7;;τ((-\*+0kM ``` [Try it online!](https://tio.run/nexus/actually#@29ubX2@RUNDN0ZL2yDb9/9/QwMDLkMjYwA "Actually – TIO Nexus") Uses the same `max((b-a)/14*7+7,0)` formula that xnor and orlp use. Explanation: ``` 7;;τ((-\*+0kM 7;; 3 copies of 7 τ double one of them ((- bring the inputs back to the top, take their difference \*+ integer divide by 14, multiply by 7, add 7 0kM maximum of that and 0 ``` [Answer] ## Groovy, 41 ~~37~~ bytes ``` {x,y->[Math.floor((y-x)/14)*7+7,0].max()} ``` This is an unnamed closure. Thanks to `xnor` and `orlp` for the formula and `James holderness` for pointing out a bug. The previous solution used `intdiv()` for integer division but it behaves differently from `//` used in python. [Try it here!](http://ideone.com/cDX7Nh) [Answer] # Haskell, ~~30~~ 24 bytes ``` a#b=max 0$div(b-a)14*7+7 ``` An infix operator taking the number of votes of your preferred candidate first. Uses the same logic as the other answers of rounding with `/14*7+7`. [Answer] # J, 15 bytes ``` 0>.7+7*14<.@%~- ``` Kinda interesting, I was working on a problem and I thought I had a solution but as it turns out I was wrong. Oh well. [Try it online!](https://tio.run/nexus/j#@5@mYGulYGCnZ65trmVoYqPnoFqny1WSWlxSDJIwNDJWMDQwULBWADJMzIG0hYGCCYhvZgRCQHFDE1MFQ0NjE67U5Ix8BQ0dPYU0fYXUxOQMTQWwMf//AwA "J – TIO Nexus") Here's the result: ``` f =: 0>.7+7*14<.@%~- tests =: 123 100 ; 23 47 ; 80 40 ; 62 62 ; 2145 1134 (,. f/ each) tests ┌─────────┬───┐ │123 100 │14 │ ├─────────┼───┤ │23 47 │0 │ ├─────────┼───┤ │80 40 │21 │ ├─────────┼───┤ │62 62 │7 │ ├─────────┼───┤ │2145 1134│511│ └─────────┴───┘ ``` [Answer] # CJam, ~~13~~ ~~12~~ 15 bytes * Saved a byte thanks to Martin Ender. * Added 3 bytes thanks to Martin Ender. * Changed `]` to `[` thanks to ETHproductions. ``` q~\-Ed/m[)7*0e> ``` Blatantly stole orlp and xnor's methods. Input is the two numbers separated by a space: `100 123` Explanation: ``` q~\-Ed/m])7*0e> q~\- e# Input two numbers, swap and subtract them. E e# Push 0xE (15) d/m] e# Float divide and take the floor. )7* e# Increment and multiply by 7. 0e> e# Max of this and 0. ``` [Answer] # Excel VBA, ~~24~~ 17 Bytes Immediates window function that takes input from cells `A1` and `B1` and outputs to the VBE immediates window. ``` ?([A1-B1]\14)*7+7 ``` **Subroutine Version, 43 Bytes** takes input `b, c` as variant\integer and prints to the VBE immediates window ``` Sub a(b,c):Debug.?Int((c-b)/14)*7+7:End Sub ``` [Answer] # [Julia 0.5](http://julialang.org/), 26 bytes ``` v\w=max(fld(w-v,14)*7+7,0) ``` [Try it online!](https://tio.run/nexus/julia5#Lc5BCsIwEIXhtT3FUCgkOoGZJDZuFO/RdiHUQKFGqZp4@5iKu@/Bv3g59ul4u3yEn0eRVES2cut2Dklmf19AREwSpgCiYyJkbQaEzjr8g/BAK1qNrV7BbCxqtvvfIKRBVpvzY5nCy4u6UcxPUCdozLsPdUkiQippuSGraxjzFw "Julia 0.5 – TIO Nexus") [Answer] # PHP, ~~41~~ 39 bytes ``` <?=7*max(0,1+($argv[2]-$argv[1])/14|0); ``` takes input from command line arguments; run with `-r`. ~~7~~ 5 extra bytes just to handle $a>$b :-/ [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` V-U /2+7 f7 w0 ``` [Run it here!](http://ethproductions.github.io/japt/?v=1.4.3&code=Vi1VIC8yKzcgZjcgdzA=&input=MTEzNCwyMTQ1) Thank you ETHproductions for shaving off 3 bytes! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` -14÷>7*0M ``` [Try it online!](https://tio.run/nexus/05ab1e#@69raHJ4u525loHv//@GhsYmXEaGJqYA) **Explanation** ``` - # push difference of inputs 14÷ # integer divide by 14 > # increment 7* # times 7 0 # push 0 M # take max ``` Or a corresponding function with same byte-count operating on a number-pair ``` Î¥14÷>7*M ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@479BSQ5PD2@3MtXz//482NDQ20TEyNDGNBQA) [Answer] # [Dyalog APL](http://dyalog.com/download-zone.htm), 14 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Takes `v1` as right argument and `v2` as left argument. ``` 0⌈7×1+(⌊14÷⍨-) ``` `0 ⌈` the maximum of zero and `7 ×` seven times `1 + (`...`)` one plus...  `⌊` the floor of  `14 ÷⍨` a fourteenth of  `-` the difference (between the arguments) [TryAPL online!](http://tryapl.org/?a=f%u21900%u23087%D71+%28%u230A14%F7%u2368-%29%20%u22C4%20123%20f%20100%20%u22C4%2023%20f%2047%20%u22C4%2080%20f%2040%20%u22C4%2062%20f%2062%20%u22C4%202145%20f%201134&run) [Answer] # Befunge, 19 bytes ``` 777+:&&\-+\/*:0`*.@ ``` [Try it online!](http://befunge.tryitonline.net/#code=Nzc3KzomJlwtK1wvKjowYCouQA&input=MTEzNCAyMTQ1) This relies on a slightly different formula to that used by orlp and xnor, since the Befunge reference interpreter has different rounding rules to Python. Befunge also doesn't have the luxury of a `max` operation. The basic calculation looks like this: ``` x = (v2 - v1 + 14)/14*7 x = x * (x > 0) ``` Examining the code in more detail: ``` 7 Push 7 [7] 77+: Push 14 twice. [7,14,14] && Read v1 and v2 from stdin. [7,14,14,v1,v2] \- Swap the values and subtract. [7,14,14,v2-v1] + Add the 14 that was pushed earlier. [7,14,14+v2-v1] \/ Swap the second 14 to the top and divide. [7,(14+v2-v1)/14] * Multiply by the 7 that was pushed earlier. [7*(14+v2-v1)/14 => x] : Make a copy of the result [x,x] 0` Test if it's greater than 0. [x,x>0] * Multiply this with the original result. [x*(x>0)] .@ Output and exit. ``` [Answer] # [Go](http://golang.org), 36 bytes `func(a,b int)int{return(b-a)/14*7+7}` [Try it online!](https://play.golang.org/p/0eZ1UaF0_K) [Answer] # JavaScript (ES6), 31 bytes ``` (a,b,c=(b-a)/14|0)=>c>0?c*7+7:0 ``` ``` f=(a,b,c=(b-a)/14|0)=>c>0?c*7+7:0 document.write(f(1134,2145)) ``` [Answer] # Java 8, 31 bytes `(a,b)->b<a?0:(a=(b-a)/2)+7-a%7;` This is a lambda expression assignable to `IntBinaryOperator`. a is your candidate's votes, b is your opponent's. java rounds down for division with positive integers, so `+7-a%7` is used to bump up the value to the next multiple of 7. [Answer] ## Ruby, ~~26~~ 27 bytes ``` ->a,b{[(b-a)/14*7+7,0].max} ``` Basically the same as xnor's and orlp's Python solution, ~~with a twist (no need to add 7, because of negative modulo, saves 1 byte in ruby, don't know about python)~~ No twist, the twist was just a bad case of cognitive dissonance. Forget it. Really. :-) [Answer] # Scala, 31 bytes ``` (a,b)=>Math.max((b-a)/14*7+7,0) ``` The ternary version is 2 bytes longer [Answer] # [Noodel](https://tkellehe.github.io/noodel), 16 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html) ``` ⁻÷14ɲL×7⁺7ḋɲl⁺÷2 ``` Pulled equation from [xor](https://codegolf.stackexchange.com/a/106436/52270) and [orlp](https://codegolf.stackexchange.com/a/106435/52270) answers, but since *Noodel* does not have a max capability had to work around that. [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%E2%81%BB%C3%B714%C9%B2L%C3%977%E2%81%BA7%E1%B8%8B%C9%B2l%E2%81%BA%C3%B72&input=40%2C80&run=false) ### How it works ``` ⁻÷14ɲL×7⁺7 # The equation... ⁻ # v2 - v1 ÷14 # Pops off the difference, then pushes on the (v2 - v1)/14 ɲL # Applies lowercase which for numbers is the floor function. ×7 # Multiplies that by seven. ⁺7 # Then increments it by seven. ḋɲl⁺÷2 # To relate with the other answers, this takes the max between the value and zero. ḋ # Duplicates what is on the top of the stack (which is the value just calculated). ɲl # Pops off the number and pushes on the magnitude (abs value). ⁺ # Add the abs to itself producing zero if the number came out negative (which means we are already winning). ÷2 # Divides the result by two, which will either be zero or the correct offset. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` MtS+0[+7*7/-HG14 ``` [Try it here!](http://pyth.herokuapp.com/?code=MtS%2B0%5B%2B7%2A7%2F-HG14%3BghQeQ&input=100%2C123%0A47%2C23%0A40%2C80%0A62%2C62%0A1134%2C2145&test_suite=1&test_suite_input=100%2C123%0A47%2C23%0A40%2C80%0A62%2C62%0A1134%2C2145&debug=0) ]
[Question] [ The program should take a string as input and reverse the consonants in it, while keeping the order of vowels. All the letters will be lowercase, so you don't have to worry about casing. Examples follow. 1. Input: `a test case`. The consonants here are `t,s,t,c,s`. They should come in reversed order, i.e. `s,c,t,s,t` and inserted back into the string to the same positions where the pre-reversed characters were located: `a sect sate`. 2. Input: `well-done`. Output: `nedl-lowe`. 3. Input: `reverse the consonants`. Output: `setenne sne cohtosarvr`. This is the code golf, the shortest solution wins. `Y` should be considered vowel regardless of what it is and not reversed. Anything, as well as numbers, punctuation, quotes, and other symbols (`@#$%^&*(){}[]\|/<>~-_+=``), could potentially appear in the input. [Answer] # Retina, ~~22~~ ~~21~~ ~~20~~ 17 ``` O#^`[b-z-[eiouy]] ``` [Try it online!](http://retina.tryitonline.net/#code=TyNeYFtiLXotW2Vpb3V5XV0&input=cmV2ZXJzZSB0aGUgY29uc29uYW50c18kI0AmIyVeKjMyMQ) 1 byte thanks to Leaky Nun! 4 bytes thanks to Martin! `O` means sort, and `#` means to sort by numeric value. Since none of the matched characters will ever have a numeric value, all letters have the same weight: 0. `^` means to reverse the order of the sorted values, which thanks to stable sorting means the values are reversed. The `-[...]` means to do the setwise difference between the outer character class and this inner class. This is part of .NET and you can read more at the [MSDN](https://msdn.microsoft.com/en-us/library/20bw873z(v=vs.110).aspx#Anchor_13). [Answer] ## Python 2, 86 bytes ``` s='';c=() for x in input():b='{'>x not in'aeiouy'<x;s+=b*'%s'or x;c=(x,)*b+c print s%c ``` Takes input as a string in quotes. Iterates through the input, replacing each consonant with `%s` in `s`. The tuple `c` stores the consonants encountered in reversed order. Then, string formatting replaces the `%s`'s in `s` with the consonants in `c`. Thanks to Sp3000 for the consonant check, which saved 4 bytes over listing the consonants. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Øaḟ“<1Ṛż» e€¢œpżf¢Ṛ$ ``` [Try it online!](http://jelly.tryitonline.net/#code=w5hh4bif4oCcPDHhuZrFvMK7CmXigqzCosWTcMW8ZsKi4bmaJA&input=&args=J3JldmVyc2UgdGhlIGNvbnNvbmFudHMn) ### How it works ``` Øaḟ“<1Ṛż» Helper link. No arguments. Øa Yield the lowercase alphabet/ “<1Ṛż» Decompress that string, yielding "oui aye". ḟ Filter; remove the characters from the right string from the left one. e€¢œpżf¢Ṛ$ Main link. Argument: s (string) ¢ Call the helper link, yielding the string of all consonants. e€ Test each character of s for membership. œp Partition s at members/consonants. $ Combine the three links to the left into a monadic chain. f¢ Filter by presence in the consonant string. Ṛ Reverse the result. ż Zipwith; interleave chunks of non-consonants and reversed consonants. ``` [Answer] # JavaScript ES6, ~~82~~ ~~81~~ ~~80~~ 78 bytes Saved a byte thanks to each of Martin and Leaky Nun, and 2 bytes to Neil! ``` a=>a.replace(r=/(?[_aeiouy])\w/g,e=>[...a].reverse().join``.match(r)[i++],i=0) ``` ## Testing ``` f= a=>a.replace(r=/(?![aeiouy])[a-z]/g,e=>[...a].reverse().join``.match(r)[i++],i=0) ; q.onchange=q.onkeydown=q.onkeyup=function(){ o.innerHTML = ""; o.appendChild(document.createTextNode(f(q.value))); } ``` ``` *{font-family:Consolas,monospace;} ``` ``` <input autocomplete="off" id=q> <div id=o></div> ``` [Answer] # GNU sed, 73 Score includes +1 for the `-r` flag passed to sed. ``` : s/([b-df-hj-np-tv-xz])(.*)([b-df-hj-np-tv-xz])/\u\3\2\u\1/ t s/./\l&/g ``` [Ideone.](https://ideone.com/FYvVMy) Repeatedly switches the first and the last lowercase consonant and converts them to upper case, until there are no more matches. Then convert the whole string back to lowercase. [Answer] # Python 2, 106 bytes ``` s=input() b=[x for x in s if x in'bcdfghjklmnpqrstvwxz']*2 print''.join(x in b and b.pop()or x for x in s) ``` Expects input in `"quotes"`, which I think is allowed. [Answer] ## Pyke, 18 bytes ``` FD~c{IK_#~c{)oR@(s ``` [Try it here!](http://pyke.catbus.co.uk/?code=FD%7Ec%7BIK_%23%7Ec%7B%29oR%40%28s&input=setenne+sne+cohtosarvr&warnings=0) or 16 bytes with the new version: (Change so if for returns all string output and had string input, return string instead of a list) ``` FD~c{IK_#~c{)oR@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=FD%7Ec%7BIK_%23%7Ec%7B%29oR%40&input=setenne+sne+cohtosarvr&warnings=0) `~c` contains the consonants: `bcdfghjklmnpqrstvwxz` ``` F - For i in input: ~c{I - if i in "bcdfghjklmnpqrstvwxz": _#~c{) - filter(reversed(input), <-- in "bcdfghjklmnpqrstvwxz") oR@ - ^[o++] ``` [Answer] # J, 53 bytes ``` C.~[:~.<@~.@/:~"1@(,.|.)@I.@e.&'bcdfghjklmnpqrstvwxz' ``` Maybe the not the best way but I wanted to use `C.` since this can be solved using permutations. ## Usage ``` f =: C.~[:~.<@~.@/:~"1@(,.|.)@I.@e.&'bcdfghjklmnpqrstvwxz' f 'a test case' a sect sate f 'well-done' nedl-lowe f 'reverse the consonants' setenne sne cohtosarvr ``` ## Explanation ``` C.~[:~.<@~.@/:~"1@(,.|.)@I.@e.&'...' Input: s '...' The list of consonants e.&'...' Generate a boolean mask where an index is true if the char at that index in s is a consonant I.@ Get a list of the true indices ( |.)@ Reverse that list (,. )@ Join the original and reversed list as columns /:~"1@ Sort each row of that 2d list ~.@ Take the distinct values in each row <@ Box them [:~. Take the distinct boxes - Now represents the permutation needed to solve this in cycle notation C.~ Permute s according the cycles and return ``` [Answer] # MATL, ~~18~~ ~~22~~ 21 bytes ``` tt2Y211Y2'y'hX-m)P5M( ``` *1 byte saved thanks to @Luis* Unfortunately the longest part of this is getting the list of consonants (`2Y211Y2'y'hX-`). [**Try it Online!**](http://matl.tryitonline.net/#code=dDJZMjExWTIneSdoWC1tKTFNYlB3KA&input=J3dlbGwtZG9uZSc) **Explanation** ``` % Implicitly grab the input tt % Duplicate twice 2Y2 % Grab the pre-defined list of all lower-case letters llY2 % Grab the pre-defined list of lower-case vowels (excluding 'y') 'y'h % Add 'y' to the list of vowels X- % Find the set difference between these two lists (the consonants) m % Create a boolean array the size of the input that is true for all consonants ) % Use this as an index to grab all consonants P % Reverse the order of the consonants 5M % Get the boolean array again ( % Re-assign the flipped consonants with the original consonant locations % Implicitly dislpay the result ``` [Answer] # Perl 5 (58 + 4 = 62 bytes) ``` $_=<>;$r=qr/(?![eiouy])[b-z]/;@a=/$r/g;s/$r/pop@a/ge;print ``` +4 penalty for running with `-0777` flag, which sets Perl to slurp mode to handle newlines correctly. Accepts input through STDIN and prints to STDOUT. ## Explanation ``` $_=<>; Read the input $r=qr/(?![eiouy])[b-z]/; Save the regex; we'll be using it twice @a=/$r/g; Store all the consonants in an array s/$r/pop@a/ge; Replace each consonant with the final value in the array and pop print Output the result ``` [Answer] ## JavaScript (ES6), 72 bytes ``` s=>s.split(/([^\W\d_aeiouy])/).map((c,i,a)=>i&1?a[a.length+~i]:c).join`` ``` Splitting on `/([^\W\d_aeiouy])/` results in the consonants falling in the odd-numbered entries in the array. It then suffices to switch those entries with the equivalent entry counting back from the end of the array and join the result together. [Answer] # JavaScript (ES6), 57 ~~70~~ **Edit** Amazing 20% saving thx @Neil Late to the party, but it seems all javascript people missed something ``` a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r)) ``` *Test* ``` f=a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r)) function test() { var i=I.value O.textContent=f(i) } test() ``` ``` #I { width:90% } ``` ``` <input id=I oninput="test()" value="reverse the consonants."><pre id=O></pre> ``` [Answer] # Perl 5, ~~92~~ ~~68~~ 55 bytes Saved **37** bytes thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)'s help. ;-) ``` $_=<>;@b=@a=/[^\Waeiou]/g;print$_~~@b?pop@a:$_ for/./g ``` A translation of [@Lynn](https://codegolf.stackexchange.com/a/83196/55531) Python solution to Perl. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~53~~ ~~50~~ 47 bytes *-3 bytes from @manatwork. -3 bytes from @Jordan.* ``` ->s{a=s.scan r=/[^\Waeiouy_]/ s.gsub(r){a.pop}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY39XXtiqsTbYv1ipMT8xSKbPWj42LCE1Mz80sr42P1uYr10otLkzSKNKsT9QryC2prIdq2F5SWFCu4RStlpObk5OsolOcX5aQoKsVCZBcsgNAA) [Answer] # Pyth, ~~26~~ ~~25~~ ~~24~~ 23 bytes ``` ~~s.i:Q++\[J-G"aeiouy"\]3\_@J~~ J-G"aeiouy"sm?@dJ@_@JQ~hZ <-- just keeping this because of the @_@ ~~J-G"aeiouy"sm?@dJ@@JQ=tZ~~ sm?@dJ-G"aeiouy"@@JQ=tZ sm|-dJ-G"aeiouy"@@JQ=tZ ``` [Test suite.](http://pyth.herokuapp.com/?code=sm%3F%40dJ-G%22aeiouy%22%40%40JQ%3DtZ&test_suite=1&test_suite_input=%22a+test+case%22%0A%22well-done%22%0A%22reverse+the+consonants%22&debug=0) [Answer] # Julia, 53 bytes ``` !s=s[flipud(i)]=s[i=find(c->'}'>c∉"aeiouy"<"$c",s)] ``` This takes a [character array](http://meta.codegolf.stackexchange.com/a/2216) as input and reverses its consonants in-place. [Try it online!](http://julia.tryitonline.net/#code=IXM9c1tmbGlwdWQoaSldPXNbaT1maW5kKGMtPid9Jz5j4oiJImFlaW91eSI8IiRjIixzKV0KCmZvciBzIGluIChbImEgdGVzdCBjYXNlIi4uLl0sIFsid2VsbC1kb25lIi4uLl0sIFsicmV2ZXJzZSB0aGUgY29uc29uYW50cyIuLi5dKQogICAgIXMKICAgIHByaW50bG4oam9pbihzKSkKZW5k&input=) *Credit goes to @Sp3000 for the lowercase consonant check.* ### How it works `i=find(...,s)` yields all indices of **s** for which the predicate *...* returns **true** and saves them it the variable **i**. `c->'}'>c∉"aeiouy"<"$c"` performs three tests and returns **true** if and only if all are positive. * `'}'>c` checks if the character **c** comes before **{**. * `"aeiou"` checks if the *string* **c** comes after **a**. * `c∉"aeiouy"` verifies that **c** is not a vowel. Finally, `s[i]` yields all consonants and `s[flipud(i)]=s[i]` assigns them to positions in **s** that correspond to the reversed indices in in **i**. [Answer] # Java, 319 305 261 188 bytes Credit to @[Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for helping with this :-) ``` char[]r(char[]s){int i=0,j=0,n=s.length;char[]o=new char[n];for(;i<n;i++){if((s[i]+"").matches("(?![eiouy])[b-z]")){o[j++]=s[i];s[i]=65;}}for(i=0;i<n;i++)if(s[i]==65)s[i]=o[--j];return s;} ``` Old: ``` s(String p){int i=0,j=0;char[]s=p.toCharArray(),o=p.toCharArray();for(;i<s.length;i++){if(((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]")))continue;o[j++]=(s[i]);s[i]='A';}for(i=0;i<s.length;i++)if(s[i]=='A')s[i]=o[--j];return new String(s);} ``` Inspiration taken from [**here**](https://stackoverflow.com/a/5692490/3893016) ❤ ### Ungolfed ``` String s(String p){ int i = 0, j = 0; char[]s=p.toCharArray(),o=p.toCharArray(); for (;i<s.length;i++) { if (((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]"))) continue; o[j++] = (s[i]); // Store the consonant into o s[i] = 'A'; // Put a special character in its place } for (i=0;i<s.length;i++) if (s[i] == 'A') // If special character s[i] = o[--j]; // Put back the consonant in reverse order return new String(s); } ``` [Answer] # R, 120 bytes New answer: ``` az=function(x){ y=strsplit(x, NULL)[[1]] a=regexpr("[bc-df-hj-np-tv-z]", y) y[a==1]=rev(y[a==1]) paste(y, collapse="") } ``` takes a character string as x ``` az("reverse the consonants") [1] "setenne sne cohtosarvr" ``` Old response below (110 bytes) was poor form on my part, which just reversed the consonants: ``` xrev=function(x){y=rev(strsplit(x, NULL)[[1]]) paste(y[is.na(match(y, c("a", "e","i","o","u","y")))], collapse="")} ``` [Answer] ## Python 2, ~~103~~ ~~98~~ 100 bytes ``` import re def r(s):a=re.split("([^\W\d_aeiouy])",s);print''.join(sum(zip(a[::2],a[-2::-2]+['']),())) ``` Port of my JavaScript answer. Edit: Saved 5 bytes thanks to @Dennis♦, of which I promptly had to spend two fixing digits. [Answer] # [s-lang](http://dgrissom.com/s-lang/), ~~17~~ 16 bytes (non-competing) *Saved one byte because s-lang no longer requires last argument bracket* ### [Try it online!](http://dgrissom.com/s-lang/?r[(?![aeiouy])%5Cw) ``` r[(?![aeiouy])\w ``` I started working on a string manipulation golfing language (I have been wanting to do this for a time now), and I thought this would be a fun question to work on it with. ## Explanation: * `r` reverses the string with a given regex character matcher (if no regex argument is given, it will default to `.`) * `[` begins the optional regex argument for `r` * `(?![aeiouy])\w` the regex to match any consonant character excluding y (unfortunately JavaScript doesn't allow character class subtraction) * `]` usually ends optional regex argument for `r`, but we don't need it since it is the last function and last argument [Answer] # APLX, 31 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` (c/t)←⌽t/⍨c←(t←⍞)∊⎕a~'aeoiuy' t ``` `⎕a~'aeoiuy'` lowercase alphabet without vowels `t←⍞` store character input as *t* `c←(`…`)∊` store Boolean "consonant?" as *c* `t/⍨` extract (consonants) from *t* `⌽` reverse `(c/t)←` replace consonants with (the reversed ones) `t` return the modified string [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .āžPIåÏø`Rǝ ``` I/O as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f9f70jj0X0BnoeXHu4/vCMh6Pjc//@jlYqUdJRSgbgMSoP4xSC2ApAoAeIMqASInwzE@UCcB1UEYydC6RKweCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXw4Qmh//WONB7dFxBxeOnh/sM7EoKOz/3vpfM/WilRoSS1uEQhObE4VUlHqTw1J0c3JT8PxC5KLUstKk5VKMlIVUjOzyvOz0vMKylWigUA). **Explanation:** ``` .ā # Enumerate the (implicit) input, pairing each character with its index žP # Push the consonants constant (excluding 'y'): "bcdfghjklmnpqrstvwxz" I # Push the input å # Check for each character if it's in the consonants string Ï # Keep the enumerated pairs at the truthy indices ø # Zip/transpose; swapping rows/columns ` # Dump the list of consonants and list of indices separated to the stack R # Reverse the list of indices ǝ # Insert the consonants at the (reversed) indices in the (implicit) input # (after which the result is output implicitly) ``` [Answer] ## Python 2.7, 144 bytes ``` def f(a):c='bcdfghjklmnpqrstvwxz';b=[x for x in list(a[::-1])if x in c];[b.insert(x,a[x])for x in range(len(a))if a[x]not in c];return''.join(b) ``` This first builds a reversed list of the consonants, then inserts each of the other characters back in at their original index. Un-golfed: ``` s = 'well-done' reverse = list(s[::-1]) consonants = [i for i in reverse if i in 'bcdfghjklmnpqrstvwxz'] for x in range(len(s)): if s[x] not in 'bcdfghjklmnpqrstvwxz': consonants.insert(x,s[x]) print(''.join(consonants)) ``` <https://repl.it/C30O> [Answer] # Mathematica 216 bytes ``` Module[{h,v,i},v=Characters["aeiouy "];h[s_]:=SortBy[Flatten[Thread/@Transpose@{v,#[[All,1]]&/@(StringPosition[s,#]&/@v)},1],Last];i[s_,{a_,n_}]:=StringInsert[s,a,n];Fold[i,StringReverse@StringReplace[#,v->""],h@#]]& ``` [Answer] # Haskell, ~~157~~ 131 bytes ``` k="bcdfghjklmnpqrstvwxz";f c((r:q),s)=if c`elem`k then(q,r:s)else(r:q,c:s);f c("",s)=("",c:s);g s=snd$foldr f(filter(`elem`k)s,"")s ``` **Update** @atlasologist's solution made me realize I only need a list of the consonants instead of pairs (no need to reverse them though since I'm using right fold.) **Ungolfed** ``` consonants = "bcdfghjklmnpqrstvwxz" -- Combining function (right fold, improved) f :: Char -> (String, String) -> (String, String) f c ((r:rest), s) = if c `elem` consonants then (rest, r:s) else (r:rest, c:s) f c ("", s) = ("", c:s) transform :: String -> String transform s = snd $ foldr f (filter (`elem` consonants) s, "") s main = do line <- getLine putStrLn . transform $ line ``` --- **Old** ``` c="bcdfghjklmnpqrstvwxz";n c(a@((f,t):q),s)=if c==f then(q,t:s)else(a,c:s);n c([],s)=([],c:s);g s=let z=filter(`elem`c)s in snd$foldr n(zip (reverse z)z,"")s ``` Creates a list of pairs of consonants, then walks through the string replacing each consonant using said list. A bit primitive, but I wanted to figure this out without looking at the answers first. :) [Answer] ## Matlab, 67 chars For an input `'this is a string of- stuff.'` ``` s=input('','s');si=regexp(s,'[b-df-hj-np-tv-xz]');s(si)=s(flip(si)) ``` produces `s = ffit is a fgnirt os- ssuht.` `si` is the indices of the consonants in the input string. The final statement replaces those characters with the same characters but in reverse order by indexing. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 81 bytes ``` -join(($a=$args|% t*y)|%{if($_-in($c=$a-match'[^\W\d_aeiouy]')){$_=$c[--$i]};$_}) ``` [Try it online!](https://tio.run/##RVBdTsMwDH7vKazJJQlqLgCqxC142EYVpR4t6pIRZxtT27MXbzDwm78f@7MP8UyJOxqGBXdQw7jYj9gHrdHV6NI7TyXkx4uZyrHfaWyscOiFsnuXfafWb5vXTds46uPxslXGjNjU6NfWYr@dn7GZzTIXxYsuQKrSykEmzuAdk6qkY/IZ2GVS5i45SxrbxnAVBGoHO0jIfzrRSSIT5I7Ax8AxuJBZVaCYMoVAwOHKdDmyS6ckTgMTlDDeJiBXgPR1kL3UysXY/MCJ@DhkAR7kEcg3cIX6F7f0@WcyT3f1qpiXbw "PowerShell – Try It Online") Less golfed: ``` $a = $args|% toCharArray $consonants = $a-match'[^\W\d_aeiouy]' $result = $a|%{if($_-in$consonants){$_=$consonants[--$i]};$_} -join($result) ``` --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 88 bytes, -f ``` $i=0;-join($args|% t*y|%{if($_-match'[^\W\d_aeiouy]'){$c=,$_+$c;$_="{$i}";$i++};$_})-f$c ``` [Try it online!](https://tio.run/##RVDNboMwDL7zFBYyCwwi7TyEtLfoYd1QFMxIxZI2TttVwLOztFs3374f25@9d2fyPNA4rthDA9OKpnmq5c4Zm6PyHzxnEB4vczaZPsdWfqqgB/H6vt1su1aRccfLmygm1E2FbYm6xrZJJzRLWqMpyyXipZA96nVJkpc8gVhVLhQE4gBaMYkqIiYdgFUgUdwt5xhKds5eDZa6UY4x67/s6RSTE4SBQDvLziobWFQgmAJZS8D2qgzBsfInHzsLmCGD6TYBuQKkr33cS108HNsf2hMfxxCJh/gP5BuZYv7LSzr8NRXPd3eaLOs3 "PowerShell – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 22 bytes ``` ⌽@(('aeiou'~⍨∘⌊⎕A)∊⍨⊢) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HPXgcNDfXE1Mz8UvW6R70rHnXMeNTT9ahvqqPmo44ukEDXIs3/aY/aJjzq7QMKe/o/6mo@tN74UdtEIC84yBlIhnh4Bv9PU1BPVChJLS5RSE4sTlXnAvLLU3OAVubnQXhFqWWpRcWpCiUZqQrJ@XnF@XmJeSXF6gA "APL (Dyalog Extended) – Try It Online") [Answer] # [Raku](https://raku.org/), ~~48~~ 46 bytes ``` {my$r=/<:L-[aeiouy]>/;S:g[$r]=pop @||=m:g/$r/} ``` [Try it online!](https://tio.run/##HcexCsIwFAXQX7mUYBZLNodqih/g5lhKCfWlCmlSXqIS2n57BM92FmJ3KnPGwUKXdc6Ctbo0t7oz9Arv3LfqfG@mTnCvl7Dgum16biYlWO0lmoxKDNAtVgsx7BVsYEiDRDFhNJHkEfJLztWP4P9h@hBHQnoSxuBj8ManKMsP "Perl 6 – Try It Online") * `$r` is set to a consonant-matching regex. * `@ ||= m:g/$r/` stores the consonants in the input string in the anonymous state array `@`, if it's empty. * `S:g[$r] = pop ...` replaces each consonant with the consonant popped off the end of the array into which all of the consonants were stored initially. [Answer] # q/kdb+, 45 bytes **Solution:** ``` {x[w]:x(|)w:(&)max x=/:.Q.a except"aeiouy";x} ``` **Explanation:** Find indices of the consonants, and replace them with the reversed consonants: ``` {x[w]:x reverse w:where max x=/:.Q.a except "aeiouy";x} / ungolfed { ; } / two-statement lambda .Q.a except "aeiouy" / alphabet (a..z) except vowels x=/: / equals each-right (returns boolean lists where input is each a consonant) max / 'or' the results together where / indices where results are true w: / save in variable w reverse / reverse this list x / index into input at these indices x[w]: / assign values to x at indices w x / return x ``` **Notes:** I had 3 ways to build the consonant list, the one in the solution is slightly better than the alternatives: * `"bcdfghjklmnpqrstvwxz"` for 22 chars (most boring) * `.Q.a _/0 3 6 11 16 19` for 21 chars (kinda cool, drop each index) * `.Q.a except"aeiouy"` for 19 chars (second most boring) ]
[Question] [ The "prime frog" is a strange animal that jumps between integers, until it arrives on 3 or 19... --- Your program should accept an integer `n` as input and output the result of the below algorithm (`3` or `19`). For a given integer `n >= 2`: 1. Let `f` be the position of the frog. It is initially set to `n` 2. if `f = 3` or `f = 19` : the frog stops jumping - halt the program and output `f`. 3. if `f` is prime : the frog jumps to the position `2×f-1`. Go back to step 2. 4. if `f` is composite : let `d` be `f`'s biggest prime divisor. The frog jumps to the position `f-d`. Go back to step 2. **Examples:** An example with `n = 5`: ``` 5 > 9 > 6 > 3 stop ``` The program should output `3`. Another example with `n = 23`: ``` 23 > 45 > 40 > 35 > 28 > 21 > 14 > 7 > 13 > 25 > 20 > 15 > 10 > 5 > 9 > 6 > 3 stop ``` Again, the program should output `3`. **Test cases:** ``` 10 => 3 74 => 19 94 => 3 417 => 3 991 => 19 9983 => 19 ``` You can assume `1 < n < 1000000` (I have checked the program ends for these values). [Answer] # [Python 2](https://docs.python.org/2/), ~~101~~ ~~93~~ ~~92~~ ~~90~~ ~~88~~ ~~87~~ 85 bytes ``` import sympy n=input() while~16&n-3:m=max(sympy.factorint(n));n-=[1-n,m][m<n] print n ``` [Try it online!](https://tio.run/##HY1BDoMgFET3/xTERSNNbaSSKm05iXFhKI0k8iGWprLp1an4kpnNTGZ8DJPDS1LuqWVRFMlY75ZA3tH6CCgN@k8oKXwnM@sfux6wam5W2nEt98r5NargFoOhRErvWMmeVXiyQ28fOIDPCcG0LQPoVSuSj45dYjW0HAQHzloQgm3qms0ywOqdPw "Python 2 – Try It Online") [Answer] # C (gcc), ~~ 87 ~~ 65 bytes ``` i,k;f(n){for(i=n;i>1;)for(k=i;k%--i;);n=~16&n-3?f(n-k?:n+n-1):n;} ``` [Try it online!](https://tio.run/##dctBCsIwEAXQfU8RCpUMdsDQYm2H2Iu4kUhkCB2luCv16jF1q5nd/@@Pw7tzMXIdyGuBxT9mzVaIz4ZgC8EyhQqRCUjs2xx3gs2YthjGQfaCBgahNbK81HRl0VAshUr3nFPldVndLlLWymtzAKD/1LVZ6vPUmi7/1ptfS6K@dmo2XOMH) **Explanation:** ``` i,k; f(n) { for (i=n; i>1;) // Loop until `k` is prime (the largest positive // `i` inequal to `k` that divides `k` is 1). for (k=i; k%--i;); // Find the largest factor `k` n = // Returning like this is undefined behaviour, // but happens to work with gcc. This can be // replaced with `return` at the cost of 4 bytes. ~16&n-3 // If `n` is 3 or 19, this expression equals 0 and // the algorithm halts. Otherwise the function // calls itself to perform the next iteration. ? f(n-k ?: n+n-1) // If `n-k` is non-zero, n is not prime. // In this case call `f` with the value of `n-k`. // (Omitting the second `n-k` between `?` and `:` // is a gcc extension) // Otherwise call `f` with `2*n-1`. : n; // All done, `n` is returned. } ``` **Portable version (72 bytes):** ``` i,k;f(n){for(i=n;i>1;)for(k=i;k%--i;);return~16&n-3?f(n-k?n-k:n+n-1):n;} ``` [Try it online!](https://tio.run/##dcvBCoJAEAbgu0@xCMYOudCgZDqYL9JFrI1ha4rFTmKvvq1dy4E5/PP9M5jh1ss1BM4dWS0w2YfX3ArxEQmW4FomlxnDBOQv48vLG/cbMUUX@8Z1cRvZikFohObAMqp7z6IhmRIV5@njyeo0O58kzZXVuAOg/1SVq1SvU4nV@luNvxZFfe1QLDiHDw) **With more appropriate variable names:** ``` f,r;o(g){for(f=g;f>1;)for(r=f;r%--f;);g=~16&g-3?o(g-r?:g+g-1):g;} ``` [Try it online!](https://tio.run/##dctBCoMwEAXQvacIgiVDDTQotTqkXqSbkjKDixoZuhN79TR222Z2/78/3rD3MVItGDTDSkE0OUa6WoQ9iCOUyhhCQHZvez6waca0NTIOfGRjYWDc4jS/1PM@zRqKtVDpFkkV6bJ63OayVkHbEwD@p67NUp@n1nb5t97@WhL1tUuz4xY/) [Answer] ## [Retina](https://github.com/m-ender/retina), ~~63~~ 62 bytes *Thanks to Neil for saving 1 byte.* ``` {`^(11+)(?<!^\2+(11+))(?=\1+$) ^(?!(11+)\1+$|111$|1{19}$)1 $_ ``` [Try it online!](https://tio.run/##HcixCoAgAEXR/f2FYKAJ0QtBhKKxnxCzoaGlIdqqb7dyuXDusZ7bvuRKpcZA1vlKUZFGq7EXMXSm4NMQaKQGohpFeb9vkl8u@kdqQs5ZTwnMbOEsvIWlg/d8AQ "Retina – Try It Online") Input and output in unary (the test suite uses decimal for convenience). This solution gets incredibly slow for larger inputs. The `9983` test case times out on TIO. ### Explanation Due to the `{`, both stages of the program are simply run in a loop until they no longer affect the string. We alternate between a stage processing composites and a stage processing primes. That lets us avoid an actual conditional (which doesn't really exist in Retina). If the current value is the wrong kind for the stage, the stage simply does nothing. ``` ^(11+)(?<!^\2+(11+))(?=\1+$) ``` This processes composites. We match a potential divisor with `(11+)`, but then we check that it's not composite with `(?<!^\2+(11+))`, so we only consider prime factors. Due to the greediness of `+`, this prioritise the largest factor. Then we check that this potential divisor is an *actual* divisor by trying to match the rest of the string with repetitions of it, `(?=\1+$)`. This divisor is simply removed from the string, which is how you subtract something in unary. ``` ^(?!(11+)\1+$|111$|1{19}$)1 $_ ``` This processes primes, except **3** and **19**. The negative lookahead makes sure that the input is not composite, not **3** and not **19**. Then we match a single `1` and replace it with the entire string. This is a unary form of computing **n - 1 + n**, which of course is **2n-1**. Once we hit **3** or **19**, neither stage can match the string and it will no longer be changed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` _ÆfṂoḤ’$µÐḶṂ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@cFvaw51N@Q93LHnUMFPl0NbDEx7u2AYU@X90z@H2R01r3P//NzTQUTA30VGwNNRRMDE0BzJALEtLC2MA "Jelly – Try It Online") ### How it works ``` _ÆfṂoḤ’$µÐḶṂ Maink link. Argument: n µ Combine the links to the left into a chain. ÐḶ Repeatedly call the chain monadically until the results are no longer unique. Yield the loop, i.e., the first occurrence of the first repeated integer, up to and excluding the repetition. Let's call the argument of the chain k. _Æf Subtract all prime factors of k from k. Ṃ Take the minimum of the differences. This yields 0 iff k is prime. Ḥ’$ Compute 2k-1. o Take the logical OR of the results. The result is now a rotation of either [3, 5, 9, 6] or [19, 37, 73, 145, 116, 87, 58, 29, 57, 38]. Ṃ Take the minimum, yielding either 3 or 19. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` Ω€p57§|o←DṠ-o→p ``` [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/51Y@alpTYGp@aHlN/qO2CS4Pdy7QBTImFfz//9/QgMvchMvShMvE0JzL0tIQiC2MAQ "Husk – Try It Online") ## Explanation ``` Ω€p57§|o←DṠ-o→p Implicit input n. Ω Do this to n until €p57 you get a prime factor of 57 (which are 3 and 19): o→p Take last element of the prime factors of n Ṡ- and subtract it from n, §| or if this gives 0 (so n is prime), o←D double and decrement n. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 ~~66~~ ~~68~~ bytes ``` #//.i:Except[3|19]:>If[PrimeQ@i,2i-1,i-#&@@Last@FactorInteger@i]& ``` * *-1 bytes, thanks to Misha Lavrov!* * *-2 bytes, thanks to Martin!* [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfXy8zXt86U9HWWE0NSBpaWtl5pkUHFGXmpgY6ZOoYZeoa6mTqKqs5OPgkFpc4uCUml@QXeeaVpKanFjlkxqr9ByrNK4lOizY0iI3lgnHMTZA4lsgcE0NzZClLQxSehXFs7H8A "Wolfram Language (Mathematica) – Try It Online") Inspired by [the tip](https://codegolf.stackexchange.com/a/106652/59292). Basically, it just recreates the algorithm. `//.` is `RepeatedReplace` and `/;` is `Condition`. So, the code will replace `i_` (a single quantity) with `If[PrimeQ@i,2i-1,i-#&@@Last@FactorInteger@i]`, until `i!=3&&!=19` evaluates `True`. Benchmark: [![benchmark](https://i.stack.imgur.com/tyb5wm.png)](https://i.stack.imgur.com/tyb5wm.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~18~~ 17 bytes ``` [ÐƵηfså#pi·<ëDfθ- ``` [Try it online!](https://tio.run/##ASQA2/8wNWFiMWX//1vDkMa1zrdmc8OlI3Bpwrc8w6tEZs64Lf//MjM "05AB1E – Try It Online") **Explanation** ``` [ # # loop until Ð så # a copy of the current value is contained in Ƶηf # the unique prime factors of 171 pi # if the current value is prime ·< # double and decrement ë - # else subtract Dfθ # the largest prime factor of a copy of the current value ``` [Answer] # JavaScript (ES6), ~~73~~ ~~71~~ 69 bytes ``` f=n=>57%n?f(n-(g=(k,d=1)=>++d<k?k%d?g(k,d):g(k/d):d<n?d:1-n)(n)):n%38 ``` ### Test cases ``` f=n=>57%n?f(n-(g=(k,d=1)=>++d<k?k%d?g(k,d):g(k/d):d<n?d:1-n)(n)):n%38 console.log('10 -> ' + f(10)) // 3 console.log('74 -> ' + f(74)) // 19 console.log('94 -> ' + f(94)) // 3 console.log('417 -> ' + f(417)) // 3 console.log('991 -> ' + f(991)) // 19 console.log('9983 -> ' + f(9983)) // 19 ``` ### Formatted and commented ``` f = n => // given n 57 % n ? // if n is neither 3, 19 or 57 (and assuming that n is > 1): f( // do a recursive call to f() with: n - // n minus (g = (k, d = 1) => // the result of the recursive function g(): ++d < k ? // increment d; if d is less than k: k % d ? // if d is not a divisor of k: g(k, d) // recursive call to g() with k and d unchanged : // else: g(k / d) // recursive call to g() with k = k / d, d = 1 : // else, d is now the highest prime divisor of n: d < n ? // if d is less than n: d // n is composite: return d, which results in f(n - d) : // else: 1 - n // n is prime: return 1 - n, which results in f(2n - 1) )(n) // initial call to g() ) // end of recursive call to f() : // else: n % 38 // return n % 38 (gives 19 as expected if n = 57) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 19 bytes *-4 bytes from [miles](https://codegolf.stackexchange.com/users/6710/miles).* Still longer than 05AB1E, though. ``` Ḥ’$_Æf$ÆP?Ṫµḟ3,19$¿ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bik4oCZJF/DhmYkw4ZQP@G5qsK14bifMywxOSTCv////zIz) [Answer] # [Python 2](https://docs.python.org/2/), ~~110~~ ~~105~~ ~~103~~ 101 bytes *-2 bytes thanks to @Lynn* ``` f=lambda n,i=2,k=0:i/n and(n*(n&~16==3)or f((2*i-1,k-i)[k>0]))or n%i and f(n,i+1,k)or f(n/i,2,k or n) ``` [Try it online!](https://tio.run/##JY3PDoIwDMbve4peNJtO2SYRIZkvYjjgv9gghWzzwMVXxy42@dqm/fXrNKfXSG7BYRpDgjhHwdrHRwqP2ydEHOmNAybpDIdanv7dDdd7B6TRO91702BB0NFd0kbS@muP3h/UGOAppdvgzup@h@rSn02r8phWmGles8OWt3@WCtRsB5ngL1wQkOBijYaq1FCzSltxU9ucToe2EQBTQEp8jmqxRlSlqEvBmGBKZOgH "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~116~~ ~~112~~ 105 bytes ``` f=lambda n,i=2:i/n*i or n%i and f(n,i+1)or f(n/i) n=input() while~16&n-3:n=[2*n-1,n-f(n)][f(n)<n] print n ``` [Try it online!](https://tio.run/##FY3BCoMwGIPv/1MUYcM6xVVFp6xPIh6cVvzBpSKObZe9elcPCSEJfOt3ny0yN9jR6CAI3KSX/vkYe4GYddZwioiF3QROLHqMYgr9cFHSVz6mLAmasb72UNJ75sX8VHlGkjfQbRYhUTESf5Rde/gdHa0bYxdwnkbmYwZxsKPSqStVBdUFFaqiulZet/wP "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~22~~ 21 bytes *Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for removing 1 byte!* ``` `tZp?Eq}tYfX>-]tI19h- ``` [Try it online!](https://tio.run/##y00syfn/P6EkqsDetbC2JDItwk43tsTT0DJD9/9/S0sLYwA) Or [verify all test cases](https://tio.run/##y00syfmf8D@hJKrA3rWwtiQyLcJON7bE09AyQ/d/rEvIf0MDLnMTLksTLhNDcy5LS0MgtjAGAA). ### Explanation ``` ` % Do...while t % Duplicate. Takes (implicit) input the first time Zp % Is it prime? ? % If so Eq % Times 2, minus 1 } % Else t % Duplicate YfX>- % Prime divisors, maximum, subtract ] % End t % Duplicate I19h % Push array [3 19] - % Subtract, element-wise. The result is truthy if and only if % it doesn't contain any zero % End (implicit). Next iteraton if top of the stack is truthy % Display (implicit) ``` [Answer] # Haskell - 154 bytes ``` f 3=3 f 19=19 f n |(c==[1])=f$2*n-1 |True=f$n-head c where c=z n;v b=reverse[x|x<-[1..(b-1)],b`rem`x==0];z j=case v j of[1]->[1];s->filter((==[1]).v)$s ``` Probably missing some golf tricks here, this is my first attempt at haskell golf. [Answer] # [Neim](https://github.com/okx-code/Neim), ~~17~~ 16 bytes ``` ͻY𝐏𝕚÷D𝐌Ξᚫ<#D𝐏𝐠𝕊 ``` Explanation: ``` ͻ Start infinite loop D Duplicate Y Push 57 𝐏 Prime factors: [3 19] 𝕚 If the second-to-top of stack is in the list ÷ Break the loop D Duplicate 𝐌Ξᚫ< If prime, double and decrement #D𝐏𝐠𝕊 Otherwise, subtract the largest prime factor ``` [Try it online!](https://tio.run/##y0vNzP3//@xul8gPcyf0f5g7ddbh7S5AZs@5eQ9nrbZRdoEIT1gAlOr6/9/S0sIYAA "Neim – Try It Online") [Answer] # [R](https://www.r-project.org/) + [numbers](https://cran.r-project.org/web/packages/numbers/numbers.pdf), ~~102~~ 99 bytes ``` function(n){while(!n%in%c(3,19))n="if"(isPrime(n),2*n-1,n-max(primeFactors(n))) n} library(numbers) ``` [Try it online!](https://tio.run/##FYpBCsIwEADv/YWFwq5swNhCDejVs19IQ4ML7TYkLVrEt8d4mMvMxOyvKvtN3MqLgODn9eRphIM0LI2DlrRBlFvNvgZOj8jzWC46H0VpEjXbN4S/vFu3LjGVhljJt5p4iDbuINs8jDFhTjaEaQcH@kR9R6ajTvdkjC5cWiSP@Qc "R – Try It Online") R isn't known for short built-ins, and even the packages follow suit! [Answer] # Java 8, ~~140~~ ~~135~~ ~~134~~ 94 bytes ``` n->{for(int f,t,m=0;57%n>0;n=f>n?2*n-1:n-m)for(t=n,f=1;f++<t;)for(;t%f<1;t/=m=f);return n%38;} ``` -5 bytes converting recursive Java 7 method to Java 8 lambda with loop. -1 byte implicit thanks to [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/145759/52210) by changing `n!=3&n!=19` and `return n;` to `57%n>0` and `return n%38;`. ~~I think it should be possible to somehow combine the two loops and check if `n` is a prime, and get it's largest prime factor at the same time, but I can't figure it out (yet). So this will be the initial version for now.~~ -40 whopping bytes thanks to @Nevay, by doing what I couldn't do: combining the loops to check for primes and largest prime factor at once. **Explanation:** [Try it here](https://tio.run/##dZLNboJAEMfvPsWExAQKWCkapevaJ6gXj7WH7brbYGEgMJg2hmenC0pqsQWyyfzmk//sQRyFn@UKD/uPRiaiLOFZxHgaAcRIqtBCKti0ZgdA2u2JDjOkHpmjJEGxhA0gcGjQX590VnRB2iMv5VM2X4xxPWXI9RqfHu7QDx7RT502jDh6mgdMu@6KWIcYjfUqYHTPU64dViiqCgQch0tWN6ztmFdviel4aXzM4j2kZmR7S0WM7y@vIJzzvNuvklQ6ySqa5MZFCdpWjHlFO/Oqz1xJUvsdCUmVSFpGqiQoKylVWeoqsbq//LPOxdMm2HMPwms7mA7AQzgAi5kHQXRNotkgZBYsBiSKgpusaBnesvbpc2uAUfeZwY@C1C/VuvhunYXXLbfXxPnZ91kcs1qcSBuL/xXBwrVaDS23r9Lb5xK9Zfduzs8O53KX6uYb) (executes even `999999` in under 1 second). ``` n->{ // Method with integer as both parameter and return-type for(int f, // Flag-integer t, // Temp-integer m=1; // Max prime factor integer, starting at 0 57%n>0; // Loop (1) as long as `n` is not 3, not 19 and not 57: n=f>n? // After every iteration: if `f` is larger than `n`: 2*n-1 // Change `n` to `2*n-1` : // Else: n-m) // Change `n` to `n-m` for(t=n, // Reset `t` to `n` f=1; // Reset `f` to 1 f++<t;) // Inner loop (2) from 2 to `t` (inclusive) for(;t%f<1; // Inner loop (3) as long as `t` is divisible by `f` t/=m=f; // Set `m` to `f`, and set `t` to `t/f` ); // End of inner loop (3) // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return n%38; // Return `n%38`, which is now either 3 or 19 } // End of method ``` [Answer] # Bash, 73 bytes ``` ((57%$1))&&$0 $[(x=$1-`factor $1|sed 's/.* //'`)?x:2*$1-1]||echo $[$1%38] ``` [Try it online!](https://tio.run/##S0oszvifb6uUBKQVVAyUFJQV0jIrFNLyi4A8hZJ8hfL8omyF/DyFEE///xoapuaqKoaammpqKvkKKtEaFbYqhroJaYnJJSD1hjXFqSkK6sX6eloK@vrqCZr2FVZGWkAVhrE1NanJGSAtKoaqxhax////t7S0MAYA) Modified slightly to work on TIO. Recursively calls its own script file using `$0`, ~~which does not work in TIO because it must be ran as `./filename.sh`~~. Accepts input as command-line argument. Uses the same modulus trick as [@Arnauld's JS answer](https://codegolf.stackexchange.com/a/145759/69583). ## Test Cases ``` $ for t in 5 23 10 74 94 417 991 9983;{ echo -n "$t -> "; ./prime-frog.sh $t; } 5 -> 3 23 -> 3 10 -> 3 74 -> 19 94 -> 3 417 -> 3 991 -> 19 9983 -> 19 ``` [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` f=lambda n:n*(n&-17==3)or f(n-max(k*all(n%k<k%j for j in range(2,k))for k in range(n+1))or 2*n-1) ``` [Try it online!](https://tio.run/##RY7BDoIwDIbP@hS9IC0O44AEWZzvMqMoDAohO2gIzz63k4f@ab4vbf75694Tl963ejDj/WGAFWfIh1zWWpc0LdAi56P5oM3MMCAn9mqTHtpgeugYFsOvJxbCEkVm/4yPkuKDIuNcko@Wo5VnAXUloAlTyTosjYxxKdV@Ny8dO0xXVW2gb7CqYktP4XQ0DlnEMkTkfw "Python 3 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 bytes ``` .W!/P57H?P_ZtyZ-ZeP ``` **[Verify all the test cases!](https://pyth.herokuapp.com/?code=.W%21%2FP57H%3FP_ZtyZ-ZeP&test_suite=1&test_suite_input=10%0A74%0A94%0A417%0A991%0A9983&debug=0)** The [Husk answer](https://codegolf.stackexchange.com/a/145755/59487) inspired me to save 2 bytes (`,3 19` to `P57`). ## How this works ``` .W!/P57H?P_ZtyZ-ZeP - Full program. .W - Functional while. While A(value) is truthy, value = B(value). Returns the last value. P57 - The prime factors of 57 ([3, 19]). / H - Count the occurences of the current value. ! - Logical NOT. 0 -> Truthy, anything else -> Falsy. ?P_Z - If the current value is prime, then: tyZ - Double the current value, decrement. -ZeP - Else, Subtract the maximal prime factor of the current value from itself. - Print implicitly. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~150~~ 126 bytes ``` for($n="$args";57%$n){$a=$n;$d=for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}};if($n-in$d){$n+=$n-1}else{$n-=$d[-1]}}$n%38 ``` [Try it online!](https://tio.run/##LcxBCsMgFATQszSMoAQpNpQmyD9J6ULQpIL8FC10ETy7ldLlzDzmtX9CLs@QUmvrniWYBri8lcFebwKsDjgCW3j6zZEuFk5vb6OOuMqThBOIqrPY@zMh1pBK6HEca7WdgHVk@C547E/a/AFrgr9r86gVLKa5tbYs8/QF "PowerShell – Try It Online") (warning: slow for bigger numbers) Iterative method. PowerShell doesn't have any prime factorization built-ins, so this borrows code from my answer on [Prime Factors Buddies](https://codegolf.stackexchange.com/a/94323/42963). First is our `for` loop. The setup sets `$n` to be the input value, and the conditional keeps the loop going so long as `57%$n` is non-zero (thanks to [Arnauld](https://codegolf.stackexchange.com/a/145759/42963) for that trick). Inside the loop we first get a list of prime factors of `$a` (set to `$n`). This is the code borrowed from Prime Factors Buddies. If the input `$a` is already prime, this will return just `$a` (important later). That (potentially just `$a`) gets stored into `$d`. Next is an `if`/`else` conditional. For the `if` part, we check whether `$n` is `-in` `$d`. If it is, that means that `$n` is prime, so we take `$n=2*$n-1` or `$n+=$n-1`. Otherwise, it's composite, so we need to find the largest prime factor. That means we need to take the last one `[-1]` of `$d` and subtract that from `$n` with `$n-=`. This works because we're looping up from `2` and thus the last element of `$d` is already going to be the largest. Once we're done looping, we just place `$n%38` (again, thanks Arnauld) on the pipeline and output is implicit. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~113~~ ~~90~~ 59 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) ``` ⎕CY 'dfns' g←{1pco ⍵:f(2×⍵)-1⋄f⍵-⊃⌽3pco ⍵} f←{⍵∊3 19:⍵⋄g ⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBI/6pjpHKqinpOUVq3OlP2qbUG1YkJyv8Kh3q1WahtHh6UCGpq7ho@6WNCBL91FX86OevcZQFbVcaSANQNajji5jBUNLKxCzuyUdLAkA "APL (Dyalog Unicode) – Try It Online") ~~TIO works with values up to ~3200. Tested on my PC for the last test case. To test on TIO, just add `f value` to the bottom of the code.~~ Doesn't apply anymore, thanks to @Adám for pointing out that my primality checking algorithm was really bad and supplying me with a replacement; also for the 23 byte save. Edited to fix byte count. ### How it works ``` ⎕CY 'dfns' # Imports every Defined Function, which is shorter than importing just the function I used (pco). g←{1pco ⍵:f(2×⍵)-1⋄f⍵-⊃⌽3pco ⍵} g← # define g as 1pco ⍵: # if the argument ⍵ is prime f(2×⍵)-1 # Call f over 2×⍵-1 ⋄f # else, call f over ⊃ # the first element of the 3pco ⍵ # list of prime factors of ⍵ ⌽ # reversed f←{⍵∊3 19:⍵⋄g ⍵} f← # Define f as ⍵ : # if the argument ⍵ ∊ # is in 3 19 # the list [3, 19] ⍵ # return the argument ⍵ ⋄ # else g ⍵ # call g over the argument ⍵ ``` [Answer] # Axiom, 93 bytes ``` h(n)==(repeat(n=3 or n=19 or n<2=>break;prime? n=>(n:=2*n-1);n:=n-last(factors(n)).factor);n) ``` test: ``` (4) -> [[i,h(i)] for i in [10,74,94,417,991,9983]] (4) [[10,3],[74,19],[94,3],[417,3],[991,19],[9983,19]] Type: List List Integer ``` There would be 68 bytes function ``` q x==(n<4=>3;n=19=>n;prime? n=>q(2*n-1);q(n-last(factors n).factor)) ``` but for n=57991 (if I remember well) it goes out the stack space reserved. [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes Port from [TFeld's answer](https://codegolf.stackexchange.com/a/145748/66418) without external libs. ``` n=input() while~16&n-3: f=n;i=2 while i<f: if f%i:i+=1 else:f/=i n-=[1-n,f][f<n] print n ``` [Try it online!](https://tio.run/##JU67CsJAEKyzX7EEFEWDnglqTq@MrY1dsJC4hwuyOS4nxsZfj6cWU8wM83CvcGtlNTTtlUyapoMYFvcIkyk8b3ynt1qPJcs1oDWyY7MC/OnIe6shYYt2xJpnRkFC9460XRgGlMzUKpO5Pdd2L2dwniWgDHEBIPhXjP5rTv5BkSTUU4PfE0B9Qy5gdTxU3rc@mu7SdYNa5rApoCygUBsoSxWxzT8 "Python 2 – Try It Online") ]
[Question] [ Related: [Multiply Quaternions](https://codegolf.stackexchange.com/q/36928/78410) ## Challenge Given a string made of `ijk`, interpret it as the product of imaginary units of [**quaternion**](https://en.wikipedia.org/wiki/Quaternion) and simplify it into one of the eight possible values `1`, `-1`, `i`, `-i`, `j`, `-j`, `k`, `-k`. The evaluation rules are as follows: $$ ii = jj = kk = -1 \\ ij = k, \quad jk = i, \quad ki = j \\ ji = -k, \quad kj = -i, \quad ik = -j $$ The multiplication of quaternions is associative but not commutative. This means that you may do the simplification in any order, but you cannot reorder the items. For the I/O format, function parameter and return from a function should be done as a string (list of chars or list of codepoints is also OK). You may assume the input is not empty. You may output any amount of leading and trailing whitespace (spaces, tabs, newlines). ## Test cases ``` i -> i j -> j k -> k ij -> k ji -> -k kk -> -1 ijkj -> -j iikkkkkjj -> k kikjkikjk -> -k kjijkjikijkjiki -> 1 jikjjikjikjikjjjj -> j ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ ~~29~~ 27 bytes ``` ≔⁰θFS≔⁺×θX³℅ι℅ιθ‹³﹪θ⁸§1ijkθ ``` [Try it online!](https://tio.run/##VYxBCsIwFET3niJ09T9EUNwIXXVZUAzoBUIT629jYpNUvX1MsC7cDDzmzXQ36TsnTUpNCNRb2HA2Yb26Os@gtY85nqMn2wMiWwxh5gAXuusAE2fCvbSHHWcnr8hKA4SIf/Q9FPklwkGHUOSjU7NxZb/P@q9tYmuVfkO1pWGsyg7rlMYh00Djkmn9NB8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The values are encoded to integers equivalent to `0..7` (modulo `8`) in the order `1`, `i`, `j`, `k`, `-1`, `-i`, `-j`, `-k`. The multiplications by `i`, `j` and `k` have the following effect on the integer: * Multiplying by `i` is equivalent to tripling the integer and adding `1`. * Multiplying by `j` is equivalent to adding `2` to the integer. * Multiplying by `k` is equivalent to tripling the integer and adding `3`. Edit: Thanks to @NickKennedy for saving 3 bytes by pointing out that the ordinals of `i`, `j` and `k` are equivalent (mod 8) to `1`, `2` and `3` respectively. This means that the integer needs to be tripled if the ordinal is odd, and then the ordinal can be added to it. Edit: Furthermore, tripling the integer (mod 8) if the ordinal is odd is equivalent to multiplying the integer by 3 to the power of the ordinal, for a further 2 byte saving. ``` ≔⁰θ ``` Start with `0`. ``` FS ``` Loop over the input... ``` ≔⁺×θX³℅ι℅ιθ ``` ... multiply the current value by 3 to the power of the ordinal, then add the ordinal. ``` ‹³﹪θ⁸ ``` Output a `-` sign if the result (mod `8`) is greater than 3. (There are other ways to express this in Charcoal but sadly I couldn't do better than 5 bytes.) ``` §1ijkθ ``` Output `1`, `i`, `j`, or `k`, depending on the result (mod `4`). [Answer] # [sed -r 4.2.2](https://www.gnu.org/software/sed/), 71 Using @Neil's [Retina 0.8.2](https://codegolf.stackexchange.com/a/226318/11259) approach: ``` : s/k/ij/ s/ii|jj/-/ s/ji/-ij/ s/(\w)-/-\1/ s/--// t s/ij/k/ s/^-?$/&1/ ``` [Try it online!](https://tio.run/##LUuxDgJRCNv5DmN0IM2tLv7IxUmHlsQzvktc/HYR9BqghZZxu2aebCBAoZh8S/CWIvx/PMyvo8PnqRd3wNaOqr6KL37eYT8hkyYLo0y0aBEyMhoqh6FfW6gtxjYrXj5jq8Jneaxc7iP9@QU "sed 4.2.2 – Try It Online") --- Previous answer: # [sed -r 4.2.2](https://www.gnu.org/software/sed/), 97 Saved 3 bytes thanks to @FryAmTheEggman. ``` : s/(\w)\1/-/ s/(\w)-/-\1/ s/--// s/ij/k/ s/jk/i/ s/ki/j/ s/ji/-k/ s/kj/-i/ s/ik/-j/ t s/^-?$/&1/ ``` [Try it online!](https://tio.run/##LYrBCgJBDEPv/Q4RPZSwVy/@yOJJD2lgV5wF/96xHSa0TcJrez17v1nDZf1e1wWOmR2eNYs7yhhQeQgsFxGjEz6AAj4IBU90ZHz4/YTzgt5pYTKGBU0VFEaqFEmoGGuKQtS8@Z6cmpP67e@D@9a6f/4 "sed 4.2.2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 82 bytes ``` e=>e.map(q=>p=+p?q:o[i=o.search(p+q),s^=i<5,i+2],p=s=1,o=' 1jikjijkij')&&'- '[s]+p ``` [Try it online!](https://tio.run/##TVBBbsMgELzzir0kgGwjuVIvTdc99RWuq1guaXdJAjFWFanq211DnaoIGGlmltmF@88@DiOFqTr7NzsfcLbYWHPqg7pgE7AIT5cH3xJ6E20/Dh8qFBddxlekx/uSiruuDBixLj1KqJkcEztiqbdbWYFsY1eEebJxGvpoIyDsBUHVAAlOwMIlcIL4FzmrlRMuC1W9KC5rFQsilxavXrek5XMrSdlLC@ud2FqklnJbeTOvsXszjXRS2sRwpEnJl7PUeeorYAPXG53MUuud@BvBHPz43C//oFoqwXc6@b8EwODP0R@tOfp3JTceNlGWcFCtMYY6vcYBIvh/9PLyt97NPw "JavaScript (Node.js) – Try It Online") Input array of chars, output string. --- # [JavaScript (Node.js)](https://nodejs.org), 66 bytes ``` e=>e.map(q=>p=p<99?q:(s^=(~p+q)%3&&36,p^=q)?104|p:49,p=s=9)&&[s,p] ``` [Try it online!](https://tio.run/##PVDLbsMgELzzFVxig2qjRokqOSmOqqhf0GOaKBbFyUJisEFVpD5@3QWXdgU70s7sLItq3hsnBrC@7MybHFs@Sl5Ldm0s6XltuX2sqk2/Iu7Aybe96@lskWWLh8IeeE838/vlp10tq8JyxyuaZTtX2P3opfOicdJhjo8IcFljQCqCQjqCRqB@UU1sqZGeiHIeGD1xpUIAOoZKWg1aTfevRUUt6JRjdR4Mgx50OkqlsUfmB7gSypy9gCf5a5fTacsb5jW@/ZWjOKd0jf5XYK0ZnhtxJmQHBZZ7GvUfCGNhOuexCSu@BOvuxNrBXLfnZtiGjySMsZbsQob9NEbENsFE4p88oSHSo9bJzlwku5gTyWcGz1xeRHeOZcAg@aLr8Qc "JavaScript (Node.js) – Try It Online") Input array of codepoints, output array of codepoints. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes ``` 3{`\bii - ij k \bik -j }T`ijk`jki -- \B$ 1 ``` [Try it online!](https://tio.run/##LYoxCoBAEAP7vEPB5grxBzZ@wNLiFCySgIXYiW8/98SwGwIz537xWPvSdlMuw52XjUQCBSO2kYRnzpSzHCQBy9igL4WoTogiXIcF0jUKQut7WBXRf4cenP4v8gI "Retina – Try It Online") Link includes test cases. Explanation: ``` 3{` ``` Loop three times. ``` \bii - ij k \bik -j ``` Perform some simplifications. ``` T`ijk`jki ``` Rotate by 120° along the `i=j=k` axis. ``` }` ``` Repeat the above loop until the output converges. (Since the inner loop iterates three times, the rotations will cancel out.) ``` -- \B$ 1 ``` Tidy up the result. [Answer] # JavaScript (ES6), ~~60 55 53~~ 52 bytes Expects an array of ASCII codes. Returns a string. This is based on [@Neil's excellent insight](https://codegolf.stackexchange.com/a/226315/58563). ``` a=>["-"[a.map(y=>x+=y%2*2*x+y,x=4),x&4]]+"1ijk"[x&3] ``` [Try it online!](https://tio.run/##nZLbDoIwDIbvfQrSRMNBRlBux4WvQbhYlJmuwAioGU8/DzFqNGTEP23vvvZvUyUuYtj32J3iVh8qK7kVPC8ghkKwRnT@yHMT8XG5CTehica14VmwNqusLCNIUREUZrUt7V63g64rVuujL/2CMbY7S1n1TPa68QHB@1JQBoGXJJ6HCwerplnlYmmaJReLP4Pnswqn2NjJEk2yqdszfbl@sc5bIdJd6t1g/r6EpB4Jf@yr7q6RnhU@5qbuO9/8Ij3jJnj/hr0C "JavaScript (Node.js) – Try It Online") ### How? According to Neil: > > at each step if the input is `i` or `k` then the integer is tripled and > incremented, and if the input is `j` or `k` then 2 is added to it > > > In JS at least, it is shorter to express the above as follows: $$x \gets x + (y \bmod 2)\times 2\times x+(y \bmod 4)$$ where \$x\$ is the sum and \$y\$ is the ASCII code of the next input character. [@NickKennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) noticed that it may actually be optimized one step further (thanks to Neil as well for pointing that out): $$x \gets x + (y \bmod 2)\times 2\times x+y$$ We end up with the following encoding for \$x\$: ``` … x x 2 1 0 \___/ | \_/ | | | | | +---> 00 = 1, 01 = i, 10 = j, 11 = k | +------> sign bit, set for positive | (which is why we start with x = 4) +----------> upper bits are ignored ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~72 67 66~~ 64 bytes ``` ->s{w=k=0;s.bytes{|x|k>0&&w^=13[k+2-x&3];k^=x&3};?-*w+"1ijk"[k]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664utw229bAulgvqbIktbi6pqIm285ATa08ztbQODpb20i3Qs041jo7zhZI11rb62qVaysZZmZlK0Vnx9b@L1BIi1bKzFSK5YKwsuCsbBgrCy6bBZfNgstmw2Wz4bLZSHqzs0AYgrJABvwHAA "Ruby – Try It Online") Thanks dingledooper for -2 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~40~~ 37 bytes ``` ΔJ2ôεDg<iËi¼õë…ijkyмyC3%<½]J1«н¾É'-×ì ``` [Try it online!](https://tio.run/##AU4Asf9vc2FiaWX//86USjLDtM61RGc8acOLacK8w7XDq@KApmlqa3nQvHlDMyU8wr1dSjHCq9C9wr7DiSctw5fDrP//aWprav8tLW5vLWxhenk "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##VY09CsJAEIX7OcUUilUMarvY@FPYeAKL1Sw6O5IVE5BY2Yqt4A1stDRdtMj24hm8SNxoGh/zB9883lRGi2ImY@zizASqaSI5JYVC4GA8LJ7HUdvenml/LsgeKM9sai/v3Zk0J68s6XXqIr9PRq388rrnD7tvePZkr4WzAmwWtFS4VjJACiEwgOibVez/Eqr1F@p5ofGWcpu4eIG1rytUBYEGBtKgCbg8WAMRl9KOEOtvA@sSEVfTvTtOXJUTfAA) ``` Δ # until the output doesn't change: J2ô # split the string into groups of 2 # (last one might be a single character) ε # for each group y: Dg<i # if the length of y is 2: Ëi # if all characters are the same: ¼õ # increment the '-'-counter and return empty string ë # else: …ijkyм # remove the two characters from "ijk" yC3%<½ # increment the '-'-counter if y converted from binary ... # ... is equal to 2 modulo 3 ] # close all loops and if statements J1« # append a 1 н # take the first character ¾É'-×ì # if the '-'-counter is odd, prepend a '-' ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~44~~ 43 bytes ``` Δ…ijk©Dâ•KĀ ‰9Ï•„ -®«ÅвJ#:Σ'-Ê]„--KD'-såi1« ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JRHDcsys7IPrXQ5vOhRwyLvIw0Kjxo2WB7uB3IeNcxT0D207tDqw60XNnkpW51brK57uCsWKKyr6@2irlt8eGmm4aHV//9nZwGNyMrMhpIA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##XU47CsJAEO3nFAMKVqtYKsFKLUzhCSyiWcjsiCtGsN3GxsbG2iKiIIKIR8haB8@Qi8SNpvIx//eYmWkQR8UsWGMPZzqUTR0HU5LoeTgYD4vskJsLKU6vfZvkJvFfBnPz6Ni9a3JzRJHe05vdvp@jWjc7NYTdTdxYCL/fELE9Uzu9FW4RwCaiucSVDEKkBYQaEFt6uW797lXp7wUP61/tQhYEChhIgSLgsmAFRFxCOYZYfR1YlRRxFZ3c8cSVOcAH) ``` Δ # Until the output doesn't change: …ijk©Dâ # = ii ij ik ji jj jk ki kj kk •KĀ ‰9Ï•" -®«ÅвJ# # = - k -j -k - i j -i - : # Replace Σ'-Ê # Sort "-" to the front „--K # Remove all non-overlapping occurences of "--" '-såi # If the result is a substring of "-": 1« # Append a 1 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 44 bytes ``` k ij ii|jj - ji -ij -- }`.- -$&- ij k \B$ 1 ``` [Try it online!](https://tio.run/##LUwxDoBACNv7DjUumPgFFz/hcA4OpYmDcdS3n2CugYbSwnXcPPfaj@NaqkAH@bjD4ISFNAPeMhmsGyx9YVs6zLUSKWITSeWgPFYiHojyvyFPi2oc8fCpVoEP "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` k ij ``` Replace `k` with `ij` as an interim measure. ``` ii|jj - ``` Substitute `-1` for `ii` and `jj`. ``` ji -ij ``` Substitute `-ij` for `ji`. ``` -- .- -$&- ``` Propagate `-`s to the left. ``` }` ``` Repeat until no more changes can be made. ``` ij k ``` Convert `ij` back into `k`. ``` \B$ 1 ``` Output `1` if there is no `i`, `j` or `k`. My original idea unfortunately turned out to be as long as the naïve approach which has since been golfed anyway: ``` ^(..)+$ -ijk$& +`^(.*)((\w)\3|(j|k)(i|j)) -$1$5$4 ijk - -- \B$ 1 ``` [Try it online!](https://tio.run/##LYrBCgJBDEPv@Y4qrcssLOoPeNmfGGQ9eGgDHkTwMv8@dmRDUkpe3s@Pvx79oOvW7zrPNgmKB@WIacviZKr1a/XcNBpNvYUZiixylQtyiIJSgHoTLL07Aswa4eB4GHDnUCRxxj9gDOTcb86TO3enfg "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^(..)+$ -ijk$& ``` Prepend `-ijk` if there are an even number of letters, because the next stage doesn't affect the parity and we want to end up with a single letter if possible. ``` +`^(.*)((\w)\3|(j|k)(i|j)) -$1$5$4 ``` Repeatedly delete two identical letters or exchange two unsorted letters. These operations both negate the final result. ``` ijk - ``` Reduce any remaining `ijk` to `-1`. ``` -- \B$ 1 ``` Tidy up the result. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~71~~ 63 bytes -8 bytes thanks to @coltim! ``` (r,"-",'r:"1ijk")@((8!A,4+A:a,'4+a:4 4#0,8\5717110953644).,)/4! ``` [Try it online!](https://ngn.bitbucket.io/k#eJxVj1ELgjAQx9/9FHoFKs5qNNO2l/ocFuSLcHdBID0kUZ+9zWbp2I3fsd+f21qddAJyEHGnQSIxpIckqaKjUNlRNyJWWaNVqBYbUZ2KUpZSbvbFdqdUuhLpWkVBcNfPZd2/O92GD3O5sUkubYNX8zC96dLzK7jXAhCMrfPAZJk8s2UeGJD+TPzzgfHnAznOvcQukHsLXSL3Gg6a9BmaNMyTxn6XZil2iybvYGQaajbW5ZD9aW/GQVZ09d1E4z8/Wm5iBA==) [Answer] # [Python 3](https://docs.python.org/3/), 89 bytes ``` a=0 for c in input():a=b'147223453614'[ord(c)%3*4+a%4]^(a&4) print('-'[:a&4]+'1ijk'[a%4]) ``` [Try it online!](https://tio.run/##HYpLCoAgFAD3naJNPS2CzFdB0EmkwIrIBBWxRae3D8wsBsbd4bCGxyjHOtmtT9dUmRd3BUIHOS7AsG8aji3vGIKwfiMrzXiBpcxwmonMkSbOKxMIVCCGt6cSmDo1iO@gMWqlz98H "Python 3 – Try It Online") It encodes the unit quaternions 1, i, j, k, -1, -i, -j, -k as the numbers 0..7 respectively, so that `a%4` represents one of 1, i, j, k, and `a&4` represents whether the value is negated. The loop works by accumulating a result in the variable `a`, multiplying one quaternion from the input on each iteration, much like you'd write `a = 1; for x in numbers: a *= x` to compute a product normally. The byte-string `b'147223453614'` encodes a multiplication table for i, j, k multiplied by 1, i, j, k. Indexing a byte-string gives the ASCII values as integers, but we only care about the lowest 3 bits and, conveniently, the ASCII value of each digit 0..7 has the correct lowest 3 bits, so this is practically like indexing a list of integers. The table is 3x4 instead of 8x8 because one operand (from the user input) can only be i, j or k, and we can ignore the sign from the other operand (the accumulator variable) and deal with the sign afterwards. The expression `ord(c)%3` converts the ASCII characters i, j, k into 0, 1, 2 respectively; the ASCII values of i, j and k are correct for this modulo 3. (If they weren't, the multiplication table could be changed.) The `^(a&4)` part XORs the result with the third bit of `a`, swapping the sign of the result from the multiplication table if this operand was negative, since we ignored the sign before. The output uses string slicing to conditionally print the minus sign (`'-'[:4]` conveniently isn't an error in Python). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 20 bytes ``` 3*żæ.ƒ0%8ṃ“ijk1””--¦ ``` [Try it online!](https://tio.run/##y0rNyan8/99Y6@iew8v0jk0yULV4uLP5UcOczKxsw0cNc4FIV/fQsv///0cbGpjpKBgamIIIcxBhBifQxPBzkYhYAA "Jelly – Try It Online") [Try all examples](https://tio.run/##y0rNyan8/99Y6@iew8v0jk0yULV4uLP5UcOczKxsw0cNc4FIV/fQsv/WQCEFXTsFIN/a/3C7CtfDHZse7lh0uJ3r4e4th9sfNa2J/P8/E6QikysLRGVxZYOobK7MLAidBZbVzebKBkvoGgJlssFyullcmZnZIJAFVZudmZ0FxjAtWSC1mdlQEiRqCDQQqD4zG4qyIHqzAA) A full program taking a list of code points and printing to STDOUT. Uses [Neil’s clever observation](https://codegolf.stackexchange.com/a/226315/42248) about the effect of multiplication by I, j and k in his Charcoal answer so be sure to upvote that one too! Thanks also to Neil for saving a byte with the observation that \$3 ^ x \mod 8\$ is 3 for all odd \$x\$ and 1 for all even \$x\$. Thanks to @cairdcoinheringaahing for saving a byte by pointing out that I could remove the trailing `”`. Thanks to @JonathanAllan for a neat 1 byte save using `ṃ`. ## Explanation (outdated) ``` 3* | 3 to the power of each codepoint ż | Zip with original list of codepoints æ.ƒ0 | Starting with zero, reduce the list using dot product (extending the shorter argument with ones) %8 | Mod 8 d4 | Divmod 4 ị"“- “ijk1 | Index into zipped "- ", "ijk1" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 61 bytes ``` ,ḅ8‘ị“;CAĖ*VÆSȮṀƒḳẹ²^÷d5ñYƭẏ§O’b8¤ _ȷ2ç/ị“1“-i“-j“-k“i“j“k“-1 ``` [Try it online!](https://tio.run/##y0rNyan8/1/n4Y5Wi0cNMx7u7n7UMMfa2fHINK2ww23BJ9Y93NlwbNLDHZsf7tp5aFPc4e0ppoc3Rh5b@3BX/6Hl/o8aZiZZHFrCFX9iu9Hh5foQ3YZArJsJIrJARDaQAPFAHBBb1/D/o4a5D3dOMzi0DKjV/3D7o6Y1kf//RytlKukoKGWBiGwQkQlmZoFFs6Ei2WCxzMxsEMiCqM3MzgJjMCcLpCYzG0pCDAAqzMyGIiBQigUA "Jelly – Try It Online") -2 bytes thanks to caird coinheringaahing --- Takes input as a list of codepoints, outputs as a string. The indexing to get the final answer is terrible. Looking for a way to improve that. This is very unclever. The first link just encodes the entire multiplication table into a size-64 list, converts the left and right arguments from base 8, and indexes into that. The main link takes the input as codepoints, subtracts 100 (which makes `ijk` equal to `567` and thus I put `-1, 1, -i, -j, -k` into `01234`), reduces the list from the left by the helper link, and then indexes the answer into a valid output format. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~104~~ ~~103~~ 101 bytes ``` a,z,n,h='h';f(s,d)int*s,*d;{for(a=n=9;z=*s++;n^=(~a+z)%3&&a>h?0:36)a=a>h?a^z^h:z;*d++=n;*d=a>h?a:49;} ``` [Try it online!](https://tio.run/##dZDhboIwFEb/8xQdi1qgLBqXJdLVvYBvMGfStDDaaiWAc8G4V2ctVJdhbKAtp9zz3ZTFn4y1LUUN0ignk3yCM1ghHghdhxUKOT5l@xJSoskCNySsogjrDYE/NGqC0Xw8psv8bZrMXwJK7JZumk2eNDjkUUS0WXqaPC/wuX0Umm0PPAWvR5bT8ilfen@oqrnYW/S1FxzUaVVD0wMIhS4ONQLdPv0uUlanPPBOHjDDQlqW7/MPQMBpesYdzaCrMUdBj4rS/JpBf7StQLwEZknshMCIr7Vv7V3Bxd@VIvBwZBXbFbD7uGYb5dnzbPSOCg0vvXQdr3xhbCt/XQvfRTsuHZcDrhxXAy7knQPZJ8RDrnpTPLsRqV4VD6OFUHbIe0lKKNm9dwKlVQvlZieZ3bRrAoRyj5T/7sFcZPsL "C (gcc) – Try It Online") Apparently I had basically the same idea as tsh, using xor. It still needs some optimization, considering how tsh's is like half the size in calculations. * -1 byte for using tab (9) instead of space (32) * -2 bytes for making a temp for `'h'` Input is a null terminated array of codepoints, output is stored to a pointer to a bunch of codepoints. ``` void f(const int *src, int dst[2]) { int acc, tmp, sign; for (acc = sign = '\t'; (tmp = *src++); ) { // My XOR math will end up with less than 'i' for 1. // TODO: fix this efficiently and I can remove some checks. if (acc < 'i') { acc = tmp; } else { // Xoring all of them together will result in the result or 'h' acc = acc ^ tmp ^'h'; } // Magic for testing when we need to negate if ((acc - tmp + 1) % 3 == 0 && acc > 'h') { // Switches between tab and '-' sign ^= 36; } } // Output sign dst[0] = sign; // Correct our xor math dst[1] = a < 'i' ? '1' : a; } ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~33~~ 26 bytes [SBCS](https://github.com/abrudz/SBCS) A port of [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)'s [Jelly answer](https://codegolf.stackexchange.com/a/226330/64121). ``` ' -' '1ijk'⌷⍨¨2 4⊤⊢⊥⍨3*2|⊢ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=U1fQVVdQN8zMylZ/1LP9Ue@KQyuMFEwedS151LXoUddSoICxllENkAMA&f=S1PQedQ3NdQ5WEE9U50rDcHLQuFlg3hwhVnIvKxMZF42mspsFLWZmdkgkIUimJ2ZnQXGKIJZIL2Z2VAS1UKgAZnZUAQE6gA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) A train submission which takes a list of codepoints as the right argument. APL has *mixed radix decode* (`⊥`) which makes the calculation part quite short: ``` 2|⊢ ⍝ each value in the input modulo 2 3* ⍝ raise 3 to this power ⊢⊥⍨ ⍝ use the resulting numbers as a mixed radix to decode the input ``` Technically the `2|` is not needed, but without it even the test cases with 2 characters start to fail because of very large numbers. `2 4⊤` calculates `4|⊢` and `2|4÷⍨⊢`, and both resulting integers are used to index into one string. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal),~~95 91~~ 55 bytes ``` λ2ẇ«½∇«:Ẋ«∨uOŻN€bMċ∇Dk«⌈Ŀṅ\e/:L‹\e*$ṅ+;Ẋ‛eeo:\erß›\e\-V ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%BB2%E1%BA%87%C2%AB%C2%BD%E2%88%87%C2%AB%3A%E1%BA%8A%C2%AB%E2%88%A8uO%C5%BBN%E2%82%ACbM%C4%8B%E2%88%87Dk%C2%AB%E2%8C%88%C4%BF%E1%B9%85%5Ce%2F%3AL%E2%80%B9%5Ce*%24%E1%B9%85%2B%3B%E1%BA%8A%E2%80%9Beeo%3A%5Cer%C3%9F%E2%80%BA%5Ce%5C-V&inputs=ii&header=&footer=) Partially ported ovs. Do I win 'Most improved'? Makes a lot more sense now. ``` λ ; # Lambda 2ẇ # Chunks of 2 «½∇« # Compressed `ijk` :Ẋ # Cartesian square «∨uOŻN€bMċ∇Dk« # Compressed string `e k ej ek e i j ei e` ⌈ # Split by spaces Ŀ # Transliterate ṅ # Join \e/ # Split by `e` : # Duplicate L‹\e* # (Length - 1) es $ṅ+ # Prepended (so es are bubbled to start Ẋ # Repeat on input until result doesn't change ‛eeo # Get rid of double es :\erß # If result is a substring of 'e' › # Append a 1 \e\-V # Replace es with -s ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~65~~ 58 bytes ``` (\w)\1 - ij k jk i ki j ji|kj|ik -$^$& -- }`.- -$&- \B$ 1 ``` [Try it online!](https://tio.run/##LYuxCgJBEEP7fMd6rMUI@ws2/sQiZ3FFErAQweb89nVWLsyEGV7y2t58Pto41XpbR@2fc28IUDBkECYEcbd2GlHuZUEE8F0vke8S6NeCNsbMeRaVpXlYID2lJLT@C2si@vCMJ6ePSf0A "Retina – Try It Online") Saved 7 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)! The main tricks deal with handling negative signs and the negative products. Negative signs are "bubbled" towards the beginning of the string to prevent needing to account for them in the other rules. The products that produce a negative such as `ji` are all reversed and then negated, to avoid dealing with them specifically. At the end, if there is no letter, we add a 1. [Answer] # [Factor](https://factorcode.org/) + `math.matrices math.quaternions`, 125 bytes ``` [ "1ijk"4 identity-matrix zip tuck substitute 1 n>q [ q* ] reduce dup sum 0 < 45 32 ? -rot vabs swap assoc-invert at 2array ] ``` [Try it online!](https://tio.run/##bVA9T8MwEN3zKx4dkVrRUhZAZUQsLIipYnCdC3Xc2onP6QeI3x4udjrBKXmy7949v7tK6ehD//728vp8j72K25lAMJoYO6/VjsHUduSGhGL2mhMrU9tORQrOeMewcqBdzh9oUJWGENRZFETQfTKMR3scVWZ0ikExHoqiPX4XkDAJ64Q2Z/KlzhV7SdqcNsYOUY8dxtbpz7d6oBk74igjXGPHT6L4KdZYJZP4EOcNxriC9u5AISJuiQnRX0bxlZRKQuONi9yvMZnLE5MlTEkumniepvWd8GUalF2DafAR3G1Yil0kzOFWLdZor@XJQGWnKfG42@MGj1je4XaBp9x3UBvZ3lGMpaVNTTalIhaj615cD0PkFaMRjCJMSm//jlEFv/9/EFQ@SBOfxZIqRan/BQ "Factor – Try It Online") On TIO it's 129 bytes; this is because Factor on TIO is ancient and doesn't have [tuck](https://docs.factorcode.org/content/word-tuck,kernel.html) which is the same as `dup -rot`. ## Explanation: It's a quotation (anonymous function) that takes an array of code points as input from the data stack and leaves an array of code points as output on the data stack. * `"1ijk"4 identity-matrix zip tuck substitute` Convert the input to quaternions that Factor can do arithmetic on. For example, `"ijkj"` -> `{ { 0 1 0 0 } { 0 0 1 0 } { 0 0 0 1 } { 0 0 1 0 } }` * `1 n>q [ q* ] reduce` Take the product. * `dup sum 0 < 45 32 ? -rot` Place the code point for the sign on the data stack. * `vabs swap assoc-invert at` Convert the product quaternion to a code point. * `2array` Make an array out of the code points that are on the stack. [Answer] # [Python 3](https://docs.python.org/3/), ~~199~~ \$\cdots\$ ~~182~~ 173 bytes ``` f=lambda s,n=0:s<'.'and f(s[1:],1-n)or len(s)>1and f(s<'2'and s[1:]or(s[0]==s[1]and'-1'or{'ij':'k','jk':'i','ki':'j','ji':'-k','kj':'-i','ik':'-j'}[s[:2]])+s[2:],n)or'-'*n+s ``` [Try it online!](https://tio.run/##bVHRboMwDHzvV/jNZCVTQydVQqU/wnjoaFCTdAGRTNqG@HZmB/YyzQLrfHf4CAxf8d7747J01eP6/na7Qsh9dSjDGZ/x6m/QZaFWZZMr6UU/wkP7LIiL2qQzFsmVPP1I3kNTVTQ1xKJU2I8TGoslOszROgKGgDMELDMMJGuOTZJFwy5pca5DXRZNI/ahLugNOB8lPvl9WKIOMUAFGa8DXgWcAJzFc2LdxrjEGeO47Oo1zqY7DZY9xm19XUBG47aLCsVOfw66jfr2X2xqcu0qdfuHVusDYtfedev0mLa8fhSnl5YVRupIckcfOeYajIdvM2TpoDn8ZotyB1R89C6LIg3DaHzMOpziDPICU5hh2kJqTT@jmVEsPw "Python 3 – Try It Online") Slightly longer version without direct mappings of \$i\$, \$j\$, and \$k\$ inter-multiplications: # [Python 3.8](https://docs.python.org/3.8/), 174 bytes ``` f=lambda s,n=0,o='ijkijki':s<'.'and f(s[1:],1-n)or len(s)>1and f(s<'2'and s[1:]or(s[0]==s[1]and'-1'or((b:=o.find(s[1],(a:=o.find(s[0]))))-a-1)*'-'+o[2*b-a])+s[2:],n)or'-'*n+s ``` [Try it online!](https://tio.run/##bVHRasMgFH3vV/h2NdVS08FGqP2RzIc0MVTtTIgOtpV8e6YmgzF20cO95x7vQR0/w21wp5dxWpZe3Ju3a9cgT5040kGANjYtqPwZDtC4DvXY17ySlDNHhgndlcOeXPjWOkOZVVkzTFF7lELESkYWGIfI4WslhkOvXZdGSYqbX/VRkhisYZwUwGA/1GVxZY0ke1@X0TaZRr5we78E5YNHAmHQQBGYBDaBzqnJrN0YmzmtbQqzarU1eefCJI22G64DolDbbcUAslMfo2qD6v6zzcBW5BnNH5qvB8iuvanWqilPeX0vn5/a1EkZP8V2H182UIW0Q196xPmiFP14k2qHYqSr9ziQXIyTdgH38AgzYhf08DN6bCa1ij8gZyDLNw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~135~~ 84 bytes ``` x#'i'=x*3+1 x#'j'=x+2 x#'k'=x*3+3 t=(cycle([pure,('-':).pure]<*>"1ijk")!!).foldl(#)0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0JZPVPdtkLLWNuQC8jOArK1jUCsbIioMVeJrUZyZXJOqkZ0QWlRqo6Guq66laYeiB1ro2WnZJiZla2kqaioqZeWn5OSo6GsafA/NzEzz7agKDOvRKVEKSszOwuEIQgIlP4DAA "Haskell – Try It Online") Had a lot of trouble doing this efficiently in Haskell. Hopefully this will inspire someone to create a better Haskell answer. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 55 bytes Port of the [Arnauld's solution](https://codegolf.stackexchange.com/a/226331/80745). Expects an array of ASCII codes. Returns a string. ``` ,4+$args|%{$x+=$_%2*2*$x+$_} '-'[$x-band4]+'1ijk'[$x%4] ``` [Try it online!](https://tio.run/##VY/NboMwEITvfoo9GJEEfCDiGgmpp55aNccIoYSY1DYFikFFIjw79R8kWRnLMzv72TT1H23lNy3LueirvGN1BcU4h3GAz@1N3r0RD8EBZ95@t9@pI84m5BP/hAdyOVfXOA38iHGhDS9O5wmhZIPCjc98CEHtWy24EdwKYYSwgvFnxe0UcVLYKImWrLBp4kiMCV38heHM1V5hTHDzvbpcU5lwu@lFy2MUggm3OH/8xBbu4MGIQBWWXcuqWwiYDg3NO3qFA@DM9loq@7JTRgGJzRn/9Hl862VX/3xcuBpJE4vSdezznEqpGW6Y0N8He819LWRsT2vjvWp64z/dN6Fp/gc "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~122~~ 120 bytes Thanks [@Neil](https://codegolf.stackexchange.com/a/226318/80745) for the `k -> ij` simplification. ``` for($s="$args";$p-ne($p=$s)){'k ij9ii|jj -9ji -ij9--9.- -$0-9ij k'-split9|%{$s=$s-replace-split$_}} $p+'1'*($p-in'','-') ``` [Try it online!](https://tio.run/##VY9PT4NAEMXvfIpJs82CMsYeiWnSxJMnjT0a01Rc6swirCxEE8pnx4WF/pmwE96bNz9YU/6qyn6pPO@zpkhrKgvI2j4rq1DY9ULsq4NdPAiDhQqFWQsbRa3UQJwQHZkBEyZAJxGTOwQU95gQg5ZoTU51cly2jiMsVsrk@1R5W@y6LhDmVq7kjcMiFVLGEmXUd0GwCYM4lCQhBtejQfAo2As9Cu0F8aViv4WT1D6KqzmrfRonEpEeiq8Yk3myTzDSPJ5rlwcq6amPs9X8Mw5BenqYz5eI4AhLaANwJWxdUXGIQag/o9JafcIaxM7PKmWbvHZGNudG/@1l@9jYuvx@/mC38r7xqKG2TZoqawfGtIzq58w@5V5nsvBvp8FTYZrRv/heF3T9Pw "PowerShell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` (\m->['-'|m 8>3]++["1ijk"!!m 4]).mod.foldl(\x y->3^y*x+y)0 ``` [Try it online!](https://tio.run/##FcixDoIwFEDRX3k0JoCkjQYHF9jcdHIETBqw@to@2gBGSPx2q9zp5D7laO7WBlXUIamJl1XM4w/BscybLKvYHrVhUURwaFJBrhPK2c4m9QwLL/Pbsp2zJd0FkthDAST9BRL/mq7TcO6FEv8BanB06l@UwgbebuhGhqDBAGrQCGaF0YBo1rRm4dsqKx9j4K33Pw "Haskell – Try It Online") A port of Neil's Charcoal answer that takes a list of codepoints as input. [Answer] # [Shue](https://codegolf.stackexchange.com/questions/242897/golf-the-prime-numbers-in-shue), 46 bytes ``` 1 i j k -1 -i -j -k =1 --= ii=- jk=i k=ij j=ki ``` [Try it online!](https://tio.run/##lVXBjpswEL37KyxOdhNo0d6QUE@7p0rbQ9VLQisHJokJ2Mg2u4128@3pGEJC2E21jRSFmXl@nnl@Js3ebbW6O8q60cZRA3Nq95YYiGmKUZTrupEVMLMKGFv8SrPX5TLlnzhLx9HXgBNSwJq2CmwuGmCSJ4Tix4BDolUQdBEWMfrSPa@1oTmVisoe6T9y3UGEKrCU@nXLZXApnwhnp8JVfkzdxdVbsvQGV/r/VOpWW@pjXJPVQlqgP0XVwr0x2rB18F0YC4aCDxO60Y7mW2FE7jD5kh@oWPsnVIFfc9/SrW8kHoEtvDvC3oFlizzreafdfqjT@8dvn@8fH6Y94gatUf6H9G5p/MqzVRBbSyWcNhY7teDYaVlbwXWmkqrLyMg2lXSsk52fXVV5V3WYS991Z@c4qoXLt6ziY8vV0cbotmF3fCKI3/g1pS/sbOsBGnM@p2@yd3wRJxnnh3@oPJrSU7/HfBirNcLP@4567eAP5K0Dls/pWMABhOP26ub9qK2ST4Ax5l9kv0GtC4x@mBa68HmL99wnR6J1iAeBQ5xzCp5/j8guhzKob736A@J6dtS6q3aNJqcB7UdX@7KYrzygG/G6OiB0VxdqA6wCxSyfxfwtcuhmoRM98zjBM39xxPvQ6eD@5Owi0dlsNUOOE0OSHW6unog9OZIxN7l1zYzeGFEP90xpdEhTiRxqUM5SYYA22lq5wlNEw6JH8AYUdAVb8SR1a7h/R5NcF7ghvo@DY0wkKcmOhDEJJQlLEu5Iis9hSqRMQ1LuUknwW5Iy3ckjLkF3h3FGiFSNP/q9jawrpIoMiILxCJRnRzvg34c34NmimEWXqoaTxkjlGJajAnowP8pyV/4F "Python 3 – Try It Online") It's... beautiful. Uses an `i`-dominated internal representation. Basically, the number of `j` and `k` characters is decreasing. The last two rules allow the movement of `j` and `k` between `i`s. Due to the rule `=1`, this is a bit slow. If you want to test this answer, I suggest you use [This](https://tio.run/##lVXBjpswEL37KyxOdhNo0d6QUE@7p0rbQ9VLQisHJokJ2Mg2u4128@3pGEJC2E21RYrCzDw/zzw/J83ebbW6O8q60cZRA3Nq95YYiGmKUZTrupEVMLMKGFv8SrPX5TLlnzhLx9HXgBNSwJq2CmwuGmCSJ4TiY8Ah0SoIugiLGH3p3tfa0JxKRWWP9I9cdxChCiylft1yGVzKJ8LZqXCVH1N3cfWWLL3Blf4/lbrVlvoY12S1kBboT1G1cG@MNmwdfBfGgqHgw4RutKP5VhiRO0y@5Acq1v4NVeDX3Ld06xuJR2AL746wd2DZIs963mm3H@r0/vHb5/vHh2mPuEFrlP8ivVsav/JsFcTWUgmnjcVOLTh2WtZWcJ2ppOoyMrJNJR3rZOdnV1XeVR3m0nfd2TmOauHyLav42HJ1tDG6bdgdnwjiN35N6Qs723qAxpzP6ZvsHV/EScb54R8qj6b01O8xH8ZqjfDzvqNeO/gDeeuA5XM6FnAA4bi9unk/aqvkE2CM@RfZb1DrAqMfpoUufN7iPffJkWgd4kHgEOecguffI7LLoQzqW6/@gLieHbXuql2jyWlA@9HVvizmKw/oRryuDgjd1YXaAKtAMctnMX@LHLpZ6ETPPE7wzF8c8T50Org/ObtIdDZbzZDjxJBkh5urJ2JPjmTMTW5dM6M3RtTDPVMaHdJUIocalLNUGKCNtlau8BTRsOgRvAEFXcFWPEndGu5/o0muC9wQf4@DI5GkJDsSklCSsCQhvoYpkTINSblLJcFPScp0J4@IRmOHcUaIVI0/9b2NrCukigyIgvEIlCdGJ@A/h/fe2Z2YRYOqhpPGSOUYlqMCejA/SrnzT1n@BQ "Python 3 – Try It Online") equivalent program. [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 108 bytes ``` a propagate: ``=>* {ii,jj,kk,ij,jk,ki,ji,kj,ik}=>{`,`,`,k,i,j,`k,`i,`j} []$1 `=>` $1 b: *=>\1/{$,`} _ $ `=>\- ``` Explanation: ``` # while the input changed last iteration... a propagate: # cancel out negatives ``=>* # ijk conversion {ii,jj,kk,ij,jk,ki,ji,kj,ik}=>{`,`,`,k,i,j,`k,`i,`j} # move negative signs to the front []$1 `=>` $1 # cleanup b: # put in 1s on empty string or leading ` *=>\1/{$,`} _ $ # ` to minus `=>\- ``` [Answer] # [J](http://jsoftware.com/), 41 bytes ``` '1ijk -'&([({~4&|,~4+3&<)(8|]+[*3^])/@i.) ``` [Try it online!](https://tio.run/##bY@xCsIwEIZ3n@JwyDW2iZZ2kKIgCE5OrqUuYvHuBh/A0lePqdrrYI/8GT7y/Uc4LD22sK8AIYMNVDHOw/FyPgXMiQUcmqROXn1puqwv08LsbLLtmrReFdfGrg/kbbCL@@3xjBWE4CpoAQlHxCNiRTIi@Uekz5wy1jaXq6qu48mVmSVEMgzPFAsJf6LW1M9DG8nvnvlO9IZ8TxwMbw "J – Try It Online") [Neil's excellent idea](https://codegolf.stackexchange.com/a/226315/15469) applied to J. [Answer] # [Python 3](https://docs.python.org/3/), 289 bytes ``` R={"ii":"-","jj":"-","kk":"-","ij":"k","jk":"i","ki":"j","ji":"-k","kj":"-i","ik":"-j"} def f(x): if x=="-":return"-1" if len(x)==1:return x if len(x)==2and x[0]=="-":return x for s,e in R.items():x=x.replace(s,e) return f(("-"if x.count("-")%2else"")+"".join(c for c in x if c!="-")) ``` [Try it online!](https://tio.run/##VY7LCsIwEEXX9ivGASHBWnzsCvkJt@KixAlOWtPSVoiI314zpQvdTe65Zybda7y34TRNZ/NGZixxhzl6vwx1vQwsSS1IEhYkZS/JbAmrZ00gz57HT3YjB05FXWYrdhCNSevKnsZnH3B3wDltKKSGMYcFQPyLj1W4Qbzsr7@ydFzbw5ATcIBzwSM9BqXLaGLRU9dUllSCOlstglMq6fKJwrbPMMpLb47UDISot4iFbzkoC7LWytIIqW3XclXrafoC) Takes input as a string. [Answer] # [Python 3](https://docs.python.org/3/), 132 bytes Function that iterates over the characters of the expression, evaluating step by step the product of a pair of characters. ``` def f(e,s=0): while e[1:]:p,e=e[:2],e[2:];a=set('ijk')-set(p);e=a.pop()[len(a):]+e;s^=p not in'ijki' return'-'[:s]+['1',e][len(e)] ``` [Try it online!](https://tio.run/##LU/LCsMgELz7Fd5WqS1NezP4JWIh0A1ZLUaipfTrU7UZ1mEdZl/pW5Y13vf9iTOfBapsrlIz/lnohRztoJ1OCg1afXMK7U27cTIZiwDyAeS5pUmOaKZLWpOQ9oVRTFK7E475YRKPa@EUm5uA8Q3Le4twBquzO1kYQKHrNSjdXjAXY4FAMfCNQiPqqe9qOJTQNaLQ4P9eCr6//vHNQ@Hgf4NqpHBEBTjG5nXjVPfjbXS9uyJtFIuYBUm5/wA "Python 3 – Try It Online") --- *Code explanation:* * `def f(e, s=0):` function definition: takes the expression to be evaluated as input `e`; the 2nd parameter `s` is the sign, passed as optional parameter to be initialized (0 => +, 1 => -). * `while e[1:]:` main loop: iterates over the characters in the expression, while there are at least 2 characters left (the empty string evaluates to False). * `p, e = e[:2], e[2:];` take the first two characters `p` (to evaluate their product), and the remaining part of the expression. * `a = set('ijk') - set(p);` evaluates the set `a` as difference between the set of 3 chars {i, j, k} and the set of 2 chars in `p`. This can be used to distinguish the different cases: if `p` is a mixed product (ij, jk, ...) then the difference set will contain the char resulting from their product; otherwise, the difference set will have `len==2`. * `e = a.pop()[len(a):] + e;` prepend to the remaining expression the char resulting from the product. This exploits the set `a` built before: `pop()` will return the correct char only if we have a mixed product: the difference set will contain only the resulting char. It is taken by slicing the single char string with `len`: actually `len=0` accounts for the fact that `a.pop` is evaluated before `len`. * `s ^= p not in 'ijki'` evaluates the sign: the product will have negative sign for {ii, jj, kk} and {ji, kj, ik}, all of them are not contained in the string `'ijki'`. The boolean evaluates to integer to compute the xor function: sign xor (1, 0) follows the sign multiplication rules. * `return '-'[:s] + ['1', e][len(e)]` finally, the function returns the results of the expression: first the sign `-` only if `s==1`. Then the results of the expression: `e` if it contains the remaining single char (exit from loop), otherwise `1`. [Answer] # x86-64 machine code, 36 bytes ``` 30 C1 74 06 28 C8 04 02 7B 05 35 31 C9 31 C0 AC 24 03 75 EC 9E 79 03 B0 2D AA 8D 41 31 E3 02 04 37 66 AB C3 ``` [Try it online!](https://tio.run/##dVNNj5swED0zv2JKFclsslGa9ENKml7aay89Vcrm4BiTGIxBmOwSovz10rGBtFupCEaeN483z4MRZfl4FKLruM2R4Y@QwfyoiwPXmEB@1rUq9WUNQVNUKPQMuYYgbTHRqrTqaCCw5wOBMypCwOPYr5fEKQs0sqlhZJLG/HCpJS6a1QdIBkkpmpkLQ8ZdxhtwbxJDF7E9kKzpZVcka1ocXVFvfkocZtFmqsyVOVsI8uLZsxfN8htR6oIk7mUnKnnfaFeJZkpu3u1Jg9YtFkY65p@NUPUTDOi6F3uBoJI1tOsAohCjDZBVWRkMv4Z4fS5UjAkTJ17hQyUtOaXJFMbW2GM22qAnjZtgI9DS6gbwVhmhz7HEz7aOVTE/fQH4W6CWthbcSrvb4xavoQpnGKYuZC4ov0w9mg1I5jGlMnelPVdlqX98kjqOyobYCxBRZcNNV3jbgDI15lwZFsEVgoS@F3vlDNd4dxdBQJzAV/o57Fb7DSEJG8dSRy4vK5JNWDixOLFPhpq/qt/gzngy37k4KSNpoLFch67sLDU0h8UML5TGBV5HOk4Wy58kd9kydjbuBMrYO32IxtlHu2Y63dPY8eWktMT/EnFKXd5s8d966zzcG7KJQnfCbeT30VDx1nW/RKL50XaP@cf3FOg32xJf6t8 "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string; and the address of the input, as a null-terminated byte string, in RSI. The starting point is after the first 11 bytes. In assembly: ``` # ECX holds 0 for 1, 1 for i, 2 for j, or 3 for k. # The high bit of AH holds a sign: 1 to negate or 0 to not negate. multiply: # Here, AL is 1, 2, or 3 for the current input letter (as above). xor cl, al # Exclusive-or CL (the low byte of ECX) with that value. # This produces the correct new value. jz flipsign # If the result is 0 (i*i, j*j, k*k), jump to flip the sign. sub al, cl # Subtract CL from AL. add al, 2 # Add 2 to AL. The possibilities based on the original CL and AL are: # 0: j*i=-k # 1: k*i=j i*j=k # 2: 1*i=i 1*j=j 1*k=k # 3: k*j=-i i*k=-j # 4: j*k=i jpo next # Jump if the sum of the low 8 bits is odd, to skip the sign flipping. # It is odd for 1, 2, and 4, so the sign is flipped for 0 and 3. flipsign: .byte 0x35 # This byte combines with the next two instructions to form # 'xor eax, 0xC031C931', which in particular flips the high bit of AH. f: xor ecx, ecx # (Start here) Set ECX to 0. xor eax, eax # Set EAX to 0. next: lodsb # Load a byte from the input string into AL, advancing the pointer. and al, 3 # AND that byte with 3, converting i,j,k to 1,2,3 respectively. jnz multiply # Jump if the result is not 0. It is 0 for the null byte. sahf # Set flags from AH. In particular, the high bit of AH goes into SF. jns skipminus # Jump if SF=0 to skip the minus sign. mov al, 0x2D # Set AL to the ASCII code of HYPHEN-MINUS. stosb # Add that to the output string, advancing the pointer. skipminus: lea eax, [rcx+0x31] # Set EAX to ECX+0x31. 0x31 is the ASCII code of 1. jrcxz oneskip # Jump if ECX is 0. add al, 0x37 # (Otherwise) Add 0x37 to AL, for a net addition of 0x68, # which makes 1,2,3 into the ASCII codes of i,j,k respectively. oneskip: stosw # Add AL and AH (which is 0) to the output string, advancing the pointer. ret # Return. ``` ]
[Question] [ *Due to technical limitations of Stack Exchange, the title is rendered incorrectly. The **correct** title for this challenge is* Make a ``` Word Icicle! Word Icicle Word cicle ord cicle ord icle ord i le or i le or i l or l or r ``` --- Today's challenge is to make icicles out of the input word. Given a string of entirely [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters), and at least 2 non-space characters, perform the following steps: 1. Print the current state of the string. 2. Replace the lexically smallest character (other than spaces) with a space. If there is a tie, replace the leftmost character. 3. Repeat on consecutive lines until the string contains only 1 non-space character. This creates the effect that the input string looks like it's melting... ``` I'm Melting!!! I'm Melting !! I'm Melting ! I'm Melting I m Melting m Melting m elting m lting m ltin m lt n m t n t n t ``` ### Rules * After a couple iterations, your output will almost surely have trailing spaces on each line. If you choose to truncate these, that is allowed. * You may have **one** trailing empty line, but not more. * Remember that the input may contain several spaces, but these are all effectively skipped. For example, the input `a a` should give ``` a a a ``` * You may take input as a list of strings if you want. For output, you may return or print a list of strings, a single string with newlines, or char matrix/2D array. Generally, I prefer permissive IO formats, so other formats are most likely allowed as long as they are consistent and clearly correspond to the right output. If in doubt, feel free to ask. As usual, full programs or functions are allowed. * Remember, this is a contest to make the shortest answer in any language! If you choose to answer in Java, try to make the shortest Java answer (in bytes) that you can. ### Test cases ``` Hello World! --> Hello World! Hello World ello World ello orld ello orl llo orl lo orl o orl o or or r AbCdEfGhIjKlMnOpQrStUvWxYz --> AbCdEfGhIjKlMnOpQrStUvWxYz bCdEfGhIjKlMnOpQrStUvWxYz b dEfGhIjKlMnOpQrStUvWxYz b d fGhIjKlMnOpQrStUvWxYz b d f hIjKlMnOpQrStUvWxYz b d f h jKlMnOpQrStUvWxYz b d f h j lMnOpQrStUvWxYz b d f h j l nOpQrStUvWxYz b d f h j l n pQrStUvWxYz b d f h j l n p rStUvWxYz b d f h j l n p r tUvWxYz b d f h j l n p r t vWxYz b d f h j l n p r t v xYz b d f h j l n p r t v x z d f h j l n p r t v x z f h j l n p r t v x z h j l n p r t v x z j l n p r t v x z l n p r t v x z n p r t v x z p r t v x z r t v x z t v x z v x z x z z PPCG is da BEST --> PPCG is da BEST PPCG is da EST PP G is da EST PP G is da ST PP is da ST P is da ST is da ST is da T is da is d is s ({({})({}[()])}{}) --> ({({})({}[()])}{}) {({})({}[()])}{}) { {})({}[()])}{}) { {}) {}[()])}{}) { {}) {}[ )])}{}) { {} {}[ )])}{}) { {} {}[ ])}{}) { {} {}[ ] }{}) { {} {}[ ] }{} { {} {} ] }{} { {} {} }{} {} {} }{} } {} }{} } } }{} } } } } } } } } } } ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 28 bytes ``` /\S/+¶<~(O`. 0L$`\S 0`$\$&¶ ``` [Try it online!](https://tio.run/##K0otycxLNPz/Xz8mWF/70DabOg3/BD0uAx@VhJhgLoMElRgVtUPbFP7/D88vSlHwTM5MzklVBAA "Retina – Try It Online")Explanation: ``` /\S/+ ``` Repeat while the input value isn't blank. ``` ¶< ``` Print the current value. ``` ~( ``` Execute the rest of the script on the value. Then, execute the result of that script as a script on the value. ``` O`. ``` Sort the characters into order. ``` 0L$`\S 0`$\$&¶ ``` Select the first nonblank character and output a Retina program that replaces the first literal (`$\`) occurrence of that character (`$&`) with a space (trailing space in original code). [Answer] # [Python 2](https://docs.python.org/2/), ~~71~~ 70 bytes -1 byte thanks to ovs ``` x=input() while x.strip():print x;r=x.replace;x=r(min(r(*' ~')),' ',1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDk6s8IzMnVaFCr7ikKLNAQ9OqoCgzr0ShwrrItkKvKLUgJzE51brCtkgjNzNPo0hDS12hTl1TU0ddQV3HUPP/fyXHJOcU1zT3DM8s7xzfPP@CwKLgktCy8IrIKiUA "Python 2 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ 11 bytes ``` ∪∘↓∘⍉⍋∘⍋⍴⌸⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgmG/9OA5KOOVY86Zjxqmwwiezsf9XaDGd2Perc86tnxqGvR//@P2iamqYfnF6UoeCZnJuekKqpzgYU81dVzFXxTc0oy89IVFWGiHqk5OfkKQOU5KTAhxyTnFNc09wzPLO8c3zz/gsCi4JLQsvCKyCqogoAAZ3eFzGKFlEQFJ9fgEKioRrVGda0mEEdraMZq1gLZ6gA "APL (Dyalog Unicode) – Try It Online") uses `⎕io←1`; returns an array of strings (vector of character vectors) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ðм{v=yð.; ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8IYLe6rLbCsPb9Cz/v/fUz1XwTc1pyQzL11RUREA "05AB1E – Try It Online") ### Explanation ``` ð # Push space м # Implicit input. Remove spaces { # Sort. Gives string of sorted, non-space chars v # For each char in that string = # Print latest string, without popping. The first time it prints the input y # Push current char ð # Push space .; # Replace first occurrence of current char by space # Implicitly end for-each loop ``` [Answer] # Pyth, ~~17~~ ~~14~~ 13 bytes ``` V-SQdQ=XQxQNd ``` [Try it here](http://pyth.herokuapp.com/?code=V-SQdQ%3DXQxQNd&input=%22Word+Icicle%21%22&debug=0) ``` V-SQdQ=XQxQNd V-SQd For each non-space character in the sorted input (Q)... Q ... print the current value of Q... = Q ... and set Q to itself... xQN ... with the first instance of the character... X d ... replaced by a space. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~60~~ ~~58~~ ~~55~~ 47 bytes ``` ->a{[-a]+a.scan(/\S/).sort.map{|x|a[x]=' ';-a}} ``` [Try it online!](https://tio.run/##HYrNCoJAFIX3PcXVjUppDxAGFWISUWERMc3i5k8Zk8o4hTXOs5u6OPCd7xz@vn3b1G3tOUpiIx2jU0WYm9NrOLWcquDCeWEpm7pBUlPXAGNmo1It0c8FjyGIsoglmj4BPTBesE2YyPK7pg1mnTBWQPdj8dAXt1Xspf4jeG7YNt@VBx6K0@dcX379ut@vfMgqiBGWXnjslSlNqawuxLSopTrWqZNg9JCNaEblW1SQEkFV@wc "Ruby – Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/) `-rn`, 142 ~~143~~ bytes ``` :a p s/$/ ABCDEFGHIJKLMNOPQRSTUVWXYZ/ s \w+$ !"#$%\&'()*+,-./0123456789:;<=>?@&[\\]^_`\L&{|}~ :b /(.).* \1/!s/ ./ / tb s/(.)(.*) \1.*/ \2/ ta ``` [Try it online!](https://tio.run/##Dc1bU4JAAAXg591fAUW0YOym3emqREhqYmhkrhYIFQ0DDEuXyeinR/twZs585@GwKNRe0ve61n2YQ0YkAtod49K8srr2da8/uBk6o1t3PLnz7qcPBDJAPxsSENfWpQ0qbyJFbWxpmGw3Wzu7e/sHh0f68cnp2fmFPKN0vnh8on159VP9AqgHkCCsYBXQJhEZAZgAAsuAX3JGWFX4gFUi0BZnv669rAgFexkvk0iE3ShJMoFTEoqwHRih@Wy92m@9ZJAO81HhlpMP72v6DR3HsISYCaEvdEx3DNEKrSqFZ4aUuVLx/pflZZylrNaK9B8 "sed – Try It Online") (note: there are tabs in the program) Since sed has no concept of lexicographical order, I had to hardcode the set of printable ASCII characters in and it takes up more than half the bytecount. Using sed 4.2.2 will reduce bytecount by 2, since that allows for unnamed labels, [Try it online!](https://tio.run/##Dc1bT4MwAAXg5/ZXFJ3YMte6ecfrhshwm2OyiXOdFwZGDAFCiRoRf7rYh5OcfOfhiDCoax1mULAGA92ecWleWX37ejAc3Yydya07nd159/MHBgXgn80GUNbWGxtc3cREa261KNtud3Z29/YPDo/045PTs/MLdcH58vHpmQ/V8qf6BVD3IcOUUA3wNlMEA5QBBgtfXkrGVCNyoBpDvCO5rr00D5C9ilZxqMB@GMcpkhQHCuz6RmC@Wm/2@yAeJeNskrvF7MP7mn9DxzEsFAkUvKCe6U4hLnFZEZkFJktSyf6XZkWUJqJu5ck/ "sed 4.2.2 – Try It Online") --- `-r` enables extended regular expressions (golfier) `-n` disables implicit printing of the pattern space at the end of the program The pattern space starts with the input `:a` label `a`, this is the main program loop `p` print the pattern space (fancy name for the buffer) now we append the set of printable ASCII characters (excluding the space) `s/$/ ABCDEFGHIJKLMNOPQRSTUVWXYZ/` append a tab, acting as the 1-byte delimiter, followed by the uppercase alphabet `s<tab>` substitute (sed can take any character as the delimiter, in this case the tab is used to save a byte from escaping the `/`) * `\w+$` the uppercase alphabet we just appended * `<tab>` with * `!"#$%\&'()*+,-./0123456789:;<=>?@&[\\]^_\`\L&{|}~<tab>` the rest of the characters, note that `\L&` is the lowercase version of the uppercase alphabet `:b` label `b`, remove characters from the beginning set that are not present in input `/(.).* \1/!` if the first character from the ASCII set is not in the input * `s/ ./ /` remove it `tb` repeat `b` until the substitution fails `s/(.)(.*) \1.*/ \2/` replace the first character in the ASCII set present in the input with a space, and remove the ASCII set `ta` recurse [Answer] # [R](https://www.r-project.org/), ~~140~~ 100 bytes -40 bytes Thanks to Giuseppe ! ``` function(x)for(i in any((z=utf8ToInt(x))<33):max(y<-rank(z,,"f"))){z[y==i]=32 cat(intToUtf8(z)," ")} ``` [Try it online!](https://tio.run/##DctBC4IwGIDhu79i7tL3gV7yEqGHiAgJiUiJiA7LWq30W4wZuui3L6/vw2u8ZGnsZUe1VZqgR6kNKKaICRoAXNZZOSt1TnY0TJME563oYUhjI@gFLoq45Ij4dachy9Q5S6ZBLSwosqWuxhccRjzg@PMSeD5pWXFrrKJ7GIYcg7EtLsvrSq4f@XPTFLR978zeVp9Df3Qc/R8 "R – Try It Online") A solution using `outer` and Giuseppe's magic to work properly is longer at 104 bytes. Inspired by [this answer](https://codegolf.stackexchange.com/questions/142037/matrix-with-1-to-ln-in-all-n-columns/142047#142047). ``` function(x,z=utf8ToInt(x)-32)apply(t(outer(rank(z,,"f"),(2-(min(z)>0)):nchar(x),">=")*z+32),1,intToUtf8) ``` [Try it online!](https://tio.run/##DczRCoIwFIDh@55Cd9M5NaHsJiKFiAgJiUiJLs1crvRMxgzby9tuf/h@PQpvG4yip9JIRTBwG/VGrDOVkIEBg1WIRdc1PzCgelNp0AV9wHLOBEMOYQCtJLAYLxA3VNaFdoqzOGI4s3On@ZJLMpnK3RVHASyZtl5aNUbSy/d9hhPXdo/98yCOdfI@NSmdu4u@mvx7G@6W4fgH "R – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes ``` f=lambda a:[*a.strip()]and[a]+f(a.replace(min(a.replace(*" ~"))," ",1)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIdEqWitRr7ikKLNAQzM2MS8lOjFWO00jUa8otSAnMTlVIzczD4mnpaRQp6SpqaOkoKRjqKn5v6AoM69EQykmT0kvKx@oMk1DyTHJOcU1zT3DM8s7xzfPvyCwKLgktCy8IrIKqFHzPwA "Python 3 – Try It Online") -4 bytes thanks to ovs [Answer] # [Python 2](https://docs.python.org/2/), ~~70~~ ~~69~~ ~~66~~ 64 bytes ``` def f(s):print s;S=set(s)-{' '};S and f(s.replace(min(S),' ',1)) ``` [Try it online!](https://tio.run/##LcqxCgIxEATQ3q/YVNmFU9DSww@4wiqFhVocyUYDuVzIpZGQb48RLAaGNxM/@b2GU2uGLVjc6ByTCxm2UV02zh32RYKso4I5mN/jkDj6WTMuLqCioa/DkahZlLc1GZi0056FpF2X6SEXuLLPLryE@CMWLJV67khPqr1Lal8 "Python 2 – Try It Online") Thx for 2 bytes from [ovs](https://codegolf.stackexchange.com/users/64121/ovs) via using `S and f()` instead of `if S:f()` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ẋ"ỤỤ$z⁶Q ``` [Try it online!](https://tio.run/##y0rNyan8///hrm6lh7uXAJFK1aPGbYH/H@7ecrj9UdMa78j//z2AavIVwvOLclIUuRyTnFNc09wzPLO8c3zz/AsCi4JLQsvCKyKruAICnN0VMosVUhIVnFyDQ7g0qjWqazWBOFpDM1azFsgGAA "Jelly – Try It Online") ### Idea The basic idea is to build the columns of the desired output directly, instead of manipulating the string and returning all intermediate results. We start by numerating the characters of the input string in the order they will be removed. For the moment, we'll pretend spaces will be removed as well. ``` tee ay oh 845139276 ``` Now, we build the columns by repeating each character by its index in this enumeration. ``` tee ay oh tee ay oh tee ay oh tee y oh t e y oh t y oh t y o t y y ``` All that's left is to remove duplicates, to account for the spaces. ### Code ``` ẋ"ỤỤ$z⁶Q Main link. Argument: s (string) $ Combine the two links to the left into a chain. Ụ Grade up; sort the indices of s by their corresponding values. Let's call the result J. Grade up again, sorting the indices of J by the corr. values in J. This enumerates the positions of s as described before. ẋ" Repeat each character of s that many times. z⁶ Zip the resulting 2D array, filling missing characters with spaces. Q Unique; deduplicate the array of rows. ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, ~~37~~ 34 bytes *Dropped three bytes with help from @TonHospel* ``` say&&s/\Q$a/ / while($a)=sort/\S/g ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJNrVg/JlAlUV9BX6E8IzMnVUMlUdO2OL@oRD8mWD/9/3@Nao3qWk0gjtbQjNWsNQBy/uUXlGTm5xX/1/U11TMwNPivmwcA "Perl 5 – Try It Online") [Answer] # JavaScript, ~~67~~ ~~66~~ 65 bytes Because I haven't golfed drunk in a while! ``` s=>[...t=s].sort().map(x=>x>` `?t+=` ${s=s.replace(x,` `)}`:0)&&t ``` [Try it online](https://tio.run/##HY5Ra8IwHMTf9ylSEJeghj0P0qEiWobM4URGV/hnSepSYlKSIGWln72Lezi4@909XMNvPAiv27iwTqqxZmNgeUkpjSxUNDgfMaFX3uKO5V0OCF7ijMHDpA8sUK9aw4XC3TwVZIDnJzKdxlE4G5xR1LgLLuHsvESF0MKoDOZQPF7RXpmo7SXL7mCnjHEorYy8x@X3Wm7q7U/RvJq9fWvf/TGebufu8zeVh8N6i3RAkqPV5viRCO5xP5CkEpOKDMlD9f@3JrRx2sKXBTL@AQ) Thanks to DanielIndie for pointing out 4 redundant bytes that beer included! [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~26~~ 24 bytes ``` {?(,x),x{x[y]:" ";x}\<x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqtpeQ6dCU6eiuiK6MtZKSUHJuqI2xqai9n@aUnh@UYqCZ3Jmck6qohJXmpKneq6Cb2pOSWZeuqIiWMQjNScnXwGoLicFzHdMck5xTXPP8MzyzvHN8y8ILAouCS0Lr4isAskGBDi7K2QWK6QkKji5BoeAhDSqNaprNYE4WkMzVrMWyFb6DwA "K (ngn/k) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 129 bytes ``` var s=ReadLine();while(s.Any(c=>c!=32)){WriteLine(s);var i=s.IndexOf(s.Min(c=>c==32?(char)999:c));s=s.Remove(i,1).Insert(i," ");} ``` [Try it online!](https://tio.run/##HcuxCsIwEIDhV2m6mAMtqFMMqTgWLEIX55Ce9qCNkAtVEZ89xm7/8P2ON44ppdmGgk2Htj@TRwn6OdCIkquTf0tnaifMfgfwuQaKuBAG/Z/IcNX4Hl@XW9Yt@UWbrI/SDTaAUurgADRn2OH0mFHSegt5Ygwxd1mUoL8pNaupaHGM5O9CiB8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/) with `-nlF/\s|/`, 39 bytes ``` @F=sort@F;say,s~\Q$F[$F++]~ ~ while/\S/ ``` This might be pushing the boundaries of Perl's flags not being counted, if so I'll revert to the previous answer. [Try it online!](https://tio.run/##DchNC4IwAIDhu79iggfFbHbwJIIlziQkxUJCPZguNIYTJ32Z/vSWhxce3g73xOASsnST28hitB9sZLLivWJzFkkolZCq5jOYwbNuCIZZDDlPaF8Bv2xKgkVRFPaYEAqWSSpR2F6dyr15tX8/kKA9dlEfD@dH8rp8hDB0PNAwUBVg58YnQR7lcVKWUlnJlWnxj3ZDQ1vGtZYgmLEv5FpgrPWN/gc "Perl 5 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), 27 bytes ``` >>ò2Ùúú^lDhrfDj|@"r kdòdj<H ``` [Try it online!](https://tio.run/##K/v/387u8CajwzMP7zq8Ky7HJaMozSWrxkGpSCE75fCmlCwbD8IqAA "V – Try It Online") Hexdump: ``` 00000000: 3e3e f232 d9fa fa5e 6c44 6872 6644 6a7c >>.2...^lDhrfDj| 00000010: 4022 7220 6b64 f264 6a3c 48 @"r kd.dj<H ``` [Answer] # [Haskell](https://www.haskell.org/), 67 bytes *12 bytes saved thanks to Laikoni* ``` f s|(a,_:b)<-span(/=minimum(id=<<words s))s=putStrLn s>>f(a++' ':b) ``` [Try it online!](https://tio.run/##Dcy7CoAgFADQX7m4pFS0hzY3tDU0xg2TJB/hLVr6d/MDzjmQzt25nA3Qx7FZ@03Ili4MvFPeBusfz61WUr4xaQISgtT13POdpgA0DIZjXVdQFZc92qAMG0sYG1hicprlHw "Haskell – Try It Online") *This one terminates in an error* # [Haskell](https://www.haskell.org/), ~~83~~ 79 bytes ``` g(a,_:b)=a++' ':b mapM_ putStrLn.(iterate$g.(span=<<(/=).minimum.concat.words)) ``` [Try it online!](https://tio.run/##DcyxCsMgEADQvV8hoRAl4bqH3N6hnTp0DJdEotQ7RQ39fNv3Ac9R@dgQWjs0jcu0GqRh6FU/rReHTOm5qHTWV80PAe2rzVTt9QBdEgnOs76hAfbi@WTYomxU4RvzXoxpTF7Qdfd/H0f1jjnsXfsB "Haskell – Try It Online") *This one terminates in an error* # [Haskell](https://www.haskell.org/), 86 bytes ``` u=concat.words g(a,_:b)=a++' ':b (take.length.u)<*>(iterate$g.(span=<<(/=).minimum.u)) ``` [Try it online!](https://tio.run/##Dc2xDoMgEADQ3a8whkSohu4GnLt36NicSoAIh4Ej/Xzq/pLnoJwmhNaq3hPuQPKX8lE6y2H@LpvQME1jPy5b5zQnOI0MBi05WYV6rNyTyUCGWcnLBaiV4k8tZPToY403Ei2CR31VelNmFYNHU5gbXnea5v6TcjiG9gc "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), ~~100~~ ~~91~~ 88 bytes ``` u=concat.words f x|(a,_:b)<-span(/=minimum(u x))x=a++' ':b (take.length.u)<*>(iterate f) ``` [Try it online!](https://tio.run/##Dc0xDoMgFADQ3VMQYyJUa3cjzt07dGy@ioUIHwOflKF3p30XeBrioawtJcnV4wo0fHzYYrWz/OXQv8ZFTNd4AvKbdAaNS44nloXIErquZe24VFpygkMNVuGb9JDEdJm5IRWAFNtFcWBQnokeFJqE1qCKja7v/9b37OmD3eryAw "Haskell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~80~~ 65 bytes ``` x=>[...x].sort().map(c=>x=x.replace(c,' ',c>' '&&console.log(x))) ``` [Try it online!](https://tio.run/##DcQxDsMgDADAr4QMwZZS/wD2Dn1B1QG5VpSKYASo8u9pb7hP@qbO7azjVvQtE6aF@CQie1HXNgDpShU4RAtGTWpOLMC7X/zO8f@2sZauWSjrAYaIE2G9@2t5SB5nOZxzK84f "JavaScript (Node.js) – Try It Online") Didn't know `replace` take string as string, not regexp [Answer] # [K4](http://kx.com/download/), ~~28~~ ~~20~~ 18 bytes **Solution:** ``` ?x{x[y]:" ";x}\<x: ``` **Example:** ``` q)k)?x{x[y]:" ";x}\<x:"PPCG is da BEST" "PPCG is da BEST" "PPCG is da EST" "PP G is da EST" "PP G is da ST" "PP is da ST" " P is da ST" " is da ST" " is da T" " is da " " is d " " is " " s " " " ``` **Explanation:** It's the same thing as [ngn](https://codegolf.stackexchange.com/a/162183/69200) is doing. Find indices that would result in an ascending list, overwrite them one-by-one with `" "`, then take the distinct to remove any duplicate lines: ``` ?x{x[y]:" ";x}\<x: / the solution x: / save input as x < / return indices that would result in ascending sort x{ ; }\ / two-line lambda with scan " " / whitespace : / assignment x[y] / x at index y x / return x ? / distinct ``` [Answer] # gcc 32-bit, ~~66~~ 65 bytes ``` char*p,i;f(a){for(i=32;i++;)for(p=a;*p;)*p==i?puts(a),*p=32:++p;} main(){char s[]="3.1415926";f(s);} ``` Thanks for Jonathan Frech for -1 byte [Answer] # MATLAB, 74 bytes This uses the 2-output form of the max() function to retrieve the smallest character and its index, having transformed the string to zero values in the spaces and 256-the character value for the printable characters. ``` s=input('s');x=1;while(x);disp(s);[x,y]=max((256-s).*(s~=' '));s(y)=' ';end ``` [Answer] # [Common Lisp](http://www.clisp.org/), ~~240~~ ~~228~~ 224 bytes ``` (setf s(read))(defun f(x)(setf y(char-code(elt s x)))(if(= y 32)1e9 y))(loop for _ across s do(print s)do(setf s(replace s" ":start1(position(code-char(reduce #'min (loop for i from 0 below(length s)collect i):key #'f))s)))) ``` [Try it online!](https://tio.run/##RY5NTgMxDIWv4pkuai8qtbCiEgdgwRlQSJzWIhNHcSo6px9cIcHOev7eTyxibdvQeGQw7BwSESbOtwoZ7/T7WDFeQz9ETYxcBhjcyTHJ@AorPD/RiV9gdaWoNsja4QNC7GrmaFJsXaq7yM@/olZCZLAZ5rON0McJm5oM0YqPnsOj0bF0c2q3X6TCf7pA7rrAET656DcWrpdx9fyopXAcIHT@4tVtmch8KW3b/LZf4N3HS71M0zT/AA "Common Lisp – Try It Online") This is my first time posting. I'm in the process of learning lisp so I'm sure someone can think of something shorter than this. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 bytes[SBCS](https://github.com/abrudz/sbcs) ``` {⎕←⍵⋄×≢⍵∩g←' '~⍨⎕UCS⍳256:∇' '@(⊃g⍋⍵)⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR31TgdSj3q2PulsOT3/UuQjE7FiZDhRUV1Cve9S7Aqgi1Dn4Ue9mI1Mzq0cd7UBhB41HXc3pj3q7gYo1H3WB9NQCzVP3SM3JyVcIzy/KSVFU50pTd0xyTnFNc8/wzPLO8c3zLwgsCi4JLQuviKwCyQYEOLsrZBYrpCQqOLkGh4CENKo1qms1gThaQzNWsxbIVgcA "APL (Dyalog Unicode) – Try It Online") Dfn. ### How? ``` {⎕←⍵⋄×≢⍵∩g←' '~⍨⎕UCS⍳256:∇' '@(⊃g⍋⍵)⊢⍵} ⍝ Main function, argument ⍵ ⎕←⍵⋄ ⍝ Print ⍵ g←' '~⍨⎕UCS⍳256 ⍝ Assign to g every Unicode character except space ×≢⍵∩ : ⍝ If ⍵∩g is not empty ∇ ⍝ Recursively call the function with argument: ' '@ ⍵ ⍝ Space at (⊃g⍋⍵) ⍝ The first (⊃) element in ⍵ graded up (⍋) with g ⍝ The dyadic grade up function will index ⍵ according ⍝ to its left argument, in this case g. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~103~~ 99 bytes ``` param($a)2..$a.length|%{($x=$a);[regex]$p=""+([char[]]$a-ne' '|sort)[0];$a=($p.replace($x," ", 1))} ``` [Try it online!](https://tio.run/##Dc1BCsIwEEDRq8RhpAnWoG5L9t7ARchiqEOziE2YFlqwnj1m@@HxS95Ylsgp1VpI6KORzMNaJJt4ntZ4nL8ad9fq4IUn3gMWB3DRfowkPgSk68yd6o4ly2r8LQxITmOxwiXRyE33oKBXd2N@tVZ4tllWryzpfYI/ "PowerShell – Try It Online") Takes input as a string into `$a`. We then loop from `2` to `$a.length` (i.e., the appropriate number of vertical times necessary to remove all but one character). Each iteration, we output the current string and conveniently saved into `$x` at the same time. We then construct a new `[regex]` object, `$p`attern consisting of the remaining characters in `$a` that are `-n`ot`e`qual to space, `sort`ed, then the `0`th one thereof. We then set `$a` equal to a new string of the regex object with the `.Replace` method to replace in the string `$x`, the `$p`attern, with a space `" "`, but only the `1`st match. Yeah, this syntax is weird. The strings are left on the pipeline and implicit `Write-Output` gives us a newline between them for free, plus one trailing newline. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 140 bytes ``` s->{for(int m=1,i;m>0;s=s.substring(0,i=s.indexOf(m=s.chars().filter(c->c>32).min().orElse(0)))+" "+s.substring(i+1))System.out.println(s);} ``` [Try it online!](https://tio.run/##bY4/T8MwEMX3foojk00aq4UxNAtiYEAMHRgQg@s45Yr/RL5LAVX97MFNB5DodPd@793p7fReV7v2Y0Tfx8Swy1oNjE5d17N/rBuCYYzhokmcrPYnyzhNBE8aAxxmAP2wcWiAWHMe@4gt@OyJNScM29c30GlLcooC3MdAg7fp7uw28BlT@2jQOAurkarm0MUkMDD41XKOtW8WNa1I0bCh6UIs5pg1htZ@PXfC592860RCqg4d2yRM1Zjm9kYqn0tIFdODIysWUsqygKL8@wvLpZTrb2LrVRxY9ZmyC4JkfRzrqfBvP6WNsT2L4iUjOLOrQp5ix9lx/AE "Java (JDK 10) – Try It Online") Technically there's a blank line, but it's not *empty*. [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü¡%/"=πbΓ ``` [Run and debug it](https://staxlang.xyz/#p=81ad252f223de362e2&i=Word+Icicle%21%0AI%27m+Melting%21%21%21%0AHello+World%21%0AAbCdEfGhIjKlMnOpQrStUvWxYz%0APPCG+is+da+BEST%0A%28%7B%28%7B%7D%29%28%7B%7D[%28%29]%29%7D%7B%7D%29&m=2) This is the same algorithm as [Luis' 05AB1E solution](https://codegolf.stackexchange.com/a/162206/527) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes ``` tSXz"tOy@=f1)(]x ``` [Try it online!](https://tio.run/##y00syfn/vyQ4okqpxL/SwTbNUFMjtuL/f/Xw/KIUBc/kzOScVEV1AA) Or [verify all test cases](https://tio.run/##y00syfmf8L8kOKJKqcS/0sE2zVBTI7bif4RLyH/18PyiFAXP5MzknFRFdS51T3X1XAXf1JySzLx0RUWQiEdqTk6@AlBZTgqI65jknOKa5p7hmeWd45vnXxBYFFwSWhZeEVkFlAwIcHZXyCxWSElUcHINDgGKaFRrVNdqAnG0hmasZi2QrQ4A). ### Explanation ``` t % Implicit input. Duplicate S % Sort Xz % Remove spaces " % For each char in that string t % Duplicate last result. This is the most recent string obtained % from replacing chars by spaces in the input O % Push 0 y % Duplicate from below @ % Push current char = % Equals? (element-wise) Gives 1 for occurrences of current char % in the most recent string, 0 otherwise f % Indices of nonzeros 1) % Get the first entry ( % Write 0 at that position. Char 0 will be displayed as space ] % End x % Delete last result, which consists only of space / char zero ``` [Answer] # Excel VBA, 167 bytes An anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window. ``` s="Code(Mid(A$1,Row(),1))":[B1].Resize([Len(A1)])="=If("&s &"=32,1E3,"&s &")":For i=1To[Len(A1)-CountIf(B:B,1E3)]:?[A1]:[A1]=[Substitute(A1,Char(Min(B:B))," ",1)]:Next ``` # Ungolfed and Commented ``` '' run as `call icicle("Test")` or `icicle"I am the WALRUS` Sub icicle(Optional str As String) If Not IsMissing(str) Then [A1] = str '' pipe input [B:B].Clear '' reset between runs [B1].Resize([Len(A1)]) = "=If(Code(Mid(A$1,Row(),1))=32,1E3,Code(Mid(A$1,Row(),1)))" '' get char number for every char in input For i = 1 To [Len(A1)-CountIf(B:B,1E3)] '' iterate across from 1 to length of input - number of spaces Debug.Print [A1] '' output a single line [A1]=[Substitute(A1,Char(Min(B:B))," ",1)] '' replace minimum char with space Next End Sub ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~32~~ 18 bytes *Saved 14 bytes thanks to Shaggy!* ``` rS ¬£=hSUbZn gYÃiN ``` [Try it online!](https://tio.run/##y0osKPn/vyhY4dCaQ4ttM4JDk6LyFNIjDzdn@v3/r@SY5Jzimuae4ZnlneOb518QWBRcEloWXhFZpcTFpRsEAA "Japt – Try It Online") ]
[Question] [ Given a string as input, print a new string with each letter pushed to the right by its respective alphabet index. We all know that A is a slow and Z is a fast letter. This means that Z gets shifted to the right by 25 spaces, A doesn't get shifted at all and B gets shifted by 1 space. Your program only has to handle uppercase letters from A-Z, and no other characters, no whitespaces, no punctuation. Note that if 2 or more letters fall onto the same space after shifting, the latest character will be used. (Example: `BA` -> `A`) ## Examples ``` "AZ" -> "A Z" "ABC" -> "A B C" "ACE" -> "A C E" "CBA" -> "  A" "HELLOWORLD" -> "  E H DLL OLO R W" ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in any language bytes wins. * Standard loopholes are forbidden. * Input must be received as a string. * You may print the result to `stdout` or return a string. * A *single* trailing whitespace and/or newline is allowed. * You may also use lowercase letters as input or output, but only use either case. [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` t=[] i=65 for c in input():t+=[' ']*26;t[ord(c)-i]=c;i-=1 print`t`[2::5].rstrip() ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8Q2OpYr09bMlCstv0ghWSEzD4gKSks0NK1KtG2j1RXUY7WMzKxLovOLUjSSNXUzY22TrTN1bQ25Cooy80oSShKijaysTGP1iopLijILNDT//1f3cPXx8Q/3D/JxUQcA "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` ''jtfy65-+( ``` [Try it online!](https://tio.run/##y00syfn/X109qySt0sxUV1vj/38PVx8f/3D/IB8XAA) Or [verify all test cases](https://tio.run/##y00syfmf8F9dPaskrdLMVFdb479LyH/HKC5HJ2cuR2dXLmcnRy4PVx8f/3D/IB8XAA). ### Explanation MATL indexing is 1-based. [This golfing trick](https://codegolf.stackexchange.com/a/133943/36398) is used here. [This other one](https://codegolf.stackexchange.com/a/86227/36398) cannot be used because we need an empty string, not an empty numeric array. Consider input `'ACE'` as an example. Stack contents are shown bottom to top. ``` '' % Push empty string % Stack: '' j % Input string % Stack: '', 'ACE' t % Duplicate % Stack: '', 'ACE', 'ACE' f % Indices of nonzero entries. Gives [1 2 ... n] where n is input length % Stack: '', 'ACE', [1 2 3] y % Duplicate from below % Stack: '', 'ACE', [1 2 3], 'ACE' 65 % Push 65 % Stack: '', 'ACE', [1 2 3], 'ACE', 65 - % Subtract, element-wise. Characters are converted to codepoints % Stack: '', 'ACE', [1 2 3], [0 2 4] + % Add, element-wise % Stack: '', 'ACE', [1 4 7] ( % Fill string '' with values 'ACE' at positions [1 4 7]. The original % empty string is extended. Non-existing values are filled with char 0, % which is displayed as space. Implicitly display % Stack: 'A C E' ``` [Answer] # [R](https://www.r-project.org/), ~~140~~ ~~133~~ ~~129~~ 74 bytes Saved a ton of bytes porting an ASCII value approach like everyone else. Sad I didn't think of it before :( ``` function(s){F[X-65+1:sum(X|1)]=X=utf8ToInt(s) F[is.na(F)]=32 intToUtf8(F)} ``` [Try it online!](https://tio.run/##K/qfk5lUlFhUqZGbWpKRn1KsyZWmYKP7P600L7kkMz9Po1iz2i06QtfMVNvQqrg0VyOixlAz1jbCtrQkzSIk3zOvBKiCyy06s1gvL1HDDShlbMSVmVcSkh8KVAAUqP2fpqHuGKUONFdD3dnJUV3zPwA) ### original answer, 129 bytes: ``` function(s){o=rep(' ',(n=nchar(s))+25) for(i in 1:n){k=substr(s,i,i) o[x<-i+match(k,LETTERS)-1]=k F=max(F,x)} cat(o[1:F],sep='')} ``` [Try it online!](https://tio.run/##HYqxCoMwFAB3v8It72EcLHQRM9iiU6fWqdYhWsVgTSSJYBG/PQ3djrvT7iNazfUX5t6O6m0wGMIsdsMqOyuUBIO7YrpfgISEgmSyG7n2FqPT2b9KgwiFDJNU4j4xs7bG@kwFFRioestiEc3cdiNM9FZUVXF/YJw0bApKNvMNSrrhEXTcgqqTtGyo6RdGCB5uAJI/Cf4beUlP3lwvOUH3Aw "R – Try It Online") generates a too-long list `o` of spaces, then iterates through `s`, replacing the values in `o` with the correct value and updating `F`, the position of the rightmost character. Then prints out the first `F` elements of `o` with no separators between them. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 16 bytes -4 bytes thanks to Emigna ``` ð₄×svyAuykN+ǝ}ðÜ ``` [Try it online!](https://tio.run/##ASQA2/8wNWFiMWX//8Ow4oKEw5dzdnlBdXlrTivHnX3DsMOc//9BQ0U "05AB1E – Try It Online") [Answer] # JavaScript (ES6), 81 bytes ``` s=>[...s].map((c,i)=>a[i+parseInt(c,36)-10]=c,a=[])&&[...a].map(c=>c||" ").join`` ``` Somewhat builds off of [Rick Hitchcock's incomplete answer](https://codegolf.stackexchange.com/a/145265/69583) but ended up rather different. Places the characters into their respective index of an empty array, then uses array spread (`[...a]`) to turn the missing elements into `undefined`, allowing `map` to replace empty elements with a space. ## Test Cases ``` let f= s=>[...s].map((c,i)=>a[i+parseInt(c,36)-10]=c,a=[])&&[...a].map(c=>c||" ").join`` ;["AZ", "ABC", "ACE", "CBA", "HELLOWORLD"] .forEach(t=>console.log(`"${t}"`, "=>", `"${f(t)}"`)) ``` [Answer] ## Perl 5, 42 bytes **41 bytes code + 1 for `-p`. The `\x1b`s in the code are literal escape characters.** Relies on ANSI escape sequences to position the cursor and therefore doesn't work on TIO. ``` s/./($-=-65+ord$&)?"\x1b[$-C$&\x1b[--$-D":$&/ge ``` ### Usage ``` perl -pe 's/./($-=-65+ord$&)?"\x1b[$-C$&\x1b[--$-D":$&/ge' <<< 'HELLOWORLD' E H DLL OLO R W ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~207~~ ~~191~~ ~~189~~ ~~183~~ ~~178~~ ~~174~~ ~~173~~ 170 bytes ``` s->{char i=0,l,c[]=new char[s.chars().map(j->j+s.lastIndexOf(j)).max().getAsInt()-64];for(;i<s.length();c[i+l-66]=l)l=s.charAt(i++);return"".valueOf(c).replace('',' ');} ``` [Try it online!](https://tio.run/##fY/NasMwEIR7zlMIXyxhW/RQclEcSP9owCXQHHowPqiyksiVZSGt04SQZ3edxqWF0uiyYmZ2lq/iW540VpqqfO9UbRsHqOo12oLSdOYc32fKAxv98f6RV60RoBpDb9Xj8L2UumuMb2vpLmV@eka2fdNKIKG59@iZK4MOHjj00ndosgSnzDpG5zlFWgJIt7RSlihFnU@mB7HhDqn0OtaxyIvUyA90knJPT8NjQmtucZVMq8jT/hTMTSl3ixWuyMna9YG1hJmfG8AkGd8UbNU4zNSkT0uzhg0mTOQq0sl4XKSa6PTcPAOsoogwJ6F1JgjolutW9r2CUCet5kLi8CqMQxQSduzYQDsQbhtVorpnxme0vECcoMMIDW@59yBr2rRAbe@DNvgXO@XW6j0Onh6ybPG6eMnuA0LY1/Lx2H0C "Java (OpenJDK 8) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 41 + (`-F`) = 43 bytes ``` map$r[$i++-65+ord]=$_,@F;print$_||$"for@r ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUClKFolU1tb18xUO78oJdZWJV7Hwc26oCgzr0QlvqZGRSktv8ih6P9/D1cfH/9w/yAfl3/5BSWZ@XnF/3V9TfUMDA3@67oBAA "Perl 5 – Try It Online") Just for @lynn [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 127 bytes ``` ,[[-<+<+>>]----[----<<->>]<<-[[>]>++++>[-<[-]<+>>]<[-<++++++++>]<[<]>-]>[>]<[-]+[<]>-[[>]<+[<]>-]>.[-]>[>]<[[->>+<<]<]>,]>>[.>] ``` [Try it online!](https://tio.run/##NYyxCgJBEEM/aG7uC0IqBYuFAxuLkEIFQQQLwe9fZ5fzFYFMkrl9rs/343t/9b5IiUCQzkJDgCxbKtGMglVSetYwBjvDwUxTM3BMO3aIPVn1j1VvA3DdF5Na6d5Px9a2y3Zuhx8 "brainfuck – Try It Online") ### Explanation ``` ,[ Take input and start main loop [-<+<+>>] Make two copies of input byte ----[----<<->>]<<- Subtract 64 from one of them to get position in alphabet There are two zero cells between the input and the remaining output cells; we wish to move these zeroes to indicate where the letter is to be moved [ A number of times equal to the position in the alphabet: [>] Go to current position in output string >++++> Create 4 (as part of creating a space if needed) [-<[-]<+>>] Move output byte back two cells; zero the previous 4 if output existed <[-<++++++++>] Otherwise move a space (32) into that position <[<]>- Move back to counter and decrement ] >[>]<[-] Delete last moved byte to make room for input byte +[<]>- Initialize slot at 1 so it is always nonzero in this loop [[>]<+[<]>-] Move input byte into slot >.[-] Output next output byte and clear >[>]< Move to space vacated in preparation to remove gap (Moves to end instead if input was A; this causes no problems) [[->>+<<]<] Move values two cells right until zero reached >, Get into position and take another byte of input ] >>[.>] Output characters beyond end of input ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 78 bytes ``` x=>{t=[' ']*26*(q=len(x))for i:0..q{t[i+ord(k=x[i])-65]=k}"".join(t).rstrip()} ``` [Try it online!](https://tio.run/##BcGxCsIwEADQXylZelcxiGAH4ZwUHAIFF4eQTQNnJUnPGwKl3x7fK5I1pxapVbqsSr7v@jAcxwEW@r4TVMSYpePzwdplVc@7LC@YqXoOuB9PgebNGPvJnEDRyk@FC@DWinBSiGDuN@em5/RwV4PY2h8 "Proton – Try It Online") 69 bytes by porting Lynn's solution: `x=>{t=[]i=65for k:x{t+=[' ']*26t[ord(k)-i]=k;i--}"".join(t).rstrip()}` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ØAiЀ+JṬ€a"⁸Zḟ€0Ṫ€o⁶ ``` [Try it online!](https://tio.run/##y0rNyan8///wDMfMwxMeNa3R9nq4cw2QTlR61Lgj6uGO@UC2wcOdq4BU/qPGbf////dw9fHxD/cP8nEBAA "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~90~~ 88 bytes ``` d=drop 1 [a]#s|s<"A"=a:d s|0<1=s b#s=(s++" ")!!0:d b#d s f(c:t)=['A'..c]#(' ':f t) f s=s ``` [Try it online!](https://tio.run/##FckxCoMwFADQPaf4JkMSLKKrmCFaoYNF6FKoSInaUKla8Tt69zRd3vLeBj@vaXJuUMP2XSEhjWkZHphRTZVJB8AjzhKFpGOoBIYhBSqDIPbTMb/Eij7dpWq45lHUt0xw4KmFXRILqNDNZlxAwWzW6xPEuo3LDhFYCQ3VD3qiOi/@FqW3yLX3UlZVfa9v1Zm27gc "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes ``` ;iB ç Ng £=hX10nY+XnG U ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O2lCIOcKTmcgoz1oWDEwblkrWG5HClU=&input=IkhFTExPV09STEQi) First attempt, may be improvable... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 76 bytes ``` SparseArray[Reverse@MapIndexed[#&@@#2+LetterNumber@#-1->#&,#]]<>""/. 0->" "& ``` Takes a list of characters as input. This generates some error messages that are safe to ignore. I included `Print` and `Character` command in the footer of the TIO link for ease of use. (`Character` command simply converts a string to a list of characters) [Try it online!](https://tio.run/##Dcu7CsIwFADQPV9REgiK1teqhogKCtFKOziEDNf2lnZIKbdR9OtjxzMcD6FBD6EtIdb7SSx6oAEPRPCzOX5whL5Bf@0q/GJlhdRabGYGQ0C6v/0LSYt0nSoh58K5neJ8uUhWqeIJl3G6fVDbBV3rYwME5XgGyxi/nI3JnlluTpwxF/8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # J, ~~37~~ 31 bytes ~~`[`]`(' '#~(1+>./)@])}(i.@#+65-~a.&i.)`~~ ``` [`]`(' '#~(1+>./)@])}#\-66-3&u: ``` -6 bytes thanks to FrownyFrog ### explanation The entire thing is a hook: ``` [`]`(' '#~(1+>./)@])} #\-66-3&u: ``` The right side calculates the new indexes for all the letters. The left side uses the gerund form of Amend `}` first to create a string of the necessary number of spaces: `(' '#~(1+>./)@])` . And then to place each letter of the original string into its appropriate index within the all-space string. [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6MTYhM01BXUles0DLXt9PQ1HWI1a5VjdM3MdI3VSq3@a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkK6QpqDs6u6rDOR6uPj7@4f5BPi7q/wE "J – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 88 bytes ``` foldr(\c->(((['B'..c]>>" ")++[c])#).(' ':))[] (x:r)#(y:t)|y>' '=y:r#t|1<3=x:r#t r#t=r++t ``` [Try it online!](https://tio.run/##Hc1BC4IwHAXwu5/izzy4YQrRbTRBTehgCHUI0h1kakVqYy5Q8LO3tMPj93iX9yiHV922ZpB1XQErTPNuK4UL4QUY49yJHN8XPAgQIOK6ueDEJj52wKGE5NzCI1XExhPVZJ6CZWYTVbaet/sdG9dmLWHKdbXpymcPDLpSngDLj75olfbgw/@ZQI7CG9oACqP4T5ysxFG4ckzSNLtm5/SAuPmKpi3vg/GElD8 "Haskell – Try It Online") [Answer] ## Haskell, 88 bytes ``` f s|q<-zipWith((+).fromEnum)s[0..]=[last$' ':[c|(c,i)<-zip s q,i==p]|p<-[65..maximum q]] ``` [Try it online!](https://tio.run/##XcrBCoIwGADge0/xI4JKOrrUIdxBTeggCF2Exg5DE39yczqFCN99QcddP75BmPdrHK3twexzmnxRN7gOYXiMSL9MslSbjAw7EcIpG4VZ/QCCK2v3sI0x@n8wMMdIqea7ThN2ORMixQflJmHm3EqBCih00wFAL6hW8KEHL3t6DuSFK0XpSJFnjtzLqqqb@lHdPPsD "Haskell – Try It Online") `q` is the list of the final indices of the letters of the input string (with an offset of `65`). Loop through all indices (starting at `65`) and find all letters for it, prepending a space. Take the last. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~117~~ ~~110~~ 84 bytes Saved 7 bytes thanks to **Ayb4tu**. Changed return type from `string` to `char[]` to save 26 bytes. ``` n=>{int i=0,l=n.Length;var t=new char[l+26];for(;i<l;)t[i+n[i]-65]=n[i++];return t;} ``` [Try it online!](https://tio.run/##PU/BaoNAED0nXzF4UjRSCs1ls4HUpu3BktAccpA9LNtVB8wIO5uUIn67VQw5zcybN@/NM7wyrbODaTQzHF1bOX2Bbrlgrz0auLX4A18aKWTvkKpCgXYVRxNlcfpjby/p@5XMZl4nYGrtCrWFEuRActsheUD5lDSS0txS5Wtx0w68JPs7k5v4ea1E2bpQ4KYRkS8wpgLVav2i5NjEsRLO@qsj8KIfxGj8@MVotgwSJrEH2EHwugsSCHbZfiqf@zw/nA/f@ds0HY/ZRwD9JDN6Wm1quGcDBqRZMoJ7tqwlbhubnh16myPZsAw5isbrftkP/w "C# (.NET Core) – Try It Online") [Answer] # **C# .NET, ~~89 Bytes~~ 87 Bytes** -2 bytes thanks to [Lan H.](https://codegolf.stackexchange.com/users/72738/ian-h) ``` f=>{var s=new char[f.Length+26];for(int i=0;i<f.Length;i++)s[f[i]+i-65]=f[i];return s;} ``` [Try it Online!](https://tio.run/##VVDBasMwDL33K0ROCWnDGKwX14Uu67ZDRsN26CHkYDwnEbQ2WG7HCPn2LF7WdH0H2XqSnp8laSGNVT0MkAdBBLk1tRXHmWfa3@hBTjiUcDb4CW8CdUjOoq6LEoStKZr6rhMeH9/k1DF5Pmm5GgfmIBthi3IN1UAC7yu@bs/CAnGtvsZilWRK166J75clq4wNUTtAfsdwdSkxjOOIiqrAMsbF8qHk/sqsciergVjX/7fBbkxNzqUgRcDBPzyRLQSPm2AOwSbd@uN1m2W7/e49e/JZnqcvAXS3goNFJWQDfzsBAtSjeHTZQGo0mYNK9hadylCr0H8/pCi6SnWzrv8B) [Answer] # Kotlin, ~~207 bytes~~ ~~189 bytes~~ ~~187 bytes~~ 177 bytes ``` fun main(){val i=(readLine()+" ".repeat(26)).toCharArray();for(x in(i.size-1) downTo 0){if(i[x]!=' '){i[x+i[x].toInt()-65]=i[x];i[x]=' '}};print(i.joinToString("").trim())} ``` If the leading blank should remain I would just call `trimEnd()` instead of `trim()`. **Unminified:** ``` fun main() { val m = (readLine() + " ".repeat(26)).toCharArray() for (x in (m.size - 1) downTo 0) { if(m[x] != ' ') { m[x + m[x].toInt() - 65] = m[x] m[x] = ' ' } } print(m.joinToString("").trim()) } ``` --- Maybe Kotlin is not the best language for code golfing but I liked the challenge and I wanted to make myself more familiar with Kotlin's standard library. [Answer] # q/kdb+, 37 bytes **Solution:** ``` @[max[1+m]#" ";m:!:[x#:]+.Q.A?x;:;]x: ``` **Examples:** ``` q)@[max[1+m]#" ";m:!:[x#:]+.Q.A?x;:;]x:"AZ" "A Z" q)@[max[1+m]#" ";m:!:[x#:]+.Q.A?x;:;]x:"ABC" "A B C" q)@[max[1+m]#" ";m:!:[x#:]+.Q.A?x;:;]x:"ACE" "A C E" q)@[max[1+m]#" ";m:!:[x#:]+.Q.A?x;:;]x:"CBA" " A" q)@[max[1+m]#" ";m:!:[x#:]+.Q.A?x;:;]x:"HELLOWORLD" " E H DLL OLO R W" ``` **Explanation:** I think this is the same idea as the J solution, calculate the correct indices for the input array and then assign them to an empty string of correct length: ``` @[max[1+m]#" ";m:til[count x]+.Q.A?x;:;]x: / ungolfed solution x: / save input as x @[ ; ; ;] / apply[variable;indices;function;parameters] : / assignment .Q.A?x / location of x in uppercase alphabet + / added to count x / length of input til[ ] / range, 0..n m: / save as m max[ ] / maximum of list 1+m / m + 1 #" " / take " ", creates empty character list ``` [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 91 bytes ``` reduce(explode|[.,keys]|transpose[]|.[1]+=.[0]-65)as[$c,$p]([];.[$p]=$c)|map(.//32)|implode ``` Expanded ``` reduce( explode # convert string to array of ordinals | [.,keys] # [ [v0,v1,...], [0,1,2,...] ] | transpose[] # [ [v0,0], [v1,1], [v2,2]...] | .[1]+=.[0]-65 # adjust position of each value ) as[$c,$p] ( [] ; .[$p]=$c # store each value at its position ) | map(.//32) # map null values to spaces | implode # convert back to string ``` [Try it online!](https://tio.run/##HYxNC8IgAIb/y9jB0XR9UJfYYVuDDoNBlyD1IJsHy6lNRwX@9ky6vDwPPLz3Z0iqG1FV3cRpWqKauiLq3HZdf@0v3YmoxFsjhQNJxAxTH2Y@LgMH/G2kHrnHKH/wj6XezUxZoy2PEcIbuioRXlN42GfM4nTIU0MBpkeEI5TpkPmJGYCKYrfNvJj@ZyF8tXFCKxsgVIuUUCizuCgze0G9uCg/ "jq – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` P FS«M⌕αι→ιM⌕αι← ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@3NKcks6AoM69EQ0lBSdOaKy2/SEHDM6@gtCS4BCicrqGpqVDNxembX5aq4ZaZl6KRqKOQqamjYBWUmZ5RAtTAGQDWnQliYqrySU0DKar9/9/D1cfHP9w/yMflv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` P Output a space to force the indent S Input string F « Loop over each letter α Uppercase letters predefined variable ⌕ ι Find index of current letter M → Move that many characters right ι Implicitly print the current letter M⌕αι← Move the same number of characters left ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 26 bytes Anonymous prefix lambda which takes the input string as argument and returns the output string. Assumes `⎕IO` (**I**ndex **O**rigin) `0`, which is default on many systems. ``` {⍵@i⊢''↑⍨1+⌈/i←(⎕A⍳⍵)+⍳≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/4MLUlNTgKzqR71bHTIfdS1SV3/UNvFR7wpD7Uc9HfqZQCkNoGrHR72bgSo0tUF05yIgs/Y/RK@CumOUOheM6eSMYDu7wtnOTo5wtoerj49/uH@Qj4s6AA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda; `⍵` represents the argument  `≢⍵` tally of the argument  `⍳` than many **ɩ**ntegers (0…LengthOfArgument-1)  `(`…`)+` plus:   `⎕A⍳⍵` the indices of the argument in the uppercase **A**lphabet  `i←` strore in `i` (for **i**ndices)  `⌈/` maximum (reduction)  `1+` add one  `''↑⍨` take that many characters from the empty string, padding with spaces as needed  `⊢` yield that (serves to separate `i` from `''`)  `⍵@i` amend that with the argument letters **at** the `i` indices [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 10 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ā,{ZFWē+1ž ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxJTJDJTdCWkZXJXUwMTEzKzEldTAxN0U_,inputs=SEVMTE9XT1JMRA__) Explanation: ``` ā push an empty array ,{ for each char in the input ZFW get its index in the uppercase alphabet ē+ add to that the 0-indexed counter 1ž at [pop; 1] insert in the array the current character ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~44~~ 38 bytes Striked out 44 is still 44 :( Bloody Pyth beginner. Saved 6 bytes thanks to @Mr. Xcoder. ``` K*d+lz26Vlz K=XK-C@zN-65N@zN;.WqeHdPZK ``` [Try it online!](https://tio.run/##K6gsyfj/31srRTunysgsLKdKwds2wlvX2aHKT9fM1A9IWeuFF6Z6pAREef//7@Hq4@Mf7h/k4wIA "Pyth – Try It Online") --- **How?** ``` K*d+lz26Vlz K=XK-C@zN-65N@zN;.WqeHdPZK Full program K*d+lz26 Assign a string consisting of (26 + input.length) whitespaces to K Vlz For-loop from 0 to input.length -C@zN-65N Calculate the index for the current letter @zN The current letter K=XK Insert the current letter into K at position i ; End statement .WqeHdPZK While the last character of H is not a whitespace, pop the last character off K ``` [Answer] # Batch, ~~418~~ 331 bytes Works with uppercase letters only and will take some seconds for longer strings. Learned new tricks here, the character to ASCII value conversion using `%=exitcodeAscii%`. Also, `if defined` and "array" access using `call`. Also, golfing by almost 100 bytes was good batch code golf training. Note the trailing space in `set z=set`. ``` @echo off setlocal EnableDelayedExpansion set z=set %z%a=%1 :a %z%v=64 :b %z%/Av+=1 cmd/Cexit %v% if %=exitcodeAscii% neq %a:~0,1% goto b %z%/Ao=v+c %z%a%o%=%a:~0,1% if %o%. geq %m%. %z%m=%o% %z%/Ac+=1 %z%a=%a:~1% if %a%. neq . goto a for /l %%n in (65,1,%m%)do ( if defined a%%n (call %z%r=%%r%%%%a%%n%% )else %z%r=!r! ) echo %r% ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 68 bytes ``` ->s{r,w="",-66;s.bytes{|b|r[(b+w+=1).times{|a|r[a]||=" "}]=b.chr};r} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ukin3FZJSUfXzMy6WC@psiS1uLomqaYoWiNJu1zb1lBTryQzFySWCBRLjK2psVVSUKqNtU3SS84oqrUuqv1fUFpSrJAWre7h6uPjH@4f5OOiHvsfAA "Ruby – Try It Online") [Answer] # x86-16 machine code, PC DOS, 27 bytes ``` 00000000: b403 cd10 d1ee ad98 91ac b402 8ad0 80ea ................ 00000010: 4102 d343 cd10 cd29 e2ef c3 A..C...)... ``` **Listing:** ``` B4 03 MOV AH, 3 ; get current cursor position row into DH CD 10 INT 10H ; call BIOS D1 EE SHR SI, 1 ; SI to DOS PSP AD LODSW ; AL = command line string length 98 CBW ; AH = 0 91 XCHG AX, CX ; CX = length OUTPUT: AC LODSB ; load DS:SI into AL B4 02 MOV AH, 2 ; BIOS set cursor position function 8A D0 MOV DL, AL ; ASCII char to DL 80 EA 41 SUB DL, 'A' ; convert ASCII char to numeric val (A=0, Z=25) 02 D3 ADD DL, BL ; add current position offset 43 INC BX ; increment position offset CD 10 INT 10H ; move cursor to column in DL CD 29 INT 29H ; write char in AL to console E2 EF LOOP OUTPUT ; loop until end of input C3 RET ; exit to DOS ``` Standalone PC DOS executable. Input from command line and prints the new "faster" version to console. **Output:** [![enter image description here](https://i.stack.imgur.com/HlPAN.png)](https://i.stack.imgur.com/HlPAN.png) [Answer] # PHP, ~~127~~ 123 bytes ``` function b($i){for($q=0;$q<strlen($i);$q++){$n[ord($i[$q])-65]=$i[$q];}while($x++<26){$m.=$n[$x-1]?$n[$x-1]:" ";}return$m;} ``` [Try it online](https://repl.it/Maak/2) Had to fix a bug that wouldn't output 'A'... ]
[Question] [ While there are many edit distance questions, such as [this one](https://codegolf.stackexchange.com/questions/51402/each-step-of-the-levenshtein-distance), there isn't a simple question to write a program that calculates the Levenshtein distance. **Some Exposition** [The Levenshtein edit distance between two strings](https://en.wikipedia.org/wiki/Levenshtein_distance) is the minimum possible number of insertions, deletions, or substitutions to convert one word into another word. In this case, each insertion, deletion and substitution has a cost of 1. For example, the distance between `roll` and `rolling` is 3, because deletions cost 1, and we need to delete 3 characterrs. The distance between `toll` and `tall` is 1, because substitutions cost 1. **Rules** * The input will be two strings. You may assume that the strings are lowercase, only contain letters, are non-empty and are a maximum of 100 characters in length. * The output will be minimum Levenshtein edit distance of the two strings, as defined above. * Your code must a program or a function. It does not need to be a named function, but it cannot be a built-in function that directly computes the Levenshtein distance. Other built-ins are allowed. * This is code golf, so the shortest answer wins. **Some Examples** ``` >>> lev("atoll", "bowl") 3 >>> lev("tar", "tarp") 1 >>> lev("turing", "tarpit") 4 >>> lev("antidisestablishmentarianism", "bulb") 27 ``` As always, if the problem is unclear, please let me know. Good luck and good golfing! ## Catalogue ``` var QUESTION_ID=67474;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=47581;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"http://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Matlab, ~~177~~ 163 bytes ``` function l=c(a,b);m=nnz(a)+1;n=nnz(b)+1;for i=0:m-1;for j=0:n-1;z=max(i,j);try;z=min([l(i,j+1)+1,l(i+1,j)+1,l(i,j)+(a(i)~=b(j))]);end;l(i+1,j+1)=z;end;end;l=l(m,n) ``` This is a straightforward implementation of this formula: [![enter image description here](https://i.stack.imgur.com/KFbN7.png)](https://i.stack.imgur.com/KFbN7.png) Ungolfed: ``` function l=l(a,b); m=nnz(a)+1; n=nnz(b)+1; for i=0:m-1; for j=0:n-1; z=max(i,j); try; z=min([l(i,j+1)+1,l(i+1,j)+1,l(i,j)+(a(i)~=b(j))]); end; l(i+1,j+1)=z; end; end; l=l(m,n) ``` [Answer] # Pyth, 34 bytes ``` J]wf}z=Jsmsm++.DdkXLdkGXLkdGhld-Jk ``` [Demonstration](https://pyth.herokuapp.com/?code=J%5Dwf%7Dz%3DJsmsm%2B%2B.DdkXLdkGXLkdGhld-Jk&input=turing%0Ataurin&debug=0) This is not particularly well golfed, and very slow. It can't handle anything past 2 changes in a reasonable period of time. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 34 bytes ``` {0∊≢¨⍵:≢∊⍵⋄⌊/(≢.↑+∘∇↓¨)∘⍵¨1↓,⍳2 2} ``` [Try it online!](https://tio.run/##LY3NSsNQEIX3eYrurqL9i4Jt32aS3LaD09yQe0MRcVdiWo1YiuBWV9lLXiCPMi8SJ2k3h3O@w5yBhIbRE5BZDUMCazFs@eMLDeefk3Yp@jzh4sD736bisl6I6WJZ89uO3w/jKwEjzo83XHxz8cr5qamuO1/WTTWVeMvlnz/wX9p2zvufpVprStRARTqB1G107JQ36wsy5lGKECjMCJxW3l3PwRkiKQKzJeVNe@YgFSKaKO/@TLIU49UFooz6D@fr2GGEVlsHAaFddx8hRYjRbrrRjAL1Dw "APL (Dyalog Classic) – Try It Online") [Answer] # JavaScript (ES6) 106 ~~113 122~~ **Edit** 16 bytes saved following @Neil suggestions As an anonymous function. ``` (s,t)=>[...s].map((u,i)=>w=w.map((v,j)=>p=j--?Math.min(p,v,w[j]-(u==t[j]))+1:i+1),w=[...[,...t].keys()])|p ``` This is a golfed implementation of the Wagner–Fischer algorithm exactly as described in the linked wikipedia article, in the section [**Iterative with two matrix rows**](https://en.wikipedia.org/w/index.php?title=Levenshtein_distance&action=edit&section=9) (even if in fact, just 1 row is used - array *w*) **Less golfed** ``` (s,t)=> { w = [...[0,...t].keys()]; for(i = 0; i < s.length; i++) w = w.map((v,j)=> p = j ? Math.min(p+1, v+1, w[j-1] + (s[i]!=t[j-1])) : i+1 ); return p } ``` **Test snippet** ``` L=(s,t)=>[...s].map((u,i)=>w=w.map((v,j)=>p=j--?Math.min(p,v,w[j]-(u==t[j]))+1:i+1),w=[...[,...t].keys()])|p console.log=x=>O.textContent+=x+'\n'; [["atoll", "bowl"],["tar", "tarp"] ,["turing", "tarpit"],["antidisestablishmentarianism", "bulb"]] .forEach(t=>console.log(t+' => '+L(...t))) ``` ``` <pre id=O></pre> ``` [Answer] # Python 2, ~~151~~ ~~140~~ 138 bytes Slow recursive implemention of the Levenshtein distance based on [Wikipedia](https://en.wikipedia.org/wiki/Levenshtein_distance) (Thanks to @Kenney for shaving of 11 chars and @Sherlock9 for another 2). ``` def l(s,t): def f(m,n): if m*n<1:return m or n return 1+min([f(m-1,n),f(m,n-1),f(m-1,n-1)-(s[m-1]==t[n-1])]) return f(len(s),len(t)) ``` Giving the correct answers for the presented test cases: ``` assert l("tar", "tarp") == 1 assert l("turing", "tarpit") == 4 assert l("antidisestablishmentarianism", "bulb") == 27 assert l("atoll", "bowl") == 3 ``` [Answer] # Python 2, 118 bytes A golf of [this solution](https://codegolf.stackexchange.com/a/67537/60919), but it doesn't look like Willem's been on for a year, so I'll have to post it myself: ``` def l(s,t):f=lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-(s[m-1]==t[n-1]));print f(len(s),len(t)) ``` [**Try on repl.it**](https://repl.it/Emfq/1) Takes two strings and outputs the distance to `STDOUT` ([allowed by meta](http://meta.codegolf.stackexchange.com/questions/8871/choosing-outputs-for-challenges/9658#9658)). Please comment suggestions, I'm sure this can be golfed further. [Answer] # [Haskell](https://www.haskell.org/), 67 bytes ``` e@(a:r)#f@(b:s)|a==b=r#s|1<3=1+minimum[r#f,e#s,r#s] x#y=length$x++y ``` [Try it online!](https://tio.run/##jc7NCsIwDAfwe5@irB42Ng9TQRA7fA/x0Gp1wbRKP9ShPvuMoujRUyC//JO0KuwNYt@bRa5mvhDbRa5nobgpKbX0Itzq@VjWpQUHNtmlF9vKiFCRrNhFdBKN28V2cCnLrkdz4pInt07edzwXBbMKHLWOHlzkA04DeaZchA0EE6LSCKG1xkXlQTkINqt4phPqrGDsOmRN07wz8YD4wsMZCcdfouwTqBwJ6h9IdHX3MYikk5@N/30xmrLhvX8A "Haskell – Try It Online") Example usage: `"turing" # "tarpit"` yields `4`. This is a recursive solution. Given two strings `e` and `f`, we first compare their first characters `a` and `b`. If they are equal, then the Levenshtein distance of `e` and `f` is the same as the Levenshtein distance of `r` and `s`, the remainder of `e` and `f` after removing the first characters. Otherwise, either `a` or `b` needs to be removed, or one is substituted by the other. `[r#f,e#s,r#s]` recursively computes the Levenshtein for those three cases, `minimum` picks the smallest one, and `1` is added to account for the necessary remove or replace operation. If one of the strings is empty, we and up on the second line. In this case, the distance is just the length of the non-empty string, or equivalently the length of both strings concatenated together. [Answer] # Python 3, ~~267~~ ~~216~~ ~~184~~ 162 bytes This function calculates the Levenshtein distance using an array that is `2 x len(word_2)+1` in size. **Edit:** This doesn't get close to the Willem's Python 2 answer, but here is a more golfed answer with many little refinements here and there. ``` def e(p,q): m=len(q);r=range;*a,=r(m+1);b=[1]*-~m for i in r(len(p)): for j in r(m):b[j+1]=1+min(a[j+1],b[j],a[j]-(p[i]==q[j])) a,b=b,[i+2]*-~m return a[m] ``` Ungolfed: ``` def edit_distance(word_1,word_2): len_1 = len(word_1) len_2 = len(word_2) dist = [[x for x in range(len_2+1)], [1 for y in range(len_2+1)]] for i in range(len_1): for j in range(len_2): if word_1[i] == word_2[j]: dist[1][j+1] = dist[0][j] else: deletion = dist[0][j+1]+1 insertion = dist[1][j]+1 substitution = dist[0][j]+1 dist[1][j+1] = min(deletion, insertion, substitution) dist[0], dist[1] = dist[1], [i+2 for m in range(len_2+1)] return dist[0][len_2] ``` [Answer] # [AutoIt](http://autoitscript.com/forum), 333 bytes ``` Func l($0,$1,$_=StringLen,$z=StringMid) Dim $2=$_($0),$3=$_($1),$4[$2+1][$3+1] For $5=0 To $2 $4[$5][0]=$5 Next For $6=0 To $3 $4[0][$6]=$6 Next For $5=1 To $2 For $6=1 To $3 $9=$z($0,$5,1)<>$z($1,$6,1) $7=1+$4[$5][$6-1] $8=$9+$4[$5-1][$6-1] $m=1+$4[$5-1][$6] $m=$m>$7?$7:$m $4[$5][$6]=$m>$8?$8:$m Next Next Return $4[$2][$3] EndFunc ``` Sample test code: ``` ConsoleWrite(l("atoll", "bowl") & @LF) ConsoleWrite(l("tar", "tarp") & @LF) ConsoleWrite(l("turing", "tarpit") & @LF) ConsoleWrite(l("antidisestablishmentarianism", "bulb") & @LF) ``` yields ``` 3 1 4 27 ``` [Answer] ## k4, 66 bytes ``` {$[~#x;#y;~#y;#x;&/.z.s'[-1 0 -1_\:x;0 -1 -1_\:y]+1 1,~(*|x)=*|y]} ``` A boring and basically ungolfed impl of the algo. Ex.: ``` f:{$[~#x;#y;~#y;#x;&/.z.s'[-1 0 -1_\:x;0 -1 -1_\:y]+1 1,~(*|x)=*|y]} f["kitten";"sitting"] 3 f["atoll";"bowl"] 3 f["tar";"tarp"] 1 f["turing";"tarpit"] 4 f["antidisestablishmentarianism";"bulb"] 27 ``` [Answer] ## Seriously, ~~86~~ ~~82~~ 78 bytes ``` ,#,#`k;;;░="+l"£@"│d);)[]oq╜Riu)@d);)@[]oq╜Riu(@)@)@[]oq╜Ri3}@)=Y+km"£@IRi`;╗ƒ ``` Hex Dump: ``` 2c232c23606b3b3b3bb03d222b6c229c4022b364293b295b5d6f71bd526975294064293b29405b 5d6f71bd5269752840294029405b5d6f71bd5269337d40293d592b6b6d229c40495269603bbb9f ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=2c232c23606c406c6b4d6032bf60b364293b295b5d6f71bd526975294064293b29405b5d6f71bd5269752840294029405b5d6f71bd526928282840293d592b6b6d60bc606b3b3b3bb03d32c040be40495269603bbb9f&input=atoll%5Cnbowl) (Note that the link is to a different version because something about the online interpreter breaks with the new, shorter version, even though it works fine with the downloadable interpreter.) It's about the most straightforward implementation Seriously allows for the recursive definition. It is very slow because it does no memoization at all. Perhaps the tabular method could be shorter (maybe by using the registers as rows), but I'm fairly happy with this, despite how much kludging-my-way-around-the-language's-shortcomings it contains. That one can use ``` []oq`<code>`Ri ``` as a proper two-argument function call was quite the nice find. Explanation: ``` ,#,# Read in two arguments, break them into lists of chars ` `;╗ƒ put the quoted function in reg0 and immediately call it k;;; put the two lists in a list and make 3 copies ░ replace the latter two with one with empty lists removed = replace two more with 1 if no empty lists removed, else 0 "..."£@"..."£@ push the two functions described below, moving the boolean above them both I select the correct function based on the condition Ri call the function, returning the correct distance for these substrings There are two functions that can be called from the main function above. Each expects two strings, i and j, to be on the stack. This situation is ensured by putting those strings in a list and using R to call the functions with that list as the stack. The first is very simple: +l Concatenate the strings and take their length. This is equivalent to the length of the longer string, since one of the strings will be empty. The second function is very long and complicated. It will do the "insertion, deletion, substitution" part of the recursive definition. Here's what happens in 4 parts: │d);) After this, the stack is top[i-,j,i,j,ci,i-], where i- is list i with its last character, ci, chopped off. []oq this puts i- and j into a list so that they can be passed as arguments recursively into the main function ╜Riu this calls the main function (from reg0) with the args which will return a number to which we add 1 to get #d, the min distance if we delete a character )@d);)@ After this, the stack is top[i,j-,ci,i-,#d,cj,j-], where j- and cj are the same idea as i- and ci []oq╜Riu listify arguments, recurse and increment to get #i (distance if we insert) (@)@)@ After this, the stack is top[i-,j-,#d,cj,#i,ci] []oq╜Ri listify arguments, recurse to get min distance between them but we still need to add 1 when we'd need to substitute because the chars we chopped off are different (((@) After this, the stack is top[cj,ci,#s,#d,#i] =Y 1 if they are not equal, 0 if they are + add it to the distance we find to get the distance if we substitute here k put them all in a list m push the minimum distance over the three options ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~78~~ 72 bytes ``` &`(.)*$(?<!(?=((?<-4>\4)|(?<-1>.(?<-4>)?))*,(?(4),))^.*,((.)|(?<-1>.))*) ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXy1BQ09TS0XD3kZRw95WA0jrmtjFmGjWgFiGdnoQAU17TU0tHQ17DRNNHU3NOD0gG6gNpgYop/n/f2JJfk6OTlJ@eQ5XSWKRDhAXgBgFmSU6JaVFmXnpXIlJySmpaTqJaUmpySkA "Retina – Try It Online") In a way, this is a pure regex solution where the result is the number of positions from which the regex matches. Because why not... Fair warning, this is super inefficient. The way this works is that it offloads the actual optimisation to the regex engine's backtracker, which simply brute forces all possible alignments, starting with as few alterations as possible and allowing one more until it's possible to match up the strings with additions, deletions and substitutions. For a slightly more sensible solution, [this one](https://tio.run/##NYtNCsIwEIX3uYYVZuwYUMjONksvIeKkTSUQ2hJG3Hj3OEVcPN7H@ylR0sx1D9dHtS2ARTw04C8d@A7Uj66/OfxsdOrtL0CvIwIPDgnxbpX1999oh6bZnWtlWXKmsLyzES6kWjdYk5C8SpqfhsMwxol4CnEYvw) does the matching only once and doesn't have any negative lookarounds. Here, the result is the number of captures in group `2`, which you could access with `match.Groups[2].Captures.Count` in C#, for example. It's still horribly inefficient though. ## Explanation I'm explaining the second version above, because it's conceptually a bit easier (as it's just a single regex match). Here is an ungolfed version I've named the groups (or made them non-capturing) and added comments. Remember that the components in a lookbehind should be read from back to front, but alternatives and lookaheads inside those should be read from front to back. Yeah. ``` .+ # Ensures backtracking from smallest to largest for next repetition (?<ops>(?<distance>.))* # This puts the current attempted distances onto two different stacks, # one to work with, and one for the result. $ # Make sure the lookbehind starts from the end. (?<= # The basic idea is now to match up the strings character by character, # allowing insertions/deletions/substitutions at the cost of one capture # on <ops>. Remember to read from the bottom up. (?= # Start matching forwards again. We need to go through the other string # front-to-back due to the nature of the stack (the last character we # remembered from the second string must be the first character we check # against in the first string). (?: (?<-str>\k<str>) # Either match the current character against the corresponding one from # the other string. | (?<-ops> # Or consume one operation to... . # consume a character without matching it to the other string (a deletion) (?<-str>)? # optionally dropping a character from the other string as well # (a substitution). ) )* # Rinse and repeat. ,(?(str),) # Ensure we reached the end of the first string while consuming all of the # second string. This is only possible if the two strings can be matched up # in no more than <distance> operations. ) ^.*, # Match the rest of string to get back to the front. (?: # This remembers the second string from back-to-front. (?<str>.) # Either capture the current character. | (?<-ops>.) # Or skip it, consuming an operation. This is an insertion. )* ) ``` The only difference to the 72-byte version is that we can drop the leading `.+` (and second group in the beginning) by finding positions at the end where we *don't* have enough `<ops>` and count all of those positions. [Answer] # JavaScript (ES6), ~~95 91~~ 89 bytes Takes input as `(source)(target)`. Essentially a port of [@Willem's Python answer](https://codegolf.stackexchange.com/a/67537/58563) (later [optimized by @FlipTack](https://codegolf.stackexchange.com/a/102910/58563)). ``` s=>t=>(g=m=>m*n?1+Math.min(g(m,--n),g(--m)-(s[m]==t[n++]),g(m)):m+n)(s.length,n=t.length) ``` [Try it online!](https://tio.run/##Zc7BbsIwDAbg@54C9eTQpogxCQkp3RPsCRCHFEJqFDuoNtvjdynqLsyX37K@X/LNf3s5j3hXy/kSpqubxHXqOoiOXEdr/tzWX16HlpAhAjXWsmkiWEvGghzp5Jweua5P85WMOVDNBqRNgaMODTtdVjOdM0tOoU05whUqrzmlykDV55@SZlVms1nt3l6c@nFWJe6LerrtP/cYkeMfRZ1xcR@vzrPiBSWI@j6hDBS4FNAzCj3feaR@6b7vp18 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 90 bytes ``` l=lambda a,b:min(l(A:=a[1:],B:=b[1:])-(a[0]==b[0]),l(A,b),l(a,B))+1if b>""<a else len(a+b) ``` [Try it online!](https://tio.run/##VU1BCsIwELz7ipBTgxFavEiwgv1G6WGXRruwSUOTIr6@phaFnmZ2ZnYmvNMw@vMlTMvCNYPDHgRoNI58wcXd1NBWptONqXEl6lRAW3Z1vspO6ZzQuALoRqljRQ@BNymvICxHK9j6Ao6oljCRT7lPxpTZU@ofUerw9yCNzFILieOLd06CadUzhL0@b22bRWlf5xP1FG1MgExxcNbnFIGn6L4rM2N@WD4 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~105~~ ~~94~~ ~~93~~ 99 bytes *-11 bytes by xnor* *+6 bytes to fix equal case* ``` l=lambda a,b:b>""<a and min(l(a[1:],b[1:])+(a[0]!=b[0]),l(a[1:],b)+1,l(a,b[1:])+1)or(a!=b)*len(a+b) ``` [Try it online!](https://tio.run/##VY2xDoMwDET3fgXNFJcMRd1Q2x@pGGyBSiQnQSSo6tenDhKoLD773uk8fdMY/C1nfjA66rFCQy09lbrL6vvKWa9Z46tpO0NlQi3XtTs/SCaYnUHdlGMLNRBmjZKCCw9eY02Qp9n6JG0KU2BWplIUPqwATjtJOBdfZDr6i2zvDdl0gOiT7W0cYkJiG0c3eElZ9Da69cvCdGyT6NpV9B8UU4z8Aw "Python 3 – Try It Online") [Answer] # Haskell, 136 bytes Call `e`. Bit slow on `antidisestablishmentarianism` etc. ``` l=length e a b=v a(l a)b(l b) v a i b j|i*j==0=i+j|0<1=minimum[1+v a(i-1)b j,1+v a i b(j-1),fromEnum(a!!(i-1)/=b!!(j-1))+v a(i-1)b(j-1)] ``` [Answer] # GNU Prolog, 133 bytes ``` m([H|A],B):-B=A;B=[H|A]. d([H|A]-[H|B],D):-d(A-B,D). d(A-B,D):-A=B,D=0;D#=E+1,m(A,X),m(B,Y),d(X-Y,E). l(W,D):-d(W,D),(E#<D,l(W,E);!). ``` Takes a tuple as argument. Example of usage: ``` | ?- l("turing"-"tarpit",D). D = 4 yes ``` `m` specifies that `B` is `A` either directly or with its first character removed. `d` uses `m` as a subroutine to calculate *an* edit distance between the tuple elements (i.e. the distance of a series of edits that converts one into the other). Then `l` is a standard trick for finding the minimum of `d` (you take an arbitrary distance, then take an arbitrary smaller distance, repeat until you can't go smaller). [Answer] # TI-Basic, ~~194~~ ~~175~~ 174 bytes ``` Prompt Str1,Str2 length(Str1→A length(Str2→B {A,B→dim([A] For(I,1,A For(J,1,B 3→dim(ʟA {I-1,J,I,J-1,I-1,J-1→B For(X,1,3 ʟB(2X-1→Y ʟB(2X→Z If YZ:Then [A](Y,Z Else max(Y,Z End Ans→ʟA(X End min(ʟA+{1,1,sub(Str1,I,1)≠sub(Str2,J,1→[A](I,J End End [A](A,B ``` -19 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) -1 byte by combining the 2 Prompts on the same line. The output is stored in `Ans` and is displayed at the end. [Answer] # Jolf, 4 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=fkxpSQ) ``` ~LiI ~L calculate the Levenshtein distance of i input string I and another input string ``` I added that builtin yesterday, but saw this challenge today, i.e., just now. Still, this answer is noncompeting. In a newer version: ``` ~Li ``` takes implicit second input. [Answer] # Perl, ~~168~~ ~~166~~ 163 bytes ``` sub l{my($S,$T,$m)=(@_,100);$S*$T?do{$m=++$_<$m?$_:$m for l($S-1,$T),l($S,--$T),l(--$S,$T)-($a[$S]eq$b[$T]);$m}:$S||$T}print l~~(@a=shift=~/./g),~~(@b=shift=~/./g) ``` Recursive implementation. Save in a `file.pl` and run as `perl file.pl atoll bowl`. ``` sub l { my($S,$T,$m)=(@_,100); $S*$T ? do { $m = ++$_ < $m ? $_ : $m for l($S-1, $T), l($S , --$T), l(--$S, $T) - ($a[$S] eq $b[$T]) ; $m } : $S||$T } print l~~(@a=shift=~/./g),~~(@b=shift=~/./g) ``` --- The other two implementations are both longer (full matrix: 237 bytes, ~~two~~one-row iterative: 187). * *update 166*: omit `()` in calling `l`. * *update 163*: eliminate `return` by abusing `do` in trinary. [Answer] # C, 192 bytes ``` #define m(x,y) (x>y?x:y) #define r(x,y) l(s,ls-x,t,lt-y) int l(char*s,int ls,char*t,int lt){if(!ls)return lt;if(!lt)return ls;a=r(1,1);if(s[ls]==t[ls])return a;return m(m(r(0,1),r(1,0)),a)+1;} --------- ``` Detailed ``` #include <stdio.h> #define m(x,y) (x>y?x:y) #define f(x) char x[128];fgets(x,100,stdin) #define r(x,y) l(s,ls-x,t,lt-y) int l(char*s,int ls,char*t,int lt) { if(!ls) return lt; if(!lt) return ls; int a = r(1,1); if(s[ls]==t[ls]) return a; return m(m(r(0,1),r(1,0)),a)+1; } int main(void) { f(a); f(b); printf("%d", l(a,strlen(a),b,strlen(b))); return 0; } ``` [Answer] # C#, ~~215~~ ~~210~~ 198 ``` public int L(string s,string t){int c,f,a,i,j;var v=new int[100];for(c=i=0;i<s.Length;i++)for(f=c=i,j=0;j<t.Length;j++){a=c;c=f;f=i==0?j+1:v[j];if(f<a)a=f;v[j]=c=s[i]==t[j]?c:1+(c<a?c:a);}return c;} ``` more readable: ``` public int L(string s,string t){ int c,f,a,i,j; var v=new int[100]; for(c=i=0;i<s.Length;i++) for(f=c=i,j=0;j<t.Length;j++){ a=c; c=f; f=(i==0)?j+1:v[j]; if (f<a) a=f; v[j]=c=(s[i]==t[j])?c:1+((c<a)?c:a); } return c; } ``` [Answer] ## PowerShell v3+, 247 Bytes ``` $c,$d=$args;$e,$f=$c,$d|% le*;$m=[object[,]]::new($f+1,$e+1);0..$e|%{$m[0,$_]=$_};0..$f|%{$m[$_,0]=$_};1..$e|%{$i=$_;1..$f|%{$m[$_,$i]=(($m[($_-1),$i]+1),($m[$_,($i-1)]+1),($m[($_-1),($i-1)]+((1,0)[($c[($i-1)]-eq$d[($_-1)])]))|sort)[0]}};$m[$f,$e] ``` I ended up making this to solve another challenges involving LD's. ### Code explanation with comments. ``` # Get both of the string passed as arguments. $c being the compare string # and $d being the difference string. $c,$d=$args # Save the lengths of these strings. $e is the length of $c and $f is the length of $d $e,$f=$c,$d|% le* # Create the multidimentional array $m for recording LD calculations $m=[object[,]]::new($f+1,$e+1) # Populate the first column 0..$e|%{$m[0,$_]=$_} # Populate the first row 0..$f|%{$m[$_,0]=$_} # Calculate the Levenshtein distance by working through each position in the matrix. # Working the columns 1..$e|%{ # Save the column index for use in the next pipeline $i=$_ # Working the rows. 1..$f|%{ # Calculate the smallest value between the following values in the matrix relative to this one # cell above, cell to the left, cell in the upper left. # Upper left also contain the cost calculation for this pass. $m[$_,$i]=(($m[($_-1),$i]+1),($m[$_,($i-1)]+1),($m[($_-1),($i-1)]+((1,0)[($c[($i-1)]-eq$d[($_-1)])]))|sort)[0] } } # Return the last element of the matrix to get LD $m[$f,$e] ``` ]
[Question] [ In this challenge, you are going to create a *Fellowship* with the goal of defeating all other fellowships in battle. **A fellowship (team) consists of 3 characters**. Each character moves independently of the rest of their team, but they will need to work together when fighting your enemy. Teams will face each other head to head in a rotating manner. Wins are worth 3 points, ties are worth 1 point, and losses are worth 0 points. Characters have Abilities. **The choice of what abilities your characters have is one of the most crucial (and fun) parts in this KotH**. They are all strong, and have the potential to wipe out your enemy. **Characters have Health Points (HP), and when their HP hits (or goes below) 0, they die**. If all characters on your opponent's team dies, then you win! **Characters have Mana. Most actions require Mana to perform**, and if you don't have enough, that action is not available to you. **Characters have a Turn Delay**. This determines the number of ticks between each turn (starts out at 100). Lower is better. **Characters have attributes**. Each character has a base of 5 in each attribute, and you are given 20 additional attribute points to divide up. After assigning attribute points, your *primary attribute* is set as your highest attribute. Available attributes are: * Strength: Gives 10 Max HP and .5 HP per turn * Intelligence: Gives 7 Max Mana and .1 Mana per turn * Agility: Reduces Turn Delay by 1 **Movement, Vision, Range** Ranges are as follows (centered around the 0). Some ranges are *cardinal*, which means that they can only go directly up, left, right, or down. ``` 444 43334 4322234 432111234 432101234 432111234 4322234 43334 444 ``` Characters have a starting vision of 2. Vision between players of the same fellowship is shared. # How to play **Construction** Players will construct their fellowship. **You need to do the following steps**: 1. **Give each character attribute points**. Each character starts out with 5 in each stat, with an additional 20 to distribute between the 3. 2. **Give each character abilities**. Each character starts out with 4 ability slots, and abilities take 1 slot by default. Some abilities are *repeatable*, and can be given to a character multiple times. Using an ability set of another submission without the owner's permission is not allowed. 3. **Write some code** for your bots. The code must be in Java, and will be used for battling (the next step) **Actions** All characters start with the 3 standard actions: 1. *Step*: Move your character in a cardinal range of 1 2. *Slice*: Attack an enemy for *PrimaryAttribute* in a cardinal range of 1 3. *Smile*: Do nothing On a characters' turn, then must pick an action to perform. Actions may have a Mana cost, and may have a Cooldown, which defines the number of turns you have to wait before performing that action again. **Abilities** Every character has 4 ability slots. If an ability is in italics, it is an action. # Abilities ``` Name Description Mana Cooldown **Mobility** *Blink* Move to a square, range 4 2 2 *Swap* Swap locations with Target 5 5 *Teleport* Move anywhere 20 5 Dash Increase the range of step by 1. Repeatable Mobile Step can move in any of the 8 directions **Attacking** *Quick* Slice twice 3 0 *Weave* Slice all visible enemies once 15 10 Absorb Each Slice steals 1 of your target's primary attribute. Lasts 20 turns Cleave Each Slice deals 1/2 damage to adjacent enemies Critital Adds a 30% chance for Slice to deal 200% damage. Repeatable Feast Each Slice increases your HP by 3. Repeatable Flexible Can Slice in any of the 8 directions Mana steal Slice steals 2 mana. Repeatable Reflexive Slice when sliced 0 3 Ranged Adds 1 to the range of Slice Swipe Each consecutive Slice on the same target deals 3 more damage than the last **Statuses** *Dispel* Removes all statuses from a Target. Range 2. 20 10 *Duel* Freezes you and your target until one of you dies. Range 1 25 0 *Knockout* You and target are stunned for the next 1000 ticks 10 10 *Meteor* All enemies are stunned for the next 100 ticks 25 10 *Leash* Target is frozen for their 2 next turns 4 6 *Poison* Poisons the enemy for 1 HP for 5 turns 5 0 *Silence* Target is silenced for 5 turns 5 7 *Slow* Target is slowed by 40 ticks for their next 3 turns 10 5 *Stun* Target is stunned for the next 300 ticks 10 10 Cold All other characters within 2 range are slowed by 10 ticks Immune No status can be applied to you **Defensive** *Force Field* Block next 5 sources of damage. Does not stack 15 5 *Ghost* For a turn, all damage heals 10 10 *Heal* Heal Target for 20 HP 10 3 *Restore* All units are restored back to full health 20 40 *Shield* You cannot be Sliced until your next turn 3 0 Evasive 25% chance for a Slice to not hit you. Repeatable Pillar Only can be sliced once a turn Resurrect When killed, come back to life with full HP (and no statuses) 0 40 Spikes When dealt damage, deal half of the damage back **Vision** *Cloak* Team becomes invisible for 5 turns 20 20 *Hide* You are invisible for 5 turns 4 7 *Phase* Become invisible for 1 turn 0 3 *Track* Target cannot go invisible, and takes 10% more damage. Lasts 10 turns. 5 5 Darkness Enemy sight range decreased by 1. Stacks, but cannot go below 1. Far sight Sight range increased by 2. Repeatable Invisible You are invisible if you start your turn out of enemy vision True sight Reveals all hidden units within range 2 at turn start **Damage** *Drain* Deals 5 damage to Target and heals self for 5 HP while they stay in 1 range 10 5 *Lightning* Deal 15 damage to all enemies 20 10 *K/O* Kills target if target is below 20% HP 20 0 *Trap* Place an invisible trap. Trap deals 15 damage when stepped on. Stacks. 10 2 *Zap* Deal 30 damage to target 30 5 Static Deals 5 damage every turn to all enemies within 1 range. Repeatable **Stats** *Werewolf* Add 10 to all stats for 5 turns 30 25 Buff Double your HP pool. Repeatable Clever Actions have 20% shorter cooldown. Repeatable Focused Increases your Mana regeration rate by Int/10. Repeatable Regenerate Increases your Regneration rate by Strength/2. Repeatable Smart Actions cost 2 less mana. Repeatable Strong You gain 10 attribute points. Repeatable Weak You lose 15 attribute points. You gain 2 ability slots (this takes one of them) **Other** *Bear* Can summon a bear which has 5 in each stat 8 10 *Clone* Clone yourself. Takes two ability slots. 100 100 *Steal* Replace this action with last action enemy Target used. Lasts 10 turns 5 0 *Wall* Create an impassible wall on targetted empty square, range 6 10 10 ``` # Statuses: * Stun allows your character to *only* perform the Smile action, and lasts X *ticks*. * Freeze prevents your character from moving, and lasts X turns. * Silence prevents your character from performing anything besides Smile, Step, or Slice, and lasts X turns. * Poison damages your character for X damage for Y turns. If you apply another poison, the damage adds together, and the duration is refreshed. * Slow adds X to the number of ticks between your turns. It does not affect your *upcoming* turn, only turns after. * Invisible makes it so you cannot be seen or damaged by your opponent. If you perform any action besides Step or Smile, it is removed. If your opponent has an ability that gives them vision of you, invisibility is removed. All statuses (except for Poison) act independently of each other. # Side Notes: * If there's a tie for the primary attribute, it is resolved as STR > AGI > INT. * You play on a 10x10 grid. Teams will be placed on opposite sides. * Percentages stack multiplicatively, except for Clever. # Submission rules You need to implement 2 functions: ``` // Create *exactly* 3 Character templates. You must return the same templates every time public List<CharacterTemplate> createCharacters(); // Choose an action for a character. If the action requires a target or location, it must be set. public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character); ``` You'll also have access to three variables (member variables): ``` Set<ReadonlyCharacter> team; Set<EnemyCharacter> enemies; Map<Point2D, EnemyCharacter> visibleEnemies; ``` That's it. Below you can find a complete API, in alphabetical order: ``` class Ability and ReadonlyAbility int getNumSlots() returns the number of slots it takes up boolean repeatable() returns true if the ability can be repeated String name() class Action and ReadonlyAction Set<Point2D> availableLocations() Set<ReadonlyCharacter> availableTargets() boolean basicAction() returns true if the action is Smile, Step, or Slice boolean breaksInvisibiliby() int getCooldown() returns the cooldown cost (not the cooldown remaining) int getManaCost() String getName() int getRemainingCooldown() boolean isAvailable() returns true if the action can be performed boolean movementAction() returns true if the action is prevented when Frozen boolean needsLocation() boolean needsTarget() void setTarget(ReadonlyCharacter target) void setLocation(Point2D location) class CharacterTemplate void addAbility(Ability) boolean canAddAbility(Ability) List<Ability> currentAbilities() Map<Stat, Integer> currentAttributes() int getRemainingPoints() returns the total number of ability points you have left to assign int getRemainingSlots() returns the total number of slots you have to assign int getStat(Stat stat) boolean isValid() returns true if your character template is complete and valid class Point2D getX() getY() class Range boolean isCardinal() returns true if the range only extends in the 4 cardinal directions int getRange() returns the distance of the range class ReadonlyCharacter and EnemyCharacter Class characterClass() int cleverness() List<ReadonlyAbility> getAbilities() Point2D getLocation() Not on EnemyCharacter double getHealth() double getMana() int getMaxHealth() int getMaxMana() Range getSightRange() Range getSliceRange() int getStat(Stat stat) Range getStepRange() ReadonlyAction getLastAction() boolean isFrozen() boolean isStunned() boolean isPoisoned() int getPoisonAmount() boolean isSilenced() boolean isInvisible() boolean isDead() Stat primaryStat() int smartness() enum Stat INT, STR, AGI ``` The above is all of the functions you could possibly need for your submission. Reflection is not allowed. **If a submission is invalid for whatever reason, please remove it or add "Invalid" to the header.** Your submission should *not* have a package declaration. Your submission should be contained in the first multi-line code block, and the first line must have the file name. # How to run the project: There are several ways: 1. Download the [JAR file](https://github.com/nathanmerrill/Fellowship/releases/tag/1.0.0), and run `java -jar Fellowship.jar`. If you want to download other submissions, pass `-q 99744`. `java` **must** point to the JDK, not the JRE. 2. Clone the [git repo](https://github.com/nathanmerrill/Fellowship), and run `gradle run`. You need to have gradle installed, and if you want to pass arguments, use `-PappArgs="['arg1', 'args2']"` 3. Clone the [git repo](https://github.com/nathanmerrill/Fellowship), and compile it yourself. You will need the following libraries: `org.eclipse.collections:eclipse-collections-api:8.0.0`,`org.eclipse.collections:eclipse-collections:8.0.0`,`com.beust:jcommander:1.48`,`com.google.code.gson:gson:2.7`,`org.jsoup:jsoup:1.9.2` **If you clone you must use the `--recursive` flag, and when you pull updates, include `--recurse-submodules`** For any of the above, your class needs to go in the `submissions/java` folder. If you are using gradle, or compiling it yourself, you can put the class in the project itself. You will need to uncomment some lines in the main function, and update them to point to your class. Scoreboard: ``` +------+-------------------+-------+ | Rank | Name | Score | +------+-------------------+-------+ | 1 | TheWalkingDead | 738.0 | | 2 | RogueSquad | 686.0 | | 3 | Spiky | 641.0 | | 4 | Invulnerables | 609.0 | | 5 | Noob | 581.0 | | 6 | Railbender | 561.0 | | 7 | Vampire | 524.0 | | 8 | LongSword | 508.0 | | 9 | SniperSquad | 456.0 | | 10 | BearCavalry | 430.0 | | 11 | StaticCloud | 429.0 | | 12 | PlayerWerewolf | 388.0 | | 13 | LongSwordv2 | 347.0 | | 14 | Derailer | 304.0 | | 15 | Sorcerer | 266.0 | | 16 | CowardlySniperMk2 | 262.0 | | 17 | TemplatePlayer | 59.0 | +------+-------------------+-------+ ``` If you have any questions, or need help, comment below, or join [the chatroom](http://chat.stackexchange.com/rooms/48475/battle-of-the-fellowships)! **Good luck and have fun** [Answer] # StaticCloud A sentient growing cloud which does static damage to anybody coming close. It consists of: * 1/3 **Invisible part** + **STR:** 5; **AGI:** 5; **INT:** 25 + **Clone**, **Invisible**, **Static** * 2/3 **Visible part** + **STR:** 5; **AGI:** 5; **INT:** 25 + **Clone**, **Static**, **Static** *You may reuse single characters from here in your team, as long as you add at least one more character which is not present here.* ``` StaticCloud.java import java.util.Arrays; import java.util.List; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.impl.factory.Sets; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.damage.Static; import fellowship.abilities.vision.Invisible; import fellowship.actions.ReadonlyAction; import fellowship.actions.other.Clone; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; public class StaticCloud extends SleafarPlayer { private CharacterTemplate invisibleTemplate() { return new CharacterTemplate(0, 0, 20, new ActionAbility(Clone::new), new Invisible(), new Static()); } private CharacterTemplate visibleTemplate() { return new CharacterTemplate(0, 0, 20, new ActionAbility(Clone::new), new Static(), new Static()); } @Override public List<CharacterTemplate> createCharacters() { return Arrays.asList(visibleTemplate(), invisibleTemplate(), visibleTemplate()); } private class InvisibleCloud extends Character { protected InvisibleCloud(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { ReadonlyAction clone = getAction(Clone.class); if (clone != null && (isVisible() || !isInEnemySightRange())) { int invisibleCount = countCharacters(InvisibleCloud.class); if (invisibleCount > 8 && setClosestSafeLocation(clone, getStaticLocations())) { return clone; } else if (setCloneLocation(clone, invisibleCount < 3 ? 3 : 1)) { return clone; } } if (step != null && isVisible() && isInEnemySliceRange() && setClosestSafeLocation(step, getStaticLocations())) { return step; } if (slice != null && isVisible() && setSliceTarget(slice, 0.01)) { return slice; } if (step != null) { ImmutableSet<Point2D> avoidLocations = !isVisible() || isInEnemySliceRange() ? Sets.immutable.empty() : getEnemySliceLocations(); if ((isVisible() || clone != null) && !getEnemyHiddenLocations().isEmpty() && setClosestLocation(step, avoidLocations, getEnemyHiddenLocations())) { return step; } if (!getStaticLocations().contains(getLocation()) && setClosestLocation(step, avoidLocations, getStaticLocations())) { return step; } } return smile; } } private class VisibleCloud extends Character { protected VisibleCloud(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { ReadonlyAction clone = getAction(Clone.class); if (clone != null) { int visibleCount = countCharacters(VisibleCloud.class); if (visibleCount > 5 && setClosestSafeLocation(clone, getStaticLocations())) { return clone; } else if (setCloneLocation(clone, visibleCount < 3 ? 2 : 1)) { return clone; } } if (step != null && isInEnemySliceRange() && setClosestSafeLocation(step, getStaticLocations())) { return step; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && !getStaticLocations().contains(getLocation())) { if (isInEnemySliceRange() ? setClosestLocation(step, getStaticLocations()) : setClosestSafeLocation(step, getStaticLocations())) { return step; } } return smile; } } @Override protected Character createCharacter(ReadonlyCharacter delegate) { if (hasAbility(delegate, Invisible.class)) { return new InvisibleCloud(delegate); } else { return new VisibleCloud(delegate); } } } ``` [Answer] # Template Player Uses **Ranged**, **Flexible**, **Zap**, and **KO**. You have permission to use this ability set if you wish. Feel free to use this bot as a template for creating your own. Remember that you need to change the filename on the first line, as well as selecting your own ability set. ``` TemplatePlayer.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Flexible; import fellowship.abilities.attacking.Ranged; import fellowship.actions.ReadonlyAction; import fellowship.actions.damage.KO; import fellowship.actions.damage.Zap; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.Player; import org.eclipse.collections.api.set.MutableSet; import java.util.ArrayList; import java.util.List; import java.util.Set; public class TemplatePlayer extends Player{ private final double CRITICAL_HEALTH = 20; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(10, 5, 5, new Ranged(), new Flexible(), new ActionAbility(KO::new), new ActionAbility(Zap::new))); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { int minPriority = Integer.MAX_VALUE; ReadonlyAction chosen = null; for (ReadonlyAction action: actions){ int priority = getPriorityFor(action, character); if (priority < minPriority){ chosen = action; minPriority = priority; } } if (chosen == null){ throw new RuntimeException("No valid actions"); } if (chosen.needsLocation()){ chosen.setLocation(chooseLocationFor(chosen, character)); } else if (chosen.needsTarget()){ chosen.setTarget(chooseTargetFor(chosen)); } return chosen; } private Point2D chooseLocationFor(ReadonlyAction action, ReadonlyCharacter character){ if (action.movementAction()){ if (character.getHealth() < CRITICAL_HEALTH){ return fromEnemy(action.availableLocations()); } else { return toEnemy(action.availableLocations()); } } return toTeam(action.availableLocations()); } private Point2D toEnemy(MutableSet<Point2D> availableLocations){ if (visibleEnemies.isEmpty()){ return availableLocations.iterator().next(); } return availableLocations.minBy(p1 -> p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)) ); } private Point2D fromEnemy(MutableSet<Point2D> availableLocations){ if (visibleEnemies.isEmpty()){ return availableLocations.iterator().next(); } return availableLocations.maxBy(p1 -> p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)) ); } private Point2D toTeam(MutableSet<Point2D> availableLocations){ if (team.isEmpty()){ return availableLocations.iterator().next(); } return availableLocations.minBy(p1 -> p1.cartesianDistance(team.collect(ReadonlyCharacter::getLocation).minBy(p1::cartesianDistance)) ); } private ReadonlyCharacter chooseTargetFor(ReadonlyAction action){ return action.availableTargets().minBy(ReadonlyCharacter::getHealth); } private int getPriorityFor(ReadonlyAction action, ReadonlyCharacter character){ if (character.isInvisible() && action.breaksInvisibility()){ return 1000; } if (action.getName().equals("Smile")){ return 999; } if (action.movementAction()){ if (character.getHealth() < 20){ return 0; } return 998; } if (action.needsTarget()) { return ((int) action.availableTargets().minBy(ReadonlyCharacter::getHealth).getHealth()); } return 997; } } ``` [Answer] # CowardlySniperMk2 Uses **Zap**, **FarSight** \*2, and **Hide**. This bot is a coward. Its highest priority is not to be targeted. To that end he uses its superior sight to see where enemies are. It uses this knowledge to avoid being seen whilst tracking/following the enemy with out being seen. If it is seen, or could be seen in the next turn then the bot will 'hide' becoming invisible for a time. In tracking mode, and there is sufficient mana and cooldown reset, then will 'Zap' the weakest visible enemy. Once mana is down to 10% then will shy away from enemies until mana is restored. In this way, it can zap as fast as possible on tracked enemy. Hopefully negating any HP regen the enemy has. Note since 'Zap' is infinite range, team members will all target the same bot when zapping. I have other varients of this same basic idea that I may add as answers: they all have differing benefits/detriments that are exploited/exposed depending on the opponents present. ``` CowardlySniperMk2.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.vision.FarSight; import fellowship.actions.ReadonlyAction; import fellowship.actions.damage.Zap; import fellowship.actions.vision.Hide; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import fellowship.*; public class CowardlySniperMk2 extends Player{ private final static boolean DEBUG=false; private static Point2D lastAttackedEnemyLocation = null; private static HashMap<ReadonlyCharacter, Boolean> rechargingManaMap = new HashMap<>(); private final double STANDARD_VISION_MOVEMENT_BUFFER = 3; private final double MIN_VISION_DISTANCE = 2; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(8, 8, 4, new ActionAbility(Zap::new), new FarSight(), new FarSight(), new ActionAbility(Hide::new))); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { // get last flag for recharging mana Boolean rechargingMana = rechargingManaMap.get(character); if (rechargingMana == null || rechargingMana) { rechargingMana = !(character.getMana()>0.90*character.getMaxMana()); } else { rechargingMana = character.getMana()<0.10*character.getMaxMana(); } rechargingManaMap.put(character,rechargingMana); HashMap<Integer, ReadonlyAction> validActions = new HashMap<>(); HashMap<Integer, String> actionString = new HashMap<>(); // see if we have arrived at the last attack location of the enemy if (character.getLocation().equals(lastAttackedEnemyLocation)) { lastAttackedEnemyLocation = null; } double closestEnemyVisionDistance = Double.MAX_VALUE; for ( Point2D enemyLocation : visibleEnemies.keySet()) { final int enemyVisibiltyRange = visibleEnemies.get(enemyLocation).getSightRange().getRange(); double visionDistanceDiff = character.getLocation().diagonalDistance(enemyLocation)-enemyVisibiltyRange; if (visionDistanceDiff< closestEnemyVisionDistance) { closestEnemyVisionDistance = visionDistanceDiff; } } for (ReadonlyAction action: actions){ int priority=-1; String message = ""; switch (action.getName()) { case "Hide": // are we, or will we be within sight range of an enemy if (closestEnemyVisionDistance < STANDARD_VISION_MOVEMENT_BUFFER ) { if (!character.isInvisible()) { message = ""+closestEnemyVisionDistance; priority = 1000; } } break; case "Step": Point2D chosenLocation = null; // are we within sight range of an enemy or are we recharging mana? if (closestEnemyVisionDistance < MIN_VISION_DISTANCE || rechargingMana) { message = "Fleeing (Seen) "+ closestEnemyVisionDistance; priority = 800; if (character.isInvisible()) { message = "Fleeing (UnSeen) "+ closestEnemyVisionDistance; priority = 500; } // simple enemy avoidance... chose location that is farthest away from closest enemy double furthestDistance = 0; for ( Point2D enemyLocation : visibleEnemies.keySet()) { for (Point2D location : action.availableLocations()) { if (location.diagonalDistance(enemyLocation) > furthestDistance) { furthestDistance = location.diagonalDistance(enemyLocation); chosenLocation = location; } } } if (chosenLocation == null) { // no moves are better than staying in current location priority = -1; break; } } // are we "tracking" an enemy? else if (lastAttackedEnemyLocation !=null) { priority = 20; message = "Tracking "+ closestEnemyVisionDistance; // head toward last attacked enemy location double distance = Integer.MAX_VALUE; for (Point2D location : action.availableLocations()) { if (location.diagonalDistance(lastAttackedEnemyLocation) < distance) { distance = location.diagonalDistance(lastAttackedEnemyLocation); chosenLocation = location; } } } // are we outside the sight range of all enemies? else if (closestEnemyVisionDistance > STANDARD_VISION_MOVEMENT_BUFFER) { // scout for an enemy priority = 10; message = "Scouting "+ closestEnemyVisionDistance; // dumb random location selection... not optimal but is sufficent. int index = getRandom().nextInt(action.availableLocations().size()); for (Point2D location : action.availableLocations()) { chosenLocation= location; if (--index == 0) { break; } } } else { // we are in the sweet zone... just out of enemy sight range but within our sight range break; } action.setLocation(chosenLocation); break; case "Zap": message = ""+closestEnemyVisionDistance; ReadonlyCharacter chosenTarget = null; double chosenTargetHealth = Double.MAX_VALUE; // target the weakest enemy for (ReadonlyCharacter target : action.availableTargets()) { if (target.getHealth() < chosenTargetHealth) { chosenTargetHealth = target.getHealth(); chosenTarget = target; } } if (chosenTarget != null) { priority = 100; action.setTarget(chosenTarget); lastAttackedEnemyLocation = chosenTarget.getLocation(); } else { // nothing to target } break; case "Smile": priority = 0; break; } // add the action to the collection of valid actions to perform if (priority >-1) { validActions.put(priority, action); actionString.put(priority, message); } } int highestPriority = -1; ReadonlyAction chosen = null; // choose the highest priority action for (Integer priority : validActions.keySet()) { if (priority > highestPriority) { highestPriority = priority; chosen = validActions.get(priority); } } String message = actionString.get(highestPriority); if (chosen == null){ throw new RuntimeException("No valid actions"); } if (DEBUG) System.out.println(this+"("+System.identityHashCode(character)+"): "+chosen.getName()+ (rechargingMana?" Mana_charge":" Mana_usable")+" H: "+character.getHealth()+" M: "+character.getMana() +(character.isInvisible()?" InVis":" Vis") +" x: "+character.getLocation().getX()+" y: "+character.getLocation().getY()+" "+message); return chosen; } } ``` [Answer] # TheWalkingDead Zombies, everyone knows them. They stay in a group doing nothing until someone shows up. They are hard to kill, and no matter how many you kill there are always more. And they usually appear out of nowhere just behind your back. * 1 x **Zombie #1** (the strongest, and therefore the alpha zombie) + **STR:** 25; **AGI:** 5; **INT:** 15 + **Clone**, **Resurrect**, **Strong** * 2 x **Zombie #2** (no one wanted to be Zombie #3 in the closing credits, therefore both got the same number) + **STR:** 15; **AGI:** 5; **INT:** 15 + **Clone**, **Resurrect**, **Absorb** *You may reuse single characters from here in your team, as long as you add at least one more character which is not present here.* ``` TheWalkingDead.java import java.util.Arrays; import java.util.List; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Absorb; import fellowship.abilities.defensive.Resurrect; import fellowship.abilities.stats.Strong; import fellowship.actions.ReadonlyAction; import fellowship.actions.other.Clone; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; public class TheWalkingDead extends SleafarPlayer { private CharacterTemplate zombie1Template() { return new CharacterTemplate(20, 0, 10, new ActionAbility(Clone::new), new Resurrect(), new Strong()); } private CharacterTemplate zombie2Template() { return new CharacterTemplate(10, 0, 10, new ActionAbility(Clone::new), new Resurrect(), new Absorb()); } @Override public List<CharacterTemplate> createCharacters() { return Arrays.asList(zombie1Template(), zombie2Template(), zombie2Template()); } private class Zombie extends Character { private int resurrectCountdown = 0; private double oldHealth; protected Zombie(ReadonlyCharacter delegate) { super(delegate); this.oldHealth = getHealth(); } @Override protected ReadonlyAction choose() { if (getHealth() > oldHealth + getHealthRegen() + 0.1) { resurrectCountdown = 40; } if (resurrectCountdown > 0) { --resurrectCountdown; } oldHealth = getHealth(); ReadonlyAction clone = getAction(Clone.class); if (resurrectCountdown > 0) { if (step != null && isInEnemySliceRange() && setAvoidEnemiesLocation(step)) { return step; } if (clone != null && !getSliceLocations().isEmpty() && setClosestLocation(clone, getSliceLocations())) { return clone; } if (clone != null && setCloneLocation(clone, 1)) { return clone; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && setAvoidEnemiesLocation(step)) { return step; } } else { if (clone != null && !getSliceLocations().isEmpty() && setClosestLocation(clone, getSliceLocations())) { return clone; } if (clone != null && setCloneLocation(clone, 1)) { return clone; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && !getSliceLocations().isEmpty() && setClosestLocation(step, getSliceLocations())) { return step; } } return smile; } } @Override protected Character createCharacter(ReadonlyCharacter delegate) { return new Zombie(delegate); } } ``` [Answer] # The Invulnerables A team of hardy warriors who can survive almost everything. This leads to a lot of timeouts, which unfortunately I often don't win. However, no matchup I've seen is unwinnable, and when the team loses, it's frequently with characters still surviving. This team's hardest matchups are against the Bear Cavalry (they are literally incapable of wiping this team, but normally win on the tiebreak due to their sheer numbers); the Rogue Squad (the team is somewhat weak to poison); and the Vampire (I'm not entirely sure why yet). In simulations, the team nearly always comes first or second. Its score is pretty stable; the winner normally depends on how well Rogue Squad does against the other competitors (its placement is a lot more random than the Invulnerables' is). ## The Mage in the Noxious Sphere * **STR**: 5; **AGI**: 5; **INT**: 25 The Mage protects itself via using the combo of **Pillar** and **Force Field**; being **Focused** and having a high Intelligence, it regenerates enough mana to cast Force Field on cooldown each time. Assuming that the opponents don't have a boosted Agility, they can thus hit it with at most five Slices per five turns, and five damage sources will be blocked over that time period. In other words, the Mage absolutely requires spells to defeat; Slicing doesn't work by itself no matter how good at it you are. The Mage can attack via Slicing for 25 in an emergency, but mostly casts **Poison** repeatedly, which is very spammable with an MP regeneration this high. Because Poison has an infinite range, limited only by the team's vision, the Mage is the way this team beats very HP-heavy or regenerative enemies; the rest of the team maintains vision on them, while the Mage deals quadratic amounts of damage. The poison inevitably ends up outpacing their HP regeneration eventually, and I don't have to worry about static damage such as Spikes in the process. ## The Giant Clifftop Falconer * **STR**: 35; **AGI**: 5; **INT**: 5 The Falconer's main job is to get the rest of the team vision of targets, so that they can be attacked, scouting the map with the eyes of a falcon. **Far Sight** gives enough vision that enemies who try to hide or run away can normally be trapped by the vision range in a corner of the map; it's not very easy to give the Falconer the runaround. **True Sight** is this team's main recourse against invisible enemies, who would otherwise be impossible to damage. Being large, and thus **Strong**, makes the Falconer very resistant to damage, and capable of heavy Slices when necessary. Finally, the Falconer can release its falcons on the enemy crowds below, ordering them to **Weave** among the enemy and dealing massive (35) area damage. In addition to the Falconer's job hunting down evasive enemies, and maintaining vision of enemies so that the Mage can keep poisoning them, the ability to occasionally Weave for 35 is key to dealing with enemy swarm teams; it's possible to hit a lot of enemies that way, and leave them low enough for the rest of the team to finish (ideally with another Weave). Swarming is pretty much an overpowered strategy under these rules, and Weave is one of the few real counters it has. Even then, it's not really good enough by itself. ## Trollbone Skullrender * **STR**: 25; **AGI**: 5; **INT**: 5 Trollbone's job is to keep the enemy hordes suppressed while the other units can do their job. Just like the Mage, Trollbone has an infinite-range spell in **Knockout**. This combos very well with the Mage's Poison; if it's ever possible to face the enemy one-by-one (and against many teams, it is), the Falconer will gain vision, Trollbone will stun them, then the Mage will stack poison on them, and they'll end up dead without the ability to do anything (Knockout lasts 1000 ticks on the target and Trollbone's regenerates the cooldown for it slightly faster than that). It's also very good at protecting Trollbone against single strong enemies; they can't do anything to him if they aren't conscious. Of course, smashing skulls with an enemy is liable to leave both concussed, but Trollbone is **Immune** to stun and poison (and a bunch of other statuses nobody cares about). As a spell-focused character who nonetheless is not very magically inclined, Trollbone regenerates magic not through intelligence, but through drinking the blood of his enemies, doing a **Mana Steal** with every hit; this gives a pretty good rate of MP regeneration (and stunned enemies make easy targets to steal MP from). Finally, Trollbone occasionally goes on a rampage and will **Weave** through the enemy ranks while smashing their heads in and drinking their blood. Against a sufficiently large swarm of enemies, this actually regains mana, and it can finish off a swarm that the Falconer weakened (25 + 35 is 60, so it works even if the enemies regenerated to some extent in between). ## Strategy Unlike many teams, I put a lot of focus into the AI, not just the teambuilding. One fundamental rule is that the team will always try to group if they aren't busy doing something else, making it harder for them to get surrounded and able to defend each other. If they're being swarmed, they'll try to hide in a corner. On the other hand, if the enemy tries to flee or run away, they roam the map, picking and pathing to random corners or the centre; this more or less guarantees that the Falconer will spot a target eventually. The movement is designed to never let the enemy get the first strike if possible; the enemy will have to walk into Slice range themself. The Mage will *always* leave up MP for Force Field, preventing a loss to MP exhaustion (the only way this can fail is with Absorb, which can get through a Force Field even if the damage doesn't). This isn't normally a problem; usually the Mage can spam Poison every turn without issues. If not intefered with, the team prefers to chase down enemies one at a time, stunning them when they come into vision, then poisoning them repeatedly until they die. With other enemies around, the team will try to kite them if possible, running around in circles and forcing most of the enemies to chase, while stunning and poisoning one of them. The main problem is with swarms, which is why there's so much Weaving here, but even then it seems hard to actually beat the strategy. ``` Invulnerables.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.*; import fellowship.abilities.attacking.*; import fellowship.abilities.defensive.*; import fellowship.abilities.vision.*; import fellowship.abilities.stats.*; import fellowship.abilities.statuses.*; import fellowship.actions.*; import fellowship.actions.attacking.*; import fellowship.actions.damage.*; import fellowship.actions.defensive.*; import fellowship.actions.statuses.*; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.characters.EnemyCharacter; import fellowship.*; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Invulnerables extends Player { @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); templates.add(new CharacterTemplate(0, 0, 20, new ActionAbility(Poison::new), new ActionAbility(ForceField::new), new Focused(), new Pillar())); templates.add(new CharacterTemplate(30, 0, 0, new ActionAbility(Weave::new), new Strong(), new FarSight(), new TrueSight())); templates.add(new CharacterTemplate(20, 0, 0, new ActionAbility(Weave::new), new ActionAbility(Knockout::new), new ManaSteal(), new Immune())); return templates; } private String lastIdentifier(String s) { String[] split = s.split("\\W"); return split[split.length - 1]; } private boolean hasAbility(ReadonlyCharacter character, String abilityName) { for (ReadonlyAbility ability : character.getAbilities()) { if (lastIdentifier(ability.name()).equals(abilityName)) return true; } return false; } private boolean hasAbility(EnemyCharacter character, String abilityName) { for (ReadonlyAbility ability : character.getAbilities()) { if (lastIdentifier(ability.name()).equals(abilityName)) return true; } return false; } private int getSquareDanger(ReadonlyCharacter character, Point2D square) { /* A square's danger is basically equal to the number of hits we'd expect to take when standing there. Each hit is worth 1; a hit of 25 damage or more is worth 2. */ int sliceDanger = 0; int otherDanger = 0; int cx = square.getX(); int cy = square.getY(); for (Point2D enemyLocation : visibleEnemies.keysView()) { EnemyCharacter enemy = visibleEnemies.get(enemyLocation); if (enemy.isStunned()) continue; /* approaching stunned enemies is a good thing */ int dx = enemyLocation.getX() - cx; int dy = enemyLocation.getY() - cy; if (dx < 0) dx = -dx; if (dy < 0) dy = -dy; if (dx + dy <= 1) { /* We're in Static range. */ if (hasAbility(enemy, "Static")) otherDanger++; } if (dx + dy <= enemy.getSliceRange().getRange() && (dx * dy == 0 || !enemy.getSliceRange().isCardinal())) { int sliceMultiplier = 1; if (hasAbility(enemy, "Quick") && !hasAbility(character, "Pillar")) sliceMultiplier *= 2; if (enemy.getStat(enemy.primaryStat()) >= 25) sliceMultiplier *= 2; if (hasAbility(character, "Pillar")) { if (sliceDanger >= sliceMultiplier) continue; sliceDanger = 0; } sliceDanger += sliceMultiplier; } } return sliceDanger + otherDanger; } private ReadonlyAction[] forceFieldAction = new ReadonlyAction[3]; private int goalX = 5; private int goalY = 5; @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { /* Which character are we? */ int characterNumber; if (hasAbility(character, "Focused")) characterNumber = 0; else if (hasAbility(character, "Immune")) characterNumber = 1; else if (hasAbility(character, "TrueSight")) characterNumber = 2; else throw new RuntimeException("Unrecognised character!"); /* If we're at the goal square, pick a new one. */ if (goalX == character.getLocation().getX() && goalY == character.getLocation().getY()) { int i = getRandom().nextInt(5); goalX = i < 2 ? 1 : i > 2 ? 9 : 5; goalY = i == 2 ? 5 : (i % 2) == 1 ? 1 : 9; } /* If there are a lot of visible enemies, try to group up in a corner in order to prevent being surrounded. */ if (visibleEnemies.size() > 3) { int xVotes = 0; int yVotes = 0; for (ReadonlyCharacter ally : team) { xVotes += ally.getLocation().getX() >= 5 ? 1 : -1; yVotes += ally.getLocation().getY() >= 5 ? 1 : -1; } goalX = xVotes > 0 ? 9 : 0; goalY = yVotes > 0 ? 9 : 0; } /* We need to know our Force Field cooldowns even between turns, so store the actions in a private field for later use (they aren't visible via the API) */ for (ReadonlyAction action : actions) { if (action.getName().equals("ForceField")) forceFieldAction[characterNumber] = action; } /* If we know Force Field, ensure we always hang on to enough mana to cast it, and never allow our mana to dip low enough that it wouldn't regenerate in time. */ double mpFloor = 0.0; if (forceFieldAction[characterNumber] != null) { double mpRegen = character.getStat(Stat.INT) / 10.0; if (hasAbility(character, "Focused")) mpRegen *= 2; mpFloor = forceFieldAction[characterNumber].getManaCost(); mpFloor -= forceFieldAction[characterNumber].getRemainingCooldown() * mpRegen; } if (mpFloor > character.getMana()) mpFloor = character.getMana(); /* We use a priority rule for actions. */ int bestPriority = -2; ReadonlyAction bestAction = null; for (ReadonlyAction action : actions) { int priority = 0; if (lastIdentifier(action.getName()).equals("ForceField")) priority = 20; /* top priority */ else if (character.getMana() - action.getManaCost() < mpFloor) { continue; /* never spend mana if it'd block a force field */ } else if (lastIdentifier(action.getName()).equals("Quick") || lastIdentifier(action.getName()).equals("Slice")) { int damagePotential = lastIdentifier(action.getName()).equals("Quick") ? 50 : 25; /* We use these abilities with very high priority to /kill/ an enemy who's weak enough to die from the damage. If they wouldn't die, we're much more wary about attacking; we do it only if we have nothing better to do and it's safe. */ ReadonlyCharacter chosenTarget = null; for (ReadonlyCharacter target : action.availableTargets()) { if (!isEnemy(target)) continue; if (target.getHealth() <= damagePotential) { chosenTarget = target; priority = (damagePotential == 25 ? 19 : 18); break; /* can't do beter than this */ } if (hasAbility(target, "Spikes") || hasAbility(target, "Reflexive")) /* (target.getLastAction() != null && target.getLastAction().getName().equals("Ghost")) */ continue; /* veto the target */ priority = (damagePotential == 25 ? 3 : 4); chosenTarget = target; } if (chosenTarget == null) continue; action.setTarget(chosenTarget); } else if (lastIdentifier(action.getName()).equals("Weave")) { priority = visibleEnemies.size() >= 3 ? 14 : visibleEnemies.size() >= 1 ? 6 : -1; } else if (lastIdentifier(action.getName()).equals("Smile")) { /* If there's a stunned or poisoned enemy in view, we favour Smile as the idle action, rather than exploring, so that we don't move it out of view. Exception: if they're the only enemy; in that case, hunt them down. Another exception: if we're running into a corner. */ for (EnemyCharacter enemy : visibleEnemies) { if (enemy.isStunned() || enemy.isPoisoned()) if (visibleEnemies.size() > 1 && visibleEnemies.size() < 4) priority = 2; } /* otherwise we leave it as 0, and Smile only as a last resort */ } else if (lastIdentifier(action.getName()).equals("Knockout")) { /* Use this only on targets who have more than 50 HP. It doesn't matter where they are: if we can see them now, knocking them out will guarantee we can continue to see them. Of course, if they're already knocked out, don't use it (although this case should never come up). If there's only one enemy target in view, knocking it out has slightly higher priority, because we don't need to fear enemy attacks if all the enemies are knocked out. Mildly favour stunning poisoned enemies; this reduces the chance that they'll run out of sight and reset the poison. */ ReadonlyCharacter chosenTarget = null; for (ReadonlyCharacter target : action.availableTargets()) if ((target.getHealth() > 50 || target.isPoisoned()) && !target.isStunned() && isEnemy(target)) { chosenTarget = target; if (target.isPoisoned()) break; } if (chosenTarget == null) continue; action.setTarget(chosenTarget); priority = visibleEnemies.size() == 1 ? 17 : 15; } else if (lastIdentifier(action.getName()).equals("Poison")) { /* Use this preferentially on stronger enemies, and preferentially on enemies who are more poisoned. We're willing to poison almost anyone, although weak enemies who aren't poisoned are faster to kill via slicing. The cutoff is at 49, not 50, so that in the case of evasive enemies who we can't hit any other way, we can wear them one at a time using poison. */ ReadonlyCharacter chosenTarget = null; int chosenTargetPoisonLevel = -1; for (ReadonlyCharacter target : action.availableTargets()) { int poisonLevel = 0; if (!isEnemy(target)) continue; if (target.isPoisoned()) poisonLevel = target.getPoisonAmount() + 1; if (poisonLevel < chosenTargetPoisonLevel) continue; if (poisonLevel == 0 && target.getHealth() <= 49) continue; /* prefer stronger targets */ if (poisonLevel == 0 && target.getHealth() == 50 && chosenTarget != null) continue; /* we poison at 50, but not with other options */ chosenTarget = target; chosenTargetPoisonLevel = poisonLevel; priority = 12; } if (chosenTarget == null) continue; action.setTarget(chosenTarget); } else if (action.movementAction()) { /* A move to a significantly safer square is worth 16. A move to a mildly safer square is worth 8. Otherwise, move to group, either with the enemy, the team, or the goal, at priority 1, if we safely can; that's our "idle" action. */ int currentSquareDanger = getSquareDanger(character, character.getLocation()); int bestSquareDanger = currentSquareDanger; int bestGroupiness = 0; Point2D bestLocation = null; priority = 1; for (Point2D location : action.availableLocations().toList().shuffleThis(getRandom())) { int danger = getSquareDanger(character, location); if (danger > bestSquareDanger) continue; else if (danger < bestSquareDanger) { priority = (currentSquareDanger - danger > 2) ? 16 : 8; bestSquareDanger = danger; bestLocation = location; bestGroupiness = 0; /* reset the tiebreak */ } int cx = character.getLocation().getX(); int xDelta = location.getX() - cx; int cy = character.getLocation().getY(); int yDelta = location.getY() - cy; int groupiness = 0; /* Always hunt down a visible enemy when they're the only remaining enemy and doing so is safe. Otherwise, still favour hunting them down, but in that situation also consider factors like grouping and exploration. */ for (Point2D enemyLocation : visibleEnemies.keysView()) if (xDelta * (enemyLocation.getX() - cx) > 0 || yDelta * (enemyLocation.getY() - cy) > 0) groupiness += (visibleEnemies.size() == 1 ? 99 : 5); /* If there are 4 or more visible enemies, then grouping is vitally important (so as to not get surrounded). Otherwise, it's more minor. */ for (ReadonlyCharacter ally : team) if (xDelta * (ally.getLocation().getX() - cx) > 0 || yDelta * (ally.getLocation().getY() - cy) > 0) groupiness += (visibleEnemies.size() > 3 ? 99 : 3); /* When exploring, we bias towards random map locations, changing location when we reach them. This helps us beat enemies that hide in the corners. When there are a lot of visible enemies, this changes to a bias to hide in a corner. */ if (xDelta * (goalX - cx) > 0 || yDelta * (goalY - cy) > 0) groupiness += (visibleEnemies.size() > 3 ? 99 : 4); if (groupiness >= bestGroupiness) { bestLocation = location; bestGroupiness = groupiness; /* leave priority, safety untouched */ } } if (bestLocation == null) continue; action.setLocation(bestLocation); } else throw new RuntimeException("unknown action" + action.getName()); if (priority > bestPriority) { bestPriority = priority; bestAction = action; } } if (bestAction == null) throw new RuntimeException("no action?"); return bestAction; } } ``` [Answer] # RogueSquad A rogue squad consists of: * 1 **Scout** (stays in shadows while exploring the map) + **STR:** 5; **AGI:** 5; **INT:** 25 + **Clone**, **Invisible**, **Far sight** * 2 **Assasins** (attack enemies with deadly poison) + **STR:** 5; **AGI:** 5; **INT:** 25 + **Clone**, **Poison**, **Focused** The by far biggest power both can use, is to call additional members of the squad to support them. *You may reuse single characters from here in your team, as long as you add at least one more character which is not present here.* ``` RogueSquad.java import java.util.Arrays; import java.util.List; import fellowship.abilities.ActionAbility; import fellowship.abilities.stats.Focused; import fellowship.abilities.vision.FarSight; import fellowship.abilities.vision.Invisible; import fellowship.actions.ReadonlyAction; import fellowship.actions.other.Clone; import fellowship.actions.statuses.Poison; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; public class RogueSquad extends SleafarPlayer { private CharacterTemplate scoutTemplate() { return new CharacterTemplate(0, 0, 20, new ActionAbility(Clone::new), new Invisible(), new FarSight()); } private CharacterTemplate assasinTemplate() { return new CharacterTemplate(0, 0, 20, new ActionAbility(Clone::new), new ActionAbility(Poison::new), new Focused()); } @Override public List<CharacterTemplate> createCharacters() { return Arrays.asList(assasinTemplate(), scoutTemplate(), assasinTemplate()); } private class Scout extends Character { protected Scout(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { ReadonlyAction clone = getAction(Clone.class); if (clone != null && (isVisible() || !isInEnemySightRange()) && setCloneLocation(clone, 3)) { return clone; } if (step != null && isVisible() && isInEnemySliceRange() && setAvoidEnemiesLocation(step)) { return step; } if (slice != null && isVisible() && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && isVisible() && setAvoidEnemiesLocation(step)) { return step; } if (step != null && !isVisible() && setExploreLocation(step)) { return step; } return smile; } } private class Assasin extends Character { protected Assasin(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { ReadonlyAction clone = getAction(Clone.class); ReadonlyAction poison = getAction(Poison.class); if (clone != null && setCloneLocation(clone, 1)) { return clone; } if (step != null && isInEnemySliceRange() && setAvoidEnemiesLocation(step)) { return step; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (poison != null && setPoisonTarget(poison)) { return poison; } if (step != null && setAvoidEnemiesLocation(step)) { return step; } return smile; } } @Override protected Character createCharacter(ReadonlyCharacter delegate) { if (hasAbility(delegate, Invisible.class)) { return new Scout(delegate); } else if (hasAbility(delegate, Poison.class)) { return new Assasin(delegate); } else { throw new IllegalArgumentException(); } } } ``` ### Base class for all my bots ``` SleafarPlayer.java import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.collections.api.RichIterable; import org.eclipse.collections.api.map.ImmutableMap; import org.eclipse.collections.api.map.MutableMap; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.MutableSet; import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.factory.Maps; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.list.primitive.IntInterval; import org.eclipse.collections.impl.tuple.Tuples; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.Player; import fellowship.Range; import fellowship.abilities.ReadonlyAbility; import fellowship.abilities.attacking.Critical; import fellowship.abilities.attacking.Reflexive; import fellowship.abilities.defensive.Spikes; import fellowship.abilities.statuses.Immune; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Quick; import fellowship.actions.attacking.Slice; import fellowship.actions.mobility.Step; import fellowship.actions.other.Smile; import fellowship.characters.CharacterInterface; import fellowship.characters.EnemyCharacter; import fellowship.characters.ReadonlyCharacter; public abstract class SleafarPlayer extends Player { private static final ImmutableSet<Point2D> MAP_LOCATIONS = IntInterval.fromTo(0, 9) .collect(x -> IntInterval.fromTo(0, 9).collect(y -> new Point2D(x, y))).flatCollect(t -> t).toSet() .toImmutable(); protected static final Comparator<CharacterInterface> HEALTH_COMPARATOR = (o1, o2) -> Double.compare(o1.getHealth(), o2.getHealth()); private static final Range BLOCKING_RANGE = new Range(1, true); private static final Range STATIC_RANGE = new Range(1); protected static boolean hasAbility(CharacterInterface character, Class<?> ability) { return character.getAbilities().anySatisfy(a -> a.abilityClass().equals(ability)); } protected static boolean isBear(CharacterInterface character) { return character.getAbilities().isEmpty(); } protected static double calcSliceDamage(CharacterInterface character) { return character.getStat(character.primaryStat()) * (hasAbility(character, Quick.class) ? 2.0 : 1.0); } protected static boolean setLocation(ReadonlyAction action, Point2D location) { if (location != null) { action.setLocation(location); } return location != null; } protected static boolean setTarget(ReadonlyAction action, ReadonlyCharacter target) { if (target != null) { action.setTarget(target); } return target != null; } protected abstract class Character { protected final ReadonlyCharacter delegate; protected Character(ReadonlyCharacter delegate) { super(); this.delegate = delegate; } protected abstract ReadonlyAction choose(); protected double getHealth() { return delegate.getHealth(); } protected double getHealthRegen() { return delegate.getHealthRegen(); } protected double getMana() { return delegate.getMana(); } protected double getManaRegen() { return delegate.getManaRegen(); } protected Point2D getLocation() { return delegate.getLocation(); } protected boolean isVisible() { return !delegate.isInvisible(); } protected double getSliceDamage() { return delegate.getStat(delegate.primaryStat()); } protected boolean isInEnemySliceRange() { return getEnemySliceLocations().contains(delegate.getLocation()); } protected boolean isInEnemySightRange() { return getEnemySightLocations().contains(delegate.getLocation()); } protected boolean isInEnemyStepSightRange() { return getEnemyStepSightLocations().contains(delegate.getLocation()); } protected double calcSliceRetaliationDamage(CharacterInterface character) { double result = 0.0; double ownDamage = getSliceDamage(); for (ReadonlyAbility ability : character.getAbilities()) { if (ability.abilityClass().equals(Critical.class)) { ownDamage = ownDamage * 2; } } for (ReadonlyAbility ability : character.getAbilities()) { if (ability.abilityClass().equals(Spikes.class)) { result += ownDamage / 2.0; } else if (ability.abilityClass().equals(Reflexive.class)) { result += character.getStat(character.primaryStat()); } } return result; } protected double calcSpellRetaliationDamage(CharacterInterface character, double ownDamage) { double result = 0.0; for (ReadonlyAbility ability : character.getAbilities()) { if (ability.abilityClass().equals(Spikes.class)) { result += ownDamage / 2.0; } } return result; } protected boolean setRandomLocation(ReadonlyAction action) { return setLocation(action, chooseRandom(action.availableLocations())); } protected boolean setRandomLocation(ReadonlyAction action, ImmutableSet<Point2D> avoidLocations) { return setLocation(action, chooseRandom(action.availableLocations().difference(avoidLocations))); } protected boolean setClosestLocation(ReadonlyAction action, ImmutableSet<Point2D> targetLocations) { return setLocation(action, chooseClosest(action.availableLocations(), targetLocations)); } protected boolean setClosestLocation(ReadonlyAction action, ImmutableSet<Point2D> avoidLocations, ImmutableSet<Point2D> targetLocations) { return setLocation(action, chooseClosest(action.availableLocations().difference(avoidLocations), targetLocations)); } protected boolean setClosestHiddenLocation(ReadonlyAction action, ImmutableSet<Point2D> preferredLocations) { return setClosestLocation(action, getEnemySightLocations(), preferredLocations); } protected boolean setClosestSafeLocation(ReadonlyAction action, ImmutableSet<Point2D> preferredLocations) { return setClosestLocation(action, getEnemySliceLocations(), preferredLocations); } protected boolean setFarthestLocation(ReadonlyAction action, ImmutableSet<Point2D> targetLocations) { return setLocation(action, chooseFarthest(action.availableLocations(), targetLocations)); } protected boolean setFarthestLocation(ReadonlyAction action, ImmutableSet<Point2D> avoidLocations, ImmutableSet<Point2D> targetLocations) { return setLocation(action, chooseFarthest(action.availableLocations().difference(avoidLocations), targetLocations)); } public boolean setCloneLocation(ReadonlyAction action, int distance) { ImmutableSet<Point2D> cloneLocations = distance < 2 ? team.collect(t -> t.getLocation()).toImmutable() : team.flatCollect(t -> t.rangeAround(new Range(distance))).difference( team.flatCollect(t -> t.rangeAround(new Range(distance - 1)))).toImmutable(); if (cloneLocations.isEmpty()) { return setRandomLocation(action, getEnemySightLocations()) || setRandomLocation(action, getEnemySliceLocations()) || setRandomLocation(action); } else { return setClosestLocation(action, getEnemySightLocations(), cloneLocations) || setClosestLocation(action, getEnemySliceLocations(), cloneLocations) || setClosestLocation(action, cloneLocations); } } protected boolean setAvoidEnemiesLocation(ReadonlyAction action) { Point2D location = chooseFarthest(Sets.mutable.ofAll(action.availableLocations()) .with(delegate.getLocation()).difference(getEnemySliceLocations()), getEnemyLocations()); if (location == null || location.equals(delegate.getLocation())) { return false; } else { return setLocation(action, location); } } protected boolean setBlockEnemiesLocation(ReadonlyAction action) { return setLocation(action, chooseRandom(action.availableLocations().intersect(getEnemyBlockingLocations()))); } protected boolean setExploreLocation(ReadonlyAction action) { return visibleEnemies.size() < enemies.size() && getTeamHiddenLocations().notEmpty() && setClosestLocation(action, getEnemyStepSightLocations(), getTeamHiddenLocations()); } protected boolean setSliceTarget(ReadonlyAction action, double minHealthReserve) { MutableSet<Pair<ReadonlyCharacter, Double>> pairs = action.availableTargets() .collect(t -> Tuples.pair(t, calcSliceRetaliationDamage(t))); Pair<ReadonlyCharacter, Double> smallest = chooseSmallest(pairs, (o1, o2) -> { int c = Double.compare(o1.getTwo(), o2.getTwo()); return c == 0 ? Double.compare(o1.getOne().getHealth(), o2.getOne().getHealth()) : c; }); if (smallest == null || smallest.getTwo() > delegate.getHealth() - minHealthReserve) { return false; } else { return setTarget(action, smallest.getOne()); } } protected boolean setPoisonTarget(ReadonlyAction action) { return setTarget(action, chooseSmallest(action.availableTargets().reject(c -> hasAbility(c, Immune.class)), HEALTH_COMPARATOR)); } protected final ImmutableSet<Point2D> getEnemyLocations() { if (enemyLocations == null) { enemyLocations = visibleEnemies.keysView().toSet().toImmutable(); } return enemyLocations; } protected final ImmutableSet<Point2D> getEnemySliceLocations() { if (enemySliceLocations == null) { enemySliceLocations = visibleEnemies.keyValuesView() .flatCollect(c -> c.getTwo().rangeAround(c.getTwo().getSliceRange(), c.getOne())).toSet() .toImmutable(); } return enemySliceLocations; } protected final ImmutableSet<Point2D> getEnemySightLocations() { if (enemySightLocations == null) { enemySightLocations = visibleEnemies.keyValuesView() .flatCollect(c -> c.getTwo().rangeAround(c.getTwo().getSightRange(), c.getOne())).toSet() .toImmutable(); } return enemySightLocations; } protected final ImmutableSet<Point2D> getEnemyStepSightLocations() { if (enemyStepSightLocations == null) { enemyStepSightLocations = visibleEnemies.keyValuesView() .flatCollect(c -> Sets.mutable.ofAll(c.getTwo().rangeAround(c.getTwo().getStepRange(), c.getOne())) .with(c.getOne()).flatCollect(r -> c.getTwo().rangeAround(c.getTwo().getSightRange(), r))) .toSet().toImmutable(); } return enemyStepSightLocations; } protected final ImmutableSet<Point2D> getEnemyHiddenLocations() { if (enemyHiddenLocations == null) { enemyHiddenLocations = MAP_LOCATIONS.difference(getEnemySightLocations()); } return enemyHiddenLocations; } protected final ImmutableSet<Point2D> getEnemyBlockingLocations() { if (enemyBlockingLocations == null) { enemyBlockingLocations = visibleEnemies.keyValuesView() .flatCollect(c -> c.getTwo().rangeAround(BLOCKING_RANGE, c.getOne())).toSet().toImmutable(); } return enemyBlockingLocations; } protected final ImmutableSet<Point2D> getTeamHiddenLocations() { if (teamHiddenLocations == null) { teamHiddenLocations = MAP_LOCATIONS.difference(team.flatCollect(c -> c.rangeAround(c.getSightRange()))); } return teamHiddenLocations; } protected final ImmutableSet<Point2D> getTeamBlockingLocations() { if (teamBlockingLocations == null) { teamBlockingLocations = team.flatCollect(c -> c.rangeAround(BLOCKING_RANGE)).toImmutable(); } return teamBlockingLocations; } protected final ImmutableSet<Point2D> getSliceLocations() { if (sliceLocations == null) { sliceLocations = visibleEnemies.keyValuesView() .flatCollect(c -> c.getTwo().rangeAround(delegate.getSliceRange(), c.getOne())).toSet().toImmutable(); } return sliceLocations; } protected final ImmutableSet<Point2D> getStaticLocations() { if (staticLocations == null) { staticLocations = visibleEnemies.keyValuesView() .flatCollect(c -> c.getTwo().rangeAround(STATIC_RANGE, c.getOne())).toSet().toImmutable(); } return staticLocations; } protected final ImmutableMap<Point2D, Double> getEnemySliceDamage() { if (enemySliceDamage == null) { MutableMap<Point2D, Double> tmp = MAP_LOCATIONS.toMap(l -> l, l -> 0.0); for (Pair<Point2D, EnemyCharacter> p : visibleEnemies.keyValuesView()) { double damage = calcSliceDamage(p.getTwo()); for (Point2D l : p.getTwo().rangeAround(p.getTwo().getSliceRange(), p.getOne())) { tmp.put(l, tmp.get(l) + damage); } } enemySliceDamage = tmp.toImmutable(); } return enemySliceDamage; } } protected ImmutableMap<ReadonlyCharacter, Character> characters = Maps.immutable.empty(); private ImmutableMap<Class<?>, ReadonlyAction> actions = null; protected ReadonlyAction step = null; protected ReadonlyAction slice = null; protected ReadonlyAction smile = null; private ImmutableSet<Point2D> enemyLocations = null; private ImmutableSet<Point2D> enemySliceLocations = null; private ImmutableSet<Point2D> enemySightLocations = null; private ImmutableSet<Point2D> enemyStepSightLocations = null; private ImmutableSet<Point2D> enemyHiddenLocations = null; private ImmutableSet<Point2D> enemyBlockingLocations = null; private ImmutableSet<Point2D> teamHiddenLocations = null; private ImmutableSet<Point2D> teamBlockingLocations = null; private ImmutableSet<Point2D> sliceLocations = null; private ImmutableSet<Point2D> staticLocations = null; private ImmutableMap<Point2D, Double> enemySliceDamage = null; protected final <T> T chooseRandom(Collection<T> collection) { if (!collection.isEmpty()) { int i = getRandom().nextInt(collection.size()); for (T t : collection) { if (i == 0) { return t; } --i; } } return null; } protected final <T> T chooseSmallest(Collection<T> collection, Comparator<? super T> comparator) { if (!collection.isEmpty()) { List<T> list = new ArrayList<>(); for (T t : collection) { if (list.isEmpty()) { list.add(t); } else { int c = comparator.compare(t, list.get(0)); if (c < 0) { list.clear(); } if (c <= 0) { list.add(t); } } } return list.get(getRandom().nextInt(list.size())); } return null; } protected final Point2D chooseClosest(Collection<Point2D> available, RichIterable<Point2D> targets) { if (targets.isEmpty()) { return chooseRandom(available); } else { Map<Point2D, Integer> map = new HashMap<>(); for (Point2D a : available) { map.put(a, targets.collect(t -> t.cartesianDistance(a)).min()); } return chooseSmallest(available, (o1, o2) -> Integer.compare(map.get(o1), map.get(o2))); } } protected final Point2D chooseFarthest(Collection<Point2D> available, RichIterable<Point2D> targets) { if (targets.isEmpty()) { return chooseRandom(available); } else { Map<Point2D, Integer> map = new HashMap<>(); for (Point2D a : available) { map.put(a, targets.collect(t -> t.cartesianDistance(a)).min()); } return chooseSmallest(available, (o1, o2) -> Integer.compare(map.get(o2), map.get(o1))); } } protected int countCharacters(Class<?> clazz) { return characters.count(c -> c.getClass().equals(clazz)); } protected ReadonlyAction getAction(Class<?> clazz) { return actions.get(clazz); } protected abstract Character createCharacter(ReadonlyCharacter delegate); @Override public final ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { characters = team.collect(c -> characters.getIfAbsentWith(c, this::createCharacter, c)) .groupByUniqueKey(c -> c.delegate).toImmutable(); this.actions = Sets.immutable.ofAll(actions).groupByUniqueKey(ReadonlyAction::actionClass); step = getAction(Step.class); slice = getAction(Slice.class); smile = getAction(Smile.class); enemyLocations = null; enemySliceLocations = null; enemySightLocations = null; enemyStepSightLocations = null; enemyHiddenLocations = null; enemyBlockingLocations = null; teamHiddenLocations = null; teamBlockingLocations = null; sliceLocations = null; staticLocations = null; enemySliceDamage = null; return characters.get(character).choose(); } } ``` [Answer] # Vampire I'm new to this and I'm not sure I know what I'm doing, but I thought it seemed interesting, so here is my attempt. The vampires will search for enemies and target the weakest, draining the life from them, while growing stronger and regaining their own health, ready to move on to their next victim. Should they be significantly injured, they will attempt to move away until their natural regeneration restores them to fighting condition. Using **Absorb**, **Feast**, **Regenerate**, **Strong** with everything in **STR** ``` Vampire.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Absorb; import fellowship.abilities.attacking.Feast; import fellowship.abilities.stats.Strong; import fellowship.abilities.stats.Regenerate; import fellowship.actions.ReadonlyAction; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.Player; import org.eclipse.collections.api.set.MutableSet; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Vampire extends Player{ private final double CRITICAL_HEALTH = 5; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(30, 0, 0, new Absorb(), new Feast(), new Regenerate(), new Strong())); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { int minPriority = Integer.MAX_VALUE; ReadonlyAction chosen = null; for (ReadonlyAction action: actions){ int priority = getPriorityFor(action, character); if (priority < minPriority){ chosen = action; minPriority = priority; } } if (chosen == null){ throw new RuntimeException("No valid actions"); } if (chosen.needsLocation()){ chosen.setLocation(chooseLocationFor(chosen, character)); } else if (chosen.needsTarget()){ chosen.setTarget(chooseTargetFor(chosen)); } return chosen; } private Point2D chooseLocationFor(ReadonlyAction action, ReadonlyCharacter character){ if (action.movementAction()){ if (character.getHealth() <= CRITICAL_HEALTH){ return fromEnemy(action.availableLocations()); } else { return toEnemy(action.availableLocations()); } } return toTeam(action.availableLocations()); } private Point2D toEnemy(MutableSet<Point2D> availableLocations){ if (visibleEnemies.isEmpty()){ return availableLocations.iterator().next(); } return availableLocations.minBy(p1 -> p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)) ); } private Point2D fromEnemy(MutableSet<Point2D> availableLocations){ if (visibleEnemies.isEmpty()){ return availableLocations.iterator().next(); } return availableLocations.maxBy(p1 -> p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)) ); } private Point2D toTeam(MutableSet<Point2D> availableLocations){ if (team.isEmpty()){ return availableLocations.iterator().next(); } return availableLocations.minBy(p1 -> p1.cartesianDistance(team.collect(ReadonlyCharacter::getLocation).minBy(p1::cartesianDistance)) ); } private ReadonlyCharacter chooseTargetFor(ReadonlyAction action){ return action.availableTargets().minBy(ReadonlyCharacter::getHealth); } private int getPriorityFor(ReadonlyAction action, ReadonlyCharacter character){ if (action.getName().equals("Smile")){ return 1000; } if (action.movementAction()){ if (character.getHealth() <= CRITICAL_HEALTH){ return 0; } return 999; } if (action.needsTarget()) { return ((int) action.availableTargets().minBy(ReadonlyCharacter::getHealth).getHealth()); } return 998; } } ``` [Answer] ## Bear Cavalry Uses **Absorb**, **Clone** and **Bear**; stats are **(+9, +0, +11)**. On the first turn, everyone creates a clone of themselves, so that the team has 6 characters on the field. Then they charge the enemy, spamming bears whenever they can, and weakening their foes with stat-absorbing attacks. The code is a mess, but it seems to work. I copied parts of it from Template Player. *You can use the characters of this team in any way you like.* ``` BearCavalry.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Absorb; import fellowship.actions.ReadonlyAction; import fellowship.actions.other.Clone; import fellowship.actions.other.Bear; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.Player; import org.eclipse.collections.api.set.MutableSet; import java.util.ArrayList; import java.util.List; import java.util.Set; public class BearCavalry extends Player{ @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(9, 0, 11, new Absorb(), new ActionAbility(Clone::new), new ActionAbility(Bear::new))); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { for(ReadonlyAction action: actions){ if (action.getName().equals("Clone") && action.isAvailable()){ action.setLocation(toTeam(action.availableLocations(), character)); return action; } } for(ReadonlyAction action: actions){ if (action.getName().equals("Bear") && action.isAvailable()){ action.setLocation(toEnemy(action.availableLocations(), character)); return action; } } for(ReadonlyAction action: actions){ if (action.getName().equals("Slice") && action.isAvailable()){ action.setTarget(action.availableTargets().minBy(ReadonlyCharacter::getHealth)); return action; } } for(ReadonlyAction action: actions){ if (action.getName().equals("Step") && action.isAvailable()){ action.setLocation(toEnemy(action.availableLocations(), character)); return action; } } for(ReadonlyAction action: actions){ if (action.getName().equals("Smile")){ return action; } } return null; } private Point2D toTeam(MutableSet<Point2D> availableLocations, ReadonlyCharacter character){ if (team.isEmpty()){ return availableLocations.minBy(p1 -> p1.diagonalDistance(character.getLocation()) ); } return availableLocations.minBy(p1 -> p1.diagonalDistance(team.collect(ReadonlyCharacter::getLocation).minBy(p1::cartesianDistance)) ); } private Point2D toEnemy(MutableSet<Point2D> availableLocations, ReadonlyCharacter character){ if (visibleEnemies.isEmpty()){ return toTeam(availableLocations, character); } return availableLocations.minBy(p1 -> p1.diagonalDistance(visibleEnemies.keyValuesView().minBy(p -> p.getTwo().getHealth()).getOne()) ); } } ``` [Answer] # Spiky Spiky is, as his names implies, not to be attacked blindly. He's tanky, can regenerate a whole lot of HP, and hits like a truck. He will hover in the center of the map, waiting for someone to come close. Using **Strong** (STR +10) x2, **Regenerate**, **Spikes** and going full STR (+40, 0, 0). ``` Spiky.java import fellowship.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.defensive.Spikes; import fellowship.abilities.stats.Regenerate; import fellowship.abilities.stats.Strong; import fellowship.actions.ReadonlyAction; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; public class Spiky extends Player { @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(40, 0, 0, new Strong(), new Strong(), new Regenerate(), new Spikes())); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { ReadonlyAction chosen = null; Boolean canSlice = false; for (ReadonlyAction action: actions) { if (action.getName().equals("Slice")) { canSlice = true; } } for (ReadonlyAction action: actions) { if (action.getName().equals("Slice")) { chosen = action; chosen.setTarget(action.availableTargets().minBy(ReadonlyCharacter::getHealth)); } if (!canSlice && action.getName().equals("Step")){ int x = ThreadLocalRandom.current().nextInt(3, 6 + 1); int y = ThreadLocalRandom.current().nextInt(3, 6 + 1); chosen = action; Point2D destination = null; if (visibleEnemies.isEmpty()){ destination = action.availableLocations().minBy(p1 -> p1.cartesianDistance(new Point2D(x, y))); } else { destination = action.availableLocations().minBy(p1 -> p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance))); } chosen.setLocation(destination); } } if (chosen == null){ for (ReadonlyAction action: actions){ if (action.getName().equals("Smile")){ chosen = action; } } } return chosen; } } ``` [Answer] # Sorcerer Clones himself to deal as much instant damage to all enemies as possible with *Weave* (it was lightning previously, but *Weave* does more damage and has a lower mana cost. ``` Sorcerer.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.Player; import fellowship.abilities.ActionAbility; import fellowship.abilities.vision.TrueSight; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Slice; import fellowship.actions.attacking.Weave; import fellowship.actions.mobility.Step; import fellowship.actions.other.Clone; import fellowship.actions.other.Smile; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.collections.api.set.MutableSet; public class Sorcerer extends Player { @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(0, 0, 20, new ActionAbility(Clone::new), new TrueSight(), new ActionAbility(Weave::new))); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { ReadonlyAction chosen = getBestAction(actions, character); if (chosen == null){ throw new RuntimeException("No valid actions"); } if (chosen.needsLocation()){ chosen.setLocation(toEnemy(chosen.availableLocations())); } else if (chosen.needsTarget()){ chosen.setTarget(chooseTargetFor(chosen)); } return chosen; } private Point2D toEnemy(MutableSet<Point2D> availableLocations){ if (visibleEnemies.isEmpty()){ return availableLocations.minBy(p1 -> p1.cartesianDistance(team.minBy(x -> p1.cartesianDistance(x.getLocation())).getLocation()) ); } return availableLocations.maxBy(p1 -> p1.cartesianDistance(visibleEnemies.keysView().maxBy(p1::cartesianDistance)) ); } private ReadonlyCharacter chooseTargetFor(ReadonlyAction action){ return action.availableTargets().minBy(ReadonlyCharacter::getHealth); } private ReadonlyAction getBestAction(Set<ReadonlyAction> actions, ReadonlyCharacter character) { Map<Class<?>, ReadonlyAction> actionMap = new HashMap<>(); for (ReadonlyAction action : actions) { actionMap.put(action.actionClass(), action); } ReadonlyAction clone = actionMap.get(Clone.class); if (clone != null && clone.isAvailable() && !clone.availableLocations().isEmpty()) { return clone; } ReadonlyAction weave = actionMap.get(Weave.class); if (weave != null && weave.isAvailable() && (clone == null || clone.getRemainingCooldown() > 0)) { return weave; } ReadonlyAction slice = actionMap.get(Slice.class); if (slice != null && slice.isAvailable() && !slice.availableLocations().isEmpty() && !character.isInvisible()) { return slice; } ReadonlyAction step = actionMap.get(Step.class); if (step != null && step.isAvailable()) { return step; } return actionMap.get(Smile.class); } } ``` [Answer] # LongSword Uses **Ranged** (Adds 1 to the range of Slice), **Flexible** (Can Slice in any of the 8 directions), **Quick** (Slice twice, Mana: 3, Cooldown: 0), **Strong** (You gain 10 more attribute points) ### STATS The starting 5 points is the base * **STR:** 5 + 20 + 10 * **AGI:** 5 + 0 * **INT:** 5 + 0 --- First of all, I really enjoyed making this bot, and I really like this KotH (this is my first submission to a KotH challenge!). (I might post more bots) ### The Bot This bot relies on Attack abilities to overpower its opponents. As far as I tested, this bot is really good against bots with relatively low health. Also, it has a large attack range, and can easily target most (or half) enemies in its sight. To compare this bot with a NetHack role, I would say it resembles closely to the [Valkyrie](https://nethackwiki.com/wiki/Valkyrie) due to the concept of the "LongSword" and the average health. **NAME** This bot has a slightly longer range than normal bots and it can attack in any direction. This reminded me most of the Long Sword in NetHack, so I named my bot as such. **BEHAVIOUR** If the character cannot see an enemy character, then it will go the the opposite side of the field (the enemy's spawn area/enemy's "base") to find enemy characters. If it finds enemies, then it will attack them with Quick, Slice (in decreasing priority). If it can't target enemies, then the bot will go towards the enemy characters to destroy them. If the character cannot see an enemy character **and** has low health, then it will retreat towards "base"/spawn area. > > Note: The bot will never retreat in the middle of battle. This bot will never Smile. > > > I used the following [regex](http://www.regexr.com/3emv2) on regexr.com to convert my Java code into a formatted code block. The code below is commented so it should be easy to understand. If you have any questions or clarifications on how it works, feel free to ping me in the [Battle of the Fellowships chatroom](http://chat.stackexchange.com/rooms/48475/battle-of-the-fellowships)! > > Edit: I fixed a minor mistake in my program to adapt the bot's movement (forwards|backwards) depending on where it started. I forgot to do this, so I edited it in now. > > > ``` LongSword.java import fellowship.*; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Flexible; import fellowship.abilities.attacking.Ranged; import fellowship.abilities.stats.Strong; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Quick; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import java.util.ArrayList; import java.util.List; import java.util.Set; public class LongSword/*Closest NetHack Role: Valkyrie*/ extends Player{ //debugging private boolean debug = false; private void println(String text) { if(debug) System.out.println(text); } //variables use to hold the start Y coordinate of the bot private boolean started = false; private int startY = 5; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(30, 0, 0, new Ranged(), //Adds 1 to the range of Slice new Flexible(), //Can Slice in any of the 8 directions new ActionAbility(Quick::new), //Slice twice, Mana: 3, Cooldown: 0 new Strong())); //You gain 10 attribute points } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { if(!started) { startY = character.getLocation().getY(); //giving startY the value of the bot's starting y-value started = true; //do this only once, that's why there is the if statement } ReadonlyAction current = null; //choosing action depending on priority int priority = Integer.MAX_VALUE; for(ReadonlyAction action:actions) { int priorityLocal = getPriority(action, character); if(priorityLocal < priority) { current = action; priority = priorityLocal; } } if (current == null){ throw new RuntimeException("No valid actions"); } println(current.getName()); if(current.needsLocation()) { if(visibleEnemies.isEmpty()) { if (character.getHealth() < 100) { //if has low health, go backwards towards "base" //println("lowHealth"); current.setLocation(move(current, character, "backward")); } else { //else go forwards to enemy's "base" current.setLocation(move(current, character, "forward")); } }else{ //go towards closest enemy current.setLocation(current.availableLocations().minBy(p1->p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)))); } } if(current.needsTarget()) { //get closest target current.setTarget(current.availableTargets().minBy(p1 -> 0)); } return current; } //move backwards or forwards private Point2D move(ReadonlyAction readonlyAction, ReadonlyCharacter character, String direction) { Point2D location = null; //move direction depending on Y coordinate of point for(Point2D point2D:readonlyAction.availableLocations()) { switch (direction) { case "forward": if(startY > 5) { //bot started at bottom if (point2D.getY() < character.getLocation().getY()) location = point2D; }else{ //bot started at top if (point2D.getY() > character.getLocation().getY()) location = point2D; } break; case "backward": if(startY > 5) { //bot started at bottom if (point2D.getY() > character.getLocation().getY()) location = point2D; }else{ //bot started at top if (point2D.getY() < character.getLocation().getY()) location = point2D; } break; } } //if no available locations, just choose the first available location if(location == null) { location = readonlyAction.availableLocations().iterator().next(); } println(location.getY()+","+character.getLocation().getY()); return location; } private int getPriority(ReadonlyAction action, ReadonlyCharacter character) { if(visibleEnemies.isEmpty()) { //if there are no visible enemies, Step. In the choose function, this becomes move forward or backward depending on health if(action.getName().equals("Step")) { return 100; } }else { /* * PRIORITIES: * 1. Quick (Slice twice) * 2. Slice * 3. Step (when enemy is not in range --> move towards enemy) */ if (action.getName().equals("Quick")) { return 1; }else if(action.getName().equals("Slice")) { return 10; }else if(action.getName().equals("Step")) { return 50; } } //Kids, don't Smile, instead Step or Slice return 1000; } } ``` [Answer] # Derailer Had to delete it *twice* since I had a bunch of logic errors. :P This one can certainly derail your plans. ;) The team: * 1 character with **Critical**, **Buff**, **Strong**, and **Quick** to quickly take out enemies while being very difficult to defeat. **+25 STR, +2 AGI, +3 INT** * 1 character with **Clever**, **Clever**, **Restore**, and **Zap**. Stays behind as support and restores the health of any teammates that are running low on HP, and can attack and defend itself necessary. **+14 STR, +3 AGI, +3 INT** * 1 character with **TrueSight**, **Spikes**, **Evasive**, and **Weave**. Not so easy to hit, and if you do, or if you get too close, it will see you and strike. **+13 STR, +3 AGI, +4 INT** ``` Derailer.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.Player; import fellowship.abilities.ActionAbility; import fellowship.abilities.ReadonlyAbility; import fellowship.abilities.attacking.Critical; import fellowship.abilities.defensive.Evasive; import fellowship.abilities.defensive.Spikes; import fellowship.abilities.stats.Buff; import fellowship.abilities.stats.Clever; import fellowship.abilities.stats.Strong; import fellowship.abilities.vision.TrueSight; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Quick; import fellowship.actions.attacking.Weave; import fellowship.actions.damage.Zap; import fellowship.actions.defensive.Restore; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.function.BinaryOperator; import java.util.stream.Collectors; public class Derailer extends Player { private static final double CRITICAL_HEALTH_PCT = .175; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> list = new ArrayList<>(); list.add(new CharacterTemplate(14, 3, 3, new Clever(), new Clever(), new ActionAbility(Restore::new), new ActionAbility(Zap::new))); list.add(new CharacterTemplate(25, 2, 3, new Critical(), new Buff(), new ActionAbility(Quick::new), new Strong())); list.add(new CharacterTemplate(13, 3, 4, new TrueSight(), new Spikes(), new Evasive(), new ActionAbility(Weave::new))); return list; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { List<ReadonlyAbility> abilities = character.getAbilities(); ReadonlyAction action = null; for (ReadonlyAbility a : abilities) { String s = a.name(); int i = s.lastIndexOf("."); if (i == -1) continue; s = s.substring(i+1, s.length()); if (s.equals("Clever")) { action = getActionForChar1(character, actions); break; } else if (s.equals("Buff")) { action = getActionForChar2(character, actions); break; } else if (s.equals("Evasive")) { action = getActionForChar3(character, actions); break; } } return action; } private ReadonlyAction getActionForChar1(ReadonlyCharacter character, Set<ReadonlyAction> actions) { int members = (int) team.stream().filter(c -> !c.isDead()).count(); List<ReadonlyAction> list = actions.stream() .sorted(Comparator.comparingInt(this::getPriority)) .collect(Collectors.toList()); for (ReadonlyAction a : list) { String name = a.getName(); if (name.equals("Restore")) { for (ReadonlyCharacter teammate : team) { if (teammate.getHealth() / teammate.getMaxHealth() < CRITICAL_HEALTH_PCT * (4 - members)) return a; } } else if (name.equals("Zap") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets() .stream() .reduce( BinaryOperator.minBy( Comparator.<ReadonlyCharacter>comparingDouble(e -> e.getHealth()) ) ) .get() ); return a; } else if (name.equals("Slice") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().iterator().next()); return a; } else if (name.equals("Smile")) return a; } throw new RuntimeException("No available actions"); } private ReadonlyAction getActionForChar2(ReadonlyCharacter character, Set<ReadonlyAction> actions) { List<ReadonlyAction> list = actions.stream() .sorted(Comparator.comparingInt(this::getPriority)) .collect(Collectors.toList()); for (ReadonlyAction a : list) { String name = a.getName(); if (name.equals("Quick") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().minBy(ReadonlyCharacter::getHealth)); return a; } else if (name.equals("Slice") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().minBy(ReadonlyCharacter::getHealth)); return a; } else if (name.equals("Step") && !a.availableLocations().isEmpty()) { Point2D e = getClosestEnemyPoint(character); if (e == null) { Point2D p = character.getLocation(); if (p.getY() > 5) { a.setLocation(a.availableLocations() .stream() .filter(x -> x.getY() < p.getY()) .findFirst() .orElse(a.availableLocations().iterator().next())); } else if (p.getY() < 4) { a.setLocation(a.availableLocations() .stream() .filter(x -> x.getY() > p.getY()) .findFirst() .orElse(a.availableLocations().iterator().next())); } else a.setLocation(randomLocation(new ArrayList<>(a.availableLocations()))); } else { int currentDistance = character.getLocation().cartesianDistance(e); a.setLocation(a.availableLocations() .stream() .filter(x -> x.cartesianDistance(e) < currentDistance) .findFirst() .orElse(randomLocation(new ArrayList<>(a.availableLocations())))); } return a; } else if (name.equals("Smile")) return a; } throw new RuntimeException("No available actions"); } private ReadonlyAction getActionForChar3(ReadonlyCharacter character, Set<ReadonlyAction> actions) { List<ReadonlyAction> list = actions.stream() .sorted(Comparator.comparingInt(this::getPriority)) .collect(Collectors.toList()); for (ReadonlyAction a : list) { String name = a.getName(); if (name.equals("Weave") && visibleEnemies.keySet().size() > 1) return a; else if (name.equals("Slice") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().iterator().next()); return a; } else if (name.equals("Smile")) return a; else if (name.equals("Step")) { Point2D p = character.getLocation(); if (!visibleEnemies.keySet().isEmpty()) { Point2D e = getClosestEnemyPoint(character); int currentDistance = character.getLocation().cartesianDistance(e); a.setLocation(a.availableLocations() .stream() .filter(x -> x.cartesianDistance(e) < currentDistance) .findAny() .orElse(randomLocation(new ArrayList<>(a.availableLocations())))); } else if (p.getY() > 5) { a.setLocation(a.availableLocations() .stream() .filter(x -> x.getY() < p.getY()) .findFirst() .orElse(randomLocation(new ArrayList<>(a.availableLocations())))); } else if (p.getY() < 4) { a.setLocation(a.availableLocations() .stream() .filter(x -> x.getY() > p.getY()) .findFirst() .orElse(randomLocation(new ArrayList<>(a.availableLocations())))); } else a.setLocation(randomLocation(new ArrayList<>(a.availableLocations()))); return a; } } throw new RuntimeException("No available actions"); } private Point2D getClosestEnemyPoint(ReadonlyCharacter c) { return visibleEnemies.keySet() .stream() .reduce( BinaryOperator.minBy( Comparator.comparingInt(x -> x.cartesianDistance(c.getLocation())) ) ) .orElse(null); } private int getPriority(ReadonlyAction action) { switch (action.getName()) { case "Quick": case "Restore": case "Weave": return 1; case "Zap": return 2; case "Slice": return 3; case "Step": return 4; case "Smile": return 5; } throw new IllegalArgumentException(String.valueOf(action)); } private Point2D randomLocation(List<Point2D> l) { return l.get((int) (Math.random() * l.size())); } } ``` [Answer] # SniperSquad A sniper squad consists of: * 1 **Spotter** (equipped with the best spotting gear available, allowing an overview of almost the whole map) + **STR:** 25; **AGI:** 5; **INT:** 5 + **Far sight**, **Far sight**, **Far sight**, **Far sight** * 2 **Shooters** (equipped with the newest multi target sniper rifles, the only drawback is the slow fire rate) + **STR:** 25; **AGI:** 5; **INT:** 5 + **Weave**, **Critical**, **Critical**, **Critical** *You may reuse single characters from here in your team, as long as you add at least one more character which is not present here.* ``` SniperSquad.java import java.util.Arrays; import java.util.List; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Critical; import fellowship.abilities.vision.FarSight; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Weave; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; public class SniperSquad extends SleafarPlayer { private static CharacterTemplate spotterTemplate() { return new CharacterTemplate(20, 0, 0, new FarSight(), new FarSight(), new FarSight(), new FarSight()); } private static CharacterTemplate shooterTemplate() { return new CharacterTemplate(20, 0, 0, new ActionAbility(Weave::new), new Critical(), new Critical(), new Critical()); } @Override public List<CharacterTemplate> createCharacters() { return Arrays.asList(shooterTemplate(), spotterTemplate(), shooterTemplate()); } private class Spotter extends Character { protected Spotter(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { if (slice != null && setSliceTarget(slice, 100.0)) { return slice; } if (step != null && isInEnemyStepSightRange() && setAvoidEnemiesLocation(step)) { return step; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && setExploreLocation(step)) { return step; } return smile; } } private class Shooter extends Character { protected Shooter(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { ReadonlyAction weave = getAction(Weave.class); if (weave != null && !visibleEnemies.isEmpty() && visibleEnemies.collectDouble(e -> calcSliceRetaliationDamage(e)).sum() < getHealth()) { return weave; } if (slice != null && setSliceTarget(slice, 100.0)) { return slice; } if (step != null && setAvoidEnemiesLocation(step)) { return step; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } return smile; } } @Override protected Character createCharacter(ReadonlyCharacter delegate) { if (hasAbility(delegate, FarSight.class)) { return new Spotter(delegate); } else if (hasAbility(delegate, Weave.class)) { return new Shooter(delegate); } else { throw new IllegalArgumentException(); } } } ``` [Answer] # Werewolves I am not the greatest at writing AI *choice selection*, especially for a ruleset as complex as this one. Combined with low ability to view a gamestate and observe the actors making decisions (and with the outcomes slightly different between runs, there's little ability to calculate a success margin of slight changes in order to improve the AI logic), but I was able to make a superior ability/attribute selection that dominated the existing bot set. Uses **Ranged**, **Swipe**, **Strong**, and **Werewolf** and otherwise uses the same AI logic as [LongSword](https://codegolf.stackexchange.com/a/100456/47990), although slightly altered. Tough to choose the most ideal values, as even no changes can sometimes result in dropping from "best" to "worst." The health-retreat-threshold is 50 here, but it seems that any value between 10 and 70 results in similar results (no other bots that provide a high enough challenge to distinguish the precise peak of performance). ``` PlayerWerewolf.java import java.util.ArrayList; import java.util.List; import java.util.Set; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.Player; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Ranged; import fellowship.abilities.attacking.Swipe; import fellowship.abilities.stats.Strong; import fellowship.actions.ReadonlyAction; import fellowship.actions.stats.Werewolf; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.characters.EnemyCharacter; public class PlayerWerewolf extends Player { //variables use to hold the start Y coordinate of the bot private boolean started = false; private int startY = 5; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(30, 0, 0, new Ranged(), //Adds 1 to the range of Slice new Swipe(), //Deal increasing damage new ActionAbility(Werewolf::new), //Turn into a werewolf for 5 turns new Strong())); //You gain 10 attribute points } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { if(!started) { startY = character.getLocation().getY(); //giving startY the value of the bot's starting y-value started = true; //do this only once, that's why there is the if statement } ReadonlyAction current = null; //choosing action depending on priority int priority = Integer.MAX_VALUE; for(ReadonlyAction action:actions) { int priorityLocal = getPriority(action, character); if(priorityLocal < priority) { current = action; priority = priorityLocal; } } if (current == null){ throw new RuntimeException("No valid actions"); } if(current.needsLocation()) { if(visibleEnemies.isEmpty()) { if (character.getHealth() < 50) { //if has low health, go backwards towards "base" //println("lowHealth"); current.setLocation(move(current, character, "backward")); } else { //else go forwards to enemy's "base" current.setLocation(move(current, character, "forward")); } }else{ //go towards closest enemy current.setLocation(current.availableLocations().minBy(p1->p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)))); } } if(current.needsTarget()) { //get closest target current.setTarget(current.availableTargets().minBy(p1 -> 0)); } return current; } //move backwards or forwards private Point2D move(ReadonlyAction readonlyAction, ReadonlyCharacter character, String direction) { Point2D location = null; //move direction depending on Y coordinate of point for(Point2D point2D:readonlyAction.availableLocations()) { switch (direction) { case "forward": if(startY > 5) { //bot started at bottom if (point2D.getY() < character.getLocation().getY()) location = point2D; }else{ //bot started at top if (point2D.getY() > character.getLocation().getY()) location = point2D; } break; case "backward": if(startY > 5) { //bot started at bottom if (point2D.getY() > character.getLocation().getY()) location = point2D; }else{ //bot started at top if (point2D.getY() < character.getLocation().getY()) location = point2D; } break; } } //if no available locations, just choose the first available location if(location == null) { location = readonlyAction.availableLocations().iterator().next(); } return location; } private int getPriority(ReadonlyAction action, ReadonlyCharacter character) { if(visibleEnemies.isEmpty()) { //if there are no visible enemies, Step. In the choose function, this becomes move forward or backward depending on health if(action.getName().equals("Step")) { return 100; } }else { /* * PRIORITIES: * 1. If near an enemy, and not a werewolf, turn into a werewolf * 2. Slice * 3. Step (when enemy is not in range --> move towards enemy) */ if (action.getName().equals("Werewolf") && action.isAvailable()) { EnemyWrapper wrap = getNearestEnemy(character); //don't turn into a werewolf unless we're close to an enemy if(wrap.location.diagonalDistance(character.getLocation()) < 3) { return 1; } }else if(action.getName().equals("Slice")) { return 10; }else if(action.getName().equals("Step")) { return 50; } } //Kids, don't Smile, instead Step or Slice return 1000; } private EnemyWrapper getNearestEnemy(ReadonlyCharacter character) { double closestEnemyDistance = Double.MAX_VALUE; Point2D closestEnemy = null; for ( Point2D enemyLocation : visibleEnemies.keySet()) { double visionDistanceDiff = character.getLocation().diagonalDistance(enemyLocation); if (visionDistanceDiff< closestEnemyDistance) { closestEnemyDistance = visionDistanceDiff; closestEnemy = enemyLocation; } } return new EnemyWrapper(visibleEnemies.get(closestEnemy), closestEnemy); } private static class EnemyWrapper { public final EnemyCharacter enemy; public final Point2D location; EnemyWrapper(EnemyCharacter e, Point2D l) { enemy = e; location = l; } } } ``` [Answer] # Railbender This bot is simply a version of **Derailer** that has had its third character replaced with a copy of the first. It produces much better results compared to Derailer. While creating Derailer, I wanted to give each character abilities that would synergize well with each other. Having one character with high HP and attack power and another character with the Restore action worked together nicely. However, it didn't seem like the third character fit in very well. That probably was the main reason Derailer didn't produce good results. So I figured that having a third character that can work well with and benefit from the others would be a better idea. ``` Railbender.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.Player; import fellowship.abilities.ActionAbility; import fellowship.abilities.ReadonlyAbility; import fellowship.abilities.attacking.Critical; import fellowship.abilities.stats.Buff; import fellowship.abilities.stats.Clever; import fellowship.abilities.stats.Strong; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Quick; import fellowship.actions.damage.Zap; import fellowship.actions.defensive.Restore; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.function.BinaryOperator; import java.util.stream.Collectors; public class Railbender extends Player { private static final double CRITICAL_HEALTH_PCT = .175; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> list = new ArrayList<>(); list.add(new CharacterTemplate(14, 3, 3, new Clever(), new Clever(), new ActionAbility(Restore::new), new ActionAbility(Zap::new))); for (int k = 0; k < 2; k++) { list.add(new CharacterTemplate(25, 2, 3, new Critical(), new Buff(), new ActionAbility(Quick::new), new Strong())); } return list; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { List<ReadonlyAbility> abilities = character.getAbilities(); ReadonlyAction action = null; for (ReadonlyAbility a : abilities) { String s = a.name(); int i = s.lastIndexOf("."); if (i == -1) continue; s = s.substring(i+1, s.length()); if (s.equals("Clever")) { action = getActionForChar1(character, actions); break; } else if (s.equals("Buff")) { action = getActionForChar2(character, actions); break; } } return action; } private ReadonlyAction getActionForChar1(ReadonlyCharacter character, Set<ReadonlyAction> actions) { int members = (int) team.stream().filter(c -> !c.isDead()).count(); List<ReadonlyAction> list = actions.stream() .sorted(Comparator.comparingInt(this::getPriority)) .collect(Collectors.toList()); Point2D closestEnemy = getClosestEnemyPoint(character); for (ReadonlyAction a : list) { String name = a.getName(); if (name.equals("Restore")) { for (ReadonlyCharacter teammate : team) { if (teammate.getHealth() / teammate.getMaxHealth() < CRITICAL_HEALTH_PCT * (4 - members)) return a; } } else if (name.equals("Zap") && !a.availableTargets().isEmpty() && closestEnemy != null && character.getLocation().cartesianDistance(closestEnemy) <= 4) { a.setTarget(a.availableTargets() .stream() .reduce( BinaryOperator.minBy( Comparator.<ReadonlyCharacter>comparingDouble(e -> e.getHealth()) ) ) .get() ); return a; } else if (name.equals("Slice") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().iterator().next()); return a; } else if (name.equals("Smile")) return a; } throw new RuntimeException("No available actions"); } private ReadonlyAction getActionForChar2(ReadonlyCharacter character, Set<ReadonlyAction> actions) { List<ReadonlyAction> list = actions.stream() .sorted(Comparator.comparingInt(this::getPriority)) .collect(Collectors.toList()); for (ReadonlyAction a : list) { String name = a.getName(); if (name.equals("Quick") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().minBy(ReadonlyCharacter::getHealth)); return a; } else if (name.equals("Slice") && !a.availableTargets().isEmpty()) { a.setTarget(a.availableTargets().minBy(ReadonlyCharacter::getHealth)); return a; } else if (name.equals("Step") && !a.availableLocations().isEmpty()) { Point2D e = getClosestEnemyPoint(character); if (e == null) { Point2D p = character.getLocation(); if (p.getY() > 5) { a.setLocation(a.availableLocations() .stream() .filter(x -> x.getY() < p.getY()) .findFirst() .orElse(a.availableLocations().iterator().next())); } else if (p.getY() < 4) { a.setLocation(a.availableLocations() .stream() .filter(x -> x.getY() > p.getY()) .findFirst() .orElse(a.availableLocations().iterator().next())); } else a.setLocation(randomLocation(new ArrayList<>(a.availableLocations()))); } else { int currentDistance = character.getLocation().cartesianDistance(e); a.setLocation(a.availableLocations() .stream() .filter(x -> x.cartesianDistance(e) < currentDistance) .findFirst() .orElse(randomLocation(new ArrayList<>(a.availableLocations())))); } return a; } else if (name.equals("Smile")) return a; } throw new RuntimeException("No available actions"); } private Point2D getClosestEnemyPoint(ReadonlyCharacter c) { return visibleEnemies.keySet() .stream() .reduce( BinaryOperator.minBy( Comparator.comparingInt(x -> x.cartesianDistance(c.getLocation())) ) ) .orElse(null); } private int getPriority(ReadonlyAction action) { switch (action.getName()) { case "Quick": case "Restore": return 1; case "Zap": return 2; case "Slice": return 3; case "Step": return 4; case "Smile": return 5; } throw new IllegalArgumentException(String.valueOf(action)); } private Point2D randomLocation(List<Point2D> l) { return l.get((int) (Math.random() * l.size())); } } ``` [Answer] # `Noob/*Destroyer*/` Uses **Strong** \* 2, **Regenerate**, and **Stun** (Stuns target for the next 300 ticks) ### STATS * **STR**: 5 + 40 * **AGI**: 5 + 0 * **INT**: 5 + 0 --- ### AI Most of Noob's code is taken from my LongSword. ### Strategy When the character first sees an enemy character, priority is giving to Stunning the enemy first, and then Slicing the enemy while they are stunned. And with its high health and regeneration, Noob should be able to survive until it is able to use Stun again. ``` Noob.java import fellowship.*; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.Stat; import fellowship.abilities.ActionAbility; import fellowship.abilities.stats.Regenerate; import fellowship.abilities.stats.Strong; import fellowship.actions.ReadonlyAction; import fellowship.actions.defensive.Shield; import fellowship.actions.statuses.Silence; import fellowship.actions.statuses.Stun; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.Player; import org.eclipse.collections.api.set.MutableSet; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Noob/*Destroyer*/ extends Player { private boolean debug = false; private void println(String text) { if(debug) System.out.println(text); } private boolean started = false; private int startY = 5; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(40, 0, 0, new Regenerate(), new ActionAbility(Stun::new), new Strong(), new Strong())); } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { if(!started) { startY = character.getLocation().getY(); started = true; } ReadonlyAction readonlyAction = null; //get priority of action int priority = Integer.MAX_VALUE; for(ReadonlyAction action:actions) { int priorityLocal = getPriority(action, character); if(priorityLocal < priority) { readonlyAction = action; priority = priorityLocal; } } if (readonlyAction == null){ println("NULL!"); throw new RuntimeException("No valid actions"); } //movement if(readonlyAction.needsLocation()) { if(visibleEnemies.isEmpty()) { if (character.getHealth() < 100) { readonlyAction.setLocation(move(readonlyAction, character, "backward")); } else { readonlyAction.setLocation(move(readonlyAction, character, "forward")); //enemy base is "forward" } }else{ readonlyAction.setLocation(readonlyAction.availableLocations().minBy(p1->p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)))); } } if(readonlyAction.needsTarget()) { readonlyAction.setTarget(readonlyAction.availableTargets().minBy(p1 -> 0)); } return readonlyAction; } private Point2D move(ReadonlyAction readonlyAction, ReadonlyCharacter character, String direction) { Point2D location = null; for(Point2D point2D:readonlyAction.availableLocations()) { switch (direction) { case "forward": if(startY > 5) { //bot starts at bottom if (point2D.getY() < character.getLocation().getY()) location = point2D; }else{ //bot starts at top if (point2D.getY() > character.getLocation().getY()) location = point2D; } break; case "backward": if(startY > 5) { //bot starts at bottom if (point2D.getY() > character.getLocation().getY()) location = point2D; }else{ //bot starts at top if (point2D.getY() < character.getLocation().getY()) location = point2D; } break; } } if(location == null) { location = readonlyAction.availableLocations().iterator().next(); } return location; } private int getPriority(ReadonlyAction action, ReadonlyCharacter character) { if(visibleEnemies.isEmpty()) { if(action.getName().equals("Step")) { return 100; } }else { if (action.getName().equals("Slice")) { return 10; }else if(action.getName().equals("Step")) { return 50; }else if(action.getName().equals("Stun") && !action.availableTargets().minBy(p1->0).isStunned()) { //if target is not stunned, stun 'em return 1; } } return 1000; } } ``` [Answer] # Living Wall A wall of living wood that can walk along the battlefield, landing strong hits on any enemy that comes by, and draining the sap out of them to bolster its maximum health. Its root system can detect vibrations, allowing it to lash out even at invisible enemies. It consists of: * 2 **Branches**: **STR** 35, **AGI** 5, **INT** 5, **Strong**, **Buff**, **Buff**, **Absorb** * 1 **Root** : **STR** 25, **AGI**, 5, **INT**, 5, **True Sight**, **Buff**, **Buff**, **Absorb** The AI is incredibly simple: find the enemy nearest to the team, then the entire wall focuses on that single enemy. There are only minor complications: if no enemies are in sight, walk towards random corners of and/or the centre of the map (thus eventually hunting down enemies who are hiding); if an enemy is within reach, attack it even if it isn't the enemy we're targeting (but prefer to focus on the enemy we're targeting, and even more so enemies we can OHKO). The team does incredibly well; in simulations, the only team (that exists at the time of writing) that can beat it is RogueSquad, and even then not always (sometimes even RogueSquad dies to the might of the wall). Invulnerables sometimes manages to scrape a draw. ~~The basic reason for the team's success is due to the combo of Buff×2 and Absorb; this means that every time we hit a STR-primary enemy, we're effectively gaining 40 HP in the short term (only 10 HP in the long term due to the increased regeneration from the stolen STR, but by then the fight should be over and our natural regeneration should tide us over), and given the natural regeneration rate of 12.5 or 17.5 on top of that, it's basically impossible to do damage fast enough to keep pace with the regeneration (an AGI team could potentially do it using hit-and-run tactics, but nobody's built one of those yet).~~ {**Update**: Apparently this combo doesn't actually work (Absorb only drains 10 HP), but the team somehow wins anyway.} Meanwhile, if the enemy *isn't* STR-primary, they won't like taking repeated 25- or 35-damage hits (and in fact may quite possibly be focused down within one of their turns); and if the enemy is INT-primary and using spells to defend themself (hi Invulnerables!), Absorb will eventually drain their MP down to the point where they can no longer afford to cast the spells. (Additionally, we have basically nothing to fear from most spells; their cooldowns are too long for their damage to outpace our regeneration. The main exceptions are Trap, which nobody's running yet, and Poison, which takes ages to wear down through 1000 or 1400 HP, but does work if the Wall doesn't beat the caster first.) True Sight is still the only ability practically capable of defeating invisible enemies (Track doesn't work because it requires the enemy to intentionally break invisibility within your LOS to use), so I had to put it on a team member out of necessity, lowering STR to fill the gap. ``` LivingWall.java import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.*; import fellowship.abilities.attacking.*; import fellowship.abilities.defensive.*; import fellowship.abilities.vision.*; import fellowship.abilities.stats.*; import fellowship.abilities.statuses.*; import fellowship.actions.*; import fellowship.actions.attacking.*; import fellowship.actions.damage.*; import fellowship.actions.defensive.*; import fellowship.actions.statuses.*; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import fellowship.characters.EnemyCharacter; import fellowship.*; import java.util.ArrayList; import java.util.List; import java.util.Set; public class LivingWall extends Player { @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 2; i++) templates.add(new CharacterTemplate(30, 0, 0, new Absorb(), new Strong(), new Buff(), new Buff())); templates.add(new CharacterTemplate(20, 0, 0, new Absorb(), new TrueSight(), new Buff(), new Buff())); return templates; } private String lastIdentifier(String s) { String[] split = s.split("\\W"); return split[split.length - 1]; } private boolean hasAbility(ReadonlyCharacter character, String abilityName) { for (ReadonlyAbility ability : character.getAbilities()) { if (lastIdentifier(ability.name()).equals(abilityName)) return true; } return false; } private boolean hasAbility(EnemyCharacter character, String abilityName) { for (ReadonlyAbility ability : character.getAbilities()) { if (lastIdentifier(ability.name()).equals(abilityName)) return true; } return false; } private int goalX = 5; private int goalY = 5; @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { /* If we're at the goal square, pick a new one. */ if (goalX == character.getLocation().getX() && goalY == character.getLocation().getY()) { int i = getRandom().nextInt(5); goalX = i < 2 ? 1 : i > 2 ? 9 : 5; goalY = i == 2 ? 5 : (i % 2) == 1 ? 1 : 9; } { int bestDistance = 99999; /* If there are visible enemies, place the goal square under the closest enemy to the team. */ for (Point2D enemyLocation : visibleEnemies.keysView()) { int distance = 0; for (ReadonlyCharacter ally : team) { Point2D allyLocation = ally.getLocation(); distance += (allyLocation.getX() - enemyLocation.getX()) * (allyLocation.getX() - enemyLocation.getX()) + (allyLocation.getY() - enemyLocation.getY()) * (allyLocation.getY() - enemyLocation.getY()); } if (distance < bestDistance) { goalX = enemyLocation.getX(); goalY = enemyLocation.getY(); bestDistance = distance; } } } /* We use a priority rule for actions. */ int bestPriority = -2; ReadonlyAction bestAction = null; for (ReadonlyAction action : actions) { int priority = 0; if (lastIdentifier(action.getName()).equals("Slice")) { int damagePotential = 35; /* We use these abilities with very high priority to /kill/ an enemy who's weak enough to die from the damage. If they wouldn't die, we still want to attack them, but we might prefer to attack other enemies instead. The enemy on the goal square (if any) is a slightly preferred target, to encourage the team to focus on a single enemy. */ ReadonlyCharacter chosenTarget = null; for (ReadonlyCharacter target : action.availableTargets()) { if (!isEnemy(target)) continue; chosenTarget = target; if (target.getHealth() <= damagePotential) { priority = 18; } else priority = 14; if (target.getLocation().getX() == goalX && target.getLocation().getY() == goalY) priority++; } if (chosenTarget == null) continue; action.setTarget(chosenTarget); } else if (lastIdentifier(action.getName()).equals("Smile")) { priority = 0; } else if (action.movementAction()) { /* Move towards the goal location. */ int bestDistance = 99999; Point2D bestLocation = null; priority = 1; for (Point2D location : action.availableLocations().toList().shuffleThis(getRandom())) { int distance = (location.getX() - goalX) * (location.getX() - goalX) + (location.getY() - goalY) * (location.getY() - goalY); if (distance < bestDistance) { bestDistance = distance; bestLocation = location; } } if (bestLocation == null) continue; action.setLocation(bestLocation); } else throw new RuntimeException("unknown action" + action.getName()); if (priority > bestPriority) { bestPriority = priority; bestAction = action; } } if (bestAction == null) throw new RuntimeException("no action?"); return bestAction; } } ``` [Answer] # DarkAbsorbers The Dark Absorbers are 2 brothers, which absorb the life force of their victims: * **Oracle Absorber** (can see invisible enemies) + **STR:** 25; **AGI:** 5; **INT:** 5 + **TrueSight**, **Flexible**, **Ranged**, **Absorb** * **Quick Absorber** (can absorb even quicker, than his brother) + **STR:** 25; **AGI:** 5; **INT:** 5 + **Quick**, **Flexible**, **Ranged**, **Absorb** They are always accompanied by a growing Darkness Cloud. Once it reaches a critical mass it starts to kill enemies. * **Darkness Cloud** + **STR:** 5; **AGI:** 5; **INT:** 25 + **Clone**, **Zap**, **Darkness** *You may reuse single characters from here in your team, as long as you add at least one more character which is not present here.* ``` DarkAbsorbers.java import java.util.Arrays; import java.util.List; import org.eclipse.collections.api.map.ImmutableMap; import org.eclipse.collections.api.set.ImmutableSet; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.ReadonlyAbility; import fellowship.abilities.attacking.Absorb; import fellowship.abilities.attacking.Flexible; import fellowship.abilities.attacking.Ranged; import fellowship.abilities.vision.Darkness; import fellowship.abilities.vision.TrueSight; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Quick; import fellowship.actions.damage.Zap; import fellowship.actions.defensive.ForceField; import fellowship.actions.other.Clone; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; public class DarkAbsorbers extends SleafarPlayer { private ReadonlyCharacter zapTarget = null; private CharacterTemplate oracleAbsorberTemplate() { return new CharacterTemplate(20, 0, 0, new TrueSight(), new Flexible(), new Ranged(), new Absorb()); } private CharacterTemplate quickAbsorberTemplate() { return new CharacterTemplate(20, 0, 0, new ActionAbility(Quick::new), new Flexible(), new Ranged(), new Absorb()); } private CharacterTemplate darknessCloudTemplate() { return new CharacterTemplate(0, 0, 20, new ActionAbility(Clone::new), new ActionAbility(Zap::new), new Darkness()); } @Override public List<CharacterTemplate> createCharacters() { return Arrays.asList(oracleAbsorberTemplate(), quickAbsorberTemplate(), darknessCloudTemplate()); } private class Absorber extends Character { protected Absorber(ReadonlyCharacter delegate) { super(delegate); } @Override protected ReadonlyAction choose() { ReadonlyAction quick = getAction(Quick.class); if (quick != null && setSliceTarget(quick, 100.0)) { return quick; } if (slice != null && setSliceTarget(slice, 100.0)) { return slice; } ImmutableMap<Point2D, Double> damage = getEnemySliceDamage(); ImmutableSet<Point2D> above5Damage = damage.select((k, v) -> v > 5.0).keysView().toSet().toImmutable(); if (step != null && (above5Damage.contains(getLocation()) || (getHealth() <= 5.0 && isInEnemySliceRange())) && setAvoidEnemiesLocation(step)) { return step; } if (quick != null && setSliceTarget(quick, 0.01)) { return quick; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && getSliceLocations().notEmpty() && setClosestLocation(step, getSliceLocations())) { return step; } if (step != null && setExploreLocation(step)) { return step; } return smile; } } private class DarknessCloud extends Character { private int zapCooldown = 0; private boolean zapNow = false; private boolean zapLater = false; protected DarknessCloud(ReadonlyCharacter delegate) { super(delegate); } private void updateZapFlags(double mana) { zapNow = zapCooldown == 0 && mana >= 15.0; zapLater = mana + 5 * getManaRegen() >= (zapNow ? 30.0 : 15.0); } private boolean isZappable(ReadonlyCharacter c, int zapNowCount, int zapLaterCount) { int forceFieldNow = 0; int forceFieldLater = 0; for (ReadonlyAbility a : c.getAbilities()) { if (a.abilityClass().equals(ForceField.class)) { forceFieldNow = a.getRemaining(); forceFieldLater = 5; } } return c.getHealth() + c.getHealthRegen() <= (zapNowCount - forceFieldNow) * 30.0 || c.getHealth() + c.getHealthRegen() * 6 <= (zapNowCount + zapLaterCount - forceFieldNow - forceFieldLater) * 30.0; } @Override protected ReadonlyAction choose() { ReadonlyAction clone = getAction(Clone.class); ReadonlyAction zap = getAction(Zap.class); zapCooldown = zapCooldown > 0 ? zapCooldown - 1 : 0; updateZapFlags(getMana()); int zapNowCount = characters.count(c -> c instanceof DarknessCloud && ((DarknessCloud) c).zapNow); int zapLaterCount = characters.count(c -> c instanceof DarknessCloud && ((DarknessCloud) c).zapLater); if (zap != null) { if (zapTarget != null && (!zap.availableTargets().contains(zapTarget) || zapTarget.isDead() || !isZappable(zapTarget, zapNowCount, zapLaterCount))) { zapTarget = null; } if (zapTarget == null) { zapTarget = chooseSmallest(zap.availableTargets().reject(c -> isBear(c) || !isZappable(c, zapNowCount, zapLaterCount)), HEALTH_COMPARATOR); } if (zapTarget != null) { zapCooldown = 5; zapNow = false; zap.setTarget(zapTarget); return zap; } } ImmutableMap<Point2D, Double> damage = getEnemySliceDamage(); ImmutableSet<Point2D> above5Damage = damage.select((k, v) -> v > 5.0).keysView().toSet().toImmutable(); if (clone != null) { if (visibleEnemies.isEmpty()) { if (setFarthestLocation(clone, getTeamHiddenLocations())) { updateZapFlags(getMana() - 100.0); return clone; } } else { if (setFarthestLocation(clone, above5Damage, getEnemyLocations()) || setLocation(clone, chooseSmallest(clone.availableLocations(), (o1, o2) -> Double.compare(damage.get(o1), damage.get(o2))))) { updateZapFlags(getMana() - 100.0); return clone; } } return clone; } if (step != null && (above5Damage.contains(getLocation()) || (getHealth() <= 5.0 && isInEnemySliceRange())) && setAvoidEnemiesLocation(step)) { return step; } if (slice != null && setSliceTarget(slice, 0.01)) { return slice; } if (step != null && !visibleEnemies.isEmpty() && setFarthestLocation(step, getEnemySliceLocations(), getEnemyLocations())) { return step; } return smile; } } @Override protected Character createCharacter(ReadonlyCharacter delegate) { if (hasAbility(delegate, Absorb.class)) { return new Absorber(delegate); } else if (hasAbility(delegate, Darkness.class)) { return new DarknessCloud(delegate); } else { throw new IllegalArgumentException(); } } } ``` [Answer] # LongSwordv2 > > "You can run, but you can't hide..."- **LongSwordv2** > > > Uses **Ranged**, **Flexible**, **Quick**, **TrueSight** This bot is *exactly* the same as LongSwordv2, except that it uses TrueSight instead of Strong. Seeing the rise in invisible bots, I decided to create a bot that is focused in taking them out since they are undetectable by many bots. With its long range and flexible Slice range and double Slice ActionAbility, LongSwordv2 should be able to inflict heavy damage before the enemy characters come into Slicing range. And in its testing stages, I'd say it wins against teams that are centred around invisible characters most of the time. ``` LongSwordv2.java import fellowship.*; import com.nmerrill.kothcomm.game.maps.Point2D; import fellowship.abilities.ActionAbility; import fellowship.abilities.attacking.Flexible; import fellowship.abilities.attacking.Ranged; import fellowship.abilities.stats.Strong; import fellowship.abilities.vision.Darkness; import fellowship.abilities.vision.TrueSight; import fellowship.actions.ReadonlyAction; import fellowship.actions.attacking.Quick; import fellowship.characters.CharacterTemplate; import fellowship.characters.ReadonlyCharacter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public class LongSwordv2 extends Player{ //debugging private boolean debug = false; private void println(String text) { if(debug) System.out.println(text); } //variables use to hold the start Y coordinate of the bot private boolean started = false; private int startY = 5; private boolean together = false; @Override public List<CharacterTemplate> createCharacters() { List<CharacterTemplate> templates = new ArrayList<>(); for (int i = 0; i < 3; i++) { templates.add(new CharacterTemplate(20, 0, 0, new Ranged(), //Adds 1 to the range of Slice new Flexible(), //Can Slice in any of the 8 directions new ActionAbility(Quick::new), //Slice twice, Mana: 3, Cooldown: 0 new TrueSight())); //Reveals all hidden units within range 2 at turn start } return templates; } @Override public ReadonlyAction choose(Set<ReadonlyAction> actions, ReadonlyCharacter character) { if(!started) { startY = character.getLocation().getY(); //giving startY the value of the bot's starting y-value started = true; //do this only once, that's why there is the if statement } ReadonlyAction current = null; //choosing action depending on priority int priority = Integer.MAX_VALUE; for(ReadonlyAction action:actions) { int priorityLocal = getPriority(action, character); if(priorityLocal < priority) { current = action; priority = priorityLocal; } } if (current == null){ throw new RuntimeException("No valid actions"); } println(current.getName()); if(current.needsLocation()) { if(visibleEnemies.isEmpty()) { if (character.getHealth() < 100) { //if has low health, go backwards towards "base" //println("lowHealth"); current.setLocation(move(current, character, "backward")); } else { //else go forwards to enemy's "base" current.setLocation(move(current, character, "forward")); } }else{ //go towards closest enemy current.setLocation(current.availableLocations().minBy(p1->p1.cartesianDistance(visibleEnemies.keysView().minBy(p1::cartesianDistance)))); } } if(current.needsTarget()) { //get closest target current.setTarget(current.availableTargets().minBy(p1 -> 0)); } Iterator<ReadonlyCharacter> iterator = current.availableTargets().iterator(); while(iterator.hasNext()) { Point2D loc = iterator.next().getLocation(); println(loc.getX()+","+loc.getY()); } return current; } //move backwards or forwards private Point2D move(ReadonlyAction readonlyAction, ReadonlyCharacter character, String direction) { Point2D location = null; //move direction depending on Y coordinate of point for(Point2D point2D:readonlyAction.availableLocations()) { switch (direction) { case "forward": if(startY > 5) { //bot started at bottom if (point2D.getY() < character.getLocation().getY()) location = point2D; }else{ //bot started at top if (point2D.getY() > character.getLocation().getY()) location = point2D; } break; case "backward": if(startY > 5) { //bot started at bottom if (point2D.getY() > character.getLocation().getY()) location = point2D; }else{ //bot started at top if (point2D.getY() < character.getLocation().getY()) location = point2D; } break; } } //if no available locations, just choose the first available location if(location == null) { location = readonlyAction.availableLocations().iterator().next(); } println(location.getY()+","+character.getLocation().getY()); return location; } private int getPriority(ReadonlyAction action, ReadonlyCharacter character) { if(visibleEnemies.isEmpty()) { //if there are no visible enemies, Step. In the choose function, this becomes move forward or backward depending on health if(action.getName().equals("Step")) { return 100; } }else { /* * PRIORITIES: * 1. Quick (Slice twice) * 2. Slice * 3. Step (when enemy is not in range --> move towards enemy) */ if (action.getName().equals("Quick")) { return 1; }else if(action.getName().equals("Slice")) { return 10; }else if(action.getName().equals("Step")) { return 50; } } //Kids, don't Smile, instead Step or Slice return 1000; } } ``` ]
[Question] [ Seems like an impossible task right? Well, it's actually not that hard. If we write the word `Infinity` as 8-bit binary ASCII code, we'll get: ``` 01001001 01101110 01100110 01101001 01101110 01101001 01110100 01111001 ``` This can be concatenated, and converted to the decimal value `5291279215216915577`. Now that's a number we can work with... The way you'll count down is: 1. Output the original string as a decimal number (as shown above) 2. Remove leading 0s in its binary representation (if any) 3. Toggle the bits in the binary representation (1->0, 0->1) 4. Output the number in decimal 5. Repeat steps 2-4 as until you reach 0. **Challenge:** Create a program or function that takes a string as input, and outputs (on any suitable format) the numbers you'll get when performing the procedure above. **Test case:** I think the challenge will be fairly easy to understand, even though it's only one test case. I'll use `Inf` instead of `Infinity` to keep this fairly short. ``` Inf 4812390 (10010010110111001100110) 3576217 ( 1101101001000110011001) 618086 ( 10010110111001100110) 430489 ( 1101001000110011001) 93798 ( 10110111001100110) 37273 ( 1001000110011001) 28262 ( 110111001100110) 4505 ( 1000110011001) 3686 ( 111001100110) 409 ( 110011001) 102 ( 1100110) 25 ( 11001) 6 ( 110) 1 ( 1) 0 ( 0) ``` ``` Input: Inf Output: 4812390, 3576217, 618086, 430489, 93798, 37273, 28262, 4505, 3686, 409, 102, 25, 6, 1, 0 ``` ``` Input: Infinity Output: 5291279215216915577, 3932092821637860230, 679593196789527673, 473328307817319302, 103132444486104185, 40982743589751686, 31074850448176249, 4953946570787718, 4053252683953273, 450346943417222, 112603010004089, 28134478351238, 7049893737593, 1746199284614, 452823970937, 96931842950, 40507110521, 28212366214, 6147372153, 2442562438, 1852404857, 295078790, 241792121, 26643334, 6911097, 1477510, 619641, 428934, 95353, 35718, 29817, 2950, 1145, 902, 121, 6, 1, 0 ``` Your code must support strings that can be represented as a binary number up to the limit of your language. All strings will only contain printable ASCII-characters from 32-126 (space to tilde). --- ## Leaderboard ``` var QUESTION_ID=98274,OVERRIDE_USER=31516;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] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -5 bytes thanks to @Dennis (convert directly from base 256 after ordinal cast) ``` Oḅ⁹µBCḄµÐĿ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=T-G4heKBucK1QkPhuITCtcOQxL8&input=&args=QW4gZXhhbXBsZSB3aXRoIDYzIGRpZ2l0cyE)** ### How? ``` Oḅ⁹µBCḄµÐĿ - Main link: s e.g. "Inf" O - cast to ordinals e.g. [73,110,102] ḅ⁹ - convert from base 256 to integer e.g. 4812390 µ µ - monadic chain separations B - convert to binary C - complement Ḅ - convert to integer ÐĿ - loop until no longer unique and collect results ``` [Answer] # Python 2, ~~89~~ ~~82~~ ~~77~~ ~~76~~ 75 bytes ``` n=0 for c in input():n=n<<8|ord(c) while 1:print n;n^=2**n.bit_length()-n/n ``` Test it on [Ideone](http://ideone.com/1aiYcE). ### How it works After initializing **n** to **0**, the second line performs the string-to-integer conversion specified in the challenges as follows. In each step, **n** is shifted **8** units to the left, then bitwise **OR**-ed with the the code point of the next character **c**. For input **Inf**, this goes as follows. ``` n 0 a = n<<8 0 b = 'I' 1001001 n = a ^ b 1001001 a = n<<8 100100100000000 b = 'n' 1101110 n = a ^ b 100100101101110 a = n<<8 10010010110111000000000 b = 'f' 1100110 n = a ^ b 10010010110111001100110 ``` Now we're ready to generate the output. To invert the bits of **n**, we proceed as follows. First, we compute the bits in **n**'s binary representation without leading zeroes. Let's call the result **k**. Then, we compute the **k**k power of **2**, which has **k+1** binary digits: a single **1**, followed by **k** **0**'s. We subtract **1** from the result, yielding a number composed of **k** ones, which we then XOR with **n** to invert its bits. For input **inf** this goes as follows. ``` n 4812390 10010010110111001100110 k 23 t = 2**k 100000000000000000000000 t -= 1 11111111111111111111111 n ^= t 3576217 1101101001000110011001 k 22 t = 2**k 10000000000000000000000 t -= 1 1111111111111111111111 n ^= t 618086 10010110111001100110 . . . n 6 110 k 3 t = 2**k 1000 t -= 1 111 n ^= t 1 1 k 1 t = 2**k 10 t -= 1 1 n ^= t 0 0 ``` On additional hurdle in the implementation is that we have to print **n** before the first step, *after* the last step, and in all steps in between. Python doesn't have do-while loops and a single *print* statement costs **8** bytes, so we do the following instead. In the straightforward implementation of the update step, i.e., ``` while n:print n;n^=2**n.bit_length()-1 print n ``` we replace the loop with an infinite one (`while 1`) and compute the `1` in the loop as `n/n`. This is equivalent while **n > 0**. Once **n = 0**, we stay in the loop, print the state once more, then try to update it. However, `0/0` triggers a *ZeroDivisionError*, breaking out of the loop and exiting with an error. Note that this causes stray output to STDERR, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/4781/12012). [Answer] # JavaScript, 82 bytes *Saved a byte thanks to @Arnuald* ``` for(y of prompt(n=0))n=n<<8|y.charCodeAt() for(;alert(n)|n;)for(i=1;i<=n;i*=2)n^=i ``` One of the very few times when a full program outperforms a function (and ES6 does not outperform ES5)... --- The above supports up to 4-letter words. Add 4 bytes to support up to 6-letter words: ``` for(y of prompt(n=0))n=n*256+y.charCodeAt() for(;alert(n)|n;n=i-n-1)for(i=1;i<=n;)i*=2 ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 14 bytes ``` 2@├¿W■├♂≈♂Y2@¿ ``` [Try it online!](http://actually.tryitonline.net/#code=MkDilJzCv1filqDilJzimYLiiYjimYJZMkDCvw&input=IkluZiI) Explanation: ``` 2@├¿W■├♂≈♂Y2@¿ @├ encode input in binary 2 ¿ convert from binary to decimal W while the number is not 0: ■ print the number without popping ├ convert number to binary ♂≈ convert each character to an int ♂Y boolean negate each int 2@¿ convert from binary to decimal ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 18 bytes Uses [CP-1252](http://www.cp1252.com) encoding. ``` Çžz+b€¦J[CÐ,_#bS_J ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4fFvnorYuKCrMKmSltDw5AsXyNiU19K&input=SW5m) **Explanation** ``` Ç # convert string to list of ascii codes žz+ # add 256 to each b # convert to binary €¦ # remove the first digit of each list of digits J # join [ # start loop C # convert to decimal Ð # triplicate , # print 1 copy _# # if the 2nd copy is 0, break loop b # convert 3rd copy to binary S # split to list _ # negate each in list J # join ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 13 bytes ``` 8W:qZA`tB~XBt ``` [Try it online!](http://matl.tryitonline.net/#code=OFc6cVpBYHRCflhCdA&input=J0luZic) ### Explanation ``` 8W:q % Push array [0 1 ... 255] ZA % Take input string and convert it from the base defined by the % alphabet [0 1 ... 255] to decimal ` % Do...while t % Duplicate B % Convert to binary ~ % Negate XB % Convert to decimal t % Duplicate. Used as loop condition: exit if zero ``` [Answer] # Mathematica, 99 bytes ``` a=FromDigits;b=IntegerDigits;NestWhileList[a[1-#~b~2,2]&,a[Join@@b[ToCharacterCode@#,2,8],2],#>0&]& ``` Anonymous function. Takes a string as input, and returns a list of numbers as output. [Answer] # Haskell, ~~109~~ ~~123~~ ~~118~~ ~~102~~ 97 bytes Thanks to @nimi for saving 5 bytes! ``` c 0=0 c n=1-mod n 2+2*c(div n 2) (++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum ``` Usage: `(++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum $ "Infinity"` Guaranteed to work on numbers up to 29 bits by the language, usually works up to 63-bit numbers on 64-bit systems. Use `map(fromIntegral.fromEnum)` instead (+14 bytes) to support arbitrarily large numbers. Works for unicode range `[0..255]`. Recursively flips bits. [Answer] # PHP, ~~132~~ ~~126~~ ~~123~~ ~~120~~ ~~108~~ 107 bytes ``` foreach(unpack("C*",$argv[1])as$i)$n=$n*256+$i;for(print$n;$n;)echo _.$n=bindec(strtr(decbin($n),"01",10)); ``` * printing 0 after loop instead of initial value before loop saves 6 bytes. * `unpack` instead of `str_split` renders `ord()` obsolete -> -3 bytes * underscore `_` as separator saves 3. * `bindec` instead of `ltrim` to remove leading zeroes: -12 * `echo` in loop body saves 1 byte over `print` in loop head. [Answer] ## Perl, 65 bytes **53 bytes code + 12 for `-Mbigint -p`.** Thanks to @[Dada](https://codegolf.stackexchange.com/users/55508/dada) for saving me 13 bytes! ``` $_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0 ``` Fairly straightforward approach, only different to most of these is that the number is stored as binary and printed out in decimal. I'm sure it can be improved, perhaps with storing details in an array. `-Mbigint` is a bit inconvenient but necessary. ### Usage ``` echo -n 'Inf' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0' 4812390 3576217 618086 430489 93798 37273 28262 4505 3686 409 102 25 6 1 0 ``` ``` echo -n 'Infinity' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0' 5291279215216915577 3932092821637860230 679593196789527673 473328307817319302 103132444486104185 40982743589751686 31074850448176249 4953946570787718 4053252683953273 450346943417222 112603010004089 28134478351238 7049893737593 1746199284614 452823970937 96931842950 40507110521 28212366214 6147372153 2442562438 1852404857 295078790 241792121 26643334 6911097 1477510 619641 428934 95353 35718 29817 2950 1145 902 121 6 1 0 ``` [Answer] # Pyth, 12 bytes ``` .usi!MjN2 2C ``` A program that takes input of a quoted string and prints the result as a list of integers. [Verify all test cases](https://pyth.herokuapp.com/?code=.usi%21MjN2+2C&test_suite=1&test_suite_input=%22Inf%22%0A%22Infinity%22&debug=0) **How it works** ``` .usi!MjN2 2C Program. Input: Q C Convert Q to an integer by code-points using base-256 (implicit input) .u Apply the following function A(N) until a repeat occurs, storing the results in a list: jN2 Convert to binary as a list !M Map negation over the above i 2 Convert from binary to integer s Integer (Converts final False to 0) Implicitly print ``` [Answer] # Python 3, ~~99~~ 95 bytes ``` x=int.from_bytes(bytes(input(),'utf-8'),'big') while x:print(x);x^=2**x.bit_length()-1 print(0) ``` Main idea is to convert string to bytes to to number. Each iteration print the output and XOR with all 1s to progress towards zero. [Answer] # Python 2, ~~117~~ 115 bytes Saving 2 bytes thanks to Cyoce. Assumes input enclosed in quotes, e.g. `"Inf"` ``` s=input() n=sum(ord(s[-i-1])<<i*8for i in range(len(s))) while n: print n;k,m=n,1 while k:k/=2;m*=2 n^=m-1 print 0 ``` `m` counts up to the highest digit, so `m-1` is a XOR mask to perform the desired operation. The longest part is converting the input into the initial bit sequence. Example: ``` "Inf" 4812390 3576217 618086 430489 93798 37273 28262 4505 3686 409 102 25 6 1 0 "Infinity" 5291279215216915577 3932092821637860230 679593196789527673 473328307817319302 103132444486104185 40982743589751686 31074850448176249 4953946570787718 4053252683953273 450346943417222 112603010004089 28134478351238 7049893737593 1746199284614 452823970937 96931842950 40507110521 28212366214 6147372153 2442562438 1852404857 295078790 241792121 26643334 6911097 1477510 619641 428934 95353 35718 29817 2950 1145 902 121 6 1 0 ``` [Answer] # Ruby, ~~104~~ ~~101~~ ~~100~~ ~~81~~ ~~80~~ 65 bytes *19 bytes saved thanks to @WayneConrad! 15 Bytes saved thanks to @philomory! 1 byte saved thanks to @LeeW!* ``` p n=$*[0].unpack('B*')[0].to_i(2) p n^=2**n.bit_length-1while n>0 ``` Takes input via command line arguments. Inspired by @JimmyJohnson's [Python answer](https://codegolf.stackexchange.com/a/98295/41042) [Answer] # [Labyrinth](http://esolangs.org/wiki/Labyrinth%20Labyrinth), 104 103 bytes ``` ' )25 }_';:_';_2/;{ ''', 6 2 1 1 { ( ' | / _ _ _}*2_ $ * _ :!\ }2_\ !: 652 @''''''' ``` [Try it Online!](http://labyrinth.tryitonline.net/#code=JyAgKTI1IH1fJzs6Xyc7XzIvO3sKJycnLCA2IDIgMSAgIDEgICB7ICgKICcgfCAvIF8gXyAgIF99KjJfICQKICogXyA6IVwgfTJfXCAgICAgIDoKIDY1MiAgICAgICBAJycnJycnJyE&input=SW5m) ## Explanation: [![Color-coded image of source code](https://i.stack.imgur.com/HK4RJ.png)](https://i.stack.imgur.com/HK4RJ.png) The instruction pointer starts at the top-left most non-wall character (walls include spaces and any letter except `v`). ### Orange: This loop gets the input one character at a time as an ASCII code, adding it to the current value and multiplying the current value by 256. * `'` No-op * `,` Push the ascii code of the next input char to the top of the stack or -1 if EOF. At this point if input was received, the code will turn right (moving down) because the top of the stack is potive. Otherwise it will turn left because the top of the stack is negative. * `|` Pop the top two items from the stack and push the result of a bitwise OR. * `_` Push zero * `256` Each digit seen pops `x` and pushes `x*10+digit`. So this combined with the push zero previous push 256 to the top of the stack. * `*` Pop `y`, pop `x`, push `x*y`. At this point since the top of the stack is positive the code will turn right to continue around the loop. ### Blue: * `)` Increment the top of the stack. When the end of input is reached, the code will turn left to get to this point with a -1 on the stack which will get incremented to zero. * `256` Having the top of the stack 0 allows us to push this 256. * `/` Pop `y`, pop `x` push `x/y` (integer division). Since we were multiplying the input by 256 each loop, we need to revert the last multiplication. * `:` Duplicate the top of the stack so we have a copy of the current value for later. * `!` Pop the top of the stack and print the integer value to STDOUT. * `\` Print a new line. * `_2` Push a two to the top of the stack. * `}` Move the top of the stack to the top of the auxiliary stack. ### Red: This loop flips the bits of the current value by XOR with a particular value calculated in the inner (green) loop. It then outputs the current value and exits the program if the current value is zero. * `_` Push zero (control flow). * `;` Discard the top of the stack (control flow). * `:` Duplicate the current value. The copy will be used to calculate the XOR. * `_` Push zero (control flow). * (Green loop) * `$` Pop `y`, pop `x`, Push `x XOR y`. * `:!` Duplicate the current value and print the integer representation. * If the current value is 0, we continue straight into the `@` and terminate. * `\` Print a new line. * `_2}` Push 2 and move to the aux stack. * `_1` Push 1 (control flow). ### Green: This loop calculates the value by which we need to XOR the current value. This is done by repeatedly doubling the top of the auxiliary stack while halving a copy of the current value on the stop of the main stack until it reaches 0. * `_` Push zero (control flow). * `;` Discard the current value which is only used to enforce control flow. * `_2` Push 2 in order to halve the current value. * `/` Divide * `{` Move the top of the aux stack to the top of the main stack. * `_2*` Double the top of the stack * `}` Move the top of the main stack back to the aux stack. * `_1` Push one for control flow. * After exiting the loop: * `;` Discard the left over zero from calculating the XOR. * `{` Move the calculated XOR to the main stack. * `(` Subtract one from XOR value. [Answer] ## PowerShell v2+, 158 bytes ``` for($a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)});$a){[convert]::ToInt64($a,2);$a=$a.TrimStart('0')-split0-replace1,0-join1} ``` Yeah, so, converting bases in PowerShell [is really sucky](https://codegolf.stackexchange.com/search?q=base+user%3A42963+is%3Aa). And we get to do it twice here. OK, so this is just a `for` loop on `$a` -- i.e., we loop so long as `$a` exists. We'll eventually reach an empty string (which is falsey), so that's how we'll terminate. The setup of the loop, `$a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)})`, takes the input `$args[0]`, casts it as a `char`-array, and loops through each character. We use the .NET `[convert]::ToString(int,base)` to convert each to a binary string. However, that doesn't include leading zeros, so we need to re-cast that string as an `[int]` and call *its* `.ToString()` method with `8` zeros as the mask. Then those strings are encapsulated in parens and `-join`ed together, then saved into `$a`. Inside the loop, we `[convert]::ToInt64(string,base)` to convert the binary number to a decimal number. That gets left on the pipeline and is subsequently flushed when the loop resets (and therefore implicitly printed). The next section performs the calculations -- we `.TrimStart()` to remove any leading zeros, `-split0` to split on zeros and get a `string`-array of `1`s, `-replace` those ones with zeros, and finally `-join` the array back together with `1`s. Then, the loop begins again. ``` PS C:\Tools\Scripts\golfing> .\count-down-from-infinity.ps1 'PPCG' 1347437383 800046264 273695559 263175352 5260103 3128504 1065799 1031352 17223 15544 839 184 71 56 7 0 ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~17~~ ~~16~~ 18 bytes ``` q256b0{_p2b:!2bj}j ``` [Try it online!](http://cjam.tryitonline.net/#code=cTI1NmIwe19wMmI6ITJian1q&input=) ``` q256b e# read printable ascii to integer 0 e# value for terminal case { e# recursive function _p e# print current number 2b e# create binary representation with no leading zeros :! e# flip bits 2b e# convert binary back to integer j e# recursive call }j e# end ``` ***NOTE:*** The old 16 byte version didn't behave correctly with empty strings: ``` q256b{_p2b:!2b}h ``` Also, thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for suggesting `p` which saves 1 byte over `N\` putting newlines into the stack. [Answer] # J, 24 bytes ``` 256-.&.#:^:*^:a:@#.a.&i. ``` Explanation will come later! [Answer] # Retina, 116 bytes Byte count assumes ISO 8859-1 encoding. Line 5 contains non-printable bytes. It's `T`\x00-\xFF`. ``` -2` ± s{`±(.) $&$1 }T`-`_o`±. [^±]+ $.& ± \d+ $* +`(1+)\1 ${1}0 01 1 {*(`1 01 +`10 011 ^0+ )M`1 ^0+ T`01`10 ``` [**Try it online**](http://retina.tryitonline.net/#code=LTJgCsKxCnN7YMKxKC4pCiQmJDEKfVRgAS1_YF9vYMKxLgpbXsKxXSsKJC4mCsKxCiAKXGQrCiQqCitgKDErKVwxCiR7MX0wCjAxCjEKIAoKeyooYDEKMDEKK2AxMAowMTEKXjArCgopTWAxCl4wKwoKVGAwMWAxMA&input=SW4) Don't try this with input longer than two characters. (It times out using the online interpreter.) We gotta convert the binary to unary before decimal. :D Unfortunately, there's a trailing zero and linefeed, but I decided to assume that was okay because the output is still correct. **Explanation** ``` -2` # Convert ASCII to decimal (ord) ± s{`±(.) $&$1 }T`-`_o`±. [^±]+ $.& ± \d+ # Decimal to binary $* +`(1+)\1 ${1}0 01 1 {*(`1 # Loop; Loop print and undo; Convert binary to unary 01 +`10 011 ^0+ )M`1 # Unary to decimal; End print and undo ^0+ # Remove leading zeros T`01`10 # Flip bits; (implicit loop end) ``` [Answer] # Ruby - 70 bytes ``` λ cat inf.rb n,=$*[0].unpack 'B*';loop{p n.to_i(2);n.tr!('10','01').sub!(/^0*/,'')} λ ruby inf.rb Hello 310939249775 788572378000 310939249775 238816564112 36061342831 32658133904 1701604463 445879184 90991727 43226000 23882863 9671568 7105647 1282960 814191 234384 27759 5008 3183 912 111 16 15 0 inf.rb:1:in `block in <main>': undefined method `sub!' for nil:NilClass (NoMethodError) from inf.rb:1:in `loop' from inf.rb:1:in `<main>' ``` The program exits with an exception after completing, but my understanding is that that is fine as long as the error output goes to STDERR rather than STDOUT (which it does). [Answer] # C, ~~147~~ ~~135~~ ~~133~~ ~~125~~ ~~122~~ ~~121~~ ~~117~~ ~~115~~ 103 bytes *Saved 5 bytes thanks to @Cyoce!* *Saved 2 bytes thanks to @Cyoce and @cleblanc!* *Saved 12 bytes thanks to @ceilingcat* ``` i,n;main(p,v)char**v;{while(*v[1])i=i*256+*v[1]++;for(;printf("%d\n",n=i),i;i^=p-1)for(p=2;n/=2;)p*=2;} ``` Ungolfed: ``` int i; int main (c,v) { char**v; while (*v[1]) /* put first command line argument into i as binary */ i = i*256 + *v[1]++; while (i != 0) { printf("%d\n",i); int p = 2,n = i; while (n /= 2) /* calculate smallest power of 2 > i */ p *= 2; i ^= p - 1; /* flip bits */ } } ``` [Answer] # C, ~~129~~ ~~120~~ ~~117~~ ~~110~~ ~~107~~ 105 Bytes ``` long long i,m,n;f(char*v){for(;*v;i<<=8,i+=*v++);for(;printf("%llu,",i),n=i;i^=m-1)for(m=2;n>>=1;m<<=1);} ``` Tested with ``` main (int c, char**v) { f(v[1]); } ``` output ``` 5291279215216915577,3932092821637860230,679593196789527673,473328307817319302,103132444486104185,40982743589751686,31074850448176249,4953946570787718,4053252683953273,450346943417222,112603010004089,28134478351238,7049893737593,1746199284614,452823970937,96931842950,40507110521,28212366214,6147372153,2442562438,1852404857,295078790,241792121,26643334,6911097,1477510,619641,428934,95353,35718,29817,2950,1145,902,121,6,1,0, ``` [Answer] # C#, ~~360~~ 359 bytes ``` using w=System.Console;using q=System.Convert;s={System.Func<int,int,string>S=q.ToString;string t="",f="";for(int i=0;i<s.Length;i++)t+=i>0?S(s[i],2).PadLeft(8,'0'):S(s[i],2);w.WriteLine(q.ToInt64(t,2).ToString());while(t!="0"){f="";foreach(var n in t)f+=n=='0'?'1':'0';t=f.TrimStart(new char[]{'0'});t+=t==""?"0":"";w.WriteLine(q.ToInt64(t,2).ToString());}}; ``` Full program: ``` using w = System.Console; using q = System.Convert; class a { static void Main() { System.Action<string> b = s => { System.Func<int,int,string> S = q.ToString; string t = "", f = ""; // Var does not work here for(int i = 0; i < s.Length; i++) t += i > 0 ? S(s[i], 2).PadLeft(8, '0') : S(s[i], 2); w.WriteLine(q.ToInt64(t, 2).ToString()); while(t != "0") { f = ""; foreach (var n in t) f += n== '0' ? '1' : '0'; t = f.TrimStart(new char[] { '0' }); t += t == "" ? "0" : ""; w.WriteLine(q.ToInt64(t, 2).ToString()); } }; b("Inf"); b("Infinity"); w.Read(); // prevent close in VS } } ``` ]
[Question] [ Recently, an electrical engineer studying traffic light timings was [fined $500 by the state of Oregon](https://motherboard.vice.com/en_us/article/oregon-man-fined-for-writing-i-am-an-engineer-temporarily-wins-the-right-to-call-himself-an-engineer) for referring to himself as an engineer. Given a 2 letter string as input, representing a US state, output: * `I am not an engineer` if the state is Oregon (`OR`) * `I am an engineer` if the state is any other US state * `What is an engineer?` given any other input Output may not contain any *leading* whitespace, but may contain as much *trailing* whitespace as you wish. You can assume the input will always be 2 uppercase letters. Here is a list of all 50 US state abbreviations: ``` AL, AK, AZ, AR, CA, CO, CT, DE, FL, GA, HI, ID, IL, IN, IA, KS, KY, LA, ME, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, OH, OK, OR, PA, RI, SC, SD, TN, TX, UT, VT, VA, WA, WV, WI, WY ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes **in each language** wins! [Answer] # C#, ~~311 309~~ ~~240~~ ~~237~~ ~~222~~ ~~195~~ ~~184~~ 183 bytes ``` s=>s=="OR"?"I am not an engineer":"MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY".Contains(s)?"I am an engineer":"What is an engineer?"; ``` [Try it online!](https://tio.run/##dY9BT8JAEIXv@yte9tQmyg8QC9kUkEp3SwCpaDystcFN2q3pLCaG8NvrIh4kkcPLJPPNvJlX0HXd2KbbkbFbLL/IlXWfsaLSRBB7xj52r5UpQE47XyY7W9ySa/3wFU51AB11FA0oini24EOeQNewjYO2KO3W2LJs@Q2XiYpFKiCX8UpJtRazDXLxhLlYYJLiTkBNkxHibLYcQY4hR15@fPUINYa6h9pAeZJNkS0SgYcV8rVXkiLf8F7cWKeNpYDC3xfOz@fv2sHQ3@6Q97vzeJ@NeYP0NsEp2/MLdLulkO2Z96emKnt5a1yZ@v1AB8e8Ydj/n4n0Mouzy2wuf9iBHbpv "C# (Mono) – Try It Online") *Saved 2 bytes by adding the space before `an` to `b`* *~~-69 (huehue)~~ -72 bytes thanks to TheLethalCoder* *-15 bytes thanks to TotallyHuman's genius states string* *-38 bytes cos more string compression* Ungolfed: ``` public static string a(string s) { var b = " an engineer"; if (s == "OR") { return "I am not" + b; } else { if ("MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY".Contains(s)) { return "I am" + b; } else { return $"What is{b}?"; } } } ``` [Answer] ## JavaScript (ES6), 182 bytes ``` s=>['I am'+(x=' an engineer'),`What is${x}?`,'I am not'+x][s=='OR'?2:'MNNMLATNAKALARAZCACOCTDEFLGAHIIAIDILINKSKYMAMDMEMIMOMSMTNCNDNENHNJNVNYOHOKPARISCSDTXUTVAVTWAWIWVWY'.search(s)&1] ``` ### Demo ``` let f = s=>['I am'+(x=' an engineer'),`What is${x}?`,'I am not'+x][s=='OR'?2:'MNNMLATNAKALARAZCACOCTDEFLGAHIIAIDILINKSKYMAMDMEMIMOMSMTNCNDNENHNJNVNYOHOKPARISCSDTXUTVAVTWAWIWVWY'.search(s)&1] console.log(f("OR")) console.log(f("NY")) console.log(f("TX")) console.log(f("YO")) ``` [Answer] # C, ~~215~~ ~~208~~ 190 bytes -7 thanks to Cool Guy ``` #define z" an engineer" #define f(s)!strcmp(s,"OR")?"I am not"z:strstr("MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY",s)?"I am"z:"What is"z"?" ``` Used @totallyhuman's "genus string". How it works: * `"string"z` automatically concatenates `"string"` with `z` (`" an engineer"`). Yes, C does that. * `!strcmp(s,"OR")` compares the string against "OR". * `?"I am not"z` returns "I am not an engineer" if true. Otherwise... * `:strstr(...,s)` checks if @totallyhuman's genius string contains the provided string. * `?"I am"z` returns "I am an engineer" if so, and... * `:"What is"z"?")` returns "What is an engineer?" otherwise. [Try it online!](https://tio.run/##NY4xT8MwFIR3fsXxWJyqDKx0qKykUNPYQWloSCsGy6RthpgqDksQv928gUp3w73vSXfu/uRcjHef7bHzLSaC9Wj9iUM70M31fhQhuQ3j4PqLCHMqSkqWpGB7@K@RpkdGLEFamVTmEnqbVkabndw0qOUer7LEU45nCbNWGdJis82gV9AZm9@rd5gVzAtMA8OkWKNUEm8V6h1b5agbmof/Ui6k@mxHdIEmWlLsbeeFZe7OdpjNwuLn8j0GwasPDx9JsviNsSj/AA) [Answer] # [Python 2](https://docs.python.org/2/), ~~228~~ 168 bytes ``` lambda s:('What is%s?','I am'+' not'*(s=='OR')+'%s')[s in'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY']%' an engineer' ``` [Try it online!](https://tio.run/##DcpBT4MwHIbxs3yK90L@rTMePC4hpoHpcNAahkM2jamxkyZb11DI4qdHDr/T8/i/obu4h@mYfEwnff7@0QhLRk2nB9gQh0e6oxz6TAuCuwx0y0KSkKqILygOxA8B1lGZy1QUAuU2rWUpd2LTohF7vIoKTwWeBeQ6z5CqzTZDuUKZzea9fodcQb5AtpBzUWuoKhd4q9HsZnmBpqXPmKAdjPu1zpiepmtnTwZ1P5pldON76wZ2ZL2@flnnx4Hx@9F70zPO@SSKSFWRUv8 "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~192~~ ~~186~~ ~~182~~ ~~178~~ 176 bytes Could probably compress the state string more. ``` lambda s,e=' an engineer':'I am'+' not'*(s=='OR')+e if s in'MINCALAZ SCT FL GA WIAKSD ME MD MA MNMS MOKY MTNE NVTX NH NJ NY ND COHIDE OR PARIL UT VA WA WV WY'else'What is%s?'%e ``` [Try it online!](https://tio.run/##ZdJRa4MwFAXg9/6K81LSrnsqexrICGprqolFrdayF8fSVWhtqb7s17sibHgYSOAL8Z57o7fv7nRtlv3Ree/P1eXjs0L7bB2BqoFtvurG2rt4FQrVRSwEmmsnnmat44g4EfOFRX1Ei7oRWhlXRvKA1M2wirCWKJQMUw/ah36sEtroFDoOS@jM@DB5tocJYDYwJYwHNw6U5yNOsJWJirDLkD@qPJ4cRSnsubWiOFUd6nbavomp7W/3uulwnA3NTAZN/vZk9Ls3KCQdSMlYriTFpGwszx9rRXlrqhKosZRHoveUIVGVMCWVY0V0UlNnmvI0n6TONKVrytN0E5puwlCeyUkBaUPSJJrIuCSaIaaaMX3bLc2X0Hwp1UypZkazZ/uxdjRtzqK8gkU3UVAvRfn/n31Zinn/Aw "Python 2 – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 184 bytes ``` s->s.format(s.equals("OR")?"I am not%s":"MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY".contains(s)?"I am%s":"What is%s?"," an engineer") ``` [Try it online!](https://tio.run/##RZLfbqJAFMbvfYovk5hAojxAu7WZglaqMzRApXazF7MWXVwFlhmbNI3P7g4HqxfzA86f75szw1Z9qOH2/e@p2NdVY7C1397BFDtvfShXpqhKb3J@ue2tdkprCFWU@OoB9eH3rlhBG2Xs46Mq3rG3OScxTVFufv6CajbapVLgW@VHlx2ge46wxt1JD0faW1fNXhlHe/m/g9pph0Uxc@9ZCLVHWZm@ZjdMhNLncw6R@KkUcsFnS2T8Dc88xmSORw45DQP40SwJIMYQgV22PH2FHEM@QS4hbSaaIg45XlJkC7vCObIl81ZVaewA2tFnX/LM/iiDQvf1PRswqBJ5uSnKPG@Ye7ql2S4Dm1wbjbvzyADjczawnBHfiHFLnxMjYtoyGLecUP2jzX4rTMM2EgZEyoaSSAqzhLhsOaeIIB0RXBVEFycdQb2CugS5C3KX1CUXxCnx6aogBUXIRfpE2k9ElRFNF9Fcz@QVk1fiXxUSqk/JPX1t@UK@i47UlXWkPWSkYO/kosAp@/BAJ@YzCh@747c/zvmfowu46a7BvdxC8qlNvveqg/FqW2XWDgP6GsORZb@0im3DAGtP1fXu02m/XLfTPvbadTz9Bw "Java (JDK 10) – Try It Online") I apologize for reusing the compressed string: I couldn't find anything better by myself... :( [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~104~~ ~~103~~ 101 bytes ``` „€À€ˆ„I€Ü‚.•~Zµ∞/'—¶[@øl•Œ2ù.•9₆\|&׃Ω#àöF},cΓ páe;ð²∍₆jÌn#dÅ?DvĆ8A•2ôìuIå©è¹„ORQi'€–}„€¤©É)ðýª'?®_×J ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcO8R01rDjcAidNtQI4niDfnUcMsvUcNi@qiDm191DFPX/1Rw5RD26IdDu/IAYoenWR0eCdI2vJRU1tMjdrh6ccmnVupfHjB4W1utTrJ5yYrFBxemGp9eMOhTY86eoFqsg735CmnHG61dyk70mbhCNRpdHjL4TWlnoeXHlp5eMWhnUB7/YMCM9WBdj9qmFwLcdOhJUDJTs3DGw7vPbRK3f7QuvjD073@//cPAgA "05AB1E – Try It Online") Old 104 byte version in case that is more easily improved. ``` „€À€ˆ„I€Ü‚.•ÂkXñ…ΓVt€Ïè∍‡Λi„2¶’að=–½6™oÑþÁāõgO·ð~ λ†₃›;â&ÄFv¾‡1~ǝQa«;cS•u2ôIå©è¹„ORQi'€–}„€¤©É)ðýª'?®_×J ``` Not happy with the compression nor the special case for `?`. [Answer] # [R](https://www.r-project.org/), ~~109~~ 96 bytes ``` function(x)sub("#"," an engineer",c("I am not#","I am#","What is#?"))[2-x%in%state.abb+!x=="OR"] ``` [Try it online!](https://tio.run/##K/qfbvs/rTQvuSQzP0@jQrO4NElDSVlJR0khMU8hNS89My81tUhJJ1lDyVMhMVchL78EJAlig@jwjMQShcxiZXslTc1oI90K1cw81eKSxJJUvcSkJG3FCltbJf8gpdj/6RogWpMLSDt6Q2knJc3/AA "R – Try It Online") 13 bytes thanks to J.Doe - through use of regex and indexation. [Answer] # [F#](http://fsharp.org), 222 211 bytes ``` let f v=let(a,b)=if"OR"=v then("I am not",".")elif"WALAKSCARINMNVTNCTX NHIDE MOHIL COKY MSD PAZ WIA WVA FL GA MA MD ME MI MT NE ND NJ NY UT WY".Contains v then("I am",".")else("What is","?")in a+" an engineer"+b ``` [Try it online!](https://tio.run/##TY/haoNAEIT/5ymGhYKSVPIAteVQ21zjncHYWBvy4wJnchDPokegT28vgUKHhYX5BnanHR@73vbTdNEOLa6x34FaHMPYtFSUFF/hztoGxKE62N7RgiIK9cXjmuVsvU1YyaWQu0om1SfkiqcZRLHiOZJi3UBsU2zYF2rOUO8YXnO8MQg/KYRPcogKMoNMId8hG3xUqBuKkt46ZeyI/w/8HR91QPVZOZjRWy8UGgs1JygLbU/Gaj3Q/DjtnzLrhp9Nb6x7PsxuFTt1iw6nK@IZvL4Hz1oLehgJQXtH0X55CO90OU1F@Qs) Expanded: ``` let f v = let (a,b) = if "OR" = v then ("I am not",".") elif "WALAKSCARINMNVTNCTX NHIDE MOHIL COKY MSD PAZ WIA WVA FL GA MA MD ME MI MT NE ND NJ NY UT WY".Contains v then ("I am",".") else ("What is","?") a + " an engineer" + b ``` Given a two-letter state *v* passed to the function *f*, build a tuple *(a, b)* representing the head and tail of the "engineer" sentence. Feel free to use the "compressed state string" freely; it's one whole byte shorter than the MINCALA one... [Answer] # [CJam](https://sourceforge.net/p/cjam), 143 bytes ``` "ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY"q#g"I am not I am What is?"N/=)" an engineer"\ ``` [Try it online!](https://tio.run/##HYpBCsIwFAX3PcUjrlx5ApFPW21s8ytpbKy4CRJqhUbU3j8GF8MbeHN/ujlG0WpJUJJzatJ2uWHFPdUDLF1xIo19gwOBK1kgb@uugCqhikTKzQVcgo/gAZyetsLZwPYJ2cAO4r0ahYSbEV4Lsr9l9uEWTN@d4M12LeACfBin4P1H3GIk/QM "CJam – Try It Online") or as a [test suite](https://tio.run/##HZDNbsIwEITvPMXKVQ899Y5UVcYBYpJdo8TEhIKqqIoolUilwq3qs6c7OfizvTM7/vn46q7jmwmVIWNLoAAOAGrOAgGIimypWMG3hpB7hc8A1LwAEIoaaBUltow2ho@nLdoYZoaPEc@IF/ikAXJgAzCAKHEAUgLUgJtukVchr4ZaQ41IjnvFDqHNBPjSBMQndCSEWtQWCzzQmdPvu5mTOY76Id4Se3G21Ll2UVgaW7SU7IG2tqJVSWtLkvuMXCjqjHhJnOlQe9yTLEk2JC2JKiGnXaTU6PAl6bHHh7Px1F1p@L7TbFrN0md3p8vt1cjzy5OhbqB@OF@Gvv/R@5xuw9/j@A8) ### Explanation ``` "ORIA...." e# Push a string in which every state is a substring, but no non-state is e# a substring. q e# Read the input. # e# Find the index of the input in the string. (-1 if not found) g e# Signum of the index: -1 for negative, 0 for 0, 1 for positive. "I am.... " e# Push this string. Note the trailing space on the first two lines of it. N/ e# Split it on newlines. = e# Get the string at index given by the signum. ) e# Pull out the last character. " an engineer"\ e# Push " an engineer" and bring the other character to the TOS. e# Implicit output. ``` Since Oregon (`OR`) is at the start of the string, finding the signum of the index of the input in that will be -1 if not found, 0 if `OR`, 1 if any other state. Which string to print can be decided by that. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~136~~ ~~135~~ ~~131~~ ~~129~~ 128 bytes More savings may be available by experimenting with the order of the state abbreviations - I'll come back to that in a while. ``` `mnnmlãGLÏz¯¬ct¸flgaá[9¨kyµmçpCijmsmtnhnvnyn¬kpÂÉcsdk¡x©vavt°±wvwy`ò øUv)?"I am {¥"OR"?"not ":P}"+` à¨\ `:`Wt à¨\? ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=YG1ubm1sheNHTM96r6xjdLhmbGdhluFbOahrebVt53BDaWptc210mJpuaG52bnlurJdrjnDCyWNzZGuheKl2YXZ0sLF3dnd5YPIg+FV2KT8iSSBhbSB7pSJPUiI/Im5vdCAiOlB9IitghCDgCKhcIGA6YFeVdCCJIIQg4AioXD8=&input=Ik9SIg==) --- ## Explanation * We take a compressed string of the lowercased abbreviations, decompress it, and split it into an array of 2 character strings using the `ò` method. * We then use the `ø` method to see if the array contains `Uv`, which is the input string converted to lowercase. * If we so, we build our output string, beginning with `"I am "` * Checking if the input string `¥` (is equal to) `"OR"` allows us to append either `"not "` or the empty string variable `P`. * And then we decompress and append the compressed string `"an engineer"`. * If the input was not found in the array, then we output the decompression of compressed string `"What is an engineer?"`. [Answer] # [Python 3](https://docs.python.org/3/), ~~180~~ ~~179~~ 178 bytes ``` def f(s):e=" not"*(s=="OR")+" an engineer";return"I am"+e if s in"PALAKSCAZ CTNMINCOR FL GA MDE ME MND MA MSD MOKY NE NH NJ NY WA OHID UTX MTNVARIA WIL WVT WY"else"What is"+e+"?" ``` [Try it online!](https://tio.run/##FZHBbsIwEETP7VeM9pQUq5feqFBlJbQxxHaVhAS4IdUUSzSgJD306@kg@clez@54V77@TadL/3K7fYUjjsmYzsNC0F8meUrGxUJ8JelMcOgR@u/YhzDI6xCm36EXg8OPzALiESNiL5@61Os603tkjbPGZb7Ce4kPDZsvYblcDsuo5ubXO7glXAG3gtuh0/CFybFptrCNa3VlNDpTomsbdDsJ5zFIdzpMiCMfncmb3I6XAZEvQ3SpoNdkTyqFTBNPGoV8qdiGYh8KhVEwOWFsHOHduiY7hZJny1xL3d7PzLXMsdQtvSy9HHXXkoKsiCWsdRlhnee9Zx@ePXzSo6JHTa2m1tCr2SpOqNDeod7doV/HvI4@W@rVhjOQpZHn8XqOUyIKks4fH65D7KckKv5TTNPbPw "Python 3 – Try It Online") [Answer] # PHP, 188 Bytes ``` $e=" an engineer";echo strpos(_TNNMLAALAKAZARCACOCTDEFLGAHIIDILINIAKSKYMEMDMAMIMNMSMOMTNENVNHNJNYNCNDOHOKORPARISCSDTXUTVTVAWAWVWIWY,$argn)&1?"I am".($argn!="OR"?"":" not").$e:"What is$e?"; ``` [Try it online!](https://tio.run/##Hc5Ba4MwFADg@35F9pDRQins2k7kkdj6pnkZmpray5ARag@LQf3/bvT6nb44xPUji0N8SfrpHlKwVziuiU9B9EH4cH8E7yc4@p9hFPMyxXHefFtmXSFWWOINa4nSSKvyU3XGgkhRRUxYNmWnc600atKsG2205ZxbLviTO5asTGFKU39hTY1slL1ebGtbdOhaR67bPT/bt/cMSPS/sN884TUFU0MGcAARxgW2@8QfwA39Ih5z4rP//PoH "PHP – Try It Online") [Answer] ## C#, 178 bytes ``` s=>(s=="OR"?"I am notx":"MINCALA MSCTNMNVAKY WAZ PARIA FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY".Contains(s)?"I amx":"What isx?").Replace("x"," an engineer"); ``` [Run in C# Pad](http://csharppad.com/gist/2df8b77923d66e3f083078065bab4b6f) Golf based on [Mayube's solution](https://codegolf.stackexchange.com/a/124148/70241); new here, so I don't have enough rep to comment. [Answer] # [Haskell](https://www.haskell.org/), 220 214 210 209 bytes ``` s(a:b:c)=[a,b]:s(b:c) s _=[] a="I am " e="an engineer " i"OR"=a++"not "++e i x|x`elem`s"MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY"=a++e i _="What is "++e++"?" ``` [Try it online!](https://tio.run/##JZDNjoIwFIX3PsVJVxqYFzBhJg34g9JiAEV0jNYJGckIY6wLF/PuDBwX/ZLe@/Wethdjf8rrtW3t0IzP46@Rtzfu@TC2w34zsDh6@8PAeCKEqSEGpSdMg7L5rpqyvHeFSsSJ8IzjiOb3AeE45aDC8@95Kq9lfbJChdqXkYRK/UwrvZHLArncYSUTTCPMJPQ8DODHyzSAmkAF3er0bAs9gV5AF9BdJ54jCSXWGfJNt8IIecHcPu/oifxiHqgsb9Bd5kO0takaeKjNTR0x/LR4e8ftXjUPDK1bwY5G2AsZCRdCLskdmfT0JRmTWc9g0nNKf8buPOwZBiTroSbZXaZk0TNiRXGCoq9eFU5QPKXoKyYqJmr6ekPOyQWpSE7WPsmZMZ2Yb4n5ihVTEqakNFOaGROzbc81szYv0s9fZG7Os91XuyKKxKH9Bw "Haskell – Try It Online") [Answer] ## Javascript 204 ``` s=>{h=/^(A[LKZR]|C[AOT]|DE|FL|[GPLV]A|[HR]I|I[DLNA]|K[SY]|M[EDAINSOT]|N[EVHJMYCD]|O[HK]|S[CD]|T[NX]|[VU]T|W[AVIY]|(OR))$/.exec(s);return(!h?"What is ":"I am "+(h[2]?"not ":""))+"an engineer"+(!h?'?':'')} ``` [Answer] # AWK, 189 bytes ``` /A[LKZR]|C[AOT]|DE|FL|[GPV]A|HI|I[DLNA]|KS|KY|LA|M[EDAINSOT]|N[EVHJMYCD]|O[HKR]|RI|SC|SD|TN|TX|UT|VT|W[AVIY]/{print"I am "($0~OR?"not ":"")"an engineer";exit} {print"What is an engineer?"} ``` If input matches a regex containing all the state abbreviations, print "I am an engineer" with a 'not' inserted in the middle if the state is Oregon, then exit. If the input does not match the regex, it must not be a US state abbreviation. [Answer] # Python 3, 238 bytes ``` def f(x):s=x in('ALAKAZARCACOCTDEFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY'[i:i+2]for i in range(0,100,2));o=x=='OR';q=(1-o)*(1-s);return q*'What is'+(1-q)*('I am'+o*' not')+' an engineer'+q*'?' ``` ### Explanation No compression techniques used. ``` def f(x): # Check if State s = x in ('ALAK...WIWY'[i:i+2] for i in range(0, 100, 2)) # Check if Oregon o = x == 'OR' # Check if neither Oregon nor State q = (1-o) * (1-s) # Construct output string return q * 'What is' + \ (1-q) * ('I am' + o * ' not') + \ ' an engineer' + \ q * '?' ``` [Answer] # Java, 173 bytes ``` s->(!"MINCALARIA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY OR".contains(s)?"What is":"I am"+(s.equals("OR")?" not":""))+" an engineer" ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 100 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) This language postdates the challenge. But the author (me) didn't see it until now. ``` éë&W≈#W¬π█▐╜╣╟◙√a☻∞ZrπU♫ÿô♠▌⌠Që≡AûpI⌡ÄNA綵↑╝╣òøΩ.¬É]╩Æ↓d∩é¡2ŲeB┼¼▬5∟┤sW♠♂↑q▐WMï╝|Ñ↑╫+3¼↔îûvlLΩ∟┬oë ``` [Run and debug it](https://staxlang.xyz/#p=82892657f72357aae3dbdebdb9c70afb6102ec5a72e3550e989306ddf45189f041967049f58e4e418714e618bcb99500ea2eaa905dca921964ef82ad328ffd6542c5ac16351cb47357060b1871de574d8bbc7ca518d72b33ac1d8c96766c4cea1cc26f89&i=AL%0AOR%0AKA%0Aor%0Aal&a=1&m=2) [Answer] # JavaScript ES6, ~~175~~171 Bytes ``` x=>[`What is${e=" an engineer"}?`,`I am${x=="OR"?" not"+e:e}`][+!!'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY'.match(x)] ``` Joined lots of good # Or 152 bytes on ISO encoding Generator: ``` 'x=>[`What is${e=" an engineer"}?`,`I am${x=="OR"?" not"+e:e}`][+!!btoa`*`.match(x)]'.replace('*',atob('MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY '.replace(/ /g,'/'))) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 0+176 bytes ``` -Dz"=an engineer" -Df(s)*s-79|1[s]-82?strstr("MINCALA=MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY",s)?"I am"z:"What is"z"?":"I am not"z ``` [Try it online!](https://tio.run/##TY7BToQwGIRfZfKfWiMHvahrNqSB1a1AMSwugvHQEEASt5otXlBf3W41Mdlk5vDNzGHaYGhb59xOj4bxz/ePybKeUV4Q59f/VNXHlCfH1DS/9O1@2v5VD9YF8bwkaIPODKPpuj35qGeWL09scHH1dfZkn4PL89BOey9GmVSRSAWyTVSqTG1FUqMSDe5FgZsUtwJqLWNEebKJka2Qxd5@Xj5CraDuoGoo3@RrFFLgoUS19ZYp/OtTy0OS0DuaF1S96AmjpZlCWvylMG8TzQc "C (gcc) – Try It Online") pure translate [Answer] # Powershell, 175 bytes ``` (('I am'+' not'*!($i='ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY'.IndexOf($args))+($e=' an engineer')),"What is$e`?")[!++$i] ``` Test script: ``` $f = { $e=' an engineer' $i='ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY'.IndexOf($args) (('I am'+' not'*!$i+$e),"What is$e`?")[!++$i] # Important! OR is a first state in the modified @totallyhuman's genuis string } @( ,('OR', 'I am not an engineer') ,('AL', 'I am an engineer') ,('IL', 'I am an engineer') ,('ZZ', 'What is an engineer?') ) | % { $s,$e = $_ $r = &$f $s "$($r-eq$e): $r" } ``` Output: ``` True: I am not an engineer True: I am an engineer True: I am an engineer True: What is an engineer? ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~236~~ ~~182~~ 181 bytes ``` lambda s:'I am not'+e if s=='OR'else'I am'+e if s in'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY'else'What is%s?'%e e=' an engineer' ``` [Try it online!](https://tio.run/##NZBBb4JAEIXv/RXvYlZTb72ZkGYDKivsYgBBbHug6VJJFI1w6a@n@2h6mC@ZeW/eTvb@M5xv3cvYeO/jpb5@ftXoV0KhvqK7DeLZom3Qe55IUmEvvZ2k/zHaTmhlfBlL6MzPjTaFjCqU8oS9TLGJsZUwoQrgJ1EWQK@hA1fOnh9h1jA7mArGKUmIVEkccpSFKxWjrP5eLM/1gLaf9a9iZp@sJ1B3sN1321n7EGNze6B2l@BNSCmWPHQpZExExIngzKfqJ0TuEKwdNvRtKYTKQQUEZ8oQFKKMqBxitpprmj49tVzTNGv6NOM14w19piBCYkdoglHGJ5iSUE146Z55KfMyqhnVnMn50eHA0GICfeUExpfccH/1sXrC/dF2w7yZ14vF@As "Python 3 – Try It Online") TIO contains test cases for all the states. -54 bytes thanks to the string compression [Answer] # q/kdb+, 174 bytes **Solution:** ``` {a:" an engineer?";$[(#:)l:ss["ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY";x];-1_"I am",$[l~(),0;" not";""],a;"What is",a]} ``` **Explanation:** ``` { // save string into variable a a:" an engineer?"; // try to find the input x in the condensed string, save location in variable l, $ is a if/else $[(#:)l:ss["ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY";x]; // found a match, check if it was at index 0 ('OR') and inject " not" if so, drop the '?' off the end -1_"I am",$[l~(),0;" not";""],a; // otherwise return 'What is an engineer?' "What is",a] } ``` **Notes:** Used the 'compressed' string from other answers, struggling to find a way to bring it into a single line in order to avoid assignment of the `a` variable (yet still add the `?` when input is not a state. [Answer] # [Retina](https://github.com/m-ender/retina), 175 bytes ``` .. I am $&~MINCALAZ SCT FL GA WIAKSD ME MD MA MNMS MOKY MTNE NVTX NH NJ NY ND COHIDE PARIL UT VA WA WV WY (..)~.*\1.* ~ OR~.* not ~ I am ..~.* What is ~? ~ an engineer ``` [Try it online!](https://tio.run/##JU5BCsIwALv3FTmozB0KvkDKNre6tZWtbk482EPRHawwd@7Xa0UIIYQkZLbL5ExYJ@U9UEo4zAurjRdcZqxhV3SZxqFByTBwVnc5RAERmUFI0UGoeoTQsoDs9QWygjxCjpA5MlXxvMCJtbzBWaOPExE9hpEklG49TW87mhJPVBs1ce8F/n@A0p8xPM2C6QO/jxnjYN1jctbOIaiKKBFrXw "Retina – Try It Online") Hopefully I've appropriated the best state list. Explanation: ``` .. I am $&~MINCALAZ SCT FL GA WIAKSD ME MD MA MNMS MOKY MTNE NVTX NH NJ NY ND COHIDE PARIL UT VA WA WV WY ``` Start building up the result. Also, insert the state list for use by the next stage. ``` (..)~.*\1.* ~ ``` If it's one of the 49 states, delete the state and list. ``` OR~.* not ~ ``` If it's Oregon, replace the state with `not`, and delete the list. ``` I am ..~.* What is ~? ``` If it's anything else, replace everything with the other output. ``` ~ an engineer ``` Add these word in last to avoid repetition. [Answer] # Crystal, 232 207 205 Bytes ``` i="ORALAKAZARCACOCTDEFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKPARISCSDTNTXUTVTVAWAWVWIWY".split(/(..)/).index ARGV[0];p (i ?"I am ": "What is ")+(i==1 ?"not ": "")+"an engineer"+(i ?"": "?") ``` [Try it online](https://tio.run/##Hc1Bb4IwGMbxr9K8J4gZZtcZYt60KBX6doFKx24Na2YTrUY4uA@@M2Nen1@e/If7zzi58zyHHHSDNVb4iQ1HrrkRxa7eYymlkLUkiVVb9TWqQgmFSipSrdLKUEEdlXQgRT1xErrU1Ts2suWtMGQ@jqYzHVq0nZW2h2y8ncOUrJMsS9dpFuKXf7AlDZsbSwLbgmTuwuCNgT25iYWRQbpKQp6/Lhav05OWCVxkPn6H6P0dVs/nv2whneffeH0Z3HDyfw). (slightly modified due to an issue of ARGV) [Answer] # Factor, 135 bytes ``` USE: usa-cities [ " an engineer"swap [ "I am"swap string>state OR = [ " not"append ] when ""] [ 2drop "What is" "?"] recover surround ] ``` More readable, and named: ``` : engineer? ( state-name -- str ) [ " an engineer" ] dip ! put this below the input on the stack [ [ "I am" ] dip ! put this below the input too but above the other string>state OR = ! string>state throws on a non-state name [ " not" append ] when "" ! otherwise and if it is OR, append this ] [ 2drop "What is" "?" ] recover surround ; ! catch error, surround string ``` `[ x ] dip` and `x swap` are equivalent in stack effect but the first is shorter only when nested: `[ [ [ x ] dip ] dip ] dip`. [Answer] # Python 2, ~~213~~ ~~211~~ 194 Bytes ``` c="uTXnMSCORIDEwVAKYmTNHILfLAZpALmNEmOKSDwINCARmEwAnJnDmAmIAgAwYcTnVToHnYmD" r=(lambda x:x in c or x[0].lower()+x[1]in c)(i)^1 u="What is "*r+("I am "+"not "*(i=="OR"))*(r^1)+"an engineer"+"?"*r ``` [Try It Online](https://tio.run/##FYvdSsMwFIDv9xSHc5WsINZLIUhYC4urLXRlWscmsdYtsJyUmJL69LXefj/Db7g6epiN8Dp@GBrGwPjcCRybN3rZb6paZXk8yF1rm3Kriu9Cvg@ysGVuq90@i6rcyNrmUdIzZVZaJS8ytl1Dh8ZtqbUZrrxgN20/vzRMjxMYgg6ch@l4f7q7udh7xpPpmJ7@BWeGn9PVKPD1qgOYH8C1Txgq0BYwQXJhIcwIgVWNnK@ZP6c8QU3Q08VQ3/ulelqmefCGAoxzVf8B) **Stuff i'm working on shortening:** * `(i=="OR")` * `or x[0].lower()+x[1]in c` **Update:** * Saved 2 Bytes by replacing `s=not r` with `s=r^1` * Separated header and footer of code [Answer] # Ruby, 164 bytes ``` ->s{r="What is an engineer?" j=379 "##(*Q0'7q;N>%*$o(.F%#&'#&#5##%$%+%5%)5r@#P,B353*/%".bytes{|i|s==(j+=i-34).to_s(36).upcase&&r="I am not"[0,i==41?8:4]+r[7,12]} r} ``` Uses a run length encoding, therefore magic string is 50 bytes long, one per state. In order to build this, it was first necessary to put the state codes in alphabetical order of state code, rather than state name. Unfortunately 7 bytes are needed to convert the base36 representation of `j` from a lowercase statecode into an uppercase statecode. **Ungolfed in test program** ``` f=->s{ #s is the input string. r="What is an engineer?" #Set r to "What is an engineer?" j=379 #Set j to one less than 380, which in base36 becomes AK, the first statecode alphabetically "##(*Q0'7q;N>%*$o(.F%#&'#&#5##%$%+%5%)5r@#P,B353*/%". #Iterate through the run length encoded string bytes{|i| #(each character represents how far in base 36 each state code is from the previous one) s==(j+=i-34).to_s(36).upcase&& #take the ascii value of the character and subtract 34 (example #=35-34=1) and add to j. Convert j to base36 to get a state code. r="I am not"[0,i==41?8:4]+r[7,12] #if the state code matches s, modify r. Take the first 4 characters of "I am not" (first 8 in the case of OR where i==41) } #and add r[7,12]==" an engineer" (12 characters of the existing value of r, starting at character 7 r} #return r %w{AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY XX}.map{|i|p [i,f[i]]} ``` ]
[Question] [ In the spirit of [re-implementing classic video games](https://codegolf.stackexchange.com/q/10713/4098), I would like to invite the community to create their best implementation of [Tetris](http://en.wikipedia.org/wiki/Tetris). ![enter image description here](https://i.stack.imgur.com/yU0eR.png) *For reference, a screenshot of the official NES version of Tetris.* ## Required Features * A reasonable scoring system must be in place, which rewards multi-line clears more than single-line clears. The current score must be visible at all times. * The next piece that will appear must be indicated in some manner. * The distribution of the seven tetrominoes should be fairly even (i.e. pseudo-randomly chosen). * The user must have the ability to rotate the current piece in both directions, as well as accelerate its descent. * When the game has ended, it should be clearly indicated that the game is over. * The source code must be structured and easily understandable. ## Optional Features * Advancing falling speed after a certain number of clears (i.e. increasing difficulty level), and advancing score per line clear, proportional to speed. * Gravity. You may choose to implement the 'classic' gravity, in which blocks can remain floating over gaps, or you may choose to implement 'flood fill' gravity, in which blocks which have been separated from their original tetromino via line clears may fall into open gaps. * High scores with name input. * Animation after line clears, and/or after obtaining a new high score. ## Limitations * Any libraries used ([jQuery](http://jquery.com/), [PyGame](http://www.pygame.org/), etc.) should be freely available. * Source code size must not exceed 4096 bytes, excluding whitespace and comments. Any external resources (data files, images, etc.) will be added to the code length, excluding any files which are generated, such as for high scores. *I realize that this is a rather arbitrary restriction; my primary goal is to discourage copy-pasting of existing implementations, and to encourage brevity and self-containment.* ## Winning Criteria This challenge will be judged as a **popularity contest**, meaning that the submission with the most upvotes will be selected as the winner. When upvoting, I encourage users to upvote any and all submissions which they feel adequately meet the above stated requirements. The winner will be chosen no sooner than 2 weeks after the first valid solution. Additionally, I will be granting a bounty to the winner, roughly proportional to the number of upvotes this question receives (`10 * #votes` rounded upwards to the nearest 50). Should there be a tie after the 2 week period has expired, the competition period will be extended by one week. Should there still be a tie, I reserve the right to place the final vote. Please ask for any clarifications. May the best implementation win! [Answer] ## Try: <http://tetris.muehe.org> ***Update*** There's a global high score. Enjoy beating it or - alternatively - hacking it :-) ![Screenshot: Tetris in action](https://i.stack.imgur.com/wfziG.png) CoffeeScript and HTML version, should fulfill the requirements to the best of my knowledge (and I have never really played Tetris). ``` $ make stats 4095 ``` Github <https://github.com/henrik-muehe/tetris> ## Features * Exponential scoring * Next piece indicator * Fair randomness * Rotation, move and drop down * Game over indication * **Highscore** with server backend that should not be *that* easily fakeable. [Answer] # Pascal Developed in FreePascal 2.6.2, should compile with Turbo Pascal 6.0 too. Only the [Crt](http://freepascal.org/docs-html/rtl/crt/) unit is used, no external resources. ``` program tetris; uses Crt; const width = 10; { playing field width } height = 20; { playing field height } const piece: array [1..7, 1..3, 0..1] of ShortInt = ( { piece shapes : piece, element, coordinate } (( 1, 0), ( 1, 1), ( 0, 1)), { O } ((-1, 0), ( 1, 0), ( 2, 0)), { I } (( 0, 1), ( 1, 0), ( 2, 0)), { L } (( 0, 1), (-1, 0), (-2, 0)), { J } ((-1, 0), ( 1, 0), ( 0, 1)), { T } (( 1, 0), ( 0, 1), (-1, 1)), { S } ((-1, 0), ( 0, 1), ( 1, 1)) { Z } ); color: array [1..7, 0..1] of Byte = ( { piece colors : foreground, background } (Yellow, Brown), { O } (LightCyan, Cyan), { I } (LightBlue, Blue), { L } (White, LightGray), { J } (LightMagenta, Magenta), { T } (LightGreen, Green), { S } (LightRed, Red) { Z } ); var area: array [1..width + 2, 1..height + 1] of Byte; { playing field } coord: array [0..3, 0..1] of Byte; { precalculated element coordinates } played, { played pieces count } removed, { completed lines count } level, { current level } score: LongInt; { accumulated score } time, { current level delay } wait, { current piece delay } made, { completed lines in current level } multi, { multiline count } screen, { original screen size } i, j, j2: Word; { counters } current, { current piece } next, { next piece } x, { horizontal coordinate } y, { vertical coordinate } position, { rotation position } k: Byte; { pressed key } ok: Boolean; { aggregated condition } { precalculates the give piece's elements coordinates } procedure coordinate(current, x, y, position: Byte); begin coord[0, 0] := x; coord[0, 1] := y; for i := 1 to 3 do begin coord[i, 0] := x + piece[current, i, position mod 2] * (Ord(position in [0, 1]) * 2 - 1); coord[i, 1] := y + piece[current, i, 1 - position mod 2] * (Ord(position in [0, 3]) * 2 - 1); end; end; { draws a piece } procedure draw(current, x, y, position: Byte; visible: Boolean); begin coordinate(current, x, y, position); for i := 0 to 3 do begin GotoXY(coord[i, 0] * 2 + 1, coord[i, 1]); if visible then begin TextColor(color[current, 0]); TextBackground(color[current, 1]); Write('[]'); end else begin TextBackground(Black); Write(' '); end; end; end; { check whether a piece can be placed in given position } function check(x2, y2, position2: Byte): Boolean; begin coordinate(current, x2, y2, position2); ok := True; for i := 0 to 3 do if area[coord[i, 0], coord[i, 1]] <> 0 then ok := False; if ok then begin x := x2; y := y2; position := position2; end; check := ok; end; begin Randomize; TextColor(LightGray); TextBackground(Black); ClrScr; screen := WindMax; for i := 0 to width + 1 do for j := 1 to height + 1 do area[i, j] := 9 * Ord(not ((i in [1..width]) and (j in [1..height]))); Window(1, 1, width * 2 + 4, height + 2); for i := 1 to (width + 2) * (height + 1) do Write('##'); Window(3, 1, width * 2 + 2, height); ClrScr; Window(1, 1, Lo(screen), Hi(screen)); Window(width * 2 + 7, 1, width * 2 + 25, 10); Writeln('Next'); Writeln; Writeln; Writeln('Piece'); Writeln('Line'); Writeln('Level'); Writeln('Score'); Window(1, 1, Lo(screen), Hi(screen)); played := 0; removed := 0; level := 1; score := 0; current := 9; next := 9; made := 0; repeat if current = 9 then begin if next = 9 then next := Random(7) + 1 else draw(next, width + 9, 1, 0, False); current := next; next := Random(7) + 1; x := width div 2; y := 1; position := 0; time := 1100 - level * 100; wait := time; Inc(played); Inc(score); if made = 25 then begin Inc(level); made := 0; end; draw(next, width + 9, 1, 0, True); Window(width * 2 + 15, 4, width * 2 + 25, 10); TextColor(LightGray); TextBackground(Black); Writeln(played:5); Writeln(removed:5); Writeln(level:5); Writeln(score:5); Window(1, 1, Lo(screen), Hi(screen)); if not check(x, y, position) then begin GotoXY(width * 2 + 7, 10); Write('Game Over'); Break; end; end; draw(current, x, y, position, True); GotoXY(1, 1); repeat Delay(1); Dec(wait); until KeyPressed or (wait = 0); draw(current, x, y, position, False); if KeyPressed then begin k := Ord(ReadKey); case k of 75, 77: check(x + Ord(k = 77) * 2 - 1, y, position); 72, 80: check(x, y, (position + Ord(k = 80) * 2 + 1) mod 4); 32: begin time := 1; Inc(score); end; end; end; if wait = 0 then begin if not check(x, y + 1, position) then begin draw(current, x, y, position, True); for i := 0 to 3 do area[coord[i, 0], coord[i, 1]] := current; multi := 0; for j := 1 to height do begin ok := True; for i := 1 to width do if area[i, j] = 0 then ok := False; if ok then begin for j2 := j downto 2 do for i := 1 to width do area[i, j2] := area[i, j2 - 1]; for i := 1 to width do area[i, 1] := 0; Inc(score, 10 + multi * 2); Inc(removed); Inc(multi); Window(3, 1, width * 2 + 2, height); TextBackground(Black); GotoXY(1, j); DelLine; GotoXY(1, 1); InsLine; Window(1, 1, Lo(screen), Hi(screen)); end; end; if multi <> 0 then Inc(made); current := 9; end; wait := time; end; until k = 27; ReadKey; TextColor(LightGray); TextBackground(Black); ClrScr; end. ``` ### Screenshot ![Tetris in Pascal](https://i.stack.imgur.com/Ygptz.png) (On Linux, in XTerm window.) ### Control * `Left` – move left * `Right` – move right * `Up` – rotate counterclockwise * `Down` – rotate clockwise * `Space` – drop down * `Esc` – exit ### Scoring * played piece – 1 point * dropped piece – 1 point * completed line – 10 point * multiple lines – multiplier \* 2 point Level starts at 1 and increases after each 25 line completing. (Multiple lines completed at once count as 1.) ### Measurement ``` bash-4.2$ sed ' s/{[^{}]*}//g # remove comments s/^ *\| *$//g # trim leading and trailing spaces /^$/d # remove empty lines s/ *\([:=<>,;+*-]\+\) */\1/g # no space around operators ' tetris.pas | wc -c 3697 ``` [Answer] ## Java (Swing) This is an implementation of the first historical [Game Boy edition](http://en.wikipedia.org/wiki/Tetris_%28Game_Boy%29) from **Nintendo(c)** from 1989. ![Game Boy Tetris Nintendo](https://i.stack.imgur.com/6ilAZ.png) How to play: `Z` = rotate left `X` = rotate right `Left` = move left `Right` = move right `Down` = move down (slowly) `Up` = rotate left (just for easier use) `R` = reset game I avoided to use more than one class (because the golf aspect comes to my mind). But now it's not golfable anymore in any case... However, I zipped and Base64-encoded one Font-File and one Image-File, so I can use it in the one and only class file. To run it, copy the Java code into your IDE and start. You don't need any additional libraries or resources. ``` import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.zip.ZipInputStream; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import javax.xml.bind.DatatypeConverter; public class JTetris extends javax.swing.JFrame { static Image IMAGE; static Font FONT; static { ZipInputStream zipImage = new ZipInputStream(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary( "UEsDBBQAAAAIABmiWkRZ0oOouwAAAJYKAAAFAAAAYy5ibXBz8p3GxQAGZUCsAcQ3gFgCiBkZWMDiCkB5GBCA0iJyLAwl+3oYYpJsGK58u8NAKjBGAgyUgVG7QHYxKUGBAjDiBJUUQUhQAMQGA3xsFL3MMBMNRrpdEABhQxQLCiDYmHZBxCF2QdhAu8CyEHLk2cWkBJSH" + "xxcoCgyg5hsbAgWhbBgJUg9Wg24XWDGQHJF2QeOCUruQwEi0S0kRe5qHKCY2zQsgkv0ItAsIKC97EQnecGTYRQUwKNsbNAYAUEsBAj8AFAAAAAgAGaJaRFnSg6i7AAAAlgoAAAUAJAAAAAAAAAAgAAAAAAAAAGMuYm1wCgAgAAAAAAABABgAkJCiSyczzwGQkKJLJzPP" + "AZCQoksnM88BUEsFBgAAAAABAAEAVwAAAN4AAAAAAA==" ))); ZipInputStream zipFont = new ZipInputStream(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary( "UEsDBBQAAAAIAEq5UEN0MGyWoggAAHgrAAAFAAAAYS50dGbklsvvC1EUx78zU+/3OxHiEuLd1jMlxKNR70cQCxumY9oOnU5Np6osdIGEDYmwZGElkYh/gI2FBUIsvFdILNgh8Rxft4d6RyxEYvq7PZ97es73nHNv8mthAOiJFiyotRtS0xMnum4Gej0HsNXx7erbI6+7" + "ks8CxqNiuVk48qTbVKB3BIy8XXLtbVv6x0cBkwuzS3SYrffvuL8MYGzJj3av3BfP4P4p8yeUA8cGxqWBSau4n+Lbu6tYET8AEoMBqIrtuzuPz33D/Uyg28VqUItgxtTrvRGAAoW4LK7BsHTnb5HAE9qB6E+PidGYhCTmYjP24AxuxTGYR98UpLEIdtsXP4zvxXfjO/HN" + "+Gp8Kg6p9O8//8ucRns93ZK6vqXfvBccXLuv7b/QH2LjVtyyYLUAdIfJaMmz6Gc83w3yd9OuSLS0WmcxRLj1xYJY/Gz9Wcyfr79XJ6aO3MEKTEAPWsDE988Y4yQM4RGAsEEeIWyiGzLCFsZjgXACY1EQ7oJeOCzclZnHhbthHs4Ld8cQPBPugT6GKdwT841+wr0wzFgl" + "3BtpwxHugxHGMeG+mGycEx6EicbdNhusYFqwYCQ4LTJmL2GDnBU20dfcK2xhjXlIOIFl5i3hLhhqjRLuiow1S7gbdlu+cHdMsh4L98DwRD/hntiTmCjcC8nEaeHe2Jq4IdwHmS7ThPtiUxdPeBDWd7nYZgPo33VANqg2Q69YitQ6Owo9Z4daZdd3uGp6etqMDfWqG6rV" + "dugF9Fa2qQlL+T9XLQ6aE9V6t1gv22EuqEQborDuROoX0b/87JPUJjeseUFFTUumdfhUHT71Y/hUHT71Y/jULyp6NWWrKLS3ub4d7lBBQeU2LFc6oBRU1fJK5IYVO6KoXVZL/fyyUhRV56ZSBUbUtETSCfyv5h5+6fWveh1+6ZVq2DWVr3vlSDW8qKQ6/fQU+UajkdQl" + "2MTHAj+s+sWW/dVSDG6kMpnMjGlzsqHLpne5Khv4Pj9TiyJ2mK9/DBQtR0KcdkQyCIupsue4lZpbS+WbqRnJdCr3USLvFdXOuu3s8CpFtcetlpphTW0P2Lzf5CS7Vd7dli0uWbStXIqQRYAqmgjhoYgSIiisg41Iexzs4H4V93WSS56ONKZhBjbQU6UnpG81bB0dSGwF" + "20gTsJTs66zFCFhjImk990XmlnVODgGjI6qxHr0Orfoz7T/P+66rTVqjprMrUJw3ifQX6lM76mRRJ31WJ4s66cczetRXjFbaazPfha9VeeLMKPA9x5zltB2FEqlKz3K9Zy+0NomdaCpDsQcfeSzTdxkxei5SfBVEo9bpglM59Po/v281HJfw+k/PVWe/oqcBW0+bp47H" + "HiPt82hLpB+dT89vum/oV7IzhZyETPD7s/7wUzk/elKi3CBl9GsGb38Osox05aR36SmzWs2XPIVFiOQMOSVE8Zu+nG9UnK80krQhiowr65twtdfVXeXR5PsMxqRpc5+7yJOKtDtZ09a356GiPXvgsm6JeaHubzsCOXkfTbmT3VrB5Q1mmbMEi0hl3TNM86VxFF2QMOXL" + "XVsuNnEF8mtAHquDQG7DxvVYSOFbbbfVQovG0NwOVV/kFKj3g4eVJZ5/3dALAzGUIl8/MMTDAvEBAC9oe9Hu/WJ/kD9s78f3gfdvpKrPs6H/A+1VkJtADAMnWXFAqEIVqjhw6KEfzQvan/Ud/cQmJdnRjoyzBLUCFAxeZ8aOHSfgk3aU+Kp6oFqX7/mn2s5L6KF+JPoC" + "8QOVOqdFAqiOpICIqxbYo82LiTEcccIZF7zjgyiD14JJ9MrUfmsUWAlrx3nybJXJ/b6v1/yIene+vjHV+OQrxNUsQ5XCpSYvtZBCXZeWD85FbA8CGE3TXXlkQwTIJkI1cvQrGmlXFAOiWYslTyXZJ1XX5JWTeT8IXbEKNaBKky2OmVbG17et7AMet8D6Vlh1kZq8sgdj" + "RckB7b9Tnx3ELVCmouKUtBHriQZczDu8dlk1i5w+SwGrFYp5mvtc03aE9NdGqP2rSNu3slZt6Ea4zTmuQc/Zcu1q0XEqj52KR/J9YIIwfN4gZOREc/Xdi+O4W6/anb3a9dGGxBoe1NRf8szqSdveBHqRE8SK4PtAbHr2cXFqh9rORFwMcgVACL6qgdi+WY9mzbjJ1agC" + "A2Uh8jgnE1wOHu0lvY4L+RGIZCzMHsnS+bwfbljlmyIz/X2Cyaf8t0jUNzue7CR+ZC32wD0kgyL537VkJY/XUtXl4/f3DWJDnotxhmJ67IyMMD2if9qO9ovOCYvrzqWCIf5Z+I4H4iCiODiKdFob37e6M40fO8Cyqtp4cxjXh5iNz2KXn84f5pI65vQ5nKrUWbPJ+fy7" + "nMF/ARx6tzdmc0q43dv7n3IcnZlxcHefezcFAJt3de7FX/bLHQWAEAaiuPe/srhiMcEncWDZMkUKwe/oJM+R+Ip1IqfPB1WCakTEbi7q6Jyb9sZ5oAgoYThNGjp24i9uhItx5j6DbyffdZC4XuWaY4gwHjnb1m/m0cxzUENOUK/VVs+f/S1qh79xC6dP/B+YfgEZgCsT" + "XRT0T4OPuu6oXXK5r1OxdrBO2xkcikrZz/l3jjozreH9LYpVi1WLVYtVi1VfjbZVGUfbqqNt1dG26mhbFaBB21blBJIgO+HzavBZNXWgKUQCsK8w58oQKQJ19BhR5mHMyUHYuOfWEHOEmL7+B49bDP3Dc/4Q0DW9aSsURmEYfqGx97+Po31eu4MFYdglBEHw47qIMAiD" + "YEEQBAuCYF1AGIZBGIRBGARB0MvBA3N8MMccc3wAkN1Zu2umvfeihkba+ueezEstLSxnogE8JMpk9thQDqGsVIWO8JSq0Bmeo/bwEjTUCV57Mn/ragPvUZkO1iWV+8u5rvDRl/NnRyv4CoqawndQ1Bx+0FhL+G0q1xX+oi6QDOAftTWBStAQqh0VUKtBvaTdDVBLAQI/" + "ABQAAAAIAEq5UEN0MGyWoggAAHgrAAAFACQAAAAAAAAAIAAAAAAAAABhLnR0ZgoAIAAAAAAAAQAYAABukYC8ys4BJXTvDjUzzwEldO8ONTPPAVBLBQYAAAAAAQABAFcAAADFCAAAAAA=") )); try { zipImage.getNextEntry(); zipFont.getNextEntry(); IMAGE = ImageIO.read(zipImage); FONT = Font.createFont(0, zipFont); FONT = FONT.deriveFont(20.0f); } catch (Exception e) { System.exit(1); } } int[] speeds = {887,820,753,686,619,552,468,368,284,184,167,150,133,117,100,100,83,83,66,66,50}; int[] points = {40,100,300,1200}; int[][][] stones = { {{0,1},{1,1},{2,1},{0,2}}, // L 0 {{0,1},{1,1},{2,1},{3,1}}, // I 1 {{0,1},{1,1},{2,1},{2,2}}, // J 2 {{0,1},{1,1},{2,1},{1,2}}, // T 3 {{0,1},{1,1},{1,2},{2,2}}, // Z 4 {{1,1},{2,1},{0,2},{1,2}}, // S 5 {{1,1},{2,1},{1,2},{2,2}} // O 6 }; Color[] colors = { new Color(220, 246, 212), // light new Color(140, 190, 116), // green new Color(60, 98, 92), // blue new Color(4, 30, 20) // dark }; int FREE = 0; int BORDER = 8; int DELTA = 20; int WIDTH = 10; int HEIGHT = 20; int SIZE = 24; int[][] field = new int[WIDTH][HEIGHT]; int[][] stone; int deltaX; int deltaY; int curStone; int nextStone = new Random().nextInt(7); int score; int level; int lines; int steps; int speed = speeds[0]; Timer tickTimer = new Timer(); Image dbImage; Image staticImage; Graphics dbg; int anim = -1; boolean blink = false; ArrayList<Integer> removeLinesRows = new ArrayList<Integer>(); boolean keyDown = true; boolean freezeKeys = false; private JTetris() { setDefaultCloseOperation(2); setResizable(false); setSize(475, 480); addPropertyChangeListener("isDirty", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { repaint(); } }); reset(); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { super.windowClosed(e); tickTimer.cancel(); } }); addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { keyDown = true; } @Override public void keyPressed(KeyEvent e) { if (freezeKeys) { keyDown = false; return; } switch (e.getKeyCode()) { case 82: reset(); break; case 37: updateField(-1, 0, false); break; case 39: updateField(1, 0, false); break; case 40: if (keyDown) updateField(0, 1, true); break; case 38: case 90: rotate(false); break; case 88: rotate(true); } } }); setVisible(true); } private void startTickTimer() { if (tickTimer != null) { tickTimer.cancel(); } freezeKeys = false; tickTimer = new Timer(); tickTimer.schedule(new TimerTask() { public void run() { updateField(0, 1, false); } }, 0, speed); } private void startRemoveLineTimer() { if (!removeLinesRows.isEmpty()) { anim = 7; } if (tickTimer != null) { tickTimer.cancel(); } tickTimer = new Timer(); tickTimer.schedule(new TimerTask() { public void run() { if (anim > 0) { blink = !blink; firePropertyChange("isDirty", false, true); } if (anim-- < 0) { blink = false; tickTimer.cancel(); if (removeLinesRows.size() > 0) { int delta = 0; for (int row : removeLinesRows) { for (int r = row + delta++; r > 2; r--) { for (int c = 0; c < WIDTH; c++) { field[c][r] = field[c][r - 1]; } } } score += points[removeLinesRows.size() - 1] * (level + 1); lines += removeLinesRows.size(); level = lines / 10; speed = speeds[level > 20 ? 20 : level]; removeLinesRows.clear(); } createNextStone(); startTickTimer(); } } }, 50, 160); } public static void main(String[] a) { new JTetris(); } @Override public void paint(Graphics g) { if (dbImage == null) { dbImage = createImage(getWidth(), getHeight()); dbg = dbImage.getGraphics(); dbg.setFont(FONT); staticImage = createImage(getWidth(), getHeight()); Graphics sg = staticImage.getGraphics(); sg.setFont(FONT); sg.setColor(colors[3]); sg.fillRect(0, 0, getWidth(), getHeight()); sg.setColor(colors[0]); sg.fillRect(40 + WIDTH * SIZE + SIZE, 70, 170, 58); sg.setColor(colors[2]); sg.fillRect(40 + WIDTH * SIZE + SIZE, 73, 170, 52); sg.setColor(colors[0]); sg.fillRect(40 + WIDTH * SIZE + SIZE, 95, 170, 27); sg.setColor(colors[2]); sg.fillRect(40 + WIDTH * SIZE + SIZE, 98, 170, 3); sg.setColor(colors[1]); sg.fillRoundRect(40 + 13 * SIZE - 15, 40 + 13 * SIZE - 15, SIZE * 4 + 30, SIZE * 4 + 30, 20, 20); sg.setColor(colors[0]); sg.fillRoundRect(40 + 13 * SIZE - 12, 40 + 13 * SIZE - 12, SIZE * 4 + 24, SIZE * 4 + 24, 15, 15); sg.fillRoundRect(330 - 6, 60 - 6, 120 + 12, 25 + 12, 15, 15); sg.fillRoundRect(330 - 6, 155 - 6, 120 + 12, 60 + 12, 15, 15); sg.fillRoundRect(330 - 6, 235 - 6, 120 + 12, 60 + 12, 15, 15); sg.setColor(colors[2]); sg.fillRoundRect(40 + 13 * SIZE - 9, 40 + 13 * SIZE - 9, SIZE * 4 + 18, SIZE * 4 + 18, 15, 15); sg.fillRoundRect(330 - 3, 60 - 3, 120 + 6, 25 + 6, 15, 15); sg.fillRoundRect(330 - 3, 155 - 3, 120 + 6, 60 + 6, 15, 15); sg.fillRoundRect(330 - 3, 235 - 3, 120 + 6, 60 + 6, 15, 15); sg.setColor(colors[3]); sg.fillRoundRect(40 + 13 * SIZE - 6, 40 + 13 * SIZE - 6, SIZE * 4 + 12, SIZE * 4 + 12, 15, 15); sg.setColor(colors[0]); sg.fillRoundRect(330, 60, 120, 25, 5, 5); sg.fillRect(40 + WIDTH * SIZE + SIZE, 40, 3, (HEIGHT - 2) * SIZE); sg.fillRoundRect(40 + 13 * SIZE - 3, 40 + 13 * SIZE - 3, SIZE * 4 + 6, SIZE * 4 + 6, 5, 5); sg.fillRoundRect(330, 155, 120, 60, 15, 15); sg.fillRoundRect(330, 235, 120, 60, 15, 15); sg.setColor(colors[3]); sg.drawString("SCORE", 340, 80); sg.drawString("LEVEL", 340, 180); sg.drawString("LINES", 340, 260); for (int r = 0; r < (HEIGHT - 2) * 24 / 18; r++) { sg.drawImage(IMAGE, 16, 40 + r * 18, 16 + SIZE, 58 + r * 18, 8 * SIZE, 0, 9 * SIZE, 18, this); sg.drawImage(IMAGE, 40 + WIDTH * SIZE, 40 + r * 18, 40 + WIDTH * SIZE + SIZE, 58 + r * 18, 8 * SIZE, 0, 9 * SIZE, 18, this); } } dbg.drawImage(staticImage, 0, 0, this); dbg.setColor(colors[3]); dbg.drawString(String.format("%6s", score > 999999 ? 999999 : score), 320, 120); dbg.drawString(String.format("%4s", level > 20 ? 20 : level), 340, 205); dbg.drawString(String.format("%4s", lines > 9999 ? 9999 : lines), 340, 285); for (int x = 0; x < 4; x++) { drawField(dbg, stones[nextStone][x][0] + 13, stones[nextStone][x][1] + 13, nextStone + 1); } for (int r = 2; r < HEIGHT; r++) { for (int c = 0; c < WIDTH; c++) { drawField(dbg, c, r - 2, field[c][r]); } } if (blink) { if (anim == 0) { dbg.setColor(colors[0]); } else { dbg.setColor(colors[1]); } for (int row : removeLinesRows) { dbg.fillRect(40, 40 + (row - 2) * SIZE, SIZE * WIDTH, SIZE); } } g.drawImage(dbImage, 0, 0, this); } private void drawField(Graphics g, int x, int y, int idx) { if (idx > DELTA) { idx -= DELTA; } g.drawImage(IMAGE, 40 + x * SIZE, 40 + y * SIZE, SIZE + 40 + x * SIZE, SIZE + 40 + y * SIZE, idx * SIZE, 0, (idx + 1) * SIZE, SIZE, this); } private void createNextStone() { curStone = nextStone; stone = stones[curStone]; deltaX = (WIDTH + 1) / 2 - 2; deltaY = 1; if (!isMoveable(0, 0)) { tickTimer.cancel(); JOptionPane.showMessageDialog(this, "Game over! Press OK for a new game."); reset(); return; } updateField(0, 0, false); nextStone = new Random().nextInt(7); } private void reset() { score = 0; steps = 0; lines = 0; level = 0; speed = speeds[0]; for (int r = 0; r < HEIGHT; r++) { for (int c = 0; c < WIDTH; c++) { field[c][r] = FREE; } } createNextStone(); startTickTimer(); } private void updateField(int hor, int ver, boolean player) { if (isMoveable(hor, ver)) { if (player) { steps++; } for (int x = 0; x < 4; x++) { field[stone[x][0] + deltaX][stone[x][1] + deltaY] = FREE; } deltaX += hor; deltaY += ver; for (int x = 0; x < 4; x++) { field[stone[x][0] + deltaX][stone[x][1] + deltaY] = curStone + 1; } firePropertyChange("isDirty", false, true); } else if (ver == 1) { freezeKeys = true; fixStone(); removeLines(); } } private void removeLines() { outer: for (int r = HEIGHT - 1; r >= 0; r--) { for (int c = 0; c < WIDTH; c++) { if (field[c][r] == FREE) { continue outer; } } removeLinesRows.add(r); } startRemoveLineTimer(); } private void fixStone() { score += steps; steps = 0; for (int x = 0; x < 4; x++) { field[stone[x][0] + deltaX][stone[x][1] + deltaY] = curStone + 1 + DELTA; } } private boolean isMoveable(int hor, int ver) { for (int x = 0; x < 4; x++) { int c = stone[x][0] + deltaX + hor; int r = stone[x][1] + deltaY + ver; if (c < 0 || c >= WIDTH || r < 0 || r >= HEIGHT) { return false; } if (field[c][r] > DELTA) { return false; } } return true; } private void rotate(boolean r) { if (curStone == 6) { // O return; } synchronized (field) { int[][] o = new int[4][2]; for (int x = 0; x < 4; x++) { o[x] = new int[] { r ? 3 - stone[x][1] : stone[x][1], r ? stone[x][0] : 3 - stone[x][0] }; } if (canRotate(o)) { for (int x = 0; x < 4; x++) { field[stone[x][0] + deltaX][stone[x][1] + deltaY] = FREE; } stone = o; for (int x = 0; x < 4; x++) { field[stone[x][0] + deltaX][stone[x][1] + deltaY] = curStone + 1; } firePropertyChange("isDirty", false, true); } } } private boolean canRotate(int[][] o) { for (int x = 0; x < 4; x++) { if (o[x][0] + deltaX < 0 || o[x][0] + deltaX >= WIDTH || o[x][1] + deltaY >= HEIGHT || field[o[x][0] + deltaX][o[x][1] + deltaY] > DELTA) { return false; } } return true; } } ``` **TODOs:** * *faster stones on higher level* **(done!)** * *original remove line animation* **(done!)** * *correct points for lines* **(done!)** * *interrupt moving down on new stone* **(done!)** * highscore screen * original rotation behavior * menu for choosing level * game-over screen * audio Comments are welcome :) [Answer] # Lua - 2876 Tetris in a terminal, works on most unix systems, pure lua, no additional libs needed. Controls are: wasd or hjkl, w/k to drop, s/j to rotate, ad/hl to move Speed increases with score, whenever multiple lines are removed, you get the square of amount of destroyed lines This is not the most possibly golfed solution, but i decided to golf it a little anyway. The newlines are just to fit text in 80 cols, i didn't include them in character count. ``` math.randomseed(os.time())if arg[1]then local function s(e)local e=io.popen( "sleep "..e)e:read"*a"return e:close()end local l={{0,1,1,0,1,1},{-1,1,-1,0,1,0} ,{-1,0,1,0,1,1},{-1,0,0,1,1,0},{-1,1,0,1,1,0},{-1,0,0,1,1,1},{-1,0,1,0,2,0}} function T(t,e,o)if o>1 then return T(-e,t,o-1)end return t,e end local t function fit(i,n,r,o)if n<1 or n>10 or r<1 or t[r][n]~=0 then return end for e=1 ,6,2 do local e,o=T(l[i][e],l[i][e+1],o)e,o=e+n,o+r if e<1 or e>10 or o<1 or((t[ o]or{})[e]or 0)~=0 then return end end return i end function put(e,r,i,n)t[i][r] =e for o=1,6,2 do local n,o=T(l[e][o],l[e][o+1],n)n,o=n+r,o+i;(t[o]or{})[n]=e end end while 1 do os.execute"clear"io.write("\27[0;37m+----------++----+\r\n".. ("| || |\r\n"):rep(2).. "| |+----+\r\n| |Score:\r\n"..("| |\r\n"):rep(16).. "+----------+\27[20F\27[C")t={}for e=1,20 do t[e]={}for o=1,10 do t[e][o]=0 end end local e,o,f,r,a,c,n=20,5,0,math.random(7),math.random(7),0,1 while 1 do f=f+ 1 s(.1)local d=io.open(arg[1],"rb")or os.exit(0,io.write"\27[49;39m",io.stdout: flush(),os.execute"clear")local i=d:read(1)while i do if i=="a"or i=="h"then if fit(r,o-1,e,n)then o=o-1 end elseif i=="d"or i=="l"then if fit(r,o+1,e,n)then o= o+1 end elseif i=="w"or i=="k"then while fit(r,o,e-1,n)do e=e-1 end elseif i== "s"or i=="j"then if fit(r,o,e,n+1)then n=n%4+1 end end i=d:read(1)end d:close()d =io.open(arg[1],"w")d:write()d:close()if f%(math.max(1,10-math.floor(c/20)))==0 then if fit(r,o,e-1,n)then e=e-1 else put(r,o,e,n)r,e,o,a,n=a,20,5,math.random(7 ),1 if not fit(r,o,e,n)then break end local e=1 local o=0 while e<21 do local n= 1 for o=1,10 do n=n*t[e][o]end if n~=0 then table.remove(t,e)local e={}for o=1, 10 do e[o]=0 end table.insert(t,e)o=o+1 else e=e+1 end end c=c+o*o end end put(r ,o,e,n)for e=20,1,-1 do for o=1,10 do io.write("\27[3"..t[e][o].."m"..(t[e][o] ==0 and" "or"#"))end io.write"\27[E\27[C"end io.write("\27[20F\27[13C\27[3",a, "m")for e=1,0,-1 do for n=-1,2 do local o for t=1,6,2 do if l[a][t]==n and l[a][ t+1]==e then io.write"#"o=e end end if e==0 and n==0 then io.write"#"o=e end if not o then io.write" "end end io.write"\27[4D\27[B"end io.write( "\27[2B\27[D\27[49;37m",c,"\27[4F\27[C")t[e][o]=0 for i=1,6,2 do local r,n=T(l[r ][i],l[r][i+1],n)r,n=r+o,n+e;(t[n]or{})[r]=0 end end io.write"\27[49;39m"io. stdout:flush()os.execute"clear"io.write "\aGame over. Will automatically start new game in 5 seconds. Use ^C to exit"s(5 )io.stdout:flush()end else local e=os.tmpname()local o=io.open(e,"w")local n= newproxy(true)getmetatable(n).__gc=function()os.execute"stty -raw echo"end os. execute"stty raw -echo"local t=""i=0 while arg[i]do t=arg[i].." "..t i=i-1 end os.execute(t..e.." &")while 1 do o:close()local t=io.read(1)o=io.open(e,"a")o: write(t)if t=="\3"then o:close()os.remove(e)os.execute"stty -raw echo" getmetatable(n).__gc=nil os.execute"sleep 0.1"os.exit()end end end ``` ![tetris in a terminal](https://i.stack.imgur.com/RwD4Z.png) [Answer] # Mathematica This code was written in Mathematica by Xiangdong Wen and can actually be played in a web browser here: [**Shape Descender**](http://demonstrations.wolfram.com/ShapeDescender/) (click on graphics to initiate arrows keys). Below are the screen shot and full code - which is pretty shor for a complete web app of this game. [![enter image description here](https://i.stack.imgur.com/fCytZ.jpg)](http://demonstrations.wolfram.com/ShapeDescender/) # Code ``` allBlocks = {{{{1, 0, 0, 0}, {1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 1, 1, 0}, {0, 1, 0, 0}, {0, 1, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {1, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}}, {{0, 1, 0, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}, {0, 0, 0, 0}}}, {{{0, 2, 0, 0}, {2, 2, 2, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 2, 0, 0}, {0, 2, 2, 0}, {0, 2, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {2, 2, 2, 0}, {0, 2, 0, 0}, {0, 0, 0, 0}}, {{0, 2, 0, 0}, {2, 2, 0, 0}, {0, 2, 0, 0}, {0, 0, 0, 0}}}, {{{0, 0, 3, 0}, {3, 3, 3, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 3, 0, 0}, {0, 3, 0, 0}, {0, 3, 3, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {3, 3, 3, 0}, {3, 0, 0, 0}, {0, 0, 0, 0}}, {{3, 3, 0, 0}, {0, 3, 0, 0}, {0, 3, 0, 0}, {0, 0, 0, 0}}}, {{{0, 0, 0, 0}, {0, 4, 4, 0}, {0, 4, 4, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {0, 4, 4, 0}, {0, 4, 4, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {0, 4, 4, 0}, {0, 4, 4, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {0, 4, 4, 0}, {0, 4, 4, 0}, {0, 0, 0, 0}}}, {{{0, 0, 0, 0}, {5, 5, 5, 5}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 5, 0}, {0, 0, 5, 0}, {0, 0, 5, 0}, {0, 0, 5, 0}}, {{0, 0, 0, 0}, {5, 5, 5, 5}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 5, 0}, {0, 0, 5, 0}, {0, 0, 5, 0}, {0, 0, 5, 0}}}, {{{6, 6, 0, 0}, {0, 6, 6, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 6, 0}, {0, 6, 6, 0}, {0, 6, 0, 0}, {0, 0, 0, 0}}, {{6, 6, 0, 0}, {0, 6, 6, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 6, 0}, {0, 6, 6, 0}, {0, 6, 0, 0}, {0, 0, 0, 0}}}, {{{0, 7, 7, 0}, {7, 7, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 7, 0, 0}, {0, 7, 7, 0}, {0, 0, 7, 0}, {0, 0, 0, 0}}, {{0, 7, 7, 0}, {7, 7, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 7, 0, 0}, {0, 7, 7, 0}, {0, 0, 7, 0}, {0, 0, 0, 0}}}}; smallBoard = Table[If[i == 1 || j == 1 || i == 6 || j == 6, 9, 0], {i, 1, 6}, {j, 1, 6}]; color[v_] := Switch[v, 0, Black, 1, Yellow, 2, Blue, 3, Magenta, 4, Cyan, 5, Red, 6, Orange, 7, Green, 9, Gray, _, Gray]; showSquare[{i_, j_}, v_] := {color[v], Rectangle[{i + 0.05, j + 0.05}, {i + 0.95, j + 0.95}]}; showHintBlock[n_, p_, x_, y_] := Table[showSquare[{i + x, j + y}, allBlocks[[n, p, i, j]]], {i, 1, 4}, {j, 1, 4}]; initBoard[ Hold[board_, num_]] := {board = Table[If[i <= 3 || j <= 3 || i >= 14 || j >= 24, 9, 0], {i, 1, 16}, {j, 1, 28}], Table[board[[i, 24]] = 0; board[[i, 25]] = 0; board[[i, 26]] = 0, {i, 7, 10}]; Table[board[[i, 25]] = 0, {i, 1, 16}]; board[[6, 25]] = 9, board[[11, 25]] = 9, Table[If[Mod[j + i, 2] == 0, board[[j, i + 3]] = 9], {i, 1, num}, {j, 4, 13}]}; bMoveTo[n_, p_, x_, y_, Hold[board_]] := Total[Table[ allBlocks[[n, p, i, j]]* board[[i + x, j + y]], {i, 1, 4}, {j, 1, 4}], 2] == 0; bGameOver[n_, p_, Hold[board_]] := Not[bMoveTo[n, p, 6, 22, Hold[board]]]; bLeft[n_, p_, x_, y_, Hold[board_]] := bMoveTo[n, p, x - 1, y, Hold[board]]; bRight[n_, p_, x_, y_, Hold[board_]] := bMoveTo[n, p, x + 1, y, Hold[board]]; bDown[n_, p_, x_, y_, Hold[board_]] := bMoveTo[n, p, x, y - 1, Hold[board]]; bRotateAnticlock[n_, p_, x_, y_, Hold[board_]] := Module[{tp}, tp = p - 1; If[tp == 0, tp = 4]; bMoveTo[n, tp, x, y, Hold[board]]]; bRotateClockwise[n_, p_, x_, y_, Hold[board_]] := Module[{tp}, tp = p + 1; If[tp == 5, tp = 1]; bMoveTo[n, tp, x, y, Hold[board]]]; showBoard[Hold[board_]] := Table[showSquare[{i, j}, board[[i, j]]], {i, 3, 14}, {j, 3, 25}]; showDropBlock[n_, p_, x_, y_] := Table[If[allBlocks[[n, p, i, j]] != 0, showSquare[{i + x, j + y}, allBlocks[[n, p, i, j]]], Black], {i, 1, 4}, {j, 1, 4}]; updateBoard[n_, p_, x_, y_, Hold[board_, score_]] := {Table[ board[[i + x, j + y]] += allBlocks[[n, p, i, j]], {i, 1, 4}, {j, 1, 4}]; score += 10 + 100*(2^ Sum[updateLine[i, Hold[board]], {i, y + 4, y + 1, -1}] - 1)}; updateLine[line_, Hold[board_]] := If[line <= 23 && line >= 4 && (Apply[And, Table[board[[i, line]] != 0, {i, 4, 13}]]) == True, Table[board[[i, j]] = board[[i, j + 1]], {i, 4, 13}, {j, line, 22}]; Table[board[[i, 23]] = 0, {i, 4, 13}]; 1, 0]; newGame[Hold[n_, p_, x_, y_, board_, nextItem_, gameOver_, pause_, num_]] := {initBoard[ Hold[board, num]]; {n, p, x, y} = {nextItem, 2, 6, 22}; nextItem = RandomInteger[6] + 1; gameOver = False; pause = False}; newBlock[Hold[n_, p_, x_, y_, board_, score_, gameOver_, nextItem_, pause_]] := {If[! pause && ! gameOver, updateBoard[n, p, x, y, Hold[board, score]]; gameOver = bGameOver[nextItem, 2, Hold[board]]; If[gameOver == False, {n, p, x, y} = {nextItem, 2, 6, 22}; nextItem = RandomInteger[6] + 1]]}; shapeDescend[Hold[level_, state_, num_]] := DynamicModule[{score = 0, gameOver = False, pause = False, board = Table[ If[i <= 3 || j <= 3 || i >= 14 || j >= 24, 0, 0], {i, 1, 16}, {j, 1, 28}], n, p, x, y, nextItem}, SeedRandom[level*10 + num]; nextItem = RandomInteger[6] + 1; newGame[Hold[n, p, x, y, board, nextItem, gameOver, pause, num]]; EventHandler[ Graphics[{Text[Style["Level", Blue, Italic, 24], {18, 12}], Text[Style["Score", Blue, Italic, 24], {18, 9}], Table[showSquare[{i + 16, j + 13}, smallBoard[[i, j]]], {i, 1, 6}, {j, 1, 6}], Dynamic[Refresh[ Switch[state, 1, newGame[Hold[n, p, x, y, board, nextItem, gameOver, pause, num]]; state = 3, 2, pause = True, 3, pause = False], UpdateInterval -> Infinity, TrackedSymbols -> {state}]; Refresh[If[! pause && ! gameOver && bDown[n, p, x, y, Hold[board]], y--, newBlock[ Hold[n, p, x, y, board, score, gameOver, nextItem, pause]]], UpdateInterval -> 3./level, TrackedSymbols -> {}]; Join[{{Text[ Style[ToString[level], Green, Italic, 24], {20, 11}], Text[Style[ToString[score], Green, Italic, 24], {20, 8}]}}, showBoard[Hold[board]], showDropBlock[n, p, x, y], showHintBlock[nextItem, 2, 17, 14]], TrackedSymbols -> {x, y, n, p, level}]}, Background -> Black, ImageSize -> {400, 400}], {"LeftArrowKeyDown" :> If[! pause && ! gameOver && bLeft[n, p, x, y, Hold[board]], x--], "RightArrowKeyDown" :> If[! pause && ! gameOver && bRight[n, p, x, y, Hold[board]], x++], "DownArrowKeyDown" :> (If[! pause && ! gameOver && bRotateClockwise[n, p, x, y, Hold[board]], p++; If[p == 5, p = 1]]), "UpArrowKeyDown" :> (If[! pause && ! gameOver && bRotateAnticlock[n, p, x, y, Hold[board]], p--; If[p == 0, p = 4]]), {"KeyDown", " "} :> If[! pause && ! gameOver && bDown[n, p, x, y, Hold[board]], y--, newBlock[ Hold[n, p, x, y, board, score, gameOver, nextItem, pause]]], "EscapeKeyDown" :> {newGame[ Hold[n, p, x, y, board, nextItem, gameOver, pause, num]]}}]]; Manipulate[ shapeDescend[Hold[level, state, initLine]], {{level, 5}, 1, 9, 1}, {{initLine, 3, "height of bottom level"}, 0, 9, 1}, {{state, 3, ""}, {1 -> "new game", 2 -> "pause", 3 -> "continue"}}, ContentSize -> {480, 450}, SynchronousUpdating -> False, SaveDefinitions -> True, Alignment -> Center, TrackedSymbols -> {}] ``` [Answer] ## C I wrote this yeaaaaars ago while sitting bored in class in high school. Supposedly, the original programmer wrote the first version of Tetris using square brackets as blocks, and it seemed simple enough to try and recreate, no? I didn't know any GUI stuff, so I made a good, old-fashioned console program. This was back before I learned C++ and those pesky proper programming practices, so the code may be a bit messy. I pretty much just winged it. ![TKlone](https://i.stack.imgur.com/Xfa87.png) It meets all of the requirements of the challenge, except the piece only rotates in one direction (clockwise). Use WASD to play, W rotates the piece. The full source code and exe can be found here: <http://sourceforge.net/projects/tklone/files/tklone/tklone-v1.0/> ## tetris.c ``` #include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> #include "defines.h" int array[FIELD_H][FIELD_W]; //field array int pieceCoords[2]; //current piece coordinates int x, y; //looping variables int thisPiece, nextPiece; //current pieces double score; //the players current score int newpiece=1; //the newpiece flag int init_h=1; /*starting coordinates of piece*/ int init_w=4; /*these are obsolete variables*/ int h_offset, w_offset; //piece position offsets from start int rtTop, rtBot, rtLeft, rtRight; //rotation thresholds for collision int b1h, b1w, b2h, b2w, b3h, b3w; //block draw offsets int rotation; /*0=normal view 1=90 degrees clockwise 2=upside-down 3=270 degrees clockwise */ clock_t speed; //time before piece falls (in milliseconds) clock_t gravity; //temp variable for speed //clock_t fps; int piececount; //number of pieces that have fallen int oldpiececount; int level; void GameInit(void); int GameStart(void); int GameMain(void); void newPiece(void); void scrollbar(void); //scrolling marquee bar void drawField(void); //graphics rendering function void setPiece(int piece); //this sets the individual piece offsets void drawPiece(void); //this sets the blocks in the array void initArray(void); //this initializes the array void getMoves(char move); //input function void rotate(int coll); //loops from 1 to 4 int collisionCheck(int side); //checks to see if piece will collide int loseGame(void); //checks to see if game has ended void eraseLastMove(void); //clears the array of the last move void setLastMove(void); //sets the piece in place for the next piece void lineClear(void); //clears filled lines and tabulates the score void predict(int undo); //predicts the next piece rotation for collision //void delay(int duration); int main() { restart: GameInit(); //some test blocks /*for(x=FIELD_H;x>3;x--) //quick lose pattern array[x][4]=1;*/ nextPiece=rand()%7; //generate a piece to use drawField(); //draw a blank field. should be a title screen printf(" / Welcome to TETRIS! \\"); //29 spaces and title getch(); //wait to start the game while(1) //main game loop { if(newpiece==1) //check to see if a new piece is required newPiece(); //if(gravity<=clock()) gravity=speed+clock(); //get the end time while(gravity>clock()) //count to the end time { if(kbhit()) { getMoves(getch()); //get input if(newpiece==1) //if piece reaches bottom... break; //...skip by redraw to save some cycles else { eraseLastMove(); //clear the last move from the array drawPiece(); //set the piece in the array drawField(); //refresh the screen scrollbar(); //draw the scrollbar } } } if(newpiece==0) /*minor speed optimization*/ getMoves('s'); //force piece down a line eraseLastMove(); //clear the last move from the array drawPiece(); //set the piece in the array drawField(); //refresh the screen scrollbar(); //draw the scrollbar } return 0; } void GameInit() { srand((unsigned)time(NULL)); //seed the random number genreator... initArray(); //...and initialize the array //reset some variables score=0; piececount=-1; //set to -1 because of newpiece loop on start oldpiececount=0; speed=1000; //starting speed of piece level=1; } void newPiece() { piececount++; //another piece has fallen setLastMove(); //set the last move in place lineClear(); //clear any full lines newpiece=0; //reset the newpiece flag rotation=0; //reset the piece rotation h_offset=0; //reset the... w_offset=0; //...piece coordinates gravity=0; //reset the gravity if(piececount-oldpiececount==10) //if 10 more pieces have fallen if(speed!=200) //200 is the lowest speed it can go { oldpiececount=piececount; //set current number of fallen pieces speed-=100; //make the speed faster level++; //increment the level counter } thisPiece=nextPiece;//get the current piece nextPiece=rand()%7; //pick the next piece setPiece(thisPiece);//get piece data if(loseGame()) //did player lose the game? { drawField(); //refresh the screen printf("You lose! Final score: %.0f. Press any key to begin a new game.",score); getch(); newpiece=1; //reset the newpiece flag /*add more initialization here*/ //goto restart; //return to start of the program exit(0); //quit the game for now } drawPiece(); //set the piece in the array drawField(); //refresh the screen scrollbar(); //draw the scrollbar } void scrollbar() { //printf("================================================================================"); printf("Score: %.0f\t\t ",score); //print the score (6 spaces) if(nextPiece==5||nextPiece==6) //print a space if the piece name is short printf(" "); printf("Next piece: "); if(nextPiece==0) //print the name of the next piece printf("straight"); else if(nextPiece==1) printf("t-shaped"); else if(nextPiece==2) printf("s-shaped"); else if(nextPiece==3) printf("z-shaped"); else if(nextPiece==4) printf("l-shaped"); else if(nextPiece==5) printf("back-l"); else if(nextPiece==6) printf("square"); printf("\t\t\tLevel %i",level); //print the level } void drawField() { system("cls"); //clear the screen for(x=0;x<FIELD_H;x++) { printf(" |"); //thirty spaces for(y=0;y<FIELD_W;y++) if(array[x][y]==1||array[x][y]==2) printf("[]"); else printf(" "); printf("| "); //thirty spaces } //bottom message bar //scrollbar(); } void drawPiece() { /* This sets the initial location of the piece with movement offset. Coordinates are based on the center of the piece. */ pieceCoords[0]=init_h+h_offset; //set height position pieceCoords[1]=init_w+w_offset; //set width position //mark the coordinates to draw the piece array[(pieceCoords[0])][(pieceCoords[1])]=2; //center piece array[(pieceCoords[0]+b1h)][(pieceCoords[1]+b1w)]=2; //other... array[(pieceCoords[0]+b2h)][(pieceCoords[1]+b2w)]=2; //...three... array[(pieceCoords[0]+b3h)][(pieceCoords[1]+b3w)]=2; //...pieces } void initArray() { for(x=0;x<FIELD_H;x++) for(y=0;y<FIELD_W;y++) array[x][y]=0; //array equals: 0 for empty // 1 for full // 2 for moving piece } void getMoves(char move) { switch(move) { case 'a': case 'A': if(collisionCheck(1)==0) //if the piece doesnt hit something... w_offset--; //...move the piece break; case 'd': case 'D': if(collisionCheck(2)==0) w_offset++; break; case 'w': case 'W': if(collisionCheck(0)==0) { rotate(0); //rotate the piece and... setPiece(thisPiece); //...get new piece data } break; case 's': case 'S': if(collisionCheck(3)==0) h_offset++; else //if the piece hits the bottom... newpiece=1; //...set the newpiece flag break; default: break; } } void rotate(int coll) { if(coll==0) //rotate clockwise { if(rotation==3) rotation=0; else rotation++; } if(coll==1) //rotate counterclockwise { if(rotation==0) rotation=3; else rotation--; } } int collisionCheck(int side) { if(side==0) //check rotation collision { predict(0); /* For the first part, we check to see if the rotation will collide with the sides. */ for(x=0;x<rtTop;x++) //check top side collision { if(pieceCoords[0]-x==0) //if piece minus top offset hits the top { predict(1); return 1; //collision detected! } } for(x=0;x<rtLeft;x++) //check left side collision { if(pieceCoords[1]-x==0) { predict(1); return 1; } } for(x=0;x<rtRight;x++) //check right side collision { if(pieceCoords[1]+x==(FIELD_W-1)) { predict(1); return 1; } } for(x=0;x<rtBot;x++) //check bottom side collision { if(pieceCoords[0]+x==(FIELD_H-1)) { predict(1); return 1; } } /* Then we check to see if any of the blocks will hit other blocks on the field. */ if(array[(pieceCoords[0]+b1h)][(pieceCoords[1]+b1w)]==1 ||array[(pieceCoords[0]+b2h)][(pieceCoords[1]+b2w)]==1 ||array[(pieceCoords[0]+b3h)][(pieceCoords[1]+b3w)]==1) { predict(1); return 1; } predict(1); return 0; } /* Here, we scan the array and check to see whether any of the blocks in the current piece are adjacent to the field sides or another block. */ for(x=0;x<FIELD_H;x++) //scan the array for(y=0;y<FIELD_W;y++) if(array[x][y]==2) //if array location contains a block { if(side==1) //check left side { if(y==0||array[x][y-1]==1) //if piece is next to border or block... return 1; //collision detected! } else if(side==2) //check right side { if(y==FIELD_W-1||array[x][y+1]==1) return 1; } else if(side==3) //check bottom { if(x==FIELD_H-1||array[x+1][y]==1) return 1; } } return 0; } int loseGame() /*need to modify the conditions of losing*/ { if(array[init_h][init_w]==1 ||array[(init_h+b1h)][(init_w+b1w)]==1 ||array[(init_h+b2h)][(init_w+b2w)]==1 ||array[(init_h+b3h)][(init_w+b3w)]==1) return 1; else return 0; } void eraseLastMove() /*need to optimize this*/ { for(x=0;x<FIELD_H;x++) //scan the array for(y=0;y<FIELD_W;y++) if(array[x][y]==2) //if the spot is filled... array[x][y]=0; //...clear the block } void setLastMove() /*also need to optimize this*/ { for(x=0;x<FIELD_H;x++) //scan the array for(y=0;y<FIELD_W;y++) if(array[x][y]==2) //if the spot is filled... array[x][y]=1; //...set the block } void lineClear() { int x2, y2; //new looping variables int empty; //is the row empty? int lines=0;//number of lines cleared for(x=0;x<FIELD_H;x++) //scan the rows { empty=0; //reset the empty flag on each row for(y=0;y<FIELD_W;y++) //scan the blocks in each row if(array[x][y]==0) //if the row isn't full... { empty=1; //...set the empty flag and... break; //...scan the next row } if(!empty) { for(y=0;y<FIELD_W;y++) //rescan the filled row... array[x][y]=0; //...and clear the blocks for(x2=x-1;x2>=0;x2--) //scan rows from the bottom up starting above cleared row for(y2=0;y2<FIELD_W;y2++) //scan each block in the row if(array[x2][y2]==1) { array[x2][y2]=0; //clear the block array[x2+1][y2]=1; //fill in the block below it } lines++; //a line has been cleared } } //tabulate the scores if(lines==1) score+=10; else if(lines==2) score+=25; else if(lines==3) score+=50; else if(lines==4) /* TETRIS! */ score+=100; } void predict(int undo) { if(undo==0) { rotate(0); //get next rotation... setPiece(thisPiece); //...and next piece data } if(undo==1) { rotate(1); //un-rotate setPiece(thisPiece); //reset the piece } } /*void delay(int duration) { clock_t done; done = duration + clock(); while(done>clock()) ; //sit and wait }*/ ``` ## setPiece.c ``` #include "defines.h" extern int rtTop, rtBot, rtLeft, rtRight; //rotation thresholds for collision extern int b1h, b1w, b2h, b2w, b3h, b3w; //block draw offsets extern int rotation; /*0=normal view 1=90 degrees clockwise 2=upside-down 3=270 degrees clockwise */ void setPiece(int piece) { if(piece==0) { switch(rotation) { case 0: //piece looks identical rotated upside-down case 2: /* The rotation thresholds dictate how far away the piece needs to be from the field edge for the next rotation. */ rtTop=1; rtBot=2; rtLeft=0; rtRight=0; /* These are the coordinates of the blocks relative to the center block. */ b1h=-1; b1w=0; b2h=1; b2w=0; b3h=2; b3w=0; break; case 1: //piece looks identical side to side case 3: rtTop=0; rtBot=0; rtLeft=1; rtRight=2; b1h=0; b1w=-1; b2h=0; b2w=1; b3h=0; b3w=2; break; } } //draw blue straight piece //snip other pieces else if(piece==6) { switch(rotation) { case 0: //a cube looks identical when rotated 90 degrees case 1: case 2: case 3: rtTop=0; //piece doesn't rotate so no thresholds needed rtBot=0; rtLeft=0; rtRight=0; b1h=-1; b1w=0; b2h=-1; b2w=1; b3h=0; b3w=1; break; } } //draw square piece } ``` [Answer] I built a javascript version <https://marchingband.github.io/tetris/> [![enter image description here](https://i.stack.imgur.com/XQGyQ.png)](https://i.stack.imgur.com/XQGyQ.png) ``` <!DOCTYPE html> <html> <body> <p>q and w rotate</p> <p id='score'>0</p> <div id='board' style='position:absolute;top:80px' ></div> </body> </html> <script> var pieceIndex=0 nextPiece=()=>{ pieceIndex=pieceIndex<pieces.length-1?pieceIndex+1:0 return pieces[pieceIndex] } const pieces=[ [ {x:0,y:-1}, {x:0,y:0}, {x:1,y:0}, {x:-1,y:0}, ], [ {x:0,y:-2}, {x:0,y:-1}, {x:0,y:0}, {x:0,y:1}, ], [ {x:1,y:0}, {x:0,y:0}, {x:2,y:0}, {x:0,y:-1}, ], [ {x:0,y:0}, {x:1,y:0}, {x:1,y:1}, {x:0,y:1} ], [ {x:0,y:0}, {x:-1,y:0}, {x:0,y:1}, {x:1,y:1} ], ] const speeds =[1000,800,600,400,300,250,200,150,100,90,80,70,60,50,40,30,20] const boardWidth = 10 const boardHeight = 20 const pixelSize = 10 const pixelBorder = 0 const boardBorder = 5 var score = 0 var level = 0 var fallingBits = [] const b = document.getElementById('board') piece = { position:{ x:boardWidth/2, y:1, }, bits:[ {x:0,y:-1}, {x:0,y:0}, {x:1,y:0}, {x:-1,y:0}, ], reset(){ piece.position={x:boardWidth/2,y:1} piece.bits=nextPiece() !piece.coordinates().every((b)=>dom[b.x][b.y]?dom[b.x][b.y].style.background=='red':true) && endGame() }, coordinates(){ return piece.bits.map((b)=>{ return {x:b.x+piece.position.x,y:b.y+piece.position.y} }) } } const dom = [] for(var x=0;x<boardWidth;x++){ var row = [] for(var y=0;y<boardHeight;y++){ var cell = document.createElement('div') cell.style.cssText='outline:thin solid;height:'+pixelSize+'px;width:'+pixelSize+'px;background:red;position:absolute' cell.style.left= (x*(pixelSize+pixelBorder)+boardBorder) + 'px' cell.style.top = (y*(pixelSize+pixelBorder)+boardBorder) + 'px' row.push(cell) b.appendChild(cell) } dom.push(row) } renderPiece=(color)=>{ piece.coordinates().forEach((b)=>dom[b.x][b.y] && (dom[b.x][b.y].style.background=color)) } drop=()=>{ piece.coordinates().every((p)=>p.y+1<boardHeight) && piece.coordinates().every((p)=>dom[p.x][p.y+1].style.background!='blue') ? movePiece(0,1) : freeze() } strafe=(d)=>{ piece.coordinates().every((p)=>p.x+d<boardWidth && p.x+d >=0) && piece.coordinates().every((p)=>dom[p.x+d][p.y].style.background!='blue') ? movePiece(d,0) : null } freeze=()=>{ piece.coordinates().forEach((p)=>dom[p.x][p.y].style.background='blue') lookForRows() piece.reset() } lookForRows=()=>{ [...dom[0].keys()].filter((i)=>dom.every((c)=>c[i].style.background=='blue')).forEach((r)=>{ removeLine(r) compressAbove(r) addPoint() }) } compressAbove=(r)=>{ // dom.reduce((acc,col,x)=>{return acc.concat(col.map((b,y)=>{return {x:x,y:y}}).filter((b,y)=>y<r && dom[b.x][b.y].style.background=='blue'))},[]).forEach((b)=>dom[b.x][b.y].style.background='red').forEach((b)=>dom[b.x][b.y+1].style.background='blue') var bits = [] dom.forEach((x,i)=>{ x.forEach((y,j)=>{ if(j<=r && dom[i][j].style.background=='blue'){bits.push({x:i,y:j})} }) }) bits.forEach((b)=>{ dom[b.x][b.y].style.background='red' }) bits.forEach((b)=>{ dom[b.x][b.y+1].style.background='blue' }) } removeLine=(r)=>{ dom.forEach((x)=>x[r].style.background='red') } changePiece=(x,y)=>{ piece.position.x += x piece.position.y += y } movePiece=(x,y)=>{ renderPiece('red') changePiece(x,y) renderPiece('yellow') } turn=(d)=>{ var newBits = [] for(let i=0;i<piece.bits.length;i++){ var x = piece.bits[i].x var y = piece.bits[i].y var bit={} if(d==1){ bit.x=-y bit.y=x }else{ bit.x=y bit.y=-x } newBits.push(bit) } if(newBits.every((p)=>p.x+piece.position.x<boardWidth && p.x+piece.position.x>=0 && p.y+piece.position.y<boardHeight && dom[p.x+piece.position.x][p.y+piece.position.y].style.background!='blue')){ renderPiece('red') piece.bits=newBits renderPiece('yellow') } } addPoint=()=>{ score++ document.getElementById('score').innerText=score score-level*10 > 10 && levelUp() } levelUp=()=>{ clearInterval(timer) level++ timer = window.setInterval(drop,speeds[level]) } endGame=()=>{ clearInterval(timer) dom.forEach((row)=>{ row.forEach((bit)=>{ bit.style.background=='red' && (bit.style.background='black') }) }) } document.onkeydown = function(e) { switch (e.keyCode) { case 37:strafe(-1);break case 87:turn(1);break case 81:turn(-1);break case 39:strafe(1);break case 40:drop();break } }; var timer = window.setInterval(drop,1000) </script> </html> ``` ]
[Question] [ # All Aboard the ASCII Train! ``` o O O ___ ___ ___ ___ ___ ___ ___ ___ ___ o | C | | O | | D | | E | | | | G | | O | | L | | F | TS__[O] |___| |___| |___| |___| |___| |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| ./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' ``` You best be prepared to ride the train, because you're about to build the train you'll be riding on. Given a string `s`, output a fully formed train as depicted above. The first thing output is always the engine that'll be tugging your string along, as depicted alone below: ``` o O O o TS__[O] {======| ./o--000' ``` Following the locomotive are rail-cars containing each character of your precious cargo. To save confusion when unloading, your company has tasked you with labeling the outside of these cars. The cars in question will always look like this: ``` ___ | # | |___| _|"""""| "`-0-0-' ``` Where the `#` is representative of the character that is inside the "cargo" hold. Chaining the engine to each car is also part of your job, as you've been tasked with overseeing the fluidity and success of this entire shipment. So, once you've labeled all the cars and got the engine on the tracks, you must ensure that the train is assembled and ready to roll. # Rules * The only input your program should take is a single string. * The engine must always be output, even if your shipment is empty. * Each car can only hold one character, don't push your luck you may damage the goods. * You need only support the following printable ASCII characters: `_-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz` If you end up doing more, that's fine too, but this is the bare minimum. * 1-2 trailing spaces are acceptable, as is a single trailing newline. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), shortest byte-count wins. [Answer] # JavaScript (ES6), ~~149~~ 144 bytes ``` s=>` o O Oa ___ o a | $& | TS__[O]a |___| {======|a_|"""""| ./o--000'a"\`-0-0-'`.replace(/a(.*)/g,(_,c)=>s.replace(/./g,c)) ``` I don't think the engine itself can be compressed, but perhaps it's possible. ### Test snippet ``` let f = s=>` o O Oa ___ o a | $& | TS__[O]a |___| {======|a_|"""""| ./o--000'a"\`-0-0-'`.replace(/a(.*)/g,(_,c)=>s.replace(/./g,c)) O.innerHTML = f("CODE GOLF") ``` ``` <input value="CODE GOLF" oninput="O.innerHTML=f(this.value.replace(/\n/g,'&lt;br&gt;'))"><br> <pre id=O></pre> ``` [Answer] # Befunge, ~~276~~ 270 bytes ``` p1p~:7>7+#:`#~_$:v >#p0p10:p00:+1g00_v#: v"!!```!!!"v>0p01g\-0g1+53p v"!}!#!}!!"v0 p115< v"!}```}!!"v^:-1< v"}#####}`">00g:| >"(.1.1.a#"^+<v1< v"P!P!p!!! "v5>g00p v"!!!!!p!!!"v6 v"^P\``TU!!"vp v"}>>>>>>|!"v+ >"(111..p0/"v6 v-1:g110">>"<g >:11p!#v_p011^ #-:#1_@>$$$$>,# ``` [Try it online!](http://befunge.tryitonline.net/#code=cDFwfjo3PjcrIzpgI35fJDp2Cj4jcDBwMTA6cDAwOisxZzAwX3YjOgp2IiEhYGBgISEhInY-MHAwMWdcLTBnMSs1M3AgIAp2IiF9ISMhfSEhInYwIHAxMTU8CnYiIX1gYGB9ISEidl46LTE8CnYifSMjIyMjfWAiPjAwZzp8Cj4iKC4xLjEuYSMiXis8djE8CnYiUCFQIXAhISEgInY1PmcwMHAKdiIhISEhIXAhISEidjYKdiJeUFxgYFRVISEidnAKdiJ9Pj4-Pj4-fCEidisKPiIoMTExLi5wMC8idjYKdi0xOmcxMTAiPj4iPGcKPjoxMXAhI3ZfcDAxMV4KIy06IzFfQD4kJCQkPiwj&input=Q09ERSBHT0xG) **Explanation** The car and engine are encoded as two sets of five strings on lines 3 to 12. The character values are off by 1 so as to avoid having to deal with the double quotes which can't be used in a Befunge string. The code works by building up the full set of characters needed to render the train on the stack. For each line of output, an appropriate car string is first added to the stack, repeated as many times as necessary for the cargo, and then one copy of the appropriate engine string. After each line has been constructed, a pair of the down arrows to left of the strings is replaced with a right arrow, so the next iteration of the loop follows a different path through the code, using a different pair of strings for the car and engine. Once all the data has been built up on the stack, there's a final rendering loop which writes out the characters, subtracting 1 each time to account for the initial encoding. ~~As a bonus, the source is designed in the shape of a [gun turret](http://vignette1.wikia.nocookie.net/battlefront/images/e/e9/Hoth_Defence_Turret.JPG), in case the train comes under attack.~~ Golfers destroyed my gun turret. [Answer] # PHP, ~~218 211 204 187~~ 183 bytes ``` o O O<?for(;$y<5;print"\n".[" o "," TS__[O]"," {======|","./o--000'"][+$y++])for($p=0;$c=a&$argn[$p++];)echo[" ___ "," | $c | "," |___| ",'_|"""""|',"\"`-0-0-'"][+$y]; ``` Takes input from STDIN; run with `-nR`. Compressing the engine or wagon would require more code to decompress than it saves on storage. I see no more potential here. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~101~~ 99 bytes Naive first attempt. ``` " o O O o"ð7×"TS__[O] {======|./o--000'"J5ä¹v… _ €ÐJy“ | ÿ | |___| _|"""""|"`-0-0-'“«5ä})øJ» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=IiAgICBvIE8gTyAgIG8iw7A3w5ciVFNfX1tPXSB7PT09PT09fC4vby0tMDAwJyJKNcOkwrl24oCmIF8g4oKsw5BKeeKAnCB8IMO_IHwgICB8X19ffCBffCIiIiIifCJgLTAtMC0n4oCcwqs1w6R9KcO4SsK7&input=MDVBQjFF) [Answer] ## Python 2, 176 bytes ``` lambda i:'\n'.join(map(''.join,zip(*[[" o O O"," o "," TS__[O]"," {======|","./o--000'"]]+[[" ___ ",' | '+x+' | '," |___| ",'_|"""""|',"\"`-0-0-'"]for x in i]))) ``` Example: ``` print f('Python') ``` gives ``` o O O ___ ___ ___ ___ ___ ___ o | P | | y | | t | | h | | o | | n | TS__[O] |___| |___| |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| ./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' ``` [Answer] ## Powershell, ~~167~~ 166 Bytes ``` $l=($a=$args[0]).Length;" o O O"+" ___ "*$l;" o "+($a[0..$l]|%{" | $_ |"});" TS__[O]"+" |___| "*$l;" {======|"+'_|"""""|'*$l;"./o--000'"+'"`-0-0-'''*$l ``` Example: ``` .\train.ps1 "PowerShell!" o O O ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ o | P | | o | | w | | e | | r | | S | | h | | e | | l | | l | | ! | TS__[O] |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| ./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' ``` Possibly Invalid! If run with no args at all it will try and print one empty string, and look like: ``` o O O o | | TS__[O] {======| ./o--000' ``` If run with an empty input string it will return correctly however: ``` .\train.ps1 "" o O O o TS__[O] {======| ./o--000' ``` (kinda) Ungolfed: ``` $l=($a=$args[0]).Length " o O O"+" ___ "*$l " o "+($a[0..$l]|%{" | $_ |"}) " TS__[O]"+" |___| "*$l " {======|"+'_|"""""|'*$l "./o--000'"+'"`-0-0-'''*$l ``` shortest compression in Powershell is going to be `+'c'*x` where c is the char and x is the number of repetitions, and that's only for trailing or leading repetitions, any center-string repetitions will require an extra `+` and an extra `"` - so there's no point in this where I can see compression saving any space, and the only repeated char set is `___` which is only 3 chars. Explanation: `$l=($a=$args[0]).Length` Take the first arg, put it into $a, then take the length of $a and put it into $l, these are the only variables you need. `" o O O"+" ___ "*$l` most of the other bits follow this format of the left-part and then the right part times the number of required chars. `" o "+([char[]]$a|%{" | $_ |"})` loop (`|%{}`) through $a as a char array, so `foreach (char $_ in $a)` for a non-pipeline version, then put the char into the text. this is an extremely simple approach, but because I can't find a good way to compress the strings past this it seems like the most useful. saved 1 Byte thanks to briantist! and here I was thinking this wouldn't get any shorter.. [Answer] # Java, 361 bytes ``` class C {static void main(String[]v){Scanner q = new Scanner(System.in);String i = q.nextLine();String[] t = {" o O O ", " o ", " TS__[O] ", " {======|", "./o--000'",};for (char c: i.toCharArray()) {t[0]+="___ ";t[1]+="| # | ".replace('#',c);t[2]+="|___| ";t[3]+="_|\"\"\"\"\"|";t[4]+="\"`-0-0-'";}for(String p:t) System.out.println(p);}} ``` ``` class C { static void main(String[]v) { Scanner q = new Scanner(System.in); String i = q.nextLine(); String[] t = { " o O O ", " o ", " TS__[O] ", " {======|", "./o--000'", }; for (char c: i.toCharArray()) { t[0]+="___ "; t[1]+="| # | ".replace('#',c); t[2]+="|___| "; t[3]+="_|\"\"\"\"\"|"; t[4]+="\"`-0-0-'"; } for(String p:t) System.out.println(p); } } ``` Example ``` java o O O ___ ___ ___ ___ o | j | | a | | v | | a | TS__[O] |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""| ./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' ``` [Answer] ## Perl, 137 bytes 132 bytes of code + 5 bytes for`-pF` flags. `ascii_train.pl`: ``` #!/usr/bin/perl -apF s/./ | $& | /g;$_=" o O O! ___ o $_ TS__[0]! |___| {======|!".'_|"""""|'." ./o--000'!\"`-0-0-'";s/!(.*)/$1x@F/ge ``` *Note that I added `-a` flag in the code, but it's only because old versions of Perl require `-a` when `-F` is used.* To run it: ``` echo -n "code-golf" | perl ascii_train.pl ``` The input must be supplied without a final newline (with `echo -n` for instance). **Explanations:** From what I've seen, it's roughly the same idea as ETHProduction's JavaScript answer. There isn't a lot going on: sadly the patterns are a bit to short to make `x` operator worth being used. First, `s/./ | $& | /g` surrounds each character of the input with `|` (and spaces) to form the second level of the train. Then inside that long string, everything between a `!` and a newline is a pattern we wish to repeat to construct the cars. That repetition is done thanks to the regex `s/!(.*)/$1x@F/ge`. (I used `!` because the input can't contain it). [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~57~~ 56 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Τ¡ā↓mΛC┌─⁵℮Ƨ⅛□→(š;∞⅟¹°⅔Ζ‽ζ÷⁴‘9n,{"s=Ο!NθæιžGš‼t╬¼Xg`‘8n┼ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwM0E0JUExJXUwMTAxJXUyMTkzbSV1MDM5QkMldTI1MEMldTI1MDAldTIwNzUldTIxMkUldTAxQTcldTIxNUIldTI1QTEldTIxOTIlMjgldTAxNjElM0IldTIyMUUldTIxNUYlQjklQjAldTIxNTQldTAzOTYldTIwM0QldTAzQjYlRjcldTIwNzQldTIwMTg5biUyQyU3QiUyMnMlM0QldTAzOUYlMjFOJXUwM0I4JUU2JXUwM0I5JXUwMTdFRyV1MDE2MSV1MjAzQ3QldTI1NkMlQkNYZyU2MCV1MjAxODhuJXUyNTND,inputs=Q09ERSUyMEdPTEY_) Explanation: ``` ..‘ push a compressed string of the locomotive in a single line 9n split in line lengths of 9 ,{ for each character in the input "..‘ push a compressed string of a wagon in a single line 8n split to line lengths of 8 ┼ add horizontally ``` [Answer] # C#, 277 Bytes Golfed: ``` string T(string s){var o=new string[]{" o O O"," o "," TS__[O]"," {======|","./ o--000'" };for(int i=0;i<s.Length;i++){o[0]+=" ___ ";o[1]+="| # | ".Replace("#",s[i]+"");o[2]+=" |___| ";o[3]+="_|\"\"\"\"\"|";o[4]+="\"`-0-0-'";}return string.Join("\r\n",o); ``` Ungolfed: ``` public string T(string s) { var o = new string[] { " o O O", " o ", " TS__[O]", " {======|", "./ o--000'" }; for (int i = 0; i < s.Length; i++) { o[0] += " ___ "; o[1] += "| # | ".Replace("#", s[i] + ""); o[2] += " |___| "; o[3] += "_|\"\"\"\"\"|"; o[4] += "\"`-0-0-'"; } return string.Join("\r\n", o); } ``` Testing: ``` Console.Write(new AllAboardTheASCIITrain().T("")); o O O o TS__[O] {======| ./ o--000' ``` And... ``` Console.Write(new AllAboardTheASCIITrain().T("Programming Puzzles & Code Golf")); o O O ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ o | P | | r | | o | | g | | r | | a | | m | | m | | i | | n | | g | | | | P | | u | | z | | z | | l | | e | | s | | | | & | | | | C | | o | | d | | e | | | | G | | o | | l | | f | TS__[O] |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| ./ o--000'"`-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-' ``` [Answer] ## C# 221 bytes nothing special happening here.. just creating each line and join them with new lines. ``` s=>{var t=new[]{" o O O"," o "," TS__[O]"," {======|","./o--000'"};foreach(var c in s){t[0]+=" ___ ";t[1]+=$" | {c} | ";t[2]+=" |___| ";t[3]+="_|\"\"\"\"\"|";t[4]+="\"`-0-0-'";}return string.Join("\n",t);}; ``` [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 178 bytes ``` [[" o O O o TS__[O] {======|./o--000'"|_nwise(9)]]+[range(length)as$i|[.[$i:$i+1]|" ___ | \(.) | |___| _|\"\"\"\"\"|\"`-0-0-'"|_nwise(8)]]|transpose|map(add)[] ``` Expanded ``` # engine def E:" o O O o TS__[O] {======|./o--000'"|_nwise(9); # car (note string interpolation) def C:" ___ | \(.) | |___| _|\"\"\"\"\"|\"`-0-0-'"|_nwise(8); # generate train [[E]] + [range(length) as $i| [.[$i:$i+1] |C]] # combine rows and concatenate strings | transpose | map(add)[] ``` Sample run ``` $ jq -MRr train.jq <<< "golf" o O O ___ ___ ___ ___ o | g | | o | | l | | f | TS__[O] |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""| ./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' $ wc -c < train.jq 178 ``` [Try it online](https://jqplay.org/s/qzHO7pFazh) [Answer] # [C (clang)](http://clang.llvm.org/), ~~217~~ ~~212~~ ~~208~~ 193 bytes ``` f(*t){for(char*p,d[]=" o O O o TS__[O] {======|./o--000' ___ | C | |___| _|\"\"\"\"\"|\"`-0-0-'",i=0;i<5;i+=puts(""))for(write(1,d+i*9,9),p=t;d[57]=*p++;)write(1,d+45+i*8,8);} ``` -4 bytes thanks to ceilingcat!! [Try it online!](https://tio.run/##XY7NasMwEITP9VMoukSSpUaFmCSoOrk/BEp9aG6OUY1dp4LUNo5KDnZeveq6IRTyDcvssnOYQhT7vN55XxHmaF81HSk@8461vEwzjRHQoAQ0@pnNmzFpkqFe/zHczhohpJRT@BljxsiAYhhwuAdkhi2@CNZ3IUFTzK2Wyt5Hyoa6/XYHgjGlY4FjZ90HueNlaNmKryhvtVNlGi0yzdowVPQ/MI8gs@RLqk7e1g595bYmNOjRNcFNRXCcPDyy5@Tlia1fWTzBVAUn/1NU@3x38OL4Cw "C (clang) – Try It Online") [Answer] # Excel VBA, 218 Bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window ``` [B1]=[Len(A1)]:?" o O O"[Rept(" ___ ",B1)]:?" o ";:For i=1To[B1]:?" | "Mid([A1],i,1)" | ";:Next:?:?" TS__[O]"[Rept(" |___| ",B1)]:?" {======|"[Rept("_|""""""""""|",B1)]:?"./o--000'"[Rept("""`-0-0-'",B1)] ``` ## Formatted for readability ``` [B1]=[Len(A1)] ?" o O O"[Rept(" ___ ",B1)] ?" o ";:For i=1To[B1]:?" | "Mid([A1],i,1)" | ";:Next:?: ?" TS__[O]"[Rept(" |___| ",B1)]: ?" {======|"[Rept("_|""""""""""|",B1)]: ?"./o--000'"[Rept("""`-0-0-'",B1)] ``` ## Sample Output ``` o O O ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ o | V | | B | | A | | | | E | | x | | p | | r | | e | | s | | s | TS__[O] |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| |___| {======|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| ./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' ``` ]
[Question] [ Write a program that takes in an integer from 0 to 65535 (216-1) and generates a *unique* 500×500 pixel image that looks as similar as possible to these 6 real life images of cracked soil: [![cracked soil sample 1](https://i.stack.imgur.com/GqnaPs.png)](https://i.stack.imgur.com/GqnaP.png) [![cracked soil sample 2](https://i.stack.imgur.com/IYtgDs.png)](https://i.stack.imgur.com/IYtgD.png) [![cracked soil sample 3](https://i.stack.imgur.com/6uWqus.png)](https://i.stack.imgur.com/6uWqu.png) [![cracked soil sample 4](https://i.stack.imgur.com/Aa3YVs.png)](https://i.stack.imgur.com/Aa3YV.png) [![cracked soil sample 5](https://i.stack.imgur.com/C4WJbs.png)](https://i.stack.imgur.com/C4WJb.png) [![cracked soil sample 6](https://i.stack.imgur.com/WVXRls.png)](https://i.stack.imgur.com/WVXRl.png) **These are thumbnails, click them to see the full-size 500×500 images.** The goal here is to **make your computer generated images as photorealistic as possible**. So ideally, if any of the images output by your program were mixed in with the 6 images above, someone seeing the images for the first time would not be able to tell the computer generated ones apart from the real ones. Perfect photorealism is tricky however, so just do the best you can. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") so the answers that have more realistic outputs will be upvoted more and be more likely to win. ## Rules * You may use image processing functions or libraries. * You may base your algorithm on information gathered from the 6 sample images, but your 65536 (216) possible output images should be visually distinct from each other *and* the sample images, especially with regard to the arrangement of the cracks. You must truly generate your images, don't just rotate and translate a selection from a preexisting photo. * You should not otherwise hardcode your outputs. A generic algorithm should be used and numbers larger than 65535 should theoretically produce valid outputs. (I've restricted it merely to accommodate small-maximum integer types.) * The input integer can be thought of as a seed that results in a random cracked soil output image. It should be deterministic though, so the same input should always result in the same output. * The output images must be exactly 500×500 pixels. * The output images may be saved in any common image file format, or simply displayed. * Be sure to include a few example output images in your answer, and their corresponding input numbers. * **The answer with the most votes wins.** Voters should of course upvote answers that attempt to produce images similar to the 6 samples, and downvote answers that break rules or give inconsistent results. The 6 sample images were taken from [texturelib.com](http://texturelib.com/). 1000×1000 pixel area selections were taken from [two larger images of cracked soil](http://texturelib.com/texture/?path=/Textures/soil/cracked/soil_cracked_0038) and then resized to 500×500. You may use analysis from these larger images in your program but the output should specifically imitate the 6 chosen sample images. [Answer] # Mathematica A [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) looks like this drawing, from Wikipedia, showing 19 cells, each containing a single seed point. A cell consists of the subregion of points which the respective generating point is closer to than any of the other seed points. [![voronoi](https://i.stack.imgur.com/gcvjD.png)](https://i.stack.imgur.com/gcvjD.png) The code below generates a diagram from 80 random points (in the square region bound by (-1,-1) and (1,1)). It uses the polygon primitives (in 2D) in the diagram to build polyhedra (in 3D). Imagine that each polygon has, just under it, a translation (-.08 in z) of itself. Think of the two polygons as the upper and lower face of a polyhedron. "Side faces" are then added to complete the polyhedron. Each polyhedron is then translated outwards, from the center of the image, on the xy plane; it moves away from the middle. The magnitude of the translation varies directly with the distance between the polyhedron's original generating random point and the center of the screen. This "spreading out" of the polyhedra in the xy plane results in crevices. ``` crackedMud[1] ``` ## [one](https://i.stack.imgur.com/pPB0K.jpg) ``` crackedMud[65535] ``` ## [last](https://i.stack.imgur.com/o7cwm.jpg) ## Code ``` ClearAll[polyhedronFromPolygon, voronoiPolygons, generatingPointFromPolygon, crackedMud] (* polyhedronFromPolygon returns a single polyhedron from a polygon *) polyhedronFromPolygon[polygon_] := Module[{twoPolygons, verticesOfUpperPolygonCell, nVertices, n = 1}, verticesOfUpperPolygonCell = Join @@ (polygon[[1]] /. {x_, y_} :> {{x, y, 0}, {x, y, -.08}}); (* number of vertices in a single *Voronoi* cell *) nVertices = Length[verticesOfUpperPolygonCell]/2; (*vertex indices of the upper and lower polygon faces *) twoPolygons = Select[Range@(2*nVertices), #] & /@ {OddQ, EvenQ}; (*vertex indices of a rectangular face of the polyhedron *) While[n < nVertices + 1, AppendTo[twoPolygons, {twoPolygons[[1, n]], twoPolygons[[2, n]], twoPolygons[[2, If[n + 1 < nVertices + 1, n + 1, 1]]], twoPolygons[[1, If[n + 1 < nVertices + 1, n + 1, 1]]]}]; n++]; (*the graphics complex returned is a polyhedron, even though it says Polygon *) GraphicsComplex[verticesOfUpperPolygonCell, Polygon[twoPolygons]] ] (* takes two dimensional coordinates and returns all of the cells of a Voronoi diagram *) voronoiPolygons[pts_] := Module[{voronoiRegion, data}, voronoiRegion = VoronoiMesh[pts, ImageSize -> Medium, PlotTheme -> "Lines", Axes -> True, AxesOrigin -> {0, 0}]; data = Join @@ (MeshPrimitives[voronoiRegion, 2][[All, 1]] /. {x_, y_} :> {{x, y, 0}, {x, y, .04}}); (* the mesh primitives are the polygons *) MeshPrimitives[voronoiRegion, 2]] (* Returns, in 3D, the point which was used to generate the nth Voronoi cell. *) generatingPointFromPolygon[n_, points_, pgons_] := FirstCase[points, {x_, y_} /; RegionMember[pgons[[n]], {x, y}] :> {x,y,0}] crackedMud[seedNumber_] :- Module[{pts, pts3D, geometricImage, nPts, polygons, polyhedra, centerPtinImage}, SeedRandom[seedNumber]; nPts = 80; pts = RandomReal[{-1, 1}, {nPts, 2}]; pts3D = pts /. {x_, y_} :> {x, y, .0}; polygons = voronoiPolygons[pts]; polyhedra = polyhedronFromPolygon /@ polygons; centerPtinImage = (Mean /@ (PlotRange /. AbsoluteOptions[ Graphics3D[{polyhedra, Blue, Point@pts3D}, Axes -> False, Boxed -> False]])) /. {x_Real, y_, _} :> {x, y, 0}; geometricImage = Graphics3D[{RGBColor[0.75, 0.75, 0.8], EdgeForm[Darker@Gray], (* # is the nth polygon which yields the nth polyhedron *) (* generatingPointFromPolygon returns the point the generated the #th polygon *) GeometricTransformation[{polyhedronFromPolygon[polygons[[#]]]}, TranslationTransform[(generatingPointFromPolygon[#, pts, polygons] - centerPtinImage)/5]] & /@ Range@nPts}, Axes -> False, Boxed -> False, ViewPoint -> {0., -1, 1.5}, Background -> Black, ImageSize -> 1200]; (*ImageTrim returns a 500 by 500 pixel clip from the center of the image *) ImageTrim[ (*ImageEffect speckles the image *) ImageEffect[Rasterize[geometricImage], {"Noise", 1/5}], {{250, 250}, {750, 750}}] ] ``` [Answer] # Java I used an approach based on recursive Voronoi diagrams. The outputs doesn't look very realistic, but I guess they're okay. Here are some example images (resized to 250x250 so that it doesn't fill the entire screen): 0: [![Image 0](https://i.stack.imgur.com/ne8ds.png)](https://i.stack.imgur.com/ne8ds.png) 1: [![Image 1](https://i.stack.imgur.com/8gjiW.png)](https://i.stack.imgur.com/8gjiW.png) ## More details about the algorithm: All images in this section are using the same seed. The algorithm starts by generating a Voronoi diagram with 5 points: [![Voronoi diagram](https://i.stack.imgur.com/0oIeq.png)](https://i.stack.imgur.com/0oIeq.png) If we look at the original images in the challenge, we can see that the lines aren't all straight like that, so we weigh the distance by a random value, based on the angle to the point, also, closer angles gives closer values: [![Weighted Voronoi diagram](https://i.stack.imgur.com/D4rpi.png)](https://i.stack.imgur.com/D4rpi.png) Now, we recursively draw these kinds of Voronoi diagrams inside of each region, with thinner and more transparent line, and remove the background, with a maximum recursion depth of 3, and we get: [![Recursive Voronoi](https://i.stack.imgur.com/zopXn.png)](https://i.stack.imgur.com/zopXn.png) Now, we just add the pale brown background, and we're done! [![Done!](https://i.stack.imgur.com/oDFnA.png)](https://i.stack.imgur.com/oDFnA.png) ## Code: The code consists of three classes, `Main.java`, `VoronoiPoint.java` and `Vector.java`: `Main.java`: ``` import java.awt.Desktop; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import javax.imageio.ImageIO; public class Main { public static int WIDTH = 500; public static int HEIGHT = 500; public static int RECURSION_LEVELS = 3; public static int AMOUNT_OF_POINTS = 5; public static int ROTATION_RESOLUTION = 600; public static int ROTATION_SMOOTHNESS = 10; public static int BACKGROUND = 0xFFE0CBAD; public static Random RAND; public static void main(String[] args) { int seed = new Random().nextInt(65536); if (args.length == 1) { System.out.println(Arrays.toString(args)); seed = Integer.parseInt(args[0]); } else { System.out.println("Generated seed: " + seed); } RAND = new Random(seed); ArrayList<Vector> points = new ArrayList<Vector>(); for (int x = 0; x < WIDTH; x++) { for (int y = 0; y < HEIGHT; y++) { points.add(new Vector(x, y)); } } BufferedImage soil = generateSoil(WIDTH, HEIGHT, seed, points, AMOUNT_OF_POINTS, RECURSION_LEVELS); BufferedImage background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < background.getWidth(); x++) { for (int y = 0; y < background.getHeight(); y++) { background.setRGB(x, y, BACKGROUND ^ (RAND.nextInt(10) * 0x010101)); } } Graphics g = background.getGraphics(); g.drawImage(soil, 0, 0, null); g.dispose(); String fileName = "soil"; File output = new File(fileName + ".png"); for (int i = 0; output.exists(); i++) { output = new File(fileName + i + ".png"); } try { ImageIO.write(background, "png", output); Desktop.getDesktop().open(output); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done. Saved as " + output); } private static BufferedImage generateSoil(int width, int height, int seed, ArrayList<Vector> drawPoints, int amountOfPoints, int recursionLevel) { BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); ArrayList<VoronoiPoint> points = new ArrayList<VoronoiPoint>(); for (int i = 0; i < amountOfPoints; i++) { points.add(new VoronoiPoint(drawPoints.get(RAND.nextInt(drawPoints.size())))); } HashMap<Integer, ArrayList<Vector>> pointMaps = new HashMap<Integer, ArrayList<Vector>>(); for (VoronoiPoint point : points) { pointMaps.put(point.hashCode(), new ArrayList<Vector>()); } System.out.println(pointMaps); System.out.println(points); for (Vector v : drawPoints) { VoronoiPoint closest = null; VoronoiPoint secondClosest = null; for (VoronoiPoint point : points) { double distance = point.getMultiplicativeDistanceTo(v); if (closest == null || distance < closest.getMultiplicativeDistanceTo(v)) { secondClosest = closest; closest = point; } else if (secondClosest == null || distance < secondClosest.getMultiplicativeDistanceTo(v)) { secondClosest = point; } } int col = 0; if (Math.abs(closest.getMultiplicativeDistanceTo(v) - secondClosest.getMultiplicativeDistanceTo(v)) < (recursionLevel * 5 / RECURSION_LEVELS)) { col = 0x01000000 * (recursionLevel * 255 / RECURSION_LEVELS); } else { pointMaps.get(closest.hashCode()).add(v); } result.setRGB((int) v.getX(), (int) v.getY(), col); } Graphics g = result.getGraphics(); if (recursionLevel > 0) { for (ArrayList<Vector> pixels : pointMaps.values()) { if (pixels.size() > 10) { BufferedImage img = generateSoil(width, height, seed, pixels, amountOfPoints, recursionLevel - 1); g.drawImage(img, 0, 0, null); } } } g.dispose(); return result; } public static int modInts(int a, int b) { return (int) mod(a, b); } public static double mod(double a, double b) { a = a % b; while (a < 0) a += b; return a; } } ``` `VoronoiPoint.java`: ``` public class VoronoiPoint { private Vector pos; private double[] distances; public VoronoiPoint(Vector pos) { this.pos = pos; distances = new double[Main.ROTATION_RESOLUTION]; for (int i = 0; i < distances.length; i++) distances[i] = Main.RAND.nextFloat() / 2 + 0.51; for (int iter = 0; iter < Main.ROTATION_SMOOTHNESS; iter++) { for (int i = 0; i < distances.length; i++) { distances[i] = (distances[Main.modInts(i - Main.RAND.nextInt(4) - 2, distances.length)] + distances[i] + distances[Main.modInts(i + Main.RAND.nextInt(4) - 2, distances.length)]) / 3; } } } public Vector getPos() { return pos; } public double getRotationFromAngle(double radians) { return distances[(int) (Main.mod(Math.toDegrees(radians) / 360, 1) * distances.length)]; } public double getRotationFromVector(Vector vec) { return getRotationFromAngle(Math.atan2(pos.getY() - vec.getY(), -(pos.getX() - vec.getX()))); } public double getMultiplicativeDistanceTo(Vector other) { return pos.getLengthTo(other) * getRotationFromVector(other); } public String toString() { return "VoronoiPoint(pos=[" + pos.getX() + ", " + pos.getY() + "])"; } public int hashCode() { return distances.hashCode() ^ pos.hashCode(); } } ``` `Vector.java`: (This class is copied from one of my other projects, so it contains some unnecessary code) ``` package com.loovjo.soil; import java.util.ArrayList; import java.util.Random; public class Vector { private static final float SMALL = 1f / Float.MAX_EXPONENT * 100; private float x, y; public Vector(float x, float y) { this.setX(x); this.setY(y); } public Vector(int x, int y) { this.setX(x); this.setY(y); } public Vector(double x, double y) { this.setX((float) x); this.setY((float) y); } public float getY() { return y; } public void setY(float y) { this.y = y; } public float getX() { return x; } public void setX(float x) { this.x = x; } /* * Gets the length ^ 2 This is faster than getting the length. */ public float getLengthToSqrd(float x, float y) { return (float) ((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y)); } public float getLengthToSqrd(Vector v) { return getLengthToSqrd(v.x, v.y); } public float getLengthSqrd() { return getLengthToSqrd(0, 0); } public float getLengthTo(float x, float y) { return (float) Math.sqrt(getLengthToSqrd(x, y)); } public float getLengthTo(Vector v) { return getLengthTo(v.x, v.y); } public float getLength() { return getLengthTo(0, 0); } public Vector setLength(float setLength) { float length = getLength(); x *= setLength / length; y *= setLength / length; return this; } public float getFastLengthTo(float x, float y) { return getFastLengthTo(new Vector(x, y)); } public float getFastLengthTo(Vector v) { float taxiLength = getTaxiCabLengthTo(v); float chebyDist = getChebyshevDistanceTo(v); return Float.min(taxiLength * 0.7f, chebyDist); } public float getFastLength() { return getLengthTo(0, 0); } public Vector setFastLength(float setLength) { float length = getFastLength(); x *= setLength / length; y *= setLength / length; return this; } public float getTaxiCabLengthTo(float x, float y) { return Math.abs(this.x - x) + Math.abs(this.y - y); } public float getTaxiCabLengthTo(Vector v) { return getTaxiCabLengthTo(v.x, v.y); } public float getTaxiCabLength() { return getTaxiCabLengthTo(0, 0); } public Vector setTaxiCabLength(float setLength) { float length = getTaxiCabLength(); x *= setLength / length; y *= setLength / length; return this; } public Vector absIfBoth() { if (x < 0 && y < 0) return new Vector(-x, -y); return this; } public Vector abs() { return new Vector(x < 0 ? -x : x, y < 0 ? -y : y); } public float getChebyshevDistanceTo(float x, float y) { return Math.max(Math.abs(this.x - x), Math.abs(this.y - y)); } public float getChebyshevDistanceTo(Vector v) { return getChebyshevDistanceTo(v.x, v.y); } public float getChebyshevDistance() { return getChebyshevDistanceTo(0, 0); } public Vector setChebyshevLength(float setLength) { float length = getChebyshevDistance(); x *= setLength / length; y *= setLength / length; return this; } public Vector sub(Vector v) { return new Vector(this.x - v.getX(), this.y - v.getY()); } public Vector add(Vector v) { return new Vector(this.x + v.getX(), this.y + v.getY()); } public Vector mul(Vector v) { return new Vector(this.x * v.getX(), this.y * v.getY()); } public Vector mul(float f) { return mul(new Vector(f, f)); } public Vector div(Vector v) { return new Vector(this.x / v.getX(), this.y / v.getY()); } public Vector div(float f) { return div(new Vector(f, f)); } public Vector mod(Vector v) { return new Vector(this.x % v.getX(), this.y % v.getY()); } public Vector mod(int a, int b) { return mod(new Vector(a, b)); } public Vector mod(int a) { return mod(a, a); } public String toString() { return "Vector(" + getX() + ", " + getY() + ")"; } /* * Returns a list with vectors, starting with this, ending with to, and each * one having length between them */ public ArrayList<Vector> loop(Vector to, float length) { Vector delta = this.sub(to); float l = delta.getLength(); ArrayList<Vector> loops = new ArrayList<Vector>(); for (float i = length; i < l; i += length) { delta.setLength(i); loops.add(delta.add(to)); } loops.add(this); return loops; } public boolean intersects(Vector pos, Vector size) { pos.sub(this); if (pos.getX() < getX()) return false; if (pos.getY() < getY()) return false; return true; } public Vector copy() { return new Vector(x, y); } public void distort(float d) { x += Math.random() * d - d / 2; y += Math.random() * d - d / 2; } @Override public boolean equals(Object o) { if (o instanceof Vector) { Vector v = (Vector) o; return getLengthToSquared(v) < SMALL * SMALL; } return false; } private float getLengthToSquared(Vector v) { return sub(v).getLengthSquared(); } private float getLengthSquared() { return x * x + y * y; } public boolean kindaEquals(Vector o, int i) { if (o.x + i < x) return false; if (o.x - i > x) return false; if (o.y + i < y) return false; if (o.y - i > y) return false; return true; } /* * Gets the direction, from 0 to 8. */ public int getDirection() { return (getDirectionInDegrees()) / (360 / 8); } /* * Gets the direction in degrees. */ public int getDirectionInDegrees() { return (int) positize((float) Math.toDegrees(Math.atan2(x, -y)), 360f); } private float positize(float f, float base) { while (f < 0) f += base; return f; } // 0 = north, // 1 = northeast, // 2 = east, // 3 = southeast, // 4 = south, // 5 = southwest, // 6 = west, // 7 = northwest public Vector moveInDir(int d) { d = d % 8; d = (int) positize(d, 8); if (d == 0) return this.add(new Vector(0, -1)); if (d == 1) return this.add(new Vector(1, -1)); if (d == 2) return this.add(new Vector(1, 0)); if (d == 3) return this.add(new Vector(1, 1)); if (d == 4) return this.add(new Vector(0, 1)); if (d == 5) return this.add(new Vector(-1, 1)); if (d == 6) return this.add(new Vector(-1, 0)); if (d == 7) return this.add(new Vector(-1, -1)); return this; } /* * Gets the angle in degrees to o. */ public float getRotationTo(Vector o) { float d = (float) Math.toDegrees((Math.atan2(y - o.y, -(x - o.x)))); while (d < 0) d += 360; while (d > 360) d -= 360; return d; } public float getRotation() { return getRotationTo(new Vector(0, 0)); } /* * In degrees */ public Vector rotate(double n) { n = Math.toRadians(n); float rx = (float) ((this.x * Math.cos(n)) - (this.y * Math.sin(n))); float ry = (float) ((this.x * Math.sin(n)) + (this.y * Math.cos(n))); return new Vector(rx, ry); } public int hashCode() { int xx = (int) x ^ (int)(x * Integer.MAX_VALUE); int yy = (int) y ^ (int)(y * Integer.MAX_VALUE); return new Random(12665 * xx).nextInt() ^ new Random(5349 * yy).nextInt() + new Random((30513 * xx) ^ (19972 * yy)).nextInt(); } public boolean isPositive() { return x >= 0 && y >= 0; } public Vector clone() { return new Vector(x, y); } } ``` ## But I don't want to compile a bunch of Java classes! [Here](http://www.mediafire.com/download/dgazw8w4g4qnaiw/Soil.jar) is a JAR file which you can run to generate these images yourself. Run as `java -jar Soil.jar number`, where `number` is the seed (can be anything up to 231-1), or run as `java -jar Soil.jar`, and it chooses a seed by itself. There will be some debug output. [Answer] # Python 3 (using Kivy library and GLSL) First generated image [![enter image description here](https://i.stack.imgur.com/CwHhI.png)](https://i.stack.imgur.com/CwHhI.png) **Python code:** ``` import os os.environ['KIVY_NO_ARGS'] = '1' from kivy.config import Config Config.set('input','mouse','mouse,disable_multitouch') Config.set('graphics', 'width', '500') Config.set('graphics', 'height', '500') Config.set('graphics', 'resizable', '0') Config.set('graphics', 'borderless', '1') Config.set('graphics', 'fbo', 'force-hardware') from kivy.app import App from kivy.graphics import RenderContext, Fbo, Color, Rectangle from kivy.clock import Clock from kivy.uix.floatlayout import FloatLayout from kivy.factory import Factory from kivy.core.window import Window class ShaderSurface(FloatLayout): seed = 0. def __init__(self, **kwargs): self.canvas = RenderContext(use_parent_projection=True, use_parent_modelview=True) with self.canvas: self.fbo = Fbo(size=Window.size, use_parent_projection=True) with self.fbo: Color(0,0,0) Rectangle(size=Window.size) self.texture = self.fbo.texture super(ShaderSurface, self).__init__(**kwargs) self.keyboard = Window.request_keyboard(self.keyboard_closed, self) self.keyboard.bind(on_key_down=self.on_key_down) Clock.schedule_once(self.update_shader,-1) def keyboard_closed(self): self.keyboard.unbind(on_key_down=self.on_key_down) self.keyboard = None def update_shader(self, dt=0.): self.canvas['resolution'] = list(map(float, self.size)) self.canvas['seed'] = self.seed self.canvas.ask_update() def on_key_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'spacebar': self.seed += 1. self.update_shader() Window.screenshot() Factory.register('ShaderSurface', cls=ShaderSurface) class RendererApp(App): def build(self): self.root.canvas.shader.source = 'cracks_sub.glsl' if __name__ == '__main__': RendererApp().run() ``` **KV file:** ``` #:kivy 1.9 ShaderSurface: canvas: Color: rgb: 1, 1, 1 Rectangle: size: self.size pos: self.pos texture: root.fbo.texture ``` **GLSL code:** ``` ---VERTEX--- uniform vec2 resolution; in vec2 vPosition; void main() { gl_Position = vec4(vPosition.xy-resolution/2., 0, 1); } ---FRAGMENT--- #version 330 precision highp float; out vec4 frag_color; uniform vec2 resolution; uniform float seed; vec2 tr(vec2 p) { p /= resolution.xy; p = -1.0+2.0*p; p.y *= resolution.y/resolution.x; return p; } float hash( float n ){ return fract(sin(n)*43758.5453); } float noise( vec2 uv ){ vec3 x = vec3(uv, 0); vec3 p = floor(x); vec3 f = fract(x); f = f*f*(3.0-2.0*f); float n = p.x + p.y*57.0 + 113.0*p.z; return mix(mix(mix( hash(n+0.0), hash(n+1.0),f.x), mix( hash(n+57.0), hash(n+58.0),f.x),f.y), mix(mix( hash(n+113.0), hash(n+114.0),f.x), mix( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z); } mat2 m = mat2(0.8,0.6,-0.6,0.8); float fbm(vec2 p) { float f = 0.0; f += 0.5000*noise( p ); p*=m*2.02; f += 0.2500*noise( p ); p*=m*2.03; f += 0.1250*noise( p ); p*=m*2.01; f += 0.0625*noise( p ); f /= 0.9375; return f; } vec2 hash2( vec2 p ) { return fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453); } float voronoi(vec2 x, out vec2 rt) { vec2 p = floor(x); vec2 f = fract(x); vec2 mb, mr; float res = 8.0; for( int j=-1; j<=1; j++) for( int i=-1; i<=1; i++) { vec2 b = vec2(float(i),float(j)); vec2 r = b+hash2(p+b)-f; float d = dot(r,r); if( d<res ) { res = d; mr = r; mb = b; rt=r; } } res = 8.0; for( int j=-2; j<=2; j++ ) for( int i=-2; i<=2; i++ ) { vec2 b = mb + vec2(float(i),float(j)); vec2 r = b + hash2(p+b)-f; float d = dot((res*res)*(mr+r),normalize(r-mr)); res = min(res,d); } return res; } float crack(vec2 p) { float g = mod(seed,65536./4.); p.x+=g; p.y-=seed-g; p.y*=1.3; p.x+=noise(p*4.)*.08; float k = 0.; vec2 rb = vec2(.0); k=voronoi(p*2.,rb); k=smoothstep(.0,.3,k*.05); float v = 0.; v=voronoi(rb*4.,rb); v=smoothstep(.0,.5,v*.05); k*=v; k-=fbm(p*128.)*.3; return k; } void main( void ) { vec2 fc = gl_FragCoord.xy; vec2 p = tr(fc); vec3 col = vec3(.39,.37,.25); vec3 abb = vec3(.14,.12,.10)/5.; p*=(1.+length(p)*.1); col.r*=crack(vec2(p.x+abb.x,p.y)); col.g*=crack(vec2(p.x+abb.y,p.y)); col.b*=crack(vec2(p.x+abb.z,p.y)); col*=smoothstep(4.,1.2,dot(p,p)); col*=exp(.66); //col=vec3(crack(p)); frag_color = vec4(col,1.); } ``` The [voronoi](http://www.iquilezles.org/www/articles/voronoilines/voronoilines.htm) function in the GLSL code is from Íñigo Quílez. Every voronoi related calculation happens in the fragment shader entirely with some procedural noise functions to create speckles and to disturb the lines of the voronoi pattern a bit. By pressing space the seed will be increased by 1 and a new image will be generated and saved as a `.png` file. **Update:** Added lense distortion, vignetting and chromatic aberration to make it more photo-realistic. Added sub-voronoi pattern. [Answer] # Java ``` import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import java.util.Scanner; import javax.imageio.ImageIO; public class CrackedSoil { static BufferedImage b; static Random rand; public static int distance(int col1,int col2){ Color a=new Color(col1); Color b=new Color(col2); return (int)(Math.pow(a.getRed()-b.getRed(), 2)+Math.pow(a.getGreen()-b.getGreen(), 2)+Math.pow(a.getBlue()-b.getBlue(), 2)); } public static void edge(){ boolean[][] edges=new boolean[500][500]; int threshold=125+rand.nextInt(55); for(int x=1;x<499;x++){ for(int y=1;y<499;y++){ int rgb=b.getRGB(x, y); int del=0; for(int i=-1;i<=1;i++){ for(int j=-1;i<=j;i++){ del+=distance(rgb,b.getRGB(x+i, y+j)); } } edges[x][y]=del>threshold; } } for(int x=0;x<500;x++){ for(int y=0;y<500;y++){ if(edges[x][y])b.setRGB(x, y,new Color(4+rand.nextInt(4),4+rand.nextInt(4),4+rand.nextInt(4)).getRGB()); } } } public static void main(String[]arg) throws IOException{ b=new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB); Scanner scanner=new Scanner(System.in); rand=new Random(scanner.nextInt()); int numPoints=10+rand.nextInt(15); Color[]c=new Color[numPoints]; int[][]ints=new int[numPoints][2]; int[]weights=new int[numPoints]; for(int i=0;i<numPoints;i++){ switch(i%4){ case 0:ints[i]=new int[]{251+rand.nextInt(240),7+rand.nextInt(240)};break; case 1:ints[i]=new int[]{7+rand.nextInt(240),7+rand.nextInt(240)};break; case 2:ints[i]=new int[]{7+rand.nextInt(240),251+rand.nextInt(240)};break; case 3:ints[i]=new int[]{251+rand.nextInt(240),251+rand.nextInt(240)};break; } c[i]=new Color(40+rand.nextInt(200),40+rand.nextInt(200),40+rand.nextInt(200)); weights[i]=50+rand.nextInt(15); } for(int x=0;x<500;x++){ for(int y=0;y<500;y++){ double d=999999; Color col=Color.BLACK; for(int i=0;i<numPoints;i++){ double d2=weights[i]*Math.sqrt((x-ints[i][0])*(x-ints[i][0])+(y-ints[i][1])*(y-ints[i][1])); if(d2<d){ d=d2; col=c[i]; } } b.setRGB(x, y,col.getRGB()); } } //ImageIO.write(b,"png",new File("voronoi1.png")); for(int i=0;i<numPoints/3;i++){ ints[i]=new int[]{7+rand.nextInt(490),7+rand.nextInt(490)}; c[i]=new Color(40+rand.nextInt(200),40+rand.nextInt(200),40+rand.nextInt(200)); weights[i]=50+rand.nextInt(5); } for(int x=0;x<500;x++){ for(int y=0;y<500;y++){ double d=999999; Color col=Color.BLACK; for(int i=0;i<numPoints/3;i++){ double d2=weights[i]*Math.sqrt((x-ints[i][0])*(x-ints[i][0])+(y-ints[i][1])*(y-ints[i][1])); if(d2<d){ d=d2; col=c[i]; } } Color col3=new Color(b.getRGB(x, y)); b.setRGB(x, y,new Color((col3.getRed()+col.getRed()*3)/4,(col3.getGreen()+col.getGreen()*3)/4,(col3.getBlue()+col.getBlue()*3)/4).getRGB()); } } //ImageIO.write(b,"png",new File("voronoi2.png")); for(int i=2+rand.nextInt(3);i>0;i--)edge(); //ImageIO.write(b,"png",new File("voronoi_edge.png")); for(int x=0;x<500;x++){ for(int y=0;y<500;y++){ Color col=new Color(b.getRGB(x, y)); if(col.getRed()+col.getBlue()+col.getGreen()>50){ if(rand.nextDouble()<0.95){ b.setRGB(x, y,new Color(150+rand.nextInt(9),145+rand.nextInt(9),135+rand.nextInt(9)).getRGB()); }else{ b.setRGB(x, y,new Color(120+col.getRed()/7+rand.nextInt(12),115+col.getGreen()/7+rand.nextInt(12),105+col.getBlue()/7+rand.nextInt(12)).getRGB()); } } } } ImageIO.write(b,"png",new File("soil.png")); } } ``` Creates a composite of two random diagrams which is then run through a simple edge detection and finally converted to the final result. **Some outputs:** [![enter image description here](https://i.stack.imgur.com/WB3St.png)](https://i.stack.imgur.com/WB3St.png) [![enter image description here](https://i.stack.imgur.com/hGjZc.png)](https://i.stack.imgur.com/hGjZc.png) [![enter image description here](https://i.stack.imgur.com/6QRXX.png)](https://i.stack.imgur.com/6QRXX.png) **Some of the intermediate steps for that last one:** [![enter image description here](https://i.stack.imgur.com/aENel.png)](https://i.stack.imgur.com/aENel.png) (The first voronoi diagram) [![enter image description here](https://i.stack.imgur.com/WlTr1.png)](https://i.stack.imgur.com/WlTr1.png) (The composite of the two voronoi diagrams) [![enter image description here](https://i.stack.imgur.com/hZiom.png)](https://i.stack.imgur.com/hZiom.png) (After the edge detection step but before the final recoloring) ]
[Question] [ I don't like typing, so I draw my mazes in a very simple format: ``` # ##### # # # ### # # # # # # # # ##### # ``` Isn't it a-*maze*-ing? Of course, I think all mazes should look 3d, similar but not he same as [this challenge](https://codegolf.stackexchange.com/questions/36299/print-ascii-voxels), for maximum a-*maze*-ingness, so I (grudgingly) manually updated the maze to look like this: ``` +-----+ +-----------------------------+ |\ \ |\ \ + \ \ + \ \ \ \ \ \ +-----------------------+ \ \ \ \ \| |\ \ \ \ \ +-----------------------+ \ \ \ \ \ +-----------------+ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ + \ \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ \ \ \---+ \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ \ \| | \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ +-----------------+ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ +-----------------------------+ \ +-----+ \| | \| | +-----------------------------+ +-----+ ``` Unfortunately, it's difficult to work with mazes in that format, and after all that manual typing, I don't want to just retype the original, so I need you to write a program to do the reversal for me. ## Rules * Input will be a multiline string or character matrix consisting only of `" "`, `"|"`, `"\"`, `"+"`, `"-"`, and newlines. * Output consists of `" "` and `"#"`, in the pattern described by the maze. * Due to my amazing maze designing skills, you can assume nothing about the structure of the maze, other than that is has a valid deconstruction. * In the 3d-ification, (the process you must now undo,) each `#` was converted to this 3x4x7 character block: ``` +-----+ |\ \ + \ \ \ +-----+ \| | +-----+ ``` * Adjacent blocks were joined together, like this: ``` +-----+-----+ |\ \ \ + \ \ \ \ +-----+-----+ \|\ \ \ + \ \ \ \ +-----+-----+ \| | | +-----+-----+ ``` but without joining lines, so it actually looks like this: ``` +-----------+ |\ \ + \ \ \ \ \ \ \ \ \ \ \ \ +-----------+ \| | +-----------+ ``` * Concave spaces sometimes block parts of other walls. ``` +-----------+ |\ \ + \ \ \ \ +-----+ \ \ \ | \ \ \---+ \ +-----+ \| | +-----+ ``` * Trailing whitespace in the input or output is acceptable. (You must specify if your answer *requires* trailing whitespace in the input.) * Leading whitespace must correspond to empty spaces in the input. * I still don't like typing, so shortest code wins ### Test cases: ``` Input: +-----+ +-----------------------------+ |\ \ |\ \ + \ \ + \ \ \ \ \ \ +-----------------------+ \ \ \ \ \| |\ \ \ \ \ +-----------------------+ \ \ \ \ \ +-----------------+ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ + \ \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ \ \ \---+ \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ \ \| | \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ +-----------------+ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ +-----------------------------+ \ +-----+ \| | \| | +-----------------------------+ +-----+ Output: # ##### # # # ### # # # # # # # # ##### # Input: +-----+ |\ \ + \ \ \ +-----+ \| | +-----+ Output: # Input: +-----------------+ |\ \ + \ \ +-----+ +-----+ +-----+ |\ \ |\ \ + \ \---+ \ \ \ \ +-----+ \ +-----+ \ \ \ \ | \| |\ \ \ \ \---+ +-----+ \ \ \ \ +-----+ +-----+ \ \ \ \ |\ \ \ \ \ + \ \ \ +-----+ +-----+ +-----+ \| |\ \ | +-----+ \ \---+ \ +-----------------+ \| | +-----------------+ Output: ### ## ## # # ## ## ### Input: +-----------------------------------------------------------------------------------------------------+ |\ \ + \ \ \ +-----------------------------------------------+ +-----------------------------------------+ \ \| |\ \ |\ \ +-----------------------------------------------+ \ \---------------------------------------+ \ \ +-----+ +-----------------------------+ \ \ \ +-----------------------------+ \ \ \ |\ \ |\ \ \ \ \ |\ \ \ \ \ + \ \ + \ \ \ \ \ + \ \ \ \ \ \ \ \ \ +-----------+ +-----+ \ \ \ \ \ +-----------------------+ \ \ \ \ \ \ \ \| |\ \ |\ \ \ \ \ \| |\ \ \ \ \ \ \ \ +-----------+ \ \---+ \ \ \ \ \ +-----------------------+ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ \ +-----------------------+ \ \ \ \ \ \ \ \ \ |\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ + \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ \ +-----------------------------+ \ \ \ \ \ \ \ \ \ \| | \ \ \ \ \ \ \| | \ \ \ \ \ \ \ \ \ +-----+ \ \ \ \ \ \ +-----------------------------+ \ \ \ \ \ \ \ \ +-----------+ \ \ \ \ \ +-----------------------------------+ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ +-----------+ \ \ \ \ \ +-----------------------+ +-----+ \ \ \ \ \ \ \ \ \ | \ \ \ \ \ \ |\ \ | \ \ \ \ \ \ \ \ \---------+ \ \ \ \ \ \---------------------+ \ \---+ \ \ \ \ \ \ \ \ \ +-----------+ \ \ \ \ +-----------+ \ \ \ +-----+ \ \ +-----+ \ \ \ |\ \ \ \ \ |\ \ \ \ \ |\ \ \| | \ \ \ + \ \ \ \ \ + \ \ \ \ \ + \ \ +-----+ \ \ \ \ +-----------------+ \ \ \ \ \ \ \ +-----+ \ +-----+ \ \ \ \ \| | \ \ \ \ \ \ \| | \| |\ \ \ \ \ +-----------------+ \ \ \ \ \ \ +-----+ +-----+ \ \ \ \ +-----------------------------+ +-----+ +-----------------------+ +-----------+ \ \ \ \ \ \ \ +-----------------------------------------------------------------------------------------------------+ \| | +-----------------------------------------------------------------------------------------------------+ Output: ################# # # # ##### # ##### # # # # # # # # # # # ##### # # # # # # # ### # ####### # # # # # # # # # ### # ## # ## # # ## # ################# Input: +-----------------+ |\ \ + \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ +-----------------+ \| | +-----------------+ Output: ### ### ### Input: (Note leading whitespace) +-----+ +-----+ |\ \ |\ \ + \ \ + \ \ +-----+-----+-----+-----+ |\ \ |\ \ | + \ \---+ \ \---+ \ +-----+-----+-----+-----+ \| |\ \ |\ \ +-----+ \ \---+ \ \ +-----+-----+-----+-----+ |\ \ |\ \ | + \ \---+ \ \---+ \ +-----+ \ +-----+ \| | \| | +-----+ +-----+ Output: # # # # # # # # ``` [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` def f(M,k=1,r='',b=0): for c in M[k][k::6]:b^=c>' ';r+=' #'[b] print r;f(M,k+3) ``` [Try it online!](https://tio.run/##1VnNjuIwDD7jp7DYA6DAaIGZOTDq3vawhz4BZaWFAS1iBFXpYUbKu7PlP23sxOkOrDZSq4rYjuPYzmeTfuS/N@vBLu5HWbPZBNXbD4X7cfzmhgKdHMgO79M3NxJQeKU@f/PUBcGVPGE1UWfyMr1m5J4VBiwz8OINhhIHxaNMGkCLhTBRYrOUFUMZT8VcpoaKZyK5TFVpLprNNBfNRp6p4uQBMozHw9UoYSROWaGMs2JGwut41svvrIM7eP@O2REsppeebAG2cO1cWxs02uYWrH05ByjSzcM2z5Zpu/OwTd@W@dtyPd@2OwDxoJSMLokGjIA092AqJJA@PErnND5bhYrXMxMyc3b6LO@5KtZODEcxJflmbCGRkJR9sHwSMg@QSTzWDphkw23WTjDOzXKk1JbLPu60c8Wjmexb8eLyjrF6CECGI@9C3tjSJCEp0eHQj2a43HpcwvHW4xrut1/JmzbdyUxOn4A3x/K4JZQeghSsYJ5QekAmGt03kRtTefAVhkBQAR7zXbNBIFaA5QJxneLuUnJBL2z2Y0LNOKGmcaMXePvxpGJcUTFQ1QvdBVgUfVjUiQZ79XAsa0PiW@piAgyM91o1DO2Lgat32bBiQYp4BeuG1RpCrCxamHROFejAdUzNOEuoQ9Vwrn@@9qfYXEmSDw0l0YIETif3gAq5k9ulgtddvTAjxNX57N1zXIXuY6KuUeXA8aGNHaSqPs/sOXEBCjRQgkBQmATNXkwCKFEh8TXEyBIv4WtXcyFAmQ5anr2RviM0i7cBZUqogEyO5H2hLAAjUkKY4W3ciOIc1XMHhax99YlF23@hR43Ssm5h7lVV38UiGr2a3MskRcg4@iZPXN@E7HHQ/Qjjv4qqV3C/8xOOGdeUc87ToCKTJtTtRD3brVWqMUfVko4S22yt2m/gi9PTVshC0rjdErdw8l7QdNuDWKhqTHYV9G6kYiJmO3aTtHy3ItUerX5Xbxuu48p6w@51vsBFO@6uon43i1qt7jT62hkBLjYZznC5xni8moxXo9HzZDT9Gc2@tbD1kqmohV9a4@kEMM2W6xyzl4MQNezs9pzxnnMc97sYD4pnWDyPxfNUPIUcaOTZR/FuFDwdaMzfZ/M0xx/r1/n79yzbZPup9Nd2u/sD "Python 2 – Try It Online") Takes input as a list of strings (or a list of lists of characters). Prints the output, terminating with error. The idea is similar to [tsh's](https://codegolf.stackexchange.com/a/191271/20260). We look at the characters marked as `?` below to see which are spaces and which are `\`: ``` +-----------+ |? ? ? + \ \ \ \ +-----+ \ ? ? |? \ \ \---+ \ +-----+ \|? |? +-----+ ``` Within each row with `?`'s, a `\` marks a vertical ridge between a filled cell and an empty cell of the maze. Because these ridges are in top layer of the maze, their `\` characters are never obscured by another maze element. To look at the `?` positions, the code iterates through rows `k=1,4,7,...` (zero-indexed), and in each row looks at every 6th position starting with position `k`. It tracks whether we're in an empty or full cell in the bit `b`, and flips that bit whenever a `\` is encountered. After each character read, it appends the character for empty () or full (`#`) according to `b`, and prints the resulting string after the row is complete. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 85 bytes ``` a=>a.flatMap(u=(l,y)=>y%3?[]:[l.flatMap((c,x)=>x<y|(x-=y+3)%6?[]:' #'[u[x]^=c+1<0])]) ``` [Try it online!](https://tio.run/##1VnBbtswDL3rKwgMhW0oMTYU2GGrs9OOO@0YZ6iRJV0Kzwlsd0sA/XuWNLUrS6REZWmH@RAoFilSFEk90vfFr6KZ16tNO67W3xf7ZbYvskmRLsui/VJs4ocsLke7JJvsrq4/TWcfpmU/Fc9H28PE9man4u0428nr5Or9kSaCN9H0Ybqdfcvm8t3N21kyS/btommzJpss4yZtNuWqjaO8ipJ0uSrbRR2X2aRM0p@HZQ@jaZqm5Szp/5fp/XpVxVF0eHUaHVk/ivqharKp@NrWq@ourYvft0KOj4@E43MaU48UKn8ke/x9GlNPLiQ8U3djmvpA8Eyek5rIjnxIr4h1O4UFDBno5TWGAQfGI3UaARYLYqLcZhkqBjwew1y6hpJmQrl0VXEunE03F86Gnqmk1hNAMJ4OVwGHETllCTxOw4yI19Gs/XvSwR28f8fsCBbdS59sIezFlVO20miUzc2Q3Z@DuB0NMk@Xevq0IrTw0zXWxVNrUdp0O8ZisWMCYs5OjcP9mMvaQX9aZrC@HjeAJBtpHxqdYPTDIZKKtQMikVCbtZOHc7MUKbblof867Wx4K5FZDQ8d7hjMQxBoqNEu5I0bhRKiKxru646iSz19pL308xzJLy/Jm//cWYlPnwtvsqQBSCi9CFLQAC@h9AKI0HNfKW5w5AFKEIIlGcDKd18GoVEGKAsEaJK6FFGBXvzrB3eKcEKFA0AvgvYDQ0m4oiQwpxeDM0Al@EClE9aNzwOkpA2RMdfFGGAWXktqGGxnI1Cv2DDUz4WuDLlhRQMT9LIEo84pAx34HFMTzhLqUGc41z@XfRGbS07ywXEjWJDA6eQeUMF3crsu8LqrF2aEuDqdvceOq9B9TNg1Kh2gPbRDA1iJ55ntEpcAhgaSEQgS8qDZ3iQCOCrkvs4WWs/ldKGqCxLA00Hxszfgd4Qi8bYAnhIyIJMDel9IC8CwlGBmeBs3AjtHjd1BwetDXbBo@y/0OKO0PLcw96qqXsUiCryavJZJDiHjbZKgDQ28@aB9YTBdgHpPTzhmXFPOOU/rCc2QIqTHBJ7@GlYlOopnvUNq/wq67HzSGy0RtXsrdy@OZnyFNzQQQablSCng3YhhImI7dq9zeGsC1uU0x@Y9Iul7QdyK2ePnvnS5rj8X8x9xnU3m66pZl4u0XN/Fx8@LcZ3IKK@O3waT/R8 "JavaScript (Node.js) – Try It Online") Basic idea is: we only care about the characters on \$ (6x+3y+3,3y) \$. If it is a dash (`-`), current cell has the different value with the one on its top, and if it is a space (), current cell has the same value. Thanks @[Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), saved 7 bytes [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 bytes ``` ṫ"J‘$m3n⁶m€6Ż^\ị⁾# Ḋ ``` [Try it online!](https://tio.run/##pZM9CgIxEIX7nGJQu8FK8BDeQAh2NrJrL6RwbQS9gHfQUkRZsBEPklwkuv@JmVkCThGG8L7JY2ayWibJxlr9OA9mZnsapZO1yW6p2V2m73whdX402XMI@n6wOr@@9nNrcVwEQhFVzgUKJUtZedY5F1IgdOom59VfQSeXrBNs5L5eMXUbwwJ8gC/vAB5BMehqBAQI0SIZIr4xiGN@2uU6RB4iKdcqTdGY2y4aI2eKXD0BDFgNV0EMSEwZIY78aSOxdTza3rML3sP@B/d8FndL616IsLjqfVs5GhXSEW@3c/gA "Jelly – Try It Online") A monadic link taking a Jelly string as input and returning the processed maze as a Jelly string including one row of trailing whitespace. 1 byte `Ḋ` could be saved if a single line of leading whitespace were acceptable. Took some inspiration from [@tsh’s formula](https://codegolf.stackexchange.com/a/191271/42248), so be sure to upvote that one too! ## Explanation ``` ṫ" $ | Tail each string using a paired member of the following: J | - Sequence along the list of strings ‘ | - Incremented by 1 m3 | Take every 3rd string (1st, 4th, 7th, ...) n⁶ | Not equal to space character m€6 | Within each list take every 6th item (1st, 7th, ...) Ż | Prepend a zero to the list ^\ | Reduce using xor, collecting up results; vectorised across lists (so starts with 0 xor first list, then output of that xor second list, and so on) ị⁾# | Index into "#", " " Ḋ | Remove first list ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 22 bytes *-1 byte thanks to Kevin Cruijssen* ``` εN3%iN.$6ιнηðÊO„ #sèJ, ``` [Try it online!](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/2MVTP99FTMzu28sPfc9sMbDnf5P2qYp6BcfHiFl87//9q6IKCtAAIQNi6gzVUTA1YGJqFsXCCGS1sBoRrGxq0aqAChPAanS7RhylHV1@AwF@ZgLgVUDbiNR9KAogObHm1kNVwKGFqwBFEMphZUhykQpwctuJBdqI1bE1ZdyE7Frgu7NuTgwq4Na5xq4zKPSwGHRkjk1igQoxFLLGsrEKcTLRixpDrcWuHiOBM4Hr2UacaTWZBTKTQsuDANr8Frdw2SmhpM3UTYDY@H/7q6efm6OYlVlQA "05AB1E – Try It Online") Port of [xnor's Python answer](https://codegolf.stackexchange.com/a/191275/6484). Takes input as a character matrix. The TIO link shows input as a multiline string for readability, with the `|€S` header converting that to the character matrix format. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 72 bytes ``` ¶(?<=(.|(¶))+)(?<-2>.)+ ¶ -4G` .+¶(.+)¶.+ $1 T` `#`\\ +\\ .(.)....|. $1 ``` [Try it online!](https://tio.run/##jZI7DsIwEET7PcVKUNhaZSUQJZ@SC1BuYQoKGgpE6XPlAL6YseIk8hexlbPzNJOJ8358nq@7925Ul@NJsVVu1Jp0eBr2Z9YEboThcDXAFBgm7UYm2O7gZtBsjAgiiQAr1hzGctC8x2loKIcgKlawHJklwo4W3Shxzs5Q2koVFG0yf5lsKihspAiSLHR@2wWLWdPJpgWXUitXNci5Ri62chPyZ9ke2qq8qH985xW23duc9ilbNMbyEgCx4dL/hQrSVivbBFuOXw "Retina 0.8.2 – Try It Online") Explanation: ``` ¶(?<=(.|(¶))+)(?<-2>.)+ ¶ ``` De-skew all of the lines. ``` -4G` ``` Delete the last three lines as I don't need them. ``` .+¶(.+)¶.+ $1 ``` Keep only the middle of each group of three lines. (In Retina 1, I believe the above two stages can be done in a single stage: `,G1,3,-5``.) ``` T` `#`\\ +\\ ``` Fill in the faces of the blocks. ``` .(.)....|. $1 ``` Keep only the second character of each block. [Answer] # [C (clang)](http://clang.llvm.org/), [~~120~~](https://tio.run/##fZLRboMgFIbvfQpq0gUEE5xbLyTEBxmLMaZuTQY2SBMzca/uQOtcY7dzA/7ff36OgSquPkr1NlbvpQay/Dy@vPI@xPFaWCgrBFhLCKEw2EheuYp4aQS/xHmxhVdvZWctZvlGL6aa9b/BP8Tr11HWgRZip9X@tK5s6QH32CZ5y9bw4g5c@vyY4cDGhlTEkJZoVkN/CZFEfd1o2PKGUxZJttO54ZGM08d8ZzJn5SZPn7OnQ0ZRhLHkPKG5jPkXxi6LG06dJaEZJdrasz4pU8OHFhHNK4z3B9vs0zhhw@gAmPB8bIf6wJ/Loo5h3KHzxUxvAjrCgiEIAt8gy5OCCDgr9I/FEedrAQxDv/VpYALAfQb@b/XRXLQC1EWM3w "C (clang) – Try It Online") 117 bytes ``` o,c,t,s,r;f(char*m){for(s=o=0;*m;!r?t^=*m!=32,s=t?35:46:0)*++m==10?m-=~++o,c=t=0,s=10:0,r||printf(&s),r=c++%6|o%3-1;} ``` [Try it online!](https://tio.run/##fZLRboMgFIbvfQpq0gUEEzq3XkiIDzI2Y0zdmgxskCZm4l7dgda5xnbnBvy/8/8cA2VcfhbqfSg/Cg1k8XV4eeVdiOOlsFBWCLCUEEJhsJK8chHxbAR/xGmxuVevZdeaT/KVno816ffBP8Trl1GWgWZix9X@Whc2e8AttkpesyU8vwFnnx8z7NlQk5IY0hDNKugvIZKoq2oNG15zyiLJNjozbzySG548koabLHlOn/YpRRHGkvMdzWTMvzF2Qdxw6lp2NKVEW3vSR2Uq@NAgonmJ8XZv620S71g/OABGPJ3Zoi7wh7KoZRi36HQ244OAjrCgD4LAG2RxVBAB1wr9S3HE9TUAhqHf@jQwAuA@A/@r@mDOWgHqIoYf "C (clang) – Try It Online") Inspired by the others answers. ``` '\'=92 ' '=32=>46='.' '#'=35 '\n'=10 // o offset == // l line // c line counter // t toggle // r => ? test, point to inspect for(o=s=0;*m; !r?t=*m-32?!t:t,s=t?35:46:0) // t^=*m!=32 @ceilingcat // if test(r) is enabled: toggle(t) and sets (s) *++m==10?m-=~++o,c=t=0,s=10:0, // next char => if it's \n overwrites (s) // and increments offset(o) and move pointer(m) r || printf (&s) // r or print! Thanks to @ceilingcat // instead of *++m-10?0:(m-=~++o,c=t=0,s=10), !r*s?putchar(s):0, Saved 5 ! r=c++%6|o%3-1;// enable test every 6 x 3+1 positions ``` ]
[Question] [ [Klein](https://github.com/Wheatwizard/Klein) is a 2D language I have designed that can be embedded on 12 different topological surfaces. A Klein program can be run on different surfaces by changing the command line arguments. The topology determines where the instruction pointer goes when it goes off the edge of the program. When moving off of the edge the ip will jump to an edge with the matching color, and will maintain its position relative to the arrow, i.e. the pointer will conserve its distance from the arrow head. For example topology `000`, the topology used by most 2D languages, causes the instruction pointer to wrap around to the other side when if moves off an edge. # Task The task is pretty simple, write a Klein program that when run will output the topology it is run in. The individual numbers may be separated by spaces. (e.g. `000` and `0 0 0` are both permissible output). You may choose to either use or ignore the `-A` command line flag it will not cost you bytes if you use it. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer will be the winner. [Here](https://tio.run/##jY5BDoIwEEXXzCkmE3dGoCw1MXoCDgAmIBQhNJ1GuuH0tS0uWLhwFj8vr/MnfbbL6FzXWryiYbW@FNt0VhoGfqPFSSPleU4hRUgRWQQW0YvoRfQi@iL6Ivoi@sL7C/YMyTRghXTwTw9I7Cg1ym5kb@yZsDGrHVljxsZms5KT3jI169bZfzB0qIFEqkX@e@RXf5igZy2dIy6ZqlsNR9yGAOCLWO6YAP0u1e50/wA) is a online test driver that can be used to test all of the topologies at once. To run in integer mode remove the `-A`. [Answer] # ~~52~~ 48 bytes ``` ./@$0<$ 21\./01 ..>..!\ @ .<..<\ 20//\11 @01$00@ ``` [Try it online!](https://tio.run/##BcGxDcAwCATA/reIRP08rpHFILQpokTZv8N373c//wy9TGlY0XQFyE1ejQKTzMaSe0egFCbVzEg6 "Klein – Try It Online") [Test Driver](https://tio.run/##jc7BDoIwDAbgM32KunDu2h2VkL2HmIg6hLBsRHfh6RHGxYMHL3@ar/mb3tp3vyz3NmGNU/Tz08dEow/QxRcmHAIqZlZbypaSZ9lmyS7ZJbtkN9lNdpPdrH7CR4Ri6PCMqlxXFyhS7wK6ex9XSUeF12lOfQyo45T06N0Q9qRp3jvfD24ddYXC@bf798ivfjfAIwa3LKRtyVUJRhrSLEBUEx0asEAVUdWAYa0bEbAsJbP9AA "Bash – Try It Online") ## Explanation In Klein the IP starts in the top left corner going right. The first step I wanted my program to do was to send the IP off the top of the program to determine the first and third bit. The IP would reenter the program as follows depending on the topology: ``` ^ I|P ./..... 201, 211 -->.......<-- 100, 110 ....... ....... ....... 200, 210 -->.......<-- 101, 111 ....... ^ ^ | | 000 001 010 011 ``` I decided that the my program would record the third bit of the topology before the second bit but swap them (using `$`) before the end. To that end I added code to push the first and third bits of each topology at the IP's points of entry described above. ``` ./..... 21...01 ....... ....... ....... 20...11 .0...0. ``` Next I focused on the topologies with `1` or `2` as their first bit. I decided to recombine them and send them off on the side not connected to the north side so I could determine their second bit. ``` ./..... 21\./01 ..>....--> 200, 201, 210, 211 ....... 100, 101, 110, 111 <--....<.. 20/.\11 .0...0. ^ ^ | | / \ 110 100 111 101 210 200 211 201 ``` Conveniently this regrouped the topologies by their second bit so I could push that to the stack. ``` ./..... 21\./01 ..>.... ....... ....<.. 20/.\11 .01.00. ``` After that I just needed to swap the second and third bit and have the program terminate. ``` ./.$... 21\./01 ..>.... @...... ....<.. 20//\11 .01$00. ``` Now that the topologies with `1` or `2` as their first bit worked, I could focus on making the topologies with `0` give the correct output. The first step was recombining them so that they could be separated into two groups based on their second bit. ``` ./.$... 21\./01 ..>....<-- 010, 011 @...... 000, 001, 010, 011 <--.<..<<.<-- 000, 001 20//\11 .01$00. ``` I first focused on those topologies with `1` as their second bit. These presented a challenge because for them the IP was on a line already used by the topologies with `2` as their first bit. Since it would be tricky to fit more than one instruction on that line (a single instruction can be jumped using the `!` instruction) and I was running low on space as a whole, I decided to redirect the IP off that line and reuse an existing `1` instruction to push the second bit. ``` ./.$... 21\./01 ..>..!\ @...... .<..<<. 20//\11 .01$00. ``` Now all that was left to do for the topologies with `1` as their second bit was to fix the order of the second and third bit and terminate. ``` ^ | ./.$..$ 21\./01 ..>..!\ @...... .<..<<. 20//\11 @01$00@ ^ ^ | | 011 010 ``` Lastly remained the topologies with `0` as their second bit. There was not much space left in the program with the largest unused space being on the top line so it was there that I redirected the IP for the topologies with `0` as their second bit. ``` ./.$.<$ 21\./01 ..>..!\ @...... .<..<\. 20//\11 @01$00@ ``` I still needed to push `0` for the second bit and fix the order of the second and third bit as well as terminate the program. Fortunately, I was able to reuse an existing `$` instruction so the `0` and `@` instructions could fit in the remaining spaces. ``` ./@$0<$ 21\./01 ..>..!\ @...... .<..<\. 20//\11 @01$00@ ``` Finally the nops can be stripped from the ends of lines to get the final program. [Answer] # ~~116~~ ~~88~~ ~~86~~ ~~77~~ ~~69~~ ~~61~~ ~~60~~ ~~59~~ ~~58~~ ~~54~~ ~~53~~ 50 bytes ``` \2..@2 /1\<$00 />!..>! 0// @0$10@1 011\.<0 \.<@>1@ ``` [Try it online!](https://tio.run/##jc@xDsIgEAbgufcUV9IZ7hjVNLyHNWlVahsJEMvSp68UFwcHlz@Xj/yX4zos07bdhoQtxuDWhwtJPp2HMbww4exREJHYk/fkMvM@c3EuzsW5uC6ui@viOvsR7wGqecQziiY/XaBKk/Vob1PIkg4C@7imKXhUISb1dHb2n5Rx/XS@D9w7oofKusX@u@RXf5zhHrzdtk5LaTQo7k4NEai2lrKtgZQCQw2TYcj/7uSJIIdp2bwB) [Answer] # ~~44 41 40 38~~ 37 bytes ``` \\1.>2 /0./ @./$(\ $>0!> 11$/10 [[email protected]](/cdn-cgi/l/email-protection) ``` [Try it online!](https://tio.run/##y85Jzcz7/z8mxlDPzohL30BPn8tBT19FI4ZLxc5A0Y7L0FBF39CAS0XPQc/w////BgYGAA "Klein – Try It Online") [Test driver.](https://tio.run/##jc6xDoMgEAbg2XuKK2HoBBxjmxjfozbRKlZTAqSy@PRUcOnQocufy3f5L/fo1zmloY9YY/B2e1ofxcs6mPwbIy4OmVKK5aScVGbKMxWn4lSciuviurgurne/4uihWia8IeP76g5VnI1DM8x@l3hh2IUtzt6h9CHKlzWLO1KE7eh8P5g7rIPK2NX8e@RXf1pg9M6k1LYkag1SCQmNkPzcAq/VqQYiLkkBF42gDw "Bash – Try It Online") Uses a 6 by 6 square. The shortest I could get with an 8 by 8 square is [38 bytes](https://tio.run/##jc4xDoMwDAXQGZ/CRBmYAs7YVoh7NJWgEAoiSlDJwulTEpYOHbp8Wc/6lp/dNoXQdx5rXJ3ZX8Z5sRgLo3ujx9kiq6qKxaSYlGaKMyWn5JScksvkMrlMLg@/4uAgm0e8I@PH6gGZn7RF3U/uEH9h2K67n5zF0q2@XIye7Zli3c/O94Oxw1rItNn0v0d@9ccZBmd1CKo5ni2AeN4ICaWqVMlvBQBvap7XoEjkivIP) if anyone wants to try improving it. ### Explanation: One the first pass-through the code encodes the first two numbers for the prefixes `0` and `1`. For `2`, it encodes the third number then the first. ``` 201 200 211 210 | | v v -> \\1.>2 IP<- /../.. <- 000, 001 ...$.. .>0... .1..10 <- 010, 011 ....1. ^ ^ | | 100 110 101 111 ``` Then we pass the IPs through the third edge to decide the final number. We combine the IPs with the same prefix. ``` 201 200 211 210 | | v v -> \\1.>2 -> 0,2 or 1,2 IP<- /../.. <- 000, 001 ...$.. .>0!>. -> 1 .1./10 <- 010, 011 ....1. ^ |^ | v| | 0| 100 110 101 111 ``` For the `0` and `1` prefixes, they both come out the top edge to decide the third number. ``` 201 200 211 210 | | |10| vvvv -> \\1.>2 -> 2 IP<- /0./.. <- 000, 001 @./$.. .>0!>. -> 1 .1./10 <- 010, 011 ....1. ^ |^ | v| | 0| 100 110 101 111 ``` For the `2` prefix, the IPs come out the corners from the bottom edge. ``` 201 200 211 210 | | |10| vvvv -> \\1.>2 -> 2 IP<- /0./.. <- 000, 001 @./$(\ $>0!>. -> 1 11$/10 <- 010, 011 [[email protected]](/cdn-cgi/l/email-protection). ^^ |^^ || v|| 1| 0|0 100 110 101 111 ``` Both edges swap the first and third number, push the second number and swaps it with the third to get the correct order. ]
[Question] [ You are given a \$3\times3\$ square matrix where each cell is any digit between \$0\$ and \$9\$ except \$7\$. Your task is to figure out the *minimum* number of digits that must be replaced with \$7\$'s so that the sums of the digits in each row and each column are the same. **NB:** There is no constraint whatsoever on the diagonals, so we end up with a semi-magical square. ## Examples Here is a matrix where three digits need to be turned into \$7\$'s so that all sums are \$20\$: $$\begin{pmatrix}8&6&6\\1&5&8\\6&9&5\end{pmatrix}\rightarrow\begin{pmatrix}\color{red}7&6&\color{red}7\\\color{red}7&5&8\\6&9&5\end{pmatrix}$$ In this one, only one digit needs to be replaced with a \$7\$ so that all sums are \$13\$: $$\begin{pmatrix}9&2&2\\0&9&4\\4&2&9\end{pmatrix}\rightarrow\begin{pmatrix}9&2&2\\0&9&4\\4&2&\color{red}7\end{pmatrix}$$ And for this one, our only option is to replace all digits with \$7\$'s: $$\begin{pmatrix}0&6&8\\3&6&1\\8&4&0\end{pmatrix}\rightarrow\begin{pmatrix}\color{red}7&\color{red}7&\color{red}7\\\color{red}7&\color{red}7&\color{red}7\\\color{red}7&\color{red}7&\color{red}7\end{pmatrix}$$ So the expected outputs for the above examples are \$3\$, \$1\$ and \$9\$ respectively. ## Rules * Because the size of the matrix is fixed, you may take input as a flattened array or 9 distinct arguments. * Because we're dealing with digits exclusively, you may also take a string of 9 characters. * The input matrix may already fulfill the sum constraints, in which case the expected answer is \$0\$. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). ## Test cases ``` [[9,4,3],[3,4,9],[4,8,4]] -> 0 [[5,1,3],[3,1,5],[1,2,1]] -> 1 [[3,9,6],[8,5,5],[8,4,0]] -> 2 [[5,3,5],[1,9,5],[3,3,3]] -> 2 [[8,3,0],[8,0,8],[0,8,4]] -> 3 [[1,5,2],[5,9,5],[6,5,3]] -> 4 [[3,0,8],[1,8,0],[1,3,8]] -> 4 [[3,3,0],[5,1,9],[9,9,5]] -> 5 [[2,4,5],[5,3,4],[4,4,8]] -> 6 [[3,0,3],[8,3,5],[8,3,4]] -> 9 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 29 bytes ``` ∧ℕ≜.&{|∧7}ᵐ²{+ᵛS&\+ᵛS&c{7}ˢl} ``` [Try it online!](https://tio.run/##PU@hDsIwFPwVgpjhQdp1hdbwE8gyAQgQJCQYQsYMIQQcBgUKgyUkGCSWr1h/ZNzeGtTd69293hsvR5PZer6YxmW2ajba/UZzFfn9w2@3xfuYF69T6Q93vzv747UTZRsMver188xaxesyiIY1TLJe/r3N87J0zllKSKXkFNACEzKUpCBOkwyKJA2UFJNkRZGlLoghzQoSJEJGBa9lVJgVKwZMsFeQAYr/P9hOMYgOmS5mFf6pvRJewagw10q9repYtbacrZQYXTQruIjvSf4ZwfeY0NGwI01/ "Brachylog – Try It Online") Or the much faster version with the last two constraint flipped for +2 bytes: ``` ∧ℕ≜.&{|∧7}ᵐ²{c{7}ˢl.&+ᵛS&\+ᵛS∧} ``` [Try it online!](https://tio.run/##PU@hDsIwFPwVgpjhQdp1hdbwE8gyAQgQJCQYQsYMIQQcBgUKgyUkGCSWr1h/ZNzeGtTd69293hsvR5PZer6YxmW2ajba/UZzFfn9w2@3xfuYF69T6Q93vzv747UTZRsMver188wmWS//3uadqFW8LoNoyAA9L0vnnKWEVEpOAS0wIUNJCuI0yaBI0kBJMUlWFFnqghjSrCBBImRU8FpGhVmxYsAEewUZoPj/g@0Ug@iQ6WJW4Z/aK@EVjApzrdTbqo5Va8vZSonRRbOCi/ie5J8RfI8JHQ070vQH "Brachylog – Try It Online") A problem for Brachylog is that the usual way to try the different 7s `{|∧7}²` would lead to the following search sequence: ``` [[5,3,5],[1,9,5],[3,3,3]] [[5,3,5],[1,9,5],[3,3,7]] [[5,3,5],[1,9,5],[3,7,3]] [[5,3,5],[1,9,5],[3,7,7]] ``` so it would try two 7s before every possible one 7. So we could either just try them all, sort them, and be happy. Or we do something more fancy: * `∧ℕ≜.` we try a natural number (starting with 0). This will be our output `.`. Also we label it `≜`. So instead of back-unification ("later the square has two 7s, so the output must have been 2"), we already fix the value of the output. * `{|∧7}ᵐ²` for every value in the square: try it unmodified or replaced by a 7. * `c{7}ˢl` all digits concatenated, with only the 7s selected, have the length equal to the output. * `+ᵛS&\+ᵛS` the sum of each row must unify with the sum of each column. [Answer] # [R](https://www.r-project.org/), ~~131~~ ~~130~~ ~~118~~ 113 bytes *Edit: -1 byte thanks to pajonk, and -4 bytes thanks to Giuseppe, which led to another -1 byte too.* ``` function(x,`-`=rowSums,j=expand.grid(rep(list(0:1),9)))min(-j[apply(j,1,function(k)!sd(c(-t(m<-7*k+x*!k),-m))),]) ``` [Try it online!](https://tio.run/##jZDBToQwEIbvPgWbvbTr1FBKWTDiS3g0xiULGmDpEsoqPj3O1Gh6gKyZtJnDfP8//wxzV5tXW31Uxubz28Ucx/ps2AQHcciH8@fTpbPQ5NXUF6a8ex/qkg1Vz061HVl4LzlknHOUYKJ5Lvr@9MUakPCn0/KNLdmRiZF1D2K/a2@n3ablIDrE4IV77qwrxqGecDiDGBRWDNSlEHNQnAfbQDwG4c0SodGTCAnURSA9Qi4SCrUT1NZY6AChR0QrHsqpZ6Cdl7pKpDgVovrv83OoRYL2j/CRR0I@HhGv5CBl6RzoBuk/CGJ@klBpj9CLRIT30S517Mr3SFa3wl3cxej3k2fzNw "R – Try It Online") **How?** `j=expand.grid(rep(list(0:1),9))` generates a matrix `j` with 512 rows, corresponding to all possible placements of `7`s in a 9-element matrix. We then `apply` the function `!sd(c(-t(m<-7*k+x*!k),-m))` to each row, to determine which ones would yield a semi-magic square if `7`s were placed at those positions in the input matrix `x`. From these rows, output the minimum row sum, which was the number of `7`s we needed to place. (Note that for golfing motives, the short `-` operator is re-assigned to the longer-named `rowSums` function to save bytes, making the code a little difficult to read...) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` JŒPµ³7⁸¦s3§;SEƲµƇḢL ``` [Try it online!](https://tio.run/##y0rNyan8/9/r6KSAQ1sPbTZ/1Ljj0LJi40PLrYNdj206tPVY@8Mdi3z@//8fbaFjBoSGOqY6IJaljmksAA "Jelly – Try It Online") Takes a flattened list. Unfortunately, it's not possible to test this with all test cases at once because it uses `³`. ## Explanation ``` JŒPµ³7⁸¦s3§;SEƲµƇḢL Main monadic link J Indices ([1..9]) ŒP Power set, ordered by length Ƈ Filter by µ ( ³ The input ¦ At indices ⁸ given by the argument, 7 replace the element with a 7 s3 Split into groups of 3 Ʋ ( § Sum of each row ; Join with S Sum of rows (i.e. sum of each column) E All equal? Ʋ ) µ ) Ḣ First element L Length ``` [Answer] # [Haskell](https://www.haskell.org/), ~~157~~ ~~143~~ ~~136~~ ~~134~~ 132 bytes ``` f z=minimum[sum[1|7<-v]|v<-foldr((<*>).(:[(7:)]).(:))[[]]z,e[sum$(v!!).((4-d)*x+).(d*)<$>l|d<-[1,3],x<-l]] l=[0..2] e(x:z)=all(x==)z ``` [Try it online!](https://tio.run/##TY7LboMwEEX3fIUjsbCTAfFMCIJ8Qbvq0vICCVBQDYlCQhHi3@mMS1A9Gvvq@szjWvTfldbLUrMpb5uuaV@t7DH9@ZQ5g5qHzKlvunxwnu0vwuWp5KdUKFJCSKnUBBUV2HzY7dDlkVOK/XhAWe5FZl/0XGaO9CFUMGaOVsrSufRcN1BWxcd0EnmhNR/zXExLWzQdy1lb3D8Zv7@eX8/HR8dc1l9vP/jUgtmMSYvhkWeIIMSIgFQCkSIfZAy@8X0gFYC/@iFyR@RiDKTB2/jQkGeITV24@glqD8l3vvtT3wCT@CPVbP2J8g1NGySbTz9/Eyji1Q9wh9jMjEwk//pgtdmKbjNXLb8 "Haskell – Try It Online") Takes a flat list of nine numbers. Shortened by 11 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) (143 should have been 147). Shortened additionally by 4 bytes. ### Explanation ``` f z=minimum[sum[1|7<-v]| -- count 7s for all solutions and take minimum v<-foldr((<*>).(:[(7:)]).(:))[[]]z, -- generate squares with all possible substitutions e -- all sums must be equal [sum$ -- compute sums of rows and columns (v!!).((4-d)*x+).(d*)<$>l| -- transform [0..2] to index list and apply to v d<-[1,3],x<-l]] -- parameters for index lists l=[0..2] -- abbreviation, used in two places e(x:z)=all(x==)z -- check whether all numbers in list are equal ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~159~~ ~~152~~ 140 bytes -7 bytes thanks to Donat -4 bytes thanks to Donat ``` lambda l:min(i.count(7)for j in range(512)if 2>len({sum((i:=[(7,L)[M<'1']for L,M in zip(l,f'{j:9b}')])[k%7::k//6])for k in[-5,6,21,22,23]})) ``` [Try it online!](https://tio.run/##TZDBbqMwEIbveQr3sLItTVLAQAAtkXpvn8DlYBLYdeMQhN2V2qrPno5tqi6X0e9/vpn5md/c3@skqnm5je3zzahLf1LENBc9Mb07Xl8nx/Z8vC7kheiJLGr6M7AizbgeSXYww8Q@7OuFMd20ku3hkcun3zSlnSce4ckz73pmBkb68dLU/SflHZfnX/umOd/fl10YfcY2uS2ghCyFLINMdJ@c3/Rlvi6O2De78V3aD0Oxs@6kp2ZD8FPQk5bonZ2NdoyS7YFQHh1895cN/5RhioN1anGt7KIbKIzWR3lEOWJXEJisJ3ctOcYV/psX36yAbg8UjkDvWgorGqYtgzpvBmOHiMR2@mAMcYN1lszK2uFE@U3KGnIQHUiBtcaaQwV51/nLk42UBaSrnUKBFf8HpNFO0RZQQ4nPFRTBRhaSaGeBFitVhypQix@7QpkEKoEKa/KzW6CNGyHD52KlS9QrnYfdkUqRSkIVqP@z43CfwAerw5RgF2hneGkRbEwecuffdLkOF@E0sQYT36fVXw "Python 3.8 (pre-release) – Try It Online") Takes input as a flat list. Solves by brute-forcing each possible set of 7's. When checking the sums of rows/columns, skips the last row. ``` f=lambda l: # l is flat list (9 elements) min( # i.count(7) # what we're trying to minimize (the number of 7's used) for j in range(512) # 512=2^9 if 2>len({ # check if the len of the set of row/column sums is 1 (it's at least 1 for sure) sum( # get the sum of a row/column (i:=[(7,L)[M<'1'] # Choose the original number or 7 based on whether the binary digit is 1 # (the alternative for the digit is ' ' or '0', which are both < '1') for L,M in zip(l, # f'{j:9b}')]) # gets length 9 binary string [k%7::k//6]) # Slice the array to get a row or column for k in # [-5,6,21,22,23]})) # corresponding slices are i[2::-1] i[6::1] i[0::3] i[1::3] i[2::3] ``` [Answer] # Java, ~~257~~ ~~246~~ ~~210~~ ~~200~~ ~~195~~ ~~190~~ ~~188~~ ~~186~~ 181 bytes ``` a->{int r=9,i=512,j,e,s,k,x,z,b,c=9;for(;i-->0;r=e!=0|r<c?r:c)for(j=s=e=0;j<3;s=j++<1?x:s,e|=x-s)for(k=x=c=0;k<9;z=b>0?7:a[k],x+=k/3==j?z:0,x+=k++%3==j?30*z:0)c+=b=i>>k&1;return r;} ``` *Saved 11 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904).* *Saved 46 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).* *Saved 19 bytes thanks to [Donat](https://codegolf.stackexchange.com/users/95987).* Takes a flat array as input. This method tries all 512 (29) possibilities by using the binary representations of the integers from `0` to `511`. On each iteration, it sets the values at all indexes where `i` has a set bit to `7`. Then, it checks if the current array is valid, in which case the answer is updated. [Try it online!](https://tio.run/##TZLBbqMwEIbvfQrvYVehDCwE6AbMEPWy0h721L1FORBKKgOFyDYRTcqzp2NvGlUjm5nf34zHI5ryWHrNc3upulIp9vd8xw7jrhMVU7rU9DkO4pm9lqJniyctRf@y2T46RLGGMv1Ri87fj32lxdD7/4Y/vf59jXLy65dabrYF2zO8lF5xFr1mElMQmIRLaKAGBS1McIIdVJjy/SAXXHheEXCJ9TcM3mVerWVWOeakQYU1BrzJI66wcd08XE@ZgvodJ09ZpMUJK0LaPOUn3BXB@ldWbtotTC62PyPEZn3KAhu57ncbR8E9SU7l4g5FUbQ/Qi5rPcqeST5fOLs9Y7PVtdIKzePZOYUYIrIYjLeCeAarJxBaPQTjLSG86hFxD8QlZERDcOMjS6aQ2Lzoqq/ID4j8XJ/1Td0lLcM/mJxbfUOFljYdrG66Ofl/g7Hkqi@ph8TeGVtbfalD2bYrs8czyTOnzcz3WEpmppDZUTjs6U3p@tUfRu0f6OfQXb/Y@@Xh0L09KhrcwmCOQ9nz3Xz5AA) [Answer] # [MATL](https://github.com/lmendo/MATL), 23 bytes ``` nW:qB!"G7@(t!hsd~?@svX< ``` [Try it online!](https://tio.run/##y00syfn/Py/cqtBJUcnd3EGjRDGjOKXO3qG4LMLm//9oYwVLBTNrBQsFUwVTEGWiYBALAA) Or [verify all test cases](https://tio.run/##LY7BCsIwEETvfsXWk8ekm9TECBYR/AFBsQQUevCggrSIJ389zm4lMBOGl8k8ruO9XMrzuHptq/l@2S7G6jb03007vE/rkvPu/DmULpIjTsSwmCCBXJ51nuyUWvIJUpNFyhSpSUC8pCDJKMsTFMVYDtIANwIZCklEe1FHdYIo2@DC2quQFVqMKWiqDTIFy6I8QVrjVy8pFste92eN7A3TFDGXfw). ### Explanation ``` n % Implicit input. Number of elements: gives 9 W % 2 raised to that :q % Range, minus 1 element-wise. Gives the 1×512 vector [0 1 2 ... 511] B! % Binary, transpose. Gives a 9×512 matrix where each colum is the binary % expansion of a number in the above vector " % For each column, c (9×1 vector of zeros and ones) G % Push input 7 % Push 7 @ % Push current c ( % Write 7 in the input at the entries specified by ones in c t!h % Duplicate, transpose, concatenate horizontally. Gives a 3×6 matrix s % Sum of each column d~ % Consecutive differences, negate. Gives a 1×5 vector containing zeros % and ones. If all values are one we have found a solution ? % If all entries are nonzero @s % Push c, sum. This is the number of sevens that were written vX< % Concatenate with any previous results and take the minimum % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` Fφ«≔⭆θ⎇&ιX²λ7κη≔⁺⪪η³E³⭆⪪糧μκζ≦Σζ¿⁼⌈ζ⌊ζ⊞υ№η7»I⌊υ ``` [Try it online!](https://tio.run/##VY5LC8IwEITP@isWTxuIoBaR0lMVDx6Egv6BoK1dTFPNwyf@9piID7wNOzvfzKYWetMK6X3VasCKwb3byY2hncKV1aR2S3HAI4d1qZXQV5ySPZMpc7VF4lC051LjiINkjENv0uOwj6pm2RdTSGdwdZBkseaQBDciEw4//p@b24XalhdsXqxIu0Va@Pvscs37RhXg/OiENLgUF2pcg7fIJ/XWjEHhTI2Ow6x16tURVrIQfnSLUG9xJozFT8KFROZ9kgzGwzRNx75/kk8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of 9 digits. Explanation: ``` Fφ« ``` Loop over all possible replacements of digits with `7`, and then some. ``` ≔⭆θ⎇&ιX²λ7κη ``` Get the next possible replacement of digits with `7`. ``` ≔⁺⪪η³E³⭆⪪糧μκζ ``` Split into rows and concatenate with the transpose. ``` ≦Σζ ``` Sum the rows and columns. ``` ¿⁼⌈ζ⌊ζ ``` If they are all the same, then... ``` ⊞υ№η7 ``` ... save the number of `7`s. ``` »I⌊υ ``` Print the minimum number of `7`s required. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes ``` ^ : +`:(.) $1:$%'¶$%`7: %(`: $`$` 6`... $&¶ 8O$#`. $.%` 18`. $* )`¶ , G`\b(1+,)\1{5} %M`7 O`. ¶. ``` [Try it online!](https://tio.run/##PY8xbsMwDEV3XqNSYjeEIFmWI2ku0KnIAWQHbIEOXTIE3YpeywfwxRyaFjJ9Uu9/irx///7cPlfd0PgG6xUynCg3pgXlstLHZVaazhmYZ1CkCAYyxoA6LDPEi3ohro0mcHGrXqElBgjvNH417oTt6P7CP@gPOsOFHctsYF1LSdijn7B41sTaY8R@mqCUgK4Sh4HVYYdOiMeEA79EDEI4gbZmfPUmUc@9FxK5suK1GFnt8x@ejh2/hJoZuPf1n93r2GtFPfc72adtO25bJ8lupONdghC@SO7pnxkr98S6YxTH9AA "Retina 0.8.2 – Try It Online") Takes input as a string of 9 digits, but link includes test suite that splits on newlines and deletes non-digits for convenience. Explanation: ``` ^ : +`:(.) $1:$%'¶$%`7: ``` Create all possible combinations of replacing a digit with a `7`. ``` %(` )` ``` Process each combination separately. ``` : $`$` ``` Triplicate the string of digits. ``` 6`... $&¶ ``` Split the first two copies into rows. ``` 8O$#`. $.%` ``` Transpose the first three columns into rows. ``` 18`. $* ``` Take the sum of each column or row. ``` ¶ , ``` Concatenate the results. ``` G`\b(1+,)\1{5} ``` Keep only those that are semimagic. ``` %M`7 ``` Count the number of `7`s used. ``` O`. ``` Sort by number of `7`s used. ``` ¶. ``` Keep only the smallest number of `7`s used. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` lhf!t{ssMMCBc:JQT7 3yU9 ``` [Test suite](http://pythtemp.herokuapp.com/?code=lhf%21t%7BssMMCBc%3AJQT7+3yU9&test_suite=1&test_suite_input=%5B9%2C4%2C3%2C3%2C4%2C9%2C4%2C8%2C4%5D%0A%5B5%2C1%2C3%2C3%2C1%2C5%2C1%2C2%2C1%5D%0A%5B3%2C9%2C6%2C8%2C5%2C5%2C8%2C4%2C0%5D%0A%5B5%2C3%2C5%2C1%2C9%2C5%2C3%2C3%2C3%5D%0A%5B8%2C3%2C0%2C8%2C0%2C8%2C0%2C8%2C4%5D%0A%5B1%2C5%2C2%2C5%2C9%2C5%2C6%2C5%2C3%5D%0A%5B3%2C0%2C8%2C1%2C8%2C0%2C1%2C3%2C8%5D%0A%5B3%2C3%2C0%2C5%2C1%2C9%2C9%2C9%2C5%5D%0A%5B2%2C4%2C5%2C5%2C3%2C4%2C4%2C4%2C8%5D%0A%5B3%2C0%2C3%2C8%2C3%2C5%2C8%2C3%2C4%5D&debug=0) Takes input as a flattened list. Translation of [xigoi](https://codegolf.stackexchange.com/users/98955/xigoi)['s Jelly answer](https://codegolf.stackexchange.com/a/221254/78186). [Answer] # [Python 3](https://docs.python.org/3/), ~~200~~ \$\cdots\$ ~~183~~ 181 bytes ``` def f(a,R=range): for b,n in sorted((bin(i).count('1'),i)for i in R(512)): c=[[a[i],7][n>>i&1]for i in R(9)] if len({(sum(c[3*i:3*i+3]),sum(c[i:9:3]))for i in R(3)})<2:return b ``` [Try it online!](https://tio.run/##TZHBboMwDIbvPIVPI9m8qSHQAhp9iF4zDi0Na7QtIEilbYhnZ3FYpcoxcn4@24nT/7hLZ@WynHULLTvioRqO9l3zMoK2G@CEFoyFsRucPjN2MpYZ/tJ0V@tYLGKOhhNmCDqwTCScMqGplDoqU@OuVna/Nw@ivsMKXnvGtPCpLZvYeP1ijZKPpvT@JGuOq2LKovS7@waSz/w1KQftroOF0@L06EaogKkCU5TeUqQox7RGUBmKIAqkKEFBovTE1hOZN8/hZiVlYArMQoYkMffBxjM3DzWpVuKdyC3Ra036LwJHLfNVJHmtSpaRmPiOWWiSBstv6T4pnIG@ac0j/d3rxg@dbrdBEAhJWBIhDStD2CIUPGouuvnQA4Hx2zXZpU2MECIhYx7R@BxqGuCv6VkYGcKtfHguABpiyxwPm34w/nnbeHIzPO9hGmeY/psoXVVjPcd8@QM "Python 3 – Try It Online") Inputs a flat list of \$9\$ integers and returns the minimum number of elements that must be replaced with \$7\$s so that the sums of the rows and columns of the corresponding \$3\times3\$ matrix are the same. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~126 123~~ 116 bytes ``` ->m{(0..510).map{|x|[120,345,678,360,147,258].map{|a|a.digits.sum{|z|x[z]>0?7:m[z]}}.uniq[1]?9:x.digits(2).sum}.min} ``` [Try it online!](https://tio.run/##PZDdasMwDIXv@xS9bEEz/k2cwtIHMb7IGC25cOnWBtLEfvZMUtJxkBGHT0fCv8PXa7l8Lh9tmg9SCKfkUaTuPucxB6UlGOugqj2YSoKyNWjn4wp0uRPf/bV/PsRjSHOe8him2MpzfUrYlCKGW/8TVDw3p3EjD/pIcBGpv5UlhAYsGJQF6jzYCLt9cKDYVUCdBsWuQaZCxqGQBLmxhqkGHM8YdvFekEi9a82lPI1FbEX8lkuEYpL2@s0lf00mOXY17nW8ybL8fwLO8SX02hjff3jfX8IYy/IH "Ruby – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes ``` q0//.k_/;!Or@@(Equal@@Tr/@Join[w=MapAt[7&,q,#],w]&/@{1,2,3}~Tuples~{k,2}):>k+1 ``` [Try it online!](https://tio.run/##RY/LSgMxGIX3fQsRipeDSSYzdWJpiQs3guiiu1IkSKnD9DbTKV2EdOtS8A18wj5C/CeZ4urkz3fOf1mZ5nO@Mk3xYfxi5KvTzy9n7K58Z8OL11rrq6dqb5ZaT2qmnzfFenoYvZjtYzO976PC5QyH0/fXrM@0FUgg3XGy3y7nu6Mtkbjrh3F5K/xbXawbfbMgU89ahZR8sJJUkabIkToHQhlEhwQy0raliEhCYUBfObKAKAN@TsnOrYJKqmVEOT15cHPkpPx/Fk2gDUHpmBpQLc@zoluQmweVVHcoNmw3bZdXIR1QQhtlAdFl4a60TfWc938 "Wolfram Language (Mathematica) – Try It Online") -30 bytes from @att [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~151~~ ~~148~~ ~~145~~ ~~142~~ 140 bytes ``` a=>{r=9;for(i=512;i--;r=e|r<c?r:c)for(j=e=0;j<3;a.map((z,k)=>x+=(i>>k&1&&++c?7:z)*(!(~~(k/3)-j)+30*!(k%3-j))),j++?e|=x-s:s=x)c=x=0;return r} ``` [Try it online!](https://tio.run/##PZDRboMwDEXf@Qr6sCopoQMCHS01/ZCKB5SFCeigCmxCXddfZ3baTpYj6@b4Ok5TfpeDMvV59Lv@Xc@VC3MJ@Y@BbVb1htWQhFFW@35mQF/NXh3MTnG6aUBDkDV7mZXrz/LM2EW0HPLJA1bnebsMl0vPU4e33YWv2ILdbqx9ldxvuCeD1YK1LxJrzkXjeQd9hckfdgNMXMGEtkaPX6Zzze886mEc4Oi4x62IhcSIBVWpiAuBaiJCq4aCqkiEVpXIbJBJMJAUwYOVltqKxPZIq6ZYBUg98@5LfhEmsRviH75EhJakuelDJf3uTJFYNcK5iZ0U20j/HbDPvoTOuHAKh/6TFnX7yrULc1f13dCf9PrUf7DKXnKeOfMf "JavaScript (Node.js) – Try It Online") 2 byte reduced thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) ### Explanation: ``` a=>{r=9; // initial value for minimum for(i=512;i--; // i is a bitmask for indexes to replace by 7 r=e|r<c?r:c) // minimum of valid squares, e is false if valid for(j=e=0;j<3; // for three rows/columns a.map((z,k)=> // body: compute sum(row) + 30*sum(column) x+= // current partial sum (i>>k&1&&++c?7:z)* // number in current cell, maybe replaced by 7 // ++c is always true, here only for counting 7s (!(~~(k/3)-j)+ // 1 for current row, else 0 30*!(k%3-j))), // 30 for current column, else 0 j++?e|=x-s:s=x) // compare sums (s is sum in first iteration) c=x=0; // initialize number of 7s and sums return r} // result ``` Note: We compare the sums of rows and columns only separately. But if the sums of all rows are equal and the sums of all columns are equal, they must be all equal to each other. The sum of the sums of all rows equals the sum of the sums of all columns. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 53 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⌊/+/¨7=,¨a/⍨1=≢¨(∪+/,+⌿)¨a←⎕∘{3 3⍴7@(⍸⍵⊤⍨9/2)⊢⍺}¨⍳512 ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=AVoApf/ijIovKy/CqDc9LMKoYS/ijagxPeKJosKoKOKIqisvLCvijL8pwqhh4oaQ4o6V4oiYezMgM@KNtDdAKOKNuOKNteKKpOKNqDkvMiniiqLijbp9wqjijbM1MTI&f=AwA&i=TczBDYNAEEPRO43sdWZtI09DdBPqoA5KoZIQKdKOfHv68rE9n/O@RhFg0Rzb8SclkMqZi1C7JTNaBWUJwCIj/Fv7Sk2VdrXqjdKRcCPEe1alRZMSSPYqYMjg@AI&r=tio&l=apl-dyalog&m=tradfn&n=f) A tradfn submission which takes a flat array as input from STDIN. loops over 512 combinations and finds the minimum. [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü+üF∙░╔┴!╜U╙],wøT╥B╠╓l6â° ``` [Run and debug it](https://staxlang.xyz/#p=812b8146f9b0c9c121bd55d35d2c770054d242ccd66c3683f8&i=%5B9,+4,+3,+3,+4,+9,+4,+8,+4%5D%0A%5B5,+1,+3,+3,+1,+5,+1,+2,+1%5D%0A%5B3,+9,+6,+8,+5,+5,+8,+4,+0%5D%0A%5B5,+3,+5,+1,+9,+5,+3,+3,+3%5D%0A%5B8,+3,+0,+8,+0,+8,+0,+8,+4%5D%0A%5B1,+5,+2,+5,+9,+5,+6,+5,+3%5D%0A%5B3,+0,+8,+1,+8,+0,+1,+3,+8%5D%0A%5B3,+3,+0,+5,+1,+9,+9,+9,+5%5D%0A%5B2,+4,+5,+5,+3,+4,+4,+4,+8%5D%0A%5B3,+0,+3,+8,+3,+5,+8,+3,+4%5D&m=2) yet another powerset answer [Answer] # [JavaScript (Node.js)](https://nodejs.org), 152 bytes ``` p=(m,l=0)=>(q=l=>([a,b,c,d,e,f,g,h,i]=m,l)?m.some((v,j)=>q(l-1,m[j]=7)||(m[j]=v,0)):new Set([a+b+c,d+e+f,g+h+i,a+d+g,b+e+h,c+f+i]).size<2)(l)?l:p(m,l+1) ``` [Try it online!](https://tio.run/##TZHbcoIwEIbveQruTCYrBgJWtNirPkEvkRkRI8QJB4WxTmuf3S4Ba2/42f323wMc00vaZmfVdNOq3sv7vYlICTriNFqTU6TxGaewgwz2IOEAORSgkghL6FvptHUpCbnAEatPRE9dKONjEr3Q242YtwtwSpeV/LQ/ZIed2I5hJyYZdmIFU5CyPcthh5kCMnZgKqFOq77kq0cJjtDLpl@HufTeybbL0la2dmRvrTgOwQeRQCxQQ1QfFuAniT1d2xxxAO6IXQhQXfDAHbCLWEAIc0wvIDAYvcAH7Bm3GF2hUYGxeOIFhty4OCxQ@XO2QIwTwcN0MLrnGI9u38weXC66uFGB8T88NO8v6A8LTReDA8QebhoYjJebu/2Hez42F2Y1MR4mHquF1tbpzqok@IkbrToy2VQT6pRpQ7SqpB2t7V4x0WUFmW32s3yg1x6xK6Ur6@8vOIf6/J5inYHfVlZXba2lo@ucoMNptcok4RBSCtc4TKj1Q1f3Xw "JavaScript (Node.js) – Try It Online") Take input as a flatten array. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 152 bytes ``` f=(a,m)=>[b=0,1].map(d=>a.map((r,i)=>b|=r.map((n,j)=>s+=d?n:a[j][i],s=0)|1<<s))|b&b-1&&a.map(r=>r.map((n,x)=>r[n-7&&(r[x]=7,v=f(a),v>m?0:m=v),x]=n))|m+1 ``` *-8 bytes thanks to @Arnauld!* [Try it online!](https://tio.run/##dZFBk6IwEIXv/ooctiQpWwqMOKITvO1hD7sHj1mqBjFYWBjYBF23Rn@70wZ05rKn5uX197q72GenzOambNqxrrfqdisEzeDARCI3IoAw9Q9ZQ7ciydwHNVCit7kI02kNe9R2JLYrvcjkPpVlClYE7BK@vlrGLpvhZhwOhx1uRPLkzsgZqccvwyE18pyKFziJgmYMTslhFSwO4sQAnzWGHEbhLa@1bUmeWWWJIEb9OZZGUa@wHvONyrbfy0qt/@mcBsxv63VrSr2jzLdNVbbU@62x7T65KrUiIiHvA0K6SFnq5tgCUedG5a3aphh/73qg48RjS@w2qj0aTeSP9a@ffpMZq6gjGZDRk10Orthc1IbQ/6XXRXcF@7KDUfZYtTi46DOXvVVXyq/qHX379t71XAl9fBIhxDOXrIiX18ag8MiCeH9NrXfelb1h1PUmZQxT4ClIjjXGOoU5TNOUjBMSDKSMIOztECKsIUzw5zs7RJtDDDN8nkPkbGQh6OyJo3lPxa5y1PzTnqMMHBXAHGvwOZujjRNhgs9RT89Q9/TUze6oEKnAVY76i92F3y@4Hxa7FGdHaE9w08jZeLm7e/qgZ304d6vx/jD@WC3@AA "JavaScript (Node.js) – Try It Online") Takes a matrix of numbers. [Answer] # [Perl 5](https://www.perl.org/), 138 bytes ``` sub{(sort map{$i=$_;%e=map{//;$c=$x=$k=0;$x+=($i>>$k&1&&++$c?7:$_)*(!(~~($k/3)-$')+30*!($k++%3-$'))for@_;($x,1)}0..2;%e>1?9:$c}0..511)[0]} ``` [Try it online!](https://tio.run/##PZDxasIwEMb/9ymqnF1iM02axlVDqu/himylgnTT0nZQEH317i5147hw9/G778LVZfNlBji5of35vLH22nTB90d9g7ODo52XjprVykLhoHdQOWmhjxyDc5ZBFaowjCIodm9bOPIFm7LHg0G10vwVXnik5WKKbRTNNfX8dG32R8ugF4rf5XIZ44JM7TZbKKg1SvGDzO@D3Xdl27WOTYLDRiRCYySCqlQkuUDVCOVVJaiKhfKqRmaNjMFAUsgnqz21EcbPaK@mWEmk/nL0Jb8Yk9g18U9fIpQnaW/6VEkfnSmMV2Pca/ymxEf674Bz/if0JvmE20ndnC8dC@HE9ng@EczeLzMe4JWC8QB2@AU "Perl 5 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 73 bytes ``` lMin[Pick[#~t~2,t[w=l+7#-l#]⋃t/@w,{_}]&/@{0,1}~Tuples~{3,3}] t=Total ``` [Try it online!](https://tio.run/##RU9BasMwELz7G4LQ0i2RLCuVKAZfeiwEmpsxRZiEmCpOaVVyENKlx976g36tH@gT1M3GIaeRdmZ2ZnfWb9c764fe5k2d3d/3z@Mwtsuhf2lZ8qkE3x5qd3PHbh3rfr8@/bw5QHiO3WzeBA4iptXHq1u/pyBBxq7w9WrvrctXy7dhRDG7f@i3@2bTsOtZeurtmEIRgoEK1YCeCgxiBRqqGAEpBWKiBChEASWmECXBwAJHGhRR6AF@dslJbQixDG4hSuOTk5qDRuSXLEyAEkdqci3wL89ZJ7VANSeU@J@o08Jj02N5Q26iSmykiMLL6K7q4uJ0l56aapLEIub8Dw "Wolfram Language (Mathematica) – Try It Online") Input a 3x3 matrix. [Answer] # [Haskell](https://www.haskell.org/), ~~100~~ 95 bytes * -5 bytes thanks to [Donat](https://codegolf.stackexchange.com/users/95987/donat). ``` f m=minimum[sum[1|7<-n]|n<-g m,a$sum.(g n!!)<$>[7,56,73,146,448]] g=mapM(:[7]) a(x:y)=all(==x)y ``` [Try it online!](https://tio.run/##TVBBasMwELz7FUrIQQbFxFacOMFqTz32BUIUEWzX1FJD5EACufcRfUOvpffS5lmusotMYbXMamZ2V3rW7qXqumGoiRGmta05Gun8SS/rcm7VxZbzhhimZ/4yoQ2xk0mc1IdX82CPppzdTe@/338@fj@vb9evqYoaYfT@kW7lWsWRpqftORa666gQp/g89JXrd9pVTki5YWTJCIfwAMvCZ8VkzkgaOA@wzHz2HAftCrQ5RAHWBfp4kG8AYA/uuQLQAuT/820ezsggo2@FbpyHwjSYcLUCOaTHkRi55zLYKg9bLEMUY08ODXl4w02kVGR0a@ETn@j@0No@qePx24Y/ "Haskell – Try It Online") The relevant function is `f`, which takes the flattened matrix `m` as input as list of `Int`'s. ## How? The real star of this answer is `g=mapM(:[7])`. What is this Haskell magic? Let's start by describing what `mapM` does. `mapM` takes as input a function `f::a->[b]` and a list `l::[a]`, applies `f` to every element of `l` (thus obtaining a list of lists `::[[b]]`), and then returns the cartesian product of these lists. To get a better intuition, consider what happens when we call `mapM(:[7])[2,3,4]`. First we apply `(:[7])` to each element of `[2,3]`, getting `[[2,7],[3,7],[4,7]]` as a result; then we take the cartesian product, resulting in ``` [[2,3,4],[2,3,7],[2,7,4],[2,7,7],[7,3,4],[7,3,7],[7,7,4],[7,7,7]] ``` It should be clear from this example that the function `g`, applied to a list `l`, returns all the lists that can be obtained from `l` by replacing some elements with a `7`. Unsurprisingly, this is exactly what we need for the first step of the solution (i.e. applying `g` to the flattened input matrix `m`); however, a bit more surprisingly, the function `g` will also come in handy later. --- Now that we know how to *summon the sevens*, we need a way to check if the rows and columns of a given matrix all have the same sum. Dealing with row/column sums in a flattened matrix can be surprisingly cumbersome in Haskell, so we'll have to be somewhat creative. The relevant piece of code is ``` a$sum.(g n!!)<$>[7,56,73,146,448] ``` `a` is simply a function to check whether all the elements of a list are the same (defined later as `a(x:y)=all(==x)y`, not particularly exciting). The interesting part of the code is ``` a$sum.(g n!!)<$>[7,56,73,146,448] ``` , which is basically finding the sum of some specific lists in `g n` (namely, the one in position `7`, the one in position `56` and so on). What's so special about these positions? Assuming `n≡[n0,n1,...,n7,n8]`, the `7`-th element of `g n` is `[n0,n1,n2,n3,n4,n5,7,7,7]`. Similarly, here is a list of the elements of `g n` we are considering. | `i` | `i`-th element of `g n` | | --- | --- | | `7` | `[n0,n1,n2,n3,n4,n5,7 ,7 ,7 ]` | | `56` | `[n0,n1,n2,7 ,7 ,7 ,n6,n7,n8]` | | `73` | `[n0,n1,7 ,n3,n4,7 ,n6,n7,7 ]` | | `146` | `[n0,7 ,n2,n3,7 ,n5,n6,7 ,n8]` | | `448` | `[7 ,7 ,7 ,n3,n4,n5,n6,n7,n8]` | With some algebra, it's easy to see that the sums of these five lists are all equal if and only if the sums of all the rows and columns of `n` are equal. --- Sorry, the clever part is over, the definition of `f` is moderately boring. ``` f m= -- f is a function that takes a flattened matrix m minimum[ -- and returns the minimum of sum[1|7<-n]| -- the numbers of 7's in n (sum 1 for each 7 in n), where n<-g m, -- n is an element of g m a$sum.(g n!!).fromEnum<$>"?ÛŭƶLJǸ"] -- all the sums of rows and columns of n are equal ``` To compensate, here is a fun fact: most of the other solutions posted here have a time complexity of \$O(2^{n^2})\$ (up to a polynomial in \$n\$), while this answer runs in \$O(4^{n^2})\$, where \$n\$ is the number of rows/columns of the input matrix. ]
[Question] [ In this challenge, you will receive an input, convert it to hexadecimal, make a couple changes, and output the result. Because they are only 16 characters in hexadecimal, your code will need to be as short as possible. --- ## Examples Examples are separated by a blank line. First line is input, second line shows the steps, third shows the output ``` 234589 234589 -> 3945D -> 39454 -> 9A1E -> 9115 -> 239B -> 2392 -> 958 958 435234 435234 -> 6A422 -> 61422 -> EFEE -> 5655 -> 1617 1617 153 153 -> 99 -> 99 -> 63 1617 ``` ## Steps The input will always be a positive integer --- In order to generate the output you will follow the following steps: 1. Convert the input to hexadecimal 2. Replace any letters with their index in the alphabet (e.g. `a -> 1, b -> 2`) 3. Convert the result back to hexadecimal 4. If the result contains any letters, go to step 2. If not, output the result --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins! [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 18 bytes ``` b⁴µ:⁵©+¹%⁵ḅ⁵ß¹®S¤? ``` [Try it online!](http://jelly.tryitonline.net/#code=YuKBtMK1OuKBtcKpK8K5JeKBteG4heKBtcOfwrnCrlPCpD8&input=&args=MjM0NTg5&debug=on) The binary, 18 byte version of the source code has the xxd dump ``` 0000000: 62 b6 8c 3a b7 85 2b 8e 25 b7 a3 b7 95 8e 88 53 83 3f b..:..+.%......S.? ``` and works with [this version of the Jelly interpreter](https://github.com/DennisMitchell/jelly/commit/dbdc6462dc7be2c33893ce6baba77f6bda4feb98). ### How it works ``` b⁴µ:⁵©+¹%⁵ḅ⁵ß¹®S¤? Define the main link -- Left input: a (number) b⁴ Convert from integer to base 16. µ Start a new, monadic link. :⁵ Divide all base 16 digits by 10. © Save the result in a register. +¹ Add the quotients to the base 16 digits. %⁵ Take all resulting sums modulo 10. ḅ⁵ Convert from base 10 to integer. ®S¤ Take the sum of the quotients from the list in the register. ? If the result is non-zero: ß Recursively call the main link. ¹ Else, apply the identity function. ``` `Ḍ` (decimal-to-integer) should have worked as a shorthand for `ḅ⁵`, but the latest version of Jelly at the time of this post had a bug that prevented me from using it. [Answer] # JavaScript ES6, ~~98~~ ~~92~~ ~~67~~ 64 bytes *Saved 3 bytes thanks to @Downgoat, 3 more thanks to @user81655* Found a much, much shorter version, ditching the loop for recursion: ``` h=x=>(y=x.toString(16))>(r=y.replace(/\D/g,z=>'0x'+z-9))?h(+r):r ``` Probably the most interesting part of this program is the `replace` function: ``` z=> // Implicit: z = one of "a", "b", "c", "d", "e", "f" '0x'+z // Add '0x' to the beginning of z. // If z == "a", this results in "0xa". -9 // Subtract 9. JavaScript automatically coerces the string to a number, // and because the prefix "0x" means "convert from hexadecimal", // the "a" is converted to 10, which then becomes 1 because of the subtraction. ``` ### Test snippet *(taken from [here](https://codegolf.meta.stackexchange.com/q/7113/42545))* ``` h=x=>(y=x.toString(16))>(r=y.replace(/\D/g,z=>'0x'+z-9))?h(+r):r ``` ``` <!-- Try the test suite below! --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");inputbox.value="234589";textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script> ``` [Answer] ## CJam, ~~21~~ 19 bytes ``` r{siGb_{(9%)}%_@#}g ``` [Test it here.](http://cjam.aditsu.net/#code=r%7BsiGb_%7B(9%25)%7D%25_%40%23%7Dg&input=749699) ### Explanation A *very* rare case of negative modulo results being helpful. :) ``` r e# Read input. { e# While the condition on top of the stack is truthy... s e# Convert to string. This is a no-op in the first iteration, but necessary e# on subsequent iterations. i e# Convert to integer. Gb e# Get base-16 digits. _{ e# Copy and map over the copy... ( e# Decrement. 9% e# Modulo 9. If the digit was originally in the range 0 to 9, it will remain e# unchanged because -1 % 9 == -1. If the digit was in 10 to 15, it will become e# 0 to 5, respectively. ) e# Increment. Undoes the decrement for unchanged digits and fixes the letter e# digits because A corresponds to 1, not 0. }% _ e# Duplicate result. @# e# Pull up original digits and try to find them in the array. This will be zero, e# i.e. falsy, if they are equal and -1, i.e. truthy, if they are not. }g ``` [Answer] # Ruby, 35 + 1 = 36 With command-line flag `p`, run ``` $_='%x'%$_ redo if$_.tr!'a-f','1-6' ``` Explanation: The -p flag creates a loop, storing the input and eventual output in the variable `$_`. `'%x'` does the hex conversion, and `tr!` does the digit substitution and returns a falsey value if there wasn't anything to change. redo starts over with the new `$_`. [Answer] # Julia, ~~78~~ 74 bytes ``` f(x)=(h=hex(x);isdigit(h)?h:f(parse(replace(h,r"[a-z]",c->Int(c[1])-96)))) ``` This is a recursive function that accepts an integer and returns a string. Ungolfed: ``` function f(x::Integer) # Get the hexadecimal representation of x as a string h = hex(x) # Check whether all characters are digits if isdigit(h) # Return the hexadecimal representation of the input h else # Replace each letter with its position in the alphabet, # parse as an integer, and call f on the result f(parse(replace(h, r"[a-z]", c -> Int(c[1]) - 96))) end end ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 23 ~~25~~ bytes ### Disclaimer *While writing this answer I noticed a bug in MATL's `dec2base` function, corrected it, and released a [new version](https://github.com/lmendo/MATL/releases/tag/3.1.0) with the correction (as well as a couple other accumulated, unrelated changes)*. *Since I am using a version which is later than this challenge, according to [consensus on Meta](https://codegolf.meta.stackexchange.com/q/5447/36398) this answer is not eligible for winning*. ### Code ``` i`0:15YAt9X\t10ZQbb=~a] ``` ### Example ``` >> matl i`0:15YAt9X\t10ZQbb=~a] > 234589 958 ``` ### Explanation ``` i % input number ` % do...while 0:15YA % convert number to representation with base defined by symbols 0,...,15 t9X\ % duplicate vector. Modulus 9 with 0 replaced by 9 t10ZQ % duplicate vector and convert to number using base 10 bb=~a % are second- and third-top stack elements different? (If so, next iteration) ] % end ``` [Answer] # Dyalog APL, 37 36 33 bytes ``` {∧/9≥X←16⊥⍣¯1⊢⍵:10⊥X⋄∇10(⊣⊥|+≤)X} ``` Thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) and [ngn](https://codegolf.stackexchange.com/users/24908/ngn) for suggestions. I'm keeping `16⊥⍣¯1⊢⍵` instead of `⍵⊤⍨⍴⍨16` - it's an extra byte, but allows us to operate on numbers of arbitrary size rather than 64-bit. [Answer] # Python, ~~118~~ 105 bytes ``` def f(n):h=hex(n)[2:];return h if h.isdigit()else f(int(''.join(map(lambda x:chr((ord(x)-47)%48+47),h)))) ``` [Answer] # PHP, ~~140~~ ~~126~~ ~~122~~ ~~114~~ ~~112~~ 87 or 84 bytes (including `-r`) Not entirely sure about how the rules around this as this is my first codegolf attempt, but the code can be run with `php -r` without needing `<?` and `?>` ### Code ``` $b=readline();while($c!=$b)$b=preg_replace('/\D/e','ord($0)-96',$c=dechex($b));echo$c ``` ### Formatted ``` $b=readline(); while($c!=$b){ $b=preg_replace('/\D/e','ord($0)-96',$c=dechex($b)); } echo "$b\n"; ``` ### Alternate Code (using argv instead of stdin) ``` for($b=$argv[1];$c!=$b;)$b=preg_replace('/\D/e','ord($0)-96',$c=dechex($b));echo$b ``` ### Formatted ``` for($b=$argv[1];$c!=$b;) { $b=preg_replace('/\D/e','ord($0)-96',$c=dechex($b)); } echo $b; ``` ### Notes Edit 1: I cut out a call to `intval()` to save 14 characters as PHP will happily treat numerical strings as numbers. Edit 2: I removed `\n` from the output that I forgot to remove after testing, and removed quote marks from the final echo to save a total of 4 characters. Edit 3: Removed the last call to `intval()` Edit 4: Saved 2 bytes by removing quote marks from the regex line Edit 5: Changed `[a-f]` to `\D` to save 3 characters, removed `strval` call from `preg_replace` for 8 more; added version that uses `argv[]` instead of STDIN, moved the loop terminator into the while statement(oops!) saving 11 more characters, and moved the dechex call into the `subject` part of `preg_replace` for another 3, making a total of 25; also added a non-stdin version as an alternate version that uses 3 less characters. Thanks for the help, @Blackhole [Answer] # [R](https://www.r-project.org/), ~~106~~ ~~103~~ 102 bytes -3 bytes by using `if` instead of `while` -1 byte thanks to Giuseppe using `as.double` instead of `as.integer` ``` a=function(y){x=as.hexmode(as.double(y)) if(grepl("[a-f]",x)){x=chartr("a-f","1-6",x);return(a(x))};x} ``` [Try it online!](https://tio.run/##FYsxCoAwEAR7n3HVBVSwsZG8RCwOPU0gRjkjRsS3x9gNOzuSEun59GOwm8dbPVHTURuO6zYxZrQ@8MKSlSouYx3jIrw7hJ6qeYAyqr8ZDUkQhLxBCU3V/qITDqd4JMynt4tvSh8 "R – Try It Online") Just add `a(your_integer_here)` to the TIO to see the result. ``` > a(234589) [1] "958" > a(435234) [1] "1617" > a(99999) [1] "4908" ``` I used recursion to reapply the function to each successive iteration, on the condition that it doesn't find any of the letters 'abcdef' within the string, when this condition is False, it outputs the result as a string. The best part was my discovery of the `chartr` function, which allows me to swap elements with corresponding elements in a string. This string comes from the function coercing the hexadecimal into a string format. Edit: I tried to use `sprint("%x",y)` instead of `as.hexmode(as.double(y))`, but I am still required to use `as.double` somewhere in the code, which was ~~2~~ 1 byte longer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` h[Au₂L‡hÐþQ# ``` [Try it online](https://tio.run/##yy9OTMpM/f8/I9qx9FFTk8@jhoUZhycc3heo/P@/kbGJqYUlAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/jGjH0kdNTT6PGhZmHJ5weF@g8v9anf/RRsYmphaWOgomxqZApo6CuYmlmSWQb2hqDCQMDGIB). **Explanation:** ``` h # Convert the (implicit) integer-input to a hexadecimal string # i.e. 234589 → "3945D" [ # Start an infinite loop: Au # Push the uppercase alphabet "ABC...XYZ" ₂L # Push a list in the range [1,26] ‡ # Transliterate: replace all letters with the integers at the same index # i.e. "3945D" → "39454" # i.e. "239B" → "2392" h # Convert the integer to a hexadecimal string again # i.e. "39454" → "9A1E" # i.e. "2392" → "958" Ð # Triplicate it þ # Leave only the digits of the last copy # i.e. "9A1E" → "91" # i.e. "958" → "958" Q # Check if these digits and the hexadecimal string are equal # i.e. "9A1E" and "91" → 0 (falsey) # i.e. "958" and "958" → 1 (truthy) # # And if they are: stop the infinite loop # (and output the remaining copy from the triplicate implicitly as result) ``` `ÐþQ` could alternatively be `D.ï` (`D`: Duplicate; `.ï`: is\_int?) for the same byte-count. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 92 bytes ``` n=>{var s=$"{n:x}";for(;(s=$"{s.Aggregate(0,(a,c)=>10*a+c%48):x}").Any(c=>c>57););return s;} ``` [Try it online!](https://tio.run/##Pc3dCsIgAAXg@55CRoHW2mbO/WQKu@m6VxDZZDcG6qIYe3ZzETuX5ztwlDsrN4b7ZNRtND513o5Gi4EHw8X8khY4vk9mc30vCRueFjL4K1zWaW17LX0PixTKVCEucHGUJ3UoG7TOUdaZD1RcKEFrxBCzvZ@sAY4tge0e8cfDAV5ISZsWIQbyHLS02aAkNNofcIXrTTAlax0TpSLhCw "C# (Visual C# Interactive Compiler) – Try It Online") Less golfed code: ``` // anonymous function with // input integer n // output is a string n=>{ // 1) Convert the input to hexadecimal var s=$"{n:x}"; for(; (s=$"{ // 2) replace letters with their index in the alphabet s.Aggregate(0,(a,c)=>10*a+c%48) // 3) Convert the result back to hexadecimal :x}" // 4) If the result contains any letters, go to step 2 ).Any(c=>c>57);); // If not, output the result return s; } ``` [Answer] ## Mathematica, 107 bytes ``` (b=FromDigits)@NestWhile[b[#/.Thread[10~Range~15->Range@6]]~a~16&,#~(a=IntegerDigits)~16,MemberQ[a_/;a>9]]& ``` Can't think of any more ways to golf this... [Answer] ## Mathematica, 80 bytes ``` i=IntegerDigits;f=FromDigits;f[#~i~16//.l_/;Max@l>9:>f[If[#>9,#-9,#]&/@l]~i~16]& ``` This uses a neat trick for while-loops I learned from alephalpha. The `//.` is "apply this substitution rule as often as possible". Then we use a pattern, `l_/;Max@l>9` which only matches if the hexadecimal digit list still contains digits greater than 9. [Answer] # Japt, ~~45~~ 40 bytes Based on my JS answer: ``` I=_nG -9}H=_=ZsG)f/\D/ ?H$($ÂZr"\\D"I):Z ``` Pretty pathetic for a golfing language, huh? There seems to be a lot of folks realizing during this challenge that their interpreters have bugs, and I am now included among them. This *should* be able to be done in 30 bytes or less, but a bug makes this impossible. This creates a function `H` that can be called like so: ``` I=_nG -9}H=_=ZsG)f/\D/ ?H$($ÂZr"\\D"I):Z} $H(234589)$ ``` Alternatively, here is a full program, taking input from STDIN: ``` I=_nG -9}H=_=ZsG)f/\D/ ?H$($ÂZr"\\D"I):Z}H$(U ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=ST1fbkcgLTl9SD1fPVpzMTYpZi9cRC8gP0gkKCTCWnIiXFxEIkkpOlp9SCQoVQ==&input=MjM0NTg5) [Answer] # GNU Sed (with eval extension), 44 ``` : y/ABCDEF/123456/ s/^/printf %X /e /[A-F]/b ``` I wish `sed` would allow `y/A-F/1-6/`. But it doesn't. [Answer] # Python 3, ~~101~~ 89 bytes Overall, this is quite similar to [Boomerang's solution](https://codegolf.stackexchange.com/a/67147/13959), but it takes a few different approaches to various aspects. ``` def d(n):n=hex(int(n))[2:];return n.isdigit()and n or d(str([ord(c)%12for c in n])[1::3]) ``` This is the expanded version of my original code: ``` def d(n): n = int(n) # Interpret input as a decimal integer. n = hex(n)[2:] # Convert it to hex, stripping the '0x'. if n.isdigit(): # If every character is a digit... return n # ...we're done. else: # Otherwise... n = ''.join(c if c < ':' else # ...don't change digits (':' is after chr(ord(c - 48)) # '9'), but do change letters ('1' is 48 for c in n) # characters before 'a'). return d(n) # Then follow the process again. ``` 11 bytes were shed thanks to @pacholik (replacing the innards of the `join` with a single operation that worked for both digits and letters). Another byte was trimmed by replacing the `join` with a string-slicing trick that hit me in a lightbulb moment (but which [already exists in the Python golfing tips](https://codegolf.stackexchange.com/a/49791/13959), albeit under a heading that specifies Python 2). [Answer] # Java, 201 bytes ``` String f(int a){String s=Long.toString(a,16);while(s.matches(".*[a-z].*")){char[]b=s.toCharArray();for(int i=0;i<b.length;i++)if(b[i]>96)b[i]-=48;s=Long.toString(new Long("".valueOf(b)),16);}return s;} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 21 bytes ``` ìG ®+zA eV ?U:ßVmuA ì ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=7EcKrit6QQplViA/VTrfVm11QSDs&input=WzIzNDU4OQo0MzUyMzQKNzQ5Njk5XQotbVE=) A significant improvement over the existing Japt answer. It doesn't handle the `153 -> 63` case proposed in a comment, but none of the other answers seem to either so I'll leave it unless the OP clarifies. Output as a list of decimal digits, could be changed to outputting a decimal number for [1 byte](https://ethproductions.github.io/japt/?v=1.4.6&code=7EcKrit6QQplViA/Vew631ZtdUEg7A==&input=WzIzNDU4OQo0MzUyMzQKNzQ5Njk5XQotbVE=) Explanation: ``` ìG #Get a list of base-16 digits, each as a base-10 number e.g. 234589 -> [3,9,4,5,13] ®+zA #Increment the numbers greater than 10 e.g. [3,9,4,5,13] -> [3,9,4,5,14] eV ? #If the second step didn't change any digit: U # Output the digits from step 1 : #Otherwise ß # Repeat the program with new input: V # The result of step 2 muA # With each digit modulo 10 ì # Treated as a base-10 number ``` [Answer] # APL(NARS) 104 chars, 208 bytes ``` f←{k←10⊥{⍵≤9:⍵⋄1+10∣⍵}¨q←{(16⍴⍨⌊1+16⍟⍵)⊤⍵}⍵⋄9≥⌈/q:k,0⋄k,1} t←{⍵≤0:0⋄0=2⊃v←f⍵:↑f↑v⋄{k←f⍵⋄0=2⊃k:↑k⋄∇↑k}⍵} ``` test: ``` t 153 63 t 0 0 t 234589 958 t 435234 1617 t ¯123 0 ``` I don't know if it is ok... Possible it is not enough for the standard quality answer... [Answer] ## Seriously, 42 bytes ``` 1╤╝4ª╗,$1WX╛@¿╜@¡;`╜@¿;)╛;(\(+%$`Mεj;)=YWX ``` Hex Dump: ``` 31d1bc34a6bb2c24315758be40a8bd40ad3b60bd40 a83b29be3b285c282b2524604dee6a3b293d595758 ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=31d1bc34a6bb2c24315758be40a8bd40ad3b60bd40a83b29be3b285c282b2524604dee6a3b293d595758&input=234589) There has to be a shorter way than this, but this is what I got... (This is where I find myself wishing `W` actually popped, since it's shorter to put a `;` right before the last one when you DON'T want it to than to put an `X` after EACH `W`. Here, having `W` pop instead of peek would save three bytes.) [Answer] # Japt, 18 bytes ``` Æ=ìG ®%9ª9Ãì)sGÃæÑ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=xj3sRyCuJTmqOcPsKXNHw+bR&input=MjM0NTg5) [Answer] # PHP, 71 bytes ``` while($n++<2|$b-$a=&$argn)$a=strtr($b=dechex($a),abcdef,123456);echo$a; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/1b8c705fe2848cd0728afdbf7dd95497e5846a13). Yields a warning for some inputs in PHP 7.1 and later; replace `-` with `!=` to fix. Yields another warning in PHP 7.2; put `abcdef` in quotes to fix. ]
[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/1696/edit). Closed 6 years ago. [Improve this question](/posts/1696/edit) **Bounty is over, thephpdeveloper wins with Conway's Game of Life** The web platform today is advancing at a rapid rate. Features like [CSS3 animations](http://www.w3.org/TR/css3-animations/), [transforms](http://www.w3.org/TR/css3-2d-transforms/), [drop shadows](http://www.w3.org/TR/css3-background/) and [gradients](http://www.w3.org/TR/css3-background/), [`<canvas>`](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element), [`<audio>`](http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#audio) and [`<video>`](http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#video) tags, [SVG](http://www.w3.org/Graphics/SVG/), [WebGL](http://www.khronos.org/webgl/wiki/Main_Page), and many more mean that you can do far more in the browser, and in far less code, than ever before. Of course, many developers don't get to use those new features, because the sites and applications they work on need to be backwards compatible with ancient, moth-eaten browsers like IE6. So, what happens if you take the harness off? Allow yourself to use any and all new features that you like? Live a little, go crazy, use weird bleeding edge features that only 1% of your users will be able to take advantage of? Of course, with unlimited resources and the ability to talk to a server, you can do all manner of things—load megabytes of code and libraries and videos, and so on—but challenges aren't very interesting without constraints. The major constraint for this contest is: what can you do in a single, self-contained, 4k [`data:` URI](https://www.rfc-editor.org/rfc/rfc2397)? Self-contained means it must not refer to any external resources, connect to any servers using WebSockets or XHR, or anything of the sort. If you want to embed resources like PNGs or MP3s, feel free to include data URIs within your data URI, or come up with some other clever way of embedding sub-resources. 4k means 4096 bytes, properly URI-encoded, ASCII text (you may use a base64 encoded data URI if you choose, to avoid URI encoding, but usually URI encoded text will be smaller than base64 for plain text). To provide inspiration, the theme of the contest is [StackOverflow memes](https://meta.stackexchange.com/questions/19478/the-many-memes-of-meta). Create a unicorn-jousting game, a Jon Skeet fact generator, a freehand-circle based drawing program, or anything to do with one of the popular StackOverflow & meta.so memes. I would encourage entries that are interactive in some way; not just a simple animation or static image, they should respond to user input, whether through events, CSS hover, scrolling, browser window resizing, or any other way you can think of. This is not a hard requirement, though; great demos that are not interactive will be considered, though interactivity would be preferred. Your entry must run in at least one public release of at least one of the 5 major browsers (IE, Firefox, Chrome, Safari, Opera). Only mainline releases (not builds from branches or builds that require patches), with no special configuration settings, plugins, or anything else that does not come with the stock browser are allowed. Nightly builds, betas, and release candidates are fine. Please specify in your entry which browsers you've tested your entry with. There are no limitations on what technologies you may use within those constraints; you may do a pure SVG animation, a pure CSS animation, something in JavaScript using WebGL, or heck, even something that uses XML and XSLT if that strikes your fancy. If you can cram it into a valid data URI, with no external dependencies, and get a browser to run it, it's fair game. To add to the competition here, on Monday, March 21, I will open a bounty on this question. How can I afford a bounty when I have only 101 rep? Well, all rep I gain from upvotes to this question between now and Monday will go into the bounty (up to the limit of 500 allowed for a single bounty; it would be pretty hard for me to hit that limit, though, given the rep cap). Entries will be accepted for 6 days after that; all entries must be in at least 24 hours before the bounty expires, to give me time to check them all out and evaluate them. At that point, I will accept the highest voted answer, and give the bounty to my favorite answer (which may or may not be the same as the highest voted). My criteria for awarding the bounty will include beauty, fun, clever technique, interesting use of new features, interactivity, and size. People should vote based on any criteria they want, as long as the entries meet the rules. Here are some sources of inspiration, to get you started: * [Chrome Experiments](http://www.chromeexperiments.com/), a collection of demonstrations of the modern web platform * [Mozilla Hacks](http://hacks.mozilla.org/), a blog about the modern web platform with many demos of new features in Firefox 4 * [JS1k](http://js1k.com/), a contest for 1k JavaScript demos * [10k Apart](http://10k.aneventapart.com/), a webapp in 10k contest * [gl64k](http://gl64k.com/), a demo contest currently running for 64k WebGL demos * [Shader Toy](http://www.iquilezles.org/apps/shadertoy/), a set of demos of what you can do with WebGL shaders Format for entries: > > **Name of entry** > > > > ``` > data:text/html,Your%20data%20URI > ``` > > *Works in Firefox 4 RC, Chrome 10, and Opera 11* > > > Description of your entry; what it does, why it's neat, what clever techniques you used. > > > > ``` > <script> > // code in expanded form to more easily see how it works > </script> > > ``` > > Any credits for inspirations, any code you might have borrowed from, etc. > > > (StackExchange appears not to accept data URIs in links, so you'll need to embed it directly in a `<pre>` tag) [Answer] # SO meme: [Everything is a meme](https://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/21224#21224) > > Everything is a meme. enough said. > > > ## Conway's Game of Life, HTML5+CSS3+JS, ### 3,543 3,561 3,555 bytes ``` data:text/html,<!DOCTYPE%20html>%0A<html><head><title>Conway's%20Game%20of%20Life%20by%20Sam-Mauris%20Yong</title><style>body{margin:20px;padding:0;font:12px/1.6%20tahoma,sen-serif;}.clr{clear:both}#ftr{padding:10px;border-top:1px%20solid%20#DDD;margin-top:10px}input[type="submit"],input[type="button"],a.btn,a.btn:visited{color:#999;-moz-border-radius:5px;-webkit-border-radius:5px;border:1px%20solid%20#EEE;color:#333;cursor:pointer;padding:4px%208px;text-decoration:none;border:1px%20solid%20#EEE;background-color:#DDD}input[type="submit"]:hover,input[type="button"]:hover,a.btn:hover{background-color:#666;border:1px%20solid%20#EEE;color:#EEE;text-shadow:#000%201px%201px%200}a.btn.%20a.btn:visited{padding:5px%208px}input[type="submit"]:focus,input[type="button"]:focus,a.btn:focus{outline:none;border:1px%20solid%20#099}</style></head><body><h1>Conway's%20Game%20of%20Life</h1><canvas%20id="c"%20width="800"%20height="600"></canvas><div%20class="clr"></div><div%20style="margin-top:5px;"><input%20type="button"%20value="Start"%20id="ctrlStart"><input%20type="button"%20value="Stop"%20id="ctrlStop"><input%20type="button"%20value="Next"%20id="ctrlNext"></div><div%20id="ftr"><i>App%20requires%20awesome%20browsers%20supporting%20HTML5.</i><br>Written%20by%20@<a%20href="http://twitter.com/thephpdeveloper">thephpdeveloper</a>%20aka%20Sam-Mauris%20Yong.</div><script>eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return%20r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new%20RegExp('\\b'+e(c)+'\\b','g'),k[c]);return%20p}('7%20$(b){j%20Q.R(b)}7%20p(b){j%20S(b)}5%20k=$("c");5%20a=k.T("U");5%209={x:V,y:W};5%20s=10;5%206=t%20B(9.x);5%20X=Y;5%20i=-1;l(i++<6.h-1){6[i]=t%20B(9.y)}7%20C(b,c){a.D="Z";a.E(b*s,c*s,s,s);a.F="11";a.G(b*s,c*s,s,s)}7%20u(b){5%20c=t%2012();4(g(b)=="H"){4(g(b.h)!="I"){5%20c=[]}13(5%20d%2014%20b){4(g(b[d])=="H"){c[d]=u(b[d])}v{4(g(b[d])=="15"){c[d]=b[d]}v{4(g(b[d])=="16"){c[d]=b[d]}v{4(g(b[d])=="17"){((b[d]==m)?c[d]=m:c[d]=n)}}}}}}j%20c}7%208(b){j%20g(b)=="I"||!b?n:m}7%20J(b,d){5%20c=0;4(b>0){4(8(6[b-1][d])){c++}4(d>0){4(8(6[b-1][d-1])){c++}}4(d<9.y-1){4(8(6[b-1][d+1])){c++}}}4(b<9.x-1){4(8(6[b+1][d])){c++}4(d>0){4(8(6[b+1][d-1])){c++}}4(d<9.y-1){4(8(6[b+1][d+1])){c++}}}4(d>0){4(8(6[b][d-1])){c++}}4(d<9.y-1){4(8(6[b][d+1])){c++}}j%20c}7%20K(){5%20d=u(6);5%20c=0;l(c<6.h){5%20f=0;l(f<6[c].h){5%20b=6[c][f];5%20e=J(c,f);4(e<2||e>3){d[c][f]=n}4(e==3){d[c][f]=m}f++}c++}6=d}7%20o(){a.D="#18";a.E(0,0,p(k.19),p(k.1a));5%20b=0;l(b<6.h){5%20c=0;l(c<6[b].h){a.F="#1b";a.G(b*s,c*s,s,s);4(6[b][c]){C(b,c)}c++}b++}}5%20q;7%20w(){K();o()}7%20L(){q=M.1c(w,1d)}7%20N(){q=M.1e(q)}7%20z(c){4(r){5%20b=O.P((c.1f-p(k.1g))/s);5%20d=O.P((c.1h-p(k.1i))/s);6[b][d]=!6[b][d];o()}}5%20r=n;o();k.1j=7(b){r=m};k.1k=7(b){z(b)};k.1l=7(b){z(b);r=n};$("1m").A=N;$("1n").A=w;$("1o").A=L;',62,87,'||||if|var|space|function|evalbool|max|||||||typeof|length||return||while|true|false|draw||time_var|dodrawing||new|deepObjCopy|else|next|||editorDraw|onclick|Array|drawCell|fillStyle|fillRect|strokeStyle|strokeRect|object|undefined|countAliveNeighbours|update|start|window|stop|Math|floor|document|getElementById|parseInt|getContext|2d|80|60|lastSpace|null|black||white|Object|for|in|string|number|boolean|fff|width|height|ccc|setInterval|250|clearInterval|pageX|offsetLeft|pageY|offsetTop|onmousedown|onmousemove|onmouseup|ctrlStop|ctrlNext|ctrlStart'.split('|'),0,{}))</script></body></html> ``` This is [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) written myself for HTML5 with canvas and CSS3. I wrote it for fun during the period of 10K Apart competition but I did not submit this for the competition. Base64 encoded version spans over 4.61KB of data, whereas the original version is ~3543 bytes. **To compress the size**: Javascript code minified by [YUI online compressor](http://refresh-sf.com/yui/), then by [Dean Edwards' packer](http://dean.edwards.name/packer/). CSS Code minified by [YUI online compressor](http://refresh-sf.com/yui/). Uses jQuery library from Google API Library. Valid HTML5 and CSS3 (experimental version of the w3 validator). To play: * Black box represents a live cell, white represents dead cell. * Click on a box to mark a live cell, click again to mark it dead. * Press `<Start>` to run the simulation, `<Stop>` to pause, and `<Next>` to show the next step * Runs awesome on Internet Explorer 9, Firefox 4 (and Firefox 3 as well), Safari 5, and Google Chrome. The human-readable (robots shall die) version: ``` <!DOCTYPE html> <html> <head> <title>Conway's Game of Life by Sam-Mauris Yong</title> <style> body{ margin:20px; padding:0; font:12px/1.6 tahoma,sen-serif; } .clr{ clear:both } #ftr{ padding:10px; border-top:1px solid #DDD; margin-top:10px } input[type="submit"],input[type="button"],a.btn,a.btn:visited{ color:#999; -moz-border-radius:5px; -webkit-border-radius:5px; border:1px solid #EEE; color:#333; cursor:pointer; padding:4px 8px; text-decoration:none; border:1px solid #EEE; background-color:#DDD } input[type="submit"]:hover,input[type="button"]:hover,a.btn:hover{ background-color:#666; border:1px solid #EEE; color:#EEE; text-shadow:#000 1px 1px 0 } a.btn,a.btn:visited{ padding:5px 8px } input[type="submit"]:focus,input[type="button"]:focus,a.btn:focus{ outline:none; border:1px solid #099 } </style> </head> <body> <h1>Conway's Game of Life</h1> <canvas id="c" width="800" height="600"></canvas> <div class="clr"></div><div style="margin-top:5px;"> <input type="button" value="Start" id="ctrlStart"> <input type="button" value="Stop" id="ctrlStop"> <input type="button" value="Next" id="ctrlNext"> </div> <div id="ftr"> <i>App requires awesome browsers supporting HTML5.</i> <br> Written by @<a href="http://twitter.com/thephpdeveloper">thephpdeveloper</a> aka Sam-Mauris Yong. </div> <script> function $(i){ return document.getElementById(i); } function p(v){ return parseInt(v); } var k = $("c"); var a = k.getContext('2d'); var max = { x: 80, y: 60 }; var s = 10; var space = new Array(max.x); var lastSpace = null; var i = -1; while(i++ < space.length - 1){ space[i]= new Array(max.y); } function drawCell(x,y){ a.fillStyle = "black"; a.fillRect(x * s, y * s, s, s); a.strokeStyle = "white"; a.strokeRect(x * s, y * s, s, s); } function deepObjCopy (dupeObj) { var retObj = new Object(); if (typeof(dupeObj) == 'object') { if (typeof(dupeObj.length) != 'undefined') var retObj = []; for (var objInd in dupeObj) { if (typeof(dupeObj[objInd]) == 'object') { retObj[objInd] = deepObjCopy(dupeObj[objInd]); } else if (typeof(dupeObj[objInd]) == 'string') { retObj[objInd] = dupeObj[objInd]; } else if (typeof(dupeObj[objInd]) == 'number') { retObj[objInd] = dupeObj[objInd]; } else if (typeof(dupeObj[objInd]) == 'boolean') { ((dupeObj[objInd] == true) ? retObj[objInd] = true : retObj[objInd] = false); } } } return retObj; } function evalbool(v){ return typeof(v) == 'undefined' || !v ? false : true; } function countAliveNeighbours(x,y){ var l = 0; // left side if(x > 0){ if(evalbool(space[x-1][y])){ l++; } if(y > 0){ if(evalbool(space[x-1][y-1])){ l++; } } if(y < max.y-1){ if(evalbool(space[x-1][y+1])){ l++; } } } // left side // right side if(x < max.x - 1){ if(evalbool(space[x+1][y])){ l++; } if(y > 0){ if(evalbool(space[x+1][y-1])){ l++; } } if(y < max.y-1){ if(evalbool(space[x+1][y+1])){ l++; } } } // right side if(y > 0){ if(evalbool(space[x][y-1])){ l++; } } if(y < max.y-1){ if(evalbool(space[x][y+1])){ l++; } } return l; } function update(){ var t = deepObjCopy(space); var x = 0; while(x < space.length){ var y = 0; while(y < space[x].length){ var cell = space[x][y]; var nalive = countAliveNeighbours(x,y) if(nalive < 2 || nalive > 3){ t[x][y] = false; } if(nalive==3){ t[x][y] = true; } y++; } x++; } space = t; } function draw(){ a.fillStyle = "#fff"; a.fillRect(0, 0, p(k.width), p(k.height)); var x = 0; while(x < space.length){ var y = 0; while(y < space[x].length){ a.strokeStyle = "#ccc"; a.strokeRect(x*s, y*s, s,s); if(space[x][y]){ drawCell(x, y); } y++; } x++; } } var time_var; function next(){ update(); draw(); } function start(){ time_var = window.setInterval( next, 250); } function stop(){ time_var = window.clearInterval(time_var); } function editorDraw(e){ if(dodrawing){ var x = Math.floor((e.pageX-p(k.offsetLeft))/s); var y = Math.floor((e.pageY-p(k.offsetTop))/s); space[x][y] = !space[x][y]; draw(); } } var dodrawing = false; draw(); k.onmousedown = function(e){ dodrawing=true; } k.onmousemove = function(e){ editorDraw(e); } k.onmouseup = function(e){ editorDraw(e); dodrawing=false; } $("ctrlStop").onclick = stop; $("ctrlNext").onclick = next; $("ctrlStart").onclick = start; </script> </body> </html> ``` A class in history: 1. Modified to remove dependency from jQuery as well as URI-encoding all spaces. Improved code in many ways (that I can't remember of). 2. Fixed bug in calculation of alive neighbours and refactored some code to reduce size. [Answer] Sorry to dig up an old thread, but I saw this challenge on the side bar and I just couldn't resist. I don't mind that the challenge is over really, it was just fun coming up with something. Maybe we could have another round? Anyway, my submission: ## Edit Sorry to dig this up *again*, but it was bothering me for ages that I couldn't get this under 1KB. Now I've done it! # Interactive, Shaded Cube: ## 960 987 1082 1156 1182 1667 1587 bytes!, HTML+CSS3+JS ``` data:text/html,<script>X='position:absolute;',S=Math,l=S.sin,V=S.cos,D='style',$='getElementsByTagName',E=H=G=(L=K=99)/2,q=-G,j=1e4,Y=',';function _(p,r,D){A=[],B=l(r),C=V(r);for(z=6;z--;)v=z*3,A.unshift({x:l(D)*(B*p[v+1]+C*p[v+2])+V(D)*p[v]+K,y:C*p[v+1]-B*p[v+2]+K});return A}function R(a,b,c){F=x[v++],a=N[a],b=N[b],c=N[c];F.setAttribute(D,X+'-webkit-transform:matrix('+(a.x-b.x)/L+Y+(a.y-b.y)/L+Y+(c.x-b.x)/L+Y+(c.y-b.y)/L+Y+b.x+Y+b.y+');opacity:'+(((b.y-a.y)/(b.x-a.x)-(c.y-a.y)/(c.x-a.x)<0)^(a.x<b.x^a.x>c.x)));F[$]('b')[0][D].background='rgb(0,'+(d(a,c)+d(a,b))+',0)';return R}function d(P,O){W=P.x-O.x,Q=P.y-O.y;return S.sqrt(W*W+Q*Q)|0}onload=function(){P=document;for(o=6;o--;)P.body.appendChild(P.createElement('P')).innerHTML='<b '+D+'="'+X+'width:99;height:99"></b>';x=P[$]('p');onmousemove=function(e){J=e.pageX-K;U=e.pageY-K};setInterval(function(){N=_([q,q,q,G,G,q,q,G,q,q,q,G,G,q,G,G,G,G],E+=J/j,H+=U/j);R(2,0,3)(5,1,2)(0,2,1)(4,3,0)(3,4,5)(1,5,4)})}</script> ``` Move your mouse. Works in Chrome (18.something, but should work on most recent ones). I golfed this pretty well, I saved a few characters using a trick I thought was pretty cool: Say you have the following: ``` function g(x){alert("hello "+x+"!")} g("dave");g("martin");g("alice");g("rose");g("bob");g("helen");g("jo"); ``` characters can be saved by returning the function within itself and doing the following: ``` function g(x){alert("hello "+x+"!");return g} g("dave")("martin")("alice")("rose")("bob")("helen")("jo"); ``` Savings depends on how many function calls you have. This is probably better for obfuscation rather than golfing though. I also saved a characters by replacing `1000` with `1e4`, giving the `Math` class, and some of its functions, aliases. Using variables for repeated strings (quite hard to find some of these saves). Also, I had the word `style` in my code a few times; some of them were strings and others were identifiers like `element.style.whatever`. Assigning the string to a variable (`D='style`) allowed me to replace the strings with `D` and to replace the identifiers like so `element[D].whatever`. Latest Edit: sorry to bring up an old comp', but some ideas how to shorten this just came to me! [Answer] ## JavaScript 489 chars This plays Guess a Number game. ``` data:text/html,<!DOCTYPE%20html><html><body><h1>Guess the number between 0 and 100</h1><p id="p">good luck</p><form><input id="i" type="text"></input></form><br><button onclick="h()">Try</button><script>var r=Math.round(100*Math.random());function h(){var a=document.getElementById("i").value;var anum="/(^\d+$)/";var res="is not a number!";if (!isNaN(a)){if(a<r) res="higher";else if(r<a) res="lower";else res="you win";}document.getElementById("p").innerHTML=res;}</script></body></html> ``` I worked it out with this code: ``` <!DOCTYPE html> <html> <head> </head> <body onload="g()"> <p id="p"></p> <script> f=function(x){ var y=x.replace(" ","%20"); window.location.assign("data:text/html,"+y); } g=function(){ var a="<!DOCTYPE html><html><body><h1>Guess the number between 0 and 100</h1><p id=\"p\">good luck</p>"+ "<form><input id=\"i\" type=\"text\"><\/input></form>" +"<br><button onclick=\"h()\">Try<\/button><script>" +document.getElementById("s").innerHTML+ "<\/script><\/body><\/html>"; f(a); } </script> <script id="s"> var r=Math.round(100*Math.random()); function h(){ var a=document.getElementById("i").value; var anum="/(^\d+$)/"; var res="is not a number!"; if (!isNaN(a)){ if(a<r) res="higher"; else if(r<a) res="lower"; else res="you win"; } document.getElementById("p").innerHTML=res; } </script> </body> </html> ``` ]
[Question] [ [Programming Puzzles & Code Golf](https://codegolf.stackexchange.com/) is about to get a [new moderator](http://meta.codegolf.stackexchange.com/a/5749/26997), [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)! This challenge is a tribute to him and our other active (or recently active) moderators: [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob), [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner), and [Chris Jester-Young](https://codegolf.stackexchange.com/users/3/chris-jester-young). The challenge title is meant to be read to the tune of the [Pepto Bismol song](https://www.youtube.com/watch?v=XghJuH6GSCo). Basically, we're going to treat them all to pizza at [The Nineteenth Bite Pizzeria](https://chat.stackexchange.com/transcript/message/23740052#23740052), but we need to make sure they share it fairly because [some](https://chat.stackexchange.com/transcript/240?m=18791027#18791027) of [the](https://chat.stackexchange.com/transcript/240?m=19372677#19372677) mods are known to be pizza addicts! The pizzas sold by the pizzeria are all rectangular blocks of text. The width and length of a pizza may be any non-negative integers as long as their product is divisible by four. Each grid space in the block of text pizza represents a slice, so it's always possible to split the slices up into four equal groups. The mods will collectively order a single pizza, providing its width and length parameters to their server in any reasonable format such as `[width],[length]`. Just before the pizza arrives at their table, you need to label each slice with the initial of the mod who gets to eat it to ensure they all share fairly. Everyone should get the same number of slices. * `E` is for Dennis * `D` is for Doorknob * `M` is for Martin * `C` is for Chris The mods are a little persnickety, however, and require that their respective sets of slices be [path-connected](https://en.wikipedia.org/wiki/Connected_space#Path_connectedness), that is, that all their slices can be reached from one another by moving up, down, left, and right, not crossing anyone else's slices (and not moving diagonal). The don't care *how* you do this as long as it is done. Once you've accurately labeled each slice, deliver the pizza to the mods with an optional trailing newline. Your labeler may be a program or a function and can print or return the labeled pizza. The shortest labeler in bites wins. # Examples **Example 1** Order: `4,1` Some Possible Labeled Pizzas: ``` EDMC ``` ``` MEDC ``` ``` CDEM ``` **Example 2** Order: `4,4` Some Possible Labeled Pizzas: ``` MMMM CCCC DDDD EEEE ``` ``` DEMC DEMC DEMC DEMC ``` ``` CCCC DEEM DEEM DDMM ``` **Example 3** Order: `8,3` Some Possible Labeled Pizzas: ``` MMMMMMCC DDDDCCCC DDEEEEEE ``` ``` DDDCMMMM DCDCMEEE DCCCMEEE ``` **Example 4** Order: `20,5` A Possible Labeled Pizza: ``` DDDDDDDDDDDDMCCCCCCCCCCC DEEEEEEEEEEDMMMMMMMCCCCC DEEEEEEEEEEDMMMCCCCCCCCC DEEEEEEEEEEDMMMMMMMMCCCC DDDDDDDDDDDDMMMMMMMMMMMC ``` (The `D`'s here are not [simply-connected](https://en.wikipedia.org/wiki/Simply_connected_space) but that's ok.) [Answer] # CJam, 20 bytes ``` q~1$*4/"CEDM"e*/:$N* ``` I think this should work :) [Try it online](http://cjam.aditsu.net/#code=q~1%24*4%2F%22CEDM%22e*%2F%3A%24N*&input=8%203) **Explanation:** This first makes a pizza labeled CC…EE…DD…MM… from left to right and top to bottom, then sorts each row in alphabetical order. The only disconnections can happen between the C-E border and E-D border, or E-D border and D-M border (if they fall on adjacent rows). But the sorting ensures that the E's go to the right side and the D's go to the left side, as C<E>D<M, so the E's and the D's remain connected. ``` q~ read and evaluate the input 1$ copy the width *4/ multiply with the height and divide by 4 "CEDM"e* repeat each letter in "CEDM" that many times / split into rows of the given width :$ sort each row N* join with newlines ``` [Answer] # K, 61 bytes ``` {[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"} ``` Examples: ``` ryan@DevPC-LX:~/golf$ rlwrap k2 K 2.8 2000-10-10 Copyright (C) 1993-2000 Kx Systems Evaluation. Not for commercial use. \ for help. \\ to exit. `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[4;1] EDMC `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[4;4] EEEE DDDD MMMM CCCC `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[8;3] EEEEEEDD MMMMDDDD MMCCCCCC `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[20;5] EEEEEEEEEEEEEEEEEEEE DDDDDDDDDDDDDDDEEEEE DDDDDDDDDDMMMMMMMMMM CCCCCMMMMMMMMMMMMMMM CCCCCCCCCCCCCCCCCCCC ryan@DevPC-LX:~/golf$ ``` I would hate to be the person who has to slice these things... [Answer] # Pyth, ~~30~~ 25 bytes ``` jb.eu_GkbceQs*R/*FQ4"EDMC ``` [Live demo and all test cases](https://pyth.herokuapp.com/?code=jb.eu_GkbceQs*R%2F*FQ4%22EDMC&input=%5B8%2C3%5D&test_suite=1&test_suite_input=%5B4%2C1%5D%0A%5B4%2C4%5D%0A%5B8%2C3%5D%0A%5B20%2C5%5D&debug=1). Cut off 5 bytes thanks to @Jakube! Same algorithm as my K answer...but a *lot* shorter. 30-byte version: ``` jb.e?%k2_bbcjkm*/*FQ4d"EDMC"hQ ``` [Live demo and all test cases for 50-byte version](https://pyth.herokuapp.com/?code=jb.e%3F%25k2_bbcjkm*%2F*FQ4d%22EDMC%22hQ&input=%5B8%2C3%5D&test_suite=1&test_suite_input=%5B4%2C1%5D%0A%5B4%2C4%5D%0A%5B8%2C3%5D%0A%5B20%2C5%5D&debug=1). [Answer] # Pyth, 20 bytes ``` VceQs*L/*FQ4"CEDM"SN ``` Uses @aditsu's sorting trick. [Demonstration.](https://pyth.herokuapp.com/?code=VceQs*L%2F*FQ4%22CEDM%22SN&input=12%2C3&debug=0) I came up with a large number of alternative programs of the same length while trying to golf this: ``` VceQs*L/*FQ4"CEDM"SN VceQsCm"CEDM"/*FQ4SN VceQs*L*FQ"CEDM"%4SN VceQ%4s*L*FQ"CEDM"SN VcQs*L/*Qvz4"CEDM"SN (Newline separated input) jbSMceQs*L/*FQ4"CEDM Vcs*L/*FQ4"CEDM"hQSN ``` [Answer] # [Stuck](http://esolangs.org/wiki/Stuck), ~~42~~ 33 It returns! And in awfully long form. :( -- I stole aditsu's sort idea to save 9 bytes :) ``` t;g*4/[4*"CEDM"z"];F*":j0GK'$:Nj ``` ### Explanation: ``` t;g*4/ # Take |-separated input, # store the first value in var stack, # multiply the two numbers and divide by 4. [4*"CEDM"z # Wrap that value in an array, make 3 copies # to get a list of length 4, zip with "EDMC" "];F*":j0GK # For each item, multiply letter by value to # to get string, join the result, split into # segments the size of the saved variable. '$:Nj # For each item, sort so the letters are in the correct # order, join by newline, print. ``` ### Example input: ``` 20|5 ``` ### Example output: ``` CCCCCCCCCCCCCCCCCCCC CCCCCEEEEEEEEEEEEEEE DDDDDDDDDDEEEEEEEEEE DDDDDDDDDDDDDDDMMMMM MMMMMMMMMMMMMMMMMMMM ``` [Answer] # Rev 1 C, 74 ``` i;f(w,h){for(i=w*h;i--;i%w||puts(""))putchar(h-i/w*2==1^"CDEM"[i*4/w/h]);} ``` For a 1-byte saving, this version reverses (only) the middle row of slices for any odd number of rows. # Rev 0 C,75 ``` i;f(w,h){for(i=w*h;i--;i%w||puts(""))putchar(h==3&i/w==1^"CDEM"[i*4/w/h]);} ``` Many answers here zigzag, but in most cases, just outputting the letters in order (left to right, top to bottom) works fine: No need to zigzag for heights 1,2 or 4 No need to zigzag for heights greater than 4 (each mod's pizza ration will wrap around.) Therefore we only actually need to zigzag when the height is 3, and then we only need to reverse the middle row. As it turns out, Dennis and Doorknob are the only mods on that row. And they can be interchanged by XORing their ASCII codes with 1. This is handy given that there's no easy way to reverse a string in C. Ungolfed in test program ``` i; f(w,h){ for(i=w*h;i--;i%w||puts("")) //loop through all squares. puts inserts a newline at the END of each line. putchar(h==3&i/w==1^"CDEM"[i*4/w/h]); //put the letter, XORing D and E for the middle row of height 3. } W,H; main(){ scanf("%d%d",&W,&H); f(W,H); } ``` [Answer] # JavaScript (ES6) 107 Zigzag solution. Using template string, the newline is significant and counted. Test running the snippet with FireFox. ``` f=(w,h)=>{for(i=o=r='',z=l=1;--l?l:c='CDEM'[l=w*h/4,i++];r[w-1]&&(o+=r+` `,r='',z=!z))r=z?r+c:c+r;return o} //TEST (test=_=>([w,h]=I.value.match(/\d+/g),O.innerHTML=f(w,h)))() ``` ``` <input id=I value='8 3'><button onclick='test()'>-></button> <pre id=O></pre> ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 83 bytes The features used in this answer are newer than this challenge (not that it matters...). Byte count assumes ISO 8859-1 encoding. ``` \d+ $*# #(?=.*¶(.+)) $1 \G#### CDEM S_`((.)+?(?=.*¶(?<-2>#)+$))|\D O`. T`DE`ED O%`. ``` [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqIwojKD89LirCtiguKykpCiQxClxHIyMjIwpDREVNClNfYCgoLikrPyg_PS4qwrYoPzwtMj4jKSskKSl8XEQKT2AuClRgREVgRUQKTyVgLg&input=Mwo4) This implements aditsu's solution which is now somewhat feasible thanks to the new sort stages. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ×:4“CEDM”xsṢ€Y ``` [Try it online!](https://tio.run/##y0rNyan8///wdCuTRw1znF1dfB81zK0ofrhz0aOmNZH/Dy/X18x61Ljv0LZD2/7/jzbRMYzVUQBSJiDKQscYRBkZ6JiCaGMdi1gA "Jelly – Try It Online") Implements [aditsu's algorithm](https://codegolf.stackexchange.com/a/55585/66833) ## How it works ``` ×:4“CEDM”xsṢ€Y - Main link. Takes h on the left and w on the right × - Yield h×w :4 - Integer divide by 4; Yield R = (h×w):4 “CEDM” - Yield "CEDM" x - Repeat each character R times s - Split into rows of length w Ṣ€ - Sort each row Y - Join by newlines ``` ]
[Question] [ Imagine a "wire" that has `n` spaces. Imagine further that there are "electrons" in that wire. These electrons only live for one unit of time. Any spaces in the wire that are adjacent to exactly one electron become an electron. In Game of Life terminology, this is `B1/S`. For example, this is a wire of length 10, with period 62. [![enter image description here](https://i.stack.imgur.com/nVhYW.gif)](https://i.stack.imgur.com/nVhYW.gif) ## Rules * Input, `n`, is a single, positive integer. * Output must be a single integer denoting the period of a wire of length n. * The starting state is a single electron at one end of the wire. * The period *does not necessarily* include the starting state. Some lengths never return to the starting state, but all of them are periodic. * A static wire (i.e., one without electrons) has period 1. * Boundary conditions are *not* periodic. That is, the wire is not toroidal in any way. ## Test cases **Special thanks to orlp for producing this list.** (I have verified it up to n=27.) ``` 1 1 2 2 3 1 4 6 5 4 6 14 7 1 8 14 9 12 10 62 11 8 12 126 13 28 14 30 15 1 16 30 17 28 18 1022 19 24 20 126 21 124 22 4094 23 16 24 2046 25 252 26 1022 27 56 28 32766 29 60 30 62 31 1 32 62 33 60 34 8190 35 56 36 174762 37 2044 38 8190 39 48 40 2046 41 252 42 254 43 248 44 8190 45 8188 ``` You can see test cases for n=2 through 21 here with my Game-of-Life-esque simulator: [Variations of Life](http://goo.gl/1t68ui). --- **EDIT:** the sequence here has been published as [A268754](https://oeis.org/A268754)! [Answer] # Python 2, 148 142 87 bytes ``` n=input() p=l=1 t=1 h=2 while t!=h: if p==l:t,l,p=h,0,p*2 h=h/2^h*2%2**n;l+=1 print l ``` Uses [Brent's cycle detection algorithm](https://en.wikipedia.org/wiki/Cycle_detection#Brent.27s_algorithm), and thus actually runs fast. --- I have also written an animation in Python (both 2 & 3 work). It needs `pyglet` to run. You can view the animation by running: ``` python -m pip install --user pyglet curl -s https://gist.githubusercontent.com/orlp/f32d158130259cbae0b0/raw/ | python ``` (Feel free to download the gist and inspect the code before running.) You can press the + and - keys to increase/decrease the *n* being visualized. --- And finally, for those interested in exploring this number sequence further, here is a readable version (this was used to generate the test cases above): ``` # Brent's cycle detection, modified from wikipedia. def electron_period(n): wire_mask = (1 << n) - 1 power = lam = 1 tortoise, hare = 1, 2 while tortoise != hare: if power == lam: tortoise = hare power *= 2 lam = 0 hare = ((hare << 1) ^ (hare >> 1)) & wire_mask lam += 1 return lam ``` [Answer] # Mathematica, 127 bytes ``` p@n_:=Tr[#2-#]&@@Position[#,Last@#]&@NestWhileList[1~Table~n~ArrayPad~1*18~CellularAutomaton~#&,{1}~ArrayPad~{1,n},Unequal,All] ``` --- **Explanation** *Rule 18*: ``` {0,0,0} -> 0 {0,0,1} -> 1 {0,1,0} -> 0 {0,1,1} -> 0 {1,0,0} -> 1 {1,0,1} -> 0 {1,1,0} -> 0 {1,1,1} -> 0 ``` --- **Test cases** ``` p/@Range[10] (* {1,2,1,6,4,14,1,14,12,62} *) ``` [Answer] ## Python 2, 68 bytes ``` f=lambda n,k=1,l=[]:k in l and-~l.index(k)or f(n,k/2^k*2%2**n,[k]+l) ``` The cycle detection could be better, but the iterative step is nice. ``` k -> k/2^k*2%2**n ``` By representing the array as a binary number `k`, the update can be done by taking the XOR of `k` shifted one left with `/2` and one right with `*2`, then truncating to `n` bytes as `%2**n`. [Answer] ## Python 3 2, 134 121 118 bytes ``` Q=input() h=[] n=[0,1]+Q*[0] while n not in h:h+=[n];n=[0]+[n[d]^n[d+2] for d in range(Q)]+[0] print len(h)-h.index(n) ``` Basically the same as [my Pyth answer](https://codegolf.stackexchange.com/questions/71970/electrons-bouncing-in-a-wire#71982), but adapted it somewhat because of lack of certain built-in functions in Python. Ungolfed version: ``` length = input() history = [] new = [0] + [1] + length*[0] while new not in history: history += [new] new = [0] + [new[cell]^new[cell+2] for cell in range(length)] + [0] print len(history) - history.index(new) ``` [Answer] ## Pyth, 39 36 bytes ``` L++Zmx@[[email protected]](/cdn-cgi/l/email-protection).[,Z1ZQ)xJyeJ ``` Uses the "cumulative fixed-point" function to iterate until just before a configuration recurs, and returns all intermediate configurations as a list of lists. This works because the rules are deterministic and the configuration of the next generation is a function of the current configuration. This means that once the same configuration appears again the automata have completed a cycle. After reaching that (the last iteration of the cycle), it calls the next-gen function one last time on the last element of the "history" list, to obtain the next configuration (which is the starting configuration of a cycle), and find its index in the history. Now the period is simply the length ( 1 + index of cycle end) minus the index of cycle commencement. **In pythonic pseudocode:** ``` Z = 0 Q = eval(input()) L def y(b): # generates next-gen from current(param) ++Zm return [Z] + map( # adds head zero padding x@bd@bhhd lambda d: b[d] ^ b[1+ 1+ d], # xor the states of adjacent cells Q range(Q)) # implicit range in map Z + [Z] # adds end zero padding -lJ.uyN.[,Z1ZQ) J = repeatTilRecur(lambda N,Y:y(N), padRight([Z,1],Z,Q)); print( len(J) - # N:value; Y:iteration count JxJyeJ J.index( y( J[-1] ) ) ) ``` The test suite takes too much time that the server will kill it, so you'll need to use the [regular program](http://pyth.herokuapp.com/?code=L%2B%2BZmx%40bd%40bhhdUQZJ.uyN%2BZ%2B1%2aQ%5DZ%3B-lJxJyeJ&input=1&debug=0) and test it one by one, or install Pyth (if you haven't) and use a script to test it. [Answer] # Jelly, ~~19~~ ~~18~~ 17 bytes ``` H^Ḥ%® 2*©Ç‘СUµiḢ ``` This code computes the first **2n** states, so it's not particularly fast or memory efficient... [Try it online!](http://jelly.tryitonline.net/#code=SF7huKQlwq4KMirCqcOH4oCYw5DCoVXCtWnhuKI&input=&args=MTA) or [verify the first 16 test cases](http://jelly.tryitonline.net/#code=SF7huKQlwq4KMirCqcOH4oCYw5DCoVXCtWnhuKIK4oG0UsOH4oKsauKBtw&input=). ### Alternate version, 13 bytes (non-competing) Versions of Jelly that postdate this challenge have built-in loop detection, enabling a solution that is both shorter and more efficient. ``` H^Ḥ%® 2*©ÇÐḶL ``` This handles the last test case with ease. [Try it online!](http://jelly.tryitonline.net/#code=SF7huKQlwq4KMirCqcOHw5DhuLZM&input=&args=NDU) ### How it works ``` 2*©Ç‘СUµiḢ Main link. Input: n (integer) 2* Compute 2 ** n. © Store the result in the register. С Do the following: Ç Apply the helper link, which updates the state, ... ‘ 2 ** n + 1 times. Collect all 2 ** n + 2 intermediate results in a list. U Upend; reverse the list of results. µ Begin a new, monadic chain. Argument: R (list of results) Ḣ Yield and remove the first element of R (final state). i Find its first index in the remainder or R. This is the length of the loop. H^Ḥ%® Helper link. Argument: s (state, integer) H Halve s. This yields a float, but ^ will cast to integer. Ḥ Double s. ^ Compute (s ÷ 2) ^ (s × 2). ® Retrieve the value stored in the register (2 ** n). % Compute ((s ÷ 2) ^ (s × 2)) % (2 ** n). ``` Note that the helper link is applied to **2n** in the first iteration, which does not encode a valid state. However, **((2n ÷ 2) ^ (2n × 2)) % 2n = (2n - 1 + 2n + 1) % 2n = 2n - 1**, which is one of the possible starting states. Since we loop **2n *+ 1*** times, we are guaranteed to encounter a state twice, making the loop detection successful. [Answer] ## CJam, ~~41~~ ~~34~~ ~~31~~ ~~27~~ 25 bytes *Thanks to Dennis for saving 3 bytes. Borrowing an idea from his Jelly answer saved another 4.* ``` 2ri#_){__4*^2/W$%}*]W%(#) ``` [Test it here.](http://cjam.aditsu.net/#code=2ri(%23_)%7B__W%24%252*%5C2%2F%5E%7D*%5DW%25(%23)&input=12) ### Explanation I'm representing the wire simply as an integer (whose bits indicate the positions of the electrons) instead of using an actual list of bits. The state is the updated via fairly simple bitwise computations. To find the period we collect all intermediate results on the stack, run the simulation for 2n-1+1 steps, and then determine the period as the number of elements since the last occurrence of the final state(plus 1). Here's a breakdown of the code: ``` 2ri# e# Compute 2^n. This has a 1 in the n+1-th bit and zeroes below it. This is e# itself not a valid state but will be turned into 2^(n-1) by the first e# update. _) e# Duplicate and increment to get number of steps to simulate. { e# Repeat that many times... __ e# Duplicate the last state twice. 4* e# Multiply by 4, shifting all bits to the left by two positions. ^ e# XOR - we only keep keep those cells where we have exactly one 1-bit e# between both copies, i.e. those that neighboured a single electron e# but shifted up by one position. We don't need handle the survival rule e# explicitly, since electrons can never be adjacent in the first place. 2/ e# Divide by 2 shifting all bits back to the right again. W$ e# Copy the initial number 2^n. % e# Modulo - this simply sets the first bit to 0. }* ] e# Wrap all states in an array. W% e# Reverse it. ( e# Pull off the latest state. # e# Find its position in the remainder of the array. ) e# Increment. ``` [Answer] # JavaScript (ES6) 99 ~~104~~ ``` n=>eval("a=[...Array(n)];k={};for(a[0]=i=1;!k[a=a.map((v,i)=>v?0:a[i-1]^a[i+1])];k[a]=i++);i-k[a]") ``` **Test** ``` f = n=>eval("a=[...Array(n)];k={};for(a[0]=i=1;!k[a=a.map((v,i)=>v?0:a[i-1]^a[i+1])];k[a]=i++);i-k[a]") console.log = x => O.textContent += x + '\n'; ;[...Array(45)].map((_, i) => console.log(++i + ' ' + f(i))) ``` ``` <pre id=O></pre> ``` [Answer] # Haskell, 170 bytes `x!p` gives the element at index p if in bounds, else 0. `n` calculates the next step. `g i` gives the `i`th step. `c x` gives the period, if starting with `x`. `f` wraps it all together. ``` n x|l<-length x-1=[mod(x!(p-1)+x!(p+1))2|p<-[0..l],let y!q|q<0=0|q>=l=0|1<2=y!!p] c x=[i-j|i<-[1..],j<-[0..i-1],let g k=iterate n x!!k,g i==g j]!!0 f n=c$1:map(*0)[2..n] ``` (Note: posted from phone that has the hugs interpreter, which is not full featured, so might have typos.) [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~38~~ ~~37~~ ~~36~~ 35 bytes ``` 1Oi(`t0Y)5BX+8L)1=vt6#Xut0)=fdt?w}A ``` This uses a loop that keeps computing new states until the new state equals any of the preceding ones. Each state is a vector of zeros and ones. These vectors are stored as rows of a growing 2D array. Computation of each new state is done by convolving the current state with the sequence `[1,0,1]`, keeping only the central part, and setting to `0` any entry that is not `1`. *EDIT (May 13, 2016) The code in the following link has been slightly modified in accordance with changes introduced in the language after this answer was written* [**Try it online!**](http://matl.tryitonline.net/#code=MU9pKGB0MFkpNUJZKzZMKTE9dnQ3I1h1dDApPWZkdD93fUE&input=MTY) ``` 1Oi( % create initial vector [1,0,0,...,0], with size equal to input ` % do...while loop t0Y) % duplicate. Get last row of array: most recent vector 5BX+8L) % compute new vector by convolving the most recent one % with [1,0,1] and keeping only the central part 1= % set ones to 1, rest to 0 v % append to 2D array t6#Xu % compute vector of unique numeric labels, so that equal rows t0)=f % indices of entries whose value equals that of the last entry. % This will contain the index of the last entry and possibly % another index, in which case we've found a repetition d % this will either be empty (which is falsy) or contain the % period, which is a nonzero number (and thus truthy) t? % duplicate. If non-empty (and nonzero) w % swap to put the 2D-array at the top of the stack. This is % falsy, because it contains at least one zero, even in the % n=1 case (the array is initiallized to 0 in that case) % So the loop will terminate, with the period left on the stack } % else A % this transforms the empty array at the top of the stack % into a true value, so that the loop will continue % implicitly end if % implicitly end loop % implicitly display stack contents (period) ``` [Answer] # Perl 6, 81 bytes ``` {my@h=my$w=2;@h.push($w=$w/2+^$w*2%2**$_)while 2>@h.grep($w);[R-] @h.grep($w,:k)} ``` **Expanded and ungolfed a bit** ``` -> $n { my @history = my $wire = 2; while 2 > @history.grep($wire) { @history.push($wire = $wire/2 +^ $wire*2 % 2**$n) } [R-] @history.grep($wire,:k) } ``` A bit of explanation: * `[op]` reduces the list using op. For example `[+] @list` will sum `@list` * `R` is a meta-op that reverses the arguments given to an op. For example `1 R- 3` will result in 2. [Answer] # C++, 211 bytes Golfed ``` #include <bitset> #include <cstdio> #define B std::bitset<1<<10> B m,t(1),h(2);int main() {int p,l;for(scanf("%d",&p);p--;m.set(p)); for(p=l=1;t!=h;h=(h>>1^h<<1)&m,l++)p==l?t=h,p*=2,l=0:0;return !printf("%d",l);} ``` With added whitespace for readability ``` #include <bitset> #include <cstdio> #define B std::bitset<1<<10> B m,t(1),h(2); int main() { int p,l; for(scanf("%d",&p);p--;m.set(p)); for(p=l=1;t!=h;h=(h>>1^h<<1)&m,l++)p==l?t=h,p*=2,l=0:0; return !printf("%d",l); } ``` Good practice for C++'s bitset; and a great education learning about Brent's cycle detection algorithm (as used by @orlp) [Answer] # Pyth, 95 bytes ``` J.[ZQ[1)K_1=bYW<K0=NY aN?hJZ?htJ1ZFTr1tlJ aN?@JTZ?x@JhT@JtT1Z) aN?eJZ?@J_2 1Z=JN=KxbJ abJ;-tlbK ``` You can try it out [here](https://pyth.herokuapp.com/?code=J.%5BZQ%5B1%29K_1%3DbYW%3CK0%3DNY%20aN%3FhJZ%3FhtJ1ZFTr1tlJ%20aN%3F%40JTZ%3Fx%40JhT%40JtT1Z%29%20aN%3FeJZ%3F%40J_2%201Z%3DJN%3DKxbJ%20abJ%3B-tlbK&input=10&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0). [Answer] # Pyth, 29 bytes ``` J^2QL%x/b2*b2JK.uyN1;-lKxKyeK ``` * [Try it online!](http://pyth.herokuapp.com/?code=J%5E2QL%25x%2Fb2*b2JK.uyN1%3B-lKxKyeK&input=18&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21&debug=0) * [Test suite](http://pyth.herokuapp.com/?code=J%5E2QL%25x%2Fb2*b2JK.uyN1%3B-lKxKyeK&input=6&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21&debug=0) Uses the algorithm `a(n+1) = ((a(n) << 1)^(a(n) >> 1)) % (2 ** N)`. [Answer] # Ruby, 72 bytes Anonymous function. ``` ->n{s=[w=1];c=p (j=s.index w=w*2%2**n^w/2 j ?c=s.size-j:s<<w)while !c c} ``` ]
[Question] [ Don't ask me how or why but while coding on a project I noticed that the characters of a couple of words had a particular pattern referred to the alphabet, I connected each character of the words with the pencil on the alphabet and I obtained two spirals, then I noticed that the first spiral was clockwise and the other was counterclockwise, and other characteristics... so I named them ***Swirling Words***! A *Swirling Word* can be: 1. clockwise or counterclockwise 2. centripetal or centrifugal Here there are some examples of *Swirling Words*: [![Swirling Words Diagram](https://i.stack.imgur.com/qGedt.png)](https://i.stack.imgur.com/qGedt.png) ### Task 1: Write a full program or function that will take a word from standard input and will output if is a *Swirling Word* and it's characteristics, in a readable format, extended text, 3 characters, flags, etc. Test cases and example outputs for different words (but you can decide how to represent the results): ``` EARTH, GROUP > NO // NOT A SWIRLING WORD OPERA, STAY, IRIS > SW,CF,CW // SWIRLING WORD, CENTRIFUGAL, CLOCKWISE MINER, TAX, PLUG, META > SW,CF,CC // SWIRLING WORD, CENTRIFUGAL, COUNTERCLOCKWISE AXIOM, AXIS, COOK > SW,CP,CW // SWIRLING WORD, CENTRIPETAL, CLOCKWISE WATCH, YETI, PILL > SW,CP,CC // SWIRLING WORD, CENTRIPETAL, COUNTERCLOCKWISE MORE EXAMPLES OF FALSE TEST CASES (NOT SWIRLING WORDS): EARTH, GROUP, OUTPUT, WORD, CONNECTION, ODD, MOM, DAD, CHARACTER, EXAMPLE, QUESTION, NEWSLETTER, OTHER ``` ### Rules: 1. The connection between the first two characters must be *up* (like in the graphics), all the even connection must be *down*, all the odd connections must be *up*. 2. You can ignore upper/lowercase or consider/convert all to upper case or all to lower case. 3. The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, etc. 4. If a word has double characters, like "GROOVE", you must collapse the doubles to one character: "GROOVE" > "GROVE". 5. The input words will contain at least 3 distinct characters. Words like "MOM", "DAD", "LOL" are not valid words. 6. It's possible to pass multiple times in the same character, like "IRIS". 7. Shortest code wins. ### Task 2: To obtain more reputation, find the longest *Swirling Words*, and it's characteristics, that you can find in the english dictionary, following the above rules. You can take for example as reference the complete list of the english words [here](https://github.com/dwyl/english-words). Happy coding! [Answer] # [MATL](http://github.com/lmendo/MATL), ~~33~~ ~~31~~ 30 bytes ``` lydhg)dt|dZSXz&=wZSdh?4M1)3M1) ``` Input is in uppercase letters (or in lowercase letters, but not mixed). Output is: * If the word is non-swirling: no output is produced * If it is swirling: two numbers are produced in different lines: + First number `1`/ `-1` indicates centrifugal / centripetal. + Second number `1`/ `-1' indicates clockwise / counterclockwise. [Try it online!](http://matl.tryitonline.net/#code=bHlkaGcpZHR8ZFpTWHomPXdaU2RoPzRNMSkzTTEp&input=J1BJTEwn) Or [verify all test cases](http://matl.tryitonline.net/#code=alliIkBnCmx5ZGhnKWR0fGRaU1h6Jj13WlNkaD80TTEpM00xKWg&input=RUFSVEggR1JPVVAgT1BFUkEgU1RBWSBJUklTIE1JTkVSIFRBWCBQTFVHIE1FVEEgQVhJT00gQVhJUyBDT09LIFdBVENIIFlFVEkgUElMTA) (code modified to take all inputs and to produce the two output numbers on the same line) ### Explanation Let's take input `'OPERAA'` as an example. The first part of the code removes double letters: ``` l % Push 1 % STACK: 1 y % Take input implicitly from below, and duplicate % STACK: 'OPERAA', 1, 'OPERAA' d % Convert to code points and compute differences % STACK: 'OPERAA', 1, [1 -11 13 -17 0] h % Concatenate horizontally % STACK: 'OPERAA', [1 1 -11 13 -17 0] g % Convert to logical % STACK: 'OPERAA', [true true true true true false] ) % Index % STACK: 'OPERA' ``` We now check if the distances between letters are non-decreasing (necessary condition for the word to be swirling): ``` d % Convert to code points and compute differences % STACK: [1 -11 13 -17] t| % Duplicate and take absolute value % STACK: [1 -11 13 -17], [1 11 13 17] d % Differences % STACK: [1 -11 13 -17], [10 2 4] ZS % Signum % STACK: [1 -11 13 -17], [1 1 1] Xz % Remove zeros (gives a vertical vector). Needed for words like 'IRIS', % where some consecutive distances are equal % STACK: [1 -11 13 -17], [1; 1; 1] &= % All pairwise equality comparisons. Gives a matrix. If all the signs % were equal the matrix will contain all ones % STACK: [1 -11 13 -17], [1 1 1; 1 1 1; 1 1 1] ``` We then check if the letters go back and forth (this is the other condition for the word to be swirling): ``` w % Swap % STACK: [1 1 1; 1 1 1; 1 1 1], [1 -11 13 -17] ZS % Signum % STACK: [1 1 1; 1 1 1; 1 1 1], [1 -1 1 -1] d % Differences % STACK: [1 1 1; 1 1 1; 1 1 1], [-2 2 -2] ``` Lastly, we check if the two conditions hold, and in that case produce the output: ``` h % Concatenate horizontally % STACK: [1 1 1 1 1 1 1 1 1 -2 2 -2] ? % If all elements are nonzero 4M % Push first signum array without zeros, from the automatic clipboard % STACK: [1; 1; 1] 1) % Get first element (tells if first difference was positive or negative) % STACK: 1 3M % Push second signum array, from the automatic clipboard % STACK: 1, [1 -1 1 -1] 1) % Get first element (tells if first movement was right or left) % STACK: 1, 1 % Implicitly end if % Implicitly display ``` [Answer] # Mathematica, ~~117~~ 111 bytes *Thanks to JHM for saving 6 bytes, and making it case-insensitive to boot!* ``` {o=OrderedQ/@{a=Abs[d=Differences[#&@@@Split@LetterNumber@#]],Reverse@a},d[[1]]>0,Or@@o&&Max[Most[d]Rest@d]<0}& ``` Unnamed function that takes a string and returns a nested list of booleans in the form `{{B1,B2},B3,B4}`. B4 records whether the word is swirling (and if it's not, the rest of the output is garbage). If the word is swirling, then B1 records whether the word is centrifugal, B2 records whether the word is centripetal, and B3 records whether the word is clockwise (True) or counterclockwise (False). Here's a longer version that post-processes (first line) the above function (spaced over the 2nd-5th lines) to make it identical to the OP: `NO` if the word isn't swirling, and the appropriate choice of `{SW,CF,CW}` , `{SW,CF,CC}` , `{SW,CP,CW}`, or `{SW,CP,CC}` if the word is swirling: ``` If[#3, {SW, If[#[[1]], CF, CP], If[#2, CW, CC]}, NO] & @@ {o = OrderedQ /@ {a = Abs[d = Differences[# & @@@ Split@LetterNumber@#]], Reverse@a}, d[[1]] > 0, Or @@ o && Max[Most[d] Rest@d] < 0} & ``` The explanation is the same as in Martin Ender's CJam answer, with one additional note: the list of consecutive differences must alternate in sign for the word to be swirling, and that can be detected by making sure all products of pairs of consecutive differences are negative (that's what `Max[Most[d]Rest@d]<0` does). Running the function on all 40,000+ words of Mathematica's `WordList[]`, we find the following 8-letter swirling words, which are the longest of their respective swirling types: ``` operetta {SW, CF, CW} opposite {SW, CF, CW} stowaway {SW, CF, CW} assassin {SW, CP, CW} assessor {SW, CP, CW} baccarat {SW, CF, CC} keenness {SW, CF, CC} positive {SW, CF, CC} ``` (Brownie points to `positive` for having no double letters, and fewer repeated letters than `stowaway`.) But the absolute champion is the 9-letter counterclockwise-swirling centripetal word `vassalage`! [Answer] # Scala, 110 bytes ``` def/(s:String)={val ? =s.sliding(2).map(t=>(t(0)-t(1)).abs).toSeq (Seq(?,?reverse)indexOf(?sorted),s(0)<s(1))} ``` Returns a tuple `(a,b)` with * `a == 1` if s is centripetal * `a == 0` if s is centrifugal * `a == -1` if s is not swirling and * `b == true` if s is clockwise * `b == false` if s is counterclockwise * b can be true or false if s is not swirling Explanation: ``` def/(s:String)={ //define a method called / with a String argument val ? =s //define ? as... .sliding(2) //an iterator for each two consecutive elements .map(t=> //foreach 2 chars (t(0)-t(1)).abs //get the absolute value of their difference ) .toSeq //and convert the iterator to a Seq, because iterator doesn't have reverse and sorted methods ( //return a tuple of Seq(?,?reverse) //a Seq of ? and reversed ? .indexOf(?sorted) //and check which of them is sorted ? , //and s(0)< s(1) //the difference bewteen the first two elements of the string. ) } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OIḟ0µAI©Ṡḟ0ṂṭḢṠ$µ®ḟ0ṠEṭ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/f8@GO@QaHtjp6Hlr5cOcCEOfhzqaHO9c@3LEIyFc5tPXQOojgAleg6P///xMrMvNzAQ "Jelly – Try It Online")** Or see the [test cases](https://tio.run/##y0rNyan8/9/f8@GO@QaHtjp6Hlr5cOcCEOfhzqaHO9c@3LEIyFc5tPXQOojgAleg6P/D7UcnPdw5Q/NR446je9z//49WSk0sKslQ0lFKL8ovLQDS@QWpRYlAurgksRJIZRZlFgOp3My81CIgXZJYASQLckrTQYKpJSCViRWZ@bkQGqQ0OT8/G0iVJ5Ykg8ytTC3JBGnJzMlRiuUCAA "Jelly – Try It Online") All upper or all lower. Returns a flag list `[D, F, S]`: `D`: clockwise = `1` / anticlockwise = `-1` `F`: centrifugal = `1` / centripetal = `-1` `S`: spinning = `1` / not spinning = `0` - if `S` is `0` the other flags are still evaluated even though they carry no useful information. ### How? ``` OIḟ0µAI©Ṡḟ0ṂṭṠḢ$µ®ḟ0ṠEṭ - Main link: s O - ordinals I - deltas (i.e. [a,b,c,...] -> [b-a,c-b,...]) ḟ0 - filter out zeros - (call this Z) µ - start a new monadic chain (i.e. f(Z)) A - absolute values I - deltas © - copy to register Ṡ - signs ḟ0 - filter out zeros Ṃ - minimum - (i.e. F = {centrifugal: 1; centripetal: -1}) $ - last two links as a monad: Ḣ - head (Z) Ṡ - sign - (i.e. D = {clockwise: 1; anticlockwise: -1}) ṭ - tack µ - start a new monadic chain (i.e. f([D,F])) ® - recall from register ḟ0 - filter out zeros Ṡ - signs E - all equal? - (i.e. S = {spinning: 1; not spinning: 0}) ṭ - tack - (i.e. [D,F,S]) ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 39 bytes ``` r{2ew::-V}:D~-_:g_0=\D#)!@:zD-:g_0=\(-! ``` [Try it online!](http://cjam.tryitonline.net/#code=cnsyZXc6Oi1WfTpEfi1fOmdfMD1cRCMpIUA6ekQtOmdfMD1cKC0h&input=T1BFUkE) The input can be uppercase or lowercase, but not mixed. The program inadvertently points out words which are not necessarily centrifugal or centripetal, but otherwise meet the requirements of being spiral. These are described as "circular" in the chart below. **To interpret the output use this chart:** ``` SPIRAL (output contains four 1s) -11-11 : Clockwise Centrifugal -1111 : Clockwise Centripetal 11-11 : Counter-clockwise Centrifugal 1111 : Counter-clockwise Centripetal CIRCULAR (output contains two 1s) -11 : Clockwise Circular 11 : Counter-clockwise Circular NONSPIRAL (output contains a 0) ``` **Explanation:** The program actually evaluates whether the sequence of non-zero differences between characters starts off positive or negative, if it alternates in sign, if the magnitudes start off increasing or decreasing, and if it continues to do so. If the magnitudes don't increase or decrease then the program breaks by operating on an empty array. The major steps are shown below (this code will also show the progress of the stack): ``` r{2ew::-V}:D~- e# take difference of overlapping pairs, removing 0s handles duplicates ede# store difference function plus 0 as D, it's multipurpose _:g_0=\ e# compute signs differences, keep first to show starting direction ede# -1 = CLOCKWISE, 1 = COUNTERCLOCKWISE D#)!@ e# difference of signs includes 0 if not alternating, keep in stack ede# 1 = ALTERNATING, 0 = NOT ALTERNATING :zD-:g e# signs of difference of absolute values, ignoring 0s (fixed magnitude) _0=\ e# keep first sign in stack to indicate how the sequence starts ede# -1 = INCREASING, 1 = DECREASING (-! e# remove first item from entire list and see if nothing remains ede# 1 = EMPTY(MONOTONE), 0 = NONEMPTY ``` [Answer] # PHP, 322 Bytes ``` for(;++$i<strlen($z=preg_replace("#(.)\\1#","$1",$argv[1]));){$t[]=$z[$i-1]<=>$z[$i]?:0;$o[]=$z[0]<=>$z[$i];$i<2?:$k[]=$z[$i-2]<=>$z[$i];}$s=preg_match("#^1?(-11)*(-1)?$#",join($t))?($t[0]!=1?1:2):0;$s+=2*preg_match($r="#^(-1|0)?([01](-1|0))*[01]?$#",join($o));$s*=preg_match($r,join($k));count_chars($z,3)[2]?:$s=0;echo$s; ``` for a more pretty Output `echo["n","+P","-P","+F","-F"][$s];` Expanded version ``` for(;++$i<strlen($z=preg_replace("#(.)\\1#","$1",$argv[1]));){ $t[]=$z[$i-1]<=>$z[$i]?:0; $o[]=$z[0]<=>$z[$i]; $i<2?:$k[]=$z[$i-2]<=>$z[$i]; } $s=preg_match("#^1?(-11)*(-1)?$#",join($t))?($t[0]!=1?1:2):0; #Clockwise direction or not $s+=2*preg_match($r="#^(-1|0)?([01](-1|0))*[01]?$#",join($o)); # True centrifugal $s*=preg_match($r,join($k)); #true or false second test for not count_chars($z,3)[2]?:$s=0; # word must have >2 different characters echo$s;# short output echo["n","+P","-P","+F","-F"][$s]; #long output alternative ``` ## Task 2 second value without short doubles rule > > 4 -F killingness 11 Bytes positivize 10 Bytes > > > 3 +F oppositive 10 Bytes logogogue 9 Bytes > > > 2 -P vassalage 9 Bytes sarcocol,sasarara 8 Bytes > > > 1 +P assession 9 Bytes apanage, aramaic, argonon, auction, avision, awarded, crenele, exesion, exition, eyewink > 7 Bytes > > > ## Visualize a word ``` header('Content-Type: image/svg+xml; charset=UTF-8'); $w=$_GET["w"]??"OOPERRA"; $w=strtoupper($w); echo '<?xml version="1.0" encoding="UTF-8"?>' .'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' .'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 -100 420 400">' .'<title>Swirl Word</title><desc>Viualize a Word</desc>'; echo '<text x="210" y="-50" text-anchor="middle" font-family="arial">'.$w.'</text>'; foreach(range("A","Z")as $x=>$c){ echo '<text x="'.(15+$x*15).'" y="110" text-anchor="middle" font-family="arial">'.$c.'</text>'; $r[$c]=15+$x*15; } for($i=0;++$i<strlen($w);){ echo '<path d="M '.($r[$w[$i-1]]).',105 A '.($radius=abs($r[$w[$i]]-$r[$w[$i-1]])/2).' '.($radius).' 0 0 0 '.($r[$w[$i]]).',105" style="stroke:gold; stroke-width:1px;fill:none;" />'; } echo '</svg>'; ``` in the snippet is the result of the SVG I have create ``` <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 -100 420 400"><title>Swirl Word</title><desc>Viualize a Word</desc><text x="210" y="-50" text-anchor="middle" font-family="arial">KILLINGNESS</text><text x="15" y="110" text-anchor="middle" font-family="arial">A</text><text x="30" y="110" text-anchor="middle" font-family="arial">B</text><text x="45" y="110" text-anchor="middle" font-family="arial">C</text><text x="60" y="110" text-anchor="middle" font-family="arial">D</text><text x="75" y="110" text-anchor="middle" font-family="arial">E</text><text x="90" y="110" text-anchor="middle" font-family="arial">F</text><text x="105" y="110" text-anchor="middle" font-family="arial">G</text><text x="120" y="110" text-anchor="middle" font-family="arial">H</text><text x="135" y="110" text-anchor="middle" font-family="arial">I</text><text x="150" y="110" text-anchor="middle" font-family="arial">J</text><text x="165" y="110" text-anchor="middle" font-family="arial">K</text><text x="180" y="110" text-anchor="middle" font-family="arial">L</text><text x="195" y="110" text-anchor="middle" font-family="arial">M</text><text x="210" y="110" text-anchor="middle" font-family="arial">N</text><text x="225" y="110" text-anchor="middle" font-family="arial">O</text><text x="240" y="110" text-anchor="middle" font-family="arial">P</text><text x="255" y="110" text-anchor="middle" font-family="arial">Q</text><text x="270" y="110" text-anchor="middle" font-family="arial">R</text><text x="285" y="110" text-anchor="middle" font-family="arial">S</text><text x="300" y="110" text-anchor="middle" font-family="arial">T</text><text x="315" y="110" text-anchor="middle" font-family="arial">U</text><text x="330" y="110" text-anchor="middle" font-family="arial">V</text><text x="345" y="110" text-anchor="middle" font-family="arial">W</text><text x="360" y="110" text-anchor="middle" font-family="arial">X</text><text x="375" y="110" text-anchor="middle" font-family="arial">Y</text><text x="390" y="110" text-anchor="middle" font-family="arial">Z</text><path d="M 165,105 A 15 15 0 0 0 135,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 135,105 A 22.5 22.5 0 0 0 180,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 180,105 A 0 0 0 0 0 180,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 180,105 A 22.5 22.5 0 0 0 135,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 135,105 A 37.5 37.5 0 0 0 210,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 210,105 A 52.5 52.5 0 0 0 105,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 105,105 A 52.5 52.5 0 0 0 210,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 210,105 A 67.5 67.5 0 0 0 75,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 75,105 A 105 105 0 0 0 285,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 285,105 A 0 0 0 0 0 285,105" style="stroke:gold; stroke-width:1px;fill:none;" /></svg> ``` [Answer] # Haskell, 148 bytes ``` z f=tail>>=zipWith f g c=and.z c.filter(/=0).map abs.z(-).map fromEnum (a:b:r)%c|a==b=(b:r)%c|1<3=c a b f s|a<-[g(>=)s,g(<=)s]=or a:a++[s%(<),s%(>)] ``` [Try it on Ideone.](http://ideone.com/ZGhs0P) Input must be either al lower or all upper-case. Output is a list of five booleans: `[SW?, CF?, CP?, CW?, CC?]`. `f "positive" -> [True,True,False,False,True]` This turned out longer than expected, especially handing the collapsing of repeated characters takes about 40 bytes. At first I compared just the first two characters to yield `CW` or `CC` before noticing that testcases like `bba` or `bbc` are valid too and defeat this approach. [Answer] # Python, 152 bytes: ``` lambda C:[C[-1]in max(C)+min(C),C[1]>C[0]]*all([[i>g,i<g][[h%2>0,h%2<1][C[1]>C[0]]]for i,g,h in filter(lambda i:i[0]!=i[1],zip(C,C[1:],range(len(C))))]) ``` An anonymous lambda function. Call as `print(<Function Name>('<String>'))`. Takes input as all lowercase or uppercase, but *not* mixed case. Outputs an array containing nothing (`[]`) if the word is not swirly, or an array in the following format otherwise: * 1st element is `True/False` for `Centrifugal/Centripetal`. * 2nd element is `True/False` for `Clockwise/Counterclockwise`. [Try It Online! (Ideone)](http://ideone.com/viRhhI) ]
[Question] [ This is much more advanced than [How to randomize letters in a word](https://codegolf.stackexchange.com/questions/3293/how-to-randomize-letters-in-a-word) and [Cambridge Transposition](https://codegolf.stackexchange.com/questions/9261/cambridge-transposition) because of the rule about which letters may be swapped with which. A simple regex will not suffice here. --- It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules: 1. Scrambling must be (pseudo) random. 2. A word is a sequence of the Latin characters, A through Z. 3. Only initial letters will ever be uppercase. 4. The first and last letters must stay untouched. 5. When scrambling, only letters within one of the following groups may exchange places: 1. `acemnorsuvwxz` 2. `bdfhkl` 3. `gpqy` 4. `it` 5. `j` (stays in place) ### Example > > # Srcmable wrods while psrrnveieg their oeiltnus > > > It is well known that a txet can still be read while the inrands of its wrods have been srcambled, as long as their fisrt and last letters plus their ovaerll ontliues raemin canstnot. Given a patnirlbe Acsii+Nwnliee txet, samrclbe ecah word anoccdirg to these relus: > > > 1. Smncrbliag must be (pusedo) rondam. > 2. A wrod is a seqencue of the Latin chreratacs, A thurogh Z. > 3. Only iniital lrttees will eevr be uppcsaere. > 4. The fisrt and lsat lettres must stay uctoenhud. > 5. When sarnclbimg, only letters wihtin one of the fwllnoiog guorps may ecxhange plaecs: > > > 1. `aneusvrowxmcz` > 2. `bhkfdl` > 3. `gqpy` > 4. `it` > 5. `j` (stays in plcae) > > > ### Emxaple > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~80~~ 74 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes by moving from `czar + vex + mow + sun` to `czar + vexes + unmown` (the repeated `e`s and `n`s are not a problem) -1 byte using `Tị` rather than `ȦÐf` -1 byte using `Œle€Øa` rather than `i@€ØB>⁵` -2 bytes by reconfiguring the layout a little ``` Tị TẊị⁹ż@œp e€ç⁸F W;“HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»Ḳ¤ç/ Ḣ,ṪjÇḟ0 Œle€Øað¬œpÇ€ÑżœpÑ¥ ``` A full program taking a character list (or Python formatted string), which prints the result of the scrambling. **[Try it online!](https://tio.run/nexus/jelly#dVE/bxMxFN/vU7wRpHCUfwssMABFQmIgUiUkJF58Lzm3Pvtq@5KUibBUtGIoLB2QkFBRJdQBdeHSdMoplfgYl@/AHJ6TkEx4sZ/93u@fZ816dBg164sD3qeD4eTy4eRzHtH0/Vl1Oh2UT6KtB9N3Xzbr0cerg3p4zPfxm9ebv8@r8mpQlycb9cUH1bZVuT0d/BqP6vJ8fFKd3ozq8lujHv7Yrvbr8utGNPmk5pDHWP0cnzFDtR/Ko8llOB@Nv89ms2cepIMeKQU72vQ0@BQ9IHjqexCowXnJby0CS5hAL5WKuIdAao02cWDaID0jmFCk2CXuJR4TFrOWoqQB6EAZ3Qk7D0oLbWkdc@gEFPJBkfdkHeSq@NdhumSRaU3hldTkmDxDqUEY7TxqH8NT2WWWhc7Gig0IRTrXAigEb5J5vQmojh0Uitz9KAJet2J4uRgKLVnBOtjjtdxRkZjrYFmdyeJF7@0YHi1AOSoER7sFaUHBekjiOfogLUWLIhhpcLdPrSk6KbxaQtyJ4YVWe5ya9BLVynMvhEvsNrAXeU5WoKPl0N0Ymoz/n7jmmjmNPSi0N4VIKVnO3YthK13/ARtsgAnsa1afsmSjVx7aRinTC1F0WHjO6IxLfTalO8Q/g2KVXFhcZtpYV3R7/bfr61bSTnfUuu7ku3vrSvooetzHLFf0R5sbgr@K/gI)** A huge amount of difficulty for Jelly here it seems (either that or I have missed a trick, which has been known to happen!) This will surely be beaten by languages with better string manipulation like ~~[Retina](https://github.com/m-ender/retina)~~(no random functionality) or [05ab1e](https://github.com/Adriandmen/05AB1E). ### How? ``` Tị - Link 1, get truthy items: list a T - truthy indexes of a ị - index into a TẊị⁹ż@œp - Link 2, selective shuffle: list a, list b T - truthy indexes of a (those indexes that may be shuffled in b) Ẋ - random shuffle ⁹ - link's right argument, b ị - index into (gets the shuffled values) œp - partition b at truthy indexes of a ż@ - zip with reversed @rguments (place shuffled values - yields a list of lists) e€ç⁸F - Link 3, value selective shuffle: list a, list b e€ - c exists in b? for €ach c in a (1s where b has shuffle-able characters, else 0s) ⁸ - link's left argument, a ç - call the last link (2) as a dyad F - flatten the result (from the yielded list of lists to one list) W;“HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»Ḳ¤ç/ - Link 4, perform all shuffles on a word's innards: list x W - wrap x in a list ¤ - nilad followed by link(s) as a nilad: “HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷» - compression of s(bdfhkl)+d( czar)+d(vexes)+d(unmown)+s( gpqy)+d( ti) - where d() looks up a word in Jelly's dictionary and s() adds a string to the compressed output. Ḳ - split on spaces: ["bdfhkl","czarvexesunmown","gpqy","ti"] ç/ - reduce by last link (3) as a dyad (shuffles by each in turn) Ḣ,ṪjÇḟ0 - Link 5, shuffle a word: list w Ḣ - head w (yields the leftmost character and modifies w) Ṫ - tail w (yields the rightmost character and modifies w) , - pair - Note: head and tail yield 0 when w is empty, so ['a'] -> ["a",0] and [] -> [0,0] Ç - call the last link (4) as a monad (with the modified w) j - join ḟ0 - filter discard zeros (thus single or zero letter words pass through unchanged) Œle€Øað¬œpÇ€ÑżœpÑ¥ - Main link: list s Œl - convert s to lowercase, say t Øa - lowercase alphabet, say a e€ - c exists in a? for €ach c in t ð - dyadic chain separation (call that u) ¬ - not (vectorises across u), say v œp - partition s at truthy indexes of v (extract words, plus empty lists from within strings of non-alphabetic characters) Ç€ - call the last link (5) as a monad for €ach (shuffle their innards) Ñ - call the next link (1) as a monad (only keep the actual words) ¥ - last two links as a dyad: œp - partition s at truthy indexes of u (get the non-words, plus empty lists from within strings of alphabetic characters) Ñ - call the next link (1) as a monad (only keep actual non-words) ż - zip together - implicit print ``` [Answer] # PHP, 278 Bytes ``` <?=preg_replace_callback("#\pL\K(\pL+)(?=\pL)#",function($t){preg_match_all("#([^bdf-lpqty])|([bdfhkl])|([gpqy])|([it])|(j)#",$t[0],$p);foreach($p as$v){$k++?$c=array_keys($n=array_filter($v)):$o=[];!$n?:shuffle($n)&&$o+=array_combine($c,$n);}ksort($o);return join($o);},$argn); ``` [Try it online!](https://tio.run/nexus/php#LVBBbsIwELzzijSskK0Eqddi0jygvfUYaOQYJzYxtnEcEKI8u2e6pFx2Z3ZnVqtZl175GfDQ2SL9EoEfGiOTswu7ITkrjdgHOchw0rZLopI6JG6MRls5pGzWukAY6PUbliyj11n5fl@XBVq6OkhvuJC14MY0XPQknW/85@aDYM0oKQvsdJ7m7WhF1M4SiPQ6OQ88ClWjDS2k@m527dL4Y7xs6Q@pkKneTLDzx/@Zjo@2f1yDWL1uc/CU4W@SC0XAJ3yAE71Cn2UliIKHwC91Ly8DAftkrTZRBoIyugJXVFv2ArZcDWpsWyNRRxcLcNlTLdyhwQQIiBw37NYPLkQCjrIg4xhssnfaTvyWT9FSdpdCuXRjMbTbAyaIp1XK7r/WLQW@Kv8A "PHP – TIO Nexus") Expanded ``` echo preg_replace_callback("#\pL\K(\pL+)(?=\pL)#" # patter \pL is shorter as [a-z] ,function($t){ # replacement function beginning preg_match_all("#([^bdf-lpqty])|([bdfhkl])|([gpqy])|([it])|(j)#",$t[0],$p); # makes groups with the regex. group 0 is the whole substring foreach($p as$v){ # loop through groups $k++?$c=array_keys($n=array_filter($v)):$o=[]; # group 0 make new empty replacement array in the other case filter the group remove empty values. #You gain an array with the keys as position in the substring and the values #store the key array and the values array !$n?:shuffle($n)&&$o+=array_combine($c,$n); #if values shuffle the values and make a new array with the keys and the shuffled values and merge the new array to the replacement array } ksort($o); # sort the replacement array ascending positions return join($o); # return the replacement as string },$argn); ``` functions [array\_combine](http://php.net/manual/en/function.array-combine.php) [array\_filter](http://php.net/manual/en/function.array-filter.php) [array\_keys](http://php.net/manual/en/function.array-keys.php) [ksort](http://php.net/manual/en/function.ksort.php) [preg\_replace\_callback](http://php.net/manual/en/function.preg-replace-callback.php) [shuffle](http://php.net/manual/en/function.shuffle.php) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 79 bytes ``` sm?td++hduuXNhTeTC,f@@GTHUG.S@HGG+-GJ."by❤jã~léܺ"cJ\jPtdedd:jb.z"([A-Za-z]+)"3 ``` where `❤` is U+0018. [Try it online!](http://pyth.herokuapp.com/?code=sm%3Ftd%2B%2BhduuXNhTeTC%2Cf%40%40GTHUG.S%40HGG%2B-GJ.%22by%18j%C3%A3~l%C3%A9%C3%9C%C2%BA%22cJ%5CjPtdedd%3Ajb.z%22%28%5BA-Za-z%5D%2B%29%223&input=It+is+well+known+that+a+text+can+still+be+read+while+the+innards+of+its+words+have+been+scrambled%2C+as+long+as+their+first+and+last+letters+plus+their+overall+outlines+remain+constant.+Given+a+text%2C+scramble+each+word+according+to+these+rules%3A%0A%0A1.+Scrambling+must+be+%28pseudo%29+random.%0A%0A1.+A+word+is+a+sequence+of+the+Latin+characters%2C+A+through+Z.%0A%0A1.+Only+initial+letters+will+ever+be+uppercase.%0A%0A1.+The+first+and+last+letters+must+stay+untouched.%0A%0A1.+When+scrambling%2C+only+letters+within+one+of+the+following+groups+may+exchange+places%3A%0A%0A+1.+%60acemnorsuvwxz%60%0A%0A+1.+%60bdfhkl%60%0A%0A+1.+%60gpqy%60%0A%0A+1.+%60it%60%0A%0A+1.+%60j%60+%28stays+in+place%29&debug=0) ## Sample It is well knwon that a text can still be raed while the irnands of its wrods have been seraclbmd, as long as their first and last lettres plus their oaervll ontliues rmeain conntsat. Given a text, sacmrble each wrod acrncdiog to thsee relus: 1. Scamrlbing must be (puesdo) rnadom. 2. A word is a suqencee of the Latin chraectars, A thuorgh Z. 3. Only iaitinl lettres will eevr be uppaersce. 4. The first and last lettres msut stay uotcnuhed. 5. When srancblimg, only lettres wiihtn one of the follnwiog guorps may enxhcage plecas: 1. `amsuvrcnoxewz` 2. `bhfkdl` 3. `gpqy` 4. `it` 5. `j` (stays in place) [Answer] # JavaScript 176 bytes ``` t.replace(/\B(\w+)\B/g,b=>{return[/[acemnorsuvwxz]/g,/[bdfhkl]/g,/[gpqy]/g,/[it]/g].forEach(d=>{g=b.match(d),b=b.replace(d,c=>{return g.splice(Math.random()*g.length,1)})}),b}) ``` **Method:** 1. RegExp iterates over the centre of each word (`/\B(\w+)\B/g`) using 1st replace fn. 2. 1st replace fn iterates an array of RegExp's for each letter-group (`/[bdfkhl/g, /[gqpy]/g, etc..` ). 3. Each iteration builds a temp array of word-centre's characters appearing in current letter-group. 4. Each iteration then uses current letter-group's RegExp to iterate over entire word-centre, using a 2nd replace fn. 5. 2nd replace fn randomly splices the temp array, removing a random character and returning it. **Demo:** Run it in JSFiddle: <https://jsfiddle.net/CookieJon/bnpznb7r/> [Answer] # C, ~~453, 356~~ 369 bytes ``` #define F for #define M rand()%s+1+q char a[256],*b=" acemnorsuvwxz\1bdfhkl\1gpqy\1it\1j";g(c,t)char*c,*t;{static int i,j,k,w,v,n,q,s,r;r=-1;if(c&&t){strcpy(c,t);if(!k)F(j=i=k=1;b[i];++i)b[i]-1?(a[b[i]]=j):++j;F(r=i=0;c[i];){F(;isspace(c[i]);++i);F(q=i;!isspace(c[i])&&c[i];++i);F(s=v=i-q-2;--v>0;)if(a[c[j=M]]==a[c[w=M]]&&a[c[j]])n=c[j],c[j]=c[w],c[w]=n;}}return r;} ``` ungolf with comments ``` // Input in the arg "t" result in the arg "c" // NB the memory pointed from c has to be >= memory pointed from t // the char is 8 bit #define F for #define M rand()%s+1+q char a[256], *b=" acemnorsuvwxz\1bdfhkl\1gpqy\1it\1j"; g(c,t)char*c,*t; {static int i,j,k,w,v,n,q,s,r; r=-1; if(c&&t) {strcpy(c,t); // copy the string in the result space if(!k) F(j=i=k=1;b[i];++i) b[i]-1?(a[b[i]]=j):++j; // ini [possible because at start k=0] F(r=i=0;c[i];) {F(;isspace(c[i]);++i); //skip spaces // the start q the end+1 i F(q=i;!isspace(c[i])&&c[i];++i); //skip word F(s=v=i-q-2;--v>0;) //loop for swap letters of the same set if(a[c[j=M]]==a[c[w=M]]&&a[c[j]]) n=c[j],c[j]=c[w],c[w]=n; } } return r; } #include <stdio.h> #define G(x,y) if(x)goto y main() {char a[256],r[256]; l1: gets(a);// i would know the string lenght<256 g(r,a); printf("%s\n",r); G(*a,l1); } ``` [Answer] # Python 3.6, ~~349~~ 340 bytes ``` from itertools import * from random import * import re def S(s): C=lambda c:len(list(takewhile(lambda x:c not in x,('j','it','gqpy','bhkfdl'))));L=[];B=[[]for i in range(5)] for l in s:c=C(l);L+=[c];B[c]+=[l];shuffle(B[c]) return''.join(B[n].pop()for n in L) A=lambda t:re.sub('[A-Za-z]{3,}',lambda x:x[0][0]+S(x[0][1:][:-1])+x[0][-1],t) ``` Indented with tabs. The function is named `A`. It doesn't use brute force, the runtime is deterministic, as OP asked. [Answer] ## Mathematica 232 Bytes ``` StringReplace[#,x:Repeated[WordCharacter,{2,∞}]:>""<>(s=StringTake)[x,{i,i}~Table~{i,StringLength@x}/.Flatten[Thread[#->RandomSample@#]&/@(StringPosition[x~s~{2,-2},#]+1&/@Characters@{"acemnorsuvwxz","bdfhkl","gpqy","it","j"})]]]& ``` The basic idea is to permute the subsets corresponding to the 4 distinct character groups. Probably room for improvement. [Answer] # JavaScript (ES6), ~~380~~ ~~327~~ ~~311~~ 294 Bytes (~~298~~ ~~282~~ 265 Bytes excluding the rules) Thanks to @Shaggy for the useful tips! ``` ((b,d)=>b.replace(/\B[a-z]+\B/gi,f=>(g=>(g.map(j=>(h=d.slice(0,~(rind=d.indexOf(j))?rind:-1),~rind?h.split`,`.length-1:-1)).map((j,k,l,m=[])=>{l.map((n,o)=>n==j?m.push(o):0),sub=m[new Date%(m.length-1)]||k,tmp=g[sub],g[sub]=g[k],g[k]=tmp}),g.join``))([...f])))(s,"aneusvrowxmcz,bhkfdl,gqpy,it"); ``` ``` var f = ((b,d)=>b.replace(/\B[a-z]+\B/gi,f=>(g=>(g.map(j=>(h=d.slice(0,~(rind=d.indexOf(j))?rind:-1),~rind?h.split`,`.length-1:-1)).map((j,k,l,m=[])=>{l.map((n,o)=>n==j?m.push(o):0),sub=m[new Date%(m.length-1)]||k,tmp=g[sub],g[sub]=g[k],g[k]=tmp}),g.join``))([...f]))) var s="Let there be scrambling"; console.log(s); console.log(f(s,"aneusvrowxmcz,bhkfdl,gqpy,it")) s="It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules"; console.log(s); console.log(f(s,"aneusvrowxmcz,bhkfdl,gqpy,it")) ``` Function *f* takes in a string of any kind (single word, multiple words, multiple words with signs in it - which it interprets as word-breaking) and ~~an array~~ a string of "rules" of any length separated by commas. That array of rules, in the case of your question, would be ~~`["aneusvrowxmcz", "bhkfdl", "gqpy", "it"]`~~ `"aneusvrowxmcz,bhkfdl,gqpy,it"` Some letters don't get mixed even though they could, since you stated in your question that letters "may exchange spaces". If I misinterpreted it, I can change the code to always scramble letters that match the rules. I know this is an enormous amount of bytes and it won't be able to compete with golfing languages, but I wanted to try anyway, hope you like it :) Human-readable non-uglified code: ``` ((txt,rules)=>txt.replace(/\B[a-z]+\B/gi,wo=>((w=>(w.map(c=>(h=rules.slice(0, ~(rind=rules.indexOf(c))?rind:-1),~rind?(h.split`,`.length-1):-1)).map((e,i,arr,a=[])=>{ arr.map((x,i)=>(x==e)?a.push(i):0), sub=a[new Date%(a.length-1)]||i, tmp=w[sub], w[sub]=w[i], w[i]=tmp }),w.join``))([...wo]))))(str, "aneusvrowxmcz,bhkfdl,gqpy,it") ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~282~~ 263 bytes -19 bytes thanks to the man (or cat) ceilingcat!! ``` c,o,d,e,g;l(*f){for(char*s[5]={"aneusvrowxmcz","bhkfdl","gqpy","it"},**h,*i=f,*t;*i;){if(isalpha(*i)){for(t=i;isalpha(*i);)i++;e=i-t-2;for(h=s;*h&&e;*h++)for(c=999;--c;)if(o=1+rand(d=1+rand()%e)%e,index(*h,t[d])&&index(*h,t[o]))g=t[d],t[d]=t[o],t[o]=g;}else++i;}} ``` [Try it online!](https://tio.run/##dVNPb9MwFD93n@KpElWcpB0b7DBCDpwQEhIHkJDoenCdl9jMtVPbadpV/eqU51Rry4Eoiu3n59@/JGIqNDfN8Shym1c55k2hk7Rm@9q6REjuUj9/WJT7MTfY@Y2z/XYlXsb5eCmf60rTpFm3OxpUGB/yNJV5qso6T0ORqoLtVZ0oz3UreZIqdkINpSquigVTWVZgqaZhel/EBln6IpWTCdIzy9igpHx8fCymU0HddWLLu8xxUyXV64S9QbpzZSrcJiQizKsFm0yu1nbBWFPG@rBZxspQLpvigNpjlqnicDiuuDIJ28M/180oRgFhvoCSFqPxlwDKQ49aw7OxvYEgeQAOAbcBBDfgg6K9JYJDXkEvlUbqQVDGcFd5sDWoQAg2LiTfIPWigXEE98Lx1VJjlQP3oK1p4kinlYNaOU9EpgLNaaIxBHQeWt29dtgNOk7ctgtaGfSkIHo6QQtrfOAmzOCz2hDfSXEOr5SAXMhBFXAhaFBEHmyE9uSl0@g/PJknM4DdzeD76VzsWnWkhwwnrceusgzii7Gr2bn9fgafTtAUHQeP6w6NwBhFTOYrD6Qy5sxF9JRTd5DOdo2EXxeUdzP4ZvSOglRBcX1OoI95I3mPGrq2RSe4x8u59zP4QSz/yW8QT8nsoDPBdkJidTn6MIOfksLyZ7M52Kjhwh0kabfmbKa2Wts@xtKQg5YICBq35M40SG@LiyHIAT5@YBQllVbGOt9t@u3L1RbFtqxq@ayvahRC0653VxWyp8LVmjT/hiQ68hTViZHRfnEz8sMfE9QKk7eMFXB7Cx/B2EAfyrpTDqubkU4Co862C36YHY5/RK1544/T/i8 "C (clang) – Try It Online") Ungolfed: ``` int func(char*p) { char *groups[] = {"aneusvrowxmcz","bhkfdl","gqpy","it",0}, **g, *s, *t; int n,r,i,l,o; for (s = p; *s;) { if (isalpha(*s)) { t = s; while (*s && isalpha(*s)) s++; // start scrambling l = s - t - 2; for(g=groups; *g && l; *g++) { for(n=999;--n;) { i = 1 + rand() % l; r = 1 + rand() % l; if (strchr(*g, t[i]) && strchr(*g, t[r])) { o=t[i]; t[i]=t[r]; t[r]=o; } } } // end scrambling } else s++; } } ``` [Answer] # JavaScript, 151 bytes Revisiting and expanding on my suggested improvements to [Bumpy's solution](https://codegolf.stackexchange.com/a/120019/58974) all these years later. ``` s=>s.replace(/\B[a-z]+\B/g,m=>[/[^bdf-jklpqty]/g,/[bdfhkl]/g,/[gpqy]/g,/i|t/g].map(r=>m=m.replace(r,c=>d.sort(_=>new Date%3-1).pop(),d=m.match(r)))&&m) ``` [Try it online!](https://tio.run/##dVLNbhMxEL7vU8yFalfdOCoFCSFtpFZICAnBASQk0kCn3smuW6/t2rPZtuLAs/BovEgYJ0p64uTxePz92be4waSjCTzbvNmum21qFklFChY1lfOryyXOnlanV5fzrh6axXK@/HHTrme3dzbc8@NKuvOlNPo7u6@7cL/vml8871ZqwFDGZjE0wxE01rpZtCr5yOXPZuFognfI9OJ8dlap4ENZ1a2MD8i6L2NVVScnQ7XV3iVvSVnfleuyuP7AYBJMZC3cOT854B4ZEJgeGDQ6SGzk7IYgErYw9caSzBAY5zC2CfwaDAuCz5seNySzJNd0xOHGUlsDJrDedXmViybC2sQkHK4Fi1JYYqaYINjxMOE3FFFo/cjWOEpCPqBxkNUzOlbw3myEBSFE4xiFCC6SNub0E035xk5/fVQBhLrfaQTUWhYjethntiTORkvpbXGm4Mt@Pp8Oo0gT22VINLa@giiC/aCKlwou9lASHEKi@5GcphxEzuUjchbaY0SdbdUyzX30Y9fDd1WcK/js7KPEZ9igPZqfcsoktjPnGAJFjYlU8UrBV0H9T2Q7kZLII4yO/ah7alXxWsG3/vkJxEwNPnM@c3EvGr07il57a/2UbXeiNAiwQNKDuHAdwe6/SUAA8Pf3H0mQBudjGjfTw9Ohuf@8h13@vofa8KG6hTJrTWJ@j1ldF1W1/Qc) [Answer] # [Go](https://go.dev), ~~364~~ ~~357~~ 347 bytes ``` import(."math/rand";."regexp") func f(s string)string{return MustCompile(`(\w)(\w+)(\w)`).ReplaceAllStringFunc(s,func(S string)string{k:=S[1:len(S)-1] for i:=range k{for _,l:=range[]string{"acemnorsuvwxz","bdfhkl","gpqy","it","j"}{if o,_:=MatchString("["+l+"]",k[i:i+1]);o{q:=Intn(len(l));k=k[:i]+l[q:q+1]+k[i+1:]}}} return S[:1]+k+S[len(S)-1:]})} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVPBitswEKX0lp_oICi1sZuSW_HiwrLQsoctpW5PTtgo9jjWWpYSSV4nG_IlvSyFfkR_pV_TkZ1dltLDQmwpmtGb996Mf_xc6_vfG140fI3QcqEmot1o46asah371bnq7fs_L_LxMJiylrv6neGqZGdTZnCNuw0LJ1WnCqgCC9YZodbhuBwMus4ouOqsu9DtRkgMlsG8D-mJ_CtchtOvuJG8wHMps-HSR4IKbOwRg-wfvCZJs3yWSFRBFr6dLSaVNiCSlPgQ--bg_17H8nSQL07XGOG3Shvb3fa7OxazVVnVjaTNerPd0yIcvW7Y8SAq0PF1kl5xV9Qjn4DlLJIRW7C4yUUiotkiPNOHbZJeKqcCz0WG4VmTNnkiFpHMt8mWciJKjmbJ4ng8Tk42ZHniz6MsfxBA4fB48vjlq8FE34IghMMkS1LmaoRtJ4oGVkb3Ciq9g5uu3WAJ-hYN-Ljkd3so9ZpNvhBdVwXstZ2r9MNc-XWuWAxZTL3JwnCSpey8KLQpSRc4DRwMWuSmqAmMO7jg7cqIkrz8rgQVsMLtYxCO8NGqN47YOUepQkFfUz4hPbBAH7A-wqGnc-AG4yGkldzDOD9cOTryxYWlDXdDQiWMdUAjRVpoM0LBCuEUN2JdOximZArf_AFSWsHVkEM6HJfQorUDxl53Q8w6ISWl8tIL6IWrdUcoRq8kth6HKNBvhQXvLA6F6q6li60gFC8YlHYjAJIX-0dipMZZlBWsupHgqNd65bWWOH1eK5aXzhPokWg2yrd3cIQE4c49kbDCkURf0_cz1BNKcVNa0JVnMpS3UPNbpFyka4WhPkosY09KarKbe7tRmP97bcnc7iHDDxansuSWFIpcMOhnEgqtrG_gFD7RaPg2b7xIToXg3BZCRJ-x9zcG_vEjC0Be1CeLns4eVSPbTSfRJstnGHb6Tu7vx_Uv) Uses an adaptation of my ["Cambridge Transposition"](https://codegolf.stackexchange.com/a/257251/77309) solution. * -7 bytes from some reorganization * -10 bytes from using string slices and general cleanup [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 241 bytes Breaks, if words contain numbers (which is quite unlikely..) ``` import random,re g=lambda c:sum([(p:="jitgpqybdfhkl".find(c))<0,p<1,p<3,p<7]) def f(m,C=[[],[],[],[],[]]): for c in m[0]:l=C[g(c)];l+=[c];random.shuffle(l) return''.join(C[g(c)].pop()for c in m[0]) h=lambda s:re.sub('(?<=\w)\w+(?=\w)',f,s) ``` [Try it online!](https://tio.run/##VZFNb9wgEIbv/hUjXxa0lpUqh1bOWlGVQ5RLT705PrAw2OxiIIDX2f757dhtqlQC8TUz7/MO4ZpH7@6/hXi7mSn4mCEKp/xURSyG1orpqATIJs0T61ho2vJk8hDerkelx7Mta22cYpLzw10VDl9o3tP82vNCoQbNpuqp7bq@@jR63hSgfQQJxsHU3fWNbZ@6gar0D3bfdrJ/@MNQp3HW2iKzvICIeY5ut6tP3jj2N74OPjD@XzFejB/YqYlYp/nIduzx0L4u/HXZs8d1s6t0lfgtY8oJWujKlwwmwYLWwtn5xUEeRQYBGd8zSOEgZUNvRyQOoWAZjUWKQVJ1IqoEXoOhWotfD6O4IMUipclILBZVBSKB9W5YV0o0EbSJiTScAitoYzFnjAmCnT8i/AWjIFk/Z2scJhKfBPmU3qUsXK7LCspncyEhASEalwVpwfckjdn/wGVN2ixU/0AAhRw3TBBS0mIIKftVMJG52WJq1qo/ydvbbOQZjnHth/bvcJqnkDaozboVv66g/FCXfVFsfyDS2hDY2kqfvBGxka33nN9@Aw "Python 3.8 (pre-release) – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~298~~ ~~281~~ ~~261~~ ~~255~~ 249 bytes ``` import random,re g=lambda c:sum([(p:="jitgpqybdfhkl".find(c))<0,p<1,p<3,p<7]) def f(m,C=[[],[],[],[],[]]): t,*u,v=m[0] for c in u:l=C[g(c)];l+=[c];random.shuffle(l) return t+''.join(C[g(c)].pop()for c in u)+v h=lambda s:re.sub('[A-Za-z]{4,}',f,s) ``` [Try it online!](https://tio.run/##TVFNb9swDL37VxC@xF5Uo0MHbHDrQ9HDsMtOO83wgZGpWIksqfpImg777RntrdsAEdQHH997lL@kydm7Tz5cr3r2LiQIaEc3i0DFvjM470YE2cY8V33l26486LT3z5fdqKajKRul7VjJun64Ff7hPccdx8ehLkZSoKpZPHV9P4j/1lC3BSTxLotTN/e3QwHKBZCgLeTWdE/9nvsN92bb9XK4/62miVNWylBl6gICpRwspO1m0xycttUfSOOdr@p/zertqZjeLMQ2UBPzrtr0jzff8eZ1@PFB/NwIJWJ9TRRThA768ksCHeFMxsDRujOzTJgAIdFLAokWYtL8tiNWgSOcJ22Ia4gJLYYxglOgudfZLYcJT8S1xDAZWIehUQBGMM7ul8xAHUDpEJnDjmCQN4ZSohDBm/xW4U4UkGldTkZbikw@I1uUzsaENjWlgPKzPjERgg/aJmQueIxS6@1XOi@g1YL4KwQI5bTKBJSSk2ZJyS2Ekc1lQ7Fdun5jb89ZyyPswjIP5V7gkGcfV1GrdYOvFxjdvimHoljHj3EZCKxj5c9eFVVTtdzX9fUX "Python 3.8 (pre-release) – Try It Online") [Answer] ## Clojure, ~~326~~ ~~322~~ 324 bytes Update 1: replaced `(map(fn[[k v]]...)...)` with `(for[[k v]...]...)` Update 2: fixed regex, using `\pL` instead of `\w` etc. ``` #(let[G(zipmap"bdfhklgpqyitj""0000001111223")](apply str(flatten(interleave(for[v(re-seq #"\pL+"%)w[(rest(butlast v))]W[(into{}(for[[k v](group-by G w)][k(shuffle v)]))]R[(rest(reductions(fn[r i](merge-with + r{(G i)1})){}w))]][(first v)(map(fn[c r](nth(W(G c))(-(r(G c))1)))w R)(if(second v)(last v))])(re-seq #"\PL+"%))))) ``` I'm looking forward to seeing something shorter. Earlier ungolfed version with a few example runs: ``` (def f #(let[G(zipmap"bdfhklgpqyitj""0000001111223")] ; Create groups, the longest "acemnorsuvwxz" goes to an implicit group nil (apply str(flatten(interleave (for[v (re-seq #"\w+"%) ; Iterate over words w [(rest(butlast v))] ; This holds the middle part W [(into{}(map(fn[[k v]][k(shuffle v)])(group-by G w)))] ; Create shuffled groups R [(rest(reductions(fn[r i](merge-with + r{(G i)1})){}w))]] ; Calculate cumulative sum of group items, used to look-up nth value from shuffled values [(first v) ; First character (map(fn[g r](nth(W g)(-(r g)1)))(map G w)R) ; Shuffled middle part (if(>(count v)1)(last v))]) ; Last character, unless the word is just a single character (re-seq #"\W+"%)))))) ; Interleave with spaces, commas, newline etc. (f "It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant.\n") ; "It is well known that a txet can sitll be read wlihe the irnands of its wrods hvae been seacmlbrd, as lnog as their fisrt and lsat letters plus their oavrell ontlieus rmaein cnontast.\n" ; "It is well kwonn that a text can sitll be raed wlihe the innards of its wrods hvae been seramlbcd, as long as their fisrt and lsat lettres plus their oravell ouiltnes rmeain cnsatont.\n" ; "It is well konwn that a text can still be read while the iarnnds of its words have been sraemlbcd, as lnog as their first and lsat lrttees plus their oaevrll ontlieus remain canntsot.\n" ``` [Answer] # [Perl 6](http://perl6.org/), ~~241~~ 195 bytes Includes +1 byte for `-p` command-line switch. ``` s:g/(<:L>)(<:L>+)(<:L>)/{$0}{[~] $1.comb.pairs.classify({first .value~~*,:k,/<[bdfhkl]>/,/<[gpqy]>/,/<[it]>/,/j/,!0}).values.map({$_».key »=>«$_».value.pick(*)})».List.flat.sort».value}$2/; ``` Ungolfed: ``` s:g/(<:L>)(<:L>+)(<:L>)/{$0}{ [~] $1.comb .pairs .classify({ first .value ~~ *, :k, /<[bdfhkl]>/, /<[gpqy]>/, /<[it]>/, /j/, !0 }) .values .map({ $_».key »=>« $_».value.pick(*) }) ».List .flat .sort ».value }$2/; ``` [Answer] ## C#, ~~438~~ ~~394~~ ~~380~~ 374 bytes ``` namespace System.Text.RegularExpressions{using Linq;s=>Regex.Replace(s,@"\p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b",m=>{var a=m.Value.ToArray();for(int i=1,j;++i<7;){var c=m.Groups[i].Captures;var n=c.Cast<Capture>().Select(p=>p.Index-m.Index).ToList();foreach(Capture p in c){a[j=n[new Random().Next(n.Count)]]=p.Value[0];n.Remove(j);}}return new string(a);});} ``` *Save 10 bytes thanks to @MartinEnder♦.* Annoyingly, [`CaptureCollection` doesn't implement `IEnumerable<T>`](https://stackoverflow.com/questions/19035527/why-can-i-not-call-select-from-a-capturecollection-object) and that's why the `.Cast<Capture>()` is needed. Hopefully, I can combine the Linq query and the `foreach` loop though. I'm sure there's a lot that can be golfed but it took me long enough just to get it working... [Try it online!](https://tio.run/nexus/cs-mono#fVNNb9swDL37VxA5SWtibJddnKYrgm0Y0A1DUmxAXR8Um4mV2ZIryYnTLr89o@1kazO7vJjmx3uPknhQIkdbiBhhvrMOc@/JA7LSSrWCW6ycP8NVmQnzsSoMWiu1ssGzkhupHgKvCcSZsBa@N36LUpt1wskYNlom8FVIxfjf1L@i2j6VKh5bZwh1CO13Aku4BAuXkxeVtZEqrEhbkZF2ZofwYRBej@7E6DFiLKRYrrSx5ah6jPhvFi6SZfora9xV8bBrHOkizt9chXXP1f1iMIS8i@npv0htG2FAkLjc/yGyEv1bPU2FuTZG7Bg/Hsi5LbUBJpUDSY3vhrAO4OJCwhjeB7yzoZv6RB839J@NLgsbysifisKVdEc97Kc2RW0xFVs3PnZMGPfnmGHsWEEnAIX/RSVYwYjgG4/TeDfSunqyPujeBE2NIk7ZkQwKkApi3lvfP3RtIlyTfhUq3MJMqETnJP4bvVOm/KkuleNRRAVFey3h2yh4FU7RE8r1Btn6ldH2Xne0M2yQplRQ62sfMRMd0Puz2IufKe2YztD/aaRDWjBkSzaYx0bkiwxhq01iYZtK8uuVRLOpF9GlKA3o0mXUYAf8jOCEOUORNJDP8u18e29/OPwB "C# (Mono) – TIO Nexus") Formatted/Full version: ``` namespace System.Text.RegularExpressions { using Linq; class P { static void Main() { Func<string, string> f = s => Regex.Replace(s, @"\p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b", m => { var a = m.Value.ToArray(); for (int i = 1, j; ++i < 7;) { var c = m.Groups[i].Captures; var n = c.Cast<Capture>().Select(p => p.Index - m.Index).ToList(); foreach(Capture p in c) { a[j = n[new Random().Next(n.Count)]] = p.Value[0]; n.Remove(j); } } return new string(a); }); Console.WriteLine(f("Scramble words while preserving their outlines")); Console.ReadLine(); } } } ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 104 bytes ``` s|\w+|$t=$&;map{@a=$t=~/\B[$_]\B/g;$t=~s/\B[$_]\B/splice@a,rand@a,1/ge}'^bdf-lqpty',bdfhkl,gqpy,it;$t|ge ``` [Try it online!](https://tio.run/##dVJLbxMxEL7vr5hDREHdJO2hF6pKTS8IiccBJCQIrSbeydqqYzu2N9uIwE9n@ZymyYnTjO2Z77UbJNqrYUi7eX@@G@Wb0avrFYdft3yDw5/p/O7H6OHn/G7aXpdzOl2kYI2SW64juwblctrK77P7RbMc23XI27MarX60dbsO29pk7O9aGYYvKvJqYYV6H5tEvTboQ5QkcWNcS1mLieS7bI2TVFXvMxmMibX06HzvMMCZmLI8ZVLsKGWDt4VQFG4OeAAh4xwXBr8kk9OBTvNGMCtYO@hoauJE1oMa9Zl9aWICh2vIMhorOUtMFGz3MuE3Ehm0LzpBvmLjSHmXMrs8oXdmAxaGNeMyF8OzpIw5/yR92djrr48qSFjpvUZipVD2UfjCluCss5LeVtUhu/K26iAMpl@HJF3j31D5DH41qarZMwxCY0qy7sQpKSGUTD5wLiI1R1bFUk0z3EfftZq@Y/ezs1sEZ7Jhe7Tdl3wFhgtfF4JExUkw/RWI/4lqLw9JbKlz2XdKS4OFb/oUPEzU5AvfiSdrqPPuKHfprfV9sdtCYwAsAOUJ@l2Ln8ayQix/fcgGsQ/jj1eTi8uLYRz@AQ "Perl 5 – Try It Online") ]
[Question] [ [Golunar](https://esolangs.org/wiki/Golunar)/[Unary](https://esolangs.org/wiki/Golunar) is a way to encode all valid [Brainfuck](https://esolangs.org/wiki/Brainfuck) programs, but it is not an enumeration, since most natural numbers do not correspond to a valid program. For the purpose of this challenge, assume a doubly infinite tape and no comments, i.e., a Brainfuck program is valid if and only if it consists solely of the characters `<>+-.,[]` and all left and right brackets match. For example, the empty program, `,[+][-].`, `[>+<[--].]` and `+[+[+][+[+]+]+]+.` are valid Brainfuck programs, while `][`, and `a[]` are not. ### Task Write a program or function that accepts a valid Brainfuck program as input and returns a natural number (**1**, **2**, **3**, …), with the following constraints: * The generated output must be different for all valid Brainfuck programs. * For every natural number **n**, there must be a valid Brainfuck program that, when provided as input, generates the output **n**. ### Additional rules * Given a Brainfuck program of 100 or less bytes, your program or function must finish within one minute. This means that you cannot iterate over all valid Brainfuck programs until you match the input. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # Python 3, ~~443~~ ~~158~~ ~~155~~ ~~154~~ ~~134~~ ~~131~~ ~~128~~ ~~124~~ ~~117~~ ~~116~~ 115 bytes ``` c=d=C=D=0 for e in input():v='[<>,.-+]'.find(e);d=d*8+v;c+=c<0<6<v;c-=d>1>v;C,D=(c,C+1,d,D)[v>6::2] print(-~D*8**C) ``` Several bytes thanks to Sp3000 and Mitch Schwartz :D ## How this works: This maps all valid BF programs into all possible, valid or invalid, BF programs, that don't start with a `[`, in a one-to-one ratio. After that, the new program is simply converted into octal. **Here is the mapping formula:** 1. Separate a BF program into 3 parts. The first part is the largest prefix consisting of only `[` characters. The third part is the largest postfix consisting of only `]` characters. The second part is the middle. 2. Dispose of the first part. These can be recomputed later. 3. Remove all `]` brackets in the third part that match `[` brackets in the second part. These can also be recomputed later. 4. Concatenate the second and third parts together. If you don't understand this explanation, you can find an extended explanation in chat starting [here](http://chat.stackexchange.com/transcript/message/23722568#23722568). **For reference, here are the first 20 programs:** ``` 1 : 2 : < 3 : > 4 : , 5 : . 6 : - 7 : + 8 : [] 9 : <[] 10 : << 11 : <> 12 : <, 13 : <. 14 : <- 15 : <+ 16 : [<] 17 : >[] 18 : >< 19 : >> 20 : >, ``` Here are the first 1000 programs: <http://pastebin.com/qykBWhmD> Here is the program I used to generate them: <http://ideone.com/e8oTVl> **Here is `Hello, World!`:** ``` >>> ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. 457711481836430915510337664562435564418569135809989841510260388418118348571803953323858180392373 ``` [Answer] # Python 2, 157 bytes ``` def f(s,o=0,d=0,D={}):T=s,o,d;x=D[T]=D[T]if T in D else~o and 0**o+sum(f(s[1:],cmp(c,"[")%-3-~o,d or cmp(c,s[0]))for c in"+,-.<>[]")if s else~d<0==o;return+x ``` Still looks pretty golfable, but I'm posting this for now. It uses recursion with a bit of caching. Annoyingly, `D.get` doesn't short circuit for the caching, so I can't save 9 bytes that way... The mapping prioritises length first, then lexicographical order over the ordering `"][><.-,+"` (see output examples below). The main idea is to compare prefixes. The variable `o` keeps track of the number of `[` brackets still open for the current prefix, while the variable `d` takes one of three values indicating: * `d = 1`: The current prefix is lexicographically earlier than `s`. Add all programs with this prefix and length `<= s`, * `d = -1`: The current prefix is lexicographically later than `s`. Add all programs with this prefix and length `< s`. * `d = 0`: The current prefix is a prefix of `s`, so we might change `d` to 1 or -1 later. For example, if we have `s = "[-]"` and our current prefix is `p = "+"`, since `p` is later than `s` lexicographically we know only to add the programs starting with `p` which are strictly shorter than `s`. To give a more detailed example, suppose we have an input program `s = "-[]"`. The first recursive expansion does this: ``` (o == 0) # Adds a program shorter than s if it's valid # For the first expansion, this is 1 for the empty program + f(s[1:], o=-1, d=1) # ']', o goes down by one due to closing bracket + f(s[1:], o=1, d=1) # '[', o goes up by one due to opening bracket + f(s[1:], o=0, d=1) # '>' + f(s[1:], o=0, d=1) # '<' + f(s[1:], o=0, d=1) # '.', d is set to 1 for this and the previous branches # since they are lexicographically earlier than s's first char + f(s[1:], o=0, d=0) # '-', d is still 0 since this is equal to s's first char + f(s[1:], o=0, d=-1) # ',', d is set to -1 for this and the later branches # since they are lexicographically later than s's first char + f(s[1:], o=0, d=-1) # '+' ``` Note how we don't actually use the prefixes in the recursion - all we care about them is captured through the variables `d`, `o` and the shrinking input program `s`. You'll notice a lot of repetition above - this is where caching comes in, allowing us to process 100-char programs well within the time limit. When `s` is empty, we look at `(d>=0 and o==0)`, which decides whether to return 1 (count this program because it's lexicographically early/equal and the program is valid), or 0 (don't count this program). Any situtation with `o < 0` immediately returns `0`, since any programs with this prefix have more `]`s than `[`, and are thus invalid. --- The first 20 outputs are: ``` 1 > 2 < 3 . 4 - 5 , 6 + 7 [] 8 >> 9 >< 10 >. 11 >- 12 >, 13 >+ 14 <> 15 << 16 <. 17 <- 18 <, 19 <+ 20 ``` Using the same Hello World example as @TheNumberOne's answer: ``` >>> f("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.") 3465145076881283052460228065290888888678172704871007535700516169748342312215139431629577335423L ``` [Answer] This answer is a formal proof for the answer by [TheNumberOne](https://codegolf.stackexchange.com/users/32700/thenumberone), [Enumerate valid Brainf\*\*k programs](https://codegolf.stackexchange.com/questions/55363/enumerate-valid-brainfk-programs/55368#55368), where it can be a bit hard to understand the fine points why the enumeration is correct. It's nontrivial to understand why there isn't some invalid program that maps to a number not covered by a valid program. Throughout this answer capitals are used to denote programs, and lowercase variables are used for functions and integers. ~ is the concatenation operator. ***Proposition 1:*** *Let the function f be the program described in that answer. Then for every program U there exists a valid program V such that f(U) = f(V)* **Definition 1:** Let g(X) be the number of `[` that appear in the program X, and let h(X) be the number of `]` that appear. **Definition 2:** Define P(x) to be this function: ``` P(x) = "" (the empty program) when x <= 0 P(x) = "]" when x = 1 P(x) = "]]" when x = 2 etcetera ``` **Definition 3:** Given a program X, denote X1 to be it's largest prefix of `[` characters, X2 its center, and X3 its largest suffix of `]` characters. **Proof of proposition 1:** If g(U) = h(U) then U is a valid program, and we can take V=U. (trivial case). If g(U) < h(U) then we can create V by prepending n = h(U) - g(U) `[` symbols. Obviously f(V) = f(U) as all `[` symbols in the prefix are removed. Now consider g(U) > h(U). Define T = U2 ~ U3. if g(T) <= h(T), then we can construct V by removing n = g(U) - h(U) `[` symbols. So we can assume that h(T) < g(T). Construct V = T ~ P(g(T) - h(T)). We need three small facts to proceed: *Claim 1:* g(U2) = g(T) U3 does not contain any `[` symbols by its definition. As T = U2 ~ U3, its `[` symbols are all in the first part. *Claim 2:* h(U3) < g(T) This follows from noting that h(T) < g(T) and h(U3) < h(U3 ~ U2) = h(T). *Claim 3:* h(V3) = g(U2) - h(U2) ``` h(V3) = h(U3) + g(T) - h(T) using the construction of V h(V3) = h(U3) + g(U2) + g(U3) - h(U2) - h(U3) apply the definition of T h(V3) = g(U2) - h(U2) *one term cancels, g(U3) is always zero, as U3 contains only `]` symbols* ``` Now we show that f(V) = f(U). ``` f(U) = U2 ~ P(h(U3) - g(U2)) = U2 claim 2, definition of P f(V) = U2 ~ P(h(V3) - g(V2)) = U2 ~ P(h(V3) - g(U2)) = U2 ~ P(g(U2) - h(U2) - g(U2)) claim 3 = U2 ~ P(-h(U2)) = U2 definition P ``` This completes the proof. Q.E.D. Let's do uniqueness as well. ***Proposition 2:*** *Let U, V be two diffrent, valid programs. Then f(U) != f(V)* This is fairly straightforward compared to the previous proposition. Let's assume that U2 = V2. But then the only way U and V can be diffrent is by adding or removing n `[` and `]` symbols to U1 and U3 respectively. Yet this changes the output of f, since f will count the number of unmatched `]` symbols in the suffix. Thus U2 != V2. Obviously, this leads to a contradiction. As U2 and V2 are literally contained in the output of f(U) and f(V) respectively, they cannot differ, except at the 'edge', the place where U2 is concatenated with U3. But the first and last symbols of U2 and V2 cannot be `[` or `]` by definition, while those are the only symbols allowed in U1, U3, V1, V3 respectively and respectively again. Thus we get U2 = V2. Q.E.D. ]
[Question] [ ## Story Indiana Jones was exploring a cave where a precious treasure is located. Suddenly, an earthquake happened. When the earthquake ended, he noticed that some rocks that had fallen from the ceiling blocked his way to the treasure. He also noticed that he could push a stone, but since stones were very heavy, he couldn't push [two consecutive stones](http://en.wikipedia.org/wiki/Sokoban#Rules). Your objective is to help Indiana Jones get the treasure. Since it's very hard to push even a single stone, the number of pushes is very important. ## Problem > > Find the best way (where Indiana Jones pushes stones as little as possible), to find the treasure. > > > ## Map (input) The map is an `m` by `n` (both larger than 1) matrix which can contain five kinds of cell: * `0` which means the blank cell, * `1` which means the wall, * `2` which Indiana Jones is located in (only one exists), * `3` which the treasure is located in (only one exists), * and `4`, which means a rock. In the first row of the map, the dimension of the map is specified like `4 6`, and from the second row to the last row of the map, the structure of the cave is specified something like this. ``` 110131 104040 100101 200000 ``` Therefore, the full map is: ``` 4 6 110131 104040 100101 200000 ``` which means ![The map](https://i.stack.imgur.com/9lxR7.png) The map is given by stdin, a file (you can specify the name of the file), or an array in the code which contains only above information. ## Output The minimum amount Indiana Jones should push. If there's no such way, output `X`. [In above case](http://bit.sparcs.org/~differ/sokoban/#2), he can push a stone in the left upward, then he can push a stone in the right rightward to get the treasure. Therefore, the output in this case is `2`. However. in this case : ``` 4 6 111131 104040 100101 200000 ``` (look below section) he can't push right stone because it will destroy the treasure. Also, pushing left stone rightward changes nothing. Therefore, the output is `X`. ## Rules * He can move in only four direction, up, down, left, and right. * He can't push [two consecutive stones](http://en.wikipedia.org/wiki/Sokoban#Rules). * He can't pull any stone, and he can push a stone only in one direction('forward'). * He can't go through walls. Only places he can go are blank cells and the treasure cell. * The stone can't be placed on the treasure. That will destroy the treasure. :( * He can't go outside of the map. ## Goals Program which can handle the most maps (provided at the 'Example' section + others) in a reasonable time (specifically, 10 seconds) and outputs the right answer wins. Here 'others' means example inputs provided in answers. This means you should make a smart algorithm so that other programs can't solve maps that your program can solve, and maps solved by other programs can be solved by your program. However, putting solutions in the code will not considered as valid. ## Note This was originally a mid-term project of an AI class which I listened to, only one thing was different : it was said that there were only *two* rocks. It was said that this problem is NP, but it was also said that a good heuristic algorithm can solve the problem quite efficiently. I used some ideas and heuristics to solve the problem efficiently, and my code could find all solutions of samples very quickly (less than a second). However, when there were more than two rocks, there were some cases where the code couldn't find the answer in a reasonable time. I had some ideas, but some of those were 'wrong', and I couldn't express other ideas to the code. I wanted to see what smart algorithms exist to solve this problem, so I wrote this. Since [I already completed the project](http://bit.sparcs.org/~differ/sokoban/) (btw, images are not mine - I googled those), you don't have to worry about that. ## Examples [Examples can be seen at here.](http://pastebin.com/H6CTVVYp) You can also see examples, and test your results at [here](http://bit.sparcs.org/~differ/sokoban/) (this should work in modern browsers). You can get the map in the format described above, by typing `whatisthis()` in the JS console. <http://bit.sparcs.org/~differ/sokoban/#0> ~ <http://bit.sparcs.org/~differ/sokoban/#19> contains examples which it was originally the class provided. ## Result Sorry, I was late.. quite a lot actually. :P (I was quite too lazy to score. Sorry.) Below is the result. (X: wrong, O: right, ?: takes at least 10s, halted) ``` Map#: 0 1 2 3 4 5 12 15 19 T1 T2 T3 T4 T5 T6 T7 Ruby: X O O ? O O O X ? ? O ? ? ? ? ? Java: O O X O X X O O ? ? O O O X O O ``` (Java 19: took 25s, the result was correct.) (I used ruby 1.9.3 and javac 1.7.0\_13) It seems that the Java algorithm was indeed better. (By the way, I thought of a similar method, but I realized that maps like test map 5 exist.) [Answer] # Ruby - Huge & blostered Somewhat naive implementation that brute-forces it's way through the labyrinth. It's not super fast in some (not so) weird cases. It can be improved by finding better heuristics than just "if it's closer to the treasure, we'll want to investigate first", but the general ideas are there. It'll also show you how Indiana got his hands on the treasure in case he can, that's bonus. ``` EMPTY = '0' WALL = '1' INDY = '2' GOAL = '3' ROCK = '4' map=%q|8 8 00001000 00000100 00000010 00000010 03004040 10000010 10000100 10000102| def deep_dup(arr) dupl = arr.dup (0..dupl.size-1).to_a.each do |i| dupl[i] = dupl[i].dup end return dupl end class Map @@visited = [] attr_reader :mapdata, :indy_r, :indy_c, :prev def self.parse(str) lines = str.split("\n") mapdata = [] indy_r = -1 indy_c = -1 lines[1..-1].each_with_index do |line, idx| row = ((mapdata ||= [])[idx] ||= []) line.split(//).each_with_index do |c, cidx| if c==INDY indy_r = idx indy_c = cidx row[cidx] = EMPTY else row[cidx] = c end end end return Map.new(mapdata, indy_r, indy_c) end def initialize(mapdata, indy_r, indy_c, prev = nil, pushed = false) @mapdata = mapdata @mapdata.freeze @mapdata.each {|x| x.freeze} @indy_r = indy_r @indy_c = indy_c @prev = prev @pushed = pushed end def visit! @@visited << self end def visited? @@visited.include?(self) end def pushes pushes = @pushed ? 1 : 0 if @prev pushes += @prev.pushes end return pushes end def history return @prev ? [[email protected]](/cdn-cgi/l/email-protection) : 0 end def next_maps maps = [] [[-1, 0], [1, 0], [0, -1], [0, 1]].each do |dr, dc| new_i_r = self.indy_r + dr new_i_c = self.indy_c + dc if new_i_r >= 0 && new_i_r < @mapdata.size && new_i_c >= 0 && new_i_c < @mapdata[0].size new_map = nil pushed = false case @mapdata[new_i_r][new_i_c] when EMPTY, GOAL then new_map = @mapdata when ROCK then if @mapdata[new_i_r+dr] && @mapdata[new_i_r+dr][new_i_c+dc] == EMPTY new_map = deep_dup(@mapdata) new_map[new_i_r][new_i_c] = EMPTY new_map[new_i_r+dr][new_i_c+dc] = ROCK pushed = true end end if new_map && !@@visited.include?(new_map = Map.new(new_map, new_i_r, new_i_c, self, pushed)) maps << new_map end end end return maps end def wins? return @mapdata[@indy_r][@indy_c] == GOAL end def to_s str = '' @mapdata.each_with_index do |row, r| row.each_with_index do |col, c| if r == @indy_r and c == @indy_c then str += 'I' else case col when EMPTY then str += '_' when WALL then str+= '#' when ROCK then str += 'O' when GOAL then str += '$' end end end str += "\n" end return str end def ==(other) return (self.mapdata == other.mapdata) && (self.indy_r == other.indy_r) && (self.indy_c == other.indy_c) end def dist_to_treasure if @distance.nil? @mapdata.each_with_index do |r, ri| r.each_with_index do |c, ci| if c == GOAL @distance = Math.sqrt((ri - @indy_r)**2 + (ci - @indy_c)**2) return @distance end end end end return @distance end def <=>(other) dist_diff = self.dist_to_treasure <=> other.dist_to_treasure if dist_diff != 0 return dist_diff else return self.pushes <=> other.pushes end end end scored = nil root = Map.parse(map) to_visit = [root] until to_visit.empty? state = to_visit.pop next if state.visited? if state.wins? && (scored.nil? || scored.pushes > state.pushes) scored = state end state.visit! to_visit += state.next_maps to_visit.reject! {|x| x.visited? || (scored && scored.pushes <= x.pushes) } to_visit.sort! to_visit.reverse! end puts scored ? scored.pushes : 'X' exit(0) unless scored steps = [scored] curr = scored while curr = curr.prev steps << curr end puts "\nDetails of the path:" steps.reverse.each_with_index do |step, idx| puts "Step ##{idx} (history: #{step.history}, pushes so far: #{step.pushes})" puts step puts end ``` **Edit:** I though of ways to possibly greatly improve the performance of this in non-obvious situations (where it currently sucks green eggs) by dropping simple movement evaluation (e.g. only care about when indy pushes rocks and/or gets to the treasure). I'll probably update the code later, once I've had time to implement. [Answer] ## Java - A bit smarter / faster Quite a bit of code there. I's trying to be faster by evaluating the pushes in order of "how likely is this to free a way to the treasure", which itself is based on two Dijkstra traversals (one stops when encountering rocks, the other ignores rocks). It's working pretty nicely, and the one example from the pastebin that appears to be troublesome for the author is solved in circa 2 seconds by this implementation. Some other examples take up to 30-40 seconds, which I still find too long, but I couldn't find a way to improve on that without breaking the stuff :) I've split my stuff in several files to get a better structure out (also why I switched to Java from ruby): Entry point: ``` import java.util.Date; public class IndianaJones { public static void main(final String[] args) throws Exception { final Maze maze = new Maze(System.in); final Date startAt = new Date(); final int solution = maze.solve(); final Date endAt = new Date(); System.out.printf("Found solution: %s in %d ms.", solution < Integer.MAX_VALUE ? solution : "X", endAt.getTime() - startAt.getTime()); } } ``` Direction helper enum: ``` enum Direction { UP(-1, 0), DOWN(1, 0), LEFT(0, -1), RIGHT(0, 1); public final int drow; public final int dcol; private Direction(final int drow, final int dcol) { this.drow = drow; this.dcol = dcol; } public final Direction opposite() { switch (this) { case UP: return DOWN; case DOWN: return UP; case LEFT: return RIGHT; case RIGHT: return LEFT; } return null; } } ``` An abstract class to represent a located part of the "maze": ``` abstract class PointOfInterest { public final int row; public final int col; protected PointOfInterest(final int row, final int col) { this.row = row; this.col = col; } public final boolean isAt(final int row, final int col) { return this.row == row && this.col == col; } @Override public final String toString() { return getClass().getSimpleName() + "(" + row + ", " + col + ")"; } @Override public final int hashCode() { return row ^ col; } @Override public final boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof PointOfInterest)) return false; if (!getClass().equals(obj.getClass())) return false; final PointOfInterest other = (PointOfInterest) obj; return row == other.row && col == other.col; } } ``` And finally, the maze itself: ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.EnumSet; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; public class Maze { private static final char WALL = '1'; private static final char INDY = '2'; private static final char GOAL = '3'; private static final char ROCK = '4'; private final Maze parent; private final Set<Maze> visited; private final boolean[][] map; private final int[][] dijkstra; private int[][] dijkstraGhost; private String stringValue = null; private int shortestSolution = Integer.MAX_VALUE; private Goal goal = null; private Indy indy = null; private Set<Rock> rocks = new HashSet<>(); private Maze(final Maze parent, final Rock rock, final Direction direction) { this.parent = parent; this.visited = parent.visited; map = parent.map; dijkstra = new int[map.length][map[rock.row].length]; for (final int[] part : dijkstra) Arrays.fill(part, Integer.MAX_VALUE); goal = new Goal(parent.goal.row, parent.goal.col); indy = new Indy(rock.row, rock.col); for (final Rock r : parent.rocks) if (r == rock) rocks.add(new Rock(r.row + direction.drow, r.col + direction.dcol)); else rocks.add(new Rock(r.row, r.col)); updateDijkstra(goal.row, goal.col, 0, true); } public Maze(final InputStream is) { this.parent = null; this.visited = new HashSet<>(); try (final BufferedReader br = new BufferedReader(new InputStreamReader(is))) { String line = br.readLine(); final String[] sizeParts = line.split(" "); final int height = Integer.parseInt(sizeParts[0]); final int width = Integer.parseInt(sizeParts[1]); map = new boolean[height][width]; dijkstra = new int[height][width]; int row = 0; while ((line = br.readLine()) != null) { for (int col = 0; col < line.length(); col++) { final char c = line.charAt(col); map[row][col] = c == WALL; dijkstra[row][col] = Integer.MAX_VALUE; if (c == INDY) { if (indy != null) throw new IllegalStateException("Found a second indy!"); indy = new Indy(row, col); } else if (c == GOAL) { if (goal != null) throw new IllegalStateException("Found a second treasure!"); goal = new Goal(row, col); } else if (c == ROCK) { rocks.add(new Rock(row, col)); } } row++; } updateDijkstra(goal.row, goal.col, 0, true); } catch (final IOException ioe) { throw new RuntimeException("Could not read maze from InputStream", ioe); } } public int getShortestSolution() { Maze ptr = this; while (ptr.parent != null) ptr = ptr.parent; return ptr.shortestSolution; } public void setShortestSolution(int shortestSolution) { Maze ptr = this; while (ptr.parent != null) ptr = ptr.parent; ptr.shortestSolution = Math.min(ptr.shortestSolution, shortestSolution); } private final boolean isRepeat(final Maze maze) { return this.visited.contains(maze); } private final void updateDijkstra(final int row, final int col, final int value, final boolean force) { if (row < 0 || col < 0 || row >= dijkstra.length || col >= dijkstra[row].length) return; if (map[row][col] || isRockPresent(row, col)) return; if (dijkstra[row][col] <= value && !force) return; dijkstra[row][col] = value; updateDijkstra(row - 1, col, value + 1, false); updateDijkstra(row + 1, col, value + 1, false); updateDijkstra(row, col - 1, value + 1, false); updateDijkstra(row, col + 1, value + 1, false); } private final void updateDijkstraGhost(final int row, final int col, final int value, final boolean force) { if (row < 0 || col < 0 || row >= dijkstra.length || col >= dijkstra[row].length) return; if (map[row][col] || isRockPresent(row, col)) return; if (dijkstraGhost[row][col] <= value && !force) return; dijkstraGhost[row][col] = value; updateDijkstraGhost(row - 1, col, value + 1, false); updateDijkstraGhost(row + 1, col, value + 1, false); updateDijkstraGhost(row, col - 1, value + 1, false); updateDijkstraGhost(row, col + 1, value + 1, false); } private final int dijkstraScore(final int row, final int col) { if (row < 0 || col < 0 || row >= dijkstra.length || col >= dijkstra[row].length) return Integer.MAX_VALUE; return dijkstra[row][col]; } private final int dijkstraGhostScore(final int row, final int col) { if (dijkstraGhost == null) { dijkstraGhost = new int[map.length][map[indy.row].length]; for (final int[] part : dijkstraGhost) Arrays.fill(part, Integer.MAX_VALUE); updateDijkstraGhost(goal.row, goal.col, 0, true); } if (row < 0 || col < 0 || row >= dijkstra.length || col >= dijkstra[row].length) return Integer.MAX_VALUE; return dijkstraGhost[row][col]; } private boolean isRockPresent(final int row, final int col) { for (final Rock rock : rocks) if (rock.isAt(row, col)) return true; return false; } public boolean isEmpty(final int row, final int col) { if (row < 0 || col < 0 || row >= map.length || col >= map[row].length) return false; return !map[row][col] && !isRockPresent(row, col) && !goal.isAt(row, col); } public int solve() { return solve(0); } private int solve(final int currentDepth) { System.out.println(toString()); visited.add(this); if (isSolved()) { setShortestSolution(currentDepth); return 0; } if (currentDepth >= getShortestSolution()) { System.out.println("Aborting at depth " + currentDepth + " because we know better: " + getShortestSolution()); return Integer.MAX_VALUE; } final Map<Rock, Set<Direction>> nextTries = indy.getMoveableRocks(); int shortest = Integer.MAX_VALUE - 1; for (final Map.Entry<Rock, Set<Direction>> tries : nextTries.entrySet()) { final Rock rock = tries.getKey(); for (final Direction dir : tries.getValue()) { final Maze next = new Maze(this, rock, dir); if (!isRepeat(next)) { final int nextSolution = next.solve(currentDepth + 1); if (nextSolution < shortest) shortest = nextSolution; } } } return shortest + 1; } public boolean isSolved() { return indy.canReachTreasure(); } @Override public String toString() { if (stringValue == null) { final StringBuilder out = new StringBuilder(); for (int row = 0; row < map.length; row++) { if (row == 0) { out.append('\u250C'); for (int col = 0; col < map[row].length; col++) out.append('\u2500'); out.append("\u2510\n"); } out.append('\u2502'); for (int col = 0; col < map[row].length; col++) { if (indy.isAt(row, col)) out.append('*'); else if (goal.isAt(row, col)) out.append("$"); else if (isRockPresent(row, col)) out.append("@"); else if (map[row][col]) out.append('\u2588'); else out.append(base64(dijkstra[row][col])); } out.append("\u2502\n"); if (row == map.length - 1) { out.append('\u2514'); for (int col = 0; col < map[row].length; col++) out.append('\u2500'); out.append("\u2518\n"); } } stringValue = out.toString(); } return stringValue; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!obj.getClass().equals(getClass())) return false; final Maze other = (Maze) obj; if (other.map.length != map.length) return false; for (int row = 0; row < map.length; row++) { if (other.map[row].length != map[row].length) return false; for (int col = 0; col < map[row].length; col++) if (other.map[row][col] != map[row][col]) return false; } return indy.equals(other.indy) && rocks.equals(other.rocks) && goal.equals(other.goal); } @Override public int hashCode() { return getClass().hashCode() ^ indy.hashCode() ^ goal.hashCode() ^ rocks.hashCode(); } private final class Goal extends PointOfInterest { public Goal(final int row, final int col) { super(row, col); } } private final class Indy extends PointOfInterest { public Indy(final int row, final int col) { super(row, col); } public boolean canReachTreasure() { return dijkstraScore(row, col) < Integer.MAX_VALUE; } public SortedMap<Rock, Set<Direction>> getMoveableRocks() { final SortedMap<Rock, Set<Direction>> out = new TreeMap<>(); @SuppressWarnings("unchecked") final Set<Direction> checked[][] = new Set[map.length][map[row].length]; lookForRocks(out, checked, row, col, null); return out; } private final void lookForRocks(final Map<Rock, Set<Direction>> rockStore, final Set<Direction>[][] checked, final int row, final int col, final Direction comingFrom) { if (row < 0 || col < 0 || row >= checked.length || col >= checked[row].length) return; if (checked[row][col] == null) checked[row][col] = EnumSet.noneOf(Direction.class); if (checked[row][col].contains(comingFrom)) return; for (final Rock rock : rocks) { if (rock.row == row && rock.col == col) { if (rock.canBeMoved(comingFrom) && rock.isWorthMoving(comingFrom)) { if (!rockStore.containsKey(rock)) rockStore.put(rock, EnumSet.noneOf(Direction.class)); rockStore.get(rock).add(comingFrom); } return; } } if (comingFrom != null) checked[row][col].add(comingFrom); for (final Direction dir : Direction.values()) if (comingFrom == null || dir != comingFrom.opposite()) if (isEmpty(row + dir.drow, col + dir.dcol) || isRockPresent(row + dir.drow, col + dir.dcol)) lookForRocks(rockStore, checked, row + dir.drow, col + dir.dcol, dir); } } private final class Rock extends PointOfInterest implements Comparable<Rock> { public Rock(final int row, final int col) { super(row, col); } public boolean canBeMoved(final Direction direction) { return isEmpty(row + direction.drow, col + direction.dcol); } public boolean isWorthMoving(final Direction direction) { boolean worthIt = false; boolean reachable = false; int emptyAround = 0; for (final Direction dir : Direction.values()) { reachable |= (dijkstraScore(row, col) < Integer.MAX_VALUE); emptyAround += (isEmpty(row + dir.drow, col + dir.dcol) ? 1 : 0); if (dir != direction && dir != direction.opposite() && dijkstraScore(row + dir.drow, col + dir.dcol) < Integer.MAX_VALUE) worthIt = true; } return (emptyAround < 4) && (worthIt || !reachable); } public int proximityIndice() { final int ds = min(dijkstraScore(row - 1, col), dijkstraScore(row + 1, col), dijkstraScore(row, col - 1), dijkstraScore(row, col + 1)); if (ds < Integer.MAX_VALUE) return ds; else return min(dijkstraGhostScore(row - 1, col), dijkstraGhostScore(row + 1, col), dijkstraGhostScore(row, col - 1), dijkstraGhostScore(row, col + 1)); } @Override public int compareTo(Rock o) { return new Integer(proximityIndice()).compareTo(o.proximityIndice()); } } private static final char base64(final int i) { if (i >= 0 && i <= 9) return (char) ('0' + i); else if (i < 36) return (char) ('A' + (i - 10)); else return ' '; } private static final int min(final int i1, final int i2, final int... in) { int min = Math.min(i1, i2); for (final int i : in) min = Math.min(min, i); return min; } } ``` [Answer] ## C++ 14 out of 16 The algorithm is inefficient and memory hungry. Additionally I couldn't afford the time to tidy it up, but I will when I have more time ;) An interesting point is that my algorithm fails at the same test maps as the questioner's. On my ancient notebook the process starts swapping for the T4 and T6 maps. Map 3 takes quite long, but is solved in time. All others are solved nearly instant. So I'll have to figure out how to solve T4 and T6 and try the algorithm on a machine with more memory. Eventually I can solve T4 and T6 there. I'll keep the post updated... Below is the result. (X: wrong, O: right, ?: takes at least 10s, halted) ``` Map# : 0 1 2 3 4 5 12 15 19 T1 T2 T3 T4 T5 T6 T7 C++ (foobar): O O O O O O O O O O O O ? O ? O Ruby (Romain): X O O ? O O O X ? ? O ? ? ? ? ? Java (Romain): O O X O X X O O ? ? O O O X O O ``` As the source code is quite long and not really nice to read... Basically it just looks for all rocks that can be reached by Indiana Jones. For the rocks that can be reached, it stores the information into which directions it can be moved. So a list of possible moves for the current map is created. For each of these possible moves a copy of the map is created and the move applied. For the newly created maps, the algorithm will check again which moves can be applied... This is done until either no further moves are possible or a way to the treasure chest is found. As the algorithm first tries all moves that would only take one movement to reach the chest, then all that would take two, and so on... the first way found is also automatically the shortest. To prevent loops, the algorithm remembers for every map what moves could be applied. If another map is created that results in a list of moves that were already found before, then they're silently dropped, as they're already being processed. Unfortunately it's not possible to execute every move only once, as there could be maps that require a rock to be moved over the same field several times. Otherwise I could save a lot of memory. Additionally to solve maps like map 3 in time, the algorithm ignores all rocks that can be walked around... So on map 3 the rock in the middle of nowhere will be moved around, but only until there are no more walls around it. The code can be compiled with g++ --std=c++0x with g++ version 4.4.3 or newer. ``` #include <vector> #include <iostream> #include <iterator> #include <sstream> #include <unordered_set> #include <utility> enum class dir : char { up, down, left, right }; enum class field : char { floor, wall, indiana, treasure, rock, border, visited }; class pos { private: int x, y; field f_type; public: pos() : x{-1}, y{-1}, f_type{field::border} {} pos(int x, int y, field f_type) : x{x}, y{y}, f_type{f_type} {} const field& get() { return f_type; } friend class map; friend class move; bool operator==(const pos& other) const { return x == other.x && y == other.y && f_type == other.f_type; } }; class move { private: pos position; dir direction; public: move(pos& position, dir&& direction) : position(position), direction(direction) {} bool operator==(const move& other) const { return position == other.position && direction == other.direction; } int int_value() const { return static_cast<char>(direction) + position.x + position.y + static_cast<char>(position.f_type); } std::string str() const; friend class map; }; std::string move::str() const { std::string direction_str; switch(direction) { case dir::up: direction_str = "up"; break; case dir::down: direction_str = "down"; break; case dir::left: direction_str = "left"; break; case dir::right: direction_str = "right"; break; } std::ostringstream oss{}; oss << "move x" << position.x << " y" << position.y << " " << direction_str; return oss.str(); } std::ostream& operator<<(std::ostream& os, const move& move_object) { return os << move_object.str(); } namespace std { template<> struct hash< ::move> { size_t operator()(const ::move& o) const { return hash<int>()(o.int_value()); } }; } class constellation { private: const std::unordered_set<move> moves; public: constellation(const std::unordered_set<move>& moves) : moves(moves) {} bool operator==(const constellation& other) const { if (moves.size() != other.moves.size()) return false; for (auto i = moves.begin(); i != moves.end(); ++i) { if (!other.moves.count(*i)) return false; } return true; } int int_value() const { int v = 0; for (auto i = moves.begin(); i != moves.end(); ++i) { v += i->int_value(); } return v; } }; namespace std { template<> struct hash< ::constellation> { size_t operator()(const ::constellation& o) const { return hash<int>()(o.int_value()); } }; } class map { private: pos* previous; pos start, border; std::vector< std::vector<pos> > rep; void init(const std::string&); public: map(std::istream& input) : previous{} { init(static_cast<std::stringstream const&>(std::stringstream() << input.rdbuf()).str()); } map& move(const move& m) { pos source = m.position; pos& target = get(source, m.direction); target.f_type = source.f_type; source.f_type = field::indiana; rep[start.y][start.x].f_type = field::floor; start = source; rep[start.y][start.x].f_type = field::indiana; return *this; } std::string str() const; pos& get() { return start; } pos& get(pos& position, const dir& direction) { int tx = position.x, ty = position.y; switch(direction) { case dir::up: --ty; break; case dir::down: ++ty; break; case dir::left: --tx; break; case dir::right: ++tx; break; } previous = &position; if (tx >= 0 && ty >= 0 && static_cast<int>(rep.size()) > ty && static_cast<int>(rep[ty].size()) > tx) { pos& tmp = rep[ty][tx]; return tmp; } border.x = tx; border.y = ty; return border; } pos& prev() { return *previous; } void find_moves(std::unordered_set< ::move>& moves, bool& finished) { map copy = *this; auto& rep = copy.rep; bool changed = true; while (changed) { changed = false; for (auto row = rep.begin(); row != rep.end(); ++row) { for (auto col = row->begin(); col != row->end(); ++col) { // check if the field is of interest if (col->f_type == field::floor || col->f_type == field::treasure || col->f_type == field::rock) { // get neighbours pos& up = copy.get(*col, dir::up); pos& down = copy.get(*col, dir::down); pos& left = copy.get(*col, dir::left); pos& right = copy.get(*col, dir::right); // ignore uninteresting rocks if (col->f_type == field::rock && (up.f_type == field::floor || up.f_type == field::indiana || up.f_type == field::visited) && (down.f_type == field::floor || down.f_type == field::indiana || down.f_type == field::visited) && (left.f_type == field::floor || left.f_type == field::indiana || left.f_type == field::visited) && (right.f_type == field::floor || right.f_type == field::indiana || right.f_type == field::visited)) { pos& upper_left = copy.get(up, dir::left); pos& lower_left = copy.get(down, dir::left); pos& upper_right = copy.get(up, dir::right); pos& lower_right = copy.get(down, dir::right); if ((upper_left.f_type == field::floor || upper_left.f_type == field::indiana || upper_left.f_type == field::visited) && (lower_left.f_type == field::floor || lower_left.f_type == field::indiana || lower_left.f_type == field::visited) && (upper_right.f_type == field::floor || upper_right.f_type == field::indiana || upper_right.f_type == field::visited) && (lower_right.f_type == field::floor || lower_right.f_type == field::indiana || lower_right.f_type == field::visited)) { continue; } } // check if the field can be reached if (up.f_type == field::visited || up.f_type == field::indiana) { if (col->f_type == field::rock && (down.f_type == field::visited || down.f_type == field::floor || down.f_type == field::indiana)) { auto insertion = moves.insert( ::move(*col, dir::down)); if (insertion.second) { changed = true; } } else if (col->f_type == field::floor) { changed = true; col->f_type = field::visited; } else if (col->f_type == field::treasure) { finished = true; return; } } if (down.f_type == field::visited || down.f_type == field::indiana) { if (col->f_type == field::rock && (up.f_type == field::visited || up.f_type == field::floor || up.f_type == field::indiana)) { auto insertion = moves.insert( ::move(*col, dir::up)); if (insertion.second) { changed = true; } } else if (col->f_type == field::floor) { changed = true; col->f_type = field::visited; } else if (col->f_type == field::treasure) { finished = true; return; } } if (left.f_type == field::visited || left.f_type == field::indiana) { if (col->f_type == field::rock && (right.f_type == field::visited || right.f_type == field::floor || right.f_type == field::indiana)) { auto insertion = moves.insert( ::move(*col, dir::right)); if (insertion.second) { changed = true; } } else if (col->f_type == field::floor) { changed = true; col->f_type = field::visited; } else if (col->f_type == field::treasure) { finished = true; return; } } if (right.f_type == field::visited || right.f_type == field::indiana) { if (col->f_type == field::rock && (left.f_type == field::visited || left.f_type == field::floor || left.f_type == field::indiana)) { auto insertion = moves.insert( ::move(*col, dir::left)); if (insertion.second) { changed = true; } } else if (col->f_type == field::floor) { changed = true; col->f_type = field::visited; } else if (col->f_type == field::treasure) { finished = true; return; } } } } } } } }; void map::init(const std::string& in) { bool first = true; for(auto i = in.begin(); i != in.end(); ++i) { if (*i == '\n') { first = false; rep.push_back({}); continue; } else if (first) continue; field tmp(static_cast<field>(*i - '0')); pos current(rep.back().size(), rep.size() - 1, tmp); switch(tmp) { case field::indiana: start = current; case field::floor: case field::wall: case field::treasure: case field::rock: rep.back().push_back(current); break; default: std::cerr << "Invalid field value '" << (char) (static_cast<char>(tmp) + 48) << '\'' << std::endl; } } } std::string map::str() const { std::string t{}; for (auto row = rep.begin(); row != rep.end(); ++row) { for (auto col = row->begin(); col != row->end(); ++col) { t += static_cast<char>(col->f_type) + '0'; } t += '\n'; } return t; } std::ostream& operator<<(std::ostream& os, const map& map_object) { return os << map_object.str(); } int solve(map&& data) { int moves_taken = -1; bool finished = false; std::vector<map> current_maps{data}, next_maps; std::unordered_set<constellation> known_constellations; while (!finished && !current_maps.empty()) { for (auto i = current_maps.begin(); i != current_maps.end(); ++i) { std::unordered_set<move> moves; i->find_moves(moves, finished); auto result = known_constellations.insert(constellation(moves)); if (!result.second) { continue; // this map constellation was already seen. prevent loops... } if (finished) break; for (auto m = moves.begin(); m != moves.end(); ++m) { map map_copy = *i; map_copy.move(*m); next_maps.push_back(map_copy); } } ++moves_taken; current_maps = std::move(next_maps); } if (!finished && current_maps.empty()) return -1; return moves_taken; } int main(int argc, char* argv[]) { map data{std::cin}; int moves_taken = solve(std::move(data)); if (moves_taken == -1) std::cout << "X" << std::endl; else std::cout << moves_taken << std::endl; return 0; } ``` Edit: The program takes its input from stdin and ignores the first line containing the size of the map. It checks if only allowed characters in the map are used, but doesn't verify that there's only one Indiana Jones and one treasure chest. So it's possible to place more than one and the least moves required to reach one of the chests is printed to stdout. Any invalid characters in the map are skipped and the program will try to calculate the least amount of moves for the resulting map. The calculation will start when stdin is closed (on my system ctrl + d). ]
[Question] [ We all know that programmers tend to be lazy. In order to maximize your free time, you decide to write a program that outputs a minimal number of keystrokes for text fed into it. [![](https://i.stack.imgur.com/Ppffu.png)](https://en.wikipedia.org/wiki/File:Qwerty.svg) **Input**: Text that has to be converted into keystrokes. You may decide on how to input the text (STDIN / reading from a file provided in the arguments) **Output**: The necessary actions in the following format: * They must be numbered * `H`it: Pressing a key and immediately releasing it * `P`ress: Pressing a key and not releasing it (this will never be optimal when the key is `R`eleased as the next keystroke) * `R`elease: Releasing a `P`ressed key **Example**: Input: ``` Hello! ``` Output: A naive solution would be: ``` 1 P Shift 2 H h 3 R Shift 4 H e 5 H l 6 H l 7 H o 8 P Shift 9 H 1 10 R Shift ``` This would be more efficient: ``` 1 P Shift 2 H h 3 H 1 4 R Shift 5 H Left 6 H e 7 H l 8 H l 9 H o ``` **Environment:** * The editor uses a monospaced font * Text is soft wrapped at 80 characters * Arrow up and Arrow down preserve the column, even if there are shorter lines in between * The clipboard is assumed to be empty * Num lock is assumed to be enabled * Caps lock is assumed to be disabled * Caps lock only works for the letters (i.e. no Shift Lock) *Hotkeys / Shortcuts*: * `Home`: Jump to the beginning of the current line * `End`: Jump to the end of the current line * `Ctrl`+`A`: Mark everything * `Ctrl`+`C`: Copy * `Ctrl`+`X`: Cut * `Ctrl`+`V`: Paste * `Shift`+Cursor moving: Marking * `Ctrl`+`F`: Opens a search dialog. + Stupid text matching, no Regular Expressions + Case sensitive + Searches wrap around + Single line text input for the search + The input is prefilled with the current selection, unless there is a newline in between, the complete input is selected + Copying / Pasting works as usual + Pressing `Enter` performs the search, selecting the first match after the current cursor position * `F3`: Repeat last search * `Ctrl`+`H`: Opens a replace dialog + Stupid text matching, no Regular Expressions + Case sensitive + Replace All, with wrap around + Single line text inputs + The search input is prefilled with the current selection, unless there is a newline in between, the complete input is selected + The replace input is empty + Copying / Pasting works as usual + `Tab` jumps to the replace input + Pressing `Enter` performs the replace all. The cursor is placed after the last replacement **Rules**: * Solutions must be a complete program that compiles / parses and executes without any further modification * The keyboard displayed above is the keyboard to use + It is not required to handle characters that cannot be typed with it * Every key must be released at the end * The cursor does not need to be at the end of file at the end **Scoring**: Your score is sum the amount of actions needed to type the following texts. The winner is the solution with the lowest score. Using my naive solution I get `1371 + 833 + 2006 = 4210`. Beat it! I will pick a winner in two weeks. 1 My naive solution ``` number = 1 H = (char) -> console.log "#{number++} H #{char}" P = (char) -> console.log "#{number++} P #{char}" R = (char) -> console.log "#{number++} R #{char}" strokes = (text) -> shiftActive = no for char in text if /^[a-z]$/.test char if shiftActive R "Shift" shiftActive = no H char else if /^[A-Z]$/.test char unless shiftActive P "Shift" shiftActive = yes H char.toLowerCase() else table = '~': '`' '!': 1 '@': 2 '#': 3 '$': 4 '%': 5 '^': 6 '&': 7 '*': 8 '(': 9 ')': 0 '_': '-' '+': '=' '|': '\\' '<': ',' '>': '.' '?': '/' ':': ';' '"': "'" '{': '[' '}': ']' if table[char]? unless shiftActive P "Shift" shiftActive = yes H table[char] else H switch char when " " then "Space" when "\n" then "Enter" when "\t" then "Tab" else if shiftActive R "Shift" shiftActive = no char R "Shift" if shiftActive input = "" process.stdin.on 'data', (chunk) -> input += chunk process.stdin.on 'end', -> strokes input ``` 2 Easy repetition ``` AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ``` 3 More complex repetition ``` We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it And if you ask me how I'm feeling Don't tell me you're too blind to see Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you (Ooh, give you up) (Ooh, give you up) (Ooh) Never gonna give, never gonna give (Give you up) (Ooh) Never gonna give, never gonna give (Give you up) We've know each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you ``` --- You can use [the replay program](http://jsfiddle.net/TimWolla/M4VNM/) written by me to test your solutions (Note: It does not support Searching / Replacing yet, everything else should work). [Answer] # Haskell 1309 + 457 + 1618=3384 Finally, an answer (score greatly improved once I realised there's tabs in your first test-had to edit question to see those). Compile with `ghc`, supply input on stdin. Example: ``` $ ghc keyboard.hs && echo hello|./keyboard 1 H h 2 H e 3 H l 4 H l 5 H o 6 H Enter ``` I tried the obvious stuff like Dijkstra but it was way too slow, even after reducing the branching to the only useful moves, which are: output the next key, or copy from the start of the line (Shift+Home, Ctrl+C, End), or paste. So, this approach uses a fixed-length clipboard, copies when a line prefix is about to become 'useful', and keeps using that prefix as long as it would be pasteable on more lines than the prefixes of lines it reaches next. When it can't use the clipboard, it falls back on the naive solution, so it's guaranteed to beat it once the length chosen is more than the cost of a copy. The minimum score is achieved when the prefix length is chosen to fit "Never gonna ". There are ways to improve on this, but I've had enough of reading Rick Astley. ``` import Data.List (isPrefixOf,isInfixOf) import Control.Monad (foldM) plen=12 softlines text=sl 0 [] text where sl n [] [] = [] sl n acc [] = [(n,reverse acc)] sl n acc (x:xs) |x=='\n'||length acc==79=(n,reverse (x:acc)):(sl (n+1) [] xs) |otherwise=sl n (x:acc) xs pasteable (a,b) (c,d)=(c>a && b`isInfixOf`d) || (c==a && b`isInfixOf`(drop (length b) d)) findprefixes l=filter (\(a,b,c)->c/=[]) $ map (\(a,b)->(a, b, map fst $ filter (pasteable (a,b)) l)) $ filter (\(a,b)->length b==plen && last b/='\n') $ map (\(a,b)->(a, take plen b)) l mergePrefixes [] = [] mergePrefixes (p:ps) = mergePrefixes' p ps where mergePrefixes' p [] = [p] mergePrefixes' (a,x,b) ((c,y,d):qs) = if length (filter (>=c) b) >= length d then mergePrefixes' (a,x,b) qs else (a, x, (filter (<c) b)):(mergePrefixes' (c,y,d) qs) uc = ("~!@#$%^&*()_+<>?:{}|\""++['A'..'Z']) lc = ("`1234567890-=,./;[]\\'"++['a'..'z']) down c = case [[lo]|(lo,hi)<-zip lc uc,c==hi] of []->error [c];p->head p applyPrefixToLine prefix [] s=return s applyPrefixToLine [] line s=emit line s applyPrefixToLine prefix line@(ch:rest) s= if prefix`isPrefixOf`line then do { s<-emitPaste s; applyPrefixToLine prefix (drop (length prefix) line) s} else do { s<-emitch s ch; applyPrefixToLine prefix rest s} type Keystroke = (Char, [Char]) key action k (n, shift) = do putStrLn ((show n)++" "++[action]++" "++k) if k=="Shift" then return (n+1, (not shift)) else return (n+1, shift) emitch (m, shift) ch= case ch of '\t'->key 'H' "Tab" (m,shift) '\n'->key 'H' "Enter" (m,shift) ' '->key 'H' "Space" (m,shift) _-> if shift && ch`elem`lc then do { key 'R' "Shift" (m, True); key 'H' [ch] (m+1, False) } else if not shift && ch`elem`uc then do { key 'P' "Shift" (m, False); key 'H' (down ch) (m+1, True) } else if ch`elem`lc then key 'H' [ch] (m, shift) else key 'H' (down ch) (m, shift) emit line s = foldM emitch s line emitPaste s = do s<-key 'P'"Ctrl" s s<-key 'H' "v" s key 'R' "Ctrl" s emitCopy s = do s<-key 'H' "Home" s s<-key 'P'"Ctrl" s s<-key 'H' "c" s s<-key 'R' "Ctrl" s s<-key 'R' "Shift" s key 'H' "End" s applyPrefix pf ((a,b):xs) p@((c,y,d):ps) s= if (c==a) then do s@(n, shift) <- emit y s s <- if shift then return s else key 'P' "Shift" s s <- emitCopy s s <- applyPrefixToLine y (drop (length y) b) s applyPrefix y xs ps s else do s<-applyPrefixToLine pf b s applyPrefix pf xs p s applyPrefix "" ((a,b):xs) [] s= do s <- emit b s applyPrefix "" xs [] s applyPrefix pf ((a,b):xs) [] s= do s<-applyPrefixToLine pf b s applyPrefix pf xs [] s applyPrefix _ [] _ s=return s main=do input <- getContents let lines = softlines input let prefixes = mergePrefixes (findprefixes lines) (n,shift) <- applyPrefix "" lines prefixes (1, False) if shift then key 'R' "Shift" (n, shift) else return(n,shift) ``` ]
[Question] [ **This is the companion thread to the main [Unscramble the Source Code](https://codegolf.stackexchange.com/q/40932/2867) challenge.** If you think you have managed to unscramble one of the cop answers, you should post your solution as the answer to this thread. As a reminder, you have one attempt at cracking each submission. Your cracking attempt will be an unscrambled version of the source code. If your guess matches the description (same characters, output, and of course language), and you are the first correct guess, then you win a point. It is important to note that your program does not have to exactly match the original, simply use the same characters and have the same functionality. This means there could be more than one correct answer. The robber with the most points (successful cracks) wins. ## Leaderboard **Too many solves** * Martin Büttner: [(Python 3, 16, matsjoyce)](https://codegolf.stackexchange.com/a/40946/21487), [(CJam, 15, Ypnypn)](https://codegolf.stackexchange.com/a/40952/21487), [(Mathematica, 29, Fox Wilson)](https://codegolf.stackexchange.com/a/40957/21487), [(JavaScript, 15, Caridorc)](https://codegolf.stackexchange.com/a/40964/21487), [(CJam, 52, user23013)](https://codegolf.stackexchange.com/a/41025/21487), [(Pyth, 11, isaacg)](https://codegolf.stackexchange.com/a/41038/21487), [(PHP, 22, kenorb)](https://codegolf.stackexchange.com/a/41054/21487), [(PHP, 13, kenorb)](https://codegolf.stackexchange.com/a/41058/21487), [(Ruby, 17, Doorknob)](https://codegolf.stackexchange.com/a/41082/21487), [(PHP, 49, bwoebi)](https://codegolf.stackexchange.com/a/41115/21487), [(Mathematica, 35, Tally)](https://codegolf.stackexchange.com/a/41120/21487), [(GolfScript, 13, Peter Taylor)](https://codegolf.stackexchange.com/a/41143/21487), [(JavaScript, 25, Cris)](https://codegolf.stackexchange.com/a/41147/21487), [(JavaScript, 29, Cris)](https://codegolf.stackexchange.com/a/41149/21487), [(JavaScript, 26, Cris)](https://codegolf.stackexchange.com/a/41176/21487), [(Bash, 33, Debasis)](https://codegolf.stackexchange.com/a/41186/21487), [(JavaScript, 10, Cris)](https://codegolf.stackexchange.com/a/41187/21487), [(Lua, 28, ChipperNickel)](https://codegolf.stackexchange.com/a/41236/21487), [(Mathematica, 18, Arcinde)](https://codegolf.stackexchange.com/a/41241/21487), [(JavaScript, 30, Qwertiy)](https://codegolf.stackexchange.com/a/41258/21487), [(CJam, 13, user23013)](https://codegolf.stackexchange.com/a/41264/21487), [(JavaScript, 41, Ismael Miguel)](https://codegolf.stackexchange.com/a/41296/8478), [(Ruby, 38, Doorknob)](https://codegolf.stackexchange.com/a/41301/8478), [(Marbelous, 36, es1024)](https://codegolf.stackexchange.com/a/41319/8478), [(PHP, 33, Ismael Miguel)](https://codegolf.stackexchange.com/a/41344/8478), [(JavaScript, 29, Joe)](https://codegolf.stackexchange.com/a/41374/8478), [(JavaScript, 28, Shawn Holzworth)](https://codegolf.stackexchange.com/a/41383/8478), [(Ruby, 35, histocrat)](https://codegolf.stackexchange.com/a/41436/8478), [(CJam, 19, Ypnypn)](https://codegolf.stackexchange.com/a/41440/8478), [(Ruby, 17, Stephen Touset)](https://codegolf.stackexchange.com/a/41453/8478), [(JavaScript, 36, MegaTom)](https://codegolf.stackexchange.com/a/42201/8478), [(JavaScript, 24, fogcityben)](https://codegolf.stackexchange.com/a/43130/8478), [(Python 3, 21, Reticality)](https://codegolf.stackexchange.com/a/43179/8478), [(JavaScript, 10, Jamie Barker)](https://codegolf.stackexchange.com/a/44302/8478), [(JavaScript, 15, Jamie Barker)](https://codegolf.stackexchange.com/a/44304/8478) **20 solves** * feersum: [(Python 3, 44, Sp3000)](https://codegolf.stackexchange.com/a/41049/21487), [(C, 70, es1024)](https://codegolf.stackexchange.com/a/41130/21487), [(MATLAB, 41, COTO)](https://codegolf.stackexchange.com/a/41131/21487), [(Brainfuck, 118, Sp3000)](https://codegolf.stackexchange.com/a/41134/21487), [(C, 30, Ethiraric)](https://codegolf.stackexchange.com/a/41157/21487), [(C, 28, Mig)](https://codegolf.stackexchange.com/a/41163/21487), [(Python 3, 46, hosch250)](https://codegolf.stackexchange.com/a/41196/21487), [(Java, 70, Rodolvertice)](https://codegolf.stackexchange.com/a/41209/21487), [(C, 29, imallett)](https://codegolf.stackexchange.com/a/41210/21487), [(Java, 226, nhahtdh)](https://codegolf.stackexchange.com/a/41218/21487), [(Little Man Computer, 63, The Wolf)](https://codegolf.stackexchange.com/a/41226/21487), [(Python 2, 89, Beta Decay)](https://codegolf.stackexchange.com/a/41229/21487), [(Python 2, 41, muddyfish)](https://codegolf.stackexchange.com/a/41265/21487), [(C, 63, es1024)](https://codegolf.stackexchange.com/a/41298/8478), [(C++, 192, Arcinde)](https://codegolf.stackexchange.com/a/41300/8478), [(Java, 108, durron597)](https://codegolf.stackexchange.com/a/41311/8478), [(C#, 604, eshansingh1)](https://codegolf.stackexchange.com/a/41327/8478), [(C, 44, Art)](https://codegolf.stackexchange.com/a/41405/8478), [(Java, 134, Olavi Mustanoja)](https://codegolf.stackexchange.com/a/41424/8478), [(Bash, 47, Vi.)](https://codegolf.stackexchange.com/a/41426/8478) **15 solves** * user23013: [(CJam, 18, Ypnypn)](https://codegolf.stackexchange.com/a/40969/21487), [(JavaScript, 26, hsl)](https://codegolf.stackexchange.com/a/40972/21487), [(CJam, 12, COTO)](https://codegolf.stackexchange.com/a/41002/21487), [(PHP, 23, bwoebi)](https://codegolf.stackexchange.com/a/41075/21487), [(PHP, 54, Steve Robbins)](https://codegolf.stackexchange.com/a/41079/21487), [(CJam, 32, Dennis)](https://codegolf.stackexchange.com/a/41148/21487), [(CJam, 19, Martin Büttner)](https://codegolf.stackexchange.com/a/41159/21487), [(Bash, 23, The Wolf)](https://codegolf.stackexchange.com/a/41235/21487), [(Ruby, 33, Doorknob)](https://codegolf.stackexchange.com/a/41248/21487), [(CJam, 34, Dennis)](https://codegolf.stackexchange.com/a/41294/8478), [(JavaScript, 82, Ismael Miguel)](https://codegolf.stackexchange.com/a/41305/8478), [(PHP, 80, Ismael Miguel)](https://codegolf.stackexchange.com/a/41318/8478), [(QBasic, 43, DLosc)](https://codegolf.stackexchange.com/a/41328/25180), [(QBasic, 42, DLosc)](https://codegolf.stackexchange.com/a/41331/25180), [(ECMAScript, 90, Cris)](https://codegolf.stackexchange.com/a/41338/8478) **10 solves** * squeamish ossifrage: [(Python, 44, Caridorc)](https://codegolf.stackexchange.com/a/40967/21487), [(PHP, 52, PleaseStand)](https://codegolf.stackexchange.com/a/40979/21487), [(Befunge-93, 17, user23013)](https://codegolf.stackexchange.com/a/41034/21487), [(BBC BASIC, 187, Beta Decay)](https://codegolf.stackexchange.com/a/41053/21487), [(C, 43, Allbeert)](https://codegolf.stackexchange.com/a/41069/21487), [(Ruby, 58, Rodolvertice)](https://codegolf.stackexchange.com/a/41108/21487), [(JavaScript, 32, hsl)](https://codegolf.stackexchange.com/a/41136/21487), [(PHP, 33, kenorb)](https://codegolf.stackexchange.com/a/41151/21487), [(Python 2, 16, imallett)](https://codegolf.stackexchange.com/a/41220/21487), [(PHP, 53, PleaseStand)](https://codegolf.stackexchange.com/a/41304/8478) * Sp3000: [(Python, 154, Fox Wilson)](https://codegolf.stackexchange.com/a/41003/21487), [(Python, 48, kgull)](https://codegolf.stackexchange.com/a/41016/21487), [(Python, 68, horns)](https://codegolf.stackexchange.com/a/41020/21487), [(Python 2, 38, FryAmTheEggman)](https://codegolf.stackexchange.com/a/41059/21487), [(Python 2, 57, FryAmTheEggman)](https://codegolf.stackexchange.com/a/41091/21487), [(Python, 74, xnor)](https://codegolf.stackexchange.com/a/41194/21487), [(JavaScript, 66, Cris)](https://codegolf.stackexchange.com/a/41302/8478), [(JavaScript, 70, Cris)](https://codegolf.stackexchange.com/a/41302/8478), [(Python 2, 37, muddyfish)](https://codegolf.stackexchange.com/a/41308/8478), [(Python, 55, FireFly)](https://codegolf.stackexchange.com/a/41394/8478) **7 solves** * grc: [(Python 2, 61, FryAmTheEggman)](https://codegolf.stackexchange.com/a/40996/21487), [(Perl 5, 47, chilemagic)](https://codegolf.stackexchange.com/a/41015/21487), [(Python, 69, Sp3000)](https://codegolf.stackexchange.com/a/41040/21487), [(Perl, 39, GentlePurpleRain)](https://codegolf.stackexchange.com/a/41121/21487), [(Perl, 36, squeamish ossifrage)](https://codegolf.stackexchange.com/a/41137/21487), [(Python 3, 110, Sp3000)](https://codegolf.stackexchange.com/a/41142/21487), [(C, 53, FireFly)](https://codegolf.stackexchange.com/a/41279/21487) **5 solves** * hsl: [(CoffeeScript, 25, Martin Büttner)](https://codegolf.stackexchange.com/a/40959/21487), [(Golfscript, 20, Josiah Winslow)](https://codegolf.stackexchange.com/a/40985/21487), [(Lua, 18, user3155415)](https://codegolf.stackexchange.com/a/41001/21487), [(Python, 54, kgull)](https://codegolf.stackexchange.com/a/41006/21487), [(Arithmetic, 31, Cris)](https://codegolf.stackexchange.com/a/41285/21487) * PleaseStand: [(PHP, 14, Tryth)](https://codegolf.stackexchange.com/a/41014/21487), [(C++, 56, hosch250)](https://codegolf.stackexchange.com/a/41024/21487), [(PHP, 21, kenorb)](https://codegolf.stackexchange.com/a/41168/21487), [(QBasic, 37, DLosc)](https://codegolf.stackexchange.com/a/41361/163), [(JavaScript, 46, FireFly)](https://codegolf.stackexchange.com/a/41382/8478) **4 solves** * bwoebi: [(PHP, 52, kenorb)](https://codegolf.stackexchange.com/a/41074/21487), [(PHP, 30, Tryth)](https://codegolf.stackexchange.com/a/41105/21487), [(PHP, 27, kenorb)](https://codegolf.stackexchange.com/a/41112/21487), [(PHP, 44, kenorb)](https://codegolf.stackexchange.com/a/41154/21487) * FireFly: [(JavaScript, 94, Shawn Holzworth)](https://codegolf.stackexchange.com/a/41364/8478), [(Python, 34, Sp3000)](https://codegolf.stackexchange.com/a/41390/8478), [(Brainfuck, 39, Mig)](https://codegolf.stackexchange.com/a/41500/3918), [(JavaScript, 69, Shawn Holzworth)](https://codegolf.stackexchange.com/a/41517/3918) **3 solves** * Optimizer: [(JavaScript, 61, jsh)](https://codegolf.stackexchange.com/a/41042/21487), [(JavaScript, 47, palerdot)](https://codegolf.stackexchange.com/a/41141/21487), [(JavaScript, 42, Shawn Holzworth)](https://codegolf.stackexchange.com/a/41410/8478) * es1024: [(PHP, 46, Ismael Miguel)](https://codegolf.stackexchange.com/a/41363/29611), [(Python shell, 15, xnor)](https://codegolf.stackexchange.com/a/41533/29611), [(Python shell, 21, xnor)](https://codegolf.stackexchange.com/a/41561/29611) * DLosc: [(Python, 41, Sp3000)](https://codegolf.stackexchange.com/a/41292/21487), [(Ruby, 37, Rodolvertice)](https://codegolf.stackexchange.com/a/41316/8478), [(CJam, 14, User23013)](https://codegolf.stackexchange.com/a/41885/16766) **2 solves** * xnor: [(Python 3, 37, matsjoyce)](https://codegolf.stackexchange.com/a/40954/21487), [(Python 2, 29, Dennis)](https://codegolf.stackexchange.com/a/40968/21487) * Daniel Wagner: [(Haskell, size 34, Petr Pudlák)](https://codegolf.stackexchange.com/a/41222/21487), [(Haskell, 42, proud haskeller)](https://codegolf.stackexchange.com/a/41230/21487) * nneonneo: [(Python, 41, Sp3000)](https://codegolf.stackexchange.com/a/41259/21487), [(C, 43, FryAmTheEggman)](https://codegolf.stackexchange.com/a/41268/21487) * Art: [(C, 51, es1024)](https://codegolf.stackexchange.com/a/41242/21487), [(C, 48, es1024)](https://codegolf.stackexchange.com/a/41402/8478) * n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳: [(Java 6+, 101, Rodolvertice)](https://codegolf.stackexchange.com/a/41028/21487), [(Java, 97, Olavi Mustanoja)](https://codegolf.stackexchange.com/a/41413/8478) **1 solve** * Ypnypn: [(Python 2, 50, Geobits)](https://codegolf.stackexchange.com/a/40940/21487) * matsjoyce: [(Python 3, 12, xnor)](https://codegolf.stackexchange.com/a/40942/21487) * user1354557: [(Python, 56, Fox Wilson)](https://codegolf.stackexchange.com/a/40973/21487) * Dennis: [(CJam, 20, Martin Büttner)](https://codegolf.stackexchange.com/a/41122/21487) * isaacg: [(Pyth, 71, FryAmTheEggman)](https://codegolf.stackexchange.com/a/41123/21487) * ConMan: [(SAS, 17, user3490)](https://codegolf.stackexchange.com/a/41199/21487) * Arcinde: [(JavaScript, 285, Beta Decay)](https://codegolf.stackexchange.com/a/41239/21487) * Shawn Hotazworth: [(Javascript, 82, TrungDQ)](https://codegolf.stackexchange.com/a/41252/21487) * nooodl: [(Ruby, 49, Doorknob)](https://codegolf.stackexchange.com/a/41255/21487) * Bhante Nandiya: [(Python 3, 37, Sp3000)](https://codegolf.stackexchange.com/a/41274/21487) * Geobits: [(APL, 17, user23013)](https://codegolf.stackexchange.com/a/41306/8478) * histocrat: [(Ruby, 23, MegaTom)](https://codegolf.stackexchange.com/a/41421/8478) * ProgramFOX: [(Python, 13, Reticality)](https://codegolf.stackexchange.com/a/44444/9275) [Answer] # [CJam, size 20, by Martin Büttner](https://codegolf.stackexchange.com/a/41046) ``` Hi "petStorm!", mame ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### How it works ``` Hi " int(17) "; "petStorm!", " len('petStorm!') "; ma " atan2( , ) "; me " exp( ) "; " exp(atan2(int(17), len('petStorm!'))) "; ``` ### Cracking the code The desired output, `2.956177636986737`, is either a Double or a Double followed by a Long. Using only the characters in `"Stop, Hammer time!"`, there are four builtin operators that return non-integer Doubles: * `mS`, which is `asin` * `ma`, which is `atan2` * `me`, which is `exp` * `mt`, which is `tan` All of them contain an `m`, so we can use at most three of them. There is only one `S` and one `a`. All of those operators need input, and `ma` is the only one that consumes two inputs. We have only three ways to push Longs: * `"...",`, which pushes the string's length (strictly less than 18). * `H`, which pushes 17. * `...!`, which pushes the logical NOT of `...`. We have no way of pushing something falsy as `...`, so the last option will always push 0. The output doesn't begin or end with `17` or `0`. Since 15 decimal digits is the usual number of digits for a Double, it seemed likely that the output was a simple Double. Assuming this, the code has to fall in one of the following categories: * `<Long> <mS|me|mt>{1,3}` * `<Long> <mS|me|mt>{x} <Long> <mS|me|mt>{y} ma <mS|me|mt>{z}`. * Any of the above, with some cast to Long (`i`) or rounding (`mo`) applied to a Double. In the second case, `x + y + z` is either 1 or 2 and one of the Longs is 0 or 17. The rest was basically brute force. After a few tries, ``` 18 , {H \ ma me 2.956177636986737 =} = ``` returned `9`, meaning that ``` H 9 ma me ``` produces the desired output. All that's left is to eliminate all but 9 characters from the string. Spaces are noops and `i` is a noop on Longs, so `"petStorm!"` is one of the possible choices. [Answer] # [Python 3, size 12, by xnor](https://codegolf.stackexchange.com/a/40939/30630) ``` ()and bciprt ``` Does nothing (expression produces an empty tuple, which is not printed). This works due to short-circuit evaluation. [Answer] # [Python, size 74, by xnor](https://codegolf.stackexchange.com/a/41184/21487) ``` any(print(set is set)for i in oct(chr is map))and aeeeeeggiilnnpprrrrrstvw ``` Well that was fun. Thanks to FryAmTheEggman, hosch250 and isaacg for suggestions/helping out. [Answer] ## [Python 2, size 50, by Geobits](https://codegolf.stackexchange.com/a/40934/16294) ``` print 2**2**2*2**2-22-2**2**2**2/2**2**2**2**2/2/2 ``` Outputs 42. [Answer] # [GolfScript, size 13, by Peter Taylor](https://codegolf.stackexchange.com/a/41092/8478) ``` ,22,{.4&?+.}/ ``` [Test it here.](http://golfscript.apphb.com/?c=LDIyLHsuNCY%2FKy59Lw%3D%3D) Another one, that I only cracked with big help from Sp3000. Thanks! So here's how we got there. Sp3000 noticed a bunch of runs of consecutive numbers in the output: ``` 1,2,3,4,[2608852181],4582,4583,4584,4585,4586,[253225388392299], 142924,142925,142926,142927,142928,[302928],497409,497409 ``` Based on that we made the assumption, that this was an increasing sequence, which only allowed for one possible splitting of the remaining numbers: ``` 1,2,3,4,260,885,2181,4582,4583,4584,4585,4586,25322,53883,92299, 142924,142925,142926,142927,142928,302928,497409,497409 ``` That's 23 numbers, which was a strong indicator for repeating the block 22 times, as well as ending the block with `.` (duplicate top stack element), such that the previous result got left behind on the stack and such that the final iteration would appear on the stack twice. That's `22,{____.}/`. Now looking at the gaps, those turn out to be 4th powers (which is nice, because we have `4` and `?`). More precisely, they are the fourth power of the index of the current number. So next we looked at which indices created a gap: ``` 4,5,6,7, 12,13,14,15, 20,21,..? ``` In binary those are ``` 00100 00101 00110 00111 01100 01101 01110 01111 10100 10101 ``` They all have the third bit set, which means that the index is probably just bitwise-and'ed with `4` (which is nice again, because we can make another `4` with `.` and have a `&`). This works particularly well, because this operation results in either `0` or `4`, and if we use that as the exponent we get either `1` or a fourth power, which is exactly what we need. So let's put that together: ``` 22,{.4&?+.}/ ``` Here is what the block does: ``` . # Duplicate current index 4 # Push a 4 & # Bitwise and ? # Raise index to resulting power + # Add to previous result . # Duplicate for use in next iteration ``` Now there were two problems left: we had a stray `,` we didn't use yet, and the first iteration is a special case, in that there is no value from a previous iteration which we could add things to when encountering `+`. We found that thanks to an unrelated comment by user23013 who casually mentioned that GolfScript starts out with an empty string on the stack (if there's nothing on STDIN). So we could use that other `,` right at the beginning to turn that string into a `0`, which was just what we needed as the start of the iteration. [Answer] # [Python 3, size 16, by matsjoyce](https://codegolf.stackexchange.com/a/40945/8478) ``` import __hello__ ``` [Answer] # [Ruby, size 17, by Doorknob](https://codegolf.stackexchange.com/a/40994/8478) ``` p 2,%r~n~i=~'*tN' ``` That was great fun. Thanks to Sp3000 for helping me out with this! And I learned that `%r?...?` literals can have any delimiters. :) [Answer] # [PHP, size 49, by bwoebi](https://codegolf.stackexchange.com/a/41096/8478) ``` print@substr(new exception,+~$$a+=++$$m+$$i+2+n); ``` That was absolutely *mental*. It got to ``` print@substr(new exception,); ``` fairly quickly, at which point I needed something that gives `-6` after the comma, having `$++$++$++$+=$~main$2` left. The main catch is that `$a`, `$m` and `$i` are all `NULL`, so using them indirectly in [variable variables](http://php.net/manual/en/language.variables.variable.php), means they all point to the same variable. However, PHP seems to be doing some weird things about resolving variable variables. With normal variables you can do things like ``` echo $a+$a=2; ``` which prints `4` (the `2` is assigned to `$a` and then added to itself). But if I do the same with variable variables: ``` echo $$a+$$a=2; ``` I get `2`, because now the first `$$a` is evaluate before the assignment. In the end I managed to force some order by putting some increments on the RHS of the `+=` which had to be evaluated before that addition-assignment. That way I got to `5` which I could then just bit-complement. Still... there are some mysterious things going on, and I have no idea why half the things I tried worked and didn't work. [Answer] # [Ruby, size 38, by Doorknob](https://codegolf.stackexchange.com/a/40970/8478) ``` [$><<(!$pece60).to_s[rand($win)].succ] ``` I'm pretty sure this is nowhere near the original source. It's deterministic despite using `rand`. Here is how this one works. `$><<` is just output. `$pece60` and `$win` are undefined global variables, which therefore are just `nil` (and they allowed me to get rid of some extraneous characters). `!$pece60` makes a `true` and `to_s` gives the string `"true"`. For ages, I tried getting a `2` or `-2` to access that `u` in there, but then I realised I could just take the `t`, and call `.succ`(essor) on it to make a `u`. `rand` with a `nil` parameter returns a random float in the interval [0,1). When using floats to index into strings, they get truncated to integers, so this will always return the first character. Finally, I had a spare pair of `[]` so I just wrapped everything in it, because thankfully everything is an expression in Ruby. Thanks to Sp3000 for throwing some ideas around in chat. [Answer] # [C, 51 by es1024](https://codegolf.stackexchange.com/questions/40932/unscramble-the-source-code/41132#41132) ``` c=0xf.cp9,hhtaglfor;main() {;; printf("%d",(++c));} ``` After 20 years of programming C today I learned about hexadecimal floating point constants. [Answer] # [Ruby, 45 (histocrat)](https://codegolf.stackexchange.com/a/41269/3918) ``` %q[zyfnhvjkwudebgmaclprs x].to_i(36)/51074892 ``` Woohoo! This is my first crack at a code golf problem, and I don't have enough rep to comment on the original post. I immediately recognized the trick used, since I've actually found use for it in production code often. It took about 5 minutes to figure out most of the structure and a few hours to come up with the complete answer. Explanation: * `%q[]` is an alternative method for creating strings. Parenthesis and curly braces may also be used. * `String#to_i` in Ruby accepts numbers in any base from 2 to 36. It will ignore the first character in the string which is not part of the number, so any extra characters can be "thrown away" after the space. And here's the code I used to crack it: ``` require 'set' # return true if the string is made up of unique characters def uniq(s) a = s.each_char.to_a return a == a.uniq end def uniq_while_same(a,b) s = Set.new a.each_char.zip(b.each_char).each do |ai, bi| return true if ai != bi return false if s.include? ai s << ai end return true end def ungolf(answer) # For each base that even makes sense [ 36, 35, 34, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 10].each do |base| # Ignore bases where it is not possible to create a unique-string number greater than answer next if answer > base ** base # Pick digits for the denominator that are not duplicates of the digits in base denominator_digits = ('1234567890'.each_char.to_a - base.to_s.each_char.to_a) # For each permutation of those digits for the denominator (1..10).each do |denominator_length| denominator_digits.permutation(denominator_length) do |denominator_s| # Maybe the denominator is in octal denominator_base = 10 if denominator_s[0] == '0' next if denominator_s.include?('8') || denominator_s.include?('9') denominator_base = 8 end denominator_s = denominator_s.join denominator = denominator_s.to_i denominator_base print "#{"\b"*64}(%q[#{(answer * denominator).to_s(base).ljust(36)}].to_i #{base})/#{denominator_s.ljust(10)}" if rand < 0.01 # Ignore denominators that are definitely impossible to have answers for next unless uniq_while_same "qtoi#{base}#{denominator_s}#{(answer * denominator).to_s(base)}", "qtoi#{base}#{denominator_s}#{((answer + 1) * denominator).to_s(base)}" # For each numerator that gives answer when divided by the denominator (answer * denominator...(answer + 1) * denominator).each do |numerator| print "#{"\b"*64}%q[#{numerator.to_s(base).ljust(36)}].to_i(#{base})/#{denominator_s.ljust(10)}" if rand < 0.01 # Remove any that are still not unique s = "#{numerator.to_s(base)}#{base}#{denominator_s}qtoi" next unless uniq s # Done. Compute which characters need to be thrown away to fill the remaining space remains = ('0123456789abcdefghijklmnopqrstuvwxyz'.each_char.to_a - s.each_char.to_a).join print "#{"\b"*64}#{" "*64}#{"\b"*64}" return "%q[#{numerator.to_s(base)} #{remains}].to_i(#{base})/#{denominator_s}" end end end end print "#{"\b"*64}" puts "\nnone" return nil end print ungolf 9410663329978946297999932 ``` Way to go embedding an NP problem inside a riddle. I have been thoroughly nerd-sniped. Good job! [Answer] # [Python [any] shell size 44, by Caridorc](https://codegolf.stackexchange.com/a/40962/11006) ``` __name__[3] or (enfin_____[42], manager[1]) ``` I'm sure there was supposed to be more to it than this, but since `__name__` equates to `__main__`, the 4th character 'a' is selected and the rest of the line is never evaluated. [Answer] ## [Perl, size 36, by squeamish ossifrage](https://codegolf.stackexchange.com/a/40963/4020) ``` $_=rof;for$i(1..2129<<7){$_++}print; ``` Another difficult one. [Answer] # [CJam, size 13, by user23013](https://codegolf.stackexchange.com/a/41213/8478) ``` G,Cf#If/sE*K% ``` [Test it here.](http://cjam.aditsu.net/) Solved by hand, like so: First, some background for non-CJammers: * `CEGIK` are all variables, which are pre-initialised to `12`, `14`, `16`, `18`, `20`, respectively. * `s` converts the top stack element to a string. * Strings are technically just arrays of characters. * `f` is pretty magic. For the purpose of this answer, the simplified version is that, for an array `a`, some other value `b` and an operator `g`, the sequence `abfg` maps `g(_,b)` onto `a` (where each element of `a` goes into the `_` slot). * `/` is division and splitting arrays (amongst other things). * `*` is multiplication and array repetition (amongst other things). * `%` is modulo and some weird operation, which in the form `ad%` for array `a` and integer `d` takes every `d`th element of `a` (like Python's slicing with step width `d`). * `#` is exponentiation (amongst other things). * `,` turns numbers into ranges (from `0` to `n-1`) and returns the length of an array. Okay, that out of the way... It was fairly obvious that we needed `,` to turn a number into a range, because the only other way to get an array would have been to build a larger number and turn it into a character array with `s` - but then we couldn't have done any further arithmetic on it. And we need an array to do something with the `f`s. I first assumed that the `f`s were used with `#` and `%`, but that would mean we would have needed a number around 90 to get the right amount of digits in the end. And also, this didn't explain what to do with `s`, and since the answer looked really golfy, I doubted user23013 just appended an `s` as an effective no-op somewhere to throw people off. So I figured, maybe he isn't even keeping the numbers small with `%`, but instead he builds an array of huge numbers, concatenates their string representation with `s`, but then only picks some odd slice out of it with `%`. So I played around a bit with the following framework: ``` __*,_f#_f/s_% ``` (You can't do `_f/` first, because that would yield zero for at least the first 12 elements.) Where the `_` are some permutation of the variables. I didn't try all of them before I got bored, and the main problem with this was that the resulting sequence of digits as always way too long. At some point it occurred to me, that we wouldn't need such a large range (i.e. the product of two numbers), if instead we used the `*` to repeat the resulting string. Due to the mismatch of the parameters of `*` and `%` this would yield no repetition in the result: ``` _,_f#_f/s_*_% ``` This yielded results of a length very close to what I was looking for. I would have actually tried all 240 of them, but fairly quickly (third or fourth attempt), I stumbled upon ``` E,Cf#If/sG*K% ``` which yields ``` 03081942753650251594592190492275006661328850322159030034930530649722385533653290754678977 ``` And I figured a match of the first six digits wouldn't be a coincidence. So the question was how to rearrange it without upsetting the actual computation: * I couldn't change `K` because that would pick out different digits altogether. * I couldn't change `C` or `I` because that would change the numbers resulting from the two map operations. * If I changed `G` that would only change the number of repetitions, which would do nothing but change the length of the result. (Which is good.) * If I changed `E` that would change the range of the array, but the range would still start with `[0 1 2 3 ...]`, so it wouldn't affect the calculation. It *would* affect the length of the base string returned by `s`, which would also mean that `K%` would pick out different digits upon additional repetitions. So I just tried swapping `E` and `G` and voila: ``` 030819828850379075460427536222159187897761502517030034671154875945928930530907551421904962649729 ``` In summary, here is what the code does: ``` G, "Push [0 1 2 3 ... 13 14 15]."; Cf# "Raise each element to the 12th power."; If/ "Divide each element by 18."; s "Concatenate all numbers into a string."; E* "Repeat 14 times."; K% "Pick every 20th digit."; ``` [Answer] # [APL, size 17, by user23013](https://codegolf.stackexchange.com/a/41037/14215) ``` +(3*3)3,(***)\3 3 ``` I spent *far* too long trying to crack this. It probably would've gone quicker if I knew APL going in. [Try it out here](http://ngn.github.io/apl/web/index.html) [Answer] # [Pyth, size 11, by isaacg](https://codegolf.stackexchange.com/a/41007/8478) ``` :\\w$ ",d,N ``` That's some mean bug abuse right there. This compiles to: ``` Pprint("\n",at_slice("\",input(), ",d,N)) ``` The relevant bug is that `\\` compiles to `"\"` instead of `"\\"`, which lets you compile Pyth into a string. [Answer] # [Python, size 69, by Sp3000](https://codegolf.stackexchange.com/a/41012/4020) ``` print(sum(list(map(ord,str((dict(((str(dict()),list()),)),str())))))) ``` That was hard... [Answer] [Python 3, 37 bytes, by Sp3000](https://codegolf.stackexchange.com/a/41081/32690) ``` print(sum(b"a".zfill(len(str(...))))) ``` Embarrassingly by far the hardest part was figuring out to convert the string into bytes. I had to sleep on it, and in the night realized 'duh, it's a bytes literal!' [Answer] # [PHP, 53, by PleaseStand](https://codegolf.stackexchange.com/a/40990/11006) Cracked it at last: ``` for($d=57,$o=35;$o+$d<999;)$o+=printf("$d%o",$d+=$o); ``` The solution came quite quickly when I noticed that the sequence consists of alternating decimal and octal numbers: ``` Dec: 57...92...132...177...228...285...348...417...492....573....661....756....858.... 571349220413226117734422843528553434864141775449210755731225661136475615328581707 Oct: ..134..204...261...344...435...534...641...754...1075...1225...1364...1532...1707 ==Dec: 92 132 177 228 285 348 417 492 573 661 756 858 967 ``` Also, the intervals between each set of numbers grew at a rate equal to the value returned by `printf()` (i.e., the number of characters written). [Answer] # [Python 2, size 132, by Vi.](https://codegolf.stackexchange.com/a/41155/32353) ``` exec('from string import printable as e\nprint "cqance"\x2Ereplace("q",e[len("fgiillmmooprrsstt")])or ",,,\016:::S[]____tuuvyy" ""') ``` Thanks for all the backslashes and quotation marks :) --- Edit: The updated 96-char version: ``` exec "try:exec'from __future__ import braces\\nt(12)'\nexcept SyntaxError as q:print(q[0][6:])" ``` This is taken entirely from Alex's solution in <https://codegolf.stackexchange.com/a/41451/32353> [Answer] # [CJam, size 15, by Ypnypn](https://codegolf.stackexchange.com/a/40936/8478) ``` 98,{7%}%{6+}%:+ ``` From the given characters, I guessed it had to be one of the three following forms: ``` __,{_%}%{_+}%:+ _,{_%}%{__+}%:+ __,{_+}%{_%}%:+ ``` which creates a two-digit range, then maps an addition and modulo operation (in either order) onto the range, before summing it. So I just started with the first one, and systematically tried permutations of `6789` in the gaps. [Answer] # [PHP, size 52, by PleaseStand](https://codegolf.stackexchange.com/a/40978/11006) ``` for(mt_srand($i=46);$i--;)echo chr(mt_rand()%95+32); ``` This turned out to be quite easy in the end. The output looks very random, and the characters `m`, `t`, `_`, `r`, `a`, `n` and `d` all appeared twice... [Answer] ## [Python 2, size 61, by FryAmTheEggman](https://codegolf.stackexchange.com/a/40947/4020) ``` print(dir('~s]l.c:st_''-p_tp.l]-~.:o:Te[_u[.i_')[10][2:][:3]) ``` I'd be very surprised if this matches the original. [Answer] # [Python 3, Sp3000, size 44](https://codegolf.stackexchange.com/a/41048/30688) ``` print(~(~(()<((),))<<(()<((),))))<<((()<())) ``` Python 3 helped me here as I was able to cause an error (left-shifting `None` by something) after printing the answer. [Answer] # [PHP, size 52, by kenorb](https://codegolf.stackexchange.com/a/41062/9409) ``` _:@print_r(chr(@++$i+pow(3<<5,1)));if($i<2*4)goto _; ``` (God, how long it took me to figure what to do with the remaining `_r` suffix. Until I noticed it was not `print`, but `print_r`...) [Answer] # [PHP, size 54, by Steve Robbins](https://codegolf.stackexchange.com/a/41077/25180) ``` echo(21<<($$$$$$${$aaaabbbbbbehi==$l&$w^2}^1==1));;;; ``` Not the original solution, I think. [Answer] # [C, es1024, length 70](https://codegolf.stackexchange.com/a/41127/30688) ``` e='C',f;main(g){Chorkil:f=printf("40%.d",e+e- -g);}hAx;*hotpoCkats(); ``` The hard part ended up being to keep track of all the unneeded characters...seriously...I had to redo them about 10 times. The only one that worried me was the `.` but somehow I stuck it in the middle of the `printf` format string and it became invisible! [Answer] ## [Python 3, size 110, by Sp3000](https://codegolf.stackexchange.com/a/41139/4020) ``` import sys,io u=sys.stdout;sys.stdout=_=io.StringIO() import this u.write(" ".join(_.getvalue().split()[::9])) ``` This was a fun one :) [Answer] # [Haskell, size 34, by Petr Pudlák](https://codegolf.stackexchange.com/a/41084/21457) ``` main=print(0xb2f3d5^0x7f1f27::Int) ``` Note that this program must be run on a 32-bit machine. If you want to check that this is the correct program and you have a 64-bit machine, you can use this instead: ``` import Data.Int main=print(0xb2f3d5^0x7f1f27::Int32) ``` It was pretty easy to guess the "frame" of the program `main=print(0x<hex digits>^0x<hex digits>::Int)`. All the magic was in searching for the right way to partition and order the digits. I didn't do very much smart here, just a brute-force search... though I did take care to abuse the fact that some digits were duplicated, there were probably about an equal number of digits in the base and exponent, and the last digit of the base almost certainly wasn't even. The complete search code is included below; it uses the [multiset-comb](http://hackage.haskell.org/package/multiset-comb) package. The full search takes about 10:33 on my machine (and produces only one right answer, of course). ``` {-# LANGUAGE NoMonomorphismRestriction #-} import Control.Monad import Data.Int import Data.List (inits, tails, group) import Numeric import Math.Combinatorics.Multiset main = print (searchFor (-1121766947)) searchFor n = do nl <- [6,5,7,4,8,3,9,2,10,1,11] (l_, r_) <- chooseSubbag nl digits l <- perms l_ guard (last l /= '2') r <- perms r_ guard ((fromString l :: Int32) ^ (fromString r :: Integer) == n) return (l, r) chooseSubbag n = chooseSubbag' n . group chooseSubbag' n xss = go (drop (n-1) (concat xss)) n xss where go _ n xss | n < 0 = [] go _ 0 xss = [([],concat xss)] go [] n xss = [] go m n (xs:xss) = do (kx, tx) <- zip (tails xs) (inits xs) (k , t ) <- go (drop (length tx) m) (n-length kx) xss return (kx++k, tx++t) digits = "1223577bdfff" fromString = fst . head . readHex perms = permutations . fromList ``` [Answer] # [Javascript, 82, by TrungDQ](https://codegolf.stackexchange.com/a/41192/32628) ``` b=/v/[0]+' ';b[0]+b[9]+b[6]+b[7]+'v'+b[7]+((0==0)+b)[1]+b[9]+b[4]+b[5]+b[6]+b[2]; ``` Took forever to get the indexes right. ]
[Question] [ [Pascal's triangle](http://en.wikipedia.org/wiki/Pascal%27s_triangle) is generated by starting with a 1 on the first row. On subsequent rows, the number is determined by the sum of the two numbers directly above it to the left and right. To demonstrate, here are the first 5 rows of Pascal's triangle: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` ## The Challenge Given an input *n* (provided however is most convenient in your chosen language), generate the first *n* rows of Pascal's triangle. You may assume that *n* is an integer inclusively between 1 and 25. There must be a line break between each row and a space between each number, but aside from that, you may format it however you like. This is **code-golf**, so the shortest solution wins. ## Example I/O ``` > 1 1 > 9 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 ``` [Answer] ## [J](http://jsoftware.com/), 12 characters ``` ":@(!{:)\@i. ``` --- ``` i.5 0 1 2 3 4 {:i.5 4 (i.5)!{:i.5 1 4 6 4 1 (!{:)i.5 1 4 6 4 1 (!{:)\i.5 1 0 0 0 0 1 1 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1 ":@(!{:)\i.5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 (":@(!{:)\@i.)`'' +----------------------------------+ |+-+------------------------------+| ||@|+-------------------------+--+|| || ||+-+---------------------+|i.||| || |||\|+-------------------+|| ||| || ||| ||+-+---------------+||| ||| || ||| |||@|+--+----------+|||| ||| || ||| ||| ||":|+-+------+||||| ||| || ||| ||| || ||2|+-+--+|||||| ||| || ||| ||| || || ||!|{:||||||| ||| || ||| ||| || || |+-+--+|||||| ||| || ||| ||| || |+-+------+||||| ||| || ||| ||| |+--+----------+|||| ||| || ||| ||+-+---------------+||| ||| || ||| |+-------------------+|| ||| || ||+-+---------------------+| ||| || |+-------------------------+--+|| |+-+------------------------------+| +----------------------------------+ ``` [Answer] # Python, 56 Bytes ``` a=[1];exec"print a;a=map(sum,zip([0]+a,a+[0]));"*input() ``` Sample usage: ``` echo 9 | python filename.py ``` Produces: ``` [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] ``` [Answer] # C, 522 A self demonstrating C answer. Couldn't be clearer! Bonus points for finding the extra character. ``` #define returns return 0 #define fr for #define twentyonechexpressis0 0 i , x [ 52 ] [ 52] ,j, y ; main (c){fr (;i< c ; i++){ x[i][i]=x[ i][0]= 1 ; }for(i =2;i<c;i++){for (j=1;j<i;j++){x [i][j] = 1 +x[i][j ]+x[i-1][j-1]+x[i-1] [j]+1-1+1-1+1-1+1-1+1-1+111-11- twentyonechexpressis0 -100-1; } } ;for(i=0 ;i<c;i++){for(j=0;j<=i;j++){ printf("%3d%c",x[i][j],(1+1+1+1)*(1+1+1+1+1+1+1+1)) ;}putchar(1+1+(1<<1+1)+1+1+1+1+1+111111-111111-1);} /*thiscomment_takes28chars*/ returns; } ``` [Answer] ## Python, 94 91 88 70 63 characters ``` x=[1] for i in input()*x: print x x=map(sum,zip([0]+x,x+[0])) ``` [Answer] ## Mathematica: 36 (41?) Mathematica has the `Binomial` function, but that takes the fun out of this. I propose: ``` NestList[{0,##}+{##,0}&@@#&,{1},n-1] ``` The line above will render a ragged array such as: ``` {{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10, 5, 1}, {1, 6, 15, 20, 15, 6, 1}} ``` Since this is a basic format in Mathematica I thought it would be acceptable, but as I read the rules again, I think it may not be. Adding `Grid@` will produce unequivocally acceptable output, for a total of **41** characters: ``` Grid@NestList[{0,##}+{##,0}&@@#&,{1},n-1] ``` `n = 6`: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 ``` [Answer] ### Golfscript (21 chars) ``` ~]({0\{.@+\}/;1].p}*; ``` Since an explanation was requested: ``` # Stack contains 'n' ~]( # Stack: [] n { # prev_row is [\binom{i,0} ... \binom{i,i}] # We loop to generate almost all of the next row as # [(\binom{i,-1} + \binom{i,0}) ... (\binom{i,i-1} + \binom{i,i})] # \binom{i,-1} is, of course, 0 # Stack: prev_row 0\ # Stack: 0 prev_row { # Stack: ... \binom{i,j-1} \binom{i,j} .@+\ # Stack: ... (\binom{i,j-1} + \binom{i,j}) \binom{i,j} }/ # Stack: \binom{i+1,0} ... \binom{i+1,i} \binom{i,i} # unless it's the first time round, when we still have 0 # so we need to pop and then push a 1 for \binom{i+1,i+1} ;1] # next_row .p }* # final_row ; ``` [Answer] # [convey](http://xn--wxa.land/convey/), 39 bytes convey is a new 2d esolang I made. It is based on conveyor belts that move values around in a factory. `v<^>` are explicit belt directions, other connections are inferred, as each function has a fixed number of inputs and outputs. For example, `+` takes 2 values in and returns 1 value. ``` v<<<.~/.] v>,v}"!{ "/&v}11 \v>+/^ $,^ _ ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidjw8PC5+Ly5dXG52Pix2fVwiIXtcblwiLyZ2fTExXG5cXHY+Ky9eXG4kLF5cbl8iLCJ2IjoxLCJpIjoiNCJ9) [![pascals triangle](https://i.stack.imgur.com/ryL3m.gif)](https://i.stack.imgur.com/ryL3m.gif) A row enters the main part from the top left. Two tiles in, the row gets `"` copied down and right. The right part prepends a `_`, which is a so called 'default value'. The actual value of `_` depends on the function it enters. It works like the neutral element, thus `_ + 3 = 3`, `4 * _ = 4`. To understand the next part we have to take a look at port order. For example, `,` will join two paths, favoring the main input port. The order is as follows (lower takes precedence): ``` For input: For output: 0 3 v ^ 1>f<3 2<f>0 ^ v 2 1 ``` So the upper `,` will favor inputs from the left, and the lower `,` will favor inputs from the top. In the animation the arrow heads are drawn a bit thicker to indicate main ports. On `/` (rising flank) whenever a new list enters the tile, `_` gets pushed to the side port. `_` and the row then get joined, whereas the `_` comes from the main port and thus has right of way. The bottom part appends a `_` by similar means: `\` (falling flank) pushes the length of the list to the side port, that will be set `$` to `_`. Finally, `_ 1 2 1` and `1 2 1 _` get added in `+` and we get the next row `1 3 3 1`! We print a newline `/}` (`_` in `}` prints newlines) and then copy the row into the output `"}`. To prevent a row colliding with the next row when they get longer, we batch `~.` the lists: we first let 1 element through, then 2, then 3 … by getting the indices `/.` of an list of `n` 1s (`{!1`}), that get discarded in a sink `]`. [Answer] # Ruby: ~~51~~ ~~49~~ 46 characters (45 characters code + 1 character command line option) ``` p=[];$_.to_i.times{n=0;p p.map!{|i|n+n=i}<<1} ``` Thanks to: * [jsvnm](https://codegolf.stackexchange.com/users/3586/jsvnm) for suggesting an alternative for the value switching (2 characters) * [G B](https://codegolf.stackexchange.com/users/18535/g-b) for spotting out a variable unused after previous improvement (4 characters) Sample run: ``` bash-4.4$ ruby -ne 'p=[];$_.to_i.times{n=0;p p.map!{|i|n+n=i}<<1}' <<< 1 [1] bash-4.4$ ruby -ne 'p=[];$_.to_i.times{n=0;p p.map!{|i|n+n=i}<<1}' <<< 9 [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] ``` [Try it online!](https://tio.run/##KypNqvz/v8A2OtZaJV6vJD8@U68kMze1uDrP1sC6QKFALzexQLG6JrMmTzvPNrPWxsaw9v9/y3/5BSWZ@XnF/3XzAA "Ruby – Try It Online") [Answer] ## Scala, ~~81~~ ~~78~~ ~~72~~ 70 characters 81 chars: first attempt, shamelessly copied from the Python version :) ``` var x=Seq(1) for(i<-1 to args(0).toInt){println(x) x=(0+:x,x:+0).zipped.map(_+_)} ``` Run it as a script, or directly in the REPL. Cut to 70 chars with something surprisingly readable and idiomatic: ``` Seq.iterate(Seq(1),readInt)(a=>(0+:a,a:+0).zipped.map(_+_))map println ``` Or ~~72~~ 70 characters with a totally different method: ``` 0 to(readInt-1)map(i=>println(0 to i map(1 to i combinations(_)size))) ``` [Answer] # [Keg](https://esolangs.org/wiki/Keg), ~~40~~ 33 bytes ``` 1:&¿1. ,(|(⑻|:⑻$@MCƒℤ. ,⑨)⑹_01. , ``` [Try it online!](https://tio.run/##y05N///f0Ert0H5DPS4djRqNRxN311gBCRUHX@djkx61LNFT0Hk0cYXmo4k74w1Aav7/twAA "Keg – Try It Online") ## Old Program Explained ![Pen](https://i.stack.imgur.com/mlTg5.png) ![Highlighted](https://i.stack.imgur.com/JVvtQ.png) [Answer] # Haskell, ~~94~~ 92 ``` f=[1]:[zipWith(+)(0:x)x++[1]|x<-f] main=readLn>>=mapM_(putStrLn.unwords.map show).(`take`f) ``` Output: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` A 71 character version which does not print a space between each number: ``` f=[1]:[zipWith(+)(0:x)x++[1]|x<-f] main=readLn>>=mapM_ print.(`take`f) ``` Output: ``` [1] [1,1] [1,2,1] [1,3,3,1] ``` [Answer] # R, 39 chars R seems to be the very right tool for this task :-) ``` x=1;for(i in 1:n)x=c(print(x),0)+c(0,x) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 10 bytes *-3 bytes thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014)* ``` mw↑¡Sż+Θ;1 ``` [Try it online!](https://tio.run/##yygtzv7/P7f8UdvEQwuDj@7RPjfD2vD///@mAA "Husk – Try It Online") ### Explanation Based on the same idea as [my Pip answer](https://codegolf.stackexchange.com/a/211994/16766): generate each row from the last one by tacking a 0 to the front of the row and adding it to itself element-wise. The Husk version creates the entire triangle as an infinite lazy list and then takes however many rows we need. ``` ;1 Start with [1] ¡ Iterate this function: S S-combinator: Sfgx is fx(gx) (aka f(x,g(x)) in C-style syntax) ż+ f: add a list itemwise to another list, keeping the extra value at the end of the longer list unchanged Θ g: prepend a falsey value (given a list of integers, prepend 0) The result of Sż+Θ is a 1-argument function that prepends a 0 to its argument and adds that itemwise to another copy of the argument ↑ From the infinite list of results, take N (where N is the input) mw Join each sublist on spaces (which means the main list gets autojoined on newlines) ``` [Answer] ## JavaScript (90 85 83 81) ``` for(n=prompt(o=i='');i++<n;o+='\n')for(s=j=1;j<=i;s=s*(i-j)/j++)o+=s+' ';alert(o) ``` Demo: <http://jsfiddle.net/tcRCS/3/> **NOTE**: Doesn't work well in practice for about n > 30 because numbers overflow built-in integer data type and become floating-point numbers. --- **Edit 1**: removed 5 characters by converting `while` to `for` and combining statements **Edit 2**: move `s=` statement inside `for` and save 2 chars **Edit 3**: combine `s=1,j=1` initializer into `s=j=1` and save 2 chars [Answer] ## in Q (25 characters/20 with shorter version) ``` t:{(x-1) (p:{0+':x,0})\1} ``` Shorter ``` t:{(x-1){0+':x,0}\1} ``` Sample usage: ``` q)t 4 1 1 1 1 2 1 1 3 3 1 ``` [Answer] # awk - 73 chars fairly straightforward implementation: ``` {for(i=0;i<$1;++i)for(j=i;j>=0;)printf"%d%c",Y[j]+=i?Y[j-1]:1,j--?32:10} ``` sample run: ``` % awk -f pascal.awk <<<10 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 ``` [Answer] ## Perl, 52, 49 characters Edit: using `say` instead of `print` ``` map{@_=(1,map$_[$_-1]+$_[$_],1..@_);say"@_"}1..<> ``` [Answer] ## APL, ~~19~~ 15 characters A bit late to the party, perhaps? ``` {⍪{⍵!⍨⍳⍵+1}¨⍳⍵} ``` It doesn't beat the J entry, though. This assumes that the index origin (`⎕IO`) is set to `0`. Unfortunately, with an index origin of `1`, we need ~~25~~ 18 characters: ``` {⍪{⍵!⍨0,⍳⍵}¨1-⍨⍳⍵} ``` There are two `⍨`s in the code to express my frustration. Demo: ``` {⍪{⍵!⍨⍳⍵+1}¨⍳⍵}5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` --- Explanations Short version: * `⍳⍵` (with an index origin of 0) produces an array of the numbers from 0 to `⍵-1` inclusive, where `⍵` is the right argument to the function. * `⍳⍵+1` generates all numbers from 0 to `⍵` * `{⍵!⍨⍳⍵+1}` generates `⍵` choose `k` for every element `k` in `⍳⍵+1`. The `⍨` (commute) operator swaps the arguments to a function around, such that the right hand argument becomes the left, and vice versa. * `{⍵!⍨⍳⍵+1}¨⍳⍵` passes each element in `⍳⍵` using the `¨` (each) operator. The result is a one dimensional array containing the first `⍵` rows of the Pascal's Triangle. * The one argument form of `⍪` takes a one dimensional vector, and makes it a column rather than a row. Each row of the triangle is put on its own line. Long answer: * Virtually the same as the other version, except that `1-⍨` is placed before an `⍳` to replicate an index origin of 0. * `0,⍳⍵` with an index origin of 1 replicates `⍳⍵+1` with an index origin of 0. [Answer] # Perl, ~~47~~ 54 characters ``` $p=1;map{print"@{[split//,$p]}\n";$p*=11}1..<> ``` It takes a number from the command line, but doesn't perform any error checks. Just realized it only works up to n=4. It was some old code I had on my hd. This works though: ``` map{@a=(1,map$a[$_-1]+=$a[$_],1..@a);print"@a\n"}a..n ``` n has to be input into the script though, or it would be one character more. [Answer] # Pascal: ~~216~~ 192 characters (Not a real competitor, just an honorific presence.) ``` var p:array[0..1,0..25]of LongInt;i,j,n,u:Word;begin Read(n);u:=0;for i:=1to n do begin p[1,1]:=1;for j:=1to i do begin p[u,j]:=p[1-u,j-1]+p[1-u,j];Write(p[u,j],' ')end;u:=1-u;Writeln end end. ``` Sample run: ``` bash-4.2$ fpc pascal.pas /usr/bin/ld: warning: link.res contains output sections; did you forget -T? bash-4.2$ ./pascal <<< 1 1 bash-4.2$ ./pascal <<< 9 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 ``` [Answer] # Perl, 37 bytes ``` s/\d+/$&+$'/eg,say$_="1 $_"for($a)x<> ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW19FTVtFXT81Xac4sVIl3lbJUEElXiktv0hDJVGzwsbu/3/Lf/kFJZn5ecX/dX1N9QwMDQA) [Answer] ## Perl, 77 Chars ``` $o[0]=1;for(1..<>){$"=" ";for(1..$_){$n[$_]=$o[$_]+$o[$_-1]}@o=@n;print"@o "} ``` Example input ``` 5 ``` Example output ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` [Answer] ## C, ~~132~~ 127 characters ``` c[25][25],n,i,j;main(){for(scanf("%d",&n);i<n;i++)for(j=0;j<=i;j++)printf("%d%c",c[i][j]=j?c[i-1][j-1]+c[i-1][j]:1,i-j?32:10);} ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes *Language created after this challenge* ``` 1iq:"tTTY+ ``` [**Try it online!**](http://matl.tryitonline.net/#code=MWlxOiJ0VFRZKw&input=OQ) ``` 1 % Push a 1. This will be the first row iq: % Take input n. Generate range [1,2,...,n-1] " % For each (that is, repeat n-1 times) t % Duplicate latest row TT % Push [1 1] Y+ % Convolve latest row with [1 1] to produce next row % Implicitly end for each % Implicitly display stack contents ``` [Answer] # JavaScript, ~~70~~ 69 bytes Generating Pascal's Triangle in a golfy manner has always given me brain ache but every time it comes up, I give it another try. Last night, armed with a few beers, I finally cracked it and came up with a *working* solution I was happy with. Fitting, then, that this should be my 500th (undeleted) solution here. 0-indexed and includes a trailing newline and a trailing space on each line. ``` n=>(g=x=>x++>n?``:(h=z=>y>x?``:z+` `+h(z*(x-y)/y++))(y=1)+` `+g(x))`` ``` --- ## Try it ``` o.innerText=(f= n=>(g=x=>x++>n?``:(h=z=>y>x?``:z+` `+h(z*(x-y)/y++))(y=1)+` `+g(x))``)(i.value=8);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o></pre> ``` [Answer] ## D ~~134~~ 128 chars ``` import std.stdio;void main(){int n,m;int[]l,k=[0,1];readf("%d",&n);foreach(i;0..n){writeln(l=k~0);k=[];foreach(e;l)k~=m+(m=e);}} ``` output for 9 is ``` >9 [0, 1, 0] [0, 1, 1, 0] [0, 1, 2, 1, 0] [0, 1, 3, 3, 1, 0] [0, 1, 4, 6, 4, 1, 0] [0, 1, 5, 10, 10, 5, 1, 0] [0, 1, 6, 15, 20, 15, 6, 1, 0] [0, 1, 7, 21, 35, 35, 21, 7, 1, 0] [0, 1, 8, 28, 56, 70, 56, 28, 8, 1, 0] ``` taking full advantage of "you may format it however you like"; there is a space between each number and a linebreak edit repositioned the assignment to `l` to shave of some chars [Answer] ## Scala, 131 characters ``` object P extends App{var x=List(1) while(x.size<=args(0).toInt){println(x.mkString(" ")) x=(0+:x:+0).sliding(2).map(_.sum).toList}} ``` Takes the input from the command line. Output for n=10: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 ``` [Answer] ## F♯ - 203 characters My first attempt at a round of code golf, and first attempt at functional programming. There is probably some obvious way to shorten it I haven't quite figured out yet. It complies in VS2010s F♯ compiler (which has the effect of running #light by default unlike earlier versions), and also works in the F♯ interpreter. Accepts input via stdin. Wish there was a better way for the input/output though! Lots of characters! ``` open System let rec C r m =if r=0||m<=0||m>=r then 1 else C(r-1)m+C(r-1)(m-1) for j = 0 to Convert.ToInt32(Console.ReadLine ()) do ( [0..j]|>List.map(C j)|>List.iter(fun k->printf "%i " k) printf "\n") ``` [Answer] *Why is there no accepted answer to this question?* ## VBA - 249 chars ``` Sub t(n) ReDim a(1 To n,1 To n*2) a(1,n)=1:y=vbCr:z=" ":d=z & 1 & z & y:For b=2 To n:For c=1 To n*2:x=a(b-1,c) If c>1 Then a(b,c)=a(b-1,c-1)+x If c<n*2 Then a(b,c)=a(b-1,c+1)+x d=IIf(a(b,c)<>0,d & z & a(b,c) & z,d):Next:d=d & y:Next:MsgBox d End Sub ``` [Answer] postscript - 59 chars (63 if you count `-dn=` to get the number of rows in) ``` [1]n{dup ==[0 3 2 roll{dup 3 2 roll add exch}forall]}repeat ``` run with ``` gs -q -dn=10 -dBATCH pascal.ps ``` to get ``` [1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1] [1 5 10 10 5 1] [1 6 15 20 15 6 1] [1 7 21 35 35 21 7 1] [1 8 28 56 70 56 28 8 1] [1 9 36 84 126 126 84 36 9 1] ``` ]
[Question] [ # Goal: Given two natural numbers (integers from 0 to infinity), output a number that is not the sum of those numbers, but is a natural number. # Example solutions (TI-Basic): * `A+B+1` * `not(A+B)` # Invalid solutions: * `A+B-1` (for inputs `0,0`, it returns `-1`, which is not natural) * `"ABC"` (`ABC` is not a number) # Notes: * The output must always be a sum of two natural numbers (which is actually just a natural number) * `-1`, `undefined`, `infinity`, `NaN` and Error messages are not natural numbers. For our purposes, `0` is natural (although not all mathematicians agree). [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), ~~4~~ ~~3~~ 1 Byte [Crossed out 4 is still 4 ;(](https://codegolf.stackexchange.com/a/82343/58375) ``` E ``` The most simple of solutions, compares if A and B are equal. Pushes true, which RProgN sees as 1, if they are the same, or false aka 0 otherwise. ## Test Cases ``` 0+0 = 1 1+0 = 0 0+1 = 0 1+1 = 1 ``` [Try it online!](https://tio.run/nexus/rprogn#@@/6//9/w/8GAA "RProgN – TIO Nexus") [Answer] # [Python](https://docs.python.org/2/), 13 bytes ``` [(0,0)].count ``` [Try it online!](https://tio.run/nexus/python2#S7ON@R@tYaBjoBmrl5xfmlfyv6AoM69EIVojUSdJUyEtv0ghUSEzT6EoMS89VcMUIpKEIpKZppCmAVauqWBrq5ConRT7HwA "Python 2 – TIO Nexus") Takes input as a tuple. Using an [object method](https://codegolf.stackexchange.com/a/95156/20260) for the function avoids the boilerplate of a `lambda`. ``` lambda a,b:a-~b # 15 bytes ``` Here, the idea is to map `(0,0)` to `1` and everything else to `0`. Since only `0+0` gives a sum of `0` among natural numbers, that always avoids matching the sum. If one could output a Boolean here, which I find shady, a byte could be saved as ``` (0,0).__ge__ ``` This checks if the input tuple is at most `(0,0)`, which is only true for `(0,0)`. In Python, `True==1` and `False==0`. Even more shadily, outputting via exit code and treating that as a Python Boolen would save two bytes: ``` [(0,0)].pop ``` If string I/O is allowed and leading zeroes are OK, there's the 8-byte solution ``` '1'.join ``` This concatenates `a1b`, which is always bigger than `a+b`. [Answer] # [Retina](https://github.com/m-ender/retina), 3 bytes ``` 1 ``` [Try it online!](https://tio.run/nexus/retina#@6/AZfj/v6GRgrEJAA "Retina – TIO Nexus") (The first line has a space before the newline. Stack Exchange isn't very good at showing trailing whitespace.) Input is the numbers in decimal, separated by a space (e.g. `12 34`). This program just changes the space to a `1`, creating a number too large to be the sum of the input numbers (it necessarily has at least 2 more digits than either, and adding two numbers produces an output with no more than 1 digit more than the larger input). [Answer] # MATL, et al. 1 byte ``` = ``` Accepts two natural numbers as inputs and compares them. If they are equal, the output is `1` and if they not equal the output is `0`. This is the same approach as @ATaco's solution. * [**MATL**](https://matl.suever.net/?code=%3D&inputs=0%0A1&version=19.7.4) * [**Jelly**](https://tio.run/nexus/jelly#@2/7//9/g/8GAA) (by @ais523) * [**Stacked**](https://tio.run/nexus/stacked#SyxKL9bT0/tv@z@/tOT/f5P/xgA) (by @Conor O'Brien) * [**APL (Dyalog APL)**](https://tio.run/nexus/apl-dyalog#@///f9qjtgm2XCYKaQrGAA) (by @Adám) * [**J**](https://tio.run/nexus/j#@///f5qCrZ6CLZeJQpqCMQA) (by @Adám) * [**Actually**](https://tio.run/nexus/actually#@2/7/78hlyEA) (by @Mego) * [**Implicit**](https://tio.run/##K87MLchJLS5JTM7@/9/2/39DBWMA) (by @MD XF) * [**W**](https://github.com/a-ee/w) (by @a'\_') * [**Keg**](https://github.com/JonoCode9374/Keg) (by @a'\_') * [**GolfScript**](https://tio.run/##S8/PSStOLsosKPlvqGD43/b/fwA) (by @Pseudo Nym) * [**Vyxal**](https://github.com/lyxal/vyxal) (by @emanresu A) [Answer] # Javascript, 10 bytes ``` x=>y=>!x+y ``` Takes 2 numbers using currying syntax like so: ``` (x=>y=>!x+y)(0)(0) // 1 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 8 bytes ``` ({}{}()) ``` [Try it online!](https://tio.run/nexus/brain-flak#@69RXVtdq6Gp@f@/MZcJAA "Brain-Flak – TIO Nexus") This is the most readable brain-flak answer I have ever written. :) Explanation: ``` ( ) # Push the sum of all the following: {} # The first input {} # The second input () # and one ``` Alternate solutions (also 8 bytes): ``` ({}[]{}) # Sum + 1 ([]{}{}) # Sum + 2 ``` There's a bunch of other solutions that only work with positive numbers: ``` (<{}>{}) ({}<{}>) ({{}}()) ({{}()}) ({{}}[]) ({{}[]}) ``` [Answer] # Vim, 3 bytes/keystrokes ``` <C-a>gJ ``` [Try it online!](https://tio.run/nexus/v#@2/jrJtol@71/78ll@F/3TIA "V – TIO Nexus") Note that `<C-a>` is actually *ctrl-a*, which represents byte `0x01`. I love it when vim (which isn't even a programming language) can compete with golfing languages. :) Input comes in this format: ``` a b ``` This simply increments the first number by one (This is the `<C-a>` part) and then joins the string representations of the two numbers together. As far as I can tell, this should never result in the sum. [Answer] # TI-Basic, 3 bytes ``` not(max(Ans ``` Alternative solutions: ``` 10^(sum(Ans 3 bytes @DestructibleWatermelon not(sum(Ans 3 bytes 1+sum(Ans 4 bytes Input :X=Y 5 bytes @ATaco Input :X+not(Y 6 bytes Input :not(X+Y 6 bytes Input :10^(X+Y 6 bytes Input :X+Y+1 7 bytes Input :not(max(X,Y 7 bytes Ans(1)=Ans(2 8 bytes Ans(1)+not(Ans(2 9 bytes not(Ans(1)+Ans(2 9 bytes ``` It's interesting that you made the question's examples in TI-Basic, but you forgot the shorter `A=B` (or maybe it was up to us to find out?) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` +‘ ``` The + adds the two inputs together then the ' increments the answer by one [Try it online!](https://tio.run/nexus/jelly#@6/9qGHG////Df4bAAA "Jelly – TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` +< ``` [Try it online!](https://tio.run/nexus/brachylog2#@69t8/9/tLGOSez/qK95@brJickZqQA "Brachylog – TIO Nexus") ### Explanation ``` + The sum of the elements in the Input... < ...is strictly less than the Output (implicitely label the output with an integer respecting this constraint) ``` This will always result in `A+B+1`, if `Input = [A, B]`. [Answer] # Mathematica, 5 bytes ``` 1+##& ``` Outputs the sum of the two arguments plus 1. For example, `1+##&[2,5]` yields `8`. (Side note: `Binomial` almost works, although `Binomial[1,0]=1` and `Binomial[4,2]=6` are counterexamples; I think they're the only counterexamples, though.) [Answer] # PHP, 17 bytes ``` <?=1-join($argv); ``` Run like this: ``` echo '<?=1-join($argv);' | php -- 0 0 > 1 ``` # Explanation This just concatenates the arguments. The first argument (script name) contains `-`. So that results in a negative number, which I negate with the minus sign. Then I add 1, just in case the first input number is a `0` (0123 = 123). [Answer] # [Perl 6](http://perl6.org/), 4 bytes ``` !*+* ``` A lambda (formed by [Whatever-currying](https://docs.perl6.org/type/Whatever)), that adds the boolean inverse (1 or 0) of the first argument to the second argument. [Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP2vqKWt9d@ai6s4sVIhTcFAR8HAGso2RGIDxQ1hbFMdBUtL6/8A "Perl 6 – TIO Nexus") [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 10 bytes ``` a->b->a-~b ``` [Try it online!](https://tio.run/nexus/java-openjdk9#ZY8xT8MwEIXn5Ffc6Ayx2iJgiNqFCYmyZEQMZ9dpjZJLZDstVRX@ejhTgyqhG9757tN7Z9sNvQvwgUeUY7CtrDUSGVflw6haq0G36D1s0RJc8sxSMK5BbeAFO7VDuACPwI0koqqigumWehqdO/@hqfml8UqnIB8wsBx7u4OO40QdnKX92zug2/sipme3ds16xnKjyg2WX2rOsor36Xjwek3mBOkp6rMPppOWigidDrY1wmt5QP9qPoMoruZZwvoxyIGjQ0uikfFYZonBZ4rs/8mPK39kyqd5AQtYcS3hHh5YH@GO@@U3 "Java (OpenJDK 9) – TIO Nexus") [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), 12 bytes makes very large numbers ``` '1?:?:[1'0l] ``` ### [Try it online!](https://tio.run/nexus/turtled#@69uaG9lbxVtqG6QE/v/vyGXAQA "Turtlèd – TIO Nexus") ## Explanation: ``` '1 write one on the starting grid square ?:?: take a number, move right that many (repeat) [1 ] while not on a grid square with a one on it '0l put a zero on that square, move left [implicit output of grid] ``` It thus outputs 10\*\*(x+y). [Answer] # PHP, 19 bytes ``` 1<?=max([0]+$argv); ``` [Answer] # SmileBASIC, 4 bytes ``` !A+B ``` not(A)+B `1+1=2 -> !1+1 -> 0+1=1` `0+1=1 -> !0+1 -> 1+1=2` [Answer] ## R, 13 bytes ``` sum(scan()+1) ``` Thanks to Jonathan Allan for his inputs ! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` Q ``` Works the same as the `RProgN` answer. Checks if `a` and `b` are the same. If so, print `1`. Otherwise, print `0` [Try it online!](https://tio.run/nexus/05ab1e#@x/4/78hl8HXvHzd5MTkjFQA "05AB1E – TIO Nexus") [Answer] ## C ~~26~~ ~~24~~ 19 bytes ``` f(c,d){return!c+d;} ``` Ungolfed version: ``` int f(int c,int d) { return !c+d; } ``` I hope I got the specification right. Can definitely be shortened!? @Pavel Thanks for saving 2 bytes @Neil Thanks for your input. [Answer] # MATLAB / Octave, 3 bytes ``` @eq ``` Accepts two inputs and checks for equality and yields `1` if they are equal and `0` otherwise. [Online Demo](http://ideone.com/Ddaya4) [Answer] # brainfuck, 12 bytes Simple solution that outputs `A+B+1`. ``` ,>,[-<+>]<+. ``` [**Try it online**](https://tio.run/nexus/brainfuck#@69jpxOta6NtF2ujrff/v4IiAA) [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 5 bytes ``` ?1n+n ``` [Try it online!](https://tio.run/nexus/dc#@29vmKed9/@/kZGRgrGxMQA "dc – TIO Nexus") Input: Two natural numbers separated by a space on stdin. Output: The digit 1 immediately followed by the sum of the two numbers, which is a number larger than the sum of the two numbers. Example: Input: `222 333` Output: `1555` [Answer] # PHP, 13 bytes; (17 REPL-less) ``` !max($argv)+0 ``` Examples ``` [0,0] -> 1 [0,1] -> 0 [1,0] -> 0 ``` For those without REPL use ``` <?=!max($argv)+0; ``` and run using ``` echo '<?=!max($argv)+0;' | php -- 0 0 ``` [Answer] # Cubix, ~~9~~ 8 bytes ``` u-~OII/@ ``` ## Explanation Expanded, this answer looks like this: ``` u - ~ O I I / @ . . . . . . . . . . . . . . . . ``` The order of the instructions that are executed is `II~-O@` ``` II~-O@ I # First input - # Minus I~ # NOT(second input) O # Output as integer @ # End program ``` Tested for all combinations of inputs where both are in the range `0-100`. Try it [here](https://ethproductions.github.io/cubix/?code=dS1+T0lJL0A=&input=MCwwCg==&speed=20). [Answer] # APL - 4 Bytes ``` 1++/ ``` Takes array, sums its elements and adds one. Test: ``` 1++/1 2 4 1++/1 0 2 ``` [Answer] # [///](https://esolangs.org/wiki////), 10 bytes + input ``` /0/1//+//[input A]+[input B] ``` *Obviously `[input A]` and `[input B]` are supposed to be replaced with the appropriate inputs* [Try it online!](https://tio.run/nexus/slashes#@69voG@or6@tr2@sbWjw/z8A) Changes 0's to 1's, then concatenates the strings. This works because: * For A,B>0, join(A,B)>A+B * join(A,B)>join(C,D) if A>C or B>D * The function f(x)='change 0's to 1's in the digits of x' is always at least x So we have join(f(A),f(B))>f(A)+f(B)>=A+B. And if one or both of the inputs are 0, we have join(1,B)>1+B>0+B, join(A,1)>A+1>A+0 and join(1,1)=11>0+0. *Note 1: This type of input has been [approved by the community](http://meta.codegolf.stackexchange.com/a/10553/60483)* *Note 2: This output doesn't give leading 0's either* *Note 3: Less bytes than Python, PHP, C#, C, Powershell and more!* [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 7 bytes ``` ?<.!?)@ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/9/eRk/RXtPh/38DBQMA "Hexagony – Try It Online") Or in more readable format, ``` ? < . ! ? ) @ ``` This beats the current Hexagony solution of 11 bytes. ## Explanation: ### If the first number is not 0, the program takes the following path: [![Not 0](https://i.stack.imgur.com/9f85z.png)](https://i.stack.imgur.com/9f85z.png) This reads the first number and branches right. Then it reads the second number, followed by wrapping and trying to read a third, but that doesn't exist so it reads 0. This is printed and the program terminated (note that if a>0, since b is non-negative a+b>0). ### If the first number is 0, the program takes the following path to start with: [![Is 0](https://i.stack.imgur.com/gU0m6.png)](https://i.stack.imgur.com/gU0m6.png) This reads the first number and branches left. It hits the corner, taking the route from along the north-west edge because the number is 0, and reads the second number. It wraps, then increments the second number and prints. [![Is still 0](https://i.stack.imgur.com/qzpXk.png)](https://i.stack.imgur.com/qzpXk.png) It bounces against the `<`, printing the incremented second input again. It increments the value and takes the north-east edge again, but this time because the current edge a twice-incremented non-negative value which is definitely positive. It then tries to get a third input, but receives 0 instead. [![Is still 0 some more](https://i.stack.imgur.com/0BOyR.png)](https://i.stack.imgur.com/0BOyR.png) Finally it wraps and gets diverted by the arrow, then tries to read a fourth input and gets 0 again. It wraps and tries to read a fifth input and receives 0 for the last time. This it prints, and wraps to the `@` and exits. Note that b\*(10^k+1)\*10>0+b=b where k is the length of b in digits, so this works. [Answer] # [√ å ı ¥ ® Ï Ø ¿](https://github.com/cairdcoinheringaahing/UnprintableName), 4 bytes ``` II1_ II Take 2 inputs and push to the stack 1 Push 1 to the stack _ Push the sum of the stack ``` To output, add `o` to the end. [Answer] # [Billiards](https://github.com/alexander-liao/java-public/tree/master/programs/ball-simulator), 11 characters = 17 bytes ``` ⇲ ⇲ + 1 + ↥ ``` Implements `x + y + 1`. Pretty elementary. It takes the inputs on two separate lines. (By the way, the language was modified slightly after the challenge, but only to suppress the prompt from inputting, not sure if this answer is still valid). # 7 characters = 11 bytes, non-competing This one is shorter but only possible after a new update of the language: ``` ⇲ ⇲ = $ ``` This uses `x == y`, which was shamelessly stolen from @ATaco's RProgN solution [ hope you don't mind (: ]. The `$`, on exit, outputs how many balls passed over it. ]
[Question] [ # Definition Fibonacci sequence `F(n)`, on the positive integers, are defined as such: ``` 1. F(1) = 1 2. F(2) = 1 3. F(n) = F(n-1) + F(n-2), where n is an integer and n > 2 ``` The Fibonacci-orial of a positive integer is the product of `[F(1), F(2), ..., F(n)]`. # Task Given positive integer `n`, find the Fibonacci-orial of `n`. # Specs **The fibonacci-orial of `100` must compute in under 5 seconds on a reasonable computer.** # Testcases ``` n Fibonacci-orial of n 1 1 2 1 3 2 4 6 5 30 6 240 7 3120 8 65520 9 2227680 10 122522400 11 10904493600 12 1570247078400 13 365867569267200 14 137932073613734400 15 84138564904377984000 16 83044763560621070208000 17 132622487406311849122176000 18 342696507457909818131702784000 19 1432814097681520949608649339904000 20 9692987370815489224102512784450560000 100 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000 ``` # References * Obligatory OEIS [A003266](http://oeis.org/A003266) * OEIS [A000045](http://oeis.org/A000045) - Fibonacci sequence [Answer] ## Mathematica, 10 bytes ``` Fibonorial ``` Another Mathematica built-in soundly beaten by a golfing language without the built-in. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` +С1ḊP ``` Input 100 finishes in 500 ms locally. [Try it online!](http://jelly.tryitonline.net/#code=K8OQwqEx4biKUA&input=MTAw&debug=on) ### How it works ``` +С1ḊP Niladic link. No input. Since the link doesn't start with a nilad, the argument 0 is used. 1 Yield 1. + Add the left and right argument. С Read a number n from STDIN. Repeatedly call the dyadic link +, updating the right argument with the value of the left one, and the left one with the return value. Collect all values of the left argument into an array. Ḋ Dequeue; discard the first Fibonacci number (0). P Product; multiply the remaining ones. ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 4 bytes Runs the input 100 within 0.2 seconds. Code: ``` R♂Fπ ``` Explanation: ``` R # Get the range [1, ..., input]. ♂F # Map over the array with the fibonacci command. π # Take the product. ``` Uses the **CP-437** encoding. [Try it online!](http://actually.tryitonline.net/#code=UuKZgkbPgA&input=MTU). [Answer] ## Brainfuck, ~~1198~~ ~~1067~~ ~~817~~ ~~770~~ ~~741~~ ~~657~~ ~~611~~ 603 ``` ,[>++++++[-<-------->]<<[->++++++++++<]>>,]>+>+>>+>+<<<<<<[->>>[[-] <[->+<]>>[-<+<+>>]<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[-> [-]>>>>>>+>+<<<<<<<<[->+<]]]]]]]]]]]+>>>>>>>>]<<<<<<<<[->[-<+<<+>>> ]<[->+<]>>>[<<<<<[->>>>>>>>+<<<<<<<<]>>>>>>>>>>>>>]<<<<<<<<[->>>[-< <<<<<<<+>>>>[->+>>+<<<]>[-<+>]>>>]<<[->>>>>>>+>+<<<<<<<<]<+<<<<<<<< ]>>>[-]>>>>>[[-]>[->+<]>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-< +>[->>>>>>+>+<<<<<<<<[-]]]]]]]]]]>]<<[<]+>>>>>>>>]<<<<<<<<[<<<<<<<< ]>>>>>[>>>>>>>>]+<<<<<<<<]>>>>>>>>>>>[<[-]>>[-<<+>>]>>>>>>>]<<<<<<< <[<<<<<<<<]>>]>>>>>>[>>>>>>>>]<<<<<<<<[+++++[-<++++++++>]<.<<<<<<<] ``` Uncompressed, with comments: ``` # parse input (max 255) ,[>++++++[-<-------->]<<[->++++++++++<]>>,] >+>+>>+>+<<<<<< [->>> # compute next fibonacci number [[-]< [->+<]>> [-<+<+>>]< # perform carries [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+< [->[-]>>>>>>+>+<<<<<<<<[->+<]] ]]]]]]]]]+>>>>>>>> ]<<<<<<<< # multiplication [-> # extract next digit of F_n (most significant first) [-<+<<+>>>]< [->+<]>>> # move back to the end [<<<<< [->>>>>>>>+<<<<<<<<]>>>>>>>>>>>>> ]<<<<<<<< # digit wise multiplication (shifting current digit) [->>> [-<<<<<<<<+>>>> [->+>>+<<<]> [-<+>]>>> ]<< # shift previous total over one gap (in effect multiplying by 10) [->>>>>>>+>+<<<<<<<<]<+<<<<<<<< ]>>>[-]>>>>> # add product to total [[-]> [->+<]> # perform carries [-<+> [-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+> [->>>>>>+>+<<<<<<<<[-]] ]]]]]]]]> ]<<[<]+>>>>>>>> ]<<<<<<<< [<<<<<<<<]>>>>> [>>>>>>>>]+<<<<<<<< ]>>>>>>>>>>> # overwrite previous product [<[-]>> [-<<+>>]>>>>>>> ]<<<<<<<< [<<<<<<<<]>> ]>>>>>> # output product [>>>>>>>>]<<<<<<<< [+++++ [-<++++++++>]<.<<<<<<< ] ``` [Try it online!](https://tio.run/##lVJBCgIxDHxQt7Lew3wk5KCCIIIHwffXJE23XSyis5BDO5mZZHt@nm6P6@tyL2VhJAdnygEIEec4N5AAiyDpZ4UcygCYszjXKCqRSClx8kdRFTg2dQrVjoSADAy3NE/0GOCer4q2BsGIUcfDB9zIxGqnuAmkdmyqQ1KhnUMbxnaDCOUSv5fJMvoiPAbN9rGfkzfCdAFMHtTmtn/2TSwu@dOxPZ32UvTq0PpKOa7rGw "brainfuck – Try It Online") Runtime for *n = 100* is less than 1 second with the online interpreter (about 0.2s locally using my own interpreter). Maximum input is 255, but would require the interpreter to support ~54000 cells (the online interpreter seems to wrap on 64k). --- **Change Log** Saved around 130 bytes with better extraction of the current digit to multiply through by, and by merging add and carry into a single pass. It also seems to be a bit faster. Saved another 250 bytes. I managed to reduce my multiplication scratch pad by two cells, which saves bytes just about everywhere by not having to shift so far between digits. I also dropped the carry after multiplying through by a digit, and instead perform a full carry whilst adding to the running total. Chopped another 50, again with better extraction of the current digit to multiply through by, simply by not moving it forward the first iteration, and working from where it is. A few micro-optimization further down account for around ~10 bytes. 30 more gone. Marking digits that have already been taken with a 0 rather than a 1 makes them easier to locate. It also makes the check if the multiplication loop has finished somewhat simpler. I reduced the scratch pad by another cell, for 80 more bytes. I did this by merging the marker for the previous product and the current running total, which reduces the shifts between gaps, and makes bookkeeping a bit easier. Saved another 50, by eliminating yet another cell, reusing the marker for fibonacci digits to mark the last digit taken as well. I was also able to merge the loop to shift the previous totals with the digit-wise multiplication loop. Saved 8 bytes on input parsing. Oops. [Answer] ## Python, 45 Bytes ``` a=b=o=1 exec"o*=a;a,b=b,a+b;"*input() print o ``` Input is taken from stdin. Output for *n = 100* finishes too quickly to accurately time. *n = 1000* takes approximately 1s. **Sample Usage** ``` $ echo 10 | python fib-orial.py 122522400 $ echo 100 | python fib-orial.py 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000 ``` [Answer] ## Haskell ~~41~~ 29 Bytes 1+11 bytes saved by @Laikoni's remarks. ``` f=1:scanl(+)1f (scanl(*)1f!!) ``` `1`,`f` and `!!` are separate tokens. The first lines defines the fibonacci sequence, the second is a function that computes the sequence of fibonacci-orials and returns the n-th for a given n. It starts printing digits almost immediately even for n=1000. [Answer] # Python 2, 39 bytes ``` f=lambda n,a=1,b=1:n<1or a*f(n-1,b,a+b) ``` Test it on [Ideone](http://ideone.com/Iu6cpa). [Answer] # J, ~~17~~ 16 bytes 1 byte is golfed with even better solution by miles. ``` [:*/+/@(!|.)\@i. ``` The idea is the same as the original but instead of forming the matrix to operate on minor diagonals we form the diagonals on the fly. --- **Original** To get the first *n* fibonomials: ``` */\(#{.+//.)!/~i. ``` Reading right to left... Create the array of consecutive integers (`i.`) up to specified one, from that array create the table (`/~`) of binomial coefficients (`!`) calculated from every pair in the array, this table is Pascal's triangle top of whlocated at the end of the first row and all elements under the main diagonal are 0, thankfully to implementation of `!`. If you sum (`+/`) all minor diagonals (`/.`), you get Fibonacci numbers, but you need to take (`{.`) as much of first elements from the resulting array as the length (`#`) of the table itself. Then the product (`*/`) applied to consecutive prefixes (`\`) of the array results into desired sequence of fibonorials. *If you wish you can take only the last one using 2 more bytes* (`{:`) but I thought that displaying all of them is not a sin `:)`. `NB. the previous code block is not a J function`. ``` {:*/\(#{.+//.)!/~i. 10 122522400 ``` For big numbers in J you use `x` at the end: ``` {:*/\(#{.+//.)!/~i. 100x 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225... ``` The program runs on avarage **0.11s**. ``` 100 timex '{:*/\(#{.+//.)!/~i.100x' 0.112124 ``` [Answer] # Pyth, 13 bytes ``` u*Gs=[sZhZ)Q1 ``` [Demonstration](https://pyth.herokuapp.com/?code=u%2aGs%3D%5BsZhZ%29Q1&input=100&debug=0) This employs a clever, non-typesafe trick. Five of the characters (`u*G ... Q1`) say that the output is the product of the input many numbers. The rest of the code generates the numbers. `=[sZhZ)` updates the variable `Z` to the list `[s(Z), h(Z)]`. Then `s` sums that list, to be multiplied. `Z` is initially 0. `s`, on ints, is the identity function. `h`, on its, is the `+ 1` function. So on the first iteration, `Z` becomes `[0, 1]`. `s` on lists is the sum function, as mentioned above. `h` is the head function. So the second iteration is `[1, 0]`. Here's a list: ``` Iter Z Sum 0 0 Not used 1 [0, 1] 1 2 [1, 0] 1 3 [1, 1] 2 4 [2, 1] 3 5 [3, 2] 5 ``` These sums are multiplied up to give the result. [Answer] # Mathematica ~~25~~ 24 bytes With thanks to Martin Ender. ``` 1##&@@Fibonacci@Range@#& ``` --- ``` 1##&@@Fibonacci@Range@#&@100 ``` Timing: 63 microseconds. ``` {0.000063, 3371601853146468125386964065447576689828006172937411310662486977801540 6711385898686165008341900290675836651822917015531720110825745874313823 1009903039430687777564739516714333248356092511296002464445971530050748 1235056111434293619038347456390454209587101225261757371666449068625033 9995735521655245297254676280601708866020010771376138030271586483293355 0772869860576999281875676563330531852996518618404399969665040724619325 7877568825245646129366994079739720698147440310773871269639752334356493 6789134243905645353892122400388956268116279491329780860702550826683922 9003714114129148483959669418215206272639036409444764264391237153249138 8089634845995941928089653751672688740718152064107169357399466473375804 9722605947689699525073466941890502338235963164675705844341280523988912 2373033501909297493561702963891935828612435071136036127915741683742890 4150054292406756317837582840596331363581207781793070936765786629772999 8328572573496960944166162599743042087569978353607028409125185326833249 36435856348020736000000000000000000000000} ``` [Answer] # Jelly, 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RḶUc$S€P ``` My first submission in Jelly. It's not as short as @Dennis' [answer](https://codegolf.stackexchange.com/a/86945/6710), but its only 2 bytes longer with a different method. Locally, it requires about 400ms compared to 380ms with @Dennis' version for *n* = 100. [Try it online!](http://jelly.tryitonline.net/#code=UuG4tlVjJFPigqxQ&input=&args=MTAw&debug=on) ### Explanation ``` RḶUc$S€P Input: n R Generate the range [1, 2, ..., n] For each value x in that range Ḷ Create another range [0, 1, ..., x-1] U Reverse that list c Compute the binomial coefficients between each pair of values $ Bind the last two links (Uc) as a monad S€ Sum each list of binomial coefficients This will give the first n Fibonacci numbers P Take the product of those to compute the nth Fibonacci-orial ``` [Answer] # R, ~~99~~ ~~96~~ ~~78~~ ~~76~~ 66 bytes This answer is uses [Binet's Formula](https://en.wikipedia.org/wiki/Jacques_Philippe_Marie_Binet), as well as the `prod(x)`function. Since **R** doesn't have a build-in `Phi` value, I defined it myself : ``` p=(1+sqrt(5))/2;x=1;for(n in 1:scan())x=x*(p^n-(-1/p)^n)/sqrt(5);x ``` It works under 5 seconds, but **R** tends to give `Inf` as an answer for those big numbers... **Ungolfed :** ``` r=sqrt(5) p=(1+r)/2 x=1 for(n in 1:scan()) x=x*(p^n-(-1/p)^n)/r x ``` **-2** bytes thanks to @Cyoce ! Oh, do I love this site ! **-10** bytes thanks to @user5957401 [Answer] # R, 82, 53, 49 bytes (48 bytes w/ different input style) ``` b=d=1;a=0;for(i in 1:scan()){d=d*b;b=a+b;a=b-a};d ``` If we can just precede the code with the input number, we get the 48 byte ``` ->n;b=d=1;a=0;for(i in 1:n){d=d*b;b=a+b;a=b-a};d ``` **EDIT:** New code. Original is below: ``` a=function(n)ifelse(n<3,1,{v=c(1,1,3:n);for(i in 3:n)v[i]=v[i-1]+v[i-2];prod(v)}) ``` Won't return anything other than Inf for `a(100)` though. And it won't work for anything but non-negative integers. Ungolfed: ``` a=function(n){ if(n<3) return(1) v=c(1,1,3:n) for(i in 3:n) v[i]=v[i-1]+v[i-2] prod(v) } ``` [Answer] ## PARI/GP, 29 bytes ``` f=n->prod(i=1,n,fibonacci(i)) ``` Or alternatively: ``` f=n->prod(i=a=!b=0,n,b=a+a=b) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 31 bytes ``` ,[1:0]:?:{hH,?bh:H+g:?c.}irbb*. ``` [Try it online!](http://brachylog.tryitonline.net/#code=LFsxOjBdOj86e2hILD9iaDpIK2c6P2MufWlyYmIqLg&input=MTAw&args=Wg&debug=on) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes ``` ×/(+.!∘⌽⍨∘⍳¨1+∘⍳⊢) ``` Explanation: ``` ×/(+.!∘⌽⍨∘⍳¨1+∘⍳⊢) 1+∘⍳⊢ ⍝ generate numbers 2-(⍵+1) ¨ ⍝ ... map to each +.!∘⌽⍨∘⍳ ⍝ n-th fibonacci number ×/ ⍝ product of all ``` Fibonacci formula explanation: ``` +.!∘⌽⍨∘⍳ ⍳ ⍝ numbers 1 to ⍵ ⍨ ⍝ apply to both sides of +.!∘⌽ ⌽ ⍝ reverse the ⍵ vector. +.! ⍝ inner product: sum and binomial ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXBpAplsQkAgI0AQKGBpZmCsYm/xPA7IPT9fX0NZTfNQx41HP3ke9K0CM3s2HVhhqQ1iPuhZpgkwCKk1TMOWCsczgLEMDg/8A "APL (Dyalog Unicode) – Try It Online") [Answer] # Ruby, 39 bytes ``` ->n{f=i=b=1;n.times{f,i,b=i,f+i,b*f};b} ``` [Answer] # Forth, 55 bytes Uses an iterative approach, built upon [my Fibonacci answer](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/60839?s=4%7C2.6394#60839) in Forth. The results overflow arithmetically for `n > 10`. The answer is case-insensitive. ``` : f >r 1 1 r@ 0 DO 2dup + LOOP 2drop 1 r> 0 DO * LOOP ; ``` [**Try it online**](http://ideone.com/SozKZR) [Answer] # Java, 165 bytes Golfed: ``` BigInteger f(int n){BigInteger[]a={BigInteger.ZERO,BigInteger.ONE,BigInteger.ONE};for(int i=0;i<n;){a[++i%2]=a[0].add(a[1]);a[2]=a[2].multiply(a[i%2]);}return a[2];} ``` This is yet another case where `BigInteger` being required due to large numbers. However, I was able to keep the text `BigInteger` to a minimum, keeping the size down. I also compared with static imports, and it made the total length longer. This program works by tracking three numbers in an array. The first two are the previous two Fibonacci numbers. The third is the accumulated value. The loop starts out by calculating the next value and storing it in alternating (0, 1, 0, 1, ...) array indices. This avoids needing to shift values with costly (in terms of source size) assignment operations. Then grab that new value and multiply it into the accumulator. By avoiding temporary objects and limiting the loop to two assignment operators, I was able to squeeze out quite a few bytes. Ungolfed: ``` import java.math.BigInteger; public class Fibonacci_orial { public static void main(String[] args) { // @formatter:off String[][] testData = new String[][] { { "1", "1" }, { "2", "1" }, { "3", "2" }, { "4", "6" }, { "5", "30" }, { "6", "240" }, { "7", "3120" }, { "8", "65520" }, { "9", "2227680" }, { "10", "122522400" }, { "11", "10904493600" }, { "12", "1570247078400" }, { "13", "365867569267200" }, { "14", "137932073613734400" }, { "15", "84138564904377984000" }, { "16", "83044763560621070208000" }, { "17", "132622487406311849122176000" }, { "18", "342696507457909818131702784000" }, { "19", "1432814097681520949608649339904000" }, { "20", "9692987370815489224102512784450560000" }, { "100", "3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000" } }; // @formatter:on for (String[] data : testData) { System.out.println("Input: " + data[0]); System.out.println("Expected: " + data[1]); System.out.print("Actual: "); System.out.println(new Fibonacci_orial().f(Integer.parseInt(data[0]))); System.out.println(); } } // Begin golf BigInteger f(int n) { BigInteger[] a = { BigInteger.ZERO, BigInteger.ONE, BigInteger.ONE }; for (int i = 0; i < n;) { a[++i % 2] = a[0].add(a[1]); a[2] = a[2].multiply(a[i % 2]); } return a[2]; } // End golf } ``` Program output: ``` Input: 1 Expected: 1 Actual: 1 Input: 2 Expected: 1 Actual: 1 Input: 3 Expected: 2 Actual: 2 Input: 4 Expected: 6 Actual: 6 Input: 5 Expected: 30 Actual: 30 Input: 6 Expected: 240 Actual: 240 Input: 7 Expected: 3120 Actual: 3120 Input: 8 Expected: 65520 Actual: 65520 Input: 9 Expected: 2227680 Actual: 2227680 Input: 10 Expected: 122522400 Actual: 122522400 Input: 11 Expected: 10904493600 Actual: 10904493600 Input: 12 Expected: 1570247078400 Actual: 1570247078400 Input: 13 Expected: 365867569267200 Actual: 365867569267200 Input: 14 Expected: 137932073613734400 Actual: 137932073613734400 Input: 15 Expected: 84138564904377984000 Actual: 84138564904377984000 Input: 16 Expected: 83044763560621070208000 Actual: 83044763560621070208000 Input: 17 Expected: 132622487406311849122176000 Actual: 132622487406311849122176000 Input: 18 Expected: 342696507457909818131702784000 Actual: 342696507457909818131702784000 Input: 19 Expected: 1432814097681520949608649339904000 Actual: 1432814097681520949608649339904000 Input: 20 Expected: 9692987370815489224102512784450560000 Actual: 9692987370815489224102512784450560000 Input: 100 Expected: 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000 Actual: 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000 ``` [Answer] # Javascript (ES6), ~~51~~ 39 bytes Recursive implementation (39 bytes) ``` f=(n,a=p=i=b=1)=>++i<n?f(n,b,p*=b+=a):p ``` Original implementation (51 bytes) ``` n=>{for(i=a=b=p=1;++i<n;){c=a;a=b;p*=b+=c}return p} ``` **Note: Starts rounding errors for the Fibonacci-orial of 16, 100 is just Infinity, runs in what appears to be <1 second.** [Answer] # [DC (GNU or OpenBSD flavour)](https://rosettacode.org/wiki/Category:Dc), 36 bytes File `A003266-v2.dc`: ``` 0sA1sB1?[1-d0<LrlBdlA+sBdsA*r]dsLxrp ``` (no trailing newline) ...now the result is held on the stack instead of using a named register (is `Y` in version 1). The `r` command is not available in the original `dc` (see [RosettaCode's Dc page](https://rosettacode.org/wiki/Category:Dc)). Run: ``` $ time dc -f A003266-v2.dc <<< 100 337160185314646812538696406544757668982800617293741131066248697780154\ 067113858986861650083419002906758366518229170155317201108257458743138\ 231009903039430687777564739516714333248356092511296002464445971530050\ 748123505611143429361903834745639045420958710122526175737166644906862\ 503399957355216552452972546762806017088660200107713761380302715864832\ 933550772869860576999281875676563330531852996518618404399969665040724\ 619325787756882524564612936699407973972069814744031077387126963975233\ 435649367891342439056453538921224003889562681162794913297808607025508\ 266839229003714114129148483959669418215206272639036409444764264391237\ 153249138808963484599594192808965375167268874071815206410716935739946\ 647337580497226059476896995250734669418905023382359631646757058443412\ 805239889122373033501909297493561702963891935828612435071136036127915\ 741683742890415005429240675631783758284059633136358120778179307093676\ 578662977299983285725734969609441661625997430420875699783536070284091\ 2518532683324936435856348020736000000000000000000000000 real 0m0.005s user 0m0.004s sys 0m0.000s ``` Trying to explain: `tos` is the contents of the top of the stack without removing it. `nos` is the element below `tos`. ``` 0 sA # push(0) ; A=pop() 1 sB # push(1) ; B=pop() 1 # push(1) # this stack position will incrementally hold the product ? # push( get user input and evaluate it ) [ # start string 1- # push(pop()-1) d # push(tos) 0 # push(0) <L # if pop() < pop() then evaluate contents of register L r # exchange tos and nos # now nos is the loop counter # and tos is the bucket for the product of the fibonacci numbers lB # push(B) d # push(tos) lA # push(A) + # push(pop()+pop()) # now tos is A+B, nos still is B sB # B=pop() # completes B=A+B d # push(tos) sA # A=pop() # completes B=A # tos (duplicated new A from above) is the next fibonacci number * # push(nos*tos) # tos now is the product of all fibonacci numbers calculated so far r # exchange tos and nos # now tos is the loop counter, nos is the product bucket ] # end string and push it d # push(tos) sL # L=pop() x # evaluate(pop()) r # exchange tos and nos # nos now is the former loop counter # tos now is the complete product. \o/ p # print(tos) # this does not pop() but who cares? :-P ``` --- # [DC](https://rosettacode.org/wiki/Category:Dc), 41 bytes ...straight forward, no tricks: File `A003266-v1.dc`: ``` 0sA1sB1sY?[1-d0<LlBdlA+sBdsAlY*sY]dsLxlYp ``` (no trailing newline) Run: ``` $ for i in $(seq 4) ; do dc -f A003266-v1.dc <<< $i ; done 1 1 2 6 $ time dc -f A003266-v1.dc <<< 100 337160185314646812538696406544757668982800617293741131066248697780154\ 067113858986861650083419002906758366518229170155317201108257458743138\ 231009903039430687777564739516714333248356092511296002464445971530050\ 748123505611143429361903834745639045420958710122526175737166644906862\ 503399957355216552452972546762806017088660200107713761380302715864832\ 933550772869860576999281875676563330531852996518618404399969665040724\ 619325787756882524564612936699407973972069814744031077387126963975233\ 435649367891342439056453538921224003889562681162794913297808607025508\ 266839229003714114129148483959669418215206272639036409444764264391237\ 153249138808963484599594192808965375167268874071815206410716935739946\ 647337580497226059476896995250734669418905023382359631646757058443412\ 805239889122373033501909297493561702963891935828612435071136036127915\ 741683742890415005429240675631783758284059633136358120778179307093676\ 578662977299983285725734969609441661625997430420875699783536070284091\ 2518532683324936435856348020736000000000000000000000000 real 0m0.006s user 0m0.004s sys 0m0.004s ``` [Answer] # C# ~~110~~ ~~109~~ ~~107~~ ~~103~~ ~~101~~ 94 Bytes ``` using i=System.Numerics.BigInteger;i f(i n){i a=0,b=1,x=1;for(;n-->0;)x*=a=(b+=a)-a;return x;} ``` ## Explanation ``` //Aliasing BigInteger saves a few bytes using i=System.Numerics.BigInteger; //Since BigInteger has an implicit from int we can also change the input //and save two more bytes. i f(i n) { //using an alternative iterative algorithm (link to source below) to cut out the temp variable //b is next iteration, a is current iteration, and x is the running product i a = 0, b = 1, x = 1; //post decrement n down to zero instead of creating a loop variable for (; n-- > 0;) //The bracket portion sets the next iteration //get the current iteration and update our running product x *= a = (b += a) - a; return x; } ``` [Iterative Fib algorithm](https://codegolf.stackexchange.com/a/3484/19547) [Answer] # [Perl 6](http://perl6.org/), 23 bytes ``` {[*] (1,&[+]...*)[^$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OlorVkHDUEctWjtWT09PSzM6TiU@tva/tUJxYqWCkkq8gq2dQnWagkp8rZJCWn6RQo2GoZ6ekYGmjqGBwX8A "Perl 6 – Try It Online") * `1, &[+] ... *` is the infinite Fibonacci sequence. * `[^$_]` takes the first `$_` elements of the sequence, where `$_` is the argument to the function. * `[*]` reduces that subsequence with multiplication. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 54 bytes ``` ([{}]<(())>){(({})()<{({}()<([({})]({}{}))>)}{}{}>)}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyO6ujbWRkNDU9NOs1pDo7pWU0PTphpIAymNaBA/FkgAKaB8LYgBpv7/NzQwAAA "Brain-Flak – Try It Online") Multiplication in Brain-Flak takes a long time for large inputs. Just multiplying F100 by F99 with a generic multiplication algorithm would take billions of years. Fortunately, there's a faster way. A generalized Fibonacci sequence starting with `(k, 0)` will generate the same terms as the usual sequence, multiplied by `k`. Using this observation, Brain-Flak can multiply by a Fibonacci number just as easily as it can generate Fibonacci numbers. If the stack consists of `-n` followed by two numbers, `{({}()<([({})]({}{}))>)}{}{}` will compute`n` iterations of the generalized Fibonacci sequence and discard all by the last. The rest of the program just sets up the initial 1 and loops through this for all numbers in the range `n...1`. Here's the same algorithm in the other languages provided by this interpreter: ## Brain-Flak Classic, 52 bytes ``` ({}<(())>){(({})[]<{({}[]<(({}<>)<>{}<>)>)}{}{}>)}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O61kZDQ1PTTrNaA8jWjI61qQbSQArEtbHTtLEDU3aatdVACKb@/zc0MPivm5Ock1hcnJkMAA "Brain-Flak – Try It Online") ## Brain-Flueue, 58 bytes ``` <>(<(())>)<>{(({}<>)<{({}({}))({}[()])}{}>[()]<>)}<>({}){} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/38ZOw0ZDQ1PTTtPGrlpDo7rWBsiqBtJApKkJJKI1NGM1a6tr7UAMoCRQAUiquvb/f0MDg/@6OUkg09JySlNLUwE "Brain-Flak – Try It Online") ## Mini-Flak, 62 bytes ``` ([{}()](())){(({})()({({}()([({})]({}{}))[({})])}{}{})[{}])}{} ``` [Try it online!](https://tio.run/##JYwxCsAwDAO/Iw2B9D0hQzoUTNMMXY3f7trpIukE0vkOWeWa43ZHUwM7QFIBNYJQZImW2EPC@ANtU4x2dD9q9TIfWZJ/Hw "Brain-Flak – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 4 bytes ``` LÅfP ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f53BrWsD//4YGBgA "05AB1E – Try It Online") -1 from Robbie0630, -1 more from an improvement on his suggestion. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~83~~ 81 bytes ``` (load library (d F(q((N)(i(l N 3)1(a(F(s N 1))(F(s N 2 (d P(q((N)(product(map F(0to N ``` [Try it online!](https://tio.run/##LcsxDoAgEAXR3lNs@ekA70BJuAJKQ7IKAhacHjGhm@JNi3fnWPMY4OQDcTyKL31DIIMHsAIRTJZ2oeBhUGcrIVbpH7oFc0nhPRsun@csWyI74EjL8QE "tinylisp – Try It Online") -2 bytes thanks to DLosc for reminding me to remove parentheses. # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 108 bytes ``` (d F(q((N)(i(l N 3)1(a(F(s N 1))(F(s N 2 (d M(q((A B)(i A(a B(M(s A 1)B))0 (d P(q((N)(i N(M(F N)(P(s N 1)))1 ``` [Try it online!](https://tio.run/##NcwxCsAgEETRPqeYcraL8QRa2CleQUgjSEgwTU5vVki6D/OYux5Pq/0cgzsCLzIJKxsSrBgWBnZtI/LVtiiMEzp4pXAs8Iw6OmVeZJ0i/1dIugVo5v9JzGCGseMF "tinylisp – Try It Online") Exceeds the maximum recursion depth around `N=14`. [Answer] ## Mathematica - 32 26 bytes ``` Fibonacci@i~Product~{i,#}& ``` @MartinEnder chopped 6 bytes! [Answer] ## [GAP](http://gap-system.org) 28 Bytes Didn't know before today that GAP has a `Fibonacci` builtin. ``` n->Product([1..n],Fibonacci) ``` [Answer] ### Ruby, 85 Bytes ``` g =->x{(1..x).to_a.collect{|y|(0..y).inject([1,0]){|(a,b),_|[b, a+b]}[0]}.inject(:*)} ``` Turned out fine, but there's probably a shorter solution. Fast Fibonnaci calculation taken from here: [link](https://stackoverflow.com/questions/6418524/fibonacci-one-liner) [Test it here](https://repl.it/Chae/0) [Answer] # Julia, 36 bytes ``` !x=[([1 1;1 0]^n)[2]for n=1:x]|>prod ``` ]
[Question] [ # Task Read a string of characters and produce the [ROT13](http://en.wikipedia.org/wiki/Rot13) of it. All characters besides `[a-zA-Z]` should be output verbatim. Each letter in the output may be in any case you wish (you do not have to preserve it). ROT13 is a simple substitution cipher where each letter of the alphabet is rotated by 13 places (it doesn't matter whether you do it forward or backward, since ROT13 is it's own inverse). # Examples ``` Input Output Hello, world! Uryyb, jbeyq! Code Golf and Coding Challenges is awesome. Pbqr Tbys naq Pbqvat Punyyratrf vf njrfbzr. Mod abuse!1!!1 Zbq nohfr!1!!1 ``` [Answer] # Bash, 23 bytes Canonical 23-character answer: ``` tr A-Za-z N-ZA-Mn-za-m ``` [Answer] # Python 2, 34 bytes ``` print raw_input().encode('rot13') ``` [Answer] ## Bash - 5 chars ``` rot13 ```   [Answer] ## Befunge - 7x30 = 210 6x26 = 156 characters New streaming version that supports both upper and lower case and should support unlimited input. ``` v,< << < ^-4-9< >:"A"\`| >:"a"\`| #>:"Z"`| >~:0`| # >:"z"`| , @ | <`"m":<v`"M":< ^ +4+9< ^ < ``` ### The old version This stores the values inside its own source code. Really shows off how horrible it is to try and output stored values in the same order that you receive them. Only supports lowercase characters. ``` vp0p11:+1g11< < < v ^-4-9< v >:"a"\`|>:"z"`|>:"m"`| >~:0`| >^ >^# ^+4+9< >$011g1+0p>12g1+:12p0g:v ^ ,_@ ``` I'm not sure exactly what limitations this has, using <http://www.quirkster.com/iano/js/befunge.html> as the interpreter it does appear to break with large inputs. [Answer] ## Ruby - 60 57 38 37 chars Edit: And just realised Ruby strings have a `tr` method. ``` puts$<.read.tr'A-Za-z','N-ZA-Mn-za-m' ``` ### Test ``` input = "The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible. Any language that can read and write standard streams is fair game." output = `echo '#{input}' | ruby golf-rot13.rb` puts "Input:" puts input puts "-------" puts "Output:" puts output ``` Gives: ``` Input: The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible. Any language that can read and write standard streams is fair game. ------- Output: Gur punyyratr: Gb ernq na vachg bs neovgenel yratgu naq cebqhpr gur EBG13 bs gur vachg. Nyy punenpgref orfvqrf N-M fubhyq or pbcvrq gb gur bhgchg ireongvz, naq pnfr fubhyq or cerfreirq vs cbffvoyr. Nal ynathntr gung pna ernq naq jevgr fgnaqneq fgernzf vf snve tnzr. ``` [Answer] # vim, 5 keystrokes Assuming normal mode and that the text is already written in the buffer: `g``g``g``?``G` Or, fallowing vimgolf's conventions: `g``?``G``Z``Z` You can also invoke it as a terminal command, something like this: ``` $ vim -c 'norm g?G' - < your text here ... ... multiple lines if you want ... ... terminate input with ctrl+D on a blank line > ``` I guess the latter would count as a "program" of 8 characters (`norm g?G`) [Answer] # R, 37 bytes ``` example("chartr");cat(rot(scan(,""))) ``` `example("chartr")` runs the examples for `chartr`, which includes the `rot` function, which is `ROT13` by default.... [Answer] ## C - 83 79 characters ``` main(c,b){while((c=getchar())>=0)b=c&96,putchar(isalpha(c)?b+1+(c-b+12)%26:c);} ``` Readable version: ``` #include <ctype.h> #include <stdio.h> int main(void) { int c, base; while ((c = getchar()) >= 0) { if (isalpha(c)) { base = (c & 96) + 1; /* First letter of the upper or lower case. */ c = base + (c - base + 13) % 26; } putchar(c); } return 0; } ``` [Answer] ## Python (117 bytes) Here's a Python version that avoids the `rot13()`-method. ``` import sys print"".join([chr(x/32*32+1+(x%32+12)%26if 64<x<91or 96<x<123 else x)for x in map(ord,sys.stdin.read())]) ``` [Answer] `tr///` solution in Perl (39 characters), boilerplate can be removed with `-p`: ``` while(<>){y/a-zA-Z/n-za-mN-ZA-M/;print} ``` Using `-p` (23 characters including the extra switch): ``` perl -pe'y/a-zA-Z/n-za-mN-ZA-M/' ``` [Answer] **DC (111 108 for the dc itself)** Ok, here it is in (mostly) dc and some sed and od magic to get it into the right format for the code. If you don't count the input thing (`echo -n MESSAGE |`) it's 160 bytes: ``` od -An -t dC|sed 's/^\ *//;s/\ \{2,3\}/\n/g'|dc -e'[13+26%]sm[65-lmx65+]su[97-lmx97+]sl[96<b64<dPc]sa[91>c]sd[123>e]sb[lux]sc[llxdd]se[ddddlaxlrx]sy[?z0<y]dsrx' ``` As a point of interest, the *dc programme* itself is only a *108 bytes* long, shorter than the non-library python version. It even preserves case and punctuation, and *beats* Javascript in the above submission! If only I could better parse the output of od, or better yet replace it altogether. EDIT: It's worth noting that the question doesn't indicate a trailing new line `10P` which saves me three further bytes. EDIT 2: There's no specification for the format of the input, so I assume it's taken in as is convenient for my programme :P [Answer] # PHP - ~~103~~ ~~98~~ 80 characters (not using str\_rot13()) ``` <?=preg_replace('#[a-zA-Z]#e','chr(($x=ord("\0"))-$x%32+1+($x%32+12)%26)',`cat`); ``` [Answer] ## Haskell, 100 characters ``` a%b=([a..b]++) main=interact$map$toEnum.((0%64$78%90$65%77$91%96$110%122$97%109$[123..])!!).fromEnum ``` [Answer] # [LispLisp](https://github.com/SYZYGY-DEV333/LispLisp) (16,636) I'm sorry. ``` ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)))) (lisp (lisp (lisp lisp)))))))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp lisp))) (lisp lisp))))))) ((lisp (lisp (lisp lisp))) (((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) ((((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp lisp)))))) (lisp (lisp (lisp lisp))))) ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp)) ((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp lisp)))))) (lisp (lisp (lisp lisp)))))))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp lisp)))))) (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)))))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) ((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))))))))) (lisp (lisp (lisp lisp))))))) ((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp lisp))) (lisp lisp))))))) ((lisp (lisp (lisp lisp))) (((((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp lisp)))))) (lisp (lisp (lisp lisp))))) (((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp)) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)))) (lisp (lisp (lisp lisp)))))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp))))) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (lisp (lisp (lisp lisp)))))))))) ((lisp (lisp (lisp lisp))) (lisp lisp)))))))))))) (lisp (lisp (lisp lisp)))))))))))) (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp)))))))))) (((lisp (lisp (lisp (lisp lisp)))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp (lisp lisp)))))) (((lisp (lisp (lisp (lisp lisp)))) ((lisp (lisp (lisp lisp))) (lisp (lisp (lisp lisp))))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) (lisp lisp))))) ((lisp (lisp (lisp lisp))) (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp)) ((lisp (lisp (lisp lisp))) ((lisp (lisp (lisp lisp))) (lisp lisp)))))))) ``` [Answer] Perl6 (54) ``` $*IN.lines».trans("a..zA..Z"=>"n..za..mN..ZA..M").say ``` [Answer] ## PHP - 41 Characters ``` while($r=fgets(STDIN))echo str_rot13($r); ``` [Answer] ## Delphi, 110 ``` var c:Char;begin repeat Read(c);Write(Chr(Ord(c)+(Ord(c in['A'..'M'])-Ord(c in['N'..'Z']))*13));until EOF;end. ``` [Answer] # C: 69 68 characters Alright, I know this thread is long dead, but I couldn't stand the (long) C-solution which doesn't even compile on Clang (but does on GCC). ``` main(c){putchar(isalpha(c=getchar())*((c|32)<110?13:-13)+c);main();} ``` It is probably almost still squeezable. It certainly was squeezable. And not only was it squeezable, it was possible to make it recursive. [Answer] # [CHIQRSX9+](http://esolangs.org/wiki/CHIQRSX9%2B), 1 ``` R ``` You just have to use the right tool for the problem. CHIQRSX9+ is Turing complete, and it can read and write from standard channels with `C`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes Saved a byte thanks to *robbie0630* ``` ADu)øJD2äRJ‡ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0aVU8/AOLxejw0uCvB41LPz/3zUvOT8lVTckw7NYpyDH1bHYVREA "05AB1E – Try It Online") **Explanation** ``` ADu # push lower-case and uppercase alphabet )øJ # zip, flatten and join, producing aAbB..zZ D2äRJ # split a copy in 2 pieces, reverse and join producing nNoO..mM ‡ # translate input by replacing members of the alphabet # with the corresponding member of the rot-13 alphabet # implicitly display ``` [Answer] # x86-16 Machine Code, IBM PC DOS, 37 bytes **Binary:** ``` 00000000: b408 cd21 3c20 7e1c 8ad0 0c20 3c61 7c0e ...!< ~.... <a|. 00000010: 3c7a 7f0a b60d 3c6e 7c02 b6f3 02d6 b402 <z....<n|....... 00000020: cd21 ebdc c3 .!... ``` Build and test using `xxd -r` **Unassembled listing:** ``` START: B4 08 MOV AH, 8 ; DOS API read char from STDIN (no echo) CD 21 INT 21H ; read char into AL 3C 20 CMP AL, ' ' ; is any non-printable control char? 7E 1C JL EXIT ; if so, end 8A D0 MOV DL, AL ; save original char in DL 0C 20 OR AL, 'a'-'A' ; lowercase the char 3C 61 CMP AL, 'a' ; is char less than 'a'? 7C 0E JL WRCHR ; if so, do not convert 3C 7A CMP AL, 'z' ; is char greater than 'z'? 7F 0A JG WRCHR ; if so, do not convert B6 0D MOV DH, 'n'-'a' ; add or subtract 13 3C 6E CMP AL, 'n' ; is char less than 'n'? 7C 02 JL ADD13 ; if so, add 13 B6 F3 MOV DH, 'a'-'n' ; otherwise add -13 ADD13: 02 D6 ADD DL, DH ; add 13 or -13 WRCHR: B4 02 MOV AH, 2 ; DOS API write char to STDOUT CD 21 INT 21H ; write char in DL EB DC JMP START ; keep looping EXIT: C3 RET ; return to DOS ``` As a standalone PC DOS executable program. Input is via `STDIN`, output to `STDOUT`. [![enter image description here](https://i.stack.imgur.com/vBuQY.png)](https://i.stack.imgur.com/vBuQY.png) Re-submitting answer to conform to `STDIN` challenge requirement. [Answer] # [C (clang)](http://clang.llvm.org/), ~~200~~ ~~164~~ ~~113~~ 86 bytes ``` main(){char*s,*t=s;for(gets(s);*s;s++)isalpha(*s)?*s+=(*s&~32)<78?13:-13:0;printf(t);} ``` [Try it online!](https://tio.run/##DcY7DsIwDADQq8CCbKeVgA4gTNWVGzBboZ9IJqnibAiuHjo86fnWq8S51reECPjxi2SyhkpvPKUM81gMDJmMzTkMJrouAmQ4kLl@y@HXnfF@uQ6n7tZujrzmEMsEBflb62NUTc3umbK@9n8 "C (clang) – Try It Online") This uses a for-loop which converts each letter into ROT13 using their ASCII values to use lesser bytes. `scanf()`'s parameters are now longer to include spaces in the string, since the previous code revision can't take spaces for input, so now it's longer. Thanks to ceiling cat for golfing 36 bytes. Thanks to EasyasPi, with the help of ceilingcat, for golfing 51 bytes. Thanks to a stone arachnid for golfing 27 bytes. [Answer] **Java 251 chars** ``` public class r{public static void main(String[] a){String s = a[0];for(int i=0;i<s.length();){char c=s.charAt(i++);if(c>='a'&&c<='m')c+=13;else if(c>='n'&&c<='z')c-= 13;else if(c>='A'&&c<='M')c+=13;else if(c>='A'&&c <='Z')c-=13;System.out.print(c);}}} ``` [Answer] # Python 3 (107) Ok, I promise to stop answering this question now, but I felt compelled to beat the DC answer in Python. This probably reflects poorly on me as a person :). ``` import sys;[print(x.isalpha()and chr((ord(x)&96)+1+(ord(x)%32+12)%26)or x,end='')for x in sys.stdin.read()] ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 49 bytes ``` 0i::"{`"@(@)*84**-::"AZ"@(@)+:}?$"4"-2d*%"A"+{?$o ``` [Try it online](https://tio.run/##S8sszvj/3yDTykqpOkHJQcNBU8vCREtLF8h3jALzta1q7VWUTJR0jVK0VJUclbSr7VXy///3SM3JyddRKM8vyklRBAA) **Explanation** `0i` On each loop we initialize the stack with **0** and an input character. `::"{`"@(@)*84**-` Convert lowercase letters into uppercase for easier future operations. `::"AZ"@(@)+:}?$` If the character isn't an uppercase letter, use the **0** instead. `"4"-2d*%"A"+` ROT-13 operation. Subtract **52**, mod by **13** and add **65** to get an uppercase letter. `{?$` If the character wasn't an uppercase before the ROT-13 operations, use the saved character instead. `o` Print as a character. [Answer] **JavaScript 1.8, 106** `alert(prompt().replace(/\w/g,function(c)String.fromCharCode(c.charCodeAt()+(c.toLowerCase()<'n'?13:-13))))` **JavaScript, 115** `alert(prompt().replace(/\w/g,function(c){return String.fromCharCode(c.charCodeAt()+(c.toLowerCase()<'n'?13:-13))}))` This solution solves the problem by adding 13 to the character code if the character in question is in the first half of the alphabet, or subtracting 13 if it's in the second half. [Answer] # Javascript (165) ``` a=prompt();y="ABCDEFGHIJKLMNOPQRSTUVWXYZ";b=y[s="substr"](13)+y[s](0,13);y+=y[l="toLowerCase"]();b+=b[l]();o='';for(i=0;a[i];i++)o+=b[y.indexOf(a[i])]||a[i];alert(o) ``` or (167) as previous Javascript solution, assuming readLine and print: ``` a=readLine();y="ABCDEFGHIJKLMNOPQRSTUVWXYZ";b=y[s="substr"](13)+y[s](0,13);y+=y[l="toLowerCase"]();b+=b[l]();o='';for(i=0;a[i];i++)o+=b[y.indexOf(a[i])]||a[i];print(o) ``` [Answer] ## C, 136 bytes I have never felt like any of my solutions are good enough to post on here, but made this for fun, and figured that it will be my gateway drug into code golf. ``` #define z(x) c>=x&&c<x+13 #define q(w) c>=w&&c<w+13 main(c){for(;(c=getchar())>=0;putchar(z('A')||z('a')?c+13:q('M')||q('m')?c-13:c));} ``` [Answer] # Jolf, noncompeting (language postdates challenge) Jolf, 3 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=LFJp) ``` ,Ri ,R rot13 i the input ``` Or, with new implicit input, `,R`. I'm sorry, but I'm not. I implemented this because it appears often in code-breaking puzzles, which I use Jolf a lot for, and recently used in an ARG. \o/ A longer one ([try that one here](http://conorobrien-foxx.github.io/Jolf/#code=z4FpIlslXSLOs3BXcHVkLnBXcDJwdSt0MyBpzrNI)): ``` ρi"[%]"γpWpud.pWp2pu+t3 iγH ρi regex replace input "[%]" "[...]" following pWpu "abc...xyzABC....XYZ" γ γ = that d functional replace . _iγH the index on the alphabet that the element is p2pu shift uppercase alphabet +t3 over thirteen pW upper + lower of that ``` [Answer] # [Julia 1.0](http://julialang.org/), 69 bytes ``` (x->(c=Char(x);print(c+isletter(c)*13*(-1)^(x&31>13)))).(read(stdin)) ``` [Try it online!](https://tio.run/##FcmxCsIwEADQ3a84OshdpULIKHZQcRBBBGchpMGm1qRcEo3@fNS3viGNVolcCuamRb3e9oox02pi6yLqhQ2jidEwaqqFrLERdMU8l6IVkn6WyEZ1GGJnHVEp1aU3cE5W32HD/uVg7/PskB5TgNPTMPz7qD5v2Plb9QU "Julia 1.0 – Try It Online") ### Explanation Most of the code is an anonymous function that takes an integer codepoint and prints the corresponding ROT-13'd character: ``` x->(c=Char(x);print(c+isletter(c)*13*(-1)^(x&31>13))) x->( ) # Anonymous function of x c=Char(x); # Cast x to Char and save as c c+ # Start with c and add to its codepoint: isletter(c)* # If c is not a letter, the rest of this is # multiplied by 0 13*(-1)^( ) # 13, times +/- 1 according to: x&31>13 # Low 5 bits of x are greater than 13 # I.e. x > 'M' (if x is uppercase) or x > 'm' # (if x is lowercase) print( ) # Output the resulting character ``` We then apply this function, vectorized, to the array of (integer) codepoints returned by `read(stdin)`. ]
[Question] [ *Blatant [rip-off](https://codegolf.stackexchange.com/q/192979/43319) of a [rip-off](https://codegolf.stackexchange.com/q/132558/43319). Go upvote those!* Your task, if you wish to accept it, is to write a program/function that outputs/returns its integer input/argument. The tricky part is that if I reverse your source code, the output must be the original integer negated. ## Examples Let's say your source code is `ABC` and its input is `4`. If I write `CBA` instead and run it, the output must be `-4`. Let's say your source code is `ABC` and its input is `-2`. If I write `CBA` instead and run it, the output must be `2`. An input of `0` may give `0` or `-0`, however, if you do support signed zero, `-0` should give `0`. [Answer] # [J](http://jsoftware.com/), 3 bytes ``` -&0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ddUM/mtypSZn5CukKZgowFiWllxcRallqUXFqSkKtnoKBmq6XBA5uKgJGh@o5T8A "J – Try It Online") `-&0` is "argument minus 0" `0&-` is "0 minus argument" [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~18~~ 14 bytes ``` $args#"sgra$"- ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9WFmpOL0oUUVJ938tF5eaSpqC@X8A "PowerShell – Try It Online") [!enilno ti yrT](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V9XSSWxKL1YSbk4vShR5X8tF5eaSpqC@X8A "PowerShell – Try It Online") First of the trivial comment-abuse answers [Answer] # x86 machine code, 3 bytes ``` C3 D8 F7 ``` The above bytes of code define a function that is a no-op: it simply returns control to the caller. That function is followed by two garbage bytes that will not be executed, since they come after a return—they are in "no man's land". In assembler mnemonics: ``` ret ; C3 fdiv st(0), st(7) ; D8 F7 ``` Okay, so now some troll comes by and reverses the order of the bytes: ``` F7 D8 C3 ``` These bytes now define a function that takes an integer argument in the `EAX` register, negates it, and returns control to the caller. In assembler mnemonics: ``` neg eax ; F7 D8 ret ; C3 ``` So…that was simple. :-) Note that we can make the "negation" instruction be *anything* we want, since it is never executed in the "forward" orientation and only executed in the "reversed" orientation. Therefore, we can follow the same pattern to do arbitrarily more complicated stuff. For example, here we take an integer argument in a different register (say, `EDI`, to follow the System V calling convention commonly used on \*nix systems), negate it, and return it in the conventional `EAX` register: ``` C3 ret D8 F7 fdiv st(0), st(7) ; \ garbage bytes that F8 clc ; | never get executed, 89 .byte 0x89 ; / so nobody cares ```   ↓ ↓ ``` 89 F8 mov eax, edi F7 D8 neg eax C3 ret ``` [Answer] # JavaScript, 11 bytes ``` n=>n//n->=n ``` [Try it Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5PXz9P1842739yfl5xfk6qXk5@ukaahomm5n8A) | [Reversed](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k43T18/z842739yfl5xfk6qXk5@ukaahomm5n8A) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` oN ``` **[Try it online!](https://tio.run/##y0rNyan8/z/f7////7qmAA "Jelly – Try It Online")** and [its reverse](https://tio.run/##y0rNyan8/98v/////7qmAA "Jelly – Try It Online"). ``` oN - (input) OR ((input) negated) No - ((input) negated) OR (input) ``` [Answer] # [Haskell](https://www.haskell.org/), 8 bytes Anonymous identity function, turning into subtraction from `0` when reversed. ``` id--)-0( ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZ5uZV5JalJhcolKckV@ul6anUZSamGJlFVxSlJmXrmvnmVeiyZVmqxDzPzNFV1dT10Dj/3@Tf8lpOYnpxf91I5wDAgA "Haskell – Try It Online") Reversed: ``` (0-)--di ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZ5uZV5JalJhcolKckV@ul6anUZSamGJlFVxSlJmXrmvnmVeiyZVmqxDzX8NAV1NXNyXz/3@Tf8lpOYnpxf91I5wDAgA "Haskell – Try It Online") [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 48 bytes ``` S S S N S N S T N T T T T T T N S T N N N T S N T N S S T N T T S S T T T T T N T S N S N S S S ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. Minor modification of [my Whitespace answer for the *I reverse the source code, you negate the output!* challenge](https://codegolf.stackexchange.com/a/192993/52210). [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4wQDE4uLiVOACssCCQBIszglWpqDw/7@hAQA) or [try it online reversed](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QUBBgRPIAgpxgoS4gEyIOEgQpExB4f9/QwMA) (with raw spaces, tabs and new-lines only). **Explanation:** Utilizing the *Exit Program* builtin being a short palindrome `NNN`. The regular program will: ``` SSSN # Push 0 to the stack SNS # Duplicate it TNTT # Read STDIN as integer, and store it at heap address 0 TTT # Retrieve the input from heap address 0, and push it to the stack TNST # Pop and print the top of the stack as number NNN # Exit the program, making everything after it no-ops ``` The reverse program will: ``` SSSN # Push 0 to the stack SNS # Duplicate it TNTT # Read STDIN as integer, and store it at heap address 0 TTT # Retrieve the input from heap address 0, and push it to the stack SSTTN # Push -1 to the stack TSSN # Multiply the top two values on the stack together TNST # Pop and print the top of the stack as number NNN # Exit the program, making everything after it no-ops ``` Small additional explanation of pushing a number: * First `S`: Enable Stack Manipulation * Second `S`: Push a number to the stack * `S` or `T`: Positive/negative respectively * Some `S`/`T` followed by a trailing `N`: number in binary, where `S=0` and `T=1` I.e. `SSTTSTSN` pushes `-10`. For the `0` we don't need an explicit `S=0`, so simply `SSSN` or `SSTN` is enough. [Answer] # [R](https://www.r-project.org/), 23 bytes I decided to give it a go without the comment trick. ### Forward ``` `+`=scan;""+-0;nacs=`+` ``` [Try it online!](https://tio.run/##K/r/P0E7wbY4OTHPWklJW9fAOi8xudgWKPbf9P9/AA "R – Try It Online") ### Reverse ``` `+`=scan;0-+"";nacs=`+` ``` [Try it online!](https://tio.run/##K/r/P0E7wbY4OTHP2kBXW0nJOi8xudgWKPbf9P9/AA "R – Try It Online") In the forward version `+` is acting a binary operator, and `-` is a unary operator. In the reverse the `+` becomes unary and the `-` is binary. So scan function takes the arguments: `file=""` which means stdin and `what=0`, which are also defaults. So when the `+` is unary the first argument is on the right, when it is binary the first argument is on the left. The ``` ;nacs=`+` ``` part of the code does nothing really useful, so in a sense my code is not really very much more valid than using the comment trick. [Answer] # [C (clang)](http://clang.llvm.org/), 23 bytes ``` f(*x){}//};x*-=x*{)x*(g ``` [Try it online!](https://tio.run/##fYrLCoAgEEX3fsUQFOOQuA7xT9qIoQQlES0GxG@3F23bnXvO9covLsVaAxLLXLQuhklZpiyZMNb4eGKriE0RYk4HrG5OKLMAuBfbYTAXAwTsWL647VcKgE07janpPx1/H6We "C (clang) – Try It Online") [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth) / [Hexagony](https://github.com/m-ender/hexagony), 6 bytes Labyrinth: ``` ?!@!`? ``` **[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fXtFBMcH@/39dUwA "Labyrinth – Try It Online")** and [its reverse](https://tio.run/##y0lMqizKzCvJ@P/fPkHRQdH@/39dUwA "Labyrinth – Try It Online"). Hexagony: ``` ?!@!~? ``` **[Try it online!](https://tio.run/##y0itSEzPz6v8/99e0UGxzv7/f11TAA "Hexagony – Try It Online")** and [its reverse](https://tio.run/##y0itSEzPz6v8/9@@TtFB0f7/f11TAA "Hexagony – Try It Online"). ### How? ``` ? - take a signed integer (` / ~) - negate ! - output top-of-stack / current-memory-edge @ - exit ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg) / Raku, 3 bytes ``` *-0 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPtfS9fgvzUXF5Crlq5gq2Cgq8UF5BYngqQ1jDStwcx0BSNrmJgpXMzU@j8A "Perl 6 – Try It Online") Creates a Whatever code block. Read in normally its standard block equivalent is `-> \x {x - 0}`, but in reverse it becomes `-> \x {0 - x}`. [Answer] # [Python 3](https://docs.python.org/3/), 22 bytes ``` lambda x:x#x-:x adbmal ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqkK5QteqQiExJSk3Med/QVFmXolGmoalpuZ/AA "Python 3 – Try It Online") A lambda which implements the identity function (or negation) [Answer] # [MarioLANG](https://github.com/tomsmeding/MarioLANG), 22 bytes ``` ;: =# :)! -- <( " [> ; ``` [Try it online!](https://tio.run/##y00syszPScxL///f2orLVpnLSlORS1eXy0aDS4kr2o7L@v9/QwMA "MarioLANG – Try It Online") He just inputs and outputs the number before he falls to EOF reversed: ``` ; >[ " (< -- !): #= :; ``` [Try it online!](https://tio.run/##y00syszPScxL///fmssumkuJS8OGS1eXS1HTikvZlsvK@v9/QwMA "MarioLANG – Try It Online") He loops until the input value is 0 and the output value is -input, the he says the number. [Answer] ## Haskell, 12 bytes ``` f=id;x-0=x f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802M8W6QtfAtkIh7X9uYmaegq1CQVFmXomCikKagul/AA "Haskell – Try It Online") Reverse: ``` f x=0-x;di=f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwtZAt8I6JdM27X9uYmaegq1CQVFmXomCikKagul/AA "Haskell – Try It Online") Not as short as [Ørjan Johansen's answer](https://codegolf.stackexchange.com/a/193054/34531), but without comments. [Answer] # Perl 5 (`-p`), ~~7~~ 6 bytes -1 thanks to @primo ``` $_*=$# ``` [TIO](https://tio.run/##K0gtyjH9/18lXstWRfn/f5N/@QUlmfl5xf91CwA) A comment doesn't change input ``` #1-=*_$ ``` Negate the input ``` $_*=-1# ``` [TIO](https://tio.run/##K0gtyjH9/1/ZUNdWK17l/3@jf/kFJZn5ecX/dQsA) [Answer] # [Gaia](https://github.com/splcurran/Gaia), 2 bytes ``` _@ ``` [Try it online!](https://tio.run/##S0/MTPz/P97h/39TAA "Gaia – Try It Online") ``` _ | implicit push input and negate @ | push next input OR push last input (when all inputs have been pushed) | implicit print TOS ``` Reversed: ``` @ | push input _ | negate | implicit print TOS ``` [Answer] # [Backhand](https://github.com/GuyJoKing/Backhand), ~~6~~ 5 bytes ``` I@-Ov ``` [Try it online!](https://tio.run/##S0pMzs5IzEv5/9/TQde/7P9/QwMA "Backhand – Try It Online") [Try it doubled!](https://tio.run/##S0pMzs5IzEv5/7/MX9fB8/9/QwMA) Made a little complex due to the nature of the pointer in Backhand. ~~I don't think it's possible to get any shorter~~ haha, turns out I was wrong. This duplicates *no* instruction and reuses both the input, output and terminate commands between the two programs. *Now* I think it is optimal, since you need all of the `IO-@` commands to work, and in a 4 byte program you can only execute two of those commands. ### Explanation: The pointer in Backhand moves at three cells a tick and bounces off the boundaries of the cell, which means the general logic is overlapping. However you can manipulate this speed with the `v` and `^` commands. The original program executes the instructions `IO-@`, which is input as number, output as number, subtract, terminate. Obviously the subtract is superfluous. In the code these are: ``` I@-Ov ^ ^ Reflect ^ Reflect again ^ ``` The reversed program executes `v-I-vO-@`. The `v` reduces the pointer steps between ticks, and the `-` subtracts from the bottom of the stack, which is implicitly zero. The extra `-` commands do nothing. The program executes like ``` vO-@I v Reduce pointer speed to 2 - Subtract zero from zero I Get input as number and reflect off boundary - Subtract input from zero v Reduce pointer speed to 1 O Output as number - Subtract zero from zero @ Terminate ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 7 bytes ``` #)]}{[( ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X1kztrY6WuP/f2MA "Brain-Flak – Try It Online") Reversed: ``` ([{}])# ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyO6ujZWU/n/f2MA "Brain-Flak – Try It Online") Note: Only works in interpreters that support comments (e.g. works in Rain-Flak, but not in BrainHack) --- If we also swap opening/closing brackets instead of just reversing the bytes we can do this in 8 bytes without using comments: ``` ({}[{}]) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6Nrq6Nlbz/39jAA "Brain-Flak – Try It Online") [Try it reversed!](https://tio.run/##SypKzMzTTctJzP7/XyO6uja2ulbz/39jAA "Brain-Flak – Try It Online") [Answer] # [R](https://www.r-project.org/), 14 bytes ``` scan()#)(nacs- ``` [Try it online!](https://tio.run/##K/r/vzg5MU9DU1lTIy8xuVj3v@n//wA "R – Try It Online") A full program that reads a number, or reads and negates a number. The reverse functionality is protected by an inline comment [Answer] # [Python 3](https://docs.python.org/3/), ~~22~~ 14 bytes ``` int#__bus__. 0 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPzOvRDk@Pqm0OD5eT8Hgf0ERUEAjTcNYU/M/AA "Python 3 – Try It Online") Uses the `int` class's constructor and a built-in pseudo-private method. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes ``` 1&0+#-0&1 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar9N9QzUBbWddAzfC/EldAUWZeSbSyrl11SL5rRUFRanFxZn5edFqsg7IOikhwCVBlelBqWWpRcaoDSL42Vk3fISgxLz3VwdDgPwA "Wolfram Language (Mathematica) – Try It Online") Forward: read `((1)&*0+#-0)&*1`=`#&` Backward: read `((1)&*0-#+0)&*1`=`-#&` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~13~~ 3 bytes ``` -∘0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////3/ao7YJuo86ZhhwpQNZBkCW7v80BUOudAVDAA "APL (Dyalog Unicode) – Try It Online") Trivial answer. Returns `arg` or `¯arg`. Saved 10 bytes by not being dumb (thanks Adám). Altered the resulting 3-byter to a more fitting function. [Answer] # Batch, 34 bytes ``` @ECHO.%1 2>MER@ @REM>2 1%=-aa/TES@ ``` Echoes (`ECHO.`) the input (`%1`). The rest of the first line technically redirects `STDERR` to a file called `MER@`, but this isn't impactful. Second line is commented out (`REM...`). ### Reversed ``` @SET/aa-=%1 2>MER@ @REM>2 1%.OHCE@ ``` Uses the arithmetic mode of the set command (`SET /a`) to subtract (`-=`) the input (`%1`) from an undefined variable (`a`) which is equivalent to `0 - input`. Again, the rest of the first line technically redirects `STDERR` to a file called `MER@`, but this isn't impactful. Second line is commented out (`REM...`). [Answer] ## Excel VBA, 12 ``` ?[A1]']1A[-? ``` Reversed: ``` ?-[A1]']1A[? ``` Input is cell A1 of the ActiveSheet. Comments still work in the Immediate Window :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` (I ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fU@P/f1MA) [Reversed](https://tio.run/##yy9OTMpM/f/fU@P/f1MA) ``` ( negates nothing I pushes input I pushes input ( negates input ``` [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 6 bytes ``` &[[email protected]](/cdn-cgi/l/email-protection)& ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X03PQU9X7f9/QwMA "Befunge-98 (FBBI) – Try It Online") [Try it reversed!](https://tio.run/##S0pNK81LT9W1tPj/X01Xz0FP7f9/QwMA "Befunge-98 (FBBI) – Try It Online") [Answer] # [Klein](https://github.com/Wheatwizard/Klein), 2 bytes *Works in all 12 topologies!* ``` @- ``` [Try it online!](https://tio.run/##y85Jzcz7/99B9////wYGBv8NAQ "Klein – Try It Online") # Reverse ``` -@ ``` [Try it online!](https://tio.run/##y85Jzcz7/1/X4f///wYGBv8NAQ "Klein – Try It Online") `-` negates the input and `@` ends the program [Answer] # [Turing Machine Language](http://morphett.info/turing/turing.html), 39 bytes [The Positive](http://morphett.info/turing/turing.html?3fbc2a79501a4424cbbb52ae008e684f) ``` 1 r - _ 0 0 l * * 0 0 - _ l 0 0 _ _ r 0 ``` [The Negative](http://morphett.info/turing/turing.html?2742e8faf2421c7f508801f64b69090b) ``` 0 r _ _ 0 0 l _ - 0 0 * * l 0 0 _ - r 1 ``` This one was a bit trickier than I thought, mostly because I had to get past my prejudices of having code that runs with 'compile' errors. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~5~~ 4 bytes ``` n-r0 ``` uses stack initialisation with the `-v` option, put your input variable there. [Try it online!](https://tio.run/##S8sszvj/P09L19Dg////umUKhgYA) [Or try the reversal](https://tio.run/##S8sszvj/38BQVyvv////umUKuoYA) **Explanation** ``` n Prints whatever is on the stack as a number - Subtract the top 2 elements on the stack. There aren't 2 elements, so it crashes. r0 Never gets executed or reversed: 0 Push a 0 onto the stack r reverse the stack (now 0, -v) - Subtract top 2 elements and push result (0-v, ie negated) n Print as number The code wraps around and executes again. It crashes on the - as there is only one item on the stack: 0. ``` [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats) `-mn`, 2 bytes ``` -X ``` [Try it online!](https://tio.run/##Ky5JTM5OTiwp/v9fN@L/f9P/url5AA "Stack Cats – Try It Online") [Try the reverse!](https://tio.run/##Ky5JTM5OTiwp/v8/Qvf/f9P/url5AA "Stack Cats – Try It Online") ### Explanation Turns out this is actually a lot easier than the previous challenge in Stack Cats. The full program (after applying `-m`) here is `-X-`. `X` is used to swap the stacks left and right of the tape head, i.e. it doesn't affect the initial stack at all, so we can ignore it. But then the program is effectively just `--` (negate the top of the stack twice), which does nothing. For the inverse program, applying `-m` gives `X-X`. Again, `X` does nothing, so the program is effectively just `-`, which negates the top of the stack. The only other 2-byte solution is `-=`, but it's virtually the same. The only difference is that `=` swaps only the tops of the adjacent stacks, not the entire stacks. But again, using `-m` feels a bit like cheating, so below is a solution that uses a fully mirrored program. --- ## [Stack Cats](https://github.com/m-ender/stackcats) `-n`, 7 bytes ``` :I<->I: ``` [Try it online!](https://tio.run/##Ky5JTM5OTiwp/v/fytNG187TCkxzAYl4rhoQqwbECgGxgET8f13D/7p5AA "Stack Cats – Try It Online") [Try the reverse!](https://tio.run/##Ky5JTM5OTiwp/v/fytNO18bTCkjb6HIBiXiuGhCrBsQKAbGARPx/XcP/unkA "Stack Cats – Try It Online") ### Explanation The considerations [from the previous answer still apply](https://codegolf.stackexchange.com/a/193215/8478): any valid solution needs to use the paired characters and `I`. The six possible solutions (included in the TIO link) are all virtually the same. `-` and `_` are equivalent in this program, and `:` can be replaced by `|` or `T` (which do the same for non-zero inputs and coincidentally also work for zero inputs). I've just picked this one to explain because it's easiest. So remember that the initial stack holds the input on top of a `-1` (on top of infinitely many zeros) whereas all the other stacks along the tape only hold zeros. Stack Cats also has the property that any even-length program does nothing (provided it terminates, but we can't use loops for this challenge anyway). The same is then obviously true for any odd-length program whose centre character does nothing... let's see: ``` : Swap the input with the -1 below. I Move the -1 one stack to the left and turn it into +1. < Move another stack left (without taking the value). - Negate the zero on top of that stack (i.e. do nothing). ``` Therefore, the second half of the program exactly undoes the first half and we end up with the input on top of a `-1` again. The inverse program is `:I>-<I:`. Let's see how that changes things: ``` : Swap the input with the -1 below. I Move the -1 one stack to the left and turn it into +1. > Move one stack right, i.e. back onto the initial stack which still holds the input. - Negate the input. < Move back to the left where we've parked the 1. I Move that 1 back onto the initial stack and turn it back into a -1. : Swap the -1 below the negated input to act as an EOF marker. ``` ]
[Question] [ This is a graphical output challenge where the task is to give the shortest code *per* language. **Task** Your code should plot a single purple pixel (hex value #800080 or rgb(128, 0, 128)), moving clockwise round a circle. It should take exactly 60 seconds to make a full journey round the circle and should continue indefinitely. Nothing else should be shown on the screen or window except for the pixel. The width of the circle should be 0.75 (rounding suitably) the width of the screen or window and the background should be white. To prevent silly solutions, the screen or window should be at least 100 pixels wide. Your code should be a **full program**. **Languages and libraries** You can use any language or library you like. However, I would like to be able to test your code if possible so if you can provide clear instructions for how to run it in Ubuntu that would be very much appreciated. **Missing top twenty languages. Help needed.** The following top twenty programming languages are currently missing any solution at all. * C, C++, C#, Python, PHP, Visual Basic .NET, Perl, Delphi/Object Pascal, Assembly, Objective-C, Swift, Pascal, Matlab/Octave, PL/SQL, OpenEdge ABL, R ### Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <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 = 62095; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 9206; 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, 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] # [Processing](https://processing.org/), ~~101~~ ~~97~~ 96 bytes *[4 bytes](https://codegolf.stackexchange.com/questions/62095/a-single-pixel-moving-round-a-circle/62099#comment149918_62099) thanks to Flambino.* *1 byte thanks to Kritixi Lithos.* ``` float d;void draw(){background(-1);stroke(#800080);d+=PI/1800;point(50+cos(d)*38,50+sin(d)*38);} ``` This creates a default 100 by 100 pixel window with the required animation. [![output window](https://i.stack.imgur.com/Ybbs0.png)](https://i.stack.imgur.com/Ybbs0.png) Disclaimer: that image is not a GIF. Don't stare at it for a minute. [Answer] # QB64, 79 bytes *QB64 is a QBasic emulator that adds some nice features. This program uses one (`CLS,15`) that isn't supported by vanilla QBasic.* ``` SCREEN 7 DO T=TIMER/9.55 PSET(COS(T)*75+99,SIN(T)*75+99),5 PLAY"c8" CLS,15 LOOP ``` **This is very loud.** It uses the `PLAY` command to halt execution for a short while before clearing the screen; otherwise the pixel will flicker and become invisible. Download [QB64](http://www.qb64.net/), load this file, click `Run` and then `Start`. Here it is in action: [![the program](https://i.stack.imgur.com/NS2bf.png)](https://i.stack.imgur.com/NS2bf.png) I took some tricks (`SCREEN 7` instead of `SCREEN 13`, and `PSET` instead of `POKE`) from @DLosc's answer, so credit is due. As in his answer, my magenta is actually `#8B008B`, which was deemed acceptable by the OP. (The constant `9.55` is an approximation of `30/π = 9.54929658551`. Is it close enough?) [Answer] # Java, ~~449~~ ~~443~~ 439 bytes Because I've always had stupid ideas. Like golfing in Java ;) . ``` import java.awt.*;import javax.swing.*;class F extends JFrame{F()throws Exception{setContentPane(new P());setSize(400,400);setVisible(0<1);for(;;Thread.sleep(100))repaint();}class P extends JPanel{double c;public void paintComponent(Graphics g){g.setColor(new Color(8388736));c=(c-0.1)%60;double t=0.104*c;g.fillRect((int)(180+Math.sin(t)*120),(int)(180+Math.cos(t)*120),1,1);}}public static void main(String[]x)throws Exception{new F();}} ``` Edit: Thanks for @Ypnypn for golfing 7 bytes! Edit2: Thanks for @Franz D. for saving 3 bytes! [Answer] # HTML, 235 ~~290~~ ~~295~~ ~~354~~ ~~347~~ bytes ``` <a><style>*{position:absolute;margin:0;box-sizing:border-box}body{height:100vh;width:100vh}a{left:12.5%;top:50%;width:75%;height:1px;border-left:1px solid purple;animation:r 60s infinite linear}@keyframes r{100%{transform:rotate(360deg ``` Save as a `.html` file and open in a browser, that doesn't need vendor prefixes, like Chrome or Firefox. Or try [this fiddle](http://jsfiddle.net/se3kc1f1/). --- This is a new version which is way shorter than my first attempt, that I had written 5 minutes before a meeting. The new size of the canvas is a square based on the viewport height. That works pretty well and is not restricted to a certain defined height. I'm very accurate about the settings in the challenge (75% size of its parent, purple and 1px). Therefore I need and can't discard or simplify the following rules: ``` * { margin: 0; box-sizing:border-box; } a { left: 12.5%; } ``` --- **Ungolfed** This is the *ungolfed* version with clean markup: ``` <!DOCTYPE html> <html> <head> <style> * { position: absolute; } body { margin: 0; height: 100vh; width: 100vh; } a { left: 12.5%; top: 50%; width: 75%; height: 1px; border-left: 1px solid purple; box-sizing: border-box; animation: r 60s infinite linear; } @keyframes r { 100%{ transform: rotate(360deg) } } </style> </head> <body> <a></a> </body> ``` **Edits** * *Added* **7 bytes**. I thought nobody would notice, that there's a default easing on the animation. ;) I've set it to `linear` now. * *Saved* **59 bytes** by throwing everything abort that the browser will handle automatically. * *Saved* **3 bytes** by removing the trailing `)}}`. Thanks to [toothbrush](https://codegolf.stackexchange.com/users/15022/toothbrush). * *Saved* **2 bytes** by using `12%` instead of `12px` which is the same value corresponding to the size of the parent element. * *Saved* **55 bytes** due to massive refactoring, also taken a lot of comments into account. Thanks a lot for all the contributions. [Answer] # TI-BASIC, 44 bytes For the TI-84+ CSE/CE calculators, which support some limited BASIC color graphics. ``` AxesOff ZSquare While rand Pt-Off(imag(Ans),real(Ans 7.5e^(-i6startTmr° Pt-On(imag(Ans),real(Ans),13 End ``` The color here is magenta, or color 13 (one can also use the `MAGENTA` token). I use `rand` instead of `1` for the infinite loop condition to provide a tiny bit of delay (~15 ms) between when the pixel is displayed and when it is turned off again. Set your calculator to radian mode before running this program; I don't count this in the size because it's the default state. Also set `Ans` to 0 by entering a 0 before the program; this is also the default. Thanks to @quartata for testing this program (I don't own a color calculator). [Answer] # Java, 339 308 289 287 bytes ``` import java.awt.*;class F extends Frame{{setSize(200,200);show();}int c;public void paint(Graphics g){g.setColor(new Color(8388736));g.fillRect((int)(99+Math.sin(--c*.01)*75),(int)(99+Math.cos(c*.01)*75),1,1);for(int i=0;++i<62864;)paint();}public static void main(String[] x){new F();}} ``` Thanks to @Peter Lenkefi, whose great solution got me started, and whose for-loop I shamelessly copied! The main saving was due to switching to pure AWT and rendering directly in the Frame -- no need for a JPanel (or Canvas). I also made the counter an integer variable, updated by simple increment, and saved a few bytes twiddling the constants to be able to strip a digit here and there. **EDIT:** Thanks to @Peter Lenkefi and @tobii for their suggestions in the comments. Beating HTML would be nice -- does anyone know how to reliably pause execution in Java without using sleep() and having to catch exceptions? **EDIT 2:** JAVA BEATS HTML (currently at 290 bytes!) :D Timing is now machine-dependent, but ~60 seconds for a full circle on my machine, which is OK according to @Lembik. Thanks again to @PeterLenkefi for his suggestion -- my answer is more than half his :) **EDIT 3:** @Ajay suggested to remove the "re" from "repaint". Two bytes less. We're getting there :) [Answer] # Mathematica, ~~102~~ ~~101~~ 94 bytes ``` Animate[Graphics[{White,Disk[],{Purple,Point[{0,1}]}}~Rotate~-t],{t,0,2π},DefaultDuration->60] ``` Creates a white circle that is hidden and places a point that follows its edge from 0 to 2π. Mathematica's `DefaultDuration` option let's me set it to complete a loop every 60 seconds. Here's a sped up version of the output: ![](https://i.stack.imgur.com/eYVdo.gif) EDIT: Change `Circle` to `Disk` to save 2 characters, added a negative sign to `t` to make it move clockwise. EDIT: Saved 7 bytes by using the `~` operator (thanks to Mauris). [Answer] # Haskell, ~~143~~ 136 bytes This uses the [gloss](http://hackage.haskell.org/package/gloss-1.9.4.1) package: ``` import Graphics.Gloss main=animate(InWindow""(100,100)(0,0))white$ \t->color(makeColor 0.5 0 0.5 1).rotate(t*6).translate 38 0$circle 1 ``` The prettier version is ``` import Graphics.Gloss purple :: Color purple = makeColor 0.5 0.0 0.5 1.0 main :: IO () main = animate (InWindow "" (100,100) (0,0)) white $ \t -> color purple . rotate (t * 6) . translate 38 0 $ circle 1 ``` [Answer] ## HTML (CSS?), 167 bytes Inspired by [insertusernamehere's answer](https://codegolf.stackexchange.com/a/62101/26575) ``` <style>body{position:fixed;left:50%;top:12%;width:1px;height:75vmin;border-top:1px solid #800080;animation:r 60s infinite linear}@keyframes r{to{transform:rotate(1turn ``` Ungolfed: ``` body { position: fixed; left: 50%; top: 12%; width: 1px; height: 75vmin; border-top: 1px solid #800080; animation: r 60s infinite linear; } @keyframes r { to { transform: rotate(1turn); } } ``` [Answer] # QBasic, 106 ``` SCREEN 7 COLOR 5,15 DO t=TIMER CLS PSET(99+99*COS(i),99+99*SIN(i)) i=i+ATN(1)/75 1IF TIMER<t+.1THEN 1 LOOP ``` Tested on [QB64](http://qb64.net), which says it has a Linux version (though I've only tried it on Windows). * `SCREEN 7` sets the graphics mode. * `COLOR 5,15` sets dark magenta as foreground color and bright white as background color. * `DO ... LOOP` is an infinite loop. Usually you would see it as `DO WHILE ... LOOP` (or you can put `LOOP WHILE` instead, or use `UNTIL` for a negated condition), but you can also leave the condition out, in which case it loops forever. * `TIMER` is the number of seconds since midnight, as a floating-point value. * `CLS` = CLear Screen. * `PSET` SETs a Point to a color, foreground color by default. * `i` starts at zero and counts up by pi/300 each time through the loop, thus completing a full circle after 600 repetitions. We calculate pi as 4\*arctan(1). * The last line waits until 0.1 seconds have elapsed. The idiom that I learned from my QBasic books was `t# = TIMER: WHILE TIMER < t# + 0.1: WEND`. But we don't need double-precision numbers (marked with `#`) for a 0.1-second difference, and it turns out that the `IF cond THEN [GOTO] line` syntax is 1 character shorter than a `WHILE ... WEND` loop. The loop repeats 600 times in 60 seconds, thus completing a full circle. ### Caveats * Color 5, dark magenta, is `#8B008B` instead of the requested `#800080` (cleared with the OP). * Screen mode 7 is 320x200, and so the circle has diameter 198, which isn't >= 0.75 of the width but is >= 0.75 of the height (also cleared with the OP). * If you run this on DOS QBasic, it's fullscreen, so the "pixel" isn't actually a single pixel on the monitor (unless you happen to have a 320x200 monitor). But it should be close enough. QB64 runs in a window that uses the exact dimensions, and thus the pixel is a literal pixel. * In QB64 at least, this takes more like 65 seconds to make a complete revolution. I don't really know why; it must be either rounding errors or overhead on the loop, though I've tried mitigating both without success. In theory, the code should work correctly as-is. In practice, one can tweak the amount by which `i` is incremented until a revolution is close enough to 60 seconds. (Try a denominator of 69 or 68.) * No pretty picture here. :( LICEcap's quality wasn't good enough to capture a single pixel accurately. [Answer] # mIRC script, 184 bytes ``` alias g { window -p @m -1 -1 100 128 f } alias f { inc %s 1 set %o $calc(%s *38/360) clear @m drawdot -r @m $rgb(128,0,128) 1 $calc($cos(%o)*38+50) $calc($sin(%o)*38+52) .timer 1 1 f } ``` This is optimised for mIRC in Wine. Start mIRC, press `Alt + R` then paste this, close the editor and run it with `/g` [![Preview](https://i.stack.imgur.com/7FkrN.gif)](https://i.stack.imgur.com/7FkrN.gif) The timing on the gif might be off. [Answer] ## R, 170 bytes ``` library(animation);for(i in 1:60){par(mar=rep(0,4));plot.new();t=2*pi*(1-i)/60;points(3*cos(t)/8+.5,3*sin(t)/8+.5,pch=19,col="#800080");ani.record()};repeat{ani.replay()} ``` It relies on package `animation`. And here 's a gif to show it works: [![In a window](https://i.stack.imgur.com/m2rjU.gif)](https://i.stack.imgur.com/m2rjU.gif) ### Invalid Solution saving to a gif (139 bytes): ``` animation::saveGIF({for(i in 1:60){par(mar=rep(0,4));plot.new();t=2*pi*(1-i)/60;points(3*cos(t)/8+.5,3*sin(t)/8+.5,pch=19,col="#800080")}}) ``` This one requires ImageMagick to be installed. The result is saved to a gif. [![![Round and round it goes](https://i.stack.imgur.com/yG7zr.gif)](https://i.stack.imgur.com/yG7zr.gif) [Answer] # Ruby with Shoes, 159 bytes ``` Shoes.app{animate{background stroke white fill purple r=0.75*c=self.width/2 t=Time.now m=Math rect c+r*m.sin(a=(t.sec+t.usec*1e-6)*m::PI/30),c-r*m.cos(a),2,2}} ``` The pixel is actually the tip of an analog clock's seconds hand. So this one is absolutely precise. ## Ruby with Shoes, 134 bytes ``` m=Math Shoes.app{animate{|f|r=0.75*c=self.width/2 background stroke white fill purple rect c+r*m.sin(a=f*m::PI/360),c-r*m.cos(a),2,2}} ``` This is a frames-per-seconds based alternative, inspired by the other answers. Although the documentation says the default fps is 10, practical tests shows it is actually 12. Both solutions take “The width of the circle should be 0.75 (rounding suitably) the width of the screen or window” literally: calculate based on window width, so the pixel occasionally may leave the bottom of a non-square window. Not sure how such case is expected to be handled. (Use minimum of width and height? Walk on oval path?) The window starts with default 600 x 500 size and is resizable. [Answer] # SVG, 177 bytes ``` <svg><g transform=translate(75,75)><circle id=x r=.5 cx=56 fill=#800080><animateTransform xlink:href=#x attributeName=transform type=rotate to=360 dur=60s repeatCount=indefinite ``` Invalid markup from hell to breakfast, but it runs (in Chrome at least). Like a HTML5 canvas, the default size for an SVG appears to be 300x150, so that's what this is assuming. *Edit: Whoops, I'd accidentally left in a duration of 6 instead of 60. Fixed that, but also found that `0.5` works as just `.5`, so no change in the byte count.* [Answer] ## X86 Machine-code - ~~150~~ ~~146~~ ~~149~~ ~~133~~ 127 bytes **Golfed version:** ``` 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F -------------------------------------------------------------------- 0000 B0 13 CD 10 BA C9 03 88 F1 BE 76 01 F3 6E B0 0F - °.Í.ºÉ.ˆñ¾v.ón°. 0010 49 68 00 A0 07 F3 AA 64 66 A1 6C 04 66 A3 80 01 - Ih. .óªdf¡l.f£€. 0020 64 66 A1 6C 04 66 2B 06 80 01 66 50 89 E5 D9 EB - df¡l.f+.€.fP‰åÙë 0030 D8 C0 DA 4E 00 DE 34 D9 FB BB 7D 01 DE 0F DE 47 - ØÀÚN.Þ4Ùû»}.Þ.ÞG 0040 FE DF 5E 02 DE 0F DE 47 FE DF 5E 00 5F 69 FF 40 - þß^.Þ.ÞGþß^._iÿ@ 0050 01 58 01 C7 BB 88 01 8B 0F 39 CF 74 C3 30 C0 AA - .X.Ç»ˆ.‹.9ÏtÃ0Àª 0060 4F 89 3F 89 CF B0 0F AA 31 C0 FE C4 CD 16 74 B0 - O‰?‰Ï°.ª1ÀþÄÍ.t° 0070 B8 03 00 CD 10 C3 20 00 20 44 04 64 00 4B 00 - ¸..Í.à . D.d.K. ``` **'Ungolfed', source version:** ``` ; golfCrcl.asm ; ; - 16 bit implementation of an animated pixel that circumscribes a circle. ; - 127 bytes .COM file ; ; - enhzflep - ; 31 Oct 2015 - initial ; - set closest colour to desired #800080 ; 2/3 Nov 2015 - removed unnecessary instuctions, used BX register to index mem by fpu ; - removed .data section alignment, better register use in curPixel/lastPixel compares and calcs, reusing value of si after palette setting [section .text] [bits 16] [org 0x100] EntryPoint: ; mov fs, bx ; bx is 0 on entry. Set fs seg register to this ; set graphics mode 320x200 mov al, 0x13 int 0x10 ; set colour #0 to be as close to the desired one as possible ; the vga palette registers are 6 bits by default (some models allow switching to 8 bits) ; therefore, we cant represent all of the 16.7m colours that we can in 24bit modes ; we're limited to 'just' 64*64*64 = 262,144 (256k) colours. Unfortunately, #800080 is not ; a colour we can represent exactly in mode13 or any other mode with 6 bit regs. mov dx, 0x3c9 mov cl, dh mov si, desiredCol rep outsb ; cx now=0 and si now points to totalTicksNeeded ; clear the screen to white mov al, 0x0f ; index of a colour thats already FF,FF,FF ; xor cx, cx ; cx = 0 - its zeroed by the rep outsb instruction above. dec cx ; cx = FFFF push word 0xA000 ; segment of video memory pop es ; pop it into es rep stosb ; es:[di] = 0F, inc di, dec cx. If cx != 0 then repeat. ; setup the timing stuff mov eax, [fs:0x046C] ; 32 bit value updated at 18.2Hz by bios mov [initialTicks], eax .drawLoop: mov eax, [fs:0x046C] ; 32 bit value updated at 18.2Hz by bios sub eax, [initialTicks] ; eax = curTime-startTime (in increments of 1/18.2 of a second --- 182 = 10 seconds) push eax ; number of elapsed clock ticks - ready to be loaded by fpu. Also stack space for calc result mov bp, sp ; get pointer to last element pushed onto the stack fldpi ; st0 = pi fadd st0 ; st0 = 2pi fimul long [bp] ; (currentTick/requiredTicks) * 2pi ; fidiv word [totalTicksNeeded] fidiv word [si] ; si still points to totalTicksNeeded after setting the palette earlier fsincos ; st0 = cos(old_st0), st1 = sin(old_st0) mov bx, radius fimul word [bx] ; fimul word [radius] - cos(angle)*radius fiadd word [bx-2] ; fiadd word [origin] - origin + cos(angle)*radius fistp word [bp+2] ; ---- X-coord ------- fimul word [bx] ; fimul word [radius] fiadd word [bx-2] ; fiadd word [origin] fistp word [bp+0] ; ---- Y-coord ------- ;--------------- pop di ; calculated Y-coord imul di, 320 ; multiply it by the screen width pop ax ; calculated X-coord add di, ax ; di = x + (pixels_per_row * y_coord) mov bx, lastIndex mov cx, [bx] ; get the mem index for the last pixel cmp di, cx ; check if we're indexing the same pixel as last time through the loop je .drawLoop ; if so, return to start of loop - no need to delete and redraw the pixel in the same spot. xor al, al ; col index 0 stosb ; draw our purple pixel dec di ; stosb advanced di to the next pixel, undo this (stosb followed by dec di is still shorter than mov es:[di], al) mov [bx], di ; save the pixel's mem address mov di, cx ; restore index of pixel drawn last time through the loop mov al, 0x0f ; pal index of white stosb ; erase the last pixel ; check for a keystroke xor ax, ax inc ah int 0x16 jz .drawLoop ; loop if no keys pressed .drawingDone: ; set text mode 80x25 mov ax, 0x3 int 0x10 ; program exit ret ; Dos pushes a 0000 onto the stack and copies CD 20 to offset 0 of our code-seg ; before it invokes our program. ret jumps back to that CD 20 (int 0x20) instruction ; Since this is a .COM file, all program, data and stack exist in the same segment. ; Using .text and .data sections only improves program readability - doing so only has minor effects on the binary produced. ; ; In this case, the assembler word aligns anything in the data section. This may have the effect of adding a padding byte, ; which we really dont need/want here. Data is machine-word aligned to improve the speed of access for the hardware. Machine-word ; is used to refer to the size of an int. In the case of 16 bit code, this will generally be 16 bits, 32 bit code has 32 bit words ; and so on. This code is 16 bit, so things should be aligned to word boundaries for maximum execution speed ; ;[section .data] desiredCol db 0x80/4, 0x00, 0x80/4 ; palette registers are only 6 bit. totalTicksNeeded dw 1092 origin dw 100 radius dw 75 ; ticks/second = 18.2 ; totalTime = 60 seconds ; totalTicks = 1092 (18.2 * 60) ; degreesPerTick = 360 / 1092 = 0.3296703 ; timerTicksAddr = 0040:006C (0000:046C) dword [section .bss] initialTicks resd 1 lastTickValue resd 1 lastIndex resw 1 ``` **Downloadable, base64 encoded version** ``` data:application/octet-stream;base64,sBPNELrJA4jxvnYB826wD0loAKAH86pkZqFsBGajgAFkZqFsBGYrBoABZlCJ5dnr2MDaTgDeNNn7u30B3g/eR/7fXgLeD95H/t9eAF9p/0ABWAHHu4gBiw85z3TDMMCqT4k/ic+wD6oxwP7EzRZ0sLgDAM0QwyAAIEQEZABLAA== ``` Copy and paste this address into your browser. Rename the resulting file `golfcrcl.com` and run in a DOS environment, i.e DosBox. [Answer] # D, 286 280 bytes (392 if written normally) ``` import simpledisplay,std.math;void main(){auto w=new SimpleWindow(100,100);auto c=50;auto r=c*2/3;int t;auto y=600/PI;w.eventLoop(50,{auto p=w.draw();p.clear;p.outlineColor=Color(128,0,128);p.drawPixel(Point(c+cast(int)(r*cos(t/y)),c+cast(int)(r*sin(t/y))));if(++t==1200)t=0;});} ``` Or the way I originally wrote it without golfing: ``` import simpledisplay, std.math; void main() { auto window = new SimpleWindow(100, 100); auto c = window.width/2; auto r = c*2/3; int t; float cycle = 20*60/(PI*2); window.eventLoop(50, { auto p = window.draw(); p.clear; p.outlineColor = Color(128, 0, 128); p.drawPixel(Point(c + cast(int) (r*cos(t/cycle)), c + cast(int) (r*sin(t/cycle)))); if(++t == 20*60) t = 0; }); } ``` Depends on simpledisplay.d and color.d located here: <https://github.com/adamdruppe/arsd> Just download those two individual files and put them in your same directory as the above code, then: `dmd yourfile.d simpledisplay.d color.d` to compile and then just run it. My little library was written to make quick animations like this fairly simple so this plays well to its strengths! Alas, I kinda like long identifier names and didn't provide a `Point` constructor that takes `float` so that adds 18 bytes casting and.... idk a couple dozen spelling out my method names. [Answer] # C#, ~~379~~ 365 bytes ``` using System.Windows.Forms;using static System.Math;class P:Form{static void Main(){var f=new P();var p=new PictureBox();f.SetBounds(0,0,1000,1000);f.Controls.Add(p);f.Show();for(var i=0d;;i+=PI/3000){p.SetBounds((int)(Cos(i)*375+500),(int)(Sin(i)*375+500),1,1);p.CreateGraphics().Clear(System.Drawing.Color.FromArgb(-8388480));System.Threading.Thread.Sleep(10);}}} ``` Depends on `System.Windows.Forms` and `System.Drawing` to run. Output is in a 1000x1000 window. [Answer] # Mathematica ~~208 185~~ 139 bytes Moves a purple pixel around an array used as an Image. **Method 1** 139 bytes ``` n=900;Dynamic@Refresh[t=DateValue@"Second";ReplacePixelValue[Image@Array[1&,{n,n}], 400{Cos[z=Pi/30t],Sin@z}+450->Purple],UpdateInterval->1] ``` --- **Method 2** 154 bytes Plots a pixel along a circular path in 60 seconds. ``` Dynamic@Refresh[t=DateValue@"Second";Graphics[{[[email protected]](/cdn-cgi/l/email-protection),Purple, Point[{Cos[z=Pi/30t],Sin@z}]},PlotRange->1,ImageSize->Full],UpdateInterval->1] ``` --- **Method 3** 193 bytes This draws a clock, with ticks and labels in white, for which the second hand is a pixel. ``` Dynamic@Refresh[ClockGauge[AbsoluteTime[],TicksStyle->White, GaugeMarkers->{None,None,Graphics[{White,Disk[],Purple, AbsolutePointSize[.01],Point@{3,0}}]},PlotTheme->"Minimal"],UpdateInterval->1] ``` [Answer] # Obj-C++ / Cocoa, ~~777~~ ~~678~~ ~~668~~ ~~657~~ ~~643~~ 628 bytes ``` #include <Cocoa/Cocoa.h> float r;@implementation V:NSView-(void)drawRect:(NSRect)d{CGContext*c=(CGContext*)NSGraphicsContext.currentContext.graphicsPort;CGContextSetRGBFillColor(c,.5,0,.5,1);CGContextFillRect(c,(CGRect){cos(r)*38+50,sin(r-=pi/300)*38+50,1,1});[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(x)userInfo:0 repeats:0];}-(void)x{self.needsDisplay=1;}@end int main(){NSRect b={0,0,100,100};NSWindow*w=[[NSWindow alloc]initWithContentRect:b styleMask:1 backing:2 defer:0];[w orderFront:0];w.backgroundColor=[NSColor whiteColor];w.contentView=[[V alloc]initWithFrame:b];[NSApp run];return 0;} ``` So this is probably the worst way to do anything, but I figured I'd try. Can be compiled on a Mac (mine anyway) with `g++ -framework Cocoa file.mm` and run from the terminal (`ctrl-C` to quit, since it's not an app). [![screenshot](https://i.stack.imgur.com/Qcv3D.gif)](https://i.stack.imgur.com/Qcv3D.gif) *Edit: Saved 99 bytes: Fixed `main()` to run on OS X 10.10 (1st version only ran on 10.8), skipped translate/rotate in favor of plain trig calculations, stopped bothering with window placement, and other small stuff.* *Edit: Saved another 10 bytes: Changed to just `orderFront` to display the window. Doesn't actually make it the front window, though, but neither did `orderFrontAndMakeKey`, so...* *Edit: Saved another 11 bytes: Skipped `NSMakeRect` and found a digit that just had to go.* *Edit: Saved another 14 bytes: Didn't need to assign the `NSTimer` instance to anything, and can apparently skip initializing `r` to zero.* *Edit: Saved another 15 bytes: I can't stop. Send help.* [Answer] # Javascript / Processingjs, ~~175~~ ~~173~~ ~~156~~ ~~153~~ 152 bytes ``` var s=256,e,h,m;void setup(){size(s,s);h=s/2;}void draw(){background(-1);m=-millis()*(PI/36000);stroke(h,0,h);e=s/2*0.75;point(h+sin(m)*e,h+cos(m)*e);} ``` To run : either visit <http://www.openprocessing.org/sketch/226733> to see it in action using processing.js, or download processing 2.0 from [processing.org](http://www.processing.org), paste the code into the processing IDE, select Javascript mode and watch it go. [Answer] ## [Elm](http://elm-lang.org/), 274 bytes ``` import Color exposing (..) import Graphics.Collage exposing (..) import Time exposing (..) main=Signal.map((\t->collage 200 200 [move(75*cos(-2*pi*t/60),75*sin(-2*pi*t/60))(filled(rgb 128 0 128)(circle 2)),outlined(solid black)(square 200)])<<inSeconds)(every(0.01*second)) ``` Try or edit it in your browser: * [Small version](http://share-elm.com/sprout/563307d8e4b05f0d6cc48c1c) * [Un-golfed version](http://share-elm.com/sprout/563307fde4b05f0d6cc48c1f) Note that if we get rid of the imports and drawing the outline around the canvas, we're down to 149 bytes, but that's probably cheating! [Answer] # C#, 301 bytes ``` using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){Application.Run(new P());}P(){Paint+=(o,e)=>{var g=e.Graphics;g.Clear(Color.White);g.TranslateTransform(150,150);g.RotateTransform(System.DateTime.Now.Second*6);g.FillRectangle(Brushes.Purple,105,0,1,1);Invalidate();};}} ``` Depends on default size metrics; size and position may be a bit off depending on a number of factors. May or may not flicker horribly; to solve that, add the following: ``` SetStyle(ControlStyles.OptimizedDoubleBuffer|ControlStyles.AllPaintingInWmPaint,true); ``` [Answer] # Lua + Löve, 189 characters ``` t=0 m=math l=love g=l.graphics function l.update(d)t=t+d end function l.draw()a=t*m.pi/30 g.setBackgroundColor(255,255,255)g.setColor(127,0,127)g.point(400+225*m.cos(a),300+225*m.sin(a))end ``` `love.update()` receives as parameter the time elapsed since previous frame. Draws in the default 800 x 600 window at fixed coordinates, as the window is not resizable anyway. [Answer] # Python 2 + Pygame, ~~221~~ ~~198~~ 193 ``` exec'from %s import*;'*3%('math','pygame','time') _,p,D=[255],128,display S=D.set_mode(_*2) while 1:S.fill(_*3);S.set_at(map(lambda f:int(p+f(pi*(time()%60)/30)*96),(cos,sin)),(p,0,p));D.flip() ``` [Answer] # C (using SDL1.2), ~~237~~ 233 ``` #include <SDL.h> #define P(f)(int)(128+96.0*f(3.14*((int)(.001*SDL_GetTicks())%60)/30)) main(){SDL_Surface*s=SDL_SetVideoMode(255,255,32,0);while(1){int*p=s->pixels;memset(p,255,260100);p[P(cos)+s->w*P(sin)]=0x800080FF;SDL_Flip(s);}} ``` Compiles & run using `gcc -I/usr/include/SDL snippet.c -lSDL -lm && ./a.out` [Answer] # ActionScript 2.0, 151 bytes Unfortunately, Adobe Flash isn't freeware, and Google informs that it doesn't work on Linux without a VM or Wine (and even with Wine, it only *mostly* works). Still, I wanted to see how well it would do on this task. Pretty well, it turns out. ``` createEmptyMovieClip("p",0) p._x=p._y=r=200 p.beginFill(0x800080) p.moveTo(r,0) p.lineTo(r-1,0) p.lineTo(r,1) onEnterFrame=function(){p._rotation+=.25} ``` The basic idea: create a new movie clip object, position it at (200, 200), and then draw a dot2 in it 200 pixels farther right. Now the movie clip is 200 pixels wide and 1 pixel high. The pivot point is the original coordinates where we started, so when we modify the `_rotation` property, the dot moves in a circle around the point (200, 200). Conveniently, `_rotation` is in degrees; 0.25 degrees/frame \* 24 frames/second \* 60 seconds/minute = 360 degrees/minute. To run from scratch if you have Flash, create a new Flash document1, open the Actions panel, and paste the above code. No further customization is required, assuming the default white background, 550x400 canvas, and 24 fps. Hit Ctrl-Enter and watch it go. If you don't have Flash itself, you can still view the results with the free Flash Player, which should come with most modern browsers. Download the SWF file [here](https://www.dropbox.com/s/msqiu4ac43shhi1/Flash%20circle%20pixel.swf?dl=1). If you can't play it, try downloading [this HTML page](https://www.dropbox.com/s/fxvkquevsqq0k43/Flash%20circle%20pixel.html?dl=1) as well and opening it, with the SWF file in the same directory. 1 Tested on Adobe Flash CS4 Professional, choosing "Flash File (ActionScript 2.0)" when asked what type of new file to create. 2 Actually a small triangle, as you'll see if you zoom in on it enough. It was the golfiest way I could find to draw a dot. [Answer] # JavaScript w/jQuery, 205 bytes ``` y=75;with($('<canvas/>').appendTo(document.body)[0].getContext('2d')){fillStyle='#800080';translate(y,y);(f=function(){clearRect(-y,-y,y*2,y*2);fillRect(0,56,1,1);rotate(Math.PI/300);setTimeout(f,100)})()} ``` [jsfiddle](http://jsfiddle.net/fwa2wbe9/), snippet below This is maybe not quite by the book. The default size of a canvas (in Chrome at least) is 300x150, so I've centered the circle on 75x75. I could center it on 150x75, and make its radius 113px (~75% of width), but it'd be outside the canvas some of the time, so I chose ~75% of height instead. But it's not particularly short anyway, so meh' ``` y=75;with($('<canvas/>').appendTo(document.body)[0].getContext('2d')){fillStyle='#800080';translate(y,y);(f=function(){clearRect(-y,-y,y*2,y*2);fillRect(0,56,1,1);rotate(Math.PI/300);setTimeout(f,100)})()} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` [Answer] ## [Blitz 2D/3D](http://www.blitzbasic.com/Products/blitz3d.php), 126 bytes ``` Graphics 180,180 ClsColor 255,255,255 Color 128,0,128 While 1 Cls ang#=ang+3 Plot 90+67*Cos(ang),90+67*Sin(ang) Delay 500 Wend ``` Unfortunately, this language is only supported on Windows (though it *may* run in Wine). [Answer] # Javascript ES6, 202 bytes ``` a=0;with((D=document).body.appendChild(D.createElement`canvas`).getContext`2d`)with(Math)setInterval((f=t=>t(a+=PI/6e3)*60+75)=>fillRect(f(cos,clearRect(0,0,150,150),fillStyle=`#800080`),f(sin),1,1),10) ``` Tested in Firefox 41. Like the other (almost) pure Javascript answer, the circle is centered at 75x75 since the canvas elements default size is 300x150 as defined by the HTML specs. [Answer] # Matlab, ~~141~~ 136 I just submit this for you, Lembik, to have a complete list. ``` v=-100:100; [y,x,m]=ndgrid(v,v,0); n=75; while 1; pause(1); c=m; c(x+i*y==round(n))=1; imshow(c); colormap([1,1,1;.5,0,.5]); n=n*exp(pi*i/30); end ``` Old version: ``` v=-100:100; [x,y,m]=ndgrid(v,v,0); while 1; c=m; c(x+i*y==round(75*(-1)^(s/30)))=1; imshow(c); colormap([1,1,1;.5,0,.5]); s=mod(s-1,60); pause(1); end ``` ]
[Question] [ [CJam](http://sourceforge.net/projects/cjam/) is a GolfScript-inspired stack-based golfing language, created by PPCG user [aditsu](https://codegolf.stackexchange.com/users/7416/aditsu). So, in the vein of other language-specific tips questions: What general tips do you have for golfing in CJam? Please post *one tip* per answer. [Answer] # Correct modulo for negative numbers It's often annoying that the result of the modulo operation gives the same sign as the first operand. E.g. `-5 3%` gives `-2` instead of `1`. More often than not you want the latter. The naive fix is to apply modulo, add the divisor once and apply modulo again: ``` 3%3+3% ``` But that's long and ugly. Instead, we can use the fact that array indexing is always modular and *does* work correctly with negative indices. So we just turn the divisor into a range and access that: ``` 3,= ``` Applied to `-5`, this gives `1` as expected. And it's only one byte longer than the built-in `%`! If the modulus is a power of 2, you can save another byte using bitwise arihmetic (which is also a lot faster). Compare: ``` 32,= 31& ``` For the special case of `65536 == 2^16` another byte can be saved by making use of the wrapping behaviour of the character type: ``` ci ``` [Answer] # Pushing concatenated character ranges * The string containing all digits `"0123456789"` can be written as ``` A,s ``` * The uppercase ASCII letters (`A-Z`) can be pushed as ``` '[,65> ``` which generates the string of all characters up to **Z**, then discards the first 65 (up to **@**). * All ASCII letters (`A-Za-z`) can be pushed as ``` '[,65>_el+ ``` which works as above, then creates a copy, converts to lowercase and appends. But there's a shorter way to do it! Then often overlooked `^` operator (symmetric differences for lists) allows to create the same ranges while saving three bytes: ``` '[,_el^ ``` `'[,` creates the range of all ASCII characters up to **Z**, `_el` creates a lowercase copy and `^` keeps only characters of both strings that appear in one but not both. Since all letters in the first string are uppercase, all in the second are lowercase and all non-letter characters are in both strings, the result in the string of letters. * The RFC 1642 Base64 alphabet (`A-Za-z0-9+/`) can be pushed using the above technique and appending the non-letters: ``` '[,_el^A,s+"+/"+ ``` An equally short way of pushing this string makes use solely of symmetric differences: ``` "+,/0:[a{A0":,:^ ``` How can we find the string at the beginning? All used character ranges (`A-Z`, `a-z`, `0-9`, `+`, `/`) can be pushed as the symmetric difference of to range that start at the null byte, namely `'A,'[,^`, `'a,'{,^`, `'0,':,^`, `'+,',,^` and `'/,'0,^`. Therefore, executing `:,:^` on `"A[a{):+,/0"` will push the desired characters, but not in the right order. How do we find the right order? Brute force to the rescue! The program ``` '[,_el^A,s+"+/"+:T;"0:A[a{+,/0"e!{:,:^T=}= ``` iterates over all possible permutations of the string, applies `:,:^` and compares the result to the desired output ([permalink](http://cjam.aditsu.net/#code='%5B%2C_el%5EA%2Cs%2B%22%2B%2F%22%2B%3AT%3B%220%3AA%5Ba%7B%2B%2C%2F0%22e!%7B%3A%2C%3A%5ET%3D%7D%3D)). * The radix-64 alphabet used, e.g, by crypt (`.-9A-Za-z`) can be generated using the above method: ``` ".:A[a{":,:^ ``` This is the shortest method I know. Since all characters in the desired output are in ASCII order, iterating over permutations isn't needed. * Not all concatenated character ranges can be pushed in the desired order using `:,:^`. For example, the range `0-9A-Za-z;-?` cannot be pushed by executing `:,:^` on any permutation of `"0:A[a{;@"`. However, we can find a rotated variation of the desired string that can, by using the code ``` A,'[,_el^'@,59>]s2*:T;"0:A[a{;@"e!{:,:^T\#:I)}=Ip ``` which will print ([permalink](http://cjam.aditsu.net/#code=A%2C'%5B%2C_el%5E'%40%2C59%3E%5Ds2*%3AT%3B%220%3AA%5Ba%7B%3B%40%22e!%7B%3A%2C%3A%5ET%5C%23%3AI)%7D%3DIp)) the following: ``` 10 0:@[a{A; ``` This means that ``` "0:@[a{A;":,:^Am> ``` has the same effect as ``` A,'[,_el^'@,59>]s ``` which can only be used with an empty stack without prepending a `[`. [Answer] # Avoid {…}{…}? Assume you have an integer on the stack. If it is odd, you want to multiply it by 3 and add 1; otherwise you want to divide it by 2. A "normal" if/else statement would look like this: ``` _2%{3*)}{2/}? ``` However, using blocks is usually not the way to go, since `{}{}` already adds four bytes. `?` can also be used to select one of two items on the stack: ``` _2%1$3*)@2/? ``` This is one byte shorter. --- Block-? with an empty if statement is always a no-go. For example, ``` {}{2/}? ``` is two bytes longer than ``` {2/}| ``` If instead you have ``` {2/}{}? ``` and the thing you are checking on is non-negative integer, you can do ``` g)/ ``` --- The new `{}&` and `{}|` are handy, but sometimes problematic if you cannot clutter the stack. Still, in the case of ``` _{…}{;}? ``` you can use a temporary variable instead: ``` :T{T…}& ``` [Answer] # Switch statements CJam doesn't have switch statements. Nested if statements work just as well, but `{{}{}?}{}?` is already 12 bytes long... If we can transform the condition into a small, non-negative integer, we can transform all case statements in a delimited string and evaluate the corresponding result. For example, if we want to execute `code0` if the integer of the stack is **0**, `code1` if it is **1**, and `code2` if it is **2**, we can either use ``` _{({code2}{code1}?}{;code0}? ``` or ``` [{code0}{code1}{code2}]=~ ``` or ``` "code0 code1 code2"S/=~ ``` `S/` splits the string into `["code0" "code1" "code2"]`, `=` extracts the corresponding chunk, and `~` evaluates the code. Click [here](https://codegolf.stackexchange.com/a/58513) to see switch statements in action. Finally, as suggested by suggested by @jimmy23013 and @RetoKoradi, we can shorten the switch even more in some cases. Say `code0`, `code1` and `code2` have lengths **L0**, **L1** and **L2**, respectively. If **L0 = L1 ≥ L2** ``` "code0code1code2"L/=~ ``` can be used instead, where `L` is **L0**. Instead of splitting at a delimiter, `/` splits the string into chunks of equal length here. If **L0 ≥ L1 ≥ L2 ≥ L0 - 1**, ``` "cccooodddeee012">3%~ ``` can be used instead. `>` removes 0, 1 or 2 elements from the beginning of the string, and `3%` extracts every third element (starting with the first). [Answer] # Golfing common array and string values There are certain short arrays or strings that crop up every now and then, e.g. to initialise grids. Naively, these can cost 4 or more bytes, so it's worth looking for operations on built-in values which will give the same result. Especially base conversion is often useful. * `[0 1]` can be written as `2,`. * `[1 0]` can be written as `YYb` (i.e. 2 in binary). * `[1 1]` can be written as `ZYb` (i.e. 3 in binary). * The matrix `[[0 1] [1 0]]` can be written as `2e!`. * `[LL]` can be written as `SS/` (splitting a single space by spaces). * `"\"\""` can be written as `L``. * `"{}"` can be written as `{}s`. The latter can be extended to cases where you want all bracket types to save another byte: * `"[{<()>}]"` can be written as `{<()>}a``. * `"()<>[]{}"` can be written as `{<()>}a`$`. Especially the base conversion trick can be useful to keep in mind for some obscurer cases that pop up every now and then. E.g. `[3 2]` would be `E4b` (14 in base 4). In even rarer cases you might even find the factorisation operator `mf` useful. E.g. `[2 7]` is `Emf`. Please feel free to extend this list if you come across any other examples. [Answer] ## Clearing the stack If you just want to clear the entire stack, wrap it in an array and pop it: ``` ]; ``` What's a bit more tricky is, if you've done a lot of computations, but only want to keep the top stack element and discard everything beneath. The naive approach would be to store the top element in a variable, clear the stack, push the variable. But there's a much shorter alternative: wrap the stack in an array and extract the last element: ``` ]W= ``` (Thanks to Optimizer who showed this to me the other day.) Of course, if there's only two elements on the stack, `\;` is shorter. [Answer] # `e` and powers of ten As in oh-so-many other languages, you can write `1e3` instead of `1000` in CJam. This works for non-integer bases and even for non-integer exponents as well. For example, `1.23e2` pushes **123.0** and `1e.5` pushes **3.1622776601683795** (square root of **10**). What's not immediately obvious is that `1e3` is actually *two* tokens: * `1` pushes the integer **1** on the stack. * `e3` multiplies it by **1000**. Why is that important? * You can call `e<numeric literal>` on something that's already on the stack. ``` 2 3 + e3 e# Pushes 5000. ``` * You can map `e<numeric literal>` over an array. ``` 5 , :e3 e# Pushes [0 1000 2000 3000 4000]. ``` [Answer] # Euclidean norms The straightforward way of calculating the Euclidean norm of a vector, i.e., the square root of the sum of the squares of its elements, is ``` 2f#:+mq ``` However, there's a much shorter way. `mh`, the hypotenuse operator, pops two integers **a** and **b** from the stack and pushes **sqrt(a2 + b2)**. If we have a vector **x := [x1 … xn], n > 1** on the stack, `:mh` (reduce by hypotenuse) will achieve the following: * First **x1** and **x2** are pushed and `mh` is executed, leaving **sqrt(x12 + x22)**, on the stack. * Then, **x3** is pushed and `mh` is executed again, leaving **sqrt(sqrt(x12 + x22)2 + x32) = sqrt(x12 + x22 + x32)** on the stack. * After **xn** has been processed, we're left with **sqrt(x12 + … xn2)**, the Euclidean norm of **x**. If **n = 1** and **x1 < 0**, the above code will produce an incorrect result. `:mhz` works unconditionally. (Thanks to @MartinBüttner for pointing that out.) I've used this trick for the first time in [this answer](https://codegolf.stackexchange.com/a/60902). [Answer] # Convert from base n with a list of numbers greater than n CJam converts a list to a number with this formula: A0\*nl + A1\*nl-1 + A2\*nl-2 + Al\*n0 (with nonnegative `n`). `n` is the base and `l` is the list length. This means Ai can be any integer, which doesn't have to be in the range of `[0,n)`. Some examples: * `0b` extracts the last item and cast it to integer. Works like `W=i` and saves a byte if it wasn't integer. But everything else in the list must also be able to cast into integer. * `1b` returns the sum. Works like `:i:+` and saves two bytes if they weren't integers. It also works with empty lists while `:+` doesn't. * `[i{_1&9 32?_@\m2/}16*;]W%:c` converts a character to a string of line endings and tabs, which can be converted back with `2bc`. The encoding function isn't easy to be golfed in a code-golf program, though. But you don't usually need that. * You can use the following code to convert a string to Unicode characters not in 16 bit, which can be converted back with `2A#b128b:c`. (Explanations will be added later. Or perhaps I'll write a new version later.) ``` 128b2A#b " Convert to base 1024. "; W%2/)W%\:+ " Convert to two base 1024 digit groups. "; [0X@ { _54+ @I+_Am>@\- _Am<@+ 0@-@1^ }fI ]);) @\+[~+]2A#b_2G#<!{2A#b}* \W%+:c ``` The similar method works with any set of `n` integers which have different values mod `n`, if you can find some way to get rid of the most significant digit. [Answer] # Using `$` as ternary if When you don't mind leaking memory, i.e., leaving unused elements on the stack that you'll later clear with `];`, the copy operator `$` can be a handy substitute for the ternary operator `?`. `?` works well if you manage to compute the condition before pushing the two items to choose from, but more often than not, the condition actually depends on those items, and having it on top of them results much more natural. If you have `A B C` on the stack, you can execute ``` !$ ``` instead of ``` \@? ``` to copy `B` if `C` is truthy and `A` otherwise. If `C` is an actual Boolean (`0` or `1`), you can execute ``` $ ``` instead of ``` @@? ``` to copy `A` if `C` is truthy and `B` otherwise. [Answer] # Map for Nested Lists Say you've got a nested list, like a matrix: ``` [[0 1 2][3 4 5][6 7 8]] ``` Or an array of strings: ``` ["foo""bar"] ``` And you want to map a block onto the nested level (i.e. apply it to each number or each character). The naive solution is a nested `%`: ``` {{...}%}% ``` However, you can actually push the inner block onto the stack and then use `f%`. `f` is "map with additional parameter", so it will map `%` onto the outer list, using the block as the second parameter: ``` {...}f% ``` Saves two bytes. Another neat trick to do something like `for (i=0; i<5; ++i) for (j=0; j<5; ++j) {...}` is ``` 5,_f{f{...}} ``` The outer `f` will map onto the first range, supplying the second range as an additional parameter. But now, if you use `f` again, only the top stack element is an array, so you `f` maps the inner block onto that, supplying the outer "iteration variable" as an additional parameter. This means the inner block is runs with `i` and `j` on the stack. This has the same number of characters as just mapping a block onto a Cartesian product (although the latter gets shorter if you need the pairs as arrays): ``` 5,_m*{~...}% ``` The difference is that this version yields a single array of results for all pairs, whereas the double-`f` yields a nested list, which can be useful if you want to store the results in a grid, with the iterator variables being the coordinates. Thanks to Dennis for showing me this trick. ## 0.6.4 Update `f` and `:` have now been immensely improved by taking any other operator including themselves. This means you can save even more bytes now. Mapping an operator onto a nested list got even shorter now: ``` {:x}% {x}f% ::x ``` This doesn't really help with mapping blocks onto nested lists though. As for the applying blocks or operators to the Cartesian product, this also got shorter now, for blocks as well as operators: ``` 5,_f{f{...}} 5,_ff{...} 5,_f{fx} 5,_ffx ``` What's nice is that you can now nest these. So you can apply an operator just as easily to the third level down a list: ``` :::x ``` Or a block with some trickery: ``` {...}ff% ``` [Answer] # Vectorized operators for ASCII art For many ASCII art challenges, it is useful to generate two different patterns to superpose them later. Vectorized operators can be very helpful to achieve different types of superpositions. One useful property of operator vectorization is that the operator is only executed once for each element of the shorter string/array, while the elements of the larger one that do not have counterparts remain untouched. * ### `.e<` The minimum operator `e<` work for pairs of strings, characters, arrays and integers; it pops two items from the stack and pushes the lower on e back. Since a space has a lower code point than all other printable ASCII characters, `.e<` can be used to "erase" parts of a generated pattern: ``` "\/\/\/\/\/" " " .e< e# This pushes " \/\/\/". ``` For a full example, see my answer to [Me Want Honeycomb](https://codegolf.stackexchange.com/a/50327). * ### `.e>` The maximum operator `e>` works as the minimum operator, with the opposite result. Again, because of the low code point of the space, `.e>` can be used to insert a pattern of printable characters in a block of spaces: ``` [[" " " " " " " "] [" " " " " " " "]][["+" "" "-" ""]["" "*" "" "/"]] ..e> e# This pushes [["+" " " "-" " "] [" " "*" " " "/"]]. ``` For a full example, see my answer to [Seven Slash Display](https://codegolf.stackexchange.com/a/51582). * ### `.e&` The logical AND operator `e&` pushes its left argument if it is falsy and its right argument otherwise. If neither pattern contains falsy elements, this can be used to inconditionally impose one pattern over another one: ``` "################" " * * * *" .e& e# This pushes " * * * *########". ``` For a full example, see my answer to [Print the American Flag!](https://codegolf.stackexchange.com/q/52615). * ### `.e|` The logical OR operator `e|` can be used as above, with reversed argument order: ``` " * * * *" "################" .e| e# This pushes " * * * *########". ``` [Answer] # Use `&` to check if an item is in a list For ``` 1 [1 2 3] #W> 1 [1 2 3] #) ``` You can use ``` 1 [1 2 3] &, 1 [1 2 3] & ``` instead, which returns 0/1 and truthy/falsey respectively. [Answer] # `z` and non-rectangular arrays The zip operator `z` transposes the rows and columns of a two-dimensional1 array **A**, whose elements can also be iterables. For non-rectangular arrays – unlike the built-in `zip` functions in, e.g., Python (truncates the rows to the same length) or Ruby (pads the rows with `nil`) – CJam simply converts the columns of the array into rows, ignoring their lengths and gaps. For example, zipping the array ``` [ [1] [2 4] [3 5 6] ] ``` is equivalent to zipping the array ``` [ [1 4 6] [2 5] [3] ] ``` or the array ``` [ [1] [2 4 6] [3 5] ] ``` as all three actions push ``` [ [1 2 3] [4 5] [6] ] ``` on the stack. While this means that `z` is not an involution (which would be useful on occasions), it has a few applications. For example: * We can align the columns of an array to the top (i.e., turn the first array into the second) by zipping twice: ``` zz ``` * Minor modifications of the above method can be used for similar problems. For instance, to align the columns of an array to the bottom (i.e., to turn the second array into the first), we can zip twice with reversed row order: ``` W%zzW% ``` * Given an array of strings, we can compute the length of the longest string like this: ``` :,:e> ``` However, by zipping and calculating the number of rows of the result, we can save three bytes: ``` z, ``` --- 1 If any of the "rows" of **A** is not iterable, `z` treats them as singletons, so zipping works for arbitrary arrays. [Answer] # Exceptions All exceptions are fatal in CJam. Since [output to STDERR is ignored by default](http://meta.codegolf.stackexchange.com/a/4781), we can use this to our advantage. All operator in CJam work by popping zero or more elements from the stack, perform some task and push zero or more elements on the stack. Exceptions occur while the task is performed, so this still pops the elements, but nothing is pushed in return. Here are a few use cases: * **Clearing a small stack** To clear a stack that contains two elements, `@` can be used. `@` tries to pop three stack elements, but fails after popping the second. Any other operator that pops three elements would serve the same purpose. See it in action [here](https://codegolf.stackexchange.com/a/58424). * **Removing two or three elements from the stack** Any operator that is not implemented for these particular elements can be used to pop two or three elements from the stack right before exiting. To pop two elements, `b` works if one of them is a character or none of them is an integer. To pop three elements, `t` works if none of the bottom-most two is an iterable, the bottom-most iterable is empty or none of them is an integer. * **Exiting from a loop** On occasions, we need to exit from a loop when an integer becomes zero or a string becomes too short. Rather than testing for these conditions, if the involved operations fail for zero, the empty string or singletons, we can simply let the program take its natural course. For an example involving arithmetic, see [here](https://codegolf.stackexchange.com/a/51535). For an example involving strings, see [here](https://codegolf.stackexchange.com/a/58329). * **Conditional execution** If the source code should not be executed for certain types of input, we sometimes can use an operator that fails that kind of input. For example, `i` will fail for strings that do not evaluate to an integer and `ew` will fail for strings of length 0 or 1. See it in action [here](https://codegolf.stackexchange.com/a/53082). [Answer] ## Max/Min from an array Here is one for starters! When you need to find the maximum or minimum number from an array, the easiest and smallest way is to sort the array and then take out the first or last element. So if the array is in variable `A` ``` A$W= ``` is the maximum and ``` A$0= ``` is the minimum. Get both at the same time is also possible ``` A$)\0= ``` This might seem obvious after reading, but anyone's first attempt tends to go towards the usage of `e<` or `e>` via iterating through the array, which goes like ``` A{e<}* ``` which is 2 bytes longer, and even longer if you want both max and min. [Answer] # Use a timestamp for large numbers If you need a very large, but arbitrary number, you'll usually either use scientific notation like `9e9` or raise one of the large built-in variables to a similar power, like `KK#`. However, if you don't care what the actual number is, and it doesn't need to be consistently the same (e.g. as the upper bound for a random number), you can do it in two bytes using ``` es ``` instead. This gives the current timestamp in milliseconds, and is on the order of 1012 [Answer] # Checking that two strings/arrays are not equal Sometimes you want a truthy value when two strings or arrays are not equal, and a falsy value if they are. The obvious solution is two bytes: ``` =! ``` Check for equality, and invert the result. However, under some conditions you can use ``` # ``` When `#` is applied to two arrays it actually searches for the second array as a subarray of the first (and gives you the index where the subarray starts). So if the two arrays are the same, the subarray will be found right at the start and give `0`, which is falsy. But if the second array cannot be found, it will give `-1` which is truthy. The reason we need some additional condition on the two arrays is that this also yields a falsy value if the second array is a non-trivial prefix of the first, e.g.: ``` "abc""ab"# ``` gives `0` although the strings are not the same. The simplest condition which rules out this case is if you know that both arrays will be the same length - in that case if one is a prefix of the other, you know that they are equal. But in specific circumstances there may be weaker conditions that are also sufficient. For instance, if you know that the strings are sorted, a prefix would always be the first string, not the second. [Answer] # `c` and 16-bit integers To add (or subtract) unsigned 16-bit integers with proper wrapping, you can use `+65536%` or `+2G#%`. However, ``` +ci ``` is a lot shorter. Characters wrap arround at **65536**, so casting to Character (`c`) then to Long (`i`) has a similar effect to `65536%`, with the added benefit that the result will not be negative. The same trick can be used to push **65535**: ``` Wci ``` [Answer] # Power sets Say you have an array and you want an array with all possible subsets of that array. The trick is to start with an empty array, and then, for each element, duplicate the subsets you already have, and add the new element to them (keeping previous result where the element *wasn't added*). Note that you need to initialise the stack with the base case, i.e. an array containing only an empty array: That could look like this: ``` [1 2 3 4 5]La\{1$f++}/ ``` The nice thing about this is, you can immediately run some computation on the subset, potentially without added characters. Say you want the products of all subsets. In that case, the base case is an array containing `1`, and at each step, you take the previous list of possible products, duplicate it, and multiply everything in the duplicate by the new element: ``` [1 2 3 4 5]1a\{1$f*+}/ ``` [Answer] # Check if items in a list are all the same I think this also worth mentioning. Use: ``` )- ``` Returns truthy if not all the same, or empty list if all the same. Errors if the list is empty. In case the item extracted might be an array (or string) itself: ``` )a- ``` Use `!` or `!!` to get boolean values. In case the item extracted might be an array, and there are at most two kind of different items, and you want it to be 1 if not all the same, this is shorter: ``` _|,( ``` [Answer] # `0=` for strings To retrieve the first element of an array, you have to use `0=` (or `(`, if you don't mind leaving the rest of the array on the stack). However, if that array is a string, casting to character is sufficient. ### Example ``` "xyz"c e# Pushes 'x. ``` [Answer] # Rotating an array (or the stack) one unit to the left CJam has the *rotate left* operator `m<`, which is normally what you should use to rotate an array an arbitrary number of units to the left. In *some* cases, you can also use `(+` to shift and append: ``` [1 2 3] (+ e# Pushes [2 3 1]. [[1] [2] [3]] (+ e# Pushes [[2] [3] 1]. ``` The second example did not work because the arrays first element is also an iterable, so `+` concatenated instead of appending. Also, if you want to dump the rotated array on the stack, you can use `:\` (reduce by swapping) unconditionally: ``` [1 2 3] :\ e# Pushes 2 3 1. [[1] [2] [3]] :\ e# Pushes [2] [3] [1]. ``` As long as you don't have an open `[`, this trick can also be used to rotate the entire stack, i.e., to bring the bottom-most stack item to the top: ``` ]:\ ``` [Answer] # Printing a list and clearing the stack Lets say your stack has a list of strings/numbers/etc. on top and some other extra items below it. i.e. ``` 123 "waste" ["a" "b" "rty" "print" "me" "please"] ``` Now you are interested in printing the last list only, so you do ``` S*]W= ``` which outputs ``` a b rty print me please ``` Which seems really smart as we use the clearing the stack trick and only print the list joined with spaces (which might not be the desired way of printing a list at times). This can be golfed further! ``` p]; ``` **That's 2 bytes shorter**! and if you have only 1 item on stack other than the list, its even shorter! ``` p; ``` The beauty of `p` is that it removes the top most item from stack, stringifies it (also adds a newline at the end) and prints to STDOUT instantly, without waiting for completion of the code. So the above code will output ``` ["a" "b" "rty" "print" "me" "please"] ``` which is the exact representation of a list when it was in stack! [Answer] # Cartesian products or all possible combinations of two or more sets CJam has an inbuilt Cartesian product calculator `m*` which takes the top two arraylists/strings on stack and create all possible pairs from it. For example ``` [1 2 3 4]"abc"m* ``` leaves ``` [[1 'a] [1 'b] [1 'c] [2 'a] [2 'b] [2 'c] [3 'a] [3 'b] [3 'c] [4 'a] [4 'b] [4 'c]] ``` as the stack But what if you want all possible combinations from more than 2 lists/strings. You use `m*` that many times ? For example ``` [1 2 3 4][5 6]"abc"m*m* ``` will leave the following on stack ``` [[1 [5 'a]] [1 [5 'b]] [1 [5 'c]] [1 [6 'a]] [1 [6 'b]] [1 [6 'c]] [2 [5 'a]] [2 [5 'b]] [2 [5 'c]] [2 [6 'a]] [2 [6 'b]] [2 [6 'c]] [3 [5 'a]] [3 [5 'b]] [3 [5 'c]] [3 [6 'a]] [3 [6 'b]] [3 [6 'c]] [4 [5 'a]] [4 [5 'b]] [4 [5 'c]] [4 [6 'a]] [4 [6 'b]] [4 [6 'c]]] ``` Notice that the products are still pairs, where one of the item is a pair itself. This is not expected and we want flattened combinations. There is an easy way to do that. Just wrap every list that you want for your cartesian product in an array, pairwise create Cartesian products and flatten it each time: ``` [1 2 3 4][5 6]"abc"]{m*{(+}%}* ``` This leaves ``` [['a 5 1] ['b 5 1] ['c 5 1] ['a 6 1] ['b 6 1] ['c 6 1] ['a 5 2] ['b 5 2] ['c 5 2] ['a 6 2] ['b 6 2] ['c 6 2] ['a 5 3] ['b 5 3] ['c 5 3] ['a 6 3] ['b 6 3] ['c 6 3] ['a 5 4] ['b 5 4] ['c 5 4] ['a 6 4] ['b 6 4] ['c 6 4]] ``` on stack. **Want the order maintained ?**, simply swap the before adding the popped item back to the array. i.e. ``` {m*{(\+}%}* ``` **Want only permutations ?** ``` {m*{(+$}%_&}* ``` **Want only unique elements in the combinations ?** ``` {m*{(+_&}%}* ``` That's all folks. *for now*. [Answer] # Operating on strings Sometimes if you are working with a complex data structure, while the items in it are simple, converting to strings may help. For example, if you want to get the first or last few items in a 2D array of bits, and don't care about the returned type, `sA<` saves a byte from `0=A<` or `:+A<`. Or if you want to modify some bits in the input, you can modify the string before evaluating it. Or if you got this structure and want to convert it to a simple list: ``` [[[[[[[[[1]2]3]4]5]6]7]8]9] ``` You can do it with many characters in other ways: ``` [a{~)\}h;]W% ``` But it can be much shorter with strings: ``` s:~ ``` It's shorter even if it may have numbers with more than one digit: ``` [`La`-~] ``` Or: ``` `']-~] ``` If you don't need another array containing many of such arrays. [Answer] # Using `N` instead of `La` In many cases you need something initialized to an array containing an empty array as its only element, which is `La`, seemingly unnecessarily 1 byte longer. In many cases you also need to add a newline after each element before printing, which would be something like `No` or `N*`. But if both are true, sometimes you may find out that you can just initialize the array with `N`, which has the newline character as its only element. Make sure you only prepend things to the elements in the rest of your code, and the first thing to prepend is always a character or an array. Or only append, if a leading newline is acceptable and that makes it shorter. Sometimes `S` also works if you need to separate the output with spaces. In rarer cases, the initial element has to be a string. But you still can use `Na` which might be shorter than appending the newline afterwards. [Answer] # Splitting on one or more occurrences Say you have a string `"abbcdbbfghbdbb"` and you want to split it on `b` ``` "abbcdbbfghbdbb"'b/ ``` This leaves on stack: ``` ["a" "" "cd" "" "fgh" "d" "" ""] ``` Notice the empty strings ? Those are there because two `b` were together and nothing was in between them. At times, you want to avoid this. You can do this by ``` "abbcdbbfghbdbb"'b/La- ``` or filtering out empty strings ``` "abbcdbbfghbdbb"'b/{}, ``` but that is 3 extra bytes. A little less known operator for this particular use case is `%`. Apart from doing mod and map and splitting based on number (`"abcd"2%` = `"ac"`), `%` can also split on strings/arrays. So for the above use case: ``` "abbcdbbfghbdbb"'b% ``` will leave ``` ["a" "cd" "fgh" "d"] ``` on stack. Thanks for @user23013 for pointing this out in one of my answers today. [Answer] ## Use fold/reduce as infix foreach We have `:x` as a shorthand for `{x}%` and or `{x}*` (depending on whether `x` is unary or binary). Unfortunately, there is no equivalent infix operator to shorten `{x}/`. However, very often when we do `{x}/`, `x` is actually a binary operator which repeatedly modifies the item lying underneath on the stack. If that's the case, and said item is not an array, we can save a byte by abusing fold/reduce as foreach: ``` 5 [1 2 3 4]{-}/ e# Gives -5 5 [1 2 3 4]+:- ``` This works because fold always leaves the first element untouched. Unfortunately, it doesn't save a byte, when the modified element is an array, because adding it would unwrap it. However, [sometimes you're lucky enough](https://codegolf.stackexchange.com/a/66594/8478) that your array already contains that element at the front, in which case reduce should be kept in mind (instead of manually removing the element before using `{}/` on the remainder). [Answer] # print and println CJam has `print` operator: `o`. It works but stack is printing immediately after all the code has executed. You can stop it if you clear the stack at the end of program. Simply put this at the end: ``` ]; ``` To println you can use `oNo` or `p` (works as ``oNo`) ]
[Question] [ From the subreddit [r/SpeedOfLobsters](https://www.reddit.com/r/SpeedOfLobsters/): > > Edit the text of an image to create a new phrase > > > This meme format/style is pretty self-explanatory. Simply have a browse through the subreddit if you need more examples. However, when coming up with ideas, it can be quite difficult to decide exactly which letters to keep and which to blank out to create my intended joke. You are to take a sentence of space separated "words" (i.e. non-empty alphabetical strings) and a target "word" (still a non-empty alphabetical string) and "blank out" characters from the sentence in order to make the target word. For example: ``` "I do not control the speed at which lobsters die", "code" -> "*********co**************d***************e******" ``` Note that the order of the target word is maintained, so `**do*****c*********e****************************` is not an acceptable output. Earlier occurrences take priority, so `"testcase string", "tas"` should be `t****as********` not `t****a***s******` You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). You may use either uppercase or lowercase, so long as it is consistent across all inputs. You may use any character that will not appear in the input (i.e any non-alphabetic character, or characters of the opposite case to the input) to "blank out" characters. The target word is guaranteed to be fully contained in the sentence (so `"abcdef", "xyz"` will never be an input) and will always be shorter than the sentence. The sentence will contain a minimum of two words (and therefore one space), each of which will be a minimum of 1 character long. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. ## Test cases ``` sentence target output I do not control the speed at which lobsters die code *********co**************d***************e****** testcase string tas t****as******** uglhwagp qvyntzmf ulhwagpqvyntzmf u*lhwagp*qvyntzmf qrkacxx wwfja jsyjdffa vwfgxf qcfvf q***c*****f************v*f*** z wzsgovhh jopw igcx muxj xmmisxdn t lmb gcujxlb *****g************c***u*j*x**********l*b kxf jgmzejypb ya e ********e******* fe oxyk y ex *e**x**** o wr fmik owrfmik o*wr*fmik pgezt yozcyqq drxt gcvaj hx l ix xemimmox e **e************************************** kqclk b hkgtrh k k************* sia prcrdfckg otqwvdv wzdqxvqb h xclxmaj xjdwt lzfw crwqqhxl ******cr*********w*******q**q**h*x*l*************** teatsase tas t*a*s*** ``` Thanks to [Lyxal](https://codegolf.stackexchange.com/users/78850/lyxal) for helping me adapt the original idea of this into this version [Answer] # [convey](http://xn--wxa.land/convey/), 59 47 bytes ``` { ?;\,&:1< v^<^ ,<$1 "=>^}"@"} >">>#=" '*'>:<=0 ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoieyBcbj87XFwsJjoxPFxudl48XiAsPCQxXG5cIj0+Xn1cIkBcIn1cbj5cIj4+Iz1cIlxuJyonPjo8PTAiLCJ2IjoxLCJpIjoiJ3Rhcydcbid0ZXN0Y2FzZSBzdHJpbmcnIn0=) Run with `tas` and `tsase` (output is `t*as*`): [![run](https://i.stack.imgur.com/04uzU.gif)](https://i.stack.imgur.com/04uzU.gif) Split the input into two streams `?;\… ^<`, then always take one letter `:1`, compare it with the head `=`, and either `@` put the letter back into the queue `,` and output a `'*'$…}`, or output the letter `}` and take the next letter `$1`. After the queue is empty, to output the rest of the string, we push some dummy 1 values into the queue (by comparing the input with itself). [Answer] # JavaScript (ES6), 35 bytes Expects `(haystack)(needle)`, where `haystack` is a list of characters and `needle` is either a list of characters or a string. Returns a list of characters. The blank-out character is `0`. ``` s=>w=>s.map(c=>c==w[s|=0]?++s&&c:0) ``` [Try it online!](https://tio.run/##bY2xDsIgFAB3v@KFoYU0ks4m1NlvaDog0BaDvIb3Yhf/HRsnB@fL3T3sy5IrceNzRh/qbCqZYTcD6afdpDODM2Yf6W366dp11DTu0qvqMBOmoBMucpaj1lrcwCNkZDgYF0zAawDaQvBgGfY1uhUS3olDIfAxiElJ4Y6nUPqBMcu2Ver0J8yB2Fk6YlxiXr4eW/rV6gc "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s[] = sentence as an array of characters w => // w = word s.map(c => // for each character c in s[]: c == w[s |= 0] // we re-use s[] as a pointer into w; it's safe to // coerce it to a number with a bitwise OR because // s[] is guaranteed to contain only spaces and letters ? // if c is equal to w[s]: ++s && c // increment s and yield c : // else: 0 // yield the blank-out character "0" ) // end of map() ``` [Answer] # [Haskell](https://www.haskell.org/), ~~61~~ ~~59~~ 44 bytes Saved ~~1~~ 16 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)! ``` (a:b)%(c:d)|a==c=a:b%d (_:b)%c='*':b%c e%_=e ``` [Try it online!](https://tio.run/##PZBBboMwEEX3nOILFQUqeoFIdN8zUBQNtsEkBgMeMEW9O4WgZvn/m5HejCb3UMZsW0zXMolicZXJL2WZyPYcySC@HbXILu@XPYtARbdMbU3XT@yQIc/DL0iLzjKE7Xi0BqwVXK@UBDG8boSGsaVjNTrIRoUpQmGlCosUecjKsSC3b/DYdPUBmdzJptpoT3WPYf7peG2rg05n96qek64h9KMYZSUeNSwPfpYz/CqHZR5KaCzCLC3dsdylZ5i18k@N0Q@DXsy/CrHbVV4ORdBS0@1X9rsa4w0t9Yi/c0rL4uOTojLB@YjtDw "Haskell – Try It Online") [Answer] # x86-16 machine code, 11 bytes Binary: ``` 00000000: a674 054e 4fb0 2aaa e2f6 c3 .t.NO.*.... ``` Listing: ``` CHAR_LOOP: A6 CMPSB ; compare [DI] and [SI], advance both 74 05 JZ MATCH ; if same char, do nothing 4E DEC SI ; back up target word to previous char 4F DEC DI ; back up sentence to previous char B0 2A MOV AL, '*' ; load overstrike char AA STOSB ; overwrite char with *, advance DI MATCH: E2 F6 LOOP CHAR_LOOP ; loop until end of sentence C3 RET ; return to caller ``` Callable function, input sentence string at `[DI]`, length in `CX`, target word string at `[SI]`. Output is modified string at original `[DI]`. Test using DOS DEBUG: [![enter image description here](https://i.stack.imgur.com/ZTDuu.png)](https://i.stack.imgur.com/ZTDuu.png) ### Alternate version, 11 bytes ``` B0 2A MOV AL, '*' ; load overstrike char CHAR_LOOP: F3 A6 REPZ CMPSB ; compare [DI++] and [SI++], repeat if same; CX-- 4E DEC SI ; back up target word to previous char; DI-- 4F DEC DI ; back up sentence to previous char; DI-- AA STOSB ; overwrite char with *; DI++ 41 INC CX ; offset CX decrement from LOOP; CX++ E2 F8 LOOP CHAR_LOOP ; loop until end of sentence C3 RET ; return to caller ``` Saves 1 byte using `REPZ` instead of `JZ`, however it's lost because the loop needs to end when `CX` is `0` and unfortunately there's no `JCXNZ` instruction to do exactly that. Bummer. [Answer] # [K (ngn/k)](https://git.sr.ht/%7Engn/k), ~~24~~ 20 bytes -4 bytes from using `" "` as the blank-out character ``` {y@<>y{y_x,y~:*x}/x} ``` [Try it online!](https://ngn.bitbucket.io/k/#eJxdUtuK2zAQfc9XHNy3EihlKZSklH3tNyxLkXXzTZF1iTVyyH57ZWdzqzAea+bMOePDqN0pv/76nU/5L23zx+4rnb/RebOJu9P8od5on9/Pm/hW/YGwONgIbg/R2wGxkQijlAIsIjUtbzDYOkTpA0Qrq33FrVgCrodbPB3xfIW8hOp90YsyRM5C0Yi+PejCE1lY3guEhWvPBXzUQ5OYHuGmfIizUQV4vKQeM/gftTY73zNOhJRUx9CF3AmlGKakNC1tjqtpjcsvrKLqceppvV6oZqQ5aDs1DTo7JrSaE8yROpAxbSBxQMRg6sKm+bGjob76ox8pF5UjStM9NaC+SPSk0Gkzyy6PNTKr9tvq0WX5ZIySsJR75IKQtMBKne51i+ShTNuXkk3++nXLrqBRyzki25ln5yA8RWg+sQ4NlblaAknTGmPpPousti8/v1SfKr3jQ48aTa+jbxbUotJX2+8vN0xoGUbPvVC817DRpUlMxU7haHKlFcQHMkWUOpGKibNKy4r55FxDw80A7m+Wpc/o1qcQYCiKP26KUbIYyoY9rBZDWK35By8f5sU=) Shoutout to @chrispsn and @ngn for helping to golf the above! * `y{...}/x` set up a reduction seeded with `y` (the characters to search for), run over the characters in `x` (the full string). confusingly, within the function itself, `x` and `y` are flipped. this ends up returning a boolean array with `1`s in the positions containing the desired matches and `0`s everywhere else * `y~:*x` compare the first character to search for (`*x`) to the current character being iterated over (`y`), updating `y` with the result of `0` or `1`. note that as soon as we have matched all the search characters, no more matches will be identified (since a character will never `~` (match) a `0` or `1`) * `x,` append this result to the list of characters to search for (essentially overloading the reduction to end up returning the desired output) * `y_` if there was a match, drop the first character (if there wasn't a match, this is a no-op). this allows us to search for the next search character in the next iteration of the reduction * `y@<>` do an [APL-style expand](https://aplwiki.com/wiki/Expand) with y and the generated boolean array (this fills with `" "`s) An alternative blank-out value can be implemented by inserting e.g. `"*"^y` at the beginning of the function. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` v¬yQić?ë0? ``` -1 byte by using `0` as filler character instead of `*`. [Try it online](https://tio.run/##yy9OTMpM/f@/7NCaysDMI@32h1cb2P//X5KaWFKcmJ7KVZJYDAA) or [verify all test cases](https://tio.run/##RZA5jtwwEEWv8qF4grmBYoeOGwOY4i6Jorg0WRQwqZ3PNezYBxj7JL5Im72MnRXeX4D6PrHJyktp44A/X98wjO1LupT3H@2z/f1t/PX9eby8vr7/HC@n0/AJwmPzGdxvOfoV2UikXUoBllGN5Qarn1KWMUFYOTwN3As5vDzhNGSZMmepB3K0m@5aZukunfVqKtM7QmlbPpzq4vmO/pGbMcSFcSLUqmaGObVZKMVQqtJ0DQWuysN6oB5J@2IMZr9XWM0J7kwzyDmbSGzIWN3UU5qfZ1qne24hhVm7Q85tn9BY1x8PKAlPbUG7IrozjxqhnF068zXerpuwa3lkNH/wFgJEpAzNC5thCCssgaSzznn6378Evi6YYBado@n8UZUswx55FIovGj6HWkTp34lAJXQ7iK/kejXNovafDlWvw8cagqH1Y3yWUx//Y/WXvw). **Explanation:** ``` v # Loop over the characters `y` of the (implicit) input-sentence: ¬ # Get the first character without popping the string # (which uses the implicit input-target the first iteration) yQi # If this first character is equal to the current character `y`: ć # Extract the head of the target-string; pop and push the remainder-string and # first character separated to the stack ? # Pop and print this first character ë # Else: 0? # Print 0 instead ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~52~~ 44 bytes Saved 8 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f(s,t)char*s,*t;{for(;*s++=*s-*t?42:*t++;);} ``` [Try it online!](https://tio.run/##hVTbjpswFHzfrziKVAlMVm237UNLt32o@hWbVUV8426wHWxY5dtT20Auu5VqJbHPMGc8DDj4nmN8OrFIbXWM80witUU6fWFCRilSSfKI1D3SPz8/fEM6SdI4PZ6KVkOTFW0U373cgRuhDzRV@o96eoZHeNkUQAS0QgMWrZaiBp1TUB2lBDINJi9wDrXYK02lAlLQzRY2XgBnyvG0LFruoQOvc5PxDvphbPXUMA/2ssqwtWAMKzMo1VgSxjIYDOM2ECYwk@JiyHMoRWeg4NhCc7Al2KYplCUtaKibvedWlkHJm4mWY7eHMfMYoyDsWMHoCwFGAmuKyhcdp5OGUUx47Hsg0mrgeMhKyC3UUFiwtCmaRtgg3eO6gj3kFdcy94gqMugkloThioPQvRnI4MyS3g69I4LFtW2cnC2JcRYnZuZgMq1cMJtj@jpvveSNBZkzzFTIbY7tJjXMhrDg@FDaOtx8aKHBrDByvcmAhhWWpu9zW6/KN/tT21GsKVkcoHVggW4GuS0Rnaeg6ReZWq8E52i2jm68e9lAYddKQyg9IZT8@pqnH1CJ7AWq0f7MvfiY@11h10IgI9EaxoX3nxFCe4MsZuQZNMvch0/udq3/IaRRhnwst4njnOKKyiXwnf39sLNff7nvF99zVX9a@9wxhsif16Il1Lq2D@my/A6qmKhg0foY4/cLgM5ICkkS2DHMB/1iRTmt5cAHxnN6Q4D9gbEnd45r2kYqhgQ@XjEcjrsx8pwtqDh9pa1Xbf1Gm81N@k0PdT3nF/J1lw@AC0Ecx2/ddMvWNIZHH8mZ2Ln/Hc2izW7zTu1cpvMM9z/WlftpHa62oLcwi6wPxW/wvPg63h1PfwE "C (gcc) – Try It Online") Function takes two input strings and return the meme-formatted string in the first parameter. ### Explanation ``` f(s,t)char*s,*t;{ // function inputs two strings for(; // loop *s // until end of string s ++ // bumping s each loop = // set character in s to... *s-*t? // depending on whether it equals character in t 42: // a '* if not equal *t++ // or character in t and bump t if equal ;); } ``` [Answer] # [Python 3.10.0a4](https://github.com/python/cpython/tree/v3.10.0a4)1, 56 bytes ``` f=lambda s,t:s and('*'+s)[x:=s[0]==t[:1]]+f(s[1:],t[x:]) ``` [Try it online!](https://tio.run/##XVI7jtswEO19itfJzqrYRZpAgA@QMwgqKP70oyiRY3GkyzuUnWwRVsT7gfOGy06dn3/@WsLzae6TcK0SiCVVEWJW1@JH8RFv9ZWre6w/m/ud6uqruTUf5hrrr6opqeaquT1JR4q4oy5@Q3nMniD9TMFPoE4jLlorCELqetlh8m0kHSJUr4uykF7poinr4kyRImY9hX62mSIRX8zDTl0SdsG67TMdzmTu8Ya@kVO3hlFIZqRkBoEh7oMyRmBLxvLpWaXZ3soD6YjWb12HwS8JvZUM9@AB7FwfWc0gTK7NJisfA0/tyzaywWDdoYd9abGLTL/fbjQ87yP2E@EX5JECjOvHDPkUXrcTX6w@CLs/5L6uUIEJVm5iQMeY0DNYu945z9/h4yqnES260VLoMvwOir3AEmRQRo4Wnta0qS3PpVbe1qwGy4ldDuZBpTzNYdJZd0jr2vH0t3JBMVf@r@vLxfiAqGfSs9QlSASrCX1u41xxdUE@S94OXfMX@E92uz3/AA "Python 3.8 (pre-release) – Try It Online") Python 3.10 [allows unparenthesized assignment expressions in indexes](https://docs.python.org/3.10/whatsnew/3.10.html#other-language-changes), which saves 2 bytes over 3.8 here, which is the newest version on TIO. 1This is the version I tested locally, this will probably work in future versions as well. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~27 25~~ 20 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ({w↓⍨←⍵=⊃w,0}¨⍞)\w←⍞ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=06guf9Q2@VHvikdtEx71brV91NVcrmNQe2jFo955mjHlYNF5AA&f=AwA&i=RZBbjuUgDET/WUVtp5dBeL9CAF9wsvomt6WZH8s@qrLsskJVbcQPdMVZCaqe1GsGeYNxGaMhCcsH5ZHrMcj0AR2MEFaQHILMICXH1lIPp3vxJ/sl3dXmfdJT9uz@AP6RLWrKzl17kooZa9koEccdtbUSc1nHX5lTn8j5EA/WM1yd3iPWayE4xSgfjuBSwmB9gpDL8XqMSGwRXXlMvK8Dt/xSFtag8p1wv3Nd3ZaQRMXq@HZf6@XMQ7jro@7WoDsTnJoywjMyAoNNCaVUfuVJpKZywgGfHHX/MtVXa56zGEHi6qprq5JDpbamnvsN3Xi27QCrzGVv5qjXPv6x63@oksYO9Rc&r=tio&l=apl-dyalog&m=tradfn&n=f) A tradfn submission which takes the two values from STDIN. Inspired by coltim's K answer. Uses space as the blotting character. -2 and -5 bytes from Adám! The expand operation `\` uses a bitmask to insert spaces between the elements of the input. `1 0 0 1 0 0/'hi' → 'h i '`  ## Explanation ``` ({w↓⍨←⍵=⊃w,0}¨⍞)\w←⍞ w←⍞ store target word in w \ expand using the following bitmask: { }¨⍞ for each character of the source word: ⍵=⊃w,0 is the character equal to the first one in w? return that w↓⍨← then drop that many characters from w (0 or 1) ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, ~~38~~ 37 bytes ``` ->t{gsub(/./){$&==t[0]?$&+t[0]*=0:0}} ``` [Try it online!](https://tio.run/##jVPbbtswDH33VxBdVnQr0mqvA7w97xvSYLB180W2rIst2kF@fZkvaZZ06YUQRFI8pA5BybZpfxDxYf3D76Rr07vHh8cvu9VtHPsN2f5c3d5P@mtMvpP9/iA2EcDnMO0AVDM@Gz5xs25VFhLZmK6v/VCJ@cxQ0S2WpG2BKp3tJY/jrHSwosrLs8BiUxuMyVCNznazelh/20bbaPUb7mO4eao/7UYzjk9sXgh5FqrJhbBLl/BFXavhp0DinpHXIC1ZeiYXTb8QM9GYS4jzm7vZfZW8PMdO6S0pCP47UiR9q3H@BuspiK8FNQmWnAbyX3VOPiTXkst3Ecdm7QkUjtrMKxtZq3cvOj6W/VN9c/gFTEOt/fhYa2@1Ap9xcA3nDBIPIctpBkqnznPrgOU88tx5mrgR5G1ey6iVy4DhNGBjy4QiQgiiSKBwfcGESKALQqKIBgiDk7rLMih0EyCXFKFqsQCsqtwhq8GDqtKoRAGFrAZe9E0KfRIJDhr7EvpIQ7AwT6CRfPDQ64H2xgCz6Mdv1CUFZAgKcgTkVV5VGqPSUFVCClkpvc0ilyfQWGqZoKUE7U3oWDdSYwY7M6IAqcJqLIQFCyOhQYQ/uvG5rt1h3ai/ "Ruby – Try It Online") Takes the sentence from STDIN and the target word as the lambda argument. Uses `0` as the blank-out character, an idea borrowed from @Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/217697/92901), which saves a byte over using `*`. For each character in the sentence: * If it is the same as the first character of the target word, retain it. Then remove the first character of the target word (`t[0]*=0` is a slightly obfuscated equivalent to `t[0]=''`). * Otherwise, replace it with `0`. [Answer] # [R](https://www.r-project.org/), ~~102~~ 98 bytes ``` function(s,w,`[`=substring){for(i in 1:nchar(s))`if`(s[i,i]!=w[1,1],substr(s,i,i)<-"*",w<-w[2]);s} ``` [Try it online!](https://tio.run/##VY5BbsMgEEX3PcWUFVRk4S6T@AA5g2XJFGMzkgsuMy5Kqp7dRU1iJdv/338zaZ3iB7FL9ToswTLGIEln3TVdTUtpEoZR/QwxSQQMUO2D9SZJUqrDoZPUoMb2tc5NpatWXyfFUFJ13Ik3ofNxl5v3Vh3o935LihP0EUJksDFwihOwd0Czcz0YhuzRerjBBD06oYWNvRPqZVOwI7aGyuz/x0KwoUdgGSefzTjD1/c58OVzKMhyjbbkyWeYim8TrX8 "R – Try It Online") ``` function(s,w, # s=sentence, w=word `[`=substring) # `[` = alias to substring function {for(i in 1:nchar(s)) # loop over all the indexes of characters in s `if`(s[i,i]!=w[1,1], # if it isn't the same as the first character in w substr(s,i,i)<-"*", # change it to a '*' w<-w[2]); # otherwise leave it and remove the first character in w s # finally, return whatever's left in s ``` --- Or, with vectors of characters (instead of strings) as input & output (thanks to user for the suggestion): # [R](https://www.r-project.org/), 75 bytes ``` function(s,w)sapply(s,function(l)`if`(length(w)&l==w[1],{w<<-w[-1];l},'*')) ``` [Try it online!](https://tio.run/##XZDBasMwEETv/orFgVoqziHXNPqAfkMIRJXXtkDRCu26IpR8uyOKW2hvyywzb5i8BvpgwWzWcYlOPEXFfdFsUwr3ev6qQV/9eFUB4ySzKvolGFPOh0v/VU6nfTnvD5e38Oi7107rdQcTRsxWED7RCWUGGsHNNltXYQyWwce0yLFhg0GxZE7Bi2rfYSCIJOAoSqYAMiNwQhzACpTZuxm2ygyDx7ZvW62b8jfF0fDz2cFI@Va9tEgFwpjptpX610kIaoKPE6hqAbR8h4x2qIo@Ns6K2sDfC/WMyXSdbtYn "R – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-plF`, 31 bytes ``` $_=<>;s/./$&ne$F[0]||shift@F/ge ``` [Try it online!](https://tio.run/##BcE7CkIxEAXQ3lXcIthpbKz8YBV4a3iIaDKaQMiEzIBN1u54TqdRj2bucTlfT@L33m0bubAe7nNKLm@9Bf8hs8iJNgsSo7EictPBFZoJ0okSnopvLjGj8kuUhiAV@nHXwk1s12v4Aw "Perl 5 – Try It Online") Input is on two lines. The first line is the target word. The second line is the sentence. Uses `1` as the blanking character. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ®¥VÎ?Vj:Q ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rqVWzj9WajpR&input=IkkgZG8gbm90IGNvbnRyb2wgdGhlIHNwZWVkIGF0IHdoaWNoIGxvYnN0ZXJzIGRpZSIKWydjJywnbycsJ2QnLCdlJ10) ``` input: > sentence as a string > target as a char array output blanked out with " ® - for each char in sentence: ¥VÎ? - == to first element in target? Vj - returns first element and remove it from array :Q - character " ``` [Answer] # [k9](https://shakti.sh/) L2021.01.29, 31 bytes ``` {(y,$0)(-1{*(x<)#y}\(=x)y)?!#x} ``` `(=x)y` get indices in sentence for each letter in target `-1{*(x<)#y}\[target indices]` get each target letter's first index in the sentence that's greater than the last target index we took (ie always looking ahead) `[first indices]?!#x` get position of each sentence index in the 'first target indices' list, defaulting to the list's length if not found `(y,$0)[index list]` index into target word with 'blank char' suffix. EDIT: assuming we want `*` as fill, we can use [coltim's awesome ngn/k answer](https://codegolf.stackexchange.com/questions/217690/speed-of-lobsters/218688#218688) to get to 24 bytes: ``` {`c"*"|x*y{y_x,y~:*x}/x} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` ≔⪪⮌⁺S¶¹θ⭆S∧⁼ι§θ±¹⊟θ ``` [Try it online!](https://tio.run/##XU67CsMwENv7FUemM6RD5kwZOmRoCc3axbWP2GD8vKT9e9elWwchCQkhZWRWQbpap1Ls5nGNzjLe6aBcCBe3F5x93HnlbP2Goofu4TvReGhIYjwtLWD85VcZ/@uT13hJu3QFbXM8e01vTD3caJNMOIjv2BIipqbEWKsKmk4z6AA@MKjgOQcHbAhKJNIgGV7GKgMuPAu3n6At1fPhPg "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order target, string. Output uses `0` as filler (+1 byte to use an arbitrary filler character). Explanation: ``` ≔⪪⮌⁺S¶¹θ ``` Append a newline to the input target, reverse it, and split it into characters. ``` ⭆S∧⁼ι§θ±¹⊟θ ``` Loop over the input string, replacing each character with `0`, unless the character matches the last element of the above list, in which case pop that element instead. [Answer] # [Racket](https://racket-lang.org/), 140 bytes ``` (define(f s t[a'()])(if(null? s)(reverse a)(if(char=?(car s)(if(null? t)#\*(car t)))(f(cdr s)(cdr t)(cons(car s)a))(f(cdr s)t(cons #\*a))))) ``` [Try it online!](https://tio.run/##bVNLcpwwEN37FK/GC4tU@Qix1zmD44VGfxAIpB4kuLyjmUlStrA2gvcpuvvRkYtB0cej55NBvL8wqbSbFNNIoDf@xLr3jjnNpov3r0gdi2pVMSnwGywsjz9fmeDxyv3XUff4@8cNpa7rWNXJm@B6Ub3ClP56@CeabgSqtaL1fDAdIthbwhM7/YIMmAKhaigGD7IKaVZKghOydcLCh3OiWh2kU6cHfDonUokEr3Unim4yDXsx3mZuZizrNtE@6oZf4sBFKchZ9xx92nqpNceatSmtdkfekwmrtejDnOGMKBgvpUcZR5eKnEDw47mxDUWjN@Ou@m0@Y@MNrRVC2QZsJ3wlAnKEHt3QGGajdsIWdrEtC2QsBCNW3sMWeLiCokY3jqG0dSzCDzjDDoaibcjkOOYootRiMAi05FWutV@5lHWpHhThy1g/UnqZa5e7zoccOKWaw6l7/0e80TVfEeQhM56@IjWoe07fx1RzEno9gEZc@uLPLawOQGlmW4eb43G031gPChHzstjiW/zaUt0oPDDp0uz55icw7xI9v9x/TNTNY/fH55crUfeiAei@HH8A "Racket – Try It Online") I know, this is super long and silly. [Answer] # Oracle SQL, 225 bytes Its not a golfing language, but ... ``` WITH r(s,w,a,b,c,l)AS(SELECT s,w,1,1,'',LENGTH(s) FROM t UNION ALL SELECT s,w,a+1,DECODE(SUBSTR(s,a,1),SUBSTR(w,b,1),b+1,b),c||DECODE(SUBSTR(s,a,1),SUBSTR(w,b,1),SUBSTR(w,b,1),0),l FROM r WHERE a<=l)SELECT c FROM r WHERE a>l ``` Which assumes a table `t` with columns `s` (sentence) and `w` (word) and uses `0` as the masking character. A neatly formatted version (which also outputs the sentence and word) is: ``` WITH r(sentence,word,sentence_pos,word_pos,output,len)AS( SELECT s, w, 1, 1, '', LENGTH(s) FROM t UNION ALL SELECT sentence, word, sentence_pos+1, DECODE( SUBSTR(sentence,sentence_pos,1), SUBSTR(word,word_pos,1), word_pos+1, word_pos ), output||DECODE( SUBSTR(sentence,sentence_pos,1), SUBSTR(word,word_pos,1), SUBSTR(word,word_pos,1), 0 ), len FROM r WHERE sentence_pos<=len ) SELECT sentence, word, output FROM r WHERE sentence_pos>len ``` Which, for the sample data: ``` CREATE TABLE t(s,w) AS SELECT 'I do not control the speed at which lobsters die', 'code' FROM DUAL UNION ALL SELECT 'testcase string', 'tas' FROM DUAL UNION ALL SELECT 'uglhwagp qvyntzmf','ulhwagpqvyntzmf' FROM DUAL UNION ALL SELECT 'qrkacxx wwfja jsyjdffa vwfgxf','qcfvf' FROM DUAL UNION ALL SELECT 'z wzsgovhh jopw igcx muxj xmmisxdn t lmb','gcujxlb' FROM DUAL UNION ALL SELECT 'kxf jgmzejypb ya','e' FROM DUAL UNION ALL SELECT 'fe oxyk y','ex' FROM DUAL UNION ALL SELECT 'o wr fmik','owrfmik' FROM DUAL UNION ALL SELECT 'pgezt yozcyqq drxt gcvaj hx l ix xemimmox','e' FROM DUAL UNION ALL SELECT 'kqclk b hkgtrh','k' FROM DUAL UNION ALL SELECT 'sia prcrdfckg otqwvdv wzdqxvqb h xclxmaj xjdwt lzfw','crwqqhxl' FROM DUAL UNION ALL SELECT 'teatsase','tas' FROM DUAL; ``` Outputs: > > > ``` > > SENTENCE | WORD | OUTPUT > :-------------------------------------------------- | :-------------- | :-------------------------------------------------- > teatsase | tas | t0a0s000 > fe oxyk y | ex | 0e00x0000 > o wr fmik | owrfmik | o0wr0fmik > kqclk b hkgtrh | k | k0000000000000 > testcase string | tas | t0000as00000000 > kxf jgmzejypb ya | e | 00000000e0000000 > uglhwagp qvyntzmf | ulhwagpqvyntzmf | u0lhwagp0qvyntzmf > qrkacxx wwfja jsyjdffa vwfgxf | qcfvf | q000c00000f000000000000v0f000 > z wzsgovhh jopw igcx muxj xmmisxdn t lmb | gcujxlb | 00000g000000000000c000u0j0x0000000000l0b > pgezt yozcyqq drxt gcvaj hx l ix xemimmox | e | 00e00000000000000000000000000000000000000 > I do not control the speed at which lobsters die | code | 000000000co00000000000000d000000000000000e000000 > sia prcrdfckg otqwvdv wzdqxvqb h xclxmaj xjdwt lzfw | crwqqhxl | 000000cr000000000w0000000q00q00h0x0l000000000000000 > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=3e7b37e6ff4dcb9ab672691602238b6c)* [Answer] # [Python 3](https://docs.python.org/3/), ~~90~~ ~~80~~ 81 bytes -10 bytes (thanks to @Danis) -Fixed error when trying to access first character (thanks for @xnor for reporting) +1 byte: Fixing return error ``` def f(t,g,i=0): l=['*']*len(t) for c in g:i=t.find(c,i);l[i]=c*(i>=0) return l ``` [Try it online!](https://tio.run/##DcvBCoMwDADQu18RejEtRQa7Kd2PiAepaRcoUdrssK@vXh@866/fU969H5QgofrsObzsPEAJ6@jGzRUSVDtAOitEYIE8c9ApsRwYPdulrLyF6JA/T1wq6a8KlH5VFsWERqlp3BtB04ey8WB0b8bafgM "Python 3 – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~131~~ ~~106~~ ~~96~~ 89 bytes ``` >>,----------[++++++++++>,----------]<[<],>[<[<+>>-<-]->[[-]<.+>]<[<.[-],>+]<[>>+<<-]>>>] ``` Input is taken as `sentence\ntarget` where `\n` is a newline [Try it online!](https://tio.run/##TYkxCoAwEAR7X5H@El8Q9iNHihg5MYKgoomvj2cjTrPD7LDHeZUzLa0B1n0wffxz8OyDBesQ4LwLDsyae8L79eoWpAqQ1xtAaG3bl5hqNaVIjiYfdx5FormKTFW6LcklDw "brainfuck – Try It Online") -25 bytes (thanks to @cairdcoinheringaahing) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38~~ 32 [bytes](https://github.com/abrudz/SBCS) -6 bytes by using a space instead of `*` as a blank out character. A port of my [Python answer](https://codegolf.stackexchange.com/a/217712/64121). Assumes `⎕IO←0`. ``` {×≢⍵:(⊃x↑⍺),(⍺↓⍨x←⊃=⌿↑⍺⍵)∇1↓⍵⋄⍵} ``` [Try it online!](https://tio.run/##TZC7ihRBFIbzfYqT9S4oKGaCkYkTCa4vUFO3vlRNdV2m63SLkTJee1iRxXwjA8FkNzFZ0DepFxlP74CYHIrv//6Cc1hv7ouRGacPZX@5el52Fw8Or/58Kx@uynzz@LR8fINl96XMv87undIsu69l/k7ogpIn5fPtMST3rLx/9/Auvimf3tJ8fVCLNu/JLPOPMl///vlo0feX5y@e0nz5bHV@qLgTslLVCoSDjUvA3SYFZyDVEmIvpQCWINcNr8G4dUwyRBCNrE6qxCIVk4yJs0hyCs1GE9@aOjPd@2HcpMkqcrb6iOAfO6k8V8OS@dAxjgg5q5ZBG8dWKMVgyErj4mm@bdGsyZwgT1G7oa6hdX2GRnMEu8UW0NomothAAmPXVFo26lBBq@0k27Ffw8gWjMSVBIdjByMBl4OyTUfUQQ5w9z62ey2nBKOb@Og9iIAJNB9YCzWCgQYBpW2sdUj@0u88Nx2soe50CjVBHrL3NRrKYsOgDzwIxTsNLvk8iIGWER4HTxVAbtDS39iKTCtMKv93XpYinbf6Cw "APL (Dyalog Unicode) – Try It Online") **Commented**: ``` { ... } ⍝ A dfn taking two arguments: ⍝ - the target word as the left argument ⍺ ⍝ - and the sentence as the right argument ⍵ ×≢⍵: ⍝ if the length of ⍵ is positive: ↑⍺⍵ ⍝ mix ⍺ and ⍵ into a character matrix, padding the shorter with spaces =⌿ ⍝ for each row, check if the two characters are equal ⊃ ⍝ take the first result ⍝ this is now ⍺[0] = ⍵[0], but this is 1 if ⍺ is empty and ' ' = ⍵[0] x← ⍝ and store it in x ⍺↓⍨x ⍝ drop x (0 or 1) characters from ⍺ ∇ ⍝ and call the dfn recursively with this value 1↓⍵ ⍝ and with ⍵ without he first character ( ), ⍝ prepend to the result of the recursive call ⊃ ⍝ the first character of x↑⍺ ⍝ take the first x characters of ⍺ ⍝ if one of these strings is empty, ⊃ and ↑ use a space as a default value ⋄⍵ ⍝ if the length of ⍵ is not positive, return ⍵ ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` «S↓₁λ?←¹'*₁ €↑1 ``` [Try it online!](https://tio.run/##yygtzv7//9Dq4Edtkx81NZ7bbf@obcKhnepaQA7Xo6Y1j9omGv7//z85PyX1v6dCSr5CXn6JQnJ@XklRfo5CSUaqQnFBamqKQmKJQnlGZnKGQk5@UnFJalGxQkpmKgA "Husk – Try It Online") It took a while, but here's a short(ish) working solution. ### Explanation The second line is a helper function, it shortens the program because we would have to call it twice, and it would need brackets both times if it was inlined. ``` €↑1 Input: a string and a character, Output: 0 or 1 ↑1 Get the first 1 characters of the string € Return the index of the character in this substring (0 if missing) ``` This function tells us if the given character is the same as the character at the beginning of the string. There would be a simpler way of doing this (`=←`), but `←` on an empty string returns a space character, and this would mess up things. The rest of the program is a call to mapacL (`«`), which scans a list using two functions, one to update the internal accumulator and the other one to generate the output. In practice, we will loop through the sentence character by character, our accumulator will start as the target word, and at each step we will update the accumulator using the current input character and the first function (`S↓₁`), and we will generate one output character using the accumulator, the current input character, and the second function (`λ?←¹'*₁`). Updating the accumulator means discarding the first character from it if it matches the current input character: ``` S↓₁ Input: accumulator and current character, Output: new accumulator ₁ Call helper function (1 if character matches, 0 if it does not) ↓ Drop that many characters S from the first input (accumulator) ``` Generating output characters means returning the character itself if it matches, and returning `'*'` if it does not: ``` λ?←¹'*₁ Input: accumulator and current character, Output: character or '*' ₁ Call helper function (1 if character matches, 0 if it does not) ? If 1: ← get the first character from λ ¹ the accumulator Else: '* Return '*' ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes ``` . _$& +`.(.)((_.)*¶)_\1 $1_$2 (.). $1 ``` [Try it online!](https://tio.run/##DchBCsMgEAXQ/ZziL6RoCwPpLXKHgk11QCE4QQd6sx4gF7PZPV4Xq22bkym6Gz3e7Dl4Hzncz1@Ir4XcEt2TruWLc67IiqaGpM267rAiGIdIxmb4lpoKdv0Mkz6Qq1DSLH8 "Retina 0.8.2 – Try It Online") Uses `_` as the filler. Explanation: ``` . _$& ``` Prepend a `_` to every character (both of the string and the target). ``` +`.(.)((_.)*¶)_\1 $1_$2 ``` Find a character which is not before a character that has already been swapped that matches the first character of the original target, and swap it with its preceding `_`, removing it from the target, and repeat until the target is empty. ``` (.). $1 ``` Remove alternate characters, i.e. keeping the `_`s unless the target character was swapped. [Answer] # [Red](http://www.red-lang.org), 71 bytes ``` func[s t][c: take t parse s[any[change[not c skip]"*"| c(c: take t)]]s] ``` [Try it online!](https://tio.run/##lZNNjtwgEIX3c4onVkmOMDfINlvLC5p/24D5scFW7t4htrtHkRKlhw0qFe@r4lFEwe8/BO/6N/l@l4tjXULuO/aOTEeBjJnGJJA66raOaeqU6JzPYEijmXvyjfwE@/I8/rXvU3@XPgrKNE7WG9oi38E9DqV3OfoJWTfsLAQHzSjatPOTv6UsYgI3ghwq5rkgJyCLlBn93UuOxqkj/99FMk2XflGTLlTNCOvm8m7lKwSynKKn5mSFOFJWK0qRA8WQtoFLSbEWqeo/uSQwuR7ZE7Kj7En5VWsMfi4wilXYpQ6o1ppUuWv2T/b2B48otgx1ul2NjFViUHYXwzbfsNGXXCEPS6WAr9uI7TUzH@pKrht4lAhpzfgpvS/x0JyMWYk9Y/M720IAjzVDsZUO0BUTTEUV1ljrK/nbDcbAphE36FHlqF9sgzxqJ0MxRxa5ZKOCz6GsfG2vwkNdQ4Oisqna1ksdeGlvsctC2kzGEoKu03MuaU5tLj/jwTWXfdfKG5fRtR9jkeBEmYwTOML8EbbUR3TtPfr7Lw "Red – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` c_~f[a:c_:"*",b___]~d___=a<>f[b]@d _f[]="" ``` [Try it online!](https://tio.run/##VVC7jtswEOz9FQsZCJLAaVIecgcBqdKlNwyB4psSTZFciysZvl936EdeDcGd2ZnFjGdopGdoObteefeu9uyFdy/N52bXd113eBf1fWXf3tS@P7Ri06n94bVprj@TPeL@vN1evrx9VG373bDEOMqU2@3XT//Phw9t25435@YHiADHgMDDEVMYod6GPEkpgCEUY7mBMfT5JgNhZbNreBCyueyqGGVGznIVYL2tK4csP6iTHk1heoI4L0dcvark6QH9Qe6LMQ2ME0EpyjFweXFCKQZzUZpuosjV/FxdoaxZh9kYcGEqYDUn8CdyQN7bTOIICKPvq0rzk6Oxf@gGUuC0X6Vbph4WVvlnACUh0DLAcoPogQUoCZS3Q8VCSfffnZi0XBGWsPIlRhCJEDSfmQNDMIIlIOmt94H@@g@RjwP0YAaNyVT8aZUtgynxJBQfNASMZRZzTScizbGuA/GRfLUmJ0rNtKpyKz6VGA2Nv8tnmGv5/7aOGdl9bi6by/UX "Wolfram Language (Mathematica) – Try It Online") Input two characters sequences as `f[word][sentence]`. [Answer] # [Elixir](https://elixir-lang.org/), ~~184~~ 169 bytes ``` defmodule A do def f x,y do cond do x==""->x q(x)==q(y)->q(y)<>f p(x),p y 1->"*"<>f p(x),y end end def p(x)do String.slice(x,1..-1) end def q(x)do String.at(x,0) end end ``` [Try it online!](https://tio.run/##bVG7jtswEOz1FQtVVmAbcR8buPKqK/IFNF@iRIriQ@JSP@@QCmLg7BR87OzM7JLLtULlHw/GhbFs0Rw@gNmmhCAAj7kG1E6snni9tu3pho07YHe9ukPuTre6/7oJmAt2nCE3l9Ot/dE@odzwie2relaoOP2OXk3yHLSi/IDHy/l8unRPkvtGIrEwfnb/bB6fX@d5iQE@zuLQfpa@YLIRSo/RWw2x5xBmzhmQCKlXtAdt7yFyH4Ap3h6hpZbxtmu@@UQeIiWhaPeilRZJeGUtUveJyBncmqe4GVF5y1/sCb1onB8JRYSUxEBgCHlgQhBYk5C46x0V65tqg7QFade@h8HOCZSkCGbBAdAYFZBNEEGbezWQdBlQ318tRhQwSLPxIc93yKRS394tOFjMI@Q9i69pC8mDMGqsaZv8fn3hzJJvEbLdaHYOmMcIkq5kgB5Bg0JAbpQxFv/bwOioHuEO/Sij7yvlrUBQBGZPPRN0lGCjSytby/8wh6srSkCq0ZSCOLBUfmUTaR@zT871qN9HTWIoo37O@PEH "Elixir – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~24 18 17~~ 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ù←⌐0ø\d▀→"ε╞☺Γ|▓ ``` [Run and debug it](https://staxlang.xyz/#p=971ba930005c64df1a22eec601e27cb2&i=%22code%22,%22I+do+not+control+the+speed+at+which+lobsters+die%22%0A%22tas%22,%22testcase+string%22%0A%22ulhwagpqvyntzmf%22,%22uglhwagp+qvyntzmf%22%0A%22qcfvf%22,%22qrkacxx+wwfja+jsyjdffa+vwfgxf%22%0A%22gcujxlb%22,%22z+wzsgovhh+jopw+igcx+muxj+xmmisxdn+t+lmb%22%0A%22e%22,%22kxf+jgmzejypb+ya%22%0A%22ex%22,%22fe+oxyk+y%22%0A%22owrfmik%22,%22o+wr+fmik%22%0A%22e%22,%22pgezt+yozcyqq+drxt+gcvaj+hx+l+ix+xemimmox%22%0A%22k%22,%22kqclk+b+hkgtrh%22%0A%22crwqqhxl%22,%22sia+prcrdfckg+otqwvdv+wzdqxvqb+h+xclxmaj+xjdwt+lzfw%22&m=2) -6 bytes, following Dingus's idea. -1 byte from recursive. (`h=` → `h`) -1 byte, using `\0` as a filler character. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~63~~ 57 bytes ``` $t,$s=$args -join($s|%{"*$_"[($c=$_-ceq$t[+$i])];$i+=$c}) ``` [Try it online!](https://tio.run/##VVHLbsIwELznK1aVKRDoF6BISD31RCV6Qwi5zjqPhjhkN69Svp3aCSl0D1l7MjuTyRamwZJizLKr0BDA@Sp4KSgQsozIe0lNks8E/UzOT744PO1mQgXi8KLwJHi3EMl@vl@JZBEIdZlfL563nnnecjZ9g9BAbhiUybk0GXCMQAViCJKhiRMVQ2Y@ia03hAlOl1NlQtf8sZTx/1X4/@rj0KZz58dIrCRZDy6TPLI6LMk9HUXSODOQqyiLGxkVcKq7nL@P2hKrAXpE/AHy/7B@@FR@SdW20DQ6lZBSl4ZaS6gbHbVu7KR03XcXoTfVj19d99dBSiOYtvuCztKxddltpvYxlGSyoR7SSJ@G194cfmACZw9sCcKcMVe4BMF2b8j2gG2Biu0PD0AcBlqJVGVsgWe76hsT1uNwz9m9b18rYnPcfKZ2fL8@byulkMjJ3Obd9u/6K9hUXFR8J6xge5N02Ci/go/BMBitL97l@gs "PowerShell – Try It Online") -6 bytes thanks to mazzy! [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 134 bytes ``` S =INPUT W =INPUT N W LEN(1) . M REM . W :F(O) S ARB . L M REM . S O =O DUPL('*',SIZE(L)) M :(N) O OUTPUT =O DUPL('*',SIZE(S)) END ``` [Try it online!](https://tio.run/##ZYy9CoMwFIXn5CnuZlJKodBJcGgxBSEmYhShWzUBBfEWE@jjp1napdP5OH9@wxHXS4zEQFGppu8oGb6kEkqh2JnDCWpoRZ10IPmdaU7T4NrekiF/kaFEQ6Gh7BvJskN2NNVDMMk51CRnilNNdN@l5/@S4ZwKVcZYgUXYMMCEW9hxhTA78C/nLDwDvOdlmmHF0Qe3e7CLoxNa9wE "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~49~~ 46 bytes -3 thanks to @ceilingcat ``` f(s,w)char*s,*w;{for(;*s;s++)*s-*w?*s=42:w++;} ``` [Try it online!](https://tio.run/##bVPLbtswELz7KwYOCtiyU7hpT1XSnnrIuTk19YHmS9SLEkmLlAJ/u0s1kWwgISBRnB2uZodLeispPd@ompZHxnFvHVP6c/bjLFZ269c0Iyax28SnL0KbVZrY1G4268TeJv5nYh@@3X33m016Ot8wLlTN8YQvd4tp8fvxzy983e0WC1U7VETVqzVeFgvEMWaGfX7aP4@sPR5iYMSXj2AatXagunZGl3AZh204ZyAOPlM0Q6kP1nFjwRRfbl/3OW4dJTZynVG1nOCjLDNPZIO262s3VGIKtKYgNAR4L3KC3PY5E4Kg80KGmTTAD1bqLsuQ68ZDSRpQHUOOUFXKBlbDoawOE78IArmsBp73zQE9mXDBoUNfoJ8ADW8gKlVMQCP54NDrgfZtC2aCg6QdyZEFlFABgVeqqnSYf9XSssABWSGdySbUKoLGUMMELSS0a33HulgEa0PXRjICLUMV04ac@Sh9EP5iIHE2Grg8pVdH5D84IqrZxXZiZ6tfnX5nNBXdvJD0mIdy9mtOw@e6tDfXvsyMGaHGt20WymsFUfL4/f81NurYbyoK3qVxusdTnGLbvumfmeNoYrM4sVp@sn/r8VluY1eq/TYWrvbr9P2GeDHG@FX4w1xzpjfS6UI13B1NHbUtTud/ "C (gcc) – Try It Online") Just noticed that there's another C answer that is even shorter. Nevermind, I leave mine here. [Answer] # ARM Thumb-2 machine code, 24 bytes Machine code ``` f811 2b01 7803 4293 bf18 232a f800 3b01 d1f8 2a00 d1f4 4770 ``` Commented assembly: ``` .syntax unified .arch armv6t2 .thumb .globl lobstah .thumb_func // C callable. // void lobstah(char *sentence, const char *target); // Input: // sentence (null terminated string): r0 // target (null terminated string): r1 // Output: // sentence is modified in place // // This is nothing but the obvious approach: a linear // search loop. Sometimes, that's best. ¯\_(ツ)_/¯ lobstah: .Lnext_target: // Load next byte from target, increment (wide insn) ldrb r2, [r1], #1 // Search .Lsearch_loop: // Load byte from sentence ldrb r3, [r0] // Is it our target? cmp r3, r2 // If it wasn't, replace with a '*' it ne movne r3, #'*' // Store back and increment (wide insn) strb r3, [r0], #1 // Loop while we don't have a match // (the flags were not modified since the cmp) bne .Lsearch_loop .Lsearch_loop.end: // Loop unless we reached the null terminator. cmp r2, #0 bne .Lnext_target .Lend: // Return bx lr ``` [Try it online! (sorta)](https://travis-ci.com/github/easyaspi314/easyaspi-ppcg/jobs/474799271#L439) It is nothing but the obvious approach, a linear search loop. You really can't make anything smaller than that. 🤷‍♂️ ]
[Question] [ I just love this simple cypher, it's so fun reading not-quite human-readable words and filling the gaps... ``` Ot wes thi bist uf tomis, ot wes thi wurst uf tomis, ot wes thi egi uf wosdum, ot wes thi egi uf fuuloshniss, ot wes thi ipuch uf biloif, ot wes thi ipuch uf oncridaloty, ot wes thi siesun uf loght, ot wes thi siesun uf derkniss, ot wes thi sprong uf hupi, ot wes thi wontir uf dispeor, wi hed ivirythong bifuri as, wi hed nuthong bifuri as, wi wiri ell guong dorict tu hievin, wi wiri ell guong dorict thi uthir wey – on shurt, thi piroud wes su fer loki thi prisint piroud, thet sumi uf ots nuosoist eathurotois onsostid un ots biong riciovid, fur guud ur fur ivol, on thi sapirletovi digrii uf cumperosun unly. ``` The rules are super-simple: * Accept some text as input (ascii characters, upper/lower case letters and punctuation). * For each vowel, rotate it to the next vowel, or back to the start. + a => e + e => i + i => o + o => u + u => a * Upper case vowels stay upper case, lower case vowels stay lower case. * Output the text after these conversions. * No need to support accents. * The all other characters should remain unchanged. * Try to do it in the smallest number of bytes. * Any old language you like. --- ## Test Cases ``` It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of light, it was the season of darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only. ``` Out: ``` Ot wes thi bist uf tomis, ot wes thi wurst uf tomis, ot wes thi egi uf wosdum, ot wes thi egi uf fuuloshniss, ot wes thi ipuch uf biloif, ot wes thi ipuch uf oncridaloty, ot wes thi siesun uf loght, ot wes thi siesun uf derkniss, ot wes thi sprong uf hupi, ot wes thi wontir uf dispeor, wi hed ivirythong bifuri as, wi hed nuthong bifuri as, wi wiri ell guong dorict tu hievin, wi wiri ell guong dorict thi uthir wey – on shurt, thi piroud wes su fer loki thi prisint piroud, thet sumi uf ots nuosoist eathurotois onsostid un ots biong riciovid, fur guud ur fur ivol, on thi sapirletovi digrii uf cumperosun unly. ``` In: ``` The quick brown fox jumps over the lazy dog. ``` Out: ``` Thi qaock bruwn fux jamps uvir thi lezy dug. ``` In: ``` Home is where the heart is. ``` Out: ``` Humi os whiri thi hiert os. ``` In: ``` Boaty McBoatface ``` Out: ``` Buety McBuetfeci ``` In: ``` AEIOUaeiou ``` Out: ``` EIOUAeioua ``` In: ``` Programming Puzzles And Code Golf ``` Out: ``` Prugremmong Pazzlis End Cudi Gulf ``` [Answer] # MS-SQL, 51 Bytes Works on SQL 2017 or above: ``` SELECT TRANSLATE(v,'AEIOUaeiou','EIOUAeioua')FROM t ``` The new function [`TRANSLATE`](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-2017) performs individual character replacement, so is ideally suited for this challenge. Input is via a pre-existing table **t** with varchar column **v**, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). In this case the table must be created using a *case-sensitive collation*, either by running on a case-sensitive server, or by using the `COLLATE` keyword (not counted toward character total): ``` CREATE TABLE t(v varchar(max) COLLATE Latin1_General_CS_AS) ``` **EDIT**: SSMS may cut off the lengthy quote above when returning the result in a "results to text" window, [this is a client setting, not a bug in my program](https://stackoverflow.com/questions/11897950/how-do-you-view-all-text-from-an-ntext-or-nvarcharmax-in-ssms). To fix, go to `Tools > Options > Query Results > SQL Server > Results to Text` and increase the "Maximum number of characters displayed in each column." [Answer] # [Bash + coreutils](https://www.gnu.org/software/bash/), 24 ``` tr aeiouAEIOU eiouaEIOUA ``` [Try it online!](https://tio.run/##dZFBUsMwDEX3nEIHYLhDFyy6YsUBlOYn1uBaGUtppjvuwA25SJFDhxI6rGzP@1/6kju2dLl4JYbovHvev7xSu3G77S6XvdPCRp5AHcxJB3I5wh5JbmTRukEPvxiPaGQR6/W4cV3JoJrFUoH9cWLSQ2qKDlkwbLw/TMqhop@z@HnrNrBpaZIsY/KN@8Z6rm/3nW2qUsbGk07YjirFUVcrbGKp4VxAiXvCCfXsqTk7DFpBc9S9wqJ3pPkWxINzplEb7aXi4ORKCXxCWe3/aCJM1IwsC5/p8/0jJihkSWvM2uCEKtqvwU1p4BqLeMM3qjAUv0oiiSf2UB3XDxG3iCsm7b959igpHo/YtYk5eordNVGHlifSQE5oZWK0CBlN42x3nCTH9sr3Uudol9lDG7sbK9ZmBz1OXGX9jpLPT18 "Bash – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 52 bytes ``` (a:b)!c|a/=c=b!c|1>0=b!!0 a!b=b map("aeiouaAEIOUA"!) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyPRKklTMbkmUd822TYJyDC0MwDSigZciYpJtklc6ba5iQUaSompmfmliY6unv6hjkqKmv9zEzPzbAuKMvNKVNKVPEsUyhOLFUoyUhWSUotLFPLTFEoyc1OLlf4DAA "Haskell – Try It Online") *Lynn saved me two bytes by pointing out that `!!0` is shorter than `head`.* ## Explanation If you have never coded in Haskell this will probably look like a pile of jibberish. So first let's ungolf it and then break it down: ``` (a:b)!c | a/=c = b!c |otherwise = b!!0 a!b=b map("aeiouaAEIOUA"!) ``` First we have a function `!`, which takes a string `s` and a character `c`. Our first pattern match catches accepts input if the string is non-empty. If the string is non-empty we compare its first character to `c`. If it's first character is not equal to `c` we toss it and call `!` again with the remainder of the string and `c`. If it is equal we return the second character in the string. Our next pattern match catches the string in all other cases, that is if the string is empty. In this case we just return `c`. All in all this function takes a character `c` and a string `s` and returns the character after the first occurrence of `c` in `s`. If we pass this with `aeiouaAEIOUA` it will perform our cipher on a single character. To make our whole function we ought to map this across the string. [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` öΦΣòC└∞ ``` [Run and debug it](http://stax.tomtheisen.com/#p=94e8e49543c0ec&i=Programming+Puzzles+And+Code+Golf) [Try it online!](https://tio.run/##ATgAx/9zdGF4///Dts6mzqPDskPilJTiiJ7//1Byb2dyYW1taW5nIFB1enpsZXMgQW5kIENvZGUgR29sZg "Stax – Try It Online") **Explanation** (unpacked) ``` Vv:tVV:t Vv:t #Push aeiou and ring translate it to input VV:t #Push AEIOU and ring translate it to input ``` Might be able to save more, will keep trying. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~10~~ ~~9~~ 8 bytes ``` T`uo`vVA ``` [Try it online!](https://tio.run/##HYnBDoIwEAXv/Yr3BSR@AhqjHowcxDMrLFClXV1aEH4e0dNMZpSD9bRZlmsRpRhu6Wot4x1t@cRdZfSo5YNHdK8eMrAirLujeUIlTWKO4hi2x9iy8v@1TBrWlJitUJhwLn@sqWST7k@XnNhKNJlKo@Sc9Q2yOM8d90h9hZ1UjIN09Rc "Retina – Try It Online") Saved 1 byte thanks to Neil! And another byte thanks to Martin! The new version of retina has vowel classes, which makes the result a bit shorter. The transliteration also makes use of the "other" class. So the `to` class looks like "aeiouAEIOUA" while the `from` class looks like "uaeiouAEIOUA" This doesn't cause any problems since the second `u` mapping to `A` will never be done since `u` was already mapped to `a`. [Answer] # Perl 5 + -p, ~~24~~ 23 bytes ``` y;AEIOUaeiou;EIOUAeioua ``` [Try it online](https://tio.run/##dZExUsMwEEX7nEIHCHRUVCkoUlFxACX@tnaiaDXatT3uuAM35CCYlZMhMQyV1/P@1359ZZT4NM/T8@5l//rmQdw/12lXJz/Pe3WjF6cB7gBRx61TOkO2jm5k5HKPNnfId6hgJGn4vDJdScscSUKCrI3IfAxVcEAktCvrD6N0LGj6SDqtzAIvnKoiUhd0Zb6xxpfTn72SC6Wu4sAZ62tSUpTFCcmeynYzwgXfOAwok4ZqPKDlAtdbQ1eY@DepthE2@xhdxxU2VHBUp@wC/IC0uP/RWBQ70pKMfnKf7x8bSk4CF7tnZRmFuFlSC7vWFyvhhAsqECS9SrYbDV5NdF5eglQsKwnVd/a92omk9mMtC4micVZbFR1Q01gW0AA7xa5lCW2lfeuMgaIVly599rYsejWp1dYVLLuOfM6@0PIQKU6PX5yVOMn8kL8B) -1 byte thanks to @DomHastings [Answer] # C, ~~85~~ ~~76~~ ~~67~~ ~~65~~ 64 bytes ``` f(char*c){for(;*c;)putchar(1[index("AEIOUAaeioua",*c++)?:c-2]);} ``` Port of Kevin Cruijssen's Java [answer](https://codegolf.stackexchange.com/a/163249/79343). Try it online [here](https://tio.run/##TcmxDoIwEADQWb7i0umuwKCjHQyDA5OTk3GoZysdoKQtwYTw7TVMuL7H9Yc5Z4vc6SCZFusDKsmKxilthseHG97mi6K5trd7o43zkxaV5LKky5nr05PUmnvtBiRYioNF0SaYdYTUGXiZmMBbSK43sQK3z@zDfwlSxZp/). Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 9 bytes, to [Christoph](https://codegolf.stackexchange.com/users/29637/christoph) for golfing 11 bytes and to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing 1 byte. Ungolfed version: ``` f(char* c) { // function taking a char array as parameter and implicitly returning an unused int for(; *c ;) // loop over the input putchar(1 [index("AEIOUAaeioua", * c++) ?: c-2]); // find the first pointer to the current char in the vowels string, NULL if not present; if it's not NULL, print the next vowel, otherwise just print the char } ``` [Answer] # Python 3, ~~62~~ 59 bytes ``` lambda x:x.translate(dict(zip(b'aeiouAEIOU','eiouaEIOUA'))) ``` Make a translation table (dictionary) ~~with `str`'s static `str.maketrans` method~~. Translate relevant characters to their destination character. EDIT: Saved 3 bytes by using the `dict` constructor to make the translation table instead of the `str#maketrans` method [Answer] # [R](https://www.r-project.org/), 43 bytes ``` chartr("AEIOUaeiou","EIOUAeioua",scan(,"")) ``` [Try it online!](https://tio.run/##dZFBbtwwDEX3cwrBqwQweocsusiqqx6AY39bRDSiQdJjzK536A17kSnlDJq4RVem8f4Xv770fh8yqetT9/L19dt3Asva9V2bX9pMXW8D1ae@656f792rp40seUY6wzzJlJwvsD7xB9lEP6PTJ0QzGtjYRrkcTA8yiRS2XGFHIxYZchOcURjTwfqHcR0U41rYbwezgUxqUxSesx/MH2wkfftnry3KdW44y4LjNbk6dHfCFmLtTxtSpjHhCr15bsYzJlGkNRp6wCp/k2bbEDOVkmZpcGTF4MklZdAVdXf/RxNR4shIstEt/frx88Q1WRaNeza2QFnGPbVJmkijhDe8I4Wh@kPSnzyTh@iyvwS7RVY2bu9Mq8eJ7PETLRubY0xRWxOd0dJEFvAVcUpcKxLGyvi2GVcuUVx973ONZYU8pFHbrNh3DXJZSHl/iFpuX7r7bw "R – Try It Online") Here's my solution wrapped in a `cat` to get it to print out more nicely: [Try it online!](https://tio.run/##dZExbsMwDEX3nELwlABG75ChQ6ZOPQBj0xYRRTRI2ka23qE37EVSygmauEUn03j/i19fcr02YNsmgphsq/3r4e0dkHis6qrM@zJDVWsDeVtX1W63u1YHCzNosIjhiGqBu2B0Rq0DPcjM8ow2Twh6LGAmbfm8Mt1Jx5xIY0ZdG3HgJhbBERNht7L@MMqNYDsmssvKrAjKuSgS9dFW5gdrQU5/9uoglPuCIw@4viZlQ1mcqAOQ1JsZQ4Q24IRysViMR@xYMIze0B1m/k2KbUafIaXQc4EtCTYWjENEmDAv7n80HsWP9CQzXMLXx@eGctDI4vcsbEAhbpfUyqED8RJOeEOCitnuknpjEcxF5@UlyNSzklJ5ZxjNTyTzH29ZSQ3b4LUV0RFLGs@CNKGf4tfyhL7Sv2XGiZIXl299jr4sgbnUa@sFl10NnwcQWh4ip8tLdf0G) [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 31 bytes ``` $_.tr!"AEIOUaeiou","EIOUAeioua" ``` [Try it online!](https://tio.run/##dZExUuwwEETzPYX@FuH@vQMBARERMSWv29YUWo1rZrwuZ/8O/4YcBDMyW4ChiDyu161ptWRs5mW5eTqa/Nnf3t0/PEYQj/vDvs63dY77Zbm3MEUNlhAaqAXugtEZegj0SSaWr2j3BcUeFUykLZ83pivpmDNpKtCtEQOfUhU0yIRuY/1gVE6Cdsxk88asiMqlKjL1yTbmT9ZGef6xVweh0leceMD2mlQMsjqhQyQ57CaEFNuAC2S2VI0NOhaE0Ru6wsLfSbVN8DnmHHqusCXByYJxSIgXlNX9i8aj@JGeZIpzePn3f0claGLxe1Y2QIjbNbVy6KJ4Cc94RwJFsavksLMUzUXn9SXI1LOSUn3nOJqfSOY/3rKSGtrgtVVRg5rGs4Au8FP8Wp7QV/q3zrhQ9uLKe5@jL8vRXOq19YJ114nPQxRaH6Lk@fjKgxEXXf4Obw "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Øcs5ṙ€-Ẏ,Ʋy ``` [Try it online!](https://tio.run/##dZExUsMwEEV7n0IHCHQcgmPI9re1RJY82rU97hgOQEMDd6Cig5YZ7pFcJKycDIlhqCzr/a/9@rqD9/Ph8Plc8c3u/WX/8Hq1@3jcfL3p5uFWzGTZiIMpwWJiY4Q68MbQmUwxXaLiAtkWGUzEdexWphNpYvTELoDXRvSxcllQwhOalfWHUagS6sGTzCszw3IMWeGpdbIyn1lt0/bPXO4ThTZjF3usr0lBkBYnuLeUNsUE42xtMCLN4rKxRBMTzKANnWCIv0m2TdC19d60McOaEioxEo2DHREW9z8ajaJHapLJzmZ//1RQMOxi0ntm1iNRrJfUHE1jk5awxRElMIKcJJtCnBUVdctLkLBmJab8znYQPZFEf7RlJhbURmvLohI5jWYBjdBT9FqaUEfqN68xktfiwrHPQYd5KyrV2tqEZVYVu94mWh4i@Pn6Gw "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ ~~68~~ 67 bytes -1 byte thanks to @ArnoldPalmer ``` V='uaeiouAEIOUA' print''.join((V[1:]+c)[V.find(c)]for c in input()) ``` [Try it online!](https://tio.run/##dVPbbtNAEH3PV4zy4gSqSEXiBakPaQltgJK0kHCp@rCxx/ZQe8faXcekT/wDf8iPhJltRJsIJEvr9TlnbmfcbELJ9sU25QzhBPr9/nZ5krQGidvxZDpbjJNe48iGJBl9Z7KDwfLm@NXt83R4sxzlZLNBOrzN2UEKZOVp2jAYDrcSp9fDH5hCDPwMjl9uk08XE7haTM/ewen17PMHeDP7Am8Xl/OPMFtOrkHh9@NvX@H17HyU9JK548KZuiZbwLy9v6/Qw9hmcKYRz7nKhXPBNQJ56Ep0CKFEKNG4IJ80wimbsIHLVM/cpCifYk@xO7lMA3TGR9kKfQDOIVCN/gjoEenYPYVE9gQ0BSrUkc@43pPtkJy5Il9a9IdSbDgtlbLCijDfE//FyKYOs7aisDmQezSerXIqKsqwJ3/EMuPu/pHbq6WFEkpucL9d8Rpd1KJvDDmVdjJXkwGu0cm@qHSFYjpCK7PagZYPkQdhp86YqoKCFc7IYRogsDq1Rhv1/@FIORJUqunMBn7//KVNWPAlO@lX0QYdcRZr9wy5cTKMu4c9aBx6tGFH0VpCaYLQ6ugLBS8Vkyf13bTyEzgKcpGJe/IBM5ABKmmFWpHUg7TGGEe3vWBJK6e@45qqI93@ONlWElYmCFkGWDiM2VKuG@MommKrzSj5Aw "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 60 bytes ``` s=>s.replace(/./g,c=>(S='aeiouaAEIOUA'+c+c)[S.indexOf(c)+1]) ``` [Try it online!](https://tio.run/##dZI9cttADIV7nwKdyJFDTw4gz7hI4cqFJ1WSYrUEubBXC84CJKMud8gNcxEFS2tCKWNX/HkPHx/e8sVNTnymQT8lbvHU7U6yu5cm4xCdx@quuetv/e6@et5tHBKP7uHL49PXh83Wb3397bmh1OLPp67y9fbzj/rkOQlHbCL3VVfdAGweFWYnoAFhj6LAHSgdUG6BVmXmfCl9TxvYluELi@uxGGaSlg9Xw2elY44kIaG8D8CBfSjGPUbC7grxT6PkM7ZjJD2@CxF0wqk4I/VBryCr1rr8@mEOGTKlvtgCD3hdAyXFvBBQBkd5BcwIwbWAE@ajhgLYY8cZYbQmz2Li/5XL8RntnYsRei6mljJ6BWUI6CZMC@UDj0UztCWb3RH@/Pq9rpVAAmfroXgGzMTtso0wdC5bSa/4JmUUTHq2rLk0ODXzYTlBUrEdSKj8J25UI5Pag52KkCi2YPUW0x5LOsuGNOEFzda25BbBruUeJ4pWcHrrfbSPR6c2YvX2GZdvej4MLtNycCkem81NXZ/@Ag "JavaScript (Node.js) – Try It Online") [Answer] # Pyth, 17 bytes ``` em=.rQdrB"aeiou"1 ``` [Try it here](http://pyth.herokuapp.com/?code=em%3D.rQdrB%22aeiou%221&input=%22It%20was%20the%20best%20of%20times%2C%20it%20was%20the%20worst%20of%20times%2C%22&debug=0) ``` em=.rQdrB"aeiou"1 m For each string... rB"aeiou"1 ... in ['aeiou', 'AEIOU']... =.rQd ... cyclically rotate the characters in the input. e Take the last. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) 2.0, ~~25~~ 21 bytes I had fun golfing this one with Shaggy. ``` r\v@=`aeia`pu)g1+UbX ``` [Run it here.](https://ethproductions.github.io/japt/?v=2.0a0&code=clx2QD1gYWVpjGFgcHUpZzErVWJY&input=IlRoZSBxdWljayBicm93biBmb3gganVtcHMgb3ZlciB0aGUgbGF6eSBkb2cuIg==) [Answer] # Java 10, ~~97~~ 87 bytes ``` s->{for(var c:s){var t="AEIOUAaeioua"+c+c;System.out.print(t.charAt(t.indexOf(c)+1));}} ``` -10 bytes after being inspired by [*@Arnauld*'s JavaScript answer (his 60-bytes version)](https://codegolf.stackexchange.com/a/163172/52210). [Try it online.](https://tio.run/##hVRNb9QwEL33V4z2lKh0Ja6sirRUCHroh1Q4AQevM0mm63iC7SRNq5X4D/xD/sh27F3YZhFCShTbb97M87Mn96pXZ/fFequN8h6uFNmnEwCyAV2pNMJ1nAL0TAXoTNfKffkGPl/I6kZeeXxQgTRcg4Vz2Pqzt08lu6xXDvQbnz/FQTifLd9f3nxeKiTu1OxUn@rF3egDNnPuwrx1UjAL85h@GQdkC3y4KTOdn77O88Vms13sirXdykixfc2kqhHN2V2QFJVIU/lOcEAfstllgEF5CDXCShaASwjUoH8FdEAGdi@hr/YFpiqMyEC@4GbC2iMlsyFfW/RHTGxZ1zFihYawnHD/YGS1w6IzFMYp26PybGOIoaoOE/YBK5Rb/13ZRzuriNfc4nSr6WATFX2ryAlzQKhVAdijG0MdmSuUE0ToxKY9aPkYSbwBZaKMgYojWpBDHSAw1Kh6tIn@jxgRIzlFy6BG@PXjp@zAgq/ZyV4j2KIjLpJwz1DKJTK0xh3k0KMN@xBREmoVJKpJB0LBi1zyFM9bdUFSUpCJeO1JblwB4l0MWmHUI2qQeoxpZGsiUorKN46xJyPu2Z2pnZQzcut6FO8qh6mY5qZVjtJxWDPOZ6kxft@@T8L73pFew8rxYCXpA9x3TeuBxeyU1qjHEQqujpgf42bIw1BH92KgOOqCLB0FvmMVRrjS8Rv7dYqmpks9N12/dVw51TTRgNvu8dGIPUtbwAUXCB/YlLN9gx/aO7VaYu9aTf4Bu0azc535eeCL2LvOqTHL97WOG9zY7D/I5mSzfQY) **Explanation:** ``` s->{ // Method with character-array parameter and no return-type for(var c:s){ // Loop over the input characters var t="AEIOUAaeioua" // Temp-String containing the order of vowels // (including additional 'A' and 'a'), +c+c; // appended with two times the current character System.out.print( // Print: t.charAt( // The character in String `t` at index: t.indexOf(c)+1));}} // The (first) index of the current character in `t` + 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~13~~ 11 bytes ``` žMDÀ‡žMuDÀ‡ ``` [Try it online!](https://tio.run/##dZJBTsMwEEX3OYXVdYVgwQ3YsOAQTvITj@p6Is@kUXa9AyfgImwQF@lFyjitKAGx6lTvf8/3d@4fff2A8/nz/eXp43g6vtkwXqbzebPZPKubvDgNcDVEHXdOaQ/ZOrqRifNPVP1AvkcBE0nL@5XpSjrmSBISZG3EwE0oghqR0K2s34xSk9GOkXRemQVeOBVFpD7oynxjrc@7P3tlyJT6ggMPWF@TkiIvTsjgKW@rCS741uGAPGsoxhodZ7jRGrrCxL9JsU2w2cfoei6wpYxGnbIL8Aekxf2PxqLYkZZk8rM7HV8rSk4CZ7tnYQMycbukFnadz1bCDheUIUh6lWwrDV5NtF9eglQsKwmVd/aj2omk9sdaFhJF66y2IqpR0lgW0AF2il3LEtpK@y0zDhStuHTpc7Rl0atJrbY@Y9nV8H7wmZaHSHG@sy/tCw "05AB1E – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 20 bytes ``` T`_o`A\EI\OUAaei\oua ``` [Try it online!](https://tio.run/##dVJBbtwwDLzrFXzAon/YFkGzhyI5JLcFGtmiLXZl0aXodbyn/qE/7EdSylk0cYueJGtmyOHQgkrZv7w8PH3lp/3x5nC8e9x7pCNP9npQmH0BjQgNFgXuQGnAsgN6Q2aW95B7B/keKzBTCTxsRFekY05UYsayFeLIbayEBhNht5H@wSi3gmFKpMtGXNAXzpWRqI@6Eb9hwcvpn75lFMp9hSOPuB2TsqKsSiyjJ9m5GSH6AHhGWTRWYYMdC8JkCV3BzH8jVTaj3X1K0HMFAwm2CsoQ0Z8xr@r/cMyKlTQns1/g14@fjjKUyGJzVmxEIQ6r68LQebEQTvgKCRbMeqXsnEavRhrWTZAW80qF6p79pFaR1D4s5UJFMYDFVkkNVjfmBemMVsXGMofW0s56xzMlCy6/5jlZs@TVqBZbL7j2ankYvdC6iJyWD849GPf7RO0JGuE5W6Fn@DYNYwG2cNdSyV8WCNwb@7Z6pgJzrBFV0GITtScDP7LXBb609ex8i87tbw53j/ZP8@TcvXAvfhjqDPfT5ZJswn0O8IkDwmdO3W8 "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # APL+WIN, 55 bytes Prompts for input string: ``` i←(10≥n←'AEIOUaeiou'⍳s)/⍳⍴s←⎕⋄s[i]←'EIOUAeioua'[n~11]⋄s ``` [Answer] # Mumps, 38 bytes ``` R T W $TR(T,"AEIOUaeiou","EIOUAeioua") ``` Mumps doesn't normally add a carriage return, as I didn't see a requirement to separate input from output it does look a bit weird on first run. For example, the output for the last test case looks like this: ``` Programming Puzzles And Code GolfPrugremmong Pazzlis End Cudi Gulf ``` If you did want to add a carriage return, add two bytes thusly: ``` R T W !,$TR(T,"AEIOUaeiou","EIOUAeioua") ``` [Answer] # Vim + [tpope/vim-abolish](https://github.com/tpope/vim-abolish), 30 bytes ``` :%S/{a,e,i,o,u}/{e,i,o,u,a}/g<cr> ``` Alternate solution, also 30 bytes: ``` Oe,i,o,u<esc>|D:%s/{a,<C-r>"}/{<C-r>",a}/g ``` According to [meta](https://codegolf.meta.stackexchange.com/a/11751/31716), vim answers can use plugins with no byte penalty. This is not a vim answer, but a *vim + abolish* answer. --- Abolish is an extremely useful plugin. [This section of the README](https://github.com/tpope/vim-abolish#substitution) nicely describes how this command (the `Subvert` command) works. [Answer] # [CJam](https://sourceforge.net/p/cjam), 29 19 bytes ``` q"aeioua"_eu+_1m<er ``` [Try it online!](https://tio.run/##dZFBTsMwEEX3PYXVLRUSey7AKapp8hMPdTzBM2nUHXfghlykjNOKEhCrOHr/e/58N680XC5vWwLLRNs9pof90/CMcrlsXyzMpMEiwgFqQbpgPEB3ge9klvITbX4g6lHBzNrKsDLdSCeSWGOGro0YpYlVcEBidCvrN@PcFLRTYjuvzApSyVWRuI@2Mt9ZS@X4Z66OhXNfcZQR6zU5G8rihI7EZbeZESK1ASeUs8VqPKCTgjB5QzeY5Tepthl@ppRCLxW2XNBYMAkRdEJe3P9oPIpf6UlmOofP948N56BRiu9Z2YjC0i6pVUJHxUs44ooKFNlukt3GIpmLhuUl2NSzsnJ9Z5rMb2TzH29ZWQ1t8Nqq6ICaxrOAT/BbfC1P6CP9W884cfLi8rXPyYclMpd6bX3BMquRYaTCy0PkdH7cfgE "CJam – Try It Online") -10 bytes thanks to @Peter Taylor Explanation: ``` q # take all input "aeioua" # push vowel pairs _eu # duplicate, uppercase +_ # concatenate, duplicate again 1m< # rotate left by 1 er # transliterate ``` [Answer] # [AutoHotkey](https://autohotkey.com/docs/Hotstrings.htm), 24 bytes AuotHotkey automatically replaces letters in a case sensitive manner. ``` a::e e::i i::o o::u u::a ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes ``` k∨:½ƛǓ;∑Ŀ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=k%E2%88%A8%3A%C2%BD%C6%9B%C7%93%3B%E2%88%91%C4%BF&inputs=Programming%20Puzzles%20And%20Code%20Golf&header=&footer=) Basic transliteration. [Answer] # [Elm](http://elm-lang.org/), ~~127~~ ~~123~~ ~~121~~ ~~112~~ 103 bytes *9 bytes saved by [Hydrazer](https://codegolf.stackexchange.com/users/104014/)* ``` f a b=case a of c::d::e->if c==b then d else f(d::e)b _->b String.map(String.toList"aeiouaAEIOUA"|>f) ``` ## Explanation This Elm answer is a port of [my Haskell answer](https://codegolf.stackexchange.com/a/163155/56656). I am still learning Elm so there might be a good deal of golfing that can be done. There are a couple of differences here between Elm and Haskell. Elm does not allow multiple declarations of a function so we have to use `case` instead. Elm is also rather fussy about strings. They are not list of characters and thus have to be treated differently then lists. In fact in order to do any useful of manipulations on strings we pretty much have to just convert them to lists. Aside from that there are a couple of small differences `::` is the list cons operator and `(|>)=flip($)`. You can test the code [here](http://elm-lang.org/try), with the following wrapper: ``` import Html exposing (text) f a b=case a of c::d::e->if c==b then d else f(d::e)b _->b g=String.map(String.toList"aeiouaAEIOUA"|>f) main=g"It was a dark and stormy night"|>text ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` kv*kV* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrdiprVioiLCIiLCJUaGlzIGlzIHRoZSBmaXJzdCB0ZXN0IGNhc2UiXQ==) ``` * # Ring translate by kv # Lowercase vowels * # Ring translate by kV # Uppercase vowels ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 25 bytes ``` {y^'x[<x]x?y}"UAEIOuaeio" ``` [Try it online!](https://ngn.codeberg.page/k#eJx1VUGO20YQvO8rBkKA2IDh3FcBgnVg2D4E3kN8WmzgIdkUOxqy6ZlpUVzDQf6QH+YlqR4qWsrY1YUiq6qnp7o4bK+/zn/8eLz7+Xh//GX+tvl08/bDR/XEsrm6ytdff7ib/4rXrTtuP8t+++Jz6zlsj9t5G1/ef7vKd69+erH5kN3kk8sduYpSdtK6zD2lV44fkUniGtpcOfttVgy/I8MnTo30F9oT0ooETt1A6Uk9jVJ3xqsoMLUXFc4YD3WkRgPn+akaiXySwYiBd12+qPGINT7un+sijZGHnbE6GenSAh4yxVKA0ug5nvUTuc43jg4U59yZvqJWIjmFiSdwkO+RlXoiPPIhuJ0Yp+FIdXZZXEf+QEMp8gwHjaEy+pr87P79+5/zngaXOonwwCgjRZambCWJa32EQXtaoEiJhnyinLvKnc/g9mV0nBM2wIktH14zCnPGDeaROGVqHJw1UkXWGzojPtBjMWwZbaMBXO0/HTjA22GxXLF08BkKOLuLVJaspR995DKyIcyvNy9Ry+L6ERMhmwi7Cms7RSalZzgtj8ikcQ3938eKQTs2fJLUaH+hPSGtahDEldOTeh4VkQSv4iDcXlQ4Y4K4cuODrOK64pmfOhgxSInrk1hDiOszXSCuAsPB6nTkSwtkyBxLAU4jySqujFw1jg9scTV9xa1Gdt7iuoCDfo+s1BPjEVkU1TgN0mBRVNcxJjuUIs9w0Bgqo6+JLuIqFldd4spu5CjalK0kdS3SHWTPC4RMsMW1UFZxJcRV+zI6sbiqJLF8kM8oLBk3mEeSlLlxcNZIFVtv6IzlwKu4KuKqaABX+88HQVxlWCz3WDpQhgLO7iKXJWvtkWIpI1vieo/jdfM78v1Fud67Kso0IPxH9yeoaAWHRYl/8A8z7Nm9ttUhYPfFSxGoCRQCbwLFuEoDgUygEJQl3ts7ir1NnR0QVhGHRsx4tFR8b6aI4TYRK4ApAZd0KvBGfJ7db7VdW19TUb1RWh7i2lLNC9W+Lp/s66KFZHc3ducX+DbKLvq+tzPgVh8eAuZ3MzTuV2nIvZPQFtVtVLzkfW/W33qw0PxbY2nD7p2Cdf8fpmlK3Q==) [Answer] ## PHP, 90 Bytes [Try it online](https://tio.run/##RcixCsIwEIDhVzmKQw76Bi1IEREnu3QuMU3aQJoLl2Sw4rPHLOLyw/@FLZT@HGpN9ipZ8mDEKeJbq40gJk5ct5XM8jUr2p/Wa1F5jsHZJKY8yKu@2wdh@9efTRkRu08xohmZVpb7bv0KYz4OpyMMfoELLRpu5EyDXfkC) **Code** ``` function f($s){echo strtr($s,array_combine(str_split(UuAaEeIiOo),str_split(AaEeIiOoUu)));} ``` **Explanation** ``` function f($s){ echo strtr( $s, #The string to operate array_combine( #combining arrays str_split(UuAaEeIiOo), #splitting this strings str_split(AaEeIiOoUu)) # With array combine php creates an array like # ["U"=>"A", "a"=>"e"....and so on] # strtr can replace strings in a string, using an array with # the values to replace and with what replace each value. ); } ``` **75 Bytes if ran with `php -r` using `$argv`** ``` <?=strtr($argv,array_combine(str_split(UuAaEeIiOo),str_split(AaEeIiOoUu))); ``` [Answer] # [J](http://jsoftware.com/), 33 bytes ``` rplc'aeiou',&((;"0)1&|.)'AEIOU'"1 ``` [Try it online!](https://tio.run/##TcvBDsFAFIXhvac46cLVpJp2SywQkiZEIjzAdMxQ1K2Zqap49yoLLE7O4s93bLyQNEYDEAJEGLTrh5iuF/PGFGdJQmVcUtDt9YZe5MfdZ@jTeJastuTFjd9BR8kDQ4MSh0pYuINCqqwDa7gsVzZA9isVm/9EX71p47XM5Amp4eoCzXccy7yw4JsyH3sWjxo73oc/NWHhaizl@7WQipoX "J – Try It Online") [Answer] # [str](https://github.com/ConorOBrien-Foxx/str), 18 bytes ``` [aeiouaAEIOUA]#D#U ``` [Try it online!](https://tio.run/##dZExbsMwDEV3n0JA1qB3CNAOmTplKjoo8bdFRBYNkY7hrXfoDXsRl3KCJm7RyTLe/@Lnl2ie5zcP4sHvXvavh9375nlzmOe9utGL0wB3hKjjxil1kK2jOxk5P6LqAfkWBYwkNXcr0400zJEkJMjaiJ5PoQiOiIRmZf1hlE4Z9RBJp5VZ4IVTUURqg67Md1b7fP4zV/pMqS04cI/1mpQUeXFCek95W41wwdcOF@RJQzEe0XCGG6yhG0z8mxTbCDv7GF3LBdaUcVKn7AL8BWlx/6OxKHalJRn95L4@PitKTgJn27OwHpm4XlILu8ZnK@GMK8oQJL1JtpUGrybqlpcgFctKQuWd/aB2I6n9WMtCoqid1VZER5Q0lgV0gd1ia1lCG2nfcsaFohWXrn0ONix6NanV1mYss07c9T7T8hApTk/f "str – Try It Online") ## Explanation ``` implicit: over each character of the input: [aeiouaAEIOUA]#D#U [ ] push this string #D set this to the operation domain #U set the charcter to the next character in the domain ``` ]
[Question] [ Don't you love those [exploded-view diagrams](https://en.wikipedia.org/wiki/Exploded-view_drawing) in which a machine or object is taken apart into its smallest pieces? [![enter image description here](https://i.stack.imgur.com/6lcse.jpg)](https://i.stack.imgur.com/6lcse.jpg) Let's do that to a string! # The challenge Write a program or function that 1. inputs a string containing only **printable ASCII characters**; 2. dissects the string into **groups of non-space equal characters** (the "pieces" of the string); 3. outputs those groups in any convenient format, with some **separator between groups**. For example, given the string ``` Ah, abracadabra! ``` the output would be the following groups: ``` ! , A aaaaa bb c d h rr ``` Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below. # Rules The **input** should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes. You can assume that the input contains **at least one non-space character**. The **output** should consist of **characters** (even if the input is by means of ASCII codes). There has to be an unambiguous **separator between groups**, different than any non-space character that may appear in the input. If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation. A separator **between characters** of each group is **optional**. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups. Other than that, the format is flexible. Here are some examples: * The groups may be strings separated by newlines, as shown above. * The groups may be separated by any non-ASCII character, such as `¬`. The output for the above input would be the string: ``` !¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr ``` * The groups may be separated by *n*>1 spaces (even if *n* is variable), with chars between each group separated by a single space: ``` ! , A a a a a a b b c d h r r ``` * The output may also be an array or list of strings returned by a function: ``` ['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr'] ``` * Or an array of char arrays: ``` [['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']] ``` Examples of formats that are not allowed, according to the rules: * A comma can't be used as separator (`!,,,A,a,a,a,a,a,b,b,c,d,h,r,r`), because the input may contain commas. * It's not accepted to drop the separator between groups (`!,Aaaaaabbcdhrr`) or to use the same separator between groups and within groups (`! , A a a a a a b b c d h r r`). The groups may appear in **any order** in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic. Note that the input cannot contain newline characters, and `A` and `a` are different characters (grouping is **case-sentitive**). Shortest code in bytes wins. # Test cases In each test case, first line is input, and the remaining lines are the output, with each group in a different line. * Test case 1: ``` Ah, abracadabra! ! , A aaaaa bb c d h rr ``` * Test case 2: ``` \o/\o/\o/ /// \\\ ooo ``` * Test case 3: ``` A man, a plan, a canal: Panama! ! ,, : A P aaaaaaaaa c ll mm nnnn p ``` * Test case 4: ``` "Show me how you do that trick, the one that makes me scream" she said "" , S aaaaa cc dd eeeeeee hhhhhh ii kk mmmm n ooooo rr ssss tttttt u ww y ``` [Answer] # Python 3.5+, ~~77~~ ~~46~~ ~~44~~ 41 bytes ``` lambda s:[a*s.count(a)for a in{*s}-{' '}] ``` Pretty simple. Goes through the unique characters in the string by converting it to a set (using Python 3.5's extended iterable unpacking), then uses a list comprehension to construct the exploded diagrams by counting the number of times each character occurs in the string with `str.count`. We filter out spaces by removing them from the set. The order of the output may vary from run to run; sets are unordered, so the order in which their items are processed, and thus this answer outputs, cannot be guaranteed. This is a lambda expression; to use it, prefix `lambda` with `f=`. ~~[Try it on Ideone!](http://ideone.com/axnIfH)~~ Ideone uses Python 3.4, which isn't sufficient. Usage example: ``` >>> f=lambda s:[a*s.count(a)for a in{*s}-{' '}] >>> f('Ah, abracadabra!') [',', 'A', 'aaaaa', 'd', '!', 'bb', 'h', 'c', 'rr'] ``` *Saved 3 bytes thanks to @shooqie!* [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 bytes ``` ḟ⁶ṢŒg ``` [Try it online!](http://jelly.tryitonline.net/#code=4bif4oG24bmixZJn&input=&args=J0EgbWFuLCBhIHBsYW4sIGEgY2FuYWw6IFBhbmFtYSEn) It does return an array, just that when it is printed to STDOUT, the separator is gone. This is indeed a function that can be called [as such](http://jelly.tryitonline.net/#code=4bif4oG24bmixZJnCsOHxZLhuZg&input=&args=J0EgbWFuLCBhIHBsYW4sIGEgY2FuYWw6IFBhbmFtYSEn) (in Jelly, each line is a function). ``` ḟ⁶ṢŒg ḟ⁶ filter out spaces Ṣ sort Œg group ``` [Answer] # Retina, 13 bytes ``` O`. !`(\S)\1* ``` The sorting is very easy (it's a builtin), it's separating the letters that takes 9 bytes. [Try it online!](http://retina.tryitonline.net/#code=T2AuCiFgKFxTKVwxKg&input=QWgsIGFicmFjYWRhYnJhIQ) The first line s`O`rts all matches of the regex `.` (which is every character), giving us `!,Aaaaaabbcdhrr`. Match is the default stage for the last line of a program, and `!` makes it print a linefeed-separated list of matches of the regex. The regex looks for one or more instances of a non-space character in a row. [Answer] # [Perl 6](http://perl6.org), 28 bytes ``` *.comb(/\S/).Bag.kv.map(*x*) ``` Note that [Bag](https://docs.perl6.org/type/Bag) like a [Hash](https://docs.perl6.org/type/Hash) or [Set](https://docs.perl6.org/type/Set) is unordered so the order of results is not guaranteed. ## Explanation: ``` # Whatever lambda 「*」 # grab the characters *.comb( # that aren't white-space characters /\S/ ) # ("A","h",",","a","b","r","a","c","a","d","a","b","r","a","!") # Turn into a Bag ( weighted Set ) .Bag # {"!"=>1,","=>1,"A"=>1,"a"=>5,"b"=>2,"c"=>1,"d"=>1,"h"=>1,"r"=>2} # turn into a list of characters and counts .kv # ("!",1,",",1,"A",1,"a",5,"b",2,"c",1,"d",1,"h",1,"r",2) # map over them 2 at a time .map( # string repeat the character by the count * x * ) # ("!",",","A","aaaaa","bb","c","d","h","rr") ``` [Answer] # Vim, ~~50~~, 46 bytes ``` i <esc>:s/./&\r/g :sor qq:%s/\v(.)\n\1/\1\1 @qq@qD ``` Explanation/gif will come later. [Answer] ## Pyth, 6 ``` .gk-zd ``` [Try it here](https://pyth.herokuapp.com/?code=.gk-zd&input=Ah%2C%20abracadabra%21&debug=0) or run a [Test Suite](https://pyth.herokuapp.com/?code=.gk-zd&test_suite=1&test_suite_input=Ah%2C+abracadabra%21%0A%5Co%2F%5Co%2F%5Co%2F%0AA+man%2C+a+plan%2C+a+canal%3A+Panama%21%0A%22Show+me+how+you+do+that+trick%2C+the+one+that+makes+me+scream%22+she+said&debug=0). Pretty simple, `-zd` removes spaces from the input, and `.gk` groups each remaining element by its value. Unfortunately, I haven't found a way to make use of auto-fill variables. Note that the output is shown as Python strings, so certain characters (read: backslashes) are escaped. If you want it to be more readable, add a `j` to the beginning of the code. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), ~~14~~ 7 bytes **7 bytes thanks to Fatalize.** ``` :@Sxo@b ``` [Try it online!](http://brachylog.tryitonline.net/#code=OkBTeG9AYg&input=IkEgbWFuLCBhIHBsYW4sIGEgY2FuYWw6IFBhbmFtYSEi&args=Wg) ``` :@Sxo@b :@Sx remove spaces o sort @b group ``` [Answer] ## Haskell, 38 bytes ``` f s=[filter(==c)s|c<-['!'..],elem c s] ``` Basically [nimi's solution](https://codegolf.stackexchange.com/a/90993/20260), but explicitly checking only letters appearing in the string. [Answer] ## JavaScript (ES6), 41 bytes ``` s=>[...s].sort().join``.match(/(\S)\1*/g) ``` [Answer] # [2sable](http://github.com/Adriandmen/2sable), 7 bytes Code: ``` Úð-vyÃ, ``` Explanation: ``` Ú # Uniquify the string, aabbcc would result into abc ð- # Remove spaces vy # For each character... à # Keep those in the string, e.g. 'aabbcc', 'a' would result into 'aa' , # Pop and print with a newline ``` Uses the **CP-1252** encoding. [Try it online!](http://2sable.tryitonline.net/#code=w5rDsC12ecODLA&input=QW5kIHRoZW4gRGVubmlzIHNhaWQ6ICJheXkgbG1hbywgbGV0IG1lIG91dGcwbGYgdSBpbiBqZWx5Ig) [Answer] ## Haskell, 40 bytes ``` f x=[v:w|d<-['!'..],v:w<-[filter(==d)x]] ``` Usage example: `f "Ah, abracadabra!"`-> `["!",",","A","aaaaa","bb","c","d","h","rr"]`. The pattern `v:w` matches only list with at least one element, so all characters not in the input are ignored. Also 40 bytes: ``` import Data.List group.sort.filter(>' ') ``` [Answer] # Ruby, 41 + 1 = 42 bytes +1 byte for `-n` flag. ``` gsub(/(\S)(?!.*\1)/){puts$1*$_.count($1)} ``` Takes input on stdin, e.g.: ``` $ echo 'Ah, abracadabra!' | ruby -ne 'gsub(/(\S)(?!.*\1)/){puts$1*$_.count($1)}' A h , c d bb rr aaaaa ! ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), 49 bytes ``` i:0(?v 84}0~/&{!* v!?: <}/?=&:&:< >&1+&}aol1-?!;^ ``` Very spaciously wasteful in the output, but i assume is still allowed given the lenience of the rules Explanation: ``` i:0(?v Collects text from input 84}0~/&{!* adds 32 (first ascii starting at space) to register and 0 to stack v!?: <}/?=&:&:< checks all characters to the current register, if equal: o prints the character and continues looping >&1+&}aol1-?!;^ when all characters are checked, adds 1 to register, prints a newline, checks the stack length to halt the program if 0, and starts looping again ``` fit some things in pretty tight, even using jumps to get around some functions so i could run the pointer vertically. Basically this puts each ASCII character on its own newline, and if none of that character exists, the line will be blank [Try it online](https://fishlanguage.com/playground/ZmDkCSR8jYJqHsvJ9) Edit: i was wrong there was an error in the code what would cause it to never complete if there was a space in the input [Answer] ## PowerShell v2+, 44 bytes ``` [char[]]$args[0]-ne32|group|%{-join$_.Group} ``` Takes input `$args[0]` as a command-line argument literal string. Casts that as a `char`-array, and uses the `-n`ot `e`qual operator to pull out spaces (ASCII `32`). This works because casting has a higher order precedence, and when an array is used as the left-hand operator with a scalar as the right-hand, it acts like a filter. We pass that array of characters to `Group-Object`, which does exactly what it says. Note that since we're passing *characters*, not strings, this properly groups with case-sensitivity. Now, we've got a custom object(s) that has group names, counts, etc. If we just print that we'll have a host of extraneous output. So, we need to pipe those into a loop `|%{...}` and each iteration `-join` the `.Group` together into a single string. Those resultant strings are left on the pipeline, and output is implicit at program completion. ### Example ``` PS C:\Tools\Scripts\golfing> .\exploded-view-of-substrings.ps1 'Programming Puzzles and Code Golf' PP rr ooo gg aa mm i nn u zz ll ee s dd C G f ``` [Answer] # C# ~~125~~ 98 Bytes ``` using System.Linq;s=>s.GroupBy(c=>c).Where(g=>g.Key!=' ').Select(g=>new string(g.Key,g.Count()))); ``` ## Explanation ``` //Using anonymous function to remove the need for a full signature //And also allow the implicit return of an IEnumerable s => //Create the groupings s.GroupBy(c => c) //Remove spaces .Where(g=> g.Key!=' ') //Generate a new string using the grouping key (the character) and repeating it the correct number of times .Select(g => new string(g.Key, g.Count())); ``` * Thanks to @TheLethalCoder who suggested the use of an anonymous function, which also allowed me to remove the `ToArray` call and just implicitly return an IEnumerable which collectively saves 27 bytes [Answer] # R, ~~198~~ ~~189~~ ~~96~~ 95 bytes ``` for(i in unique(a<-strsplit(gsub(" ","",readline()),"")[[1]]))cat(rep(i,sum(a==i)),"\n",sep="") ``` **Ungolfed :** ``` a<-strsplit(gsub(" ","",readline()),"")[[1]] #Takes the input from the console for(i in unique(a)) #loop over unique characters found in variable a cat(rep(i,sum(a==i)),"\n",sep="") # print that character n times, where n was the number of times it appeared ``` ~~This solution is currently not entirely working, when `\` are involved.~~ *Now it is !* Thank **a lot** you to @JDL for golfing out *102* bytes ! [Answer] # Swift, ~~105~~ 91 bytes Thanks to @NobodyNada for 14 bytes :) Yeah, I'm pretty new to Swift... ``` func f(a:[Character]){for c in Set(a){for d in a{if c==d && c != " "{print(c)}} print("")}} ``` Characters within a group are separated by a single newline. Groups are separated by two newlines. [Answer] # Mathematica, 36 bytes Built-in functions `Gather` and `Characters` do most of the work here. ``` Gather@Select[Characters@#,#!=" "&]& ``` [Answer] # Pyth, 5 bytes ``` .gksc ``` [Try it here!](https://pyth.herokuapp.com/?code=.gksc&input=%27%22Show+me+how+you+do+that+trick%2C+the+one+that+makes+me+scream%22+she+said%27&debug=0) Takes input as a Python string (i.e. wrapped in quotes, escaped quotes and slashes as necessary). Explanation: ``` c Split (implied) input on whitespace s Sum together .gk Group by value ``` If you guarantee at least one space in the input, there's a 4-byte solution: ``` t.gk ``` [Try it here!](https://pyth.herokuapp.com/?code=t.gk&input=%27%22Show+me+how+you+do+that+trick%2C+the+one+that+makes+me+scream%22+she+said%27&debug=0) Explanation: ``` .gk (Q) groups the characters in the string by their value this sorts them by their value, which guarantees that spaces are first t Remove the first element (the spaces) ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 11 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Function returning list of strings. ``` (⊂∩¨∪)~∘' ' ``` `(⊂∩¨∪)` the intersection of the entirety and its unique characters `~∘' '` except spaces [TryAPL online!](http://tryapl.org/?a=%28%28%u2282%u2229%A8%u222A%29%7E%u2218%27%20%27%29%A8%27Ah%2C%20abracadabra%21%27%20%27%5Co/%5Co/%5Co/%27%20%27A%20man%2C%20a%20plan%2C%20a%20canal%3A%20Panama%21%27%20%27%22Show%20me%20how%20you%20do%20that%20trick%2C%20the%20one%20that%20makes%20me%20scream%22%20she%20said%27&run) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ðoÑ ``` [Try it online!](https://Not-Thonnu.github.io/run#P2hlYWRlcj0mY29kZT0lQzMlQjBvJUMzJTkxJmZvb3Rlcj0maW5wdXQ9QWglMkMlMjBhYnJhY2FkYWJyYSEmZmxhZ3M9) `ðo` removes spaces from the string. `Ñ` is a built-in for "group by". There is no body so it just groups identical characters together. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ñ x ó¥ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=8SB4IPOl&input=IkFoLCBhYnJhY2FkYWJyYSEi) [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), ~~53~~ ~~50~~ 46 bytes ``` l'~')?v0 v?(0:i<]r+1r[ \~rvol-1 ^?:<;?('!'l~oa ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoibCd+Jyk/djBcbnY/KDA6aTxdcisxcltcblxcfnJ2b2wtMVxuXj86PDs/KCchJ2x+b2EiLCJpbnB1dCI6In5+fiEhIUJCQiBDQ0NlZWUiLCJzdGFjayI6IjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwICIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) Finally beat the current fish answer. Note the link pre-populates the stack to make it faster but this is unnecessary for the correctness of the program. Each element of the stack stores how often the nth character appears in the input. [![enter image description here](https://i.stack.imgur.com/cWriH.png)](https://i.stack.imgur.com/cWriH.png) The top row pushes `ord('~')` 0s to the stack. The second row reads the input. Use `[r1+r]` to get the nth element of the stack, add 1 to it, then put it back into place. The left (red) half of the third row reverses the stack so the higher valued items are on the top. Now we know that the length of the stack is the character code of the count the top element represents. This allows very convenient printing. The left (grey) half of the bottom row checks if the count of the nth character is 0. If so go to the right half of the third row. The right (blue) half of the bottom row prints a line break `ao`. Then pops the top of the stack. If we now have less than `ord('!')` items on the stack only spaces remain and we exit (since we shouldn't print spaces) The right half of the third row runs if there is more than one occurrence of the top character. If so, we subtract one occurrence, then print the length of the stack as a character. [Answer] # [R](https://www.r-project.org), 65 bytes ``` cat(strrep(z<-names(y<-table(strsplit(readline(),""))),y)[z>" "]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMFNk6LUxJSczLxU27TSvOSSzPw8DU0lR4XcxDwdhUSFghwInZyYl5hjpRAApHITFZWWlpak6VrcdExOLNEoLikqSi3QqLLRBcqlFmtU2uiWJCblpIIkigtyMks0YDZoaOooKWlqaupUakZX2SkpKMVqQgxaAKWgNAA) Full program that accepts input by reading a line from the terminal, and outputs a space-separated string of character-groups. The input & output are chosen to be directly comparable to the earlier R answers of [Billywob](https://codegolf.stackexchange.com/a/91944/95126) and [Frédéric](https://codegolf.stackexchange.com/a/91000/95126). Nevertheless, we could also golf a little further within the original rules, by writing a function that accepts input as an array of characters, and outputs an array of strings: # [R](https://www.r-project.org), 49 bytes ``` function(x)strrep(z<-names(y<-table(x)),y)[z>" "] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3DdNK85JLMvPzNCo0i0uKilILNKpsdPMSc1OLNSptdEsSk3JSgVKaOpWa0VV2SgpKsVCNTpl5BaUltkA9xQU5mSUaSo4KuYl5OgqJCgU5EDo5MS8xx0ohAEjlJioq6SgpaUZHG8bGcqVpgPVqQkxasABCAwA) Note that this could be further shortened to [42 bytes](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3tWI0KjSLS4qKUgs0qmx08xJzU4s1Km10SxKTclKBUpo6lZrRVXZKCkqxUB1OmXkFpSW2QD3FBTmZJRpKjgq5iXk6CokKBTkQOjkxLzHHSiEASOUmKirpKClpRkcbxsZypWmA9WpCTFqwAEIDAA) using a version of R that is more-recent than the challenge to allow us to exchange `function` for `\`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes Here's some JS solutions without regex. Uses linebreak as separators between groups. ``` s=>[...s].sort().map(c=>b==(b=c)?c:` `+c,b=0).join``.trim() ``` [Try it online!](https://tio.run/##NY9Bb8IwDIXv/RVeT4koYWemgDhwR9qRIsV1U1po4irJNvHru1QVB@uznp/19B74i5HCMKWt59bOnZ6jPlyVUvGmIockpHI4CdKHRmvRaJJH2pvCbKhq9KdUDx68MSqFwQk5f10LAHPqK8AmIGG74MNUi1rXvHvPqpzAoc9WmMaVhB7HPVwy3Put/O75D5yFBS/@gZYh9ZggR9KzyrsF9nbVHD5tXMy5k0VXQszXiENripvqOJyRepELEvvIo1Uj30UnotyUtS@lnP8B "JavaScript (Node.js) – Try It Online") --- Alternative that might not be supported by some browsers because of `at(-1)` (**62 bytes**) : ``` s=>[...s].sort().map(c=>a+=a.at(-1)==c?c:` `+c,a="")&&a.trim() ``` Try it: ``` f=s=>[...s].sort().map(c=>a+=a.at(-1)==c?c:` `+c,a="")&&a.trim() ;[ `Ah, abracadabra!`, `\\o/\\o/\\o/`, `A man, a plan, a canal: Panama!`, `"Show me how you do that trick, the one that makes me scream" she said` ].forEach(s=>console.log(f(s))) ``` --- Alternative funny solution (**67 bytes**) : ``` s=>[...s].sort().map(a=c=>c!=' '?a[c]=[a[c]]+c:0)&&Object.values(a) ``` [Try it online!](https://tio.run/##NY@xbsMwDET3fAWTIZFQV@2cQikydG6Bjo4BM7RcO5FEQ1JS9OtdCUYG8hHHu@EueMdIYZzSs@fOzL2eoz7USqnYqMghCakcTgI16QOt9Q5271hTo@uymyfav8rt9vN8MZTUHe3NRIFyfqtXAO1xqADPAQm7gnVbFfV04pfHLMoRHPpshckuJPRo9/CV4R6xzffAv@AMFPzxDTqGNGCCFEa6Vvk2wN4smsOricWcuxl0G4j5G3Hs2lWjeg4fSIPIRYl9ZGuU5R/RiyilnP8B "JavaScript (Node.js) – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 10 bytes -1 byte from @doug's improvement ``` {.x" "_=x} ``` [Try it online!](https://ngn.codeberg.page/k#eJylkstugzAQRff+ionVRSpBXKmbBtRF/iBSlknUOMYEBMYUO4UoSr+99jhpHpsuegEdgx+6d4Y8OU4GCvTjfTgRYpPj0/Lw3SU5AAzpRlfpeJPzsk6H9JB2z+sTsUs6KyLg244LnnmMKIFxRGcOENEiIPKg3AtH2y2i68K0CMgCRvR57Q9erTS7PP5Q98ELd2qtkYwxvxrQCCjeOC/Q1oGCN7xOYO6g7nxRpa6Gfk01TjiIomCkxbe6vjOZBMxvvKJZuih0D0qCx0HvIdNgC27BdqWoIjeWoBsZvileSeMXG9FJrlYUjJs2vMxCUHeF8xdooUBdgp+j9/05yjmMDAr7DgF7nMmwsNSiHjoRWkDLEiEwJK2qm7ZFNFTFOGFaRgprW5MwJnQmd7rOJ8ZyUclBFLzZyYnQin3upbGlbgybvkzfXpkc2tqtzuKvUvaxzmMeG1eZZkfI4w9EfM/xJn+0lPyn6NeaE/IDwivNJg==) Returns characters in order of appearance in original input. * `=x` group the input, returning a dictionary mapping distinct values to the indices in which they appear in the input * `" "_` remove the space character * `.x` index back into the input using the indices returned above, and return just the values of the dictionary (i.e. the list of repeated characters) [Answer] # [Octave](https://www.gnu.org/software/octave/), 61 bytes ``` @(x)mat2cell(y=strtrim(sort(x)),1,diff(find([1 diff(+y) 1]))) ``` This is an anoymous function that takes a string as input and outputs a cell arrray of strings. [Try at Ideone](http://ideone.com/WoRneV). ### How it works * `sort` sorts the input string. In particular, spaces will be at the beginning. * `strtrim` removes leading spaces. * `diff(+y)` computes consecutive differences between characters (to detect group boundaries)... * ... so `diff(find([1 diff(+y) 1])` gives a vector of group sizes. * `mat2cell` then splits the sorted string into chunks with those sizes. [Answer] # Processing, 109 bytes ``` void s(char[] x){x=sort(x);char l=0;for(char c:x){if(c!=l)println();if(c!=' '&&c!='\n'&&c!='\t')print(c);l=c;}} ``` Its the brute force approach, sort the array, then loop through it. If it doesn't match the last character printed, print a newline first. If it is whitespace, skip the printing step. [Answer] # Javascript (using external Library - Enumerable) (~~78~~ 67 bytes) ``` n=>_.From(n).Where(y=>y!=' ').GroupBy(x=>x).WriteLine(y=>y.Write()) ``` Link to lib: <https://github.com/mvegh1/Enumerable> Code explanation: This is what Enumerable was made to do! Load the string into the library, which converts it to a char array. Filter out the white space entries. Group by char. Write each group to a line, according to the specified predicate. That predicate says to join all the elements of the current group into a string, without a delimiter. [![enter image description here](https://i.stack.imgur.com/QGLlE.png)](https://i.stack.imgur.com/QGLlE.png) [Answer] ## Bash + coreutils, ~~53~~ ~~50~~ 45 bytes ``` sed 's: ::g;s:\(.\)\1*:& :g'<<<`fold -1|sort` ``` There is no separator between the characters of a group and the groups are separated by space. There is one trailing group separator, but as I understood that's acceptable. **Run:** ``` ./explode_view.sh <<< '\o /\ o /\ o k' ``` **Output:** ``` // \\\ k ooo ``` ]
[Question] [ Objectives: Output a String which contains every positive integer strictly below 1000. The obvious answer would be to concatenate every one of them, and that would create a String of 2890 characters (thanks manatwork), to avoid this kind of easy answer, the length of the string must be under 1500 characters. Here is a straightforward Java code which outputs a 1200 chars String. ``` import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static org.junit.Assert.assertTrue; /** * Created with IntelliJ IDEA. * User: fab * Date: 05/11/13 * Time: 09:53 * To change this template use File | Settings | File Templates. */ public class AStringToContainThemAll { @Test public void testsubStrings() throws Exception { String a = generateNewString(); boolean cool = true; for (int i = 0; i < 1000; i++) { assertTrue(a.contains(Integer.toString(i))); } } private String generateNewString() { List<Integer> myTree = new ArrayList<Integer>(); String finalString = new String("100"); for (int i = 10; i < 1000; i++) { myTree.add(i); } while (myTree.size() > 0) { if (finalString.contains(Integer.toString(myTree.get(0)))) { myTree.remove(0); } else { String substringLong = finalString.substring(finalString.length() - 2, finalString.length()); boolean found = false; loop: for (Integer integer : myTree) { if (integer.toString().startsWith(substringLong) && !finalString.contains(integer.toString())) { finalString = finalString.concat(integer.toString().substring(2, 3)); myTree.remove(integer); found = true; break loop; } } if(! found){ finalString = finalString.concat(myTree.get(0).toString()); myTree.remove(0); } } } return finalString; } } ``` Shortest code win, bonus point for the shortest String! [Answer] ## GolfScript (35 31 26 chars) ``` 10,{:x),{:&x=x+,{x&@}/}/}/ ``` Output is ``` 000100110111200201210211220221222300301302310311312320321322330331332333400401402403410411412413420421422423430431432433440441442443444500501502503504510511512513514520521522523524530531532533534540541542543544550551552553554555600601602603604605610611612613614615620621622623624625630631632633634635640641642643644645650651652653654655660661662663664665666700701702703704705706710711712713714715716720721722723724725726730731732733734735736740741742743744745746750751752753754755756760761762763764765766770771772773774775776777800801802803804805806807810811812813814815816817820821822823824825826827830831832833834835836837840841842843844845846847850851852853854855856857860861862863864865866867870871872873874875876877880881882883884885886887888900901902903904905906907908910911912913914915916917918920921922923924925926927928930931932933934935936937938940941942943944945946947948950951952953954955956957958960961962963964965966967968970971972973974975976977978980981982983984985986987988990991992993994995996997998999 ``` (1020 chars) This is a variant on the Lyndon word concatenation approach: rather than use the primitive 1-char words it uses multiples of 111 for shorter code but repeated occurrences of those numbers; and rather than use minimal elements of the conjugacy groups it uses maximal elements, because that shortens the loops. --- ``` 10,:^{:x^>{x.@:&<+^>{.x>{x&@}*}/}/}%3>0. ``` at 40 chars (can probably still be improved) generates an optimal string, which is of length 999 chars: ``` 100200300400500600700800901101201301401501601701801902102202302402502602702802903103203303403503603703803904104204304404504604704804905105205305405505605705805906106206306406506606706806907107207307407507607707807908108208308408508608708808909109209309409509609709809911121131141151161171181191221231241251261271281291321331341351361371381391421431441451461471481491521531541551561571581591621631641651661671681691721731741751761771781791821831841851861871881891921931941951961971981992223224225226227228229233234235236237238239243244245246247248249253254255256257258259263264265266267268269273274275276277278279283284285286287288289293294295296297298299333433533633733833934434534634734834935435535635735835936436536636736836937437537637737837938438538638738838939439539639739839944454464474484494554564574584594654664674684694754764774784794854864874884894954964974984995556557558559566567568569576577578579586587588589596597598599666766866967767867968768868969769869977787797887897987998889899900 ``` Trying to make this do reverse strings runs into problems with omitting the multiples of 111. To see that 999 is the optimal length (since my brief comments above don't convince everyone), start from the full de Bruijn sequence which (taken as a cyclic string) contains every 3-digit sequence of characters from 0 to 9. Since there are 1000 of them, it must be at least 1000 characters long; that it can be precisely 1000 characters long is usually proven by an Eulerian walk on a graph whose nodes are two-digit sequences `xy` with 10 edges, each labelled with one digit `z`, which take `xy` to `yz`. We don't need sequences beginning `0`, so given a de Bruijn sequence we can rotate to put `000` at the end. Then we don't need either of the sequences which wrap round to the beginning, but we do need two of the `0`s to finish the sequence starting with the digit before `000`, so we can delete one of them to get a 999-character string. Every remaining `0` is used in a number which doesn't begin with `0`. [Answer] ### GolfScript, 17 characters ``` 999,{`1$1$?0<*+}/ ``` Plain approach to add each number if not already present in the string (note: 999 is not checked or added, but contained already in the output). Output is 1133 characters: ``` 01234567891011131415161718192021222425262728293032333536373839404344464748495054555758596065666869707677798087889099100102103104105106107108109110112114115116117118119120124125126127128129130132133134135136137138139140142143144145146147148149150152153154155156157158159160162163164165166167168169170172173174175176177178179180182183184185186187188189190193194195196197198199200203204205206207208209219220221223225226227228229230231235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290294295296297298299300304305306307308309311329330332334336337338339340342346347348349350354355356357358359360364365366367368369370374375376377378379380384385386387388389390395396397398399400405406407408409422439440443445447448449450453457458459460465466467468469470475476477478479480485486487488489490496497498499500506507508509533549550554556558559560564568569570576577578579580586587588589590597598599600607608609644659660665667669670675679680687688689690698699700708709755769770776778780786790797799800809866877879880887888897898899900908932943954965976979987989 ``` [Answer] I don't have any code, but I thought someone might appreciate this intuitive proof that 999 characters is the lower bound to the length of the output: First, every 1- and 2-digit number is part of a 3-digit number, so ignore everything less than 100. 100-999 inclusive is 900 3-digit numbers. The most optimal way to solve the problem is if every character is used as much as possible. That means the numbers overlap as much as possible, like this: ``` 123 234 345 ``` The first number will therefore add 3 characters, and each subsequent number will add 1 character. That gives 3 + 899 = 902 characters as a lower bound. However, when there is a zero, we can't use it to start a new 3-digit number. We can reuse it in the middle of another 3-digit number though, as long as it is not followed by another zero: ``` 120 203 <- Ok. 034 <- not a number 100-999. ``` But: ``` 100 002 <- not a number 100-999. 023 <- not a number 100-999. ``` Therefore, each zero which appears in the output extends the output by 1 character - except for the last two characters which may be zero as they do not overlap any further numbers: ``` ??? ??0 ?00 ``` There are 81 numbers with strictly one zero in the middle (?0?), 81 with strictly one zero at the end (??0), and 9 with two zeros (?00). Every ??0 number can share a zero with either a ?0? number or a ?00 number, but not both. ?0? and ?00 can never share zeros, so there must be at least 81 + 9\*2 zeros in the output. This gives a lower bound of 3 + 899 + 81 + 9\*2 - 2 = 999 characters. Apologies if this is considered off-topic, but it was too long to fit in a comment. [Answer] ## Golfscript - 13 bytes, 1315 output ``` 991,{`.$2>>}, ``` The above selects those numbers from *0-990* whose first digit is the largest digit of the number, i.e. the last digit of the sorted string representation is lexicographically less than the string itself. The logic is the following: For a 3 digit number *abc*, if *a* is not the largest digit of the number, the number my be skipped, because it will be covered by one of two cases later on: 1. ***b < c*** (e.g. *123*) Because *c* is the largest digit, the number *cab* will not be skipped. In this example *312* will not be skipped, nor will the next value *313*, which when concatenated (*312 313*) contains *123*. 2. ***b ≥ c*** (e.g. *132*) Because *b* is the largest digit, the number *bca* will not be skipped. In this example *321* will not be skipped, nor will the next value *322*, which when concatenated (*321 322*) contains *132*. If *b = c* (e.g. *122*), this case also applies. The value *bca* will not be skipped, as before, and because *a* is necessarily less than *b*, *bc<a+1>* will not be skipped either. In this example, *221 222* contains *122*. Because the above code tests the third digit, rather than strictly the last, all values from *0-99* are included in the result. The values from *1-99* may be skipped, however, because if every 3-digit sequence is present, then every 1-digit and 2-digit sequence must also be present. The values from *991-999* may also be skipped, as the are generated by (*909 910*, *919 920*, ... *989 990*). At 1315 bytes of output, this is comfortably under the problem's specification of less than 1500. Output: ``` 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101110111200201202210211212220221222300301302303310311312313320321322323330331332333400401402403404410411412413414420421422423424430431432433434440441442443444500501502503504505510511512513514515520521522523524525530531532533534535540541542543544545550551552553554555600601602603604605606610611612613614615616620621622623624625626630631632633634635636640641642643644645646650651652653654655656660661662663664665666700701702703704705706707710711712713714715716717720721722723724725726727730731732733734735736737740741742743744745746747750751752753754755756757760761762763764765766767770771772773774775776777800801802803804805806807808810811812813814815816817818820821822823824825826827828830831832833834835836837838840841842843844845846847848850851852853854855856857858860861862863864865866867868870871872873874875876877878880881882883884885886887888900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990 ``` ### Variation #1 **14 bytes, 1233 output** ``` 991,{`.$-1>>}, ``` By selecting strictly the last digit for comparison, rather than the third, many of the unnecessary values less than *100* are eliminated, shortening the resulting string. ``` 101120212230313233404142434450515253545560616263646566707172737475767780818283848586878890919293949596979899100101110111200201202210211212220221222300301302303310311312313320321322323330331332333400401402403404410411412413414420421422423424430431432433434440441442443444500501502503504505510511512513514515520521522523524525530531532533534535540541542543544545550551552553554555600601602603604605606610611612613614615616620621622623624625626630631632633634635636640641642643644645646650651652653654655656660661662663664665666700701702703704705706707710711712713714715716717720721722723724725726727730731732733734735736737740741742743744745746747750751752753754755756757760761762763764765766767770771772773774775776777800801802803804805806807808810811812813814815816817818820821822823824825826827828830831832833834835836837838840841842843844845846847848850851852853854855856857858860861862863864865866867868870871872873874875876877878880881882883884885886887888900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990 ``` ### Variation #2 **16 bytes, 1127 output** ``` 991,99>{`.$2>>}, ``` By prying off all values less than *99* beforehand, the resulting string can be shortened even more. ``` 99100101110111200201202210211212220221222300301302303310311312313320321322323330331332333400401402403404410411412413414420421422423424430431432433434440441442443444500501502503504505510511512513514515520521522523524525530531532533534535540541542543544545550551552553554555600601602603604605606610611612613614615616620621622623624625626630631632633634635636640641642643644645646650651652653654655656660661662663664665666700701702703704705706707710711712713714715716717720721722723724725726727730731732733734735736737740741742743744745746747750751752753754755756757760761762763764765766767770771772773774775776777800801802803804805806807808810811812813814815816817818820821822823824825826827828830831832833834835836837838840841842843844845846847848850851852853854855856857858860861862863864865866867868870871872873874875876877878880881882883884885886887888900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990 ``` --- ## Golfscript - 19 bytes, 1016 output ``` 910,99>{`.2$\?)>+}/ ``` The above counts from *99* to *909*, adding any value that hasn't already appeared (*909* would normally be the last value added in this way). Moving *99* to the front is an optimization to avoid needing *910* at the back. Output: ``` 99100101102103104105106107108109111112113114115116117118119120122123124125126127128129130132133134135136137138139140142143144145146147148149150152153154155156157158159160162163164165166167168169170172173174175176177178179180182183184185186187188189190192193194195196197198199200202203204205206207208209222223224225226227228229230233234235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290293294295296297298299300303304305306307308309333334335336337338339340344345346347348349350354355356357358359360364365366367368369370374375376377378379380384385386387388389390394395396397398399400404405406407408409444445446447448449450455456457458459460465466467468469470475476477478479480485486487488489490495496497498499500505506507508509555556557558559560566567568569570576577578579580586587588589590596597598599600606607608609666667668669670677678679680687688689690697698699700707708709777778779780788789790798799800808809888889890899900909 ``` --- ## Golfscript 26 bytes, 999 output ``` 909.,99>{`..$.2><3$@?+>+}/ ``` Note that the *1016* character string produced by the previous solution is nearly optimal, except for having two extra digits for each multiple of *111* (i.e. `11111` instead of `111`, `22222` instead of `222`, etc.). The solution can be made optimal by removing these extra digits (only inserting one digit at each of these values, instead of three), and by rotating `909` to the front, eliminating a `9` (this differs from the previous versions, which moved `9100` to the back instead). Unrolled and commented: ``` 909.,99> # add 909 to the stack, and duplicate # create an array from 0..908, and # remove the first 99 elements (99..908) { `.. # stringify, duplicate twice $.2>< # non-divisibility by 111 check # true if the last char of the sorted # string is greater than the first char 3$@? # first position of this number in # the total string so far (-1 if not found) +> # add the two previous results, # and slice from that point # (see explanation below) + # concat what remains to the total string }/ # loop over the set ``` The logic to choose which characters are appended follows three cases: 1. ***111* ∤ *n*, *n* ⊄ *s*** The value from the first check is *1*, and from the second *-1*. The slice will begin starting from index *0*; it will return the whole string. 2. ***111* ∤ *n*, *n* ⊂ *s*** The value from the first check is *1*, and from the second something *≥ 2*. The slice will begin staring from index *≥ 3*; it will return an empty string. 3. ***111* ∣ *n*, *n* ⊄ *s*** The value from the first check is *0*, and from the second *-1*. The slice will begin starting from index *-1*; it will return the last character only. The sum of the logic is that any value which hasn't yet appeared will be appended in whole - unless it is a multiple of *111*, in which case only one character will be appended. All other values will be ignored. Note that the string produced is different than the optimal one produced by [Peter Taylor's answer](https://codegolf.stackexchange.com/a/13091/4098). History: ``` 899,{101+.111%{`.2$\?0<*}{3/9%}if+}/ 899,{101+`.2$\?0<\.~111%2*)<*+}/0 899,{101+`.2$\?0<\..2>-!2*>*+}/0 899,{101+`...2>|,1|<2$@?0<*+}/0 999,{`..$.2>>2*>2$@?0<*+}/3>0 899,{101+`..$.2><3$@?+>+}/0 ``` Output: ``` 909910010110210310410510610710810911121131141151161171181191201221231241251261271281291301321331341351361371381391401421431441451461471481491501521531541551561571581591601621631641651661671681691701721731741751761771781791801821831841851861871881891901921931941951961971981992002022032042052062072082092223224225226227228229230233234235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290293294295296297298299300303304305306307308309333433533633733833934034434534634734834935035435535635735835936036436536636736836937037437537637737837938038438538638738838939039439539639739839940040440540640740840944454464474484494504554564574584594604654664674684694704754764774784794804854864874884894904954964974984995005055065075085095556557558559560566567568569570576577578579580586587588589590596597598599600606607608609666766866967067767867968068768868969069769869970070770870977787797807887897907987998008088098889890899900 ``` [Answer] ## Perl, ~~37 34 33~~ 32 (~~1136~~ 1132 characters) ``` for$@(1..999){$_.=$@x!/$@/}print ``` ~~for$@(1..999){$\_.=$@if!/$@/}print~~ ~~for$i(1..999){$\_.=$i if!/$i/}print~~ ~~for(1..1e3){$s.=$\_ if$s!~/$\_/}print$s~~ Outputs: ``` 12345678910111314151617181920212224252627282930323335363738394043444647484950545557585960656668697076777980878890991001021031041051061071081091101121141151161171181191201241251261271281291301321331341351361371381391401421431441451461471481491501521531541551561571581591601621631641651661671681691701721731741751761771781791801821831841851861871881891901931941951961971981992002032042052062072082092192202212232252262272282292302312352362372382392402432442452462472482492502532542552562572582592602632642652662672682692702732742752762772782792802832842852862872882892902942952962972982993003043053063073083093113293303323343363373383393403423463473483493503543553563573583593603643653663673683693703743753763773783793803843853863873883893903953963973983994004054064074084094224394404434454474484494504534574584594604654664674684694704754764774784794804854864874884894904964974984995005065075085095335495505545565585595605645685695705765775785795805865875885895905975985996006076086096446596606656676696706756796806876886896906986997007087097557697707767787807867907977998008098668778798808878888978988999009089329439549659769799879891000 ``` ### Shorter string: ~~38 37~~ 34 (1020 characters): ``` $_.=$@x!/$@/while$@=--$@%1e3;print ``` ~~for($@=1e3;$@--;){$\_.=$@if!/$@/}print~~ ~~for($i=1e3;$i--;){$\_.=$i if!/$i/}print~~ Outputs: ``` 999998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888887886885884883882881880877876875874873872871870867866865864863862861860857856855854853852851850847846845844843842841840837836835834833832831830827826825824823822821820817816815814813812811810807806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555554553552551550544543542541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` Still not happy with the duplication especially the 99999 at the beginning! I think many more checks would create a lot more code though... Edit: Added suggestion from @Peter Taylor Edit 2: Some great suggestions from @primo! Thank you [Answer] ## APL (20, output: 1020) ``` {∨/⍺⍷⍵:⍵⋄⍵,⍺}/⍕¨⍳999 ``` Explanation: * `{∨/⍺⍷⍵:⍵⋄⍵,⍺}`: if `⍺` is a substring of `⍵`, return `⍵`, else return `⍵,⍺` * `/`: reduce over * `⍕¨`: the string representation of each of * `⍳999`: the integers from `1` to `999`. Output: ``` 9999989979969959949939929919909889879869859849839829819809789779769759749739729719709689679669659649639629619609589579569 55954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913 91291191090890790690590490390290190088888788688588488388288188087787687587487387287187086786686586486386286186085785 68558548538528518508478468458448438428418408378368358348338328318308278268258248238228218208178168158148138128118108 07806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735 73473373273173072672572472372272172071671571471371271171070670570470370270170066666566466366266166065565465365265165 06456446436426416406356346336326316306256246236226216206156146136126116106056046036026016005555545535525515505445435 42541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411 410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` ## APL (41, output: 999) ``` '0',⍨⊃{⍵,⍺⍴⍨(1=⍴∪⍺)∨3×~∨/⍺⍷⍵}/⌽⍕¨100+⍳898 ``` Explanation: * `⌽⍕¨100+⍳898`: `('999' '998' ... '101')` (in reverse order, because reduction goes right to left in APL, i.e. `F/a b c ≡ a F (b F c)`) * `/`: reduce * `⍵,⍺⍴⍨`: right argument, followed by the first `N` characters of the left argument, where `N` is: * `3×~∨/⍺⍷⍵`: `3` if `⍺` is not a substring of `⍵`, otherwise `0` * `(1=⍴∪⍺)`: `1` if `⍺` only has one unique characcter, otherwise `0` * `∨`: greatest common divisor of the previous two values, so: `1` if `⍺` is not already in `⍵` and only has one unique character, `3` if `⍺` is not already in `⍵` but has more than one unique character, `0` otherwise. * `'0',⍨`: add a zero to the end of the result Output: ``` 10110210310410510610710810911121131141151161171181191201221231241251261271281291301321331341351361371381391401421431441451 46147148149150152153154155156157158159160162163164165166167168169170172173174175176177178179180182183184185186187188 18919019219319419519619719819920020220320420520620720820922232242252262272282292302332342352362372382392402432442452 46247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290293294 29529629729829930030330430530630730830933343353363373383393403443453463473483493503543553563573583593603643653663673 68369370374375376377378379380384385386387388389390394395396397398399400404405406407408409444544644744844945045545645 74584594604654664674684694704754764774784794804854864874884894904954964974984995005055065075085095556557558559560566 56756856957057657757857958058658758858959059659759859960060660760860966676686696706776786796806876886896906976986997 00707708709777877978078878979079879980080880988898908999009099100 ``` [Answer] # Ruby: ~~50~~ 46 characters (1020 characters output) ``` s="" 999.downto(0){|i|s[n=i.to_s]||s+=n} $><<s ``` Sample run: ``` bash-4.1$ ruby -e 's="";999.downto(0){|i|s[n=i.to_s]||s+=n};$><<s' 999998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888887886885884883882881880877876875874873872871870867866865864863862861860857856855854853852851850847846845844843842841840837836835834833832831830827826825824823822821820817816815814813812811810807806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555554553552551550544543542541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` Test run: ``` bash-4.1$ ruby -e 's="";999.downto(0){|i|s[n=i.to_s]||s+=n};$><<s' | ruby -ne 'p (0..999).reject{|i|$_[i.to_s]}' [] ``` ## Ruby: ~~102~~ 97 characters (999 characters output) ``` s="" 999.downto(0){|i|s[n=i.to_s]||[2,1].map{|j|n[0,j]==s[-j,j]&&s+=n[j,9]and break}&&s+=n} $><<s ``` Sample run: ``` bash-4.1$ ruby -e 's="";999.downto(0){|i|s[n=i.to_s]||[2,1].map{|j|n[0,j]==s[-j,j]&&s+=n[j,9]and break}&&s+=n};$><<s' 999899799699599499399299199098898798698598498398298198097897797697597497397297197096896796696596496396296196095895795695595495395295195094894794694594494394294194093893793693593493393293193092892792692592492392292192091891791691591491391291191090890790690590490390290190088878868858848838828818808778768758748738728718708678668658648638628618608578568558548538528518508478468458448438428418408378368358348338328318308278268258248238228218208178168158148138128118108078068058048038028018007776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666566466366266166065565465365265165064564464364264164063563463363263163062562462362262162061561461361261161060560460360260160055545535525515505445435425415405345335325315305245235225215205145135125115105045035025015004443442441440433432431430423422421420413412411410403402401400333233133032232132031231131030230130022212202112102012001110100 ``` Test run: ``` bash-4.1$ ruby -e 's="";999.downto(0){|i|s[n=i.to_s]||[2,1].map{|j|n[0,j]==s[-j,j]&&s+=n[j,9]and break}&&s+=n};$><<s' | ruby -ne 'p (0..999).reject{|i|$_[i.to_s]}' [] ``` [Answer] # JavaScript, 39 ``` for(k=i="999";~k.indexOf(--i)?i:k+=i;); ``` 1020 character output: ``` 999998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888887886885884883882881880877876875874873872871870867866865864863862861860857856855854853852851850847846845844843842841840837836835834833832831830827826825824823822821820817816815814813812811810807806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555554553552551550544543542541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` Verification: `for(i=0;i<1000;i++)console.assert(k.indexOf(i)>=0)` [Answer] # Mathematica (~~62~~ 64 chars, 1002 output) Because this makes use of a native function, I appreciate all the more the beauty of shorter solutions from scratch. Output is 1002 chars long. ``` << Combinatorica` "79" <> DeBruijnSequence["0"~CharacterRange~"9", 3] "799798787770760750740730720710980970960950940930920910108908708608508408308208889998988081009909008007006005004003002000190180170160150140130120119118117116115114113112912812712612512412312213913813713613513413313214914814714614514414314215915815715615515415315216916816716616516416316217917817717617517417317218918818718618518418318219919819719619519419319212111029028027026025024023022922822722622522422392382372362352342332492482472462452442432592582572562552542532692682672662652642632792782772762752742732892882872862852842832992982972962952942932322202103903803703603503403393383373363353349348347346345344359358357356355354369368367366365364379378377376375374389388387386385384399398397396395394343330320310490480470460450449448447446445945845745645546946846746646547947847747647548948848748648549949849749649545444043042041059058057056055955855755695685675665795785775765895885875865995985975965655505405305205106906806706696686679678677689688687699698697676660650640630620610790780779778978879" ``` [Answer] # Mathematica, 51 chars ``` ""<>Table[ToString/@({i,j,k}-1),{i,10},{j,i},{k,i}] ``` Output(1155 chars): ``` 000100101110111200201202210211212220221222300301302303310311312313320321322323330331332333400401402403404410411412413414420421422423424430431432433434440441442443444500501502503504505510511512513514515520521522523524525530531532533534535540541542543544545550551552553554555600601602603604605606610611612613614615616620621622623624625626630631632633634635636640641642643644645646650651652653654655656660661662663664665666700701702703704705706707710711712713714715716717720721722723724725726727730731732733734735736737740741742743744745746747750751752753754755756757760761762763764765766767770771772773774775776777800801802803804805806807808810811812813814815816817818820821822823824825826827828830831832833834835836837838840841842843844845846847848850851852853854855856857858860861862863864865866867868870871872873874875876877878880881882883884885886887888900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999 ``` [Answer] # Python - 53 ~~63~~, 1134 output This is pretty brute forcish, but it is valid. Yes it has a leading zero, but it saves two characters by not having `range(1,1000)`. ``` s='' for i in range(1e3):s+=`i`*(not`i`in s) print s ``` The above throws a `DeprecationWarning` over the use of 1e3 in the `range()` call, but it saves a character over using 1000. There is a slightly more optimal length output version as well, by reversing the string at the cost of ~~6~~ 5 characters **(thanks to r.e.s and filmor for the tips)**: # Python - 58, 1021 output ``` s='' for i in range(999,9,-1):s+=`i`*(not`i`in s) print s ``` [Answer] # Java-~~126~~ 98 chars (Java 6) ``` class b{static{String s="";for(int a=999;a>0;a--)s=s.contains(""+a)?s:s+a;System.out.println(s);}} ``` Output (1020 chars): ``` 999998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888887886885884883882881880877876875874873872871870867866865864863862861860857856855854853852851850847846845844843842841840837836835834833832831830827826825824823822821820817816815814813812811810807806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555554553552551550544543542541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` Can reach a good (according to [Peter Taylor](https://codegolf.stackexchange.com/questions/13088/a-ring-to-rule-them-all-a-string-to-contain-them-all#comment25855_13088), but later he said 999 was optimal) String length by adding a few chars (+20 chars for ~~147~~ 118): ``` class b{static{String s="";for(int a=999;a>0;a--)s=s.contains(""+a)?s:(a+1)%111==0?s+a%10:s+a;System.out.println(s);}} ``` Output (1002 chars): ``` 999899799699599499399299199098898798698598498398298198097897797697597497397297197096896796696596496396296196095895795695595495395295195094894794694594494394294194093893793693593493393293193092892792692592492392292192091891791691591491391291191090890790690590490390290190088878868858848838828818808778768758748738728718708678668658648638628618608578568558548538528518508478468458448438428418408378368358348338328318308278268258248238228218208178168158148138128118108078068058048038028018007776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666566466366266166065565465365265165064564464364264164063563463363263163062562462362262162061561461361261161060560460360260160055545535525515505445435425415405345335325315305245235225215205145135125115105045035025015004443442441440433432431430423422421420413412411410403402401400333233133032232132031231131030230130022212202112102012001110101100 ``` **Edit**: Thanks to Fabinout for pointing out that Java 6 can save 28 chars. [Answer] # K, 33 ``` {$[#ss[x]@y;x;,/x,y]}/["";$!1000] ``` Basically the same as Howards solution - 1133 characters. ``` 01234567891011131415161718192021222425262728293032333536373839404344464748495054555758596065666869707677798087889099100102103104105106107108109110112114115116117118119120124125126127128129130132133134135136137138139140142143144145146147148149150152153154155156157158159160162163164165166167168169170172173174175176177178179180182183184185186187188189190193194195196197198199200203204205206207208209219220221223225226227228229230231235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290294295296297298299300304305306307308309311329330332334336337338339340342346347348349350354355356357358359360364365366367368369370374375376377378379380384385386387388389390395396397398399400405406407408409422439440443445447448449450453457458459460465466467468469470475476477478479480485486487488489490496497498499500506507508509533549550554556558559560564568569570576577578579580586587588589590597598599600607608609644659660665667669670675679680687688689690698699700708709755769770776778780786790797799800809866877879880887888897898899900908932943954965976979987989 ``` [Answer] ## Windows PowerShell - 40, 1020 Output ``` 999..0|%{$s+=if(!($s-match$_)){"$_"}};$s ``` Output: ``` 999998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888887886885884883882881880877876875874873872871870867866865864863862861860857856855854853852851850847846845844843842841840837836835834833832831830827826825824823822821820817816815814813812811810807806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555554553552551550544543542541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` [Answer] ## Pyke, 13 bytes (noncompeting), string length 1133 Pyke is newer than the challenge and thus is noncompetitive . ``` k~mV~oi{!o`*+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=k%7EmV%7Eoi%7B%21o%60%2a%2B) ``` - o = 0 k~mV - repeat 1000 times, i = "" ~oi{ - str(o) in i ! - not ^ o`* - str(o++) * ^ + - i += ^ ``` [Answer] # Haskell, 75 bytes - 1002 output A sieve approach that returns a minimal solution. ``` (\n->head.filter(\s->and[show k`isInfixOf`s|k<-[1..n]]).map show$[1..])1000 ``` Note that this solution is impractically slow. [Answer] # Powershell, 36 bytes, 1020 output ``` 999..9|%{$s+=(,"$_")[$s-match$_]};$s ``` Output: ``` 999998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888887886885884883882881880877876875874873872871870867866865864863862861860857856855854853852851850847846845844843842841840837836835834833832831830827826825824823822821820817816815814813812811810807806805804803802801800777776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555554553552551550544543542541540534533532531530524523522521520514513512511510504503502501500444443442441440433432431430423422421420413412411410403402401400333332331330322321320312311310302301300222221220211210201200111110101100 ``` ## Alternative, 69 bytes, 1000 output ``` 999..9|%{$s+=("$_",($x="$_"[-1]))[2*($s-match$_)+($s+$x-match$_)]};$s ``` Output: ``` 9998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888788688588488388288188087787687587487387287187086786686586486386286186085785685585485385285185084784684584484384284184083783683583483383283183082782682582482382282182081781681581481381281181080780680580480380280180077767757747737727717707667657647637627617607567557547537527517507467457447437427417407367357347337327317307267257247237227217207167157147137127117107067057047037027017006665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555455355255155054454354254154053453353253153052452352252152051451351251151050450350250150044434424414404334324314304234224214204134124114104034024014003332331330322321320312311310302301300222122021121020120011101100 ``` ## Alternative, ~~82~~ 73 bytes, 999 output (minimum) ``` for(;$z=9..0|?{"000$x"-notmatch-join"$x$_"[-3..-1]}|%{"$_"}){$x+=$z[0]}$x ``` This is simplified algorithm from [Generate the shortest De Bruijn](https://codegolf.stackexchange.com/a/173125/80745) adapted for constants: alphabet=`9876543210` and length=`3` Output: ``` 999899799699599499399299199098898798698598498398298198097897797697597497397297197096896796696596496396296196095895795695595495395295195094894794694594494394294194093893793693593493393293193092892792692592492392292192091891791691591491391291191090890790690590490390290190088878868858848838828818808778768758748738728718708678668658648638628618608578568558548538528518508478468458448438428418408378368358348338328318308278268258248238228218208178168158148138128118108078068058048038028018007776775774773772771770766765764763762761760756755754753752751750746745744743742741740736735734733732731730726725724723722721720716715714713712711710706705704703702701700666566466366266166065565465365265165064564464364264164063563463363263163062562462362262162061561461361261161060560460360260160055545535525515505445435425415405345335325315305245235225215205145135125115105045035025015004443442441440433432431430423422421420413412411410403402401400333233133032232132031231131030230130022212202112102012001110100 ``` --- Test script: ``` $f= { #999..0|%{$s+=if(!($s-match$_)){"$_"}};$s #999..9|%{$s+=("$_",($x="$_"[-1]))[2*($s-match$_)+($s+$x-match$_)]};$s-replace'1100','100' #999..9|%{$s+=("$_",($x="$_"[-1]))[2*($s-match$_)+($s+$x-match$_)]};$s #999..9|%{$s+=(,"$_")[$s-match$_]};$s-replace'(.)\1{3,}','$1$1$1' #999..9|%{$s+=(,"$_")[$s-match$_]};$s-replace'(.)\1{3,}','$1$1$1'-replace'1100','0' for(;$z=9..0|?{"000$x"-notmatch-join"$x$_"[-3..-1]}|%{"$_"}){$x+=$z[0]}$x #999..9|%{$s+=(,"$_")[$s-match$_]};$s } $s=&$f $s "Length:" $s.Length "count(###)!=1:" $x=@{} 0..($s.Length-3)|%{$s.Substring($_,3)}|Group|%{ $x[+$_.Name]=$_.Count } 100..999|?{$x.$_-ne1}|%{,($_,+$x.$_)}|%{"$_"} "count(##)!=10:" $x=@{} 0..($s.Length-2)|%{$s.Substring($_,2)}|Group|%{ $x[+$_.Name]=$_.Count } 10..99|?{$x.$_-ne10}|%{,($_,+$x.$_)}|%{"$_"} "count(#)!=100:" $x=@{} 0..($s.Length-1)|%{$s.Substring($_,1)}|Group|%{ $x[+$_.Name]=$_.Count } 0..9|?{$x.$_-ne100}|%{,($_,+$x.$_)}|%{"$_"} "All numbers:" 999-eq(1..999|?{$s-match$_}).Count ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) and [1109 characters](https://tio.run/##yy9OTMpM/f//UVOLm4vf4aXxmX6H1/yPTf8PAA) ``` ₄FDNå_iNì ``` Outputs: ``` 90990190089989088981980980880079979879078978878077977870970870770069969869769068968868768067967867767066966866760960860760660059959859759659058958858758658057957857757657056956856756656055955855755650950850750650550049949849749649549048948848748648548047947847747647547046946846746646546045945845745645545044944844744644540940840740640540440039939839739639539439038938838738638538438037937837737637537437036936836736636536436035935835735635535435034934834734634534434033933833733633533430930830730630530430330029929829729629529429329028928828728628528428328027927827727627527427327026926826726626526426326025925825725625525425325024924824724624524424324023923823723623523423323022922822722622522422320920820720620520420320220019919719619519419319219118918818718618518418318218017917817717617517417317217016916816716616516416316216015915815715615515415315215014914814714614514414314214013913813713613513413313213012912812712612512412312212011811711611511411311211110910810710610510410310210110099919089888079787770696867666059585756555049484746454440393837363534333029282726252423222018171615141312119876543210 ``` [Try it online](https://tio.run/##yy9OTMpM/f//UVOLm4vf4aXxmX6H1/z/DwA) or [verify it contains all numbers below 1000](https://tio.run/##yy9OTMpM/f//UVOLm4vf4aXxmX6H1/yPddEBCtgcnptd5mevpJCWX5qXopBYopCZl5JaoaBkX6nzHwA). **Explanation:** ``` ₄ # Push 1000 F # Loop N in the range [0,1000): D # Duplicate the top value on the stack Nå_i # If it does not contain N as substring yet: Nì # Prepend N to it # (Output implicitly after the loop) ``` [Answer] # PHP, ~~48~~ 44 bytes Thanks to @primo for reminding me of `ereg`. ``` for($i=1e3;--$i;ereg($i,$s)?:$s.=$i);echo$s; ``` or ``` for($i=1e3;ereg(--$i,$s)?$i:$s.=$i;);echo$s; ``` output: 1020 chars. requires PHP<7 ## PHP 7, 48 bytes: `ereg` has been removed in PHP 7 ``` for($i=1e3;--$i;strstr($s,"$i")?:$s.=$i);echo$s; ``` If the second argument to `strstr` (or `strpos` and other string searching functions) is not a string, it will be used as an ascii code, so `$i` needs a cast to string. [Answer] # Groovy, 49 chars/bytes I wasn't sure whether to do this as a function returning a string variable, or print out the result, so this just prints it to stdout. Using the regex matcher saved 2 bytes, using ternary operator instead of "if" saved another byte. The output string is 1133 characters. ``` a='';1000.times{a+=(a==~/.*$it.*/)?'':it};print a ``` Output: ``` 01234567891011131415161718192021222425262728293032333536373839404344464748495054555758596065666869707677798087889099100102103104105106107108109110112114115116117118119120124125126127128129130132133134135136137138139140142143144145146147148149150152153154155156157158159160162163164165166167168169170172173174175176177178179180182183184185186187188189190193194195196197198199200203204205206207208209219220221223225226227228229230231235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290294295296297298299300304305306307308309311329330332334336337338339340342346347348349350354355356357358359360364365366367368369370374375376377378379380384385386387388389390395396397398399400405406407408409422439440443445447448449450453457458459460465466467468469470475476477478479480485486487488489490496497498499500506507508509533549550554556558559560564568569570576577578579580586587588589590597598599600607608609644659660665667669670675679680687688689690698699700708709755769770776778780786790797799800809866877879880887888897898899900908932943954965976979987989 ``` [Answer] # Game Maker Language, 1014 - String 1000 `show_message(909910010110210310410510610710810911121131141151161171181191201221231241251261271281291301321331341351361371381391401421431441451461471481491501521531541551561571581591601621631641651661671681691701721731741751761771781791801821831841851861871881891901921931941951961971981992002022032042052062072082092223224225226227228229230233234235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290293294295296297298299300303304305306307308309333433533633733833934034434534634734834935035435535635735835936036436536636736836937037437537637737837938038438538638738838939039439539639739839940040440540640740840944454464474484494504554564574584594604654664674684694704754764774784794804854864874884894904954964974984995005055065075085095556557558559560566567568569570576577578579580586587588589590596597598599600606607608609666766866967067767867968068768868969069769869970070770870977787797807887897907987998008088098889890899900)` Also: ## Ruby, 1003 - String 1000 `p'909910010110210310410510610710810911121131141151161171181191201221231241251261271281291301321331341351361371381391401421431441451461471481491501521531541551561571581591601621631641651661671681691701721731741751761771781791801821831841851861871881891901921931941951961971981992002022032042052062072082092223224225226227228229230233234235236237238239240243244245246247248249250253254255256257258259260263264265266267268269270273274275276277278279280283284285286287288289290293294295296297298299300303304305306307308309333433533633733833934034434534634734834935035435535635735835936036436536636736836937037437537637737837938038438538638738838939039439539639739839940040440540640740840944454464474484494504554564574584594604654664674684694704754764774784794804854864874884894904954964974984995005055065075085095556557558559560566567568569570576577578579580586587588589590596597598599600606607608609666766866967067767867968068768868969069769869970070770870977787797807887897907987998008088098889890899900'` ]
[Question] [ ## The Challenge Write a program or function that takes no input and outputs a 3-dimensional vector of length \$1\$ in a **theoretically uniform** random direction. This is equivalent to a random point on the sphere described by $$x^2+y^2+z^2=1$$ resulting in a distribution like such [![Random distribution of points on a sphere with radius 1.](https://i.stack.imgur.com/xM4hO.png)](https://i.stack.imgur.com/xM4hO.png) ### Output Three floats from a theoretically uniform random distribution for which the equation \$x^2+y^2+z^2=1\$ holds true to precision limits. ## Challenge remarks * The random distribution needs to be **theoretically uniform**. That is, if the pseudo-random number generator were to be replaced with a true RNG from the **real** numbers, it would result in a uniform random distribution of points on the sphere. * Generating three random numbers from a uniform distribution and normalizing them is invalid: there will be a bias towards the corners of the three-dimensional space. * Similarly, generating two random numbers from a uniform distribution and using them as spherical coordinates is invalid: there will be a bias towards the poles of the sphere. * Proper uniformity can be achieved by algorithms including but not limited to: 1. Generate three random numbers \$x\$, \$y\$ and \$z\$ from a *normal* (Gaussian) distribution around \$0\$ and normalize them. + [Implementation example](https://tio.run/##ZVDLasMwELzrKxZyiBSKW5pboLdALz2WXkoJcrS2F@yV0CPU/XlXlt1XugehGWY1o3Fj7Czvp4kGZ30EToMbQQdgJ4TBBrxmY4fTBc/ReqkOAvIsCH7NA7yyqxZxxdYPupcKmiw6AfH8Sotyr94ANvDcecTMGnSYD46ryWxeow/Q@Aw0POoUAmkGQyF6qlMky6C9TWzgrgRZnOgDzZowB1kvt/kLVU@s@7YEkguvviNv4EgXMgiozx3UI8QOoUduYwe2KWhZKU4eY/L831BM@K4H1@NPgKvKhHCeOMrtSyEO2xv4u6K@BE/FfBaENEja7e5LgzQ3eLWixPQJ) 2. Generate three random numbers \$x\$, \$y\$ and \$z\$ from a *uniform* distribution in the range \$(-1,1)\$. Calculate the length of the vector by \$l=\sqrt{x^2+y^2+z^2}\$. Then, if \$l>1\$, reject the vector and generate a new set of numbers. Else, if \$l \leq 1\$, normalize the vector and return the result. + [Implementation example](https://tio.run/##jZLBTsMwDIbveQpLO6ydtkG3W0UvcEJCXJi4TunqrhFpEtIEGC9fkjYtWwGJHFrV8f/5t2t1MpUU27ZltZLagLC1OgFtQChCCixBU1HIev@GByN1FKcE3HmvGEfYaYsp/OfM4F6UTDCDwKVUZIjntMGADpHMFV73NbtXtI1Hxq7SiMBEgQrdQ5hgzpvOUTdQavdBwQpWSl1DwRqjWW4Nk8LJwFToFUeE6HoJSTzauHAQbGxgcWFvBUmw8VSx0nSwcGXkOXqV/MLecxRHU323yJmg/LgWzmfUp8SefUf5wXJqRnavG2msnABvMkjSv4Z@q5G@9FPxBv3oPSFIOTaNi1MBrg6@Wsp9Jwk5Z@Se0EW8U8rZJxbnPywbfF5NG53B46AIVx1Go7Fa/KSRFj9orfg472y6eYQozYSJ5s9dIJ0v4VISDwkPnQWf0Ng6YovFBtw@APM7MJHEpP0C) 3. Generate two random numbers \$i\$ and \$j\$ from a *uniform* distribution in the range \$(0,1)\$ and convert them to spherical coordinates like so:\begin{align}\theta &= 2 \times \pi \times i\\\\\phi &= \cos^{-1}(2\times j -1)\end{align}so that \$x\$, \$y\$ and \$z\$ can be calculated by \begin{align}x &= \cos(\theta) \times \sin(\phi)\\\\y &= \sin(\theta) \times \sin(\phi)\\\\z &= \cos(\phi)\end{align} + [Implementation example](https://tio.run/##lZJNT8MwDIbv/RWWOCydCoJym8SJKzcQF4SmrPVWT2sSOSm0@/MlH5voBkMih1ixXj@v3doMrtHqfhypNZodqK41A0gLymRZjWtgqWrdLj@wcppFvsjAn5BcUpHiFh68@iYJYxBlDpNzBS@fGkjVaNBfyh2gwWyFbGHN/iGhU7TW3EJN1jGtOkda@TJwDYaKDYK4LeAujy34pJPfHg9Qwjy0YcjH1N9JC8@mQaZK7qDSmmtS0mGCRJxppvI0keSq0laUR@AWrr37HzgPKfyb2X8srMEPczrLiqSNbj3AD7dgFfvJ0yCWlPDAPLg9SnZoSaqpWx9Rwy@oUPov1BBR@wtdpdLzcwG1j6i0LhPUW1/AUMD@Pe0Puo7VQZWN2MvW7PCwZF59tnRZZpiUE7PXmFjMCjgtyY@CJ1Qb1wSB7VpB83kZ/wKFNTorybPxCw) * Provide in your answer a brief description of the algorithm that you are using. * Read more on sphere point picking on [MathWorld](http://mathworld.wolfram.com/SpherePointPicking.html). ## Output examples ``` [ 0.72422852 -0.58643067 0.36275628] [-0.79158628 -0.17595886 0.58517488] [-0.16428481 -0.90804027 0.38532243] [ 0.61238768 0.75123833 -0.24621596] [-0.81111161 -0.46269121 0.35779156] ``` ## General remarks * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer using the fewest bytes in each language wins. * [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/), [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * Please include a [Try it Online](https://tio.run/#)-link or equivalent to demonstrate your code working. * Please motivate your answer with an explanation of your code. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes ``` RandomPoint@Sphere[] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T8oMS8lPzcgH8hxCC7ISC1KjY79H/sfAA "Wolfram Language (Mathematica) – Try It Online") Does exactly what it says on the tin. [Answer] # [R](https://www.r-project.org/), 23 bytes ``` x=rnorm(3) x/(x%*%x)^.5 ``` [Try it online!](https://tio.run/##K/r/v8K2KC@/KFfDWJOrQl@jQlVLtUIzTs/0/38A "R – Try It Online") Generates 3 realizations of the \$\mathcal N(0,1)\$ distribution and normalizes the resulting vector. Plot of 1000 realizations: [![enter image description here](https://i.stack.imgur.com/emKP6.png)](https://i.stack.imgur.com/emKP6.png) [Answer] # x86-64 Machine Code - ~~63 62 55~~ 49 bytes ``` 6A 4F push 4Fh 68 00 00 80 3F push 3F800000h C4 E2 79 18 4C 24 05 vbroadcastss xmm1,dword ptr [rsp+5] rand: 0F C7 F0 rdrand eax 73 FB jnc rand 66 0F 6E C0 movd xmm0,eax greaterThanOne: 66 0F 38 DC C0 aesenc xmm0,xmm0 0F 5B C0 cvtdq2ps xmm0,xmm0 0F 5E C1 divps xmm0,xmm1 C4 E3 79 40 D0 7F vdpps xmm2,xmm0,xmm0,7Fh 0F 2F 14 24 comiss xmm2,dword ptr [rsp] 75 E9 jne greaterThanOne 58 pop rax 58 pop rax C3 ret ``` Uses the second algorithm, modified. Returns vector of `[x, y, z, 0]` in xmm0. Explanation: ``` push 4Fh push 3f800000h ``` Pushes the value for 1 and 2^31 as a float to the stack. The data overlap due to the sign extension, saving a few bytes. `vbroadcastss xmm1,dword ptr [rsp+5]` Loads the value for 2^31 into 4 positions of xmm1. ``` rdrand eax jnc rand movd xmm0,eax ``` Generates random 32-bit integer and loads it to bottom of xmm0. ``` aesenc xmm0,xmm0 cvtdq2ps xmm0,xmm0 divps xmm0,xmm1 ``` Generates a random 32 bit integer, convert it to float (signed) and divide by 2^31 to get numbers between -1 and 1. `vdpps xmm2,xmm0,xmm0,7Fh` adds the squares of the lower 3 floats using a dot product by itself, masking out the top float. This gives the length ``` comiss xmm2,dword ptr [rsp] jne rand+9h (07FF7A1DE1C9Eh) ``` Compares the length squared with 1 and rejects the values if it is not equal to 1. If the length squared is one, then the length is also one. That means the vector is already normalised and saves a square root and divide. ``` pop rax pop rax ``` Restore the stack. `ret` returns value in xmm0 [Try it Online](https://tio.run/##ZZHbToQwEIavmaeYmHhl3QAewwN4643xRokpbXfFQFs7dcWnX3sAZbUJZfjmnzL/lBOpsRu@zndCHA6bXns1vNCX9nxCbaxT236CzW4w3YAj7zVs1OSV02hd0G6BvGtgw0n0PZ48nW4Z5qd9Lk8gFjRQCD4MuFP@UQlvHBT2g17RdRaK0exjwNDR/EV2YFhCQR9dhAyr65TglvApgJbhNI5lYkQxrlhKnF22K1jP8DZAsfdENclUuJSvYZVgdQzrBGsoBsXRyZ5hsJp7VHxieDH7mueQrcSGkzFrbA4m47I@bFA45QF@JtFAmsS8yunyDvEPuri7LeMKiX3nDJeCk198y0/jJFrvsterNqgc17IBJ@M7HxJ@HPibFsupmHMQOpYLSqPJyp1TPNzwwyvX91o1wBWppTjJ4hZ0YVjyvQ7X8ofLfp/hilexf2nXvGY/RaycbqJ1YcaeaKU4NthGF2rp@LhNiAP/9Rd9/Cdh@mE/HL4B). [Answer] # [Python 2](https://docs.python.org/2/), 86 bytes ``` from random import*;R=random z=R()*2-1 a=(1-z*z)**.5*1j**(4*R()) print a.real,a.imag,z ``` [Try it online!](https://tio.run/##JclLCoAgFEbhuatoqD8lKDUKN9EOLvQy8sHFSW7egkYHvpOfcqZoW9s5hY4prl98yIkL5sX9IKpbpIIdjCAnzVBRFaAnmAuQI76pRGYfS0eaN7p70j7Q0dfWXg "Python 2 – Try It Online") Generates the z-coordinate uniformly from -1 to 1. Then the x and y coordinates are sampled uniformly on a circle of radius `(1-z*z)**.5`. It might not be obvious that the spherical distribution is in factor uniform over the z coordinate (and so over every coordinate). This is something special for dimension 3. See [this proof](http://mathworld.wolfram.com/Zone.html) that the surface area of a horizontal slice of a sphere is proportional to its height. Although slices near the equator have a bigger radius, slices near the pole are titled inward more, and it turns out these two effects exactly cancel. To generate a random angle on this circle, we raise the imaginary unit `1j` to a uniformly random power between 0 and 4, which saves us from needing trig functions, pi, or e, any of which would need an import. We then extract the real imaginary part. If we can output a complex number for two of the coordinates, the last line could just be `print a,z`. --- # [Python 2](https://docs.python.org/2/), 85 bytes ``` from random import* a,b,c=eval('gauss(0,1),'*3) R=(a*a+b*b+c*c)**.5 print a/R,b/R,c/R ``` [Try it online!](https://tio.run/##DcXJDYAgEADAP1XwE9aNeMSnTdDBgmeiQABNrB59TCa8efeuL2WN/uKR3Px3XMHHDIzQoJ2Wh05RbXSnJFrsJFYwSKYnQUC1AVNbsBKgGVmIh8uclEbzs0qX8gE "Python 2 – Try It Online") Generates three normals and scales the result. Thanks to ovs for saving 1 byte with `eval` in the second line. --- **[Python 2](https://docs.python.org/2/) with numpy, 57 bytes** ``` from numpy import* a=random.randn(3) print a/sum(a*a)**.5 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1chrzS3oFIhM7cgv6hEiyvRtigxLyU/Vw9E5WkYa3IVFGXmlSgk6heX5mokaiVqamnpmf7/DwA "Python 2 – Try It Online") `sum(a*a)**.5` is shorter than `linalg.norm(a)`. We could also do `dot(a,a)` for the same length as `sum(a*a)`. In Python 3, this can be shortened to `a@a` using the new operator `@`. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~40 33~~ 22 bytes We sample form a 3d standard normal distribution and normalize the vector: ``` (x=randn(1,3))/norm(x) ``` [Try it online!](https://tio.run/##y08uSSxL/f9fo8K2KDEvJU/DUMdYU1M/L78oV6NC8/9/AA "Octave – Try It Online") [Answer] # [Unity C#](https://docs.unity3d.com/ScriptReference/Random-onUnitSphere.html), 34 bytes ``` f=>UnityEngine.Random.onUnitSphere ``` Unity has a builtin for unit sphere random values, so I thought I'd post it. [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` 1&3Xrt2&|/ ``` [Try it online!](https://tio.run/##y00syfn/31DNOKKoxEitRv//fwA "MATL – Try It Online") ### Explanation This uses the first approach described in the challenge. ``` 1&3Xr % Generate a 1×3 vector of i.i.d standard Gaussian variables t % Duplicate 2&| % Compute the 2-norm / % Divide, element-wise. Implicitly display ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~34 50~~ 49 bytes ``` ->{[z=rand*2-1]+((1-z*z)**0.5*1i**(rand*4)).rect} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1646usq2KDEvRctI1zBWW0PDULdKq0pTS8tAz1TLMFNLSwMsaaKpqVeUmlxS@9/QQK8kMze1uLpAIS06tvY/AA "Ruby – Try It Online") Returns an array of 3 numbers `[z,y,x]`. `x` and `y` are generated by raising `i` (square root of -1) to a random power between 0 and 4. This complex number needs to be scaled appropriately according to the `z` value in accordance with Pythagoras theorem: `(x**2 + y**2) + z**2 = 1.` The `z` coordinate (which is generated first) is simply a uniformly distributed number between -1 and 1. Though not immediately obvious, dA/dz for a slice through a sphere is constant (and equal to the perimeter of a circle of the same radius as the whole sphere.) . This was apparently discovered by Archimedes who described it in a very non-calculus-like way, and it is known as Archimedes Hat-Box theorem. See <https://brilliant.org/wiki/surface-area-sphere/> Another reference from comments on xnor's answer. A surprisingly short URL, describing a surprisingly simple formula: <http://mathworld.wolfram.com/Zone.html> [Answer] # TI-BASIC, 15 bytes \* ``` :randNorm(0,1,3 :Ans/√(sum(Ans² ``` Using the algorithm "generate 3 normally distributed values and normalize that vector". Ending a program with an expression automatically prints the result on the Homescreen after the program terminates, so the result is actually shown, not just generated and blackholed. \*: `randNorm(` is a [two-byte token](http://tibasicdev.wikidot.com/miscellaneous-tokens), the rest are [one-byte tokens](http://tibasicdev.wikidot.com/one-byte-tokens). I've counted the initial (unavoidable) `:`, without that it would be 14 bytes. Saved as a program with a one-letter name, it takes 24 bytes of memory, which includes the 9 bytes of file-system overhead. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [тε5°x<Ýs/<Ω}DnOtDî#}/ ``` Implements the 2nd algorithm. [Try it online](https://tio.run/##ATAAz/9vc2FiaWX//1vRgs61NcKweDzDnXMvPM6pfURuT3REw64jfS////8tLW5vLWxhenk) or [get a few more random outputs](https://tio.run/##ATMAzP9vc2FiaWX/NUb/W9GCzrU1wrB4PMOdcy88zql9RG5PdETDriN9L/8s//8tLW5vLWxhenk). **Explanation:** NOTE: 05AB1E doesn't have a builtin to get a random decimal value in the range \$[0,1)\$. Instead, I create a list in increments of \$0.00001\$, and pick random values from that list. This increment could be changed to \$0.000000001\$ by changing the `5` to `9` in the code (although it would become rather slow..). ``` [ # Start an infinite loop: тε # Push 100, and map (basically, create a list with 3 values): 5° # Push 100,000 (10**5) x # Double it to 200,000 (without popping) < # Decrease it by 1 to 199,999 Ý # Create a list in the range [0, 199,999] s/ # Swap to get 100,000 again, and divide each value in the list by this < # And then decrease by 1 to change the range [0,2) to [-1,1) Ω # And pop and push a random value from this list } # After the map, we have our three random values D # Duplicate this list n # Square each inner value O # Take the sum of these squares t # Take the square-root of that D # Duplicate that as well î # Ceil it, and if it's now exactly 1: # # Stop the infinite loop }/ # After the infinite loop: normalize by dividing # (after which the result is output implicitly) ``` [Answer] # JavaScript (ES7), ~~77 76~~ 75 bytes Implements the 3rd algorithm, using \$\sin(\phi)=\sin(\cos^{-1}(z))=\sqrt{1-z^2}\$. ``` with(Math)f=_=>[z=2*(r=random)()-1,cos(t=2*PI*r(q=(1-z*z)**.5))*q,sin(t)*q] ``` [Try it online!](https://tio.run/##FYvLCsIwEADv/Yq9dTdtgxU82Xj3IHgXkdCHTalZmwSFiN8e62mGgZn0S/vWmWeoLHd9Sm8TRjzpMNKgbupwiWor0CmnbccPQqrqsmWPYc3no3C4KKyrKCIJIXdEYim9sRhWuaaBHVpQsNmDhQbqP4uC4JMBtGw9z72c@Y4Dkpx43fIScqLsm34 "JavaScript (Node.js) – Try It Online") ### Commented ``` with(Math) // use Math f = _ => // [ z = 2 * (r = random)() - 1, // z = 2 * j - 1 cos( // t = // θ = 2 * PI * // 2 * π * i r(q = (1 - z * z) ** .5) // q = sin(ɸ) = sin(arccos(z)) = √(1 - z²) // NB: it is safe to compute q here because // Math.random ignores its parameter(s) ) * q, // x = cos(θ) * sin(ɸ) sin(t) * q // y = sin(θ) * sin(ɸ) ] // ``` --- # JavaScript (ES6), 79 bytes Implements the 2nd algorithm. ``` f=_=>(n=Math.hypot(...v=[0,0,0].map(_=>Math.random()*2-1)))>1?f():v.map(x=>x/n) ``` [Try it online!](https://tio.run/##HYtLDoJAEAX3nKJ3dAuM4FIcPIEnMMZM@AgEuglMCMZ49nEkb1GLV9Wb1Szl3E02Yalq5xr91AWyvhnbqvY9iUWl1Krvaez3UKOZ0Bv7PRuuZEQ6nJKMiIrs2iCd193ZdLEdmVwjMw61BQYNae5xgezPKCL4BACl8CJDrQZ5oa9VLx1jGENIFHzdDw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = _ => // f is a recursive function taking no parameter ( n = Math.hypot(... // n is the Euclidean norm of v = // the vector v consisting of: [0, 0, 0].map(_ => // Math.random() * 2 - 1 // 3 uniform random values in [-1, 1] ) // )) > 1 ? // if n is greater than 1: f() // try again until it's not : // else: v.map(x => x / n) // return the normalized vector ``` [Answer] # [Processing](https://processing.org/) 26 bytes Full program ``` print(PVector.random3D()); ``` This is the implementation <https://github.com/processing/processing/blob/master/core/src/processing/core/PVector.java> ``` static public PVector random3D(PVector target, PApplet parent) { float angle; float vz; if (parent == null) { angle = (float) (Math.random()*Math.PI*2); vz = (float) (Math.random()*2-1); } else { angle = parent.random(PConstants.TWO_PI); vz = parent.random(-1,1); } float vx = (float) (Math.sqrt(1-vz*vz)*Math.cos(angle)); float vy = (float) (Math.sqrt(1-vz*vz)*Math.sin(angle)); if (target == null) { target = new PVector(vx, vy, vz); //target.normalize(); // Should be unnecessary } else { target.set(vx,vy,vz); } return target; } ``` [Answer] # [Python 2](https://docs.python.org/2/), 86 bytes ``` from random import* x,y,z=map(gauss,[0]*3,[1]*3);l=(x*x+y*y+z*z)**.5 print x/l,y/l,z/l ``` [Try it online!](https://tio.run/##DcVLCoAgFEDReatoqM9H9qFRtJJoIEQf8IcZ@Ny8Objneoq3s2MpZ3CmDcoedY/xLkRoEhLm1SjPLvW9L279DhNuQ5UvemUJkiAgkSFzgG5ufHhsbJPUSLUsdSk/ "Python 2 – Try It Online") Implements the first algorithm. --- # [Python 2](https://docs.python.org/2/), ~~107~~ 103 bytes ``` from random import* l=2 while l>1:x,y,z=map(uniform,[-1]*3,[1]*3);l=(x*x+y*y+z*z)**.5 print x/l,y/l,z/l ``` [Try it online!](https://tio.run/##FcVNCoMwEEDhfU6RpY7TipZuKulFpAvBioHJD0OkmVw@1cX7XpS0Bz/WunFwmhe/nrMuBk6gyIzqt1v6anoPr4yCxbglNoe3W2CH8234wAPny3Yi02TInYB0BUoLcH@qyNYnnXtCOSs91foH "Python 2 – Try It Online") Implements the second algorithm. [Answer] # [Haskell](https://www.haskell.org/), ~~125~~ ~~123~~ ~~119~~ 118 bytes ``` import System.Random f=mapM(\_->randomRIO(-1,1))"lol">>= \a->last$f:[pure$(/n)<$>a|n<-[sqrt.sum$map(^2)a::Double],n<1] ``` [Try it online!](https://tio.run/##Hcy7CsIwFADQ3a8IJUMCTaWOJcnk4iBCHdsqV0xoMS@TdBD89/hYz3BmSA9lTCmLDT5mdH6lrGzTg7t7u9HCQjiS8cpk/Et/OBHW1i2llfGmklKgEZg0kDLW3RDWqDDZOsqxhLfjbEjPmJu0WvyNyGVHoev2fr0ZNdWOt1OxsDgkkEa/KsTFZVQ@ "Haskell – Try It Online") Does three uniforms randoms and rejection sampling. [Answer] # JavaScript, 95 bytes ``` f=(a=[x,y,z]=[0,0,0].map(e=>Math.random()*2-1))=>(s=Math.sqrt(x*x+y*y+z*z))>1?f():a.map(e=>e/s) ``` You ~~don't~~ need *not* to input `a`. [Answer] # [Julia 1.0](http://julialang.org/), 24 bytes ``` x=randn(3) x/hypot(x...) ``` [Try it online!](https://tio.run/##yyrNyUw0rPhfUJSZV5KTp5GUmp6Z97/CtigxLyVPw1iTq0I/o7Igv0SjQk9PT/N/al6K5n8A "Julia 1.0 – Try It Online") Draws a vector of 3 values, drawn from a normal distribution around 0 with standard deviation 1. Then just normalizes them. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~21~~ ~~19~~ 18 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` {╘3Ƀ∞(ß_²Σ√_1>}▲/ ``` Implementation of the 2nd algorithm. [Try it online](https://tio.run/##ASsA1P9tYXRoZ29sZv//e@KVmDPDicaS4oieKMOfX8KyzqPiiJpfMT594payL///) or [see a few more outputs at the same time](https://tio.run/##AS4A0f9tYXRoZ29sZv9Fe/974pWYM8OJxpLiiJ4ow59fwrLOo@KIml8xPn3ilrIv/3D/). **Explanation:** ``` { }▲ # Do-while true by popping the value: ╘ # Discard everything on the stack to clean up previous iterations 3É # Loop 3 times, executing the following three operations: ƒ # Push a random value in the range [0,1] ∞ # Double it to make the range [0,2] ( # Decrease it by 1 to make the range [-1,1] ß # Wrap these three values into a list _ # Duplicate the list of random values ² # Square each value in the list Σ # Sum them √ # And take the square-root of that _ # Duplicate it as well 1> # And check if it's larger than 1 / # After the do-while, divide to normalize # (after which the entire stack joined together is output implicitly, # which is why we need the `╘` to cleanup after every iteration) ``` [Answer] # Java 8 (*@Arnauld*'s modified 3rd algorithm), ~~131~~ ~~126~~ ~~119~~ ~~111~~ 109 bytes ``` v->{double k=2*M.random()-1,t=M.sqrt(1-k*k),r[]={k,M.cos(k=2*M.PI*M.random())*t,M.sin(k)*t};return r;} ``` Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/191514/52210), so make sure to upvote him! -2 bytes thanks to *@OlivierGrégoire*. This is implemented as: \$k = N\cap[-1,1)\$ \$t=\sqrt{1-k^2}\$ \$u=2\pi×(N\cap[0,1))\$ \$x,y,z = \{k, \cos(u)×t, \sin(u)×t\}\$ [Try it online.](https://tio.run/##TVA9b4MwEN3zK260aeyULh0QkTp2IKoUqUuUwTFOYz7s1D6oEOK30yN06HLf7@7eq1SvRFXWs25UjFAo68YNgHVowlVpA4clBSh9d2nM6QyafXpbQs8zqk8bMoXCGxQZwG4HT6@AHvBm4DKgEdp3DmnkAA5ymHuxH9dFUOcvSSGDcqVvGRfpFvNCxu@ALBV1UvNtOJ3zsd4WUvvI1umP938QniA1o3WspnDKgsEuOAjZNGfLV3c6YzVEVEiuX35uiRw7YrDui4govjK7@sCILtg8fc7ACrEnxx8tgOMQ0bTSdyjvhMPGsYoUkx3aRr6FoIYo0a87mTM/DwEZl05q5rqm4fxPp2n@BQ) **Previous 3rd algorithm implementation (~~131~~ ~~126~~ 119 bytes):** ``` Math M;v->{double k=2*M.random()-1,t=2*M.PI*M.random();return k+","+M.cos(t)*M.sin(k=M.acos(k))+","+M.sin(t)*M.sin(k);} ``` Implemented as: \$k = N\cap[-1,1)\$ \$t=2\pi×(N\cap[0,1))\$ \$x,y,z = \{k, \cos(t)×\sin(\arccos(k)), \sin(t)×\sin(\arccos(k))\}\$ [Try it online.](https://tio.run/##TZCxbsMgEIb3PMUpE9SBNF06IGfvQFSpUpeqA8EkIbaPCM6uosjP7mInUrtw4vsPcd@dTW/EuapH25iUQBuPtwWAR3LxYKyD3XQF@KDo8QiWfQZfQc9VpsMiH9rQCbQCWK@heAUKQCcH@ys5YUOHlFt2gFDC2IvtrQrdvnFQly9PWkaDVWgZF5sVzeD97R9V0VEXEepiuVoWWtqQGPHckDyyutTSTKTm/JFP@C/nahjVNN8lf@gtJDKUSz9N32ZJdhf6@gbD74aHEFnWBl9unhV4Iba58DnK@tdErpWhI3nJ76hBhu5nXhfjEqVl2DUNf6xlGH8B) ### Explanation: ``` Math M; // Math on class-level to use for static calls to save bytes v->{ // Method with empty unused parameter & double-array return double k=2*M.random()-1, // Get a random value in the range [-1,1) t=M.sqrt(1-k*k), // Calculate the square-root of 1-k^2 r[]={ // Create the result-array, containing: k, // X: the random value `k` M.cos(k=2*M.PI // Y: first change `k` to TAU (2*PI) *M.random()// multiplied by a random [0,1) value ) // Take the cosine of that *t, // and multiply it by `t` M.sin(k) // Z: Also take the sine of the new `k` (TAU * random) *t}; // And multiply it by `t` as well return r;} // Return this array as result ``` --- # Java 8 (2nd algorithm), ~~153~~ 143 bytes ``` v->{double x=2,y=2,z=2,l;for(;(l=Math.sqrt(x*x+y*y+z*z))>1;y=m(),z=m())x=m();return x/l+","+y/l+","+z/l;};double m(){return Math.random()*2-1;} ``` [Try it online.](https://tio.run/##LVDBcoMgEL3nK3ZyAo2m5srgHySXzOTS6YEqaUkRUkArOn67XY2HfW9Y3sJ7@xCdyB71z1xp4T2chTLjDkCZIN1dVBIuyxHgGpwyX1CRm1U1dJRhd9ohXMAAh7nLyrG27aeW0PPTIWINWJrdrSOMaH4W4Tv3vy6QPunTmMR0SAZKy4JF3hCKakTaL8icDK0z0B91uj/s07jxcNRsYtsvqBs33fq0E6a22ExOWcGmGZ09Uacq8EEEpG7x3WA88ory/gGCvrItFjEwKF68MVBZViLR9QqDRx9kk9s25E@cC9oQI//WRRGam7wiptWabguZ5n8) *2nd algorithm:* ``` v->{ // Method with empty unused parameter & String return-type double x=2,y=2,z=2,l; // Start results a,b,c all at 2 for(;(l=Math.sqrt(x*x+y*y+z*z)) // Loop as long as the hypotenuse of x,y,z >1; // is larger than 1 y=m(),z=m())x=m(); // Calculate a new x, y, and z return x/l+","+y/l+","+z/l;} // And return the normalized x,y,z as result double m(){ // Separated method to reduce bytes, which will: return Math.random()*2-1;} // Return a random value in the range [-1,1) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~20~~ 19 bytes ``` {≥|3ʁƛ∆Ṙd⌐;:²∑√:1}/ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%7B%E2%89%A5%7C3%CA%81%C6%9B%E2%88%86%E1%B9%98d%E2%8C%90%3B%3A%C2%B2%E2%88%91%E2%88%9A%3A1%7D%2F&inputs=&header=&footer=) Uses the second method. ## Explanation ``` {≥|3ʁƛ∆Ṙd⌐;:²∑√:1}/ { } While ≥ Greater or equal | do: 3ʁ [0,1,2] ƛ ; Map: ∆Ṙ Random number from 0 to 1 d Double ⌐ Subtract from 1 : Duplicate ² Square ∑ Sum √ Square root : Duplicate 1 Push 1 / Divide [the vector by the length] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of [Arnauld's implementation](https://codegolf.stackexchange.com/a/191514/58974) of the 2nd algorithm. ``` MhV=3ÆMrJ1 >1?ß:V®/U ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TWhWPTPGTXJKMQo%2bMT/fOlauL1U) ``` MhV=3ÆMrJ1 Mh :Get the hypotenuse of V= : Assign to V 3Æ : Map the range [0,3) Mr : Random float J1 : In range [-1,1) >1?ß:V®/U :Assign result to U >1? :If U is greater than 1 ß : Run the programme again :V®/U :Else map V, dividing all elements by U ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 24 bytes ``` W<1Ks^R2JmtO2.0 3;cR@K2J ``` [Try it online!](https://tio.run/##K6gsyfj/P9zG0Ls4LsjIK7fE30jPQMHYOjnIwdvI6/9/AA "Pyth – Try It Online") Uses algorithm #2 ``` W # while <1 # 1 < Ks # K := sum( ^R2 # map(lambda x:x**2, Jm 3 # J := map( , range(3)) tO2.0 # lambda x: random(0, 2.0) - 1 )): ; # pass R J # [return] map(lambda x: , J) c @K2 # x / sqrt(K) ``` [Answer] # [OCaml](https://ocaml.org), ~~110~~ ~~99~~ 95 bytes ``` (fun f a c s->let t,p=f 4.*.a 0.,a(f 2.-.1.)in[c t*.s p;s t*.s p;c p])Random.float acos cos sin ``` EDIT: Shaved off some bytes by inlining \$ i \$ and \$ j \$, replacing the first `let ... in` with a `fun`, and taking advantage of operator associativity to avoid some parens `()`. [**Try it online**](https://tio.run/##NY7BasMwEETv@YrBJ8kkS1p6C@0X9JQeSzCLvEoF8kpIm/6@m5iUYWCGB8OUwEte3YjhfNMBVnAVlcYmmFOM0kQNjXUuC34lWGkdwuEHlhbB6He78wapS45T0mRwHifUltQm0TknFbgvu/crhaKBDcNd7jN1o4UrXN/gVOIUc2HzcKuLN0UEI6AfPrIYbF/fI95oJMaR9uwiXulAL@STfgfYSB311P9DQL3457VtFRxKx8M96eq9X/8A) --- Original solution: ``` Random.(let a,c,s,i,j=acos,cos,sin,float 4.,float 2. in let t,p=i*.(a 0.),a (j-.1.) in[c t*.s p;s t*.s p;c p]) ``` First I define: $$ a = \arccos,\ \ c = \cos,\ \ s = \sin \\ i \sim \textsf{unif}(0,4),\ \ j \sim \textsf{unif}(0,2) $$ OCaml's [`Random.float` function](https://caml.inria.fr/pub/docs/manual-ocaml/libref/Random.html#VALfloat) includes the bounds. Then, $$ t = i \cdot a(0) = \frac{i\pi}{2},\ \ p = a (j-1) $$ This is very similar to the 3rd example implementation (with \$ \phi = p \$ and \$ \theta = t \$) \$ - \$ except that I pick \$ i \$ and \$ j \$ within larger intervals to avoid multiplication (with 2) later on. [Answer] # [Nim](http://nim-lang.org/), 105 101 100 99 bytes ``` import math,random randomize() let t=TAU.rand u=2.0.rand-1 v=sqrt 1-u*u echo [t.cos*v,t.sin*v,u] ``` [Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEITexJEOnKDEvJT@XC0JlVqVqaHLlpJZwKZTYhjiG6oGEuRRKbY30DMBsXUMuhTLb4kKgbkPdUq1SrtTkjHyF6BK95PxirTKdEr3izDwgXRr7/z8A "Nim – Try It Online") Uses the third method with a bit of substitution: $$u = \cos(\phi) = 2j - 1$$ $$v = \sin(\phi) = \sqrt{1-u^2}$$ [Answer] # [Raku](http://raku.org/), 65 bytes ``` {(&cos,&sin,{1})».(τ.rand)Z*(&sin,&sin,&cos)».(acos 2.rand-1)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMtOb9YR604M0@n2rBW89BuPY3zLXpFiXkpmlFaGmBxCAFUBpZNBDIUjMAqdA01a/@n6RUnViqk5RcpxBka/AcA "Perl 6 – Try It Online") This function uses the "convert two random numbers to spherical coordinates" method. `τ.rand` generates the first number in the range of zero to τ (tau, that is, twice pi) and `acos 2.rand - 1` generates the second with the acos argument in the range of -1 to 1. `(&cos, &sin, {1})».(...)` applies the cosine function, the sine function, and an anonymous function that always returns `1` to the first random parameter, producing a list of the results. Similarly, `(&sin, &sin, &cos)».(...)` applies the sine, sine, and cosine functions to the second random parameter, producing a second list. Finally, `Z*` zips those two lists together using multiplication. [Answer] # [Pxem](https://esolangs.org/wiki/Pxem), 58 bytes (filename). Because Pxem does not handle decimal values nor negative values (negative values can be supplied via input but cannot be generated in other ways), I am representing them as integers. Unprintables are represented as a backslash followed by three-digit octal value of its code point. ``` x\003\144.w\002.r\002.!+.+.o.v21.y.c\013.r.c.t.c.!.a.m.n.m.m.!.-.v\001.-.c.a ``` ## Output format It outputs 10x, 10y, and 10z rather than x, y, and z. ``` "%c%d%c%d%c%d\n", sign, value, sign value, sign, value ``` Sign is as either `+` or `-`; always output. Value is multiplied by 10. Thus the precision of the program is up to 0.1. ## With comments ``` XX.z # memory layout: counter, l # until counter is zero; do .ax\003\144.wXX.z   # output sign   .a\002.r\002.!+.+.oXX.z   # while :; do   .a.v21.yXX.z     # generate a random number 0<=x<=10     .a.c\013.rXX.z     # continue if x^2>l; otherwise break     .a.c.t.c.!XX.z   # done   .a.aXX.z   # output x   .a.m.nXX.z   # update l to l minus x^2   .a.m.m.!.-XX.z # decrement counter; done .a.v\001.-.c.a ``` [Try it online!](https://tio.run/##fVdrV@JIE/7ur2iykXQTcumIisToMOjrsKuMOq7H0aAnQFAwJGwSFA3sX5@3upMImZ0znoPpp6q67n17jp5@/IEM3aBI30G0rqK93a1th@7s7BgbfoAJLiG3/xQgMaFK9LQ0Am9wUDaIyVjBAClNHykv8Ywu4hAprQjZd7qy10XSne1XutLiMXSnSCVm5MZIcWfmbOJEz0jXDcN059MgjNFp66F5emq1TBy/TV306Mb9wB@Wyxz1g8nE8QfkQBu4L5o/8zxkHJRpuZxNPm9efbEEEWdySJnmCjiLiAn7yI1lOlCWQm7270775uHb1ZFl6PpWTjz/@q19c/r9ofX18vK4dWVR8w4JYvK5@e3Lw/Xx5bf2104DdKBuucwDCtA0iEbzFMmfU@nb/wq7k5nnxC6KnrhoMI1h@BqEg2jqjeJy2fFGToSURyRBmmVB/CQsJUtiX6lc7vx9eto6O7IaXD1mpgZm9DQaxjyrA8TkMkJaqj@IgCxEmWU/MN0Xx0NCCQ0dL3KFxQJIXBGXnS8id4CkSJtrb5oZwb93TeLT31GXySLgm30oNheXhkGIPafnepYARk2SgJc4WGCuRbuv7Yha0miaYs/smJrtc3wOeu9V1fY1zew1zWUKVUoNUZtqZpzhul6AlFJRC1Z4d68AKQVxf41dL0Cqb4vaaI29VYB7wH1Yg6C7v4I7uwVIKUhHa45uFSClYPpljb1TgFSHMIdrnugFSHUI012zvVeAlNZELVxTbhQgpSD@usbeLUBqgLH5GrtegNQA229r7L0CpAYYe1/Lkl6EYMtZc3y7ACmFNMRrumsFSHWwNVnLym4BUh1sDdaU1wuwBhWQ1yCYVlZwC7ilNQiOiGsQLG0yuJTS5TIg6RrQ@M6lJSese@fmABr1hM2xsWoTG9s@@69WbCJq9pZt2FQDqUhTK9DW83ynS1U1PFMsJdrd6/zt3Rl0tVLSMXseKFyab7AqNKSZ2t19xmXNJGpooBV0KD6SMvN395@qXbALHuC7dAguGJ8Qc@Epk0npSK0Ai3uWWod4ptxNUasyag9cgDIlgEpJBKOmNjV7F0BNxaqfQMGH4OBDcKAd5YIFsZyT5aERmmKSmvuEmGrYC7g0auaUuMlTK5Y6wLH9O6S8dysDpi0O1ygQEs9PNw1W4ywHxKa8kmlwTjprCd42Lj5Uqty3@KJYkzwfXyAzR03IyzwrLs/sKm9pfk4yTfyXupJ6klX9VxOlfC9dq4c2Gmb7pSXYVCAJDwTfTQN/9NCPXoZuGE/kkripdJm0TTExtcdUhrWjndCqvWSsc2zTjOesexTNelhg9RCqbPYhjIUGbM5VbpYsM4NF@d8JH4laL3SdZw6gbE0seEEwRX4Qo4kT959G/qMAoh/hgnaZuY@J1gMnMSWEu1niBD0FIoB/crDJAQUgkaVANn78r9M8O7akuQ2HsU1rNfUVRoYa8v8lWZXVQH0xqPqm9m2dbqmh2ldj@JVUR52oPvwmMFbUF5hA4dtXHWmj9bVzddy5sjY2@k7kwpHHrQho5CNc0SqLim3r27sVkl5wJI0xuIgENxzTdCOnvzENR348/Ji7eO0jpQ/sH0NrOPP78SjwbWRGYd@SPh@ftDtJFMI9BI5Dd0CWcDYOBekcH5Hk291z9S9MutaRCcOuLGfMY0yS0I1noY9KMghk5D9XZCAe0Iz814rMtGTUqwKVmVFozrvBlyS5tECE21UUM5O8zARmuEWSNErBhr/NQKi2Mt4JvqzefuiGi5U38t0D/VDUG0ru0pfUgEhN3lj3vGtl6C9BIAUSSkk/mf@bmZ/5Vm6yic8yd9DZQug7MeSa3dlGMcotTiHc16eR5@ISZI8EH0mDUQKUxWKGb4CRUX3crl5Xj6oeSWAt8inJtQUCpmd5rv8YP@FrYrJ7jdne90wyw/jIAsejOMTXVVluV6Gf/xV4EMLhkVyrN2rbZJlpH4HNc3yyMveAz6qt6m31O0nOLEF9aKAOrBsHDdz@aAIXMYjMfXRD@E5nsWC2LJhr3sJNk3tgcidru/utcrm1v10nfCWaQGv9K9zX7ra2uyJsIrdWraa0ssnpYgURXE@n0RrkoGVZWwZJUhG4EMcjf@YuWXqZaGu/VgeZg@1dwkip8ZXZVDP5buHvBLWUWt1kdTLP8W3lex5oP8/2Ob5ahR/l1JuPsrxAAcbVa5K0LZ0bGlu8RSHdY9aU1bGidK1rVhWG2l1ObMtyl@NxN891uLIIWcR8oZEKK3Vu6nW1En5yYo4vqtxECZYWy2cJ0AVvg2vrYp8JZhOvsxlvv51x8IsZ7x/W2RRuXVl5EOfeP8E6tFb0CdCf2dYDb4NzzJg5p4cdSFzat3@ytj3HziFMlB0WdOMmC95cLfqKRRWjgp19nVRYVeCbJ@@fn5WNszVwk0WHxxWPQDeADUHdhFNBhU4TGujWDeGONHoZRbDXCawJWPKdw/GBdzje9Bre5rjBxxofQy2W6U4Ibll6F2rOngg/76N9IkiZZ0OcviI@RLJ9W1gE/ISx0nMmPdvh6gTnDnurKaH/TBf9GYwGEpKQMjTyAwmuIue4TNhDJjfi8iZMT7kEGo434rMsm7I83sdsa2TNBilM0znOIAyI@WvnWAQD13PhWQdFgxbmKtsWNDZsGvswXaZpK/MNv801yhT6O92K5RTDRm0GC@f1GZ7RiB0b7DkLV6A@4k/eGevyYMKeckAM/0NcPcEHNaR0agWBxQJP4VnZhGfqaFB149HErU7701n1JXo3B/AgJYu1J3ztt0/4ReyMPLiV1tayzG7GSZ1dT/gdSFpg0GDbPpLTm7Vi0Npurb61U6uTRQ8SBvmDo1LIw4Xt1xIxRiLOH@3Ny5OHs@bNYsHn1/S9HaIZCjUQIUjKduue1UOiTg4AZidFz@xZgrA87hzlhKWEFnMnfITo23OUFW/@4/8 "ksh – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes ``` ⎕←{⍵÷((+/⍵*2)*0.5)}?⍳3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20Tqh/1bj28XUNDWx/I0DLS1DLQM9WstX/Uu9n4/38A "APL (Dyalog Classic) – Try It Online") ]
[Question] [ Your assignment is to write a program of **even length**, that prints an ASCII-art square (described below), that increases its side length by **1** unit each time the original source code is pasted in the middle of the current code. It is quite hard for me to define this task very well, so I'll give you an example: * Let's say your initial code was `CODE` and that it printed: ``` 0 ``` * Then, insert `CODE` in the middle: your code becomes `COCODEDE` and it should print: ``` 00 00 ``` * Re-insert `CODE` in the middle: your code becomes `COCOCODEDEDE` and should print: ``` 000 000 000 ``` * And so on. Your answer should theoretically work after any number of iterations, but I understand if, due to language performance limitations, it cannot run reasonably over a certain threshold. Some rules: * You can use any **printable ASCII** (32-127) as the character to use for your square. Your choice needs to be constant (You should use the same character for each iteration). * The initial output square must have side-length **1**. * An ascii-art square is defined as a string with **N** lines (separated by **N-1** linefeeds / newlines), and with each line containing **N** copies of the chosen character. * Your output isn't allowed to contain any extraneous whitespace, other than a trailing newline. * You can use the defaults for input and output (programs or functions are allowed, but snippets are not). * The *middle* of your code is defined as the point where the source code can be split in two parts such that the two are equal. * Your answers will be scored by the length of **your original program**, in bytes. The lowest byte count wins. In case there's a tie, the answer that was submitted earlier wins. * You can use [this program](https://tio.run/##bY5BC4JAEIXv8yvmqEiJehPsUp37AbKI1aYDOrvsboW/flsthMC5vGH45r2nJ9crLrynUSvj0E4WQBnqiNsBK7ypuwwSzvvWdK86E8DP8SpNox4NsZXGkWIbEGIXrVguYoB3T4PETfyAWQkY5uc/S10OkqN5izFNMReY4Nok@SL/RCkWj82EXYUZgDZzreXDe3@8nM6@@AA "Python 3 – Try It Online") to apply the insertions without having to do that by hand. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 2 bytes ``` 5 ``` [Try it online!](https://tio.run/##K6gsyfj/n8v0/38A "Pyth – Try It Online") Also [Try it doubled](https://tio.run/##K6gsyfj/n4vL1PT/fwA), [tripled](https://tio.run/##K6gsyfj/n4uLy9TU9P9/AA)! ### How does that work? `\n` is the command that prints its argument with a trailing newline, while **returning it** simultaneously. So, each time you make an insertion, you turn the integer literal **5** into a number containing **N** copies of **5** concatenated, and the leading newlines basically make sure it's printed the appropriate number of times, thus keeping it square. [Answer] ## JavaScript (ES6), ~~42~~ ~~32~~ 30 bytes ``` s=[this.s]+0; console.log(s); ``` Second iteration: ``` s=[this.s]+0; s=[this.s]+0; console.log(s);console.log(s); ``` This works by appending a `0` to `s` each time the first half of the code is run, and printing `s` itself each time the second half is run. Takes advantage of four quirks of JavaScript: 1. The current environment can be referred to with `this`. This allows us to do `this.s` in place of `s`. 2. When accessing a property that has not been defined on an object, instead of throwing an error, JavaScript returns `undefined`. 3. An array plus a number returns a string. `[1,2,3] + 4 === "1,2,34"` 4. When stringifying an array, `undefined` is converted to the empty string, which means that `[undefined] + 0 === "0"`. Put together, this means that we can express the first half (generating a string of zeroes) in just 13 bytes. If using `alert` instead of `console.log` is allowed, we can save 4 more bytes by shortening the second half. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` 5= ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f1Pb/fwA "05AB1E – Try It Online") Port of [my Pyth answer](https://codegolf.stackexchange.com/a/154643/59487). [Answer] # [Python 2](https://docs.python.org/2/), ~~42~~ ~~38~~ 28 bytes ``` id='%s@'%id ;print id[22:]; ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzPFVl212EFdNTNFQcG6oCgzr0QhMyXayMgq1vr/fwA "Python 2 – Try It Online"). You can also try the [2nd](https://tio.run/##K6gsycjPM/r/PzPFVl212EFdNTNFQcEalVdQlJlXopCZEm1kZBWLxvv/HwA "Python 2 – Try It Online") and [3rd](https://tio.run/##K6gsycjPM/r/PzPFVl212EFdNTNFQcEaH6@gKDOvRCEzJdrIyCoWL@//fwA "Python 2 – Try It Online") iterations [Answer] # [Python 2](https://docs.python.org/2/), 22 bytes ``` i=0;i+=1; i print'*'*i ``` [Try it online!](https://tio.run/##PY7BDoIwEETP7FdsSEwFGqXVE6R/4B8oMQarbWKWpvSgX4@0gqfNzLzJjvsEM5Cc@uGuVZ7nk1V1ayslWrTgvKXASlbaaY52Y/DWbdmFWAFA6qVpG2vFj0N20vQMhnEkuI2j9gFpI5WqwaBC2ksAiLyYVbznxnTJkKthmg7gMXj02o1oCQWX/MCPDWTpBWRzcI3o0hBlIqskZBILiivJMQ6GTL91/zenLw "Python 2 – Try It Online") Doubled: ``` i=0;i+=1; ii=0;i+=1; i print'*'*i print'*'*i ``` Note that the second half starts with a newline character. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~170~~ ~~168~~ ~~96~~ ~~80~~ ~~72~~ 70 bytes Much shorter version. Still wish I could find a solution without the preprocessor. ``` i;main(n){for(;i++<n;)printf #if 0 #endif (" %*c",n=__LINE__/4, 10);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM08jT7M6Lb9IwzpTW9smz1qzoCgzrySNSzkzTcGAi0s5NS8lM41LQ0lBVStZSSfPNj7ex9PPNT5e30RHwdBA07r2/38A "C (gcc) – Try It Online") Old 168 byte version: ``` #ifndef A #define A p(c){putchar(c);}j,n;main(i){for( #else #define A n++, #endif A #ifndef B #define B i=++n;i--;p(10))for(j=n;j--;)p(64);} #else #define B #endif B ``` [Try it online!](https://tio.run/##XY1BCgIxDEX3PUWhm5ROQUHchFm0Nxk6raZoLKOuBs9e42JEzCbh8fN@8qeUejdUeM5FB2VkEWcddINk1/Z8pPO0yImvOjBeJ2Igu5bbAsrkyz3/fLBzg0CeqaigZDZt/IaiptE5RvIeG@x31n5MdWSsQmyD40Ga/sxxk8be3w "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` False+=1 ;print'*'*False; ``` [Try it online!](https://tio.run/##K6gsycjPM/r/3y0xpzhV29ZQAQysC4oy80rUtdS1wOLW//8DAA "Python 2 – Try It Online"), [2nd](https://tio.run/##K6gsycjPM/r/3y0xpzhV29ZQAQys0bgFRZl5Jepa6lpgcXTu//8A "Python 2 – Try It Online") and [3rd](https://tio.run/##K6gsycjPM/r/3y0xpzhV29ZQAQys8XMLijLzStS11LXA4gS4//8DAA "Python 2 – Try It Online") iteration This makes use of the fact that bools in Python are basically ints and the names `False` and `True` were reassignable in Python 2. # [Python 1](https://www.python.org/download/releases/1.6.1/), 32 bytes ``` exit=exit+'*' ;print exit[30:]; ``` [Try it online!](https://tio.run/##K6gsycjPM/z/P7Uis8QWRGira6krKFgXFGXmlSiABKKNDaxirf//BwA "Python 1 – Try It Online"), [2nd](https://tio.run/##K6gsycjPM/z/P7Uis8QWRGira6krKFij8wuKMvNKFEAC0cYGVrEY/P//AQ "Python 1 – Try It Online") and [3rd](https://tio.run/##K6gsycjPM/z/P7Uis8QWRGira6krKFgT4hcUZeaVKIAEoo0NrGIJ8v//BwA "Python 1 – Try It Online") iteration In Python 1 the builtin strings `exit` and `quit` existed to inform the user of the interactive shell how to exit it. The default value is `"Use Ctrl-D (i.e. EOF) to exit."`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` ⊞υωLυ⸿ ``` [Try it online!](https://tio.run/##ARsA5P9jaGFyY29hbP//4oqez4XPie@8rM@F4ri///8 "Charcoal – Try It Online") Explanation: ``` ω Predefined empty string (any variable would do here) υ Predefined initially empty list ⊞ Push ``` `υ` ends up with a length of the number of repetitions. ``` υ List L Length Implicitly print as a row of `-`s ⸿ Move to start of next line ``` [Answer] # [Haskell](https://www.haskell.org/), 68 bytes ``` let s@(z:n)="0\n"in case lines<$>[]of(h:t):_->(h:h:t)>>(z:h++n);_->s ``` Try it online [once](https://tio.run/##FctBCoMwEEDRqwziwiBC12kTegeXVSSE2IjjNDhx4@Ed093jw4@O14AoDGYQDBn43ZyalKkeA1ULgXccABcK/KrtZ/zNTdRZ6amzBX9aW4bYtqSeJbJsrlwG0pH7vAPL5Wd0X5bOp3QD "Haskell – Try It Online"), [twice](https://tio.run/##y0gszk7NyflfrGAb8z8ntUSh2EGjyipP01bJICZPKTNPITmxOFUhJzMvtdhGxS6asIrY/DSNDKsSTat4XTsgA8S0swNqyNDWztO0BgoWE1bxPzcRaK6tQkFpSXBJkULx/3/JaTmJ6cX/dZMLCgA) or [thrice](https://tio.run/##y0gszk7NyflfrGAb8z8ntUSh2EGjyipP01bJICZPKTNPITmxOFUhJzMvtdhGxS6aGipi89M0MqxKNK3ide2ADBDTzg6oIUNbO0/TGihYTA0V/3MTgTbbKhSUlgSXFCkU//@XnJaTmF78Xze5oAAA). Because of Haskell's laziness an expression like the one above counts as a function which takes no arguments, as per [this Meta question](https://codegolf.meta.stackexchange.com/q/12924/56433). [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~44~~ 34 bytes [crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/a/153011/76162) ``` ,>-[<+>---]++++++++++[<]>[.>]<---- ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fx0432kbbTldXN1YbDqJtYu2i9exibYDCuv//AwA "brainfuck – Try It Online") [Try it doubled](https://tio.run/##SypKzMxLK03O/v9fx0432kbbTldXN1YbDDAEQCDaJtYuWs8u1gYorIsh8P8/AA "brainfuck – Try It Online"), [tripled](https://tio.run/##SypKzMxLK03O/v9fx0432kbbTldXN1YbDAgLgEC0TaxdtJ5drA1QWJewwP//AA "brainfuck – Try It Online"). Look, no padding! Prints squares of `U`. It splits right down the middle of the 10 `+`s. [Answer] # Ruby, 18 bytes ``` $/=?x+$/; puts$/; ``` [Try it online!](https://tio.run/##KypNqvz/X0Xf1r5CW0XfWkGhoLSkGMj4/x8A) [Doubled!](https://tio.run/##KypNqvz/X0Xf1r5CW0XfWkEBiVlQWlIMZECp//8B) [Tripled!](https://tio.run/##KypNqvz/X0Xf1r5CW0XfWkEBO7OgtKQYyECl/v8HAA) [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 74 bytes ``` (((((()()()){}){}){}){})((()()()()()<>){})<>([]){({}[()]<(({})<>)<>>)}{}<> ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fAww0QVCzuhaBYIIgaGMHErGx04iO1azWqK6N1tCMtdHQAIsBkZ1mbXWtjd3///91HQE "Brain-Flak (BrainHack) – Try It Online") Try it [doubled](https://tio.run/##SypKzMzLSEzO/v9fAww0QVCzuhaBYIIgaEOUIjuQiI2dRnSsZrVGdW20hmYsUCNYDIjsNGura0EUEYr@//@v6wgA "Brain-Flak (BrainHack) – Try It Online") and [tripled](https://tio.run/##SypKzMzLSEzO/v9fAww0QVCzuhaBYIIgaEM9RXYgERs7jehYzWqN6tpoDc1YoEawGBDZadZW14Ioain6//@/riMA "Brain-Flak (BrainHack) – Try It Online"). ### Explanation ``` (((((()()()){}){}){}){}) # push 48 ("0") onto first stack ((()()()()()<>){}) # push 10 (\n) onto second stack <>([]){({}[()]< # a number of times equal to the height of the first stack: (({})<>)<> # copy the top of the first stack to the second stack >)}{}<> # cleanup and return to second stack ``` The break point is in the middle of the `<>` in the "push 10" section. Breaking this up will leave a 5 on the third stack until we reach the corresponding second half, at which point pushing 10 will resume right where it left off. While it is possible to push a printable ASCII value (space) in 22 bytes, this would make the central `<>` be executed after pushing `5`. By adding two more bytes, I was able to move the `<>` so that all of the progress toward pushing `10` was on the third stack. As a bonus, this also made the resulting square more aesthetically pleasing. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 112 bytes ``` (load library) (d N((q((x)(i x(inc x)1)))(v(h(t(t(h(t(q())))))))))(join(repeat-val(string(repeat-val 42 N))N)nl) ``` [Try it online!](https://tio.run/##TYgxDoMwEAS/cuVukSIR7/AfDFhw0ekAYyH79U5oosxIU0xRb6bn3jtsi7OYjjnmRsEsATiASqhUqE9S@SSJCyvK17sH@APvTR057SmWxxUNZ8nqy9@R4SWBDHRj7x8 "tinylisp – Try It Online") Also [doubled](https://tio.run/##nYsxDoMwEAS/cuVukQLEO/wHB1C46HQQYyHzegcaRM2utMVoJ6vvputSK2yOg5i@U0w7BYME4AcUQqVAvZfChiQ2TMhHzz0ODz1ewXdWRxqXMebXFg1rTuqfG5GulUAGuvGpV@sf) and [fivefold](https://tio.run/##3YtBDoMwEAO/skf70AOId@QPKaCy1WqhIULh9SlcEG/AlnwYebL6broutcLmOIjpO8W0UzBIAH5AIVQK1HspbEhiw4R89Nzj8HCPV/Cd1ZHGZYz5tUXDmpP650akayWQgW58ulfrHw). The "build a string in the first half, print it in the second half" approach that a lot of languages are taking won't work in tinylisp, since there are no mutable variables. Instead, we do some serious code nesting. When a second copy of the code is inserted, it is placed inside the `(q())`, which wraps it in a list. Then `(h(t(t(h(t(...))))))` drills into that list to the part after `(d N`. `(v(...))` evaluates it; then we pass it to the unnamed function `(q((x)(i x(inc x)1)))`, which increments the resulting value if it's a number and returns 1 if it's the empty list. The final result in the outermost nested version of the code is assigned to `N`. In essence, we've set up a weird sort of recursion that counts the number of nesting levels. The second half of the code then creates a string of `N` asterisks, then a list of `N` such strings, then joins the list on newlines. The result is displayed with a trailing newline. [Answer] # [R](https://www.r-project.org/), 44 bytes ``` F=F+1;T=TRUE*TRUE+12; write(strrep(1,F),""); ``` [Try it online!](https://tio.run/##K/r/383WTdvQOsQ2JCjUVQtEaBsaWXOVF2WWpGoUlxQVpRZoGOq4aeooKWla//8PAA "R – Try It Online") Prints with a trailing newline. The `T=TRUE*TRUE+12` is just to pad the length. [Try it doubled](https://tio.run/##K/r/383WTdvQOsQ2JCjUVQtEaBsaWWMV5CovyixJ1SguKSpKLdAw1HHT1FFS0sQl/P8/AA) and [Try it tripled](https://tio.run/##K/r/383WTdvQOsQ2JCjUVQtEaBsaWRMvyFVelFmSqlFcUlSUWqBhqOOmqaOkpEmi8P//AA). [Answer] # [Julia 0.6](http://julialang.org/), 29 bytes All my ideas were longer than adapting xnor's clever python solution. ``` i=0;i+=1; i println("0"^i) ``` Becomes ``` i=0;i+=1; ii=0;i+=1; i println("0"^i) println("0"^i) ``` [Try it online!](https://tio.run/##yyrNyUw0@/8/09bAOlPb1tBaAQgyuQqKMvNKcvI0lAyU4jI1//8HAA "Julia 0.6 – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~130~~ 68 bytes Now with no comments! See the [edit history](https://codegolf.stackexchange.com/posts/154670/revisions) for an explanation of the old algorithm. ``` X =X + 1 A =ARRAY(X,DUPL(1,X)); I I =I + 1 OUTPUT =A<I> :S(I) END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/nzNCwTZCQVvBkIvTUcHWMSjIMVIjQsclNMBHw1AnQlPTmsuT01PB1hOixD80JCA0BKjOxtOO0ypYw1OTy9XP5f9/AA "SNOBOL4 (CSNOBOL4) – Try It Online") Try it [doubled](https://tio.run/##K87LT8rPMfn/nzNCwTZCQVvBkIvTUcHWMSjIMVIjQsclNMBHw1AnQlPTmqACLk9OTwVbT4gS/9CQgNAQoDobTztOq2ANT00uVz8XIpT8/w8A "SNOBOL4 (CSNOBOL4) – Try It Online") and [tripled](https://tio.run/##K87LT8rPMfn/nzNCwTZCQVvBkIvTUcHWMSjIMVIjQsclNMBHw1AnQlPTmnIFXJ6cngq2nhAl/qEhAaEhQHU2nnacVsEanppcrn4u1FHy/z8A "SNOBOL4 (CSNOBOL4) – Try It Online") Explanation: ``` X =X + 1 ;* increment X A =ARRAY(X,DUPL(1,X)); ;* create an x-length array with 1 repeated x times for each element I I =I + 1 ;* for i < x OUTPUT =A<I> :S(I) ;* output a[i] END ``` Because an `END` label is required and anything after the first `END` label is ignored, we get two advantages for this challenge: * operations in the first half of the program are repeated `X` times for the `X` repetitions * there will (to the interpreter) only exist one copy of the second half, *including labels*. This suggests that we use the repetition for the first half, and then we can use a more "conventional" labeling approach to repeat the output `X` times. The first half is ``` X =X + 1 A =ARRAY(X,DUPL(1,X)); ``` which, when repeated, increments `X` the appropriate number of times, and creates an `ARRAY` `A` with indices from `1` to `X` and where each element of `A` is the string `1` repeated `X` times. Then no matter how many times the program is repeated, the interpreter only sees: ``` I I =I + 1 OUTPUT =A<I> :S(I) END ``` which is a typical SNOBOL program that prints out the elements of `A` one at a time until the index goes out of bounds, then terminates the program. `;` is an optional line terminator usually reserved for one-line `EVAL` or `CODE` statements that quite neatly brings the byte count to 68 and marks the halfway point, allowing the code to be appended there. [Answer] # [shortC](//git.io/shortC), ~~56~~ 44 bytes -12 bytes: wait duh I'm using shortC why not use some shortened C stuff ``` s[];A strcat(s,"@");// Js);/*filling space*/ ``` I would've used standard C, but that requires a `}` at the end which messes with replication. shortC inserts it at EOF implicitly. * [Try it online! (1x1)](https://tio.run/##K87ILypJ/v@/ODrW2pGruKQoObFEo1hHyUFJ01pfn8urGEhppWXm5GTmpSsUFyQmp2rp//8PAA) * [Try it online! (2x2)](https://tio.run/##K87ILypJ/v@/ODrW2pGruKQoObFEo1hHyUFJ01pfH7sol1cxkNJKy8zJycxLVyguSExO1cIh@v8/AA) * [Try it online! (3x3)](https://tio.run/##K87ILypJ/v@/ODrW2pGruKQoObFEo1hHyUFJ01pfnxRRLq9iIKWVlpmTk5mXrlBckJicqkWS6P//AA) * ... * [Try it online! (15x15)](https://tio.run/##K87ILypJ/v@/ODrW2pGruKQoObFEo1hHyUFJ01pff1SUdFEur2IgpZWWmZOTmZeuUFyQmJyqNSpKhuj//wA) [Answer] # [Perl 5](https://www.perl.org/), 25 bytes **24 bytes code + 1 for `-p`.** Appreciate that you might not want to allow commandline flags, please let me know if this is not valid. ``` $@=0 x++$n;;$_="$@ "x$n; ``` [Try it online!](https://tio.run/##K0gtyjH9/1/FwdZAoUJbWyXP2ppkdrytkooDl1IFkEMq@/9/rn/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 10 bytes ``` s+=0 <<<$s ``` **[Try a full test suite online!](https://tio.run/##TVHLbsIwELz7K0Y8lERVEHBMA7dWqlSpVdsjF0NsYimxI9tAC4Jfp2untPVlH96ZWY@Prr4uIVGWSB5eHpOru1tMWVmWI3elmrEhrGjNXsBbrhqlt9DiQFFAaUjVCObtTm@4F8gd8hlkwLiuUT5e05g3lFnnUfNGIpU8A9cVnNgYCqlcZ6yfzzXmyDmI5IemNgf4msQPJqD3wrHOEqNEMnYrfbm8vz4/fVwuKx3KcvFzliudYDBKS9Ia9Mk6GzDGpLFQYfPTbDKZT8/3qAxjoDNEJEYteCVsbN2U3nYaw/G8KnqVBCOF0SltClUUiyI73wjIh7hsZ83W8jbIiLbzXxB6r6zRrdA@jlKNXOHo6vDMHsyrChwNqQePgz@/hm9M2xlNYIT1tfj0QSriyHdIHuxag75xE5vtnrI/5v5dnshiI/zt/@Uror5@Aw "Zsh – Try It Online")** ...yeah, this is a bit better. Append to string N times, then print N times. Turns out `<<<foo<<<foo` works just fine. --- ### [Zsh](https://www.zsh.org/), 64 bytes Character used: (space). ``` f(){printf '%*s\n' $1} :<<'E' E repeat $[i=LINENO/3];f $i exit ``` **[Try a full test suite online!](https://tio.run/##VVFNT@MwFLz7V4zaoCRIgW25BZdbkZAQrHa5AQe3eSaWEjtyTMtStX@9@5zwIXzx88ubmTeT974@XkFDSqTL@@v0qLN813ljg0Z6cto/2RTJbC9KKdNlKsRSeOpIBSSPZnF7c7e8uz@/eL7USIygNxPEkVmEmMJT6zaE4JVpjH2BpS3fBGOhTUMi@Fe7VoFQ9Chm0BHTd40Jw2ceC44r3wfUqtHItMqhbIWe1o6vTK9yMc4XFnMUCkzyQVO7LULN4lsX0RvqxZcldnQ4/P19e/NwODzZ@JSLj3MVzU6STLLWZCxW@UQIoZ2HiZvvZmdn81/7S1ROCPCZYiBGTaoiP7Q@lf68WkxP5lU5qnCMBskua0pTlosy338ScA7Dsp13L161UYbaLvwD2Y3xzrZkwzDKbxQG730dbY5gVVVQaFg9Zhzz@Qp87drOWQYjrm/pLUSpAce5Q6sY1wr889dDs91w9c08@gpMNjSklD@Wr5j6@B8 "Zsh – Try It Online")** The midpoint is between the second `E` and the newline following it. A heredoc will end when there is an `E` on a line by itself, which happens right in the middle of the code. ]
[Question] [ **Question :** You will be given the starting and ending integers of a sequence and should return the number of integers within it which do not contain the digit `5`. The start and end numbers should be included! > > **Examples:** > > > 1,9 → 1,2,3,4,6,7,8,9 → Result 8 > > > 4,17 → 4,6,7,8,9,10,11,12,13,14,16,17 → Result 12 > > > 50,60 → 60 → Result 1 > > > -59,-50 → → Result 0 > > > The result may contain five. The start number will always be smaller than the end number. Both numbers can be also negative! I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution. **Edit** This is a code-golf challenge, so the shortest code wins. [Answer] ## JavaScript (ES6), ~~36~~ 33 bytes Takes input with currying syntax `(a)(b)`. ``` a=>F=b=>b<a?0:!/5/.test(b)+F(b-1) ``` ### Formatted and commented ``` a => // outer function: takes 'a' as argument, returns F F = b => // inner function F: takes 'b' as argument, returns the final result b < a ? // if b is less than a 0 // return 0 : // else !/5/.test(b) + // add 1 if the decimal representation of b does not contain any '5' F(b - 1) // and do a recursive call to F with b - 1 ``` ### Test cases ``` let f = a=>F=b=>b<a?0:!/5/.test(b)+F(b-1) console.log(f(1)(9)) console.log(f(4)(17)) console.log(f(50)(60)) console.log(f(-50)(-59)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Dennis (use fact that indexing into a number treats that number as a decimal list) ``` rAw€5¬S ``` **[TryItOnline!](https://tio.run/nexus/jelly#@1/kWP6oaY3poTXB////1zU1/K9rYgIA)** # How? ``` rAw€5¬S - Main link: from, to e.g. -51, -44 r - range(from, to) e.g. [-51,-50,-49,-48,-47,-46,-45,-44] A - absolute value e.g. [51,50,49,48,47,46,45,44] w€ - first index of... for €ach (0 if not present) 5 - five e.g. [1,1,0,0,0,0,2,0] ¬ - logical not e.g. [0,0,1,1,1,1,0,1] S - sum e.g. 5 ``` \* The absolute value atom, `A` is necessary since a negative number cast to a decimal list has negative entries, none of which would ever be a `5` (the given example would count all eight rather than two). [Answer] # [Bash](https://www.gnu.org/software/bash/) + grep, 17 bytes ``` seq $@|grep -cv 5 ``` [Try it online!](https://tio.run/nexus/bash#@1@cWqig4lCTXpRaoKCbXKZg@v//f5P/huYA "Bash – TIO Nexus") [Answer] # [2sable](https://github.com/Adriandmen/2sable), ~~6~~ 5 bytes Saved a byte thanks to *Adnan* ``` Ÿ5¢_O ``` [Try it online!](https://tio.run/nexus/2sable#@390h@mhRfH@//9Hm@gYmscCAA "2sable – TIO Nexus") **Explanation** ``` Ÿ # inclusive range 5¢ # count 5's in each element of the range _ # negate O # sum ``` **Note:** This works due to a bug in `¢` making the function apply itself to each element instead of counting matching elements in the list. [Answer] # Python2, ~~59~~ ~~55~~ ~~52~~ ~~51~~ ~~47~~ ~~43~~ 42 bytes ``` f=lambda a,b:a<=b and-(`5`in`a`)-~f(a+1,b) ``` A recursive solution. Thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for giving me motivation to find a solution using logical operators! Also, thanks to [@JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) and [@xnor](http://@https://codegolf.stackexchange.com/users/20260/xnor) for guiding me and chopping the byte from 43 to 42! # Other attempts at 43 bytes ``` f=lambda a,b:a<=b and-~-(`5`in`a`)+f(a+1,b) f=lambda a,b:a<=b and 1-(`5`in`a`)+f(a+1,b) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) / Unix utilities, 21 bytes ``` seq $*|sed /5/d|wc -l ``` [Try it online!](https://tio.run/nexus/bash#@1@cWqigolVTnJqioG@qn1JTnqygm/P//3@T/4bmAA "Bash – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ ~~7~~ 6 bytes Saved a byte thanks to *Adnan* ``` Ÿ5.å_O ``` [Try it online!](https://tio.run/nexus/05ab1e#@390R1ml6eGl8f7//5twGZoDAA "05AB1E – TIO Nexus") **Explanation** ``` Ÿ # inclusive range 5.å # map 5 in y for each y in the list _ # logical negation O # sum ``` [Answer] # Pyth, ~~9~~ 8 bytes Saved a byte thanks to FryAmTheEggman! ``` lf-\5T}E ``` Explanation: ``` Q # Input }E # Form an inclusive range starting from another input # order is reversed, but doesn't matter f-\5T # Filter by absence of '5' l # Count the number of elements left ``` [Try it online!](http://pyth.herokuapp.com/?code=lf-%5C5%60T%7DE&input=4%0A17&debug=0) [Answer] # [Perl 6](http://perl6.org/), 23 bytes ``` {+grep {!/5/},$^a..$^b} ``` [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS1Ow/V@tnV6UWqBQrahvql@roxKXqKenEpdU@784sVIhTcFQR8HSmgvCNtFRMDS3/g8A "Perl 6 – TIO Nexus") ### How it works ``` { } # A lambda. $^a..$^b # Range between the two lambda arguments. grep {!/5/}, # Get those whose string representation doesn't match the regex /5/. + # Return the size of this list. ``` [Answer] # [Haskell](https://www.haskell.org/), 39 bytes ``` s!e=sum[1|x<-[s..e],notElem '5'$show x] ``` [Try it online!](https://tio.run/nexus/haskell#@1@smGpbXJobbVhTYaMbXaynlxqrk5df4pqTmqugbqquUpyRX65QEfs/NzEzT8FWoaAoM69EQUXBRNHQ/D8A "Haskell – TIO Nexus") Usage: ``` Prelude> 4 ! 17 12 ``` Explanation: ``` [s..e] -- yields the range from s to e inclusive x<-[s..e] -- for each x in this range x<-[s..e],notElem '5'$show x -- if the char '5' is not in the string representation of x [1|x<-[s..e],notElem '5'$show x] -- then add a 1 to the resulting list s!e=sum[1|x<-[s..e],notElem '5'$show x] -- take the sum of the list ``` [Answer] # R, 33 bytes ``` f=function(x,y)sum(!grepl(5,x:y)) ``` Usage: ``` > f=function(x,y)sum(!grepl(5,x:y)) > f(40,60) [1] 10 > f(1,9) [1] 8 > f(4,17) [1] 12 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 36 bytes ``` @(m,n)sum(all(dec2base(m:n,10)'-52)) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkauTp1lcmquRmJOjkZKabJSUWJyqkWuVp2NooKmua2qkqfk/Ma9Yw0TH0FzzPwA "Octave – TIO Nexus") [Answer] ## Groovy, ~~47~~ ~~45~~ ~~43~~ 40 bytes ``` {a,b->(a..b).findAll{!(it=~/5/)}.size()} ``` This is an unnamed closure. [`findAll`](http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html#findAll(groovy.lang.Closure)) is similar to adding an `if` condition in a list comprehension in python. [Try it online!](https://tio.run/nexus/groovy#@59mW52ok6Rrp5Gop5ekqZeWmZfimJNTraiRWWJbp2@qr1mrV5xZlaqhWcsVHW2gYxqrE22iY2gOpAx1DA2gFIg2BUqaxsbqpSYmZ1QXFGXmleTkKaQBjYkGygJJw1jN2v//AQ) [Answer] # PHP 7.1, ~~57~~ 55 bytes ``` for([,$a,$b]=$argv;$a<=$b;)$n+=!strstr($a++,53);echo$n; ``` Run with `php -r '<code>' <a> <b>` [Answer] # Mathematica, ~~46~~ ~~44~~ 42 bytes *Thanks to alephalpha and DavidC for saving 2 bytes each!* ``` Tr@Boole[FreeQ@5/@IntegerDigits@Range@##]& ``` Unnamed function taking two integer arguments and returning an integer. `IntegerDigits@Range@##` converts all the numbers between the inputs into lists of digits; `FreeQ@5` tests those lists to decide which ones do not contain any `5`. Then `Boole` converts booleans to zeros and ones, and `Tr` sums the results. Other solutions (44 and 47 bytes): ``` Count[Range@##,x_/;IntegerDigits@x~FreeQ~5]& ``` `IntegerDigits@x~FreeQ~5` determines whether the list of digits of a number is free of 5s, and `Count[Range@##,x_/;...]&` counts how many numbers between the inputs pass that test. ``` Tr[Sign[1##&@@IntegerDigits@#-5]^2&/@Range@##]& ``` `1##&@@IntegerDigits@#-5` takes the list of digits of a number, subtracts 5 from all of them, and multplies the answers together; `Sign[...]^2` then converts all nonzero numbers to 1. [Answer] ## Ruby, ~~36~~ 35 bytes ``` ->a,b{(a..b).count{|x|!x.to_s[?5]}} ``` Thx IMP1 for -1 byte [Answer] # Java 7, ~~80~~ 78 bytes ``` int c(int a,int b){int r=0;for(;a<=b;)r+=(""+a++).contains("5")?0:1;return r;} ``` **Ungolfed:** ``` int c(int a, int b){ int r = 0; for (; a <= b; ) { r += ("" + a++).contains("5") ? 0 : 1; } return r; } ``` **Test code:** [Try it here.](https://ideone.com/hR2BBr) ``` class M{ static int c(int a,int b){int r=0;for(;a<=b;)r+=(""+a++).contains("5")?0:1;return r;} public static void main(String[] a){ System.out.println(c(1, 9)); System.out.println(c(4, 17)); } } ``` **Output:** ``` 8 12 ``` [Answer] # PowerShell, ~~42~~ 41 bytes ``` param($a,$b)$a..$b|%{$z+=!($_-match5)};$z ``` Called from the command line as .\no5s.ps1 1 20 [Answer] # Regex `🐇` (Perl / PCRE), ~~160~~ 147 bytes `^(?(?=-x*,(?!-))-?+x*(,x*(?!$))?|-?(?=(x*),-?(x*))(?=(x*),?(?=\2)(?=\3)(x*,-?|[^,]*)(x*))\4,?+x*)(?!((?=(x+)(\8{9}x*))\9)*(x{10})*x{5}\b)(?(4)\4\6)` [Try it online!](https://tio.run/##RVDNUoMwEL7zFGkmhyxs2qBQpZSmztSrJ29imZZpZ3Boi1BncCgefQAf0RepCx31kGy@v80mxabM/fPunYkyZE1@SFc5E6OQYDRd3D3ezVpreyilqCIdTmchNCzbEoKmKLP9kfF4z8OWVJcieVS9rasjuRNULrqwee10889q4mEikpC6MClyajenVJFnR8mRIzGhxZhI6Tb2csj2PbtbFQ2lp9pwxSecw5DXvGardUUstPMcoo@RNBNRgjSmcRyRom6BXnEZ8q8ROYecfX9@MT4UKU18ormttk2S@4dFkpyX0kgTqdpGaQYKQBmntiXSMgMBYE6q02VtA9KJCvzCjo@vOhhfAzGkn56W@GxDb4s97FqRPpB9xAEZ3zZB24sB2LJuXBrZrhu/jdfkkx6F4jGczy4GlofujeVrHGtL@QEq/1I76GqNLlUvCALsNqv7@h8 "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##hVbrbuJGFP7PU0zYKsyYIcW5NeA4KE2QgpSQFUvU7YasZcwAVszY8mVDLvztA/QR@yBNz1wMJrAqAnvmXL5znTN4UVSbeN77pxEb@5yhzxe99r5zcXvZdu66nb7zR@eyf4VOSp987gXZiKHTyIvZ/t70rORN3Rg50f0DslGv/PvT0@PwIPvz@flrf3r8NMXv33ELt@za3KC4tVMjpNaqzg1M4dfa@YWQ1ltN8PHcIBRW8CL5VtAH@2I7OCBAAf7b/Xf6YBApNjikAgr4O1iqVAkenLw2FpLZIAaev5r1BTHmr0eLwRDk8CEoDY7JO/noZpkiI7KdqGpahRiTNPb5RAS5ovkhUJk7O9uQOyv5PEURLFOHxXEYYy/kSYpkgowZSxJ3wgh6TdJRs@mBBDo9RZoslpLO@CiwUMzSLObItBYbmGLvhSNG0TAMAxTaYzdIBKw0o@Hu94@OH6wSgo8/RljWypkwjeFoKaxwsCr23cXVee/EIJpJUeK/sHCMl47/mlMK8oQQaUV8cIhaKggvzFLURMtAiQivLNWQ9KCJyh@Cl8rlMmiVB7xMlvkYB1kyVZEsk1JalDKe@BPORigI@UQ9XJ48sdiSCZs9O54bBOCGjl3vnGEQeo/I8Cj6EfojZIzc1IXciSSJJbJthAXHILsrDKKxq9VlZeq6MjPX5xgApIPRPTRCwDiOSM18sOuWCkF1B4o8u4xbzbIFq6odqVcZuvJCdDABegaIB/tOCkUFXQE/gYWELgL5PMpSoS4DgxIiI2b5fuam3tSRsRirtUKLWZIFKVUlsPQZ/9L51paU8ThhwIR4IYRJOl0TMMIfzEtBS1cCznpufxb5AcO6Kb587vdI5O15DjiLCdUY39q9W6ff7t10uuf99mVObn/tt7uX7Uv0pgk3d9f9znWn26ZoV3qp39q3Oln19E4MLamrUTwf8qnlCsmwN/LjwN5NmTOOw5kTuWnKYo5j6Pvu3fW1BijqwGFO2TyFtOYrextfw@INFIhg2ZQ5BC10Kt3WeR8BlKnAn/lFkJpJrILQiEXp/wrFzMvixA/5VkFpdhzGSM6bl2UvwwwJ4H7A6mj7nKpuJFZ@BvLyvBAEdDGTcGXAK2D6xTYtyZIae2KWYGLbdYKEZZ9nzFohgFHoQmFWTc9kxVt6FYUJCKxZznU5e3JAnyIORXLT0NdGdVuiqlCG7uSiMdxhgrnYCGGgVBHmp3mrFWMSOh@MLc@mHHliytGytSkBwFgEYhBoDqishxMot/YSmOJZRSb8OBfemWQLyD1IVavimq3Qyjp/gRhcAtt8W1meKcMFq9ttLTbiFtlQ5qXx2gfjMzaDhsIJYKk4pAJFlXlFZBhKL3WFQWVaoOQNleeNr2NCqkFIFQ3@kIwwhEwlVTqcl0PM68JobDa5rNEQsvxoKXFbXBibsa0XDf3z198IJrCa89K9paSamuuHXc6J4siDcsp@q8vvasjAWp@rQpaF8wr1tI52d7WFHVsPxV7vtud0b2/O@xdXZD0rhTmXD/M0zlgBW/RB6afdqePbcrkufjbvYD4yhldRbM5RJbDck@LVpJgwqpc3p/Ib7vB3kzZKh9T8rXRUp8f1Uu2oQWtH6i22Zr1OTXgfNhoNKh5Aoua/3jhwJ8l7LZBGaif/AQ "C++ (gcc) – Try It Online") - PCRE (faster) Takes its input in unary, as two strings of `x` characters whose lengths represent the numbers, with optional `-` signs on their left side, joined by a `,` delimiter. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.) Most of the logic of this regex is taken up with handling the logic of integer ranges. It's rather unnatural... literally. Natural numbers (including zero) are much easier for a regex to operate on. ``` ^ (?(?=-x*,(?!-)) # Do the following if A is negative and B is nonnegative -?+ # skip sign of A, if any x* # handle the range from larger to zero, inclusive (,x*(?!$))? # handle the range from B inclusive to zero exclusive | # Do the following if A is nonnegative or B is negative -? # skip sign of A, if any (?= (x*), # \2 = abs(A); -?(x*) # \3 = abs(B) ) (?= (x*),?(?=\2)(?=\3) # \4 = what to skip so tail = the larger of A or B; # tail = the larger of A or B (x*,-?|[^,]*)(x*) # \6 = {the smaller of A or B} - \4 ) \4,?+ # tail = the larger of A or B x* # handle the range from larger to {smaller or zero} ) (?! # Negative lookahead - assert this can't match ( (?=(x+)(\8{9}x*)) # \8 = floor(tail / 10); \9 = tail - \8 \9 # tail = tail - \9 == \8 )* # Iterate the above any number of times, minimum zero (x{10})*x{5}\b # Assert tail % 10 == 5 ) (?(4)\4\6) # If \4 is set, clamp the range at the smaller end ``` It uses conditionals, which are not supported by ECMAScript, but it'd be easy enough to port (though the regex would be even longer). The `🐇` output method is required for this algorithm to be possible in ECMAScript (there isn't yet a regex engine that can emulate ECMAScript and count possible matches, but I'm planning on adding this to [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/) soon). # Regex (.NET), 163 bytes `^(?=(-x*,(?!-))?)(?>-?)(?(1)|(?=(x*),-?(x*))(?=(x*),?(?=\2)(?=\3)(x*,-?|[^,]*)(x*))\4(?>,?))(?(,)(?(1),)|(?(((?=(x+)(\8{9}x*))\9)*(x{10})*x{5}\b)|())x?)*(?(4)\4\6)` [Try it online!](https://tio.run/##RZBBTsMwEEX3PYWJjDKT2lUMbSGtgkGsOUFSUFpMY5QmUeKqFmm2HIAjcpHiFCEW9sz/8/U0mro6qKbNVVGcaBMnjdoqu1osSnWAe//0DDIGbgMG8oIjSgR5x4cfBB6HmQ2QcTkU/JPSNenVINNrdI6bH5NntgrwHEunjsHkkAf2S2IDC@AMGCOkt13Un6MRBmA7EfYY2G7Wp2sXRLTS2RKmDpXO8eTfM@@x2tW6UK8eLulHHC7fqkZlmxxoQXRJqC7rvcGOZjEteFsX2njMWxJqY6AZOZJL0vncDyDRpVnRF14YEuLYt36QPGUmd/d4WLd/U@yRv1e6PCP0G9BdTJuJy21y1QK1iN3gfmB3aLRRPK9a07utxJL8G4SXlbtxoUtFPLfl9@cXoQ412TbVvm4TIVaTTVabfaPayabalwa9vj8JFo2mTNyMZiGbhyM@ixif/dZBijBkwtUoiph7zmDiBw "PowerShell – Try It Online") Returns its output as the capture count of group `\11`. ``` ^ (?= (-x*,(?!-))? # \1 = set iff A is negative and B is nonnegative ) (?>-?) # skip sign of A, if any (?(1) | # Do the following if A is nonnegative or B is negative (?= (x*), # \2 = abs(A); -?(x*) # \3 = abs(B) ) (?= (x*),?(?=\2)(?=\3) # \4 = what to skip so tail = the larger of A or B; # tail = the larger of A or B (x*,-?|[^,]*)(x*) # \6 = {the smaller of A or B} - \4 ) \4 # tail = the larger of A or B (?>,?) # skip sign of B, if any ) # First handle the range from larger inclusive to # {smaller inclusive or 0 exclusive} (?(,) (?(1),) # If crossing from negative to nonnegative, handle # the inclusive range from B to 0 | (?( ( (?=(x+)(\8{9}x*)) # \8 = floor(tail / 10); \9 = tail - \8 \9 # tail = tail - \9 == \8 )* # Iterate the above any number of times (x{10})*x{5}\b # Assert tail % 10 == 5 ) | () # Push a capture onto the \11 stack ) x? # Advance by 1, but if already at the end, allow the # loop to iterate once more so as to include 0 in # the count. )* (?(4)\4\6) # If \4 is set, clamp the range at the smaller end ``` It could also be ported to an output method of the sum of the lengths of two capture groups (two, because the output can exceed the largest of the two inputs), though this would probably make it significantly longer. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Id5ȷc~ ``` (No ATO link since it's down at the moment) #### Explanation ``` Id5ȷc~ # Implicit input -> 1, 10 I # Inclusive range -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] d # Cast to digits -> [[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0]] ȷ # To each list: -> [1] [2] [3] [4] [5] [6] [7] [8] [9] [1,0] 5 c # Count 5s -> 0 0 0 0 1 0 0 0 0 0 ~ # Logical NOT -> [1, 1, 1, 1, 0, 1, 1 1, 1, 1] # Implicit sum -> 9 # Implicit output ``` [Answer] # Python 2, 61 56 bytes ``` lambda a,b:len([n for n in range(a,b+1) if not"5"in`n`]) ``` -5 bytes thanks to tukkaaX [Answer] ## Swift 52 bytes ``` ($0...$1).filter { !String($0).contains("5") }.count ``` [Answer] ## Batch, 95 bytes ``` @set/an=0,i=%1 :g @if "%i%"=="%i:5=%" set/an+=1 @set/ai+=1 @if %i% leq %2 goto g @echo %n% ``` Manually looping saves some bytes because I need the loop counter in a variable anyway. [Answer] # PHP, 56 bytes ``` for($i=$argv[1];$i<=$argv[2];)trim(5,$i++)&&$x++;echo$x; ``` Run like this: ``` php -r 'for($i=$argv[1];$i<=$argv[2];)trim(5,$i++)&&$x++;echo$x;' 1 9 2>/dev/null;echo > 8 ``` A version for PHP 7.1 would be 53 bytes (credits to Titus): ``` for([,$i,$e]=$argv;$i<=$e;)trim(5,$i++)&&$x++;echo$x; ``` # Explanation ``` for( $i=$argv[1]; # Set iterator to first input. $i<=$argv[2]; # Loop until second input is reached. ) trim(5,$i++) && $x++; # Trim string "5" with the characters in the # current number; results in empty string when # `5` is present in the number. If that is not # the case, increment `$x` echo$x; # Output `$x` ``` [Answer] # CJam "easy pure mathematics solution", 60 ``` {{Ab5+_,\_5#)<\9e]);_4f>.m9b}%}:F;q~_:z$\:*0>{((+F:-}{F:+)}? ``` [Try it online](http://cjam.aditsu.net/#code=%7B%7BAb5%2B_%2C%5C_5%23)%3C%5C9e%5D)%3B_4f%3E.m9b%7D%25%7D%3AF%3Bq~_%3Az%24%5C%3A*0%3E%7B((%2BF%3A-%7D%7BF%3A%2B)%7D%3F&input=%5B-22222222%201234567890%5D) It takes the numbers in any order, in an array. **Explanation:** One core problem is to calculate f(n) = the number of non-5 numbers from 1 to n (inclusive) for any positive n. And the answer is: take n's decimal digits, replace all digits after the first 5 (if any) with 9, then replace all digits 5..9 with 4..8 (decrement), and convert from base 9. E.g. 1752 → 1759 → 1648 → 1\*9^3+6\*9^2+4\*9+8=1259. Basically, each digit position has 9 acceptable values, and a 5xxxx is equivalent to a 49999 because there are no more valid numbers between them. Once we solved this, we have a few cases: if the input numbers (say a and b, a<b) are (strictly) positive, then the result is f(b)-f(a-1). If they are negative, then we can take the absolute values, reorder them and use the same calculation. And if a<=0<=b then the result is f(-a)+f(b)+1. The program first implements the function F as described above (but applied to each number in an array), then reads the input, converts the numbers to the absolute value and reorders them, and uses one of the 2 calculations above, based on whether a\*b>0 initially. [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` i,j=input();k=0 while i<=j:k+=not"5"in`i`;i+=1 print k ``` [Try it online!](https://tio.run/nexus/python2#@5@pk2WbmVdQWqKhaZ1ta8BVnpGZk6qQaWObZZWtbZuXX6JkqpSZl5CZYJ2pbWvIVVCUmVeikP3/v66hmY4ZAA "Python 2 – TIO Nexus") Not the shortest Python answer Uses same algorithm but a different way of implementing with a while loop and is not a lambda function. [Answer] # C++ | in too many bytes, 165 125 thanks to Christoph! ``` int main(){int c=0;for(int i=0;i<=8;i++){int d;int n=i>=0?i:-i;while(n!=0){if(d=n%10==5){break;}n=n/10;c++;break;}}return c;} ``` I took the liberty of creating a function `e_` to determine if a 5(or any other number) is present in an integer instead of using `to_string()` and `.find()` so that must count for something. *note: `e_` is only declared as an extra function in the un-golfed version for readability.* un-golfed: ``` int e_(int e,int i){ int d; int n=i>=0?i:-i; while (n != 0){ d=n%10; if (d==e){ return 1;} n=n/10;} return 0;} int main() { int l = 1;int h = 8;int e = 5;int c = 0; for(int i=l; i<=h; i++){ if (e_(e,i)==0) c++;} return c;} ``` **How `e_` function works:** `int n=i>=0?i:-i;` Inverses our number if it is less than 0 so it's always positive. `d=n%10;` Divides it by 10 and gets remainder (`n%base;` will always return the last digit of an integer). We check that it equals 5, if it does the number can be discarded, if not `n=n/10;` removes the end digit and loops again. [Answer] ## Hoon, ~~110~~ 94 bytes Hoon's range function, `gulf`, doesn't work for signed integers, which increases the length by a bit :( ``` =+ si^f=:(curr lien test 53) |= {a/@s b/@s} |- ?: =(a b) (f <b>) (add (f <a>) $(a (sum -1 a))) ``` Use the signed integer library. Create a function `f`: `:(a b c d)` is a macro that expands into `(a b (a c d))` so this is `(curr lien (curr test 53))`, aka create a curried function that tests if any element of a list is 53 (`'5'`) Create a function that takes `a` and `b`. Create a loop: if `a==b` return `f(tostring(b))`, else return `add(f(tostring(a)) recurse(a=a+1))` ``` > =f =+ si^f=:(curr lien test 53) |= {a/@s b/@s} |- ?: =(a b) (f <b>) (add (f <a>) $(a (sum -1 a))) > (f -1 -9) 8 > (f -4 -17) 12 > (f -50 -60) 1 > (f --59 --50) 0 ``` (Hoon's signed integers use `-` as a prefix, so `--5` is negative 5 and `-5` is positive 5) [Answer] # SmileBASIC, 55 bytes ``` INPUT S,E FOR I=S TO E INC N,INSTR(STR$(I),"5")<0NEXT?N ``` Nothing special, just uses `INSTR` and `STR$` to check for `5`. [Answer] # Java 7, 77 bytes This is an improvement of [Kevins Answer](https://codegolf.stackexchange.com/a/107475/58696), but since I don't have the reputation to comment yet, this new answer will have to do. So what I did was: * Replace the `indexOf` statements with `contains` (-1 byte) * Move the incrementing part of the for-loop into the conditional statement (-2 bytes) --- for-loop (**77 bytes**): ``` int c(int a,int b){int r=1;for(;a++<b;)r+=(""+a).contains("5")?0:1;return r;} ``` recursive (**79 bytes**): ``` int d(int r,int a,int b){r+=(""+a).contains("5")?0:1;return a!=b?d(r,a+1,b):r;} ``` **Output:** ``` 8 12 8 12 ``` Test it *[here](http://ideone.com/X7lsXF)* ! ]
[Question] [ > > This question is part of a series Brain-flak Birthday challenges designed to celebrate Brain-Flak's first Birthday. You can find more information about Brain-Flak's Birthday [here](https://hackmd.io/KwRgnARiAcCGAsBaaEBMAGR8DG8Cmis0AZsVhPLOtsWAOzQAmIQA?view). > > > Today is Brain-Flak's first Birthday! So I thought we would throw it a surprise birthday party. So in your favorite language print ``` Surprise! Happy Birthday, Brain-Flak! ``` *(Trailing whitespace is permitted)* As always programs should be golfed. However since Brain-Flak programs are made of brackets, it wont count any brackets in your source against you. (The characters `()[]<>{}` don't count towards your byte total), but they must be balanced as to not upset Brain-Flak. # Rules Here is a breakdown of the rules * The brackets in your source must be balanced. That is the parentheses of your program must be spanned by the following grammar: `S -> SS | (S) | [S] | <S> | {S} | E` where `E` is the empty string. That is to say that a balanced string is either the concatenation of two balanced strings, braces around a balanced string, or the empty string. * The score of a program is the number of non-bracket bytes. * Your goal should be to minimize your score in whatever language you choose. * Standard rules apply so you may write either a complete program or a function. * in the event of a tie raw byte count acts as a tie breaker There are certainly going to be zero byte solutions in certain languages ([Parenthesis Hell](https://esolangs.org/wiki/Parenthesis_Hell), [Parenthetic](https://esolangs.org/wiki/Parenthetic), [Glypho](https://esolangs.org/wiki/Glypho), [Lenguage](https://esolangs.org/wiki/Lenguage)). Try to find ways to golf well in languages where this is not a trivial task. [Answer] # [Haskell](https://www.haskell.org/) (before GHC 8.4), (~~10119 7767 7626~~ 7540 bytes), score ~~15 14~~ 10 ``` (<>)(<><>)(<>)(<<>>)()=(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)(<><>)))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))<<>>((<><>)<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))<<>>(((<>)((<>)((<>)((<>)((<>)(<><>))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))<<>>((<><>)<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))<<>>(((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)((<>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))<<>>[]))))))))))))))))))))))))))))))))))))) (<>)'y'pred(:) ``` [Try it online!](https://tio.run/nexus/haskell#@69hY6cJxBASiG3sgKSmrYYGmDtkCbCPiAMgL2vgNwS3EjzWEq0Jl6vpZSu5wUmMVUgaaeMykiKffk4YJQY0T5MORpPGKDF4UuNoIqVOcA9sgOF1M/2aB/gNAIuNln6j5dFoyUPvYB9kbXVS@xIIpTRMHdjDl87JEXckD/oKZrR4H85F9GjEjiaK0QQyaOtt2g/MDVRXhObtEGJMHE3cw67wGo1SCkKVSoGHaf0IKbuwWDSaHkeLJzwpLzqWKKVcurog96hXqhcUpaZoWGn@z03MzFOwVSgoLQkuKVJQUUCV1tD8DwA "Haskell – TIO Nexus") The last line defines an anonymous function `(<>)'y'pred(:)`. Call with `(<>)'y'pred(:)()` to yield the string. **Edit:** A huge thanks to [@Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) for suggesting to pass the helper functions as parameters instead of declaring them, saving *four* scoring bytes! The non-bracket bytes are ``` = 'y'pred: ``` ### How does it work? A string `"wxy"` in Haskell is syntactic sugar for a list of characters `['w','x','y']`, which again is syntactic sugar for the subsequent construction with the cons operator `:` and the empty list: `'w':'x':'y':[]`. By defining `(<<>>)=(:)` we yield the same string by writing `'w'<<>>('x'<<>>('y'<<>>[]))`. Because chars are ordered, we can compute the predecessor of each char with a function called `pred`. Using only the char `'y'` and `pred`, the string becomes `pred(pred 'y')<<>>(pred 'y'<<>>('y'<<>>[]))`. By defining `(<>)=pred` and `(<><>)='y'` we can represent the string using balanced brackets only: `(<>)((<>)(<><>))<<>>((<>)(<><>)<<>>((<><>)<<>>[]))` However, in the end we don't want a string but a function returning a string, so we define our cons operator as `(<<>>) x xs ()=x:xs` instead. (Of course with `x` and `xs` replaced by identifiers using balanced brackets only: `(<<>>)(<>)(<><>)()=(<>):(<><>)`). This way, `((<>)((<>)(<><>))<<>>((<>)(<><>)<<>>((<><>)<<>>[])())())` is a function of type `() -> String` and appending a final `()` yields the original string: `((<>)((<>)(<><>))<<>>((<>)(<><>)<<>>((<><>)<<>>[])())())()` Using this method we achieve a solution with score 15. However, we can condense the three declarations into one by declaring a function which takes four arguments: `'z'`, `pred`, `(:)` and `()` for calling. --- The following function `encode` encodes a string with chars smaller or equal to `'y'` in this way: (Why `y`? Because it's the largest char in `"Surprise!\nHappy Birthday, Brain-Flak!"` and thus yields the shortest representation. Thanks again to Ørjan Johansen for pointing this out.) ``` c x = let l = fromEnum 'y' - fromEnum x in "(" ++ ([1..l]>>"((<>)") ++ "(<><>)" ++ ([1..l]>>")") ++ "<<>>" encode s = concatMap c s ++ "[]" ++ ([1..length s-1]>>")()") ++ ")" ``` [Try it online!](https://tio.run/nexus/haskell#VU49D4IwEN39FY/GoQQhqTMwkGhcnBiRoSlViKU0pSTy67EYSXS6e/e@bhF4IYOSDspPdmSIcbdDf9JT7yl0GoQSRBFoxZJE1XlOKE3zkITrkfh1Bf@CjUxTD7CTWgyNxOgLxKAFd1duIDxeNVX9Y5b64VqMMfuk0C0nJEvP/ScZzORKZ7HHN5OUkzW2G2Vw0xduzIyis65t@HxAYb0nPiv@DMjyBg "Haskell – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ ~~37~~ ~~36~~ 34 bytes *-1 thanks to dzaima* *-2 thanks to Erik the Outgolfer* ``` exec("".join([chr(len(x))for(x)in'()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()())'.split("{}")])) ``` [Try it online!](https://tio.run/##5ZUxDoAgEAT/QuNdY@F3jJXBiDFA1EJjfDv6BExk0TMUlLN7sHt@W3pnqxD0qltSqhycsVS3/USjtrQyd266LmMLYuzZDzQRykTbyzHOG9Qk8vJ4JuE/V35WkNAITFol3y0igHLRscq6GSLH@4Q4nEH@R/VjqRhSekrGoN1ES4ul0Fd@@ep@TB7WprAiiIBF6@GinP1oFlL7obhhDuEE "Python 2 – Try It Online") Relevant characters: ``` exec"".joinchrlenxforxin''.split"" ``` # Explanation This program builds the string: ``` print"Surprise!\nHappy Birthday, Brain-Flak!" ``` It does this by converting a long string of parentheses into character codes. Once the string is built it executes it. It builds the string with the skeleton: ``` "".join([chr(len(x))for(x)in'<...>'.split("{}")])) ``` This splits the string along `{}` and maps each section to the character code corresponding to its length. We can then build the entire string out of parens for a cost of zero bytes. [Answer] # [Retina](https://github.com/m-ender/retina), 59 - 24 = 35 bytes ``` Su{p()se!¶Ha<<>[]i{thd}>,[](a)n-Fl}k! T`<>()[]{}`\pyri Bra ``` [Try it online!](https://tio.run/nexus/retina#@88VXFpdoKFZnKp4aJtHoo2NXXRsZnVJRkqtnU50rEaiZp6uW05ttiJXSIKNnYZmdGx1bUJMQWVRpoJTUeL//wA "Retina – TIO Nexus") By comparison, the boring solution takes 38 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` “”Lb⁹Ọ ``` Inside the `“”` you need to put the output of this Jelly program: ``` ⁾()Ȯ“cWṪḂÇa'ỴOḞḊʂFGĖƓẋ0Ɗ/⁷ẓƊĖṘḲ"ÇẈW'ⱮḟėıḲ7¿’¡ ``` *-1 byte thanks to [Jonathan Allan](/u/53748) (allowed trailing newline)* There are 53127666317289661939246122975355844970973062889031671423309402549417051416384149‌​80886139013 (we'll call this `n`) `()`s between `“”`. **Explanation**: ``` “”Lb⁹Ọ ḷ“Main link. Arguments: 0” “” ḷ“String containing n pairs of round brackets” L ḷ“Take its length” b⁹ ḷ“Convert to base 256 (ints representing digits)” Ọ ḷ“Convert char codes to chars” ``` [Answer] # [Lenguage](https://esolangs.org/wiki/Lenguage), 0 bytes Just 10024793746353848520175158940670214213802394805963081469362831141755126591573942436182287015467334956253918417576118983828148929806934751198148656645940502264502520032312455157880058174845907554602116807351044784410936407102892289953027884533102082518964744402664917253792543505897552998982122997648280947470217067174451441654554437678556775097996646071948 bytes made of balanced brackets. Python 3 program to generate my favorite version, given enough time and memory: ``` for i in range(0x4e24a0fa26624a0fa00084984c021249249800000004000c5001f509c4941f5312507d18062800007d4c494000fa10e0112497d4800000021c49283e80831403ea1c4941f44c000000100849249249309261260c4941f400871280003ea124924924c18a01f50938924a0fa30018a003e80800000100004c492500fa10625001f421389283ea124924926000000010601125f46):print(end='()') ``` [Answer] # [Haskell](https://www.haskell.org/), (~~12006~~ 13485 bytes), score ~~18~~ 17 EDIT: * -1 byte: Got the `toEnum` version to work without extensions by moving the `toEnum` to the main function, at the cost of a `$`. * -1 byte, then +1 again: If you look in the edit history, you'll see I changed to something completely different. And only later did I check the other answers and see that @Laikoni had done almost the same idea one hour earlier, and got it a byte better! So I rolled back to my earlier method. Use as `putStrLn$(<<>>)()`. ``` (<<>>)<>(<<<>>>)=length(<<<>>>):(<<>>) (<<>>)()=toEnum<$>... ``` [Try it online!](https://tio.run/nexus/haskell#7do9CsIwGIDh3XN0aK4gSTY3N0dxcBAVbBRJz18jpZMHUPAZ3v7QFsr3ZCl0OF5Leox1V5/b0vUx5hz6MM0HMbd9O8gh3U7lXC/L6Xq@vlruT/W@KeMQu7w/tIfem@8XfuZNRIyEqJkOV@tOpESCpmkwsZJEmoSoUBJV0RQp35Gy3kRRFEn8y5SCf8hEhqhIiaYo0hRZfU50ml4 "Haskell – TIO Nexus") where `...` is the result string of the following expression: ``` convert="[]"++concat["<>([]"++([1..fromEnum c]>>"<>[]")++")"|c<-reverse"Surprise!\nHappy Birthday, Brain-Flak!"] ``` The only non-balanced characters are ``` =length: =toEnum$ ``` The following variant (13484 bytes) has score 16 except that it needs GHC's `ExtendedDefaultRules` extension, and so only works in GHCi by default. (Unless you like heaps of warnings, you also want `-fdefer-type-errors` and `-Wno-deferred-type-errors` for some reason.) ``` (<<>>)<>(<<<>>>)=toEnum(length(<<<>>>)):(<<>>) (<<>>)()=... ``` [Try it online!](https://tio.run/nexus/haskell#7drBaoNAFEDRvV8h2IWzmB8IKoRWTCAkJWnoopQi@EwCZgzTERpCv92YiJu2@wZyF1dFniBzZiN40oG/eH6ZLuarj2zy6OuykFKsdseDaLG2tp9@oL@908@5V1Pr66iV4s/p2XiercdZ6qdfTkwhxZOUeVO5ZVNJP7XPdyY@NG7l7Mw8hFGUJCpUbX8RJd25u0hU7OrUNPuwErNx2@GuGvVz3vBc/PbePXM5/H/qZt6EEEOCUGN1cGXfEVKEBJqsBibsJEIaCUIFJUKV0CSk@I4k9huhSCgicS@rpPiHjJBBlJAiNAlFNAlZ@r2ibXsG "Haskell – TIO Nexus") # How it works * Haskell allows defining your own (multi-character) operators, and `<>` are legal operator characters. Moreover, if parenthesized, these can be used for any value, not just two-argument functions. * `(<<>>)` on the second line is the main function, it takes a single dummy argument `()` and returns the final string. * The operator `<>` takes two lists and prepends the *length* of the second to the first (in the second version, also first converting the length to a character.) Operators are left associative by default, so this chains easily. * A list of any length can now be constructed by chaining empty lists `[]` with `<>`. * The final string can now be constructed by chaining lists whose lengths encode the desired characters – this uses only balanced `()<>[]` characters – and then (in the main version) mapping `toEnum` over the resulting list. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~19~~ ~~14~~ ~~13~~ ~~10~~ ~~9~~ 8 bytes ``` "(()()...()()<"q>)m(l)m(d)q ``` where the string at the beginning is: ``` (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()<>()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()<>()()()()()()()()()()()()()()()()< ``` The total byte count is "only" ~~6694~~ ~~3394~~ 3354, so you can [try it online!](https://tio.run/nexus/japt#@6@koUl1aGNHA0MJQs2BsJb@dg5zXw6E9@jlP8LWoLuEeg6jgxdHQl4YmKKNyERKDccN86w@MPFHP1vpYxPtbRnAjEZiuhx22XKYxjK9Q5A0@6gWEvT15jBrVRDhH02lQg0lGzslzVyNHCBO0Sz8/x8A) ### Explanation The actual method used is explained in other answers: Split on `<>`, map each run of parens to `chr(len(x))`, join again on the empty string. Here, it's the golfing that's the fun part. Before "golfing", the original code might look like ``` "..."q"<>" mZ{Zl d} q"" ``` which is a quite literal description: `"...".split("<>").map(Z => Z.length.toChar()).join("")` Now we need to minimize non-bracket chars. How? Well, first we can do some actual golfing: ``` "..."q"<>" ml md q ``` This roughly represents `"...".split("<>").map(Z => Z.length).map(Z => Z.toChar()).join()`. Now we can abuse the confusing way Japt treats parentheses. `(` represents going up one level, as in most languages, but `)` represents going down *two* levels (a space goes down one level), which means we can optimize the code to: ``` "..."q("<>")m(l)m(d)q ``` This code acts just the same as the above, but uses two fewer non-bracket chars. Additionally, if an operator is the first input to a function, it gets turned into a string so that the function can decide what to do with it. This means that we can avoid the quotes if we just make every run of parentheses 1 byte shorter, and split on `>` instead (with some clever arrangement to cancel out the resulting `>)` in the code): ``` "(...<"q>)m(l)m(d)q ``` This saves us a further two bytes, since we took out two of the quotation marks. [Answer] # [Haskell](https://www.haskell.org/), (~~1965 3131~~ 18073 bytes), score ~~31 23~~ 19 ``` (<>)=(:) (<<>>)=['\n'..] (((<<><>>):(<<<>>>))<<>><>([()]:(<><>)))()=(<<><>>)<>(((<<>>)<<>><>(<><>))()) (((<<><>>):(<<<>>>))<<>><>((<><><>):(<><>)))()=((<<<>>>)<<>><>(<><>))() f=(<<>>)<<>><>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([]<>([()]<>([]))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) ``` [Try it online!](https://tio.run/nexus/haskell#7ZexbsIwFEX3fMVTVIn3hIJgjZJs/QJGmiGEEFDBVCYM/XrqJJSqHTrSDucOxy/2w1Z8bwZ2kqay7PzetZIU9yqRxtWnTSOVnMepy7nnujpUrm42svZV/dp0Zzm5w3u0k1UpucSrMg611qm38NiKbv3p@OwuR6klkcXcxEetzMUPzWplVmgs06nswlQYYovDurut31dbdcnC7i1XzQrLNbVIs6wI5Wry4iazWRmp9jP9XBqKMBZm/RA26k8Lk6E0Mw0/vzWGJR23uTWOLWr2225DVzYsfO342fRjo2ibfztgeC/wIIwh4yoA6QDEARACQBwADgMygZuPOJk48S3iHCAEgBAA8D8TQ0y5HhzmKgBxAAQDcwFGApwDJIY/@IQIEAeAcwCHAdYTWK4MYDjOcQt4/aiTDSGEEEIIIfT3uh6rvZNc3i7dsvPyJFu16wc) Usage: The last line is an anonymous function. Bind it to e.g. `f` and call with `f()`. The 19 non-bracket bytes are ``` =: ='\n'.. ::= ::= ``` plus a trailing newline. --- ### Score 23 version (3131 bytes): ``` (<<>>)=['\n'..] (('{'{-}-}:(<><>))<>((<<><>>):(<<<>>>)))()=(<<><>>):((<><>)<>(<<>>))() (((<><><>):(<><>))<>((<<><>>):(<<<>>>)))()=((<><>)<>(<<<>>>))() "[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][]{{}}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][{}][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][{}]"<>(<<>>) ``` [Try it online!](https://tio.run/nexus/haskell#@69hY2Nnp2kbrR6Tp66nF8uloaFerV6tW6tba6VhY2djp6lpY6cBUgRSBhQCKQcKampo2iJEISqBCsGGAeWAxoDFbMB6CBiDpBsiCtSfZqsUHUslWF0bG00vSDe7qmtH/TMIw4vGNuEyu7q6tnYwunl4pVL6pSG89pHt22GTx@hYotPYTzT0yRDP06TYhyMUyXbpkK/1hkVOJyYWKIopOviCVimJ9ikUlw1AcSVYS/9/bmJmnoKtQkFpSXBJkYKKQpqChuZ/AA "Haskell – TIO Nexus") The 23 non-bracket bytes are ``` ='\n'.. ''--::=: ::= "" ``` --- ### Score 31 version (1965 bytes): ``` (<<>>)=['\n'..'~']++(<<>>) putStr[(<>)|('{'{-}-},(<>))<-zip">[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][{}][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][]{}[][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][{}][][][]{}{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}][][][{}][]{}[][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][{}][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{}[][][][]{}][][][][][][][][][][][][][][][][][][][][]{}"(<<>>)] ``` [Try it online!](https://tio.run/nexus/haskell#@69hY2Nnp2kbrR6Tp66np16nHqutDRHjSrMtKC0JLimK1rCx06zRUK9Wr9at1a3VAXE1bXSrMguU7KJjqQOraylXQV1YXUtPGxF20cnW6lqqxxBt458s3Wi@pHcaQnUDPtuplv6RbKObb0lOSwObWqhpI7EuGURxQWps0SN2YXaAaXLCitgSYMBTMHJBT4LvlCB1cuz/3MTMPAVbhbT/AA "Haskell – TIO Nexus") After all brackets are stripped, these 31 bytes remain: ``` ='\n'..'~'++ putStr|''--,-zip"" ``` ### How does it work? `['\n'..'~']` yields the list of all characters from newline to `~` which includes all printable ASCII chars. `(<<>>)` is an identifier chosen to have zero bytes under the given scoring rule. `(<<>>)=['\n'..'~']++(<<>>)` thus yields an infinite repetition of the list of chars. In the second line `zip"> ... "(<<>>)` zips a long string of brackets with the infinite string, yielding a list of tuples with a bracket char in the first component and some ASCII char in the second. For each tuple in this list we check if it matches the pattern `('{'{-}-},(<>))`, that is whether it has a `{` bracket as first component. `{- ... -}` is an in-line comment in Haskell, so `'{'{-}-}` is a balanced version of `'{'`. If the match is successful the second component of the tuple is bond to the identifier `(<>)` and added to string build via the list comprehension. Finally `putStr` prints the string. `putStr[(<>)|('{'{-}-},(<>))<-zip"> ... "(<<>>)]` --- Directly printing the string is 46 bytes: ``` putStr"Surprise!\nHappy Birthday, Brain-Flak!" ``` [Answer] # HTML, 37 Bytes ``` Surprise!<p>Happy Birthday, Brain-Flak! ``` ``` Surprise!<p>Happy Birthday, Brain-Flak! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes ``` …·»! ™”ŽØ¢©,žÞ”"-Flak!"J ``` Uses the [**05AB1E** encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md). [Try it online!](https://tio.run/nexus/05ab1e#ASsA1P//4oCmwrfCuyEK4oSi4oCdxb3DmMKiwqksxb7DnuKAnSItRmxhayEiSv// "05AB1E – TIO Nexus") [Answer] # Pyth, ~~4⃠~~ ~~3⃠~~ 2 bytes *Crossed out 4 is not regular 4 if you use ~~zalgo~~ Unicode magic* *Thanks to Roman Gräf and Neil for saving 1 byte.* The code is `Cl(()()()`…`()()())` where the outer parenthesis contains `41505989310382548390036033574496753883572705382055993299460470741732071419050117038172961` concatenated copies of `()`. (Stack Exchange did not allow me to post the full code.) Creates a tuple (`(`…`)`) of empty tuples (`()`), takes the length (`l`) and converts it to a base-256 string (`C`). [Answer] # [Japt](https://github.com/ETHproductions/japt), 6687 bytes, score 5 ``` (([[[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]][[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]]]ml)md)q ``` [Try it online!](https://tio.run/nexus/japt#7dixDQAgCETRdWAmQmcphfsXuIADAP7YGx8kHDFFzMw7HG/yTqwo6SMmnB0t7zvqVWlC35j/CP8016gauY0SKSJ2EPKLZCRFMGDqratVubl9ZHIM/wXz2BpLT@YF "Japt – TIO Nexus") This is in a similar vein as my [other Japt answer](https://codegolf.stackexchange.com/a/118172/42545), but it uses nested arrays instead of a string. The nice things about nested arrays (besides the fact that defining them doesn't take any bytes) is that they're pre-organized, so you don't have to do any fancy split-on-`<>` magic, or decode from a huge base 256 number, or anything like that. The actual logic is just `.map(X => X.length).map(X => String.fromCharCode(X)).join("")`. [Answer] # [Haskell](https://www.haskell.org/), 9735 bytes, score 9 ``` 'y'<<>>pred (<><>)<<>>(<<>>)=[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)(<><>))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))]<>[(<><>)]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))]<>[(<><>)]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))))))))))))))))))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>)))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))]<>[(<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)((<<>>)(<><>))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))] ``` [Try it online!](https://tio.run/##7Vm7DoIwFN35ig4mlEG/ALroamLiYoIOjaASeQVw8OetEBIdVF4qtOR04ATSXk459/Ze2hNPz67vCy@IoyQjC57x2TIKI88hlFCTGcTQtIB7IbFIfMnWWUImZCv0q26ajMWJ62h5r7xfcUuLi2HZJVJA@WkatZ3J7CaW6vrV0eg0vmJSEvD5iSrteDwtDMG/i8fJxhOAVa9Lgx8DAD0EGuJPCTVV0qNqglLUpbX2iieIAMCY1nn4s9oKq/kH3Xkn4DFiQL99q5akcfTRs8ZVOSAzA/rOovA3ACpBgNKV4MBnMZLuJQxXEbd4CeIV0EeSgJ/JLdyf9XlhhTzxHQPEE2AUZ/FC3PYHnx9TMd3MV6s7 "Haskell – Try It Online") The 9 scoring bytes are ``` 'y'pred = ``` This works in current versions of Haskell (GHC 8.4 or newer) where `(<>)` is in `Prelude`. Thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) for pointing out that this breaks my [previous solution](https://codegolf.stackexchange.com/a/118265/56433) but allows to save another scoring byte. ### Explanation As `(<>)` on two lists is the same as `(++)`, we can represent a string `"abc"` as `"a"<>"b"<>"c"` instead. Strings are lists of characters, so `['a']<>['b']<>['c']` denotes the same string. Now, as in the previous answer, we only want a single character literal, so we stick with he highest one `'c'` and represent the others as predecessors of it: `[pred(pred 'c')]<>[pred 'c']<>['c']`. Finally, by replacing `'c'` with `(<><>)` which is a valid identifier and `pred` with `(<<>>)`, we get an encoding of the string `"abc"` that only consists of balanced parenthesis: `[(<<>>)((<<>>)(<><>))]<>[(<<>>)(<><>)]<>[(<><>)]`. The following function encodes an arbitrary string in this manner: ``` f s = show max_char ++ "<<>>pred\n(<><>)<<>>(<<>>)=" ++ encode s where max_char = maximum s s `unless` b = if b then "" else s encode [] = "" encode (x:r) = let repl = ([succ(succ x) .. max_char] >>) in "" ++ "[" ++ repl "(<<>>)(" ++ "(<<>>)" `unless` (x == max_char) ++ "(<><>)" ++ repl ")" ++ "]" ++ "<>" `unless` (r == "") ++ encode r ``` [Try it online!](https://tio.run/##fVHBbsMgDL33K1xOoG79gCnk0EO1@45ZtLLEEVEJjUyipl@f4S7KugntHQyYZ579sCac0bl5biCAhmAvV@jM9FFZQ7DbgciyPO8J63cvszzLFZ8lB6UFE9BXlxohbCDiapHwvmOs72jett3YLTRGgNPoHYZwgs9IaJu4DBY9CAHoAr@4cheNooxEIf6m5fRCKt6seYbDAQh7F/OyCGNVSQ4wKdjv18ZKiGP8Kmv9o8ACtqEQkEjfFcS3HTLJWC7Fz7RyAq3XFlS6hp3@R1EleyzTHWT5ozqxuhAp3cVPmjsTfYh/4gckUw3QzG8j9dQG3G5eTd/f4NDSYGtze4IDRfLz0Znz9gs "Haskell – Try It Online") [Answer] # [Chip](https://github.com/Phlarx/chip), 553+3 = 556 bytes, score 127+3 = 130 ``` ((<>)ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZt()((((((((((((((((((((((((((( ((()))))))))xx)))))x))))))))xx)))))x))))xg()((((((((((((((((((((((((((((((((({ *})<>))))))))xx)))))x)))))))))x)))))x))))f)*{((((((((((((((((((((((((((([ Z<>])xxxx)x)))))xxx)))xx)))x)))x)))))))))))}e{(((((((((((((((((((((((( ((())))))x)))xx)))x))x))x))xx))))xxx)x)x)))}d{(((((((((((((((((((((((((((( ((())x)))))x)))))))))))x)x))x)))))xxxx)))))}c{(((((((((((((((((((((((( (((())x)x)x))x))))))x)x)))))))xx))x)x))x)))}b{((((((((((((((((((( (((()x)))xxxx))x))x))x))))xx))))xx)x))xxx))}a ``` +3 for arg `-w`. [Try it online!](https://tio.run/nexus/chip#jY9LCsMwDET3Pokm0BuEHCShi35zgUAERmd3ReWoTqndDLJsL@ZJk4j6AeMBLQSqK@jBJma7fv15bnJMMXQC3avCQ/F/oosN0hTGfjgrQRnZ9aZZ20EBecT/@Up3Lt64NkPurY0y6jsSzOw72kNuzY3IXO4DO5G5IMo1Vgns87w@kSyeNrmklE7rCw "Chip – TIO Nexus") The non-bracket bytes are ``` ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZt xxxxxxxg *xxxxxf* Zxxxxxxxxxxxxe xxxxxxxxxxxxxd xxxxxxxxxc xxxxxxxxxxxb xxxxxxxxxxxxxxxxa ``` Ungolfed/unbalanced: ``` *}vZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZt Z'))))))))xx)))))x))))))))xx)))))x))))xg x))))))))xx)))))x)))))))))x)))))x))))f )))))x)xxxxx)))xxx))xxx)xxx)xxxxxxxxxe xxxxx)xxx))xxx)xx)xx)xx))xxxx)))x)x)xd x)xxxxx)xxxxxxxxxxx)x)xx)xxxxx))))xxxc )x)x)x)xx)xxxxxx)x)xxxxxxx))xx)x)xx)xb ))xxx))))xx)xx)xx)xxxx))xxxx))x)xx)))a ``` As you can see, the original code uses only right-side brackets, so all left-side brackets are for balancing only. In the course of coming up with this solution, I found a much denser string representation in Chip the I had had for my previous answers e.g. [hello world](https://codegolf.stackexchange.com/a/108888/56819), and so I've updated those as well. ### How it works: The bit hanging off the left produces a 1-cycle pulse to get things started. This pulse travels along the `Z`'s at a rate of 1 per cycle, which provides the timing. When each `Z` is powered, it's corresponding column produces the ascii code of the character at that index, which then gets output by the elements `a` through `g` (one per bit of the output byte, except the high bit `h` which is always 0). When finished, the `t` terminates execution. The ascii encoding is straightforward: `)` means 1 and `x` means 0. However, the bottom 5 rows are mostly `x`, so I invert those bits in the final solution, effectively swapping the two symbols. ### Is this the best possible score? I doubt it. At the absolute minimum, I think we need the following: 1 each `a` through `g`, since those are the active output bits, 1 `*` or similar to provide a starting signal, 1 `t` to terminate execution, 36 `Z`s or `z`s to time out each letter, and the command arg `-w`. This all sums to a score of 48. Above that theoretical minimum, my solution has 7 newlines, a second `*`, an extra `Z`, and 73 `x`s. [Answer] ## C, 9265 bytes, score 37 ``` i;f(){for(i=0;putchar(i+=strspn("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[<[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[<[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]>]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]>]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"+i,"[]")+1););} ``` See it [work online](https://ideone.com/5G5tEA). ## C, 8589934626 bytes, score 34 ``` i;f(){for(;putchar(i+=strspn("STRING"+i,"[]")+1););} ``` Where `STRING` is the same large string literal as used in the above example, except that it has two differences in the very middle of the string where there is a substring `<>`. Just before `<`, are 4294962688 additional `[` characters, and just after `>` are 4294962688 additional `]` characters. The program will work under the following assumptions: * INT\_MAX is 2^31-1, and INT\_MIN is -2^31. * Compiled with wrapping behavior for signed arithmetic. (-fwrapv) * Function strspn is capable of processing 4294962689 characters at a time. * Compiler is capable of compiling a string literal composed of 8589934592 characters. Those assumptions are possible on modern 64 bit architectures, where type int is 4 bytes and type size\_t is 8 bytes. The function strspn returns type size\_t, and the same type is related to the internal limit for maximum object size. Type size\_t being 8 bytes would satisfy the last two assumptions. This difference in this version is that variable i doesn't have to be reset to 0, since it wraps around to 0 after the last character is printed. [Answer] # C# Interactive, 45 Bytes ``` "Surprise!\nHappy Birthday, Brain-Flak!" ``` I know, it's kind of boring, but if executed in the C# interactive, it produces the desired output - and actually I doubt there's a smaller way to solve this in C#. However, there is a more stilful way: ``` var a=new BitArray("[][]()()[]()[]()[]()[]()[][][]()()[]()()[][][]()()()()()[][][]()()[]()()[][][]()[]()()[]()[][]()[][]()()[][][]()[]()[]()()[][]()[]()()()()[]()()()[]()[]()()()()()()()[]()()[]()[]()()()()[][]()()()()()[][][]()()()()()[][][]()[]()()[][][][]()()()()()()[]()()()[]()()()()[]()[]()()[]()[][]()()[]()()[][][]()()()[]()[][][]()()()()[]()[][]()()()[]()()[][]()[]()()()()[][]()[]()()[][][][]()()()[][]()[]()()()()()()()[]()()()[]()()()()[]()()[]()()[][][]()[]()()()()[][]()[]()()[]()[][]()()[][][]()[][]()[]()[][]()[]()()()[][]()()()[]()()()[][]()[][]()[]()()()()[][]()[][]()[]()[][]()[]()()()()[]()()".Replace("()","0").Replace("[]","1").Select(/*<*/s=>s=='1').ToArray());var b=new byte[a.Count];a.CopyTo(b,0);Console.Write(Encoding.UTF8.GetString(b)); ``` But this is 145 Bytes big. With line breaks it looks like that: ``` var a = new BitArray( "[][]()()[]()[]()[]()[]()[][][]()()[]()()[][][]()()()()()[][][]()()[]()()[][][]()[]()()[]()[][]()[][]()()[][][]()[]()[]()()[][]()[]()()()()[]()()()[]()[]()()()()()()()[]()()[]()[]()()()()[][]()()()()()[][][]()()()()()[][][]()[]()()[][][][]()()()()()()[]()()()[]()()()()[]()[]()()[]()[][]()()[]()()[][][]()()()[]()[][][]()()()()[]()[][]()()()[]()()[][]()[]()()()()[][]()[]()()[][][][]()()()[][]()[]()()()()()()()[]()()()[]()()()()[]()()[]()()[][][]()[]()()()()[][]()[]()()[]()[][]()()[][][]()[][]()[]()[][]()[]()()()[][]()()()[]()()()[][]()[][]()[]()()()()[][]()[][]()[]()[][]()[]()()()()[]()()" .Replace("()", "0") .Replace("[]", "1") .Select(/*<*/s => s == '1') .ToArray()); var b = new byte[a.Count]; a.CopyTo(b, 0); Console.Write(Encoding.UTF8.GetString(b)); ``` This interprets the brackets as boolean values and then as a string. Actually I'm not an advanced code golfer, so any suggestions are appreciated! [Answer] # [CJam](https://sourceforge.net/p/cjam), 6683 bytes, score 3 ``` [(a lot of square brackets omitted)]{,c}% ``` I shortened the code here to not clutter up the page too much. You can see the full code in the TIO link. The only non-bracket characters are `,c%`. [Try it online!](https://tio.run/nexus/cjam#7djBDYAwCAXQaby5EeHkGMbZcQEHAHzpvemDhE9aEZETTg55JyulPjJxTrR839GvShv6Zv4T/tPco2pym5KUyA4ivySjFGFgmq3rVbm9fTQ5lv@C5X1ez1H1Ag "CJam – TIO Nexus") **Explanation** The program starts by pushing an array of arrays of empty arrays. Each sub array contains a number of empty arrays corresponding to an ASCII value of a character in the desired string. Then for each subarray (`{...}%`), it gets the length of the array (`,`) and casts that length to a character (`c`). The resulting string is implicitly printed. [Answer] # C, ~~69~~ 64 bytes [**Try Online**](http://ideone.com/fwSoNx) ``` f(s,t)char*t;{if(*t)*t-123||putchar(s),f(s+(*t==60)-(*t==91),t+2);} main(){f(83,"{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}[][][]{}[][]{}<><>{}[][][][][][][][][]{}<><><><><><><><><><>{}[][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><>{}{}<><><><><><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><>{}<><>{}[][][][][][][][][][][][]{}[][][][]{}[][][]{}<><><><><><><><><><><><><><><><><><><><><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}[][][][][][][][][][][][][][][][][]{}<><><><><><><><>{}<><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}[][][][][][][][][][][]{}<><><><><><><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}");} ``` **How I did it** * I basically encoded the text using a modified version of my [solution](https://codegolf.stackexchange.com/a/116883/47981) from [**the incremental cipher challenge**](https://codegolf.stackexchange.com/questions/116808/incremental-cipher), modified to fit the requirements. [*Try Online*](http://ideone.com/IBnVd7) > > > ``` > p(int x){putchar(x);} > j;f(char*t){ p(t[0]); for(int i=1; t[i]; i++){ j=t[i]-t[i-1]; while(j>0)p('<'),p('>'),j--; while(j<0)p('['),p(']'),j++; p('{'),p('}'); }} > > ``` > > * Next I replaced `*` with `{}`, `>` with `<>`, and `<` with `[]` so they don't count, so now this code count is 1 because of the starting character `S`. > > > ``` > S<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}[][][]{}[][]{}<><>{}[][][][][][][][][]{}<><><><><><><><><><>{}[][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><>{}{}<><><><><><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><>{}<><>{}[][][][][][][][][][][][]{}[][][][]{}[][][]{}<><><><><><><><><><><><><><><><><><><><><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}[][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}[][][][][][][][][][][][][][][][][]{}<><><><><><><><>{}<><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{}<><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}[][][][][][][][][][][]{}<><><><><><><><><><>{}[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]{} > > ``` > > * Finally I wrote a parser, which just sum on `<>`, subtract on `[]`, print current sum on `{}`, and terminates on the end of the string `\0`. --- **C, 49 bytes** [**Try Online**](http://ideone.com/l82U4K) ``` main(){puts("Surprise!\nHappy Birthday, Brain-Flak!");} ``` [Answer] # Lua 5.3, 108097107033101 bytes, score ~~28~~ 27 ``` load(([[REPLACE]]):gsub([[[<>]-{()}]],[[%1]]):gsub([[...]],([[]]).char))() ``` Here, `REPLACE` is replaced by a length 108097107033034 string of free characters. The string encodes data by putting `{}` at certain key positions. The first `gsub` will replace the string by the indices of the `{}`s (via the empty capture group `()`). The second `gsub` breaks this resulting string into 3-digit blocks and replaces each block by its ASCII representation. Note that the syntax for raw strings in Lua is (basically) `[[string contents]]`, which is quite useful in reducing the score. The (unescaped) string I'm generating is `print"Surprise!\nHappy Birthday, Brain-Flak!"`. Replacing each character with its 3-digit decimal ASCII code gives `112114105110116034083117114112114105115101033092110072097112112121032066105114116104100097121044032066114097105110045070108097107033034`. The code I use can only generate sequences of increasing natural numbers (at least 2 apart) that don't start with initial zeroes. So, this number gets split into `11, 2114, 105110, 1160340, 83117114, 112114105, 1151010330, 9211007209, 71121121210, 320661051141, 1610410009712, 10440320661140, 97105110045070, 108097107033034`. (This last number is exactly the length of the `REPLACE` value, as the last match of the pattern will give the index of the final `}`, noting that Lua-indices start at 1. If the last number was odd, then the pattern and string would have to be modified slightly, although it's not hard.) I didn't actually generate and run this program because it is too big (although it theoretically could work on a 64-bit machine, it wouldn't fit on my hard drive). As a proof of concept, here's a small program that prints `3` using the same principle: ``` p=print load(([[<<><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>{}]]):gsub([[[<>]-{()}]],[[%1]]):gsub([[...]],([[]]).char))() ``` This generates the code string `p"3"` via the number `112034051034` via the split `11, 203, 405, 1034`. [Answer] # [Pip](https://github.com/dloscutoff/pip), 6681 bytes, score 3 ``` C#*[[()()...()]...[()()...()]] ``` (with a lot of parentheses and some square brackets redacted). [Try it online!](https://tio.run/##7djBDYAwCAXQYbyoazhG0wF66/4XXMABAF96b/og4ZPutSOe4x7jvCqcWeSdrJT6yMRZ0fJ9R74qdeib@U/4T3OOqsltSlIiO4j8koxShIGpti5X5fr20eRo/gs2I14 "Pip – Try It Online") We construct a list of lists, each of which contains `()` (nil) some number of times. `#*` maps the length operator, resulting in a list of numbers. `C` takes each number as an ASCII code and converts it to a character. The resulting list of characters is then automatically concatenated together and printed. Happy belated birthday, Brain-Flak! [Answer] # Mathematica, 40 bytes ``` "Surprise! Happy Birthday, Brain-Flak!"& ``` Anonymous function. Takes no input and returns a string as output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “µḍ'Ṭẋs:|`¿wwƈг×U7¿» ``` Nothing at all clever here, just a dictionary + string compression of the text plus a trailing newline to remove an unmatched `<`. For a truly golfy approach see [this answer](https://codegolf.stackexchange.com/a/118163/53748) by Erik the Outgolfer. **[Try it online!](https://tio.run/nexus/jelly#ASgA1///4oCcwrXhuI0n4bms4bqLczp8YMK/d3fGiMOQwrPDl1U3wr/Cu///)** [Answer] # PHP, 42 Bytes ``` <?="Surprise! Happy Birthday, Brain-Flak!"?> ``` [Try it online!](https://tio.run/nexus/php#@29jb6sUXFpUUJRZnKrI5ZFYUFCp4JRZVJKRklipo@BUlJiZp@uWk5itqGRv9/8/AA "PHP – TIO Nexus") -5 Bytes the boring solution ``` Surprise! Happy Birthday, Brain-Flak! ``` # PHP, 60 Bytes ``` <?=join(array_map(function($v){return chr(strlen($v)/2);},explode("[]","<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>[]<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>")))?> ``` [Try it online!](https://tio.run/nexus/php#7dZNCsIwEAXgq0hwMQMFoVv7c5BSJNSIlZqUMZWKePYIrj1Akj6yyyLMNwPzEqq2vrnRkhbRr9Ndz3RZ7OBHZ2n/5LcYv4jdDVehh5fJ/G4PJR8/hVnnyZ0Nqa5XhaqaFE7Xp1EnrFBijjDBmaLl/xvxdSmHuWH/Q7hNcxxdQ25DCSlE@IMgv5CMSBEYYEpbF1fn8p0jNkfeLsXMbRPCFw "PHP – TIO Nexus") [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), score 23 ``` '....' '(<>)+'match[#'2/]map#:out ``` Where `...` is the omitted string. (This can be generated with [this](https://tio.run/nexus/stacked#@69uYVxda2hoDiJMQIQRjGVgCmKBCAPD6lpjkDKD6lpzoLylOVwhiDACSQMZZmZwXWCTwFywSQZQPSCVJiZIqkEKwTIQbUB1JkCGuQFIxAImZQ6yXV1BPSZFW10hWrlO3cZOXSvWUF@hKLUgRyG/tOT/fwA).) [Try it online!](https://tio.run/nexus/stacked#7daxCYAwEIXhVYQUp1gIlhKyiFgEmzRBi1iJs58LOEAu/qQP@d7Bvaj4YOHcj413YkXJHDHhtGj5vqO@lFqYG/sf4T/NdaRGb6NEiog/CP1FM9IiGDDZ1tWVXLtzZHO07ZJOeh@GUXIse1qdzNOW4@mW4yqqLw "Stacked – TIO Nexus") Yeah not that creative. Gets the number of all `<>`s and converts them to character codes. [Answer] # [Perl 5](https://www.perl.org/), 3304 bytes, 16 score ``` say(map{chr(y{()}{})}q[()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()({}()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()({}()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){}()()()()()()()()()()()()()()()()({})()()()()]=~m{[()]+}g) ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIjN7GgOjmjSKOyWkOztrpWs7YwWkOT6rC6lgaGDk5r6W8nHW0ckHikk6VEWIOshHquooP/hnWiHDAbSQheajiOfh7UHBkFJ31tpY9NtLdlADMaiVYPt2w5TGOZ7iFImn1Ucx59vTnMCgJNoppncHasbV1uNbAnE6tdm675//@//IKSzPy84v@6vqZ6BoYGAA "Perl 5 – Try It Online") Uses @HeebyJeebyMan's Python solution's run length encoding of the text. [Answer] # Java, 140 bytes [**Try Online**](http://ideone.com/Jp9olb) ``` class H{public static void main(String[]args){ String t="()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()[]"; for(int i=0,s=0;i<t.length()/*>*/;i+=2){if(t.charAt(i)=='('/*)*/)s++;else{System.out.printf("%c",s);s=0;}}}} ``` [Answer] ## C, 52 bytes, score 46 ``` f(){puts("Surprise!\nHappy Birthday, Brain-Flak!");} ``` Naive version. Here is the [optimized version](https://codegolf.stackexchange.com/a/118954/67705). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` Surprise!¶Happy Birthday, Brain-Flak! ``` [Try it online!](https://tio.run/nexus/charcoal#@x9cWlRQlFmcqnhom0diQUGlglNmUUlGSmKljoJTUWJmnq5bTmK24v//AA "Charcoal – TIO Nexus") Just prints the string. [Answer] # [(,)](https://esolangs.org/wiki/(,)), 2.045077961748942e+75 chars, score 16 <https://codepen.io/Onilily/pen/BaGzpjq> Basically it’s this: ``` ((),[…])(,(()(),(()))((),(,(()(),(()())((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))((()()()))),,,(()()),()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))(,,,(()())()()()()()()()()()()),,,()) ``` Where […] is () repeated 1.022538980874471e+75 times. You can see it works by replacing `Surprise! Happy Birthday Brain-Flak!` with something else like `ab`. ]
[Question] [ The string `tut-tutut-tut-tuttut-tut` can be constructed with overlapping or concatenated instances of the word `tut-tut`: ``` tut-tutut-tut-tuttut-tut tut-tut tut-tut tut-tut tut-tut ``` The string `tut-tututut-tutut-tut` cannot: ``` tut-tututut-tutut-tut tut-tut^ |tut-tut | tut-tut | this u is unaccounted for ``` Given a string, determine whether it's constructed of overlapping or concatenated instances of the word `tut-tut`. Where two or more `tut-tut` strings overlap they must share the same letters in the same positions. ### Rules * Standard I/O rules apply. You can use any two *distinct, consistent* values to distinguish the true and false cases. * You may assume the input strings are nonempty and only contain lowercase ASCII letters and `-`. * This is code golf, shortest code in bytes wins. ### Test Cases True: ``` tut-tut tut-tut-tut tut-tutut-tut tut-tuttut-tut tut-tut-tut-tut-tut tut-tutut-tut-tutut-tut tut-tutut-tut-tuttut-tut tut-tut-tutut-tuttut-tut tut-tuttut-tutut-tut-tutut-tut ``` False: ``` x tut tut- -tut t-tut tu-tut tut-tutx tut-tutt xtut-tut ttut-tut tutut-tut tut-tu-tut tut-tuttut tuttut-tut tut-tut-tutt tut-tutt-tut tut-tuttut-tu tut-tututut-tut tut-tuttuttut-tut tut-tututut-tutut-tut ``` [Answer] # Regex (POSIX ERE / RE2 or better), ~~23~~ ~~21~~ 20 bytes ``` ^\b((t?\But)?-tut)+$ ``` Based on regexes by thejonymyster and Bubbler. [Try it on regex101!](https://regex101.com/r/o2oBkT/7) - RE2 [Try it online!](https://tio.run/##dVBdT4MwFH32/oqTQgaLIXGvMLLEhyU@65ubhkkjS5qhhUWi9bdj6WBlo/IAveeejx52WVW0kmc5IpkjCCCXy@C1f4L2ZbMLw3q1uT/W81VU6/et3w5r@ir2guNh/Ziit4BQ6hnRAcwXDNskL@lGz9/wK2yV4m9FmVTpIjHYidMJmP8j4rt48cuQgnkGDTuy4Sj@LvkHov0n17NkmM1gll3OkzzyGGBQyoLrTFQaZfPEYtqI8vLAWw@dhki36RoN3/H5cnIQ3YKp1OIOE@fiP0PyYFoRNTTQ6STs5WOX5mxHzTlglHSReRVP7ttayvS6tu6kzOSHjFv9AQ "Bash – Try It Online") - GNU ERE (Bash + egrep) [Try it online!](https://tio.run/##dVDdToMwFL7vU3TBrOdMYTMxXoxUEhN9APXOaYKsm9UOmlIUZ3x2LFMGE7xpe9rvty/xW5wnRmrr51ouhdlk6av4qAxPxTu9EeurUgNs@cV0Uj0ungBstLgsLEa@devxUTWZbjGw2a01Ml0DBrmSiYDzE/8MMVxlBiSfhaC4EfFSyVQA4oinhVKh5Kf4SSiVK5CoHd0Chm5WdDym6n72MOLMY/WgC5tbAyrYxDZ5BoMRuzOFmFPK5uw6Vrk7sh23QWL4VXm0BhHigtZhm717PpwGgMOEPrW9HxAZfPhPkHh014iQkjRw8kP8pXdVyr0cKfcGHacDzz/2ZDhtC@nHbev2yvQ@pNvqGw "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##dVBLb4JAEL7Pr5jIxmVTDXLohRWJje2xJ4@kG20wIdmiXSChIfSv06GWh0IvO6/vMbOXyOjH@uMLmZFY6vP7QSNzJJX@erfdbzcVnM7GZrG/kuuNpOiKEuMTdUR5MXGS4SxMZrJCptHHND@mGcHVYukuXBF9NkMMBv0VTQR6yJQEJCG0iTifdwhNCFckEbd4a2A3EP8bHWYcEfC9ySMPkXv85aBTSrmQFWldwUxLrJR6ft0pVb@FR9vOgvApz0SwzOh9YHVtYSMBQHXTa@Mwv60mgNOEMbXvT4hMDv4TBAt/7wUooIXDlfhHH6oUnRwUncHA6cbzzh6mt@0h43X7c0fHjD5keNUP "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgkWsVYKofq1CnoGKblpmXWZwBZAZG6yvY2ysohRSVplopKCgpKCoqKLkl5hQDeUqaOirxCmn5RQo5mXmpxdax1lxQjf/jYpI0NErsY5xKSzTtdUuApLbK//9AGsTmgtLIbFQeFoXYNWBqRYhjMQSrBC4DK7hgirggyqGakPVWwA3hqoAbi2Q@ik1olnJhdyNCCaYjEZ7E8AJGMCD7BQA "Perl 6 – Try It Online") - Raku`:P5` [Try it online!](https://tio.run/##dZBbT4MwFMff@ymOXSOtsguvq4TEOI2JcQZ9E20Y6YRYGCldssT42edhXnbDB8rpv//zO5c6r9cXUZ3XwCyEQIcUBlBb/aasrk2aae4NB2eRUnlqnMoWZV0YbROeCJnEw8bzwcNvjqJ6062hcrpyDVfq@vZuopTwIRCIpMMllaSoCtVox2mdWT2Ypdm7s3goU5SFoz7QfkCFJPOF5awIR5KZcI7Yhj8@Xd3eCyk@oJhzZp4bZ42uMBL94CUMaVJRgeZmOcMXlP2R3w@E3LgLobN80VokIDWQBFAHvmWcniJy9HISej0PS7Ay3GygTF2Wc2Z9tEhoId@bMWnjlLYWuxQn4UM8uVH3UzWJ42kc0Umrj4GOOSsj@mSXegx4o9epaTDE8eATG9jQKDNUfh7slgu5fk1mnLsouVw6EfUdnudsve5BiyME7632@9@N928dxu6E49St3gHpfPgPSHqwmZ2QFfm1k@/En/RdyuoPR1Z/BXYq7dU8KE@6u91ajtvdjns0zNFCdqf6Ag "PHP – Try It Online") - PCRE [Try it online!](https://tio.run/##dZFNb9swDIbv/hWsMzRSuqrZtYYXrMB6Wodh2W3ZAMWWY6Wy7Ely6yHwb8@o2PlqPB8skSIf8iXX/IXfrtPnrSyq0jhYo81kySYRnHpqJ9Wgz4iVaPxLVS@VTCBR3Fp44lLDpndZxx0eL6VMocAHMndG6hVws7I/f1FwuSlfLXxuElE5WWJiAPAolYAs1uJ1dyUhS8pUMHwPafRQZ5kwIv0ueCoMLHdh506yz@zNjNKor2vfu@g193xCbLxECTz9IrUglF7FulaKyoxYJv7UXFkS3k0mk5DSzXloRyDEDQI2SHAHAgLukLDEuOfI3sTjhR7700Vt52u/ceeE0WDi/oZqi8oXsDTCacwTrjUqlbqqHcTgxfU@Mv9rnSiY1BTXox3IeBpBr28Xz3Juv4rGYXuwAexMXsVT2qeV@F7hWJzSxAPiD74eVuxmpbBYB9FI6KUjA4hiSuiVywn9OIXra1Asybn55MgUhzAejelujf574i7JsfkCWYYVnUUUct72kJGCZVKnhMIMwh@mFvcAIdxD@IiDRAN3315keVTbtoFf1Pb3YolLmS0eakdntw7/N@@2fgHbEXhgEKDP@/fn6f3cGggcTrhMPfoHIIMP/wMGI9hpD4Im2IcHXWKffkppDrigORQ4qXRW8035YLjbY8hlu0e5F2IuBnKq6h8 "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##dVLLbtswELzzK7ZyEVOJ7EYN0INkxUAO/YAihxa2K8g09UBliiApyHHgX69KUn7IscoDxV3OzuysSDifZIS0o4KRst5QmK2rSqovgmZ0N805f0YkTwTEfLGCCH44L03zZ/1U/3p7@/maf2ty3P5erjFW8@VLrdz5ROn94XPrfsQ5HtzzKOYPfoguYoXWEjTZPqOCKeBC7zEVohKYVEwqsNr3WyplklH3XapNEBANgNkMjllztHnKNmUIgqpaMPDDg6XcJgXDLrwj0IsvtFpJGebuxF9FjyHUGvP0NVZQmcgUZPpgwZZT4wuW6QteqxC6nuyAgsBOSMtpsvCUk9tEkRyaPFEdSVoJwIZ2b/gtZUZVWTCKOy8F8zp2TbKP/FOnZhUp4L0L@s5MAY@XbOyGV7e2cPG4grs7OJ0/RePR2D3DrG0z1hT3@44lTQTJOwbPNuxpLy7MwXkVNQ0AHAjA@Z6UUgdOTzhtRKFoVzklsZ4Qdo8eprLYUxP5nvFaGVe27mD346/R8z20IzAyCOnnYp7M6ds/X0cDwOGC29JLfoBk8OJ/hGgEdiII7dAJjrrCY3mfZXemQ7uzQE/pSvODPBru9gK5bfdi98bMzUD6rv6StEwy2U5K@0Ji@0D@AQ "C++ (gcc) – Try It Online") – Try It Online") - Boost [Try it online!](https://tio.run/##dVBLbsMgEN3PKaa4krGaRLayo0KRuugJurNTya2JgkSxBURycnkXmjp2arphGOZ95tGd3bHV20F@da1xaM92ZQQY5GgIIcN79UGp21UvJ5ft1s6fT4@DH5QFWxf7Z7zwHA6tQYVSB/LGukZqBojygBeGnZHa0ezaK6GpyrDWDarS0zlPK50yVFyVedCLwPL9A0@TdFQSuuHkzZwEQyQBbMTGitp8HqlZoWcJZQWS19oXhiQYT0SVhYWLIcGgAODjhEhjnd/vuwgwTlhSp/eISHTwnyAk@BMLoIcRDlfiL32u0t/koL8ZzJzuPP/YQ3zbCbJcd4q7CLP4kHmqbw "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##dVDPT4MwFL73r/goZpsxNMzjSENmpkcPZreBZIt1NqmElJKxi/86FhiDCV7afu99P96rLg7nSoPjTRxFmbFUnLBZb9dMi/1HAMn9AKcvqQQUPwqTE0B@Qjp1PStMHkCkDW8Z1A2185Yx5zRKaWAVaucz5j3GDauVOoqJ78ycQ8xmlu7HDp@7c9sDMi1TAwX@A40QdKsLsQIoVqAve5VbQDunC7eFSfL8ukmS6j06LBYmjJ4Kcx96xp4Pd1XlojYixOK61t3D9y2aIE4LxtK@PmEy2fjPkLhodiakJB2dtMKLfOhSXu1IeQ0YJN1k/okn09P2lPG4/bqjZUYfMtzqFw "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##dVDPT4MwFL73r3iBJm1VjF4hyxZNvHnz5jTB7SGNtZDSBTLC345lusFGvfS9134/3teyqNFUOSrVU7N4NfiJzVsca6z5ivXv6w/O7XL9sLNiGVl3XtOerW6Cx@K7lAq3gUjofnGXZIXBdJNzqkBqoFKXDtvKjNO9aGsjLUZ5UdnOge8TmYEDRqneRrqwQ6vkF7LwiokpGNyr20NJjRBQfmCZ2@fUbnKsHEsIaNmL2WEMrANUFbr5KXU1Zp2AoEv8WlR1fQgDkRAXaYh1rNP@fPIA/YQ5dbz3iHgf/hMkIRzyEdKQI5z8Ev/oU5XmJEeak8HE6czzwp74tx0h83XHuLMwsw@ZpvoB "PowerShell – Try It Online") - .NET ``` ^ # Anchor to start of string. \b # Assert there is a word boundary here. Given the context, this is # equivalent to asserting that the first character isn't "-". ( ( t? # Optionally match and consume "t". \B # Assert that this is not a word boundary. Given the context, this # is equivalent to asserting that the string does not start here. ut # Match and consume "ut". )? # Optionally match the above. -tut # Match and consume "-tut". )+ # Iterate the above as many times as possible, minimum one. $ # Assert we've reached the end of the string. ``` Alternative 20 bytes: ``` ^(tut-(tu\Bt?)?)+\b$ ``` [Try it on regex101!](https://regex101.com/r/o2oBkT/8) - RE2 [Try it online!](https://tio.run/##dVDdToMwFL7vU3TBrOdMYTMxXoxUEhN9APXOaYKsm9UOmlIUZ3x2LFMGE7xoe077/ZyvL/FbnCdGauvnWi6F2WTpq/ioDE/FO70R66tSA2z5xXRSPYItrO@2xaWNMMLjxdNRNZluMbDZrTUyXQMGuZKJgPMT/wwxXGUGJJ@FoLgR8VLJVADiiKeFUqHkp/hJKJUrkKgd3QKGrld0PKbqfvYw4sxjdaMLm1sDKtjENnkGgxG7M4WYU8rm7DpWuSvZjtsgMfyqPFqDCKmHdqs5u/VhNwAcJvSp7f2AyODDf4LEo7tEhJSkgZMf4i@9q1Lu5Ui5N@g4HXj@sSfD07aQ/rht3F6Y3od0U30D "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##dZDJTsMwEIbvforBtYgN6ZJrTRQJURASoihwI2ClkUsinDRyXKkS4tnLpCzdwsH2eOafb5Y6r9cXUZ3XwCyEQIcUBlBb/aasrk2aae4NB2eRUnlqnMoWZV0YbROeCJnEw8bzwcMzR6d6062gcrpyDVfq@vZuopTwIRCIpMMllaSoCtVox2mdWT2Ypdm7s3gpU5SFoz7QfkCFJPOF5awIR5KZcI7Yhj8@Xd3eCyk@oJhzZp4bZ42u0BL94CUMaVJRgeJmOcMIuv2R3w@E3KgLobN80UokIDWQBNAPfMs4PUXk6OUk9HoelmBluNlAmbos58z6KJHQQr43Y9LGKW0tdilOwod4cqPup2oSx9M4opPWPwY65qyM6JNd6jHgj16npkETx4NPbGBDo8xQ@XmwWy7k@pW7pevjlVy6SETiPJmx9boHLY6QNobn9921938dwu6E49StvwPSGfgPSHqwmZ2QFfmVk@/En/RdyuoPR1Z/BXYq7dU8KE@6u91Kjtvdjns0zNFCdqf6Ag "PHP – Try It Online") - PCRE This version doesn't work properly in GNU ERE; it [matches `tut-tuttut-tu`](https://tio.run/##dVBda4MwFH3e/RWHKLUyhPVVK4U9FPa8va3dsDPMQqhbtEy27Le7mGpjayb4cc89HznusqpoJc9yRDJHEEAul8FrfwXty7w@1pF@bO7rVbgKbzc7vx3W9FXsBcfD@jFFbwGh1DOiA5gvGLZJXtKNnr/hV9gqxd@KMqnSRWKwE6cTMP9HxHfx4pchBfMMOu/IhqP4u@QfiPafXM@SYTaDWXY5T/LIY4BBKQuuM1FplIWJxbQR5eWBtx46DVHXTN/De/x9OTmIbsFUanGHiXPxnyF5MK2IGhrodBL28rFLc7aj5hwwSrrIvIon92ktZXpcW3dSZvJDxq3@AA "Bash – Try It Online"). This appears to be a bug in GNU ERE, and is still present in the latest version. Note that `^(a\Bb?){2}$` incorrectly matches `aba`: [Try it online!](https://tio.run/##RY3BCoJAFEXX@RWXSVIXQrZ0lKCF0Lp2ZTE2QwqD1kgEOX67jZPh293zzn2vYG05KME4QsXheVBJ4l2n8YaLz867Yht0m94d/th5l5UU2GeHFFMVUusTwhrElQQ55Y2zMPkDt0WutbiVDW3TiFr2c8YCcTsZr@OoJ0hBlpb6o2wdLe5KPBBWT2GyIlitYJfjn6N6iRgg0HqGGZOtoSSgMzOHHN7UYmAF@wI "Bash – Try It Online") - GNU ERE (bug) / [Attempt This Online!](https://ato.pxeger.com/run?1=m70kKbE4Y8HOotTEFAXdohQFdXWFIhsb9XgoUF9aWpKma7EmTiMxxinJXrPaqFYFInRzH0wNV3lGZk6qgqdbsK0C1ByFnJqaaAXdPAUllRwlhVjrlHwuTiC_SkGlWCG2piY1OSPfutjW0BosBlED0qCkUp1jZWBlWKukYKugpAwW1QApBqupSU0vSi1Q0M0sTAXyi5QU1NQUwJIge0KKSlOtFBSUFGpqEIJuiTnFQFElTWuEGNAgrpT8vFSILxYsTkxKhDAB "Bash - Attempt This Online") (bug) [Try it online!](https://tio.run/##XZBfa8MgFMXf@ymck0ZH@id7rJPAWDoKox1Z35ZOTDBNmElF7VPpZ89uuofBHrxcj4ef9x7b2OEptY1FxCGB8AKjObJOH6XT1qhK02gxf0ilbJQJsjp1tjXaFbRgvMgXPopRBKcGUR71aOiD7oOnUq43b5mULEYJAyRenDGftH0rvQ4U28rpeamq7@CgSNN2bcAxwrMEMz6pT46SViw5MaIGrKcf@5fNlnF2QW1Nifn0wRndQ8dmyUEIXPSYgdmfS3gBOV7Gs4Txm7tlumpOo4UjoCZ8gkBH9I8xnQJyebgT0X0EX5BO3BLoVKgaSlwMFo5GyG8yRvkgtXMwJbsT73n2Krc7meX5Lk9xNuorhFeUdCneu7NeIbjhtTIeWlgPXWGAGw0Tg/n1X7aU8eGLquK5TNnl8UqGQZXqBw "PHP – Try It Online") - PCRE (no bug) But `^a\Bb?a\Bb?$` correctly doesn't match `aba`: [Try it online!](https://tio.run/##RY3NCsIwEITP9imGtbR6KNhrfxA8FDzrTaukJthCaDVBBI3PXtNY6R4W5tuZ2YrpuleCcUSKIwyhsiw8jxP2J3bcVGu3/P6PvWfdSIFtscsxRiGNOSBqQb4klCnvvJnVL/gapTHiUnepzuPUsZ9nCJD/lskqiT@EHDR3dDGYnceIqxI3RM1dWK0IQQB3HP7s1UMkAMGYCRZMaktpmU7MFnm8a0XPKvYF "Bash – Try It Online") - GNU ERE / [Attempt This Online!](https://ato.pxeger.com/run?1=m70kKbE4Y8HOotTEFAXdohQFdXWFIhsb9XgoUF9aWpKma7EmLjHGKckeTKhAhG7ug6nhKs_IzElV8HQLtlWAmqOQU1MTraCbp6CkkqOkEGudks_FCeRXKagUK8TW1KQmZ-RbF9saWoPFIGpAGpRUqnOsDKwMa5UUbBWUlMGiGiDFYDU1qelFqQUKupmFqUB-kZKCmpoCWBJkT0hRaaqVgoKSQk0NQtAtMacYKKqkaY0QAxrElZKflwrxxYLFiUmJECYA "Bash - Attempt This Online") 21 bytes without word-boundary assertions (GNU ERE or better): ``` ^(tut-(tut?|))+tut$\2 ``` 21 bytes without word-boundary assertions or backreferences (ECMAScript or better): ``` ^(?=t)((t?ut)?-tut)*$ ``` ## Regex (ECMAScript or better), 22 bytes ``` ^((?=tut-tut).{1,7})*$ ``` [Try it online!](https://tio.run/##dU/RTsIwFH3vV5TM0HsXNiAxmtBUnvQD1DejSTMKVku3dJ1OCN8@B3Ew2Hy46T2955x77of8knnidOajPNML5dap/VQ/lRNWfdNHtbovM4CNuBuH1RvAXPjCR3VhvJ2ObncYXlXheIOxT5@803YFGOdGJwpuRtE1Il@mDrSYcDDCKbkw2ipAHAhbGMO1mOKWUKqXoDGr5R6Q19jQ4ZCal8nrQLCA7UFW@Nw7MPFa@uQdHM7ZsyvUjFI2Yw/S5HXLDtqGiXxXBXRPIuQvc/O2@3PUQ@wXdKWn/x6T3sF/hiSgh4sIKUlDJ21heXQg5dHz3PxiTzvLxf5T/k66zoXtmL8 "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##dU/fa4MwEH7PX3HU0CTDzvowBqapFLo97qmPY6EbFoTMdlHBIdm/7s5tWlvdQ7jcfT/uu1NizV3z/gnUSqjN8W1vgAYSW7XabnabtSOHo@U0VUu5WkusoaghPeBE1CebZgXMnrOZdEANKMjL17xAuvYXoR@K5KMFIR7Ml4gIiIBqSQCNgKNwPu8ZBhmhyBLmsW4BbynqCwJqAxGznS2TCIBF7HFvcvwyIR16/ZKpkeC0fnjaat28cB6roiwW@MRtHfr3TtzQpvGgNSHkD@rq8H/ZTRCnBWPpeT5hMgn8Z0g8@LmYkIp0dDIUVr0DqXrPS/OrPcMsV/vP@UfpRhcOY34D "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgkWsVYKofq1CnoGKblpmXWZwBZAZG6yvY2ysohRSVplopKCgpKCoqKLkl5hQDeUqaOirxCmn5RQo5mXmpxdax1lxQjf/jNDTsbUtKS3SBWFOv2lDHvFZTS@X/f6gQF5RGZqPysCjErgFTK0IciyFYJXAZWMEFU8QFUQ7VhKy3Am4IVwXcWFTz0aziwu4yhBJMpyG8huFwDM8j@wAA "Perl 6 – Try It Online") - Raku`:P5` [Try it online!](https://tio.run/##dZDfT8IwEMff@1ecpXGtGT/2ZEJt9iIaE4Nm@ibazKW4xW4sXUlICH873lAEAR@6Xa/f@9z3rs7r9VVc5zUwBwpon0IPamc@tDO1TTPDg37vItY6T63X2aysC2vchE@EnCT9JgghwDPFpP4wraDypvIN1/rm7n6ktQghEoik/TmVpKgK3RjPaZ0503tPs0/v8KNtURaehkC7ERWSTGeOs0INJLNqitiGPz1f342FFEsoppzZl8Y7ayqMRDd6VYpOKipQ3Mzf8QXT4SDsRkJu1IUwWT5rJRKQGkkCmAe@Y5yfI3LweqaCToAtWKk2GyhTn@WcuRAlElrI92Zs2nhtnEOX4kw9JqNbPX7QoyR5SGI6avNDoEPOypg@u7kZAt7oTWobDHE8WKGBDY0yS@XqYLdcyPUb57Hyc9/FI3rLKLxciQu2XnegBRLy87T978d/byeEpwuOS3f5E5CTD/8BSQc20xOyIFs52S9c/BLI4pf5F37QZ9/LQf@d/yN3RxPu2/wC "PHP – Try It Online") - PCRE [Try it online!](https://tio.run/##dZFbb5swFIDf@RWnZGrsrHXTp0lFrNqk9WmdpmVvu0gOmODUGIYPLVPEb8@OE5LmwpCQz/U7t6V8ltfL9Gmti6qsEZakC12KSQSHlga1GbTVaqFa76maudEJJEY6B49SW1j1JocS6XkudQoFOdgMa20XIOuF@/GLA@Z1@eLgU5uoCnVJiQHAgzYKstiql43IQpGUqRLkD3n0sckyVav0m5KpqmG@CTs2sl1mr2acR31dd4XRS@75jLl4TiPI9LO2inF@EdvGGK4z5oT600jjWHgzmUxCzlfHoVsCYzgIWBEB9wQC3BBhTnFPkXsbj3/asX8x6ra27qtEVLWFOu4lmraofAHHI9rGLJHW0qTaVg1CDH643sZmfx2qQmjL6TwWQcfTCPr5NvEil@6LapHagxVQZ/oinvI@rSR/RWtBY5kHxLe@HlXc7spQsS3EEqEfnRjAjDDKLjBn/P0ULi/BiCSX9QdkU1rCeDTmmzP671FiklPzBbFqUWw1Zohz2kPGCpFpmzIO9xB@rxt1BxDCHYQPtEhS6PbdWZZHdV0X@EOtfzN2H2OD1/Rzsbq9etfxyZu1P8F6BB4ZBL179x7Kx9pA4HDCeeqrfQAy6PgfMBjBZvogaINdeHCY2O4JQbtnHsNP6hz2clL/tf@z7s4mPGzzHw "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##dVLbjpswEH33V0xJtbFTki5dqZUg7Ep96AdU@9BVNkWsYy4qMZYxIpsov15qm5CQSy0BczlzzswYKsQ0pbQd5ZwW9YrB/K0sK/VZspRtZpkQj4hmsYRILJYQwk/ne9P8eXuoX97ffz1nX5sMt78xfgpVrab6IbOd537bk8nHllwiHRcmIozEJy9AJ7lcq0kWrx9RzhUIqd8Rk7KUmJa8UmDVJ2tWVXHKyK5SK9@nGgDzORyixrRxxldFAJKpWnLwgr2lXMc5xwR2CPQRC61WMI4FmXrL8D6AWmMevkQKSuOZglQbFmw5NT7nqU6IWgXQ9WRX5Pt2R1pOkwV9rFrHimbQZLHqSJJSAja0W8NvKVOmipwz3M2Sc7dj1yTb0Os7NSdPAG8J6JzZAh6/8jEJzrK2cHG/hLs76O0P4Xg0JkeYHdusNcHDvqOKxZJmHYNrG3b1LASewHmWNfMBHPDB@REXlXacgXDSyFyxrnJGI70hTA4zzKp8y4znuWbW0kxl6/b2fbgavd99OwIjg9Dhz@m/Q/vcuwG8XXBdeorfILmZ@B8hGoHdCEIb1MPRsHBzZECbI@c5@YXOsJcL/VP/V91dTThs8y9Nijit2mlhrzyyN/4P "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##dY/BSsQwEIbv8xRjKjSRbmnxIESCN5/AW12h2CwbiGlJstBd8dlro3bb3cZDmEzy/9/80x39vjX3g/roWuvRHV1mJVgUaAkhwxulT8If/GY8LP8ss4cvdnc7jF9VyTfl9hFPooBda1GjMsGeO98owwFR7fDEsbPKeMp@ey0N1Qxr06CuRrsQ6atJOWqhqyLwIrJieyPSJJ1I0jSCvNiD5IgkiK3Mnazt@57aDEeX1E4iea7HwpGEwbNRsxC4HBIMBIC/zaa6vF92EWHcsLbO7xFI9OM/ICT4sxZAD5Mclsb@TID@zLyEX81ZZrmaP@dfpVttuIz5DQ "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##dU9da4MwFH3PrzjG0Y8xg@5lUAlS6Pa4h9G3zkrHsi6QicRILWP76y7a2trqHsLNvefjnquLt32lwfEitqLMWCp2WMyXc6bF5j2E5H6I3adUAopvhckJID8gnXqeFSYPIdKGF4Q1oFZeEHNOX1MaWoVa@Yx593HDOkgdxcRXZvYRRiNL92OHj92xxYBMy9RAgf9CIwJd6kLMAIoZ6NNG5bahrdORe2iT5PF5kSTVejKJuCmMZ9@UfQd3Dz/T25uqclFbEXKE2tr9X3YDxGFBX3qeD5gMAv8ZEhfN1YSUpKWTrrA8OZDy5HlpfrWnm@Vq/zl/L13vwm7MPw "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##dU9BasMwELzrFYstkBTi0JwKNqaBQm@99VZaMMm6FlUlIyvYxOjtrhKaxIndg9hd7czsTG1atE2FSg3U5u8Wv7D7SFONLd@w4ZPzp9ztXRKeWPXr5aMXCzqwzTJ6Nj@1VLiLREYP@UNWGovFtuJUgdRApa4DpZclpwfRt1Y6TCrTOB/A60yWEIBJoXeJNu7YKvmNLF4wMQZD2AYnSmqEiPITy65eC7etsAksIaBnb3aPKTAPqBoM80sRasq8gMhn81pU@SGGI5GQv3TnOu5vpxngPGFKvf7PiMwu/hMkMZzyEdKRM5yMid1FgXQXzVvxuztjL3f3r/4n7iYJxzZ/AQ "PowerShell – Try It Online") - .NET ``` ^ # Anchor to start of string ( (?=tut-tut) # Assert that the following 7 characters match "tut-tut", # without consuming them. .{1,7} # Skip anywhere from 1 to 7 characters )* # Iterate the above as many times as possible $ # Assert we've reached end of string ``` Alternative 22 bytes: ``` ^(t(?=ut-tut).{0,6})*$ ``` ## Regex (Python / Ruby), 21 bytes ``` ^((?=tut-tut).{,7})*$ ``` [Try it online!](https://tio.run/##dY/BSsQwEIbv8xRjKjSRbmnxIESCN5/AW12h2CwbiGlJstBd8dlro3bb3cZDmEzy/9/80x39vjX3g/roWuvRHV1mJVgUaAkhwxulT8If/GY8LP/MHr7Y3e0w/lQl35TbRzyJAnatRY3KBHfufKMMB0S1wxPHzirjKfvttTRUM6xNg7oa7UKkryblqIWuisCLyIrtjUiTdCJJ0wjyYg@SI5IgtjJ3srbve2ozHF1SO4nkuR4LRxIGz0bNQuBySDAQAP4Wm@ryftlFhHHD2jq/RyDRj/@AkODPWgA9THJYGvszAfoz8xJ@NWeZ5Wr@nH@VbrXhMuY3 "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##dU9da4MwFH3PrzjG0Y8xg91LoRKk0O1xD6NvnZWOZl0gE4mRWsb21120tbXVPYSbe8/HPVfn74dSg@NV7ESRskTssZgv50yLzTaA5H6A/adUAorvhMkIID8gnWqe5iYLIJKaNwkqQK28ScQ5fUtoYBVq5TPmPUY16yh1FBNfqTmEGAws3Y8cPnSHFgNSLRMDBf4LjRB0qXMxAyhmoM8bldmGNk4n7rGN46eXRRyX69Eo5CY3nn1j9v0w/Rnf35Wli8qJkBPS1Pb/uush9gu60su8x6QX@M@QuKiPJqQgDZ20hcXZgRRnz2vzmz3tLDf7L/k76ToXtmP@AQ "Ruby – Try It Online") - Ruby Python and Ruby support the quantifier shorthand of `{,N}` to mean `{0,N}`. Alternative 21 bytes: ``` ^(t(?=ut-tut).{,6})*$ ``` [Try it online!](https://tio.run/##dY/BaoQwEIbv8xTTWDBZXFEKPaSEvfUJerNbkJplA2mUJIK7pc9uTRdXd7WnyWT@/5t/mpM/1uapV19NbT26k0usBIsCLSGk/6Ce7kTrt771LP1Onn/Y5rEfJkXOt/n@Bc8ig0NtUaMywZ06XynDAVEd8Myxscp4yi69loZqhqWpUBeDXYj43cQctdBFFngrsmz/IOIoHknSVIK82VZyRBLEVqZOlvbzSG2Cg0tqJ5G8lkPhSMLiyahZCJz3EQYCgL8cNtb5@7ZbEa4bltbpfwWyOvgPCBH@nQXQwSiHubG7EqC7Mm/hd3vmWe72T/kX6RYXzmP@Ag "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##dU/JTsMwFLz7KyYO6oKIlXLooZYVVSocOaDeSoiKcIslE0WOo6ZC8OshC2nTJpzsebO8eSZ7OxYGAs9yL/OExfKA1XK9ZEZu3zmU8DkOH0pLaLGXNiWA2kE51TzJbMoh41o34xWhN94sFIK@xJSXDr3xGfPuw1rVWB3N5GdijwFGo1Luh44Yu@OSAxKjYgsN8QODAHRtMrkAKBagj1udloC2SX/aBkbRw9MqiorXiZ0EIrOezeyUfd3Nv6e3N0XhokoixDZM@3b/l2hAOGzoW8/zgZBB4r9A4qI@mpCctHLSNeanBJKfMi/Dr/Z0u1ztP/fvtetd2K35Cw "Ruby – Try It Online") - Ruby # Regex ([Raku](https://docs.raku.org/language/regexes)), ~~25~~ 21 bytes[SBCS](https://en.wikipedia.org/wiki/Windows-1252) ``` ^tut»((t?ut)?\-tut)+$ ``` Ported from a previous (21 byte) version of the "POSIX ERE / RE2 or better" regex. [Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgoR@rUKegYpuWmZdZnAFkBkbrK9jbKyiFFJWmWikoKCkoKioouSXmFAN5Spo6KvEKaflFCjmZeanF1rHWXFCN/@NKSksO7dbQKLEvLdG0j9EFcjW1Vf7/B9IgNheURmaj8rAoxK4BUytCHIshWCVwGVjBBVPEBVEO1YSstwJuCFcF3Fgk81FsQrOUC7sbEUowHYnwJIYXMIIB2S8A "Perl 6 – Try It Online") Porting the 21 byte lookahead-using version comes to **28 bytes**: ``` ^<?before t>((t?ut)?\-tut)*$ ``` [Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgoR@rUKegYpuWmZdZnAFkBkbrK9jbKyiFFJWmWikoKCkoKioouSXmFAN5Spo6KvEKaflFCjmZeanF1rHWXFCN/@Ns7JNSgTKpCiV2Ghol9qUlmvYxuiVASkvl/38gDWJzQWlkNioPi0LsGjC1IsSxGIJVApeBFVwwRVwQ5VBNyHor4IZwVcCNRTIfxSY0S7mwuxGhBNORCE9ieAEjGJD9AgA "Perl 6 – Try It Online") ## \$\large\textit{Anonymous functions}\$ # [Raku](https://docs.raku.org/), ~~29~~ 25 bytes[SBCS](https://en.wikipedia.org/wiki/Windows-1252) ``` {/^tut»((t?ut)?\-tut)+$/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7v1o/rqS05NBuDY0S@9ISTfsYXSBXU1tFv/Z/cWKlgoa9nlqagr29glJIUWmqlYKCkoKiooKSW2JOMZCnpKmjEq@Qll@kkJOZl1ps/R@oF6SfC0ojs1F5WBRi14CpFSGOxRCsErgMrOCCKeKCKIdqQtZbATeEqwJuLJL5KDahWcqF3Y0IJZiORHgSwwsYwYDsFwA "Perl 6 – Try It Online") # [Ruby](https://www.ruby-lang.org/), ~~29~~ ~~28~~ 30 bytes ``` ->s{s=~/^\b((t?\But)?-tut)+$/} ``` [Try it online!](https://tio.run/##dVBfT4MwEH@/T3GUZZsxMObjmpPEBz@Bb4DGxaIklRBaIsPoV8fCxmCjvrS9u9@f@7Ws9oc2pda7V9@KfjfP8X691mH8UOmb0NPmvF1sftqGAo5fH5kUKOldaAWIWYqN0/WLSiuOIn/j2NCWdwMZeduEiMU544Yho8D3vbvkhFq8UJ7Jo4QjffFZ6EOIy6WhBYlDK3dlZohFmeUa00gmGCJ7KiuxQ2S4Q/b4KpUpWK8HA1L2ZetiBwUwy3cBhnv6vqwsQDthTh37FhHr4D9BcLFPBVDDAIcj8USfqtRnOajPBhOnC88re7BvO0Lm645xZ2FmHzJN9Qc "Ruby – Try It Online") # JavaScript, ~~35~~ ~~34~~ 33 bytes ``` s=>/^\b((t?\But)?-tut)+$/.test(s) ``` [Try it online!](https://tio.run/##dZBRb4MgFIXf@RVMlwLpartXDTXpw5K9721uiVNMWAg6uG4mTX@7w26tttIXuMD5zr2Hz/w7t4WRDax0XYq@4r3l2/V79kEppNmuBZauwK3L@3UEwgK1rE8s3yRGfLXSCEqMyEsltSAsKlwN4lmDMFVeCLqXumkhbkxdCGsjC6XUBxbVmpIj8aD4do8wtnixwBNV3UL0YyQ490wTlmDLHxOnU4NOvW7e7jgJyU2oooqlwYtpRYxxEAdPubKuDNjg4SUUSw6sD/HAIOTyDplP@7S@PHmEfmCOjvceE@/DLUMU4mNAhDp0kqM/8B@funRnO9SdG0w6XfS8ao/8046S@bhj3FmY2YdMU/0C "JavaScript (Node.js) – Try It Online") # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~35~~ 34 bytes ``` $args-match'^\b((t?\But)?-tut)+$' ``` [Try it online!](https://tio.run/##dZBBboMwEEX3c4qRGRVQZSndJooiddETdNe0Eo2GYsmB1DgCBXF2atMSSCEb2@P574@/T0XFpsxY647SbdNRYr5KeUzsIQs/9p9RZHf757ONd9K69ZHCrt3QZbvapIXh5JBFpFHlSCo/uX4DiCqN6BI3lVGWZVaUtnX6p76BTi35G4VAWRgk/bZ67@tAxOjZFlmX3B8RRweUeZFzpVXOKCjyRg@UOt5R4as58xoxHNjwJXH72l3EwlvCPSfS0HYBeh7ApfMJh316vq0WhMvAHB3vF0wWG/cMIcA@JUANgxx@wT986lJf7aC@DphMupn5bzwsv3aUzJ87xp2FmX3INNUP "PowerShell – Try It Online") # Java, 36 bytes ``` s->s.matches("((?=tut-tut).{1,7})*") ``` [Try it online!](https://tio.run/##dVBPb4IwFL/3Uzwx0dZoo6clMjTbwdO2i7stO3RYpK4UQotijJ/dVUBFYQdSXn9/Xzdsy0ab1e9JREmcGtjYmWZGSBpkyjciVnTgQgMcuMiXTGt4Z0LBAQEk2Y8UPmjDjD22sVhBZDG8NKlQ669vYOlak4IKsKi8n0t0@BrHkjM1gwC8kx7NNI2Y8UOusYPx3DOZGdmP0MNk@HQkA4ecXOuz9JlSPAWhksyAB4rvLnd4udeGR1QoYtsrA8Ibu7ALheSACz4Nmf7gucHElgIRYNHxxqSSxRZPbDMjFT4beBO36F3WBWnDShNlHd6E4gUrACyp5GptQkxmY@j1QFI/ZOmLwWPS8frdPilsrNFDDg4oSxK5x5LAHJzPNONTAAem4CyY1HZwbEJDJYmLjsfjqQtnBULVQ13O@v/91EJsFzSlt/sWk1bgP0PUhWI5hHJ0oaNSWMnrLvnVDuXXgFrSXeZDPGpve6M0697WbSzTeJD6Vn8 "Java (JDK) – Try It Online") ``` s->s.matches("tut\\b((t?ut)?-tut)+") ``` [Try it online!](https://tio.run/##dVBLU8IwEL7nVyxlBhKUDF6phdEDJ/WCN/EQSkqDIe00Wx7j8NsxlFeh9ZTs7vfaXYiV6C5mP3u1TJMMYeFqnqPSPMpNiCoxvONDZdjxSaiFtfAulIFfApDmU61CsCjQPatEzWDpZnSMmTLzr28Q2dyyAgowOmk/H6ePr0mipTADiCDY2@7A8qXAMJaWepjjZDKlFIc5smHXlezBY3vf6YxDYYzMQJk0RwjAyPW5R8dbi3LJlWEuvUFQQc@Hday0BFrgeSzsh9wgZS4UqIiqRtBjJ1ri5qlLhtrQg0Dw5Be5j3FBO7OjiHEKb8rIAhUB1VxLM8eYskEPWi3QPIxF9oK0xxpBu9lmhYwTuvOhERdpqrdUMxiC95nlsg/gQR@8kdDWFZ5zqLA088lut9s34cAgxF3ncKHzW/7fVjXAekKVeu3XiNQO/hMkTSiWI2RDznByJJ7oZZXNRY5sLgYlpxvPO3tSn/YKqca9rltZpnKQ8lZ/ "Java (JDK) – Try It Online") ``` s->s.matches("\\b((t?\\But)?-tut)+") ``` [Try it online!](https://tio.run/##dVBLU8IwEL7nV6xlBhKUDF6phZEDJ/WCN@shlJQGQ9pptjzG4bdjKG9aL0k2@71252IpOvPpz04tsjRHmLuaF6g0jwsToUoNb/tQabZ9EmlhLbwLZeCXAGTFRKsILAp01zJVU1i4Hh1jrszs6xtEPrOshAKMjtovh@7TME21FKYPMQQ72@lbvhAYJdJSLwwnlOIgDIcFskEH3fnosZ3vdMaRMEbmoExWIARg5Or0R8cbi3LBlWEuvUFQQdeHVaK0BFrieSLsh1wjZS4UqJiqh6DLjrTU9TOXDLWhe4Hg2S9zH@KCdmYHEeMU3pSRJSoGqrmWZoYJZf0uNJugeZSI/BVplz0ErUaLlTJO6M6Hxlxkmd5QzWAA3mdeyB6ABz3wRkJbV3jOocLSzCfb7XbXgD2DELed/YZO9/X7tqoB1hOq1Mt/jUht4z9B0oByOELW5AQnB@KRfq2yPsuR9dngyunG886e1Ke9QKpxL@NWhqks5HqqPw "Java (JDK) – Try It Online") # [Julia](https://julialang.org/) v1.2+, ~~39~~ ~~38~~ 37 bytes ``` s->endswith(s,r"^\b((t?\But)?-tut)+") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVFdSsNAEMbXOcWYYLuLBuybNKQBHzyBb1YhpbvtyrCVZIMhV_AIghShh9LTOGmaJjXpy-7Ozvcz3-7n7jUnk2y_dbTLnQ7ufq6yYKbsMns3bi2ym9R7mS-EcPH8PncyDhyv1548gL_KSCeUqRD1JkVCYzFVyZKMVZmQgLiizSIhLEOjeXlLjXVkhQzZIcQycmmuGMVNUnbFhiRntzgaIT1Nni-jsT_mLuKeJzR3MUbvkUlTRA-n6D1U7rxXXqwJDZYkcFlPuf29-PCxYgHw-FWEZu-eT6sB4DChT23vB0QGG-cEwcd9QIACGjjUxAO9q1Ic5aA4GnScTjz_2cPwtC2kP24btxem9yDdVPWn_AE "Julia - Attempt This Online") # [R](https://www.r-project.org/), 40 bytes ``` \(L)grepl('^((?=tut-tut).{1,7})*$',L,,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVHPSsMwGMdrniKusuSTTNaTslC8eepR8DKE2iUzULKSpFA69gQ-gpcp-Aq-iz6Nqe3WztZDSL4vvz_fL3l9M_t3GX0UTs5uvuiSxrA2Is8oeaT0NnKFm_kFV9uQXe_g8oKwmLEQWvynjeYcV5FUmaAT61ZKT4AjuTE0xkpjW-S5EdY-JEYrvbbUiGQVKy0srQBgizBWklpIE0fJUhPgNgp509Xpc-JlAE-nXufJOl-w0HufRyQggGuOkiKzgkoPY-TeFGKBMWHkLvHdBSYAtVYNjIHvUJptPLgC3ky__z57CXDNQqjNedj759NqBDhOGFK7_ojI6MV_gijAvxERKtEBjhpiS--rlEc5VB4Nek4nnn_s0fi0HWQ4bhd3EGbwIP1Uzaf8AA "R - Attempt This Online") ``` \(L)grepl('^tut\\b((t?ut)?-tut)+$',L,,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVFLTsMwEBXbOYVpUO0RrkR3qFHUHasskdhESGlqF0uRG9mOFAVxAo7ApiBxBe4Cp8EhbZM2YWXPzPvMs9_eze5DRp-lk7Pbb5awGDdGFDmjj650SbJizC1Lh8uZL_H6ivKY8znu8V82uglJHUmVCzaxbq30BEOQW8NiojSxZVEYYe1DarTSG8uMSNex0sKyGhGfgRAlmcUsdYwmmmJoo3nYdnX2lHoZJNOp11lZ5ws-996XEQ0okoajpMitYNLDOL03pVgQQjm9S313QShio9UAYwxfIMu3Hlxj2G6_-7l4DUjDAvDhmoCHs38_rUaA44QhteuPiIwO_hOEgPxFBKjgAIeWuKf3VaqjHFRHg57TieeZPYxv20GG63ZxB2EGD9JP1X7KLw "R - Attempt This Online") ``` \(L)grepl('^\\b((t?\\But)?-tut)+$',L,,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVHPSsMwGMdrniKusuTDDOxNFsrAg6ceBS9B6LZkBkpWkhRKxSfwEbxMwVfwXfRpTO22drZeknxffn--X_L6ZnfvKvkovZpdf1FBU9hYWeSUPAixpNQvhLgpPSxmPqyXF4SljMWwx3-65IrjOlE6l3Ti_FqbCXCktpamWBvsyqKw0rn7zBptNo5ama1TbaSjNQA8IYy1og5WmadEGALcJTFvu2b1mAUZwNNp0Fk6HwoWB-_zhEQEcMPRSuZOUhVgjNzZUs4xJozcZqE7xwSg0WqAKfBntMq3AVwDb6fffZ-9RLhhIRTCNQEPe_98Wo0AxwlDatcfERm9-E8QRfg3IkIVOsBRS9zT-yrVUQ5VR4Oe04nnH3s0Pm0HGY7bxR2EGTxIP1X7KT8 "R - Attempt This Online") # [PHP](https://php.net/), 47 bytes ``` fn($s)=>preg_match('/^\b((t?\But)?-tut)+$/',$s) ``` [Try it online!](https://tio.run/##dVBbb4IwGH3vr6i1kTbTCK90Hckyt@xFF@bbcEQNiEmnpNSEZPG3s686BQd76eX0fOfSPMur@yDPckxTWaU7RgsuH3KdbOKvpVlnzBl/RivGTBA9HgwPRgbWOzp2hkCsRLrXjG6lK6iS6SYxBXufP71OueDfeJsyqj4Ko1UCsoqPvIWUJNoRDuTisIIXgIfucORxcWJvebLO9pYiMKh6AmHAMas1BgOQdBc96fQdsLB0fAqrloWJE60hD@/Jt3DyEk9n8SQMZ2FAJhb3MfEZtZl4QOb6kPgYEPK8VAUcCRfHsxyhiohj1ceWgxD0tZ0ve/N8e@sgdg@0R2u8Q6Tz4T9B1MenQgiV6EJH58Hf8aZKeZVD5dWg4XTj@ccedaetKe24dd1WmdaHNFv9AA "PHP – Try It Online") # [Python](https://docs.python.org/), ~~54~~ 53 bytes ``` lambda s:re.match(r'\b((t?\But)?-tut)+$',s);import re ``` [Try it online!](https://tio.run/##dVBLbsMgEN1ziqldCVCbyFF2WChSFz1Bd3EWpMYKEsYWEMnJ5V3TxLFT0w3DDO8zj/biT43Z9qpuG@vBXVwOV57lUPGi16I@lgIcs3JdC/99IhYXR0L8rvg4e7pb@eF8e8XvjuZ3ASv7qrGgQZkgtna@VIYhAFXBlUFrlfGE3notDdEUhClB71ebA@e4MJiB5nqfsWEQgWWHF45TPCpJU/Lky54lA0gCuApQqZ2E5FMMhUES3Ca0piHgpk8h0BAaIoQYY53fn7sIME5YUqd5RCT68J8gSuE3FkIdGuHoRrzT5yrdQw51D4OZ05PnH3sU33aCLNed4i7CLD5knuoH "Python 3 – Try It Online") ## \$\large\textit{Full programs}\$ # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~21~~ 20 bytes ``` ^\b((t?\But)?-tut)+$ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8uJklDo8Q@xqm0RNNetwRIaqv8/w@kQWwuKI3MRuVhUYhdA6ZWhDgWQ7BK4DKwggumiAuiHKoJWW8F3BCuCrixSOaj2IRmKRd2NyKUYDoS4UkML2AEA7JfAA "Retina – Try It Online") # [Pip](https://github.com/dloscutoff/pip), ~~25~~ ~~24~~ 21 bytes ``` +`(t?\But|\b)-tut`~=a ``` [Try it online!](https://tio.run/##K8gs@P9fO0GjxD7GqbSkJiZJU7ektCShzjbx////urr/gRyQAJSCkAgWAA "Pip – Try It Online") Thanks to DLosc for demonstrating this syntax. This is apparently shorthand for [`^((t?\But|\b)-tut)+$`](https://tio.run/##dVBLboMwEN37FFOoZFttIqLsjKxKXfQE2YUsSDGKJWOQbSQS5e4UNyGQ4q7GM/M@89yc3anW215WTW0c2LNN4cKTFEqe9SqvjkUOlhmxrnL3fSIGE@I@ss/WXbMjXbnW0bdX/G5pehcwoi9rAwqk9mJr6wqpGQKQJVwYNEZqR@itV0ITRSHXBaj9anPgHGcaM1Bc7RM2DAKw5PDCcYxHJaELHu1MKxhA5MGlhwplBURf@VAYRN5tQivqA276GDwNoSGCjzHW@fu5CwDDhCV1mgdEgov/BFEMv7EQ6tAIRzfinT5X6R5yqHsYzJyePP/Yo/C1E2R57hR3EWbxIfNUPw "Python 3 – Try It Online"). This regex is slightly less inefficient speed-wise, but by moving all distinctive operations inside the loop, it allows this shortcut to be used. # [Ruby](https://www.ruby-lang.org/) `-n`, ~~25~~ 24 bytes ``` p~/^\b((t?\But)?-tut)+$/ ``` [Try it online!](https://tio.run/##KypNqvz/v6BOPy4mSUOjxD7GqbRE0163BEhqq@j//w9kgDhQCkIiWP/yC0oy8/OK/@vmAQA "Ruby – Try It Online") Prints `nil` for false and `0` for true, which are respectively falsey and truthy in Ruby. If printing `0` or `1` is desired, replace `p~` with `p !!` (+2 bytes). # [Perl](https://www.perl.org/) `-p`, ~~27~~ ~~26~~ 25 bytes ``` $_=/^\b((t?\But)?-tut)+$/ ``` [Try it online!](https://tio.run/##dVC9boMwEN79FCdzIqCGBoYssShShz5BR1TktKZBIsbCRqKJ8uqlDm0CCXTx3dnf31mJulx3jRawfgyjkMH@C/NYN9sjZrGqFOtsXb2lW88zSfrcGD8JjD0fcNUxzE4MtOFGAB4YHlxX1YU0NJXUTnHE4H1X7RWzmjzGjBW5Vwr5aXbIwXXBumhTe8iX4TLypVg4C//YK3iYB0/2wU/oa92IDQDd0BdeattS/9RjADmDRn6IHDDrHDgDCbHZzvkuddzfTjPAecKUOtzPiMw@/CdIHOi3IqQlFzj5Jf7RxyrtVY60V4OR043nnT2ZTztApnGHdSfLTD5kvNV3pUxRSd0F6gc "Perl 5 – Try It Online") # [MATL](https://github.com/lmendo/MATL), 25 bytes ``` '^\<((t?\But)?-tut)+$'XXn ``` [Try it online!](https://tio.run/##y00syfn/Xz0uxkZDo8Q@xqm0RNNetwRIaquoR0Tk/bdXDykqTVWvVXdLzClOVf@vDpQDyUMpCIlgqQMA "MATL – Try It Online") MATL appears to have `\<` and `\>` as its word boundary assertions, and apparently doesn't support `\b`, yet somehow still supports `\B`. I can't currently explain this; I thought it used PCRE. # [Zsh](https://www.zsh.org/), ~~35~~ 34 bytes ``` [[ $1 =~ '^\<((t?\But)?-tut)+$' ]] ``` [Try it online!](https://tio.run/##hVBLCsIwEN3PKd4i0AQR7N4S8Bpt3UhDdwU7QlD06jHFtklNxE0yyZt5n7mPvTNSSVfXECWqF4pzc5SSdXO6sdJ79udOFGhbp4jMcAV3I0OSByZwueN6@8o05gfS0fCfIckCvwjVgwADMZn3VXfpBxxQQWh6xqksLWT0oZ3JYw27ipFd5SMfG0df5iifJbSkYcIykqjJuv5mLufM7g0 "Zsh – Try It Online") Zsh uses GNU ERE as its regex engine, so while `\b` would work, `\<` should be slightly more efficient due to only checking for the type of word boundary that can occur at that location. # [PHP](https://php.net/) `-F`, ~~48~~ ~~47~~ 46 bytes ``` <?=preg_match('/^\b((t?\But)?-tut)+$/',$argn); ``` [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdPy4mSUOjxD7GqbRE0163BEhqq@ir66gkFqXnaVr//w8UAYlyQWlkNioPi0LsGjC1IsSxGIJVApeBFVwwRVwQ5VBNyHor4IZwVcCNRTIfxSY0S7mwuxGhBNORCE9ieAEjGJD98i@/oCQzP6/4v64bAA "PHP – Try It Online") - bare-bones test harness [Try it online!](https://tio.run/##dVBNb4JAFDx3f8WIhNW0BL26IEkPpj21SXtTShBWIaFA1jU1Cr/dLn5ipRx22XlvZt68ebCK96@TDweCBxFMEYFSCNum/umje9t1CsGX/ncgw7hHra/ZvNeT7ux5LfuuKdX5qFv0SQ/EMuuz/ZlIeBjnMDNotrtzx7rQaFVD2izTGMUYYR5xps5C5CHeX96xg5UX0iriwponWX3DDGFxGcKMsIpzIf284Jkvg6XzlsGcnDQq8hMnKUczCNKynB7s9VSDx6KcPKj3FvoWXlnWk7CtM2RIFpiiU1eOnTAMBei7dDQYDSt0HNAuVQKQMc9wCFU3jg19p4aeDr2K3RqbaxxLA69CgLIE3ySS1aIBHAdDeIZxWc6nWPMRoB1HOkCTIF0pTGNYJAwXWJmSKM/4vouaRIhafb3@8938v321NLYT7qlXvEWktfCfIOniEIyQDTm3kyPxRG@qbC5yZHMxaDjdeP6xJ@3TXlvux73GvQtzt5Bmql8 "Bash – Try It Online") - fancier test harness [Answer] # [Zsh](https://www.zsh.org/), ~~66~~ 54 bytes ***-6 bytes** thanks to Neil, **-6 bytes** by switching to `-e` thanks to pxeger.* ``` s=xxxxxx$1 repeat $#1 [[ ${s:$[i++]:13} = *tut-tut* ]] ``` [Try it online!](https://tio.run/##hY/LCsMgEEX38xUX6iIPApXuAqEfErIoRUlXKdGCNOTbjS15mGipMDjOOHfueavWyiRNlNAohFWV@R7GqRdPcdNgJ466BhtUyepHnjclv4yokOmXLlxkaBqbEsmuhxZKI6G5s9x@vn9FPsYHwtGtHhGJNn4JpgMBEuxj3mXi3nY4O0B2pdGnMrSIkS9rVn0y68b96oML3@nB3UYXeA/4/0LwGcJO "Zsh – Try It Online") ~~[Try it online!](https://tio.run/##hY/PCsMgDMbveYrAPNiWwWS3QtmDiIcxlPbUUR3I2j67c1v/2OqYIIkm@fL9nrp2imbU6cp@DmHfCJ28y6tBcmDIOZJel4Q3RSFKdh6xwtw8zNHfHIUYBmkb4zIA1XZopDZIYarPMcy3r0RjeiAeXf8TIsnCL8GsB0SF5G3eZ/JWt3jymOQCY0hlYRaDUNYu@mCXjdvVOxeh0527lS7yHvH/hWAThHsB "Zsh – Try It Online")~~ The problem stated is equivalent to: Every sliding 13-character window of `xxxxxx[string]xxxxxx` contains `tut-tut`. In Bash and Zsh, the `${var:${idx}:13}` is valid even if the string isn't long enough, so the trailing `xxxxxx` are unneeded. We loop over each window, and `exit` out if any single test fails thanks to `errexit`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 21 bytes ``` ∧/7∨/'tut-tut'⍷6∘↓⍣¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEcdy/XNH3Ws0FcvKS3RBWL1R73bzR51zHjUNvlR7@JD6w3/Vz/qmwpUmQahHvVufdTd8qij/VHvvFog/g/VxwWlkdmoPCwKsWvA1IoQx2IIVglcBlZwwRRxISuvgOvjqoCbhGokmunILkCzFeFqDDdh@AvZcQA "APL (Dyalog Classic) – Try It Online") ``` 6∘↓⍣¯1 pad with leading spaces 'tut-tut'⍷ find occurrences of tut-tut ∧/7∨/ present in every group of 7 consecutive positions ``` [Answer] # Python3, 61 bytes: ``` f=lambda x:x==''or'tut-tut'==x[:6|f(x[4:])|f(x[6:])|f(x[7:])] ``` [Try it online!](https://tio.run/##jZBNCsIwEIXXzilCN0nEiqhUKeQKXqB2UbHBQE1KjBDBu8ei/W8KLkJefubN96Z8mZuSu2OpneOsyO6Xa4ZsbBnDWGlsniasFmbMJnH05sQm@zilXxE14lCJ1HGlkUBCIi4Kk2tyUjJfoSAIag@o974enjwf/QXT0u7eY@J9mDGseNePshCG4LPElMawKLWQhnAiKIWfxiFebjcUYDazBQtNM/i1rZv3GWwLA7bFG3KOkPuxRlG6UUyCTob1f2L3AQ) [Answer] # [Python](https://www.python.org), 50 bytes ``` def f(s):s[:7]=="tut-tut"and f(s[~ord(s[7])%5|4:]) ``` Signals by exit code: errors out if the input is "tut-tut"-decomposible. ## How? Recursively checks that input starts with "tut-tut". Based on the next character directly computes where the next "tut-tut" has to start. ``` 0 1 2 3 4 5 6 7 8 9 ... --- t u t - t u t | - | | | ==> t u t | - | t u t --- --- t u t - t u t | u | | | ==> t | u | t - t u t --- --- t u t - t u t | t | | | ==> | t | u t - t u t --- ``` The figure shows offsets inferred from char at position 7: * `"-"` --> 4 * `"u"` --> 6 * `"t"` --> 7 The magic formula `~x%5|4` implements this map. `x` is the code point of input character. Importantly, any input is mapped to 4,5,6,7, so the algorithm can neither get stuck nor skip any characters. Now, if we can cover the input with `"tut-tut"`s we will eventually reach the end and error out as soon as we try to access out-of-bounds characters. Otherwise the algorithm will simply stop at the first place that cannot be covered. [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jVJS0xTSNIo1rYqjrcxjbW2VSkpLdIFYKTEvBSQRXZdflAKkzGM1VU1rTKxiNaE6HdPyixRyFDLzFPILUvM0DDStuBRKiiqt0jRy9IpLijILNDQ1rQuKMvNKNJT8lDS5FFIrklMLSqygQpFKUIMW3GLMh9rJBaWR2ag8LAqxa8DUihDHYghWCVwGVnDBFHFBlEM1IeutgBvCVQE3FtV8NKu4sLsMoQTTaQivYTgcw_PIPoAEPAA) ### Thanks to eagle-eyed @Jonathan Allan for spotting a problem with my first attempt. ### Wrong [Python](https://www.python.org), 54 bytes ``` def f(s):s[:7]=="tut-tut"and f(s[~ord(s[7])%31%12%8:]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3zVJS0xTSNIo1rYqjrcxjbW2VSkpLdIFYKTEvBSQRXZdflAKkzGM1VY0NVQ2NVC2sYjWhuh3T8osUchQy8xTyC1LzNAw0rbgUSooqrdI0cvSKS4oyCzQ0Na0LijLzSjSU_JQ0uRRSK5JTC0qsoEKRSlCDFtxizIfaywWlkdmoPCwKsWvA1IoQx2IIVglcBlZwwRRxQZRDNSHrrYAbwlUBNxbVfDSruLC7DKEE02kIr2E4HMPzyD6ABDwA) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 70 bytes ``` b-->"tut-tut". n-->(b;"ut-tut";"-tut"),(n;""). t-->b;b,n. +X:-t(X,[]). ``` [Try it online!](https://tio.run/##dVBLDoMgFNxzCsIKIngASXoKFybWGGnRNkGxiqm3t2isX1yQx/vNm5m60UoXrP2@h4DBVpq0nipprrICP3UnlEw/nTaypfDxypqW@GAQjN2Q6QyzD/mgsikWHM0FjqZAKK44Qnbe2L7gglY@8KKAGRzROCH@MOS6yZTCpSyFbHBIYQwWWLp8D@mp4N643HRirC032lXvCjkhFAIvtOLBhcg/yBgX0BX9cKff3hz//ZbLnteR5JnynLml7madcne@uSxx@Xu25@7B0aEf "Prolog (SWI) – Try It Online") -4 from jo king. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ ~~14~~ 13 bytes ``` mp13l‛≠₈‹∞vcg ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwibXAxM2zigJviiaDigojigLniiJ52Y2ciLCIiLCJ0dXQtdHV0XG50dXQtdHV0LXR1dFxudHV0LXR1dHV0LXR1dFxudHV0LXR1dHR1dC10dXRcbnR1dC10dXQtdHV0LXR1dC10dXRcbnR1dC10dXR1dC10dXQtdHV0dXQtdHV0XG50dXQtdHV0dXQtdHV0LXR1dHR1dC10dXRcbnR1dC10dXQtdHV0dXQtdHV0dHV0LXR1dFxudHV0LXR1dHR1dC10dXR1dC10dXQtdHV0dXQtdHV0XG54XG50dXRcbnR1dC1cbi10dXRcbnR1dC10dXR4XG50dXQtdHV0dFxueHR1dC10dXRcbnR0dXQtdHV0XG50dXQtdHUtdHV0XG50dXQtdHV0dHV0XG50dXQtdHV0LXR1dHRcbnR1dC10dXR0dXQtdHVcbnR1dC10dXR1dHV0LXR1dFxudHV0LXR1dHR1dHR1dC10dXRcbnR1dC10dXR1dHV0LXR1dHV0LXR1dCJd) | [12 bytes with `g` flag](https://vyxal.pythonanywhere.com/#WyJBZyIsIiIsIm1wMTNs4oCb4omg4oKI4oC54oiedmMiLCIiLCJ0dXQtdHV0XG50dXQtdHV0LXR1dFxudHV0LXR1dHV0LXR1dFxudHV0LXR1dHR1dC10dXRcbnR1dC10dXQtdHV0LXR1dC10dXRcbnR1dC10dXR1dC10dXQtdHV0dXQtdHV0XG50dXQtdHV0dXQtdHV0LXR1dHR1dC10dXRcbnR1dC10dXQtdHV0dXQtdHV0dHV0LXR1dFxudHV0LXR1dHR1dC10dXR1dC10dXQtdHV0dXQtdHV0XG54XG50dXRcbnR1dC1cbi10dXRcbnR1dC10dXR4XG50dXQtdHV0dFxueHR1dC10dXRcbnR0dXQtdHV0XG50dXQtdHUtdHV0XG50dXQtdHV0dHV0XG50dXQtdHV0LXR1dHRcbnR1dC10dXR0dXQtdHVcbnR1dC10dXR1dHV0LXR1dFxudHV0LXR1dHR1dHR1dC10dXRcbnR1dC10dXR1dHV0LXR1dHV0LXR1dCJd) Returns `1` for true, or falsy for false (`0` or an empty list). ``` mp13l‛≠₈‹∞vcg m # Mirror the input - append its reverse p # Append the input to that 13l # Get all overlapping strings of length 13 ‛≠₈‹∞vc # For each, does it contain "tut-tut"? g # Minimum. Returns an empty list for an empty list (no idea why) ``` -3 from porting Jonathan Allan's Jelly answer! -1 thanks to emanresu A. Previously: ## [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` 6Iø.13l`≠₈-`∞vcA ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiNknDuC4xM2xg4omg4oKILWDiiJ52Y0EiLCIiLCJ0dXQtdHV0XG50dXQtdHV0LXR1dFxudHV0LXR1dHV0LXR1dFxudHV0LXR1dHR1dC10dXRcbnR1dC10dXQtdHV0LXR1dC10dXRcbnR1dC10dXR1dC10dXQtdHV0dXQtdHV0XG50dXQtdHV0dXQtdHV0LXR1dHR1dC10dXRcbnR1dC10dXQtdHV0dXQtdHV0dHV0LXR1dFxudHV0LXR1dHR1dC10dXR1dC10dXQtdHV0dXQtdHV0XG54XG50dXRcbnR1dC1cbi10dXRcbnR1dC10dXR4XG50dXQtdHV0dFxueHR1dC10dXRcbnR0dXQtdHV0XG50dXQtdHUtdHV0XG50dXQtdHV0dHV0XG50dXQtdHV0LXR1dHRcbnR1dC10dXR0dXQtdHVcbnR1dC10dXR1dHV0LXR1dFxudHV0LXR1dHR1dHR1dC10dXRcbnR1dC10dXR1dHV0LXR1dHV0LXR1dCJd) Uses the same idea as @GammaFunction's Zsh answer. ``` 6Iø.13l`≠₈-`∞vcA 6Iø. # Surround the input with 6 spaces on both sides 13l # Get all overlapping strings of length 13 `≠₈-`∞vcA # Do all of them contain "tut-tut"? ``` [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 42 bytes ``` f""=1 f(a@(_:_++b)++c)|a=="tut-tut"=f$b++c ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NScnWkCtNI9FBI94qXls7SVNbO1mzJtHWVqmktEQXiJVs01SSgIL/cxMz8xRsFdIUYDJQCkIiWEr/AQ "Curry (PAKCS) – Try It Online") Returns `1` for truth, and nothing otherwise. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 42 bytes ``` {^.comb⊆m:ex/tut\-tut/>>.&{.from..^.to}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7vzpOLzk/N@lRV1uuVWqFfklpSYwukNC3s9NTq9ZLK8rP1dOL0yvJr639X5xYqaASr2Brp6CnlqaQll@kkJOZl1r8H6gcpIULSiOzUXlYFGLXgKkVIY7FEKwSuAys4IIp4kJWXgHXx1UBNwnVSDTTkV2AZivC1RhuwvAXsuMA "Raku – Try It Online") An anonymous function that takes a string and returns a true/false value for if it is composed of overlapping 'tut-tut's. ### Explanation ``` { } # Anonymous function block ^.comb # The range 0 to length of input ⊆ # is a subset or equal to m:ex/tut\-tut/ # Match all instances of 'tut-tut' >>.&{ } # And map them to .from..^.to # The range of covered indexes ``` This basically finds the indexes covered by each 'tut-tut' and makes sure that they cover the entire string. Note that you could easily generalise this function to any string. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes ``` Ẹ|a₀"tut-tut"sl;?b₍↰ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuHTWJj5oalEpKS3SBWKk4x9o@6VFT76O2Df//w0QhJAjDlAEA "Brachylog – Try It Online") ### Explanation This is a pretty straight-at-the-problem approach; possibly something more subtle would be shorter. ``` Ẹ|a₀"tut-tut"sl;?b₍↰ Ẹ Either the input is the empty string | Or a₀ A prefix of the input "tut-tut" is "tut-tut" s Take a nonempty substring of "tut-tut" l Get its length ;?b₍ Remove that many characters from the start of the input string ↰ Recurse ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~24~~ 23 bytes *Edit: saved 1 byte based on Dominic van Essen's comment.* ``` ±Λ≤7Ẋ-J¥¨μζ-μζ¨X7¹e_6→L ``` [Try it online!](https://tio.run/##yygtzv7//9DGc7MfdS4xf7irS9fr0NJDK87tObdNF0QcWhFhfmhnarzZo7ZJPv///y8pLdEFYgiJYAEA "Husk – Try It Online") ## Explanation ``` ±Λ≤7Ẋ-J¥¨μζ-μζ¨X7¹e_6→L ±Λ≤7 check if all differences are ≤7 Ẋ- take the difference of all adjacent elements in list J put indices list the into the middle of [-6,1+len(input)] ¥ create indices list of all occurrences of "tut-tut" in substring list ¨μζ-μζ¨ "tut-tut" X7¹ create list of substrings of input with length 7 e_6→L list [-6,1+len(input)] ``` [Answer] # [sed](https://www.gnu.org/software/sed/), 39 bytes ``` :a s/tut-tut/TUTTUT/i ta s/[^TU]// T cN ``` [Truthy test cases -- outputs nothing](https://ato.pxeger.com/run?1=m724ODVlebSSbl6RUuyCpaUlaboWN9WtErmK9UtKS3SBWD8kNASI9DO5SkCi0XEhobH6-lwhXMl-EOVQXQturoXq4ILSyGxUHhaF2DVgakWIYzEEqwQOAyGuBgA) [Falsy test cases -- outputs one N for each line](https://ato.pxeger.com/run?1=m724ODVlebSSbl6RUuyCpaUlaboWN9WtErmK9UtKS3SBWD8kNASI9DO5SkCi0XEhobH6-lwhXMl-EOVQXQtunq7gAqoHYV0uXTALQpbqwoSBuALGKOGqgLK4SuCMUiSWLqpGKBNVAdQkGANNPZCC8dAMLsE0qRROg0iInwA) The idea here is quite simple: * Continuously replace `tut-tut` with `TUTTUT`, using case-insensitive matching, until the input stops changing. * Check if there are any lowercase characters or `-` left. * If so, output an `N` for failure. Otherwise, output nothing for success. # [sed](https://www.gnu.org/software/sed/), 29 bytes, straight regex, thanks to Deadcode ``` s/^((t?\But)?\b-tut)+$// t cN ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlebSSbl6RUuyCpaUlaboWe4v14zQ0SuxjnEpLNO1jknRLgLS2ir4-VwlXsh9EDVTpgluMlUBZkAouKI3MRuVhUYhdA6ZWhDgWQ7BK4DKwggumiAuiHKoJWW8F3BCuCrixSOaj2IRmKRd2NyKUYDoS4UkML2AEA7JfIFEAAA) Thanks to Deadcode for this alternate approach which forgoes looping and solves it with a single application of a true regex. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žO.øü13"tut-"ûδåP ``` Port of [*@GammaFunction*'s Zsh answer](https://codegolf.stackexchange.com/a/251775/52210), so make sure to upvote him/her as well! [Try it online](https://tio.run/##yy9OTMpM/f//6D5/vcM7Du8xNFYqKS3RVTq8@9yWw0sD/v8H8YAYQoIwlAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/6P7/PUO7zi8x9BYqaS0RFfp8O5zWw4vDfiv8x/EBWIuKI3MRuVhUYhdA6ZWhDgWQ7BK4DKwggumiAuiHKoJWW8F3BCuCrixSOaj2IRmKRd2NyKUYDoS4UkML2AEA7JfAA). **Explanation:** ``` žO # Push constant string "aeiouy" .ø # Prepend and append this string to the (implicit) input ü13 # Pop and create overlapping parts of size 13 "tut-"û # Push string "tut-" and palindromize it to "tut-tut" δ # Map over each overlapping part using "tut-tut" as argument: å # Check if the part contains "tut-tut" as substring P # Product to check if all are truthy # (after which the result is output implicitly) ``` [Answer] # JavaScript (ES6), 58 bytes A non-regex solution. ``` f=([c,...a],i)=>i>6?!c:c=="tut-"[i&3]&&f(a,-~i)|3%~-i&f(a) ``` [Try it online!](https://tio.run/##jVKxDoIwEN39C0mENqFdSBxMiptf4FYZmgpaQ6iBYjAx/HpVFjRpyw0deu/u3t27dxMP0clW3Q1p9Lm0tmKIy5RSKopUYZarfLtfy51kLDK9IRFXcVbEcYVESkaFX9lmJOr7xVbqptN1SWt9QQk/tr25PosEr37jFZrafF6EfUgYXcJB7aE0EMI5E0QNTA2M8VeRnBp@EHXnUnpwt/eQOsK@Eb2jh3caAus6oCEgUlC/BW0XhXeDoOuGGkMOHrIZwDIAs8JMTTyOmKC52r4B "JavaScript (Node.js) – Try It Online") ### How? We use a pointer \$i\$ into the string \$s=\$ `"tut-tut"`. At each iteration, we make sure that the current character from the input string matches \$s[i]\$, then we either increment \$i\$ or restart with \$i=0\$ if we are allowed to do so. The parsing is successful if we end up with \$i=7\$ exactly when the end of the input string is reached. The table below summarizes after which positions it's possible to restart with \$i=0\$ and how this can be computed with the expression `3 % ~-i & 1`. | i = position | character | restart after? | 3 % ~-i | 3 % ~-i & 1 | | --- | --- | --- | --- | --- | | 0 | t | No | 0 | 0 | | 1 | u | No | NaN | 0 | | 2 | t | No | 0 | 0 | | 3 | - | Yes | 1 | 1 | | 4 | t | No | 0 | 0 | | 5 | u | Yes | 3 | 1 | | 6 | t | Yes | 3 | 1 | [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` m0;w13Ƥ“"ṁĿ4ṘṘ»Ṃ ``` A monadic Link that accepts a list of characters and yields `1` if constructible or `0` if not. **[Try it online!](https://tio.run/##y0rNyan8/z/XwLrc0PjYkkcNc5Qe7mw8st/k4c4ZQHRo98OdTf8f7t5ydM/h9kdNa1S8gUTk//8lpSW6QMwFpZHZqDwsCrFrwNSKEMdiCFYJXAZWcMEUcUGUQzUh662AG8JVATcWyXwUm9As5cLuRoQSTEciPInhBYxgQPYLAA "Jelly – Try It Online")** ### How? The input must (a) start with `tut-tut`, (b) end with `tut-tut`, and (c) have `tut-tut` as a contiguous substring of all of its length \$13\$ slices. We can, however, just test that (c) holds for the input concatenated with its reverse concatenated with the input (e.g. `abc` -> `abccbaabc`). This works since `tut-tut` is palindromic and any bad starts or bad ends in the input will now nest between any `tut-tut`s. ``` m0;w13Ƥ“"ṁĿ4ṘṘ»Ṃ - Link: list of characters, S e.g. "abc" m0 - reflect -> "abccba" ; - concatenate -> "abccbaabc" Ƥ - for infixes... 13 - ...of length 13: w “"ṁĿ4ṘṘ» - first 1-indexed index of "tut-tut" or 0 if not found Ṃ - minimum (an empty list yields 0) ``` --- Bit of a shame it takes half the code to make "tut-tut"! [Answer] # [Husk](https://github.com/barbuz/Husk), ~~22~~ ~~18~~ 17 bytes *Edit: saved ~~4~~ 5 bytes based on [Jonathan Allan's idea](https://codegolf.stackexchange.com/a/251810/95126)* ``` ▼M€X13‼S+↔⁰¨μζ-μζ ``` [Try it online!](https://tio.run/##yygtzv7//9G0Pb6PmtZEGBo/atgTrP2obcqjxg2HVpzbc26bLoj4//9/SWmJLhBDSAQLAA "Husk – Try It Online") ``` ‼ ⁰ # apply twice to the input: S+↔ # join to itself reversed X13 # and split this into strings of 13 characters; M # now map over these € # do they contain ¨μζ-μζ¨ # the compressed string "tut-tut"? ▼ # and return the minimum result ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 39 bytes ``` x=>x.replace(/(?=tu)((t?ut)?-tut)*/,"") ``` [Try it online!](https://tio.run/##lZLLCsMgEEX3@QxXTmmabTfWH8lGQqQpQcSMwX69SUmhxCfdOHDmcuflS6xiGcyksV3vXjLv2MPdzKhnMYy0o5yhBUqRWwTe4v5euish4LWZFFKCxuLz3SsCTXMguUOLHykBiFiO5zMVs7pp2f6nqRSqigpFv1rSKynmJVyXC90i9xOI6yc6yjXpkp2foEvOmB@8sI8QV1b8X@II6ZsWr1T8DcHp/AY "JavaScript (V8) – Try It Online") Returns a falsy string if the string is correctly composed of `tut-tut`s, and a truthy string otherwise. Mostly the same logic as my (slightly broken) [regex solution](https://codegolf.stackexchange.com/questions/251772/tut-tut-tut-tut-tut#comment560666_251777), except instead of having the "this regex matches the entire string or else it fails" logic be in the regex, its in the fact that we only delete one occurrence of the pattern. If the entire string is not composed of the pattern, there will be string remaining after the replacement, and in js, any nonempty string is truthy, with the empty string being the only falsy string :-) (in case you wonder why this doesn't fail for cases where two valid strings are concatenated: regex is greedy, and will grab the largest match it can grab) Breakdown: ``` x=>x.replace(/(?=tu)((t?ut)?-tut)*/,"") // full function x=>x.replace(/ /,"") // return the string with exactly one // match of the following regex removed (?=tu) // string starting with "tu" ( )* // which contains at least 0 of // the following pattern // (actually at least 1, since otherwise, // the pattern would be empty and // thus would fail the "tu" check) (t?ut)?-tut // any of "-tut" // (will never be at the start due to the // "tu" check, but can appear in cases // where the entire "tut" overlaps), // "ut-tut" // (in cases where just the "t" is overlapping, // also can never be at the start) // or "tut-tut" // (this one always comes first // due to the "tu" check) ``` BTW this regex saves a byte over the straightforward regex `/tut-tut((t?ut)?-tut)*/` because we don't actually have to use the entire "tut-tut"; the first group `((t?ut)?-tut)` is forced to complete to `tut-tut` once it's forced to start with `tu`, if that makes sense... :-) [Answer] # [Factor](https://factorcode.org/), 36 bytes ``` [ R/ tut\b((t?ut)?-tut)+/ matches? ] ``` [Try it online!](https://tio.run/##dVC5DsIwDN39FR5bIegOQ0fEwkDFBAwhMsfQkqSuGoT49lAEvUgYotjxO/xyEpJvxm2z1Xo5R11jSbqiQlKJyhDzXZlrwWjoTFbhAkDXD@CKp81p72E97gLAMMGn9u8BkeDgnyBYaFHwwX9ZQ7LtVMB2ugODkdWPK4SX7CH@ln1KL4P3D6MwT3A73CTY1PtjFHFacZy@J/EkwVywvFCZ4sHlQuHMvQA "Factor – Try It Online") Port of Deadcode's (Bubbler's/thejonymyster's) [regex answer](https://codegolf.stackexchange.com/a/251777/97916). # [Factor](https://factorcode.org/) + `math.unicode`, 63 bytes ``` [ "xxxxxx"dup surround 13 clump [ "tut-tut"swap subseq? ] ∀ ] ``` [Try it online!](https://tio.run/##dVG7DsIwDNz9FVZ3KiE2GBgRCwtiQh1KG0pFm6Z5qEUIiZHv5EdCgD5JiBQlse/OvvgYRrLgerddb1ZzLCsUpFSERkRgwgvFUprgmXBKMsxDefIVTaMiJsg4kfLCeEolLgDK6gpSyYnZ7Tm8j18OoJtgU/u4Q8SZ@CcINbQo@OIb1pBcdypQd7qDAqNSP1XB3WQPsbvsXVoerH8YmbmB3qNXf5YXK4ZCcTM9GuN0hlGmcoYm36A9UYVvxMGMeokBPh93DHRuYr5@AQ "Factor – Try It Online") Port of GammaFunction's [Zsh answer](https://codegolf.stackexchange.com/a/251775/97916). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ⬤θ№✂⁺×⁶ψθκ⁺¹³κ¹…tut-⁷ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0ejUEfBOb8UyAnOyUxO1QjIKS3WCMnMTS3WMNNRqNTUUSgE4mwdBbCEoTGQDeQbArFzZXJOqnNGfoGGUklpia6SjoK5JhBY//8P4gIxlIKQCNZ/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a valid string, nothing if not. Explanation: A port of my golf to @GammaFunction's zsh answer. ``` θ Input string ⬤ All indices satisfy ⁶ Literal integer `6` × Repetitions of ψ Null byte ⁺ Plus θ Input string ✂ ¹ Sliced from κ Current index to ¹³ Literal integer `13` ⁺ Plus κ Current index № Contains tut- Literal string `tut-` … Extended to length ⁷ Literal integer `7` ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 24 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ☼▌☼▐l£{_C<ÿtut-ñ╧\╞};]ε* ``` Port of [*@GammaFunction*'s Zsh answer](https://codegolf.stackexchange.com/a/251775/52210), so make sure to upvote him/her as well! [Try it online.](https://tio.run/##y00syUjPz0n7n6OgbqUQW1mY8//RjD2PpvWAyQk5hxZXxzvbHN5fUlqie3jjo6nLYx5NnVdrHXtuq9b//0ogUSBW4oKxUHnofKzKcWnDZgBCBqtROKRwG1sBUQRVCqRgGuEGoJpUgWQoSDuSVSi2orkAwzkQDlY/ICvE5g3kwMDiUSxBhuJnAA) **Explanation:** ``` ☼▌ # Prepend a leading "100000" in front of the (implicit) input-string ☼▐ # Append "100000" as well l£ # Push the input-string, pop and push its length { } # Loop that many times: _ # Duplicate the current string C< # Pop the copy, and keep its first 13 characters ÿtut-ñ # Push string "tut-", and palindromize it to "tut-tut" ╧ # Check if the string contains this "tut-tut" as substring \ # Swap so the string we've duplicated is at the top of the stack again ╞ # Remove its leading character ; # After the loop, discard the remaining string from the stack ] # Wrap everything else on the stack into a list ε* # Product (reduce by multiplication) to verify whether all checks were # truthy # (after which the entire stack is output implicitly as result) ``` [Answer] # [Rust](https://www.rust-lang.org/), 101 bytes ``` |s:&str|(0..s.len()).scan(0,|r,i|{if s[i..].starts_with("tut-tut"){*r=7}*r-=1;Some(*r)}).all(|i|i>=0) ``` [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ab36eb7d3a2f58e531a798f15cd87573) Returns a boolean with the obvious meaning. [Answer] # [jq](https://stedolan.github.io/jq/), ~~78~~ 68 bytes ``` [range(length) as $i|"xxxxxx\(.)"[$i:13+$i]|contains("tut-tut")]|all ``` [Try it online!](https://tio.run/##yyr8/z@6KDEvPVUjJzUvvSRDUyGxWEEls0apAgxiNPQ0laJVMq0MjbVVMmNrkvPzShIz84o1lEpKS3SBWEkztiYxJ@f/fyifC0ojs1F5WBRi14CpFSGOxRCsErgMrOCCKeJCVl4B18dVATcJ1Ug005FdgGYrwtUYbsLwF7Lj/uUXlGTm5xX/1w0CAA "jq – Try It Online") ~~[Try it online!](https://tio.run/##yyr8/z9aTyGxWEGlvEappLREF4iVajLzijNTUjWKEvPSUzWAMjmpeeklGZpgdZk1ShVgEAOU0VSKVsm0MjTWVsmM1YytSczJ@f8fagoXlEZmo/KwKMSuAVMrQhyLIVglcBlYwQVTxIWsvAKuj6sCbhKqkWimI7sAzVaEqzHchOEvZMf9yy8oyczPK/6vGwQA "jq – Try It Online")~~ Port of my Zsh answer. ~~The `<> as $<>` feels optimizable, but I couldn't figure it out.~~ *EDIT: Turns out, it was optimizable!* [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` pÔiU ãD eø`t©-t© ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cNRpVSDjRCBl%2bGB0qS10qQ&input=WwoidHV0LXR1dCIKInR1dC10dXQtdHV0IgoidHV0LXR1dHV0LXR1dCIKInR1dC10dXR0dXQtdHV0IgoidHV0LXR1dC10dXQtdHV0LXR1dCIKInR1dC10dXR1dC10dXQtdHV0dXQtdHV0IgoidHV0LXR1dHV0LXR1dC10dXR0dXQtdHV0IgoidHV0LXR1dC10dXR1dC10dXR0dXQtdHV0IgoidHV0LXR1dHR1dC10dXR1dC10dXQtdHV0dXQtdHV0IgoKIngiCiJ0dXQiCiJ0dXQtIgoiLXR1dCIKInQtdHV0IgoidHUtdHV0IgoidHV0LXR1dHgiCiJ0dXQtdHV0dCIKInh0dXQtdHV0IgoidHR1dC10dXQiCiJ0dXR1dC10dXQiCiJ0dXQtdHUtdHV0IgoidHV0LXR1dHR1dCIKInR1dHR1dC10dXQiCiJ0dXQtdHV0LXR1dHQiCiJ0dXQtdHV0dC10dXQiCiJ0dXQtdHV0dHV0LXR1IgoidHV0LXR1dHV0dXQtdHV0IgoidHV0LXR1dHR1dHR1dC10dXQiCiJ0dXQtdHV0dXR1dC10dXR1dC10dXQiCl0KLW1S) ``` pÔiU ãD eø`t©-t© :Implicit input of string U p :Append Ô : Reverse iU :Prepend input ã :Substrings of length D : 13 e :All ø : Contain `t©-t© : Compressed string "tut-tut" ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 57 bytes ``` x=>x.split`-tut`.every(i=>+{ut:1,tut:1,'':x[3]+1}[j=i])>j ``` [Try it online!](https://tio.run/##jVJBCoMwELz3GV6iWAXpTYjHvqC3VFBsbCPBiIkSKX172nqxhSTuJYfM7szu7HT1XMtmZINKenGjpsVG40KncuBMVYmaVJXSmY5LyHARPyeVZ0e1vgjlmpzKOHuRDrMyKjrTiF4KTlMu7iEil3FSj6VE0eH3vw2DT/@XOIhciB/dw0H0UBmI4FYJkgaWesb460DXnpxrLm1Oazu9Q9Ty7RrRObp/J@1Z1wJpj0le/3a83TXeDoKu6yOGHNwXM0BkAGGFhTpxJGKFtm7zBg "JavaScript (Node.js) – Try It Online") Regless See another regless solution [here](https://codegolf.stackexchange.com/a/251796/) [Answer] # [C (gcc)](https://gcc.gnu.org/), 58 bytes Assumes non-empty input ``` f(char*s){s=bcmp(s,"tut-tut",7)?!*s:f(s+4)|f(s+6)|f(s+7);} ``` [Try it online!](https://tio.run/##nVJbT4MwFH7frziSkLQbxOnURRF9MP4Kt4fZtRvRwcKpkYj8dbFAua74YNPm9Ny@c2XujrE8F4TtN/EUaYr@KzscCTqW/JCuepazpI9nU7wTBGdX9LsgNxVZUi/Lg1DCYROEhEI6AXVKJJAcJb6swYe0RYL6O2BPBGaPUU8jRqsyo43p/kBOtFltXdDGu4UZACZd8BKmG7SfwDCb09w0Z66pZ2usq9cgU@2mRvb6kHnlmIu58@TImeTbas4XDozd@b@vjsaiEKVeLbbn7I3HerlWyfPlKrl9Uu@6SLrDL@pcRRQDKRIOwi1PlNvc0997wOCLR4LUpdBzLZg2Eg9ms9KalmDVlnc2XeFV214arb1GX0REpRVE0r6UK2nTvKHbMVYmglg2gvsA9hZsXIWqNOkAOk316Pt8rWGzSZb/MPG@2WHufv4C "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 62 bytes ``` f(char*s){s=bcmp(s,"tut-tut",7)?0:!s[7]|f(s+4)|f(s+6)|f(s+7);} ``` [Try it online!](https://tio.run/##nVJbT4MwFH7frzguIWk3iPNKFNEH46/YeMCu3YiOLZwaiZO/LpZSGLDOB5s2p@f2nSvzVoyVpSBsHWcTpHsMX9lmR9Adyw/pqTd2ffo0uz/DuR99C4LTa6rJbU18GhRlkkrYxElKKOxHoI5GA8lR4jyCEPYHNGi@A/ZIYPc46WnFOKjsaKd0fyDnxqyxrmjrfYAZAOZdcA3TDdpPYJjNcW6Gs9fUs7XW1WuQrXZbI3t9KAI95mruPN9xJvmynvOFC6fu7N/XRGPbFKVZLbbm7I1nZrkW@cvlIr97Vu@mSrrDXzW5im0GpEo4SZc8V26zwHwfAJMvvhWkKYWeG8GklQQwnWprqsHqLe9susKrt10bRUGrryKi0goiaV/KlbRt3tBtlykTQcYOgvcIzhIcXKSqNOkCum31GIY8MrDFqCh/mHiPV1h6n78 "C (gcc) – Try It Online") -7 bytes from xnor's comment to another answer and 2 from ceilingcat [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 19 bytes ``` ʷ{;"tut-tut"=ip,}ᵗN ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FttOba-2ViopLdEFYiXbzAKd2odbp_stKU5KLoYqWXCLcTNcBReMhcpD52NVjksbNgMQMliNwiGF29gKiCKoUiAF0wg3ANWkCiRDQdqRrEKxFc0FGM6BcLD6AVkhNm8gBwYWj2IJMhQ_QyIPAA) A port of [my Curry answer](https://codegolf.stackexchange.com/a/251779/9288). See also [@DLosc's Brachylog answer](https://codegolf.stackexchange.com/a/251821/9288). ``` ʷ{;"tut-tut"=ip,}ᵗN ʷ{ } Loop until failure ; Split the input into two parts "tut-tut"= Check if the second part is "tut-tut" ip Take a proper prefix of the second part , Append it to the first part ᵗN Check if the result is empty ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~94~~ 86 bytes ``` d;b;f(char*s){for(b=~0;b&&s[3]|b+4;s-=b=d&b|d==1?0:~3)s+=d=strstr(s,"tut-tut")-s;b=b;} ``` [Try it online!](https://tio.run/##nVLNUoMwEL73KTKdaScpMFKpB43Rg@NTUA5NCMqotMPGkbGljy6G8FOg1IPMJmSz@337kxXOixBFEVJOIyxeN@kCyD7appizo0v5fA6@Fxy4taLgMM7COT@EjC0f3bujR8BiIQOVasFgT9WncvSaEgcoZ5zmRZwo9LGJE0zQfoL0ZyIgJUGBHyCG9i3IRs1xoJ5djCMuIkc5TqZxtku2P5iz2q3xLv8t@kQzIMy65IamG7SfwDCb89xqbbymnu9oXb0GjdU@1sheH3Jqnrl8d5ntpFAyrN55aaNL4v5b6mhim4Ayo6U3Kd5k6gf@qhqvdfZ8vc5un/S6KdPu6F6TrR53hMuU4ySUmYa5tD7eI4i/5TbCTTHkqr5YtDcUWZbxJoasmvPOrGu@at6NU0BbexkRtDXCijB29PoWqS1tC4fQXapdIjydAXIe0CxEM1gnujxlI7DbJgBjMiAVKp/kxY@I3jcvUDhfvw "C (gcc) – Try It Online") *Saved 8 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)* Inputs a pointer to a string. Returns `~3` if the input is constructed of overlapping or concatenated instances of the string `"tut-tut"` or `0` otherwise. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes I know it's not as short as some other answers, but here's my solution. ``` ^(tut(-tut))(\1|(ut)?\2)*$ ``` [Try it online!](https://tio.run/##K0otycxL/K@qkcD1P06jpLREQxdIaGpqxBjWaAAZ9jFGmloq//8DBUESXFAamY3Kw6IQuwZMrQhxLIZglcBlYAUXTBEXRDlUE7LeCrghXBVwY5HMR7EJzVIu7G5EKMF0JMKTGF7ACAZkvwAA "Retina 0.8.2 – Try It Online") ]
[Question] [ My mom really wants me to eat broccoli, but I hate it and never want to eat it. Mom wants to trick me so she cuts it into small pieces, puts it in a salad and mixes it. Help me find out if the salad contains broccoli! **Input:** Array of mixed letters of all the ingredients. For a single broccoli ingredient it could be: ``` [c,o,r,b,l,c,i,o] ``` **Output:** Boolean or other convienient output allowing to distinguish if a salad contains broccoli or not. **Rules:** * all possible ingredients are `onion`, `broccoli`, `celery` and `beans` * input array is always formed of mixing valid ingredients (meaning that it can be always decoded back to the original ingredients array) * input array cannot be decoded into more than one valid ingredient combination * each ingredient can occur 0 or more times in the salad **Sample test cases:** `true` stands for a salad with broccoli ``` [c,o,r,b,l,c,i,o] //true [o,b,n,o,i,i,e,l,n,a,o,r,n,s,b,o,c,c] //true [l,c,b,r,r,o,r,c,i,i,c,o,c,b,o,c,c,b,i,o,l,o,l,o] //true [] //false [o,n,i,o,n] //false [b,n,s,i,a,o,n,b,a,s,e,e,n,o,n] //false [b,r,o,c,c,o,l,i,e,y,e,r,l,a,e,e,n,s,y] //false [e,n,s,o,e,n,i,o,a,o,o,e,n,n,e,l,n,l,e,o,e,r,c,l,o,y,i,r,y,r,y,b,e,l,n,n,c,c,r,c,e,y,i,e] //false ``` **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!** [Answer] # [Python 2](https://docs.python.org/2/), ~~34~~ 32 bytes -2 bytes thanks to @dingledooper ``` lambda a:cmp(*map(a.count,'bs')) ``` [Try it online!](https://tio.run/##dVHLDoMgELz7Fd7QxvTQYxO/pO0BKKYkuhi0B7/eoh3iQlOTCexjZnZxXOaXo8vatfe1l4N6ylJe9TBWp0GOlTxr96a5EWoSdb2O3tJcdtVNaNEIF@ADVEAfsOXsnn/UxdHq0EKgWMCAtuUlk9viCRwHWZ1KRjcFimd0zSw0k0jlvrFFrk/OYAUv0W6fKA7rn82IyVA6pWLLWLYkwV2iZgD6L@Oz4eOw8R0XnB55mclOe08iy0uOtcZl4rS8Rtlv6xE7Zq/Zey7Q87jHU2U6xFaLGobxTRh9/QA "Python 2 – Try It Online") Returns `1` for true, `0` for false [Answer] # [J](http://jsoftware.com/), 14 bytes ``` [:=/1#.'cy'=/] ``` [Try it online!](https://tio.run/##ZY6xCgJBDER7vyJosQh6antwlWBlZSsWuyFiZMlArtqvPyNi4UkIITMvQ57Tskt3GnpKtKE99dHbjo6X82m69sPusOoStzTsbtN6IfxA@APdKTG8VFYk@pFRDKpSLcNtLGCeAZWLO5xVGfz2i6JGfbHDB5utMIXNtGKjZljJo4j9ux7ZqCpNvOYgxjYjQoJEbkYMi5erQJwrmnrzVkIxZmdpKnE6vQA "J – Try It Online") *Idea of invariant based on letter counts from mathjunkie's [clever answer](https://codegolf.stackexchange.com/a/204690/15469) -- be sure to upvote him.* * 0 for contains broccoli * 1 for not Tests if the number `c`s is equal to the number of `y`s. This will only be true when no broccoli is present. [Answer] # perl -ple, 14 bytes ``` $_=y-y---y-c-- ``` [Try it online!](https://tio.run/##DYsxCsBACAT7e0day5R5S8iJhSDu4aXx8zEWywwDuyTsrDruKymJekxUNQPMMB2MmMaKMeXxPeAKH@Ib0vag4WJuAgk2pEZGzi7OHCyp8mG9/dlFtn4 "Perl 5 – Try It Online") Prints 0 if no broccoli is present, something else if there is. [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), 26 bytes ``` @(b)b&&diff(sum(b'=='cl')) ``` [Try it online!](https://tio.run/##XY5BCsJADEX3nsKNTrvpDQpeZRIzEIj5kFFhTl8jgljJIuG95BPwvT5la@uyLNtlopnO56u2NvXHbaKyroWtzPPWpsIIMlaU@Xi6x0MOyUAOVTGvCO8E5l9rTBEIVmXwW5LCsn533nOr1j9xrvAdIe9a4VS7iP@7yEiYypCwmr6PnU8AycSKbJ5PmkCCDUNjxKAkzhwsQ@V7uL0A "Octave – Try It Online") Credit to @mathjunkie's answer for the idea. Interestingly comparing `c` and `l` counts also works because `celery` has one of each, but `broccoli` has a different number. MATLAB likes to expand `==` into 2D arrays if the inputs are vectors in differing orientations. However this doesn't work with empty arrays. Fortunately empty is false in MATLAB and non-empty with any non-zero elements is true, so we can simply use the input as a logical true-false to capture that case. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „bsS¢Ë ``` -1 byte by reversing the output: will output `0` if it contains broccoli and `1` if not. [Try it online](https://tio.run/##yy9OTMpM/f//UcO8pOLgQ4sOd///n5pXnJ@al5mfmA@k8lJz8nJS81OLknPyKzOLKosqk4AiecnJRcmplZmpAA) or [verify all test cases](https://tio.run/##Jc2xCcNQDATQVYxq7@AhUoYUX0KFQOhAHwK/S5UmTcgAKTJKvIkXcWSCioPHHUJvbLpfx/pcaNrur4mWfbu9uZ@@n/Wxz/uZBMkuBpoJHDBTj4aMzhApdOFMpJgJ5DA2eB3NEx2bMEQlR7eG4NZV4y9ZZbjp0PRW2kdpBbQ2DRVRv1yhKY5hOXJwSYik6DClyw8). **6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** alternative which outputs `1` if it contains broccoli and `0` if not: ``` AS¢üÊн ``` [Try it online](https://tio.run/##yy9OTMpM/f/fMfjQosN7Dndd2Pv/f2pecX5qXmZ@Yj6QykvNyctJzU8tSs7Jr8wsqiyqTAKK5CUnFyWnVmamAgA) or [verify all test cases](https://tio.run/##Jc3BCQJRDATQVpactwexBo/i4SfkEAgZyAfhN@DBk1iCdejFbcAabGTNIjkMPGYIemPT9TyW246m7@U@0W7dH96P5blcP691Xo8kSHYx0EzggJl6NGR0hkihC2cixUwgm7HB62ieaNuEISo5ujUEt64af8kqw02HprfSPkoroLVpqIj65QpNcQzLkYNLQiRFhymdfg). **Explanation:** ``` „bs # Push string "bs" S # Convert it to a character-list: ["b","s"] ¢ # Count each in the (implicit) input Ë # Check if the counts are the same for both letters (1 if truthy; 0 if falsey) # (after which it is output implicitly as result) A # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz" S # Convert it to a character-list: ["a","b","c",...,"z"] ¢ # Count each in the (implicit) input-list ü # For each overlapping pair of counts: Ê # Check that they are not equal to one another (1 if truthy; 0 if falsey) н # Pop and only leave the first check (for letters 'a' and 'b') # (after which it is output implicitly as result) ``` If the amount of `b` and `s`/`a` are the same, it means the input only contains `beans` and no `broccoli`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~19~~ 12 bytes ``` >/+/↑'cl'=⊂⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v/fTl9b/1HbRPXkHHXbR11Nj3rn/f@fVJSfnJyfkwkA "APL (Dyalog Classic) – Try It Online") Note that you have to add `⎕←` to the beginning for it to output. Originally created with **ngn/apl**. ``` >/+/↑'cl'=⊂⍞ ⍞ ⍝ get input 'cl'=⊂ ⍝ make two packed vectors: characters equal to c and l +/↑ ⍝ turn into two row matrix and add (to get number of 'c's and 'l's >/ ⍝ Are there more 'c's than 'l's? ``` returns broccoli: 1, no broccoli: 0 [Answer] # JavaScript (ES6), ~~33~~ 32 bytes *Saved 1 byte by not forcing a Boolean value, as suggested by @SteveBennett* Takes a string and returns *undefined* (falsy) for a broccoli-free salad (yummy!) or a string (truthy) otherwise (yuck!). ``` s=>s.split`b`[s.split`s`.length] ``` [Try it online!](https://tio.run/##fY/BTkNBCEX3foW71y58f1B/pDZ5A9IWQ7gNjDXz9c@p0USTsWEBuRxyL2/lWpJDL/XJ8Srrcbfm7jnnvJjWhZb9z5jLbOKnej6sDE@YzIbTZtp/aD0/UoAZpodp@/B7fdxMjCBjxbT9d3UHATlUxbwgPKm7DCBjikCwKoNvDCms1w39w04v/pUX7/Ve5FEOV/hAJ08tcCop4mPi20eahJVOZRtQXYZ0j4LevP9rAgk2NI0WjbrizMHSVPr5@gk "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` ›№θb№θs ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIwzm/FMgr1FFQSlLS1FFAcIuVNDU1rf//j87XSdLJ08nXyQTCVJ0cIDsRyCsC0sVAmXydZJ3k2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean; `-` for broccoli, nothing for none. Explanation: ``` №θb Number of `b`s in input › Exceeeds №θs Number of `s`s in input Implicitly print ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 32 bytes ``` s=>s.map(c=>++this[c],r=y=0)|r>y ``` [Try it online!](https://tio.run/##ZY9hbsMgDIX/9xT7CauX7AJkB0mjhTDSsVET4WwS0u6eGTdaK03IAfw@v0c@7Lcll8OyPtES3ny@JPz0ZZvNRqaj5mIX5Ux3PK7vgXo3QDbFPOuf3JXNJaQUfRPTWY2H3kGCDBNEcBAgDQ9tu@Yvf@gTN5HFwMuzjGAFRSBWEuPuBtfpicUsiJMhJ9CO8s7ubCP1N3jo63G2kSQRBcK73iR5QbKRTSzfPC/8x@U9qAbUFxeuzGe78wTljr92kig1s/pfb7j/beQ9iYeTZxfmMn9rTTuDklgJL7q/JYxN9ku0zqv21Kvm8UWfhvYM6hVIm25W1NASwzrCqLXefgE "JavaScript (SpiderMonkey) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` s=>s.map(c=>n+=~~{r:1,y:-1}[c],n=0)|n ``` [Try it online!](https://tio.run/##ZY/RTsMwDEXf@xXsLQGvZa@TUj6kq2hqsqkoc6qkIFXAfr04XsUmochN4nt8b/puP23COIzTlsKbW45mSaZO5dmOCk1NT@Zy@Yr7Hcz77e6nwRbIPOtvWjBQCt6VPpxUVzQIASL04AFhgNA@VNUUP1zRBG4SiwMvxzKBFZQgsRIYxxucp3sWoyAoQyjQivLO7mwj9TdYNPl4tD5JIglEd71e8gbJJjaxfHO86B8X16AckF88c0U@25VPMN/x104QJWdm/@uN1r/1vAfxQHn2zFzkb65@ZUgSM@FEd7eEroxu9Badqg6NKh9f9KGtTqBeIWlTbzZHlco0@mHqoNNaL78 "JavaScript (Node.js) – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 11 bytes **Solution:** ``` </+/"sb"=/: ``` [Try it online!](https://tio.run/##Jc1BCsNACAXQu7hpSynZp@1hRjEgET84K08/NRQXH55@PF841zr2z/bcaDJ9t30dtzsJkl0M9CZwwEw9BjImQ6TRhTORYiaQy9jgPb26KmGITo5pA8FjqsZfsm/hpqXpo3VWawe0OwMd0a9coSmOsqwsbgmRFC1Teqwf "K (oK) – Try It Online") **Explanation:** Shamelessly stolen "more s' than b's" logic from [mathjunkie](https://codegolf.stackexchange.com/a/204690/69200): ``` </+/"sb"=/: / the solution "sb"=/: / "sb" equal (=) each-right (/:) +/ / sum </ / s less than b? (aka no brocoli?) ``` [Answer] # Zsh, 22 characters ``` ((${#1//a}==${#1//b})) ``` Expects the ingredients as a single command line parameter. Sets the exit code to 1 for broccoli alert and 0 for no broccoli. (Just to keep the exit code semantics of 0 = Ok / non-0 = error. Using `<` for comparison would save 1 character but reverse the result's encoding.) Sample run: ``` manatwork@manatwork ~ % . ./broccoli-detector.zsh obnoiielnaornsbocc manatwork@manatwork ~ % echo $? 1 manatwork@manatwork ~ % . ./broccoli-detector.zsh broccolieyerlaeensy manatwork@manatwork ~ % echo $? 0 ``` [Try it online!](https://tio.run/##qyrO@P9fQ0OlWtlQXz@x1tYWwkqq1dT8//9/flJefmZmak5eYn5RXnFSfnIyAA "Zsh – Try It Online") / [Try all test cases online!](https://tio.run/##XZCxagMxDIbn3FOI5IKTIYRCu7SEDJ36DllsndIKjFSkW9ySZ7/qSEhp8SDpsz9@oy//mD6NZTxDWj8@OTzD2k@SIL3Ju9HAJKPH9KoyZhaHYoqoleGYuu6sBnx/Fy0kVCsVWcPRIspMVbKaeAkvYMVipobMqDizwlrjxNWsCOscXsQ5q5TsRHIlt1xqZDUH9RY0ilI4WaNIRFVSMqza2Jq1EkQQDakxpRcYtFs4jbDbwbL//fhy2mz679XDfp8vh8O1K5ftdlr8X80wr@aPCv2xG1Ro@gE "Zsh – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes ``` +`[^bs]|bs|sb 1`b ``` [Try it online!](https://tio.run/##PY5BCsQgDEX3vcfAwGQzp5hDSIcacSGUCDqbQu/u/PxKkWiS//JNy79icTyen228tvDVvp7az67L8t50jJCkShOVXZIUqesSKipDt@Bk9E0iGZMOpYJLoJxXdBu1RDpRnQxe@GGegQlaG5uGXGlYaG6AI6qMY7feppEb@CoHoiGPk@tygLuyyo57u99V2Vx/x1s5m7jOAa7h9tDJGH9yIlPP6x8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` +`[^bs]|bs|sb ``` Delete everything that's not a `b` or an `s`, plus any remaining `bs` or `sb` pairs that result from bean salad. ``` 1`b ``` Check whether there is any broccoli. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ċⱮ⁾abE ``` A monadic Link accepting a list of characters which yields `0` if the salad contains broccoli and `1` if not. **[Try it online!](https://tio.run/##y0rNyan8//9I96ON6x417ktMcv3//796al5xfmpeZn5iPpDKS83Jy0nNTy1KzsmvzCyqLKpMAorkJScXJadWZqaqAwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##Lc2xDYJBCAXg/l/kGtdwCmNxEAoM4SVcdaU2Fq5iTFzARie5RU7OGIpHPiCcxKzP@bmN52OcX5X2830dl/uch8IIMlaUbVdADlUxrwhvBOalxhSBYFUGLySFZa3Z78oVvhryphVOtYn4nyL3YSpdwmpy64szIXlWkeH50AQSbOgaPTqlOHOwdJWyHb8 "Jelly – Try It Online"). ### How? Tests whether the number of `'b'`s (in both 'broccoli' & 'beans') is equal to the number of `'a'`s (in only 'beans'). ``` ċⱮ⁾abE - Link: list Ɱ - map across... ⁾ab - ...what: list of characters = ['a', 'b'] ċ - ...applying: count E - all equal? ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 41 bytes ``` s->s.reduce(0,(a,c)->c<98?a-1:c<99?a+1:a) ``` [Try it online!](https://tio.run/##ZU@xTgMxDN37FValSnfQnugGLRSxIDEwlQ0xOG6uuKTxyc5VOiG@PeQKC0JRYvu952fngCdcHHYfmY@daIJDqZs@cWjaPlJiic3FevKPtKQejyNFAc3gGTnC5wSg611gAkuYSjgJ7@BYuGqblOP@9Q1Q91afpQAv8hTT4@@c25Jvz7YbaOEu22JjjfpdT766mlc4p3qxodub63tcLFclubnHy@UK67w@m7Wi1QkVkre0@jMGYDtY8sdG@tR0ZY/UVtOZrWBmszidnzvm0DbYdWF4sLJHNUINvaNaVdebq/pnxNdkvF85k6gLxJLFRWH2IaJoNCdEOZBTFSVmEhoRxxLKyRLLL7OLxijRoXkfx1qLRAL7wWvAgtmQyyO@qFFKiMU9ePFKQQbWQQdXkEik5Af23w "Java (JDK) – Try It Online") Uses a `chars()`-Stream as input, returns any strictly positive value if it contains brocoli. ## Credits * -5 bytes thanks to [Elgirhath](https://codegolf.stackexchange.com/users/94596/elgirhath) by comparing `b` to `a` instead of `b` to `s`, and by allowing any positive value instead of a strict boolean. [Answer] # [asm2bf](https://esolangs.org/wiki/Asm2bf), 73 bytes [Try it online!](https://tio.run/##3VPRasMwDPygm/cFQj8i/NAYBmGlgUC/P5NsxZHdhw72NqUQRz7rTqd62W/r4@tZvo8DDGFmEOlPV8mWlLLmRBfQd8okNW3AZEDdFt0ylFBiSVkhF9rS@qJ6Ar2gVICdFfv8YK44FUDQsJNQMbZ2hp7lFl7V42QMgbBdsSq8ZfMIFIoxVkkZgcEqdUDnl4nQ9I5FBgJzqLeASUPt4xThDBKqp0G7eQBWvxl0yqkuajTL3DO3snlpLeR/biLorybicgRexS9H@0M2p@WqJVfzv@oudtCy@c0tCbfQ2TDNCfwqdbRmHmy4wHgZZWJ7usqpG@lzPVmGfuFjIvfo822H0VP9yMdxL8u@b3tZ17KVZStlWbe7Pj8 "brainfuck – Try It Online") Takes input on stdin as a string; outputs either `ASCII(0x00)` or `ASCII(0x01)`. ``` @l in r1 ceqr1,.b cadr2,1 ceqr1,.s cadr3,1 jnzr1,1 gt r2,r3 outr2 ``` Commented code: ``` ; Essentially, our game plan is to compare amount of `b' and `s' occurences. ; Start a new label @loop ; Read a character from stdin, put it in r1. in r1 ; If r1 = 'b' (note the way of expressing a character constant), set ; the condition flag. ceq r1,.b ; If the condition flag is set, add 1 to r2 cadd r2,1 ; If r1 = 's', set the condition flag. Otherwise, clear it. ceq r1,.s ; If the condition flag is set, add 1 to r3 cadd r3,1 ; If r1 is bigger than zero, we didn't hit eof yet, so continue reading. ; Note: The golfed version is based on a certain property beyond explaining. ; It's related to the way how labels work under the hood. jnz r1,%l ; The loop finished. ; Compare r2 and r3 (the accumulators). gt r2,r3 ; Display the result out r2 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as a string with reversed output. ``` èÕ¶Uèc ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=6NW2Vehj&footer=IVU&input=WyJjb3JibGNpbyIsIm9ibm9paWVsbmFvcm5zYm9jYyIsImxjYnJyb3JjaWljb2Nib2NjYmlvbG9sbyIsICIiLCJvbmlvbiIsImJuc2lhb25iYXNlZW5vbiIsImJyb2Njb2xpZXllcmxhZWVuc3kiLCJlbnNvZW5pb2Fvb2VubmVsbmxlb2VyY2xveWlyeXJ5YmVsbm5jY3JjZXlpZSJdLW1S) - includes all test cases, footer negates the output for easier testing [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 39 bytes ``` i=>i.Count(x=>x==98)>i.Count(x=>x=='s') ``` [Try it online!](https://tio.run/##bVDNSsQwED7bpxh62Qa6ix4EpbaXBU/ePYiHZJjVgTADk65uWfbiM/iEvkhNEIWq5DDJ95fhw7TGxPPtXvAmjcby1EJQjQPsoJ@5H3iz1b2MzaEfDn1/feV@Iau0cnNXvXiDkdKYoAehV3h4hGN11tSoFiKy1i2MtifXFlCDKDNF8WqSgiIu6IjBTA2ZUbGwgTXmsxDlx87H9J0orLKEgiT2KsEnIvlDWo7VyDSRRZ8FaVoKMqKUQ73mIXnVSEqGUSe2yaaQEUE0pInpx1mdumqr2Rlpc2880h0LNTXkLgE@3t9yGUY41q6rdmrk8RmaUlzDLaADlq8KXZWr@yfneN6uL08lCI4X5Vo@btgVc1ed5k8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~57~~ \$\cdots\$ ~~53~~ 52 bytes Saved 3 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)!!! Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` a;f(char*s){for(a=0;*s;++s)a+=*s-99?*s>120:-1;a=!a;} ``` [Try it online!](https://tio.run/##dVHBTsMwDL3vK0KkSU27ahu3ETo@hO2QmBQshRg55VCmfntxu3EAFedgx372k5@hfgUYR2fbAt4cl9lcWuLCNTtbZltV2biqKXN9ODyV@bi/3z3Ue@uaO2eH8d1hKoy6rJTY3K26kLv8fFaNumgg9hGQ9EZty44/Q7mdkZNp8okQQ0yOOGVPAIuwCJ6ZGBCBYEJ5pChvETwnWxfzb6aElJZLPmV0lLzLIaR/QSy0FDH0gaMTYO6XgVKhIGSOxCVZLQYKDJF65J57L5kEwBB6DPrPgMHObpIeU6dQBNxZcY8q41egtpiFNdvbbxbbyHnwR/7JPlh620Kf9DqftKqPav1ykq2uR8Hz5jZGQmOuhMNqGL8B "C (gcc) – Try It Online") Takes a string as input and returns a \$1\$ for edible and a \$0\$ for *grossing me out*! [Answer] # [PHP](https://php.net/), ~~44~~ 42 bytes -2 bytes thanks to @Elgirhath ``` $b=count_chars($a,1);echo+($b[98]>$b[97]); ``` [Try it online!](https://tio.run/##bY/dSsRADEbvfYqyFLpFEbxSqasPootMQpYGhnwls3sxiM9eUwQVmZmLwMnJ3zIv69PLMi/d6WJ8Vlh32vdp/Fh7OjAudn7nOXkJdnM3TsIzrvc9vT4@HJ@3cH8cp/XzauNRODCcMiuGsbvtdm@2m35SIIOqZEtwKwTmhpSZ3OGsyuDNIUWO/0f9dofD9oZ/NDq0Jluc1eBkRROMUhGxtuGxArJKFc8prFIbVmBIzEiIYHFhFohzRlWvXimIMTtLVfktX78A "PHP – Try It Online") [Answer] ## Javascript, 46 characters Shortening Yaraslav's answer: ``` s=>(q=z=>s.filter(e=>e==z).length)('b')>q('s') ``` ## Javascript, 62 characters ``` x=>([,a,b]=/(a*)(b*)/.exec(x.sort().join``),b.length>a.length) ``` Maybe I missed something? Just counts if there are more `b` than `a`. [Answer] # Google Sheets, ~~34~~ 33 bytes *Saved 1 byte thanks to Steve Bennett* ``` =CountIf(A:A,"b")>CountIf(A:A,"s" ``` Input is in column `A`. When you exit the cell, Sheets will automatically add the trailing parentheses. There's nothing really clever about this solution besides implementing the concept from others. [![enter image description here](https://i.stack.imgur.com/Sau7D.png)](https://i.stack.imgur.com/Sau7D.png) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 62 bytes ``` s=>s.filter(e=>e=='b').map(Date)>s.filter(e=>e=='s').map(Date) ``` [Try it online!](https://tio.run/##jZAxTgQxDEX7PQVdkoK5AMpWXCQxHjAy/iMngHL6IUgUi1Y7IBeW/J/tb7@Wj9LIZev3hife17y3fG7LKtrZI@cz5xxqSMtb2eJj6Zyu1Hap7gRrUF4UzzF8Sn@5qw4iqIR0uhTXGAhelQRhaZtKjyGkdBP6F4xqEGG1ArdW5@JDXKm6w0mEQN90FeiM203p4XR1Id77wZHHfk1gh0S1JgVWS2O2v9gfEzzYtUy@jUN@AuDpoGAmm19TBjsphvjwUWfFiJx4CP8atH8B "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 56 bytes ``` s=>s.filter(e=>e=='b').length>s.filter(e=>e=='s').length ``` [Try it online!](https://tio.run/##jZBBbgMxCEX3OUV3Hi86F6icu9iUSagQP8JuK59@6kpVlCqKW7FA4j/gw1v@yJVcLu3Z8Mr7lvaajnXdRBv7wunIKYUS4qpsp3a@k@pV2glWobwqTkv4lHZ@Kg4iqIR4uBW3JRC8KAnCWi8qbQkhxofQv2AUgwirZbjVMhZPcaXiDicRAn3TRaAjHjfFl8PdhXhvkyPnfk1gU6JYlQwruTLbX@yPCe7smgdf@5QfAHg4yBjJxteUwU6KLt69l1ExIifuwr8G7V8 "JavaScript (Node.js) – Try It Online") ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/18107/64722) # French License Plates [French license plates](https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_France) come in a sequential order, following a specific pattern of numbers and letters : `AB-012-CD` ## Challenge Write a program or function that, for a given number, outputs the corresponding [french license plate](https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_France) number. Your program should not handle any special case as specified in the linked page. It should be able to generate the full `26*26*1000*26*26 => 456 976 000` possible plates, or as far as your language can support. The numbering system goes as follows: * AA-000-AA to AA-999-AA (numbers evolve first); * AA-000-AB to AA-999-AZ (then the last letter on the right); * AA-000-BA to AA-999-ZZ (then the first letter on the right); * AB-000-AA to AZ-999-ZZ (then the last letter on the left); * BA-000-AA to ZZ-999-ZZ (then the first letter on the left). ### Input * The plate number's index as an integer ### Output * The corresponding french license plate number ### Additional information * Letters have to be uppercase * You can use both 0-based and 1-based indexing to generate the plates (meaning AA-000-AA can correspond to `0`or `1`, assuming all the other test cases use the same indexing. This is [code-golf](https://codegolf.stackexchange.com/tags/code-golf/info), shortest answer in every language wins! ## Test cases (0-based indexing) ``` 0 -> AA-000-AA 1 -> AA-001-AA 999 -> AA-999-AA 1000 -> AA-000-AB 675 999 -> AA-999-ZZ 676 000 -> AB-000-AA 456 975 999 -> ZZ-999-ZZ ``` [Answer] # Pure [Bash](https://www.gnu.org/software/bash/) (no external utils), 64 * 2 bytes saved thanks to @NahuelFouilleul ``` x={A..Z} eval f=($x$x-%03d-$x$x) printf ${f[$1/1000]} $[$1%1000] ``` [Try it online!](https://tio.run/##PY5NC4JAGITv7694kRWVUFdKRVKhQ127Fx22/WAF01ApQfztpkXenpmBmbmzVk@cdZijasqCe63GNEXreD5ZU58NB8@7jCBfrESV2aQnvWvSrXAXcuDZFFWnkAzqSgI/oJTeRiQzm1@e5hbg@lELZJt@HYC3LkqJjWQCO9l2nLVyj6IGyXWNBvl76OZIbM9fj62JY4CoKzlRCCBJEljWIIrDhaM4WtQujJKf8QE "Bash – Try It Online") - takes about 10s to run over the 7 testcases. * Line #1 is a simple assignment of a string to a variable * Line #2 is a brace expansion to build an array of printf format strings, one for all 456,976 possible letter combinations, with the digits not yet specified. The `eval` is required to ensure variable expansion (of x) occurs before brace expansion. * Line #3 indexes the array to get the appropriate format string and takes the digits portion as its parameter. [Answer] # [Perl 5](https://www.perl.org/) (-ap), 47 bytes ``` $_=AAAA000;$_++while$F[0]--;s/(..)(\d+)/-$2-$1/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tYRCAwMDKxV4rW1yzMyc1JV3KINYnV1rYv1NfT0NDViUrQ19XVVjHRVDPX//zczN7W0tPyXX1CSmZ9X/F83sQAA "Perl 5 – Try It Online") --- # [PHP](https://php.net/), 74 bytes ``` for($a=AAAA000;$argn--;$a++);echo preg_replace('/(..)(\d+)/','-$2-$1',$a); ``` [Try it online!](https://tio.run/##HYzRCsIgGIXvfYoYgopz0yCHWEQ3PcUgZLktCP2xPf/sr3NxznfgcGCFer4C@pwLp@FyQ2mtPQ1lSUphSil8nNZ8gBKXR4nwDlPkrOddJ/j4lKJnLVP0qKhhLQ3C1/@6GVPjqyaGOOeIwU9ih9OP7WCx7Rm2V06fqu5f "PHP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 79 78 77 bytes ``` lambda n:f"%c%c-{n%1000:03}-%c%c"%(*(65+n//1000//26**i%26for i in[3,2,1,0]),) ``` [Try it online!](https://tio.run/##XY7BaoNAEIbveYphYUHNiqvWLQoeNodCIYdAbjY9GN2lC2YjyQZSSp7drLEa29vM9883M@23@TrquJP5rmvKw74uQWcS4QpX/o/GIaU0o/HN7wHCjuewZKmDoOdBEDHPUzhi8ngCBUp/xCQiIaGfLnG7Wkgw4mwcpduLISCuraiMqN1sAVBW5lI2kIMcYtey9qS0cYaEAMrR07Hthm@3CJSc1HxKQTRnAeiNv69Rv2jxOEutxLlvH/U5t/wBwxGGM5im6YBtMZ@16mzHauTsNfljFMUzYb/O6t/dl4Slo1YUk9bdAQ "Python 3 – Try It Online") I somehow never realised that the `f"string"` format shortcut exists until seeing Black Owl Kai's answer. [Answer] ## Ruby, ~~61~~ ~~59~~ 55 bytes ``` ->n{s='AA-AA000-';eval's.succ!;'*n;s[2]+=s[5,4];s[0,9]} ``` Also 55 bytes: ``` ->n{s='AA-AA000-';eval's.succ!;'*n;s[2]+=s.slice!5,4;s} ``` [Try it online!](https://tio.run/##KypNqvyfpmD7X9cur7rYVt3RUdfR0cDAQFfdOrUsMUe9WK@4NDlZ0VpdK8@6ONooVtu2ONpUxyQWyDHQsYyt/V@gAGQoGOooWFpaAmmgVh0FM3NTMM/M3AzIj9XLTSyorqmoUUiLrgDqAAA) This initializes a counter to `AA-AA000-`, increments it `n` times (by multiplying a string of the code that does so by n and `eval`ing), and then moves the last 4 characters after the 3nd. [Answer] ## Haskell, ~~85~~ ~~81~~ ~~79~~ 77 bytes ``` ([h++'-':n++'-':t|h<-q"AZ",t<-q"AZ",n<-q"099"]!!) q g=mapM(\_->[g!!0..g!!1])g ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyM6Q1tbXVfdKg9CldRk2OgWKjlGKemUwBh5IIaBpaVSrKKiJlehQrptbmKBr0ZMvK5ddLqiooGeHpA0jNVM/5@bmJmnYKuQks@loKBQUJSZV6KgopCmYIDKNTM3tbS0RBczMzAw@P8vOS0nMb34v25yQQEA "Haskell – Try It Online") [Answer] # [PHP](https://php.net/), ~~96~~ ~~84~~ 79 bytes -5 byte thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel)'s great comments. ``` for($s=AAAA;$x++^$argn/1e3;)$s++;printf('%.2s-%03u-'.$s[2].$s[3],$s,$argn%1e3); ``` [Try it online!](https://tio.run/##HY/dasMwDIXv/RSiODQl/82aErIxdtHdDkLvtq5kidIYMttYDu3TL3MihDj64BwhPej5@VUPmrEkgfMgCFwT2hBIyBZhVJZA9XBvjBTyRtDIDqSyokWnDYI2QlrsVm4HBIM0jRZaNY0d/GCrfhFoVPeYoTHKXA1qZayL8k/XU11/1Ltq7pXxOb28uar4Iwi@eWNuMskwr3acgqBaj/T@1ov3FHlpPkXbmNPn/rLM/BJyCleL5ywuD9tBweZLbio2SfeMzx@OpixjZVmyLE1TVhwPiy6OxbI9HYpyBX9KW6EkzdH7Pw "PHP – Try It Online") I take advantage of the fact that you can increment letters in PHP! So `AAAA++` would become `AAAB` and `AAAZ++` would become `AABA`. I calculate how many times the letters have to be incremented by getting integer part of `input/1000`. Then increment the four characters length that many times and its first two and last two characters will automatically become the left and right side of the plate. For example for input of `675999` number of letter increments is `(int)(675999 / 1000) = 675`, so `AAAA` will become `AAZZ`. Finally, the middle number is calculated by `input%1000` and everything is printed in the specified format with help of [printf](https://www.php.net/manual/en/function.printf.php). `%.2s` prints first two characters of the string, `%03u` pads the number in the left with 3 zeros. [Answer] # C, 88 86 bytes ``` #define d(b)a/b/1000%26+65 f(a){printf("%c%c-%03d-%c%c",d(17576),d(676),a%1000,d(26),d(1));} ``` Pretty simple, it uses division and modulus to extract the fields, adds 'A' for the letters to map them to ASCII characters, and printf formatting for the numbers. [Try it online!](https://tio.run/##dY7NCgIhEIDP7VOIITiUrG6piK/SxdU1PCQR3ZZ9dtMo6JBzmZ@Pb2Y8u3pfyj4sMeUFBTqDG@dRcM7JpA5KDpE6WO@PlJ@RYuKJZ4SfAmsVPgYqtNQKaqFacqSZtZveMwFgt1JVdHMpU0DrsIsUfYKDRd/Fl4zB/kLRh8aYLmznO1Bp2Tfr9x3zLJX5b27lBQ "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~22~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Au2ããs₄‰`UèX₄+¦'-.øý ``` -2 bytes (and increased the performance by not generating the entire list) thanks to *@Grimy*. 0-based indexing. [Try it online](https://tio.run/##yy9OTMpM/f/fsdTo8OLDi4sfNbU8atiQEHp4RQSQqX1ombqu3uEdh/f@/29uYmFsYGIKAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WKvpPCobZKCkv1/x1Kjw4sPLy5@1NTyqGFDQujhFRFApvahZeq6eod3HN77X@d/tIGOoY6lpaWOoYEBkGlkbGKqYwgGOmbmpiAJM3MzkJS5iYWxAVDSxNTMEiwRCwA). **Explanation:** ``` Au # Push the lowercase alphabet, and uppercase it 2ã # Create all possible pairs by taking the cartesian product with itself: # ["AA","AB","AC",...,"ZY","ZZ"] ã # Get the cartesian product of this list with itself: # [["AA","AA"],["AA","AB"],...,["ZZ","ZZ"]] s # Swap to push the (implicit) input ₄‰ # Take the divmod-1000 of it # i.e. 7483045 becomes [7483,45] ` # Push these values separated to the stack U # Pop and store the remainder part in variable `X` è # Index the integer part into the list of letter-pairs we created earlier # i.e. 7483 will result in ["AL","BV"] X # Push the remainder part from variable `X` again ₄+ # Add 1000 to it ¦ # And remove the leading 1 (so now the number is padded with leading 0s) # i.e. 45 becomes 1045 and then "045" '-.ø '# Surround this with "-" (i.e. "045" becomes "-045-") ý # Join the two pairs of letters by this # i.e. ["AL","BV"] and "-045-" becomes "AL-045-BV" # (after which the top of the stack is output implicitly as result) ``` The last part (`s₄‰`UèX₄+¦'-.øý`) could be `I₄÷èI₄+3.£.ý'-ý` for an equal-bytes alternative: [Try it online](https://tio.run/##yy9OTMpM/f/fsdTo8OLDiz0fNbUc3n54BYjWNtY7tFjv8F513cN7//83N7EwNjAxBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X/HUqPDiw8vrnzU1HJ4@@EVIFrbWO/QYr3De9V1D@/9r/M/2kDHUMfS0lLH0MAAyDQyNjHVMQQDHTNzU5CEmbkZSMrcxMLYAChpYmpmCZaIBQA). ``` I₄÷ # Push the input, integer-divided by 1000 è # Use it to index into the letter-pairs we created earlier # i.e. 7483045 becomes 7483 and then ["AL","BV"] I₄+ # Push the input again, and add 1000 3.£ # Only leave the last three digits # i.e. 7483045 becomes 7484045 and then "045" .ý # Intersperse the pair with this # i.e. ["AL","BV"] and "045" becomes ["AL","045","BV"] '-ý '# And join this list by "-" # i.e. ["AL","045","BV"] becomes "AL-045-BV" # (after which the top of the stack is output implicitly as result) ``` [Answer] # [J](http://jsoftware.com/), ~~56~~ ~~49~~ 46 bytes ``` 226950 A.'--',7$_3|.4,@u:65 48+/(4 3#26 10)#:] ``` [Try it online!](https://tio.run/##VY6xCsIwFEX3fsXFCrHYxLRNUhMQTAUn6eAYEAexiIuTm/8eo0RihjfcczmXd/czRiZsDAhqcJhwlGF3POx92yotOSwjlJK6n5@7FxP19mmUhFgvVwuBrmwVGl6V5uSrorhebg9MUL3UWsdIrKWcc2otATWh5f@8SbxJPNiJf6bypeFnhJRLzsUqvhDLIf9A9SqZzuWmkEp/ZYwDg38D "J – Try It Online") *-3 bytes thanks to FrownyFrog* The whole thing is nothing but 7 nested trains -- if that ain't fun, what is? ``` ┌─ 226950 ├─ A. │ ┌─ '--' ──┤ ├─ , │ │ ┌─ 7 └────────┤ ├─ $ │ │ ┌─ _3 └──────┤ ├─ |. │ │ ┌─ 4 └───┤ │ ┌─ , │ ├─ @ ─┴─ u: └────┤ │ ┌─ 65 48 │ ├─ / ───── + └─────┤ │ ┌─ '4 3#26 10' └───────┼─ #: └─ ] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 82 bytes ``` n=>'32-654-10'.replace(/\d/g,x=>Buffer([x&4?n/10**(x-4)%10+48:n/1e3/26**x%26+65])) ``` [Try it online!](https://tio.run/##dc9BDoIwEAXQvadgg7TF0hbaKiZg4BioCwIt0RAgoIbbIwuiqDiryeTl/8w1faRd1l6aG67qXA06GKogtDwXS8Exo5bTqqZMMwXIKSfFpg/C@K61asGxX/NDRRhFCPSYQ5NRm@/240V5xJUI9aYrbSnOEA5ZXXV1qZyyLoAGxjQUQoMQI4owpRRH0WqZsRlj/5jv@y827n8YG4s@S@NfJrfiOy1Jlph8p8XLL3Ah/VlakkxpwxM "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->n{[*?A*4..?Z*4][n/1e3][/../]+"-%03d-"%(n%1e3)+$'} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlrL3lHLRE/PPkrLJDY6T98w1Tg2Wl9PTz9WW0lX1cA4RVdJVSNPFSisqa2iXvu/QCHaQEfBUEfB0tISSBsYAHlm5qZgnpm5GZhvYmpmCRaK1ctNLKiuqahRSIuuiK39DwA "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 101 bytes ``` b=0:3;a=scan()%/%c(10^b,1e3*26^b)%%rep(c(10,26),e=4);intToUtf8(c(a[8:7],-20,a[3:1]-17,-20,a[6:5])+65) ``` [Try it online!](https://tio.run/##LcjdCoMgFADgpxE860T@5DEN32JdhYGGQTdtVO/vNtjl95215iC8HlO41nRwYB1buRRLRln0Q9GSgbGzvPlvURFgCT2M@3E/X9O9Dd9P8@BtxFYJTLP2MrbS/kXeRGjIQCVrnHP1Aw "R – Try It Online") Just does the needed arithmetic computations. I saved 5 bytes by including in the vector `a` a useless value at `a[4]`, allowing me to reuse the helper vector `b`. Consider for example the second character (the `B` in `AB-012-CD`). That character changes every \$26\times26\times1000=676\,000\$ plates, so the value of that character for input `n` is the `n %/% 676000 %% 26`th letter of the alphabet, where `%/%` is integer division and `%%` is modulus in R. The other characters are computed similarly. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØAṗ2,`ØDṗ3¤ṭŒp⁸ị2œ?j”- ``` A monadic Link accepting an integer (1-indexed) which yields a list of characters... Crazy-slow since it builds all the plates first! **[Try it online!](https://tio.run/##ATUAyv9qZWxsef//w5hB4bmXMixgw5hE4bmXM8Kk4bmtxZJw4oG44buLMsWTP2rigJ0t////MTAwMA "Jelly – Try It Online")** (wont complete) Or try [a reduced alphabet version](https://tio.run/##y0rNyan8//9RwxxHJ@dHDXMf7pxupJNweIYLkGF8aMnDnWuPTip41Ljj4e5uo6OT7bOASnT///9vaWBgCAA "Jelly – Try It Online") (only "ABC" for the letters). --- For code which completes in a timely manner here's a 32 byte full-program (0-indexed) which creates the single plate instead using modular arithmetic and numeric base decompression: ``` dȷ+“©L§“£ż’µḢṃØAṙ1¤ḊŒHW€jDḊ€$j”- ``` **[Try this one!](https://tio.run/##y0rNyan8/z/lxHbtRw1zDq30ObQcRC8@uudRw8xDWx/uWPRwZ/PhGY4Pd840PLTk4Y6uo5M8wh81rclyAbKBtErWo4a5uv///zczNzMwMAAA "Jelly – Try It Online")** [Answer] # APL+WIN, 61 bytes Prompts for integer: ``` m←⎕av[4↑66+n←((4⍴26),1E3)⊤⎕]⋄(2↑m),'-',(¯3↑'00',⍕4↓n),'-',2↓m ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/7nAplAocSyaJNHbRPNzLTzgAIaGiaPercYmWnqGLoaaz7qWgJUEfuou0XDCKgmV1NHXVddR@PQemMgT93AQF3nUe9UoO7JeRAZoKLJuf@Bpv9P4zLgSuMyBGJLS0sQy8AAJGBmbgrhm5mbQURMTM0swYIA "APL (Dyalog Classic) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` Nθ¹✂I⁺θφ±³≔⪪⍘⁺X²⁶¦⁵÷θφα²η¹⊟ηM⁹←⊟η ``` [Try it online!](https://tio.run/##bY3NCsIwEITvPkWOG6gHU7T@nPy5FLQE@gSxbttATNpmWx8/RoRelGFgYPebqVo1VE6ZEHLbjVSMzzsO0PPDQg7aEqzmVBpdIZyVJ5Bm9NAnrOY8YQU2ihBSzuPr0XvdWCg7owlOymNJEW6@hHSv2C02CVtHLrd00ZN@4NykokV0@2ddug7az8LNTQi7hO2vWNPPOQSRpduoTITlZN4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the number. ``` ¹ ``` Print a `-`. ``` ✂I⁺θφ±³ ``` Add 1000 to the number, then cast the result to string, and print the last three digits. ``` ≔⪪⍘⁺X²⁶¦⁵÷θφα²η ``` Divide the number by 1000, then add 26⁵, so the conversion to custom base using the uppercase alphabet results in a string of length 6, which is then split into pairs of letters. ``` ¹ ``` Print a `-`. ``` ⊟η ``` Print the last pair of letters. ``` M⁹← ``` Move to the beginning of the number plate. ``` ⊟η ``` Print the rest of the desired letters. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 42 bytes ``` {S/(..)(\d+)/-$1-$0/}o{('AAAA000'..*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OlhfQ09PUyMmRVtTX1fFUFfFQL82v1pD3REIDAwM1PX0tDSjVeJja/9bcxUnViqkaajEayqk5RcpGOgoGOooWFpaAmmgSh0FM3NTMM/M3AzIV1DWUTAxNbMEC/4HAA "Perl 6 – Try It Online") Port of Grimy's Perl 5 solution. Slow for large input values. [Answer] # Excel, ~~183~~ ~~167~~ ~~155~~ 147 bytes -16 bytes thanks to @Neil. (6 by using `E3`) -12 bytes thanks to @Keeta. (`TRUNC` instead of `QUOTIENT`) -8 bytes thanks to @Jonathan Larouche (`INT` instead of `TRUNC`) ``` =CHAR(65+INT(A1/17576E3))&CHAR(65+MOD(INT(A1/676E3),26))&"-"&TEXT(MOD(A1,1E3),"000")&"-"&CHAR(65+MOD(INT(A1/26E3),26))&CHAR(65+MOD(INT(A1/1E3),26)) ``` Concatenates 5 parts: ``` CHAR(65+INT(A1/17576E3)) CHAR(65+MOD(INT(A1/676E3),26)) TEXT(MOD(A1,1E3),"000") CHAR(65+MOD(INT(A1/26E3),26)) CHAR(65+MOD(INT(A1/1E3),26)) ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 107 bytes ``` import StdEnv A=['A'..'Z'] N=['0'..'9'] $n=[[a,b,'-',x,y,z,'-',c,d]\\a<-A,b<-A,c<-A,d<-A,x<-N,y<-N,z<-N]!!n ``` [Try it online!](https://tio.run/##Hc2xCoMwFIXh3aeIIGS5kS5tCegQaIdCcXFrdLgmtghJLNUW9eGbJl0@zj8dZXp03o76bXpicXB@sM/xNZN61mf3SUQpqaB5Tm@0TaoQuxg8ROZKKRE6oIzCAits/6VAt02DBRPQRVRER5aCVbBGtkCbps7XM4arkmTkcNxzzv1X3Q0@Js8uV39aHdpBTT8 "Clean – Try It Online") Defines `$ :: Int -> [Char]` giving the n-th zero-indexed licence plate. [Answer] # [Japt](https://github.com/ETHproductions/japt), 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Obscenely slow! Seriously, don't even try to run it! Tip of the hat to [Kevin](https://codegolf.stackexchange.com/a/193459/58974) for making me realise where I was going wrong when fighting to get this working last night. ``` ;gBï ï ïq#d0o ùT3 û-5 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O2dC7yDvIO9xNfIg%2bVQzIPstNQ&input=OA) - limits the number range to `000-005`. ``` ;gBï ï ïq#d0o ùT3 û-5 :Implicit input of integer g :Index into ; B : Uppercase alphabet ï : Cartesian product with itself ï : Cartesian product of the result with itself ï : Cartesian product of that with #d0 : 1000 o : Range [0,1000) ùT3 : Left pad each with 0 to length 3 û-5 : Centre pad each with "-" to length 5 q : Join the first element (the 2 pairs of letters) with the second (the padded digit string) ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 94 bytes ``` : x /mod 65 + emit ; : f dup 1000 / 17576 x 676 x ." -"swap 0 <# # # # #> type ." -"26 x 1 x ; ``` [Try it online!](https://tio.run/##LU1LDsIgFNxzigkuDS0YgVBM72JsURdNCWLU0@OjNC/zfjOZCWvKD3EPdZQy4It@WScYjSPm5ZnhMSBgekcoKSV6KKutIZ3Zesch@OtzjZC4HLDXiPyLcyNPVaYInuzj5uTQpUpCjODkfkvwTCIyRXDO1a2GRWasbjeltc9ZG7c/yx8 "Forth (gforth) – Try It Online") 0-indexed. Input is taken from top of stack ### Code explanation ``` \ extract out some common logic : x \ start a new word definition /mod \ divide first argument by second and get both quotient and remainder 65 + \ add 65 (ascii A) to quotient emit \ output ; \ end word definition : f \ start a new word definition dup 100 / \ duplicate input and divide by 1000 17576 x \ divide by 26^3 and output ascii char 676 x \ divide by 26^2 and output ascii char ." -" \ output "-" swap 0 \ grab original number and convert to double-cell number <# # # # #> \ convert last 3 chars of number to a string type ." -" \ output string followed by "-" 26 x \ divide result of last mod by 26 and output ascii char 1 x \ output ascii char for remaining amount ; \ end word definition ``` [Answer] # [q](https://code.kx.com/v2/ref), 78 bytes ``` {sv["-","0"^-4$($:[x mod 1000]),"-"]2 2#(|).Q.A mod[x div 1000*26 xexp(!)4]26} ``` --- ``` x div 1000*26 xexp(!)4 / input (floor) divided by 1000*26 ^ 0 1 2 3 mod[ ]26 / mod 26 .Q.a / alphabet uppercase, indexed into by preceeding lines, for x=1000, we'd get "BAAA" 2 2#(|) / reverse and cut into 2x2 matrix ("AA";"AB") ($:[x mod 1000]),"-" / string cast x mod 1000 and append "-" -4$ / left pad to length 4, " 0-" "-","0"^ / fill nulls (" ") with "0" and prepend "-" sv[ x ]y / join elems of y by x ``` [Answer] # T-SQL, 135 bytes ``` select concat(CHAR(65+(@i/17576000)),CHAR(65+(@i/676000)%26),'-',right(1e3+@i%1000,3),'-',CHAR(65+(@i/26000)%26),CHAR(65+(@i/1000)%26)) ``` [Answer] # [Julia 1.0](http://julialang.org/), 86 bytes ``` i->(join('A'.+digits(i÷1000,base=26,pad=4))string(i%1000,pad=3)*'-')[[4;3;8;5:8;2;1]] ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/U9dOIys/M09D3VFdTzslMz2zpFgj8/B2QwMDA52kxOJUWyMznYLEFFsTTc3ikqLMvHSNTFWwJEjQWFNLXVddMzraxNrY2sLa1MrC2sjaMDb2v0NxRn65QpqGgSYXjGmIYFpaWiKJAw1D8MzMTeNRpM3MzeJRVJiYmsVbQlX9BwA "Julia 1.0 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 88 bytes ``` lambda n:g(n/676000)+'-%03d-'%(n%1000)+g(n/1000) g=lambda n:chr(65+n/26%26)+chr(65+n%26) ``` [Try it online!](https://tio.run/##PY3NDoIwEITvPMVempawhIJ2SUnqi6gHlPCT4EIaLj59hRqdy843m91Z39u4cBV6dwtz@3p0LXAzKC6oJq11mslc6FOXS6FYlDE5ttElg/ufPEevyGRcVCQqSrMfHxD6xQPDxHDVCCWCtXaf@wsEqk2kbx3C2ZCN0b1JYNfqJ96AUbqLxF5xGj4 "Python 2 – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~130~~ 127 bytes ``` func[n][g: func[a b c][t: copy""loop a[insert t b +(n % c)n: n / c]t]a: g 3 #"0"10 s: g 4 #"A"26 rejoin[s/1 s/2"-"a"-"s/3 s/4]] ``` [Try it online!](https://tio.run/##VYrLCsIwFAX3/YpDRKqIJK1tSrPzF9yGLGr6oCJJSeLCr69R0eriwsw947p2PnUtpEp6Mfc3o6VRchB4YYMztJJBQNvpTsjV2gmNHI3vXECI625jsIbeGgEDGuOgGoEBB6wIIxlL/NOKaEeSc7juYkcjPc3gaU72pInn6SFaodQ8udEE9GDJh7Iv1XW9fFPGloZXZfq78or/7UXJ0/rdzA8 "Red – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 89 bytes ``` lambda n:h(n//676)+f"-{n%1000:03}-"+h(n) h=lambda x:'%c%c'%(x//26000%26+65,x//1000%26+65) ``` [Try it online!](https://tio.run/##PY5BCoMwEEX3nmIIBBOMJGqNJGBP0o21BAU7iriwiGdPBymdzefNPPizfLZhxiqG9hGn7v18dYB@EKi1bazMAssP5IUxxpvqzFlGJ5kM7U/dfcp73qdc7FqXljRe2szWirD4k4xhXgFhRBBGQaHAOUdJggLb1BdR3cW32rprJX0CNMs64iYCO9C7E/I7HIFeOJmMXw "Python 3 – Try It Online") *-1 byte thanks to mypetlion* [Answer] # [MATLAB](https://github.com/ETHproductions/japt), 113 bytes ``` c=@(x,p)char(mod(idivide(x,1000*26^p),26)+65); s=@(n)[c(n,3),c(n,2),num2str(mod(n,1000),'-%03d-'),c(n,1),c(n,0)] ``` --- Explanations: The first line define a function which will produce a char (from `A` to `Z`), function of 2 inputs. The index number `x` to convert into a plate number, and an integer `p` which will be used as an exponent for 26 (i.e. `26^p`). This second input allow to adjust the calculations for the first alphanumeric plate digit (`p=3`) down to the last one (`p=0`). For example, for the second digit, cycled every 1000\*26\*26 iterations, the operation: `mod(idivide(x,1000*26^2),26)` return an index between 0 and 25, which is then converted to an ASCII `char` by adding 65 (because the index are `0` based) The second line simply concatenate characters together. Each alphanumeric character is calculated with the use of the function `c(x,p)`, the numeric character are simply calculated with a `modulo` operation and converted to string. Each component of the string composing the plate number is as follow: ``` digit # | how often is it cycled | code ---------------------------------------------------------------- digit 1 | cycle every 1000*26*26*26=1000*26^3 | c(n,3) digit 2 | cycle every 1000*26*26 =1000*26^2 | c(n,2) digit 3,4,5 | cycle every iteration | num2str(mod(n,1000),'-%03d-') digit 6 | cycle every 1000*26 =1000*26^1 | c(n,1) digit 7 | cycle every 1000 =1000*26^0 | c(n,0) ``` --- Since I can't let you try MATLAB online (*edit:* actually you can [try it online](http://ideone.com/R31AkI) ), I'll let MATLAB users the possibility to verify the test cases: ``` % chose some test cases n = uint32([0;1;999;1000;675999;676000;456975999]) ; % work out their plate numbers plates = s(n) ; % display results fprintf('\n%10s | Plate # \n','Index') for k=1:numel(n) fprintf('%10d : %s\n',n(k),plates(k,:)) end ``` outputs: ``` Index | Plate # 0 : AA-000-AA 1 : AA-001-AA 999 : AA-999-AA 1000 : AA-000-AB 675999 : AA-999-ZZ 676000 : AB-000-AA 456975999 : ZZ-999-ZZ ``` --- **Variant:** Note that the option to let `sprintf` or `fprintf` take care of the number to character conversion is possible. It allow to simplify the function `c`, but overall result in a few more bytes in this implementation (119 bytes): ``` c=@(x,p)mod(idivide(x,1000*26^p),26)+65 ; s=@(n)sprintf('%c%c-%03d-%c%c\n',[c(n,3),c(n,2),mod(n,1000),c(n,1),c(n,0)]') ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~136~~ ~~106~~ 105 bytes ``` #define P(i)s[i]=65+x%26;x/=26; z;s[]=L" -%03d- ";f(x){z=x%1000;x/=1e3;P(9)P(8)P(1)P(0)wprintf(s,z);} ``` [Try it online!](https://tio.run/##TY3RCoIwFIav8ykOhrBR0pY5G2Nv0IX35kWoi120IqOG4rOvCSU78B/Ox3fgb9Jr0zi3bjulTQcl0rivdC1ZvrHJngm7k35Hg@irWp5igDQhWZsCnE0sFLJ4HKRNKCFkfqVdJkrEcYmOPtSH4M/jqc1LoX47YDE5f8Ptog1633WLYYxWCsFvCBYh0hA55wHOhQuyIg8tK9hiDznjfzu5Lw "C (gcc) – Try It Online") -7 bytes from [celingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)'s [solution](https://tio.run/##bY7NCoJAFEbX@RQXQ5ipkcbMseEy7@BeWvhbs8jCsRiMnt0yIgL9VofDWXyFfyyKYViWVa2bChKSMc1yalJ9UNnaejnajcrR6bE4ZS2Y9KBcAN/jYekDuFgTSx@9sl7AOR/boAoxISJikm0F/dD@R8FIK6NEtLZ4bXXT1cSwnuJzeDOcM92Q@0WXFB7OoibwHad4vXWGuC7Ffx/MeinlnB8PTr2Io9lexGLa7yIhJ/1zeAE), with additional -23 inspired by it -1 byte from ceilingcat's [solution](https://tio.run/##TY3RCoIwFIav8ykOhrBR0pY5G2Nv0IX35kWoi120IqOG4rOvCSU78B/Ox3fgb9Jr0zi3bjulTQcl0rivdC1ZvrHJngm7k35Hg@irWp5igDQhWZsCnE0sFLJ4HKRNKCFkfqVdJkrEcYmOPtSH4M/jqc1LoX47YDE5f8Ptog1633WLYYxWCsFvCBYh0hA55wHOhQuyIg8tK9hiDznjfzu5Lw) by changing the `char[]` to a `wchar_t[]` implicitly cast to `int[]` Uses 0-based indexing. Explanation/Ungolfed: ``` int s[] = L" -%03d- "; // Pre-made wide-string with dashes and ending null byte // and wprintf directive for digits int z; // Temporary variable to store the digit part void f(int x) { z = x % 1000; // The digits represent x % 1000 x /= 1000; s[9] = 'A' + x % 26; // Place least significant letter x /= 26; // Divide off least significant letter s[8] = 'A' + x % 26; // Place second letter x /= 26; // Divide off second letter s[1] = 'A' + x % 26; // Place third letter x /= 26; // Divide off third letter s[0] = 'A' + x; // Place fourth letter (Don't need to % 26 because x < 26 now) wprintf(s, z); // Print finished string (with x%1000 replacing %03d) } ``` [Answer] # [Kotlin](https://kotlinlang.org), 93 bytes ``` {i:Int->val c={v:Int->'A'+i/v/1000%26} ""+c(17576)+c(676)+"-%03d-".format(i%1000)+c(26)+c(1)} ``` [Try it online!](https://tio.run/##lVfbbhs3EH3XV9BCgkjJ6mYnNuzWAeQkLQIkcIEEKOo3apcrEV6RG5IrRTX87e4ZXnbXcYqiQR7E5XA4c@bMHPpWu0qqh9mMfVR14y6Y0m4j1ZqV2rBClLypHHPCOpZzKyzTZgBbrphUTqyFYSvh9kIo9rcwGt8L9vrNaXZ@9iY7Pz@fDsj4nRHcicJ7hG/Lcl0IttZVyfINryqh1uKCDDfO1fZiNqN92p5ax/Nb8R1WMJnmejv7Nlucn7w@OSbz34xQ@YZ9krlQVrA/KtxiB72dKu7UfgfXbgXCZpxZ8a0RyklekbU2hTAZwqsqvafUYVCLXJYyZzV3ThjFdEmWqtmuhLE@zUrQjmUXbHk1mS@OJ@/eh2xTSn71p5FOwGFt9NrwLe5iZaNyJ7UCFtxlHhVOpmu5A4zhiozpxqEcFkYCgRsjbK1VgejItPxJfvHklP2lG5PuI2O70U1VUF0ZcCwqhKMOIUNe@aoybr1hSBqVksrfC2LcYlVzgM8@uuRpJTwFVvDkNFsLJQzdTyfKpqrY8elL/F/M5/OX/idZX74lXrDzs1OG76zW1kpyEEqTES7cspIHdll2oCQqlL3B5QhSMdvUtTYuUOrrJuVL9bIH68QWjEKRyYsvpPWUWi4nuG@yXFKoWICUtBilSoqdrnY@H8ZKaawb/9I/dtU/dsNGyDFCw60LpwIPmA7fjVxvHvu46l990/fh7/svJ1f9@G@eOvm3QCpRRhdXfQhubv5HHN5HANwPhxb6PuFeWNClEN8J@W4seNNrz@H21CMa/5TDXY/5Q8uikNQpoKlU6JMtp5Xf@hS7b8N3noUrwcAPYYjO3gBd4GnTwPcKI43NJyvsFb53F@E32fnYKZ4fqRyHxmgruIpt15GJPHfp0Nk5GLzIAntts/VjBL1AnnA7MO3NUIoJ33zPcT@TQgyJ2xiRcUpOaAxm1HjGn@fK7uEL/Sl2whzIvG0SjC57FDx0V41S2umOcSh0@jdnk7ddXo/3Fu3e4oc9UCjuhX7q7VHb931epb3TIAm9czc33d5pls5d9WLpSQntdeT1aX74XqOYJCxpou4lCo0xv8Vwt1QVjMFcWD/dWqlhqBpEzU7Ze5FX3NA8ZI1SqEQRAN2uCkiAZvsweRTBSfNIKvCjvS3oYAET1Fk6uo7vtCxCCwvXQDa2/DZypxO@vNKW@ADz3DXgNl3IwWAMrekA3lPUI1@zC/SeG7NLdjcYEFYkb62C/MDZqEnJrjR66797R1P2u3B@aUU4DlGLlq1RT6Q33CBARIokkx0vipiq1yVek4ay5ZR9oT60IKVKpqsDtc/qwGpogm8wnFgc@3cCvSMwGKKlLqO3qgrSiqHh0okSqpgM0Ua@2Qu5kwASvoltU79NuLUhj3a8akRCbpC4@WL54pXPcub3Z3T6OfQp@f/Mb0mrrSNVyRgEdNUNSOb2OhlGnDMaEnmAfisLktY4vaId8RG9StwpuN2Q0FF@yXFbJ0kjDv6T45DScPiqy2hx9ubsdNz7cErLNrXh5Pn8pJgMp2FMBuo8pwR7Rt3h40euFmN2PxqHl1OPWoW0yO/gw3/aPZ6p0WREwynC7WlKEzq0EfzkWmFYpRYikgX@BLufvdXAJ5EeFLHZAv1WGjQjiqYmJ6RQTFb7MsPk/CQw7@FOXiCeyVvazS/vdmHlKTDbpdLfDwjkFtwA6hMsI455gA1w3T/4u973APKJZW2ubZOEqHxWofgJVeko9hpUc5UaDZ/5@X7Jnt3VHs3x/XA8uKez8YAvz2cOOrXjLn/ysE5VCtXZwnrEzdrijWoMP/z6xTP7bVekr@aAgvIidRuUKQi6F/Epe8dJq3iEHy9xUYfJAQFCLujcUlZITOlW@ektF8zR4mRB6MTHG2I1/inPrkkT99KKLAIURl5ExSGsO09bql5EhuL8JJUYjY@Opk6jnOAs2ciSecjYEcCZT6dQDYgGlGIcme82Ru/ZR0Cz5tXSrBuizoeUzGjQSd7wipNUYgAdDcPpPsPHEbVr1UFBJd/Cgv6uoNEV80DSwbaT/YtOZ7NOOmP@rSQGkrRKR2jc47xDi4yEMdpc4IGAdOj5PY4gtSRqo0chqaTx7zebkiGiBKgQbiWtuy5H8wzvFlL0zE/TrEXj1GOYkTjTd9bBmnB9jA0FSgnjWeJ/EPse/gE "Kotlin – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 161 bytes ``` i,t,u,v,a,c,f=int(input()),1000,676,26,ord('A'),chr,lambda x:c(a+x//v)+c(a+x%v) m,n=i%t,i//t e,o=n%u,n//u print('-'.join([f(o),(3-len(str(m)))*'0'+str(m),f(e)])) ``` [Try it online!](https://tio.run/##JcxLDoIwFEbhOatwQnqv/NgqAsGEgeswDpBHqIGW1EJw9Rh1dr7Jmd6@tybZNg2PGQsq1OhKbTxpM82emHFUSiHLM5wyWNeQuApG3TsM1fhoqt16qamKVikXjn4VLhyMMKUOPbSUPmhhSxPOMFLOweS@dxGLw9NqQ7eOLIOSeGgNvbyjkZn3QonoD3TU8p15285pVuRpUagP "Python 3 – Try It Online") ]
[Question] [ A number is balanced if the sum of the digits on each half of the number is equal, so: `1423` is balanced because `1+4 = 2+3`, so is: `42615` because `4+2=1+5`. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits. **Challenge:** Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced. **Test cases (true)** ``` 1 6 11 141 1221 23281453796004414 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088 ``` **Test cases (false)** ``` 10 12 110 15421 5234095123508321 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454 ``` There will not be numbers starting with zero, for instance `00032` instead of `32`. You must support numbers up to at least 100 digits (so larger than `2^64-1`). As always, optional input format, so you may surround the number with apostrophes if desired. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 7 bytes ``` €D2äO`Q ``` **Explanation** Using **141** as example: ``` €D # duplicate each (turns the number into a list of digits) # STACK: ['1','1','4','4','1','1'] 2ä # split list in 2 (as we duplicated each element, # the middle element will exist on both sides for an odd length input # STACK: [['1','1','4'],['4','1','1']] O # sum each sublist # STACK: [6,6] ` # flatten # STACK: 6, 6 Q # compare for equality # STACK: 1 (true) ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oKsRDLDpE9gUQ&input=NTIzNDI4MTIxNjU2NjY2NjU1NjU1NTU2NjU1NjU2NTAyODA5NzQ1MjQ5NTUyNDY2MzM5MDg5NzAyMzYxNzE2NDc3OTgzNjEwNzU0OTY2ODg1MTI4MDQxOTc1NDA2MDA1MDg4) [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~31~~ 29 bytes ``` i:0(?v ~00}v> v+r+>l4(? >{=n; ``` [Try it online!](http://fish.tryitonline.net/#code=aTowKD92Cn4wMH12Pgp2K3IrPmw0KD8KPns9bjs&input=MjMyODE0NTM3OTYwMDQ0MTQ) Line 1: Standard input loop Line 2: Discard the -1 on top of the stack, push two 0's and rotate one to the bottom of the stack (this ensures that inputs of length <3 don't exhaust the stack later in the program) Line 3: If the length of the stack is >3, add the top two and bottom two elements of the stack together. Line 4: If top and bottom of the stack are equal, output 1, 0 otherwise. *Edit: realised that there's no need to take the characters mod 12, 2 bytes saved* [Answer] # Haskell, ~~64~~ 63 bytes ``` b(a:t@(r:s))=a-last t+b(init t);b _=0 (==0).b.map fromEnum.show ``` One Byte Saved thanks to nimi [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 20 bytes ``` @eL@2tM,Lr@2t:M:+a#= ``` [Try it online!](http://brachylog.tryitonline.net/#code=QGVMQDJ0TSxMckAydDpNOithIz0&input=NTIzNDI4MTIxNjU2NjY2NjU1NjU1NTU2NjU1NjU2NTAyODA5NzQ1MjQ5NTUyNDY2MzM5MDg5NzAyMzYxNzE2NDc3OTgzNjEwNzU0OTY2ODg1MTI4MDQxOTc1NDA2MDA1MDg4) ### Explanation ``` @eL Get the list of digits L of the input L@2tM, Get the second half M of L Lr@2t Get the second half of the reverse of L :M The list [L, M] :+a#= The sum of elements of L and the sum of elements of M must be equal ``` [Answer] ## Mathematica, 57 bytes ``` Tr@(#-Reverse@#)[[;;⌊Length@#/2⌋]]==0&@*IntegerDigits ``` ### Explanation I was really hoping I could use this approach in some language, and it seems to be doing fairly well in Mathematica. The idea is to avoid having to obtain both the front and the back half by combining the list with its reverse and looking *only* at the front half. ``` ...&@*IntegerDigits ``` First, we turn the input into a list of decimal digits and pass the result to the unnamed function on the left. ``` ...(#-Reverse@#)... ``` Now we subtract the reverse of the list from the list itself. If the digits are `{a1,a2,...,an}` then the result will be `{a1-an,a2-an-1,...,an-a1}`. ``` ...[[;;⌊Length@#/2⌋]] ``` We extract the first half of this list (excluding the middle digit although that doesn't actually matter, because the corresponding difference will be `0` anyway). ``` Tr@... ``` And then we sum this list. So that's: ``` a1 - an + a2 - an-1 + ... + a⌊n/2⌋ - a⌈n/2⌉+1 ``` Rearranging: ``` a1 + a2 + ... + a⌊n/2⌋ - (a⌈n/2⌉+1 + ... + an-1 + an) ``` The input is balanced if the two halves have the same sum. Hence, this expression is zero if the input is balanced. So that's what we check: ``` ...==0 ``` [Answer] # Java, 85 bytes ``` n->{int s=0,i=0,l=n.length();for(;i<l/2;)s+=n.charAt(i)-n.charAt(l-++i);return s==0;} ``` Note: the input is given as `String` as Java can't handle without `BigInteger` (and `BigInteger`s are constructed using a... `String`.) ## Testing and ungolfed: ``` import java.util.function.Predicate; public class Main { public static void main(String[] args) { Predicate<String> f = n -> { int s = 0, i = 0, l = n.length(); for (; i < l / 2;) { s += n.charAt(i) - n.charAt(l - ++i); } return s == 0; }; String[] truthies = {"1", "6", "11", "141", "23281453796004414", "523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"}; for (String s : truthies) { boolean result = f.test(s); System.out.println(result); } String[] falsies = {"10", "12", "110", "15421", "5234095123508321", "6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"}; for (String s : falsies) { boolean result = f.test(s); System.out.println(result); } } } ``` [Answer] # JavaScript (ES6), ~~59~~ ~~55~~ ~~51~~ ~~44~~ 42 bytes ``` f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n ``` Turns out I was using the wrong strategy entirely. This version recursively finds the sum of the first half minus the sum of the second half, then returns the logical NOT of the result. If we could return falsy in place of truthy and vice-versa, this would be 35 bytes: ``` f=([x,...a])=>a[0]?x-a.pop()+f(a):0 ``` ### Test snippet ``` f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n ``` ``` <input id=I value="23281453796004414"><br> <button onclick="console.log(`Result of f(${I.value}): `+f(I.value))">Run</button> ``` [Answer] ## Haskell, 55 bytes ``` g(h:t)=read[h]-g(reverse t) g _=0 (==0).g.(<*"xx").show ``` The recursive function `g` unwraps a number string from both ends by repeatedly taking the head, then reversing. It subtracts the recursive result from the head, which causes it alternate coefficients of +1 and -1, with +1 applied to the first half and -1 to the second half. ``` g "12345" == 1 - g "5432" == 1 - (5 - g "432") == 1 - (5 - (4 - g "32")) == 1 - (5 - (4 - (3 - g "2")) == 1 - (5 - (4 - (3 - 2)) == 1 + 2 + 3 - 4 - 5 ``` So, it takes the sum of the first half minus the sum of the second half. This has the issue that with an odd number of digits, the center tiebreaks to the left, but the main function fixes that by `(<*"xx")`, which doubles every character, i.e. "12345" becomes "1122334455". That way the middle digit splits evenly on both sides and cancels out. [Answer] ## PowerShell v2+, 85 bytes ``` param($a)!((,'('+$a[0..(($b=$a.length)/2-1)]+'0)-('+$a[($b/2)..$b]+'0)')-join'+'|iex) ``` Takes input `$a` as a string (necessary to support numbers `>2^64-1` without getting into extremely clunky `[biginteger]` casting on the command line). For the explanation, let's assume input of `'1423'`. We're then constructing a new string. The two array slices are obvious (`$a[...]`), and that's surrounded by three additional strings `(`, `0)-(`, and `0)`, formulating an array of `char`s and `string`s. Note the `,` at the front to enforce array concatenation, not string concatenation. That whole array is `-join`ed together with `+`, resulting in a string like `(+1+4+0)-(+2+3+0)`, and you can see that the `0`s are needed to prevent syntax errors. That's fed into `|iex` (short for `Invoke-Expression` and similar to `eval`), which will compute the mathematical result. So long as the string is balanced, you'll get `0` as an output, which we encapsulate in parens and take the Boolean-not thereof `!(...)`, to output `True`. If it's any non-zero integer, it'll output `False`. ### Test Cases ``` PS C:\Tools\Scripts\golfing> '1','6','11','141','23281453796004414','523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'} 1 True --- 6 True --- 11 True --- 141 True --- 23281453796004414 True --- 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088 True --- PS C:\Tools\Scripts\golfing> '10','110','15421','5234095123508321','6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'} 10 False --- 110 False --- 15421 False --- 5234095123508321 False --- 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454 False --- ``` [Answer] # Perl, 29 bytes Includes +5 for `-lpF` Give number on STDIN ``` balanced.pl <<< 1423 ``` `balanced.pl`: ``` #!/usr/bin/perl -lpF $;+=$_-pop@F for@F;$_=!$ ``` [Answer] # C#, 83 bytes ``` n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;}; ``` [**Try it online!**](http://ideone.com/PtJ5bm) Full source, including test case: ``` using System; using System.Numerics; namespace BalancedNumber { class Program { static void Main(string[] args) { Func<BigInteger,bool>s= n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;}; Console.WriteLine(s(1)); //true Console.WriteLine(s(6)); //true Console.WriteLine(s(11)); //true Console.WriteLine(s(141)); //true Console.WriteLine(s(23281453796004414)); //true BigInteger bi = BigInteger.Parse("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"); Console.WriteLine(s(bi)); //true Console.WriteLine(s(10)); //false Console.WriteLine(s(12)); //false Console.WriteLine(s(110)); //false Console.WriteLine(s(15421)); //false Console.WriteLine(s(5234095123508321)); //false bi = BigInteger.Parse("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"); Console.WriteLine(s(bi)); //false } } } ``` The BigInteger data type allows any number length. If the number is too large, the compiler complains (*error CS1021: Integral constant is too large*), so the **BigInteger.Parse(String)** method is used instead. The solution can actually be reduced to **72 bytes** considering the input is a string (and updating the program accordingly): ``` t=>{int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;}; ``` [Answer] ## Python 3, ~~107~~ ~~102~~ 76 bytes ``` n=input() l=len(n) print(sum(map(int,n[:l//2]))==sum(map(int,n[l//2+l%2:]))) ``` -26 bytes by [@Rod](https://codegolf.stackexchange.com/users/47120/rod)! [Answer] ## Ruby, 63 bytes ``` ->s{e=s.chars*?+ l=s.size e[l-1-r=l%2,2*r+1]="==" l<2||eval(e)} ``` Note: arg `s` must be string. ### Testing(minitest 5+ required): ``` require 'minitest/autorun' class TestRunner < Minitest::Test def setup @truthy_nums = %w(1 6 11 141 23281453796004414 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088) @falsy_nums = %w(10 110 15421 5234095123508321 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454) @f=->s{e=s.chars*?+ l=s.size e[l-1-r=l%2,2*r+1]="==" l<2||eval(e)} end def test_true @truthy_nums.each do |e| assert @f[e], e end end def test_false @falsy_nums.each do |e| assert !@f[e], e end end end ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` YIṠ≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqE6xpsiLCJZSeG5oOKJiCIsIjskWsabYCA8PSBgajvigYsiLCIxXG42XG4xMVxuMTQxXG4xMjIxXG4yMzI4MTQ1Mzc5NjAwNDQxNFxuNTIzNDI4MTIxNjU2NjY2NjU1NjU1NTU2NjU1NjU2NTAyODA5NzQ1MjQ5NTUyNDY2MzM5MDg5NzAyMzYxNzE2NDc3OTgzNjEwNzU0OTY2ODg1MTI4MDQxOTc1NDA2MDA1MDg4XG4xMFxuMTJcbjExMFxuMTU0MjFcbjUyMzQwOTUxMjM1MDgzMjFcbjYyNDA5MTEzMTQzOTkwNzI0NTk0OTM3NjU2NjExOTEwNTg2MTM0OTE4NjMxNDQxNTIzNTIyNjI4OTczNTE5ODgyNTA0MzExNDA1NDY2NjAwMzU2NDg3OTUzMTY3NDAyMTI0NTQiXQ==) Beats all other answers. ## How? ``` YIṠ≈ Y # Interleave the input with itself, giving a list with each digit duplicated I # Split into two halves Ṡ # Sum each ≈ # Is this list all equal? ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` .ι2äOË ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f79xOo8NL/A93//9vaGRkCAA "05AB1E – Try It Online") Same concept. [Answer] # Retina, ~~64~~ 44 bytes ``` ^((.)*?).?(?=(?<-2>.)*$) $1 \d $* ^(1+) \1$ ``` [**Try it online**](http://retina.tryitonline.net/#code=XigoPzouKD89Lio_KD8oMikoPz0uXDIkKSkoLlwyPyQpKSkqKSguKS4qCiQxICQyClxkCiQqCl4oMSspIFwxJA&input=MjMyODE0NTM3OTYwMDQ0MTQ) The first stage splits the string in the middle, omitting the middle character if there is one (~~taken and modified from [here](https://stackoverflow.com/a/28052126/2415524).~~ Courtesy of Martin.) Then, replace digits with their unary representation, and match if the two halves are of equal length. [Answer] ## JavaScript (ES6), ~~74~~ ~~67~~ ... ~~59~~ 50 bytes Recursively sums the difference of the first and last digits until there's less than two digits left: ``` let f = n=>!(F=n=>n[1]?(n.pop()-n.shift()+F(n)):0)([...n]) // some truthy examples console.log(f("11")); console.log(f("141")); console.log(f("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088")); // some falsy examples console.log(f("12")); console.log(f("110")); console.log(f("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454")); ``` [Answer] # R, ~~105~~ 96 bytes Turns out R is very verbose. Takes input as a character. ``` function(x){y<-as.numeric(unlist(strsplit(x,"")));l<-length(y)%/%2;sum(tail(y,l))==sum(head(y,l))} ``` Formatted nicely: ``` function(x){ y=as.numeric(unlist(strsplit(x,""))) l=length(y)%/%2 sum(tail(y,l))==sum(head(y,l)) } ``` Explanation * `y<-as.numeric(unlist(strsplit(x,"")))` Split the input (a string\_, and coerce it to a vector instead of a list, and then turn it back into integers. * `sum(tail(y,`: `tail` takes the last *n* elements, found by: + `length(y)%/%2))`, where `%/%` is integer division, to get the ceiling of the quotient, where the length is odd. * `sum(head(y,length(y)%/%2))`: like `tail`, `head` takes the first *n* elements of the vector, found in the same way. ## Edits * Saved seven bytes thanks to niam * Switched to `=` instead of `<-` , saved another two bytes. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~410~~ ~~206~~ ~~204~~ 178 + 3 = 181 bytes Here is a 178 byte version that uses the `-a` flag. *26 bytes golfed off by DJMcMayhem* [Try it Online](http://brain-flak.tryitonline.net/#code=KFtdKSg8KCgpKCkoPD4pKT4pPD57KHt9WygpXSk8Pigoe30oKVsoe308KHt9KCkpPildKSl7e30oPCh7fSh7fTwoe31bKCldKT4pKT4pfXt9PD59e308Pnt9e30oe308Pil7KHt9WygpXTwoe308Pik8Pj4pfXt9KFtdPD5bW11dPD4peyg8e317fT4pfXt9KHt7fTw-W3t9XTw-fTwoKCkpPil7e317fSgoPD4pKX17fQ&input=MTIxMzExMg&args=LWE) ``` ([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){(<{}{}>)}{}({{}<>[{}]<>}<(())>){{}{}((<>))}{} ``` Here is a longer 410 byte version that does not use the `-a` flag. [Try it Online](http://brain-flak.tryitonline.net/#code=eygoe30pKSg8KCgoKSgpKCkoKSgpKXt9PD4pPik8Pnsoe31bKCldKTw-KCh7fSgpWyh7fSldKSl7e30oPCh7fSh7fSkpPil9e308Pn17fTw-KHt9PHt9Pik8Pig8KCgoKSgpKCkoKSgpKXt9KDw-KSk-KTw-eyh7fVsoKV0pPD4oKHt9KClbKHt9PCh7fSgpKT4pXSkpe3t9KDwoe30oe308KHt9WygpXSk-KSk-KX17fTw-fXt9PD57fXt9KHt9PD4pfXt9PD4oW10pKDwoKCkoKSg8PikpPik8Pnsoe31bKCldKTw-KCh7fSgpWyh7fTwoe30oKSk-KV0pKXt7fSg8KHt9KHt9PCh7fVsoKV0pPikpPil9e308Pn17fTw-e317fSh7fTw-KXsoe31bKCldPCh7fTw-KTw-Pil9e30oW108PltbXV08Pil7e317fSg8Pil9e30oKFtdKTw-KSh7PHt9Pnt9PChbXSk-fXt9PD5bezx7fT57fTwoW10pPn17fV08KCgpKT4pe3t9e30oKDw-KSl9e30&input=MTI0MDM) ``` {(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)}{}<>([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){{}{}(<>)}{}(([])<>)({<{}>{}<([])>}{}<>[{<{}>{}<([])>}{}]<(())>){{}{}((<>))}{} ``` # Explanation Here is an explanation of the shorter solution To begin the number is converted to all of its ASCII values by the `-a` flag. We push the stack height (i.e. number of digits) and divide by two. ``` ([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>) ``` For each number less than the number we just pushed we move a digit to the other stack ``` {({}[()]<({}<>)<>>)}{} ``` If the stacks have different heights we remove the top item from the current stack ``` ([]<>[[]]<>){(<{}{}>)}{} ``` We want the difference between the sums of each stack. So we use the following algorithm to sum each stack. ``` {{}} ``` This assumes no digit has an ASCII value of zero, which is a valid assumption. We run this for both stacks and take the difference (The `<(())>` is necessary for the next part. ``` ({{}}<>[{{}}]<(())>) ``` We now want to negate the sum. If the sum is zero it will pop the top off revealing the one we pushed earlier otherwise it will remove both the number and the one and place a zero on top. ``` {{}{}((<>))}{} ``` [Answer] # Actually, ~~17~~ 16 bytes This answer is inspired by [ElPedro's Python 2 answer](https://codegolf.stackexchange.com/a/94314/47581) and their idea to use `[-b:]`. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=JOKZguKJiDtswr1M4pSCwrFhSM6jKXTOoz0&input=NTIzNDI4MTIxNjU2NjY2NjU1NjU1NTU2NjU1NjU2NTAyODA5NzQ1MjQ5NTUyNDY2MzM5MDg5NzAyMzYxNzE2NDc3OTgzNjEwNzU0OTY2ODg1MTI4MDQxOTc1NDA2MDA1MDg4) ``` $♂≈;l½L│±aHΣ)tΣ= ``` **Ungolfing** ``` Implicit input n. $♂≈ list(str(n)). This converts n to a list of n's digits. ;l Duplicate the list of digits and get its length. Call it len. ½L Push len//2. │ This duplicates the stack. Stack: len//2, digit_list, len//2, digit_list ± Negate the len//2 at TOS for later. a Invert the stack. Stack: digit_list, len//2, digit_list, -(len//2) HΣ Push digit_list[:len//2], then push its sum. ) Rotate this first sum to BOS. tΣ Push digit_list[-(len//2):], then push its sum. = Check if those sums are equal. Implicit return. ``` [Answer] # [Perl 6](https://perl6.org), ~~42 39~~ 33 bytes ``` {[==] .comb[{^($_/2),Int($_/2)..*}]>>.sum} ``` [Test it](https://tio.run/##ZZFNj9MwEIbv/hWzotAESuPxV@xW6SIOSFw47QFpWVBoXTYiTavErVpV4a@XcQrLSkSJM/Nm3vHjyc63tbnsOw8HM13O2eYEr5bblYficr4vigeYLreb7/fnr8noWybSyccmXKPp9HX/sFhMu/2mv5DrZfBdgFkBddX4Lkmny7rsump9mp0ZQBfK4OH9dlvD6DgnYXSEAm6zWQWh3fsMqjVk47vYYll2vhtnsSj7ssrg9jYW39zAp6qeA7yA1od928Q0usKjbz2UrW/GAcrmBKvqRxU61rOB6Exl/Wzlax88uaP/mkTjlZWiMsBqGxs8lgf/vAsd7N1wsALWNVUld0QLn4vFNb1uEbU@nUDyoay7/74OYp/OGYtTjkecs11dNvBm6Ez6etv@2eXtApLZT39KRv6488vgV@lkdijrvU9GVbPbhzSFOM6qg/iT/ooTeKqncNDgF4yBQMYUPH1k/eXfiCGJk08ZQ2YYIkNFjxDIhBQWlZa5M5wrhYppIRVpAo028dKablqGwGguLHe50kI5TYsxUjpuXc6FNJijUXnuLIU818oZY61Gcih0lHPaQ3NrGXtOto4zi2ickAiOXloRWgThjuySPJIEIyhHlKikczwXSjvlZB45ER1ybQ1K5dAaKlFIfi2EEQQnNTprheZKIiquCZtQpDbK5k5LNLniAqmh@g0 "Perl 6 – Try It Online") ``` {[==] .comb[^(*/2),(*/2).Int..*]>>.sum} ``` [Test it](https://tio.run/##ZZFNj9MwEIbv/hWzotBkKYnHX7FbpYs4IHHhtAekZZFC67IRaVolbtWqKn@9jFNYViJKnJk3844fT7a@a8xl13vYm2wxY@sjvFlslh7Ky@mhLB8hW2zW3x@@Jbe5SCfDmn1qQ5bdPs7nWb9bny9keR18H2BaQlO3vk/SbNFUfV@vjtMTA@hDFTx82GwaGB1mJIwOUMJdPq0hdDufQ72CfHwfWyyq3vfjPBblX5c53N3F4psb@Fw3M4BX0Pmw69qYRld48p2HqvPtOEDVHmFZ/6hDz85sIDpR2Xm69I0PntzRf02i8cpKURVguYkNnqq9f9mFDvZ@OFgJq4aqknuihS/l/Jpet4jaOZ1A8rFq@v@@DuI5nTEWRxyPOGPbpmrh7dCZ9NWm@7PLuzkk05/@mIz8YesXwS/TyXRfNTufjOp2uwtpCnGcdQ/xD/0VJ/BcT@GgwS8YA4GMKXj@yM6XfyOGJE4@ZQyZYYgMFT1CIBNSWFRaFs5wrhQqpoVUpAk02sRLa7ppGQKjubDcFUoL5TQtxkjpuHUFF9JggUYVhbMU8kIrZ4y1Gsmh0FHOaQ/NrWXsJdkqziyicUIiOHppRWgRhDuyS/JIEoygHFGiks7xQijtlJNF5ER0yLU1KJVDa6hEIfm1EEYQnNTorBWaK4mouCZsQpHaKFs4LdEUigukhuo3 "Perl 6 – Try It Online") ``` {[==] .comb[^*/2,^*/2+*/2]>>.sum} ``` [Test it](https://tio.run/##ZVFNj9owEL37V8yqtCRdSjz@ig0Ku@qhx572UGm7ldJgulFDQIlBIJT@dTqGdrtSo3gy8/ze@Hmy9V1jzrvew95MqzlbH@FdtVl6KM6nx6J4gmm1WX9//PY@E5MYbmk9LRbTfrcezkR@G3wfYFZAU7e@T9Jp1ZR9X6@OsxMD6EMZPHzcbBoYHeYEjA5QwF02qyF0O59BvYJs/BBbVGXv@3EWSdnXZQZ3d5F8cwOf62YO8AY6H3ZdG8uoCs@@81B2vh0HKNsjLOsfdejZwC6OTkQbZkvf@OBJHfXXIgqvXikrAyw3scFzufevu9DF7i8XK2DVECt5ILfwpVhcy@sRERvSCSSfyqb/b/cCDumcsTjceMU52zZlC7eXzoSvNt2fUz4sIJn99Mdk5A9bXwW/TCezfdnsfDKq2@0upCnEcdY9xH/zF5zAC5/SCwa/YAxkZEzJyyYbzv9GDEmcfMoYMsMQGSpaQiATUlhUWubOcK4UKqaFVIQJNNrER2t6KVwSo7mw3OVKC@U0BWOkdNy6nAtpMEej8txZSnmulTPGWo2kUOio5nSG5tYy9trZKs4sWuNkiczRRyuyFo1wR3JJGkmAEVQjSlTSOZ4LpZ1yMo8@ER1ybQ1K5dAaoigkvRbCCDInNTprheZKIiquyTZZkdoomzst0eSKC6SG6jc "Perl 6 – Try It Online") (from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)) ## Explanation: ``` { # lambda with implicit parameter 「$_」 [==] # reduce the following using &infix:«==» .comb\ # split input into individual characters [ # index into that using: # first half of the values (includes middle value) # 「(0/2) ..^ (*/2)」 ^ * / 2, # last half of the values (includes middle value) ^ * / 2 # same number of values as first half + * / 2 # shifted up by half ]\ >>.sum # sum each of the two halves separately } ``` [Answer] # Javascript, 73 bytes Good ol' ES5 loops ``` for(a=c=0,b=(l=(s=prompt()).length)-1;a<~-l/2;c-=s[a++]-s[b--]);alert(!c) ``` What's happening here? ``` for( a=c=0, // a = left digits of the number // c = the result b= // b = right digits of number (l= // l = length of number - 1 (s=prompt()) // s = the number as input from user .length)-1; a<~-l/2; // while a < length of number / 2, rounded down (~-) c-= s[a++] // c -= left digit - s[b--] // c += right digit (because - and - == +) ); // for balanced numbers c should be 0 alert(!c) // 0 equals false in javascript, so output the opposite of c ``` [Answer] # Python 2, 73 bytes ``` def f(n):x=map(int,str(n));d=len(x)/2;print sum(x[:d])==sum(x[-d:])or d<1 ``` Tests are at **[ideone](http://ideone.com/I98HFT)** We have to use `str()` rather than `` since `n` may be outside the range of signed int. [Answer] # Python 2, ~~83~~ 77 bytes ``` g=[int(h)for h in raw_input()];b=int(len(g)/2);print sum(g[:b])==sum(g[-b:])or b==0 ``` **EDIT** reduced to 77 with help from @Rod ``` g=[int(h)for h in raw_input()];b=len(g)/2;print sum(g[:b])==sum(g[-b:])or b<1 ``` Examples: ``` D:\>bal.py 1 True D:\>bal.py 6 True D:\>bal.py 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088 True D:\>bal.py 10 False D:\>bal.py 110 False D:\>bal.py 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454 False ``` [Answer] # PHP, ~~73~~ ~~67~~ ~~60~~ 57 bytes Requires PHP 7.1 for negative string offsets: ``` for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s; ``` Run: ``` echo 15324 | php -nR 'for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;';echo ``` # Previous version Note: requires PHP 7 for the spaceship operator. ``` for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s; ``` Run like this: ``` php -d error_reporting=30709 -r 'for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;' -- 15324;echo ``` ## Explanation Iterates over the digits in the number. Checks if the digit belongs to the first half or the second half (or is the middle digit) by comparing the digit's index to the length of the input with combined comparison (`2 * $x <=> $l - 1`). Then multiply that with the digit, take the sum of all digits. If it's a balanced number, the sum will be `0`. Example with input `15324`: ``` index 0 1 2 3 4 digit 1 5 3 2 4 2*index 0 2 4 6 8 length-1 4 4 4 4 4 factor 1 1 0 -1 -1 # Result of the spaceship operator result 1 5 0 -2 -4 -------------- sum 0 ``` # Tweaks * Don't set the digit to `$d`, just iterate the length of the input. Saved 5 bytes. * String offset `null` doesn't have to be cast to `int` for PHP to interpret it as `0`. Saved 1 byte. * Using negative string offsets to get the digits from the second half and iterating to half of the string. Saved 7 bytes, but requires PHP 7.1 * Saved 3 bytes by using `$argn` [Answer] ## Clojure, ~~66~~ 64 bytes Update: Took `str` out from the `map int` function. ``` (comp #(=(apply +(map -(drop(/(count %)2)%)%))0)#(map int %)str) ``` This would have been shorted if the input format was more flexible, now I had to first map the integer into a sequence of ASCII values. The inner `map` calculates pair-wise differences of values from the two halves, and this checks if the sum of deltas is zero. `((comp f g h) x y z)` = `(f (g (h x y z))`. Actually this ended up being the same length as just doing the mapping within a `let` and just define a single function. [Answer] # [Factor](https://factorcode.org/) + `math.unicode sequences.repeating`, 32 bytes ``` [ 2 repeat halves [ Σ ] same? ] ``` [Try it online!](https://tio.run/##RVBLTgMxDN3nFDlB5X9iWLBEbNggVlUXoxJoRTudTqdUCHEa7sOVigsLIsexX2y/Jz93y2k3nh8f7u5vr/Kh7Y@tX7bDbGxD66Z1//KP5dc29m2Tt920mh379XL31PIwtml6H8Z1P@X9KV@ntD99JEyWEBNKXCJMxFRRlIsbgAhKUmIJjNDULkc1LNxvYApUwYsoiWs4M2aH6gWIDQualOI1QigqblarYnQIeuQQHAq1JoRgDx3xqISKCyd4VHJ8cwBGkSMyCrtDIVEX53KRhOgIWg1ZHKtFiWD0K5FR6GBFr5UUhBEFNBQGK6tJLa6MVgQIY6Ckz/M8U/7bZ151m7fY5Dx/f@VFPnTbdpMX52035Nn5Bw "Factor – Try It Online") ``` ! "141" 2 repeat ! "114411" halves ! "114" "411" [ Σ ] same? ! t ``` [Answer] # C (GCC), 66 bytes ``` char*c,*d;i;f(s){for(d=index(c=s,i=0);c<--d;)i+=*c++-*d;return!i;} ``` [Try It Online!](https://tio.run/##lVFNSwNBDL33V9QFYbcfkMwkmYlrr/4Cj72U2a0u6Cq7WxBKf3tNVRA9OBiGkCEvj@S9tH5I6XxOj7thkVaLpu7qfTlWx/3LUDabrm/atzJtxlW3gapOt@t1U1fdcrNIy@Xa0EM7HYb@qqtP5@dd15fV7Dibf8XrYRrL4n44tPOpHad52o3teFNU9Tdi6PppXxbXzbYvVnOrsKj@7EumjzkCpCzCuRzEeReR2AcVACKkDJ6dJ5twKCyXYLZn6aMQBhdBA7EjZUsi3itEDeC8YEChEDRaCYFJRWJktAlCtT/YBgwx/tjglwXb/m73NP7HBchqlPUhS8GU1fmiG6hd6@1En4WLMzSiR/KqEByxkvpwER1RETgKelKMYhBCY2fnxJnSnlFjdAzkEQnYPDBdPQvFoOxRAoFDI/x0@nR@Bw) Explanation: ``` char*c,*d;i; f(s) { // d = the first null-terminator in s, c = s, i = 0 // Before the first and after each iteration, decrement d and break out of // the loop if c has surpassed d. for(d=index(c=s,i=0);c<--d;) // Add the ascii values of c and d to i, increment c. // The ascii values of a number equals the ascii value of 0 plus the // number, so if numbers j and k are respectively stored in c and d, // *c - *d = (i + '0') - ('j + '0') = i - j = the signed difference i+=*c++-*d; // If the sum of the signed differences are 0, return 1; otherwise 0 return!i; } ``` [Answer] # sed (165 + 1 for -r) 166 ``` /^.$/c1 :l;s,^([^!])([^!]*)([^!])!?([^=]*)=?(.*),\2!\4\1=\5\3,;tl;: s,.?!|0,,;s,2,11,;s,3,21,;s,4,31,;s,5,41,;s,6,51,;s,7,61, s,8,71,;s,9,81,;t;s,1=1,=,;t;/^=$/c1 c0 ``` Output: 1 for true 0 for false [Try it online!](http://sed.tryitonline.net/#code=L14uJC9jMQo6bDtzLF4oW14hXSkoW14hXSopKFteIV0pIT8oW149XSopPT8oLiopLFwyIVw0XDE9XDVcMyw7dGw7OgpzLC4_IXwwLCw7cywyLDExLDtzLDMsMjEsO3MsNCwzMSw7cyw1LDQxLDtzLDYsNTEsO3MsNyw2MSwKcyw4LDcxLDtzLDksODEsO3Q7cywxPTEsPSw7dDsvXj0kL2MxCmMw&input=MQo2CjExCjE0MQoxMjIxCjIzMjgxNDUzNzk2MDA0NDE0CjUyMzQyODEyMTY1NjY2NjY1NTY1NTU1NjY1NTY1NjUwMjgwOTc0NTI0OTU1MjQ2NjMzOTA4OTcwMjM2MTcxNjQ3Nzk4MzYxMDc1NDk2Njg4NTEyODA0MTk3NTQwNjAwNTA4OAoxMAoxMgoxMTAKMTU0MjEKNTIzNDA5NTEyMzUwODMyMQo2MjQwOTExMzE0Mzk5MDcyNDU5NDkzNzY1NjYxMTkxMDU4NjEzNDkxODYzMTQ0MTUyMzUyMjYyODk3MzUxOTg4MjUwNDMxMTQwNTQ2NjYwMDM1NjQ4Nzk1MzE2NzQwMjEyNDU0&args=LXI) [Answer] # Python 2.7, 102 92 bytes For loop works better :/ ``` s=`input()` a,b,l=0,0,len(s) for i in range(l/2):a=a+int(s[i]);b=b+int(s[l-i-1]) print a==b ``` Same idea, just use length - i to get other side. It will never reach the center of an odd number. Old code ``` s=input() l=len(s) def n(i):return 0if not i else int(i[0])+n(i[1:]) print n(s[:l/2])==n(s[l/2+l%2:]) ``` Gets input Saves length of input Recursive func to get sum of string Compare the first half sum to the second half sum Trying to get it below 100, but its hard :/ [Answer] # C function, 74 ``` l;i;t;f(char *n){l=strlen(n);for(t=i=0;i<l/2;)t+=n[i]-n[l-++i];return !t;} ``` [Ideone.](https://ideone.com/O1i46p) ]
[Question] [ # Background: Standard operation math like basic addition and multiplication in the real world work like these: ``` 12 + 123 = 135 ``` and ``` 12 * 123 = 1476 ``` *That's not interesting and boring!* Many schools are already interpreting this as practice, practice, practice of formal algorithms. That implies a pretty rigid and boring mathematical diet and is not what is intended in this challenge. Get ready to play some fun on our beloved site. Consider the process of adding two positive integer numbers, then adding again all the digits of its result. Repeating with the addition until only a single digit is obtained. For example: 1. The result of `12 + 123` is 135. 2. Adding all the digits of 135 we obtain `1 + 3 + 5 = 9`. The number of steps required to obtain a single digit value 9 in this repeated addition is 2. As with the previous process of the addition, the multiplication of two positive integer numbers follows the same process. Multiply all the digits of its result and then repeating this process until only a single digit remains. Take the above example: 1. The result of `12 * 123` is 1476. 2. Multiply all the digits of 1476 we obtain `1 * 4 * 7 * 6 = 168`. 3. Multiply again all the digits of 168 we obtain `1 * 6 * 8 = 48`. 4. Multiply again all the digits of 48 we obtain `4 * 8 = 32`. 5. Multiply once again all the digits of 32 we obtain `3 * 2 = 6`. The number of steps required to obtain a single digit value 6 this repeated multiplication is 5. For this challenge's sake and avoiding any misuse of math notations, I introduce these two dummy notations: `(+)` and `(*)`, **but you may use any notation you like**, which work like the followings: 1. The operation of repeated addition process to obtain a single value is `12 (+) 123 = 9`. 2. The operation of repeated multiplication process to obtain a single value is `12 (*) 123 = 6`. # Challenge: The challenge is to write either a program or a function which can perform **both of operations** as explained in the background section: `(+)` and `(*)`. # Input: The inputs of the program or the function are two positive integers and one operation either `(+)` and `(*)`. **The format of the input is an arbitrary choice of the programmer**. You may format the input, for example, `a (+) b` or `F(a, (+), b)` or any format you wish. # Output: The output of the program or the function must contain the result of operation and the number of steps required with freestyle format as you wish. Test Cases (ignore the input and output format): ``` 81 (+) 31 --> (4 ; 2) 351 (+) 14568 --> (6 ; 3) 21 (*) 111 --> (8 ; 3) 136 (*) 2356 --> (0 ; 2) ``` # General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins the challenge. Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use. * [Standard rules apply](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours. * If possible, your program can properly handle large numbers. If not, that will just be fine. --- [***Let the game begin!!***](http://pre10.deviantart.net/f372/th/pre/i/2013/159/9/4/let_the_game_begin__by_synergy14-d6893ns.jpg) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~33~~ ~~32~~ ~~30~~ 29 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) This extends APL to include the prefix notation `+/A n₁ n₂` and `×/A n₁ n₂`. (In fact, you can use any operation to the left of the `/A`.) Returns a list of {result, repetition count}. ``` A←{(⊃,≢)⍺⍺{∪⍵,⍨⍺⍺⍎¨⍕⊃⍵}⍣≡⍺⍺⍵} ``` > > `A←{` define a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function) in terms of left-hand function `⍺⍺`, and right-hand argument `⍵` > > > > > > > `(⊃,≢)` the first element of, followed by the count of > > > > > > `⍺⍺{` the supplied function (`+/` for sum or `×/` for product) fed to the higher-order function > > > > > > > > > > > > `∪` the unique elements of > > > > > > > > > `⍵,⍨` the argument appended to > > > > > > > > > `⍺⍺` the fed function applied to > > > > > > > > > `⍎¨` the evaluation of each character of > > > > > > > > > `⍕` the character representation of > > > > > > > > > `⊃⍵` the first element of the argument > > > > > > > > > > > > > > > `}⍣≡` applied repeatedly until the result is identical to the argument, beginning with > > > > > > `⍺⍺⍵` the originally fed function (`+/` or `×/`) applied to the original argument > > > > > > > > > `}` [end of higher-order function definition] > > > [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%20A%u2190%7B%28%u2283%2C%u2262%29%u237A%u237A%7B%u222A%u2375%2C%u2368%u237A%u237Ae%A8%u2355%u2283%u2375%7D%u2363%u2261%u237A%u237A%u2375%7D%20%u22C4%20+/A%2081%2031%20%u22C4%20+/A%20351%2014568%20%u22C4%20%D7/A%2021%20111%20%u22C4%20%D7/A%20136%202356&run) (`⍎` has been emulated with `e` for security reasons.) Thanks to @ngn for saving a byte. --- # 0 bytes (in jest) Dyalog APL actually already has full support for Anastasiyan math; instead of `(+)` and `(×)`, it uses `+{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/⍎¨⍕⍵}⍣=⍵⍺⍺⍨⍺}` and `×{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/⍎¨⍕⍵}⍣=⍵⍺⍺⍨⍺}`. Try [`81 +{(⊃,≢)⍺⍺{∪⍵,⍨⍺⍺e¨⍕⊃⍵}⍣≡⍺⍺/⍺⍵} 31`](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%2081%20+%7B%28%u2283%2C%u2262%29%u237A%u237A%7B%u222A%u2375%2C%u2368%u237A%u237Ae%A8%u2355%u2283%u2375%7D%u2363%u2261%u237A%u237A/%u237A%u2375%7D%2031&run) and [`21 ×{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/e¨⍕⍵}⍣=⍵⍺⍺⍨⍺} 111`](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%2021%20%D7%7Bn%u21900%u22C4n%2C%u237A%u237A%7Bn+%u21901%u22C4%u237A%u237A/e%A8%u2355%u2375%7D%u2363%3D%u2375%u237A%u237A%u2368%u237A%7D%20111&run). [Answer] ## Haskell, 108 bytes ``` f=map(read.pure).show g h=(\x->(h.f$last x,length x+1)).takeWhile(>10).iterate(h.f) (a#b)o=g(foldr1 o)$o a b ``` Defines the function `#` which first takes `a` and `b` and then the operator `o`. Fun fact: this works with any operator (actually, any function) you want! [Answer] ## Pyke, 16 bytes ``` RE`DltImbRoKr)oh ``` [Try it here!](http://pyke.catbus.co.uk/?code=RE%60DltImbRoKr%29oh&input=B%0A21%2C+111&warnings=0) ``` RE - evaluate the input as Pyke code - (`B` is product and `s` is sum, the second line is a tuple) ` - i = str(^) ltI ) - if len(i) != 1: mb - map(i, int) R - get the `B` or `s` from input oK - o++ r - goto_start() oh - o++ + 1 ``` Takes multiply as `B` and add as `s`. The two numerical inputs are separated by commas. [Answer] # JavaScript (ES6), 59 Recursive function, the input format is tailored to simplify the recursive call: * operator : '+' or '\*' * operands : array of two values ``` f=(o,v,s=1,t=eval(v.join(o)))=>t>9?f(o,[...t+''],s+1):[t,s] ``` **Test** ``` f=(o,v,s=1,t=eval(v.join(o)))=>t>9?f(o,[...t+''],s+1):[t,s] ;[ [81,'+',31, /* -> */ 4, 2] , [351,'+',14568, /* -> */ 6, 3] , [21,'*',111, /* -> */ 8, 3] , [136,'*',2356, /* -> */ 0, 2] ].forEach(t=>{ var [a,o,b,k1,k2] = t, [r,s]=f(o,[a,b]); console.log(k1==r && k2==s ? 'OK':'KO',a,o,b,'->',r,s) }) ``` [Answer] # Python 2, 60 bytes ``` f=lambda s,c=0:s[1:]and f(min(s).join(`eval(s)`),c+1)or(s,c) ``` Input is a string like `81+31`, output is a tuple of a singleton string and a counter (e.g., `('4', 2)`. Test it on [Ideone](http://ideone.com/uC30St). [Answer] ## Pyth, 16 ``` eJ.uvjhQ`N.vQ)lJ ``` Takes input like `"+ 123 12"` for addition, and `"* 123 12"` for multiplication. Outputs like `result<linefeed>steps`. [Try it here](http://pyth.herokuapp.com/?code=eJ.uvjhQ%60N.vQ%29lJ&input=%22%2B%20123%2012%22&debug=0), or run a [Test Suite](http://pyth.herokuapp.com/?code=eJ.uvjhQ%60N.vQ%29lJ&test_suite=1&test_suite_input=%22%2B%20123%2012%22%0A%22%2B%2081%2031%22%0A%22%2B%20351%2014568%22&debug=0), but note that this relies on eval, so only the addition variant will work in the online interpreter. Multiplication works correctly with the offline interpreter. This uses the cumulative reduction function to create a list of intermediate results, so for `"+ 351 14568"` we get `[14919, 24, 6]`. This works because single digit numbers are a fixed point of the Anastasiya addition and multiplication. Then we just get the last element of the array as well as the length of the array. This will work for arbitrarily large numbers, at least until you run out of memory. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Dj⁹VµÐĿḊĖṪ ``` Input is a pair of numbers and either `+` or `×`. [Try it online!](http://jelly.tryitonline.net/#code=RGrigblWwrXDkMS_4biKxJbhuao&input=&args=MjEsIDExMQ+w5c) or [verify all test cases](http://jelly.tryitonline.net/#code=RGrigblWwrXDkMS_4biKxJbhuaoKw6ciRw&input=&args=WzgxLCAzMV0sIFszNTEsIDE0NTY4XSwgWzIxLCAxMTFdLCBbMTM2LCAyMzU2XQ+KyvDl8OX). ### How it works ``` Dj⁹VµÐĿḊĖṪ Main link. Left argument: [x, y] (integers). Right argument: + or × µÐĿ Repeatedly execute the chain to the left, initially with argument [x, y], then with the previous return value. Stop when the results are no longer unique, and return the array of all intermediate results. D Decimal; convert the integers [x, y] or the return value z to base 10. j⁹ Join, separating by the link's right argument, i.e., '+' or '×'. V Evaluate the result. This casts the previous return value to string, so, e.g., [8, 1, '+', 3, 1] becomes "81+31" before evaluation. Ḋ Dequeue; discard the first intermediate result, i.e., [x, y]. Ė Enumerate; prefix each integer in the array with its 1-based index. Ṫ Tail; extract the last index-value pair. ``` [Answer] # ARM Machine Code, 48 bytes Hex dump: ``` b570 2a00 bf0c 1840 4348 2101 230a e00c 3101 0015 fbb0 f6f3 fb06 0413 2a00 bf0c 192d 4365 0030 d1f5 0028 280a d2f0 bd70 ``` This function doesn't depend any system calls or library functions. This is Thumb-2 code, which is a variable-length instruction encoding (2 or 4 bytes) for 32-bit ARM. Thus, the maximum value it can process is 2^32-1. 2 bytes could be dropped if it didn't conform to the AAPCS (**46 bytes**), since we wouldn't have to stack registers at the beginning. Ungolfed assembly (GNU syntax): ``` .syntax unified .text .global anastasiya .thumb_func anastasiya: @Input: @r0 - First number @r1 - Second number @r2 - 0 for add, 1 for multiply @Output: @r0 - Resultant value @r1 - Number of steps push {r4,r5,r6,lr} cmp r2,#0 ite eq @if r2==0 addeq r0,r0,r1 @r0+=r1 mulne r0,r0,r1 @else r0*=r1 movs r1,#1 @r1 is the number of steps movs r3,#10 b endloop loop: adds r1,r1,#1 @Increment number of steps movs r5,r2 @r5=1 if multiply, 0 if add parseDigits: udiv r6,r0,r3 @r6=r0/r3 mls r4,r6,r3,r0 @r4=r0 - r6*r3 @Last two operations were r4=r0%r3 (r3==10) cmp r2,#0 ite eq @if r2==0 addeq r5,r5,r4 @r5+=r4 mulne r5,r5,r4 @else r5*=r4 movs r0,r6 @r0=r6 (Set r0 to r0/10) bne parseDigits @while (r0!=0) @Now our new total is in r5 movs r0,r5 @Put it in r0 endloop: cmp r0,#10 bhs loop @while (r0 >=10) pop {r4,r5,r6,pc} @Return ``` Testing script in C: ``` #include <stdio.h> unsigned long long anastasiya(unsigned,unsigned,unsigned); int main(void) { unsigned x,y,op; printf("Enter first operand, second operand, and 0 for addition or 1 for multiplication.\n"); scanf("%u%u%u",&x,&y,&op); unsigned long long res = anastasiya(x,y,op); printf("Result = %u, steps = %u\n",(unsigned)res ,(unsigned)(res >> 32)); } ``` [Answer] # R, ~~175~~ ~~167~~ ~~164~~ ~~140~~ ~~134~~ ~~127~~ ~~126~~ 119 bytes ``` function(G,S,D){i=1;O=switch(S,"+"=sum,prod);x=O(G,D);while(x>9){i=i+1;x=O(strtoi(strsplit(paste(x),"")[[1]]))};c(x,i)} ``` **Ungolfed :** ``` f=function(G,S,D) #The function takes : the left operand, the operation symbol (between quote marks) #and then the right operand i=1 #That's the counter O=switch(S,"+"=sum,prod) #`O` takes the value `sum` if `S` matches `+`, `prod` #(which is the next agument) if not. x=O(G,D) #Does the first operation while(nchar(x)>1) #While the number of character of the result #of the operation is not of length 1, i.e., an integer : i=i+1 #Increase the counter x=O(strtoi(strsplit(paste(x),"")[[1]])) #Apply the operation `O` to the first operation and #the eventual subsequent ones c(x,i) #Outputs the result and the counter ``` ~~`ifelse` is back ! *Yeah !*~~ *Nop* **Usage :** ``` Special addition > f(31,"+",81) [1] 4 2 Special multiplication > f(136,"*",2356) [1] 0 2 ``` Thanks a lot to **@plannapus** for golfing out *24* bytes ! *-7* bytes thanks to a good idea from **@Vlo** ! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~20~~ 15 bytes ``` [¼¹iOëP}Dg#S]¾‚ ``` **Explanation** ``` [ Dg# ] # loop until number is single digit ¼ # increase counter ¹iO # if operation is addition, sum list ëP} # else take product of list S # split into a list of digits ¾‚ # pair final number with counter and output ``` Operator is 1 for addition, 0 for multiplication. [Try it online](http://05ab1e.tryitonline.net/#code=W8K8wrlpT8OrUH1EZyNTXcK-4oCa&input=MQpbMTIsMTIzXQ) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 17 bytes ``` +×⁵?µDSP⁵?$ÐĿµL;Ṫ ``` [Try it online!](http://jelly.tryitonline.net/#code=K8OX4oG1P8K1RFNQ4oG1PyTDkMS_wrVMO-G5qg&input=MA&args=ODE+MzE+MQ) Given arguments like `x y 1`, this computes the Anastasiya sum `x (+) y`. Given arguments like `x y 0`, this computes the Anastasiya product `x (*) y`. Output is given as `[number of steps, result]`. [Answer] # R, ~~130~~ 124 chars A somewhat different approach from [@Frédéric](https://codegolf.stackexchange.com/a/90925/6741)'s: ``` f=function(a,f,b){b=c(a,b);n=1;while((m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)))>1){b=d%%10^(1:m)%/%10^(1:m-1);n=n+1};c(d,n)} ``` Indented, with newlines: ``` f=function(a,f,b){ b=c(a,b) # Take both numbers n=1 #Counter while((m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)))>1){ #My own special digit splitter! (d is the result and m is the nb of char of d) b=d%%10^(1:m)%/%10^(1:m-1) n=n+1 } c(d,n) #Print results } ``` Line 4 probably needs more explanations: ``` switch(f,'(+)'=sum,prod) #pick which operator to use switch(f,'(+)'=sum,prod)(b) # apply it to b d<-switch(f,'(+)'=sum,prod)(b) #Saves the result in d nchar(d<-switch(f,'(+)'=sum,prod)(b))#Measures the number of character of d m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)) #Saves it in m (m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)))>1 #Checks if it is more than 1 ``` Test cases: ``` > f(12,"(+)",123) [1] 9 2 > f(12,"(*)",123) [1] 6 5 > f(351,"(+)",14568) [1] 6 3 ``` [Answer] # Octave, 85 bytes ~~MATLAB, 123, 114, 105, 94 bytes~~ Decided to translate this to Octace, to take advantage of the direct indexing, and incrementing capabilitites. Takes the input on the form: `f(a,operator)`, where `a = [number1, number2]`, and `operator==1` gives the product, and `operator==2` gives the sum. ``` function[x,i]=f(a,o) g={@prod,@sum}{o};x=g(a);i=1;while(x=g(num2str(x)-48))>9;i++;end ``` Explanations: `g={@prod,@sum}{o}` : Chooses the appropriate function, product or sum and assigns it to `g` `x=g(a)` takes the sum or product of the inputs `i=1; ... i++` : Incrementer to count the number of steps ``` while(x=g(num2str(x)-48))>9; num2str(x)-48) % turns a number 123 into an array [1 2 3]. g(num2str(x)-48)) % Takes the sum or product of the array x=g(num2str(x)-48)) % Assign that value to the variable x x=g(num2str(x)-48))>9 % Checks if x > 9, continue looping if yes ``` Removed two newlines, a space, and placed both input numbers in a vector instead of separate arguments. This saved 9 bytes, thanks to pajonk! Removed `k=@(x)...` to save another 11 bytes thanks to beaker =) Finally, translated the whole thing to Octave to save another 9 bytes... [Answer] # Java, ~~164~~ ~~159~~ 146 bytes ``` int[]p(int t,int m,String[]d){int r=m;for(String i:d){int x=Integer.decode(i);r=m<1?r+x:r*x;}return r>9?p(++t,m,(r+"").split("")):new int[]{r,t};} ``` First argument is just the counter, always 0 Second argument is method, 0 for ADD and 1 for MULTIPLY. Third argument is an array of Strings, which contains the values to add/multiply. # Ungolfed ``` public static int[] p(int t, int m, String[] d) { int r = m; for (String i : d) { int x = Integer.decode(i); r = m < 1 ? r + x : r * x; } return (r + "").length() > 1 ? p(++t, m, (r + "").split("")) : new int[]{r, t}; } ``` thanks to @Kevin Cruijssen for cutting a few bytes. thanks to @milk for shaving 5 bytes. # Test Program ``` public static final int ADD = 0; public static final int MULTIPLY = 1; public static void main(String[] args) { System.out.println(Arrays.toString(p(0, ADD, new String[]{"12", "123"}))); //9 System.out.println(Arrays.toString(p(0, MULTIPLY, new String[]{"12", "123"}))); //6 } public static int[] p(int t, int m, String[] d) { int r = m; for (String i : d) { int x = Integer.decode(i); r = m < 1 ? r + x : r * x; } return (r + "").length() > 1 ? p(++t, m, (r + "").split("")) : new int[]{r, t}; } ``` [Answer] # Python, ~~160~~ ~~146~~ 129 bytes ``` def r(s): n=str(eval(s));c=0 while n[1:]:exec("n=str(reduce(lambda a,b:a%sb,map(int,list(n))))"%"*+"["+"in s]);c+=1 return n,c ``` Will post an explanation soon. Input is in the form `12+12` or `5*35` (with normal `+` and `*` signs), and assumes that those are the only two operators. It can handle number inputs as large as your computer's memory allows. I'm almost certainly confident that this can be further. **EDIT:** *~~16~~ 31 bytes saved thanks to @Copper.* [Answer] # R, 110 bytes Using @plannapus' splitter. `function(A,F,B){r=Reduce;x=r(F,A,B);y=1;while(x>9){m=nchar(x);x=r(F,x%%10^(1:m)%/%10^(1:m-1));y=y+1};cat(x,y)}` ``` f=function(A,F,B){ r=Reduce # Shortcut for Reduce x=r(F,A,B) # A operator B y=1 # Initiate counter while(x>9) # If number of digits > 2, or number > 9 {m=nchar(x) # Count number of digits x=r(F,x%%10^(1:m)%/%10^(1:m-1)) # @plannapus's splitter, then feed into the A operator B operator C, etc while condition true y=y+1} # Increment counter cat(x,y)} # Print ``` Output ``` > f(136,"*",2356) 0 2 > f(31,"+",81) 4 2 > f(2,"+",3) 5 1 > (function(A,F,B){r=Reduce;x=r(F,A,B);y=1;while(x>9){m=nchar(x);x=r(F,x%%10^(1:m)%/%10^(1:m-1));y=y+1};cat(x,y)})(21,"*",111) 8 3 ``` edit: I can't count. [Answer] # Clojure 126 bytes ``` (defn f [o a b] (loop [n (o a b) c 1] (if (< n 10) [n c] (recur (reduce #(o %1 %2) (map #(- (int %) 48) (str n))) (inc c))))) ``` Function is called like so: ``` (f + 81 31) ``` Here is the code ungolfed: ``` (defn f [o a b] (loop [n (o a b) c 1] (if (< n 10) [n c] (recur (reduce #(o %1 %2) (map #(- (int %) 48) (str n))) (inc c))))) (def test-cases [[+ 81 31] [+ 351 14568] [* 21 111] [* 136 2356]]) (map #(apply f %) test-cases) ;;=> ([4 2] [6 3] [8 3] [0 2]) ``` Bear in mind that Clojure is still new to me, so this is likely not the best solution. The challenge was fun all the same. Additionally, the code ran with very large numbers without any difficulty. [Answer] # [Perl 6](http://perl6.org) 53 bytes ``` {$/=(&^b($^a,$^c),{[[&b]] .comb}...10>*);$/[*-1],+$/} ``` Since `( 12, &[+], 123 )` is acceptable for the input, I can get it down to 53 bytes. ( `&[+]` is short for `&infix:<+>` which is a "reverence" to the numeric infix addition operator ) If the second argument had to be a string `(+)` it would be 87 bytes ``` {my&b=::("&infix:<$^b.substr(1,1)>");$/=(b($^a,$^c),{[[&b]] .comb}...10>*);$/[*-1],+$/} ``` ## Explanation: ``` # bare block lambda with 3 parameters declared using placeholder syntax { # store list into 「$/」 # ( used 「$/」 so that I don't have to declare a variable ) $/ = ( # declare second placeholder parameter, and call it &^b( # with the first and third placeholder parameters $^a, $^c ), # bare block lambda with implicit parameter 「$_」 { # list reduce using the second parameter from outer block [[&b]] # a list of the digits of 「$_」 (implicit method call) .comb } # keep doing that until ... # it produces something smaller than 10 # ( Whatever lambda ) 10 > * ); # returns # final result ( last value from list ) $/[ * - 1 ], # and count of values in list +$/ } ``` ## Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my &anastasiya-math = {$/=(&^b($^a,$^c),{[[&b]] .comb}...10>*);$/[*-1],+$/} my @test = ( ( 81, &[+], 31 ) => (4, 2), ( 351, &[+], 14568 ) => (6, 3), ( 21, &[*], 111 ) => (8, 3), ( 136, &[*], 2356 ) => (0, 2), ); plan +@test; for @test -> $_ ( :key(@input), :value(@expected) ) { cmp-ok anastasiya-math(|@input), &[»==«], @expected; } ``` ## Normal Usage: ``` # override built-in Bag operator 「(+)」 in current lexical scope my &infix:<(+)> = &anastasiya-math.assuming: *, &[+], *; # add a new operator my &infix:<(*)> = &anastasiya-math.assuming: *, &[*], *; say 12 (+) 123; # (9 2) say 12 (*) 123; # (6 5) ``` [Answer] # Python 2, ~~107~~ 97 bytes ``` g=lambda x,o,i=1:x<10and[x,i]or g(eval(o.join(`x`)),o,i+1) lambda a,o,b:g(eval('%s'*3%(a,o,b)),o) ``` An anonymous function that takes input via argument of a first operand `a`, an operator `o` (`'+'` or `'*'`) and a second operand `b`, and returns a list of the form `[result, steps]`. **How it works** The anonymous function creates a string by concatenating the operands with the operator between them, and then evaluates it; this is the first step described in the question. Then, this value and the operator are passed to the recursive function `g`. Here, a counter `i`, which is incremented for every recursive call, is used. If the input is less than `10`, a single digit must have been reached, so this and `i` are returned. If not, the input is converted to a string and each character in this string is joined with the operator, giving the desired calculation, which is then evaluated and passed to the function recursively. [Try it on Ideone](http://ideone.com/rmjobD) [Answer] # Groovy, 102 bytes ``` def p,e,r;p={t,m,d->e=d*.toInteger();r=m<1?e.sum():e.inject{a,b->a*b};r>9?p(++t,m,""+r as List):[r,t]} ``` ### Degolfed ``` def p,e,r p = { t, m, d -> e = d*.toInteger() r = ( m<1 ? e.sum() : e.inject { a, b -> a * b } ) r > 9 ? p(++t, m, "" + r as List) : [r,t] } ``` ### Explanation Based on @Sean Bean 's excellent solution for Java. * `p`: The closure (function, lambda, whatever) that implements the solution * `t`: The current call depth (number of iterations), `p` should always be invoked with `t=1` * `m`: The operation to perform, `0` for "add", `1` for "multiply" * `d`: The list of operands, each operand is a String object * `e`: The elements of `d`, each converted to an Integer * `r`: The sum or product of `e`, depending on the operation `m` * result statement, starting with `r > 9`: + If multi-digit (`r > 9`), reinvoke, incrementing depth `t` and converting `r` to a list of digit strings (and return result). + If single-digit, return `r` and `t` as a list. ### Test Program ``` final ADD = 0 final MULTIPLY = 1 println p(1, ADD, ["12", "123"]) //9, 2 println p(1, MULTIPLY, ["12", "123"]) //6, 5 println p(1, ADD, ["2", "3"]) //5, 1 ``` ### Results ``` [9, 2] [6, 5] [5, 1] ``` [Answer] ## Haskell, ~~76~~ 70 bytes ``` (x#y)f=until(<[10])(\[s,i]->[foldr(f.read.pure)0$show s,i+1])[f x y,1] ``` Returns a two element list with the result and number of steps. Works for arbitrary large numbers. Usage example: `(351#14568)(+)` -> `[6,3]`. Edit: Thanks to @BlackCap for 6 bytes. [Answer] # R, 91 bytes Using @Vlo's code, which makes use of @plannapus's splitter, and some ideas I generated while golfing @Frédéric's answer, this is the shortest R answer yet. (An unusually large number of R answers here today...) ``` function(A,F,B){x=F(A,B);while(x>9){m=nchar(x);x=F(x%%10^(1:m)%/%10^(1:m-1));T=T+1};c(x,T)} ``` Crucially, this requires that the input for the operator be either `sum` for (+) or `prod` for (\*). Under the rules of the challenge, this seems to be okay. With indentation: ``` function(A,F,B){ x=F(A,B); while(x>9){ m=nchar(x); x=F(x%%10^(1:m)%/%10^(1:m-1)); T=T+1 }; c(x,T) } ``` Main differences from @Vlo's answer are: 1. Instead of using `Reduce`, we rely on the input argument being a function, and just call it explicitly. (Yay for functions being first-class objects!) 2. Instead of initializing a new variable as our counter, we abuse R's builtins and use `T`, which evaluates to `TRUE` (aka `1`), but since it's not a reserved variable we can modify it. Thus `T+T` is `2`. So we use that as our counter. 3. Instead of `cat`ing the output, we just return it as a vector with `c`. As well as saving two bytes, the fact that the output is forced into a vector ensures that `T` is of class `numeric`. If we use `cat`, and `T` hasn't been incremented, then we get erroneous output like `1 TRUE`. [Answer] # Ruby, 55 bytes Recursive call. Used to be very different from @edc65's JavaScript answer but as I optimized it eventually became a direct port developed almost independently from their answer, minus one final optimization involving checking the eval'ed result instead of the length of the list of operands being passed in, which allowed me to surpass their byte count. Input is a string representing the operator, and an array containing the operands. [Try it online.](https://repl.it/CrXP/2) ``` f=->o,x,i=1{y=eval x*o;y>9?f[o,y.to_s.chars,i+1]:[y,i]} ``` [Answer] # Perl, 38 bytes Includes +2 for `-ap` Run with the input on STDIN and spaces around the operator: ``` amath.pl <<< "12 + 123" amath.pl <<< "12 * 123" ``` The output is digit and steps separated by `+A` `amath.pl`: ``` #!/usr/bin/perl -ap 1while++$\,$_=eval."+A",s/\B/$F[1]/g ``` If outputting the steps in unary is ok this 35 byte version works better: ``` #!/usr/bin/perl -lap 1while$\.=1,$_=eval,s/\B/$F[1]/g ``` [Answer] ## Mathematica, ~~105~~ 94 bytes *Code.* ``` {x,y}=(c=0;f//.a_:>(c++;t=o@@IntegerDigits@a);{t,c})&/.{{f->#1+#2,o->Plus},{f->#1#2,o->Times}} ``` *Usage.* ``` x[81, 31] (* {4, 2} *) x[351, 14568] (* {6, 3} *) y[21, 111] (* {8, 3} *) y[136, 2356] (* {0, 2} *) ``` *Explanation.* The two functions `x` (for (+)) and `y` (for (\*)) are created at the same time by replacing the parameters `f` and `o` in ``` (c = 0; f //. a_ :> (c++; t = o@@ IntegerDigits@a); {t, c} )& ``` with their appropriate values. For `x`, `f` becomes `#1 + #2` and `o` becomes `Plus`; for `y`, they respectively become `#1 #2` and `Times`. Rewriting the function `x` for the last part of the explanation: ``` x = ( c = 0; #1 + #2 //. a_ :> (c++; t = Plus@@IntegerDigits@a); {t, c} ) &; (* The symbol //. stands for ReplaceRepeated. The rule a_ :> (c++; t = Plus@@IntegerDigits@a) is applied until the result no longer changed. Specifically, the rule increments the counter of 1 at each step (this is c++), then takes the sum of the digits of the previous result (this is Plus@@IntegerDigits@a). The rule stops to apply when the variable t is less than 10. We return the final result and the number of steps with {t, c}. *) ``` [Answer] # Java 7, ~~203~~ ~~195~~ 192 bytes ``` int c=1;String c(long a,long b,int o){return p(((o<1?a+b:a*b)+"",o)+","+c;}long p(String n,int o){long x=o,q;for(String s:n.split("")){q=new Long(s);x=o<1?x+q:x*q}c++;return x<10?x:p(x+"",o);} ``` It uses `long` (maximum value of 263-1). If it would use `int` instead (maximum value of 231-1) it would only be 1 byte less (**191 bytes**): ``` int c=1;String c(int a,int b,int o){return p(((o<1?a+b:a*b)+"",o)+","+c;}int p(String n,int o){int x=o,q;for(String s:n.split("")){q=new Integer(s);x=o<1?x+q:x*q}c++;return x<10?x:p(x+"",o);} ``` It can most likely be golfed a bit more. Having to print the steps as well as the answer for both operators takes some bytes, though.. Uses 0 (for `(+)`) and 1 (for `(*)`). **Ungolfed & test code:** [Try it here.](https://ideone.com/bw0D5Y) ``` class Main{ static int c = 1; static String c(long a, long b, int o){ return p((o < 1 ? a+b : a*b) + "", o) + "," + c; } static long p(String n, int o){ long x = o, q; for(String s : n.split("")){ q = new Long(s); x = o < 1 ? x + q : x * q; } c++; return x < 10 ? x : p(x+"", o); } public static void main(String[] a){ System.out.println(c(81, 31, true)); c = 1; System.out.println(c(351, 14568, true)); c = 1; System.out.println(c(21, 111, false)); c = 1; System.out.println(c(136, 2356, false)); } } ``` **Output:** ``` 4,2 6,3 8,3 0,2 ``` ]
[Question] [ This challenge has two threads. This is the cops' thread. The robbers' thread is located [here](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread). Your challenge is to choose an [OEIS](https://oeis.org) sequence and write two *full programs* in two different languages that produces that nth item in the sequence when given an n via STDIN, or an other forms of standard input, where n is any positive number. However your two programs must be anagrams, meaning each can be rearranged from the other's letters. Programs must output the decimal of the number followed by optional whitespace to STDOUT. Programs may output to STDERR however it should be ignored and if the hidden case does so it must be clearly stated that this is the case. If you wish you may also output by character code. However if you do so in your hidden solution you must state such in the body of your submission. You will then present the OEIS number, the source code for and the name of *one* language it is in. Robbers will crack your submission if they find an anagram of the original submission that runs in a language other than the one you already presented. To crack an answer they must only find ***any*** language and program which produces the sequence and is an anagram of the original, not necessarily the answer the you were thinking about. Thus you are incentivized to make it as hard as possible to find any language that does the task using their list of symbols. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest un-cracked program is the winner. ## Languages Languages will be considered different if the two proposed solutions do not complete the task in both languages. This will include different versions of *the same language* as long as neither the cop's solution or the robber's solution produce the correct output in the other's language. i.e. If the there are two solutions 1 and 2 that are in language A and B respectively solution 2 must not produce the correct output in language A and solution 1 must not produce the correct output in language B. # Safety Once your submission has been uncracked for a week you may post your solution and declare your post safe. If after a week you choose not to post a solution your answer may still be cracked. [Answer] # ~~Python 2, 118 bytes, [A042545](https://oeis.org/A042545)~~ [Cracked](https://codegolf.stackexchange.com/a/99395/12012) ``` i=input();s=1/(801**.5-28);a=[0,1] for p in range(i):a+=[a[-2]+a[-1]*int(s)];s=1/(s-int(s)) print a[i]#,,,.//000fhlmo| ``` I didn't feel like implementing a trivial sequence, so I decided to go with my PPCG user ID. I wrote this in the other language first, which should give you a clue about what that language is, though I'd bet 100 dollars that this will be cracked in a golfing language before it's cracked in the intended other language. **Note:** Due to floating-point precision errors, this is only accurate up to an input of 14. The intended solution is the same way. ## Intended solution, JavaScript (ES7) ``` for(i=prompt(),s=1/(801**.5-28),a=[1,0];i--;s=1/(s-n)) n=s|0,a.unshift(a[1]+a[0]*n); alert(a[0]) //#+2:[]giiiiinnpt ``` Works in pretty much the same way as the Python solution, though the sequence is stored largest-first rather than smallest-first due to the fact that JS does not support negative indexing. [Answer] # Brain-Flak, 24 bytes, [A000290](http://oeis.org/A000290), Safe Yet another square solution. This time there is nothing but parentheses ``` ({(({}[()])()){}[()]}{}) ``` --- The intended solution was in [Brain-Flueue](https://github.com/Wheatwizard/Brain-Flueue), a version of brain-flak that uses queues instead of stacks. The program was: ``` ({(({})[()]){}}{})[()()] ``` The languages are considered distinct because neither of the two programs halt when run in the other language. [Answer] # ~~Python 2, 38 bytes, [A000290](http://oeis.org/A000290)~~ [Cracked by Emigna](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99163#99163) ``` def e(X):return X*X print e(input())## ``` This will probably be very easy to crack. I'm mostly posting this as a starting point. Orignial solution in CJam: ``` ri:XX*e#def ()return X e#pnt (input()) ``` [Answer] # ~~[CJam](https://sourceforge.net/projects/cjam/), 7 bytes, [A005843](http://oeis.org/A005843)~~ [Cracked!](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99198#99198) ``` ri2*e#^ ``` This is a basic `2*n` sequence. Explanation: ``` r e# read input i e# convert to integer 2* e# multiply it by 2 e#^ e# this is a comment that is ignored by the interpreter ``` [Try it online!](http://cjam.tryitonline.net/#code=cmkyKmUjXg&input=MjE) --- # Original Solution, [Carrot](https://github.com/kritixilithos/Carrot) ``` #^i*2er ``` Carrot is an esolang created by me. I have stopped developing it a long time ago. The reason I chose this is because I hoped that it would be hard for other languages to comment out the unnecessary parts of the code. Explanation: ``` #^ This pushes the input to the stack (anything before the ^ is the stack) i Convert stack to integer *2 Multiply it by 2 er These are ignored because they are not Carrot commands Implicit output ``` [Try it online!](http://kritixilithos.github.io/Carrot/) [Answer] # ~~Brain-Flak, 44 bytes, [A000290](http://oeis.org/A000290)~~ [Cracked](https://codegolf.stackexchange.com/a/99166/56656) ``` <({({})({}[()])}{}))()()()turpentine/"*"*4splint> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=PCh7KHt9KSh7fVsoKV0pfXt9KSgpKCkoKXR1cnBlbnRpbmUvIioiKjRzcGxpbnQ-Cg&input=NA&debug=on) --- ## Original solution, Python 2 ``` print(input()**(len(set("{}{}{}[]()<>"))/4)) ``` [Answer] # ~~[2sable](http://github.com/Adriandmen/2sable), 15 bytes, [A000290](http://oeis.org/A000290)~~, [Cracked!](https://codegolf.stackexchange.com/a/99237/31957) Hopping on the same **n2** train :p. ``` *?"!#$&<=@\^{|} ``` [Try it online!](http://2sable.tryitonline.net/#code=Kj8iISMkJjw9QFxee3x9&input=NA) [Answer] # ~~Excel, 12 bytes, [A000012](http://oeis.org/A000012)~~ [Cracked](https://codegolf.stackexchange.com/a/99207/47066) ``` =IF(1=1,1,1) ``` Maybe not the toughest, but a fun one to crack. [Answer] # Python 2, 25 bytes, [A000583](https://oeis.org/A000583), [cracked](https://codegolf.stackexchange.com/a/99278/45941) ``` Y=input("");print`Y**4`,X ``` This program exits with an error after printing the output. --- My hidden code (substantially different from the cracked solution!): ## [Actually](http://github.com/Mego/Seriously), 25 bytes ``` 4,n`*`Y")ii(*nppruttY;="X ``` [Try it online!](http://actually.tryitonline.net/#code=NCxuYCpgWSIpaWkoKm5wcHJ1dHRZOz0iWA&input=NTA) Explanation: ``` 4,n`*`Y")ii(*nppruttY;="X 4,n input, repeat 4 times `*`Y do * until the stack stops changing (fixed-point combinator) ")ii(*nppruttY;="X push this string and immediately pop and discard it ``` [Answer] # Python, 118 bytes, [A042545](https://oeis.org/A042545), Safe ``` i=int(input());s=pow(801.0,0.5);a=[0|0,1] for Moshprtflmah in range(i):s=1./(s%1);a+=[a[-2]+a[-1]*int(s)]; print(a[i]) ``` This time it works in both 2 and 3. And there's no comments! What will you do? Note: As with the old solution, this loses precision after the first 15 terms due to floating-point arithmetic errors. ## Intended solution, JavaScript (ES6) ``` giiiiinnnnprt: i=prompt([n=+2]);s=Math.pow(801,.5);for(a=[1,0];i--;a.unshift(a[1]+a[0]*(s|0)))s=1/(s%1) alert(a[0]) ``` Though I kept several old versions, I somehow managed to lose *this* copy, but fortunately piecing it together from the others wasn't too hard. I see now that I had an extraneous `prt` in both programs that could have been golfed out. Oh well. [Answer] # Python 2, 124 bytes, [A144945](http://oeis.org/A144945), [Safe] Cracking this would have earned you a 500 rep bounty! Too late! > > Number of ways to place 2 queens on an n X n chessboard so that they attack each other. > > > I hope it's not too easy. I arranged my code so the whitespace is clearly visible. Those are spaces and newlines only. *Note: intended solution outputs via character code* ``` n=input();print((3+2)*n*n+~0*6*n+1)*n/3; +6; +7+7+7+7+7+7+7+7+7;+++++++++++++++9+9*9*9 ``` [**Try it online**](https://repl.it/EU0M/1) ### Intended Solution, [Headsecks](http://esolangs.org/wiki/Headsecks): ``` r2=ni***p** ( p((0 ;3+++3;+;/ ) i+++nn +)7 n n+++ 17+~ +)7;97++++7 69+9n+ ++7+n 69 +7+ ++7 **7+++tut ``` This is equivalent to the following BF program: ``` >>,[->>>+>>>+>>>+++++<<<<<<<<<]>>>->>>>>>-<<<[[>+<-]>[>>[<<<+>>+>-]<[>+<-]<-]<<<<]>>+++>[-<-[<+<<]<[+[->+<]<+<<]>>>>>]<<<.,. ``` [Answer] # Fuzzy Octo Guacamole, 26 bytes, [A070627](https://oeis.org/A070627) [Safe] ``` 49++*5^pm#]%:"?:.=:#,|"1:@ ``` Test cases: ``` 1 -> 1 3 -> 23 5 -> 1 ``` Solution: ``` ^::::|*?1=#@]","%.#49++5pm ``` Works in Magistack. [Answer] # ~~Pyth, 75 bytes, [A004526](https://oeis.org/A00526)~~ [Cracked, milk](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99263#99263) More of a playful test than anything, but: ``` /Q/////////////////****22222 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2;;;;; ``` [Try it online!](https://pyth.herokuapp.com/?code=%2FQ%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2a%2a%2a%2a22222+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2%3B%3B%3B%3B%3B&input=129&debug=0) Milk's solution (Convex): ``` 2/Q2 2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2*2*2*; 2*; 2; 2; 2; ``` [Try it online](http://convex.tryitonline.net/#code=Mi9RMiAyLzIvMi8yLzIvMi8yLzIvMi8yLzIvMi8yLzIvMi8yLzIvMioyKjIqOyAyKjsgICAgICAgICAgICAgICAgIDI7IDI7IDI7&input=Nw) Intended solution (///): ``` /*///;2/;// ///22/Q//2;///;//;***2222222222222222222222 ``` [Try it online](http://slashes.tryitonline.net/#code=LyovLy87Mi87Ly8gLy8vMjIvUS8vMjsvLy87Ly8yMjIyMjIyOyoqKjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIgICAgICAgICAgICAgICAgICAgIA&input=) Takes input in the form of 2's before the last semicolon and outputs the correct number of Q's. The sequence is 0-indexed (i.e. 0 is 0, 1 is 0, 2 is 1, ...) Found slight syntactical mistakes in the ///, so edited all solutions. [Answer] # MATL, 7 bytes, [A000217](https://oeis.org/A000217), [cracked](https://codegolf.stackexchange.com/a/99253/36398) ``` :sp{1}x ``` The sequence is `n(n+1)/2` (triangular numbers), starting at input `n=1` as specified by the challenge: `1`, `3`, `6`, `10`, ... (Output for input `0` is not guaranteed to be the same in the two programs). The program in the other language exits with an error (after producing the correct output in STDOUT). [Try it online!](http://matl.tryitonline.net/#code=OnNwezF9eA&input=MTA) ``` : % Push [1 2 ... n], where n is implicit input s % Sum of that array. Gives the desired result p % Product of that. Gives the same number {1} % Push a cell array containing number 1 x % Delete it ``` [Answer] # ~~Python 2, 37 bytes, [A000290](http://oeis.org/A000290)~~ [Cracked](https://codegolf.stackexchange.com/a/99172/47066) ``` print(input()**(1+1)) "'10°3¢','m'" ``` [Answer] # ~~Python 3, 27 bytes, [A000012](https://oeis.org/A000012)~~, [Cracked](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99360#99360) No input this time! ``` if 1: if 1: print( '1' ) ``` The indents are tabs, but not to save bytes - they are required for whitespace. I don't think it needs a TIO link or explanation! (Probably won't take long to crack in some way) Intended answer (Whitespace): ``` -Start- if1:if1:print('1') -End- ``` (Start and end not part of the program) Sorry, I forgot to add that it prints to STDERR: [Try it online!](http://whitespace.tryitonline.net/#code=ICAgCQoJCiAJaWYxOmlmMTpwcmludCgnMScp&input=) [Answer] # [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 11 bytes, [A001844](http://oeis.org/A001844) [Safe!] ``` hha02^d+**+ ``` [A crack that sort-of works is `dh*h++^2*0a`, in Pyth.](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99252#99252) It's not the right output format though. My code is still out there! (and it's not in Pyth) Test Cases: ``` 0 -> 1 1 -> 5 ``` Solution: ``` ^++d0ah*2*h ``` In Jolf. [Answer] # ~~WinDbg, 39 bytes, [A000007](https://oeis.org/A000007)~~ [Cracked by jimmy23013](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99213#99213) ``` ~e.block{j(0>=@$t0)?@$t0+(1<7);??0}t":" ``` The difficult sequence of `0**n`. Input is done by passing a value in the pseudo-register `$t0`. My original solution was C#: ``` @t=>(object)(0<@t?0:1)??"$$700~lk.{}+"; ``` [Answer] # JavaScript ES6, 38 bytes, [A000290](http://oeis.org/A000290), [Cracked](https://codegolf.stackexchange.com/a/99244/31957) ``` J=>eval(Array(J).fill(J).join`+`)|2-2; ``` This square train is pretty nifty, but isn't going anywhere fast. (Get it? *square* train? as in, wheels? no? okay, fine. *critics*.) --- Intended answer: Reticular ([Try it online!](http://reticular.tryitonline.net/#code=aW4ySm87PT5ldmFsKEFycmF5KEopLmZpbGwoSikuamArYCl8LTI&input=Ng)), ``` in2Jo;=>eval(Array(J).fill(J).j`+`)|-2 in take input, convert to number 2J raise to the second power o; output and terminate; ignores following chars ``` [Answer] # ~~[MATL](http://github.com/lmendo/MATL), 13 bytes, [A002275](http://oeis.org/A002275)~~ [Cracked!](https://codegolf.stackexchange.com/a/99226/31716) ``` i:"@ax'1'] v! ``` [Try it online!](http://matl.tryitonline.net/#code=aToiQGF4JzEnXQp2IQ&input=) Explanation: ``` i % Grab input : % Push (range(1,input)) " % For each element in this range: @ % Push it a % Is is truthy? x % Delete it '1' % Push '1' ] % End loop v % Join all of these '1's together ! % Transpose and display ``` [Answer] # ~~[2sable](http://github.com/Adriandmen/2sable), 13 bytes, [A002378](https://oeis.org/A002378)~~, [Cracked!](https://codegolf.stackexchange.com/a/99286/8478) Hoping I didn't miss something. Computes **a(n) = n × (n + 1)**: ``` >*?"!&)<=@\\} ``` --- My version: ``` ?"\>@&*})<\=! ``` Or the unfolded version: ``` ? " \ > @ & * } ) < \ = ! . . . . . . ``` Note that the `>` in the top-left corner is unused (except for the 2sable program). I did this to confuse the robbers (but that obviously didn't work haha). [Try it online!](http://2sable.tryitonline.net/#code=Pio_IiEmKTw9QFxcfQ&input=Ng) [Answer] # 2sable, 15 bytes, [A087156](https://oeis.org/A087156) ``` D1QiA0*<}.;2->> ``` [Try it online](http://2sable.tryitonline.net/#code=RDFRaUEwKjx9LjsyLT4-&input=Nw) The sequence of non-negative numbers, except for 1. [Answer] # [Befunge 93](http://www.quirkster.com/iano/js/befunge.html), 14 bytes, [A121377](https://oeis.org/A121377), [Cracked by milk](https://codegolf.stackexchange.com/a/99398/42854)! ``` &52* %68*+ .@Q ``` Fun fact: The intended solution to this is the first time I've ever used that language. My solution in Pyth. &@ print an error, but that goes to STDERR which according to the OP is ignored. ``` +%Q*5 2*6 8.&@ ``` [Answer] # Python 2, 35 bytes, [A048735](http://oeis.org/A048735), Safe ``` print(lambda u:u&u<<1)(input())>>1 ``` --- The original solution was in my own programming language [Wise](https://github.com/Wheatwizard/Wise). ``` :<<>&>print(lambda uuu1)(input())1 ``` Most of the characters are irrelevant no-ops. The important characters are the first six. `:` creates two copies of the first item on the stack. `<<>` bit shifts twice to the left and once to the right which is equivalent to bit shifting once to the left. `&` takes the bitwise and of the top and second item (the original and the bit shifted copy). Lastly `>` bit shifts once to the right. [Answer] # 05AB1E, 5 bytes, [A000012](https://oeis.org/A000012), Safe ``` $;$1? ``` Sequence of 1's. [Try it online](http://05ab1e.tryitonline.net/#code=JDskMT8&input=ODY) ### Intended Solution: Arcyou ``` 1;$$? ``` [Try it online](http://arcyou.tryitonline.net/#code=MTskJD8&input=NTQ). I couldn't find documentation for this language, so don't have an explanation of how it works exactly. [Answer] # ~~Python 2, 70 Bytes, [A000217](https://oeis.org/A000217)~~ [Cracked!](https://codegolf.stackexchange.com/a/99210/25180) I have a feeling this won't be cracked in the language I used for the other version, we will see :) ``` o=input() v=0 i=1 while o: v+=i i+=1 print v #| d00->1@@@++-^,,[ ``` --- I realized afterwards I had incorrectly obfuscated the code (it doesn't change the posted answer's validity). Here's the code I started with in Haystack: ``` v 0 v 0 i 1 - > d0[v ^-1@+@d+1@?,,o| ``` [Answer] # ~~[05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes, [A000042](http://oeis.org/A000042)~~ [Cracked!](https://codegolf.stackexchange.com/questions/99156/polyglot-anagrams-robbers-thread/99329#99329) ``` 1×,1*-^$) ``` This is the *Unary representation of natural numbers* (OEIS). So if the input was `3`, for example, then output would be `111`. Explanation: ``` # implicit input 1 # pushes 1 to the stack × # pushes "1" × (the input) , # outputs the stack 1*-^$) # irrelevant ``` [Try it online!](http://05ab1e.tryitonline.net/#code=McOXLDEqLV4kKQ&input=Nw) --- # Original Solution, [Carrot](https://github.com/kritixilithos/Carrot) ``` 1^*$-1×^) ``` Explanation ``` 1^ Push "1" to the stack * Multiply the string by $-1 ...the input (as an integer) minus 1 times ×,) Ignored by the interpreter ``` The `*` multiplies the string by `(n+1)` times, so that `a^*3` results in `aaaa` and not `aaa`. So that is why I subtracted `1` from the input. Only now I realise that the `)` has been irrelevant in both the languages :D [Try it online!](http://kritixilithos.github.io/Carrot/) [Answer] # J, 2 bytes, [A000290](http://oeis.org/A000290), [Cracked](https://codegolf.stackexchange.com/a/99379/31957) ``` *~ ``` Well, might as well start going for those two-byters. Yields **n** × **n**, or **n**2. ## ~~intended solution, Jolf, 2 bytes~~ ``` *~ ``` Well. Yeah. This is my own language and I think it works because `~` looks for an extended character, but doesn't find one, so it just ignores it. ¯\\_(ツ)\_/¯ Oops. [Answer] # ~~[ABCR](https://github.com/Steven-Hewitt/ABCR), 24 bytes, [A023443](https://oeis.org/A023443)~~ [Cracked!](https://codegolf.stackexchange.com/a/99394/55696) ``` 70: Quit xi. Classy queue! ``` There's a bunch of no-ops. Calculates `n - 1`. [Answer] # 05AB1E, 8 bytes, [A000042](https://oeis.org/A000042), [Cracked](https://codegolf.stackexchange.com/a/99348/41805) ``` F1}J,(1& ``` Test cases: ``` 1 -> 1 2 -> 11 3 -> 111 ``` [Answer] ## ~~[Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros), 6 bytes, [A000012](https://oeis.org/A000012)~~ [Cracked](https://codegolf.stackexchange.com/a/99468/42545) ``` )49.o( ``` Always outputs `1`. ]
[Question] [ I suddenly really want to play tennis, but alas I do not have a court! Surprise! This is where you come in. You have to print a tennis court for me, but you have to do it in the fewest bytes possible because of confidential reasons. ## Tennis court ``` --------- | | --------- | | | xxxxxxxxx | | | --------- | | --------- ``` ## This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # Python 2, 65 bytes ``` s='-','|'+' '*7,'-','| ','x' for i in s+s[3::-1]:print(i*9)[:9] ``` Flp.Tkc saved a byte. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~29~~ ~~27~~ 26 bytes ``` '-9ש'|ð4׫Dûs®s¨¨ûû'x5×»û ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Jy05w5fCqSd8w7A0w5fCq0TDu3PCrnPCqMKow7vDuyd4NcOXwrvDuw&input=) ``` '-9ש Push "---------" and store it as temporary value '|ð4׫Dûs Push palindromized("| ") = "| |" and push "| " ® Push "---------" again s¨¨û Strip the last 2 characters from "| " and push palindromized("| ") = "| |" û Palindromize last item -> "| | |" 'x5× Push "xxxxx" » Join everything with newlines û Palindromize the result and implicitly display it ``` [Answer] # Python 3 - ~~73~~ 72 bytes ``` d=b,a,c='| |','-'*9,'| | |' print(a,*d,'x'*9,c,a,b,a,sep='\n') ``` **Python 3.6** - 75 bytes ``` x=f"{'-'*9}\n|{' '*7}|\n{'-'*9}\n| | |\n" print(x,'x'*9,x[::-1],sep='') ``` Credit goes to [flp-tkc](https://codegolf.stackexchange.com/users/60919/flp-tkc). Thank you :) [Try here!](https://repl.it/EszP/2) [Answer] # [///](https://esolangs.org/wiki////), ~~64~~ 56 bytes ``` /f/---//e/ //a/fff |ee | fff //d/|e|e| /adxxxxxxxxx da ``` [Try it online!](https://tio.run/nexus/slashes#NcaxDQAxCMXQnilYAHkmJPgzpGB3kivOr/EiIgIad4dEkk23j30HxfRjZJ0/q9y9 "/// – TIO Nexus") Another 56 byte solution: ``` /f/---//e/| //a/fff e | fff //d/ee| /adxxxxxxxxx da ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 25 bytes ``` 9é-ÄÙÒ r|$.4äGMãlr|jj.kÒX ``` [Try it online!](https://tio.run/nexus/v#ASMA3P//OcOpLcOEw5nDkiByfCQuNMOkR03Do2xyfGpqLmvDklj//w "V – TIO Nexus") This should be 23 bytes: ``` 9é-ÄÙÒ r|$.4äMÒXãkr|jj. ``` But I ran into several bugs while creating it. :( [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¡⁵÷ḞȯḤɼ’b4ị“- x|”s5ŒBŒḄY ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4oCcwqHigbXDt-G4nsiv4bikybzigJliNOG7i-KAnC0geHzigJ1zNcWSQsWS4biEWQ&input=)** I had hoped to use the 1,3,1 quarter court repetition, but can't squeeze that into less (a raw version being 28: `“ßṂuB’b4s3x“¢¤¢‘ị“- x|”ŒBŒḄY`). ### How? ``` “¡⁵÷ḞȯḤɼ’b4ị“- x|”s5ŒBŒḄY - Main link: no arguments “¡⁵÷ḞȯḤɼ’ - base 250 number: 375116358919167 b4 - convert to base 4: [1,1,1,1,1,0,2,2,2,2,1,1,1,1,1,0,2,2,2,0,3,3,3,3,3] ị“- x|” - index into character list "- x|" (1-based): "-----| -----| |xxxxx" s5 - split into chunks of length 5: ["-----","| ","-----","| |","xxxxx"] ŒB - bounce (vectorises): ["---------","| |","---------","| | |","xxxxxxxxx"] ŒḄ - bounce (non-vectorising version): ["---------","| |","---------","| | |","xxxxxxxxx","| | |","---------","| |","---------"] Y - join with line feeds: - implicit print ``` [Answer] # J, ~~70~~ ~~54~~ ~~51~~ 50 bytes *Saved a byte thanks to Zgarb!* ``` 9 9$'-| |-| | |x| | |'#~3 9 1 7{~4#.inv 1851926050 ``` Some standard compression technique, using a compressed RLE. ``` 9 9$'-| |-| | |x| | |'#~3 9 1 7{~4#.inv 1851926050 --------- | | --------- | | | xxxxxxxxx | | | --------- | | --------- ``` [Answer] # Ruby, 60 bytes ``` -4.upto(4){|i|puts''.rjust(9,%w{x |%3s - |%7s -}[i.abs]%'')} ``` **Ungolfed** ``` -4.upto(4){|i| #iterate -4 to 4. puts''.rjust(9, #Print the null string right justified to length 9 padded by repititions of %w{x |%3s - |%7s -}[i.abs]%'') #the string from the %w{} array modified like sprintf by the % operator } #so that %Ns is replaced by N spaces. ``` [Answer] # bash/Unix tools, ~~58~~ 57 bytes ``` dc<<<4o16i3FFFFp20002prp20202p15555pszpszfp|tr 0-3 ' x|-' ``` Only four characters other than newline appear in the desired output, allowing each line to be coded as a base-4 number. These numbers are then written in hexadecimal in the script, for brevity. The Unix calculator dc is used both for the base-16 to base-4 conversion and for stack manipulation to allow easy repetition of lines in the right places. *Edit:* Shaved one byte off by swapping two of the base-4 digits used to code characters, permitting the tr command to be one byte shorter than the previous version. [Answer] ## JavaScript, 85 bytes ``` console.log('---| ---| |xxx| |---| ---'.replace(/(.)((.).)/g,'$1$3$3$2$3$3$3$1\n')) ``` [Answer] ## JavaScript (ES6), ~~86~~ ~~84~~ ~~83~~ 81 bytes *Saved 2 bytes, thanks to Neil* ``` a=`--------- `;a+=`| | `+a;b=`| | | `;console.log(a+b+`xxxxxxxxx `+b+a) ``` ### Alternate method #1, 93 bytes ``` console.log('01232101242421512424210123210'.replace(/./g,n=>`- | x`[n].repeat('911739'[n]))) ``` ### Alternate method #2, 86 bytes Suggested by Neil: ``` console.log(`-${s=` | - | `}x${s}-`.replace(/.*/g,s=>s.repeat(9).slice(-9))) ``` ### Alternate method #3, 91 bytes A recursive approach: ``` console.log((f=(n,c=`xxxx | | | --------- | | `[n]||'-')=>~n--?c+f(n)+c:'x')(43)) ``` [Answer] # [SOGL 0.5](https://github.com/dzaima/SOGL), ~~24~~ ~~23~~ 20 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) (non-competing) ``` -9*"D√⅜‘⁴"Hοr‘¹q x9*o± ``` Explanation: ``` "'|⁶.f,‘9n_h¹q x9*o± "'|⁶.f,‘ pushes "------------------| || | |" 9n splits into chunks of 9 stack: [["---------","---------","| |","| | |"]] _ puts all the contents of the array into the stack stack: ["---------","| |","---------","| | |"] h swaps the 2nd from top with 3rd from top ¹ turns back into array stack: [["---------","| |","---------","| | |"]] q outputs the array without popping it from stack x push "x" stack: [["---------","| |","---------","| | |"], "x"] 9* repeat it 9 times stack: [["---------","| |","---------","| | |"], "xxxxxxxxx"] o output that ± reverse the array implicitly output the reversed array ``` So how does the compressed string work? The string converted from base250 to binary is `1000000100111110010100001110100000001100010001` and approxametally what it does: ``` 100 boxstring (a custom dictionary string with chars " -/\|_\n") 000010 choose only the "-"s 01111 with length of 15+(different chars used)+2 = 18 chars there is only 1 char type, so results in "------------------" 100 another boxsting 101000 choosing " " and "|" 01110 with length of 14+(different chars used)+2 = 18 chars 100000001100010001 the data; 0 = " " and 1 = "|" has "------------------" and "| || | |" and just joins them together ``` non-competing, because language postdates the challenge. And this challenge is only a day old. I knew I should've put something up yesterday. I did this as a test for my language and it ended up too good not to post. Pretty sure this is golfable more too. [Answer] # [///](https://esolangs.org/wiki////), 59 bytes ``` /_/--------- //s/ /_|ss | _|s|s| xxxxxxxxx |s|s| _|ss | _ ``` [Try it online!](https://tio.run/nexus/slashes#@68fr68LA1z6@sX6CgoK@vE1xcUKNVxACgi5KmCAC8KHyf7/DwA "/// – TIO Nexus") [Outgolfed...](//ppcg.lol/a/103607/41024) [Answer] # Javascript (ES6), 86 bytes: ``` a=`--------- | | ---------`;b=`| | | `;console.log(a+` `+b+`xxxxxxxxx `+b+a) ``` Test here: ``` a=`--------- | | ---------`;b=`| | | `;console.log(a+` `+b+`xxxxxxxxx `+b+a) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 26 bytes ``` '-5ש'|4úD®sÂðñ)í€û»'x5×»û ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Jy01w5fCqSd8NMO6RMKuc8OCw7DDsSnDreKCrMO7wrsneDXDl8K7w7s&input=) [Answer] # PHP, ~~66~~ 62 bytes This is the original answer (66 bytes): ``` <?=$a="--------- | | --------- | | | xxxx",x,strrev($a); ``` It generates a notice because of the unknown constant `x`. The notice can be suppressed by setting `error_reporting=0` in `php.ini` or in the command line: ``` $ php -d error_reporting=0 tennis.php ``` The last line of the output doesn't end with a newline character. --- The updated answer (62 bytes), improving an improvement suggested by @Titus: ``` <?=$a=($b="--------- | ")." | $b| | xxxx",x,strrev($a); ``` Run it without a configuration file (it defaults with `error_reporting=0` this way): ``` $ php -n tennis.php ``` Both versions of the code contain literal new lines embedded in the string (1 byte shorter than `\n`) and cannot we unwrapped. [Answer] # PHP, 72 bytes ``` <?=$a="--------- ",$b="| | $a",$c="| | | ","xxxxxxxxx $c$a$b"; ``` I almost hate it when it´s shorter like this than with calculating a little. [Answer] # Ruby, 52 bytes ``` puts [b=[a=?-*9,"|%8s"%?|,a],c="| | |",?x*9,c,b] ``` Using the double simmetry, the lines are: `0-1-0 / 2-3-2 / 0-1-0`, the loop can be easily unrolled and the nested list is flattened on output. [Answer] ## Pyke, ~~28~~ ~~26~~ 25 bytes ``` \|ddsssd7*.X--||"R\x5*nJs ``` [Try it here!](http://pyke.catbus.co.uk/?code=%5C%7Cddsssd7%2a.X--%7C%7C%22R%5Cx5%2anJs) ``` d7* - " " * 7 .X--||" - grid(^, corners="-", sides="-", left="|", right="|") \|dds - "| " s - palindromise(^) s - palindromise(^) \x5* - "x" * 5 nJ - "\n".join(^) s - palindromise(^) ``` [Answer] # 05AB1E, 25 bytes ``` '-9ש'|ð4׫û®…| ûû'x5×»û ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/#MlEsh) Explanation: ``` '-9× # Push "---------" © # Store in register_c '|ð4׫ # Push "| " û # Palindromize, giving "| |" ® # Retrieve from register_c …| # Push "| " ûû # Palindromize twice, giving "| | |" 'x5× # Push "xxxxx" » # Join by newlines û # Palindromize # Implicit print ``` [Answer] # Vim, 32 bytes ``` 9i-^[Y3pO||^[7i ^[YGPkP4lr|YpO^[9ix^[ ``` This will print the tennis court into a vim buffer. `^M` represents the Enter key (0x0d) and `^[` is the Escape key (0x1b). You can run these keystrokes/code by saving them to a file and running ``` vim -s <filename> -u NONE ``` ### Printing to stdout If it has to be printed to stdout instead, you could save the buffer to a file (I used "a") and use whichever shell `vim` is set to use (I used `bash`) as well as the `cat` program in order to print the tennis court to stdout (51 bytes): ``` 9i-^[Y3pO||^[7i ^[YGPkP4lr|YpO^[9ix^[:w!a|sil !cat %^M:q^M ``` It's the same as the earlier version but with `:w!a|sil !cat %^M:q^M` added onto the end [Answer] ## J, 36 bytes ``` 9$'-'([,(' '4}]),[,],'x',:])9$'| ' ``` This works on the REPL, which is the standard way of using J: ``` 9$'-'([,(' '4}]),[,],'x',:])9$'| ' --------- | | --------- | | | xxxxxxxxx | | | --------- | | --------- ``` With **41 bytes**, I can print the result to STDOUT: ``` echo 9$'-'([,(' '4}]),[,],'x',:])9$'| ' ``` [Try it online!](https://tio.run/nexus/j#@5@anJGvYKmirquuEa2joa6gblIbq6kTrROro16hrmMVqwmUq1FQUFD//x8A "J – TIO Nexus") ## Explanation I construct the tennis court one row at a time. ``` 9$'-'([,(' '4}]),[,],'x',:])9$'| ' 9$'| ' The string repeated to length 9: y = '| | |' '-'( ) Apply this verb to x = '-' and y: 'x',:] y with a row of 'x'-chars above it. This is a 2x9 matrix, and "," now works by prepending new rows to it. ], Prepend another y. [, Prepend x, which is repeated to a row of length 9. (' '4}]), Prepend y with 4th character replaced by a space. [, Prepend x again. Now we have this 6x9 matrix: --------- | | --------- | | | xxxxxxxxx | | | 9$ Repeat it to have 9 rows. ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~67~~ 66 bytes ``` ($a='-'*9) ($b="| |") $a ($c="| "*2+"|") 'x'*9 $c $a $b $a ``` [Try it online!](https://tio.run/nexus/powershell#@6@hkmirrquuZanJpaGSZKtUowABNUqaXCqJQLFkiJiSlpG2EkhQvQKomEslGSSrkgQk//8HAA "PowerShell – TIO Nexus") Just some string multiplication, setting variables, and ensuring they're encapsulated in parens to place copies on the pipeline. The default `Write-Output` at program completion gives us newlines between for free. *Thanks to @ConnorLSW for saving an obvious byte.* [Answer] # [Canvas](https://github.com/dzaima/Canvas), 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` A←⁹w5+7q⁴‟5n┼ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjIxJXUyMTkwJXUyMDc5JXVGRjU3JXVGRjE1KzcldUZGNTEldTIwNzQldTIwMUYldUZGMTUldUZGNEUldTI1M0M_,v=8) [Answer] # Python 2, 75 bytes ``` a,b,c='-'*9,'| |','| | |' for e in[a,b,a,c,'x'*9,c,a,b,a]:print e ``` Uses variables borrowed from @GurupadMamadapur Alternative also for 75 ``` a,b,c='-'*9,'| |','| | |' print'\n'.join([a,b,a,c,'x'*9,c,a,b,a]) ``` [Answer] # Emacs, ~~43~~ 35 keystrokes `M-9` `x` `RET` : nine x's, return `C-SPC` : set mark `|` `M-3` `SPC` `|` `M-3` `SPC` `|` `RET` : pipe, three spaces, pipe, three spaces, pipe, return `M-9` `-` `RET` : nine hyphens, return `|` `M-7` `SPC` `|` `RET` : pipe, seven spaces, pipe, return `M-9` `-` `RET` : nine hyphens, return `C-x` `C-x` : exchange point and mark, selecting region `M-w` : copy region `C-p` : previous line `C-y` : yank copied text `M-x` `rev-r` `RET` : execute `reverse-region` command [Answer] # Lua, 82 Bytes. ``` y=[[--------- | | --------- ]]z="| | |\n"io.write(y,z,"xxxxxxxxx\n",z,y) ``` I tried many methods, and yet this one proved the victor. [Answer] # [Pushy](https://github.com/FTcode/Pushy), 33 bytes This question had 33 upvotes, and there were 33 answers, so I just had to post a 33 byte solution... ``` 9:45;T`| `wT`| |`4dT5:120;w" ``` [**Try it online!**](https://tio.run/nexus/pushy#@29pZWJqHZJQowAECeUQRk2CSUqIqZWhkYF1udL//wA) --- ## Explanation The code can be split into several parts, to make it easier to understand. The first part works like so: ``` 9:45; \ Push the char '-' 9 times T \ Push 10, which is a linefeed `| ` \ Push these charcodes ``` The stack is now: ``` --------- | ``` The mirror operator, `w`, then mirrors the whole stack, producing: ``` --------- | | --------- ``` Then: ``` T \ Push a linefeed `| |` \ Push these chars 4d \ Copy the last 4 characters T \ Push a linefeed 5:120; \ Push the char 'x', 5 times ``` The stack is now beginning to look like the tennis court: ``` --------- | | --------- | | | xxxxx ``` To finish it, we use the mirror operator `w` once more, which reflects this string to produce the full tennis court. ``` --------- | | --------- | | | xxxxxxxxx | | | --------- | | --------- ``` All that's left now is to print, which is done by the `"` character. [Answer] **Unix Shell; using dc and tr; 55 Bytes:** ( Optimization of Mitchell Spector solution ) ``` dc<<<4o16i3FFFFp20002prp20202p15555psrfrp|tr 0-3 ' x|-' ``` **Others Solutions : Using sed; 81 Bytes;** ``` echo "---| ---| |xxx| |---| ---"|sed "s/\(.\)\(.\)\(.\)/\1\2\2\2\3\2\2\2\1\n/g" ``` **Using dc in function : 88 Bytes** ``` b(){ dc<<<2o16i1${1}p|tr '01' ' '$2;};(b FF -;b 01 \|;b FF -;b 11 \|)>f;cat f;b FF X;tac f ``` **or** ``` b(){ echo "obase=2;$1"|bc|tr '01' ' '$2;};(b 511 -;b 257 \|;b 511 -;b 273 \|)>f;cat f;b 511 X;tac f ``` **Using bc in function : 99 Bytes** ``` b(){ echo "obase=2;$1"|bc|tr '01' ' '$2;};(b 511 -;b 257 \|;b 511 -;b 273 \|)>f;cat f;b 511 X;tac f ``` [Answer] # Powershell, 56 bytes ``` (('-'*9),'| |'+'-'*9+'| | |'+'x'*9)[0..4+3..0] ``` Explanation: straightforward half-of-the-court # Alternative, 68 bytes ``` ('-----','| '+'-'*5+'| |'+'x'*5)[($r=0..4+3..0)]|%{-join$_[$r]} ``` Explanation: quarter-of-the-court uses the same indexes for both row and column display ]
[Question] [ Write a program (or function) (let's call it P1), that when run, outputs another program P2 of the same language and exactly 1 byte longer than P1. Program P2 when run, should output a 3rd program P3 that's 1 byte longer than P2. P3 must output a program P4 that's one byte longer than P3, etc. The same for P5, P6, ..., P∞. The program chain should go indefinitely, or to a place where the interpreter can't handle anymore (but must remain as a theoretically valid program in the language) # Rules * Standard loopholes forbidden * All programs in the chain should be in one language * No input is given. Output goes to stdout or function return value * The program must end after a period of time. A program that stops generating output after a certain time spot but never terminates does not qualify The shortest program P1 in bytes in each language wins! [Answer] # JavaScript (ES6), ~~14~~ 12 bytes -2 bytes thanks to @Shaggy ``` f=_=>"f=_"+f ``` ## Testing snippet ``` s=`f=_=>"f=_"+f`; for(i=10;i--;s=eval(s)()) o.innerText+=s+"\n"; ``` ``` <pre id=o></pre> ``` [Answer] # [7](https://esolangs.org/wiki/7), 4 bytes of ASCII ``` 1603 ``` [Try it online!](https://tio.run/##M///39DMwPj/fwA "7 – Try It Online") I know that 7 isn't normally encoded in ASCII, but this time it's a more convenient encoding so that we're adding 1 byte with each run, not 3 bits. I'm also not sure whether this counts as cheating or not. (It's usual to be unclear whether or not a 7 quine is cheating, as it straddles the borderline in a number of ways.) You can make a decent argument that the `0` encodes the `6`, but in general it's unclear where the resulting characters "come from" in 7 because it has so many, fairly bizarre, implicit behaviours. This program prints itself with `1` appended, and will do so even if you append a number of `1`s to it. Here's a commented debug trace of `160311`: ``` || 160311 Initial data ||; initial program 160311 ||7 60311 1 command = append 7 to data |1 0311 6 command = escape from the last | onwards (7 escapes to 1) |16e77 0311 commands = append 6e77 to data |16e77 16e77 Implicit (program is empty): copy data past last | to program |16e777 6e77 1 command = append 7 to data 71603111 e77 6 command = escape from the last | onwards 71603111 e77 e7 command = output in same encoding as the source ``` (There are no `|` left in the program, so `e` will immediately quit the program as a side effect, meaning that the final `7`s never run). The basic confusion about where all the characters are coming from is that most commands in 7 just produce data when run, and then `6` attempts to reconstruct a sequence of commands that would produce the given fragment of data; this often ends up close to, but not identical to, the original. (For quining purposes, you normally write a 7 program in such a way that the result will be almost the same, normally differing in leading or trailing `7`s.) So for example, the `1` in the data becomes `716`, which is the easiest way to append `1` to the current data string. We originally produced it with `16`, a different (but similar) character sequence, destructively removing one of the `|` markers the data started with. (I guess perhaps the best argument that this isn't a literal-only quine is that the output is different from the input!) [Answer] # [Haskell](https://www.haskell.org/), ~~74~~ 66 bytes EDIT: * -2 bytes by H.PWiz by using `<>`, then -6 by moving the `(10*)<$>`. This now uses the newly free `<>` operator (`Semigroup` multiplication, requires GHC 8.4 to work without an import.) ``` main=putStr$fst<>show$(10*)<$>("main=putStr$fst<>show$(10*)<$>",1) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqgXnJqbmV6UX1qgoWFjp6n5PzcxM8@2oLQkuKRIJa24xMauOCO/XEXD0EBL00bFTkMJv7ySjqHm//8A "Haskell – Try It Online") (Cheats with an import since TIO doesn't have GHC 8.4 yet.) # How it works * `main=putStr$` is boilerplate to output the following string value. * `fst<>show` is a function that takes a tuple, and returns a string consisting of the first element of the tuple concatenated with the tuple's string representation. I.e. ``` (fst<>show)(s,t) = fst(s,t)<>show(s,t) = s++show(s,t) ``` * `(10*)<$>` multiplies the *last* element of the following tuple by 10, adding a digit `0` to its string representation. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~134~~ 132 bytes Slight reworking of the canonical C quine. Dreadfully long. ``` x;*s="x;*s=%c%s%c;main(i){for(i=__LINE__;i--;puts(&x));printf(s,34,s,34);}";main(i){for(i=__LINE__;i--;puts(&x));printf(s,34,s,34);} ``` [Try it online!](https://tio.run/##S9ZNT07@/7/CWqvYVglMqiarFqsmW@cmZuZpZGpWp@UXaWTaxsf7ePq5xsdbZ@rqWheUlhRrqFVoaloXFGXmlaRpFOsYm@iACE3rWiWydf7/DwA "C (gcc) – Try It Online") [Answer] ## [Fission 2](https://github.com/C0deH4cker/Fission), 7 bytes ``` '!+OR!" ``` [Try it online!](https://tio.run/##S8ssLs7MzzP6/19dUds/SFHp/38A "Fission 2 – Try It Online") [The standard Fission quine](https://codegolf.stackexchange.com/a/50968/8478), but with an extra `!` that prints an additional 0x01 at the beginning of the code on each iteration. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes ``` (f=(x)->print1("(f="f")("1x")"))(1) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/XyPNVqNCU9euoCgzr8RQQwnIV0pT0tRQMqxQ0lTS1NQw1Pz/HwA "Pari/GP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 38 bytes ``` s="print's=%r;exec s'%(s+'#')";exec s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWqaAoM69EvdhWtcg6tSI1WaFYXVWjWFtdWV1TCSrA9f8/AA "Python 2 – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 420 bytes ``` ->+++>>+++>+>++>+++>+>+>+++>>>>>>>>>>>>>>>>>>>>+>+>++>+++>++>>+++>+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+>+>>+++>>+++>>>>>+++>+>>>>>>>>>++>+++>+++>+>>+++>+++>+>++>>+++>+>+++>+>++>+++>>>+>+>++>+++>+>+>>+++>>>>>>>+>+>>>+>+>++>+++>+++>+>>+++>>>+++>+>++>+++>++>>+>+>++>+++>+>+>>+++>>>>>+++>+>>>>>++>+++>+++>+>>+++>>>+++>+>+++>+>>+++>>+++>>++[[>>+[>]++>++[<]<-]>+[>]<+<+++[<]<+]>>->[>]++++>++[[<++++++++++++++++>-]<+++++++++.<]>. ``` [Try it online!](https://tio.run/##hU9BCsNACHzQsHmBzEfEQ1oolEAOhbx/m7qtWROSuiA6O47j7TU@58dyn2otBEBP68OvaOgxelaM/QvnxBpH0lwIBjHsRNUtzi7YyX5XZZcdI1@Jc6HN35XM7i5Adc1K8wEVk2LeCwQNgJGFTmkk/fykYLENG8Q41PoG "brainfuck – Try It Online") This is a modification on the "standard" [BrainFuck quine](https://github.com/jaburns/brainfuckToC/blob/master/quine.b), with a `.` at the end that tacks on an extra `.` each iteration. The quine itself encodes Brainfuck characters as a stack of hex digits: specifically, the hex digits of `c-0x2b`, which conveniently are the following: ``` +: 0x00 -: 0x02 [: 0x30 ]: 0x32 <: 0x11 >: 0x13 ,: 0x01 .: 0x03 ``` The encoding covers two snippets of code: `>++[[>>+[>]++>++[<]<-]>+[>]<+<+++[<]<+]>>->[>]++++>++` pushes the encoding of the encoding itself, and `[[<++++++++++++++++>-]<+++++++++.<]` walks the stack and prints everything. [Answer] # [Dirty](https://github.com/Ourous/dirty), 9 bytes ``` '"n[!]a!␛ ``` [Try it online!](https://tio.run/##S8ksKqn8/19dKS9aMTZR8dGE2f//AwA "Dirty – Try It Online") ``` ' start and end a string literal " push a literal ' n remove newlines [!] print the string a push the alphabet ! print the first character ␛ end the program ``` **If source-code reading is allowed:** # [Dirty](https://github.com/Ourous/dirty), 8 bytes ``` Q[!]W33! ``` [Try it online!](https://tio.run/##S8ksKqn8/z8wWjE23NhY8f9/AA "Dirty – Try It Online") **Explained:** ``` Q push the source code [!] print each character W clear the now-empty stack 33! print an exclaimation mark ``` **Might be valid:** # [Dirty](https://github.com/Ourous/dirty), 4 bytes ``` Q[‼] ``` [Try it online!](https://tio.run/##S8ksKqn8/z8w@lHDntj//wE "Dirty – Try It Online") It prints the source code with a trailing newline. (And a bunch of spaces, due to a bug. It works the same without them though.) Note that it only works in the native character set, and not when you use the UTF8 front-end - so to try it on TIO you need to replace the character it outputs between the `[]`s with `‼`, which is the UTF8 equivalent for what it's printing. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 9 bytes ``` {'.~1'}.~ ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v1pdr85QvVav7v9/AA "GolfScript – Try It Online") # [CJam](https://sourceforge.net/p/cjam), 9 bytes ``` {"_~1"}_~ ``` [Try it online!](https://tio.run/##S85KzP3/v1opvs5QqTa@7v9/AA "CJam – Try It Online") I'm posting both of these solutions in the same answer, since they're just trivial variations of each other and work in exactly the same way. They're both based on the common GolfScript quine `{'.~'}.~` (or `{"_~"}_~` in CJam), which is described in more detail e.g. in [this previous answer of mine.](https://codegolf.stackexchange.com/questions/21831/program-that-creates-larger-versions-of-itself-quine-variant/21876#21876) The only difference is that this variant appends a `1` byte to the end of its output. As it happens, any string of `1`s (or any other integer literal without leading zeros) is itself a trivial quine in both GolfScript and CJam, so any ones already present at the end of the code above will simply be copied verbatim to the output. Since GolfScript (and CJam) use arbitrary-length integers, this will work for arbitrarily long programs, at least as long as the computer running the code has enough memory to store it. [Answer] # Java 8, ~~162~~ 146 bytes ``` v->{String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s).replaceAll(%1$c1+$%1$c,%1$c%1$c);}"+1;return s.format(s,34,s).replaceAll("1+$","");} ``` [Try it online.](https://tio.run/##jU9Ni8IwEL37K4ZgIcEaKHorLuwP0Iuwl8VDjFFS07RkpoVF@tu7E@xlbwvzwcy8x7zXmNFsu97F5vacbTCIcDQ@vlYAPpJLd2MdnPIIcKbk4wOs/Or8DUZV83bi5EAy5C2cIMIB5nH78VrAeBB/psIWWFRru6nq5GhIEVDfu9Qaklju9iUqnVwf@OtnCDIjq806tzKXnKqexP/YgqmiFIIZc/3W2Q/XwDoXuWP20bJd@db3fTFqsfqD5FrdDaR7vpCM2so4hKAW19P8Cw) [Try the first output program](https://tio.run/##jU9Ni8IwEL37K4ZgIcEaKHorLuwP0Iuwl8VDjFFS07RkpoVF@tu7E@xlbwvzwcy8x7zXmNFsu97F5vacbTCIcDQ@vlYAPpJLd2MdnPIIcKbk4wOs/Or8DUZV83bi5EAy5C2cIMIB5nH78VrAeBB/psIWWFRru6nq5GhIEVDfu9Qaklju9iUqnVwf@OtnCDIjq806tzKXnKqeKvE/umCuKIVgyly/hfbDNbDQRe@YjbTsV74Ffl@MWrz@ILlWdwPpni8ko7YyDiGoxfY0/wI); [Try the second output program](https://tio.run/##jU9Na8MwDL3vVwjTgE1Tg9luoYP9gPZS2KXs4LnucOs4wVICo@S3pzLNpbeCPpD0HnrvYke76XqfLqfr7KJFhJ0N6fYGEBL5fLbOw76MAAfKIf2Bk99dOMGoGt5OnBxIloKDPSTYwjxuPm8LGLfiaapchZVZubVpsqchJ0B97nJrSWL9/lGj0tn3kb9@xSgL0qxXpdWllFTNZIx4jS@YLGohmDM3D6X98BtZ6SJ4LE5aNiwfCo8/Vi1m/5F8q7uBdM8Xkkk7mYYY1eJ7mu8); [Try the third output program](https://tio.run/##jU9Na8MwDL3vVwjTgE1Tg9luoYP9gPZS2KXs4LnucOs4wVICo@S3pzLNpbeCPpD0JL13saPddL1Pl9N1dtEiws6GdHsDCIl8PlvnYV9KgAPlkP7Aye8unGBUDXcndjYkS8HBHhJsYR43n7cFjFvxVFWuwsqs3No02dOQE6A@d7m1JLF@/6hR6ez7yF@/YpQFadarkuoSiqtmMsaI1w4I3ha1ELw0Nw@q/fAbmerCeCxSWlYsHxSPP1Ytav@RfKu7gXTPE5JJO5mGGNUifJrv). **Explanation:** ``` v->{ // Method with empty unused parameter and String return-type String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s).replaceAll(%1$c1+$%1$c,%1$c%1$c);}" // The unformatted source code +1; // Plus a random digit (1 in this case) return s.format(s,34,s) // Create the quine .replaceAll("1+$","");} // Then remove any trailing 1s ``` [quine](/questions/tagged/quine "show questions tagged 'quine'")-part: * The `String s` contains the unformatted source code. * `%s` is used to input this String into itself with the `s.format(...)`. * `%c`, `%1$c` and the `34` are used to format the double-quotes. * `s.format(s,34,s)` puts it all together Challenge part: * `+1` adds a 1 to both the unformatted and formatted program. * `.replaceAll("1+$","");}`: Because we only want to increase the program byte-count by one instead of two, we remove any trailing 1s before returning. [Answer] # [Jstx](https://github.com/Quantum64/Jstx), 4 [bytes](https://quantum64.github.io/Jstx/codepage) ``` £↕♣: ``` [Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.2/JstxGWT.html?code=wqPihpXimaM6) [Answer] # [><>](https://esolangs.org/wiki/Fish), 9 bytes ``` #o<:}-1:" ``` [Try it online!](https://tio.run/##S8sszvj/XznfxqpW19BK6f9/AA "><> – Try It Online") Variation on a classic ><> quine, which simply adds another dupe command to copy the `#` in the front. [Answer] ## [Perl 5](https://www.perl.org/), 32 bytes ``` $_=q{say"\$_=q{$_ };eval"};eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rawujixUikGzFKJ56q1Ti1LzFGCUFz////LLyjJzM8r/q/ra6pnYGgAAA "Perl 5 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), ~~76~~ ~~72~~ 61 bytes ``` Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]]",Repr[x+sp]] ``` [Try it online!](https://tio.run/##SywpSUzOSP3/P6AoM69E0S2/KDexJLrCylYJXUC1WCcotaAoukK7uCA2VgmZw/X/PwA "Attache – Try It Online") Standard quine which adds a space to the end of `x` after each iteration. First few iterations: ``` Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]]",Repr[x+sp]] ``` ``` Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]] ",Repr[x+sp]] ``` ``` Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]] ",Repr[x+sp]] ``` etc. ### Attache, 72 bytes ``` y:=1Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x] ``` [Try it online!](https://tio.run/##SywpSUzOSP3/v9LK1jCgKDOvRNEtvyg3sSS6wspWCSioWowuqlqsU6llaKATlFpQpFgRq4TC4/r/HwA "Attache – Try It Online") This is simply a variation of the standard format quine, with a variable `y` that is set to `10*y` after each iteration The first few iterations: ``` y:=1Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x] ``` ``` y:=10Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x] ``` ``` y:=100Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x] ``` etc. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 6 bytes ``` "'<S@> ``` [Try it online!](https://tio.run/##KyrNy0z@/19J3SbYwe7/fwA "Runic Enchantments – Try It Online") > > This one was weird. All I had to do was remove a `~` from the original quine [found by Jo King](https://codegolf.stackexchange.com/a/172877/47990). > > > Every additional run appends another `<` to the end, e.g.: > > > > ``` > "'<S@><<<<<<<<< > > ``` > > All of which do nothing. > > > Direct copy of [this answer](https://codegolf.stackexchange.com/a/179913/47990) on a related challenge. It just so happened to already grow by 1 byte every iteration (strong argument for this challenge being a duplicate of that one or vice versa). [Answer] # [Swift 4](https://developer.apple.com/swift/), 89 bytes ``` let(a,b)=(";print(\"let(a,b)=\\((a,b+\"-\"))\"+a)", "");print("let(a,b)=\((a,b+"-"))"+a) ``` Includes a trailing newline [Try it online!](https://tio.run/##Ky7PTCsx@f8/J7VEI1EnSdNWQ8m6oCgzr0QjRgkuFhOjAWJoxyjpxihpasYoaSdqKukoKClpQtUiKYWoVNIFqgMp4/r/HwA "Swift 4 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 88 bytes ``` main=putStr$snd(span(<'m')s)++show s;s='#':"main=putStr$snd(span(<'m')s)++show s;s='#':" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIpTgvRaO4IDFPw0Y9V12zWFNbuzgjv1yh2LrYVl1Z3UqJFLX//wMA "Haskell – Try It Online") Grows by prepending `#` to the data string. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 33 bytes ``` f\ @(-> ol) ["f\ ";f;";f1";#0];f1 ``` An interesting variant on the normal quine that appends a 1 after each iteration. Progression: ``` f\ @(-> ol) ["f\ ";f;";f1";#0];f1 f\ @(-> ol) ["f\ ";f;";f1";#0];f11 f\ @(-> ol) ["f\ ";f;";f1";#0];f111 ... ``` # Explanation ``` f\ @ #. Sets f to a function that does the following: (-> ol) [ #. Output each: "f\ "; #. String for declaration of f f; #. Formatted representation of f's function ";f1"; #. String for call of f #0 #. Argument passed into f ];f1 #. Call f with 1 as the argument ``` One of the interesting parts of this quine is that Wonder can work with numbers of arbitrary precision, so the progression won't break after a certain amount of ones. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~20~~ 18 bytes ``` "34s+cTZL"34s+cTZL ``` [Run and debug it](https://staxlang.xyz/#c=%2234s%2BcTZL%2234s%2BcTZL&a=1) Generates an extra space before the 2nd quotation mark every iteration. ## Explanation Uses the program `"34s+cTZL "34s+cTZL` to explain. ``` "34s+cTZL "34s+cTZL "34s+cTZL " String literal 34s+ Prepend a double quote, Now the string is `"34s+cTZL ` cT Copy and trim trailing spaces Z Put a 0 under the top of stack Stack now (from top to bottom): `["34s+cTZL,0,"34s+cTZL ]` L Collect all elements on stack, from bottom to top Implicit output, 0 is converted to space. ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 7 bytes ``` ":r2ssH ``` [Try it online!](https://tio.run/##S8/PScsszvj/X8mqyKi42OP/fwA "Gol><> – Try It Online") [Try it online!!](https://tio.run/##S8/PScsszvj/X8mqyKi42MPj/38A "Gol><> – Try It Online") [Try it online!!!](https://tio.run/##S8/PScsszvj/X8mqyKi42MPD4/9/AA "Gol><> – Try It Online") This is a simple variation of the regular [Gol><> quine](https://codegolf.stackexchange.com/a/160994/78410) but adds a copy of `H` each time it's run. Since the `H` command halts the program, additional `H` at the end does not change the behavior. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 89 bytes ``` var s="var s={0}{1}{0}+8;Write(s.Trim('8'),(char)34,s);"+8;Write(s.Trim('8'),(char)34,s); ``` Inspired by Kevin Cruijssen's answer. [Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSW0L6/CizJJUjWK9kKLMXA11C3VNHY3kjMQiTWMTnWJNayWCKv7/BwA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` “⁾;⁶;ØV” ṘV ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//4oCc4oG@O@KBtjvDmFbigJ0g4bmYVv// "Jelly – Try It Online") [Answer] ## ColdFusion, 277 bytes ``` <cfset u=Chr(34)><cfset q="<cfset u=Chr(34)><cfset q=%s%s%s><cfoutput>%screateObject(%sjava%s,%sjava.lang.String%s).format(q,[u,q,u,Chr(35),u,u,u,u,Chr(35)])%s</cfoutput> "><cfoutput>#createObject("java","java.lang.String").format(q,[u,q,u,Chr(35),u,u,u,u,Chr(35)])#</cfoutput> ``` This is a trivial modification of [my ColdFusion quine](https://codegolf.stackexchange.com/a/159608/9365) which adds a newline each extra time it's called. Tested locally on lucee-express-5.2.6.60 [Answer] ## Windows Batch, ~~38~~ 36 bytes ``` echo|set/p"=q">q&copy/b/y %0+q %0 :: ``` This code creates a file called "q", containing the letter 'q', and then appends it to the original file. Note that "::" is an alias for "rem" that does not require an additional space. Saved 2 bytes thanks to user3493001. [Answer] # [T-SQL](https://www.microsoft.com/sql-server), 175 bytes ``` DECLARE @ VARCHAR(MAX)='DECLARE @ VARCHAR(MAX)=*SET @=TRIM(REPLACE(@,0x2a,CHAR(39)+@+CHAR(32)+CHAR(39)))PRINT @'SET @=TRIM(REPLACE(@,0x2a,CHAR(39)+@+CHAR(32)+CHAR(39)))PRINT @ ``` First I wrote an SQL quine, then I modified it to add an extra space (somewhat inspired by [this answer](https://codegolf.stackexchange.com/a/159477/78876)). [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~22~~ 19 bytes ``` r:#,_ #;'D2/'<,,@;" ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//8vslLWiVdQtlZ3MdJXt9HRcbBW@v8fAA "Befunge-98 (PyFunge) – Try It Online") Adds a < before the last " every generation. [Answer] ## [Jstx](https://github.com/Quantum64/Jstx), 4 bytes ``` £↕☺V ``` [Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.2/JstxGWT.html?code=wqPihpXimLpW) ## Explanation Verbose code: ``` meta.source Push the source load 1 Push 1 string.concat Concatenate source with 1 Implicit output ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 71 bytes ``` #define a(b)*s=#b;b a(main(){printf("#define a(b)*s=#b;b\na(%s;)",s);}) ``` Every iteration adds a semicolon after the closing brace of the main function. [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIVEjSVOr2FY5yTqJK1EjNzEzT0OzuqAoM68kTUMJi6KYvEQN1WJrTSWdYk3rWs3///8lp@Ukphf/1y0HAA "C (gcc) – Try It Online") ]
[Question] [ ## Introduction Suppose you have a ruler with numbers from **0** to **r-1**. You place an ant between any two of the numbers, and it starts to crawl erratically on the ruler. The ruler is so narrow that the ant cannot walk from one position to another without walking on all the numbers in between. As the ant walks on a number for the first time, you record it, and this gives you a permutation of the **r** numbers. We say that a permutation is *antsy* if it can be generated by an ant in this way. Alternatively, a permutation **p** is antsy if every entry **p[i]** except the first is within distance 1 from some previous entry. ## Examples The length-6 permutation ``` 4, 3, 5, 2, 1, 0 ``` is antsy, because **3** is within distance 1 of **4**, **5** is within distance 1 of **4**, **2** is within distance 1 from **3**, **1** is within distance 1 from **2**, and **0** is within distance 1 from **1**. The permutation ``` 3, 2, 5, 4, 1, 0 ``` is not antsy, because **5** is not within distance 1 of either **3** or **2**; the ant would have to pass through **4** to get to **5**. ## The task Given a permutation of the numbers from **0** to **r-1** for some **1 ≤ r ≤ 100** in any reasonable format, output a truthy value if the permutation is antsy, and a falsy value if not. ## Test cases ``` [0] -> True [0, 1] -> True [1, 0] -> True [0, 1, 2] -> True [0, 2, 1] -> False [2, 1, 3, 0] -> True [3, 1, 0, 2] -> False [1, 2, 0, 3] -> True [2, 3, 1, 4, 0] -> True [2, 3, 0, 4, 1] -> False [0, 5, 1, 3, 2, 4] -> False [6, 5, 4, 7, 3, 8, 9, 2, 1, 0] -> True [4, 3, 5, 6, 7, 2, 9, 1, 0, 8] -> False [5, 2, 7, 9, 6, 8, 0, 4, 1, 3] -> False [20, 13, 7, 0, 14, 16, 10, 24, 21, 1, 8, 23, 17, 18, 11, 2, 6, 22, 4, 5, 9, 12, 3, 15, 19] -> False [34, 36, 99, 94, 77, 93, 31, 90, 21, 88, 30, 66, 92, 83, 42, 5, 86, 11, 15, 78, 40, 48, 22, 29, 95, 64, 97, 43, 14, 33, 69, 49, 50, 35, 74, 46, 26, 51, 75, 87, 23, 85, 41, 98, 82, 79, 59, 56, 37, 96, 45, 17, 32, 91, 62, 20, 4, 9, 2, 18, 27, 60, 63, 25, 61, 76, 1, 55, 16, 8, 6, 38, 54, 47, 73, 67, 53, 57, 7, 72, 84, 39, 52, 58, 0, 89, 12, 68, 70, 24, 80, 3, 44, 13, 28, 10, 71, 65, 81, 19] -> False [47, 48, 46, 45, 44, 49, 43, 42, 41, 50, 40, 39, 38, 51, 37, 36, 52, 35, 34, 33, 32, 53, 54, 31, 30, 55, 56, 29, 28, 57, 58, 59, 60, 27, 26, 61, 25, 62, 63, 64, 65, 66, 67, 24, 23, 22, 21, 68, 69, 20, 19, 18, 17, 70, 71, 16, 15, 72, 73, 74, 75, 76, 14, 13, 12, 77, 11, 10, 9, 8, 78, 7, 79, 80, 6, 81, 5, 4, 3, 82, 2, 83, 84, 1, 85, 86, 87, 0, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] -> True ``` Fun fact: for **r ≥ 1**, there are exactly **2r-1** antsy permutations of length **r**. [Answer] ## Pyth, 7 bytes ``` /y+_QQS ``` [Try it online.](http://pyth.herokuapp.com/?code=%2Fy%2B_QQS&input=%5B0%5D%0A%5B0%2C%201%5D%0A%5B1%2C%200%5D%0A%5B0%2C%201%2C%202%0A%5B0%2C%202%2C%201%5D%0A%5B2%2C%201%2C%203%2C%200%5D%0A%5B3%2C%201%2C%200%2C%202%5D%0A%5B1%2C%202%2C%200%2C%203%5D%0A%5B2%2C%203%2C%201%2C%204%2C%200%5D%0A%5B2%2C%203%2C%200%2C%204%2C%201%5D%0A%5B0%2C%205%2C%201%2C%203%2C%202%2C%204%5D%0A%5B6%2C%205%2C%204%2C%207%2C%203%2C%208%2C%209%2C%202%2C%201%2C%200%5D%0A%5B4%2C%203%2C%205%2C%206%2C%207%2C%202%2C%209%2C%201%2C%200%2C%208%5D%0A%5B5%2C%202%2C%207%2C%209%2C%206%2C%208%2C%200%2C%204%2C%201%2C%203%5D&test_suite=1&test_suite_input=%5B0%5D%0A%5B0%2C%201%5D%0A%5B1%2C%200%5D%0A%5B0%2C%201%2C%202%5D%0A%5B0%2C%202%2C%201%5D%0A%5B2%2C%201%2C%203%2C%200%5D%0A%5B3%2C%201%2C%200%2C%202%5D%0A%5B1%2C%202%2C%200%2C%203%5D%0A%5B2%2C%203%2C%201%2C%204%2C%200%5D%0A%5B2%2C%203%2C%200%2C%204%2C%201%5D%0A%5B0%2C%205%2C%201%2C%203%2C%202%2C%204%5D&debug=1) (Only small test cases are included due to exponential run-time.) Outputs 2 for Truthy, 0 for Falsey. ``` / Count the number of occurences of S the sorted input (implicit Q) y in the order-preserved power set +_QQ of the input prepended by its reverse ``` In other words, ``` lambda l: subseq(sorted(l), concat(reverse(l), l)) ``` where `subseq` outputs whether the elements of the first list appear in order in the second list, not necessarily adjacent. The `subseq` is done in Pyth by taking all subsets of the second list, which keep the order of the elements, and counting the number of occurrences of the first list. This takes exponential time. Why does this work? For a permutation to be antsy, stepping from 0 to n-1 must consist of going only left, then going only right. This is because the elements greater than the first element must increase left to right, and those less than it must decrease left to right. ``` [2, 3, 1, 4, 0] ^ ^ 0 ^ 1 2 ^ 3 ^ 4 ``` If we mirror the list by putting a reversed copy to its left, this walk now only goes right. ``` [0, 4, 1, 3, 2, 2, 3, 1, 4, 0] ^ | 0 ^ | 1 | ^ | 2 ^ | 3 ^ | 4 ``` Conversely, any rightward of this mirror list corresponds to a left-then-right walk of the original list. This rightward just is a sorted subsequence of 0 to n-1. In an antsy list, this sorted subsequence is unique, except for an arbitrary choice between the two adjacent copies of the original first element. [Answer] ## Haskell, 46 bytes ``` (%)=scanl1 f l=zipWith(+)(min%l)[0..]==max%l ``` Checks whether the vector difference of the running maxima and the running minima is [0,1,2,3...]. ``` l = [2, 3, 1, 4, 0] scanl1 max l = [2, 3, 3, 4, 0] scanl1 min l = [2, 2, 1, 1, 0] difference = [0, 1, 2, 3, 4] ``` Zgarb saved 2 bytes with `(%)=scanl1`. [Answer] # JavaScript (ES6), 45 ``` a=>a.every((v,i)=>a[v]=!i|a[v-1]|a[v+1],a=[]) ``` I thought it's too simple to need as explanation, but there is a trick, and just in case, here is my first version, pre-golf ``` a => { k = []; // I'll put a 1 in this array at position of each value // that I find scanning the input list return a.every((v,i) => { // execute for each element v at position i // the index i is needed to manage the first iteration // return 1/true if ok, 0/false if not valid // .every will stop and return false if any iteration return falsy k[v] = 1; // mark the current position if ( i == 0 ) { // the first element is always valid return true; } else { return k[v-1] == 1 // valid if near a lesser value || k[v+1] == 1; // or valid if near a greater value } }) } ``` Note: in the golfed code `a` is used instead of `k`, as I need no reference to the original array inside the `every` call. So I avoid to pollute the global namespace reusing the parameter **Test** ``` antsy= a=>a.every((v,i)=>a[v]=!i|a[v-1]|a[v+1],a=[]) var OkAll=true ;`[0] -> True [0, 1] -> True [1, 0] -> True [0, 1, 2] -> True [0, 2, 1] -> False [2, 1, 3, 0] -> True [3, 1, 0, 2] -> False [1, 2, 0, 3] -> True [2, 3, 1, 4, 0] -> True [2, 3, 0, 4, 1] -> False [0, 5, 1, 3, 2, 4] -> False [6, 5, 4, 7, 3, 8, 9, 2, 1, 0] -> True [4, 3, 5, 6, 7, 2, 9, 1, 0, 8] -> False [5, 2, 7, 9, 6, 8, 0, 4, 1, 3] -> False [20, 13, 7, 0, 14, 16, 10, 24, 21, 1, 8, 23, 17, 18, 11, 2, 6, 22, 4, 5, 9, 12, 3, 15, 19] -> False [34, 36, 99, 94, 77, 93, 31, 90, 21, 88, 30, 66, 92, 83, 42, 5, 86, 11, 15, 78, 40, 48, 22, 29, 95, 64, 97, 43, 14, 33, 69, 49, 50, 35, 74, 46, 26, 51, 75, 87, 23, 85, 41, 98, 82, 79, 59, 56, 37, 96, 45, 17, 32, 91, 62, 20, 4, 9, 2, 18, 27, 60, 63, 25, 61, 76, 1, 55, 16, 8, 6, 38, 54, 47, 73, 67, 53, 57, 7, 72, 84, 39, 52, 58, 0, 89, 12, 68, 70, 24, 80, 3, 44, 13, 28, 10, 71, 65, 81, 19] -> False [47, 48, 46, 45, 44, 49, 43, 42, 41, 50, 40, 39, 38, 51, 37, 36, 52, 35, 34, 33, 32, 53, 54, 31, 30, 55, 56, 29, 28, 57, 58, 59, 60, 27, 26, 61, 25, 62, 63, 64, 65, 66, 67, 24, 23, 22, 21, 68, 69, 20, 19, 18, 17, 70, 71, 16, 15, 72, 73, 74, 75, 76, 14, 13, 12, 77, 11, 10, 9, 8, 78, 7, 79, 80, 6, 81, 5, 4, 3, 82, 2, 83, 84, 1, 85, 86, 87, 0, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] -> True` .split`\n`.forEach(row => { var rowElements = row.match(/\w+/g), expected = rowElements.pop()=='True', input = rowElements.map(x => +x), result = antsy(input), ok = result == expected; OkAll = OkAll && ok; console.log(ok?'OK':'KO', input+' -> '+result) }) console.log(OkAll ? 'All passed' : 'Failed') ``` [Answer] ## Python 2, 49 bytes ``` f=lambda l:l==[]or max(l)-min(l)<len(l)*f(l[:-1]) ``` Checks whether each prefix of the list contains all numbers between its min and max inclusive. It does so by checking if the difference of the max and min is less than its length. --- **54 bytes:** ``` f=lambda l:1/len(l)or-~l.pop()in[min(l),max(l)+2]*f(l) ``` Checks if the last element is either one less than the min of the other elements, or one more than their max. Then, removes the last element and recurses. On a single-element list, outputs True. This can also be checked via an amusing but longer list comprehension. ``` lambda l:all(l.pop()in[min(l)-1,max(l)+1]for _ in l[1:]) ``` I'd like to use the inequality `min(l)-2<l.pop()<max(l)+2`, but the `pop` needs to happen first. Using a program to output via error code would likely be shorter. [Answer] ## Mathematica, 42 bytes ``` !MatchQ[#,{a__,b_,___}/;Min@Abs[{a}-b]>1]& ``` Uses pattern matching to try and find a prefix `a` whose maximum difference from the next element `b` is greater than `1` (and negating the result of `MatchQ`). [Answer] # Perl, ~~39~~ ~~38~~ 35 bytes Includes +1 for `-p` Give sequence on STDIN: ``` antsy.pl <<< "2 1 3 0" ``` `antsy.pl`: ``` #!/usr/bin/perl -p s%\d+%--$a[$&]x"@a"=~/1 /%eg;$_++ ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 11 bytes ``` &-|R1=a4L)A ``` [Try it online!](http://matl.tryitonline.net/#code=Ji18UjE9YTRMKUE&input=WzQsIDMsIDUsIDIsIDEsIDBd) Or [verify all test cases](http://matl.tryitonline.net/#code=YAomLXxSMT1hNEwpQQpEVA&input=WzBdClswLCAxXQpbMSwgMF0KWzAsIDEsIDJdClswLCAyLCAxXQpbMiwgMSwgMywgMF0KWzMsIDEsIDAsIDJdClsxLCAyLCAwLCAzXQpbMiwgMywgMSwgNCwgMF0KWzIsIDMsIDAsIDQsIDFdClswLCA1LCAxLCAzLCAyLCA0XQpbNiwgNSwgNCwgNywgMywgOCwgOSwgMiwgMSwgMF0KWzQsIDMsIDUsIDYsIDcsIDIsIDksIDEsIDAsIDhdCls1LCAyLCA3LCA5LCA2LCA4LCAwLCA0LCAxLCAzXQpbMjAsIDEzLCA3LCAwLCAxNCwgMTYsIDEwLCAyNCwgMjEsIDEsIDgsIDIzLCAxNywgMTgsIDExLCAyLCA2LCAyMiwgNCwgNSwgOSwgMTIsIDMsIDE1LCAxOV0KWzM0LCAzNiwgOTksIDk0LCA3NywgOTMsIDMxLCA5MCwgMjEsIDg4LCAzMCwgNjYsIDkyLCA4MywgNDIsIDUsIDg2LCAxMSwgMTUsIDc4LCA0MCwgNDgsIDIyLCAyOSwgOTUsIDY0LCA5NywgNDMsIDE0LCAzMywgNjksIDQ5LCA1MCwgMzUsIDc0LCA0NiwgMjYsIDUxLCA3NSwgODcsIDIzLCA4NSwgNDEsIDk4LCA4MiwgNzksIDU5LCA1NiwgMzcsIDk2LCA0NSwgMTcsIDMyLCA5MSwgNjIsIDIwLCA0LCA5LCAyLCAxOCwgMjcsIDYwLCA2MywgMjUsIDYxLCA3NiwgMSwgNTUsIDE2LCA4LCA2LCAzOCwgNTQsIDQ3LCA3MywgNjcsIDUzLCA1NywgNywgNzIsIDg0LCAzOSwgNTIsIDU4LCAwLCA4OSwgMTIsIDY4LCA3MCwgMjQsIDgwLCAzLCA0NCwgMTMsIDI4LCAxMCwgNzEsIDY1LCA4MSwgMTldCls0NywgNDgsIDQ2LCA0NSwgNDQsIDQ5LCA0MywgNDIsIDQxLCA1MCwgNDAsIDM5LCAzOCwgNTEsIDM3LCAzNiwgNTIsIDM1LCAzNCwgMzMsIDMyLCA1MywgNTQsIDMxLCAzMCwgNTUsIDU2LCAyOSwgMjgsIDU3LCA1OCwgNTksIDYwLCAyNywgMjYsIDYxLCAyNSwgNjIsIDYzLCA2NCwgNjUsIDY2LCA2NywgMjQsIDIzLCAyMiwgMjEsIDY4LCA2OSwgMjAsIDE5LCAxOCwgMTcsIDcwLCA3MSwgMTYsIDE1LCA3MiwgNzMsIDc0LCA3NSwgNzYsIDE0LCAxMywgMTIsIDc3LCAxMSwgMTAsIDksIDgsIDc4LCA3LCA3OSwgODAsIDYsIDgxLCA1LCA0LCAzLCA4MiwgMiwgODMsIDg0LCAxLCA4NSwgODYsIDg3LCAwLCA4OCwgODksIDkwLCA5MSwgOTIsIDkzLCA5NCwgOTUsIDk2LCA5NywgOTgsIDk5XQ). ### Explanation This computes a matrix of all pairwise absolute differences and keeps the upper triangular part. The result is true iff there is at least a 1 value in all columns except the first. ``` &- % All pairwise differences | % Absolute value R % Upper triangular part 1= % Does each entry equal 1? a % Logical "or" along each column 4L) % Remove first value A % Logical "and" of all results ``` [Answer] # R, ~~72~~ ~~64~~ 60 bytes ``` v=scan();for(i in seq(v))T=c(T,diff(sort(v[1:i])));all(T==1) ``` A permutation is antsy if and only if all its left subpermutations are continuous (i.e. have difference one when sorted). ~~If input is guaranteed to have length more than one, then we can replace `1:sum(1|v)` with `seq(v)`, which saves four bytes.~~ The `seq(v)` in the if condition behaves differently when the input is of length one --- it generates the sequence `1:v` instead of `seq_along(v)`. However, fortunately, the output turns out to be `TRUE` in this case, which is the desired behaviour. The same also happens for zero-length input. In R, `T` is a preset variable equal to `TRUE` (but R allows you to redefine it). `TRUE` is also deemed to be equal to `1`. Thanks to @Billywob for some helpful improvements to the original solution. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes ``` Âìæ¹{¢O ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4LDrMOmwrl7wqJP&input=WzIsIDMsIDEsIDQsIDBd) or as a [modified test suite](http://05ab1e.tryitonline.net/#code=fHZ5I8Kpw4LDrMOmwq57wqJPLA&input=MCAxCjEgMAowIDEgMgowIDIgMQoyIDEgMyAwCjMgMSAwIDIKMSAyIDAgMwoyIDMgMSA0IDAKMiAzIDAgNCAx). **Explanation** Uses the process described by [xnor in his brilliant Pyth answer](https://codegolf.stackexchange.com/a/97230/47066). Returns 2 for truthy instances and 0 for falsy. ``` Âì # prepend a reversed copy of input to input æ # take powerset ¹{ # push a sorted copy of input ¢ # count occurances of sorted input in powerset O # sum occurances (which for some reason is needed, feels like a bug) ``` [Answer] ## Perl, 63 bytes Note that [@Gabriel Banamy](https://codegolf.stackexchange.com/users/60884/gabriel-benamy) came up with a shorter (55 bytes) [answer](https://codegolf.stackexchange.com/a/97259/55508). But I think this solution is still interesting, so I'm posting it. The bytes count includes 62 bytes of code and `-n` flag. ``` s/\d+/1x($&+1)/ge;/ 1(1*)\b(?{$.&=$`=~m%\b(11)?$1\b%})^/;say$. ``` To run it : ``` perl -nE 's/\d+/1x($&+1)/ge;/ 1(1*)\b(?{$.&=$`=~m%\b(11)?$1\b%})^/;say$.' <<< "3 2 5 4 1 0" ``` **Short explanations** : converts each number `k` to the unary representation of `k+1` (that `+1` is needed so the `0`s don't get ignored). Then for each number `k+1` (expressed in unary as `1(1*)`), we look if either `k` (`$1` holds `k`) or `k+2` (which is then `11$1`) are present in the preceding string (referenced by `$-backtick`). If no, then we set `$.` to zero. At then end we print `$.` which will be `1` if we never set it to zero, or zero otherwise. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) ~~302 264~~ 256 Bytes Thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) for saving 46 bytes ``` ([]){{}({}<>)<>([])}{}<>(({}))([]){{}({}<>)<>([])}{}<>(({}<>))<>(()){{}(({})<(({})<>[({})]<>(())){((<{}{}>))}{}{{}({}<><{}>)(<>)}{}<>({}<<>(({})<>[({})<>(())]){((<{}{}>))}{}{{}({}<><{}>)(<>)}{}<>>)<>>[({})](<()>)){{}{}(<(())>)}{}}([][()(())]){((<{}{}>))}{} ``` The top of the stack will be a 1 for truthy and a 0 for falsy. Truthy: [Try it Online!](http://brain-flak.tryitonline.net/#code=KFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-KCh7fSkpKFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-KCh7fTw-KSk8PigoKSl7e30oKHt9KTwoKHt9KTw-Wyh7fSldPD4oKCkpKXsoKDx7fXt9PikpfXt9e3t9KHt9PD48e30-KSg8Pil9e308Pih7fTw8Pigoe30pPD5bKHt9KTw-KCgpKV0peygoPHt9e30-KSl9e317e30oe308Pjx7fT4pKDw-KX17fTw-Pik8Pj5bKHt9KV0oPCgpPikpe3t9e30oPCgoKSk-KX17fX0oW11bKCkoKCkpXSl7KCg8e317fT4pKX17fQ&input=NDcgNDggNDYgNDUgNDQgNDkgNDMgNDIgNDEgNTAgNDAgMzkgMzggNTEgMzcgMzYgNTIgMzUgMzQgMzMgMzIgNTMgNTQgMzEgMzAgNTUgNTYgMjkgMjggNTcgNTggNTkgNjAgMjcgMjYgNjEgMjUgNjIgNjMgNjQgNjUgNjYgNjcgMjQgMjMgMjIgMjEgNjggNjkgMjAgMTkgMTggMTcgNzAgNzEgMTYgMTUgNzIgNzMgNzQgNzUgNzYgMTQgMTMgMTIgNzcgMTEgMTAgOSA4IDc4IDcgNzkgODAgNiA4MSA1IDQgMyA4MiAyIDgzIDg0IDEgODUgODYgODcgMCA4OCA4OSA5MCA5MSA5MiA5MyA5NCA5NSA5NiA5NyA5OCA5OQ) Falsy: [Try it Online!](http://brain-flak.tryitonline.net/#code=KFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-KCh7fSkpKFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-KCh7fTw-KSk8PigoKSl7e30oKHt9KTwoKHt9KTw-Wyh7fSldPD4oKCkpKXsoKDx7fXt9PikpfXt9e3t9KHt9PD48e30-KSg8Pil9e308Pih7fTw8Pigoe30pPD5bKHt9KTw-KCgpKV0peygoPHt9e30-KSl9e317e30oe308Pjx7fT4pKDw-KX17fTw-Pik8Pj5bKHt9KV0oPCgpPikpe3t9e30oPCgoKSk-KX17fX0oW11bKCkoKCkpXSl7KCg8e317fT4pKX17fQ&input=MzQgMzYgOTkgOTQgNzcgOTMgMzEgOTAgMjEgODggMzAgNjYgOTIgODMgNDIgNSA4NiAxMSAxNSA3OCA0MCA0OCAyMiAyOSA5NSA2NCA5NyA0MyAxNCAzMyA2OSA0OSA1MCAzNSA3NCA0NiAyNiA1MSA3NSA4NyAyMyA4NSA0MSA5OCA4MiA3OSA1OSA1NiAzNyA5NiA0NSAxNyAzMiA5MSA2MiAyMCA0IDkgMiAxOCAyNyA2MCA2MyAyNSA2MSA3NiAxIDU1IDE2IDggNiAzOCA1NCA0NyA3MyA2NyA1MyA1NyA3IDcyIDg0IDM5IDUyIDU4IDAgODkgMTIgNjggNzAgMjQgODAgMyA0NCAxMyAyOCAxMCA3MSA2NSA4MSAxOQ) The idea is to hold the minimum and maximum number that the ant has visited in the off stack. Then compare each number to both of those and update the appropriate one. If the next number is not 1 less than the min or 1 more than the max, break out of the loop and return false. --- **Brief Explanation:** ``` ([]) # duplicate the bottom element by {{}({}<>)<>([])}{}<> # reversing everything onto the other stack (({}))([]) # duplicating the top element {{}({}<>)<>([])}{}<> # and reversing everything back (({}<>))<> # copy the top element to the other stack (push twice) (()){{} # push a 1 so the loop starts, and repeat until the top # two elements are equal (({})< # hold onto the top element to compare later (({})<>[({})]<>(())) # push a 0 if diff with the top of the other stack is +1 {{}({}<><{}>)(<>)}{} # logical not (the previous line pushed a 1 as the second # element already) {{}({}<><{}>)<>(<()>)}{} # replace the top of the other stack with this element if # the logical not gave us 1 <>({}<<> # take the minimum off the other stack temporarily (({})<>[({})<>(())]) # push a 0 if diff with the top of the other stack is -1 {((<{}{}>))}{} # logical not (the previous line pushed a 1 as the second # element already) {{}({}<><{}>)(<>)}{} # replace the top of the other stack with this element if # the logical not gave us 1 <>>)<> # put the minimum on back on >) # put the element you were comparing back on [({})](<()>)){{}{}(<(())>)}{} # push 1 or 0 for not equal to the element we held earlier # (push the second number back on) } # repeat the loop if the top 2 weren't equal ([][()(())]){((<{}{}>))}{} # logical not of the height of the stack ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~9~~ ~~8~~ 7 bytes ``` ;@UŒPċṢ ``` [Try It Online!](http://jelly.tryitonline.net/#code=O0BVxZJQxIvhuaI&input=&args=WzIsIDAsIDEsIDNd) A Jelly translation of xnor's answer. Old solutions: ``` ;\Ṣ€IỊȦ ;\Ṣ€IE€P ``` [Try it online!](http://jelly.tryitonline.net/#code=O1zhuaLigqxJReKCrFA&input=&args=WzIsIDEsIDMsIDBd) Works very similarly to my Pyth answer below: ``` ;\ All prefixes (Accumulate (\) over concatenation (;)) Ṣ€ (Ṣ)ort each (€) prefix I (I)ncrements of each prefix (differences between consecutive elements). Implicit vectorization. E€ Check if all elements are (E)qual (they will be iff the permutation is antsy, and all elements will be 1) for each (€) prefix P Is this true for all prefixes? ỊȦ For the other answer, are (Ȧ)ll elements 1 or less (Ị)? ``` [Answer] ## CJam (21 20 bytes) ``` {:A,{_)A<$2*)@-#},!} ``` [Online test suite](http://cjam.tryitonline.net/#code=MTpUOzA6RjtxIixydWVhbHNlLT4iLX5dMi97flwKCns6QSx7XylBPCQyKilALSN9LCF9Cgp-PW99Lw&input=WzBdIC0-IFRydWUKWzAsIDFdIC0-IFRydWUKWzEsIDBdIC0-IFRydWUKWzAsIDEsIDJdIC0-IFRydWUKWzAsIDIsIDFdIC0-IEZhbHNlClsyLCAxLCAzLCAwXSAtPiBUcnVlClszLCAxLCAwLCAyXSAtPiBGYWxzZQpbMSwgMiwgMCwgM10gLT4gVHJ1ZQpbMiwgMywgMSwgNCwgMF0gLT4gVHJ1ZQpbMiwgMywgMCwgNCwgMV0gLT4gRmFsc2UKWzAsIDUsIDEsIDMsIDIsIDRdIC0-IEZhbHNlCls2LCA1LCA0LCA3LCAzLCA4LCA5LCAyLCAxLCAwXSAtPiBUcnVlCls0LCAzLCA1LCA2LCA3LCAyLCA5LCAxLCAwLCA4XSAtPiBGYWxzZQpbNSwgMiwgNywgOSwgNiwgOCwgMCwgNCwgMSwgM10gLT4gRmFsc2UKWzIwLCAxMywgNywgMCwgMTQsIDE2LCAxMCwgMjQsIDIxLCAxLCA4LCAyMywgMTcsIDE4LCAxMSwgMiwgNiwgMjIsIDQsIDUsIDksIDEyLCAzLCAxNSwgMTldIC0-IEZhbHNlClszNCwgMzYsIDk5LCA5NCwgNzcsIDkzLCAzMSwgOTAsIDIxLCA4OCwgMzAsIDY2LCA5MiwgODMsIDQyLCA1LCA4NiwgMTEsIDE1LCA3OCwgNDAsIDQ4LCAyMiwgMjksIDk1LCA2NCwgOTcsIDQzLCAxNCwgMzMsIDY5LCA0OSwgNTAsIDM1LCA3NCwgNDYsIDI2LCA1MSwgNzUsIDg3LCAyMywgODUsIDQxLCA5OCwgODIsIDc5LCA1OSwgNTYsIDM3LCA5NiwgNDUsIDE3LCAzMiwgOTEsIDYyLCAyMCwgNCwgOSwgMiwgMTgsIDI3LCA2MCwgNjMsIDI1LCA2MSwgNzYsIDEsIDU1LCAxNiwgOCwgNiwgMzgsIDU0LCA0NywgNzMsIDY3LCA1MywgNTcsIDcsIDcyLCA4NCwgMzksIDUyLCA1OCwgMCwgODksIDEyLCA2OCwgNzAsIDI0LCA4MCwgMywgNDQsIDEzLCAyOCwgMTAsIDcxLCA2NSwgODEsIDE5XSAtPiBGYWxzZQpbNDcsIDQ4LCA0NiwgNDUsIDQ0LCA0OSwgNDMsIDQyLCA0MSwgNTAsIDQwLCAzOSwgMzgsIDUxLCAzNywgMzYsIDUyLCAzNSwgMzQsIDMzLCAzMiwgNTMsIDU0LCAzMSwgMzAsIDU1LCA1NiwgMjksIDI4LCA1NywgNTgsIDU5LCA2MCwgMjcsIDI2LCA2MSwgMjUsIDYyLCA2MywgNjQsIDY1LCA2NiwgNjcsIDI0LCAyMywgMjIsIDIxLCA2OCwgNjksIDIwLCAxOSwgMTgsIDE3LCA3MCwgNzEsIDE2LCAxNSwgNzIsIDczLCA3NCwgNzUsIDc2LCAxNCwgMTMsIDEyLCA3NywgMTEsIDEwLCA5LCA4LCA3OCwgNywgNzksIDgwLCA2LCA4MSwgNSwgNCwgMywgODIsIDIsIDgzLCA4NCwgMSwgODUsIDg2LCA4NywgMCwgODgsIDg5LCA5MCwgOTEsIDkyLCA5MywgOTQsIDk1LCA5NiwgOTcsIDk4LCA5OV0gLT4gVHJ1ZQ) ### Dissection This uses the observation by xnor in his Haskell answer that the difference between the maximum and minimum of the first `n` elements should be `n-1`. ``` { e# Define a block. Stack: array :A, e# Store the array in A and get its length { e# Filter (with implicit , so over the array [0 ... len-1]) _)A< e# Get the first i+1 elements of A (so we iterate over prefixes) $2*) e# Extract the last element without leaving an empty array if the e# prefix is of length 1 by first duplicating the contents of the e# prefix and then popping the last element @-# e# Search the prefix for max(prefix)-i, which should be min(prefix) e# giving index 0 }, e# So the filter finds values of i for which the prefix of length i+1 e# doesn't have max(prefix) - min(prefix) = i ! e# Negate, giving truthy iff there was no i matching the filter } ``` --- ### Alternative approach (also 20 bytes) ``` {_{a+_)f-:z1&,*}*^!} ``` [Online test suite](http://cjam.tryitonline.net/#code=MTpUOzA6RjtxIixydWVhbHNlLT4iLX5dMi97flwKCntfe2ErXylmLTp6MSYsKn0qXiF9Cgp-PW99Lw&input=WzBdIC0-IFRydWUKWzAsIDFdIC0-IFRydWUKWzEsIDBdIC0-IFRydWUKWzAsIDEsIDJdIC0-IFRydWUKWzAsIDIsIDFdIC0-IEZhbHNlClsyLCAxLCAzLCAwXSAtPiBUcnVlClszLCAxLCAwLCAyXSAtPiBGYWxzZQpbMSwgMiwgMCwgM10gLT4gVHJ1ZQpbMiwgMywgMSwgNCwgMF0gLT4gVHJ1ZQpbMiwgMywgMCwgNCwgMV0gLT4gRmFsc2UKWzAsIDUsIDEsIDMsIDIsIDRdIC0-IEZhbHNlCls2LCA1LCA0LCA3LCAzLCA4LCA5LCAyLCAxLCAwXSAtPiBUcnVlCls0LCAzLCA1LCA2LCA3LCAyLCA5LCAxLCAwLCA4XSAtPiBGYWxzZQpbNSwgMiwgNywgOSwgNiwgOCwgMCwgNCwgMSwgM10gLT4gRmFsc2UKWzIwLCAxMywgNywgMCwgMTQsIDE2LCAxMCwgMjQsIDIxLCAxLCA4LCAyMywgMTcsIDE4LCAxMSwgMiwgNiwgMjIsIDQsIDUsIDksIDEyLCAzLCAxNSwgMTldIC0-IEZhbHNlClszNCwgMzYsIDk5LCA5NCwgNzcsIDkzLCAzMSwgOTAsIDIxLCA4OCwgMzAsIDY2LCA5MiwgODMsIDQyLCA1LCA4NiwgMTEsIDE1LCA3OCwgNDAsIDQ4LCAyMiwgMjksIDk1LCA2NCwgOTcsIDQzLCAxNCwgMzMsIDY5LCA0OSwgNTAsIDM1LCA3NCwgNDYsIDI2LCA1MSwgNzUsIDg3LCAyMywgODUsIDQxLCA5OCwgODIsIDc5LCA1OSwgNTYsIDM3LCA5NiwgNDUsIDE3LCAzMiwgOTEsIDYyLCAyMCwgNCwgOSwgMiwgMTgsIDI3LCA2MCwgNjMsIDI1LCA2MSwgNzYsIDEsIDU1LCAxNiwgOCwgNiwgMzgsIDU0LCA0NywgNzMsIDY3LCA1MywgNTcsIDcsIDcyLCA4NCwgMzksIDUyLCA1OCwgMCwgODksIDEyLCA2OCwgNzAsIDI0LCA4MCwgMywgNDQsIDEzLCAyOCwgMTAsIDcxLCA2NSwgODEsIDE5XSAtPiBGYWxzZQpbNDcsIDQ4LCA0NiwgNDUsIDQ0LCA0OSwgNDMsIDQyLCA0MSwgNTAsIDQwLCAzOSwgMzgsIDUxLCAzNywgMzYsIDUyLCAzNSwgMzQsIDMzLCAzMiwgNTMsIDU0LCAzMSwgMzAsIDU1LCA1NiwgMjksIDI4LCA1NywgNTgsIDU5LCA2MCwgMjcsIDI2LCA2MSwgMjUsIDYyLCA2MywgNjQsIDY1LCA2NiwgNjcsIDI0LCAyMywgMjIsIDIxLCA2OCwgNjksIDIwLCAxOSwgMTgsIDE3LCA3MCwgNzEsIDE2LCAxNSwgNzIsIDczLCA3NCwgNzUsIDc2LCAxNCwgMTMsIDEyLCA3NywgMTEsIDEwLCA5LCA4LCA3OCwgNywgNzksIDgwLCA2LCA4MSwgNSwgNCwgMywgODIsIDIsIDgzLCA4NCwgMSwgODUsIDg2LCA4NywgMCwgODgsIDg5LCA5MCwgOTEsIDkyLCA5MywgOTQsIDk1LCA5NiwgOTcsIDk4LCA5OV0gLT4gVHJ1ZQ) This checks directly that each element after the first is at distance 1 from a previous element. Since the input is a permutation and hence doesn't repeat values, this is a sufficient test. Thanks to Martin for a 1-byte saving. ### Dissection ``` {_{a+_)f-:z1&,*}*^!} { e# Declare a block. Stack: array _ e# Work with a copy of the array { e# Fold... a+ e# Add to the accumulator. _)f- e# Dup, pop last, map subtraction to get distance of this element from e# each of the previous ones :z1&, e# Check whether the absolute values include 1 * e# If not, replace the accumulator with an empty array }* ^! e# Test whether the accumulator is equal to the original array e# Note that this can't just be = because if the array is of length 1 e# the accumulator will be 0 rather than [0] } ``` [Answer] # Java, ~~100~~ ~~98~~ ~~79~~ 75 bytes ``` a->{int n=a[0],m=n-1;for(int i:a)n-=i==m+1?m-m++:i==n-1?1:n+1;return n==0;} ``` Formerly: ``` a->{int m,n;m=n=a[0];--m;for(int i:a)if(i==m+1)m=i;else if(i==n-1)n=i;else return 0>1;return 1>0;} ``` Saved 3 bytes by replacing `true` and `false` with `1>0` and `0>1`. Saved 23 bytes thanks to excellent suggestions from Peter Taylor! Ungolfed: ``` a -> { int n = a[0], m = n - 1; for (int i : a) n -= i == m + 1? m - m++ : i == n - 1? 1 : n + 1; return n == 0; } ``` Keep track of the highest and lowest values seen so far as `m` and `n`; only accept a new value if it is `m + 1` or `n - 1` i.e. the next higher or lower value; initialize the high value, `m`, to one less than the first element so that it will "match" the first time around the loop. Note: this is a linear-time, online algorithm. It requires only three words of memory, for the current, highest-so-far, and lowest-so-far values, unlike a lot of the other solutions. If the next value misses both the high and low ends of the range, the lowest-so-far value is set to `-1` and then the low end can never proceed and reach zero. We then detect an antsy sequence by checking whether the low value, `n`, reached zero. (Unfortunately this is less efficient because we always have to look at the entire sequence rather than bailing out after the first *wrong* number, but it's hard to argue with a 23-byte savings (!) when other solutions are using O(n^2) and exponential time approaches.) Usage: ``` import java.util.function.Predicate; public class Antsy { public static void main(String[] args) { int[] values = { 6, 5, 4, 7, 3, 8, 9, 2, 1, 0 }; System.out.println(test(values, a -> { int n = a[0], m = n - 1; for (int i : a) n -= i == m + 1? m - m++ : i == n - 1? 1 : n + 1; return n == 0; } )); } public static boolean test(int[] values, Predicate<int[]> pred) { return pred.test(values); } } ``` Note: this can also be written without taking advantage of Java 8 lambdas: # Java 7, 89 bytes ``` boolean c(int[]a){int n=a[0],m=n-1;for(int i:a)n-=i==m+1?m-m++:i==n-1?1:n+1;return n==0;} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ụ<ƝṢƑ ``` [Try it online!](https://tio.run/##PZO7bRxBEER9RnEBrLHznwGUyeFMOsQlQFeObAUgh6CpBASZBC6PYyLLet19NBaz21PTU11V@/J8vb4ex/3/@4/bn/u/t9vv4@PX58@/x3E@75ft6bxvp8SattP393bK8ZpjN1u1BKbY1x6wZDB9lUD6dg2wF3YrpGjbHu20Wal1qwkxrDy30/LLo0m1siDdINn2ncNkv1ltWLnb@bjwwYqxiiF4Y0ewxAh6z8mQOpXhLlDSe/LBhMvZmjW/NSZkhmVqQE6opc3FCNAQouj82r37VL@i9w5ODab2a7aWs/tVNByCVZhPvzTTkqnVdqltLU6@aO3aq3oaynNW9QpZtFS/Qe/hI03EhY76ToTiHI@wBbpaa/PRC@IK27nfVQwvICVAZw68gxgXdVOvNRd1mmRFS4ORDgzYam1YOMyEgQYMAgl0cMdm6Nv1OcKcuZvetbqDebpvA4qMmB4@cBXC1RiGEwhUQ2sEQCwE5l6jmFwA/IMHQpYQGCGMcnUv8Y8hEQ1jYMI4cEdMdEEfDEAX0ye7VhgIW/xHCktdCZOTD4yhltMV@RsuApNaWpvrhpyYjcGmfSiDcGTPwrSba9MjNdxxlOyumP9sxdMQeZz@v8zI5PR/heRiC0kmFqSXdJN0okl0iCbRWuty@QI "Jelly – Try It Online") In [Is it a tower permutation?](https://codegolf.stackexchange.com/questions/243173/is-it-a-tower-permutation), xnor comments > > This is closely related to Antsy Permutations -- a tower permutation is one whose inverse permutation, read backwards as a list, is antsy. > > > Combining [pxeger's answer](https://codegolf.stackexchange.com/a/243174/3852) to that question with `Ụ` (Grade, which inverts permutations) yields a short Jelly answer to this question. Instead of reversing the list before inverting the permutation, which would cost another byte, I just check for "anti-towers" by changing `>` to `<`. [Answer] # Pyth ([fork](https://github.com/Steven-Hewitt/pyth)), 13 bytes ``` !sstMM.+MSM._ ``` No Try It Online link for this fork of Pyth. The fork includes the deltas function `.+`, which is not part of the standard Pyth library. Explanation: ``` ._ For each of the prefixes: SM Sort it .+M Get deltas (differences between consecutive elements), which for antsy permutations would all be 1s tMM Decrement each of the elements (all 0s for antsy permutations) ss Sum all the results from the above together, 0 for antsy and >0 for non-antsy ! Logical negation. ``` [Answer] # J, 14 bytes ``` /:~-:>./\-<./\ ``` This is based on @xnor's [method.](https://codegolf.stackexchange.com/a/97240/6710) ## Explanation ``` /:~-:>./\-<./\ Input: array P \ For each prefix of P >./ Reduce using the maximum <./\ Get the minimum of each prefix of p - Subtract between each -: Test if it matches /:~ P sorted ``` [Answer] # Perl, ~~66~~ 54 +1 = 55 bytes +1 byte for `-n`. ``` s/\d+/$.&=!@a||1~~[map{abs$_-$&}@a];push@a,$&/eg;say$. ``` Explanation: ``` s/\d+/$.&=!@a||1~~[map{abs$_-$&}@a];push@a,$&/eg;say$. #input is automatically read into $_. #regex automatically is performed on $_. s/ / /eg; #Substitution regex. #/g means to keep searching after the first match #/e evaluates the replacement as code instead of regex. \d+ #Match of at least 1 digit. Match automatically gets stored in $& $.&= #$. is initially 1. This basically says $. = $. & (code) !@a #Since @a is uninitialized, this returns !0, or 1 #We don't want to check anything for the first match || #logical or 1~~ #~~ is the smartmatch operator. When RHS is scalar and LHS is array reference, #it returns 1 iff RHS is equal to at least one value in de-referenced LHS. [map{abs$_-$&}@a]; #Return an array reference to the array calculated by |$_ - $&| #where $_ iterates over @a. Remember $& is the stored digit capture. push@a,$& #pushes $& at the end of @a. say$. #output the result ``` Prints 0 if false, 1 if true. -11 bytes thanks to @Dada [Answer] ## Brainfuck, 60 bytes ``` ,+[>+>+<<-] ,+ [ [>->->+<<<-] >- [ +>+ [ <<< ] ] >[>] <[<+<+>>-] <<<,+ ] >. ``` The permutation is given as bytes with no separators and no terminating newline. Since `\x00` occurs in the input, this is designed for implementations with `EOF = -1`. The output is `\x00` for false and `\x01` for true. If a permutation of `\x01` up to `chr(r)` is allowed, then we can replace all instances of `,+` with `,` for a score of 57 with an `EOF = 0` implementation. [Try it online](http://brainfuck.tryitonline.net/#code=LFs-Kz4rPDwtXQosClsKICBbPi0-LT4rPDw8LV0KICA-LQogIFsKICAgICs-KwogICAgWwogICAgICA8PDwKICAgIF0KICBdCiAgPls-XQogIDxbPCs8Kz4-LV0KICA8PDwsCl0KPi4&input=NjU0NzM4OTIxMA) (57-byte version): Input can be given as a permutation of any contiguous range of bytes excluding `\x00`, and the output will be `\x00` for false and the minimum of the range for true. We keep track of the min and max seen so far, and for each character after the first, check whether it is min-1 or max+1 or neither. In the case of neither, move the pointer outside the normal working space so that the local cells become zero. The memory layout of the normal working space at the beginning of the main loop is `c a b 0 0` where `c` is the current character, `a` is min, and `b` is max. (For the 60-byte version, everything is handled with an offset of 1 because of `,+`.) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ⇧2lvƒ<ÞṠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiQGY6MXwiLCLih6cybHbGkjzDnuG5oCIsIjtcbsabQGY7IiwiW1swXSwgWzAsIDFdLCBbMSwgMF0sIFswLCAxLCAyXSwgWzAsIDIsIDFdLCBbMiwgMSwgMywgMF0sIFszLCAxLCAwLCAyXSwgWzEsIDIsIDAsIDNdLCBbMiwgMywgMSwgNCwgMF0sIFsyLCAzLCAwLCA0LCAxXSwgWzAsIDUsIDEsIDMsIDIsIDRdLCBbNiwgNSwgNCwgNywgMywgOCwgOSwgMiwgMSwgMF0sIFs0LCAzLCA1LCA2LCA3LCAyLCA5LCAxLCAwLCA4XSwgWzUsIDIsIDcsIDksIDYsIDgsIDAsIDQsIDEsIDNdLCBbMjAsIDEzLCA3LCAwLCAxNCwgMTYsIDEwLCAyNCwgMjEsIDEsIDgsIDIzLCAxNywgMTgsIDExLCAyLCA2LCAyMiwgNCwgNSwgOSwgMTIsIDMsIDE1LCAxOV0sIFszNCwgMzYsIDk5LCA5NCwgNzcsIDkzLCAzMSwgOTAsIDIxLCA4OCwgMzAsIDY2LCA5MiwgODMsIDQyLCA1LCA4NiwgMTEsIDE1LCA3OCwgNDAsIDQ4LCAyMiwgMjksIDk1LCA2NCwgOTcsIDQzLCAxNCwgMzMsIDY5LCA0OSwgNTAsIDM1LCA3NCwgNDYsIDI2LCA1MSwgNzUsIDg3LCAyMywgODUsIDQxLCA5OCwgODIsIDc5LCA1OSwgNTYsIDM3LCA5NiwgNDUsIDE3LCAzMiwgOTEsIDYyLCAyMCwgNCwgOSwgMiwgMTgsIDI3LCA2MCwgNjMsIDI1LCA2MSwgNzYsIDEsIDU1LCAxNiwgOCwgNiwgMzgsIDU0LCA0NywgNzMsIDY3LCA1MywgNTcsIDcsIDcyLCA4NCwgMzksIDUyLCA1OCwgMCwgODksIDEyLCA2OCwgNzAsIDI0LCA4MCwgMywgNDQsIDEzLCAyOCwgMTAsIDcxLCA2NSwgODEsIDE5XSwgWzQ3LCA0OCwgNDYsIDQ1LCA0NCwgNDksIDQzLCA0MiwgNDEsIDUwLCA0MCwgMzksIDM4LCA1MSwgMzcsIDM2LCA1MiwgMzUsIDM0LCAzMywgMzIsIDUzLCA1NCwgMzEsIDMwLCA1NSwgNTYsIDI5LCAyOCwgNTcsIDU4LCA1OSwgNjAsIDI3LCAyNiwgNjEsIDI1LCA2MiwgNjMsIDY0LCA2NSwgNjYsIDY3LCAyNCwgMjMsIDIyLCAyMSwgNjgsIDY5LCAyMCwgMTksIDE4LCAxNywgNzAsIDcxLCAxNiwgMTUsIDcyLCA3MywgNzQsIDc1LCA3NiwgMTQsIDEzLCAxMiwgNzcsIDExLCAxMCwgOSwgOCwgNzgsIDcsIDc5LCA4MCwgNiwgODEsIDUsIDQsIDMsIDgyLCAyLCA4MywgODQsIDEsIDg1LCA4NiwgODcsIDAsIDg4LCA4OSwgOTAsIDkxLCA5MiwgOTMsIDk0LCA5NSwgOTYsIDk3LCA5OCwgOTldXSJd) Like Lynn's Jelly answer, takes my [Vyxal answer](https://codegolf.stackexchange.com/a/246382/92689) to [Is it a tower permutation?](https://codegolf.stackexchange.com/q/243173/92689), adds a grade up at the beginning, and changes `>` to `<`. ## How? ``` ⇧2lvƒ<ÞṠ ⇧ # Grade up (i.e. sort indices by corresponding values) 2l # Get overlapping pairs vƒ< # For each pair, check if the first item is less than the second ÞṠ # Is it sorted in ascending order? ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 22 bytes ``` :@[fb:{oLtT,Lh:T:efL}a ``` [Try it online!](http://brachylog.tryitonline.net/#code=OkBbZmI6e29MdFQsTGg6VDplZkx9YQ&input=WzQ6Mzo1OjI6MTowXQ) ### Explanation I haven't found a concise way of checking whether a list contains consecutive integers or not. The shortest I found is to generate a range between the first and last element of that list and check that that range is the original list. ``` :@[fb Take all but the first prefixes of the Input :{ }a This predicate is true for all those prefixes oLtT, Sort the prefix, call it L, its last element is T Lh:T The list [First element of L, T] :efL Find all integers between the First element of L and T. It must result in L ``` [Answer] ## Batch, 133 bytes ``` @set/au=%1,l=%1-1,a=0 @for %%n in (%*)do @call:l %%n @exit/b%a% :l @if %1==%u% (set/au+=1)else if %1==%l% (set/al-=1)else set a=1 ``` Takes input as command-line arguments. Exits with error level 0 for success, 1 for failure. [Answer] ## Java, 170 bytes ``` boolean f(int[]a){int l=a.length,i=0,b=0,e=l-1;int[]x=new int[l];for(;i<l;i++)x[i]=i;for(i--;i>0;i--)if(a[i]==x[b])b++;else if(a[i]==x[e])e--;else return 0>1;return 1>0;} ``` Array `x` has values from 0 to maximum number in order (Python would be much better here...). The loop goes backwards trying to match the lowest (`x[b]`) or the highest (`x[e]`) number not yet encountered; if it does, that number could be reached in that step. [Test code here](https://ideone.com/bV6LcM). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ηε{¥P}P ``` [Try it online!](https://tio.run/##NZM7bhZBEIRzTrFyvEg775kEJ4jYueUAJAIiBw4tH4cjIHIO4Cv91Nc1Dlbz6J7u6qra55fvP379vKXx7ev93fH5y3F3f3v/@/7n9d/vh7eH23l7vJ4@PV7nkbSk8/g4nUf2LjuU4644ocThck6KHB2K0xyszvT5inNywfZRSbGqqx5Xio@4neex3NUVatwqo0dGjrC7T4VbXI247fF6N9t4mKVEAjsCykpA1z6nSNSjDGolJe2TJ1JezlGrueeeDfwLEkCmpKXYAj4glFD0fF0uPlWuaN/J0/upeM1RcXZ3ot5QWgX3dM9MSUZW2aWytRh70doVq/oajPNW9xWs8Kh6g9rDE02IBY7qTmjiHZ9yC3C11ubJC8wqt9PfHG4dAKWEzhzIBjAa9SCvNXM6g7GipYFIDwZotTb0G6HBgAMGAQQ8WK@56e06jq3NvILuWi1gnpZtAJER05aBTvBW9yw8gJ@6qWZ@uIJf2gbC5PmRDxjwWDa/8BCIq6VEPmaEM3QBCNMAHS6hBXrgH1qCnmyq0A@wyA8T4bmyNU6eFz3DpWu7b5gDBg2vNtMGm2iNvkH9JgbesF546QrRph01LDhEdhPm/6zYDNuO0z/L3Jac/lMwLqpgZFyBeTE3RseZOAdn4qy1nv4D "05AB1E – Try It Online") [Answer] # [R](https://www.r-project.org/), 57 bytes ``` function(x,y=x[-1],`!`=cummin){y[]=y+1-!x&y-1+!-x;any(y)} ``` [Try it online!](https://tio.run/##dZTbattAFEXf8xUyhWITGTQXzYwI7mO/oG8hNMa0EGgUSGywCP1296xzprVTrAejsedc197y62l82X/fjvu3aXP6eRh3@6eXcXlsp83xfu0e2sfF42Z3eH5@Glfv0/3DZrp168Xx87R2t4v18W47Tstp9ftkBc75q8W/svLl5sZOu2W3WjWfmvWX5tvr4cf517ZxVy9c28xntI2fu/MXBb9uf72dL70mhrm6Qa@7i9If053WlvtwNd1raQmKcw0sotOImRHlsv87pYTH61FJo6RK1sDSNoPtPdc5apzkJM3xmmDLlusteo3KGpi0RZ37Yv3/6KJL0BxOxEqig6ecvdNcqeOhJEFOzs6YSpz3Wr63ySpLUAzXuwVWkrxBwgdIMKrkBKk4dNavSIcg50SclCxyH702Kcma0yJLWGS7YmN4SsJKyg5SNgZbJ8gzyV2UT48NyJXfI@MjidTL1M62ZEEjxpG6BZjk8ZHYwLjyjL3BCEgisYn@RrpKylASkNgDUzAYjZLy7HvDXBRikEfPRJKQmVaePcJnlSXDgEUYAg6maqnEk3zNVa7SqQIxmqa@mJKZEVnRzStDc1DGuh41QBYrfZCAD@RMokM7Q4KiTAbaUJGDRpeIpi6KsjYYkYrZWJBtwAspiCEJpJSYN3pIyvw4AjjqzFBld4YAidXLQ/VoNizsro7ujSSAkR/JVY3KCpS4Ue3VqY7FTJbNA7BNxtDe4mD@qA4t9paV6tJi7xNeRii8jVHwM37H@5gVM2FWzDYMH/4ETn8A "R – Try It Online") Completely different and somewhat shorter approach to [JDL's previous R answer](https://codegolf.stackexchange.com/a/97231/95126). Returns `FALSE` for antsy sequences, `TRUE` for not-antsy sequences. Add two bytes to reverse the output to truthy for antsy sequences: [59 bytes](https://tio.run/##dZTbattAFEXf8xUyhWITCTQXzYwo7mO/oG8hNCa0EGgUSGywKP1296xzprVTrAejsedc197y62l62X/bTfu3eXv6cZge908v0/rYztvjXefu24fVw/bx8Pz8NG1@zXf32/nWdavjx7lzt6vu@Ml1u2lez5vfJytxrrBZ/SssX25u7PS47jeb5kPTfW6@vh6@n39tG3f1wrXNckbb@KU7f1Hwy@7n2/nSa2JYqhv0ur8o/T7daW25D1fTvZaWoLjUwCJ6jVgYUS6Hv1NKeLwelTRKqmQNLG0z2t5LnaPGSU7SHK8Jtmy53mLQqKyBSVvUuS/W/48uugTN4USsJDp4ytk7zZU6HkoS5OTsjKnEea/lB5ussgTFeL1bYCXJGyV8hASjSk6QimNv/Yp0CHJOxEnJIvfRa5OSrDktsoRFtis2hqckrKTsKGVjsHWCPJPcRfkM2IBc@T0yPpJIvUztbEsWNGIcqVuASR4fiQ2MK884GIyAJBKb6G@kq6QMJQGJPTAFg9EoKc9hMMxFIQZ5DEwkCZlp5TkgfFZZMgxYhCHgYKqWSjzJ11zlKr0qEKNp6ospmRmRFd2yMjQHZazrUQNksdIHCfhAziQ6tDMkKMpkoA0VOWh0iWjqoihrgxGpmI0F2Qa8kIIYkkBKiXmjh6TMjyOAo84MVXZnCJBYvTxWj2bDwu7q6MFIAhj5kVzVqKxAiRvVXr3qWMxk2TwA22QM7S0O5o/q0GJvWakuLfY@4WWEwtsYBT/jd7yPWTETZsVs4/juT@D0Bw), but save 4 bytes by taking input using `scan`: [55 bytes](https://tio.run/##BcFLCoAwDAXAq7xuRJGA8S8lJxHR4sqFEfxAc/o6cye93jXo@5ikKM8eNC@8SZyJF7@5TfbvPA/1Ni9iJZOLmRGXjqJnCmq5FalHhxYDGoyYUINRpR8) [Answer] # Mathematica, 47 bytes A little longer than Martin Ender's solution (surprise surprise!). But it's one of my more unreadable efforts, so that's good :D ``` #=={}||{Max@#,Min@#}~MemberQ~Last@#&&#0@Most@#& ``` Explanation: ``` #=={} empty lists are antsy (function halts with True) || or {Max@#,Min@#}~MemberQ~Last@# lists where the last number is largest or smallest are possibly antsy (else function halts with False) && and #0@Most@#& recursively call this function after dropping the last element of the list ``` [Answer] # Java 7, ~~170~~ 169 bytes ``` import java.util.*;Object c(int[]a){List l=new ArrayList();l.add(a[0]);for(int i:a){if(l.indexOf(i)<0&l.indexOf(i-1)<0&l.indexOf(i+1)<0)return 0>1;l.add(i);}return 1>0;} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/OZZi4O) ``` import java.util.*; class M{ static Object c(int[] a){ List l = new ArrayList(); l.add(a[0]); for(int i : a){ if(l.indexOf(i) < 0 & l.indexOf(i-1) < 0 & l.indexOf(i+1) < 0){ return 0>1; //false } l.add(i); } return 1>0; //true } public static void main(String[] a){ System.out.println(c(new int[]{ 0 })); System.out.println(c(new int[]{ 0, 1 })); System.out.println(c(new int[]{ 1, 0 })); System.out.println(c(new int[]{ 0, 1, 2 })); System.out.println(c(new int[]{ 0, 2, 1 })); System.out.println(c(new int[]{ 2, 1, 3, 0 })); System.out.println(c(new int[]{ 3, 1, 0, 2 })); System.out.println(c(new int[]{ 1, 2, 0, 3 })); System.out.println(c(new int[]{ 2, 3, 1, 4, 0 })); System.out.println(c(new int[]{ 0, 5, 1, 3, 2, 4 })); System.out.println(c(new int[]{ 6, 5, 4, 7, 3, 8, 9, 2, 1, 0 })); System.out.println(c(new int[]{ 4, 3, 5, 6, 7, 2, 9, 1, 0, 8 })); System.out.println(c(new int[]{ 5, 2, 7, 9, 6, 8, 0, 4, 1, 3 })); System.out.println(c(new int[]{ 20, 13, 7, 0, 14, 16, 10, 24, 21, 1, 8, 23, 17, 18, 11, 2, 6, 22, 4, 5, 9, 12, 3, 15, 19 })); System.out.println(c(new int[]{ 34, 36, 99, 94, 77, 93, 31, 90, 21, 88, 30, 66, 92, 83, 42, 5, 86, 11, 15, 78, 40, 48, 22, 29, 95, 64, 97, 43, 14, 33, 69, 49, 50, 35, 74, 46, 26, 51, 75, 87, 23, 85, 41, 98, 82, 79, 59, 56, 37, 96, 45, 17, 32, 91, 62, 20, 4, 9, 2, 18, 27, 60, 63, 25, 61, 76, 1, 55, 16, 8, 6, 38, 54, 47, 73, 67, 53, 57, 7, 72, 84, 39, 52, 58, 0, 89, 12, 68, 70, 24, 80, 3, 44, 13, 28, 10, 71, 65, 81, 19 })); System.out.println(c(new int[]{ 47, 48, 46, 45, 44, 49, 43, 42, 41, 50, 40, 39, 38, 51, 37, 36, 52, 35, 34, 33, 32, 53, 54, 31, 30, 55, 56, 29, 28, 57, 58, 59, 60, 27, 26, 61, 25, 62, 63, 64, 65, 66, 67, 24, 23, 22, 21, 68, 69, 20, 19, 18, 17, 70, 71, 16, 15, 72, 73, 74, 75, 76, 14, 13, 12, 77, 11, 10, 9, 8, 78, 7, 79, 80, 6, 81, 5, 4, 3, 82, 2, 83, 84, 1, 85, 86, 87, 0, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 })); } } ``` **Output:** ``` true true true true false true false true true false true false false false false true ``` [Answer] # [JavaScript], 54 bytes ``` e=>e.every((f,m)=>!m||e.some((e,o)=>o<m&&(e-f)**2==1)) ``` [Try it online!](https://tio.run/##jVTRbtswDHzPV2h5KOzCjSPJtuRh7o8MezBcue2WxJntdC3WfnvGI1UgRRNgD65dkTySd6f8bJ/aqRsf9/PNbrgLx745huY2rMJTGF@SpM@2aXP7Zfv6GlbTsA1JErKBToZv26urJNz06fW1aRqdpsc8f5jn/fQ1zzsCuh82/Wqa2@5XeO4e2t19WHXDNv99CNP8OOymvHZGu7zdzdPLzT6M28PccmDR0Z9ZtdMUxlk1KnlqN4eQqfC8D90c7lLV3Kq/C6Ue@xhTTdOchBFTCijDJqw2w32y3BPaMuXzMcyHcUefb/TMD@PwRy3DOA7jcvG2WEjXpE@@r3@kmZrHQ0hPDzOlz53rTF3Mz5S5EDIRrW8304eY4TJ7AdRydB1xPxVrBqawPVdsGJdyigvokrDmhPPTUax8H5Cyi7NJFScRhuM8n6laFr7QtuA0Kqm4xHC@rOnPNig5yXFexQ3izHHxjwWkNdWwAQxEsVyKL5RQvQaf9G00QxCcAU@UpOlbC6mUZwx3KdGX4XRkFJTwETVHN7RfnOtvsSoh1TR4DYKwAyFY6lGvZQJPPS19V8ijBp7iheG2vpJxqCHDOUotsLqX4QxgwSNB1wRdWFnS0ruiWEFPCXdQjqPzAktBLR3x0MPJ@h4SYizC9mAbtXgo32Jsehel0GQhGeVWmIGlYLioOoajpAo7wTYYkJJdxWyXpYjgmWJLrxKTUYHD1PQurcCVjoVz4ARLYRjwIvJ7eAY60b8uCurXrE9RiOrGi9YurlthXf2/2mEkEF3ExYEKQouoD8gCuRAEs/EqWsiC5pgVxNvIDkQBcaWVleEB6A5CQDLExMRYGzuCfHAILiEaOGQuTdzGivDYCt4BdexqG82hhRwYge9BHf3thDCn4214N5cRCWAUGIP1ikyCaHiXzbjmewjavQhUC/OVsBvh5JLDSdHTXi6sj772cifhfkiJ2wBL4QbghuC2wNpkO/GWE2vWJ9rhd4WkO/4D "JavaScript (Node.js) – Try It Online") ]
[Question] [ Here’s the picture of the first published picture of the Mandelbrot set. Use the fewest bytes possible to write a program or function that outputs the following. ![the Mandelbrot set](https://upload.wikimedia.org/wikipedia/commons/d/d7/Mandel.png) A trailing new line is permitted. Character `*` cannot be replaced by any other character. [Useful information](https://math.stackexchange.com/a/3510304/305967): Center is \$(-0.75, 0)\$, \$\Delta x = 0.035\$, and \$\Delta y = 1.66\Delta x\$. Iteration count is 250. As text (for checking): ``` * **** ****** ***** * ********* *** **************** ******************** ** ************************* **************************** ******************************* ****************************** * ***** ******************************** *********** ******************************** ************* ******************************* ** ************** ****************************** **************************************************************** ** ************** ****************************** ************* ******************************* *********** ******************************** * ***** ******************************** ****************************** ******************************* **************************** ************************* ******************** ** *** **************** * ********* ***** ****** **** * ``` Thanks @Sisyphus for providing the parameters. [Answer] # [Ruby 2.5](https://www.ruby-lang.org/), 98 bytes ``` -15.upto(15){|y|68.times{|x|z=0;250.times{z=0.035*x-1.9751+y/17.21i+z*z};putc z.abs<2?42:32};puts} ``` [Try it online!](https://tio.run/##KypNqvz/X9fQVK@0oCRfw9BUs7qmssbMQq8kMze1uLqmoqbK1sDayNQAKgDk6RkYm2pV6BrqWZqbGmpX6hua6xkZZmpXaVXVWheUliQrVOklJhXbGNmbGFkZG4HFimv//wcA "Ruby – Try It Online") Very straightforward implementation, with a little bit of trickery to allow using `times` instead of `upto` in the inner loop. Unfortunately, loop merging is two bytes longer, although it may help in other languages: ``` -1034.upto(1104){|x|z=0;250.times{z=x%69*0.035-2.0101+x/69/17.21i+z*z};putc x%69>0?z.abs<2?42:32:10} ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~86~~ ~~85~~ 84 bytes -1 thanks to [sanchez](https://codegolf.stackexchange.com/questions/217537/the-first-published-picture-of-the-mandelbrot-set/217567?noredirect=1#comment507555_217567) ``` Print@@@Array[If[Re@Nest[#^2+c&,c=.035#2+I.0581#,199]<2,"*"," "]&,8{4,9},-5{3,79/7}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1iamVoS/T@gKDOvxMHBwbGoKLEy2jMtOijVwS@1uCRaOc5IO1lNJ9lWz8DYVNlI21PPwNTCUFnH0NIy1sZIR0lLSUdJQSlWTcei2kTHslZH17TaWMfcUt@8NvZ/7H8A "Wolfram Language (Mathematica) – Try It Online") Uses the constants found by Sisyphus. Mathematica does have such functions as `MandelbrotSetIterationCount` and `MandelbrotSetMemberQ` (which, with the default 1000 iterations, produces a slightly different image). Unfortunately, `MandelbrotSetIterationCount`'s name is a bit too long, while setting the `MaxIterations` option for `MandelbrotSetMemberQ` makes it even more verbose. [Answer] # [MATL](https://github.com/lmendo/MATL), 45 bytes *Some numerical constants have been taken from [Sisyphus' answer](https://codegolf.stackexchange.com/a/217539/36398)* *Thanks to [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for a correction!* ``` O8W:"U-1.9751:.035:.4-15:15!17.21j/++]|2<42*c ``` [**Try it online!**](https://tio.run/##y00syfn/398i3EopVNdQz9Lc1NBKz8DY1ErPRNfQ1MrQVNHQXM/IMEtfWzu2xsjGxEgr@f9/AA) ### How it works ``` O % Push 0 8W % Push 2^8, that is, 256 : % Range. Gives [1 2 ... 256] " % For each. This iterates 256 times U % Square, element-wise -1.9751:.035:.4 % Push range from -1.9751 to 0.4 (actually to 0.37) with step 0.035 -15:15 % Push range from -15 to 15 (with step 1) ! % Transpose into a column vector 17.21j/ % Divide by 17.21j, element-wise + % Add with broadcast. Gives the complex grid + % Add element-wise to result from previous iteration ] % End | % Absolute value, element-wise 2< % Less than 2? Element-wise 42* % Multiply by 42 (ASCII code of '*'), element-wise c % Convert to char (char 0 is displayed as space). Implicit display ``` As a curious note, the program uses `:` with three different meanings: * Unary range function (`:` appplied to `256`) * Ternary range literal (`-1.9751:.035:.4`) * Binary range literal (`-15:15`) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 56 bytes Feels very long. ``` 67ÝƵú*Ž @-тn/15D(Ÿт*Ž6À/δ‚εε₅FDnÆsP·‚y+DnO4›©#}„* ®è]øJ» ``` [Try it online!](https://tio.run/##AV8AoP9vc2FiaWX//zY3w53GtcO6KsW9CkAt0YJuLzE1RCjFuNGCKsW9NsOAL8604oCazrXOteKChUZEbsOGc1DCt@KAmnkrRG5PNOKAusKpI33igJ4qIMKuw6hdw7hKwrv//w "05AB1E – Try It Online") Since *05AB1E* does not support complex numbers the computation is done in a more manual way, keeping complex numbers as pairs `[a, b]`: $$(a+bi)^2 = (a^2-b^2) + 2abi$$ ``` D # duplicate the pair n # square each part: [a^2, b^2] Æ # reduce by subtraction: a^2-b^2 s # swap to copy P # take the product: a*b · # double it: 2*a*b ‚ # pair both results: [a^2-b^2, 2*a*b] ``` $$|a+bi|>2 \Leftrightarrow \sqrt{a^2+b^2}>2 \Leftrightarrow a^2 + b^2 > 4$$ ``` n # square each part: [a^2, b^2] O # take the sum: a^2+b^2 4› # is this larger than 4: a^2+b^2>4 ``` Complete code commented: ``` 67ÝƵú*Ž\n@-тn/ # generate the x coordinates: ([0..67]*350-19751)/10000 67Ý # push the range [0 .. 67] Ƶú* # multiply each value by 350 Ž\n@- # subtract 19751 from each тn/ # divide by 100**2 15D(Ÿт*Ž6À/ # generate the y coordinates: [15..-15]*100/1721 15D # push 15 twice ( # negate one copy Ÿ # take the inclusive range [15 .. -15] т* # multiply each value by 100 Ž6À/ # divide by 1721 δ‚ # create a grid of all x-y pairs ε # map over each line: ε # map over each pair: ₅F } # iterate 255 times # (produces the same output as 250 iterations) DnÆsP·‚ # square the current value y+ # add the coordinate D # duplicate current value nO4›© # check if the magnitude is larger than 2 # # if this is the case, stop the loop # this is necessary because the program will actually crash if trying to continue with infinite values „* ®è # index with the last result of |z|>2 into the string "* " ] # close all loops ø # transpose the grid J # join each line into a single string » # join lines by newlines ``` [Answer] # [R](https://www.r-project.org/), ~~151~~ 138 bytes *Edit: -13 bytes thanks to Giuseppe* ``` write(matrix(unlist(Map(rep,c(" ","*"),utf8ToInt("T `#^%^$Y (S\" /Q3 !I8I;E>D=8 $$?6*!?5, >2! - =!_#")-31)),68)[,c(1:16,15:1)],1,68,,"") ``` [Try it online!](https://tio.run/##DczBCoJAEADQX5kdDWZlJDZxWQz1UgcPHSIvUVkSBkKZbCv195vXd3jW@6/tXUev1tn@R9Pw7D@Odu1Ithv5TgjIGKHkyT1M/a4GR1jDLWgWTXgEoMMZYblPQFSmWm@LTW4AwrDUkShThmIlIIZcXAOUcaKkZG3kaW5VpjSrNFPywmpGZkTp/R8 "R – Try It Online") Encodes the run lengths of s and `*`s for the top half as a text string, converts these to a matrix (together with itself reversed by row), and outputs using `cat`. Bearing in mind that actually calculating the Mandelbrot set in [R](https://www.r-project.org/) costs only [123 bytes](https://codegolf.stackexchange.com/a/204933/95126), including full-colour graphic display, this might not be the golfiest solution... but the text encoding was fun anyway... [Answer] # JavaScript (ES6), ~~128 ... 124~~ 123 bytes Based on the parameters [used by @Sisyphus](https://codegolf.stackexchange.com/a/217539/58563). ``` f=(k=2138)=>k?` *`[k--%69&&-~(g=X=>++n>>8?X*X+Y*Y<4:g(X*X-Y*Y-k%69*.035+.3699,Y=2*X*Y-(16+~(k/69))/17.21))(Y=n=0)]+f(k):'' ``` [Try it online!](https://tio.run/##DcpBDoIwEEDRvadwI8y0tlDQCsQp16AxJhAEoiVgxLjk6pXdy89/Nb9maT/P91dM86PzvidwlKg0QzKurHd7Vt@cEAedB4FYYaCKDOeTMVlZsYpbZq@nYoDNYrNw28hknJ65THWeHy0lrNo6KM1XcJHOESN1kYlCBEsTxXjnPTgswtC387TMYyfHeYAeEP0f "JavaScript (Node.js) – Try It Online") ### Commented ``` f = (k = 2138) => // f is a recursive function taking a counter k // which encodes: x = k mod 69 // y = floor(k / 69) - 15 k ? // if k is not equal to 0: `\n *`[ // character lookup: k-- % 69 && // append a linefeed if k mod 69 = 0 // (decrement k afterwards) -~( // otherwise use the result of ... g = X => // ... the recursive function g which takes X // and also uses Y and an iteration counter n ++n >> 8 ? // increment n; if it's not equal to 256: X * X + Y * Y < 4 // return true if X² + Y² is less than 4 : // else: g( // do a recursive call to g with: X * X - Y * Y // the updated X: - k % 69 * .035 // X² - Y² - x * 0.035 + 0.3699 + .3699, // Y = 2 * X * Y // the updated Y: - (16 + ~(k / 69)) // 2XY + y / 17.21 / 17.21 // ) // end of recursive call )(Y = n = 0) // initial call to g with X = Y = n = 0 ] // end of character lookup + f(k) // append the result of a recursive call : // else: '' // stop the recursion ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~74~~ 73 bytes ``` F¹⁶«F⁶⁸«≔⁰θ≔⁰ηFφ«≔⁺⊕×·⁰³⁵⁻κ⁸⁵⁻×θθ×ηηζ≔⁺∕ι¹⁷·²¹⊗×θηη≔ζ軧 *‹⁺×θθ×ηη⁴»⸿»‖O↑ ``` [Don't try it online!](https://tio.run/##dY8xb8IwEIVn@BWnTGfkIkKBojIhsSC1KqpgY0mTS2PVOMQOUQXit7uOrVTKwHDSPd937/nSItFpmUhr81IDxgsGt@HA94ul7wdrY8S3wgmHiq16uvDaw3lgu@FOXgxuVarpRKqmDPfiRAbHk@c5h3eh3PSHw3LOGOt0IKo2hUMQRRvRElcf1DPfiEZkhIJD/DKexg7alJcv@R9VdbtFb/faXXF3tdNC1biutyqjX4xgFHF4I2NCwsMPcZg5Z2fiPIJFdNSRe7gPPymXlNYfDWmZnPH1cGYra@1TI/8A "Charcoal – Try It Online") Link is to verbose version of code. Performs 1,000 iterations, so it's too slow for TIO. It can be made faster by halving the number of iterations, which costs a byte: ``` F¹⁶«F⁶⁸«≔⁰θ≔⁰ηF⊘φ«≔⁺⊕×·⁰³⁵⁻κ⁸⁵⁻×θθ×ηηζ≔⁺∕ι¹⁷·²¹⊗×θηη≔ζ軧 *‹⁺×θθ×ηη⁴»⸿»‖O↑ ``` [Try it online!](https://tio.run/##dY/NbsIwEITP8BSrnNaVQYSWH5UTEgeQioqqcuslTTaNhXGIHaKKimd3HVuplEMPlnbW38zYaZHotEyktXmpAeM5g5/hwM/zpZ8Ha2PEl8IJh4qterrw2sPbRDaUYc6Cp4MO8mpwp1JNZ1K1A97FmQyOJ48zDnuh3O2Jw3LGGOt0IKq2jUMQRVvVEjdf2AvfiEZkhIJDvBhPYwdtyuun/KuqOm/R896639zdOWihalzXO5XRN0bwEHF4IWNCw78P4vDkkl2IywgR0YeO3OI@fKNcUlq/NqRlcsHn44WtrLWjRv4C "Charcoal – Try It Online") Link is to verbose version of code. Previous 74-byte compression-based version: ``` ”}∧q÷W9r¤1αlIχ‽§heY⟧>℅ν⊞P ~E .Q×jn⁵\6⧴<¤< U#V‽↶³≧JJD‴>π v‹»λê= ↨∨|>zθ9”‖O↓ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRENJgRygFZNHji4gIEejlha5OhXI0qkFtZE0rUDVCH1aZLhZCwtQIMUMLVyAaCO08AAiDdHCD6hiCm5DoFFAjEtwm4Ic/mSbgh6NJBuCoYtgoGhRCJQ0rbmCUtNyUpNL/MtSi3ISCzSsXPLL8zSt////r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by printing the top half as a compressed string literal and reflecting it. I also tried printing the bottom half and reflecting, but this increased the byte count to 78 bytes. I also tried printing the reflection of the image and for the bottom half this reduced the byte count to 75 bytes but for the top half it actually increased it to 81 bytes. I also tried using manual run length encoding but I couldn't even get it as low as 81 bytes. Previous 75-byte even faster pure Charcoal calculation version (uses the original 250 iterations): ``` F¹⁶«F⁶⁸«≔⁰θ≔⁰ηF²⁵⁰«≔⁺⊕×·⁰³⁵⁻κ⁸⁵⁻×θθ×ηηζ≔⁺∕ι¹⁷·²¹⊗×θηη≔ζ軧 *‹⁺×θθ×ηη⁴»⸿»‖O↑ ``` [Try it online!](https://tio.run/##dY8xb8IwEIVn@BWnTOfKRQltKCoTEgtSKxBqN5Y0ORqrxiF2iCoQv904tlIpQ4eT7vm@e8@Xl5nOq0xae6g0YDJjcB2PfD@b@360NEZ8K4w51Gwx0KXXHp6mcaD78VaeDa5VrulIqqECP8SRDE7ip5TDu1Bu@sNhnjLGeh2IusvhEETZhXTExUcNzFeiFQWh4JC8TKaJg1bV@Uv@RdX9bjnYvfR33FxttVANLpu1KugXI3iIOLyRMSHh3w9xeHbOzsR5BItoryP3cBvv6CApbzYtaZmd8PXzxBbW2sdW3gE "Charcoal – Try It Online") Link is to verbose version of code. If Python exponentiation worked on `inf` then it would have been only 73 bytes: ``` F¹⁶«F⁶⁸«≔E²¦⁰θF²⁵⁰UMθ⎇ν⁺∕ι¹⁷·²¹⊗×μ§θ⁰⁺⊕×·⁰³⁵⁻κ⁸⁵⁻Xμ²X§θ¹¦²§ *›⁴ΣXθ²»⸿»‖O↑ ``` [Don't try it online!](https://tio.run/##TZDNTsMwEITPzVOscrKRWyWGlIqeKiqhHioiKDcuJtkWC9tpnB9AqM9uHDequqfdnfnG1hafwhaVUM7tKwsknVP4iyahny9CP1k1jTwYshVHwhkklEFNl34fTDxLKHjpsdJamJLUDHZojbC/xDDIVdeQtexliUQySO9nPPX8uuo@FJZkJzU2RDNYtRtT4s9AJ9TXSG5MYVGjaS/eWXKbMdhK49UvBossmM9zXn2jHdL4wIfhKnd4lw/Z4e@5laa9yDHcxAyeLIrWQ3cMXjs9xtVX1Ckaufjdxn5xil5wr7Bon3u0yp/n4e1Il865aa/@AQ "Charcoal – Try It Online") Link is to verbose version of code. With some hacky uses of `PythonEvaluate` and `EvaluateVariable` to get around the fact that the version of Charcoal on TIO doesn't support complex numbers I can do it in 58 bytes: ``` F¹⁶«F⁶⁸«≔⁰θF²⁵⁰≔⁺⁺∕ιUV17.21j⊕×·⁰³⁵⁻κ⁸⁵×θθθ§ *‹▷absθ²»⸿»‖O↑ ``` [Try it online!](https://tio.run/##NY3BbsIwEETP5CtWPq0rFyVBoaickOCABGqE2p56MclS3BoHbBO1qvh21wlwWc3u7Myr9tJWjdQh7BoLmI05/CWDXo8nvR7MnFOfBlMBJz6Ne2/mRcrh5pT67K5jrlpVEyoB5a/fN2bRSn2WnpBlT8M8@2KcC1iaytKBjKcaX9WBHA7TUSFgrUys@BYwKTjvHq/mqePyO7y0ynic@aWp6QcZPDABK3IO76h3aZXc6oiUW8e6mIA81sXwJbnF2Ydl8XBJNrTTVPmXlqyWR3x@O/JpCOGx1f8 "Charcoal – Try It Online") Link is to verbose version of code. 54 bytes using the newer version of Charcoal on ATO: ``` F¹⁶«F⁶⁸«≔⁰θF²⁵⁰≔⁺⁺∕ιI17.21j⊕×·⁰³⁵⁻κ⁸⁵×θθθ§ *‹↔θ²»⸿»‖O↑ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BTsMwEEXXzSlGXo2RWyVBKRFdRbCpBKJCsKIsUmdCDa7b2m6EhHoSNl2A6JU4A5eom4bN6M_89_U1n3s5L61clnq3-974up___tVLC5gMOXxEvVYP81b3CufUi8FYwJqPwt6aaRZz6JyJ3rjTuFaNqgiVgKvSeWTJxSBNXhnnAsZGWlqQ8VThg1qQw3gQn2cCbpUJyTcBecb5kTy562Md_--cWGU8Fn5sKnpHBmdMwA05h8UsoAFLQzSA26hD2dSycNhG91Rrkv6uIavLFV4-rvjoy82k6x7_eWL9RrPnbj0A "Charcoal – Attempt This Online") Link is to verbose version of code. Saves 1 byte by using `Cast("17.21j")` instead of `PythonEvaluate("17.21j")` and 3 bytes by using `Abs(q)` instead of `EvaluateVariable("abs", q)`. [Answer] # [Perl 5](https://www.perl.org/), 127 bytes ``` say for@o='e1q4o6o5j119d31@bD12ZIZLVOUNI1155PG;2PF=1OC21>1N2p4'=~s/./($i++%2?'*':$")x(-48+ord$&)/ger=~/.{68}/g,reverse@o[0..14] ``` [Try it online!](https://tio.run/##BcHRCoIwFADQX5Gwpllbd21iyUooCiHUl3oweihcUgSzjaSI/PV1TiP1g9uXkU7LMUxia84f56p0ogSS8GQqVPwOMKumkFzWQMu03B3yfZYCcF5sY1psBOQrCgvIaMOQ6AzBxHNvQdCnSzREc7fnv70xiwKlK3fgk1pq0RH8DaMfqUdatlIbmajjBGNgJ2v/ "Perl 5 – Try It Online") ``` say #prints each line + \n newline at end for @o= #for all lines, also saved in array @o 'e1q4o6o5j119d31@bD12ZIZLVOUNI1155PG;2PF=1OC21>1N2p4' #lengths for spaces and *s =~ s/./ ($i++%2?'*':$") x (-48+ord$&) /ger #...decode into lengths and output #...space or * of each length =~ /.{68}/g, #...partition lines on every 68th char reverse@o[0..14] #add mirror of first 15 lines ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 97 bytes Using `zopfli --i 10000 --deflate -c mandlebrot.txt | xxd` and no trailing spaces. Increasing iterations beyond 10000 doesn't seem to make a difference. ``` 00000000: c595 a901 c040 0c80 7ca6 8866 ff01 2bb1 .....@..|..f..+. 00000010: 574c f0d0 debf 05a6 4850 3c88 e216 9105 WL......HP<..... 00000020: f869 829a f63b 5ab2 30c1 6f3f 81c4 06d2 .i...;Z.0.o?.... 00000030: 23a5 e19a 9908 1124 4700 0933 a2f4 d618 #......$G..3.... 00000040: 3afd 1ffa 545c ac49 df1d 619b f6c6 c1c1 :...T\.I..a..... 00000050: 15e4 ee0e eb97 a8b0 c114 4e5e a8d9 02f3 ..........N^.... 00000060: 01 . ``` [Try it online!](https://tio.run/##jdC7SoQxEAXg3qc4oJ0wzOS2ySpop4KIhSCICLmNCIrVdr7777i7xV86TQjhfJxJ27X2Od93X8vCx9mixxJRCws6Bwb3zNj0mpBzSlC1B9eaAPQ310Q/REp0TicHQcyIm9ChPBhjNgVHi4ccGb7njOkkoQhH4Pl@r9Dt4@X@PBrODM2pILtSock3xNocPHdBUq/I0gM4DWc9Pix48UJM31crw5vhfI2YYkYpnCHiAsKGbaviParTgJEkA6eHGmc3RH5lBDN81QFRrYghdtQeCobKQJLSrFtP6GK1sLXc0yvdEdX1LtEMiTNgTp6YrWxQc2MLiZWZcdp1FLBTf/zT/Ty8rYxkhv37/4aW5Rc "Bubblegum – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~218 217 200~~ 191 bytes ``` lambda:a+['*'*64]+a[::-1] D=2**31 a=[f'{y:68b}'.translate(' *'*25)for y in[4**7,30<<12,63<<12,31<<12,3143680,125828992,33554412,D//8-8,D//4-2,D-1,D-2,6082*D-1,16378*D-1,32766*D-2,458750*D-4]] ``` [Try it online!](https://tio.run/##LY7NCoMwEITvPoV4icbfZJO4it76FtZDSiu12CjqRUqf3UbpYflmdhiYaVufo4F9qa/7oN@3uy512BBKqBJtqJuyjFnrXGpOKTBH101HPlup8PYlyTprswx6ffjEtQUug26c3c3tTSMozSPIqorxSMEJYH8IUJhFjEvkWBT2A1IKYaNLmmKMB0RsXczs2XqGnB6GKcjxVMBzpegRCom5zKwUbbs709yb1feuxkteY29878/hHDbYYe7iB0Gw/wA "Python 3 – Try It Online") Terrible score, but I wanted to see how it would look with bitmasks in the style of a typical [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge *-1 thanks to @thedefault* *-17 thanks to @xnor* *-9 thanks to @benrg* --- # [Python 3](https://docs.python.org/3/), 165 bytes ``` lambda:a+["*"*64]+a[::-1];a=[''.join((i-31)%64*' *'[i-31>>6]for i in j)for j in b'T`@Rc@Qe@Rd@M` h@Hb o@Js a!@Gx@F{@D~@D}@7` d$\x7f@6j!\x7f@5l ~@1a m }'.split(b"@")] ``` [Try it online!](https://tio.run/##NY7BCoJAFEV/5SXFzBgKoikYxVtERdAiaaeCYxaNjKOkCyP01w2lVvfc1TnVu3mWyh7qTTRIXqQZ9/ky1HRNd514yUPfN6x4zTchIWZeCkWpMGyLLVxHJ6CTcHzbrRs/yhcIEApyNmI@YkquCQY3vNwxyPCcwBOPKZR4qoHP8NDi/oO7Hncdeglk86j1Hujms2lXEnq0OBTQEbOupGhoqqHG4qF6CdVQEqlf0D9MTmI5imvKGBu@ "Python 3 – Try It Online") Run-length encoded. [Answer] # [Python 2.6](https://docs.python.org/2.6/), 128 bytes ``` print"x\xda\xbd\x94\xa1\x15\x001\x0c\x85|\xa7@\xb3\xff\x80'\xbf\x0e\xe2\xf0\xf0\xfa\xda4\x14|E\xd2\xe2i\x14)\xa2\xa8\x1eM\x9dv\xb7\x99\xeb@_\xf4\xc7\x0b\x81\xd6p\xf4Hl\x88\xaaK\x84\x88#G\x1c\xca\xbd\xa1xi<;\xfd\x0c\xfd*\xfe\x7f\x93>\x1d}LC\xe3\xff\x8f\x1b\xd6G\x88\xf0\xe7\x12\xad\xcb{T\xd1*R=\xf0\x03-<\x12|".decode("zip") ``` This is an ASCII-fied version of the program. The actual program is encoded in latin-1 and looks like: ``` 00000000: 7072 696e 7422 78da bd94 a115 5c78 3030 print"x.....\x00 00000010: 310c 857c a740 b3ff 8027 bf0e e2f0 f0fa 1..|.@...'...... 00000020: da34 147c 45d2 e269 1429 a2a8 1e4d 9d76 .4.|E..i.)...M.v 00000030: b799 eb40 5ff4 c70b 81d6 70f4 486c 88aa ...@_.....p.Hl.. 00000040: 4b84 8823 471c cabd a178 693c 3bfd 0cfd K..#G....xi<;... 00000050: 2afe 7f93 3e1d 7d4c 43e3 ff8f 1bd6 4788 *...>.}LC.....G. 00000060: f0e7 12ad cb7b 54d1 2a52 3df0 032d 3c12 .....{T.*R=..-<. 00000070: 7c22 2e64 6563 6f64 6528 227a 6970 2229 |".decode("zip") ``` Since Python 2.7, the default encoding of a file is now ASCII instead of Latin-1, so you need to prepend the file with `#coding=L1` for the smaller version to run. [Try it online!](https://tio.run/##RVJda9swFH33r7gkD0pKEuwkXZquHYUxurEOxtZHwZAsORYklrBvGrnLfnt2tGSbQebcj3Pusa9Cz7Vv5tPQh/40pOfadRRav2nVjgBdQ0@KXTMtJnSoXVkTO0/G264RTN0@BN9yNqTvHq0dW2XoE9XqxRLX9p@Q6khRx61rNpBpHVtyTH7PE1BVY8hGW@45kRRnWaLRPWkRwOBBlNEoGbWRcb2UURUyFtdSxjwHyksZb66PSK8e0LOQsaqQyaVABJRbGe0c2fxyVFKDTLE8fgCcp7JL4RgaiNQNAvsFs8wLJFYAa/Tohx8gg1cik2uMwHDzJqTkxy1C0JT6DLBMwfARKrBWXoyrIrq7t2g2Z8uVucIL3lbwuF68Q7f59fQeg/5@AU6h04jHs3gybzG7SB6hUuqfzygXV9/uz8V8Mb1L5eNgZmzpjR0NXl0YjEWWHRzX5INtRmKH3223uvU8C72YkDhoMU4Lqm4zwlPN/uxnlHYwTqvABkh8vSxya5sN17fgAZ17IKF7tp04uV26DPR/wun0Gw "Python 2 (PyPy) – Try It Online") This is quite a boring answer: I zipped the original image into a string S then run `print S.decode('zip')`. [Answer] # [C (gcc)](https://gcc.gnu.org), ~~212~~ 200 bytes ``` double atof(),x;s;Y=16;main(a,b)int**b;{for(;--Y+16;puts(""))for(x=-1.975;s=x<2;x+=.035,printf(L" *"+s/251))for(_Complex y=x+Y*.0581i,z=a/3*y;s++<251&cabs(z=z*z+(a>2?atof(b[1])+1i*atof(b[2]):y))<2;);} ``` [Try it online!](https://tio.run/##LY7djoIwFIRfhXBhelqKFoO6e@x64a0vQIwxbQVDAkIsJoWNr27Fn8uZ@SYzhp@N8f7U3HSVB6prCgKRQ4uZFAusVXkhKtJQXjpKNf4XzZUg5xkbw/bWWRKGAC/TSS7in2WKVrp1go7JeDZPo/Y6NguyCwMaMjtNUvHBj9umbqvcBb10LKPxLF2JMhqkms5pj5ax9YhOjNKWDHKgAyPqL9m87@m9OAATJf2q5AC/PcA4Cnj3/mGKSp2t51X9BA "C (gcc) – Try It Online") Thanks to @KevinCruijssen for -1. [Julia set coordinates can be added as command line args.](https://tio.run/##LU7LisIwFP2V0sWQmzTVtNR5XKMLt/5AEZEkWim0tpgKacVfN2bGgbM5L84x/GyM98fupptTpIauIpA4tFhKscBW1ReiEg31ZaBU473qrgQ5L1kw@9tgSRwD/IpOcpF@fxZopVtm6JhM53mR9NfQrMg2jmjM7CwrxDt@2HRt35xcNErHSprOiy9RJ5NUs5yOaBlbhuiHUdqSSU50YkStsvXfPb0Te2Cipv8s28PPCBBGAR/e@zQPeJqqUWfredO@AA "C (gcc) – Try It Online") Slightly golfed less. ``` double atof(),x;s; Y=16; main(a,b)int**b;{ for(;--Y+16;puts("")) for(x=-1.975;s=x<2;x+=.035,printf(L" *"+s/251)) for(_Complex y=x+Y*.0581i,z=a/3*y;s++<251&cabs(z=z*z+(a>2?atof(b[1])+1i*atof(b[2]):y))<2;); } ``` [Answer] # [C, gcc](https://gcc.gnu.org), ~~141~~ ~~140~~ ~~138~~ ~~137~~ 136 bytes [Try it](https://tio.run/##JcrtCsIgFIDhWwl/hM5c6pgNzryDbmJJjgP7YlugRreeFf17eXid6J3LOVplTgHGDieK7OnnlYIQkSsDy2PfKCGM/TBY00AQApYVp93TKzkUhONZa/Uf9rjcZ09liSxZtBJcd9toYq0@Iuet1hKSTUUSoShlVfOyuvD4zbpRyOCV89v5oeu3LIbxAw) ``` y=16,x;main(i){for(;--y+16;puts(""))for(x=68;x--;printf(L" *"+i/221))for(typeof(0.i)z=i=0;cabs(z)<2&i++<220;z=z*z-x*.035+.37+y*.0581i);} ``` Compile using gcc. `-lm` may be required. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 87 bytes ``` jsX0_Bms.e*b@" *"kCMdc."n K{„‹–¥\dmnl4’_·N—2#‘¦óE,Á–¦#Óç>§óÔí¤:—A1åìJV~t…Á"\n*\*64 ``` [Try it here!](http://pythtemp.herokuapp.com/?code=jsX0_Bms.e%2ab%40%22+%2a%22kCMdc.%22%01n%0AK%15%7B%C2%84%12%C2%8B%C2%96%C2%A5%5Cdm%16nl4%C2%92_%C2%B7N%C2%972%23%C2%91%0B%C2%A6%C3%B3E%2C%C3%81%C2%96%C2%A6%23%C3%93%C3%A7%3E%C2%A7%C3%B3%C3%94%C3%AD%C2%A4%3A%C2%97A1%C3%A5%C3%ACJV%7Et%C2%85%C3%81%22%5Cn%2a%5C%2a64&debug=0) *Above preview does not display all characters in the code! The link leads to a working and copyable source.* [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 1700 bytes ``` {i}{i}{i}ii{c}{c}{c}{c}{c}ccc{i}c{d}{c}cccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}cccc{d}{c}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}{i}cccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}ccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}cccccc{i}c{d}c{i}ccccccccc{d}{c}c{d}{d}ddc{i}{i}ii{c}{c}{c}{c}c{i}ccc{d}c{i}{c}cccccc{d}ccccccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}ccc{i}{c}{c}{d}c{i}cc{d}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{i}{c}{c}ccccc{d}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccccc{i}{c}{c}cccccccc{d}c{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}c{d}{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}{d}c{d}{d}ddc{i}{i}ii{c}{c}cccc{i}c{d}c{i}ccccc{d}ccccc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}ccc{i}{c}c{d}cc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}cc{i}{c}ccc{d}c{i}{c}{c}{c}c{d}c{d}{d}ddc{i}{i}ii{c}cccccccc{i}cc{d}c{i}{c}cccc{d}c{i}{c}{c}{c}{d}cc{d}{d}ddc{i}{i}{i}ii{c}{c}{c}{c}{c}{c}cccc{d}cccc{d}{d}ddc{i}{i}ii{c}cccccccc{i}cc{d}c{i}{c}cccc{d}c{i}{c}{c}{c}{d}cc{d}{d}ddc{i}{i}ii{c}{c}cc{i}{c}ccc{d}c{i}{c}{c}{c}c{d}c{d}{d}ddc{i}{i}ii{c}{c}ccc{i}{c}c{d}cc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}cccc{i}c{d}c{i}ccccc{d}ccccc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}{d}c{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}c{d}{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccccc{i}{c}{c}cccccccc{d}c{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{i}{c}{c}ccccc{d}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}ccc{i}{c}{c}{d}c{i}cc{d}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}c{i}ccc{d}c{i}{c}cccccc{d}ccccccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}cccccc{i}c{d}c{i}ccccccccc{d}{c}c{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}ccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}{i}cccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}cccc{d}{c}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}ccc{i}c{d}{c}cccc{d}{d}ddc ``` [Try it online!](https://tio.run/##pZVLDgMhCIZP1EM10KasuzSe3XaEEWrUwZK4mDF8/DwU8XHHJ71ft1ISZV5ECbJdAPDdhoTyU78wI8IMOMzFjvELQOyV8Cr4APHNOTTU4GuaAUHVHWbjZKXN1LFO9cqucyQbO2vNAc2Hup0qecVpgK0WfmChMKr6WbYfzYVoM5WiubHWK22cZjiM2BSxb3fvY9TA4cFWfNLAoGgk30h1443dPk2B87p9MbZv4P83PTxeAqNte5JGZrX7NZi/N6V8AA "Deadfish~ – Try It Online") ]
[Question] [ Here is the (quite scary) Five little ducks song(it is not long): ``` Five little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only four little ducks came back. Four little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only three little ducks came back. Three little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only two little ducks came back. Two little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only one little duck came back. One little duck went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but none of the little ducks came back. Mother duck herself went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", and all of the little ducks came back. ``` Your task is not to output this song. You should take a verse and output the next verse, cyclically (the next verse of the last verse is the first verse). ## Rules * No standard loopholes, please. * Input/output will be taken via our standard input/output methods. * The *exact* verse must be outputted, and there should be no differences when compared to the song lyrics. The input will not be different when it is compared to the song lyrics too. ## Examples ``` Mother duck herself went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", and all of the little ducks came back. ``` Expected: ``` Five little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only four little ducks came back. ``` --- ``` Three little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only two little ducks came back. ``` Expected: ``` Two little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only one little duck came back. ``` ## The Catalogue The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](https://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 193467; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "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, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 500px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # JavaScript (ES9), 227 bytes This is similar to the Node version below but uses a formula based on `parseInt()` instead of `Buffer()` to identify the input verse. This is [ES2018](https://www.ecma-international.org/ecma-262/9.0/index.html) (aka ES9) because we're using a regular expression with the `/s` flag ([dotAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll)). ``` s=>'Mother duck herself1and all23,,Three4two3,Five4four3,Four4three3,One01but none23,Two4one0'.split`,`[parseInt(s,30)&7].replace(/\d/g,n=>[x=' little duck',y=/ w.*\n/s.exec(s),' of the',x+='s',x+y+'but only '][n])+s.slice(-11) ``` [Try it online!](https://tio.run/##vZTfb9owEMff81ecKnWOi2tIQZu0yexlVJqmCpWivgASbuKUbJ4dxQkhfz09B1S1pT@eyot99vl799Eld3/lWrq4yPLy3NhEbVOxdWJIrmy5UgUkVfwP0HBKp5E0CUitL/qMTVeFUoOytn12ma3VILVVgSaug9K7@mxsVC@6q0ow1iiUTGs7QKtHuMt1Vi7ZcpZLjPvblKFj/R798m3BC5VrGauwO0@698yI4WwjCODzUquWhbBGdKHmZ3PTdVxtVBw6ygjYFJCXsE1HEOe3pkN8cmt0A2QxMwvacdzpDIOfRxHd3o4mNyMQsPT4TzM4qJVBYSvGK9mwwK6xFBgfVpnWDnwdqhxkLRse7Av1yxfKySxhcHJdSTwcrCcseETy9XqeNZb/FdzhMx4ElwfeYzC1H@5tqOmh@yhUtX2H6aXzGEQ@9JOkz4DGL3yfzON7a//vv12kV1r5M7n2U@IDrGWwmwMhmZu5IfRHELQtyVNbjGS8CnEoQEZBDCG2xlmtuLb3YYrtDh1AUUhw352FgFY7CzO8iyicwtcF/AQy/kPgO5DRZDKekFZHfS66fQA "JavaScript (Node.js) – Try It Online") ### How? In this version, we parse the entire input verse as base 30 (`0` to `t`) and perform a bitwise AND with 7. The parsing stops on the first invalid character, leading to: ``` verse | valid part | base 30 -> decimal | AND 7 -------+------------+--------------------+------- 0 | 'fi' | 468 | 4 1 | 'fo' | 474 | 2 2 | 'three' | 23973734 | 6 3 | 't' | 29 | 5 4 | 'one' | 22304 | 0 5 | 'mother' | 554838747 | 3 ``` --- # [JavaScript (Node.js)](https://nodejs.org), ~~233 231~~ 227 bytes *Saved 2 bytes thanks to @Shaggy* ``` s=>'Three4two3,Four4three3,Mother duck herself1and all23,One01but none23,,,Two4one0,,Five4four3'.split`,`[Buffer(s)[2]%9].replace(/\d/g,n=>[x=' little duck',y=/ w.*\n/s.exec(s),' of the',x+='s',x+y+'but only '][n])+s.slice(-11) ``` [Try it online!](https://tio.run/##vZRRb9MwEMff8ylOkyYn1HOXtUIC5CIh2heEKkrFSxqpXnJZA8au4qRpPn13ziq0rQye1pfY5/P/7udzzj/VTrmsKrf1lbE5Hgp5cHLClpsKcVy3dsRntqnGtbdH/KutN1hB3mS/gCYOdRErk4PS@mbE5wav49umBmMNks35srVjml9zPit3OC4o1IgJt9Vlvebr5FNTFFiFLkpu0st3qahwq1WG4XCVD@@4kZNkLxnQ5lpjn5TxTg6hFW9WZugE7jEjMWdgCyAwxvcDyZwfugHzINboDliamDQaOOF0ScGv4jg6/Jguvk9BwtpzPc7goEVDwl5MS6rjgd3RmSk@bEqtHfgDN1tQrepEcKzIZ18Rp8qcw8W3RpFx8r3gwR8kX4inWTP1G@GWtokgmJ14z8HUX/HLUMtT91moWvsPpufOcxD50I@SPgGaP/O9Mo/vs@O//3KR/tKzr8l1fA7@g7UOHl6BkK3MyrDoQxD0LSkKW01VtglDx6GMQE4gs8ZZjULbu7CgdocBkChkND7YUkKvTcKS1uIILuFtCh@Bzb8weA9suljMF6zXRT5XdLgH "JavaScript (Node.js) – Try It Online") ### How? The third character of each input verse can be used as a unique identifier. By taking its ASCII code modulo 9, we get: ``` verse | 3rd char. | ASCII code | MOD 9 -------+-----------+------------+------- 0 | 'v' | 118 | 1 1 | 'u' | 117 | 0 2 | 'r' | 114 | 6 3 | 'o' | 111 | 3 4 | 'e' | 101 | 2 5 | 't' | 116 | 8 ``` The output verses are encoded with the following templates: ``` verse | template -------+--------------------------------- 0 | 'Five4four3' 1 | 'Four4three3' 2 | 'Three4two3' 3 | 'Two4one0' 4 | 'One01but none23' 5 | 'Mother duck herself1and all23' ``` Where each digit is replaced with a string according to the following table: ``` digit | replaced with -------+--------------------------------------------------- 0 | ' little duck' 1 | / w.*\n/s.exec(s) 2 | ' of the' 3 | ' little ducks' 4 | ' little ducks' + / w.*\n/s.exec(s) + 'but only ' ``` Where the regular expression `/ w.*\n/s` extracts this common part from the input: ``` went out one day,[LF] over the hills and up away.[LF] Mother Duck said, "Quack Quack Quack Quack",[LF] ``` We finally add the last 11 characters of the input, which is `" came back."`. [Answer] # [Python 3](https://docs.python.org/3/), ~~267 263~~ 254 bytes *4 bytes saved thanks to @ovs* ``` def f(s): for a in zip(T[2:]+T,T):s=s.replace(*a) return s T="8:9:and allHO1BnoneHT2No1T3Nt2F4Nt3FiveINf4MotherD herself" for r in "H of theI,4ourI,3hreeI,2woI,1neL:,ILs:,L littleD,D duck,NBonly ,Bbut ".split(','):T=T.replace(r[0],r[1:]) T=T.split(':') ``` [Try it online!](https://tio.run/##vZTBitswEIbveopBl9itGhonhVbgw4YQYki9W1Y3rw9KLBNRrWQkOSF9@VRKTOlu2Pa00UEgzeifbwT/dEe/M3p6OjWihTZxKUXQGgscpIZfsktYldH6IyMspS53Yys6xbci@cBTBFb43mpwiOX4K/1GuW6AK7W6n8y10WLFstJM2LT02XJW@ulS7kVRtrPvxu@EXUDYnFAtRrGgjQXxCkwLIVqQmeltQaY7K8IhO5iCTLRYU1KsHSVrUNJ7JRZkAU2//UnKudHqCGS@6T3gsetCPBmRUUpZzv5A2@pzTWw1oXWK4v2QRkfpaR9ZXI4xjpSD/FnbwUFoDyYIh56g4UeCTEiPmLCTSjmIffcd8AM/jtGlO1iEp@C4bAjgHz0Ph6sdE7Q5qwbyNrT7suqWPwvYhLQxQsur6C2YfPz8t6HYdfgmVAfzD6bXwVsQRem/ir4Aun8Ve2eeaLvBQm9/0qB65hk8@J5cw1T4D1Zw3uBH/KSfNE7ReSxIso@DQej@WVjuRXIxahxTYXVWap@0yT4NBMuHu7vicf2Iq3iR55fMSn76UlOa1QRH1dNv "Python 3 – Try It Online") Works by replacing the relevant parts by the respective parts of the next verse. After the preinitialisation, `T` is `['8', '9', 'and all of the little ducks', 'One little duck', 'but none of the little ducks', 'Two little ducks', 'but only one little duck', 'Three little ducks', 'but only two little ducks', 'Four little ducks', 'but only three little ducks', 'Five little ducks', 'but only four little ducks', 'Mother duck herself']`. # Alternative [Python 2](https://docs.python.org/2/), 252 bytes *by @ovs* ``` lambda s:reduce(lambda s,a:s.replace(*a),zip(T[2:]+T,T),s) T="8:9:and allHO1BnoneHT2No1T3Nt2F4Nt3FiveINf4MotherD herself" for r in "H of theI,4ourI,3hreeI,2woI,1neL:,ILs:,L littleD,D duck,NBonly ,Bbut ".split(','):T=T.replace(r[0],r[1:]) T=T.split(':') ``` [Try it online!](https://tio.run/##vZRBj9owEIXv@RUjX0haF5VApdZSDosQIhLNbrW@QQ5m44ioxo5sB0T/PB1Dtuou2va05GDJfpPnbyy9aY9@a3R6qrP1SYndphLgmJVV9yTj5z0VzA2tbJXAww8iob@aNuarlJUfOeUJdUnEM/KVfWNCVyCUWtyPptpoueBpYUZ8XPh0Pin8eN7sZV7Uk@/Gb6WdAS5OqppEtbFgodFAFmBqQDWnE9PZnI63VuImPZicjrRcMpovHaNLUI33Ss7oDJD1Jy2mRqsj0Omm80CGrkU9HtBBwnjG/8Db1eeS2tWIlQGZP5exQXLaBxaXEUICZW9/9nZwkNqDQWPsCSpxpJHB8oAJ20YpB6HvrgVxEMdhdOkOZvgrONFUFMiPTuDmaiU02pxdkbzGdl/e@iR2EjZYNoyi@ZV6CyYfHv9tKH4t34TqYP7B9Fq8BVGw/uvSF0D3r7R35gmx6yP09iP1rmeePoPvydVPhf9gYfL6PJK1XmuSROex0NB9GAxSdztphZfxJagJiwC/1jaIXcf7BAnmD3d3@ePykazCQZZdKlfNpy8lY2lJ0ZecfgM "Python 2 – Try It Online") [Answer] # [QuadR](https://github.com/abrudz/QuadRS), ~~257~~ 242 bytes -14 thanks to Black Owl Kai, -1 thanks to Kevin Cruijssen ``` ive Four hree Two( little duck)s One little( duck) Mother( duck) herself four two( little duck)s only on(e little duck) but none and all of the our Three wo One\1 Mother\1 herself Five little\1s three one\1 none of th\1s and all but only four ``` [Try it online!](https://tio.run/##ZZDNasMwEITv@xRLTi6YgN@h@FZKIEdfNvEamyraVj82fnpnJYsmIRehHc1@M@gvUu@2bZoZWokORscM50UqNFMIhrGP158PD9@Wi1LtEnxJGNmVCfXq2QwwJEh43xdrVhRb8YsOlxjQimUg2yMZgzKgYiFRzrnLIim7a0pe1/xHtVq60LrGQ8h2yd6E3FHppbBzWO6RSm5b5j/X8biwVUu2qURrDTKzS41wnIzxmFDxF2mh9Vga4aeuoqepr/FwiqTD23moH@H6Oa@hV7oxXtR1vAM "QuadR – Try It Online") [Answer] # T-SQL, ~~407 390 388~~ 382 bytes ``` DECLARE @ CHAR(999)=REPLACE(REPLACE('SELECT CASE LEFT(v,2)WHEN''Fi74,''Four''),122,4,''three'')WHEN''Fo74,''Three''),123,5,''two'')WHEN''Th75,''Two''),121,16,''on#'')WHEN''Tw716,''On#''),115,20,''none of th#s'')WHEN''On715,''Mother duck herself''),115,8,''and all'')WHEN''Mo719,''Fiv#s''),113,14,''but only four'')END FROM i',7,'''THEN STUFF(STUFF(v,1,'),'#','e little duck')EXEC(@) ``` Input is via a pre-existing table \$i\$ with `VARCHAR(MAX)` field \$v\$, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). After a couple of byte-saving `REPLACE`s, executes the following as dynamic SQL: ``` SELECT CASE LEFT(v,2) WHEN'Fi'THEN STUFF(STUFF(v,1,4,'Four'),122,4,'three') WHEN'Fo'THEN STUFF(STUFF(v,1,4,'Three'),123,5,'two') WHEN'Th'THEN STUFF(STUFF(v,1,5,'Two'),121,16,'one little duck') WHEN'Tw'THEN STUFF(STUFF(v,1,16,'One little duck'),115,20,'none of the little ducks') WHEN'On'THEN STUFF(STUFF(v,1,15,'Mother duck herself'),115,8,'and all') WHEN'Mo'THEN STUFF(STUFF(v,1,19,'Five little ducks'),113,14,'but only four')END FROM i ``` Uses a `CASE` statement and `STUFF` commands to insert/overwrite characters at the listed positions. **EDITS**: 1. Replace original (below) with an entirely different strategy 2. Saved two bytes by switching to `LEFT` instead of `SUBSTRING` and eliminating a space 3. Saved 6 bytes by changing variable to `CHAR` and moving an extra letter into the second `REPLACE` (thanks, @CDC!) Here's my first version, using a different method (post-replacement, formatted): ``` DECLARE @ VARCHAR(MAX) SELECT @=v FROM i SELECT @=REPLACE(@,PARSENAME(value,2),PARSENAME(value,1)) FROM string_split('e.but none.and all -e.One little duck.Mother duck herself -o.only one little duck.none of the little ducks -o.Two little ducks.One little duck -r.two little ducks.one little duck -r.Three.Two -u.three.two -u.Four.Three -v.four.three -v.Five.Four -t.and all of the.but only four -t.Mother duck herself.Five little ducks','-') WHERE LEFT(value,1)=SUBSTRING(@,3,1) PRINT @ ``` `STRING_SPLIT` and `PARSENAME` are used to break a string into rows and columns via `-` and `.` separators. The first column is a key character that is matched against the 3rd letter of the input verse (thanks for the idea, @Night2). The second and third are the replacements being performed for that verse. [Answer] # Java 10, 347 bytes ``` s->{String L=" little duck",M="Mother duck herself";int i=9;for(var t:("ive;Four;hree;Two"+L+"s;One"+L+";four;two"+L+"s;only one"+L+";but none;and all of the;"+M).split(";"))s=s.replace(t,++i+"");for(var t:("Five"+L+"s;but only four;and all;none of the"+L+"s;one"+L+";three;"+M+";One"+L+";wo;Three;our").split(";"))s=s.replace(i--+"",t);return s;} ``` [Try it online.](https://tio.run/##vZVNi9swEIbv@ysGnWz8QU@FRriXLguFzYayuTU9KLay0a4iGUm2CYt/ezrWKmmy2SSl0FyMPl7mfWYGjZ9Zy7Ln6mVTSmYtjJlQrzcAQjluFqzk8DBsAR6dEeoJyigsbEzxvL/Bj3XMiRIeQEGxsdnX1yC5LwhI4ZzkUDXlC0nHBRlrt@TG7wEXlssFoWgGovhCF9pELTPgRhERLad3ujF0aTin006T5D4hlk4U9ysU46XbnWsl16C3l/PGgcIdZaoCJiXoBaAxJck4zm2NVBGhJI5tYXPDa4mJRi5NEpEQEh9w3CFIsBiCehtvHSLTwSaE36EECufZ0RPXO@5O06k/xyDkJIzIMkRJXUwNd41RYGm/GSpeN3OJxQ41b7WoYIU9C235@QtY/NawIYnQCMet@8YshxEo3sFW@qYD8Dnud8pCx7El2ueLR2ydzpRusW@YJCyFlBaG9JsaWMfW@UyFtt4ObbVMVCnMyI@G4e7oOyMY7KCUh9YlW3GYozAn6Q7wSHU1QN/Dy4TTY9n1EDv9F4DvRVfDG@LvOX9IN3mnuQbc3sO9XL4P5tZ/hzycXScZPWIfb1/z49o6vsqRK6/xnTupIj@qT9yR72oE5JxiOz3Oac46TBp3wULl5R@bf/bJyDA@OXPR50/bKL3/SfWb3w) **Explanation:** We first replace all parts one by one with integers in the range \$[10,21]\$, and then these integers back to their replacements. The reason this is done in two steps, is because we would otherwise replace replacements. ``` s->{ // Method with String as both parameter and return-type String L=" little duck",M="Mother duck herself"; // Two temp strings to save bytes int i=9; // Temp replacement integer, starting at 9 for(var t:("ive;Four;hree;Two"+L+"s;One"+L+";four;two"+L+"s;only one"+L+";but none;and all of the;"+M).split(";")) // Loop over the parts to replace: s=s.replace(t, // Replace the part, ++i+""); // with the integer pre-incremented by 1 for(var t:("Five"+L+"s;but only four;and all;none of the"+L+"s;one"+L+";three;"+M+";One"+L+";wo;Three;our").split(";")) // Then loop over the parts to replace with in reverse: s=s.replace(i--+"", // Replace the (post-decrementing) integer, t); // with the replacement-part return s;} // And then return the modified String as result ``` [Answer] # [Python 2](https://docs.python.org/2/), 1034 bytes This is my code! It employs a simple dictionary. After running this code, you can enter any verse and it will output the next verse. PS: I am new to this channel and this is my first post. I really liked this challenge so decided to give it a try. Please feel free to correct me. ``` import sys i=sys.stdin.readlines() s={"Mother":"""Five little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only four little ducks came back.""", "Five":"""Four little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only three little ducks came back.""", "Four":"""Three little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only two little ducks came back.""", "Three":"""Two little ducks went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but only one little duck came back.""", "Two":"""One little duck went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", but none of the little ducks came back.""", "One":"""Mother duck herself went out one day, over the hills and up away. Mother Duck said, "Quack Quack Quack Quack", and all of the little ducks came back."""} print s[i[0].split(" ")[0]] ``` [Answer] # [PHP](https://php.net/) (7.4), ~~253~~ 247 bytes -6 bytes by improving how the replacements array is built with more help from "Unpacking inside arrays". ``` <?=strtr($argv[1],array_combine([0,1,...$a=[Five.$l=($o=" little duck").s,($b="but only ").four.$l,Four.$l,$b.three.$l,Three.$l,$b.two.$l,Two.$l,$b.one.$o,One.$o,"but none of the$l","Mother duck herself","and all of the$l"]],[...$a,$a[0],$a[1]])); ``` [Try it online!](https://tio.run/##bVDBaoUwELz7FUvIQWEJz3MrvZR3K6XQm0hZNVZpXiJJVPx6u/peaUt72dmdDLOzGftx2@4fihB99Kkk/z6XeYXkPa1vjbvUg9VpecIclVKSivI8zFpJU6TSFQLMEKPR0E7Nh8hUwFTWhainCM6aFZjq3ORZjucbylrF3uvdAl@/mp1c3EFdgQln@cnh8xUOT8scuA5ir6URKJ4cd/5YDtwEbTpmybZAxnwLqwrLIzxKKk/VXvOqyrK7bdv@sYBFW85/3MCX0YqJm1nDQugHYwLsG6YRaKFVJTeHx90h0NAiiJeJePhTBSa/s/38vQANXTTUrFOf "PHP – Try It Online") This creates an array of every possible replacement (12 used + 2 unused) in a `key=>value` format. Example: `['Mother duck herself' => 'Five little ducks', etc...]` and then just replaces those using [strtr](https://www.php.net/manual/en/function.strtr.php). The only interesting thing is my first ever usage of ["Unpacking inside arrays"](https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.unpack-inside-array) which is a new feature in PHP 7.4. --- # [PHP](https://php.net/), 264 bytes ``` <?=str_replace(($a=[[Five.$l=($o=" little duck").s,($b="but only ").four.$l],[Four.$l,$b.three.$l],[Three.$l,$b.two.$l],[Two.$l,$b.one.$o],[One.$o,"but none of the$l"],["Mother duck herself","and all of the$l"]])[$i=strpos(vuroet,($v=$argv[1])[2])],$a[++$i%6],$v); ``` [Try it online!](https://tio.run/##bZDNSsUwEIX3fYohRGi5oaALNxrcyN2JCO5CkbRNbTA2JX@lT1@nuV1c0U04@eYwM2fmcd62xyfug/twajayU2VJJRfirJOqqeEltZyA0SEYBX3svkhVe1bSlpM2BrCTWQHRYKNDe8PE@aIYbeswOqUu9P2QGS/2gFnsyE5YtIhes2C594QU7ABhVNQQLJIXi9rlNQCFV2YgjMipB2nMlbWpBNV7qNn6MkVnVcCVE6fSfSZxi@W7pmoYleJ0ovrmHmWqHrZt@2cALGrCnDkrXkCurLAJPWiEURvjYZ8fZ5CLXOvi6PC8d/BS9wzIW5T4@fMSVvze/PrKHjr5raBFX/0D "PHP – Try It Online") I have stored different words of each verse in an array. I find which verse the input is using third character of the input as it is unique (`vuroet`). Then I simply replace different words of that verse with different words of the next verse. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 352 bytes ``` import StdEnv,Text $n={#"Five"+e+"four"+d,"Four"+e+"three"+d,"Three"+e+"two"+d,"Two"+e+"one"+a,"One"+a+b+"but none"+f,"Mother duck herself"+b+"and all"+f}.[indexOf{n.[2]}"tvuroe"]+" came back." a=" little duck" b=" went out one day,\nover the hills and up away.\nMother Duck said, \"Quack Quack Quack Quack\",\n" d=a+"s" e=d+b+"but only " f=" of the"+d ``` [Try it online!](https://tio.run/##ZZDBbsIwDIbvfQrL49bSw@69MaRJm9gEN8rBNMmISJ2qTQsV4tXXOWU7TYri378sf7Yrp4mn2qveaajJ8mTrxrcBtkG98JDt9DUkCy5uT7i2g8ZUp2h832KqMlzPQpxwarWerd1DRe/iH06MknsWnzLczDE9pnjsA/BsmwzffTjpFlRfnUFEp53BWESsgJyTmnu@t6z0dWNunO@fD3cMQ996jYcUoaJaw5Gqc44JFQjOhiAbxXaYHMW4aA7ghShAUDRmJftBgEKFk3Wug0jqG6ALjXnJv/Os4jwdWZVBiZ@9AODfX6I0w0QVlGKHiS7U33ae3QiYGOF7E1FykWkbSO5bwALiLfI8x@m7Mo6@umn5@jatRqbaVo/kw1Ewvq2npZPXMTXN@AM "Clean – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 262 bytes ``` x=>$@"{l[g=x[2]*37%724%7]}{g-5:; little} duck{g-4: herself;s;\} went out one day, {(x=x.Split('\n'))[1]} {x[2]} {g-5:and;but} {g-4:all;only;none} {(g>3?"of the":l[g+1].ToLower())} little duc{g%3:ks;;k} came back.";var l=" Four Three Two One Mother".Split();int g ``` [Try it online!](https://tio.run/##bZFNb8IwDIbv/RVWNEQ7GBpfQmpW4DBxYpqmIe0AHEKblqhZMiUtUFX97cxhO4C2Q@LIsl8/rxPbh9iK86JU8VNSKfYp4q4tjFDZNI3Op2h6Nye1XGfRaT3Y3g8nrclg1Jpsmzp7GIcUpCgKyRtIyjjH1CiEPTeWy5RaumngyFUBusSjOCSs6nq1f4pOvfcvbPTbG9UOgnV/23i1k8fgVJlK6K4sGrgIMimpVrKiCjUw52fT4YzoFIo9JyGSdfrb3kov9ZEbPwiaXyRHVGetYZhbSvMGYvbJYcfivEfogRmQEYGFLg2s9oZzWB01vCLji0ZZQ34BAyqQPztT72clwCCCOVmIA78ak9t/fOoDNw4R9kJKC@gJyi9gR1b1vJ8h8IytYJlIukDIW4ls8OcmpOvtLrqygtTx3sy9duV9GFHwpVDcZwH1Um18Ry8Q@ZFieIIxhk4ngPqqFCudqfTSc6vQnLMoGs3c3kN8jWf4FaED@QY "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~115~~ 111 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` τ*^&k─Zè0µ9┬$█◘çl╟☼:Drσ59ò╠▄┴╢Q♂╔¡ô╜Oa╣▀yèA÷╨%^♀█Ö+╡◄ì=∙%╧o▌Θ<▲Çα¿╗√;1°┼╤V◘ú┐♥▒ÇM☼b╩░o]YaL4░ƒ%(Æ♫Q0æÆä⌂¡╘○Eâó╪¡ ``` [Run and debug it](https://staxlang.xyz/#p=e72a5e266bc45a8a30e639c224db08876cc70f3a4472e5353995ccdcc1b6510bc9ad93bd4f61b9df798a41f6d0255e0cdb992bb5118d3df925cf6fdde93c1e80e0a8bbfb3b31f8c5d15608a3bf03b1804d0f62cab06f5d59614c34b09f2528920e51309192847fadd4094583a2d8ad&i=Five+little+ducks+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Abut+only+four+little+ducks+came+back.&a=1&m=1) [All the verses as test cases](https://staxlang.xyz/#p=e72a5e266bc45a8a30e639c224db08876cc70f3a4472e5353995ccdcc1b6510bc9ad93bd4f61b9df798a41f6d0255e0cdb992bb5118d3df925cf6fdde93c1e80e0a8bbfb3b31f8c5d15608a3bf03b1804d0f62cab06f5d59614c34b09f2528920e51309192847fadd4094583a2d8ad&i=Five+little+ducks+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Abut+only+four+little+ducks+came+back.%0A%0AFour+little+ducks+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Abut+only+three+little+ducks+came+back.%0A%0AThree+little+ducks+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Abut+only+two+little+ducks+came+back.%0A%0ATwo+little+ducks+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Abut+only+one+little+duck+came+back.%0A%0AOne+little+duck+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Abut+none+of+the+little+ducks+came+back.%0A%0AMother+duck+herself+went+out+one+day,%0Aover+the+hills+and+up+away.%0AMother+Duck+said,+%22Quack+Quack+Quack+Quack%22,%0Aand+all+of+the+little+ducks+came+back.&a=1&m=1) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~356~~ ~~343~~ ~~340~~ 336 bytes ``` param($p)$l,$M=' little duck','Mother duck herself' ("ive!our;four!three;hree!wo;Four!Three;two!one;s c! c;Two!One;s w! w;only one!none of the;k c!ks c;One$l!$M;but none!and all;$M!Five$l`s;and all of the!but only four"-split';')[$(switch -r($p){^Fi{0,1}^Fo{2,3}^Th{2,4,5}^Tw{6..9}^O{10,11}^M{12,13}})]|%{$p=$p-creplace($_-split'!')} $p ``` [Try it online](https://tio.run/##vVRNa@MwEL3rV4yMsrapYpp@LOyKQA9LbiYs5FaaVnUUbKJaXn/UG1T/9nRkzJI0ZXNqLiPPmyfNm5FHhWlVWaVK6x1bwxTsrpClfAlYETLNWTz1QWd1rRWsmmTjcz82darK3gP8qJRe@yTwsldFTVOKNRpap6VSwhnaGjFz0KKH6tZQkytRQUIhEQt0573bUmiFyfUWMExzNGDWgJnEBqkb5AskMk1ZLJ6bGhyDynwFUmvBYjrD/Ew/VWLAht3UcftjnS5vXBVYjC/88J4FVZvVSQrj0tVql7PMXvJJt5wZe8Wvu@UixfWG3@JXa79H0Y9uObcTpCAntpMrPrnuuvDhbWRZMWXFOClVoWWiAvY4pKF@2BFW7DpC2KvrVIX9vfOJ07rfVKxe5Sizl4qQ3HJicIMrANJM6wpcVU0BspXbiAw38MvdQCWzFQfvdyPRObIeJwcNOMyayBcFz0iLiH/He2VHnHMo6/@WU9IWx6SzaGvNSWUfKefQ5Y7eS/qJrPkHxher2hvZUw375AX5SnWHL8J/xOGYZjihl/@m9Q1GYAlAD19c4DKCIRYlpslrF/uLsQG8Z9mDg0qEvgE@p@wRXY8FSBqrPxgIfz7lzJadRzqyewc). **More readable version:** ``` param($p) $l, $M = ' little duck', 'Mother duck herself' $replacements = @" ive!our four!three hree!wo Four!Three two!one s c! c Two!One s w! w only one!none of the k c!ks c One$l!$M but none!and all $M!Five$l`s and all of the!but only four "@ -split '\n' $i = switch -regex ($p) { ^Fi { 0, 1 } ^Fo { 2, 3 } ^Th { 2, 4, 5 } ^Tw { 6..9 } ^O { 10, 11 } ^M { 12, 13 } } $replacements[$i] | % { $p = $p -creplace ( $_ -split '!' ) } $p ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~265~~ ~~263~~ ~~255~~ ~~251~~ 246 bytes ``` $d='Five1four2s,Four1three2s,Three1two2s,Two1one2,One23but none52s,Mother duck herself3and all52s'-split',' '2s34',' little duck',-join($args-split'(\s)')[5..39],'but only ',' of the'|%{$d=$d-replace++$i,$_} $d[+"$args"[2]*37%724%7]+' came back.' ``` [Try it online!](https://tio.run/##vVTBbuIwEL37K0apWcNiUJOA0B6QOKx6W1Ur9cZGlZs4Ja2Js3FCFlG@nR2HhM2WSpxKDvb4zYzf80Qzma5kblZSqQON57sDjebsLtlIN9Zl7hl@h5tbrHIp8fBgd7eotLUr7epUevweF/@pLCDF4xQ9P3SxkjlEZfgKaBipYl@kEQil0M1GJlNJwTgjzDP@BA3Ac6FkncH46EUnaZ@K/Nk0of1fZsAGy@l47H8LOLNcOlVbsKk6BmRjb70dKqfRKJeZEqEcDmnC6eOe0Gg5dOrLnKUXfPVnvZk36c2CIYNQrCU8ifB1zA57QqjR6TPMYeEQW4CuKAOVTJG0JkZIbDnRG3wjUsMqUcqAfWCZgajEdkyaCny3FTAiiTg4P0skgrPV4eT0HFvx/1n/KSTOglthZyHXEFb//gvKHs5jriKt0peEvY@4hix7dYf0XNX9u4BPFmVbs2mVC@X6oHk/U1wzFy5rI2TRJ4T36y5dTgN@NG6DwQm8bUG3A7ot6HVArwX9Dui34KQDTlpwiiAZwBv0YEcAP7qx1eFA5Z9MhoWMcHTQx6Mrl6ZUBQJfaNwEdh2jUP4@pdWOmzblBso01Ou1rXihIUpwAootNN7jTfvDXw "PowerShell – Try It Online") I used the brute force to find the expression `+"$args"[2]*37%724%7`. ``` verse | 3rd char. | ASCII code | *37%724%7 -------+-----------+------------+----------- 0 | 'v' | 118 | 1 1 | 'u' | 117 | 2 2 | 'r' | 114 | 3 3 | 'o' | 111 | 4 4 | 'e' | 101 | 5 5 | 't' | 116 | 0 ``` Thanks [@Arnauld](https://codegolf.stackexchange.com/a/193474/80745) for the `3rd char`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 134 bytes ``` “€µ‚•„í†ìˆÈ“#’ „ê Ðœs’δJ樅î¥Ðœº¶s‚ìðδJD…€³€É δ쨦“€ƒ€Ÿ€‚€€““€³Šª€‚€€“‚’ „ê Ðœs ’δJ셋邃.δJU.•4Ôāl•|н2èk©è.ª?I„ ý#3.$17£ðý„ ¶:,X®è? ``` [Try it online!](https://tio.run/##ZU9NSwJRFN3Pr7hoy2GgDwjauJGgoEWLoO1TXzg4OjEfykCLV4s@dmFtEgkpklEmETSpwM276iaQfsP7I9MdbVMu3uHec@495z7bZTmTx7ESTXURyTclGko8KfGIr0q0MPq6xGvS0ko8QMJ2AW@ndy618@H@5EqGSrSxJ18SVn7KESkNjLBPapakxHNAgDcwH2IkQ9leJs3qBNN3giSRMCmav1cMpi3ZXZEa/26A5REYJTniAzs0MqsbRB0Z9IctvJ@cW1ScfY83MCzJDoaG7Gb2yAI0HKc3jbX1bfmMfRwvKDna0Y9lD8NMHO@aVQ6W6XkWh4KfL7lQ4xUPbJ9ehSgW6Jpd5Q54RQ5F07JcYJUC@KfAaiwwtAObBAeytAouMws6pA59Rs0KpnQtt3C1Ajixfedvap6VOeRozPgB "05AB1E – Try It Online") Since i'm relatively new to 05AB1E, this can maybe be golfed a lot ``` ### Preparation of the output strings ### “€µ‚•„í†ìˆÈ“ push "one two three four five" # split that by spaces ’ „ê Ðœs’ push " little ducks" δJ join each number with " little ducks" ć¨ separate "one little ducks" and drop the "s" …î¥Ðœº¶ push "mother duck herself" s swap it with "one little duck" ‚ì prepend both strings to the list ["mother duck herself", "one little duck", "two little ducks" ... ] ðδJ append a space to each list entry D duplicate it …€³€É push "but only " δì prepend "but only " to each list entry ¨¦ drop the first and last list entry “€ƒ€Ÿ€‚€€“ push "and all of the" “€³Šª€‚€€“ push "but none of the" ‚ push the two strings into a list ’ „ê Ðœs ’δJ append " little ducks " to each ì prepend it to the sentence list ["and all of the little ducks ", "but none of the little ducks ", "but only one little duck " ...] …‹é‚ƒ. push "came back." δJ append that to each list entry U save that list in X for later use ### Determine which verse has to be answered ### .•4Ôāl• push "eoruvt" |н2è get the third letter of the input k get the index of that letter in "eoruvt". Now we know which verse we must return © save that index in ® for later use ### Print the answer strings ### è.ª? print that index of the first sentence list (first three words of answer) I„ join the four input strings by <space><newline> ý # split that by spaces 3.$ cut off the first three words 17£ keep only the next 17 words ðý join remaining words by spaces „ ¶: replace <space><newline> by only <newline> , print that ("went out ... Quack\",") X®è? print the last line of answer ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 143 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Tried encoding a single verse with replacements but, in the end, adapting [Arnauld's solution](https://codegolf.stackexchange.com/a/193474/58974) ended up being shorter. Have another idea that might, hopefully, work out shorter again but don't know when I'll get to try it. ``` tBn)i`Fr4È(e3 Two4e0 MÇ@r Ýõ Êelf1d a¥23 O01¿t Í 23 TËG4two3 Five4fr3`·g`v`b¢Î)r\dÈ°g[V=` Ò¤ Ýõ`W=Uf/ w.*\n/s ` e`V±'sV+W+`¿t § `] ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=dEJuKWlgRoxyNMgoZTMKVHdvNI1lMApNx0ByIN31IMoEZWxmMYRkIGGlMjMKT5owMb90IM0KMjMKVMtHNHR3bzMKRml2ZTRmjHIzYLdnYHacjGBios4pclxkyLBnW1Y9YCDSlaQg3fVgVz1VZi8gdy4qXG4vcyBgII8gkGVgVrEnc1YrVytgv3QgjacgYF0&footer=K1I&input=WwonTW90aGVyIGR1Y2sgaGVyc2VsZiB3ZW50IG91dCBvbmUgZGF5LApvdmVyIHRoZSBoaWxscyBhbmQgdXAgYXdheS4KTW90aGVyIER1Y2sgc2FpZCwgIlF1YWNrIFF1YWNrIFF1YWNrIFF1YWNrIiwKYW5kIGFsbCBvZiB0aGUgbGl0dGxlIGR1Y2tzIGNhbWUgYmFjay4nCgonRml2ZSBsaXR0bGUgZHVja3Mgd2VudCBvdXQgb25lIGRheSwKb3ZlciB0aGUgaGlsbHMgYW5kIHVwIGF3YXkuCk1vdGhlciBEdWNrIHNhaWQsICJRdWFjayBRdWFjayBRdWFjayBRdWFjayIsCmJ1dCBvbmx5IGZvdXIgbGl0dGxlIGR1Y2tzIGNhbWUgYmFjay4nCgonRm91ciBsaXR0bGUgZHVja3Mgd2VudCBvdXQgb25lIGRheSwKb3ZlciB0aGUgaGlsbHMgYW5kIHVwIGF3YXkuCk1vdGhlciBEdWNrIHNhaWQsICJRdWFjayBRdWFjayBRdWFjayBRdWFjayIsCmJ1dCBvbmx5IHRocmVlIGxpdHRsZSBkdWNrcyBjYW1lIGJhY2suJwoKJ1RocmVlIGxpdHRsZSBkdWNrcyB3ZW50IG91dCBvbmUgZGF5LApvdmVyIHRoZSBoaWxscyBhbmQgdXAgYXdheS4KTW90aGVyIER1Y2sgc2FpZCwgIlF1YWNrIFF1YWNrIFF1YWNrIFF1YWNrIiwKYnV0IG9ubHkgdHdvIGxpdHRsZSBkdWNrcyBjYW1lIGJhY2suJwoKJ1R3byBsaXR0bGUgZHVja3Mgd2VudCBvdXQgb25lIGRheSwKb3ZlciB0aGUgaGlsbHMgYW5kIHVwIGF3YXkuCk1vdGhlciBEdWNrIHNhaWQsICJRdWFjayBRdWFjayBRdWFjayBRdWFjayIsCmJ1dCBvbmx5IG9uZSBsaXR0bGUgZHVjayBjYW1lIGJhY2suJwoKJ09uZSBsaXR0bGUgZHVjayB3ZW50IG91dCBvbmUgZGF5LApvdmVyIHRoZSBoaWxscyBhbmQgdXAgYXdheS4KTW90aGVyIER1Y2sgc2FpZCwgIlF1YWNrIFF1YWNrIFF1YWNrIFF1YWNrIiwKYnV0IG5vbmUgb2YgdGhlIGxpdHRsZSBkdWNrcyBjYW1lIGJhY2suJwpdLW1S) - includes all verses [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 156 bytes ``` ≔⌕tvuroe§θ²δ§⪪”↶0∨↘»≔xj➙⌈´βXPNLA‽⟦O⧴&▷V'¦³≧ψZρ⊞t”¶δF‹δ⁵”↶↧V4ⅉH‴G%”F‹δ⁴s⮌…⮌θ¹⁸⸿η⸿ζ⸿§⪪”}∧h⁴NQ≕Q^⪫ΦG✂q'ⅉMG./_⸿s⁵6P⁴″⊟±NNpOfBz↷Fι‖TM→⁻γ?k⁴ς!d⁵º'E,θ}x§-υ”¶δ✂ε±¹¹ ``` [Try it online!](https://tio.run/##fVFBTsMwELznFSufHClUKgIJiVNVFAkJKNAec3GTTWNh7NZ2EsLnwyaFlIaWi2XP7M7sjtNC2NQI1bYz5@RG81jqjDNfldYgi2Dm73WGH3wXwWUYRpCFt8GzldrzH2a5VdJzFssKEx2b0iZ6VVikx6o2iV5ouj0aX6CFrEzfgC4OVU7aLNGslyTN3FjgD@gczyK4DkPYmzAgca@wb2XjuqtDnWPDYK9YdRZ83qQK54XZDsiO3KY3YTiUssQe@orT8OdpeLT@uvRgtGogpwR@D@0SPXC@y@UsWZtzlNFHXXtGd6jJSXQsKXQGQqlT5Cj1/SpLJVPkGMETboRHPp12EbXt4tgWatQ0UD8UIaKJAkO59h6FVMpBZ1xuQdSimQTff37XdToh6bvYSyno8edkUfDfQpCKd4Q1FU7ai0p9AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⌕tvuroe§θ²δ ``` Look at the third character of the first line to work out which verse we want. ``` §⪪”↶0∨↘»≔xj➙⌈´βXPNLA‽⟦O⧴&▷V'¦³≧ψZρ⊞t”¶δF‹δ⁵”↶↧V4ⅉH‴G%”F‹δ⁴s⮌…⮌θ¹⁸ ``` Output the first part of the first line by indexing into the list of strings `Five`, `Four`, `Three`, `Two`, `One`, `Mother duck herself`. Then print `little duck` and `s` as appropriate, followed by the last 18 characters of the input line (which are always the same on each verse). ``` ⸿η⸿ζ⸿ ``` The middle two lines are always the same on each verse. ``` §⪪”}∧h⁴NQ≕Q^⪫ΦG✂q'ⅉMG./_⸿s⁵6P⁴″⊟±NNpOfBz↷Fι‖TM→⁻γ?k⁴ς!d⁵º'E,θ}x§-υ”¶δ✂ε±¹¹ ``` For the last line it turns out to be golfier to include `little ducks` in the list of alternatives for some reason, but the last 11 characters are still copied from the input. [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~373~~ 355 bytes Nothing too crazy here. An easy few byte reduction would be to replace the two-character variables (a1,a2,a3,e1..e6) with single character ones. ``` read a{1..3} b read c read d read e{1..6} W="$e1 $e2" X="${e3^} $a2 $a3" Y="$e5 $e6" Z="$e4 $Y" p=$X case $a1 in M*)p="Five ${Y::12}";s="but only four $Y";;O*)p="${d::11} herself";s="and all of $Z";;Tw*)p=${X/s};s="$e1 none of the $a2 ducks $e6";;Th*)s="$W one $e4 duck $e6";;Fo*)s="$W two $Z";;Fi*)s="$W three $Z";;esac echo $p $b;echo $c;echo $d;echo $s ``` [Try it online!](https://tio.run/##ZZDLasMwEEX3@opBaJMQXJy0WcR4V7ILpVDIY1GQ5QkyVS1j2THB@NvdkewWQhfSPO6RdEeZdHoca5Q5yD6Oos0AGQulmkI@BfTidmDHlAuMQeCasxPlPW4@BxByTWvD2dnLLyRvObv4/BnEmbMqFSempEOiYihKOCwXVcr3xY06/Xm3i9cDT1zKs7YBW5o7XG1b@6NJ8hZQ0edExQNorB2aa6BlSa6NAXsFcSH0o/Os6E9PbvC6d1raEj3QaAw281Z9uWCQeL1ceOwIHvJmvTqLe/srNp2d7t8Xfy1dI05NdFIxVJqYCkSWTKmaYz5HN45hWlM0jcHZRYcljRtGppa8r5i9YR2s6sIYB37AtgLZyXvEDpaEGl69RSeLfAX8vZVU/Nv5ij1@5MOrSn4jZIRFPw "Bash – Try It Online") ~~[Try it online!](https://tio.run/##ZZDBasMwDIbvfgphfFhHyUi79dBQ2GH0VkZh0HaHgeOoOMyLS5w0lOBnzyynO4QdLFn6P@FfzqXTw7B/mPUMlbYgXplnNcoCZJ8mydJDPpZqTMWYkMSVZ4cNF5iCwAVnx3DvcfnlQchFOEvOTiS/BHnF2Sfdn0GcOFPSYQBSKCu2e5xdNnxbXkOnP63X6cLzzG143jZgK3ODs21rmsoy9h5Z0RcBSz1orB2ac8RlFRwbA/YM4pPYj45g0R@fnCeAbFa2QiIajdFj0apvF93RgI4DxwgfgFDyS8wfsrUTpOns/bFtORV0jThK6KRiexAXEHkWsqJQUHDDELc2ZdMYvHvpsAprx9VDS97mzF6xjoZ1aYwD2rO9gOzkLWE7G4Qa3siik2UxB75vZSj@RT5n0w@dvKrkD0IesOQX "Bash – Try It Online")~~ [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 247 bytes ``` {S:i/ne\sl.*?<(s//}o{m/..(.)(\S*)**3%\s(.**92).*(.**11)/;[(my$l=" little ducks")~$3 XR~"Mother duck herself$2and all of the","One{$l~=$2}but none of the","Five{$l~="but only "}four","Four{$l}three","Three{$l}two","Two{$l}one"]["eotvur".index($0)]} ``` [Try it online!](https://tio.run/##vZTNa4MwGMbv/hUvwRUViWsLg32UXUZvo2ztYVB7SGukspiI0Top@q@7xI2t1nW39mLyPk8@fs8LMaEpu2niEgYhTKDZz@8ij1NfMuw8PljS8yqxjz2MLWxb/tyxHWd85UsLO87tyMaOngyHtne/tOLSZBMELMoyRiHIN@8S2bU5hrfXGj2LbEvTVgU1kZSF5ojwAAhjIEJQLnLRjNO9yeqJOarWeQZccPprTqPdl4u0JzgrAVWhyFPtqUF5VbZNqV670GMrFEKXhdCFOg6tloiKbKd24YgH9MMyr@1V1UhSAh6ENfI5glCkIFmeJlgmKo6lRCXbjSbo5IOCcoXS4iiJlK4hdiqmAoZtxJgEHTFPgBSkxMZ3E550EySJAhfQS05U0fsi1/gJqSN2b92QmMJaLcOGMe25l2Bq@3waatG3L0JViH@Yjs1LEOmjDy7tAM2OvDPzHDym003645mek6v7AziF9Qk "Perl 6 – Try It Online") Definitely golfable, especially the last 5 elements in the list in the form `"num $l num-1"`, or the starting regex that matches the right parts of the old input. [Answer] # [ink](https://github.com/inkle/ink), 353 bytes ``` =d(v) ~temp n=(v?"Fi")+(v?"F")*4+(v?"Th")+(v?"T")*2+(v?"O") {n-1:{n:{n-5:{n-4:{n-3:One|Two}|Three}|Four}|Five} little duck{n-2:s}|Mother duck herself} went out one day, over the hills and up away, Mother Duck said "Quack Quack Quack Quack", {n-1:but {n-2:only {n:{n-5:{n-4:one|two}|three}|four}|none of the}|and all of the} little duck{n-3:s} came back. ``` [Try it online!](https://tio.run/##vZRRa4MwEIDf8yuOPNXNFNZ2L4LuZQz2MMqgj8KwM6I0jUVju1LdX@8uqTCtXVsfVtEjXi5333nnJXKxZx5I/qU@1jzL@YC@JGsOIlFKcAiLz0UOGy4VpAU@ElXB1vZJisagYg5xIkQOgQyhWEGwCbZDn7yluJPBMx6GPEhCG3z6XgT41pE@RWdz41psIUqLrB36M1hymKPhkFrAPHLM2jlwM1YVZ5z3gp11T9yOdpP2Yz22vxmp9t@IfAl0emTejxM6mD65zCm17zQyPvt81DqY4Yy1SkT/zqtPB0JchUtct8lrpEV8Vl/kVa4Q1KghyR2yM8uK@ECmhWrvMS@sHaDjXxdoyjzm7V3ctci34ssVSHewfsKxQ617s6DW3cSsZnGtmqFqZFZTapGdZA/OTuLNHrWYaDF2sBNKbNuqNP9ZVerZgBKnWdVMG21HTl6VJ4pRdatxphh2p8fhr0pQ@wCtm8fEN53eSgEDlkrTqwN9ZOgbnVaV7VIeJzXGpBoV3ZvPfMUsP9duJ/7iMyleNcZ/AA "ink – Try It Online") First, uses substring checks to figure out what verse we're in - that's easy enough thanks to the capitalisation of the numbers at the start - `F`, `T` and `O` don't occur in any other places, and you can distinguish the second and fourth verse from the first and third by also checking for `Fi` and `Th` respectively. Then we just do what ink does best and print plain text specked with conditionals. I tried using switch statements at first, but while that looked nicer, it actually ended up longer. You'd think the `Quack`s would be a good place to use variables, what with a string being repeated a bunch, but variables come with enough overhead that every way I tried to do that made the code longer. Maybe that's a sign I'm not supposed to golf in ink. [Answer] # [Zsh](https://www.zsh.org/), 270 bytes ``` read {a..d} read e read f set `cat` case $a in M*)a=Five b=$5 c=$6 set but only four ${@:5};;O*)a=Mother b=$c c=herself 1=and 2=all;;*o)a=One c=duck set but none of the ${@:4} 6+=s;;T*)a=Two 3=one 5=duck;;*r)a=Three 3=two;;*)a=Four 3=three;;esac <<Q $a $b $c $d $e $f $@ ``` [Try it online!](https://tio.run/##ZVDLasMwELzvVyxBl6bB0EdyqCLIofQWQiAfkLW8xqaqVCw5Jg35dnflQCH0Iu3Ozo5m9BObceyYKrxQUVRXmGq@XTVETni0lI5gKTIqwtbDdv5A5qM9MZRGLcEatZqIZZ8weHfGOvQdqsvmbXnVepfZ25Aa7jLfCl/KyK6GJ0O@gmdDzmk9D8LbeZZ51dvPP0UfPGOoUQQmzdcrrB5N1PqQhQ9DgBcjFFhOa6LTZbjpmGWQhiBItiuWcp9xrTmShfV6DxJIlagsqgoUg6pBbcYxZ0PXpuQYs2jEgb1km/IJROcFhBN3k6emdS6iBMH@G2mgcwG3tPguqxiprRY42/ckzb9ztoD7X7t71dIXYym0YvwF "Zsh – Try It Online") Explanation: ``` # {a..d} expands to a b c d # so, read four words and assign them to a, b, c, and d # (d also gets all the extra words beyond the 4th) read {a..d} # read two lines and store them in e and f read e read f # assign the words in the remainder of the input # to the numbered variables 1... set `cat` # if the first word... case $a in # starts with M (i.e. Mother) M*) a=Five b=$5 # "little" c=$6 # "ducks" # set the numbered variables # ${@:5} is the existing numbered vars from 5 onwards set but only four ${@:5} ;; # One O*) a=Mother b=$c # "duck" c=herself 1=and 2=all ;; # ends with o (Two) *o) a=One c=duck set but none of the ${@:4} # "duck" -> "ducks" 6+=s ;; # Three T*) a=Two 3=one 5=duck ;; # Four *r) a=Three 3=two ;; # anything else (Five) *) a=Four 3=three ;; esac # now print: <<Q $a $b $c $d $e $f $@ ``` ``` ]
[Question] [ > > This challenge was inspired by a programming blog I frequent. Please see the original post here: [A Programming Puzzle](http://programmingpraxis.com/2013/06/28/a-programming-puzzle/) > > > --- # Challenge Define a function \$f:\mathbb{Q}\to\mathbb{Q}\$ such that \$f(f(n)) = -n\$ for all non-zero integers \$n\$, and where \$\mathbb{Q}\$ is the set of rational numbers. # Details In whatever language you prefer, please define **one** function or program \$f\$ that accepts as parameter **one** number \$n\$ and returns or outputs **one** number \$f(n)\$. Input may be provided through whichever mechanism is most natural for your language: function argument, read from STDIN, command-line argument, stack position, voice input, gang signs, etc. Output should be a return value from a function/program or printed to STDOUT. I would like to restrict answers to functions that do not take advantage of program state or global memory/data that is visible from outside of the function \$f\$. For example, keeping a counter outside of \$f\$ that counts how many times \$f\$ was called and just doing a negation based on this count isn't very challenging or interesting for anyone. The decisions \$f\$ makes should rely only on data within \$f\$'s lexical scope. However, this restriction is probably inappropriate for some stack-oriented languages or other types of languages that do not distinguish these types of data or scopes. Please use your best judgement to keep with the spirit of this challenge. --- # Scoring Standard code golf rules apply - your score is the number of **bytes** in your source code. The minimal answer requires the domain and codomain of \$f\$ to be a subset of the rationals \$\mathbb{Q}\$. If you restrict your domain and codomain of \$f\$ to the integers \$\mathbb{Z}\$, then your score is the ceiling of 90% of the number of **bytes** in your source code. # Tiebreak In the event of a tie, the following will be used in order: 1. Fewest number of printable non-whitespace **symbols** in your source code 2. Earliest date and time of answer submission --- You are not required to support arbitrarily sized numbers. Please interpret the sets \$\mathbb{Z}\$ and \$\mathbb{Q}\$ as datatypes in your chosen language (typically integer and floating point, respectively). If your solution relies entirely on the underlying structure or bit pattern of a data type, please describe its limitations and how it is being used. [Answer] ## Python: ~~61 34 30 29~~ 27 points f: Q -> Q in math: ``` | 0.5-x if x is in Q \ Z f(x) = | | x+0.5 if x is in Z ``` in Python: ``` f=lambda x:.5+[x,-x][x%1>0] ``` tested with ``` filter(lambda n: n[0] != -n[1], map(lambda n:(n,f(f(n))),range(0,50))) ``` logic behind this: When you take an integer `n` and put it into `f` you will get `x+0.5`. This is not an integer any more, so the next application will be `0.5-(x+0.5)` which is `-x`. ## Credits Thanks to * [Bakuriu](https://codegolf.stackexchange.com/users/5219/bakuriu) for striping it down from 61 characters to 34 characters. * [Volatility](https://codegolf.stackexchange.com/users/7911/volatility) for further reducing code size to 30 characters. * [copy](https://codegolf.stackexchange.com/users/3428/copy) for reducing code size to 29 characters (and fixing a potential floating point problem). * [aditsu](https://codegolf.stackexchange.com/users/7416/aditsu) for mentioning an inconsistency that came with the changes above. ## Notes First I thought this would be ok ``` f = lambda n: 1j*n ``` but its f:N->C and that is not allowed :-/ [Answer] ## J, 9 points (10 chars) Based on [stackoverflow answer](https://stackoverflow.com/questions/731832/interview-question-ffn-n): ``` (*-[*_1&^) ``` First idea (13 chars): ``` ((-*)-2&|*+:) ((-*)-2&|*+:) _10 _9 _8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8 9 10 _9 10 _7 8 _5 6 _3 4 _1 2 0 _2 1 _4 3 _6 5 _8 7 _10 9 ((-*)-2&|*+:) _9 10 _7 8 _5 6 _3 4 _1 2 0 _2 1 _4 3 _6 5 _8 7 _10 9 10 9 8 7 6 5 4 3 2 1 0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _10 ``` [Answer] ## C, 41 points (41 or 45 chars) Works using both 32- and 64-bit. `f : Z -> Z` (except `INT_MAX`): ``` f(n){return (abs(n)%2*2-1)*n+n?(-n<n)*2-1:0;} ``` --- If we don't have to include `0` we can shave off some chars (41 chars): `f : Z -> Z` (except `0` & `INT_MAX`): ``` f(n){return (abs(n)%2*2-1)*n+(-n<n)*2-1;} ``` --- This function works by dividing all integers into 4 groups based on their sign and parity. So we have the 4 different combinations: ``` + even, + odd, - even, - odd ``` As we need to switch the sign of the number, but not the parity after two passes, we get two different possible sequences: ``` + even -> - odd -> - even -> + odd -\ ^-------------------------------------/ + even -> + odd -> - even -> - odd -\ ^-------------------------------------/ ``` In this example I have chosen the first one. First we need to map all even positive integers to odd negative integers. We do this by changing the sign and incrementing the number (you could also choose to decrement the number instead): ``` f1(n) = -n + 1 ``` We then need to map all odd negative integers to even negative integers. We need to make sure that `f2(f1(n)) = -n`: ``` f2(f1(n)) = -n f2(-n + 1) = -n f2(-n) = -n - 1 f2(n) = n - 1 ``` Using the same methods we find `f3` and `f4`: ``` f3(n) = -n - 1 f4(n) = n + 1 ``` To combine these functions into one single function, we observe that every time `n` is even we switch the sign of `n` and every time `n` is positive we increment by one and otherwise we decrement by one: ``` f1(n) = -n + 1 (+ even) f2(n) = n - 1 (- odd) f2(n) = -n - 1 (- even) f4(n) = n + 1 (+ odd) ``` This can thus be rewritten as: ``` f(n) = odd(n) * n + sign(n) ``` where `odd(n)` returns `1` for odd numbers and `-1` for even numbers. There are 4 solutions total: ``` f(n) = odd(n) * n + sign(n) (edge cases: f(f(0)) -> -2, f(f(INT_MAX)) -> -8) f(n) = even(n) * n - sign(n) (edge cases: f(f(0)) -> -2, f(f(INT_MIN+1)) -> -6) f(n) = odd(n) * n - sign(n) (edge cases: f(f(1)) -> -3, f(f(INT_MIN)) -> -5) f(n) = even(n) * n + sign(n) (edge cases: f(f(-1)) -> -1, f(f(INT_MIN)) -> -5) ``` `INT_MIN` might always be considered an edge case in all 4 functions as `-INT_MIN == INT_MIN` => `f(f(INT_MIN)) = INT_MIN`. [Answer] Here's my go at it. ``` long f(int i){return i;} int f(long i){return -i;} ``` [Live example](http://coliru.stacked-crooked.com/view?id=be236496794bb50e2076885c937ed936-f674c1a6d04c632b71a62362c0ccfc51): ``` int main() { for(int i=-10; i<10; i=i+3) std::cout << f(f(i)) << "\n"; } ``` The input types cn be arbitrarily tailored to suit your needs. This version works for integer literals that are smaller in magnitude than 2^32-1. [Answer] # JavaScript, 18 ``` f=n=>n%1?.5-n:n+.5 ``` Using the new fat arrow notation (Firefox 22). Other version (18): ``` f=n=>n%1?-.5/n:.5/n ``` Previous version (20): ``` f=n=>n-~~n?.5-n:n+.5 ``` Example: ``` > [-3,-2,-1,1,2,3].map(f).map(f) [3, 2, 1, -1, -2, -3] ``` [Answer] # Mathematica 18 ``` f=#+1/2-4#(#-⌊#⌋)& ``` Here `⌊...⌋` is the floor function. It uses only rational numbers (not lists, complex numbers, etc) ``` f[10] f[f[10]] ``` > > 21/2 > > > -10 > > > ``` f[-5] f[f[-5]] ``` > > -9/2 > > > 5 > > > [Answer] x86 assembly language (FASM). The argument and the result are in eax register. It works properly for -2^30 < N < +2^30-1 16 bytes executable code. ``` use32 f_n: lea edx, [2*eax] xor edx, eax btc eax, 30 shl edx, 1 jnc .end neg eax .end: retn ``` [Answer] # Common Lisp: 35 bytes ``` (defun f(x)(/(if(> 1 x)-1/2 1/2)x)) ``` # Scheme (and Racket): 36 bytes ``` (define(f x)(/(if(> 1 x)-1/2 1/2)x)) ``` Ungolfed with comments and explanation: ``` (define (f x) (/ ;; divide (if (> 1 x) ;; if x is below 1 -1/2 ;; then -1/2 (the fraction) 1/2) ;; else 1/2 (the fraction) x)) ;; gets divided with x ``` For any number `x` in `[1,->]` the `if` will turn into the fraction `1/2` which is a real exact number in both languages. The divide part will then become `(/ 1/2 x)` so the fraction will become `1/(x*2)` which always is below `1`. For `1` it will be `1/2`, for `2` it's `1/4`, etc. For any number below 1 the `if` will turn in to the fraction `-1/2`, which makes the function do `(/ -1/2 x)` which is `-1/(2*x)` but since we can expect the value to be result of the previous run we can substitute x for 1/(x\*2) making a double application `-1/((1/(x*2))*2) = -x` E.g. since `1` turns into `1/2` the second application is `(/ -1/2 1/2) ==> -1` [Answer] # C, 60 (⌈66 \* .9⌉) ``` int f(int x){if(!x&1||!~x)return ~x;if(x<0)return x-1;return x+1;} ``` Here is an uncondensed version: ``` int f(int x){ if(!x&1 || !~x) return ~x; if(x<0) return x-1; return x+1; } ``` This method works using only integers, so it gets the 90% score bonus. I was originally writing it in java, but realized that this program in particular could benefit from C-style logical operators. As there is no integer corresponding to `-INT_MIN`, `f(f(INT_MIN))` returns `INT_MIN` instead. The underlying mapping is algebraically rather simple. Executing the statement `x=f(x)` replaces x with: * `x+1`, if `x` is positive and odd * `-x+1`, if `x` is positive and even * `x-1`, if `x` is negative and odd * `-x-1`, if `x` is negative and even The result of each case will fall under the next case the next time the function is applied to x. As you can see, composing a case with the case following it yields `-x`. The code is a result of some clever simplification of the function to take advantage of the bit structure of two's compliment integers. [Answer] # [><>](https://esolangs.org/wiki/Fish), 21 + 3 = 24 bytes, 22 points ``` :0)$:0($:1$2%2*-*+-n; ``` Use the [official Python interpreter](https://gist.github.com/anonymous/6392418), and use the `-v` command line option to enter input, at a cost of 3 bytes. I have a feeling that this could be better--I'll keep looking at it and try to golf it down. Given input `n`, the program outputs ``` (n>0) - ((n<0) + n * (1 - 2*(n%2))) ``` where `(n>0)` and `(n<0)` are booleans. This is equivalent to [Gelatin's Python answer](https://codegolf.stackexchange.com/a/17119/36885) ``` (n>0) - (n<0) - n * (-1)**n ``` but `><>` doesn't have a built-in exponentiation operator so we use `(1 - 2*(n%2))` in place of `(-1)**n`. ### What follows is mathematical theory -- read if (and only if) you are interested: Given any function `f: Z -> Z` such that `f(f(n)) = -n` for all `n` in `Z`, we see immediately that `f(f(f(f(n)))) = n`, or in other words, `f^4` is the identity function. In particular, `f` is invertible, and its inverse function is `f^3`. Thus `f` is a permutation of `Z`, and since `f^4 = Id`, it follows that every orbit (or cycle) of `f` has size either `1`, `2`, or `4`. Next, we see that `f(0) = 0`. Proof: `f(0) = f(-0) = f(f(f(0))) = -f(0)`, so `f(0) = 0`, as desired. Conversely, suppose `x` is in a cycle of length `1` or `2`, so `f(f(x)) = x`. Then `-x = x` so `x = 0`. Thus `f` is made up entirely of 4-cycles, except for the fixed point (1-cycle) at `0`. Further, every 4-cycle must have the form `(x, y, -x, -y)`, and by rotating the cycle around we may assume that `x` and `y` are both positive. Conversely, every such product of 4-cycles partitioning the nonzero integers determines a choice of `f`. Thus each choice of `f` corresponds uniquely to a directed graph whose vertices are the positive integers, such that every vertex is incident to exactly one arrow, either entering or exiting. More precisely, in the underlying undirected graph, every vertex has degree exactly `1`. (Each 4-cycle `(x y -x -y)` with `x` and `y` positive corresponds to the arrow `x --> y`.) The function in this answer (and several other answers here) corresponds to the graph where `1 --> 2`, `3 --> 4`, and in general `2k-1 --> 2k`. Such graphs are in bijection with infinite sequences of ordered pairs `(a_n, p_n)`, where each `a_n` is a positive integer and each `p_n` is either `0` or `1`: given a sequence `(a_1, p_1), (a_2, p_2), (a_3, p_3), ...`, we first pair `1` with `1 + a_1`, and then we form either the arrow `1 --> 1 + a_1` or the arrow `1 + a_1 --> 1` depending on whether `p_1` is `0` or `1`. Essentially, the arrow is either a `<` sign or a `>` sign, depending on the parity of `p_1`. Next, take the smallest unpaired positive integer `k`, and count up from `k`, exactly `a_2` steps, SKIPPING any number that is already paired with something. Pair `k` with the result, and set the direction of the arrow depending on `p_2` as above. Then repeat with `(a_3, p_3)`, etc. Each arrow will eventually be determined this way, so the process is well defined. The function in this answer corresponds to the sequence `(1,0), (1,0), (1,0), ...`, since at step `n` the smallest unpaired integer is `2n-1` and no integers larger than `2n-1` have been paired with anything, so we get `2n-1 --> 2n` for each `n` (arrows are oriented this way because each `p_n` equals `0`). The cardinality of this set is `(N*2)^N = N^N`, which by the last paragraph of [this answer](https://math.stackexchange.com/a/154995/198422) equals `2^N`, the cardinality of the real numbers. [Answer] To fix the earlier J answer (I don't have enough reputation to comment on the original): ``` (*+[*1-~2*2|]) ``` It just replaces the `_1&^` with `1-~2*2|]`, which gives the opposite sign. So I changed the `-` to a `+` (which only matters on input of `1` and `_1`). Here are the tests: ``` (*+[*1-~2*2|])6 3 _9 _8 1r2 _4.6 0 1 _1 7 _2 8 _9 1 7.28 0 2 _2 (*+[*1-~2*2|])7 _2 8 _9 1 7.28 0 2 _2 _6 _3 9 8 0 _10.3568 0 _1 1 NB. f^:2 = f@:f (*+[*1-~2*2|])^:(2)6 3 _9 _8 1r2 _4.6 0 1 _1 _6 _3 9 8 2 _5.0832 0 _1 1 ``` As you can see, the domain and range are of all real numbers, but it only works for integers (including 0). Explanation: ``` ( * + [ * 1-~ 2* 2|] ) signum n + n * pred (twice (n mod 2)) ``` [Answer] ## GolfScript `ceiling(26*.9)=24` Golfscript only handles integers, so apply the `Z` bonus for a total of 24 points: ``` .{..0>2*(\)2%!2*(@*+}{ }if ``` The special case of 0 accounts for 8 characters. Ignoring 0, we can have a 17 point answer: ``` ..0>2*(\)2%!2*(@*+ ``` This code does the following to an integer `x` on top of the stack: * If `x` is 0, leave `0` on the stack and apply no more rules. * If `x` is even, negate `x`. * If `x` is positive, add `1`. * If `x` is negative, subtract `1`. This logically connects sets of 4 numbers in a cycle, where `f` traverses elements of the cycle, and opposite corners of the cycle are negatives of each other. Every integer is part of exactly 1 such cycle, except 0 which is special cased. For example, for `{-8, -7, 7, 8}`: * `7 f -> 8` * `8 f -> -7` * `-7 f -> -8` * `-8 f -> 7` The only relevant test cases I could think of were a negative odd, negative even, positive odd, positive even, `0`, and then I threw in `-1` and `1` since their proximity to `0` may have caused problems: ``` [-10 -5 -1 0 1 5 10] {.{..0>2*(\)2%!2*(@*+}{ }if}:f; {f f}% -> [10,5,1,0,-1,-5,-10] ``` I'm sure the actual GolfScript can be improved somewhat. It doesn't feel like it should take up 26 characters! Would love to hear some suggestions. [Answer] ## Java, just for fun Here's an implementation that does an actual bijection between ℤ and ℤ², which is an [odd function](http://en.wikipedia.org/wiki/Even_and_odd_functions) at the same time (g(-x) == -g(x)). It treats the corresponding ℤ² element as a complex number and multiplies it by "i", then converts back to ℤ. f(x)=g⁻¹(ig(x)) f(f(x))=g⁻¹(-g(x))=-x The function runs in O(1). ``` public class Ffn { public static int f(int n) { if (n == 0) { return 0; } // adjust sign int s = n > 0 ? 1 : -1; int m = n * s; // calculate square "radius" int r = (int) (Math.sqrt(2 * m - 1) + 1) / 2; int q = r * 2; // starting point int x = r, y = r; int k = q * (r - 1) + 1; if (m - k < q) { // go left x -= m - k; } else { // go left x -= q; // go down y -= m - k - q; } // multiply by i int x2 = -y * s, y2 = x * s; // adjust sign s = y2 < x2 || y2 == x2 && x2 < 0 ? -1 : 1; x2 *= s; y2 *= s; if (y2 == r) { // go left k += r - x2; } else { // go left and down k += q + r - y2; } return k * s; } public static void main(final String... args) { for (int i = 0; i < 1000000; ++i) { if (f(f(i)) != -i || f(f(-i)) != i) { System.out.println(i); } } } } ``` P.S. Happy New Year! [Answer] # Python 3 - 38 Similar to @moose's answer, but, `f(n) == n`. Works for all integer values. ``` f=lambda x:x*(isinstance(x,int)*2.0-1) ``` [Answer] ## Perl, 33 (non-whitespace) ``` sub f{($=)=@_;$=-$_[0]?-$=:"$=.1"} ``` **Edit:** * `$=.".1"` shortened to `"$=.1"` (thanks ardnew). **Math:** ![Math](https://i.stack.imgur.com/XuTuu.png) **Ungolfed:** ``` # script.pl sub f { ($=) = @_; # short for $= = int($_[0]); # "int" is implicit in assignments to $=; # ($=) can be prepended by "local" to get # the function free of side effects. $= - $_[0] ? # short for $= != $_[0], check if input is integer -$= # input is not an integer : $= . ".1" # input is integer } # Testing chomp; $_ = sprintf "f(f($_)) = f(%s) = %s\n", f($_), f(f($_)); ``` **Examples:** ``` perl -p script.pl 7 f(f(7)) = f(7.1) = -7 2 f(f(2)) = f(2.1) = -2 0 f(f(0)) = f(0.1) = 0 -1 f(f(-1)) = f(-1.1) = 1 -10 f(f(-10)) = f(-10.1) = 10 -1.23 f(f(-1.23)) = f(1) = 1.1 3.4 f(f(3.4)) = f(-3) = -3.1 1.0 f(f(1.0)) = f(1.1) = -1 ``` [Answer] # Julia, 26 ``` julia> f(n::Int)=n//1 f (generic function with 1 method) julia> f(n)=int(-n) f (generic function with 2 methods) julia> f(f(4)) -4 ``` Not super competitive, but very Julian since it relies on multiple dispatch. It just makes n a Rational if its an Int, or an int with a minus sign if it is anything else. One might object that this is 2 functions, but Julia considers this to be one function with two methods, and it is equivalent to defining one function with an if statment on the type of `n`. [Answer] # [Candy](https://github.com/dale6john/candy), ~~20~~ 18 bytes Uses the 3 -> 4 -> -3 -> -4 -> 3 trick. ``` ~A2%{|m}1A0>{+|-}. ``` To invoke it use the -i switch on the interpreter Example of double-invokation: ``` $ candy -i 7 -e '~A2%{|m}1A0>{+|-}.' program length: 18 >>> 8 $ candy -i 8 -e '~A2%{|m}1A0>{+|-}.' program length: 18 >>> -7 $ candy -i -7 -e '~A2%{|m}1A0>{+|-}.' program length: 18 >>> -8 $ candy -i -8 -e '~A2%{|m}1A0>{+|-}.' program length: 18 >>> 7 ``` Long form: ``` peekA pushA digit2 mod # even/odd if else negate # negate even numbers endif digit1 pushA digit0 greater # positive/negative if add # add two numbers from stack (original stack value, and delta) else sub # diff two numbers from stack (original stack value, and delta) endif retSub ``` [Answer] ## Dyalog APL, 9 points ``` ×-⍨⊢ׯ1*⊢ ``` The source is 9 bytes long and qualifies for the bonus (which doesn't help at all). It also uses the formula from the top SO answer. [Answer] ## Python: 32 bytes (29 points) f: Z -> Z ``` f=lambda n:(n>0)-(n<0)-n*(-1)**n ``` Using Ben Reich's method. [Answer] ## [GTB](http://timtechsoftware.com/?page_id=1309 "GTB"), 22 ``` @S;N,"--$x?N)→N~N#~-N& ``` [Answer] # Java, 113 bytes The approach is pretty simple. It ended up more bytes than I anticipated, but can perhaps be golfed down a bit. ``` public class F{public static int f(int x){if(x<0)x+=-2147483647-++x;x+=1073741824;return x<0?-2147483647-++x:x;} ``` It basically creates 4 different "areas" of x, utilizing the fact that Java happily lets variables wrap around. I had to do some tricky conversion for negative numbers which is the main reason this ended up bigger than anticipated. Works for all x besides -2147483648. [Answer] Same sequence of numbers (3, 4, -3, -4, 3 ...) as the golfscript answer, but implemented in perl (42 chars after whitespace is stripped) ``` sub f{($_[0]%2?1:-1)*$_[0]+($_[0]<0?-1:1)} ``` More legibly: ``` sub f { ($_[0] % 2 ? $_[0] : -$_[0] ) + ( $_[0] < 0 ? -1 : 1 ) } ``` Or even more legibly: ``` sub f { my $n = shift; my $sign = $n >= 0 ? 1 : -1; # note that in perl $n % 2 is the same as int($n) % 2 if( $n % 2 ) { # odd: add one to magnitude return $n + $sign } else { # even: subtract one from magnitude then invert return -($n - $sign) } } ``` Output: ``` ski@anito:~/mysrc/.../acme$ echo 3 | perl -e 'sub f{($_[0]%2?1:-1)*$_[0] + ($_[0]<0?-1:1)}; my $x = <>; for(0..10) { print "$_: $x\n"; $x = f($x); }' 0: 3 1: 4 2: -3 3: -4 4: 3 5: 4 6: -3 7: -4 8: 3 9: 4 10: -3 ``` [Answer] # Sed, 25 bytes. ``` |sed s/0+/0-/|sed s/^/0+/ ``` **Usage:** ``` $ echo 1.23 |sed s/0+/0-/|sed s/^/0+/ 0+1.23 $ echo 0+1.23 |sed s/0+/0-/|sed s/^/0+/ 0+0-1.23 ``` [Answer] # Matlab, 26 characters ``` f=@(n) (n<0)-(n<0)-n*(-1)^n ``` [Answer] # C++ - ~~63~~ 55.8 This is how the code looks: ``` int f(int n){return (n&45056?n^45056:n|45056)*(n&45056?-1:1);} ``` It doesn't work on integers whose fourth byte is equal to 0xB as it uses that value to keep track of passes. Otherwise works on any member of Z, including zero. [Answer] Updated with function supplied by Synthetica (obviously the one who should get credit for this now) Language: Python Number of characters: 41 including whitespace ``` f=lambda x:-float(x) if str(x)==x else`x` ``` [Answer] # Prolog, 36 bytes **Code:** ``` X*Y:-X//1=:=X,Y is 0.5+X;Y is 0.5-X. ``` **Explained:** ``` Dyadic predicate which converts integers to floats and floats back to negated integers. ``` **Example:** ``` 10*X. X = 10.5 10*Y,Y*X. X = -10, Y = 10.5 ``` [Answer] # Javascript ES6, ~~27~~ 26 bytes ``` a=>a%1?-Math.floor(a):a+.2 ``` [Answer] # [Mouse-2002](https://github.com/catb0t/mouse15), ~~21~~ ~~19~~ 12 bytes ``` $A1%[1%_|1%] ``` Defines a function `A`; call it like `#A,#A,?;;` (which will wait for the user to enter any number). Alternatively, call it like `#A,#A,n;;` where `n` is any number. [Answer] # Julia, 21 ``` f(x)=(1-2(1>x>-1))/2x ``` Then ``` julia> f(f(12//1)) -12//1 ``` p//q is julia's literal notation of rational numbers. ]
[Question] [ Write the shortest possible program (length measured in bytes) satisfying the following requirements: * no input * output is to stdout * execution eventually terminates * total number of output bytes exceeds [Graham's number](http://en.wikipedia.org/wiki/Graham%27s_number) Assume that programs run until "normal" termination on an *ideal* computer1 able to access unlimited resources, and that the common programming languages are modified if necessary (without changing the syntax) to allow this. Because of these assumptions, we might call this a kind of Gedankenexperiment. To get things started, here's a 73-byte Ruby program that computes fω+1(99) in the [fast-growing hierarchy](http://en.wikipedia.org/wiki/Fast-growing_hierarchy#Functions_in_fast-growing_hierarchies): ``` f=proc{|k,n|k>0?n.times{n=f[k-1,n]}:n+=1;n};n=99;n.times{n=f[n,n]};puts n ``` 1 EDIT: More precisely, suppose we're taking an existing system and modifying it only to have no upper limit on storage size (but it is always finite). The execution-times of instructions are *not* supposed to be modified, but the machine is assumed to be ideal in that it will have no upper limit on its operating lifetime. [Answer] ## Haskell, ~~59~~ ~~57~~ ~~55~~ 63 ``` (f%s)1=s;(f%s)n=f.(f%s)$n-1 main=print$((flip((%3)%(3^))3)%4)66 ``` How it works: `%` simply takes a function and composes it `n-1` times on top of `s`; i.e. `%3` takes a function `f` and returns a function of `n` that equals applying it `f` to 3, `n-1` times in a row. If we iterate the application of this higher-order function, we get a fast-growing sequence of functions – starting with exponentiation, it's exactly the sequence of Knuth-arrow-forest sizes: `((%3)%(3^))1 n = (3^)n     = 3ⁿ = 3↑n` `((%3)%(3^))2 n = ((3^)%3)n = (3↑)ⁿ⁻¹ $ 3 = 3↑↑n` `((%3)%(3^))3 n = (((3^)%3)%3)n = (3↑↑)ⁿ⁻¹ $ 3  = 3↑↑↑n` and so on. `((%3)%(3^))n 3` is `3 ↑ⁿ 3`, which is what appears in the calculation to Graham's number. All that's left to do is composing the function `(\n -> 3 ↑ⁿ 3) ≡ flip((%3)%(3^))3` more than 64 times, on top of 4 (the number of arrows the calculation starts with), to get a number larger than Graham's number. It's obvious that the logarithm (what a lamely slow function that is!) of `g₆₅` is still larger than `g₆₄=G`, so if we print that number the output length exceeds `G`. ⬛ [Answer] # Binary Lambda Calculus, 78 bits = 9.75 bytes Here is an expression in Binary Lambda Calculus that is less than 10 bytes, yet surpasses Graham's Number. This is over 5x shorter than my [previous post](https://codegolf.stackexchange.com/questions/6430/post/219469) in JavaScript. Since [Binary Lambda Calculus](https://esolangs.org/wiki/Binary_lambda_calculus) is radically different than JavaScript, I decided to answer this in a separate post. ``` 010101000001110011101000000101011000000101101101011010000110100000011100111010 ``` You can find some interpreters [here](https://tromp.github.io/cl/cl.html). ## **[Explanation I made on another post](https://codegolf.stackexchange.com/questions/31695/post/219649)** Essentially, this binary expression encodes this lambda calculus expression: ``` (\f x.f (f x))(\f n.n (\g m.m g m) f n)(\x.x x)(\f x.f (f x)) ``` The decodings can be described like this: * `(\f x.f (f x))` at the start and at the end corresponds to the Church Numeral \$2\$. * `(\f n.n (\g m.m g m) f n)` takes in a function \$f\$ and a number \$n\$, and returns \$f\_n (n)\$ where \$f\_0 (n) = f(n)\$ and \$f\_{m+1} (n) = f\_m^n (n)\$ using functional recursion. Let's call this function \$S\$. * `(\x.x x)` corresponds to the function that raises a number to the power of itself, or \$f(x)=x^x\$. Since Church Numerals naturally nest the function that they apply to, the lambda calculus string gets reduced as follows: $$2Sf2 \rightarrow S(Sf)2$$ Since each \$S\$ adds \$\omega\$ to the growth rate of the function, and the \$f(x)=x^x\$ has growth rate \$f\_2\$ in the Fast Growing Hierarchy, then \$(Sf)\$ has growth rate \$f\_{\omega}\$, and \$S(Sf) = 2Sf\$ has growth rate \$f\_{\omega2}\$. This means the expression \$2Sf2\$ described above has the value of about \$f\_{\omega2} (2)\$ in the Fast-growing Hierarchy. This is greater than Graham's Number. Therefore, Graham's Number can be beaten by a program that less than 10 bytes! [Answer] ## GolfScript (49 47 chars) ``` 4.,{\):i\.0={.0+.({<}+??\((\+.@<i*\+}{(;}if.}do ``` See [Lifetime of a worm](https://codegolf.stackexchange.com/a/18931/194) for lots of explanation. In short, this prints a number greater than fωω(2). [Answer] # [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), ~~7.625~~ ~~7.5~~ ~~6.75~~ 6.125 bytes, ~~61~~ ~~60~~ ~~54~~ 49 bits ``` 0100011010000110011000000101101100000011100111010 ``` This encodes: ``` (\x.x x) (\y.y (y (\g m.m g (\f n.f (f n))))) ``` To simplify things a bit, let `H = (\g m.m g 2)` where `2` is the [Church numeral](https://en.wikipedia.org/wiki/Church_encoding) `(\f n.f (f n))`. These are the first few steps of the reduction: ``` (\x.x x) (\y.y (y H)) (\y.y (y H)) (\y.y (y H)) (\y.y (y H)) ((\y.y (y H)) H) (\y.y (y H)) (H (H H)) H (H H) (H (H H) H) H (H H) H (H H) 2 H (H H) 2 (H H) 2 2 (H H) 2 (H H) 2 H H (H H 2) (H H) 2 H H 2 H 2 (H H) 2 2 H 2 H 2 (H H) 2 H (H 2) H 2 (H H) 2 H (H 2) 2 2 (H H) 2 2 (H 2) 2 2 (H H) 2 H 2 (H 2 2) 2 (H H) 2 H 2 2 2 2 2 (H H) 2 2 2 2 2 2 2 (H H) 2 2^^6 (H H) 2 ``` The next step is applying `H H` \$2\uparrow\uparrow6\$ times to `2`. After an odd number of aplications the result is not a number, but after an even number of aplications it is. Here \$2\uparrow\uparrow6\$ is not an aproximation, and since it is even, the final answer will be a number. We will use \$\frac{2\uparrow\uparrow6}{2}\$ times a function that applies `H H` twice. The function `H H (H H n)` grows as fast as the [Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function), to see this, let's take a look at a more general case. The function `k H 2 n` grows as fast as \$2\uparrow^kn\$: ``` 0 H 2 n = 2 n = n^2 > 2*n = 2{0}n k+1 H 2 n = H (k H 2) n = H (\x.k H 2 x) n >= H (\x. 2{k}x) n = n (\x. 2{k}x) 2 = 2{k+1}(n+1) > 2{k+1}n ``` Applying this to `H H (H H n)` we get `H H (H H n) = H H n H 2 = n H 2 H 2 = H (n-1 H 2) H 2 = H (n-1 H 2) 2 2 = 2 (n-1 H 2) 2 2 = n-1 H 2 (n-1 H 2 2) 2 >= n-1 H 2 2{n-1}2 2 >= 2{n-1}2{n-1}2 2 = 2{n}3 2 > 2{n}3`, which is about the same as \$A(n,n)\$. So the size of the expression `2^^6 (H H) 2` is about \$g\_{\frac{2\uparrow\uparrow6}{2}} > g\_{64}\$. [Answer] # Python 3, 53 bytes ``` m=lambda x:-x if x<0 else m(x-m(x-1))/2;print(1/m(9)) ``` It computes the reciprocal of the gap between the 9 and the smallest tame fusible number above it, which is shown [here](https://arxiv.org/pdf/2003.14342.pdf) to be at least \$f\_{\varepsilon\_0}(2)\$ in the fast-growing hierarchy, thus beating Graham's number. # Pyth, ~~24~~ 22 bytes -2 bytes thanks to r.e.s. ``` DlHR?<HZ_H/l-Hl-H12)lT ``` Same algorithm as before. I changed the argument 9 to 10 (which due to the predefined variable `T` doesn't increase the length), thus making the output at least \$f\_{\varepsilon\_0}(3)\$, absolutely dominating Graham's number and every other answer so far. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~29~~ 28 bytes ``` M?*GHgtGtgGtH^ThH=ZTV99=gZTZ ``` Defines a lambda for hyper-operation and recursively calls it. Like the definition for Graham's number, but with larger values. This: ``` M?*GHgtGtgGtH^3hH ``` Defines a lambda, roughly equal to the python ``` g = lambda G, H: g(G-1, g(G, H-1)-1) if G*H else 3^(H+1) ``` This gives the hyper-operation function, g(G,H) = 3↑G+1(H+1). So, for example, g(1,2)=3↑23 = 7,625,597,484,987, [which you can test here](https://tio.run/##K6gsyfj/39dey90jvcS9JN29xCPOOMMj3VDB6P9/AA "Pyth – Try It Online"). `V<x><y>` starts a loop that executes the body, `y`, `x` times. `=gZT` is the body of the loop here, which is equivalent to `Z=g(Z,10)` The code: ``` M?*GHgtGtgGtH^3hH=Z3V64=gZ2)Z ``` Should recursively call the hyperoperation above 64 times, giving Graham's Number. In my answer, however, I've replaced the single digits with `T`, which is initialized to 10, and increased the depth of recursion to 99. Using [Graham Array Notation](http://googology.wikia.com/wiki/Graham_Array_Notation), Graham's Number is [3,3,4,64], and my program outputs the larger [10,11,11,99]. I've also removed the `)` that closes the loop to save one byte, so it prints each successive value in the 99 iterations. [Answer] # Javascript, 50 Bytes, \$f\_{\omega+8} (9)\$ ``` n=(y,x=9)=>y?y-9?n(y-1,x?n(y,x-1)*9:9):x:n(x);n(8) ``` Here, n is a binary function. The function is defined as followed: * `n(9,x) = x` * `n(y,0) = n(y-1,9)` * `n(y,x) = n(y-1,n(y,x-1)*9)` The `*9` ensures that `n(y,x)` is an increasing function with respect to x. * `n(9,x)` = x * `n(10,x)` = 9^(x+1) * `n(11,x)` ~ 9^^x * `n(12,x)` ~ 9^^^x * `n(y+1,x)` recurses over `n(y,x)` with respect to x. We also defined n(y)=n(y,9), so n(y) grows as fast as \$f\_{\omega}\$ in the Fast Growing Hierarchy. Now here is the twist: * `n(0,x)=n(x)=n(x,9)` This starts an entirely new hierarchy starting from `y=0` all the way up to `y=8`. * `n(0,x)` grows at \$f\_{\omega}\$ in the FGH * `n(1,x)` grows at \$f\_{\omega+1} = G\$ * `n(2,x)` grows at \$f\_{\omega+2}\$ * ... * `n(8,x)` grows at \$f\_{\omega+8}\$ Therefore, `n(8)` ~ \$f\_{\omega+8} (9) > G\_{64}\$ [Answer] ## Ruby, ~~54~~ ~~52~~ 50 bytes ``` f=->b{a*=a;eval"f[b-1];"*b*a};eval"f[a];"*a=99;p a ``` --- ## Ruby, ~~85~~ ~~81~~ ~~76~~ ~~71~~ ~~68~~ ~~64~~ ~~63~~ ~~59~~ 57 bytes ``` f=->a,b=-a{eval"a*=b<0?f[a,a]:b<1?a:f[a,b-1];"*a};p f[99] ``` Pretty much fast growing hierarchy with f(a+1) > fω+1(a). --- ## Ruby, 61 bytes ``` f=->a,b=-a{a<0?9:b==0?a*a:f[f[a-1,b],b>0?b-1:f[a,b+1]]};f[99] ``` Basically an Ackermann function with a twist. --- ## Ruby, ~~63~~ 59 bytes ``` n=99;(H=->a{b,*c=a;n.times{b ?H[[b-1]*n*b+c]:n+=n}})[n];p n ``` --- ## Another Ruby, ~~74~~ 71 bytes ``` def f(a,b=a)a<0?b:b<0?f(a-1):f(a-1,f(a,b-1))end;n=99;n.times{n=f n};p n ``` Basically Ackermann function to itself 99 times. [Answer] ## Python (111+n), n=length(x) Although this one is not as short as the answerer's Ruby program, I'll post it anyway, to rule this possibility out. It uses the Ackermann function, and calls the Ackermann function with m and n being the values from another call to the Ackermann function, and recurses 1000 times. This is **probably** bigger than Graham's number, but I'm not sure, because nobody knows the exact length of it. It can be easily extended, if it's not bigger. ``` x=999 b='A('*x+'5,5'+')'*x def A(m,n):n+1 if m==0 else A(m-1,A(m,n-1)if n>0 else 1) exec('print A('%s,%s')'%(b,b)) ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~24~~ ~~20~~ 18 bytes ``` "`'1$,*~'+"{.~~})* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/XylB3VBFR6tOXVupWq@urlZT6/9/AA "GolfScript – Try It Online") ``` "`'1$,*~'+" # Push this string {.~~})* # Becomes {.~}126* and this duplicates and executes the string 126 times ``` When executed, this string modifies the string at the top of the stack: ``` ` # Parse it to a string inside the string 'foo' -> '"foo"' '1$,*~'+ # Add '1$,*~' at the end '"foo"' -> '"foo"1$,*~' ``` When we execute this new string it does whatever `foo` used to do, but many times. ``` 1$, # Get the number of bytes of the string at the top of the stack "foo" * # Make that many copies of foo ~ # Execute all of them ``` We will be dealing with only one string, that will modify itself 126 times. Let `L` be the number of loops and `B` the number of bytes the string has. These values can be calculated with \$B=2^{L+1}+3L+7\$, but for simplicity's sake we will round `B` down to `L`. The number of bytes grows exponentially because every time a loop is added, every `"` becomes `\"` and every `\` becomes `\\`. Now the loops execute `L` times instead of `B`. When the string has no loops it just adds `"` `"1$,*~` around itself, in other words `L = L + 1`. With `a` loops it executes `L` times the version with `a-1` loops. This is exactly the same definition of `f` in the [fast growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy) for when `a` is a successor: $$f\_0(L)=L+1$$ $$f\_a(L)=f\_{a-1}^L(L)$$ Before each execution `a` and `L` are the same number, so every time we execute the string, `L` becomes \$f\_\omega(L)\$. We execute it 126 times starting with `L = 0`, so the number of bytes in the output will be: $$f\_\omega^{126}(0)=f\_\omega^{122}(f\_8(8))>f\_\omega^{122}(122)=f\_{\omega+1}(122)$$ [Answer] # [Functoid](https://github.com/bforte/Functoid), 14 bytes ``` B"W(BiCA])9.Ef ``` [Try it online!](https://tio.run/##SyvNSy7Jz0z5/99JKVzDKdPZMVbTUs817f9/AA "Functoid – Try It Online") The pointer wraps around whenever it moves out of the source code, this happens once here, making the code equivalent to `B"W(BiCA])9.EfB"W(BiCA])9.Ef`. The string `"W(BiCA])9.EfB"` gets converted to base 10 and becomes `"91772447243986"`. Now we can rewrite the code as `BkW(BiCA])9.Ef`, where `k` represents that big number. ``` BkW(BiCA])9 # set the current function to B k W (B i C A ]) 9 . # evaluate and print the current function as a number Ef # terminate the program ``` Let `f_a` be a lambda function equivalent to \$f\_a\$ in the [fast growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy). To increase the index by 1, the function needs to be applied to itself `n` times \$f\_a^n(n) = f\_{a+1}(n)\$. In code this would be `f_(a+1) n = n f_a n = C A f_a n`. To get any finite index we just need to apply `C A` a lot of times to `f_0 = ]`: ``` f_0 = ] f_1 = C A ] f_2 = C A (C A ]) f_3 = C A (C A (C A ])) ... ``` \$f\_\omega(n) = f\_n(n)\$ = `n (C A) ] n = W (i (C A) ]) n` The expression `B k W (B i C A ]) 9` can be reduced to `k (W (i (C A) ])) 9 = k f_ω 9` and this returns \$f\_\omega^{91772447243986}(9)\$. [Answer] # Python 3, 79 bytes ``` f=lambda x,y:f(x-1,f(x,y-1))if x*y else x+y+1 z=9;exec("z=f(z,z);"*99);print(z) ``` f(x,y) is a modified version of ackermann for golfing purposes f(x,y) = f(x-1,f(x,y-1)) if both x and y are greater than 0 f(x,0) and f(0,y) each add one to the nonzero entry (if both are zero, it is 1) Then the program does recursion on f(x,x) 99 times. [Answer] # JavaScript, 68 bytes, however uncompeting for using ES6 ``` a=(x,y)=>y?x?a(a(x-1,y)*9,y-1):a(9,y-1):x;b=x=>x?a(9,b(x-1)):9;b(99) ``` `a` function is similar to up-arrow notation with base 9. ``` /a(a(x-1,y)*9,y-1) x>0, y>0 a(x,y)=|a(9,y-1) x=0, y>0 \x y=0 ``` `b` function is: b(x)=bx(9). `b(99)` is ~fω+1(99), compared to Graham's number<fω+1(64). [Answer] # Python 3, ~~174~~ ~~171~~ ~~168~~ ~~148~~ ~~125~~ ~~117~~ ~~116~~ ~~112~~ 101 bytes 3^^^...^3 with Graham's number arrows i.e. G(65) (boring, I know) ``` a=lambda b,c:3if b<2else(a(a(b-1,c),c-1)if c else 3*b) G=lambda k:a(3,G(k-1))if k else 4 print(G(65)) ``` Pretty human-readable. a implements arrow notation, G is Graham's sequence. ## Improvements * Replaced G(64)+1 with G(65), saving two bytes * Replaced `if c==1:return a**b` with `if c==0:return a*b`, saving one byte * Renamed ar function to a and renamed variable a to k, saving three bytes * Turned G function from a proper function into a lambda, saving twenty bytes, believe it or not! * Turned a function from a proper function also into a lambda, saving twenty-three bytes! * Removed k from a function since we will only be using it with base 3, saving eight bytes. * Removed an unnecessary space * Removed some more unnecessary spaces, saving four bytes * Shortened definitions of a and G, saving eleven bytes [Answer] # [7](https://esolangs.org/wiki/7), 17.5 bytes ``` 00000000: 505e 91e7 a3a4 63c8 edda 476d ea0b d556 P^....c...Gm...V 00000010: d7e .. ``` Written in octal: ``` 24057221717216443074435566443555724057252555375 ``` [Try it online!](https://tio.run/##HYqxDQAACMJeUhT5/zI0LrRJkY0OCkilkNNdoRty5nHtD8R5ifYC "7 – Try It Online") `721gge644355` is a function that, given a function `f_a()`, returns `f_(a+1)()`: ``` |f_a() 721gge644355 |c7{f_a()}ggerr # Where {f_a()} represents the pacified version of f_a() # Applying the result to some number n, to see that it worked: |n c7{f_a()}ggerr |n|f_a() nr f_a() n # Make n copies of f_a(), resulting in f^n_a() n r # Apply it to n, resulting in f^n_a(n) = f_(a+1)(n) ``` From that, a function `f_w()` can be written: ``` |n cc71721644307443556ggerrr |n|n|721gge644355 nrr n # A function (\x -> x^n), representing f_0() 721gge644355 nr # Add 1 n times to the index of f_0(), resulting in f_n() n r # Apply the result to n, resulting in f_n(n) = f_w(n) ``` The full program computes `f^256_w(2)`, which is greater than Graham's number: ``` || 24057221717216443074435566443555724057252555375 ||cg6r|cc71721644307443556ggerrr|cg6r|crcrrre|r ||cg6r|cc71721644307443556ggerrr|cg6r|crcrrre|r r ||cg6r|cc71721644307443556ggerrr|cg6r|crcrrre r ||cg6r|cc71721644307443556ggerrr|cg6r crcrrre cg6r # The number 2 cr # Raise 2, to itself returning 4 cr # Raise 4, to itself returning 256 cc71721644307443556ggerrr r # Make 256 copies of f_w(), resulting in f^256_w() cg6r r # Apply this function to 2, resulting in f^256_w(2) e # Print the result in the same encoding as the source code ``` We can see the code working by reducing it to just `f_w(2)`. This outputs `2^2^18`, which is represented by `2^18` copies of `2405` in the same encoding as the source. ``` 2405722171721644307443556644355575375 ``` [Try it online!](https://tio.run/##HcXBEQAgCAPBliQQrv/KouNnl0RzjFQUqp3pw8Pe/Rk3Ti4 "7 – Try It Online") [Answer] **Python: 85** ``` f=lambda a,a:a*a exec'f=lambda a,b,f=f:reduce(f,[a]*b,1)'*99 exec'f('*64+'3'+',3)'*64 ``` Which maybe could be shortened to *74 + `length(X)`*: ``` f=lambda a,a:a*a exec'f=lambda a,b,f=f:reduce(f,[a]*b,1)'*int('9'*X) f(3,3) ``` Where `X` is an appropriate big number such that the resultant hyperoperation on `3, 3` is bigger than Grahams number(if this number is less than `99999999999` then some byte is saved). --- Note: I assume the python code is executed on the interactive interpreter hence the result is printed to stdout, otherwise add `9` bytes to each solution for the call to `print`. [Answer] # Javascript, 83 bytes Another Ackermann function solution. ``` (function a(m,n,x){return x?a(a(m,n,x-1),n,0):(m?a(m-1,n?a(m,n-1):1):n+1)})(9,9,99) ``` [Answer] # Ruby, 60 bytes ``` f=->n{n.times{eval("n.times{"*n+"n+=1"+"}"*n)};n};f.call(64) ``` This is \$f\_{\omega+1}(64)\$, exactly, which is slightly bigger than Graham's number :) I copied this from Simply Beautiful Art on their Bignum Bakeoff post. ]
[Question] [ Choose a set of four bytes without replacement (i.e. no byte repeated), and not necessarily in any particular order, from any one of the following four sets: 1. The characters of any one single-byte encoding 2. The Unicode characters in the range 00–FF 3. The signed decimal integers in the range −128–127 4. The unsigned decimal integers in the range 0–255 The four values you chose (please state which they are) will be the valid inputs. You must pair each value with one of the below ASCII artworks. Given (by any means) one of your four valid inputs, respond (by any means, even list of strings) with the corresponding ASCII art. Extra white-space is allowed on all sides, as long as the image is in there in one contiguous 2D area. First byte: ``` /\ / \ | | | | | | |____| \__/ | | | | | | | | /\ | | /\ / \| |/ \ | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | | || || | AAAAAAAAAAAA ``` Second byte: ``` /\ / \ | | | | | | |____| \__/ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | AAAA ``` Third byte: ``` /\ / \ | | | | | | |____| \__/ | | | | | | |__| /\ ``` Fourth byte: ``` db _/\_ \__/ | | | | | | |__| /\ ``` > > What's new about this ASCII art Kolmogorov complexity challenge? > > > 1. The ability to select valid inputs presents a new aspect to the challenge. The inputs are clearly too limited to encode the entire result, but can carry enough information to merit attention. > 2. The multiple possible outputs share a lot of structure, so reuse of code or sub-images is feasible both within each image and between images. > 3. There is enough duplication that even languages which are not well-geared towards challenges like this have a fair chance of being able to use clever code rather than just hard-coding strings extensively. > > > [Answer] # JavaScript (ES6), 247 bytes RegPack'ed. Expects 0...3 as input. ``` n=>[...'BigFu!#?%$Rocket'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),`oF#$! FRFRFRF|??|$i$t$t$t$t%# t # !t!BBB uuceeeeeee%c%|?| o#, db _#_ iggg |?|%#g|o|e%t%t%tkgttgttcu,o#%! RRR|??|%ieF R|oo| $ oo% ?__#/\\!/o\\uAAAAFo g ti\\?/Bkkk`).split`,`[n] ``` [Try it online!](https://tio.run/##dY7NioMwFIX3eYpIDCaMk/6trYwLH8CtKdqJaUiVXKlx6CLv7tgpdDHQcy4c7uXjcK/nn/Okbnb0nw46vVyyxWXHWgiRFNaUc0RyGlegeu2Tk7jpblaasSlVPDuyezaJaRysZ4pzcQXr2F2MMDLO0xZKEkeorP4c8jzENvZPU4I9JijyUVEUaF4rn6KKhjwgICnuvlFDGmSNMWi9UWICBE39w73xfh01p0BohKqqetRTq0tcBYCAYgRAEc6bhmykjDYg5fy1qgRskLdS5pui7/uWP79v07Z2p0WBm2DQYgDDktpl25N0Cf7AF7blayTrxtF/aPeCdu@h/Qvav4cOL@jA@fIL "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes ``` NθF⁼³θ«PAA↑↑¹⁸↗²‖MM⁴±χ»¿θ«↙²↓⁴M↗__¶\_¶»↓d/_¶ _\↓×⁴∨›²θ⁶¿‹¹θAA↑¶/_‖M ``` [Try it online!](https://tio.run/##XVBfS8MwHHxeP8WPPCUQ2TqHiD4NFBHWOYa@BUqtv26BLGmTdD6Inz0m9c9WX0Jyd7k7rt5XtjaVCuFRt71f94dXtLRjt1ljLND7rq@Uo5ccOsbgI5sUvfKytVJ7SpZLEnWTwhyR3ry06b4ZmPjgkF@PgK3c7T2HeQK32CisfSGtNZb@eSw4rHFXeaT5jEX0M5MNxC4p98fnzrzrFTa/Rmcoh8V5mSHuJCFlKbQQ8SCDMSqHMPpN3qaRhVKIpBhRz/KALrV7svTBYixo6TwtwuGKpaKp5gqdo/n3TpvTPqOkNAsRelqmiP8jhDALF0f1BQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a number 3-0. Explanation: ``` Nθ ``` Input the number. ``` F⁼³θ«PAA↑↑¹⁸↗²‖MM⁴±χ» ``` If it is 3, draw half the booster, then mirror it, then move to the tip of the rocket. ``` ¿θ«↙²↓⁴M↗__¶\_¶» ``` If it is not 0, draw the left half of the front fuel tank. ``` ↓d/_¶ _\ ``` But if it is 3, draw left half of the nose cone. ``` ↓×⁴∨›²θ⁶ ``` Draw the left side of the rocket. ``` ¿‹¹θAA↑¶/_‖M ``` Draw the appropriate base of the rocket and then mirror to finish. [Answer] # [Clean](https://clean.cs.ru.nl), ~~292~~ ~~278~~ ~~273~~ ~~271~~ ~~262~~ 261 bytes *-5 bytes thanks to [Adám](https://codegolf.stackexchange.com/questions/155065/falcon-heavy-stages/155072#comment378325_155072)* ``` import StdEnv,Text e=[k,k,k,"|__|",m] l=repeatn o="\\__/" n="/ \\" m="/\\" u="| |" s="AAAA" k="| |" ?z=[m,n,u,u,u,"|____|",o:z] ``` # ``` \i=[cjustify 12[c\\c<-:q]\\q<-[?[k,k,k,k,m+" "+k+" "+m,n+k+n,k+k+k:l 18(k+k+k)]++[s+s+s],?(l 24k++[s]),?e,["db","_/\\_",o:e]]!!i] ``` [Try it online!](https://tio.run/##RU9BasMwELzrFZvtJcEybpIeSohqCu2h0EMhvVnCKI5cVEtyYsuhCX57XdmUdgdWo2GZnS2Mkm6w9aEzCqzUbtD2WDcedv7w7M70XX15olhW0RHY53mP1ApiWKOOSnpHaoac53mCxDFMADhHYgMb345hD6F6JC3Dx1BIqkkLSnplmaWOdhNG68m83lzFkCRwlqZTLchGwS2FJYUVhTXZedl4cgNl5wqvawcMuGZZ8dm1XpcXWK6ygvNiG29OgvPTNs7S3@wVtRECRtXUw@LAHK1CrzYGlvfziS5EFGVtFCBoOjewuqtGQSxoqmiGhz1SzMNt@RhUCTGbaRHiHBvlp/0hjtGth/gBSiO90S7cMCqE/Q/N/9KvF8N3EQY/2iHeD/HL6/B0cdLqop0@b8GirBv7Aw) A lambda function, mapping the `Int` values `0..3` to the images in the order listed in the OP. [Answer] # [Python 2](https://docs.python.org/2/), ~~292~~ ~~290~~ ~~284~~ ~~282~~ 281 bytes ``` i,j,d,e,x,y=input()," "," /\\ ","/ \\","| |","\__/" f=i<1 l,m,n,p,q,s=3*f*j,j*(i<3),d*f,e*f,x*f,j*(i>0) print"\n".join(([l+j+d,l+j+e]+[l+"| |"]*3+[l+"|____|",l+j+y],[" db\n_/\_",y])[i>2]+([l+j+x]*4+[n+s+x+n,p+s+x+p]+[q+s+x+q]*18+[s+"A"*(4,12)[f]],[m+x]*3+[m+"|__|",m+d])[i>1]) ``` [Try it online!](https://tio.run/##JY7RasQgEEXf8xXikzpD0yT7sA@bhX6HilBMqLJxTZNCAvvv6ZgVrtcZxnsm7@vPM7XHETCixwE33PuQ8t8qJHLGSbUxxWvGjCF/MfYiM87VvBr7cGuqB06YMOOMS9@pUUWMSoRbJ9GrEQfSRiq9@6es8m9IKzeJf8RnSELoB0TwWO7BAlUFUSBWde/S0SFmmdgtas78t0muNo7jbqUO99bCO2az6gI6wQIb0EanZwqdz9dsVXMFvQD/4kpcsGmlHi0lTuUjwaYTRqgJ/BncWHkc3T8 "Python 2 – Try It Online") Takes an integer 0 to 3 as input and uses list indexing (1 or 0) to build each output. -2 for an unneeded pair of brackets. -6 by removing a variable assignment that was only used once. -2 for another single use variable. -1 with a tip from @Rod [Answer] # [Ruby](https://www.ruby-lang.org/), ~~234~~ ~~212~~ 205 bytes ``` ->n{y=*"| " h=%w{/ /\ }+["| "]*3+%w{|__ \\_}+y*3 t=%w{|_ /} [h+["| ","/\\ | ","/ \\| ",*["| || "]*18,?A*6],h+y*21<<?A*2,h+t,%w{d _/ \\_}+y*3+t][n].map{|a|a.rjust(6," ")+a.reverse.tr("\\\\/d","/\\\\b")}} ``` [Try it online!](https://tio.run/##PY3RSsQwEEXf8xXDiNAmMXG3sPiwUfyOJpSuzVIE49KmSmny7XW2q87TvYfLmWE6zevZrA/PYZkNxwTIenP/vWjQFrKoiQA6XgliqWnA2iaLmVcsmo2Azqzutx1K1NbCLQAtr4lvhpSukt2TfHnlByd7Mux3xyO1PZUoSdVBo//tIro6OPXRXpbUplYN79MYi4NEwFJQ9V9@GL2KQ4GWTne339aesMx5LR6Vqkrl27ceuk9IITGAyxRHwDqYuyVkh3/kTI9@M/OhW38A "Ruby – Try It Online") Takes an integer 0-3. Builds an array of the left halves of each phase, indexes in, then pads and reflects each row. All padding is to the same width, so the latter phases have leading whitespace. Returns an array of strings. -2 bytes: Declare `y` as an array right away instead of needing `*[y]` later. -5 bytes: Replace `x="\\"` with `t=%w{_| \\}`. -5 bytes: Less dereferencing, more array addition. -1 bytes: `h+y*21+[?A*2]` -> `h+y*21<<?A*2` in phase 1. -3 bytes: The spec allows the omission of `*$/` to join the result. -4 bytes: `["b","\\_","_/"]` -> `%w{b \\_ _/}` in phase 3. -2 bytes: Use `%w` notation in the head array also. -7 bytes: Use `rjust` instead of manual padding (this also means generating the left side and mirroring it, instead of starting with the right side) Ungolfed: ``` ->n{ y=*"| " # Same as y=[" |"] h=%w{/ /\ }+["| "]*3+%w{|__ \\_}+y*3 # Head for phases 0-2 t=%w{|_ /} # Tail for phases 2,3 [ h+["| ","/\\ | ","/ \\| ",*["| || "]*18,?A*6], # Phase 0 h+y*21<<?A*2, # Phase 1 h+t, # Phase 2 %w{d _/ \\_}+y*3+t # Phase 3 ][n].map{|a| # Choose phase a.rjust(6," ") + # Pad left to width 6 a.reverse.tr("\\\\/d","/\\\\b") # Add mirror (right side) } } ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 90 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ┐∙2╚;+ƨA+.1>?jj■|_ /√+}R 3<?'».1>⌡9R" kΓC+SA}‘03ž}.‽'⁴R╬³2±6«ž}.3=?4R╬³"XƧ⁸│\׀2⁴‘4n10žP}╬³ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTEwJXUyMjE5MiV1MjU1QSUzQisldTAxQThBKy4xJTNFJTNGamoldTI1QTAlN0NfJTIwLyV1MjIxQSslN0RSJTBBMyUzQyUzRiUyNyVCQi4xJTNFJXUyMzIxOVIlMjIlMDlrJXUwMzkzQytTQSU3RCV1MjAxODAzJXUwMTdFJTdELiV1MjAzRCUyNyV1MjA3NFIldTI1NkMlQjMyJUIxNiVBQiV1MDE3RSU3RC4zJTNEJTNGNFIldTI1NkMlQjMlMjJYJXUwMUE3JXUyMDc4JXUyNTAyJTVDJXUwNUMwMiV1MjA3NCV1MjAxODRuMTAldTAxN0VQJTdEJXUyNTZDJUIz,inputs=Mw__,v=0.12) Inputs 0/1/2/3 correspondingly to the bytes 1/2/3/4 [Answer] # [Red](http://www.red-lang.org), 333 bytes ``` f: func[g][t:{ }b:{ /\ }c:{/ \}d:{ |}e:{|}j:{\__/}k:{| |}a:{AAAA}h:[1[t b]1[t c]3[d t e]1[d{____}e]1[t j]]z:[3[t k]1[t{|__|}]1[t b]]r: func[w][foreach[i v]w[loop i[print rejoin v]]]switch g[1 do[r h r[4[t k]1[b k b]1[c k c]18[k k k]]r[1[a a a]]]2 do[r h r[24[t k]]r[1[t a]]]3 do[r h r z]4 do[r[1[t{ db}]1[t{_/\_}]1[t j]]r z]]] ``` [Try it online!](https://tio.run/##RY9LbsQgDIb3OYU1F4jyWFTseoVuHQslQCaPajKitJGGcPbUkKQ1EvbnH8OPNXr/MBqQ9l5A//1QeCd0wgNH6DjnDQQlfA7QBJ36WzDCb2ESvpEyDzNDbLbCv3OEQWCBDjqKu6IKNTgwTNpLjmCSMBG9BFZczZH9JuUW6Bgke1pZCfvFmlYNOMIPrfi5LE8Y8WnHhwNrpmV8cJ/oax2dGuCOBegFLQxgsT7v7mBOZhRnRcUbzlzM/AjbbIEXz5f/Y@Uxl2SXxOpPhBfVCaLmQXfJsZd5I8P1q3iIaD8s3opb1kORnVRGKi@qIlUX1ZHqbP8F "Red – Try It Online") Takes 1 - 4 as input ``` f: func [ g ] [ t: { } b: { /\ } c: {/ \} d: { |} e: {|} j: {\__/} k: {| |} a: {AAAA} h: [1 [t b] 1 [t c] 3 [d t e] 1 [d {____} e ] 1 [t j]] z: [3 [t k] 1 [t {|__|}] 1 [t b]] r: func [ w ] [ foreach [ i v ] w [ loop i [print rejoin v]]] switch g [ 1 do [r h r [4 [t k] 1 [b k b] 1 [c k c] 18 [k k k]] r [1 [a a a]]] 2 do [r h r [24 [t k]] r [1 [t a]]] 3 do [r h r z] 4 do [r [ 1 [t { db}] 1 [t {_/\_}] 1 [t j] ] r z] ] ] ``` ## [Rebol](http://www.rebol.com/), 258 bytes I made an experiment with Rebol's `compress` function, compressing a string of all the 4 stages and printing the corresponding part of it after decompression: ``` f: func[n][o:[[1 374][374 196][570 74][644 37]] b: decompress debase{eJzjUgAB/RguMKWgAGbUgDg1OFnxQABmKcTEx+uDGTVQOZwM/RgwA2QTyBYQG2wbiAHDw5vjiAS4IEEOCwGoWmQKGsaQAIYE4eAhqeMFSCICGZKSxBWvHxPPBVYKDzkoAVamHwMAjkWmoKkCAAA=} repeat i o/(n)/2[prin b/(i + o/(n)/1)]] f 3 /\ / \ | | | | | | |____| \__/ | | | | | | |__| /\ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~209~~ 183 bytes ``` ->n{z=[a=' /\\ ',b='/ \\']+['| |']*3+%w{|____| \__/}+[c='| |']*24+[?A*n] n>4&&z[10..-n/6]=n>8?[c,a+c+a,b+c+b]+[c*3]*18:['|__|',a] n==5&&z[0,6]=%w{db _/\_} z.map{|i|i.center(12)}} ``` [Try it online!](https://tio.run/##FY1NDoIwGET3nqIbqbaFyo@GmBTjOdqmaSsmLmwIQoxQzo4fs5jN5L3pR/dbn2JNmzBPQlqBEVcKYeYE5ggphTWVOCJIxJqUdP@do4FEpIzhC5VebPM2FhWVtzsJeheaKkkmmZ@yLA38okVo6pv0zFJPLXPQDrSelJrk9RX84MPMAijEeSNPDCC4ejhkuDLLbsretpvjK74y34ah7Q95cVyWtRuHD3rKvNDrHw "Ruby – Try It Online") Required inputs as follows: ``` Centre core + upper stage + fairing: 4 As above + boosters : 12 Upper stage + fairing: 6 Upper stage without fairing 5 ``` The idea is to take the `centre core + upper stage + fairing` as a default and modify it for the other outputs. **Commented** ``` ->n{ #z = array of parts for centre core + upper stage + fairing, with n A's at the bottom z=[a=' /\\ ',b='/ \\']+['| |']*3+%w{|____| \__/}+[c='| |']*24+[?A*n] #if n not 4, z from element 10 to the last [10..-1] or last but one [10..-2] = n>4&&z[10..-n/6]= n>8?[c,a+c+a,b+c+b]+[c*3]*18: #centre core + boosters# ['|__|',a] #upper stage engine n==5&&z[0,6]=%w{db _/\_} #if n==5, replace first 6 elements with unfaired payload z.map{|i|i.center(12)} #pad each element of array to 12 characters } #return array of strings (format allowed by question) ``` [Answer] # [Jstx](https://github.com/Quantum64/Jstx), 124 [bytes](https://quantum64.github.io/Jstx/codepage) ``` ↕t▌ÇÇÉÇ~éÇÇÇÇÇÇÇÉΘçK↑ε♀▄ü╙Çz⌡"#ße┐é+\òEhZ█╣S♪[ƒuø>!f♪K▌;0♂9☺}ås══½☻eP▌◙&£óZß:&╝af$V≈-wº[√D(♪╘Pφó√ò▲¶>å⌡◘├^∟z◘αßj◙÷»|æ⌠┼øk&£b ``` Explanation ``` ↕t▌ÇÇÉÇ~éÇÇÇÇÇÇÇÉΘçK↑ε♀▄ü╙Çz⌡"#ße┐é+\òEhZ█╣S♪[ƒuø>!f♪K▌;0♂9☺}ås══½☻eP▌◙&£óZß:&╝af$V≈-wº[√D(♪╘Pφó√ò▲¶>å⌡◘├^∟z◘αßj◙÷»|æ⌠┼ # Push literal /\\n / \\n | |\n | |\n | |\n |____|\n \__/\n | |\n | |\n | |\n | |\n /\ | | /\\n/ \| |/ \\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\n| || || |\nAAAAAAAAAAAA0\n /\\n / \\n| |\n| |\n| |\n|____|\n \__/\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n AAAA0\n /\\n / \\n| |\n| |\n| |\n|____|\n \__/\n | |\n | |\n | |\n |__|\n /\0\n db\n_/\_\n\__/\n| |\n| |\n| |\n|__|\n /\ ø # Push literal 0 k # Push a list of strings obtained by splitting the second stack value with the first stack value. & # Swap the top two stack values. £b # Push the value in the list of the second stack value at the index of the first stack value. ``` [Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.3/JstxGWT.html?code=4oaVdOKWjMOHw4fDicOHfsOpw4fDh8OHw4fDh8OHw4fDic6Yw6dL4oaRzrXimYDiloTDvOKVmcOHeuKMoSIjw59l4pSQw6krXMOyRWha4paI4pWjU%24KZqlvGknXDuD4hZuKZqkvilow7MOKZgjnimLp9w6Vz4pWQ4pWQwr3imLtlUOKWjOKXmSbCo8OzWsOfOibilZ1hZiRW4omILXfCulviiJpEKOKZquKVmFDPhsOz4oiaw7LilrLCtj7DpeKMoeKXmOKUnF7iiJ964peYzrHDn2ril5nDt8K7fMOm4oyg4pS8w7hrJsKjYg%3D%3D&args=MA%3D%3D) [Answer] # [C (clang)](http://clang.llvm.org/), ~~421~~ 408 bytes ``` r,d,i;f(t){char *s=" ",*e="\n",*l[]={" /\\ ","/ \\","| |","|____|","\\__/","| |","AAAA","|__|"," /\\ ","_/\\_","\n"," db","| || || |"},*p[]={"VABU3C1DVE8FFF1G","VABU3C1DVE4F1RYAFAKBFBKZ9MM1YGGG","VABU3C1DVE3F1HI","VLJE3F1HI"},*a="",*b,*c=e,*q=p[t];for(r=1;d=*q++;r=(d/48&&57/d)?d-48:r,c=(d/89&&90/d)?e+90-d:c,a=(d/82&&86/d)?s+86-d:a)if(d/65&&77/d)for(b=l[d-65],i=0;i<r;i++)printf("%s%s%s",a,b,c);} ``` [Try it online!](https://tio.run/##VY9tT8IwEMff71Ncalz2UBxTwGGpBtShIm9MNFFGlrFu2gQnduMV8tnxzocYr2n@d7/73zXNW/kyq553e7rKl2tVwKBulH47eDm1doYrrkXpNO4mf8kMeLVkgMG4V0iWVKjL2VxuGARJgpQFAEmC@kGuD0pSDEqSJE2D7w6VQ4zvNlW/4ylqSuaKoFr8@H8v23Jv9fXew3B0f3QeXjxcRnEch2M0/qFOHN49DuPhZBSPJk/96TR8HI//W47i8OqayO3NT46rM8nwQwvu5bLg3rtczZq5KN@MY2QolPTefV8Y6aigE9l29zhQ7plqdaITw3OiUd@2@22ihd9vt9RJzrMvfmjbUY947Uc95JmrS@S9rm0f0xZ6YiGXM9Xqdedcy7bQAyO077sro6umdNh@TYfxjC947ortDjG8ZrpyXNhYQJUWFtAiDRLaAjQMoIOCS8gBpaNddMBq3dQOY5RvLQtM0axNhQPWdvcJ "C (clang) – Try It Online") ]
[Question] [ # Challenge Write a program or function that takes in 4 non-negative integers, A, B, C, and D, that represent two fractions, A/B and C/D, where B and D are non-zero and A <= B and C <= D. Output an ASCII art depiction of the fractions made of `|x-` characters on two lines as follows: * The lines will always be the same, minimal length for the input, and both always start and end with `|`. * The top line will depict A/B by having B sections of `-`'s separated by `|`'s with A of the sections replaced by `x`'s as if they are filling up the 1 whole of the full line. * Likewise, the bottom line will depict C/D by having D sections of `-`'s separated by `|`'s with C of the sections replaced by `x`'s as if they are filling up the 1 whole of the full line. It will probably make the most sense if I show an example. Suppose A/B = 2/5 and C/D = 1/3, then the output should be: ``` |xx|xx|--|--|--| |xxxx|----|----| ``` Here the lines are the same length, as required, and the top one depicts 2 out of 5 sections filled with `x`'s while the bottom one depicts 1 out of 3 sections filled with `x`'s. As another example, A/B = 1/2 and C/D = 5/8 would give: ``` |xxxxxxx|-------| |x|x|x|x|x|-|-|-| ``` Notice how the number of `x`'s or `-`'s in each section between `|`'s is the same in any one line but can vary depending on the fractions and the requirement that the two lines are the same length overall. In the first example it'd be impossible to just have 1 character between the `|`'s for 2/5 ``` |x|x|-|-|-| (2/5 with 1 character between bars) |xx|--|--| (invalid for 1/3 paired with 2/5 since line too short) |xxx|---|---| (invalid for 1/3 paired with 2/5 since line too long) ``` but with 2 characters between `|`'s it works as shown above. **Your program must use the shortest lines possible.** This keeps them easy to read. The cool idea here is that it's super easy to look as these ASCII art depictions of fractions and see which one is greater or if they are equal, just by how the sections line up. So for the first A/B = 2/5 and C/D = 1/3 example, this output ``` |xxxxx|xxxxx|-----|-----|-----| |xxxxxxxxx|---------|---------| ``` would be invalid, as, even though the lines are the same length and depict the correct fractions, they can be shorter as shown above. # Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge so the shortest program wins! Additional notes and rules: * As stated, B and D will be positive, and A will be from 0 to B inclusive, and C will be from 0 to D inclusive. * There must be at least one `x` or `-` between each pair of `|` as otherwise it's impossible to tell how much of the fraction is filled. * The output can have a trailing newline or not, doesn't matter. * You can take in two fractions directly instead of 4 integers if it makes sense for your language. # Testcases Each testcase is 3 lines, the input `A B C D` on one line, followed by the two lines of the output. Empty lines separate testcases. ``` 2 5 1 3 |xx|xx|--|--|--| |xxxx|----|----| 1 2 5 8 |xxxxxxx|-------| |x|x|x|x|x|-|-|-| 0 1 0 1 |-| |-| 0 1 0 2 |---| |-|-| 1 3 1 2 |x|-|-| |xx|--| 1 2 1 3 |xx|--| |x|-|-| 1 2 2 4 |xxx|---| |x|x|-|-| 1 2 2 2 |x|-| |x|x| 3 3 1 9 |xxxxx|xxxxx|xxxxx| |x|-|-|-|-|-|-|-|-| 3 5 4 7 |xxxxxx|xxxxxx|xxxxxx|------|------| |xxxx|xxxx|xxxx|xxxx|----|----|----| 28 30 29 30 |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|-|-| |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|-| 7 28 2 8 |x|x|x|x|x|x|x|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-| |xxxxxx|xxxxxx|------|------|------|------|------|------| 1 7 2 13 |xxxxxxxxxxxx|------------|------------|------------|------------|------------|------------| |xxxxxx|xxxxxx|------|------|------|------|------|------|------|------|------|------|------| 1 7 2 14 |xxx|---|---|---|---|---|---| |x|x|-|-|-|-|-|-|-|-|-|-|-|-| 0 10 0 11 |----------|----------|----------|----------|----------|----------|----------|----------|----------|----------| |---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------| 3 10 4 11 |xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|----------|----------|----------|----------|----------|----------|----------| |xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|---------|---------|---------|---------|---------|---------|---------| 10 10 11 11 |xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx| |xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx| ``` [Answer] # Excel (ms365), 134 bytes Credits to @[JosWooley](https://codegolf.stackexchange.com/users/116680/jos-woolley) for this is essentially his answer. [![enter image description here](https://i.stack.imgur.com/BDlDL.png)](https://i.stack.imgur.com/BDlDL.png) Formula in `E2`: ``` ="|"&TEXTJOIN({"";" |"},0,REPT(REPT({"x","-"},(1+(MOD(D1,B1)=0))*LCM(B1,D1)/VSTACK(B1,D1)-1)&"|",CHOOSE({1,2;3,4},A1,B1-A1,C1,D1-C1))) ``` --- **2nd Answer**: 74 + 81 = 155 bytes Credits to @[EngineerToast](https://codegolf.stackexchange.com/users/38183/engineer-toast) for this is essentially his answer. Formula in `E2`: ``` =LET(x,2-SIGN(MOD(D1,B1)),z(A1,B1,LCM(B1,D1)*x)&" "&z(C1,D1,LCM(B1,D1)*x)) ``` Note that there should be a literal newline character pieces this together, where `z()` refers to a named function: ``` =LAMBDA(a,b,m,LET(x,m/b-1,"|"&REPT(REPT("x",x)&"|",a)&REPT(REPT("-",x)&"|",b-a))) ``` --- ***Original Answer:** 118 + 138 = 256 bytes* Formula in `E2`: ``` =z(TEXTJOIN("|",0,,IF(SEQUENCE(B1)<=A1,"x","-"),),TEXTJOIN("|",0,,IF(SEQUENCE(D1)<=C1,"x","-"),)) ``` This refers to a named function called 'z': ``` =LAMBDA(a,b,LET(x,LEN(a),y,LEN(b),q,SUBSTITUTE(SUBSTITUTE(IF(x<y,a,b),"|-","|--"),"|x","|xx"),IF(x=y,a&CHAR(10)&b,IF(x<y,z(q,b),z(a,q))))) ``` The idea here is that we create two strings with single 'x' and '-' between pipe-symbols. Z is a named function that will now check the length of both strings and will replace '|x' and '|-' with '|xx' and '|--' respectively for the shortest of the two. It will do so untill the strings have the same length. When found the same length, just concat them together with a newline. [Answer] # Python, 152 bytes Here's the program I used to generate the testcases. I'm sure someone more skilled could golf it down more (and I'd be interested to see!). ``` import math def p(a,b,c,d): L=math.lcm(b,d) if L==max(b,d):L*=2 def f(l,x,d):print('|'+f'{"x"*l}|'*x+f'{"-"*l}|'*d) f(L//b-1,a,b-a) f(L//d-1,c,d-c) ``` It defines the function `p` so calling `p(A, B, C, D)` produces the output. The idea is to imagine all but the first `|` in each line as part of the `x` or `-` sections to simplify the math, and then put the `|`'s back in later. The lcm of the denominators L is the length of the lines, not counting the first `|`. When L is equal to the larger of B or D then each section would be length 1 which would end up looking like `||||||` so the `if L==max(b,d):L*=2` line fixes that situation. Other than that trick it's mostly doing some f-string fanciness to print the lines with the correct values. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` √∏`¬©.¬øD¬Æ√†Q>*¬Æ√∑<‚Äûx-SŒ¥√ó'|√¨sI√≠√Ü√∏√óJ‚ǨƒÜ ``` Port of [*@blaketyro*'s Python answer](https://codegolf.stackexchange.com/a/260823/52210), so make sure to upvote him/her as well! Input as a pair of pairs `[[a,b],[c,d]]`, output as a pair of strings. [Try it online](https://tio.run/##AUoAtf9vc2FiaWX//8O4YMKpLsK/RMKuw6BRPirCrsO3POKAnngtU860w5cnfMOsc0nDrcOGw7jDl0rigqzEhv//W1syLDVdLFsxLDNdXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@P7wj4dBKvUP7XQ6tO7wg0E4LSG23edQwr0I3@NyWw9PVaw6vKa48vPZw2@Edh6d7PWpac6Tt/6HdOoe22f@Pjo420jGN1Yk21DGOjdVRiAYyjIBcUx0LCNdAxxDIBZEoXCOYYmOwXiNkvWhGGemYoHKhio2hei1hXJAzTHTMIVwjCx1jA5BySxANFjLXMbIAG2ABM88czDU0RuObwN1qAHG7IcwKsIAJXMAQqsTQECwUCwA). **Explanation:** ``` √∏ # Zip/transpose the (implicit) input-matrix, swapping rows/columns: # [[a,b],[c,d]] ‚Üí [[a,c],[b,d]] ` # Pop and push both rows separated to the stack ¬© # Store the top pack [b,d] in variable `¬Æ` (without popping) .¬ø # Pop and get its Least Common Multiple D # Duplicate that ¬Æ√† # Push the maximum from pair [b,d] Q # Check if it's equal to the LCM > # Increase that 0 or 1 by 1 * # Multiply it to the LCM ¬Æ/ # Divide it by the values of pair `¬Æ` < # Decrease both by 1 ‚Äûx- # Push string ["x-"] S # Convert it to a pair ["x","-"] Œ¥ # Apply double-vectorized on the two pairs: √ó # Repeat the string the integer amount of times '|√¨ '# Then prepend a "|" in front of each of the four strings s # Swap so the pair of numerators is at the top of the stack I # Push the input-matrix again √≠ # Reverse each inner row √Ü # Reduce each inner list by subtracting √∏ # Create pairs of the two top pairs # [a,c] and [b-a,d-c] ‚Üí [[a,b-a],[c,d-c]] √ó # Repeat the earlier strings that many times J # Join the inner pair of strings together ‚Ǩ # Map over both strings in this pair: ƒÜ # Enclose it; appending its own head (the "|") # (after which the pair of strings is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, ~~31 29~~ 27 bytes ``` yD‚à܃ø~c√üdŒµ»Æ/‚Äü Å‚⧂Äõx-i*∆õ\|j\|√∏. ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJqIiwiIiwieUTiiIbEv35jw59kzrXIri/igJ/KgeKJpOKAm3gtaSrGm1xcfGpcXHzDuC4iLCIiLCJbMywgNSwgMiwgM10iXQ==) or [Verify some test cases](https://vyxal.pythonanywhere.com/?v=1#WyJBIiwiIiwieUTiiIbEv35jw59kzrXIri/igJ/KgeKJpOKAm3gtaSrGm1xcfGpcXHzDuC4iLCI74oGLwrbDuC4gIyBmb3JtYXQgdGVzdCBjYXNlcyIsIlszLCA1LCAyLCAzXVxuWzEsIDIsIDUsIDhdXG5bMCwgMSwgMCwgMV1cblszLCAzLCAxLCA5XVxuWzI4LCAzMCwgMjksIDMwXSJd) -2 bytes thanks to lyxal :) I'm aware of Vyncode but I'm probably going to stick to regular SBCS bytes in my answers for the time being. | Code | Stack (bottom to top) | | --- | --- | | Implicit input | `(3 | 5 | 2 | 3)` | | `y` Every other, and the rest | `(3 | 2) (5 | 3)` | | `D` Push top of stack twice | `(3 | 2) (5 | 3) (5 | 3) (5 | 3)` | | `‚à܃ø` Least Common Multiple | `(3 | 2) (5 | 3) (5 | 3) 15` | | `~c` Execute without pop: Is A in B? | `(3 | 2) (5 | 3) (5 | 3) 15 0` | | `√üd` If so, double, otherwise don't | `(3 | 2) (5 | 3) (5 | 3) 15` | | `Œµ` Absolute difference | `(3 | 2) (5 | 3) (10 | 12)` | | `»Æ` Carry second-to-top over | `(3 | 2) (5 | 3) (10 | 12) (5 | 3)` | | `/` Divide | `(3 | 2) (5 | 3) (2 | 4)` | | `‚Äü` Rotate stack right | `(2 | 4) (3 | 2) (5 | 3)` | | `Å` Range [0, n) | `(2 | 4) (3 | 2) ((0 | 1 | 2 | 3 | 4) | (0 | 1 | 2))` | | `‚â§` Greater than or equal to? | `(2 | 4) ((0 | 0 | 0 | 1 | 1) | (0 | 0 | 1))` | | `‚Äõx-` String literal "x-" | `(2 | 4) ((0 | 0 | 0 | 1 | 1) | (0 | 0 | 1)) "x-"` | | `i` Index into | `(2 | 4) (("x" | "x" | "x" | "-" | "-") | ("x" | "x" | "-"))` | | `*` Repeat string n times | `(("xx" | "xx" | "xx" | "--" | "--") | ("xxxx" | "xxxx" | "----"))` | | `∆õ` Map over each item: | Showing first pass through: | | `\|j` Join by "|" | `"xx|xx|xx|--|--"` | | `\|√∏.` Enclose in "|" | `"|xx|xx|xx|--|--|"` | | `j` flag: Join final result by newlines | Implicit output of result | Let me know if this format of explanation is good, by the way. I'm trying to experiment with doing it in a method that is more obvious what is happening, but it does take up a lot of space. [Answer] # JavaScript (ES6), 113 bytes ``` (p,q,P,Q)=>(F=w=>(n=q*w-Q*W)?F(w+=n<0||!++W):(g=w=>n>q*w?n=` `:'x-|'[n++%w?n>p*w|0:2]+g(w))(w)+g(W,p=P,q=Q))(W=2) ``` [Try it online!](https://tio.run/##Zc9Ba4MwFAfwu58iO5QmJopGh60u9rSe68mDCBVb3UaJ2o45mPvs7ql1pAgxhl/@eXn5yL6yW359rz8NWZ3OfSF6XLOGHVhERIj3ooVZikZvjUiPyW6PWyrki9V1T5TGxMflkJAhBHZSHLWjv/42unUiKV2BhLXedpbPU1rilhD4YBGzWhxYIyKAWHDSB4mGUII4Q88M2Qw5KGWjwHrCzSzWGBjmhXDllDMif6yzrAzDXcj/KWeus1UEmnEZ8mbhGwgNl2@H/6weGze40jiU8aYunCW56mOs6X22culgrmr2PWjbk2qpZhbV9TXL33CGRIh@UF7JW3U5m5eqxKZpZiR4oGJC0F8S9H8 "JavaScript (Node.js) ‚Äì Try It Online") ### Commented ``` ( p, q, // p / q = 1st fraction P, Q // P / Q = 2nd fraction ) => ( // F = w => // F is a recursive function taking a first width w // explicitly and a second width W implicitly (n = q * w - Q * W) // let n be the difference between q * w and Q * W // (NB: n is reused as a counter in the 2nd phase) ? // if n is not equal to 0: F( // do a recursive call to F: w += n < 0 // increment w if n is negative || !++W // increment W if n is positive ) // end of recursive call : // else (n = 0): ( g = w => // g is a recursive function taking w n > q * w ? // if n is greater than q * w: n = `\n` // append a linefeed and reset n to a 0'ish value : // else: 'x-|'[ // append one of these characters: n++ % w // if w is not a divisor of n (which is ? // incremented afterwards): n > p * w // append '-' if n > p * w, or 'x' otherwise | 0 // : // else: 2 // append the separator '|' ] + g(w) // append the result of a recursive call )(w) + // 1st call to g, using (w, p, q) g(W, p = P, q = Q) // 2nd call to g, using (W, P, Q) )(W = 2) // initial call to F with w = W = 2 ``` [Answer] # [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 45 [bytes](https://github.com/abrudz/SBCS) Call as `A C f B D`. ``` {'-x|'[2,‚箂Üë‚ç∫(>‚åà2√ó1,2‚â†/‚ä¢)¬®‚åä‚çµ√ó‚äÇ√∑‚箂àò‚ç≥‚ç®(‚àß‚åà2√ó‚åà)/‚çµ]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZHPSsNAEMbxmqeYW1JoaXaT0j8HL1WwFwXbi5QisUlEqLWQCkrtRSXE2BRFpIKXIIqhVymCx_Yp9DhP4uxGWvCQye_75tuZhX2e2udW5-Rw3-p14mll2zp2vJ7Vdt5O-26u9N0YqLmzC7XJsxgl6N9j9KWt4yjgiwnLcryJ8xi-ZOYJjkKMZosJhpeLTxENnjD6INAweE_zVDN5CrWGr95B2_tZ21DtI6-nAo4fq3ug2m7XUxUStR3073TFpYrRGMMrhv4D-fXdKtXGVq2u9B2vD9SHATkyNwO8vYZUibFANyG3qQNvgQsCGRitoSLPzhPQOBSArAxoDASXiHRy6FsSl12DmP_lVic4mEsSXUPmypIKYEKRiJfAoCllqqSKQJrLRQyKYpixQjNdqov9TA4hNlNmssGYUIpS2eza_94pjtP_Lw) Or, for the same length: ``` {'-x|'[2,‚箂Üë,¬®2,¬®(¬Ø1+‚äÉ(,√∑‚箂àß‚åà2√ó‚åà)/‚çµ)/¬®‚癬®‚ç∫>‚ç≥¬®‚çµ]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZG_S8NAFMdxzV_xtiSY0twlpT8GlyrYQQXrIqVIbBoRai1cBaV2USmlNUURcXDpoBi6OEgQHNO_Qsf3l_juIi043Pc-733ffd9wzzP_wmudHh14ndZ0Vtr2Tpqi4zWar2fdIFP43urpmfNLvcYtDCMc3FtJxOkYyTtbxdG1Yc0_pTF8w9shnz-RmlkMYzObRBjOpHytYfghIa73X8RhQ_ysrOv-sejogJPH8j7oftAWukZFZQcHd7YWkGI4oXiGgwfqV3fLpHublarWbYoukA896qi5GHB8A2klYwFHV9St2cDrEIBEBk69r6m3SQQGhxxQywSDgeQCkU0dOgviynWI-d_c8gUHd0HSddRcUVEOXMgT8QI4lFIkpSoPVHO1iEFehjlLdNOlttzPVAixmzJTBmOy0rTSRtv_90HTaXr_Ag) [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~265 253 248 239~~ 230 bytes ``` function g(p,q){return q?g(q,p%q):p}function l(s,j){a=s;for(i=1;i++<M;)a=a s;b=a=j?a"|":z;for(i=1;i++<j;)b=b a;return b}L+=(L=(B=$2)*(D=$4)/g(B,D))==(B<D?D:B)?L:0,$0="|"l("x",$1,M=L/B-1)l("-",B-$1)"\n|"l("x",$3,M=L/D-1)l("-",D-$3) ``` [Try it online!](https://tio.run/##VY1fa4MwFMXf/RQXcZA7IzWJxVZ7EcRH@w32EscqumK1f9hY18/urtIVCkl@JzfnnNivz3HcXbr3c3PooBa9HPB6/Dhfjh0MWS0G2b8MmPS3h2cvTrLFq6VTujscRUMqbXx/s03RkoVTWpGlNrPur5v8PDnaFCuqwKb3@upW@iRKEjl5Gl9FQV6Ei1rkskAkHm@KrEhyzMoklF5I3LgX7rcrPSW3VC7yQCEPAlfmgafQfeseBjMbioehCDyD46hAwxJWTggKeN@pHQWG1UTNNDM1RHdqx8zva@YSIogdvQLDuTWfTgx801yqIJ7i5l9EU304/aM4yCqalJqHSvH6Aw "AWK ‚Äì Try It Online") * -9 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) * -9 bytes: + -1 replaced `""` with `z` + -8 replaced last structure by implicit assignation --- This use POSIX awk, and not gawk. In gawk you can use the abbreviation `func` for `function`. [GAWK function](https://www.gnu.org/software/gawk/manual/html_node/Definition-Syntax.html) : > > In many awk implementations, including gawk, the keyword function may be abbreviated func. (c.e.) However, POSIX only specifies the use of the keyword function. This actually has some practical implications. If gawk is in POSIX-compatibility mode (see Command-Line Options), then the following statement does not define a function: > > > > ``` > func foo() { a = sqrt($1) ; print a } > > ``` > > [Answer] # [Julia](https://julialang.org), 77 bytes ``` n|d=(l=lcm(d...);x=l*2^(l‚ààd).√∑d.-1;p='|';@. p*('x'^x*p)^n*('-'^x*p)^(d-n)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBBbsMgEEXVrW_Q3ewMVo0MODIRQuoFegIrliLjqKkosRIieeED5A7dZJMz9AA9RbvsSQrGqbyB9zV_PsN83N7OZr-9Xm9nt8vF94sdtUJGmfYdaUIIloMyGWuQ-b1cNCZfn5rkVPYqHVP5TKDPUDqkzZD1uLGe85mRzi3GMfTn4dF1J3dSdVIzWEmgwDdPSU2BSViBCFwAleCPBbPo4cHP_v3LXgblgicPj_51ZP9WCVVgJoAX3rX2V9AVMBGaRAyoAlO-FOU8SjHNRWNgUOWsaCxSGnSySXaHIzg1_RT64946YwkaUbdtX9uDQQ6HdWJ5ryEMndVxQ_f1_wE) Accepts input as two vectors: numerators `n` and denominators `d`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 45 bytes ``` =GyW}J/*FKeMQiFKKJjmsm?%k/Ged?>cFdckG\x\-\|hG ``` [Try it online!](https://tio.run/##K6gsyfj/39a9MrzWS1/LzTvVNzDTzdvbKyu3ONdeNVvfPTXF3i7ZLSU52z2mIkY3pibD/f//6GhjHdNYnWgTHfPYWAA "Pyth ‚Äì Try It Online") Takes input as a list of lists `[[a, b], [c, d]]`. ### Explanation First we compute the length of the lines (minus 1). This is the least common multiple of `b` and `d`, multiplied by 2 if it is exactly `b` or `d`. We save this number in the variable `G`. ``` # implicitly assign Q = eval(input()) KeMQ # assign K to [b, d] *FK # multiply the elements of K / iFK # divide by the gcd of K (to obtain lcm) J # assign this to J yW J # conditional apply doubling to J }J K # if J is in K =G # assign this to G ``` Next, we loop through the input and `G+1` choosing the correct character for each position through two conditional operators. ``` jmsm?%k/Ged?>cFdckG\x\-\|hGQ # implicitly add Q m Q # map d over Q m hG # map k over G+1 ?%k/Ged # if (k % (G / d[-1])): ?>cFdckG # if (d[0] / d[1] > k / G): \x # "x" # else: \- # "-" # else: \| # "|" s # sum the list of chars into a string j # join on newlines and print ``` [Answer] # [Arturo](https://arturo-lang.io), ~~113~~ 105 bytes ``` $->a[e:lcm@[a\1a\3]if‚à®e=a\1e=a\3->'e*2map a[x y]->[124]++map e'z->(0=z%e/y)?->124->(z>x*e/y)?->45->120] ``` [Try it](http://arturo-lang.io/playground?U5lJE0) ``` $->a[ ; a function taking a list of four integers named a e:lcm@[a\1a\3] ; assign lcm of 2nd and 4th args to e if‚à®e=a\1e=a\3-> ; if e is equal to 2nd or 4th arg... 'e*2 ; double e in place; this ensures no zero-width sections map a[x y]-> ; map over input in pairs, assign to x and y [124]++ ; prepend pipe character to... map e'z-> ; map over [1..e] and assign current elt to z (0=z%e/y)?-> ; does e/y divide z? Then... 124 ; pipe -> ; otherwise (z>x*e/y)?-> ; is z greater than x times e/y? Then... 45 ; x -> ; otherwise 120 ; hyphen ] ; end function ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~98 94~~ 93 bytes ``` ->a,b,c,d{[[a,b],[c,d]].map{|x,y|[p,*[?x*~k=b.lcm(d)/y*~1[b%d*(d%b)]]*x,*[?-*~k]*y-=x,p]*?|}} ``` [Try it online!](https://tio.run/##VcpLCoMwFAXQeVfRiaDhxhptoR1YF/J4A2Nw0gqhrZDgZ@tphCJ0dj/nNWof@jrIewuNDmYiiolBMTPnQ2un2cHPZCGocWJ91Dp/dkNqspMXqyKdGJGaRGfMwm1GRsPCy9rBsmjmZQl2/LyPPZW4QKHiw68XuKGAKvYhnij/gNrA3iuco7hy@AI "Ruby ‚Äì Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 166 ~~172~~ bytes > > -6 bytes thanks to @KevinCruijssen ! > > > Thank you for the challenge, it was very cool! ``` (a,b,c,d)->{var r="";int i,j=0,p=b,q=d;while(p!=q|p<=b|q<=d)p+=p<q?b:0*(q+=d);for(;j++<2;r+="|\n",b=d,a=c)for(i=0;i++<b;)r+="|"+(i>a?"-":"x").repeat(p/b-1);return r;} ``` [Try it online!](https://tio.run/##tVXNmpowFN3PU6RZQQlW0PmcMWZ8gXbVZaeLAHGKRYSAln6jy@76CNOXmxexAQKCRL9aRwPk797DOffm4pyuqTn3vu@ilRP4LnADmiTgE/VD8HxzA4AfpozPqMvAR7pwPCpWgfh9TrkfPoGZJvYBRbkZcMrOLTtPx8Jym2MkKU0FtAQIyo7sNIoc5CJPNx@e15QDTiDEuauP5qSPIuKgmHj4xzc/YFr0jsSbaEKcTTwhnh4ZJJrEU2fcf6/FhljAsyXX8NwwJjbmBoGbxxAih3iIElfP93zSx77YdrBe7END8x/oFJpwDDOo9ziLGE216INjWjrmLF3xEHC83eFcgoyOVLJe@h5gaxqckI@qGLEsYm7KPL0dOs6SVZACIuPRm9XhwKXZzyRli95ylfYi4ZAGoaZVUD0Wr2iQaCWGPoWvL7@E3jF8/fNb9LohN@oMKOgvRIq1ksuXr4Dyp6QiWAgDNrpFFhoAgACAmyzLL9OU12MopsVCMS9WIJDMS38L5Qh3tX9WO5gSoG5m0ToIffF@cUuEwueolV1ZmdJOyWggbCvLTBpJXUr@Lf0V6yPYtmjDvdpNQ@UJjyYbad2xHBS875uRbD1rVs2mQLlFQzRq5eOgk7lppKjabDz2KVfn3b5DA5GPe/Gstf1fMzcH5@R8gA67ERL87P2x7Lzw35qMzbHQneoUB2GUH7VBu1Ja5dIEuGByAesLhB0WhepuFIo63N2i7@ffBmtf9l3FVxvmH5ju@hVHimIW@od7/Y0jox6@tX7FS5SjK@m3igNgWWdE4E2HZ0TgbUYyAuX/@Xb3Fw "Java (JDK) ‚Äì Try It Online") --- A little explanation of my answer: first we calculate the "**Least Common Multiple strictly greater than the `b` and `d` parameters**" using the following: `p=b,q=d;while(p!=q|p<=b|q<=d)p+=p<q?b:0*(q+=d);` which leaves the result in `p`. Then we draw the 2 lines (using a small loop) with an inner loop that decides using its index wether we should draw a `x` or `-`, and we repeat this character a number of times using: the "**greater-LCM**", divided by the `b` or `d` parameter (depending on the current line), minus 1. And the `|` and `\n` are put where they should be during the process. [Answer] # SAS, 181 (73+108) bytes 1. The code: Macro (73): ``` %macro m(x,n,k);s=repeat("&k",&n-2);do i=1to &x;put s+(-1)"|"@;end;%mend; ``` Data step (108): ``` data;set;L=LCM(b,d);L=L+(L=b<>d)*L;put"|"@;%m(a,L/b,*)%m(b-a,L/b,-)put/"|"@;%m(c,L/d,*)%m(d-c,L/d,-)put;run; ``` *Process:* Process assumes that input data are passed in a SAS dataset with variables `a`, `b`, `c`, and `d`. Dataset has to be created just before executing the code. Example data (extending test cases): ``` data i; input A B C D; cards; 2 5 1 3 1 2 1 3 1 2 2 4 1 2 2 2 3 3 1 9 1 3 1 9 1 3 3 9 3 9 5 15 3 5 4 7 28 30 29 30 7 28 2 8 1 7 2 13 1 7 2 14 0 10 0 11 3 10 4 11 10 10 11 11 2 3 11 17 1 10 2 10 10 100 20 100 1 10 10 100 1 10 1 1 1 1 1 10 3 3 1 9 1 1 1 1 0 1 0 1 ; run; ``` 2. Human readable code: Macro: ``` %macro m(x,n,k); s = repeat("&k", &n-2); do i = 1 to &x; put s +(-1) "|" @; end; %mend; ``` Data step: ``` data ; set ; L = LCM(b, d); L = L + (L = b<>d)*L; /* put / / a +(-1)"/" b " " c +(-1)"/" d; */ put "|" @; %m( a, L/b, *) %m(b-a, L/b, -) put / "|" @; %m( c, L/d, *) %m(d-c, L/d, -) put ; run; ``` Uncoment the `put / / a +(-1)"/" b " " c +(-1)"/" d;` line to have nicer looking result in the log. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` Ժƌ∏‚äûœÖÔºÆԺƌ∑‚äûœÖԺƂâœÖŒ∂Ôº∑Œ£Ôπ™Œ∂œÖ‚ⶂäïŒ∂Ôº¶œÖ¬´‚ü¶‚≠Ü‚äïŒ∂‚éáÔπ™Œ∫√∑Œ∂Œπ¬ß-x‚ÄπŒ∫√óŒ∏√∑Œ∂Œπ|‚üß‚âîŒ∑Œ∏ ``` [Try it online!](https://tio.run/##fZBPa8JAEMXP@imGnGZgPbTSU0@Cl4AWQW/iISZTdzHZ6P6xmraffd2tCoGCp2Eev/fmMaUsTNkWdQi5Pnj34ZstGzzS@3DhrUQvoK9T1Pu7fMJNrFU7jUvfoCcBXZS@pKoZ/qR5W/m6xU6AJyKYF4c7n@vScMPacXUzfbYGYgJ8DwcLo7TD9dLFuYuWPoxdPLJiowtzeaTvUys3VSdVcTqlKDITl@uKz5iNzpmAGVubuJVq2OLxvyFZsp@MaBO7DO4lpYD0ot8QXuENXmAcRqf6Cg "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation: ``` Ժƌ∏‚äûœÖÔºÆԺƌ∑‚äûœÖN ``` Input the four integers, but push the denominators to the predefined empty list. ``` ‚âœÖŒ∂Ôº∑Œ£Ôπ™Œ∂œÖ‚ⶂäïŒ∂ ``` Calculate the adjusted LCM of the denominators, which is like the LCM execpt that it can't equal either denominator. This is achieved by starting the search with the sum of the denominators. ``` Ôº¶œÖ¬´ ``` Loop over the denominators. ``` ‚ü¶‚≠Ü‚äïŒ∂‚éáÔπ™Œ∫√∑Œ∂Œπ¬ß-x‚ÄπŒ∫√óŒ∏√∑Œ∂Œπ|‚üß ``` Calculate the display for this denominator. ``` ‚âîŒ∑Œ∏ ``` Copy the second numerator to the first so that the second loop calculates the display for the second denominator correctly. 43 bytes by taking the inputs in the order B, D, A, C: ``` Ôº¶¬≤‚äûœÖԺƂâœÖŒ∂Ôº∑Œ£Ôπ™Œ∂œÖ‚ⶂäïŒ∂Ôº¶œÖ¬´ÔºÆŒ∏‚ü¶‚≠Ü‚äïŒ∂‚éáÔπ™Œ∫√∑Œ∂Œπ¬ß-x‚ÄπŒ∫√óŒ∏√∑Œ∂Œπ| ``` [Try it online!](https://tio.run/##ZY49i8JAEIZr/RVDqhmIxXlYWQnXBPQQTCcWuWQ0i8lGd3c0F73fvm78AOGqgZn3mefNy8zkTVZ5v20M4JhgKbZEiSHRB3HfUv@wQaLpcGat2mlcSY1CMXRhdS5VxXBfLZpCqga7GISIYJEdnvlE54Zr1o6LB3T3CMFlOHhXHMNpsDRKO1yvXJi78OOdxi5YUzY6M78v3b6v6b7USRXcuxWFzMwluuAWo1EbxTBna/tcqmq2ePwP9Eh0jYg2ocGf9xP4hDF8@NGpugE "Charcoal ‚Äì Try It Online") Link is to verbose version of code. [Answer] # [J](http://jsoftware.com/), 55 52 51 bytes ``` '-x|'{~(*.(%*1+e.),)&{:(2,~&,2,.}.@#"+)&>;&((>i.)/) ``` [Try it online!](https://tio.run/##lZExb4MwEIV3fsXFFLDBGNsoLTgNQq3UqerQlXiqEjVdulZK8F@nB2WAELXqYFv@7t57Z/mjK1dG2duVKaPIIyI6wNZABBwkGFypgMfX56cuSr/O0cnRWNAgVsleMM7Ck6Gau5BrLlpR@yRhYbUJKa2OgmWsY97Lg4BflbJ1oV4o/9ANga41/9VhXlo3Q@TOXwopxfZKZEQxOpr0ORZRzU1zQxJlmI7l1jJLA3fOjqK2LBYZbX5y7DS/MRxftiGqH8QGrpnOgmPc11Qb2Vq2IxKUH1ZsMs7@7f0TFKzhABry4Yq/M1KNdA3FjKIFUtyvUn3hkCNVC6oHei1NX/Tmo0M5o7qAXPbdJZ6zyl1f620Kz@u@AQ "J ‚Äì Try It Online") Great challenge, surprisingly difficult to golf, and tried a few different approaches just to get this: The basic idea is: 1. First create each fraction with no dividing bars, using 0 for "empty" and 1 for "full". Eg, \$ \frac{2}{3}\$ is `1 1 0` and \$\frac{1}{5}\$ is `1 0 0 0 0`. 2. Next we compute the amount each number needs to "puff up", so that the final length is the modified LCM -- 15 in this case. The modification, described in many other answers, is to double the LCM when one of the denominators *is* the LCM. 3. "Puff up" each number as needed -- 5x for \$ \frac{2}{3}\$ and 3x for \$\frac{1}{5}\$ (extra spaces for clarity): ``` 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 ``` 4. Change the first element in each group to a 2, to represent the divider, and append and extra 2 at the end: ``` 2 1 1 1 1 2 1 1 1 1 2 0 0 0 0 2 2 1 1 2 0 0 2 0 0 2 0 0 2 0 0 2 ``` 5. Convert to ascii: ``` |xx|--|--|--|--| |xxxx|xxxx|----| ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 30 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` z·∫∏√êD≈Ä∆Å∆á‚Å∫√ó_\¬µ¬´L¬©ƒ±`x-si;√óƒ±'|j'|·πõ ``` Requires Thunno 2.2.0+ for stack rotation. ATO is on v2.1.9. Port of Jacob's Vyxal answer. See that answer for a more detailed explanation. #### Explanation ``` z·∫∏ # Uninterleave into two pieces √êD # Quadruplicate so four copies are on the stack ≈Ä # Pop one copy and push the LCM ∆Å∆á # Without popping anything, check for containment ‚Å∫√ó # Increment and multiply (i.e. double if true) _ # Subtract the list from this number \ # Divide the two lists ¬µ¬´ # Rotate the stack left L # Lowered range of each number ¬© # Less than or equal to ƒ± # Map over this list of lists: `x- # Push the string "x-" s # Swap so the list is on top i # Index into the string ; # End map √ó # Multiply each string by each number ƒ± # Map over this list of lists: '|j # Join the list by the character "|" '|·πõ # And surround this string by the character "|" # N flag joins by newlines # Implicit output ``` #### Screenshot [![Screenshot](https://i.stack.imgur.com/G1D4Hm.png)](https://i.stack.imgur.com/G1D4H.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` :g/He¬°$$·πö·π¨‚Ǩ·∏∑‚±Æ"∆≤~R}¬¶"·π≠‚Ǩ1·ªã‚Äú|x-‚ÄùY ``` A full program that accepts the denominators, `[B, D]` and the numerators, `[A, C]`, and prints the result. **[Try it online!](https://tio.run/##AU4Asf9qZWxsef//OmcvSGXCoSQk4bma4bms4oKs4bi34rGuIsayflJ9wqYi4bmt4oKsMeG7i@KAnHx4LeKAnVn///9bMTAsIDExXf9bMywgNF0 "Jelly ‚Äì Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/98qXd8j9dBCFZWHO2c93LnmUdOahzu2P9q4TunYprqg2kPLlB7uXAsUNHy4u/tRw5yaCt1HDXMj/xcbhUYdXq4fruPgHamZ9ahx36Fth7b9/x8dbaSjYKqjYKijYByroxANpCECFiCeAVgCRKLwjKAqjcECRgh9qKYAkQkKD6zSGKbPEsoDWmaio2AO4hlZACVBFliCaJCIOZBjAdZsATXKHGKTMSrXBOZAA4h7DaGGg/gmML4hVIGhIVgkFgA "Jelly ‚Äì Try It Online"). ### How? ``` :g/He¬°$$·πö·π¨‚Ǩ·∏∑‚±Æ"∆≤~R}¬¶"·π≠‚Ǩ1·ªã‚Äú|x-‚ÄùY - Main Link: [B, D]; [A, C] ∆≤ - last four links as a monad - f([B, D]): $ - last two links as a monad - f([B, D]): $ - last two links as a monad - f([B, D]): / - reduce by: g - greatest common divisor (GCD) ¬° - repeat... e - ...number of times: exists in? - i.e. if the GCD is one B or D: H - ...action: halve (the GCD) : - ([B, D]) integer divide (that) (vectorises) ·πö - reverse ·π¨‚Ǩ - untruth each - e.g. 4 -> Patten = [0,0,0,1] " - zip with ([B, D]) applying: ‚±Æ - map (across implicit range [1..x]): ·∏∑ - left argument - i.e. B and D copies of the respective Patterns " - zip with ([A, C]) applying: ¬¶ - sparse application... R} - ...to indices: range of right -> [1..A] or [1..C] ~ - ...action: bitwise NOT -> 0:-1 and 1:-2 ·π≠‚Ǩ1 - tack each to a one - handles the leading "|" ‚Äú|x-‚Äù - list of characters = "|x-" ·ªã - (repeated, augmented Patterns) index into (those) - 1-based and modular so -2 & 1 are '|', 0 is '-', and -1 is 'x'. Y - join with a newline - implicit, smashing print ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=pairmap -pa`, ~~97~~ 96 bytes ``` ($_,$\)=pairmap{"|x"x$a."|-"x($b-$a)."| "}@F;($c<0?$_:$\)=~s/\|\K./$&$&/g while$c=y///c-length$\ ``` [Try it online!](https://tio.run/##NY1BC4IwGEDv/YoxPkShOS2EWEmdulTHbgOZY@hg6XCDjKyf3rJDx/fg8awaTBFCDNUSeFJaoYebsE88jXgEkeKJ4DGGmoBIZljg1@G4jUHusj1U7Fe8HeUTP6UUIohog@6tNgpk@aCUSmJU1/gWeAg5WqE12nx663XfuUAuZ@08Y1evzX87yyLN8iwQK74 "Perl 5 ‚Äì Try It Online") Brute force method. Creates each fraction with only one character between the lines. Then it extends the length of the shorter by one more character between the lines, repeatedly, until the two lengths are the same. ]
[Question] [ While idly twisting my [Rubik's cube](https://en.wikipedia.org/wiki/Rubik%27s_Cube) around, my son noticed that it kept going back to the solved state. I'm pretty sure he thought this was some sort of voodoo magic at first, but I explained that if you keep repeating the same sequence of moves, it will always return to its original state. *Eventually.* Of course, being a kid, he had to try it out for himself and picked a "random" sequence he thought would be tricky. He lost track after ten repeats or so, and asked me how many times he would have to repeat it. Not knowing the sequence he was using, I told him I didn't know, but that we could write a program to find out. This is where you come in. Of course, I *could* just whip something up, but he'd like to type it in himself. He isn't a very fast typist yet, though, so I need the *shortest program possible*. ### Objective Given a sequence of turns, output the fewest number of times it must be performed to return the cube to its original state. This is code golf, so least bytes wins. You can write a program or function, and all the other usual defaults apply. ### Input Input is a sequence of moves, taken as a string, list, or other format suitable for your language. Feel free to use a separator (or not) between moves if in string form. There are six "basic" moves that must be taken into account, along with their inverses: ``` R - Turn the right face clockwise L - Turn the left face clockwise U - Turn the up (top) face clockwise D - Turn the down (bottom) face clockwise F - Turn the front face clockwise B - Turn the back face clockwise ``` The inverses are represented by adding a prime mark `'` after the letter. This indicates you turn that face counterclockwise, so `F'` turns the front face counterclockwise, and `F F'` would return it to the original state right away. For the interested, this challenge is using a limited set of [Singmaster Notation](http://rubiks.wikia.com/wiki/Notation). Ruwix has [some nice animations](http://ruwix.com/the-rubiks-cube/notation/) if you'd like to see it in action. ### Output Output is simply the minimum number of times the input sequence must be performed. ### Examples ``` Input Output FF' -> 1 R -> 4 RUR'U' -> 6 LLUUFFUURRUU -> 12 LUFFRDRBF -> 56 LF -> 105 UFFR'DBBRL' -> 120 FRBL -> 315 ``` Here's a (quite naive) solver to compare your answers to, written in Java. It also accepts `2` for double moves (so the fourth case is equivalent to `L2U2F2U2R2U2`). ``` import java.util.ArrayList; import java.util.List; public class CycleCounter{ public static void main(String[] args){ int[] cube = new int[54]; for(int i=0;i<54;i++) cube[i] = i; String test = args.length > 0 ? args[0] : "RUR'U'"; List<Rotation> steps = parse(test); System.out.println(steps.toString()); int count = 0; do{ for(Rotation step : steps) cube = step.getRotated(cube); count++; }while(!isSorted(cube)); System.out.println("Cycle length for " + test + " is " + count); } static List<Rotation> parse(String in){ List<Rotation> steps = new ArrayList<Rotation>(); for(char c : in.toUpperCase().toCharArray()) switch(c){ case 'R':steps.add(Rotation.R);break; case 'L':steps.add(Rotation.L);break; case 'U':steps.add(Rotation.U);break; case 'D':steps.add(Rotation.D);break; case 'F':steps.add(Rotation.F);break; case 'B':steps.add(Rotation.B);break; case '\'': steps.add(steps.get(steps.size()-1)); case '2': steps.add(steps.get(steps.size()-1)); break; } return steps; } static boolean isSorted(int[] in){for(int i=0;i<in.length-1;i++)if(in[i]>in[i+1])return false;return true;} enum Rotation{ R(new int[]{-1,-1,42,-1,-1,39,-1,-1,36, -1,-1,2,-1,-1,5,-1,-1,8, 20,23,26,19,-1,25,18,21,24, -1,-1,11,-1,-1,14,-1,-1,17, 35,-1,-1,32,-1,-1,29,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1}), L(new int[]{9,-1,-1,12,-1,-1,15,-1,-1, 27,-1,-1,30,-1,-1,33,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 44,-1,-1,41,-1,-1,38,-1,-1, -1,-1,6,-1,-1,3,-1,-1,0, 47,50,53,46,-1,52,45,48,51}), U(new int[]{2,5,8,1,-1,7,0,3,6, 45,46,47,-1,-1,-1,-1,-1,-1, 9,10,11,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 18,19,20,-1,-1,-1,-1,-1,-1, 36,37,38,-1,-1,-1,-1,-1,-1}), D(new int[]{-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,24,25,26, -1,-1,-1,-1,-1,-1,42,43,44, 29,32,35,28,-1,34,27,30,33, -1,-1,-1,-1,-1,-1,51,52,53, -1,-1,-1,-1,-1,-1,15,16,17}), F(new int[]{-1,-1,-1,-1,-1,-1,18,21,24, 11,14,17,10,-1,16,9,12,15, 29,-1,-1,28,-1,-1,27,-1,-1, 47,50,53,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,8,-1,-1,7,-1,-1,6}), B(new int[]{51,48,45,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,0,-1,-1,1,-1,-1,2, -1,-1,-1,-1,-1,-1,26,23,20, 38,41,44,37,-1,43,36,39,42, 33,-1,-1,34,-1,-1,35,-1,-1}); private final int[] moves; Rotation(int[] moves){ this.moves = moves; } public int[] getRotated(int[] cube){ int[] newCube = new int[54]; for(int i=0;i<54;i++) if(moves[i]<0) newCube[i] = cube[i]; else newCube[moves[i]] = cube[i]; return newCube; } } } ``` [Answer] # Pyth, ~~66~~ 63 bytes ``` l.uum.rW}Hdd@_sm_B.iFP.>c3Zk3xZHG_r_Xz\'\39Nf!s}RTcZ2y=Z"UDLRFB ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=l.uum.rW%7DHdd%40_sm_B.iFP.%3Ec3Zk3xZHG_r_Xz%5C%27%5C39Nf!s%7DRTcZ2y%3DZ%22UDLRFB&input=RUR%27U%27&test_suite_input=FF%27%0AR%0ARUR%27U%27%0ALLUUFFUURRUU%0ALUFFRDRBF%0ALF%0AUFFR%27DBBRL%27%0AFRBL&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=l.uum.rW%7DHdd%40_sm_B.iFP.%3Ec3Zk3xZHG_r_Xz%5C%27%5C39Nf!s%7DRTcZ2y%3DZ%22UDLRFB&input=RUR%27U%27&test_suite=1&test_suite_input=FF%27%0AR%0ARUR%27U%27%0ALLUUFFUURRUU%0ALUFFRDRBF%0ALF%0AUFFR%27DBBRL%27%0AFRBL&debug=0). Notice that the program is kinda slow and the online compiler is not able to compute the answer for `RU2D'BD'`. But be assured, that it can compute it on my laptop in about 12 seconds. The program (accidentally) also accepts `2` for double moves. ### Full Explanation: **Parse scramble:** First I'll deal with the prime marks `'` in the input strings. I simply replace these with `3` and run-length decode this string. Since Pyth's decoding format requires the number in front of the char, I reverse the string beforehand. `_r_Xz\'\39`. So afterwards I reverse it back. **Describe the solved cube state:** `=Z"UDLRFB` assigns the string with all 6 moves to `Z`. We can describe a cube state by describing the location for each cube piece. For instance we can say that the edge, that should be at UL (Up-Left) is currently at FR (Front-Right). For this I need to generate all pieces of the solved cube: `f!s}RTcZ2yZ`. `yZ` generates all possible subsets of `"UDLRFB"`. This obviously also generates the subset `"UDLRFB"` and the subset `"UD"`. The first one doesn't make any sense, since there is no piece that is visible from all 6 sides, and the second one doesn't make any sense, since there is no edge piece, that is visible from the top and the bottom. Therefore I remove all the subsets, that contain the subsequence `"UD"`, `"LR"` or `"FB"`. This gives me the following 27 pieces: ``` '', 'U', 'D', 'L', 'R', 'F', 'B', 'UL', 'UR', 'UF', 'UB', 'DL', 'DR', 'DF', 'DB', 'LF', 'LB', 'RF', 'RB', 'ULF', 'ULB', 'URF', 'URB', 'DLF', 'DLB', 'DRF', 'DRB' ``` This also includes the empty string and all the six 1-letter strings. We could interpret them as the piece in the middle of the cube and the 6 center pieces. Obviously they are not required (since they don't move), but I'll keep them. **Doing some moves:** I'll do some string translations to perform a move. To visualize the idea look at the corner piece in `URF`. What happens to it, when I do an `R` move? The sticker on the `U` face moves to the `B` face, the sticker `F` moves to the `U` face and the sticker on the `R` face stays at the `R` face. We can say, that the piece at `URF` moves to the position `BRU`. This pattern is true for all the pieces on the right side. Every sticker that is on the `F` face moves to the `U` face when an `R` move is performed, every sticker that is on the `U` face moves to the `B` face, every sticker on the `B` moves to `D` and every sticker on `D` moves to `F`. We can decode the changes of an `R` move as `FUBD`. The following code generates all the 6 necessary codes: ``` _sm_B.iFP.>c3Zk3 ['BRFL', 'LFRB', 'DBUF', 'FUBD', 'RDLU', 'ULDR'] ^ ^ ^ ^ ^ ^ U move D move L move R move F move B move ``` And we perform a move `H` to the cube state `G` as followed: ``` m.rW}[[email protected]](/cdn-cgi/l/email-protection) m G map each piece d in G to: .rW d perform a rotated translation to d, but only if: }Hd H appears in d (d is currently on the face H) xZH get the index of H in Z @... and choose the code in the list of 6 (see above) ``` **Count the number of repeats:** The rest is pretty much trivial. I simply perform the input scramble to the solved cube over and over until I reach a position that I previously visited. ``` l.uu<apply move H to G><parsed scramble>N<solved state> u...N performs all moves of the scramble to the state N .u... do this until cycle detected, this returns all intermediate states l print the length ``` [Answer] # GAP, ~~792 783 782~~ ~~749~~ 650 Bytes This seems to be working. If it messes up with something let me know. Thanks to @Lynn for suggesting that I decompose some of the primitive moves. Thanks to @Neil for suggesting that instead of `Inverse(X)` I use `X^3`. Usage example: `f("R");` ``` R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17);L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31);U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38);A:=R*L^3*F*F*B*B*R*L^3;D:=A*U*A;;F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45);B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12);d:=NewDictionary((),true);AddDictionary(d,'R',R);AddDictionary(d,'L',L);AddDictionary(d,'U',U);AddDictionary(d,'D',D);AddDictionary(d,'F',F);AddDictionary(d,'B',B);f:=function(s) local i,p,b,t;p:=(); for c in s do if c='\'' then t:=t^2;else t:=LookupDictionary(d,c);fi;p:=p*t;od;return Order(p);end; ``` Here is the ungolfed code with a bit of explanation ``` # Here we define the primitive moves R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17); L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31); U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38); #D:=(7,34,21,16)(8,35,20,17)(9,36,19,18)(48,46,52,54)(47,49,53,51); F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45); B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12); # Here we define D in terms of other primitive moves, saving on bytes # Thanks @Lynn # This is actually doable with a maximum of 3 of the primitive moves # if a short enough sequence can be found. D:=U^(R*L^3*F*F*B*B*R*L^3); # create dictionary and add moves to it with appropriate char labels d:=NewDictionary((),true); AddDictionary(d,'R',R); AddDictionary(d,'L',L); AddDictionary(d,'U',U); AddDictionary(d,'D',D); AddDictionary(d,'F',F); AddDictionary(d,'B',B); f:=function(s) local c,p,t; # p will become the actual permutation passed to the function p:=(); for c in s do if c='\'' then # The last generator we mutiplied (that we still have in t) # should have been its inverse. Compensate by preparing to # multiply it two more times to get t^3=t^-1. Thanks @Neil. t:=t^2; else t:=LookupDictionary(d,c); fi; p:=p*t; od; return Order(p); end; ``` [Answer] # Mathematica, ~~413~~ 401 bytes ``` Evaluate[f/@Characters@"RFLBUD"]=LetterNumber@"ABFEJNRMDAEHIMQPCDHGLPTOBCGFKOSNADCBILKJEFGHQRST"~ArrayReshape~{6,2,4}; r[c_,l_]:=(b=Permute[c,Cycles@f@l];MapThread[(b[[#,2]]=Mod[b[[#,2]]+{"F","B","L","R"}~Count~l{-1,1,-1,1},#2])&,{f@l,{3,2}}];b); p@s_:=Length[c={#,0}&~Array~20;NestWhileList[Fold[r,#,Join@@StringCases[s,x_~~t:""|"'":>Table[x,3-2Boole[t==""]]]]&,c,(Length@{##}<2||c!=Last@{##})&,All]]-1 ``` --- **Explanations** A Rubik's Cube is made up with 20 movable **cubies** (8 corners, 12 edges). Each cubie can be given a number: *corners*: ``` N starting position 1 UFR 2 UBR 3 UBL 4 UFL 5 DFR 6 DBR 7 DBL 8 DFL ``` *edges*: ``` N starting position 9 UF 10 UR 11 UB 12 UL 13 FR 14 BR 15 BL 16 FL 17 DF 18 DR 19 DB 20 DL ``` Note that when the cube is twisted, the cubies are generally not on their starting positions any longer. For example, when `R` is done, the cubie `1` moves from `UFR` to a new position `UBR`. In such notation, a 90 degree turn can be described by 8 movements of cubies. For example, `R` is described by ``` from to UFR UBR UBR DBR DBR DFR DFR UFR UR BR BR DR DR FR FR UR ``` Since each cubie has a unique starting position, each position has a unique starting cubie. That is to say, rule `UFR->UBR` is just `1->2` (means that `R` takes the cubie on the starting position of cubie `1` to the starting position of cubie `2`). Thus, `R` can be simplified further to a cycle ``` Cycles[{{1,2,6,5}, {10,14,18,13}}] ``` --- To fully solve a Rubik's Cube, we also need to align the cubies to their corresponding starting orientations. The faces of a cube is painted in different colors, the scheme that I often use when solving cubes is ``` face color U yellow D white F red B orange R green L blue ``` When we analyzing the orientations of corners, colors other than yellow or white are ignored, and yellow and white are considered as the same color. Suppose cubie `1` is on its starting position `UFR`, the yellow facet may be aligned to three different faces. We use an integer to represent these cases, ``` 0 yellow on U (correct) 1 yellow on R (120 degree clockwise) 2 yellow on F (120 degree counterclockwise) ``` Suppose cubie `1` is on `DFL`, its three possible orientations are ``` 0 yellow on D (correct) 1 yellow on L (120 degree clockwise) 2 yellow on F (120 degree counterclockwise) ``` When we analyzing the orientations of edges, red and orange are ignored, and yellow and white are ignored only if the edge has a green or blue facet. Suppose cubie `10` is on its starting position `UR`, the green facet may be aligned to two different faces. Its two possible orientations are ``` 0 green on R (correct) 1 green on U (180 degree) ``` Suppose cubie `10` is on `DF`, its two possible orientations are ``` 0 green on D (correct) 1 green on F (180 degree) ``` --- An array is used to store the state of a cube. The starting state of a cube is ``` {{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0},{9,0},{10,0},{11,0},{12,0},{13,0},{14,0},{15,0},{16,0},{17,0},{18,0},{19,0},{20,0}} ``` which means that every cubies are on their starting position with correct orientation. After `R`, the state of the cube becomes ``` {{5,2},{1,1},{3,0},{4,0},{6,1},{2,2},{7,0},{8,0},{9,0},{13,1},{11,0},{12,0},{18,1},{10,1},{15,0},{16,0},{17,0},{14,1},{19,0},{20,0}} ``` which means that cubie `5` is now on position `1` (`UFR`) with orientation `2`, cubie `1` is now on position `2` (`UBR`) with orientation `1`, cubie `3` is now still on position `3` (`UBL`) with orientation `0`, and so on. --- **Test cases** ``` p["FF'"] (* 1 *) p["R"] (* 4 *) p["RUR'U'"] (* 6 *) p["LLUUFFUURRUU"] (* 12 *) p["LUFFRDRBF"] (* 56 *) p["LF"] (* 105 *) p["UFFR'DBBRL'"] (* 120 *) p["FRBL"] (* 315 *) ``` [Answer] # Haskell, 252 bytes ``` r=[-2..2] s=mapM id[r,r,r] t m p@[x,y,z]=case m of"R"|x>0->[x,z,-y];"L"|x<0->[x,-z,y];"U"|y>0->[-z,y,x];"D"|y<0->[z,y,-x];"F"|z>0->[y,-x,z];"B"|z<0->[-y,x,z];c:"'"->t[c]$t[c]$t[c]p;_->p f m=length$s:fst(span(/=s)$tail$iterate(flip(foldl$flip$map.t)m)s) ``` Sample runs: ``` *Main> f ["F","F'"] 1 *Main> f ["R"] 4 *Main> f ["R","U","R'","U'"] 6 *Main> f ["L","L","U","U","F","F","U","U","R","R","U","U"] 12 *Main> f ["L","U","F","F","R","D","R","B","F"] 56 *Main> f ["L","F"] 105 *Main> f ["U","F","F","R'","D","B","B","R","L'"] 120 *Main> f ["F","R","B","L"] 315 *Main> f ["R","U","U","D'","B","D'"] -- maximum possible order 1260 ``` The key observation here is that it’s simpler to model the Rubik’s cube as a 5×5×5 grid of points rather than a 3×3×3 grid of oriented cubies. Corner cubies become cubes of 2×2×2 points, edge cubies become squares of 2×2×1 points, and moves rotate slices of 5×5×2 points. [Answer] # Ruby, 225 bytes ``` ->s{n=0 a=[] b=[] 64.times{|i|a<<j=[(i&48)-16,(i&12)-4,i%4-1];b<<j*1} d=1 (n+=1 s.reverse.chars{|c|m="UFRDBL".index(c) m ?(e=m/3*2-1 b.each{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)} d=1):d=-1})until n>0&&a==b n} ``` Similar to Anders Kaseorg's answer and inspired by Jan Dvorak's [answer](https://codegolf.stackexchange.com/a/44775/15599) to a previous question. However unlike those answers, I don't need 125 cubies. I use a rubik's cube of 27 cubies, but rectangular dimensions. In the solved state the corners are at `+/-1,+/-4,+/-16`. I generate an array of 64 cubies, each with a centre chosen from `x=[-1,0,1,2], y=[-4,0,4,8], z=[-16-0,16,32]`. The cubies with coordinates of 2, 8 and 32 are unnecessary, but they do no harm, so they are left in for golfing reasons. The fact that the length, width and depth of the cubies are different: (1,4,16) means it is easy to detect if they are in the right place but with wrong orientation. Each cubie is tracked as it is moved by the faceturns. If the coordinate of a cubie in the axis corresponding to the face (multiplied by `e=-1` for U,F,R or `e=1` for D,B,L) is positive, then it will be rotated by swapping the coordinates in the other 2 axis and applying an appropriate sign change to one of the coordinates. This is controlled by multiplying by `e*d`. The input sequence is scanned in reverse order. This makes no difference, so long as the "normal" rotations are performed anticlockwise instead of clockwise. The reason for this is so that if a `'` symbol is found, the value of `d` can be changed from 1 to -1 in order to cause rotation of the following face in the opposite direction. **Ungolfed in test program** ``` f=->s{n=0 #number of repeats=0 a=[] #empty array for solved position b=[] #empty array for current position 64.times{|i| a<<j=[(i&48)-16,(i&12)-4,i%4-1] #generate 64 cubies and append them to the solved array b<<j*1 #duplicate them and append to active array } d=1 #default rotation direction anticlockwise (we scan the moves in reverse) ( #start of UNTIL loop n+=1 #increment repeat counter s.reverse.chars{|c| #reverse list of moves and iterate through it m="UFRDBL".index(c) #assign move letter to m (for ' or any other symbol m is false) m ? #if a letter (e=m/3*2-1 #e=-1 for UFR, 1 for DBL b.each{|j| #for each cubie j[m%=3]*e>0&& #m%=3 picks an axis. If the cubie is on the moving face of the cube (j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)#rotate it: exchange the coordinates in the other 2 axes and invert the sign of one of them according to direction } #as per the values of e and d. d=1 #set d=1 (in case it was -1 at the start of the b.each loop) ): d=-1 #ELSE the input must be a ', so set d=-1 to reverse rotation of next letter } )until n>0&&a==b #end of UNTIL loop. continue until back at start position a==b n} #return n p f["FF'"] # 1 p f["R"] # 4 p f["RUR'U'"] # 6 p f["LLUUFFUURRUU"] # 12 p f["LUFFRDRBF"] # 56 p f["LF"] # 105 p f["UFFR'DBBRL'"] # 120 p f["FRBL"] # 315 ``` [Answer] # Python 2, 343 bytes ``` def M(o,v,e): k=1 for m in e: for c in'ouf|/[bPcU`Dkqbx-Y:(+=P4cyrh=I;-(:R6'[m::6]:i=~ord(c)%8*k;j=(ord(c)/8-4)*k;o[i],o[j]=o[j]-m/2,o[i]+m/2;v[i],v[j]=v[j],v[i];k=-k V=range(20) o,v,e=[0]*20,V[:],[] for c in raw_input():i='FBRLUD'.find(c);e+=i<0and e[-1:]*2or[i] M(o,v,e);n=1 while any(o[i]%(2+i/12)for i in V)or v>V:M(o,v,e);n+=1 print n ``` Input is taken from stdin. The given sequence of twists is performed repeatedly on a virtual cube until it returns to the solved state. The cube state is stored as an orientation vector and permutation vector, both of length 20. Orientations are somewhat arbitrarily defined: an edge cubie is oriented correctly if it can be moved into place without invoking an R or L quarter turn. The orientation of the corner cubies is considered relative to the F and B faces. --- **Sample Usage** ``` $ echo FRBL|python rubiks-cycle.py 315 $ echo RULURFLF|python rubiks-cycle.py 1260 ``` [Online Demonstration](http://rextester.com/YEVV53248) and [Test Suite](http://rextester.com/YUDCN56828). [Answer] # [Cubically](//git.io/Cubically), ~~9~~ 6 bytes ``` ¶-7)8% ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P//0DZdc00L1f//gwA) (Nonworking until Dennis updates the TIO Cubically interpreter) Explanation: ``` ¶-7)8% ¶ read a string, insert into code -7 add 1 to notepad (subtracts the 7th face "sum" from notepad, defaulted to -1) )8 jump back to start of code if cube unsolved % print notepad ``` This language will dominate all [rubiks-cube](/questions/tagged/rubiks-cube "show questions tagged 'rubiks-cube'") challenges >:D [Answer] ## Clojure, 359 bytes This might be my 2nd longest codegolf. Realizing I could drop trailing zeros from vectors `A` to `F` made me very happy :D ``` #(let[I(clojure.string/replace % #"(.)'""$1$1$1")D(range -2 3)S(for[x D y D z D][x y z])A[0 1]B[0 0 1]C[1]D[-1]E[0 -1]F[0 0 -1]](loop[P S[[n R]& Q](cycle(map{\F[A[B A D]]\B[E[F A C]]\L[D[C B E]]\R[C[C F A]]\U[B[E C B]]\D[F[A D B]]}I))c 0](if(=(> c 0)(= P S))(/ c(count I))(recur(for[p P](if(>(apply +(map * n p))0)(for[r R](apply +(map * r p)))p))Q(inc c))))) ``` Less golfed: ``` (def f #(let [I (clojure.string/replace % #"(.)'""$1$1$1") D [-2 -1 0 1 2] S (for[x D y D z D][x y z]) L {\F [[ 0 1 0][[0 0 1][ 0 1 0][-1 0 0]]] \B [[ 0 -1 0][[0 0 -1][ 0 1 0][ 1 0 0]]] \L [[-1 0 0][[1 0 0][ 0 0 1][ 0 -1 0]]] \R [[ 1 0 0][[1 0 0][ 0 0 -1][ 0 1 0]]] \U [[ 0 0 1][[0 -1 0][ 1 0 0][ 0 0 1]]] \D [[ 0 0 -1][[0 1 0][-1 0 0][ 0 0 1]]]}] (loop [P S c 0 [[n R] & Q] (cycle(map L I))] (if (and (> c 0) (= P S)) (/ c (count I)) (recur (for[p P](if(pos?(apply +(map * n p))) (for[r R](apply +(map * r p))) p)) (inc c) Q))))) ``` This simply implements 3D rotations of selected subsets of `5 x 5 x 5` cube. Originally I was going to use `3 x 3 x 3` and it took me a while to realize why I wasn't getting correct results. Good test cases! Some extra bytes for fist encoding `"RUR'U'"` as `"RURRRUUU"`. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 255 bytes Derived separately from the almost-identical Haskell answer as an answer to [this question](https://codegolf.stackexchange.com/questions/178276/order-of-elements-of-the-rubiks-cube) which was closed as a duplicate when it was almost finished, so I posted the answer here. ``` import StdEnv,StdLib a=[-2..2];b=diag3 a a a ?m=iter(size m*2-1)\p=:(x,y,z)=case m.[0]of'F'|z>0=(y,~x,z);'U'|y>0=(~z,y,x);'R'|x>0=(x,z,~y);'B'|z<0=(~y,x,z);'D'|y<0=(z,y,~x);'L'|x<0=(x,~z,y);_=p $l=length(takeWhile((<>)b)(tl(iterate(map(sseq(map?l)))b)))+1 ``` [Try it online!](https://tio.run/##LZBda4MwFIbv@yukFJJsUaxjN7NpobjBoFctZRddGammNSxRV7OhIv70ZSd2hHw973lCklQJXlhdZt9KeJrLwkpdlVfj7Uz2XPxQmDbyNOHs4EdBEB3jE8skvzx43LXJSjNpxBXXsgP9LvLn5L1iT7ihLe0IS3kNODiEx/KMXlDfLUOGWzo0EMZoj/rWgaGD6gbAFvWNAxDToQWwBmXhKiAflQQUB5wxOGUDymJU3Ckk/mDVZKaYEsXF5NjwT/GWSyUwXizJiWCjsLsvNwJrXuG6Fl9usVKEQEzI/dzuDIfnM2/mHabbKZ3u/3uCYFjfFkf7m54Vv9TWf93YpC24lilscvsYhnqEt4/7Aw "Clean – Try It Online") ]
[Question] [ I'm supposed to sort a list of numbers, but I'm super lazy. It's really hard to figure how to swap all the numbers around until all of them are in increasing order, so I came up with my own algorithm that will guarantee that the new list is sorted¹. Here's how it works: For a list of size **N**, we'll need *N-1* iterations. On each iteration, * Check if the N'th number is smaller than the *N+1'th* number. If it is, then these two numbers are already sorted, and we can skip this iteration. * If they are not, then you need to continually decrement the first *N* numbers until these two numbers are in order. Let's take a concrete example. Let's say the input was ``` 10 5 7 6 1 ``` On the first iteration, we'll compare 10 and 5. 10 is larger than 5, so we decrement it until it's smaller: ``` 4 5 7 6 1 ``` Now we compare 5 and 7. 5 is smaller than 7, so we don't need to do anything on this iteration. So we go to the next and compare 7 and 6. 7 is larger than 6, so we decrement the first three numbers until it's smaller than 6, and we get this: ``` 2 3 5 6 1 ``` Now we compare 6 and 1. Again, 6 is larger than 1, so we decrement the first four numbers until it's smaller than 1, and we get this: ``` -4 -3 -1 0 1 ``` And we're done! Now our list is in perfect sorted order. And, to make things even better, we only had to iterate through the list **N-1** times, so this algorithm sorts lists in **O(N-1)** time, which I'm pretty sure is the fastest algorithm there is.² Your challenge for today is to implement this Lazy Sort. Your program or function will be given an array of integers in whatever standard format you like, and you must perform this lazy sort and return the new *"sorted"* list. The array will never be empty or contain non-integers. Here are some examples: ``` Input: 10 5 7 6 1 Output: -4 -3 -1 0 1 Input: 3 2 1 Output: -1 0 1 Input: 1 2 3 Output: 1 2 3 Input: 19 Output: 19 Input: 1 1 1 1 1 1 1 1 1 Output: -7 -6 -5 -4 -3 -2 -1 0 1 Input: 5 7 11 6 16 2 9 16 6 16 Output: -27 -25 -21 -20 -10 -9 -2 5 6 16 Input: -8 17 9 7 Output: -20 5 6 7 ``` As always, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so write the shortest program you can! --- ¹ *This doesn't mean what it sounds like it means, but it is technically true* ² *I am completely kidding, please don't hate me* [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` f(a:r)|h:t<-f r=h-max(r!!0-a)1:h:t f x=x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0apIsybDqsRGN02hyDZDNzexQqNIUdFAN1HT0AoozpWmUGFb8T83MTNPwVahoCgzr0RBRSFNIYcrxzba0EDHVMdcx0zHMPY/AA "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14 12 11~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to ETHproductions (use the minimum dyad, `«`) ``` I’«0Ṛ+\Ṛ+ ``` A monadic link taking and returning lists of integers. **[Try it online!](https://tio.run/##y0rNyan8/9/zUcPMQ6sNHu6cpR0DIv7//2@qY65jaKhjpmNopmOkYwmiQGwA "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8/9/zUcPMQ6sNHu6cpR0DIv4f3XO4/VHTmiwgBqHGfToKkWB@475D2w5t@/8/OtrQQMdUx1zHTMcwVifaWMcITBsCaWMQbQnmoEGgGEiLoSFIlxlQqSWIArGBMroWOobmQBHz2FgA "Jelly - Try It Online"). I really don't think this is Lazy™ enough! ### How? ``` I’«0Ṛ+\Ṛ+ - Link: list of integers, a e.g. [ 8, 3, 3, 4, 6, 2] I - increments between consecutive items of a [-5, 0, 1, 2,-4 ] ’ - decrement (vectorises) [-6,-1, 0, 1,-5 ] 0 - literal 0 « - minimum of decremented increments and zero [-6,-1, 0, 0,-5 ] Ṛ - reverse [-5, 0, 0,-1,-6 ] \ - cumulative reduce with: + - addition [-5,-5,-5,-6,-12] Ṛ - reverse [-12,-6,-5,-5,-5] + - addition (with a) [-4,-3,-2,-1, 1, 2] ``` [Answer] ## JavaScript (ES6), 61 bytes ``` a=>a.map((b,i)=>a=(b-=a[i+1])>0?a.map(c=>i--<0?c:c-b-1):a)&&a ``` ### Test cases ``` let f = a=>a.map((b,i)=>a=(b-=a[i+1])>0?a.map(c=>i--<0?c:c-b-1):a)&&a console.log(JSON.stringify(f([10, 5, 7, 6, 1]))) // -4 -3 -1 0 1 console.log(JSON.stringify(f([3, 2, 1]))) // -1 0 1 console.log(JSON.stringify(f([1, 2, 3]))) // 1 2 3 console.log(JSON.stringify(f([19]))) // 19 console.log(JSON.stringify(f([1, 1, 1, 1, 1, 1, 1, 1, 1]))) // -7 -6 -5 -4 -3 -2 -1 0 1 console.log(JSON.stringify(f([5, 7, 11, 6, 16, 2, 9, 16, 6, 16]))) // 27 -25 -21 -20 -10 -9 -2 5 6 16 console.log(JSON.stringify(f([-8, 17, 9, 7]))) // -20 5 6 7 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` I»1U 0ị;Ç_\U ``` [Try it online!](https://tio.run/##y0rNyan8/9/z0G7DUC6Dh7u7rQ@3x8eE/v//P9rQQEfBVEfBXEfBTEfBMBYA "Jelly – Try It Online") ### How it works ``` I»1U Helper link. Argument: l (list of integers) I Compute the increments (difference between items) of l. »1 For each item n, take the maximum of n and 1. U Reverse. 0ị;Ç_\U Main link. Argument: l (list of integers) Ç Call the helper link with argument l. ; Concatenate this with 0ị the 0th last item of the (1-indexed) l. (Can't use Ṫ because it modifies l) _\ Cumulatively reduce the result by subtraction. U Reverse. ``` The basic idea at play is this: If you reverse the input and output arrays, the output is simply the input with each delta of 0 or greater replaced with -1. For example: ``` [10, 5, 7, 6, 1] input [ 1, 6, 7, 5, 10] reverse [ 5, 1, -2, 5 ] deltas [ -1, -1, -2, -1 ] min(deltas, -1) [ 1, -1, -2, -1, -1] reverse and concat the last item of the original [ 1, 0, -2, -3, -4] re-apply deltas [-4, -3, -2, 0, 1] reverse ``` [Answer] # k, 20 bytes ``` {x-|+\0,1_0|1+-':|x} ``` [Try it online.](http://johnearnest.github.io/ok/?run=%7Bx-%7C%2B%5C0%2C1_0%7C1%2B-%27%3A%7Cx%7D%27%2810%205%207%206%201%3B3%202%201%3B1%202%203%3B%2C19%3B1%201%201%201%201%201%201%201%201%3B5%207%2011%206%2016%202%209%2016%206%2016%3B-8%2017%209%207%29) Explanation: ``` { } /function, x is input |x /reverse x -': /difference between every element 1+ /add one to each difference 0| /make minimum difference be 0 0,1_ /swap first difference with a 0 +\ /cumulative sum | /reverse again x- /subtract from x ``` [Answer] ## Haskell, 56 bytes ``` a#(x:y:z)=map(+min(y-x-1)0)(a++[x])#(y:z) a#x=a++x ([]#) ``` [Try it online!](https://tio.run/##ZYpBDsIgEADvvGITPCxhScpBsU14CeGwiTYSCzbVA/XzqFfM3Gbmxs/7dVlaY4l12qe38plX1DkV3E01Vg0KWetQo5L464Jl9V9TxewxRKla5lTAw@UhAGDdUnnBAWYIdqAjOTqRjX0Z/wx1ROgOcybraCQX2wc "Haskell – Try It Online") Keep the first part of the list in parameter `a`. At each step add the next element `x` to the end of `a` and increase all elements of a by the minimum of `(y-x-1)` and `0`. [Answer] # [Python](https://docs.python.org/2/), 54 bytes ``` f=lambda a,*r:r and[f(*r)[0]-max(r[0]-a,1)]+f(*r)or[a] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVFHq8iqSCExLyU6TUOrSDPaIFY3N7FCowjESNQx1IzVBovnF0Unxv7PsY02NNAx1THXMdMxjOUqKMrMK1EAyudoQtnpGjma/wE "Python 2 – Try It Online") Takes input splatted like `f(1,2,3)`. Outputs a list. Uses exponential time. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 153 bytes ``` {(({})<>[({})])(({}({}))[({}[{}])])<>(([{}]({})))([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}({}<>{}())((<>))}{}{}}{}<>{}([]){{}({}<>)<>([])}<> ``` [Try it online!](https://tio.run/##NY0xDsNQCEP3nMQeMrRdERf5@kM6VKpadciKODvFX8pkPzDmeR7v3/76Hp@qACJpPiSTIjmKR@TsmTkgu@aENgaQzglzMnTDjmVk11mkiyKbJbEq5TqFdaLktcaYvCL61diu6rHdt1vt5x8 "Brain-Flak – Try It Online") This includes `+1` for the `-r` flag. ``` #While True { #Push the last value left in the array minus the counter onto the alternate stack (({})<>[({})]) #Put the counter back on top of the alternate stack (({}({}))[({}[{}])]) #Toggle <> #Find the difference between the last two inputs left on the array (([{}]({}))) #Greater than or equal to 0? ([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} #If So: { #Pop the truthy/falsy value {} #Increment the counter by the difference between elements +1 ({}<>{}()) #Push two falsys ((<>)) #Endwhile } #Pop the two falsys {}{} #Endwhile } #Pop the falsy {} #Toggle back <> #Pop the counter #Reverse the stack {} ([]){{}({}<>)<>([])}<> ``` [Answer] ## C#, 76 bytes ``` a=>{for(int d=0,i=a.Length-1;i>0;a[--i]-=d)d=a[i-1]-d<a[i]?d:a[i-1]-a[i]+1;} ``` This modifies the list in place. It goes through the list backwards and keep a running total of the delta to apply to each number. [Answer] ## JavaScript (ES6), 59 bytes ``` f=([n,...a],p=a[0]-n)=>a+a?[(a=f(a))[0]-(p>1?p:1),...a]:[n] ``` [Answer] # R, 56 bytes `function(s){s-c(rev(cumsum(rev(pmax(0,-diff(s)+1)))),0)}` [Answer] # JavaScript (ES6), 68 bytes ``` a=>a.map((v,i)=>(d=v-o[i+1]+1)>1?o=o.map((v,j)=>j>i?v:v-d):0,o=a)&&o ``` Input and output is an array of integers. ## Test Snippet ``` f= a=>a.map((v,i)=>(d=v-o[i+1]+1)>1?o=o.map((v,j)=>j>i?v:v-d):0,o=a)&&o ``` ``` <input id=I oninput="O.value=f(this.value.split` `.map(x=>+x)).join` `"> <input id=O disabled> ``` [Answer] # JavaScript (ES6), 50 bytes ``` f=a=>(b=[...a]).some((_,i)=>a[i]-->=a[i+1])?f(a):b ``` **Explanation:** This is a recursive solution, which first clones the array, then decreases all values up until an element is greater or equal to the next element in the array. The function calls itself as long as any elements are out of order. When the elements are finally sorted, the clone is returned. (We can't return the array itself, because the `some()` method would have decremented all its elements, making them all off by -1.) **Test cases:** ``` f=a=>(b=[...a]).some((_,i)=>a[i]-->=a[i+1])?f(a):b console.log(f([10,5,7,6,1])+''); console.log(f([1,1,1,1,1,1,1,1,1])+''); console.log(f([5,7,11,6,16,2,9,16,6,16])+''); console.log(f([19])+''); console.log(f([-8,17,9,7])+''); console.log(f([1,2,3,4,5,6,7])+''); ``` [Answer] ## SWI-Prolog, 194 bytes ``` :-use_module(library(clpfd)). f([],[],_,_). f([A|B],[M|N],P,D):-A#=M-D-E,A#<P,abs(M,S),T#=S+1,E in 0..T,label([E]),f(B,N,A,D+E). l([],[]). l(A,B):-reverse(Z,B),f([X|Y],Z,X+1,0),reverse(A,[X|Y]). ``` Might be able to try it online here: <http://swish.swi-prolog.org/p/LazySort.pl> You ask `l(L, [10,5,7,6,1]).` which says "solve for L, where L is the lazy sorted version of this list". The two functions are: * `l`azysorted(A,B) - states that A is the lazysorted version of B, if they're both empty lists, or if A can be obtained by reversing B, calling a helper function to walk the list and do a subtraction with an accumulator pushing each value lower than the previous one, and reversing the result of that back to the right way around. * `f` helper matches two lists, the value of the previous number in the list, and a rolling difference accumulator, and solves for the new value of the current list position being the original value minus the difference accumulator, optionally minus a new value required to force this value below the previous number in the list, and `f` must solve for the tail of the list recursively with the now increased difference accumulator. Screenshot of the test cases on Swish: [![image showing the test cases running on Swish](https://i.stack.imgur.com/QoPU2.png)](https://i.stack.imgur.com/QoPU2.png) [Answer] ## JavaScript (ES6), 61 bytes ``` a=>a.reduceRight((r,e)=>[e-(d=(c=e-r[0]+1)>d?c:d),...r],d=[]) ``` Not the shortest solution but I couldn't pass over the opportunity to use `reduceRight`. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 89 88 86 79 bytes * Saved just 1 byte with a slightly different approach. * Saved another 2 bytes with a simplification of the `for`s. * Saved 7 bytes thanks to the amazing golfing skills of VisualMelon. ``` a=>{for(int i=0,j,k;++i<a.Length;)for(k=a[i-1]-a[j=i]+1;--j>=0;)a[j]-=k>0?k:0;} ``` [Try it online!](https://tio.run/##tY/BSsQwEIbvfYrBU0uT0ggqmk0X8SYrCB48lB5CTbvT7iaQBEVKn72mrSi7ePVnEib/ZPhmakdrY9UEQfVBOgfP1rRWHqPZGZZ7lvPSYw3vBt/gSaKOk5/S76dZL5/Oq2N2X3s0eoPal1UBDYhokqIYGmPj4AGKnHSk52mKG5ntlG79nidztReyRMoqKstOYJUyTmlXiJwnwaio6It829/lfJx4dAJeUOBBgFYf368BWE7gisANgWsCDEZ@0tPEPuF/jf9gtDMHlb1a9GqHWsXOW9Rt9mjC7hcEQvjkrPecvXIZW9nhXBK4XbPF@L9pxiUbpy8 "C# (.NET Core) – Try It Online") First `for` iterates through the array, then it calculates the decrement and finally the second `for` decrements the elements if necessary until the `i`th position. Is it valid to just modify the original array instead of returning a new one (still getting used to the rules)? ]
[Question] [ As a little kid, I liked to play with these toys a lot: [![enter image description here](https://i.stack.imgur.com/xRBjI.jpg)](https://i.stack.imgur.com/xRBjI.jpg) They probably intended for these to be used for art, but I always used them for math! Fractals, patterns, etc. One time, I was given this challenge: > > Build a triangle without using any of the green triangle tiles. > > > This challenge stumped me for the longest time, until I stumbled upon a really beautiful and simple way to do it with just 3 trapezoids: ``` /\ /_/\ /__\_\ ``` Now, take this triangle, and rotate it: ``` ______ \ \__/ \/ / \/ ``` Using these two triangles, we can construct larger triangles out of them. Here is a triangle of height 2: ``` /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ ``` And here are triangles of height 3-7: ``` #3 /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ /\ \__/\ \__/\ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\ #4 /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ /\ \__/\ \__/\ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\ #5 /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ /\ \__/\ \__/\ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\/__\_\ #6 /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ /\ \__/\ \__/\ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\/__\_\/__\_\ #7 /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ /\ \__/\ \__/\ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\/__\_\/__\_\ /\ \__/\ \__/\ \__/\ \__/\ \__/\ \__/\ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\ ``` # The Challenge Write a program or function that takes a number *n* and prints a triangle-less triangle of height *n*. Trailing spaces on each line is acceptable, and up to one trailing or leading newline is also acceptable. IO can be in any reasonable format. The input is guarenteed to be a positive integer, so you don't have to worry about negative numbers, decimals, non-numbers etc. Shortest answer in bytes wins! [Answer] # Ruby, 79 ``` ->n{1.upto(n*=3){|i|puts (' '*(n-i)).ljust(n+i,'/__\_\/\ \__/_/\/ '[i%3*6,6])}} ``` A. (-4 bytes, `-1` `+1`) changed from 0-indexed (`.times`) to 1-indexed (`1.upto`) B. (-5 bytes) changed from array of three 6-char strings to selection of 6-char substring of 18-char string. C. (-1 byte) `m=n*3` -> `n*=3` D. (-5 bytes) reduced all five double backslashes to single backslashes (partly made possible by reordering of string required for point A) # Ruby, 94 ``` ->n{(m=n*3).times{|i|puts (' '*(m-i-1)).ljust(m+i+1,[ '/\\ \\__','/_/\\/ ','/__\\_\\'][i%3])}} ``` **explanation** The basic unit is a 3x6 diamond as follows (last character on each row duplicated for clarity:) ``` /\ \__/ /_/\/ / /__\_\/ ``` All we need to do is display a suitable window of this pattern. Ruby's `ljust` allows you to pad with any string, not just spaces. Normally `ljust` would be used to pad a string of printable characters by adding spaces at the end, but here we use it in reverse: to pad a string of spaces by adding printable characters at the end. **ungolfed in test program** ``` f=->n{ (m=n*3).times{|i| #for each line of the triangle puts (' '*(m-i-1)). #print m-i-1 spaces, ljust(m+i+1,[ '/\\ \\__', #left justified and padded to total length m+i+1 '/_/\\/ ', #by one of these three strings '/__\\_\\'][i%3]) } } f[gets.to_i] ``` [Answer] # CJam, 47 ``` ri_"/__\_\/_/\/ /\ \__"6/f**eeW%{_S.*s\~,\-<N}/ ``` **Explanation:** ``` ri_ read the input, convert to integer and duplicate "…" push that string, containing the repeating pattern (3 lines in reverse order, concatenated) 6/ split into (3) lines of 6 characters f* multiply (repeat) each line n times * repeat the array of 3 lines n times at this point we have an array of 3*n strings with 6*n characters each ee enumerate the array (obtaining an array of [index string] pairs) W% reverse the array (so the lines are in correct order and indices in reverse order) {…}/ for each [index string] pair _ duplicate the pair S.* vectorized-multiply with " " this effectively replaces the index with a string of <index> spaces s convert the pair to string, effectively concatenating the spaces with the string \ swap with the other copy of the [index string] pair ~, dump the index and string on the stack and get the string length \- subtract the index from it - this is the desired line length < cut the concatenated string to that length N add a newline ``` [Try it online](http://cjam.aditsu.net/#code=ri_%22%2F__%5C_%5C%2F_%2F%5C%2F%20%2F%5C%20%5C__%226%2Ff**eeW%25%7B_S.*s%5C%7E%2C%5C-%3CN%7D%2F&input=4) [Answer] # [Retina](https://github.com/mbuettner/retina), ~~150~~ ~~122~~ 118 bytes The output to this challenge looks awesome, by the way! Input is in unary. The output contains a trailing linefeed. The code uses ISO 8859-1 encoding. Note the trailing space on the penultimate line. ``` (?=_\\¶.*1) _\/__\ (?=/_/\\¶.*1) /_/\/ (^|__)(?=/\\¶.*1) $1/\ \__ ms}`(.*1*)1 /\¶/_/\¶/__\_\¶$1 m`^(?=(.*¶)*.) $#1$* ``` [**Try it online**](http://retina.tryitonline.net/#code=KD89X1xcwrYuKjEkKQpfXC9fX1wKKD89L18vXFzCti4qMSQpCi9fL1wvIAooXnxfXykoPz0vXFzCti4qMSQpCiQxL1wgXF9fCm1zfWAoLioxKikxJAovXMK2L18vXMK2L19fXF9cwrYkMQptYF4oPz0oLirCtikqLikKJCMxJCog&input=MTExMQ) ### Explanation If you want a more in-depth explanation, comment or message me in chat. ``` (?=_\\¶.*1) # Matches the start of the 3rd line of every triangle /__\_\ # and prepends another layer if needed (?=/_/\\¶.*1) # 2nd line of each triangle /_/\/ (^|__)(?=/\\¶.*1) # 1st line of each triangle $1/\ \__ ms}`(.*1*)1 # This and above in a multi-single-line loop. /\¶/_/\¶/__\_\¶$1 # This stage adds a flattened triangle on top m`^(?=(.*¶)*.) # Prepend a space for every line following -1 $#1$* ``` Thanks to Martin for golfing 32 bytes off. [Answer] #Tarmo's ascii printing language, 46 bytes. ``` 1 /\| /_/\|/__\_\2 \__|/ 0n{n-a-1{~}1a{2#1}$} ``` Just by looking to such odd programming languages like CJam, it's makes me bit dizzy how complex, unnatural and cryptic language can be, that I wanted to "boldly go where no man has gone before", and invent my own language. As a result I've created my own language for ascii patterns printing. Basic idea is that you can define first patten and then printing - using same kind of character '1' or '2' or whatever number - you can define your own print pattern. Once pattern is defined (Starts from number till number end) - next numbers will execute pattern printing. For example ``` 1 /\| /_/\|/__\_\01 ``` Outputs like this: ``` /\ /_/\ /__\_\ ``` Will define pattern 1 and then print it right away. Pattern is defined everything separated with '|' character. 0 at the end - acts like pattern termination. Special characters like '$' are reserved as line-feed, and '~' is reserved for spacing - half - of specific pattern. ``` 1 /\| /_/\|/__\_\01$~11$~1~11 ``` Will outputs text like this: ``` /\ /_/\ /__\_\ /\ /_/\ /__\_\ /\ /_/\ /__\_\ ``` Next goes for-loops. That one needs to be easily visible - so I've retained {} brackets for for-loops, but variable names are auto-named - so first bracket will use 'a' variable, second 'b' and so on. Iteration will go always from 0 to specific number - and that number is defined before {} brackets. 'n' is reserved variable for whole function input. So code: ``` 1 /\| /_/\|/__\_\0n{1$} ``` Will outputs ( With n == 4 ): ``` /\ /_/\ /__\_\ /\ /_/\ /__\_\ /\ /_/\ /__\_\ /\ /_/\ /__\_\ ``` And '#' is special modifier for trim lead whitespace. And finally whole solution: DrawPatterns.cs: ``` using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CSharp; class DrawPatterns { //Command line parameters - for example like this: "1 /\| /_/\|/__\_\2 \__|/ 0n{n-a-1{~}1a{2#1}$}" 3 static Dictionary<char, String[]> patterns = new Dictionary<char,string[]>(); static string Tabs(int n) { if( n < 0 ) n = 0; String r = ""; for( int i = 0; i < n ; i++ ) r += " "; return r; } static int[] left = new int[10]; static int top = Console.CursorTop; static int lastTop = Console.CursorTop; static public void DoPrint(char c, char modifier = ' ') { if (c == '$') { for (int i = 0; i < left.Length; i++) left[i] = 0; top = lastTop + 1; return; } if (!patterns.ContainsKey(c)) return; if (modifier == '½' || modifier == '~') { int maxSize = patterns[c].Select(x => x.Length).Max(); for( int i = 0; i < left.Length; i++ ) left[i] += maxSize / 2; return; } int iLine = 0; foreach (var l in patterns[c]) { Console.SetCursorPosition(left[iLine], top + iLine); if( top + iLine > lastTop ) lastTop = top + iLine; String s = l; if (modifier == '#') s = s.TrimStart(' '); Console.WriteLine(s); left[iLine] += s.Length; iLine++; } } static void Main(string[] _args) { List<String> args = _args.ToList(); String todo = ""; String code = ""; char nextVar = 'a'; String lf = "\r\n"; int align = 1; char lastModifier = ' '; int nextArg = 1; Dictionary<String, String> argValues = new Dictionary<string,string>(); bool bDebug = false; if (args.Count != 0 && args[0].ToLower() == "-d") { bDebug = true; args.RemoveAt(0); } if (args.Count == 0) { Console.WriteLine("Usage: DrawPatterns.cs [options] \"script\" <arguments to script>"); Console.WriteLine("[options] allowed:"); Console.WriteLine("-d - debug"); return; } String prog = args[0]; for( int i = 0; i < prog.Length; i++ ) { char c = prog[i]; // Define pattern. if (c >= '0' && c <= '9' && !patterns.ContainsKey(c)) { String p = Regex.Match(prog.Substring(i + 1), "[^0-9]*").Groups[0].Value; patterns[c] = p.Split('|'); i += p.Length; if( prog[i + 1] == '0' ) i++; continue; } String procRemain = prog.Substring(i); // modifier specified, but pattern number is not provided - use first pattern. if( lastModifier != ' ' && ( c < '0' || c > '9' ) ) { code += Tabs(align); code += "print('1' , '" + lastModifier + "');" + lf; lastModifier = ' '; } switch ( c ) { case '{': code += Tabs(align); code += "for ( int " + nextVar + " = 0; " + nextVar + " < " + todo + " ; " + nextVar + "++ )" + lf; // Check for all variable names if they can be used in program. foreach ( var m in Regex.Matches(todo, "[a-zA-Z_][a-zA-Z0-9_]*", RegexOptions.Singleline) ) { String varName = m.ToString(); if( varName.Length == 1 && varName[0] <= nextVar ) // Already declared as a loop. continue; if( argValues.ContainsKey(varName ) ) continue; if( nextArg >= args.Count ) { Console.WriteLine("Insufficient parameters provided to script - argument '" + varName + "' value is needed"); return; } argValues[varName] = args[nextArg]; nextArg++; } code += Tabs(align); code += "{" + lf; nextVar++; todo = ""; align++; break; case '}': align--; code += Tabs(align); code += "}" + lf; break; default: if (((c >= '0' && c <= '9') || c == '<' || c == '$') && todo == "") { code += Tabs(align); code += "print('" + c + "' , '" + lastModifier + "');" + lf; lastModifier = ' '; continue; } if (c == '½' || c == '~' || c == '#') { lastModifier = c; continue; } if( c == '\r' || c == '\n' ) continue; todo += c; break; } } //for String code2 = ""; code2 += "using System;" + lf; code2 += "public class ExecClass { static void Exec( Action<char, char> print"; object[] invokeArgs = new object[ argValues.Count+1]; invokeArgs[0] = new Action<char, char>(DoPrint); int iValueIndex = 1; foreach ( var kv in argValues ) { code2 += ","; code2 += "int " + kv.Key; invokeArgs[iValueIndex] = Int32.Parse(kv.Value); iValueIndex++; } code2 += ") {" + lf; code2 += code; code2 += "} };"; if( bDebug ) { int line = 1; String lineNumberedCode =Regex.Replace(code2, "^(.*)$", delegate(Match m) { return (line++).ToString("d2") + ": " + m.Value; }, RegexOptions.Multiline ); Console.WriteLine(lineNumberedCode); Console.WriteLine(); Console.WriteLine(); } left[0] = Console.CursorLeft; for( int i = 1; i < left.Length; i++ ) left[i] = left[0]; top = Console.CursorTop; try { var compileResult = new CSharpCodeProvider().CompileAssemblyFromSource( new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true }, code2); if (compileResult.Errors.HasErrors) { foreach (CompilerError ce in compileResult.Errors) { if (ce.IsWarning) continue; Console.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText); } return; } var method = compileResult.CompiledAssembly.GetType("ExecClass").GetMethod("Exec", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); method.Invoke(null, invokeArgs); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.SetCursorPosition(1, lastTop); Console.WriteLine(); Console.WriteLine(); } //Main } ``` With command line arguments like this: -d "1 /| /*/|/\_\_\_\2 \_*|/ 0n{n-a-1{½}1a{2#1}$}" 3 Will outputs this: ``` 01: using System; 02: public class ExecClass { static void Exec( Action<char, char> print,int n) { 03: for ( int a = 0; a < n ; a++ ) 04: { 05: for ( int b = 0; b < n-a-1 ; b++ ) 06: { 07: print('1' , '~'); 08: } 09: print('1' , ' '); 10: for ( int c = 0; c < a ; c++ ) 11: { 12: print('2' , ' '); 13: print('1' , '#'); 14: } 15: print('$' , ' '); 16: } 17: } }; /\ /_/\ /__\_\ /\ \__/\ /_/\/ /_/\ /__\_\/__\_\ /\ \__/\ \__/\ /_/\/ /_/\/ /_/\ /__\_\/__\_\/__\_\ ``` [Answer] ## JavaScript (ES6), 119 bytes ``` n=>`,/\\ \\__,/_/\\/ ,/__\\_\\`[r=`repeat`](n).split`,`.map((s,i)=>` `[r](n*3-i)+s[r](n).slice(0,i*2)).slice(1).join`\n` ``` Where `\n` represents the literal newline character. If a leading line with `n*3` spaces and a newline is acceptable then the `.slice(1)` can be removed for a saving of 9 bytes. [Answer] ## Python 2, 118 bytes ``` def f(n,s=["/\\ \\__","/_/\\/ ","/__\\_\\"]): print'\n'.join(map(lambda x:' '*(n*3-x)+(n*s[x%3])[:x*2+2],range(n*3))) ``` Similar approach to [Level River St's Ruby answer](https://codegolf.stackexchange.com/a/77785/47302). [Try it online](https://repl.it/CFzj/0) [Answer] ## Python 2, 142 bytes ``` def f(n,m):return f(n-1,m+3)+[' '*(m+x)+(y*n)[x*2:]for x,y in((2,' \\__/\\'),(1,'/ /_/\\'),(0,'/__\\_\\'))]if n else[] print '\n'.join(f(n,0)) ``` The principle is very similar to other answers: take three repeated strings and then layer them in such a way that you only need to trim some of them to get the triangle, then pad them on the left. [Answer] # C++, 395 Bytes First time code golf with a glorious size of 395 bytes in C++. In my case, it feels a little like a contest for obfuscation : D ``` #include <iostream> #include <cstring> #define A for (int k=0;k<((s-(i+1))*3+(2-j));k++) cout<<" "; using namespace std; string t[3]={"/\\","/_/\\","/__\\_\\"};string r[2]={" \\__","/ "};int tr=3;int main(int,char**argv){int s=atoi(argv[1]);for(int i=0;i<s;i++){for(int j=0;j<tr;j++){A for(int l=1;l<=2*(i+1)-1;l++){if((l%2)==0&&(j<2)){cout<<r[j];}else if ((l%2)==1)cout<<t[j];}A cout<<endl;}}} ``` [Answer] # Pyth, 66 bytes ``` jmj+L**3-Qhd\ [+*2;j" \\__"*Jhd]"/\\"+;j"/ "*J]"/_/\\"*J"/__\\_\\" ``` [Try it online!](http://pyth.herokuapp.com/?code=jmj%2BL%2A%2A3-Qhd%5C%20%5B%2B%2A2%3Bj%22%20%5C%5C__%22%2AJhd%5D%22%2F%5C%5C%22%2B%3Bj%22%2F%20%22%2AJ%5D%22%2F_%2F%5C%5C%22%2AJ%22%2F__%5C%5C_%5C%5C%22&input=4&debug=0) ]
[Question] [ ### Intro There are 3 nails in the wall. You've got a piece of string that is fixed to the picture frame with both ends. To hang the picture, you entangled the string with the nails. But before letting the picture go: Can you predict whether the image is going to fall, just by looking at how the string is wrapped around the nails? ![](https://i.stack.imgur.com/dAAc2.jpg)![](https://i.stack.imgur.com/DlKK4.jpg) In the first example the picture will not fall. In the second example the picture is going to fall. ### Challenge Given the path of the string around `N` nails, determine whether the picture is going to fall or not. Return a [truthy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey?answertab=votes#tab-top) value if the picture is going to fall, and a falsy value otherwise. ### Details * You can assume that the nails and the picture are arranged in a regular `N+1`-gon, with the picture at the bottom. * You can assume that there are no knots in the rope, i.e. the rope can be continuously be uwrapped from one of the two ends. * Each nail is enumerated clockwise with a letter of the alphabet. You can assume that there are at most 26 nails (A-Z). * A clockwise wrap around a nail is denoted with the lower case letter, a counter clockwise wrap is denoted with an upper case letter. The first example from above will be encoded as `BcA`, the second example is encoded as `CAbBac`. For the inclined reader: This problem is equivalent to determining whether an element of the [free group](https://en.wikipedia.org/wiki/Free_group) - generated by the set of nails - is the identity or not. This means it is sufficient to repeatedly cancel substrings like `aA` or `Aa` until you reached a fixed point. If the fixed point is an empty string, this is the neutral element, otherwise it is not. ### Examples ``` Picture will fall: Aa CAbBac aBbA DAacAaCdCaAcBCBbcaAb ARrQqRrUuVHhvTtYyDdYyEKRrkeUWwua AKkQqEeVvBESWwseYQqyXBbxVvPpWwTtKkVHLlWwNBbAanYYyyhWwEJZUuNnzjYyBLQqQqlEGgebeEPLlTtZzpUuevZzSsbXSGgsUuLlHhUQquPpHUuFfhTZzIitGgFAaBRrBbbYXxOoDZTDdtzVvXxUudHhOVvoUuXKkxyBEeLlbFfKkHhfVAaQqHAaJjODdoVvhSsZzMZzmPpXNBbnxBbUuSSsUuDRrdNnUusJDIiUuIidCEGgeMmcLlDPOopdTEeQqCAETtNnYyeGUuPEFfSsWwHheAaBbpgCcOHUuhAaCcoEFBbfeaFHhfcCFFffNncGFfgtjMVUuKAakvKkXxLlTMmtmOFfoUuXSsYZzLXxlyxUuRPZzTtprSsWwRrPLlpGgMmKRrDHhdRCcUurYNnKCckykXJjxWwUSsJjKkLlKkuBbBbOoWwWwIiUuPDdBbCcWHBbCFfcDdYBbLlyVvSsWGgEewCchDdYywAaJjEepPpPpQXxZzFfLGXxglNnZzYDdyqCcKWXxwXxQqXTtxkFfBSSAasTFftZzsXGgxSsLlLlbZzAaCCccXVvYyxTIiOoBbFftCVQqDdBbGgAavQqKkDPpKTCctRrkdcvAaQWOowLOolqVMmvZAaHCBbcPphIiRKkrLlzFMOomDIiXJjIixMmdNnMHhmfNTtIiKkSDdTtsVvHhnAaNSVvTUutNnXxsGIiXxPpPHhUupgNnAaAAOoaaIiHJjhVvLlnYyXxQqSsTtKJjkBbNnVvEYCcFfMHGghBbmNnEeJTtjJjWYywyeNWwDIiZYyzOodnMQqmVvCcQqxVvGNnEeNBbngVvUGgYyBbDdVvIiAAaauPpQKDdEekNnVLlvHhGSDIidPZzpsPCcpgQqKkQqNOonLlIiLlJjqPAaPXxTtppYyCPpHhCIicARBbracXxWwXEVUuUuGgZHhzBSsbvGgFfeVvxLlNKknWwBLlIibWOowNnRSsrSEeKAakOosLZzZRrHhzTtTFfUuNnOKkotXxTtla Picture will not fall: A BcA ABCD aBaA bAaBcbBCBcAaCdCaAcaCAD ARrQqRrUatuVHhvTYyDdYyEKRrkeUAua AEEeQqNneHhLlAIiGgaECXxcJjZzeJFfVWwDdKkvYWwyTJjtCXxANIinaXWwxcTWwtUuWwMmTBbVWIiFLlWwZzfwPLlEepvWZzwKkEYEeWXxwySXTtEexRIiNBbnWAaTtQqNnBMSsWwOombwWwPVPpGPpgYyvDdpBbrQqHhUusKRrDAVvadLlWwOZzokGJCXSSssXxxJPpGIigZzjJjLlOoNRrnPpcMZzmjgJjNDEeQqWKkNTtnSswIidCcnYBGgbyJSsjPpIiMmMmMmSNnWVvwZzIQqLXHhxTPptlisOoeTtTtYMmVvPpyKNnMFfmkXxSVvsCGJjXxgXYJPpjWwQIiXxqyDdxFfDdAaRNnJjrctHBbZzhEQqMmeCcRBbrGgAaAaJNnRrYyWwSDdVvsJOojQGgWWwIBbiwRrqJjjWwOoFPMmDdRrQOoqNnRrDPJjpMmdPpGFfVvWUuwgpWCcNnPpwfUXCcZzJjUSsuXxxUuuRGgHhrSQqJjOosMMTtmHhmKkXxDdLlWwjSUuAaMmKYyksZzVvPZzVEeVvvHhZZOozBbzMmZCczYyGgISsiQqpXxMmXxEMmeRrAGgaGgMOGgomZFfDdzSSssBGPpgbTtBbOoRWWwGgLJjlEeGgLDdRrUulNnZzJjJjUKkuXxFfwATtaZzLVvlWwSsMmrBAaELleGBLFflbgHhbIFfiBbPpTWZzwKkKLASsaTJYyjtBbBbWwIiZCcWwzIiZLlUTtuBbYyBbIizTJjtLTtDOOoBbodBbllSsUGgLlAKkauYykUuUNnPpuDFfAaLNVvnVvlHhdMmBAaBbIiVRrGWOoPpwgWXwKkvJjOoTtYCUucVGgYyLlVvFfvRrMmySsDdbtICZzcNnINSOosDQAaXoxRGgKkrqdZznDdXxZzMGgmiJjNnACcMQqmaNnWZzUOuwTVvAJjSsaRrGgSsTtOMmRroVvRrtAVGgvMmaINniDGCcOogRrWwMVvYFfyTtmTtVvOoOIiodRrGgAxaSsGgiJja ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 21 bytes ``` +`(.)(?!\1)(?i)\1 ^$ ``` [Try it online!](https://tio.run/nexus/retina#PVXnqhw3FP6/bxFIwCYQ8BMEaXrvFROs0fTe28s7Rw6Ehbmwe0fnfFV/fJF@/Pzzx5e/vn75@7fv3@DZfP3@7fP55/efPxH5cCjDhH4IztCHR4QiwuUcQRRzOKMEZR@kdc4iFOGJBS@6tiJxlifG2R2e9hxd/q51oaz30WXCCWRMkuepo0tQ0@Awx7dNHqw7i7P0glQVWSHYeu/v6TsHR3Gmr7dlsSdVW3DovVwHznLYsxwcYln76as0u1SJiGB3xVmWxLc18anP5/sbnvEdHLlcW@E5BUesdfeDhULvM7HUOrkuQ0ScRUZEbS0@n8Kz9rb0NdJ3sOcY9hxvnAWH58Fc3l1zcwyOTeWVJjiUJufYpsZA9Z63rWnOfaFwFg4J/m6OyVNIwWELYult0SXXBWyXzRVHLdi6BuroJIg4KwsiwhaUE8WyNEcqiWW1t0YYHBoi3al18Q00GMM@WGLJAHhbkr56fPcP4HLt9PX3eWUj3BUIm6XKGDR35eU6dzkaHGtijhpHu6eL1faOrsDb1Fbr9F7rDpzhzJqiK7oYHpvPccbRSIanWFI@T3Cm9094wuFSJRQXR2v48rkYV0Ix2/Bx4jt9xVKX4rvqzTF9Ez5/Fo5qUXxf8e0ssb/fnVhiz0Nk88US9Nxiqbq9Te9Bg/QFIjhK4/BMnttXGmvCIMzOhc7C1pEqRE5n0TrenjWfo7u7djk9QbLImi7dmvolNIYzRURmHrTnWmlcrVv1/hUNaxpAKICtNLcxgHSGXA@l6e9Ko3Uen/v7Fp5yPSJieuHpBweoFt@bBO/cAA5MdsyVCT8jZE2EKI2stnV46j1oy7B5GzhabTucmWN4CglHxdKQparG2WCOQqH6e6u2ETD2FGZ0wS5p8rzWlI@GswzhyVFngWhI7H@Z06rwDKQKUpDxeXgqDUKEgMkdjc@FooMZeg/rSh4clIPu82ZzdK4YO85iWtOo90qj92q72IjY8Q2@mJOHg5TUnNJQ5OJsJTQGD8QC2Cs4pCqV6xdDsE4ITwmxBauZWjdGF2ZnZYxjc3S9bfWEgtnRmjY9fVN3hff8HeRkwbW0btrZuJ580AdT9EGY46ElCPpAzDHNoB/@7wrCIf6DBBYUcyzkWu@R0kgVEbj4pmqbvoUqliGwlWvdmUTX46vtDr8hU2lGEkfXTf3o2oMjuozBx1kYKY3IOiV9ywsCAMY8o/S9tE5IhILZ8PHAhEJxu0rDWI4Q8Xc2HBssNWCSDAJgh/Ys2TOwf/L5DExBJ4D@G4sSCk@SsxFW@k6dpHIx1MEW37cK7yhNlb4gs95bk@muoz1TVh5tpbYmz1BGWgeWG73tYoVBxwRLVfao3tbas9IYA/t45hiFJ0BQnEWP5fr27Xnvm82aCqB5T4yBNeijgYXFcoBKAL9unKS2ELs4gTXa6HKYbZeHz2@x5HNEXHNU25XuEOf0rQVnMYaCo8wELFSQYVB2TZ7o8pjbNtWaWkeqIugCnDVQJovatowe0TYGPndXx5oW9gpvq@0McQLsINQZBcdVzRFHTYB@lUHM0fRVW6iZAxgKjsOVKrlePQfOA/sYhr8PEEPWa/wvUlsvOBCB0kqeDpoXgMKD3SHg9TS1phdnrzGkHH2TR6oUb2ucZY4h0PEtACR3ReAeaD1LqqYhZdhfJg9mamb@zhrOBVRSpastuAP@MjTB8auuVFAugCaMgbQL@TuBag1P2MrbjGHFiAh6X0hYF8s@AxiZIpYNzuzZ/89imo68jfhq8rQ7K1NWpLBpdMGFlOp94O/QsSzQSvMyH@v@zlus4ibotr6HSwXW6eHWJAegh0wyEg9eLBHRzfCEVoGrLjcGzO4OpQndVYJMAs9VFMP4k1EK9uCCg4asOfQ@PMXydFdjeLyNz7Nd4dIXpFFMD8jnHUTi6QZFoCKXPH1HPmcFbkjV0IBfR8RRVk0E7Ji@gXVcfngitQWMMLlifWcZg7vCLemuO4KRpzEQxRwbXoJ7barcFVIJVS6WD8js7@FpTZbSTDl7Hd3E26QKBpF/AQ "Retina – TIO Nexus") Like flawr's solution, this just repeatedly deletes adjacent uppercase/lowercase pairs and then checks whether the result is empty or not. As for how one matches an uppercase/lowercase pair: ``` (.) # Match and capture a letter. (?!\1) # Ensure that the next character is not the same, to avoid matching # "aa" and "AA". (?i) # Turn on case-insensitivity. \1 # Match the backreference. In .NET, when using case insensitivity, # backreferences also get case-insensitive, so this *can* still match # iff the cases of the two letters are different. ``` [Answer] # MATLAB, 76 bytes ~~Octave, ~~82~~ ~~79~~ 77 bytes~~ This might be the first time I've seen where MATLAB is actually *shorter* than Octave (by an entire byte)! New answer in MATLAB: ``` c=input('');k='Aa';while k<1e5,k=k+1;c=strrep(c,65+mod(k,64),'');end;~nnz(c) ``` Answer in Octave: ``` c=input('');k='Aa';while k++<1e5,c=strrep(c,['',65+mod(k,64)],'');end;~nnz(c) ``` Saved ~~three~~ five bytes thanks to flawr. `~nnz(c)` is shorter than `isempty(c)`, and `'Aa'` is two bytes shorter than `[0,32]`. [Try it the Octave-version online!](https://tio.run/#Ad4NI) --- **Explanation:** `c=input('')` asks the user for input. We define `k='Aa'` as a character array. `while k++<1e5`: While loop where both elements in `k` are incremented each iteration, `Aa`, `Bb`, `Cc` and so on. The loop will continue until the largest element is `1e5`, which should be sufficiently high for most strings. It can be increased to `9e9` without increasing the byte count. We'll take the `strrep` function in steps, starting from the middle. By using `mod(k,64)` we'll get the following when we reach the end of the alphabet (if we convert `k` back to characters): ``` ans = Yy ans = Zz ans = [{ ans = \| ans = ]} ans = ^~ ans = _ ans = `� ans = aA ans = bB ``` As you can see, there will be some symbols in between, but then it will wrap around and start with the alphabet again, but now with the lower case letters first. This is a very short way to check both `Aa` and `aA`. `['',65+mod(k,64)]` concatenates the numeric values from the `mod`-call, with an empty string, converting the numbers to characters. `strrep` is used to remove elements from the string `c` and return it. It will search for all occurrences of `k` in the string and replace it with an empty string. After `1e5` iterations we'll either have an empty string or a non-empty string. We check if there are any elements in `c` using `nnz(c)`. We return `not(nnz(c))`, thus `1` if it's empty, and `0` if there are characters left in `c` [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 30 bytes ``` od4&x,N.I1=$6&d3~c-$~48*=,2&xx ``` [Try it here!](http://play.starmaninnovations.com/minkolang/?code=od4%26x%2CN%2EI1%3D%246%26d3%7Ec-%24%7E48*%3D%2C2%26xx&input=AKkQqEeVvBESWwseYQqyXBbxVvPpWwTtKkVHLlWwNBbAanYYyyhWwEJZUuNnzjYyBLQqQqlEGgebeEPLlTtZzpUuevZzSsbXSGgsUuLlHhUQquPpHUuFfhTZzIitGgFAaBRrBbbYXxOoDZTDdtzVvXxUudHhOVvoUuXKkxyBEeLlbFfKkHhfVAaQqHAaJjODdoVvhSsZzMZzmPpXNBbnxBbUuSSsUuDRrdNnUusJDIiUuIidCEGgeMmcLlDPOopdTEeQqCAETtNnYyeGUuPEFfSsWwHheAaBbpgCcOHUuhAaCcoEFBbfeaFHhfcCFFffNncGFfgtjMVUuKAakvKkXxLlTMmtmOFfoUuXSsYZzLXxlyxUuRPZzTtprSsWwRrPLlpGgMmKRrDHhdRCcUurYNnKCckykXJjxWwUSsJjKkLlKkuBbBbOoWwWwIiUuPDdBbCcWHBbCFfcDdYBbLlyVvSsWGgEewCchDdYywAaJjEepPpPpQXxZzFfLGXxglNnZzYDdyqCcKWXxwXxQqXTtxkFfBSSAasTFftZzsXGgxSsLlLlbZzAaCCccXVvYyxTIiOoBbFftCVQqDdBbGgAavQqKkDPpKTCctRrkdcvAaQWOowLOolqVMmvZAaHCBbcPphIiRKkrLlzFMOomDIiXJjIixMmdNnMHhmfNTtIiKkSDdTtsVvHhnAaNSVvTUutNnXxsGIiXxPpPHhUupgNnAaAAOoaaIiHJjhVvLlnYyXxQqSsTtKJjkBbNnVvEYCcFfMHGghBbmNnEeJTtjJjWYywyeNWwDIiZYyzOodnMQqmVvCcQqxVvGNnEeNBbngVvUGgYyBbDdVvIiAAaauPpQKDdEekNnVLlvHhGSDIidPZzpsPCcpgQqKkQqNOonLlIiLlJjqPAaPXxTtppYyCPpHhCIicARBbracXxWwXEVUuUuGgZHhzBSsbvGgFfeVvxLlNKknWwBLlIibWOowNnRSsrSEeKAakOosLZzZRrHhzTtTFfUuNnOKkotXxTtla) ### Explanation ``` od Take character from input and duplicate it 4& If top of stack is truthy, jump 4 spaces x Dump top of stack , NOT top of stack N. Output as number and stop I1= 1 if stack has 1 element, 0 otherwise $6& If top of stack is truthy, jump 16 spaces (to the beginning) d3~c Duplicate top two items of stack, in reversed order - Subtract $~ Absolute value 48* Push 32 =, 0 if top two items are equal, 1 otherwise 2&xx If top of stack is truthy, dump two elements from top ``` Minkolang's toroidal nature is leveraged here to eliminate the need for an outer loop. The general idea here is to check if the top two elements of the stack are 32 units apart (meaning they're an uppercase/lowercase pair), and if they are, pop both of them off. Since this is done "in realtime", so to speak, nesting of pairs is handled properly. [Answer] # [Haskell](https://www.haskell.org/), ~~98 97 85~~ 81 bytes This is just a naive implementation that repeatedly tries to cancel adjecent letters until there is no more change, and then determines the result from that. Thanks @nimi for -12 bytes and @xnor for another -4 bytes! ``` o=fromEnum r(a:b:l)|abs(o a-o b)==32=l|1>0=a:r(b:l) r x=x f=null.until((==)=<<r)r ``` [Try it online!](https://tio.run/nexus/haskell#Fcm7CsIwFADQvV9xKQ7JoPjYQm8hjW5ufsFNJFjIQ24T7NB/jzqd4bSMnnO8pRo7FqSsCnIju4gMtM9gJeLljGE7jUckxeL/HcOKa@cx1RAONZU5CIEocRhYcos0J0B41/IofE@wg@WVPz889FdNTpN5GtJuMpN1pG3fvg "Haskell – TIO Nexus") or [Verify all examples!](https://tio.run/nexus/haskell#VVVHDxu3Er77VwhGDjbwHLxyM6AA3N57f8mBy@29N/i/O0MbCBII2pW0Imfma/w@votl7Plh7z8sn/DX9Gv3@RtO10/jC38ZX@nn9/t//30vr@7bf3779xt/XT7Rf3xYXtf7@lC8h73rft2Hre4@/Y6//La88PuNPy/fe1wPr/dr2jd3W7Th9ctrrcYTbj2eXsXr/x8R/vivjyxKGUzgA2ZSBDcOYYIwm7EYEYZlUoJRCj8jZ7FnZ/H3QKoOb4tvLotvXnWWNvfDc6c7IbW1Zz4PDoZ3w3PNY3u@Iya9gsOawtPb1DaQtC48DSiEhzi@7yo8eSXxd2N4mvhmNHu2544XyzzNeUvrvC15Jn/Pj@Rx1zRyxXL1d62TKt@ed2uS/F0oKi955HoTSwFhxlmYNI2jyxy5xOOy7QmO6PL3TKrM4Bj9PVLb62b4XOtSoVBbqSoChO1ZQlhpTC4bg6Ny1@TRk6e3pgj6HC4m9XfXhbqcs2TG4O@rwsm1v8t1xtJO9Z5oHWeZ45R5fG7PLOK9zRjiOxf93eKFwl3DU6py6C6dSpaY0HUF@JKRF5i0yLEAXRBWEIrCGIgoFOXW6IG/qwi3h9pGF8Cg91tvCgUdwF3j5NGiq7thLsdKHm@bFlrCWQCwSSz1HjjhpCpzWOLvS2wMKkvau42U5gpP312VRm21Tm13JmVScwzP8KTzWFzGpCwJJbgKBQF2mVTr7uCAzcWSz0@WVJTyk2LF55MFLzu6kkcoNDG6ys4YkifmsntmiRpG1xld9hx529UKBeO6CK@eUACfaySWl7tqHXCQPAAES0gUHPF9eXJtjgwQs7GBPdN2xBLhw57VlrMm1WPJBmrLyAGUheZ4aubYzYHeHwnCEhWqNVVy7ajtonWPoJtjD0TB2HJ96T1Qp0tVXxjeJtdq63KZt63BIVUDwoYbHJ6/A2vRtYqw5oLhQGT7VBrwGCFzxFiuJaWpgkPrgFs6m7uCopWmZVJjCA4@ZolQ6JJYVkzaGwOfK97WKE0IiN25EZ7QSxLfjzlmg27PfXCwxJ7BGiL9L1VaGRy@WIILUi4LDrlGCGMQua1yGZ@3UEProF3RhY0y4H1aLZZMJUXHng1zHLROrrVOaWYLYSu6QBdTfLPgkoqVa4IcJl0wiUADEQ/y8nexTKTqYcBYB5inANuC1Ay1HcKToXulFGNjcNx1cfmcytEcVy15EmeBdd4GdFLjmmo7brRc9yMC4M0QekUMy/0IFUy/geEZkkKc/BUtmEXc32IFbz@D5R@5gn7GCk99ZQy5VGkdkmuxxDwbXURpkidXhCIAcDO1PeLwvD2l2eAZMuR6wFF4XsQLz83fw1PvPSYNQrkWaAQlT3GCX0DHR5g8p9ryMZ9T1d4uaJbPL0euKSkhwt5GizM6NRloKgW/WIE1idYEZB1cNgGwECEgl5U6DwUHzmgJM3nGVlTYCNJjja5LgTVyXSYPqELrzNFwlsGaCM2aplQag6NThmoLCh3c9aT5QoaYEcv0Vty1sSa51nv6co0hDA4YQbZnLZKqy7OmratXc8yBlS3Wexq4twqKF4oeEgTkvbKi0oBLoxjaaMLTpiqfAetLKLgMYccYlGYhG7g/eSrenvU@ZwnVDPUgWB6EsMR3eLpUnKtijo0tliFEB5PWkD2z0jQUHsHSey4DTs1xpks4S2kmcB/MDkQdob@f5RSyxIDRz8KPWJI8SgOptANC/r47YilVi2vDfqA2Xfe2HlxLY5D7AWrj@jvCkHHx3UJQw6BwoUcOWCNJzPFh0kfvE5Y88S2WsrvW9jxF4P/o4mEkZ0GgHghJUyzHPqGzP5QehrKZehsNRAemEktNaUAdcKfT@PuPdFOAOR@CMwLQTuRtGJI4OKArd9X7hUGY17pcZDSh6FIYI5WFomZSa/J@SkzVkLtiT4nvZqPZS3MXOg1POL8SrfO9DSKZ@l@uH6pjzds4kybiCFHYdXAGQTsdHLJ4h@nBwhTEnRMKhDUjOCCE4GTM9J6hR41cB84igoUB5zKMoPxBIQV5sP5OAho0WhccQnE4i97f7spl6SazyQPUyIYL4HM2wtF4ASOQqHOWPAOX0bzXxbKvQa8DYglNMgxyTB7f3E8vOJDSwIxQuaTxaOq9s8Ch6iwbgpKH3mPZGGpOhGNwLJ0FXAnJLxQ30OxtwWGOplyPGV2OLuyuYgmF8Mc/vv8J "Haskell – TIO Nexus") [Answer] ## Haskell, 62 bytes ``` a%l|b:t<-l,abs(a-b)==32=t|1>0=a:l f=null.foldr((%).fromEnum)[] ``` [Try it online](https://tio.run/nexus/haskell#VVXXyiS5Fb73UwyDF2Zgd3G4W/wbVDnnvOyFSpVzUEX23cdHM2Bsmq7q7mrpnPMlfcM/DX/mv9F//TL8jPP9C/4l//rx8c9/fNA///7vv33g34a/VB/TMQy/VvNQbF@@/PT112qbR3E6xq@///FtxO306ePTclCfbsb06a@f9ma@4Dbi5VP16ffPCH/@@TOPcg4T@IC5HMFNQJggzBc8RoTjuZxglMPPyNvc1dvCI1KaM6DpIxTpI@re1pdhfB1sJ6T37iqW0cmJfnztZequT8Lld3Q6S3wFVO8jxRjiy4JCeErT52niS9Sy8LCmt0sfznBXdx1EuS7zUnSMIaDZu4RHeWavv@eJL9d7eBiD0oTuejiLEh5S1QTZq7ZUriWEOW/j8jxNbnsWskAo6BudyR0ehdLY0TmHR6L398OJpTHkUqX3SlNFCLurgrDW2UIxR2fj79lrZu/oLAn0Od1cHh6@D3UFbyusKTx2TVDb8FDbgmedmiMxBsGx56UIxNJdeSQG1JrSp5TDwxGlyt/jS2lK6C5fap7Y0HUD@JJZlLi8KrEEXRBekqrKmogsVTXtzCg8dIT7U@@TG2AwRzraUsUG8Pc0e43kHh6Yy3OyN6DLxkp4GwC2yLU5AieC0hQeT8JjS61J50n/9InW3fEV@rvW6b0x6P3B5Vxuz/EVX2weRyi4nCexAlepIsAulxvDE52wuVyL5cWThlF@MazEcnHg5SZ39kqVISd3PVhT9qZC8aw80ePkvpLbXZOA3r1Ucb6P8B5IFfC5J3J9@7sxAAfZC0DwhCTRmT53oLb2zAExlI/clbUj1wif7qr3grPoAU8oqK0gJ1AW2/Nl2POwRuZ4ZggrTKjO0qitp/ebMbySac8jEAVjq@1tjkCdqTRjZQVUbfXeF4qA7tGpNBPClh@dQXgAa8m9y7DmhuFAZMdSW/AYIXvGWG0VrWui0xiAWzabv4Oita7ncmuKTjHliVSZilw3XD5ak1hqAe20LgbEntKKL@glS5/XnovJdNcxOnnirmANmf2XKa2OzlCuwQW5UESn2iKEMYjc1YVCLHuoYQzQruzDRgXwvuwOT5aaoeOulj1PxqC2xqB1q4Owk9ygiyV9eHBJw6stQR6Xb5gkoIFEBHmFh1xnSvNyYKwTzFOBbUFqlt5P8cWxvXKGsTV5/r75YsnkaM@7kb2Zt8G6gAKdzLi23s@UlRu@RwC8OcKuiOOF76GC2TcwPEdyiJP/RgvmkfA/sYLpj2D5v1xBP2JFZL6yplJpjAGprVxjkU9uonXZW2pSFQG4hd6faXw9gdZReIYstZ1wEl83CeKLhkd8mWPA5VGsthKLoOytLvAL6PiMs/fSezEVS6baxwfNiuXtqS0jJUY4oKw4ZzKTgaZy8IsTOYvsLEDWKRQLAAsRAnLZmfNQdOKClbCzd@5ljU8gPfbkvjVYo7Z19oIqjMGeLW@bnIWwrOlqrbMENmWs96DQyd8vli9kSjm5zh/N3ztnUVtzZC/fmuLohBFUdzUSpbkDZ6FDu9tzCazQ1BxZ4D46KF6qRkgQkPfOy1oHLk1SaKOLL5epfAWsb6kSCoQ9a9K6jVBwf/Y2oruaY8kTphnmQbA8CGFLn/jymTh3zZ47V65jiA4ubyF7Vq3rGDySY45CAZza88qWCI7WLeA@mB2IOuPwuOol5okFo19VmPAke7UOUukAhMLj8ORaaTbfhf1AbaYZ0BFcy2JQ@A5q54cHwpBx6dNDUMOgcGFHDlgjy@z55fLXHDOevOkj16q/t@66JOD/5BZhJG9DoB4ISVuu5zFjs7@MHo6xmQeUBaIHU8m1oXWgDrizacLje7ppwFwIwZkAaBcKKIYkjk7oyt/NceMQFo2hlDlDqoYcxshVqWq53FmCHxLTDeTvONDSp6Mse1nuQqfxBedXZgxhQCGSmf/V9mU6NgIq2CwRZ4jCYYAzCNoZ4JDFB0wPFmYgHoJUIWxY0QkhBCdjYY4cO2rUNvI2GSwMONdxAuVPBinIgw8PErGgMYbolKrT28zx8XehyKnKZy9Qo1o@gC@4CCfzDYxAoq5F9k5CwfLelOuxBb1OiCcsyTDIMXtD@7iC6ERaBzNC5ZrFo22O3gaHqrdRBCVPc8SqNbWCDMfgXHsbuBKSX6oeoDmg0WnPttrOBVuObuzvcg2F8Oc/vv0H) Credit to [flawr for the `abs`](https://codegolf.stackexchange.com/a/106746/20260) and [Laikoni for the `fromEnum` map](https://codegolf.stackexchange.com/questions/106745/no-strings-attached#comment259702_106746). The helper function `%` takes an already-simplified string `l`, and prepends the symbol `a` before simplifying the result. If `l` starts with the inverse character to `a`, they cancel. Otherwise, `a` is simply prepended. Note that no further simplification is needed at this stage. The main function `f` prepends and simplifies each character in turn via a `foldr`. Then, it checks whether the result is empty. To check whether two characters are opposite cases and so should cancel, see if their ASCII values differ by 32. Each element is processed by `fromEnum` before being passed to `%`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` DvADu‚øDíìvyK}}õQ ``` [Try it online!](https://tio.run/nexus/05ab1e#FVNHzqg2ED4bpvcOhh023fRiivSknCNnSJaRsv9vkou8DEJigfHMV39LXJDO//748@df6efvn7/4Y/769fOP//u3YDJ/lauEIzlMr73K/PXBiNwJ95b0ig6TJZo1pJeDiFBMWfY8bXrJRh6fzvT22YMsf/XXQVabilSyZw3Rkb9LfFY8f8Od4FBt9vi0Bq2N/fX0Fi0@lbqN8lfvDrVRhAIFGyIkw7c7S3kklcebcHzHZ6m1bsLn@MQmux8kV9ZAlNpkWlsnQuGvmlAYvSuVc8LbcM9fO39Hb8GAc7oRic8whL1SsJXOFJ@7IeldfOpdKX5I7ZFag@S581JGcuWvoiBHhzNlT6XGpycrdbinl9ZWgI4sjUhdQN0KhUhnWUGkrgoFUFBRUeramaiq1M3R20l8mkLBuMnwDTLY4zG6Sv0RCPcsfy18Dw/wCrz8jY5l@1YEGwi2qI09msEmaW0ZiDQ@t8yZTJGyh2Gjv9MrDnejN5k1mOxEBBF3Tq/0@vh4UomISFMN3kpNpTJDxBqehMNwtZGrS6QtfHyuTyu5Wjx4fHznr1JbKr6bwZnyN5PKZxWpmeL7wre/4ui4mVKjMBSKPVJq8HPHanOHuzWAB/kLQoiU4oRnzx3pnTsjMOYQE3/94KiNUHB/NZnkLWYk0iPYWEk5WJa682W587Am9shzodBERKi3tHoXmGyzhlex3XkEo4C23t32CNbZWjvWTnTonclCqYyOPeFaOwmFEyY8ik9wDd@7CnduIAchO5fGgWNBcOei0DvN6NuEWwN4@3ELd0i00TNEnCnhciZSpbY1tWkRGZ1Jrozo6I0@BcWeykkvwJJnz@vO5WT765hwkforVEP9/v2S1iQ8VhtoAZHKhOudIBQFhNw3pVKuGOywBoCrhjCoBN@X3RPp0nzq@KvjzpM16J01GP3qCYWHb8jFkj0itKQV9Y4KASJbQTFkAMsQr/hUm1xrXwTF4lCeGmoLUXNMNqUX@maRT2NnCsJ9C@Xqi6M771b@5sEG96ID7PyK65psPr51Q/E/ "05AB1E – TIO Nexus") **Explanation** ``` Dv # input number of times do: A # push lowercase alphabet Du # push uppercase alphabet ‚ø # zip the alphabets together (['aA', ..., 'zZ']) Díì # prepend a copy with each element reversed ('Aa' ...) v # for each pair in the resulting list yK # remove it from the accumulated string (starts as input) }} # end loops õQ # check result for equality to empty string ``` [Answer] # Mathematica, 102 bytes ``` ""==StringDelete[""|##&@@#<>#2&~MapThread~{Join[a=Alphabet[],A=ToUpperCase@a],A~Join~a}]~FixedPoint~#& ``` Unnamed function taking an alphabetic string as input and returning `True` or `False`. The heart of the implementation is creating a function that deletes any cancelling pair, like `"Pp"` or `"gG"`, from a string. The expression `{Join[a=Alphabet[],A=ToUpperCase@a],A~Join~a}` produces an ordered pair of lists of characters, the first list being `{"a","b",...,"Z"}` and the second being `{"A","B",...,"z"}`. Then `#<>#2&~MapThread~` produces a list where the corresponding elements of these two lists have been concatenated, that is, `{"aA","bB",...,"Zz"}`. The fun expression `""|##&@@` then (through the magic of the argument sequence `##`) produces a list of alternatives `"" | "aA" | "bB" | ... | "Zz"`; finally, `StringDelete[...]` is a function that deletes any occurrence of any of those alternatives from a string. It now suffices to repeatedly apply that function to the input string until the result doesn't change, which is accomplished by `~FixedPoint~#`, and then test whether the result is the empty string with `""==`. [Answer] ## JavaScript (ES6), 73 bytes ``` f=(s,t=s.replace(/(.)\1+/gi,s=>s.replace(/(.)(?!\1)./,'')))=>s==t?!s:f(t) ``` Unlike .NET, JavaScript has no way of turning off case sensitivity in the middle of a match, so instead we have to find all substrings of repeated letters case insensitively, and then delete any mismatching pair of adjacent characters, which by this point must be an upper/lowercase pair. [Answer] ## Perl, 28 bytes ``` 1 while s/.(??{$&^' '})//;$_ ``` **Explanation:** Perl allows one to include a dynamically generated regular expression inside of a standard regular expression. The `.` matches anything. The `(??{` is the start of the generated regex. The `$&` variable will contain the entire matched string so far, which in this case is just whatever `.` matched. The `^` operator does either numeric xor or string xor, depending on the values of the operands. In this case, it will be string xor. The `' '` is just a string containing a space, which conveniently has the ascii (or unicode!) value of 32. When a space is xor-ed with a char in the range a-z or A-Z, it will change from upper to lower case or vise versa. The `})` is the end of the generated regex. `1 while s/whatever//` will repeatedly search for a pattern and replace it with the empty string. `$_` is the default variable. This variable is what perl does fun and exciting stuff upon when you don't specify another variable. Here I'm using it to return a truthy or falsy value, since a zero length string is false, and a nonzero length string which does not equal `"0"` is true. I'm also assuming that the input string was originally placed in it. [Try it here](http://codepad.org/V81i0V5s) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 151 bytes ``` f(S):-S="";string_code(I,S,X),string_code(J,S,Y),J is I+1,32is abs(X-Y),B is J+1,sub_string(S,0,I,_,T),sub_string(S,B,_,0,U),string_concat(T,U,V),f(V). ``` Takes a long time to run on the longer false cases because of backtracking. [Try it online!](https://tio.run/nexus/prolog-swi#VVTHjuQ2EP2VwZy6Ye1ibd9s@EAqh1bOlwFFxZZaOf/8bAkeA2sIEKiiWPXqvVf8zG/O/a9vzj/v739P81i1xQft0uwmMw4T3plfQwqEojujvFXTm/zb78yff8CCJNMt/AZhfIUVCE9L8vHvsZvD/GBk5oNx7/@PYoj9YLxf0reUzDeX8Rj/zuQ3//798zO/vSPyfmfeYMGiBBP69UFwgr6WHCIUETZlCaKYxQklKPnaQvZoDfboLb5Uru4cHVwaHbxqj3XmBdvyX2ak1tbAZ/6KeSfYpiyyhiPEye6vZh9s7qzWvqQ1waZDUdJG0XGUwcYrsbfo7fmMDqxZgzU0vFhkScabWuPO8dl7S7bGpzMloSMWk7dojVR61rCYveQtQl668SlXs1gIiGB7xEkShbvRcbHLpfPpr@HuLalUGv7aeUuo1vuB@UxrEiFXa6nMfUSsQUJEeRpc2vlr6Uzx@YjPl9mHgLPdceItjgN1OXtM9dZbJoWTK2@Rq5S9kD5eVGs40@j61OUza2AR7856Gx2Z6C0mL@TOFGxSmQG6pC9YagDqEnimHS/gJM@IACgoKwh5rrdUFPJifj58b1ERqVe1Dneg4fGaX4aQXw04UxSfWrg3B/Rlm/Hpzv14lbBHIKwXi8cLdOGkMrVZ6i1jpLcqS@ujDpXnHmyeMylPtdYatV5wghOjC7Zgu/oxuRQnLA0keAs5BYVxojWHv0JyseCzjaXlJft2ccVnvQmPFe7xKeSaGO5Fo7fxGXHpMbBUDcJ9C3drCN15r4UcOw4ikyvkoOcUisXuTFoDGsQnEMFSGvprdOyuXBkdBmFm1reGC45YILJag1pzZq@6LJ3BcSldQbLA6DbN6JrBf7zWGBHpMqzZl3Jlq/WoNafwMLoXCAVty9X@eIF0D6l85bo7y5VaO1zqzpO/SmWLiO74q@stoFq4TyKc2aE5MNnSFzpsI2R0hMiVpDxLf9Ua0PbqzZnA0cqzxone@isfsVTIH5JYlDh56S2fKe78VJ4BMHZkerABljg6TqNL24c1vPyVpdYAoyFe/15OK/zVEwuYgoRL/VWuECIETG6pXMpnNdTQGoArOpAoBd37yWRpX1zsWINudK3WyJXWKM/BRMQMd/BFHx0sTEnJyhVFNk5GQkPwQMiDvbxFLGKpPDEM1grDk8PYgtV0tW6DDV@5kotjvbWdaXT47LKj0U1afMb2COfcGeS8BtdQ626@yjVwDXz/CQ "Prolog (SWI) – TIO Nexus") **Ungolfed** ``` f(S):- The string S corresponds to a falling picture if: S=""; S is the empty string, or... string_code(I,S,X), X is the character code at some index I string_code(J,S,Y), Y is the character code at some index J J is I+1, J is I+1 32 is abs(X-Y), X and Y differ by 32 (difference between lower/upper case) B is J+1, ... sub_string(S,0,I,_,T), ... sub_string(S,B,_,0,U), ... string_concat(T,U,V), ... f(V). The concatenation of the substrings before and after the letters X and Y corresponds to a falling picture. ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` x=>Buffer(x).map(c=>c==e[i]?--i:e[++i]=c^32,i=e=[])&&!i ``` [Try it online!](https://tio.run/##VZZHrxxFFIX38y/YID@BvYAd6IGqc87ZGLm6Ouec/ry5BZIlNNLMYqb6hnPOV9PgA69kqaft4zBm@Tfh/dv1/gezF0W@fLjePvV4@kDe/yDv7/nn@sufHz/Wv@Wff/qp/vJO/v71l5/r9/z985e3H3/8of72@@srwi8WpQwmL8yk6MUhTBBmMxYjwrBMSjBKX8hZ7NlZ/D2QqsPb4pvL4ptXnaXN/fDc8QuprT3zeXAwvBueax7b8x0x6RUc1hSe3qa2gaR14WlACTzE8X1X4ckrib8bw9PEN6PZsz13vFjmac5bWudtyTP5e34kj7umkSuWq79rnVT59rxbk@TvQlF5ySPXm1gKCDPOwqRpHF3myCUel21PcESXv2dSZQbH6O@R2l43w@dalwqF2kpVESBszxLCSmNy2Rgclbsmj548vTVF0OdwMam/uy7U5ZwlMwZ/XxVOrv1drjOWdqr3ROs4yxynzONze2YR723GEN@56O8WLxTuGp5SlUN36VSyxISuK9gtGXmBSYscC9AFYQWhKIyBiEJRbo0e@LuKcHuobXTBGvR@602hoAO4a5w8WnR1N8zlWMnjbdNCSzgLLGwSS70HRTipyhyW@PsSG4PKkvZuI6W5wtN3V6VRW61T251JmdQcwzM86TwWlzEpS0IJ3oWCgLZMqnV3cMDDxZLPT5ZUVPCT7orPJwtednQlj1BoYnSVnTEkT8xl98wSNYyuM7rsOfK2qxUKxnURXj2hAD3XSCwvd9U60CB5YBEsIVFwxPflybU5MiDMxgb2TNsRS4QPe1ZbzppUjyUbeC0jB0gWmuOpmWM3B3p/JAhL1KTWVMm1o7aL1j2Cbo49CAVjy/Wl9yCdLlV9YXibXKuty2XetgaHVA0IG25weP4OqkXXKsKZC4YDk@1TacDXCJkjxnItKU0VHFoH2tLZ3BUcrTQtkxpDcPAxS4RCl8SyYtLeGPhc8bZGaULY2J0b4Qm9JPH9mGM26PbcBwdL7BmiIdLfUqeVweGLJaQg5bLgkGuEMAaT2yqX8XkLNbQO2hVdeFAGuk@rxZKppNuxZ8McB62Ta61TmtlC2Iou8MUU3yykpGLlmiCHSRdMIvBAxIO9/F0sE6l6GAjWAeEpILZgNUNth/Bk6LNSumNjcNx1cfmc2tEcVy15EmeBc94GctLgmmo7brRcBwB4MQS9EMNygBGMXhBzhqQAkO8wwSzivoMEb/@h5H8kQRQkPE2SMeRSpXVIrsUS82x0EaVJnlwRigDWmantEYfn7SnNBt8hQ64HHIXnRbzw3Pw9PPXeY9IglGuBQid5ihMSAs49wuQ51ZaP@Zz69HbBpXx@OXJNZQgR9jZanNFprMBFKSTECqxJtCaQ5@CyCVYJ0ACDrDRrKDhwRkuYyTO2osJGwIs1ui4Fzsh1mTzgA60zR8NZBmsilC5NqTQGR6cM1RY8ObjrSYlChpgRy/RW3LWxJrnWe/pyjSEMDhhBtmctkqrLs6atq1dzzEGHLdZ7ithbBY8LRQ/MAEOvrKg0kMsohjaa8LSpr2fY9CUUXIawYwxKs5AN8p48FW/Pep@zhLqEpg5CDtIv8R2eLrXjqphjY4tlCLBg0hpoMytNQ9cjWHrPZaCoOc70CGcpzQR5g9lBqCP097OcQpYYMPpZ@BFLkkdpgEM7bMjfd0cspWpxbXge@EvXva2HnFLwcf8utXH9HWGgWny3gGYYFN7oJQNhSBJzfJj00fuEJU98i6XsrrU9TxEkPrp4GMlZELgHsGiK5dgndPaHysNQNVNvowh0YCqx1JQG3AGfdBp//5dnCijnAyojWNqJvA0De4MDunJXvV8YhHmty0VGE4ouhTFSWShqJrUm7z@LqRpyV@wp8d1slLaUtNBpeMKNlWid720AYZp4uX6ojzVv40zKwBHg13Vw60A7HVyreIfpIbR0iTsnFAhrRnAAduAuzPSeoZeLXAfOIkJoYc9lGEH5g64U7MH6OwkoWrQuOITicBa9v92Vy9JNZpMHpJENF5bP2QhH4wWKAEPnLHkGLqOE18Wyr8GvA2IJZRcGOyaPb@6nFxxIaWBGqFxSIJp67yxwjTrLhqDkofdYNoaaE@HiG0tngVQC64XiBpm9LTjM0ZTrMaPH0YXdVSyhEP76aZ26evv61/D1@/@YcVjHLv/UjeUH4QN5e3t7ffsH "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` t"[]yd|32=fX<tQh(]n~ ``` [Try it online!](https://tio.run/nexus/matl#@1@iFB1bmVJjbGSbFmFTEpihEZtX9/@/epJjolNykpOzU7JjonOKc6JjcqKzo4s6AA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#VZXHjuy6FUXn/gxPrsf21B6QyjlH4wGmqJwjFfDgX78@vA8wbBRa1d1V0gl778V//Tz//M/f3vL3v/31H3X699Nr//Lb/O@fYvjzByI//vRDQAUmFH4huEDwJiJCERFKgSCKBVxQggr4N/J3b/P36IrVloVn9opl9kqGvw9VlNwXfxIyBm@TqphhKUjuo8q87U1x8cTMXZM7PI0hVs0xuW0oROYse982uSU9jy57/vrsxaa3edsoKU1VVJJrjuGZf2t0VSz/gqNIA6U5ossc1Tbytstd1eiS6zbMP607lUZGBPs7LoosfZxFzEOxPL@YpU90lWrrxGyJrtQYnhdLlTkWcm0MalvHiHibiojeO2K5xKwNjvyz8m9y1xT6nB9cRFcQQF3R30t7jq5DF7UuurSuFHin1kTNUXSdZS1DqfI2AUnhac/ZWynR5UpyHRzJrbYVdFesjUAd6LqF/dJFknFRV0SGLqggy3Vtz1SR6@bsrTi6DEQGZgzpA2uwpnNy5JoPEBxZ/pnpM74wl@/mX3iuOy/h77CwVWmsCTQR1bb0BRpde2bPhkCHd0j1/knuKDj03hjM0RguXODCWZI7ufk8rljiQqCJCle5pqAuLszxjRk8XGmk6hZoyyW/@a6kanXh5aVP/sm1qaRPM9pz/mVi@W4CNZL0udPH29LwfAa5xkGAyBHKNeh5pErzBIc5ggb5B4sQKE1jlr1PqHXOgkGYU4i9jbejNIgwbzMG0V2NUKAnuK2kDCRLnOU2nWXcYmtiOSIqN6q7tlrnG8Nujp9sOcsEQsHYWvdYE0hnqe1U2@GpdcYQiGV4HjFT2xkRO4hZGF2gWvocCtzzwHBgsmttbPgYIWchROtUvW9jZo6gLZ8tOMDRej/gwp5jJmUClWtLVZoWF5M9S5Uenr3eJ7Cxt7KTG3rJs/dzlnK2vG2KmUC9DaKh8O9ypzUxi5QGUlCIZcy0DiFCwOSeIZZSNUANc4R2lQAeVILu6@EKdG34drzNdpbZHLXOHPV@cxFx0wd8sWavAClpBa2jyMfFTmgKHkglsFd0KU2uth@GYDEITw2xBavZxjAnN@bPKviO7dkPjj2QKm5HZznM/Mv9He4LT5CTB9cxhuXk5cZfCIAfTPkVYUH8BRXC/4LAY1oATv6LFiIg8X@wQs4/wPJ/XEF/YEXiubLnSm3NEWmd0hBJSB@q9/lX6XIdw3JLY2BZcr@h3p/wGbK1biZpcj80TO4zupLbmkJcxInWyRxB@VffkBfwMUvy7zYGKZMq7to3AM9K1eNrHRclQSQ8eXFs8ZCBpwrIixu7q@KuIBYTyxUWCwgBuxw8eShmpOQlnPxbBkUXUqDHkT6PDvdoXZN/4ApzdBbb32d3pZw1faP3tsinTIwBHDoHx835QucMK03x6sHRu6vWWRN/BfacxAxG0LzNTNX2Cd31HLvDWSpQ5cysiQP3NcDxcj0BQcDeh6DoPaQ0zaCNPrk97vINdv3ItVgi4tuz3u/0hPTnXyt5mzVVAuWe4RmEyIMR9uxN7oCb89CdpfeUJgF04KID9mx63/P1yK41iSVo6iwbv0V09X6F9MHsIBRLoutu1kSgNox@11Eq0PzTe6DSBRuKrstXGrXdAw@eB26zrPCcILUcg@KvpfZBdCECjMveAUANg8KFHzkQjTx3lg8XnzXlAv2yV2m04Oi8bU0h/@kjwUj@jsA9AElHaZYp57N/XB7M1SzCkwPRh6mUxtR7cAe882mi6xfddFAuAnCmsLQbhScBEscMugoOa9oxIpI5Vgo25XosYIxCk@sOF@4a/mExw0TBQUI9e/uTs5dzFzpNbji/cnOMwhOQzPOvdR/3sRmeosOJuAAKxxHOIGhnhEOWXDA9RJgv8RLlGhHTjhlACE7G0powP2q0LvZ3BSIMe26SFMozvlKwhxBdNOagMceYyTXzd2t6g0Msi1MT8g@k0ewAli96iKTLA4oAUbcy/2ax5Ly3lGbqwK8zEignGQE75l/kXHcYM6T3MCNUbjgeHWvydzhU/f1EUJJZE9HsuRMVOAaXxt8hlUB@uX5B5vCMmbM4WreU/Hb0kOBQGihEfvwH) (it takes a while). ### Explanation ``` t % Input string implicitly. Duplicate " % Do as many times as input size [] % Push empty array y % Duplicate current string onto the top d| % Absolute consecutive differences 32= % Convert to true if 32, false otherwise fX< % Index of first occurrence of true, or empty of all false tQ % Duplicate, add 1. This gives the next index, or empty h % Concatenate. Gives the two consecutive indices of letters % to be removed, or empty ( % Assign an empty array to those positions, i.e. delete them ] % End n~ % Number of elements, negate ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes ``` (Or@@ToCharacterCode@#//.y_||z_/;Abs[y-z]==32:>1<0)===1<0& ``` [Try it online!](https://tio.run/##VcxLS8NAGIXh/fcrhgaKLmq87GynzDcTQXChphcpMZQzk9QErdVxoqT0v8eAUHB14IXzbBGqcotQO3QbIbuTe6/UfGcqeLhQerMrShXF8Vm7Phz263jM9itrR/tcyqvL6@nF5PxUStnPsHvw9XvIIjGaik0W5bkYiliJWejzy@zjrQ5q8EwMMmw1HEFbpoThGKYwYKeNtg5siVP/@Jn6RbO8rb7nYdUmxaq9uUv9a7l4@mlATNoxsTZJr4DJMrSz/f9owXBydBD@pH8QNxh0vw "Wolfram Language (Mathematica) – Try It Online") [Answer] # C `-m32`, 100 + 4 = 104 bytes ``` n;i,k;j;f(s){for(i=0;~++i;)if(k=i%128,n=(k^32)<<8|k,(j=strstr(s,&n))&&k)memmove(j,j+2,strlen(j+1));} ``` No TIO link, because it takes a few minutes to execute, as it loops through all 32-bit integers. It takes a `char *` (zero-terminated string) which will be modified and points to `\0` iff the result is empty. We construct an string containing an uppercase and a lowercase letter with `(k^32)<<8|k`. When this int is read as a little-endian `char *`, the top 2 bytes are the null terminator. If that substring is found, we delete these 2 characters with `memmove`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ØẠżŒs¤œṣF¥ƒ$ÐLṆ ``` [Try it online!](https://tio.run/##VZU3rizHGYXzuw5tpKq99zarrvbeu5ABlQpUolCApIwhE0qK@PC0j6eNXP1FAgSEAWaCnurfnHO@aou@fz4/v/zl2z//@vXfX3/Yfvn71z9/@/lv4i//@M8Pf/jyJ/3bz99/fvvXT1/@@N/vfkw@PxH54FCGCf0gOEMfPCIUES7nCKKYwxklKPtA7uos7hocoVyf/p48fJ48guauXRFE10E@kNY5i1CEJxa86NqKxFmeGGd3eNpzdPm71oWy3keXCSXImCTPU0eXoKbBYY5vmzxYdxZn6QWpKrJCsPXe39N3Do7iTF9vy2JPqrbg0Hu5DpzlsGc5OMSy9tNXaXapEhHB7oqzLIlva@JTn8/3NzzjOzhyubbCcwqOWOvuBwuF3mdiqXVyXYaIOIuMiNpafD6FZ@1t6Wuk72DPMfQ53jgLDs@Dury75uYYHJvKK01wKE3OsU6Ngeo9b1vTnPtC4SwcEvzdHJOnkILDFsTS26JLrgvoLpsrjlrQdQ27pZMg4qwsiAhdUE4Uy9IcqSSW1d4aYXBoiHSn1sU3rMEY9sESSzaAtyXpq8d3/8Bcrp2@/j6vrIS7wsJmqTIGUISX69zlaHCsiTlqHO2eLlbbO7oCb1NbrdN7rTtwhjNriq7oYvPYfI4zjkYyfIslBW1xpvdPeMLLpUooLo7WTPCL7UooZhs@Tnynr1jqUnxXvTmmb8Lnz8JRLYrvK76dJfb3uxNL7HmIbL5Ygp5bLFW3t@k9aJC@sAiO0jg8k@f2lcaaMAizc6GzsHakCpHTWbSOt2fN5@gOXsvpCZJF1nTp1tQvoTGcKSIyM6k910rjat2q969oWNMAQsHYSnMbA0hnyPVQmv6uNFrn8bm/b@Ep1yMipheefnCAavG9SXDmhuHAZMdcmfAYIWsiRGlkta3DU@9BWzabt4Gj1bbDmTmGp5BwVCwNWapqnA3mKBSqv7dqG8HGnsKMLuglTZ7XmvLRcJYhPDnqLBANif2XOa0Kz0CqIAUZn4en0iBECJjc0fhcKDqooffQruTBi3LQfd5sjs4V246zmNY06r3S6L3aLjYidnyDL@bk4SAlNac0FLk4WwmNwQOxAPYKDqlK5frFEKwTwlNCbMFqptaN0YXZuzK2Y3N0vW31hILZ0Zo2PX1Td4Vz/g5ysuBaWjftrFwPAPjAFH0gzPGAEYI@IOaYZgCQ32FCOMT/DhKy/4aS/yMJYiARWJLMsZBrvUdKI1VE4OKbqm36FqpYhrDOXOvOJLoeX213eIZMpRlJHF039aNrD47oMgYfZ2GkNCKDTvqWFyQEnHtG6XtpnZAIBfPp44FLheJ2lYbJECHi76w4NliswEUZJMQO7VmyZ5Dn5PMZVgnQAINsLGsoPEnOSljpO3WSysXAiy2@bxXOKE2VvuADvbcm011He6aMLm2ltibPpoy0Djw5etvFiELHBEtV9qje1tqz0hgD@3jmGIUnjKA4ix7L9e3b8943mzUVoMOeGAND7KOBx8VyAGaAoTdOUlvIZZxAG210OczXC2z6Fks@R8Q1R7Vd6Q55T99acBZjKDjKXMJSByEH6dfkiS6P2XFTral1pCoCWOCsAdosatuy9Yi2MfA5KGpNCzvC22o7Q95gdhDqjILjquaIoyaMfpVBzNH0VVvg0AEbCo7DlSq5Xj0H3gf@Mgx/HyCnDHz8r0ttveBABKiWPB2gGQaFL3bJQBjS1JpenL3GkHL0TR6pUrytcZY5hsTHtwAjuSsC9wAWLamahpTN/jJ5MFMz83eGQBemkipdbcEd8MumCY5feaaCcgGgMoalXcjfCbA3PKErbzOGFSMi6H0hYV0s@wzGyBSxbHBmz/5vFtN05G3EV5On3RltGWmh0@iCGyvV@8DfAcIs8UrzMh/r/s5bjIETwK/v4daBdnq4VskB00No2RIPXiwR0c3wBOzAXZgbA2aXi9KE7ipBaGHPVRRD@ZOtFOzBBQcNGVr0PjzF8nRXY3i8jc@zXeHSF6RRTA@WzzuIxNMNigBDlzx9Rz5nhDekamjAryPiKGMXATumb2Adlx@eSG1hRqhcMSBaxuCucI26646g5GkMRDHHhpfg4psqd4VUAuvF8gGZ/T08rclSmilnx9FNvE2qoBD5Hw "Jelly – Try It Online") Outputs `1` if the picture will fall, and `0` if not ## How it works ``` ØẠżŒs¤œṣF¥ƒ$ÐLṆ - Main link. Takes a string S on the left $ - Group the previous 2 links into a monad f(S): ¤ - Group previous links into a nilad, A: ØẠ - Alphabet; "ABC...XYZabc...xyz" Œs - Swapcase; "abc...xyzABC...XYZ" ż - Zip; ["Aa", "Bb", ..., "Yy", "Zz", "aA", "bB", ..., "yY", "zZ"] ¥ - Group previous 2 links into a dyad g(S, p), where p is some pair of letters: œṣ - Split S at this pair F - Flatten ƒ - Reduce the nilad A by g(S, p), initialising with S on the left ÐL - Repeatedly apply f(S) until a fixed point (empty list if fall, non-empty if not) Ṇ - Logical NOT ``` [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes ``` s=input() for i in s*len(s):s=s.replace(i+i.swapcase(),'') print(not s) ``` [Try it online!](https://tio.run/##VZXHjiQ3FkX3@RW96yrNQMBAuwG0YHjv/Y7B8D6C4X@@51ECBAwSyFpkkc/cew@XZ2/m6Y9f5V2Sr//88dvPnz9/0T/baTn2r@9PNW8/2h/t9IP@NpTTF/3@L/2T/r6Vy4BJ@dX@q/2dXnghmJZf3//@@fP7s2zttH9N8/6Dfv@Cu75/IfzhUc5h8sFcjj4CwgRhvuAxIhzP5QSj/IO8zV29LTwipTmDPX2EIn1E3dv6MoyvA3@Q3rurWEYnJ/rxRcvUXZ@Ey@/odJb4Cna9jxRjiC8LSuApTZ@niS9Ry8LDmt4ufTjDXd11EOW6zEvRMYZgz94lPMoze32aJ75c0/AwBqUJ3fVwFiU8pKoJsldtd7mWEOa8jcvzNLntWcgCodjf6Ezu8CiUxo7OOTwSvb8fTiyNIZcqvVeaKkLYXRWEtc4Wijk6G59mr5m9o7Mk0Od0c3l4@D7UFbytsKbwoJqgtuGhtgXPOjVHYgyCY89LEYilu/JIDHZrSp9SDg9HlCqfxpfSlNBdvtQ8saHrBnZLZlHi8qrEEnRBeEmqKmsislTVe2dG4aEj3J96n9ywBnPcR1uq2AA@TbPXSO7hgbk8J3uDfdlYCW@DhS1ybY6giKA0hceT8NhSa9J50j99onV3fIU@1Tq9Nwa9P7icy@05vuKLzeMIBZfzJFbgW6oIaMvlxvBEJ1wu12J58aRhgl9sV2K5OPBxkzt7pcqQk7serCl7U6F4Vp7ocXJfye2uSbDfvVRxvo8wDaQK9KSJXN8@NQbQIHthETwhSXSmzx2orT1zIMzOR@7K2pFrhE931XvBWfSAJzt4rSAnSBbb82XY87BG5nhmCCvMpM7SqK2n95sxvJJpzyMIBWOr7W2OIJ2pNGNlBbva6r0vFMFOo1NpJoQtPzqD8ADVkpvKcOaG4cBkx1Jb8DNC9oyx2ipa10SnMYC2bDafgqO1rudya4pOMeWJVJmKXDdcPlqTWGrB3mldDBt7Siu@oJcsfV57LibTXcfo5Im7QjRk9r/MaXV0hnINKciFIjrVFiGMweSuLhRi2UMNY4B2ZR8uKkD3hTo8WWq2HXe17HkyBrU1Bq1bHYSd5AZfLOnDQ0oaXm0J8rh8wyQBDyQi2Cs85DpTmpeDYJ0QngpiC1az9H6KL47dlbMdW5Pn080XS2ZHe6ZG9mbeBueCHeRkwbX1ft5ZuQEA8OEI@iCOFwAjGH0g5hzJASD/wATzSPgHJHj/GyX/RxLEQCKyJFlTqTTGgNRWrrHIJzfRuuwtNamKYJ2F3p9pfD2B1u3wG7LUdsJJfN0kiK89POLLHAMuj2K1lRh0sre6ICHg3DPO3kvvxVQsmU8fH1wqlrentkyGGOFgZ8U5k8UKXJRDQpzIWWRnAXlOoVhglQANMAhlWUPRiQtWws7euZc1PgFe0OS@NTijtnX2gg@MwZ4tb5uchTC6dLXWWQKbMtZ78OTk04sRhUwpJ9f5o/m0cxa1NUf28a0pjk4YQXVXI1GaO3CWfWipPZegw56aI0Pso4PHpWoEZoChKS9rHeQySaGNLr5c5usVNn1LlVAg7FmT1m1kh7xnbyO6qzmWPGEuYamDkIP0W/rEl8/sSDV77ly5jgEWXN4CbVat69h6JMcchQIUteeVHREcrVsgbzA7CHXG4XHVS8wTC0a/qjDhSfZqHXDogA2Fx@HJtdJsvgv3gb9MM9hHyCkDn/DXUjs/PBAGqqVPD2iGQeGLPTIQhiyz55fLX3PMePKmj1yrPm3ddUkg8cktwkjehsA9gEVbrucxY7O/TB6OqZkHO0OgB1PJtaF14A74y6YJj794poFyIaAygaVdKNgxsDc6oSufmuPGISwaQylzhlQNOYyRq1LVcrmzBH9bTDeQT3GgpU@3M9oy0kKn8QUvVmYMYbADhFni1fZlPjaCXbAZA2eA3zDAqwPtDPCs4gOmh9CyJR6CVCFsWNEJ2IG3sDBHjj0uaht5mwyhhT3XcQLlT7ZSsAcfHiRiaDGG6JSq09vM8fGpUOS7ymcvSKNaPixfcBFO5hsUAYauRfZOQsEIb8r12IJfJ8QTxi4Mdsze0D6uIDqR1sGMULlmQLTN0dvgGfW2HUHJ0xyxak2tIMPDN9feBqkE1kvVAzIHe3Tas622c8GOoxv7VK6hEP4f "Python 3 – Try It Online") ]
[Question] [ Your task is, given a positive integer `n`, to generate an expression that equals the number `n`. The catch is: you're only allowed the number `1` in the output. The operators at your disposal are: * `+`, `-`, `*` and `/` + `/` is floating-point division (so `5/2 = 2.5`). * `sqrt` (as `s`) * `ceil` and `floor` (as `c` and `f` respectively) * `!` (factorial) + The factorial, in this case, only works for positive integers. You are also allowed to stack `1`'s together, so something like `11` is acceptable in the output. However, they count as the same number of `1`'s that's in the number (so `11` counts as 2 `1`'s). You must also include brackets in the output, so that the expression in the output, when executed through the order of operations, will result in the input. They do not count as operations, though. ## Examples: * Input = 24, one possible output = `(1+1+1+1)!` * Input = 11, one possible output = `11` * Input = 5, one possible output = `c(s((1+1+1+1)!))` + The ceiling of the square root of `24` is `5`. ## Rules: * You are guaranteed that the input is a positive integer from `1` to `2^31-1`. * Your program must work for any positive integer up to `2^31-1`, even if they are not tested. * Your program must finish processing all outputs for all numbers in the set in 1 hour. * The results for every run of the program must be exactly the same - also, no seeds. * You are only allowed to hardcode the expressions for a maximum of 10 numerical values. * You are not allowed to have imaginary numbers anywhere in the output (so no `s(some negative number)`). * You are also not allowed to have numbers larger than `2^31-1` or smaller than `-2^31+1` anywhere in the output, even when they are `sqrt`ed or `/`ed (so no `(((1+1+1)!)!)!` or `((1+1+1+1)!)!`). ## Set of Numbers: ``` 945536, 16878234, 32608778, 42017515, 48950830, 51483452, 52970263, 54278649, 63636656, 78817406, 89918907, 90757642, 95364861, 102706605, 113965374, 122448605, 126594161, 148064959, 150735075, 154382918, 172057472, 192280850, 194713795, 207721209, 220946392, 225230299, 227043979, 241011012, 248906099, 249796314, 250546528, 258452706, 276862988, 277140688, 280158490, 286074562, 308946627, 310972897, 322612091, 324445400, 336060042, 346729632, 349428326, 352769482, 363039453, 363851029, 392168304, 401975104, 407890409, 407971913, 425780757, 459441559, 465592122, 475898732, 482826596, 484263150, 506235403, 548951531, 554295842, 580536366, 587051904, 588265985, 588298051, 590968352, 601194306, 607771869, 618578932, 626776380, 667919873, 681786366, 689854904, 692055400, 697665495, 711608194, 734027104, 750869335, 757710567, 759967747, 777616154, 830071127, 833809927, 835873060, 836438554, 836945593, 863728236, 864158514, 871273503, 881615667, 891619600, 897181691, 918159061, 920521050, 924502226, 929983535, 943162304, 950210939, 950214176, 962610357, 974842859, 988572832 ``` (These are 100 random numbers from 1 to 1 billion.) ## Scoring System: Your score is determined like so: * Your program will be tested against the random numbers in the set. + You must provide the output generated using the random numbers in the set (either inside your answer or as a pastebin link). * Your then have two "scores": A primary score and a secondary score. + Your primary score is `(no. of 1's in output)*(no. of operators in output)`. If your primary score is the lowest, you win. + Your secondary score is the time of your upload, in GMT, and in 24-hour time. So, if you upload your program on September 12th, 00:00 GMT, then your score is `12/09/2016, 00:00` (use `DD/MM/YYYY HH:MM` for your formatting). Display your score like so: ``` (language name) Primary Score = (primary score) Secondary Score = (secondary score) (no. of 1's) `1`'s, (no. of operators) operators ``` Replace all the things in the brackets with your language name, primary score and secondary score respectively. ## Current Winner: ### The current winner is @ChrisJefferson, who has a primary score of `3,810,660`. [Answer] # C++11 Further small update: Do much less adding, and try all numbers of form A\*B+C. I believe that, within the time limit, this is fairly close to optimal, assuming you only use `+`, `*` and `!`. I leave other operators to people with more time than me! Small update: Try harder to make use of factorials and numbers like 11....111. Also fixed bug that I wasn't counting `!` in my costing New result: Primary Score = 3,810,660 Secondary Score = 12/09/2016 20:00 2532 `1`s, 1505 operators. Various tricks put together. My program starts by setting the shortest program for all factorials and numbers of the form 111..111 (I don't think this falls foul of the hard-wiring rule, as these are the shortest ways to make these numbers. I could rearrange my code so I check these patterns in my dynamic programming if you want). Then do a partial dynamic programming approach, trying various forms: * A + B * A\*B + C * A! + B * 11....11 + B Unfortunately I can't try all the ways of decomposing a number, so I choose for factorial and 11...11 to only try the nearest number, for A+B to try things near A/2, and for A\*B+C to try only quite small As. It would be easy to extend this to try some '-'s, by trying to overshoot slightly sometimes (particular in A\*B - C), but I quite like only trying to grow. Also, it is very hard to optimise the optimisation condition (I don't like it!) because in principle you can't come up with a 'best' value for each number in isolation, you have to consider your set of answers globally (which I don't intend to do). Warning: This program needs a 64-bit machine, and around 10GB of memory (as I inefficiently make a giant array for all partially-computed results). Program: ``` #include <algorithm> #include <vector> #include <string> #include <assert.h> #include <iostream> #include <cmath> std::vector<int> numints; std::vector<int> numops; std::vector<std::string> strings; void fill_all_ones(long maxval) { int val = 1; int len = 1; std::string name = "1"; while(val < maxval) { val = val * 10 + 1; len++; name = name + "1"; numints[val] = len; strings[val] = name; } } void get_best_for_next_full(long i); // let's just assume this is the best way to make factorials void fill_all_factorials(long maxval) { // skip 1 and 2 long result = 6; long val = 3; while(result < maxval) { get_best_for_next_full(val); strings[result] = "(" + strings[val] + ")!"; numints[result] = numints[val]; numops[result] = numops[val] + 1; val++; result = result * val; } } long get_nearest_all_ones(long i) { int val = 11; int prevval = 1; while(val < i) { prevval = val; val = val * 10 + 1; } return prevval; } long get_nearest_factorial(long i) { int val = 6; int prevval = 2; int step = 3; while(val < i) { prevval = val; step++; val = val * step; } return prevval; } int getlen(long i); void get_best_for_next_full(long i) { if(numints[i] > 0) return; int best = INT_MAX; // we'll do better than this std::string beststring = "invalid2"; int ones = -1; int ops = -1; for(long loop = 1; loop <= i/2; loop++) { int new_val = getlen(loop) + getlen(i - loop); if(new_val < best) { best = new_val; ones = numints[loop] + numints[i - loop]; beststring = "(" + strings[loop] + "+" + strings[i - loop] + ")"; ops = numops[loop] + numops[i - loop] + 1; } } for(long loop = 2; loop * loop <= i; loop++) { long divisor = i / loop; long rem = i - loop*divisor; assert(rem >= 0); int new_val; if(rem == 0) { new_val = getlen(divisor) + getlen(loop); } else { new_val = getlen(divisor) + getlen(rem) + getlen(loop); } if(new_val < best) { best = new_val; if(rem == 0) { ones = numints[divisor] + numints[loop]; beststring = "(" + strings[divisor] + "*" + strings[loop] + ")"; ops = numops[divisor] + numops[loop] + 1; } else { ones = numints[divisor] + numints[loop] + numints[rem]; beststring = "(" + strings[divisor] + "*" + strings[loop] + "+" + strings[rem] + ")"; ops = numops[divisor] + numops[loop] + numops[rem] + 2; } } } numints[i] = ones; strings[i] = beststring; numops[i] = ops; } void check_divising(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops); void check_adding(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops); void get_best_for_next_partial(long i) { if(numints[i] > 0) return; long best = INT_MAX; // we'll do better than this long ones = 1; std::string beststring = "invalid"; long ops = 1; // Special: Try a nearby all ones { long loop = get_nearest_all_ones(i); check_adding(i, loop, best, ones, beststring, ops); } // Special: Try nearest factorial { long loop = get_nearest_factorial(i); check_adding(i, loop, best, ones, beststring, ops); } for(long loop = 2; loop * loop <= i; loop++) { check_divising(i, loop, best, ones, beststring, ops); } numints[i] = ones; strings[i] = beststring; numops[i] = ops; } void check_adding(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops) { int new_val = getlen(loop) + getlen(i - loop); if(new_val < best) { best = new_val; ones = numints[loop] + numints[i - loop]; beststring = "(" + strings[loop] + "+" + strings[i - loop] + ")"; ops = numops[loop] + numops[i - loop] + 1; } } void check_divising(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops) { long divisor = i / loop; long rem = i - loop*divisor; assert(rem >= 0); int new_val; if(rem == 0) { new_val = getlen(divisor) + getlen(loop); } else { new_val = getlen(divisor) + getlen(rem) + getlen(loop); } if(new_val < best) { best = new_val; if(rem == 0) { ones = numints[divisor] + numints[loop]; beststring = "(" + strings[divisor] + "*" + strings[loop] + ")"; ops = numops[divisor] + numops[loop] + 1; } else { ones = numints[divisor] + numints[loop] + numints[rem]; beststring = "(" + strings[divisor] + "*" + strings[loop] + "+" + strings[rem] + ")"; ops = numops[divisor] + numops[loop] + numops[rem] + 2; } } } long count = 0; long countops = 0; const int little_cutoff = 200000; int getlen(long i) { if(numints[i] == 0) { if(i < little_cutoff) get_best_for_next_full(i); else get_best_for_next_partial(i); } if(numints[i] == 0) { std::cout << i << " failure!" << numops[i] << ":" << strings[i] << std::endl; exit(1); } return numints[i] + numops[i]; } const std::vector<long> vals = {945536, 16878234, 32608778, 42017515, 48950830, 51483452, 52970263, 54278649, 63636656, 78817406, 89918907, 90757642, 95364861, 102706605, 113965374, 122448605, 126594161, 148064959, 150735075, 154382918, 172057472, 192280850, 194713795, 207721209, 220946392, 225230299, 227043979, 241011012, 248906099, 249796314, 250546528, 258452706, 276862988, 277140688, 280158490, 286074562, 308946627, 310972897, 322612091, 324445400, 336060042, 346729632, 349428326, 352769482, 363039453, 363851029, 392168304, 401975104, 407890409, 407971913, 425780757, 459441559, 465592122, 475898732, 482826596, 484263150, 506235403, 548951531, 554295842, 580536366, 587051904, 588265985, 588298051, 590968352, 601194306, 607771869, 618578932, 626776380, 667919873, 681786366, 689854904, 692055400, 697665495, 711608194, 734027104, 750869335, 757710567, 759967747, 777616154, 830071127, 833809927, 835873060, 836438554, 836945593, 863728236, 864158514, 871273503, 881615667, 891619600, 897181691, 918159061, 920521050, 924502226, 929983535, 943162304, 950210939, 950214176, 962610357, 974842859, 988572832}; const long biggest = 988572832; int main(void) { numints.push_back(2); strings.push_back("(1-1)"); numops.push_back(1); numints.push_back(1); strings.push_back("1"); numops.push_back(0); numints.push_back(2); strings.push_back("(1+1)"); numops.push_back(1); numints.resize(biggest + 1); strings.resize(biggest + 1); numops.resize(biggest + 1); fill_all_ones(biggest); fill_all_factorials(biggest); for(long i = 0; i < little_cutoff; ++i) get_best_for_next_full(i); for(long v : vals) { get_best_for_next_partial(v); std::cout << v << ":" << strings[v] << "\n"; count += numints[v]; countops += numops[v]; } std::cout << count << ":" << countops << ":" << count * countops << "\n"; } ``` Results: ``` 945536:((1111*(1+(11+11))+(1+1))*((1+11)*(1+(1+1))+1)+1) 16878234:(((1+(1+1111))*(1+(1+(1+111)))+(11+11))*((1+11)*11+1)+(1+1)) 32608778:((((((1+(1+1)))!+(111+11111))*(11*11)+111)*(1+11)+1)*(1+1)) 42017515:((11)!+((((1+111)*11)*11+1)*((1+11)*(1+11)+11))) 48950830:((((11+11)*(1+11))+(11111*(1+(1+1))))*((1+111)*(1+(1+11))+1)+1) 51483452:(((1+(1+1111))*(1+111)+1)*(11+(((1+11)*11+(1+1))*(1+(1+1))))+111) 52970263:((11+((1111*11+(1+(1+1)))*(1+(1+1))))*(111*(1+(1+11))+1)+11) 54278649:((11)!+(((1+(11+(11+(11+1111))))*111+1)*(1+(1+111))+1)) 63636656:((((11+111)*(1+(1+1)))*(1+111)+11)*(1+(111+((((1+(1+1)))!)!*(1+1))))) 78817406:(((((111*(11+11)+1)*(1+1))*(1+111)+111)*(1+11)+1)*(1+11)+(1+1)) 89918907:(((111+((1+(1+((1+(1+1)))!)))!)*(1+1))*(1+1111)+((11*11)*(1+(1+1)))) 90757642:((1111+((11+11111)*(1+1)))*(111*(11+((1+(1+(1+1))))!)+1)+(1+111)) 95364861:((11)!+(((((((11+11)*11)+11111)*111)*11+(1+1))*(1+1))*(1+1)+1)) 102706605:(((11)!+(((111+((11*11)*11))*(1+(((1+(1+1)))!)!))*11))*(1+1)+1) 113965374:((((111*(1+(1+(1+11))))*1111+((1+(11+11))*11+1))*11+1)*((1+(1+1)))!) 122448605:(((((1+(1+1)))!)!+((111*11)*11))*((1+(((1+(1+1)))!)!)*(1+11)+1)+(1+1)) 126594161:(((((11*11)+(((1+(1+1)))!)!)*(1+111))*(1+11)+1)*(1+111)+1) 148064959:((11)!+(((111*111+(1+11))*111+1)*((1+(1+11))*((1+(1+1)))!+1)+(1+(1+1)))) 150735075:(((111*111+(1+1))*(1+1111)+(1+11))*11+(1+((1+(1+1)))!)) 154382918:((1111*(1+11)+1)*(((1+(11+(111+111)))*(1+1))+11111)+111) 172057472:((((((1+11)*11)*11+1)*(1+(1+1)))+11111)*(11+11111)+((1+11)*11)) 192280850:(((11111*(1+11)+11)*(1+(((1+(1+1)))!)!)+(11+111))*(1+1)) 194713795:((11)!+((((111+11111)*(1+(1+(1+111)))+((1+(1+1)))!)*11)*11+1)) 207721209:(((111*111)*(1+(11+11))+(1+1))*(1+(1+(11+(((1+(1+1)))!)!)))+(1+(1+(1+1)))) 220946392:((11)!+((((1+(1+(1+1111)))*(11+111))*111+11)*(1+11)+(1+(1+(1+1))))) 225230299:((111111111+((111*111+(1+((1+(1+1)))!))*(11+111)+(11+11)))*(1+1)+1) 227043979:((((((11+11)*11)+11111)*(1+(1+1))+1)*1111+(1+(1+1)))*((1+(1+1)))!+1) 241011012:(((11)!+((11)!+((11)!+((11+1111)*((1+111)*((1+(1+1)))!+1)))))*(1+1)) 248906099:(((11111+(((((1+(1+1)))!)!*111)*(1+1)))*(1+111)+111)*(1+(1+11))) 249796314:(((11)!+(((((1+(1+1)))!)!+((1+1111)*(1+11)))*(11+111)+111))*((1+(1+1)))!) 250546528:((11)!+(((111*111)*(1+(1+(1+11)))+11)*(111*11)+(1+(11+1111)))) 258452706:(((11)!+(((((1+(1+1)))!)!*((1+(1+1)))!+1)*(11+(((1+(1+1)))!)!)))*((1+(1+1)))!) 276862988:(((11+(1111*(1+1)))*(((1+(1+1)))!+1111))*111+(((1+(1+1)))!+11)) 277140688:(((111*111+(1+(1+(1+(1+11)))))*(1+1))*(11+(111+11111))+(1+111)) 280158490:((11)!+(((1+(111+111111))*(((1+(1+1)))!)!+(1+(1+1)))*(1+(1+1))+1)) 286074562:(((11)!+((((11+1111)*(11+11))*(1+1)+1)*(1+(11+1111))))*(1+(1+1))+1) 308946627:((11)!+((((1+1111)*(((1+(1+1)))!)!+((11+11)*(1+1)))*(1+111)+1)*(1+(1+1)))) 310972897:((11111*(1+(1+1))+1)*(((1111+(111*11))*(1+1))*(1+1)+1)+11) 322612091:((((((1+11)*(1+11))*(1+11)+(1+1))*111+1)*(1+111))*(1+(1+(1+(1+11))))+11) 324445400:(((1111111+(1+(1+1)))*(1+1))*((1+11)*(1+11)+(1+1))+(1+111)) 336060042:(((1+1111)*(1+(11+111))+(1+111))*(11+((111*11+1)*(1+1)))+(1+1)) 346729632:(((1+(1+(11111+(111*111))))*((1+111)*11+1)+(1+(1+(1+11))))*(1+11)) 349428326:(((((11+11)*11)*11+1)*(1+1111)+1)*(1+(((1+(1+1)))!+111))) 352769482:(((1+11111)*(111*(11+11))+((11+111)*((1+1)*(1+1)+1)))*(1+(1+11))) 363039453:(((((1+111)*(1+111)+1)*(1+1))*(1+(1+11))+11)*(1+(1+1111))) 363851029:((((111*11+1)*1111+11)*((1+11)*11+(1+1))+(1+11))*(1+1)+1) 392168304:(((((1+(1+1111))*(1+111))*11+1)*(1+(1+11))+11)*(11+11)) 401975104:(((((1+11)*(1+11)+1)*111)*111+11)*((1+111)*(1+1)+1)+(1+(1+(1+1)))) 407890409:(((1+11111)*11)*((1+1111)*(1+(1+1))+1)+((1+1111)*(1+1)+1)) 407971913:((11)!+((11)!+(((1+(1+11111))*(1+1)+1)*(((11+111)*11)*11+1)+(1+1111)))) 425780757:(((1111+((((1+11)*11)+11111)*(1+(1+1))))*11+1)*1111+((1+(1+1)))!) 459441559:(((11111+(((1+(1+111))*(1+1)+1)*111))*111+1)*(1+(1+(1+111)))+(1+(1+11))) 465592122:(((11)!+((((1111*(11*(1+(1+1))+1)+1)*(1+(11+11)))*(1+1)+1)*111))*(1+1)) 475898732:(((11)!+(((((1+111)*11+(1+1))*(1+11))*(1+1)+1)*(1+(1+111))))*11+1) 482826596:(((1+(((111*11)*11)+(11111*(1+1))))*111+1)*(11+111)+((1+(1+1)))!) 484263150:(((111*111+(1+(1+1)))*111+11)*(1+(111+((11+11)*11)))) 506235403:(((1+11))!+((((1+(1+1111))*(1+1111)+((11+111)*(1+1)))*11+1)*(1+1)+1)) 548951531:((((111+111)*(1+1)+1)*111+11)*11111+((11+111)*(1+11)+1)) 554295842:(((1+11))!+((((1+1111)*111+1)*((1+1)*(1+1)+1))*(11+111)+(1+111))) 580536366:(((1+(111+((111*111+11)*(1+11))))*(1+111)+1)*(11+((1+(1+(1+1))))!)+11) 587051904:(((((1+1111)*(1+11))*(1+(1+1))+1)*(111*11+1)+(111*((1+(1+1)))!))*(1+11)) 588265985:(((1+11))!+((1+(111+(1111*(1+(1+11)))))*((1+111)*(11*((1+(1+1)))!+1)+(1+(1+1))))) 588298051:((((((11+111)*11)*11)+(11111*(1+(1+1))))*(1+1111)+1)*11) 590968352:(((((((1+(1+1)))!)!+11111)*111+(11+11))*((1+111)*(1+1)+1)+1)*(1+1)) 601194306:((((1111*(1+(1+(1+(11+111))))+1)*111+(1+1))*(1+(1+1))+1)*(1+(1+11))+11) 607771869:(((1+11))!+(((11)!+(((1111*11+1)*(1+1))*(1+(11+111))+11))*(1+(1+1)))) 618578932:(((((1111*111)*11+1)*(1+1)+1)*(1+1))*(1+(1+(1+111)))+(1+111)) 626776380:((((1+(1+(1+1))))!+((((1+(1+1)))!)!+(1111*111)))*(1+(11+((1+((1+(1+1)))!))!))) 667919873:((((((1+(11+111))*11+1)*111+(1+(1+1)))*1111+1)*(1+1))*(1+1)+1) 681786366:(((1+11))!+((11)!+(((11)!+((11)!+((1+(1+11111))*((1+11)*(1+11))+111)))*(1+1)))) 689854904:(((11+((11111+((1+1111)*11))*(1+1)))*((11+111)*11+1)+11)*11+(1+1)) 692055400:(((1+11))!+(((((1+(1+111))*(1+(1+(1+11))))*11)*11+1)*(1+(1+1111))+1)) 697665495:(((1+11))!+(((((((1+(1+1)))!)!*(1+(1+(1+111)))+1)*(1+11))*(1+1)+1)*111)) 711608194:(((11)!+(((1+(1+(1+(1+1111))))*(11+((11+111)*(1+1)))+(1+1))*1111))*(1+1)) 734027104:(((111*(11+((1+(1+(1+1))))!)+1)*(((1+(1+1)))!+11)+1)*11111+1111) 750869335:((11111111+((1+(((1+(1+1)))!)!)*((1+11)*11+1)+1))*(11*((1+(1+1)))!+1)) 757710567:((((((11+111)*11)+111111)*(1+(1+1))+1)*(1+(11+1111))+(1+(1+1)))*(1+1)+1) 759967747:(((11)!+(((1+(1+(111+11111)))*(1+(1+111)))*(1+(11+11))+1))*11) 777616154:((11111*(111+(((111*11+1)*(1+1))*(1+1)))+(11+111))*(1+(1+(1+11)))) 830071127:((((1+111)*111)*((1+(1+1)))!+1)*(((1+(1+1)))!+(11+11111))+(111*(1+1)+1)) 833809927:((((11+1111)*(1+1)+1)*111+1)*(1+(1+(11+(1111*(1+(1+1))))))+111) 835873060:(((((11+(111+111))*111+1)*(1+(1+111))+1)*(1+(1+11))+1)*(11+11)) 836438554:(((1+11))!+(((11111*(1+1)+1)*((11+(((1+(1+1)))!)!)*11+1)+1111)*(1+1))) 836945593:(((1111*1111+(1+111))*(1+(1+111))+(1+(1+1)))*((1+(1+1)))!+1) 863728236:(((1+(1111+((11+11111)*(1+1))))*(111*111+((1+(1+1)))!))*(1+(1+1))) 864158514:(((1+11))!+(((1111*(1+(1+(1+11)))+((1+(1+1)))!)*111+1)*(111*(1+1)+1)+11)) 871273503:((((1+11111)*(11+11)+1)*((1+(1+11))*(1+1)+1)+1)*((1+11)*11)+111) 881615667:((11111+((111*111+11)*(1+1)))*((111*111)*(1+1)+1)+((11+1111)*11)) 891619600:(((11)!+((11)!+((((1+(11+11))*(1+1))+111111)*11)))*11+(1+(1+1))) 897181691:((11+(11+(11+((1+(1+((1+(1+1)))!)))!)))*(11+(11111*(1+1)))+((111*11+1)*11)) 918159061:(((11)!+(((11+11)*11+1)*(1+(1+11))))*(1+(11+11))+(1+(1+(1+1)))) 920521050:(((11)!+((((1+(11+1111))*(1+(1+(1+1111))))*(1+111)+111)*(1+(1+1))))*(1+1)) 924502226:((((1111*(1+11))*(1+1)+1)*((111*(1+11)+1)*(1+1)+1))*(1+(1+11))+11) 929983535:(((11)!+((((11+111)*111+1)*111)*((1+11)*(1+1)+1)+(1+1)))*(1+11)+11) 943162304:(((11)!+((((((1+((1+(1+1)))!))!+(111*111))*111+(1+1))*(1+111))*(1+1)))*(1+1)) 950210939:(((11+(111+11111))*(1+(1+(1+(((1+(1+1)))!)!)))+(1+1))*(((1+(1+1)))!+111)+(1+1)) 950214176:(((11)!+((((111*111)*(1+(1+11)))*11+1)*((1+(11+111))*(1+1)+1)))*(1+1)) 962610357:((((1+11))!+((1+((((1+(1+1)))!)!+(111*(1+11))))*(11+1111)+(1+111)))*(1+1)+1) 974842859:((((((11*(1+((1+(1+1)))!))+1111)*11+1)*(1+111))*((1+(1+1)))!)*111+11) 988572832:(((111111111+((11111*(1+(1+1111))+11)*11+(1+(1+1))))*(1+1))*(1+1)) ``` [Answer] # Haskell **Primary score: 27242281** **Secondary score: 12/09/2016 09:01** **11891 `1`'s, 2291 operators** ``` import Data.List nums = iterate (\x -> x*10+1) 1 g n | n > a = show a ++ "+(" ++ g (n-a) ++ ")" | n < a = show a ++ "-(" ++ g (a-n) ++ ")" | otherwise = show a where a = minimumBy (\x y -> compare (abs$x-n) (abs$y-n)) . take 2 . reverse $ takeWhile (<=n*10) nums ``` It basically finds the shortest way to make it using only + and - Output: ``` 945536: 1111111-(111111+(11111+(11111+(11111+(11111+(11111-(1111-(11+(11-(1+(1))))))))))) 16878234: 11111111+(1111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111-(11111-(111+(111+(111+(111+(11+(1+(1))))))))))))))) 32608778: 11111111+(11111111+(11111111-(1111111-(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111+(1111+(111-(1))))))))))))))) 42017515: 11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(111111+(111111-(11111+(11111-(1111+(1111+(1111+(1111+(111+(111+(11+(11+(11+(11-(1+(1+(1)))))))))))))))))))))) 48950830: 11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(111+(111+(11+(11+(11+(11+(11+(1+(1+(1+(1))))))))))))))))))))))))))) 51483452: 11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(1111+(111+(11-(1+(1))))))))))))))))))))))) 52970263: 11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(111111+(111111+(111111+(11111+(11111+(11111-(1111+(1111+(1111+(111+(111+(11+(11+(11+(11-(1+(1+(1)))))))))))))))))))))))) 54278649: 11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111-(111+(111+(11+(11-(1+(1+(1+(1)))))))))))))))))))) 63636656: 111111111-(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(111111+(111111-(11111+(11111+(11111-(1111+(1111+(1111-(11))))))))))))))))) 78817406: 111111111-(11111111+(11111111+(11111111-(1111111-(111111-(11111+(11111+(11111+(11111-(1111+(1111+(1111+(1111+(111+(111+(111+(11+(11+(11+(11-(1+(1+(1+(1+(1))))))))))))))))))))))))) 89918907: 111111111-(11111111+(11111111-(1111111-(111111-(11111+(11111+(11111-(1111+(1111+(1111-(11+(11-(1+(1+(1+(1)))))))))))))))) 90757642: 111111111-(11111111+(11111111-(1111111+(1111111-(111111+(111111+(111111+(11111+(11111-(1111+(1111-(111+(11+(11+(1+(1+(1))))))))))))))))) 95364861: 111111111-(11111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111-(11111+(11111+(11111-(1111+(1111-(111+(111+(111+(111-(11+(11+(11-(1+(1+(1+(1+(1)))))))))))))))))))))))) 102706605: 111111111-(11111111-(1111111+(1111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111-(1111+(1111+(1111+(1111+(111-(11+(11+(11+(11+(11-(1+(1+(1+(1+(1)))))))))))))))))))))))))) 113965374: 111111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(111111+(11111+(11111+(11111+(1111+(111+(111-(11+(11+(11+(11-(1+(1+(1+(1))))))))))))))))))))) 122448605: 111111111+(11111111+(111111+(111111+(1111+(1111+(1111+(1111-(111+(111+(111-(11+(11+(11+(11+(11-(1+(1+(1+(1+(1)))))))))))))))))))) 126594161: 111111111+(11111111+(1111111+(1111111+(1111111+(1111111-(111111-(11111+(11111+(11111+(1111+(1111+(1111+(1111+(1111-(111+(111+(11+(11+(11+(11+(11+(1+(1+(1+(1+(1)))))))))))))))))))))))))) 148064959: 111111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(111111+(111111+(111111-(11111+(11111+(11111+(11111+(1111+(111+(111+(111+(111+(111+(11+(11+(11+(11-(1+(1+(1)))))))))))))))))))))))))) 150735075: 111111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111-(1111+(1111-(111+(111+(111+(111+(11+(11+(11+(1+(1+(1+(1)))))))))))))))))))))))))))) 154382918: 111111111+(11111111+(11111111+(11111111+(11111111-(1111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(1111-(111+(111+(111+(111-(11+(11+(11-(1+(1+(1))))))))))))))))))))))))) 172057472: 111111111+(11111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(1111111-(111111+(11111+(11111+(11111+(11111+(11111-(1111+(1111-(111+(111+(111-(11+(11+(11-(1+(1+(1+(1+(1))))))))))))))))))))))))))))) 192280850: 111111111+(111111111-(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(11111+(11111+(11111+(11111+(11111+(1111+(1111+(1111-(111+(111+(11+(11+(11+(1+(1+(1+(1+(1))))))))))))))))))))))))) 194713795: 111111111+(111111111-(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(1111111-(111111+(111111+(11111+(11111+(11111+(11111+(1111+(1111+(111+(111+(111+(111+(11+(11-(1+(1+(1+(1)))))))))))))))))))))))))) 207721209: 111111111+(111111111-(11111111+(1111111+(1111111+(1111111+(11111+(11111+(11111+(11111+(11111+(1111-(111-(11+(1+(1+(1)))))))))))))))) 220946392: 111111111+(111111111-(1111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111+(1111-(111+(111+(11+(11+(11+(11+(11-(1+(1))))))))))))))))))) 225230299: 111111111+(111111111+(1111111+(1111111+(1111111-(111111+(111111+(111111-(11111-(1111+(1111+(1111-(111+(111+(111-(11+(11+(11+(1)))))))))))))))))) 227043979: 111111111+(111111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111-(111+(111+(111+(111+(11+(11-(1+(1)))))))))))))))))))) 241011012: 111111111+(111111111+(11111111+(11111111-(1111111+(1111111+(1111111+(111111-(11111-(111-(11+(1))))))))))) 248906099: 111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(11111+(1111+(1111+(1111+(1111+(1111+(111+(111+(111+(111+(111-(11-(1)))))))))))))))))))) 249796314: 111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(1111111-(111111+(111111-(11111+(11111-(1111+(1111+(1111+(111+(111+(111+(11+(11-(1+(1+(1))))))))))))))))))))))) 250546528: 111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(111111-(11111-(1111+(1111-(111+(11+(11+(1+(1+(1+(1))))))))))))))))))))))) 258452706: 111111111+(111111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(111111-(11111-(1111+(1111+(1111-(111+(111+(111+(111+(11+(11+(11+(11-(1+(1+(1+(1))))))))))))))))))))))))))) 276862988: 111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(1111111-(111111+(111111-(11111+(11111+(1111+(1111+(1111+(111+(111+(111+(11+(1))))))))))))))))))) 277140688: 111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(1111111-(111111+(111111+(111111+(111111+(11111+(11111+(11111-(1111+(1111+(1111+(111+(111+(111+(111-(11+(11))))))))))))))))))))))) 280158490: 111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(111111+(11111+(11111+(11111+(11111+(1111+(1111+(1111-(111+(111+(111+(111-(11+(11+(11+(11+(1+(1+(1))))))))))))))))))))))))))) 286074562: 111111111+(111111111+(111111111-(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(1111+(1111+(1111-(111+(1+(1+(1+(1+(1))))))))))))))))))))))))) 308946627: 111111111+(111111111+(111111111-(11111111+(11111111+(1111111+(1111111-(11111+(11111+(11111+(11111+(11111+(1111+(1111-(11+(11+(11+(11-(1+(1+(1+(1+(1)))))))))))))))))))))) 310972897: 111111111+(111111111+(111111111-(11111111+(11111111+(111111+(11111+(11111+(1111+(1111+(1111+(1111+(111+(111+(111+(111-(11-(1+(1+(1+(1)))))))))))))))))))) 322612091: 111111111+(111111111+(111111111-(11111111-(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111+(1111-(111+(11+(11-(1+(1+(1)))))))))))))))))) 324445400: 111111111+(111111111+(111111111-(11111111-(1111111+(1111111+(1111-(111+(11+(11+(11+(11))))))))))) 336060042: 111111111+(111111111+(111111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(11+(11+(11+(11))))))))))))))))))))) 346729632: 111111111+(111111111+(111111111+(11111111+(1111111+(1111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(1111+(111+(111+(111+(11+(11+(11+(1+(1))))))))))))))))))))) 349428326: 111111111+(111111111+(111111111+(11111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(111111-(11111+(1111+(1111+(1111+(1111+(111+(111+(111+(111+(111+(11-(1+(1+(1+(1))))))))))))))))))))))))))) 352769482: 111111111+(111111111+(111111111+(11111111+(11111111-(1111111+(1111111+(111111+(111111+(111111+(111111+(111111+(11111-(1111+(1111+(111+(111+(111+(111+(111+(11+(11+(11+(1+(1+(1+(1+(1))))))))))))))))))))))))))) 363039453: 111111111+(111111111+(111111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(111111+(111111+(111111-(11111+(11111+(11111+(11111-(1111+(1111+(1111+(1111+(111+(111+(111+(111+(111-(11-(1+(1+(1)))))))))))))))))))))))))))) 363851029: 111111111+(111111111+(111111111+(11111111+(11111111+(11111111-(1111111+(1111111+(111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(111-(11+(11+(11-(1+(1+(1+(1+(1)))))))))))))))))))))))))))) 392168304: 111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111-(11111+(11111+(11111+(11111+(11111-(1111+(111+(111+(111+(111+(111-(11+(11+(11-(1+(1+(1+(1+(1))))))))))))))))))))))))))))) 401975104: 111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(11111111+(11111111-(1111111+(1111111-(111111+(111111+(11111+(11111+(1111+(1111+(111+(111+(111+(111+(11-(1+(1+(1))))))))))))))))))))))) 407890409: 111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(1111+(111+(111+(111+(111-(11+(11+(11+(1+(1)))))))))))))))))))) 407971913: 111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(111111-(11111+(11111+(1111+(1111+(1111+(1111+(1111+(111+(111+(111-(11+(11+(1)))))))))))))))))))))))) 425780757: 111111111+(111111111+(111111111+(111111111-(11111111+(11111111-(1111111+(1111111+(1111111+(111111+(111111+(1111+(1111+(1111-(111+(111+(111+(11+(11-(1+(1)))))))))))))))))))) 459441559: 111111111+(111111111+(111111111+(111111111+(11111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(111111-(1111+(1111+(1111-(111+(111+(111+(111+(1+(1+(1+(1+(1)))))))))))))))))))))))) 465592122: 111111111+(111111111+(111111111+(111111111+(11111111+(11111111-(1111111-(11111+(11111+(11111+(1111+(1111+(1111-(111-(11+(1))))))))))))))) 475898732: 111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111-(1111111+(1111111-(111111+(111111+(111111+(11111-(1111+(111+(11+(11+(11+(11+(1))))))))))))))))))) 482826596: 111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111-(111-(11+(11+(11+(11-(1))))))))))))))))))))))))))))) 484263150: 111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111+(111111+(111111-(11111+(11111+(11111+(11111-(1111+(1111+(1111+(111+(111-(11+(11+(11+(11-(1+(1+(1+(1+(1))))))))))))))))))))))))))))))) 506235403: 111111111+(111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111+(111111+(111111-(11111+(1111+(1111-(111+(11+(11+(11+(11-(1+(1)))))))))))))))))))))))))) 548951531: 111111111+(111111111+(111111111+(111111111+(111111111-(11111111-(1111111+(1111111+(1111111+(1111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111-(111+(111+(111+(111-(11+(11+(1+(1)))))))))))))))))))))))))) 554295842: 111111111+(111111111+(111111111+(111111111+(111111111-(1111111+(111111+(11111+(11111+(11111+(1111+(1111+(1111+(1111-(111+(111+(111-(11+(11+(11+(11+(1+(1+(1))))))))))))))))))))))) 580536366: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(111111-(11111+(11111-(1111+(1111+(1111-(111+(111+(111-(11+(11+(11+(1))))))))))))))))))))))))) 587051904: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111-(1111111+(1111111-(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111+(1111+(1111+(111+(111+(111-(11+(1+(1+(1+(1+(1))))))))))))))))))))))))))))) 588265985: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111-(1111111-(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111-(1111-(111+(111+(111+(111-(11+(1+(1)))))))))))))))))))))))) 588298051: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111-(111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(1111+(1111-(111+(111+(11+(11+(11+(11+(11-(1+(1+(1+(1)))))))))))))))))))))))))))) 590968352: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(1111111+(1111111-(111111+(11111+(11111+(11111-(1111+(111+(111+(111+(111+(111+(11+(11-(1+(1))))))))))))))))))))))) 601194306: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(1111111+(111111-(11111+(11111+(1111+(1111+(1111+(1111+(1111+(111+(11+(11+(1+(1+(1+(1+(1))))))))))))))))))))))))) 607771869: 111111111+(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111+(1111+(1111+(1111+(1111+(111+(111+(111+(11+(11-(1+(1)))))))))))))))))))))))) 618578932: 1111111111-(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(111111+(111111+(111111-(11111+(11111+(1111+(11+(11+(11+(11-(1+(1))))))))))))))))))))))) 626776380: 1111111111-(111111111+(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111+(111111-(1111+(111+(111+(111-(11+(11+(11+(11+(1+(1))))))))))))))))))))))) 667919873: 1111111111-(111111111+(111111111+(111111111+(111111111-(1111111+(111111+(11111+(11111+(11111-(1111+(1111+(111+(11+(1+(1+(1+(1+(1)))))))))))))))))) 681786366: 1111111111-(111111111+(111111111+(111111111+(111111111-(11111111+(1111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(111111-(11111-(1111+(1111+(111+(111+(111-(11+(11+(11-(1))))))))))))))))))))))) 689854904: 1111111111-(111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(1111111-(111111+(11111+(11111+(11111+(1111-(111+(111+(111+(111+(11+(1+(1+(1+(1))))))))))))))))))))) 692055400: 1111111111-(111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(11111+(11111+(11111+(11111+(11111+(111+(11+(11+(11+(11+(1))))))))))))))))))))) 697665495: 1111111111-(111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(11111111-(1111111+(1111111+(111111+(1111+(111-(11+(11+(11+(11+(11-(1+(1+(1+(1+(1)))))))))))))))))))))) 711608194: 1111111111-(111111111+(111111111+(111111111+(111111111-(11111111+(11111111+(11111111+(11111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111+(1111+(1111-(111+(111+(111+(111-(11+(11+(1+(1+(1+(1+(1))))))))))))))))))))))))))))))) 734027104: 1111111111-(111111111+(111111111+(111111111+(11111111+(11111111+(11111111+(11111111-(1111111-(111111+(111111+(111111+(111111-(11111+(11111+(1111+(1111+(1111+(1111+(111+(111+(111+(111-(11-(1+(1+(1+(1))))))))))))))))))))))))))) 750869335: 1111111111-(111111111+(111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(111111+(111111+(11111+(11111-(1111+(1111+(111+(111+(111+(111+(1)))))))))))))))))))) 757710567: 1111111111-(111111111+(111111111+(111111111+(11111111+(11111111-(1111111+(1111111-(111111-(11111+(11111+(11111+(11111-(111+(111+(111+(111+(111-(11)))))))))))))))))) 759967747: 1111111111-(111111111+(111111111+(111111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111-(11111+(11111+(11111-(1111-(11+(11+(11-(1+(1)))))))))))))))))) 777616154: 1111111111-(111111111+(111111111+(111111111+(111111+(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(1111+(111+(111+(111+(111+(111-(11+(11+(11+(11-(1+(1+(1))))))))))))))))))))))))) 830071127: 1111111111-(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111-(11111+(11111+(11111+(11111-(1111+(1111+(1111+(1111+(11+(1+(1+(1+(1)))))))))))))))))))))))) 833809927: 1111111111-(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(111111+(111111+(111111+(111111+(11111+(11111+(11111-(1111+(111-(11+(11+(11+(1+(1+(1+(1+(1)))))))))))))))))))))))) 835873060: 1111111111-(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(111111+(111111+(111111-(11111+(1111+(1111+(1111+(1111+(111+(111+(11+(11+(11+(11+(11-(1+(1+(1))))))))))))))))))))))))))) 836438554: 1111111111-(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111-(111111+(111111+(1111+(1111+(1111+(1111+(1111+(111+(111+(111+(1+(1+(1))))))))))))))))))))))) 836945593: 1111111111-(111111111+(111111111+(11111111+(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111+(1111+(11+(11+(11+(1+(1+(1+(1+(1)))))))))))))))))))))))))) 863728236: 1111111111-(111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(1111-(111+(111+(111+(111+(11+(1+(1))))))))))))))))))))))))))) 864158514: 1111111111-(111111111+(111111111+(11111111+(11111111+(1111111+(1111111+(111111+(111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(1111-(111+(111+(111+(11+(11+(11+(11-(1+(1))))))))))))))))))))))))) 871273503: 1111111111-(111111111+(111111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111+(1111+(1111+(1111-(111+(11+(11+(11+(11+(11+(1+(1+(1+(1)))))))))))))))))))))))))))) 881615667: 1111111111-(111111111+(111111111+(11111111-(1111111+(1111111+(1111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111+(111+(1+(1)))))))))))))))))))))) 891619600: 1111111111-(111111111+(111111111-(1111111+(1111111+(111111+(111111+(111111+(111111+(111111-(11111+(11111+(11111+(11111+(1111+(1111+(111+(111+(111+(111-(11+(11+(11+(11))))))))))))))))))))))) 897181691: 1111111111-(111111111+(111111111-(11111111-(1111111+(1111111+(111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(11111-(1111+(1111+(1111+(111+(111+(111+(111+(111+(11+(11+(1+(1)))))))))))))))))))))))))) 918159061: 1111111111-(111111111+(111111111-(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(11111+(11111+(11111+(11111+(1111+(1111+(1111+(111+(111-(11+(11+(11+(11+(1+(1+(1+(1+(1)))))))))))))))))))))))))))))) 920521050: 1111111111-(111111111+(111111111-(11111111+(11111111+(11111111-(1111111+(111111+(111111+(111111+(111111+(111111+(11111+(11111+(11111+(1111+(111-(11+(11+(11+(11+(1+(1+(1+(1+(1))))))))))))))))))))))))) 924502226: 1111111111-(111111111+(111111111-(11111111+(11111111+(11111111+(1111111+(1111111+(11111+(11111+(11111+(11111+(11111+(1111+(1111+(1+(1+(1+(1+(1))))))))))))))))))) 929983535: 1111111111-(111111111+(111111111-(11111111+(11111111+(11111111+(11111111-(1111111+(1111111+(1111111+(11111+(1111+(1111+(1111+(1111+(1111-(111+(111-(11+(11-(1)))))))))))))))))))) 943162304: 1111111111-(111111111+(11111111+(11111111+(11111111+(11111111+(11111111+(1111111+(111111+(11111+(11111+(11111+(11111+(11111+(1111+(1111+(1111+(1111-(111-(11+(11+(11-(1+(1))))))))))))))))))))))) 950210939: 1111111111-(111111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(1111111-(111111+(111111-(11111+(111+(111-(11+(11+(11+(11+(1+(1+(1+(1+(1)))))))))))))))))))))))) 950214176: 1111111111-(111111111+(11111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111+(1111111-(111111+(111111-(11111-(1111+(1111+(1111-(111+(111+(11+(11+(11+(11+(1+(1+(1))))))))))))))))))))))))) 962610357: 1111111111-(111111111+(11111111+(11111111+(11111111+(1111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(11111+(11111+(11111+(11111+(11111-(1111-(111+(111+(111+(11+(11+(1+(1)))))))))))))))))))))))) 974842859: 1111111111-(111111111+(11111111+(11111111+(1111111+(1111111+(1111111-(111111+(111111+(111111+(111111-(11111+(11111+(11111+(11111+(1111+(111+(111+(111+(111+(11+(11+(11-(1+(1)))))))))))))))))))))))) 988572832: 1111111111-(111111111+(11111111+(111111+(111111+(111111-(11111+(11111-(1111+(1111+(1111+(1111+(111+(111+(111+(111+(11+(11+(11+(11+(11+(1+(1+(1))))))))))))))))))))))) ``` [Answer] # Python, score 17136288 secondary score: 12/09/2016 08:53 (4784 ones and 3582 operations) Work in progress but OP asked for my current code... ``` # get number in factorial base, ignoring the place of 0! (always 0) r=lambda n,q=[],i=2:n and r(n//i,q+[n%i],i+1)or q # rewrite a number in a form using only 1s by converting its factorial base, the range only requires using up to 12 places, again ignoring the 0! place so we only hard code 1 and [5-12] (9 numbers) def g(n): k=['','1']+['1'+'+1'*i for i in range(1,4)]+['(11-1)/(1+1)','t(1+1+1)','1+t(1+1+1)','11-1-1-1','11-1-1','11-1','11','1+11'] q=r(n) return n<13and k[n]or(q[0]and'1+'or'')+'+'.join((v>1and'('+k[v]+')*'or'')+(i>2and't'or'')+'('+k[i]+')'for i,v in enumerate(q[1:],2)if v) #get g(n) representations after differencing from 0, 11, 111, 1111, ... then return the one with the minimal stand-alone score def h(n): o=[g(n)]+[str(v)+(v<n and'+('or'-(')+g(abs(v-n))+')'for v in[int('1'*l)for l in range(2,11)]] s=[sum(map(v.count,'+-*/t'))*v.count('1')for v in o] return o[s.index(min(s))] # A Factorial function for analysis with eval def t(n): r = 1 while n: r *= n n -= 1 return r ``` Output - note that `t` is the factorial function, so as not to be confused with `f` for `floor` if it gets used - I evaluated each using the function `t` (above) to double check that they are all correct: ``` 945536 11111111-(1+(1+1)+(1+1)*t(1+1+1)+((11-1)/(1+1))*t((11-1)/(1+1))+(t(1+1+1))*t(t(1+1+1))+(11-1-1-1)*t(11-1-1)+(1+1)*t(11-1)) 16878234 11111111+(1+(1+1+1)*t(1+1+1)+t(1+1+1+1)+((11-1)/(1+1))*t((11-1)/(1+1))+t(t(1+1+1))+(11-1-1-1)*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+t(11-1)) 32608778 111111111-(1+(1+1)*t(1+1+1)+(t(1+1+1))*t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+(t(1+1+1))*t(11-1-1)+(11-1)*t(11-1)+t(11)) 42017515 111+((1+1)*(1+1)+(1+1+1)*t((11-1)/(1+1))+((11-1)/(1+1))*t(t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+t(11)) 48950830 111+(1+t(1+1+1)+(1+1+1)*t(1+1+1+1)+(1+1+1)*t(t(1+1+1))+(11-1-1-1)*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(1+1)*t(11-1)+t(11)) 51483452 11111111+(1+(1+1)+(1+1+1)*t(1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+(1+1)*t(t(1+1+1))+(1+1)*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+t(11-1-1)+t(11)) 52970263 111111111-((1+1)+t(1+1+1)+t((11-1)/(1+1))+(t(1+1+1))*t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+t(11-1-1-1)+((11-1)/(1+1))*t(11-1)+t(11)) 54278649 1+(1+1)+t(1+1+1)+(1+1+1+1)*t(t(1+1+1))+t(1+t(1+1+1))+((11-1)/(1+1))*t(11-1-1-1)+(11-1-1)*t(11-1-1)+(1+1+1)*t(11-1)+t(11) 63636656 1111111+(1+t(1+1+1+1)+(t(1+1+1))*t(t(1+1+1))+((11-1)/(1+1))*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+(1+1)*t(11-1-1)+(t(1+1+1))*t(11-1)+t(11)) 78817406 1111+(1+t(1+1+1)+(1+1)*t(1+1+1+1)+t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(11-1)*t(11-1)+t(11)) 89918907 1+(1+1)+t(1+1+1+1)+(1+1)*t((11-1)/(1+1))+t(1+t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(1+1)*t(11-1)+(1+1)*t(11) 90757642 1111111+(1+(1+1)+(1+1)*t(1+1+1+1)+(1+1+1)*t(1+t(1+1+1))+(1+t(1+1+1))*t(11-1-1)+(1+1)*t(11-1)+(1+1)*t(11)) 95364861 11111111+((1+1)*(1+1)+(1+1+1)*t(1+1+1)+(1+1)*t(1+1+1+1)+((11-1)/(1+1))*t(1+t(1+1+1))+t(11-1-1-1)+(1+1)*t(11-1-1)+t(11-1)+(1+1)*t(11)) 102706605 1111+((1+1)+(1+1)*t(1+1+1)+(1+1+1)*t((11-1)/(1+1))+(1+1)*t(1+t(1+1+1))+(1+1+1)*t(11-1-1)+(t(1+1+1))*t(11-1)+(1+1)*t(11)) 113965374 t(1+1+1)+(1+1)*t(1+1+1+1)+t((11-1)/(1+1))+t(t(1+1+1))+(1+1+1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1)+(11-1-1)*t(11-1)+(1+1)*t(11) 122448605 111111+((1+1)+(1+1)*t(1+1+1)+t((11-1)/(1+1))+(1+1)*t(t(1+1+1))+t(1+t(1+1+1))+t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(1+1+1)*t(11)) 126594161 111111111+((1+1)+(1+1)*t(1+1+1+1)+t((11-1)/(1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+(1+1+1+1)*t(11-1)) 148064959 1111111111-((1+1+1)*t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+(11-1-1-1)*t(11-1-1-1)+(1+1+1)*t(11-1-1)+t(11-1)+(1+1)*t(1+11)) 150735075 11111111+((1+1)*(1+1)+t((11-1)/(1+1))+t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+((11-1)/(1+1))*t(11-1)+(1+1+1)*t(11)) 154382918 1111111+(1+t(1+1+1)+(1+1+1)*t((11-1)/(1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1)*t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1-1)*t(11-1)+(1+1+1)*t(11)) 172057472 1111+(1+t((11-1)/(1+1))+t(t(1+1+1))+(1+1)*t(1+t(1+1+1))+t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(1+1+1)*t(11-1)+(1+1+1+1)*t(11)) 192280850 1111111111-(1+(1+1)*(1+1)+(1+1+1+1)*t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1)*t(11-1-1)+(11)*t(11)+t(1+11)) 194713795 111111111+((1+1)*(1+1)+((11-1)/(1+1))*t((11-1)/(1+1))+((11-1)/(1+1))*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1)*t(11-1-1-1)+t(11-1)+(1+1)*t(11)) 207721209 111111+((1+1+1)*t(1+1+1)+(1+1)*t((11-1)/(1+1))+(1+1+1)*t(t(1+1+1))+t(11-1-1-1)+(1+1)*t(11-1-1)+(1+1)*t(11-1)+((11-1)/(1+1))*t(11)) 220946392 111111111+(1+((11-1)/(1+1))*t(t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1-1-1)*t(11-1)+(1+1)*t(11)) 225230299 1111111111-((1+1)*t(1+1+1)+(1+1)*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+t(11-1-1)+(1+1)*t(11-1)+(11-1)*t(11)+t(1+11)) 227043979 1111111111-((1+1)*t(1+1+1)+t(t(1+1+1))+(1+1)*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+(t(1+1+1))*t(11-1-1)+t(11-1)+(11-1)*t(11)+t(1+11)) 241011012 11+(1+(1+1+1)*t((11-1)/(1+1))+(1+1+1+1)*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(t(1+1+1))*t(11)) 248906099 11+((1+1)*t(1+1+1+1)+((11-1)/(1+1))*t((11-1)/(1+1))+(1+1)*t(1+t(1+1+1))+(11-1-1-1)*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+(1+1)*t(11-1)+(t(1+1+1))*t(11)) 249796314 111111+(1+(1+1)+((11-1)/(1+1))*t(t(1+1+1))+(1+1+1+1)*t(1+t(1+1+1))+(11-1-1-1)*t(11-1-1)+(1+1)*t(11-1)+(t(1+1+1))*t(11)) 250546528 111+(1+(1+1+1+1)*t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+(1+1+1)*t(11-1-1-1)+(1+1+1)*t(11-1)+(t(1+1+1))*t(11)) 258452706 11+(1+t(1+1+1)+(1+1)*t(1+1+1+1)+(1+1)*t(t(1+1+1))+(1+1)*t(11-1-1-1)+(1+1)*t(11-1-1)+((11-1)/(1+1))*t(11-1)+(t(1+1+1))*t(11)) 276862988 111+(1+(1+1)*(1+1)+(1+1+1)*t(1+1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+((11-1)/(1+1))*t(1+t(1+1+1))+(11-1-1-1)*t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1)*t(11-1)+(t(1+1+1))*t(11)) 277140688 1111+(1+(1+1)+t(1+1+1)+(1+1)*t(1+1+1+1)+(1+1+1+1)*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1+1)*t(11-1-1)+(11-1)*t(11-1)+(t(1+1+1))*t(11)) 280158490 (1+1)*(1+1)+t(1+1+1)+(1+1+1)*t(1+t(1+1+1))+(1+1)*t(11-1-1)+(1+t(1+1+1))*t(11) 286074562 1111+(1+(1+1)+(1+1)*t(1+1+1+1)+t((11-1)/(1+1))+(1+1+1+1)*t(t(1+1+1))+(1+1+1)*t(11-1-1-1)+(11-1-1-1)*t(11-1-1)+t(11-1)+(1+t(1+1+1))*t(11)) 308946627 11111+((1+1)*(1+1)+(1+1+1)*t(1+1+1+1)+((11-1)/(1+1))*t(t(1+1+1))+(1+1+1)*t(11-1-1-1)+t(11-1-1)+(11-1-1-1)*t(11-1)+(1+t(1+1+1))*t(11)) 310972897 111111111+((1+1)*(1+1)+t(1+1+1)+(1+1+1+1)*t(1+1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+((11-1)/(1+1))*t(11)) 322612091 11+((1+1)*t((11-1)/(1+1))+(1+1)*t(t(1+1+1))+(1+1)*t(1+t(1+1+1))+(11-1-1)*t(11-1-1)+(11-1-1-1)*t(11)) 324445400 1111+(1+(1+1)*t(1+1+1+1)+(t(1+1+1))*t(t(1+1+1))+((11-1)/(1+1))*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1)+t(11-1)+(11-1-1-1)*t(11)) 336060042 11+(1+t(1+1+1)+t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1)+(1+1+1+1)*t(11-1)+(11-1-1-1)*t(11)) 346729632 11111+(1+(1+1+1)*t((11-1)/(1+1))+(1+1)*t(t(1+1+1))+t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+(1+t(1+1+1))*t(11-1)+(11-1-1-1)*t(11)) 349428326 11+(1+(1+1)+(1+1+1)*t(1+1+1+1)+(1+1+1)*t(1+t(1+1+1))+(11-1-1-1)*t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1-1-1)*t(11-1)+(11-1-1-1)*t(11)) 352769482 1111+(1+(1+1)+(1+1)*t(1+1+1+1)+((11-1)/(1+1))*t(t(1+1+1))+t(1+t(1+1+1))+t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1-1)*t(11-1)+(11-1-1-1)*t(11)) 363039453 111111+(t(1+1+1)+(1+1+1+1)*t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+t(1+t(1+1+1))+t(11-1-1-1)+t(11-1)+(11-1-1)*t(11)) 363851029 1111+(t(1+1+1)+(1+1+1)*t(1+1+1+1)+(1+1+1)*t(t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+t(11-1)+(11-1-1)*t(11)) 392168304 11111111+(1+(1+1+1)*t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+(t(1+1+1))*t(11-1)+(11-1-1)*t(11)) 401975104 1111111+(1+(1+1)+t(1+1+1)+t(1+1+1+1)+(1+1+1)*t((11-1)/(1+1))+(1+1+1)*t(t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(11-1)*t(11)) 407890409 11111+((1+1+1)*t(1+1+1)+(1+1+1)*t(t(1+1+1))+(1+1+1+1)*t(11-1-1)+(1+1)*t(11-1)+(11-1)*t(11)) 407971913 11111+((1+1+1)*t(1+1+1)+t(1+1+1+1)+t((11-1)/(1+1))+(1+1+1+1)*t(t(1+1+1))+(1+1)*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(1+1)*t(11-1)+(11-1)*t(11)) 425780757 111+(t(1+1+1)+(1+1)*t(t(1+1+1))+(1+1+1)*t(11-1-1-1)+(1+1+1)*t(11-1-1)+(1+t(1+1+1))*t(11-1)+(11-1)*t(11)) 459441559 1111111+((1+1)*t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+(1+1)*t(1+t(1+1+1))+(1+1+1)*t(11-1-1)+((11-1)/(1+1))*t(11-1)+(11)*t(11)) 465592122 1111+(1+(1+1)*(1+1)+t(1+1+1)+t((11-1)/(1+1))+t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1)*t(11-1-1)+(1+t(1+1+1))*t(11-1)+(11)*t(11)) 475898732 11111+(1+(1+1)+(1+1+1)*t(1+1+1)+t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+(1+1+1)*t(11-1-1-1)+t(11-1-1)+(11-1)*t(11-1)+(11)*t(11)) 482826596 111111+(1+(1+1)*(1+1)+t((11-1)/(1+1))+(t(1+1+1))*t(t(1+1+1))+(1+1)*t(11-1-1-1)+t(11-1)+t(1+11)) 484263150 t(1+1+1)+t(1+1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+(t(1+1+1))*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+t(11-1)+t(1+11) 506235403 1111+((1+1)*t(1+1+1)+t((11-1)/(1+1))+(1+1)*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+((11-1)/(1+1))*t(11-1-1)+(1+t(1+1+1))*t(11-1)+t(1+11)) 548951531 11+((1+1+1+1)*t((11-1)/(1+1))+(t(1+1+1))*t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1-1-1)*t(11-1)+t(11)+t(1+11)) 554295842 (1+1)+(1+1)*t((11-1)/(1+1))+(1+1)*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(11-1-1)*t(11-1)+t(11)+t(1+11) 580536366 1111111111-(1+t(1+1+1+1)+(1+1)*t((11-1)/(1+1))+((11-1)/(1+1))*t(t(1+1+1))+t(11-1-1-1)+(1+1)*t(11-1-1)+(1+1+1)*t(11-1)+t(11)+t(1+11)) 587051904 1111111111-(1+t(1+1+1)+(1+1+1+1)*t(1+t(1+1+1))+t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+t(11-1)+t(11)+t(1+11)) 588265985 11+(t(1+1+1)+(1+1)*t(1+1+1+1)+(1+1+1)*t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+t(11-1-1)+(11-1-1-1)*t(11-1)+(1+1)*t(11)+t(1+11)) 588298051 11111111+((1+1)+(1+1+1)*t(1+1+1)+(1+1+1)*t((11-1)/(1+1))+t(t(1+1+1))+t(1+t(1+1+1))+((11-1)/(1+1))*t(11-1-1-1)+((11-1)/(1+1))*t(11-1)+(1+1)*t(11)+t(1+11)) 590968352 1111111+(1+t((11-1)/(1+1))+t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+(11-1-1-1)*t(11-1)+(1+1)*t(11)+t(1+11)) 601194306 1111111+(1+(1+1)*(1+1)+t(1+1+1)+t(1+1+1+1)+((11-1)/(1+1))*t((11-1)/(1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1+1)*t(11-1-1)+(1+1+1)*t(11)+t(1+11)) 607771869 1111111+((1+1)+(1+1)*t(1+1+1)+t(1+1+1+1)+(1+1)*t((11-1)/(1+1))+t(t(1+1+1))+t(1+t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+t(11-1-1)+(1+1)*t(11-1)+(1+1+1)*t(11)+t(1+11)) 618578932 111111111+(1+(1+1)*t(1+1+1)+(1+1)*t(1+1+1+1)+(1+1)*t((11-1)/(1+1))+(1+1+1+1)*t(11-1-1-1)+(11-1-1-1)*t(11-1-1)+(1+t(1+1+1))*t(11-1)+t(1+11)) 626776380 1111+(1+(1+1)*(1+1)+t(1+1+1+1)+t((11-1)/(1+1))+t(t(1+1+1))+(1+1)*t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(1+t(1+1+1))*t(11-1)+(1+1+1)*t(11)+t(1+11)) 667919873 111111+((1+1)+t((11-1)/(1+1))+((11-1)/(1+1))*t(t(1+1+1))+((11-1)/(1+1))*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+(11-1-1-1)*t(11-1)+(1+1+1+1)*t(11)+t(1+11)) 681786366 t(1+1+1)+(1+1+1)*t((11-1)/(1+1))+(1+1+1)*t(1+t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+(11-1-1-1)*t(11-1-1)+((11-1)/(1+1))*t(11)+t(1+11) 689854904 1111+(1+(1+1+1)*t(1+1+1+1)+t((11-1)/(1+1))+((11-1)/(1+1))*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+t(11-1-1)+(1+1+1)*t(11-1)+((11-1)/(1+1))*t(11)+t(1+11)) 692055400 11+(1+(1+1)*(1+1)+t(1+1+1+1)+(1+1+1+1)*t(t(1+1+1))+t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(1+1+1)*t(11-1)+((11-1)/(1+1))*t(11)+t(1+11)) 697665495 1111111111-((1+1)*(1+1)+(1+1)*t(1+1+1)+(t(1+1+1))*t(t(1+1+1))+(1+1+1)*t(11-1-1-1)+(11-1-1)*t(11-1-1)+(1+1+1)*t(11-1)+(11-1)*t(11)) 711608194 (1+1)*(1+1)+t(1+1+1)+t(1+1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+t(11-1-1)+(11-1-1)*t(11-1)+((11-1)/(1+1))*t(11)+t(1+11) 734027104 11+(1+(1+1)*(1+1)+(1+1)*t(1+1+1+1)+(1+1)*t(t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+(1+1+1+1)*t(11-1)+(t(1+1+1))*t(11)+t(1+11)) 750869335 111111111+((1+1)*(1+1)+(1+1)*t(1+1+1)+(1+1)*t(1+1+1+1)+t(t(1+1+1))+(1+1+1)*t(11-1-1)+(1+1+1+1)*t(11)+t(1+11)) 757710567 11111+((1+1)*(1+1)+(1+1)*t(1+1+1)+(1+1)*t((11-1)/(1+1))+t(t(1+1+1))+t(1+t(1+1+1))+(11-1-1-1)*t(11-1-1)+(11-1)*t(11-1)+(t(1+1+1))*t(11)+t(1+11)) 759967747 1111+((1+1)*t(1+1+1)+t(1+1+1+1)+t((11-1)/(1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1)*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(1+t(1+1+1))*t(11)+t(1+11)) 777616154 11111+(1+(1+1)+((11-1)/(1+1))*t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+((11-1)/(1+1))*t(11-1)+(1+t(1+1+1))*t(11)+t(1+11)) 830071127 1111+((1+1)*(1+1)+(1+1)*t(1+1+1)+(1+1+1)*t(t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(11-1-1-1)*t(11-1)+(11-1-1-1)*t(11)+t(1+11)) 833809927 1111111111-(t(1+1+1+1)+(1+1+1)*t((11-1)/(1+1))+(1+1+1+1)*t(1+t(1+1+1))+t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(11-1)*t(11-1)+(t(1+1+1))*t(11)) 835873060 1111111111-(1+(1+1)+(1+1)*t(1+1+1+1)+((11-1)/(1+1))*t(t(1+1+1))+(1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+(11-1-1-1)*t(11-1-1)+(11-1-1)*t(11-1)+(t(1+1+1))*t(11)) 836438554 111+(1+(1+1+1)*t(1+1+1)+t(1+1+1+1)+((11-1)/(1+1))*t(11-1-1)+(11-1)*t(11-1)+(11-1-1-1)*t(11)+t(1+11)) 836945593 11111111+((1+1)+(1+1)*t((11-1)/(1+1))+(1+t(1+1+1))*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+(1+t(1+1+1))*t(11-1)+(11-1-1-1)*t(11)+t(1+11)) 863728236 1111+(1+(1+1)*(1+1)+(1+1+1)*t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+t(11-1-1-1)+(1+t(1+1+1))*t(11-1)+(11-1-1)*t(11)+t(1+11)) 864158514 111+(1+(1+1)+(1+1+1+1)*t(1+t(1+1+1))+(1+1+1)*t(11-1-1-1)+t(11-1-1)+(1+t(1+1+1))*t(11-1)+(11-1-1)*t(11)+t(1+11)) 871273503 111111111+((1+1+1)*t(1+1+1+1)+(t(1+1+1))*t(t(1+1+1))+t(1+t(1+1+1))+(1+t(1+1+1))*t(11-1-1-1)+(1+1+1+1)*t(11-1-1)+(1+t(1+1+1))*t(11)+t(1+11)) 881615667 111+((1+1)*t(1+1+1)+t(1+1+1+1)+((11-1)/(1+1))*t(t(1+1+1))+(1+1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+(11-1-1)*t(11-1-1)+(11-1)*t(11)+t(1+11)) 891619600 1111111+(1+(1+1)+t(1+1+1)+(1+1)*t((11-1)/(1+1))+t(t(1+1+1))+(1+1+1+1)*t(11-1-1)+(1+1+1)*t(11-1)+(11-1)*t(11)+t(1+11)) 897181691 111111+((1+1)+(1+1+1)*t(1+1+1)+(1+1)*t((11-1)/(1+1))+t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+(1+1)*t(11-1-1)+((11-1)/(1+1))*t(11-1)+(11-1)*t(11)+t(1+11)) 918159061 1111+(t(1+1+1)+t(1+1+1+1)+(1+1)*t((11-1)/(1+1))+t(t(1+1+1))+(t(1+1+1))*t(1+t(1+1+1))+t(11-1-1-1)+(11)*t(11)+t(1+11)) 920521050 11111+(1+(1+1+1)*t(1+1+1)+(t(1+1+1))*t(t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(t(1+1+1))*t(11-1-1)+(11)*t(11)+t(1+11)) 924502226 (1+1)+t(1+1+1+1)+((11-1)/(1+1))*t((11-1)/(1+1))+(t(1+1+1))*t(t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+t(11-1)+(11)*t(11)+t(1+11) 929983535 1111111111-((1+1)+t(1+1+1)+(1+1)*t(1+1+1+1)+(1+1)*t(1+t(1+1+1))+t(11-1-1-1)+(11-1-1)*t(11-1-1)+((11-1)/(1+1))*t(11-1)+(1+1+1+1)*t(11)) 943162304 1111+(1+(1+1+1)*t(1+1+1+1)+t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+(11-1-1)*t(11-1-1)+(t(1+1+1))*t(11-1)+(11)*t(11)+t(1+11)) 950210939 111111111+((1+1)+(1+1+1)*t(1+1+1)+(1+1)*t(1+1+1+1)+(1+1)*t((11-1)/(1+1))+(1+1+1)*t(11-1-1-1)+(1+1)*t(11-1-1)+(11-1-1)*t(11)+t(1+11)) 950214176 1111111+(1+t(1+1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+(1+1)*t(1+t(1+1+1))+(1+1+1+1)*t(11-1-1-1)+((11-1)/(1+1))*t(11-1-1)+(11-1-1-1)*t(11-1)+(11)*t(11)+t(1+11)) 962610357 111+(t(1+1+1)+(1+1+1+1)*t((11-1)/(1+1))+(1+1)*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+1)*t(11-1-1)+t(11-1)+(1+1)*t(1+11)) 974842859 111111+((1+1)+(1+1+1)*t(1+1+1)+(1+1)*t(1+1+1+1)+t(t(1+1+1))+(1+t(1+1+1))*t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1)+(1+1+1+1)*t(11-1)+(1+1)*t(1+11)) 988572832 1111111111-(1+(1+1)+(1+1)*t(1+1+1)+t(1+1+1+1)+t(t(1+1+1))+t(1+t(1+1+1))+(t(1+1+1))*t(11-1-1-1)+(1+t(1+1+1))*t(11-1-1)+(1+1+1)*t(11)) ``` [Answer] ## JavaScript (ES6), 27212498, 2016-09-12 09:46:34Z ``` f=(n,a='+',s='-',m=n*9+'',r=m.replace(/./g,1))=>r-n?m<'55'?--r/10+a+f(n-r/10,a,s):r+s+f(r-n,s,a):r; s = ''; [945536, 16878234, 32608778, 42017515, 48950830, 51483452, 52970263, 54278649, 63636656, 78817406, 89918907, 90757642, 95364861, 102706605, 113965374, 122448605, 126594161, 148064959, 150735075, 154382918, 172057472, 192280850, 194713795, 207721209, 220946392, 225230299, 227043979, 241011012, 248906099, 249796314, 250546528, 258452706, 276862988, 277140688, 280158490, 286074562, 308946627, 310972897, 322612091, 324445400, 336060042, 346729632, 349428326, 352769482, 363039453, 363851029, 392168304, 401975104, 407890409, 407971913, 425780757, 459441559, 465592122, 475898732, 482826596, 484263150, 506235403, 548951531, 554295842, 580536366, 587051904, 588265985, 588298051, 590968352, 601194306, 607771869, 618578932, 626776380, 667919873, 681786366, 689854904, 692055400, 697665495, 711608194, 734027104, 750869335, 757710567, 759967747, 777616154, 830071127, 833809927, 835873060, 836438554, 836945593, 863728236, 864158514, 871273503, 881615667, 891619600, 897181691, 918159061, 920521050, 924502226, 929983535, 943162304, 950210939, 950214176, 962610357, 974842859, 988572832].forEach(n => { s += f(n); console.log(n, f(n)); }); l = s.match(/1/g).length; console.log((s.length - l) * l); ``` Only uses + and -. Based on my answer to [Minimize Those Ones](https://codegolf.stackexchange.com/questions/79207/minimize-those-ones/79226) [Answer] # Python **Primary Score = 2214138604871819402525** **Secondary Score = 12/09/2016, 07:53** Here is the code: ``` def print_1s(n): return ("1+" * n)[:-1] ``` Just to get the ball rollin'. Basically outputs `1+1+1...+1`, where the number of `1`'s in the outputted expression is equal to `n`. In total, there are `47054634305` `1`'s for the set of numbers, and `47054634205` operators (which are all `+`'s). Not going to post a pastebin here, because you get the idea. [Answer] # awk **primary score 46933701** **secondary score 12/09/2016 19:20** **(6901 ones, 6801 ops)** ``` { for(b=""; $0; $0=int($0/2)) b=and($0, 1) b for(chall=""; length(b=substr(b,2)); ) { if(chall!="") chall=chall"*" chall=chall"(1+1)" if(substr(b, 1, 1)=="1") { chall=chall"+1" if(length(b)>1) chall="("chall")" } } print chall } ``` Simply prints the binary representation calculated from left to right. For example 19 is 10011 which is (((((**1**)\*2+**0**)\*2+**0**)\*2+**1**)\*2+**1**). I just leave out the `+0` and write the `2` as `(1+1)`. I was just curious about how this method would be scoring. Output: ``` 945536: (((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 16878234: (((((((((1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 32608778: (((((((((((1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 42017515: ((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 48950830: ((((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1) 51483452: ((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1) 52970263: ((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 54278649: (((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1 63636656: (((((((((((1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1) 78817406: ((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1) 89918907: ((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 90757642: ((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 95364861: (((((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1 102706605: (((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1 113965374: (((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1) 122448605: (((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1 126594161: ((((((((((((((1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1 148064959: (((((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 150735075: ((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 154382918: (((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1) 172057472: (((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 192280850: ((((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 194713795: (((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 207721209: (((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1 220946392: (((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1) 225230299: ((((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 227043979: ((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 241011012: (((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1) 248906099: (((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 249796314: (((((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 250546528: ((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 258452706: (((((((((((((((((1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 276862988: (((((((1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1) 277140688: ((((((((((1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1) 280158490: ((((((((((((1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 286074562: (((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 308946627: ((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 310972897: ((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1 322612091: (((((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 324445400: ((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1) 336060042: ((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 346729632: ((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 349428326: ((((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1) 352769482: ((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 363039453: (((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1 363851029: (((((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1 392168304: (((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1) 401975104: ((((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 407890409: ((((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1 407971913: (((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1 425780757: ((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1 459441559: ((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 465592122: ((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 475898732: ((((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1) 482826596: (((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1) 484263150: (((((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1) 506235403: ((((((((((((1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 548951531: ((((((((((((((1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 554295842: ((((((((((1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 580536366: ((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1) 587051904: (((((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 588265985: ((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1 588298051: ((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 590968352: (((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 601194306: (((((((((((((((((1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 607771869: ((((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1 618578932: (((((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1) 626776380: (((((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1) 667919873: ((((((((((((((1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1 681786366: ((((((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1) 689854904: (((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1) 692055400: ((((((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1) 697665495: ((((((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 711608194: (((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 734027104: (((((((((((((1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 750869335: (((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 757710567: ((((((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 759967747: ((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 777616154: (((((((((((((((((1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 830071127: ((((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 833809927: (((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 835873060: (((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1) 836438554: ((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 836945593: (((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1 863728236: ((((((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1) 864158514: (((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 871273503: (((((((((((((((((1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 881615667: (((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1 891619600: ((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1) 897181691: (((((((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 918159061: ((((((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1 920521050: ((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1) 924502226: (((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1) 929983535: ((((((((((((((((((1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1 943162304: (((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 950210939: ((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 950214176: ((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) 962610357: ((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1 974842859: ((((((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1 988572832: (((((((((((((((1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)*(1+1)*(1+1)*(1+1) ``` [Answer] # Python 3 **Primary Score: `69720516`** **Secondary Score: `09:30 14/09/2016`** ``` def genNum(num): dic = { 6: "(1+1+1)!", 24: "(1+1+1+1)!", 120: "((1+1+1)!-1)!", 720: "((1+1+1)!)!", 5040: "((1+1+1)!+1)!", 40320: "((1+1+1)!+1+1)!", 362880: "(11-1-1)!", 39916800: "(11)!", 479001600: "(11+1)!", 6227020800: "(11+1+1)!" } lis = [6227020800,479001600,39916800,362880,40320,5040,720,120,24,6] out = "" for i in lis: if num/i >= 1: st = dic[i] + "*(" + genNum(num // i) + ")" out += st if num%i != 0: out += "+" + genNum(num%i) return out else: st = "1+"*num return st[:-1] ``` ***Edit:*** Now uses multiplication to greatly reduce the score. This makes great use of factorials and recursion. In total, the program uses: * **`5958` ones** * **`11702` operators** [**Ideone it!**](https://ideone.com/mDspXr) [Answer] # JAVA **Primary Score** `1045978739` **Secondary score** `12/09/2016 16:05` 37193 `1s` 28123 `operators` ``` void main() { int arr[]={945536, 16878234, 32608778, 42017515, 48950830, 51483452, 52970263, 54278649, 63636656, 78817406, 89918907, 90757642, 95364861, 102706605, 113965374, 122448605, 126594161, 148064959, 150735075, 154382918, 172057472, 192280850, 194713795, 207721209, 220946392, 225230299, 227043979, 241011012, 248906099, 249796314, 250546528, 258452706, 276862988, 277140688, 280158490, 286074562, 308946627, 310972897, 322612091, 324445400, 336060042, 346729632, 349428326, 352769482, 363039453, 363851029, 392168304, 401975104, 407890409, 407971913, 425780757, 459441559, 465592122, 475898732, 482826596, 484263150, 506235403, 548951531, 554295842, 580536366, 587051904, 588265985, 588298051, 590968352, 601194306, 607771869, 618578932, 626776380, 667919873, 681786366, 689854904, 692055400, 697665495, 711608194, 734027104, 750869335, 757710567, 759967747, 777616154, 830071127, 833809927, 835873060, 836438554, 836945593, 863728236, 864158514, 871273503, 881615667, 891619600, 897181691, 918159061, 920521050, 924502226, 929983535, 943162304, 950210939, 950214176, 962610357, 974842859, 988572832 }; int sum=1; for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+":"); while(arr[i]>11){ System.out.print("("+"1"); sum=11; while(sum<=arr[i]){ if(sum<=arr[i]) System.out.print("*11"); sum*=11; } arr[i]=arr[i]-sum/11; System.out.print(")"); if(arr[i]!=0) System.out.print("+"); } while(arr[i]--!=0){ System.out.print(1); if(arr[i]!=0) System.out.print("+"); } System.out.println(); } } ``` ``` 945536:(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1 16878234:(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1+1 32608778:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+1+1+1+1 42017515:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+1 48950830:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1 51483452:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+1+1+1+1+1+1+1+1+1 52970263:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1 54278649:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1 63636656:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1 78817406:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1 89918907:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1 90757642:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+1+1+1+1+1+1+1+1 95364861:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1 102706605:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1 113965374:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1 122448605:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1 126594161:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1 148064959:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1 150735075:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1 154382918:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1 172057472:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1 192280850:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1 194713795:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1 207721209:(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11)+(1*11)+1+1+1 220946392:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+1+1+1+1+1+1+1+1+1 225230299:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1+1 227043979:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1+1 241011012:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1 248906099:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+1+1+1+1 249796314:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1+1+1 250546528:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1 258452706:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1 276862988:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1 277140688:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1 280158490:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1+1+1+1 286074562:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1 308946627:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1 310972897:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1 322612091:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1 324445400:(1*11*11*11*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+(1*11)+1+1+1+1+1+1 ``` [Answer] # Emacs Lisp **Primary score: 81638725** **Secondary score: 12/09/2016 09:35** ``` (defun 1s (n) (let((x 1)r) (while (> (/ n x) 11) (setq x (1+ (* x 10)))) (while (> n 0) (while (>= n x) (push x r) (push '+ r) (setq n (- n x))) (setq x (/ x 10))) r)) ``` Basically builds a sum over the domain (1, 11, 111, ...) which is equivalent to n. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 15642720 Secondary Score=30/05/2017, 21:11 ``` BEGIN{RS="[,\n]"} func f2(x) { div=int(x/11) mod=x%11 } func trans(z){ r="" if (z > 6) { r="11" for (i=11;i>z;i--){ r=r"-1" } } else if (z>0){ r=r 1 for (i=1;i<z;i++){ r=r"+1" } } } {n=$1 do {f2(n) trans(mod) if (r) s=s"(" r ")" if(div){ if (r)s=s"+" s=s"11*(" count++ } n=div } while(div >10) trans(div) s = s r for (i=0;i<count;i++)s = s")" print $1": " s slength+=length(s) ones+=gsub("1","",s); parens+=gsub("[()]","",s); ops+=length(s); s="" count=0; } END { print "Total string length: " slength print "Ones: " ones print "Ops: " ops print "Parens: " parens print "Primary Score="ones*ops } ``` [Try it online!](https://tio.run/nexus/awk#VVNNbxtHDL3rVwwWKSBFMkrOBzmsuz4UDYpc0qLpLc3BtWVHgLMyduU2teHf7j7Oyo0DSau3Mxy@R/LN009vfnn77uH39333YfPn8LF7XFzdDRfhKi6/rMLDIoTL3d/9bjgsv3zPvML75/1l/@U75sUx8jCeD9PyfuWxY991@NtdheV9OAsyZ2jrzF2DV/sxLHc98@nu7P50d3KymkM8aOxOjlGPeD6G7c20nZOd0eo50xj4m0Snux@RZ73@Js/6ZR4ofRj6Vzh2uQ8PqGzwOo7CUU57c5pxFaZ@6pZdGEPoVt28vkQHnpPPUR60ngnaAebXy@Prxf5uOKzXiyN3GHqcXqCWfz7tbraeKpwxgXFm99SLMIUev3HxXBOhppao1dV2m5rbEYMIr7j7IXRhwrmb7XB9@LTu5//lhFz7YTut@@vp7q9lx92m6zbT6hRHz8ft8P/Gh@Xq49e9/e30IgUWpjbGpgBa0L43735uk5wFdH/sD@c3YTrg7TrMB5uiGX6N@xVafMM1vVi9nRdvX6z91uT58iz0xc64@3w@/hveX@zHbd95qtd@9HHx9GS5lCSbwFK1xpQ3IUWhqlo3IUdiLVyAqhWqiTahcK4plwgUTSlKAspRq2TbBEn4SEE@rZU1E1A142qkm4BHUck4a@DMVRi8FJVECCTMyaQkhQaOMWO/rUYplrnF5kqgKSDiQprw84CSU43gANRIRbOCgS3GSrWQw6yc1BAbSTVyJGSIeGZJFh2WmChaW1XKydRhZmJ8PQD1k1ALyNiUxBAZC5UsJVaHFT1RLzeqVIlWfVWV0YIGKzFijBwKaS6CvIkqNEhEbxKTaazmMEZxjeww51wy4VhKAgnk3UtZNEJEg5ZjxcgAIUAsV1@VRAmTTQ3WgiZDOmrFlBNBeiY2THaGiuKytwTQlI2Tj75o9XEBov2Zi3cd1RYkiaDIWqpVdQ2grD4kcZjhCPauF5KYIL35A/bhklBQgVcMjXD/VCrNLg6VCpvLKbXlqmWGhiA/ZmSQ7rYTDMVy8lajj@hwFTceVwg2lyNRVFE1NIiosasEhB3rzCYQXnJjE4Nh5v6KKZyb3SXKjCsAFsCUYdDWKMUNEEvJAwp4qYg6NANfdgha@LQgFl0mZPHB1gQpZjNEoVBODgWuLXOs@CU0iIRAeCD6fcR9gmGK@6wqEsHsHlCdQJy4GqCJS4drGBtuGFwDRrP8tnhpESrJYS4Uo7vEYHPo8CrQRcaMvDbcboRasiPMrB6LVjIlN4Gpj7a6CWDtou65/wA "AWK – TIO Nexus") Ones: 4590 Ops: 3408 Primary Score=15642720 Secondary Score=30/05/2017 21:11 ]
[Question] [ Determining whether a Turing machine halts is well known to be undecidable, but that's not necessarily true for simpler machines. A *Foo machine* is a machine with a finite tape, where each cell on the tape has an integer or the halt symbol `h`, e.g. `2 h 1 -1` The instruction pointer starts by pointing to the first cell: ``` 2 h 1 -1 ^ ``` At every step, the instruction pointer moves forward by the number it points to, then negates that number. So, after one step, it would move forward `2` cells, and turn the `2` into a `-2`: ``` -2 h 1 -1 ^ ``` The Foo machine keeps doing this until the instruction pointer is pointing to the halt symbol (`h`). So, here is the full execution of this program: ``` 2 h 1 -1 ^ -2 h 1 -1 ^ -2 h -1 -1 ^ -2 h -1 1 ^ -2 h 1 1 ^ ``` The tape is also circular, so if the instruction pointer moves off of one side of the tape, it goes to the other side, e.g.: ``` 3 h 1 3 ^ -3 h 1 3 ^ -3 h 1 -3 ^ -3 h -1 -3 ^ -3 h -1 3 ^ 3 h -1 3 ^ ``` One interesting thing about these Foo machines is that some do not halt, e.g.: ``` 1 2 h 2 ^ -1 2 h 2 ^ -1 -2 h 2 ^ -1 -2 h -2 ^ -1 2 h -2 ^ -1 2 h 2 ^ ``` This program will continue looping in those last four states forever. So, write a program which determines if a Foo machine halts or not! You can use any (reasonable) input format you like for the Foo machines, and you can choose to use `0` as the halt symbol. You can use any two distinct outputs for the case where it does halt and the case where it doesn't. Your program must, of course, output an answer in a finite amount of time for all valid inputs. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make your program as short as possible! ## Test cases ``` 2 h 1 -1 Halts 3 h 1 3 Halts h Halts 1 1 1 1 h Halts 2 1 3 2 1 2 h Halts 3 2 1 1 4 h Halts 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 h -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 Halts 2 h Does not halt 1 2 h 2 Does not halt 8 1 2 3 3 4 8 4 3 2 h Does not halt 1 2 4 3 h 2 4 5 3 Does not halt 3 1 h 3 1 1 Does not halt 1 2 h 42 Does not halt ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 71 bytes ``` x=>{for(int i=0,k=0,f=x.Count;i++<1<<f;k%=f)k-=(x[k]*=-1)%f-f;i/=x[k];} ``` [Try it online!](https://tio.run/##fVDLTsMwEDzHX7FEqpRQp82jSBWOixAcAPXGgUPVQ4hsaiXYUuxCqyjfXuwEpXAAr3btHY1nH6WOSi1Ot6URSuaPa6FNLqRZrTg9Heiq5aoJbA6Cxriyzulhdqf20hAxneZJnnNSTSgPq4gGh021vaRREk54xImYUweQ7kTQR9GAYdoABck@N9t2iCmOcYKjpMNoALIeyMY8Hl8JHuyMpI6JXUx7dP7vGWVczXQUWfbfM2sLvLSefYud2Q6L@/vqR2OZawW7mPxix3iRdqgjyO6NFeUucJNXIGQ/ftjC81Eb9m5XKLWq2eylEYathWSBNo2Qb7MnJWTgg4@hCkMCCHmvStWgKrs60@wZQZ5pjshrkefxoApt3iGvLEy5g3ag8aLWjECH/qx1YXk34D8UtdE@XIN/r5gGqQzsLORb0e70BQ "C# (Visual C# Interactive Compiler) – Try It Online") I don't know if the following is valid, since it requires a custom delegate with a signature of `unsafe delegate System.Action<int> D(int* a);` and has to be wrapped in an `unsafe` block to be used, but here it is anyways: # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 64 bytes ``` x=>f=>{for(int i=0,k=0;i++<1<<f;k%=f)k-=(x[k]*=-1)%f-f;k/=x[k];} ``` [Try it online!](https://tio.run/##fVJNb9wgED2bXzG1lMpO8K4/Uimql62q7qGqUilSDj2s9kBt7EV2QAKSOrL463XBTp320PIxwGN4zPCodFJJxaaqp1rDnZKtog8wokehacOgZj1rqWFw/6wNe9h8rAyXYseF2cMhcsMl0LhEKNCGGl7Bk@Q1fKVcRNooLtrjCahqdbwyjggdoCZoGsi@IfuxkcrTACcp7kha8qurXbbbNWV3QZq4S0g0HLvTJUmy@KJJHLwlHijtVKInqsAwbYCAYD@Op3GxOU5xhpPMYrQAxQwU6zpdZxle6iuSe0/sbT6j2/@Wlcbfma8kN/PxwtVrfON68UL26u2xdB7f/RFY4UPB3mZ/eaf4OrfIlsi9FqPVOfKZd8DFnH48/lbnkxRa9mzzTXHDbrlgLypsvkinSAghhi6OS0Co4QOrZ/0G8rY7pievUPBdyh5k597TqEdWosCoZxS4jaCOhjjqNrdMtObsBA8sCipqqjOMy4GG9pqVYNE/Q3nj/D5A@Jn2RofwHsKDZBqENHB2UOhILXLNem47/ayanrZ62i7f5hc "C# (.NET Core) – Try It Online") This function takes in an int\* and returns a Action; in other words, it is a curried function. The only reason I use pointers is because of codegolf.meta.stackexchange.com/a/13262/84206, which allows me to save bytes by already having a variable already defined with the length of the array. Saved 9 bytes thanks to @someone [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 11 bytes ``` N1¦ṙ⁸ḢƊÐLḢẸ ``` [Try it online!](https://tio.run/##y0rNyan8/9/P8NCyhztnPmrc8XDHomNdhyf4AOmHu3b8Pzrp4c4Z1o8a5ijo2ik8aphrfbid63D7o6Y1kf//RxvpGOgY6ugaxupEG4OZxkCWARAb6kAgiG0EEtcBkUY6EDmQNiMgywIsZgyEJjoWQGyMpALEMwDTpmBTjUGm6YBIw1gA "Jelly – Try It Online") A monadic link that takes the input as a list of integers using 0 to mean halt. Returns 0 for halting inputs and 1 for those that don’t halt. Avoids the issue of needing to work out number of iterations because of the use of `ÐL` which will loop until no new result seen. Thanks to @JonathanAllan for saving a byte! ## Explanation ``` ƊÐL | Loop the following as a monad until the result has been seen before: N1¦ | - Negate the first element ṙ⁸ | - Rotate left by each of the elements Ḣ | - Take just the result of rotating by the first element Ḣ | Finally take the first element Ẹ | And check if non-zero ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~63~~ 89 bytes ``` def f(x): for i in range(2**len(x)):a=x[0];x[0]=-a;b=a%len(x);x=x[b:]+x[:b] return a==0 ``` [Try it online!](https://tio.run/##NU/LCoMwELznK/ZSULtCHvYSyZeEHCKNrVCiBAvx61PXUBZmZ2eWgdmO/b1GVcozzDA3udUM5jXBAkuE5OMrNLLrPiGeVqu9yZa7kcD0fpyMv1VrzKczaXfPVk@OQQr7N0XwxvByGMusRI4Ce@GQWXVxRVRgHU6HJBUJZRV4/ZbXy1C1y0T5pwNSGu1HTVSUhoSiZnLnGDXK1Og468GWlrg3GaluW8oP "Python 3 – Try It Online") Also works for Python 2; a byte can be saved in Python 2 by replacing return with print and having the function print to stdout instead of returning. R turns `True` for halting and `False` for non-halting. Thanks to @Neil and @Arnauld for noting that I needed to check longer for halting. Thanks to @Jitse for pointing out a problem with `[2,0]`. Thanks to @mypetlion for noting that the absolute of the tape values could exceed the tape length. [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` def f(a): s={0,};i=0 while{(*a,)}-s:s|={(*a,)};a[i]*=-1;i-=a[i];i%=len(a) return a[i]==0 ``` [Try it online!](https://tio.run/##ZU/dCoMgGL3Op/BmoKHgzwaR@CTRRTAjIdqoxhitZ3eltWGDDznfOec7HO@vsbl10rmrqWGNKpyDZNATI7OymoHk2djWTCitCJ7pkA9vvS2qKmyZasqVpXrFyp50a7olAiS9GR99B1daa@buve1GVKNCEMgI5ARSXmIMvrzceRnRLNq4d4SJFRFuCQxAbHpk@MsKXUREZ/u99HMmMPOv/IUeIoLIdnw5fkGGut61Vl9E9wE "Python 3 – Try It Online") -40 bytes thanks to JoKing and Jitse [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~46 43~~ 36 bytes ``` {$_.=rotate(.[0]*=-1)xx 2**$_;!.[0]} ``` [Try it online!](https://tio.run/##PUztCoJAEPzdPsUEEir4cXcVQvgS0T8REVJOsIxTSDGf/bq7IIadnZ1Z5tWo/qwfCw4tcujVq@JcDVM9NX5cpGWYRyyYZ/Aw9KrL3lqbbgcFv@@ezRhgpd1YL2hRfG7XRCZpEr8HdR9L2jSHBEPESDghSBLDD5K4dWDZvJFjcMrcLQyOyMyIf2q1dPtkmoTtgGX2BQ "Perl 6 – Try It Online") Represents halt by `0` and returns true if the machine halts. This repeats the logic `2**(length n)` times, where if the pointer ends up on the halt cell, it stays there, otherwise it will be on a non-halt cell. ~~This works because there are only `2**n` possible states (ignoring halt cells) for the Foo machine to be in, since each non-halt cell has only two states.~~ Okay yes, there are states than that, but due to the limited possible transitions between pointers (and therefore states) there will be less than 2\*\*$\_ states... I think ### Explanation ``` { } # Anonymous codeblock xx 2**$_ # Repeat 2**len(n) times .[0]*=-1 # Negate the first element $_.=rotate( ) # Rotate the list by that value ;!.[0] # Return if the first element is 0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes ``` goFć©(š®._}®_ ``` [Try it online!](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf/T892OtB9aqXF04aF1evG1h9bF/9f5Hx1tpGOgY6ijaxirE20MZhoDWQZAbKgDgSC2EUhcB0QagfgK0WCGjhFYyiA2FgA "05AB1E – Try It Online") Takes the input as a list of integers with 0 as the halting instruction. Returns 1 for halting and 0 for not halting. Thanks to @KevinCruijssen for saving 2 bytes! [Answer] # Java 8, ~~78~~ ~~79~~ 73 bytes ``` a->{int k=0,l=a.length,i=0;for(;i++<1<<l;k%=l)k-=(a[k]*=-1)%l-l;k/=a[k];} ``` Straight-forward port of [*@EmbodimentOfIgnorance*'s C# .NET answer](https://codegolf.stackexchange.com/a/189575/52210), so make sure to upvote him! Thanks to *@Arnauld* for finding two bugs (which also applies to some other answers). Results in an `java.lang.ArithmeticException: / by zero` error when it's able to halt, or no error if not. [Try it online.](https://tio.run/##dVJdb4IwFH33VzQmJmWWDsQlZoDJsmxv24t7Mz50CFqpYMrFSAy/nbXFTXSapm167sc59/Zu2J7Zm2XaRIIVBfpgPDv2ECqAAY/QRllpCVzQpMwi4HlGX/OsKLexDHgG88UUJShsmD09qidKQ4eIkFERZytYEx46fpJL7PPhMHCDQPjpIBRWaoeYzdPFQ2i71kDYCn4MNeDXjd9T5LvyWyjyk4Z9zpdoq3ThGUiereYLxCytEaFZVUC8pXkJdKdMIDLc/5IlrKtn1Ld84wNxAXhEHOISRdfBPIN5XcjpPlzSLucykQoh@hxdGlrQJeM/@IY4y5R3W/c7E0V8rdvQkFEXmhhuT60xmajtXSvRZg075n66rNDTBRF9uv95xi1R3TsPgGm@cVEyKaV3W4/Po/IiJasKCnn7X5hZw36nLlm1GRBKKIuieAfKwz9BtzrzmaNYylz@ZqgjBtEavx10rBpJFB@s4/14ZT3Fmdrq5gc) **Explanation:** ``` a->{ // Method with integer-array as parameter and no return-type int k=0, // Index integer, starting at 0 l=a.length, // The length `l` of the input-array i=0;for(;i++<1<<l; // Loop 2^length amount of times: k%=l) // After every iteration: take mod `l` of `k` k-= // Decrease `k` by: (a[k]*=-1) // Negate the value at index `k` first %l // Then take modulo `l` of this -l; // And then subtract `l` from it // (NOTE: the modulo `l` and minus `l` are used for wrapping // and/or converting negative indices to positive ones k/=a[k];} // After the loop: divide `k` by the `k`'th value, // which will result in an division by 0 error if are halting ``` [Answer] # [Haskell](https://www.haskell.org/), 79 bytes ``` s x|m<-length x,let g(n:p)=(drop<>take)(mod n m)(-n:p)=iterate g x!!(2^m)!!0==0 ``` [Try it online!](https://tio.run/##bZFNS8QwEIbv@yveLh4SSJd@CWXZ7smLoHjYY60S3Ngt2yQlSd0K/vfadj3YaoZMmGcyw5vMiduzqOu@ko02Dnfc8c1ByKo0um3g@1DaQYk3YS03n3jXBh/C2Eori32GdJNswt6i@5I7vxaqdCd0rBYOJVHbhmbkaHSz2zt@FpRIfYSCpMSfcpUThjuBEp3nkehFUs8LsizonbDOIkOOPGIBC5kfFiv8LIY8nmA8Y8EsCtnV5jQaq9joo0XmSkOW/KlY9h0FRTOWTv3iwRKWDjtm/1WNPJjO24XyeNTJRv/rlcVqJXmlsN3i/gmEXqMMkjePryDPHfw9mtYdnHlQuEGrLtocLXJ70pdhBFgPwxuurBkmQoYZ0YJi@tq@/wY "Haskell – Try It Online") Returns `True` for halting machines, and `False` otherwise. Input in the form of a list, with `0` representing a halting state. Assumes a version of GHC greater than 8.4 (released Feb 2018). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔⁰ηFX²L諧≔θ籧θη≧⁻§θη绬§θη ``` [Try it online!](https://tio.run/##ZY47C8IwFIXn5lfc8QYi1MfWqaNgS3EtHUKNSaAkNrk@QPztMdhFEc50@M5jNDKMXk4p1TFa7bAUYHjFzj4Adv6uAm4EHJTTZHDmnMOTFQta096d1APnnBDQKi1J4beZ6YoVjbws/NFqQ9hYd40Cfrhl8sW6YB1h6@mvJqW@h62A/GX90U5ACcOQVrfpDQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default Boolean output, which is `-` for true and nothing for false. Explanation: ``` ≔⁰η ``` Initialise the instruction pointer. ``` FX²Lθ« ``` Loop as many times as there are theoretically possible states. ``` §≔θ籧θη ``` Negate the value at the instruction pointer. ``` ≧⁻§θηη ``` Subtract the new value from the instruction pointer. Charcoal's array accesses are cyclic so this automatically emulates Foo's circular tape. ``` »¬§θη ``` At the end of the loop, output whether the program halted. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~71~~ 67 bytes ``` x=>{for(p=l=x.length,i=2**l;i--;)p+=l-(x[p%l]*=-1)%l;return!x[p%l]} ``` Basically the same as [*@EmbodimentOfIgnorance*'s C# .NET answer](https://codegolf.stackexchange.com/a/189575/52210) 4 byte save thanks to [*@Arnaud*](https://codegolf.stackexchange.com/users/58563/arnauld) [Try it online!](https://tio.run/##dZDbCsIwDIbvfYp6MXawlW2dII565YXvoF4M7Q4S2rFVGYjPPuvqRLFCCCH/R5I/5@yatcemqhUR8sT7nPUdW99y2Xg1A9bNgYtClbhicRBAWhGS@vWMAfG6Xe3AIWAk8h1IG64ujZia5r0/StFK4HOQheduM1DtyvUnn93c28UYhRhFGJHo4P@odFSpRQwtvWigTdj02EzDyBSxnXrrOpIX8sW4e7GRvEVCKlRqZxZjr@k6WxYsx@10CL1jOWT69ySDGyQc64X9MdTYH9inib/jNJI8z@sf "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` x=>{for(p=l=x.length,i=2**l;i--;p+=l-(x[p%l]*=-1)%l)x[p%l].f} ``` This version uses `undefined` as a halting symbol and throws a `TypeError: Cannot read property 'f' of undefined` when the machine halts and terminates quietly when the machine doesn't halt. [Try it online!](https://tio.run/##hZFfa4MwEMCf66fIS2lijaB2UCrZ0x72EQpdH0ST6giJjXE4ip/dZQnrqrMdHJfc3e/@5PKefWRNrqpaYyELOpzJ0JHnC5MK1oSTLuRUnHQZVCT2fZ5WGKf1mnAMu0O95Eef4AgtOXJWyPqBkb3J9xZafRq9OMM9Ss2pqG6VACzjDTV2D/JM5yWkCFx@o1q1Nuj1Xi5FIzkNuTzB1WvGdbNboZGXwUMcgFYUlFWCFgGIAoCjI/pDJVMqmYGuxEwssllOHnGxqx4Ad4kf01fOyGaCjp//Jl4kbYCQGpRmEzOLmHQz1kzD7c9UiRXTc2t18u@oLs2ht02s72l@ocl4XTb3@7F3y9@gm/jOLxj38AU "JavaScript (Node.js) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 156 bytes Still golfable IMO, but I'm okay with it for now. Returns `0` for non-halting `Foo`s and `1` for halting `Foo`s. Takes the input in `a` as an `Array[Int]`, so `h` is taken as `0`. ``` var u=Seq[Array[Int]]()//Keep track of all states var i=0//Index while(u.forall(_.deep!=a.deep)){if(a(i)==0)return 1//Check if we are in a previously encountered step ; Halt u:+=a.clone//Add current state in the tracker var k=i//Stock temp index i=(a(i)+i)%a.length//Move index to next step if(i<0)i+=a.length//Modulus operator in Scala can return a negative value... a(k)*=(-1)}//Change sign of last seen index 0//Returns 0 if we met a previous step ``` It is pretty long to run (around 4 seconds for all the test cases) because of the multiple full-array lookups I did, plus the `.deep` that create copies... But you can still [try it online.](https://tio.run/##bVDLasMwELzrK9RAQWpUI9stBFMdcuyhpxzTUBR7XasRsqvYfWDy7a6ktPGhYtEuzMwOszqWUsup3b9B2eMnqQyGrx5MdcTrrhsRqqDGNZHF2lr5vX00/Y4Wrotx@pAWD2ID79uZ2xGKPK4ER5@N0kCGpG6t1Jq8JBVAdyVkmJSOytkSRYXg1EI/WINTNBRLJyh1ayD4HIRCSgTdUtFrmWgwr32D3K564FR59S8kyYHeCHKb0hPi0wmhzirTa0MWm6YddIX3gNNiQS94TUJukjHOUub26H8uD1weo3gMTNm5omTmrZjv2VkwR3w2c0geCxl2WBazXQXD3NUdW7mX/9nHPDzNw7yPn5X79Mz38CHoNP0A "Scala – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç₧┬òE▐tµ|⌡1 ``` [Run and debug it](https://staxlang.xyz/#p=809ec29545de74e67cf531&i=[2,+0,+1,+-1]%0A[3,+0,+1,+3]%0A[0]%0A[1,+1,+1,+1,+0]%0A[2,+1,+3,+2,+1,+2,+0]%0A[3,+2,+1,+1,+4,+0]%0A[1,+2,+0,+2]%0A[8,+1,+2,+3,+3,+4,+8,+4,+3,+2,+0]%0A[1,+2,+4,+3,+0,+2,+4,+5,+3]%0A[3,+1,+0,+3,+1,+1]%0A[1,+2,+0,+42]&a=1&m=2) It takes input in the form of an integer array, with `0` representing halt. It outputs `1` for a halting and `0` for a non-halting machine. [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 88 bytes ``` for(;$F[$i]&&!$k{"$i|$F[$i]"};$i=($i+$F[$i])%@F){$k{"$i|$F[$i]"}=1;$F[$i]*=-1}$_=!$F[$i] ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0jDWsUtWiUzVk1NUSW7WkklswbCV6q1Vsm01VDJ1IbwNVUd3DSr0ZTYGkJ1a9nqGtaqxNsqQrj//xsrGCkYAqGJgsG//IKSzPy84v@6vqZ6BoYG/3ULEgE "Perl 5 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` !hu.<+_hGtGh ``` [Test suite!](https://pythtemp.herokuapp.com/?code=%21hu.%3C%2B_hGtGh&test_suite=1&test_suite_input=%5B2%2C0%2C1%2C-1%5D%0A%5B3%2C0%2C1%2C3%5D%0A%5B1%2C1%2C1%2C1%2C0%5D%0A%5B2%2C1%2C3%2C2%2C1%2C2%2C0%5D%0A%5B0%5D%0A%5B3%2C2%2C1%2C1%2C4%2C0%5D%0A%5B1%2C2%2C0%2C2%5D%0A%5B1%2C2%2C4%2C3%2C0%2C2%2C4%2C5%2C3%5D%0A%5B3%2C1%2C0%2C3%2C1%2C1%5D%0A%5B2%2C0%5D&debug=0) Uses the straight-forward approach. Recurse until we see the list twice in an identical state. For programs that halt, the list will eventually have a leading `0` because that's where the recursion stops. For programs that don't halt, the list won't begin with the `0`, but rather be in a state from which the process would be periodic and therefore the Foo machine wouldn't halt. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 40 bytes ``` Not@&N@Periodic[{On[0,`-,_]&Rotate!_@0}] ``` [Try it online!](https://tio.run/##XZBBa8MwDIXv@RUZjJ5kiKW0ywajgd2zMnYzpgupu@XSlMa3sd@ePSUkYbORbT1/PFuqY6ybrzCc06fnoepiuanKQ7i13alt3PfrxWX0YejoN29drGO4O5bZjx@qEE69u79em0@fJIdbe4nvoY8vdR96d6bUJSmGY8rIkrGeplzGXOY0mw@WprkIrBjpyqs4CZbyRdrvndqTYTJCJiezJbMj80CmIPOIqwyhCAALwgKxYCwgC8oW@JFhDXUBxaAYFINiUAyKYcZwE3ACTvQ5cAJOwMnOj99Zil7r0g7wnBZjPYKZU4EQ@seqlI37du2SaGNIV/vXN2efeD/8Ag "Attache – Try It Online") ## Explanation ``` {On[0,`-,_]&Rotate!_@0} ``` This performs a single iteration of the Foo machine; it negates the first member, then rotates the array by the (original, non-negated) first element of the array. `Periodic` will apply this function until a duplicate result is accumulated. A machine either halts, or goes into a trivial infinite loop. If it halts, the first element will be 0. Otherwise, it will be non-zero. `&N` is a golfy way of obtaining the first element of a numeric array. Then, `Not` returns `true` for 0 (halting machines) and `false` for anything else (non halting machines). ]
[Question] [ ## The challenge Well, I think it is quite clear, isn't it? You have to make a function or a program that takes a string as an argument and outputs the corrispondent Yoda-speaking. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins. ## The input The input could be **any** string without linefeed. You can translate a string if it is composed like this: *Subject* + Verb + Something else. Where *Subject* is a personal pronoun (I, you, he, she, it, we, they). You don't have to recognize that the second word is a verb. If the first word isn't a pronoun, the input is valid but the output will be `Too difficult, this sentence is.` ``` You have to win this code challenge -> Translatable Luke has to win this code challenge -> Untranslatable ``` Input can end with a letter, a . or a !, not with a ?. Furthermore, strings can contain Non-Ascii, Parenthesis, commas, colons ... ## The output In case of a translatable sentence, the output is the same sentence, with the subject and the verb at the end of the sentence. ``` You have to win this code challenge -> To win this code challenge, you have. ``` Comma, period and lower-case on the pronoun are mandatory. (Except, of course, if the pronoun is I). As stated before, if it is untranslatable you have to output the string `Too difficult, this sentence is.` ## Examples ``` You have to win this code challenge -> To win this code challenge, you have. He won this code challenge -> This code challenge, he won. (I know this is not yoda-speaking, but I don’t want to overcomplicate this challenge) I ate an ice cream earlier! -> An ice cream earlier, I ate. I liked the Star Wars original trilogy more than the prequel’s one. -> The Star Wars original trilogy more than the prequel’s one, I liked. I find your lack of faith disturbing -> Your lack of faith disturbing, I find. I think we are done with the examples -> We are done with examples, I think. He is your son, Vader -> Your son, Vader, he is. I think they’ll add new features -> They’ll add new features, I think. I made a fantastic code challenge (I hope) -> A fantastic code challenge (I hope), I made. I love constants like π -> Constants like π, I love. I’ll be the next President, I swear! -> Too difficult, this sentence is. This challenge is great! -> Too difficult, this sentence is. Is this challenge great? -> Too difficult, this sentence is. Luke is not ready for this task -> Too difficult, this sentence is. Somebody loves constants like π -> Too difficult, this sentence is. [Empty string] -> Too difficult, this sentence is. ``` [Answer] # Retina, ~~162~~ ~~137~~ ~~145~~ ~~134~~ ~~131~~ 129 Multiple punctuation is now handled correctly. Test case: `You will not win this challenge...! -> Not win this challenge..., you will.` [Try it Online!](http://retina.tryitonline.net/#code=Wy4hXSQKClRgQS1aYGEtemBeXHdcdwpHYF4oSXx3ZXx5b3V8cz9oZXxpdHx0aGV5KSBcUysgXFMKKFxTKyBcUyspICguKikKJDIsICQxLgpUYGEtemBBLVpgXi4KXiQKVG9vIGRpZmZpY3VsdCwgdGhpcyBzZW50ZW5jZSBpcy4&input=WW91IHdpbGwgbm90IHdpbiB0aGlzIGNoYWxsZW5nZS4uLiE) ``` [.!]$ T`A-Z`a-z`^\w\w G`^(I|we|you|s?he|it|they) \S+ \S (\S+ \S+) (.*) $2, $1. T`a-z`A-Z`^. ^$ Too difficult, this sentence is. ``` Description: If there is punctuation in the end, delete it. ``` [.!]$ ^empty line ``` Transform the pronoun to lower case, except it is I. ``` T`A-Z`a-z`^\w\w ``` Filter out any line that does not match `<Pronoun><space><word><space><word>...` ``` G`^(I|we|you|s?he|it|they) \S+ \S ``` Split into `pronoun + verb`, `remainder`. Then rearrange. ``` (\S+ \S+) (.*) $2, $1. ``` Transform the first character to upper case. ``` T`a-z`A-Z`^. ``` If the result is empty, it didn't pass the filter above. Print an error message. ``` ^$ Too difficult, this sentence is. ``` [Answer] # ES6, 212 This can probably a bit further golfed down: ``` i=>(r=/(you|s?he|it?|we|they)( \S+) ([^\.!?]+)/i.exec(i))?(c=(a,b)=>a[`to${['Low','Upp'][b]}erCase`]())(r[3].slice(0,1),1)+r[3].slice(1)+", "+c(r[1],+(/i/i.test(r[1])))+r[2]+".":"Too difficult, this sentence is." ``` [JSFiddle](https://jsfiddle.net/uLrbyqg0/1/) (requires up-to-date browser like Chrome) or run it via node.js Ungolfed: ``` i=>{ r=/(you|s?he|it?|we|they)( \S+) ([^\.!?]+)/i.exec(i); //Main RegExp c=(a,b)=>a[`to${['Low','Upp'][b]}erCase`](); //shortcut for toUpperCase/toLowerCase if (r) return c(r[3].slice(0,1),1)+r[3].slice(1) + ", " //the "something else", properly formated + c(r[1], +(/i/i.test(r[1]))) //The subject lowercased except for "i" or "I" + r[2] + "."; //The End else //no match, no sentence to translate return "Too difficult, this sentence is."; } ``` [Answer] # JavaScript (ES6), 164 bytes ``` s=>([,p,,i,r]=s.match`^(((I)|You|He|She|It|We|They) \\S+) (.*?)[.!]?$`)?r[0].toUpperCase()+r.slice(1)+`, ${i?p:p.toLowerCase()}.`:"Too difficult, this sentence is." ``` ## Explanation It's almost painful how many bytes capitalising the first letter of a string takes in JavaScript... ``` s=> // Match and get specific parts of the input string ([,p,,i,r]=s.match`^(((I)|You|He|She|It|We|They) \\S+) (.*?)[.!]?$`)? r[0].toUpperCase()+r.slice(1) // capitalise first letter +`, ${i?p:p.toLowerCase()}.` // lower-case the pronoun (unless it is I) :"Too difficult, this sentence is." ``` ## Test Test does not use destructuring assignment to make it more cross-browser compatible. ``` var solution = s=>(p=s.match`^(((I)|You|He|She|It|We|They) \\S+) (.*?)[.!]?$`)?p[4][0].toUpperCase()+p[4].slice(1)+`, ${p[3]?p[1]:p[1].toLowerCase()}.`:"Too difficult, this sentence is." ``` ``` <input type="text" id="input" value="I love constants like π...!" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Python, 261 bytes ``` import re def a(b): if b[-1:]in".!": b=b[:-1] if re.match('(I|YOU|S?HE|IT|WE|THEY) \w+ \S+',b.upper()): b=(b+',').split() if b[0]!="I": b[0]=b[0].lower() b=" ".join(b[2:]+b[:2]) return b[0].upper()+b[1:] return "Too difficult, this sentence is." ``` Turns out Python doesn't mind things like `b[-1]in".!"` Next I'll play with the match object more, if no-one beats me to it :) [Answer] # Python, ~~218~~ ~~217~~ 204 bytes Not sure if this can be further golfed down. ``` def f(s):t=s.split();u=' '.join(t[2:]).rstrip('!.');return['Too difficult, this sentence is.','%s, %s %s.'%(u[0].upper()+u[1:],['I',t[0].lower()][t[0]!='I'],t[1])][t[0]in'I We You He She It They'.split()] ``` Ungolfed: ``` def f(s): t = s.split() u = ' '.join(t[2:]).rstrip('!.') return [ 'Too difficult, this sentence is.', '%s, %s %s.' % (u[0].upper() + u[1:], ['I', t[0].lower()][t[0] != 'I'], t[1]) ][t[0] in 'I We You He She It They'.split()] ``` [Answer] # GNU sed, 129 bytes I'm including +1 byte for the `-r` flag. ``` #!/bin/sed -rf /^I /b s/^(You|[HW]e|She|It|They) /\L&/ t s/.*/Too difficult, this sentence is./p d : s/[.!]$// s/^([^ ]+ [^ ]+) (.*)/\u\2, \1./ ``` ### Explanation If we match a leading `I` we jump to the label: ``` /^I /b ``` If we match one of the other pronouns, we downcase it, then jump to the label: ``` s/^(You|[HW]e|She|It|They) /\L&/ t ``` Otherwise we print the failure message and move to the next input line: ``` s/.*/Too difficult, this sentence is./p d ``` If we jumped to the label, we remove any final punctuation: ``` : s/[.!]$// ``` and swap the first two words with the rest of the sentence, capitalising the new first word and adding the required punctuation as we do so: ``` s/^([^ ]+ [^ ]+) (.*)/\u\2, \1./ ``` ]
[Question] [ In one of the more iconic xkcd strips, Randall Munroe visualised the timelines of several films in narrative charts: [![enter image description here](https://i.stack.imgur.com/VnwbU.png)](http://xkcd.com/657/large/) (Click for larger version.) Source: [xkcd No. 657](http://xkcd.com/657/). Given a specification of the timeline of a movie (or some other narrative), you are to generate such a chart. This is a popularity contest, so the answer with the most (net) votes will win. ## Minimum Requirements To tighten the spec a bit, here is the minimum set of features every answer must implement: * Take as input a list of character names, followed by a list of events. Each event is either a list of dying characters, or a list of groups of characters (signifying which characters are currently together). Here is one example for how the Jurassic Park narrative could be encoded: ``` ["T-Rex", "Raptor", "Raptor", "Raptor", "Malcolm", "Grant", "Sattler", "Gennaro", "Hammond", "Kids", "Muldoon", "Arnold", "Nedry", "Dilophosaurus"] [ [[0],[1,2,3],[4],[5,6],[7,8,10,11,12],[9],[13]], [[0],[1,2,3],[4,7,5,6,8,9,10,11,12],[13]], [[0],[1,2,3],[4,7,5,6,8,9,10],[11,12],[13]], [[0],[1,2,3],[4,7,5,6,9],[8,10,11,12],[13]], [[0,4,7],[1,2,3],[5,9],[6,8,10,11],[12],[13]], [7], [[5,9],[0],[4,6,10],[1,2,3],[8,11],[12,13]], [12], [[0, 5, 9], [1, 2, 3], [4, 6, 10, 8, 11], [13]], [[0], [5, 9], [1, 2], [3, 11], [4, 6, 10, 8], [13]], [11], [[0], [5, 9], [1, 2, 10], [3, 6], [4, 8], [13]], [10], [[0], [1, 2, 9], [5, 6], [3], [4, 8], [13]], [[0], [1], [9, 5, 6], [3], [4, 8], [2], [13]], [[0, 1, 9, 5, 6, 3], [4, 8], [2], [13]], [1, 3], [[0], [9, 5, 6, 3, 4, 8], [2], [13]] ] ``` E.g. the first line means that at the beginning of the chart, T-Rex is a lone, the three Raptors are together, Malcolm is alone, Grant and Sattler are together, etc. The second to last event means that two of the Raptors die. How exactly you expect the input is up to you, as long as this kind of information can be specified. E.g. you may use any convenient list format. You can also expect the characters in the events to be the full character names again etc. You may (but don't have to) assume that each list of groups contains each living character in exactly one group. However, you should *not* assume that the groups or characters *within* one event are in particularly convenient order. * Render to screen or file (as a vector or raster graphic) a chart which has one line for each character. Each line must be labelled with a character name at the beginning of the line. * For each normal event, there must be, in order, some cross-section of the chart in which the groups of characters are clearly resembled by proximity of their respective lines. * For each death event, the lines of the relevant characters must terminate in a visible blob. * You do *not* have to reproduce any other features of Randall's plots, nor do you have to reproduce his drawing style. Straight lines with sharp turns, all in black, without further labels and a title is perfectly fine to enter the competition. There's also no need to use the space efficiently - e.g. you could potentially simplify you algorithm by only ever moving lines downwards to meet up with other characters, as long as there is a discernible direction of time. I've added a [reference solution](https://codegolf.stackexchange.com/a/39729/8478) which fulfils exactly these minimum requirements. ## Making it Pretty This is a popularity contest though, so on top of that, you may implement whatever fanciness you want. The most important addition is a decent layouting algorithm which makes the chart more legible - e.g. which makes bends in the lines easy to follow and which reduces the number of necessary line crossings. This is the core algorithmic problem of this challenge! The votes will decide how well your algorithm performs at keeping the chart tidy. But here are some more ideas, most of them based on Randall's charts: **Decorations:** * Coloured lines. * A title for the plot. * Labelling line ends. * Automatically relabelling lines which have gone through a busy section. * Hand-drawn style (or other? as I said, there's no need to reproduce Randall's style if you have a better idea) for lines and fonts. * Customisable orientation of the time axis. **Additional Expressiveness:** * Named events/groups/deaths. * Disappearing and reappearing lines. * Characters entering late. * Highlights which indicate (transferable?) properties of characters (e.g., see the ringbearer in the LotR chart). * Encoding additional information in the grouping axis (e.g. geographic information like in the LotR chart). * Time travel? * Alternative realities? * A character turning into another? * Two characters merging? (A character splitting?) * 3D? (If you *really* go that far, please make sure that you're actually using the additional dimension to visualise someting!) * Any other relevant features, which could be useful to visualise the narrative of a film (or book etc.). Of course, many of these will require additional input, and you're free to augment your input format as necessary, but please document how data can be entered. Please include one or two examples to show off the features you implemented. Your solution should be able to deal with any valid input, but it's absolutely fine if it's better suited to certain kinds of narratives than others. ## Voting Criteria I have no illusions that I could tell people how they should spend their votes, but here are some suggested guidelines in order of importance: * Downvote answers which exploit loopholes, [standard ones](http://meta.codegolf.stackexchange.com/q/1061/8478) or others, or hardcode one or more results. * Do not upvote answers which don't fulfil the minimum requirements (no matter how fancy the rest might be). * First and foremost, upvote nice layouting algorithms. This includes answers which don't use a lot of vertical space while minimising crossing of lines to keep the graph legible, or which manage to encode additional information into the vertical axis. Visualising the groupings without making a huge mess should be the main focus of this challenge, such that this remains a programming contest with an interesting algorithmic problem at heart. * Upvote optional features which add expressive power (i.e. are not just pure decoration). * Lastly, upvote nice presentation. [Answer] **Python3 with numpy, scipy and matplotlib** ![Jurassic Park](https://i.stack.imgur.com/YLfjo.png) **edit**: * I tried to keep the groups in the same relative position between events, hence the `sorted_event` function. * New function to calculate the y position of the characters (`coords`). * Every *alive* event is plotted two times now, so the characters stick together better. * Added legend and removed axes label. ``` import math import numpy as np from scipy.interpolate import interp1d from matplotlib import cm, pyplot as plt def sorted_event(prev, event): """ Returns a new sorted event, where the order of the groups is similar to the order in the previous event. """ similarity = lambda a, b: len(set(a) & set(b)) - len(set(a) ^ set(b)) most_similar = lambda g: max(prev, key=lambda pg: similarity(g, pg)) return sorted(event, key=lambda g: prev.index(most_similar(g))) def parse_data(chars, events): """ Turns the input data into 3 "tables": - characters: {character_id: character_name} - timelines: {character_id: [y0, y1, y2, ...], - deaths: {character_id: (x, y)} where x and y are the coordinates of a point in the xkcd like plot. """ characters = dict(enumerate(chars)) deaths = {} timelines = {char: [] for char in characters} def coords(character, event): for gi, group in enumerate(event): if character in group: ci = group.index(character) return (gi + 0.5 * ci / len(group)) / len(event) return None t = 0 previous = events[0] for event in events: if isinstance(event[0], list): previous = event = sorted_event(previous, event) for character in [c for c in characters if c not in deaths]: timelines[character] += [coords(character, event)] * 2 t += 2 else: for char in set(event) - set(deaths): deaths[char] = (t-1, timelines[char][-1]) return characters, timelines, deaths def plot_data(chars, timelines, deaths): """ Draws a nice xkcd like movie timeline """ plt.xkcd() # because python :) fig = plt.figure(figsize=(16,8)) ax = fig.add_subplot(111) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_xlim([0, max(map(len, timelines.values()))]) color_floats = np.linspace(0, 1, len(chars)) color_of = lambda char_id: cm.Accent(color_floats[char_id]) for char_id in sorted(chars): y = timelines[char_id] f = interp1d(np.linspace(0, len(y)-1, len(y)), y, kind=5) x = np.linspace(0, len(y)-1, len(y)*10) ax.plot(x, f(x), c=color_of(char_id)) x, y = zip(*(deaths[char_id] for char_id in sorted(deaths))) ax.scatter(x, y, c=np.array(list(map(color_of, sorted(deaths)))), zorder=99, s=40) ax.legend(list(map(chars.get, sorted(chars))), loc='best', ncol=4) fig.savefig('testplot.png') if __name__ == '__main__': chars = [ "T-Rex","Raptor","Raptor","Raptor","Malcolm","Grant","Sattler", "Gennaro","Hammond","Kids","Muldoon","Arnold","Nedry","Dilophosaurus" ] events = [ [[0],[1,2,3],[4],[5,6],[7,8,10,11,12],[9],[13]], [[0],[1,2,3],[4,7,5,6,8,9,10,11,12],[13]], [[0],[1,2,3],[4,7,5,6,8,9,10],[11,12],[13]], [[0],[1,2,3],[4,7,5,6,9],[8,10,11,12],[13]], [[0,4,7],[1,2,3],[5,9],[6,8,10,11],[12],[13]], [7], [[5,9],[0],[4,6,10],[1,2,3],[8,11],[12,13]], [12], [[0,5,9],[1,2,3],[4,6,10,8,11],[13]], [[0],[5,9],[1,2],[3,11],[4,6,10,8],[13]], [11], [[0],[5,9],[1,2,10],[3,6],[4,8],[13]], [10], [[0],[1,2,9],[5,6],[3],[4,8],[13]], [[0],[1],[9,5,6],[3],[4,8],[2],[13]], [[0,1,9,5,6,3],[4,8],[2],[13]], [1,3], [[0],[9,5,6,3,4,8],[2],[13]] ] plot_data(*parse_data(chars, events)) ``` [Answer] ## T-SQL I'm not happy with this as an entry, but I think this question deserves at least a try at it. I will try to improve this later time permitting, but labeling will always be a problem in SQL. The solution requires SQL 2012+ and is run in SSMS (SQL Server Management Studio). The output is in the spatial results tab. ``` -- Variables for the input DECLARE @actors NVARCHAR(MAX) = '["T-Rex", "Raptor", "Raptor", "Raptor", "Malcolm", "Grant", "Sattler", "Gennaro", "Hammond", "Kids", "Muldoon", "Arnold", "Nedry", "Dilophosaurus"]'; DECLARE @timeline NVARCHAR(MAX) = ' [ [[1], [2, 3, 4], [5], [6, 7], [8, 9, 11, 12, 13], [10], [14]], [[1], [2, 3, 4], [5, 8, 6, 7, 9, 10, 11, 12, 13], [14]], [[1], [2, 3, 4], [5, 8, 6, 7, 9, 10, 11], [12, 13], [14]], [[1], [2, 3, 4], [5, 8, 6, 7, 10], [9, 11, 12, 13], [14]], [[1, 5, 8], [2, 3, 4], [6, 10], [7, 9, 11, 12], [13], [14]], [8], [[6, 10], [1], [5, 7, 11], [2, 3, 4], [9, 12], [13, 14]], [13], [[1, 6, 10], [2, 3, 4], [5, 7, 11, 9, 12], [14]], [[1], [6, 10], [2, 3], [4, 12], [5, 7, 11, 9], [14]], [12], [[1], [6, 10], [2, 3, 11], [4, 7], [5, 9], [14]], [11], [[1], [2, 3, 10], [6, 7], [4], [5, 9], [14]], [[1], [2], [10, 6, 7], [4], [5, 9], [3], [14]], [[1, 2, 10, 6, 7, 4], [5, 9], [3], [14]], [2, 4], [[1], [10, 6, 7, 5, 9], [3], [14]] ] '; -- Populate Actor table WITH actor(A) AS ( SELECT CAST(REPLACE(STUFF(REPLACE(REPLACE(@actors,', ',','),'","','</a><a>'),1,2,'<a>'),'"]','</a>') AS XML)) SELECT ROW_NUMBER() OVER (ORDER BY(SELECT \)) ActorID, a.n.value('.','varchar(50)') Name INTO Actor FROM actor CROSS APPLY A.nodes('/a') as a(n); -- Populate Timeline Table WITH Seq(L) AS ( SELECT CAST(REPLACE(REPLACE(REPLACE(REPLACE(@timeline,'[','<e>'),']','</e>'),'</e>,<e>','</e><e>'),'</e>,','</e>') AS XML) ), TimeLine(N,Exerpt,Elem) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) N ,z.query('.') ,CAST(REPLACE(CAST(z.query('.') AS VARCHAR(MAX)),',','</e><e>') AS XML) FROM Seq CROSS APPLY Seq.L.nodes('/e/e') AS Z(Z) ), Groups(N,G,Exerpt) AS ( SELECT N, ROW_NUMBER() OVER (PARTITION BY N ORDER BY CAST(SUBSTRING(node.value('.','varchar(50)'),1,ISNULL(NULLIF(CHARINDEX(',',node.value('.','varchar(50)')),0),99)-1) AS INT)), CAST(REPLACE(CAST(node.query('.') AS VARCHAR(MAX)),',','</e><e>') AS XML) C FROM TimeLine CROSS APPLY Exerpt.nodes('/e/e') as Z(node) WHERE Exerpt.exist('/e/e') = 1 ) SELECT * INTO TimeLine FROM ( SELECT N, null G, null P, node.value('.','int') ActorID, 1 D FROM TimeLine CROSS APPLY TimeLine.Elem.nodes('/e') AS E(node) WHERE Exerpt.exist('/e/e') = 0 UNION ALL SELECT N, G, DENSE_RANK() OVER (PARTITION BY N, G ORDER BY node.value('.','int')), node.value('.','int') ActorID, 0 FROM Groups CROSS APPLY Groups.Exerpt.nodes('/e') AS D(node) ) z; -- Sort the entries again WITH ReOrder AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY N,G ORDER BY PG, ActorID) PP, COUNT(P) OVER (PARTITION BY N,G) CP, MAX(G) OVER (PARTITION BY N) MG, MAX(ActorID) OVER (ORDER BY (SELECT\)) MA FROM ( SELECT *, LAG(G,1) OVER (PARTITION BY ActorID ORDER BY N) PG, LEAD(G,1) OVER (PARTITION BY ActorID ORDER BY N) NG FROM timeline ) rg ) SELECT * INTO Reordered FROM ReOrder; ALTER TABLE Reordered ADD PPP INT GO ALTER TABLE Reordered ADD LPP INT GO WITH U AS (SELECT N, P, LPP, LAG(PP,1) OVER (PARTITION BY ActorID ORDER BY N) X FROM Reordered) UPDATE U SET LPP = X FROM U; WITH U AS (SELECT N, ActorID, P, PG, LPP, PPP, DENSE_RANK() OVER (PARTITION BY N,G ORDER BY PG, LPP) X FROM Reordered) UPDATE U SET PPP = X FROM U; GO SELECT Name, Geometry::STGeomFromText( STUFF(LS,1,2,'LINESTRING (') + ')' ,0) .STBuffer(.1) .STUnion( Geometry::STGeomFromText('POINT (' + REVERSE(SUBSTRING(REVERSE(LS),1,CHARINDEX(',',REVERSE(LS))-1)) + ')',0).STBuffer(D*.4) ) FROM Actor a CROSS APPLY ( SELECT CONCAT(', ' ,((N*5)-1.2) ,' ',(G)+P ,', ' ,((N*5)+1.2) ,' ',(G)+P ) AS [text()] FROM ( SELECT ActorID, N, CASE WHEN d = 1 THEN ((MA+.0) / (LAG(MG,1) OVER (PARTITION BY ActorID ORDER BY N)+.0)) * PG * 1.2 ELSE ((MA+.0) / (MG+.0)) * G * 1.2 END G, CASE WHEN d = 1 THEN (LAG(PPP,1) OVER (PARTITION BY ActorID ORDER BY N) -((LAG(CP,1) OVER (PARTITION BY ActorID ORDER BY N)-1)/2)) * .2 ELSE (PPP-((CP-1)/2)) * .2 END P ,PG ,NG FROM Reordered ) t WHERE a.actorid = t.actorid ORDER BY N, G FOR XML PATH('') ) x(LS) CROSS APPLY (SELECT MAX(D) d FROM TimeLine dt WHERE dt.ActorID = a.ActorID) d GO DROP TABLE Actor; DROP TABLE Timeline; DROP TABLE Reordered; ``` The resulting timeline looks like the following ![enter image description here](https://i.stack.imgur.com/2uJIr.png) [Answer] ## Mathematica, Reference Solution For reference, I provide a Mathematica script which fulfils exactly the minimum requirements, nothing more, nothing less. It expects the characters to be a list of the format in the question in `chars`, and the events in `events`. ``` n = Length@chars; m = Max@Map[Length, events, {2}]; deaths = {}; Graphics[ { PointSize@Large, ( linePoints = If[Length@# == 3, lastPoint = {#[[1]], #[[2]] + #[[3]]/(m + 2)}, AppendTo[deaths, Point@lastPoint]; lastPoint ] & /@ Position[events, #]; { Line@linePoints, Text[chars[[#]], linePoints[[1]] - {.5, 0}] } ) & /@ Range@n, deaths } ] ``` As an example, here is the Jurassic Park example using Mathematica's list type: ``` chars = {"T-Rex", "Raptor", "Raptor", "Raptor", "Malcolm", "Grant", "Sattler", "Gennaro", "Hammond", "Kids", "Muldoon", "Arnold", "Nedry", "Dilophosaurus"}; events = { {{1}, {2, 3, 4}, {5}, {6, 7}, {8, 9, 11, 12, 13}, {10}, {14}}, {{1}, {2, 3, 4}, {5, 8, 6, 7, 9, 10, 11, 12, 13}, {14}}, {{1}, {2, 3, 4}, {5, 8, 6, 7, 9, 10, 11}, {12, 13}, {14}}, {{1}, {2, 3, 4}, {5, 8, 6, 7, 10}, {9, 11, 12, 13}, {14}}, {{1, 5, 8}, {2, 3, 4}, {6, 10}, {7, 9, 11, 12}, {13}, {14}}, {8}, {{6, 10}, {1}, {5, 7, 11}, {2, 3, 4}, {9, 12}, {13, 14}}, {13}, {{1, 6, 10}, {2, 3, 4}, {5, 7, 11, 9, 12}, {14}}, {{1}, {6, 10}, {2, 3}, {4, 12}, {5, 7, 11, 9}, {14}}, {12}, {{1}, {6, 10}, {2, 3, 11}, {4, 7}, {5, 9}, {14}}, {11}, {{1}, {2, 3, 10}, {6, 7}, {4}, {5, 9}, {14}}, {{1}, {2}, {10, 6, 7}, {4}, {5, 9}, {3}, {14}}, {{1, 2, 10, 6, 7, 4}, {5, 9}, {3}, {14}}, {2, 4}, {{1}, {10, 6, 7, 4, 5, 9}, {3}, {14}} }; ``` we'll get: [![enter image description here](https://i.stack.imgur.com/dDJ38.png)](https://i.stack.imgur.com/dDJ38.png) (Click for larger version.) That doesn't look *too* bad, but that's mostly because the input data is more or less ordered. If we shuffle the groups and characters in each event (while maintaining the same structure), stuff like this can happen: [![enter image description here](https://i.stack.imgur.com/0VOw6.png)](https://i.stack.imgur.com/0VOw6.png) Which is a bit of a mess. So as I said, this fulfils only the minimum requirements. It doesn't try to find a nice layout and it isn't pretty, but that's where you guys come in! ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/28897/edit) The goal is to write program that will produce a word **unexpectedly** (program doesn't look like it is going to produce a word). Example (JavaScript): ``` alert(([0][1]+"").slice(4,8)) ``` > > alerts "fine" - [jsfiddle](http://jsfiddle.net/L6W5R/3/). > > > Explanations: > > 1. `[0][1]` returns undefined, because there only one element in array `[0]` > > 2. Adding empty string converts `undefined` to string "undefined" > > 3. `slice(4,8)` outputs fifth to eight characters of `undefined` > > > --- This is **underhanded popularity contest**. [Answer] # CJam ``` "​​‌‌​​​‌‌‌‌​​‌‌​​‌‌​‌‌‌‌​​​​‌​​​‌​‌‌‌​​​‌​​​​‌​​​‌‌​‌​​‌‌​​‌‌‌‌‌​‌​​​​​‌‌‌​​​‌‌​​​‌‌​‌‌‌‌‌‌​‌​‌‌‌​‌​‌​‌​‌‌​‌​‌‌​‌​​‌​​​‌​‌​‌‌​​​​‌​‌​‌‌​​​​‌​​‌‌​​‌​‌‌​​​​‌​​‌‌‌​​​​​‌‌‌​​‌​‌​‌​‌​​‌‌‌‌​‌‌​​​​​​‌‌​‌​​​​‌​‌‌​​‌​​‌​‌​‌‌‌‌​​‌​‌‌​‌​‌​​​‌‌‌​‌​​​‌‌​​‌‌​​‌​‌‌​‌​​‌​​‌​‌‌‌​​‌‌​​‌‌​‌​‌‌​‌‌‌​​​‌​​​​‌​‌​​‌​​​​​​‌​‌‌​​‌‌​‌​​​‌​​‌​‌":iXf&YbBB*b:c ``` Prints *Pneumonoultramicroscopicsilicovolcanoconiosis*. [Try it online.](http://tinyurl.com/nk2qges) (Permalink works in Chrome. You have to copy and paste the code in some browsers.) To understand how it works, [click here](http://tinyurl.com/op6x7y2) to run this: ``` "​‎‏‌‎‌​​‎‍‌‍‌‏​‌‏‌​‏‌‏‍​‎‏‌‍​‏‏​‎‌‏‏​‍‍‏‏‏‎‍‎‏‌‌‎‍‎‏‏​‍‍‍‌‌‎‎‌‏​‎‏‏​‏‏‍‏‏‍​‌‍‌‏‏‎‍‏​‌‎‌‍‏‏‌‏​​‌​‍‏‌‍​‌‍​​‌‌‌‏​‎​​​‌‍​‏​‎‏​​​‎​‎‎‌​‏​​​‌‍‌‏‍‏‌​‌‎‏​​‌‏‎‎‎‎‌​‎​‏‏​‏‏‍‏‌​‍​‏‏​​‍‎‌‏‌‎‏‍‍‌‍‎‍‌​‍‌‎‏​‌‎‌‌‍‏‍‌​‌‍​‍‍​‏‌‏​‎‏‍​‎‎‎‍‍‌‌‏​‏​​‏‎‍‏‎‍‏​‎‏‏‍​‌‍‌​​​‍‌‌‎‎‍​‏‎‍‏‏‍‍​‍‍‌‌‏‏‍‏‌​‌‌​​‌‌​‌‍‍‎​‎‎‎‍​‌‎‌‏​‍‎​​‏​​‍‎​‏‌‍‍‎‌‌‏‏‌​‎‍‎‏‍‏‏‍‏‌‏‍‍‏‍‍‏‎‍​‎‌‏‎‍​​‎‎​‎‏‍‍‌‎‍‍‏‏‌‏‎‏​‎‍‍‍‎‍‌‎‎‌​‍‏​‌‏‏‍‎‎‏‏​‌‌‎‍‌‍‎‏‎‎‎‍‎‏‏‏‌‌‍‏‎‍‍‏‍‍​​‍‎‍‌‌‎‌‎‏‏‏‌​‎​‍‏‎‏‎‌‌‍‏‎‎‌‍​‎‏‍‍​‍‏‏‏‏‏‌‍‎‌​​​‍‏‏​‌​‎‌‏‌‎‎‍‎‍‎‏‌​‏‏‌​‏‎‍‍‏‌‎‍​‌‎‎‌​‍​‎‎‎‎‌‌‎​‎​​‏‌‍‍‌‎‍‍‏‎‎‏‍‎​‌‎‎‍‎‍​‎‎‏‎‌​‌‎‏‌‏‍‍‍‌‎‌‏‍​‍‍‍‍‍‌‌‎‍‏‎‎​​‎‎‎​‎​‏‍​​‏‎​​‍‌‌‍‌‍‎‍‍‏‏‏‎‌‏‍‏‎‎‌‍‌​‏‎‏‎‎‏‏‍‍‏‌‌‎‍‎‎‎‍‎‌​​‌‏‎‌​‏‍‍‍‌‍‏‌‌‍‌‌‎‍‌‏‍‎‍‌‏​‎‏‌​‎​‎‌‎​‌‍‌‏‎‌‌‌‌‎‍​‏​‌‌‎‌‌‏‍‎​‏‎‎‌‎‌‌‍‎‎‎‎‏‍‏‌‎‌‏‍‎​‏‍‍​​‍‎‏​‎‏​‏‎‌‍‍‏‍​‎‎‌‏‏‍‌‏‎‍‏‍‍‌‍​​‌‎‏‍‍‍​‏​‍​‏‏​‏‏‍‌‌‌‏‏‍‌‎‌‍‎‎‏​‏​‎‍‏‏‎‍​​‏​‏‎‏‌‌​​‏‍‍‍​‎​‏‌‎‍‌‏‌‏‎​‌‍‎​​‎‎​‏‌‌​‌​‏​‌​‎​‏​‎‏‌‎​‏​​​‍‌‏‏‏‌​‍‍‏​‍‌​​‎‏‍​‏‌​‏‍‌‏‏‏​‏‏‎​​​‌‎​‌​‏‎‌​‍‍‎​‏‎​‎‏‌‌‎‍‏‎‌​‎‏‌​‎‏‏‍‎‏​‌‍​‍​‍‎‎‌‎‎​‏​​‌‍‎‍‌‌‌​​‎‌‎‎‍​‏​‍‍‍​​​​‍‏‌​​​‍‎‌‌‌‍​‌‌‍‌‌‌‎‏‌‍‏‌‌‎‎‎‍‏‎​‍‌‍‏‍​‌‍‎‌‏‍‎​‎‏‎‍‎‏‎​​‏‍​‏‎​‎‏‍​​‏‎‍​‏‍‌‏‍‍‍‏‏‍‏‎​‎‌‏​‏‏‎‌‏​‍‏‎‎‌‌‏‏‍‎‏​‎‌​‌‌‎‌​‍‍​​‎‌​‍​​‏‍‎‏‎‌‍‍​‍‍‌‎​‌‏‏​​‏‌‏‍​‌‍‏‍‎‍​​‏​‏​‏‏‏‎​‎‌‏‏‍​‏‍‏‍‌‎‍‌‏‎‏‏‏‎‌‌​‏‌‍‏‌‌​‏‎‏‍​‌‏‏​‎‍‏‍‌‎‍‎‌‌‏‏‍‍‏‍‎‌‏‎‍‎‏‍‏‍‌​‌‏​‌‏‎‎‌‎‎‌‍‍‌‏‌‌‌‏‍‏‌‍‌​‏‍​‍‌​​‏‏​‌​‏‍‎‏‏‏‍‎‍‌‍‌‍‍‍‏‎‎‏‏‏‏​‌‏​‎​‏​‌‎‏‏‎‏​‍​​‍​​‍‌‏‍‏‌​​‎‍‏‌‏‏‍‏‎‌‎‍‏‍‎‍​‍‌‏‍‍‎‌‏‌​‎‎‍‎‏‎​‍​‍‍‏‏‎‍‏‎‌​‍‍‏‎​‍​‍‏‎‎‎‏‍​‏‌‌‌​‏‎‌​‎‌‍​‎‍‌‏‏‎‎​‏‌‌‍‏‏‎​‍‌​​‎‍‏‎‌‏‎‏‌‌‌​‍‍‌‍‏​‌‎‌​‏‌​​‎‍‏‌‍​‍‎​​‎​​​‌​​​​‎‎​‌‎‎‎​‎‍‏‍‍‎‏‌‌‌‍‎​​‏‎‎‍‍‍‍‏‎‌‍​​​‍‍‍‎​‎‏‌‎‏​‍‌‍‍‍‏‌​‌‌​‎​‏​‍​‍‏‏‎‎‍‎‍‌​‏‎‌​‏‏​‎​‌‎​​​​‎‏‍‌​​‎​‌‎​‏‌‌‍‍‌‎‎​‎‎‍‌​‎‍​​‍‎‍‎‌‌‍‌‌‌‌‌‏‎‏​‌‎‏‎‌‏‌‏‍‍‎‌‌‎‎‌‍​‌​​‏‍‌‎‏‍​‎‍‍‍‎‍‌‎‎​‌​‏‎‏‏‏‏‏‎‎‍‌​‏‍‎‏‎‏‍‎‌‌‌‍‌​‎‌​‌‏‎‎‎​‌​‌‎‏‏‏‌‎‌‍​‌‏‏‏‎‎‍‏‏‎‍‎‌‎‏‌‎‎‍​‌‌‌‍‏‍‏​‍‎​‍‎​‏‌‍‏​‌‍‎‏‎‎‏‌‎‌‏​‎​‍‌‍‌‎‏​‌‍‌​‏‎​​‏‏‎​​​​‍​‎‍​‏‌​‍‌‌‌​‏‏‏‏‍‍‎‍‌‌‌‍‎‎‍‏​‎‍‏‌‍‎‏‏‍‍​​‌‎​‎‌​‎‏‍‌‌‏‌‏‏‍‍​‌‎‎‏‌‍‎​‌‏‍‍‎‌‌‏‎‍​‎​‎‌‎‏​​‍​‎‌‍‍‍‏‏‌‌‏‌‌​​‍‏‌‍​‏‌‍‏‎​‏‏‏‌‍‏‌‌‎‏‍​‎​‏​‏‎‌‏‏​‌‏​‍‏‍​‎‎​‌​‎‎‎‌​‍​‍​‌‎‌‌​‍​​‏‎‏‏‎‏‏​‎‎‌‍‏‏​​​‍‌‍​‎‏‏‏‏​‏‎‏‏‌​‌‎‎​​‎‎‏​​‏‍‎‎‎‏‌‎‍‎‎‌​‌‌‌‎‌‍‎‎‍‌‍‍‌‌​‎‏‌‏‌‎​‌‎‍‍​‏‎​‏‌​​‎‎​‌​‌‌‌‏‍‍‏‎‌‏‏‏‎‎‎‍‌​‏​​‏‌‎‌‎‏‌‍‍‎‍‌‍‍‍​‍​‎‍‌‌​‍‍‏‌‌‍‏‏‍‏​‎‎‍‍‎‎‍‏​‍‎‌​‍‌‎‏‍​‏‌‍‍‎‏​​‏​‍‌​‍‍‎‏‍‎‍​​‎‌‍‎‎​‏‍‌​‌‏‏‎‌‏​‎‏‏​‎​‌‌‍‍‍‏​‌​​‌‎‍‏‎‍‌‌‏‌‌‎‌‌‍‏‍‍‏​‌‌‎‏‌‍‌‎‌‍‎​​‎​‎‍‏‌‌​​‏‎​​‏‍‏‍‏‏​‎‍‎‏‏‌​‌​‍‌‌‏‎​‎‍‍​​​​‏‍‏‏‍‍":i5f%5b5I*b' f+~ ``` ### I still don't get it! * > > The first code block is actually 970 bytes long, since there are 318 zero-width characters (U+200B and 0+200C) between the two double quotes. Even with a monospaced font, these characters are completely invisible. > > > * > > `X`, `Y` and `B` are variables initialized to 1, 2 and 11. > > > * > > `:iXf&` casts each character to an integer (8203 or 8204) and computes the parity. This way, U+200B becomes 1 and U+200C becomes 0. > > > * > > `Yb` converts the array of integers from above to an integer by considering it a base 2 number. > > > * > > `BB*b` converts that integer into an array of its digits as a base 121 number. > > > * > > The sad smiley `:c` casts each digit to its corresponding ASCII character. > > > * > > The second code block is actually 6543 bytes long. It follows the same idea, but it uses the characters U+200B to U+200F, base 5 numbers and string evaluation. > > > [Answer] # Python2.x ``` import re try: re.compile("[") except re.error, e: print e.message.split()[0] ``` [try it](https://ideone.com/Y7nLlY) [Answer] # Python I don't expect any upvote (but pwease don't downvote this either - unless the net votes are above 0!), because of course I claim *NO MERIT WHATSOEVER* on this answer, but in my opinion, the award would go hands down to **Tim Peters** for this Python code... ``` import this ``` (If you've never heard about it, [try it here](https://ideone.com/aL3cl6) :) ) [Answer] Ok - here'we go: **Javascript:** ``` new Function("‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‌‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍".split("‌").map(function(v){return String.fromCharCode(v.length)}).join(''))(); ``` Evaluate it in your console... > > It can't be that easy. Try to find it yourself. > > > [Answer] # C - ioccc feeling ``` #define\ __(a,b) b##a __(in(O){,ma) __(at*f=&O;,flo) #define\ _ __(ntf("%f",*f);,pri) __(ng,lo)__(ng $;O=, lo) __(NE__;$=,__LI) O*4*2699*14449 *__(1ll,1765069);O=~--O;_-_- _-_-_-_-_-_-__(ts(&$);},pu) ``` **output (using gcc 4.7.2):** > > -nan-nan-nan-nan-nan-nan-nan-nan BATMAN > > > # C - WinApi leave it to the professionals ``` #include <Windows.h> CONST CCHAR *ParseStringOutputHandler(HANDLE hOut) { /* * Prototype for SEH support function. */ CONSOLE_SCREEN_BUFFER_INFO SBInfo; COORD crdSBInfoCoord; COORD crdMaxWinSize; COORD crdSize; WORD wMagicNum = 0x40; WORD wAttr = 0x14; INT8 i; static CCHAR szParseArray[9]; /* * This file contains the definitions and prototypes for the compiler- * dependent intrinsics, support functions and keywords which implement * the structured exception handling extensions. */ crdSBInfoCoord.X = _WIN32_WINNT_NT4 >> 8; crdSBInfoCoord.Y = SUBVERSION_MASK / 28; crdMaxWinSize.X = EXCEPTION_EXECUTE_HANDLER | 0x2; crdMaxWinSize.Y = (_WIN32_IE>>010) + 3; crdSize.X = _WIN32_IE_IE20 >> 0x8; crdSize.Y = 0x15; SBInfo.dwCursorPosition = crdSBInfoCoord; SBInfo.dwMaximumWindowSize = crdMaxWinSize; SBInfo.dwSize = crdSize; SBInfo.wAttributes = wAttr; /* * Currently, all MS C compilers for Win32 platforms default to 8 byte * alignment. */ for (i = 1; i <= 8; ++i){ switch (i){ case STRICT: szParseArray[i-1] = SBInfo.dwCursorPosition.X; break; case DM_COPY: szParseArray[i-1] = SBInfo.dwCursorPosition.Y; break; case DC_PAPERSIZE: szParseArray[i-1] = SBInfo.dwMaximumWindowSize.X; break; case _CRT_PACKING/2: szParseArray[i-1] = SBInfo.dwMaximumWindowSize.Y; break; case 0x5: szParseArray[i-1] = SBInfo.dwSize.X; break; case DC_BINS: szParseArray[i-1] = SBInfo.dwSize.Y; break; case (_WIN32_WINNT>>8)|(_WIN32_WINNT&1): case 010: szParseArray[i-1] = SBInfo.wAttributes; } szParseArray[i-1] |= wMagicNum; if (i > 7){ szParseArray[sizeof(szParseArray)-1] |= wMagicNum; } } szParseArray[8] = NULL; // set WINVER based on _WIN32_WINNT return szParseArray; } ``` **output:** > > DICKBUTT > > > [Answer] ## CJam This is my first practice with **CJam**: ``` 77c79c_78c7(8+6*3+c"K"["MICHAEL" "JACKSON"]:Ls4=Ls6=@'R'E\ ``` I'm sure I could do it better with more practice but it was fun. It prints out > > MOONWALKER > > > You can check it out [here](http://cjam.aditsu.net/). [Answer] # C *Works only on a little-endian machine* How to make a simple multiplication ? ``` int main(void) { //this is an easy multiplication example int a = 37897 * 210; //print the result printf("%s",&a); return 0; } ``` outputs `boy` > > 37897\*210 = 7958370 (0x796f62) > > `boy` ASCII representation is 62-6f-79 (0x796f62 on little-endian) > > printf with `%s` print the string, not the integer. > > > [**>> Try it here**](http://ideone.com/IskGA8) [Answer] # Javascript **Round 2:** **Improved Solution:** ``` try{Joe}catch(е){alert(е.message.replace(/de?/g,''))} ``` *53 characters* **Old Solution:** Prints the same but in more short `char` length: ``` try{Joe}catch(е){console.log(е.message.replace(/de|d/g,''))} ``` *60 characters* **Round 1:** *I am going to Joe's place, he is sick, even computer says that:* ``` try { x = Joe; } catch (err) { msg = err.message.split(" "); console.log(msg[0] + " " + msg[1] + " " + msg[2] + " " + msg[3].substring(2, 6)); } ``` *162 characters.* ``` try{x=Joe}catch(e){m=e.message.split(" ");console.log(m[0]+" "+m[1]+" "+m[2]+" "+m[3].substring(2,6))}; ``` *103 characters.* *"Joe is not fine"* [Answer] # dc `dc` can be used with pretty obscure expressions. Here is an example, nearly asking you a question! (second line): ``` dc -e '[<!][P[ ]P]sr[|]30 4+[p]5[ ]500d+300dZ73 16d6-r[PnPnPnPP]sa[sz-=r2;h*7+++[know ]lax]sb vv:ha7 d0 [you] sp[eak?] lbx' ``` > > Output: `I know 1337 5p34|<!` > > > Edit: splitting original answer into three different ones (`bash` and haskell proposals in separate posts) [Answer] # C, C++ Here's an oldie that could easily be adapted to other programming languages: ``` #include <stdio.h> int main() { int i = 0x6F56DF77; printf("%8X", (i << 1) + 1); } ``` > > The trick is using the numbers >9 in hexadecimal (or higher) number systems. This one print's `DEADBEEF`, but there can be many [variations](http://en.wikipedia.org/wiki/Hexspeak). AFAIK Mac OS used to mark released memory in certain debug builds as dead beef. > > > [Try it!](http://ideone.com/uNaoPG) [Answer] ## Common Lisp No attempts to hide *how* this one works. ``` (let ((*print-base* 36)) (print #x1A92721254086478787CE5D7)) ``` > > SPANISHINQUISITION > > > [Answer] # sed Of course with `sed` one is waiting for a string output. But if you do not already know this one, I think it can be considered as… unexpected: ``` sed 's/ //g;s/h.*yo//;s/od.*//;y/euHodityn,/ -aegmoptt/;s/ //;e' <<< 'Hey, have you done it today?' ``` I can't write the answer correctly in a “spoiler” block, so you'll have to try it yourself :) (Hint: works best on Debian/Ubuntu. Don't loose your time on Mac.) **Edit:** I discovered that I *could* use code in spoiler blocks, so output is now hidden below. > > > ``` > (__) > (oo) > /------/ > / | || > * /---/\ > ~~ ~~ > ...."Have you mooed today?"... > ``` > > > > [Answer] # CJam ``` PT/ ``` Try it at <http://cjam.aditsu.net/> Also, for fun: ``` "HAL":) ``` [Answer] # PowerShell Can it be multiple words? If so, allow this to blow your freakin' mind. ``` function recurse() { $r = 72,29,7,0,3,-79,87,-8,3,-6,-8 $s = "" $t = { $a,$b = $r $d+=$args[0]+$a $s+=[char]$d if ($b -ne $null) { return recurse $d $b $s } return $s } function recurse() { $r = $args[1] $s = $args[2] . $t } . $t } recurse 0 ``` > > Returns "Hello world" in a very complicated way > > > [Answer] # **Ruby** ``` def handle(switch) case switch when 'a', print(switch << 'a') when 'n', print(switch.sub!('b','n')) when 'q', print(switch.gsub('b','q')) when 'b', nil else print('s!') end end handle('b') ``` [Demo](https://ideone.com/h9VJVK) [Answer] # Perl ``` print pack qq; \1108; ,hex for qw; 2e5d66e 4b88fad 4560770 3aedf79; ``` Prints a friendly message for a special day! > > Outputs `Happy Birthday!!` (Was given to a programmer friend who hates Perl.) > > The white space and semicolon as the delimiting characters are meant to deceive. > > **qq;\1108;** (equivalent to "H8") > > > The semicolons are the delimiters for the double quote method. \110 is the octal code for H, followed by a plain 8, giving us the packing code "H8", meaning 8 hex digits > > **hex** > > > Converts a hex string to an integer. No parameter means it runs on $\_ (default variable) > > **for qw;2e5d66e 4b88fad 4560770 3aedf79;** > > > The semicolons are the delimiters for the quoted list method. `for` indicates to run the entire block on the left once per each hex string. > > "Unobfuscated", the script is: > > `print pack("H8", hex($_)) for (2e5d66e 4b88fad 4560770 3aedf79);` > > Each of those hex values, when de-hexed into an 8 digit number, and then packed into a 4 characters, will print 4 of the letters of **Happy Birthday!!** > > > > > > > > > > > > > > > [**Run it here**](http://ideone.com/rCkc5b) [Answer] *The goal is to write program that will produce a word unexpected* I didn't read past that. I have a serious issue with reading long passages (and error messages). I decided to create a simple program that alerts "5". Unfortunately, I can't seem to get it to work. ``` (function () { "use strict"; function logError(e) { // I have a serious issue with reading long error messages // I'll just print the first word of the error and figure out what it means console.log(e.message.split(" ")[0]); } // Useful assert method for debugging function assert(value, message) { if (value === false) { throw new Error(message); } } // Sets a varaible "a" to 5 and alerts it try { // Try it the old fashioned way a = 5; alert(a); } catch (e) { logError(e); // In some legacy browsers, that might now work // because alert requires a string try { // create objA which has a method "word", which always returns a word, or a string var objA = { word: function () { return new String(5); } }; // Make sure it is a string assert(typeof objA.word() === "string", "word didn't return a string"); alert(objA.word()); } catch (e) { logError(e); // Some browsers, such as chrome, just won't work // It's time to be evil and force them to work! try { eval("a = 5" + "alert(a)"); } catch (e) { logError(e); } } } })(); ``` Tested in the google chrome console. It produces (literally) *a word unexpected*. <http://jsfiddle.net/prankol57/Af4sH/> (For the jsfiddle, you must open your console, there won't be any html output) [Answer] # Javascript > > alerts "hello" > > > ``` var $$ = String.fromCharCode;this[(+{}+[])[-~[]]+(![]+[])[-~-~[]]+([][+[]]+[])[-~-~-~[]]+(!![]+[])[-~[]]+(!![]+[])[+[]]]($$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((+!+[])+(-~+[]))*((+!+[])+(-~+[]))))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(-~+[]))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+$$(((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+(((!+![])^((+!+[])+(-~+[])))))); ``` *caveat: one variable declaration.(no time for changing `String.fromCharCode` to symbols)* [more readable code](http://pastie.org/private/ccpgdwddgstzwglkonktuw) (solution is derived from this code (it's mine BTW)) ### Ref: 1. <http://sla.ckers.org/forum/read.php?24,33349,33405> 2. <http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html> (inspired for accessing `alert` from symbols) [Answer] # Ruby ``` display(STDOUT) unless case class Do self end when method(:print).to_proc end ``` I've used this trick in an earlier underhanded contest, but I thought I'd dress up the output a bit differently. [Demo](https://ideone.com/QpiePQ) First person to explain where the word > > Domain > > > comes from wins a no-prize. [Answer] # JavaScript, 10 characters `alert(1/0)` Test it on <http://jsfiddle.net/cC52Z/>! ## Output > > Infinity > > > ## Explanation > > Instead of disallowing division by zero, JavaScript makes it always return Infinity (division of a negative by zero produces -Infinity). > > > [Answer] ## Emacs Lisp for version 22.1.1 (that comes on osx) Run this right on the command line `emacs -q --batch --eval "(progn (execute-kbd-macro \"\C-[xinfo\C-m\C-[xfun\C-i\C-m\C-u49\C-n\") (search-forward (string(+ ? ? (*)? )(+(/ ? (+(*)(*)(*))) ? ? ? (*(+(*)(*))(+(*)(*))))))(print (buffer-substring-no-properties (+(*)(*)(*)(point)) (progn (forward-word(*)) (point)))))"` Output: **"woman"** ![demo](https://i.stack.imgur.com/7giTB.gif) [Answer] ## Python Inspired by @Roberto's answer. ``` try: exec('from __future__ import braces') except Exception as e: print(e.msg) ``` > > Another Python easter egg; it prints: `not a chance` > > > [Answer] ## TI-BASIC ``` : ``` (Either type the colon on an empty screen, or make an empty program or one containing just colons.) Prints "Done" [Answer] # [Homespring](https://esolangs.org/wiki/Homespring) (Empty program) ### Output > > In Homespring, the null program is not a quine. > > > ### Why? > > Homespring prints this message when interpreting a empty program to prevent cheating at [quine](/questions/tagged/quine "show questions tagged 'quine'") code golf challenges > > > [Answer] # GolfScript ``` 0:b;"#{STDIN.inspect}"${b{..}{.}if 78={6-.1:b;}{}if;}% ``` Outputs: ``` HOST ``` [Try it out here.](http://golfscript.apphb.com/?c=MDpiOyIje1NURElOLmluc3BlY3R9IiR7YnsufXt9aWYgNzg9ezsnSCcxOmI7fXt9aWZ9JQ==) How it works: > > `"#{STDIN.inspect}"` returns `"#<IO:<STDIN>>"`. `$` sorts it into `"#:<<>>DIINOST"`. The rest of the program loops through the string, dropping chars until it finds an `N`. Then, it changes the `N` to a `H` and keeps the rest of the chars. > > > [Answer] ## Perl ``` #!perl eval('(*16,z<=:3??0<x06161xBBQ$8t'^(( '0'x27)^((((((('h'x6).'A'.'b'x5).'a'. 'h'x2).'A'.'h'x5).'A'.'H'x3).'f'x2)))) ``` > > **Output:** Mohammad Anini 3:) > > > [Answer] # Julia ``` (repr(typeof(""))*repr(typeof(' '))*repr(typeof(1//1)))[6:7:27] ``` Another option: ``` print(print()) ``` [Answer] # T-SQL ``` declare @S char(3) -- Declare a string variable that holds three characters set @S = 1000 -- Implicitly convert the value 1000 to string select ascii(@S) -- Get the ASCII code value of the leftmost character ``` Outputs > > The Answer to the Ultimate Question of Life, the Universe, and Everything > > > [SQL Fiddle](http://sqlfiddle.com/#!6/d41d8/18418) [Answer] ## JavaScript ``` for (var i in this) { if(parseInt(i[0]+i[2],16)==174) { this[i](i[0]+i[1]+i[2]); break; } } ``` Not the cleverest. But, I sure do like what it has to say! [Tested in Chrome](http://jsfiddle.net/Geq3Z/). [Answer] # Bash ``` <<< echo echo echo ``` or ``` `echo echo echo` ``` > > Both commands output `echo`, of course. > > > ]
[Question] [ ### Task Given two strictly positive integers **n** and **d** as input, determine whether **n** is [evenly divisible](https://en.wikipedia.org/wiki/Divisibility_rule) by **d**, i.e., if there exists an integer **q** such that `n = qd`. You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the our [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output. The output should be a [truthy or a falsy value](https://codegolf.meta.stackexchange.com/a/2194); truthy if **n** is divisible by **d**, and falsy otherwise. Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your *algorithm* has to work for arbitrarily large integers. You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.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 ``` n, d output 1, 1 truthy 2, 1 truthy 6, 3 truthy 17, 17 truthy 22, 2 truthy 1, 2 falsy 2, 3 falsy 2, 4 falsy 3, 9 falsy 15, 16 falsy ``` ### Leaderboard The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 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 = 86149; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; 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), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḍ ``` This took me hours to golf. [Try it online!](http://jelly.tryitonline.net/#code=4biN&input=&args=Mw+Ng) [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), ~~72~~ ~~70~~ ~~64~~ ~~62~~ ~~58~~ 46 bytes ``` {({}[()]{(<()>)}{}<({}[()]<({}())>)>)}{}{{}}{} ``` Takes dividend and divisor (in that order) as input and prints the divisor (truthy) or nothing. Since each stack has an implicit, infinite amount of zeroes, empty output should be considered falsy. While not stack-clean, this solution uses only a single stack. [Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fVsoKV17KDwoKT4pfXt9PCh7fVsoKV08KHt9KCkpPik-KX17fXt7fX17fQ&input=NDIgNw) *Thanks to @WheatWizard for golfing off 2 bytes!* ### How it works ``` INPUT: a (dividend), b (divisor) INITIAL STACK: n = a, d = b, r = 0 An infinite amount of zeroes follows. { While n is non-zero: ( {} Pop n from the stack. [()] Yield -1. { While the top of the stack (initially, d) is non-zero: (<()>) Push 0. } {} Pop 0. This will remove d from the stack if d = 0, leaving r on top. We can think of this as performing the assignment (d, r) = (r, d) if d = 0. < ( {} Pop d. [()] Yield -1. < ( {} Pop r. () Yield 1. ) Push r + 1. > Yield 0. ) Push d + (-1) + 0 = d - 1. > Yield 0. ) Push n + (-1) + 0 + 0 + 0 = n - 1. } Each iteration decrements n, swaps d and r if d = 0, decrements d, and increments r. FINAL VALUES: n = 0 d = b - r r = a % b if a % b > 0 else b {} Pop n. { While the top of the stack is non-zero: {} Pop it. } This pops d and r if d > 0 (and, thus, a % b > 0) or noting at all. {} Pop d or a 0, leaving r if r = b and, thus, a % b = 0. ``` ## Modulus calculation, 42 bytes The above full program can be modified in a trivial manner to calculate the modulus instead. ``` {({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{} ``` As before, this method is not stack-clean, but it uses only a single stack. A modulus of **0** will leave the stack empty, which is roughly equivalent to leaving **0**; each stack contains infinite zeroes. [Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fVsoKV08KHt9WygpXTwoe30oKSk-KT57KDwoKT4pfXt9KX17fXt9&input=NDIgOA) ### How it works Compare the two loops of the divisibility tester and the modulus calculator. ``` {({}[()]{(<()>)}{}<({}[()]<({}())>)>)} {({}[()]<({}[()]<({}())>)>{(<()>)}{})} ``` The only difference is the location of `{(<()>)}{}`, which swaps **d** and **r** if **d = 0**. To calculate the modulus, we perform this swap *after* decrementing **d** and incrementing **r**. This change does not affect the outcome if **a %b > 0**, but if **a % b = 0**, it leaves **(n, d, r) = (0, b, 0)** – rather than **(n, d, r) = (0, 0, b)** – on the stack. Thus, to obtain the modulus, we only have to pop **n** and **d** with `{}{}`. ## Stack-clean modulus calculation, 64 bytes The 42-byte modulus algorithm is not stack-clean, so it cannot be used as is in all programs. The following version pops dividend and divisor (in that order) from the active stack and pushes the modulus in return. It has no other side effects. ``` ({}(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}>) ``` This solution is largely based on @WheatWizard's previous 72-byte record, but it saves 6 bytes by never switching stacks. [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9KDwoKT4pKXsoe31bKCldPCgoe30oKVsoe30pXSkpe3t9KDwoe30oe30pKT4pfXt9Pil9KHt9e308e30-KQ&input=NDIgOA) ### How it works ``` INPUT: a (dividend), b (divisor) INITIAL STACK: n = a, b ( {} Pop and yield n = a. (<()>) Push d = 0. ) Push n + 0 = n. STACK: n, d = 0, b {( While n in non-zero: {} Pop and yield n. [()] Yield -1. < (( {} Pop and yield d. () Yield 1. [({})] Pop b, push it back on the stack, and yield -b. )) Push d + 1 + -b = d + 1 - b twice. { While/if d + 1 - b is non-zero, i.e., if d < b - 1 {} Pop d + 1 - b (second copy). (<( {} Pop d + 1 - b (first copy). ({}) Pop b and push it back on the stack. )>) Push d + 1 - b + b = d + 1, then 0. } If the loop wasn't skipped entirely, pushing 0 breaks out. If d < b - 1, it essentially performs the assignment d = d + 1. However, if d = b - 1, we get d = d + 1 - b = b - 1 + 1 - b = 0. In all cases, we wind up with d = (d + 1) % b. {} Pop 0. > Yield 0. )} Push n + -1 + 0 = n - 1. Break if n - 1 = 0. STACK: n = 0, d = a % b, b ( {} Pop and yield n = 0. {} Pop and d = a % b. <{}> Pop b, but yield 0. ) Push 0 + a % b + 0 = a % b. ``` [Answer] # x86\_32 machine code, 8 bytes ``` 08048550 <div7>: 8048550: 99 cdq 8048551: f7 f9 idiv %ecx 8048553: 85 d2 test %edx,%edx 8048555: 0f 94 c0 sete %al ``` This is my first code golf answer, so hopefully I'm following all the rules. This first calls cdq to clear out the edx register, then performs signed division on the ecx register, which stores the remainder in edx. The test edx, edx line will set the zero flag if edx is zero, and sete puts a 0 for false if edx was not zero, and puts a 1 for true if edx was 0. This is just the code snippet that contributes to the byte count, but for testing, [here](https://godbolt.org/g/Puxr5x) is the C code I wrote with the inline assembly because it's easier this way to handle I/O. [Answer] # Hexagony, ~~15, 13, 12~~ 10 bytes Everybody's favorite hexagon-based language! :D TL;DR works using magic, unformatted solutions in decreasing byte count: ``` ?{?..>1'%<.@!'/ ?{?!1\.'%<@.> ?{?\!1@'%\!( ?{?!1\@'%< ``` Saved 2 bytes thanks to @MartinEnder's layout wizardry. @FryAmTheEggman saved 1 byte by using the corners more creatively Both @MartinEnder and @FryAmTheEggman came up with a 10 byte solution that doesn't print anything for falsely values. [My solution](http://hexagony.tryitonline.net/#code=P3s_Li4-MSclPC5AIScv&input=MTIgNQ) (15): Unformatted: ``` ?{?..>1'%<.@!'/ ``` Formatted: ``` ? { ? . . > 1 ' % < . @ ! ' / . . . . ``` [@Martin Ender's Solution](http://hexagony.tryitonline.net/#code=P3s_ITFcLiclPEAuPg&input=MTIgMQ) (13): Unformatted: ``` ?{?!1\.'%<@.> ``` Formatted: ``` ? { ? ! 1 \ . ' % < @ . > . . . . . . ``` Explanation: First, we get the input and take the modulus. ``` ? { ? . . . . ' % . . . . . . . . . . ``` Then, it checks if the modulus is 0 or not. If it is, the IP turns 60 degrees left, bounces off the mirror, sets the cell to 1 and prints. Then, the IP continues onto the fourth row. When it reaches the `>`, it turns to the right instead (because the value of the cell is now 1). It goes oob, and comes back in the bottom right corner heading NW. The IP hits the `<`, goes along the top row, and comes back in the right corner to hit the `@`, stopping the program. ``` . . . ! 1 \ . . . < @ . > . . . . . . ``` If the modulus turns out to be positive, the IP turns 60 degrees to the right. Once it goes out the bottom right corner, it continues on the bottom left edge because of Hexagony's wrapping rules. The `'` is reused to make the IP go to a cell with 0 in it. The IP then travels along the fourth row, wraps around to the second, hits print, and gets reflected into the `<`. The rest of the path to the `@` is the same. ``` . . . ! . \ . ' . < @ . > . . . . . . ``` That's some serious wizardry. [@FryAmTheEggman's Solution](http://hexagony.tryitonline.net/#code=ICA_IHsgPwogXCAhIDEgQAonICUgXCAhICgKIC4gLiAuIC4KICAuIC4gLg&input=MTIgNA) (12): Unformatted: ``` ?{?\!1@'%\!( ``` Formatted: ``` ? { ? \ ! 1 @ ' % \ ! ( . . . . . . . ``` Explanation: Like the other solutions, it gets the input and takes the modulus. ``` ? { ? . . . . ' % . . . . . . . . . . ``` Then, the IP gets deflected into the bottom corner. If the modulus is positive, it goes on the top left edge. The `?` has no more input, so it sets the cell to 0. The `!` then prints the 0, and the `@` terminates the program. ``` ? . . \ ! . @ . . \ . . . . . . . . . ``` Things are much trickier for when the modulus is 0. First of all, it gets decremented, then reset to 0, then set to 1, then printed. Then, the 1 gets decremented to 0. After that, the program runs like it does at the beginning until it tries to do `0%0`. That makes it throw a silent error and quit. ``` ? { ? . . 1 . ' % \ ! ( . . . . . . . ``` I really like the silent error trick, but a simpler way would be to replace the `(` with `/` so that the IP passes through the first time, but gets reflected into `@` the second. [Collaborative solution](http://hexagony.tryitonline.net/#code=ICA_IHsgPwogISAxIFwgQAonICUgPCAuIC4KIC4gLiAuIC4KICAuIC4gLg&input=MTIgNQ) (10): Unformatted: ``` ?{?!1\@'%< ``` Formatted: ``` ? { ? ! 1 \ @ ' % < . . . . . . . . . ``` This program starts out the same as all the other programs, getting the input and modding it. If the input is 0, the IP turns left when it hits `<`. It gets deflected into `1!@`, which prints 1 and quits. ``` . . . ! 1 \ @ . . < . . . . . . . . . ``` If the input is positive, the IP turns right when it hits `<`. It exits through the corner, and goes along the top right edge hitting the @ without printing. ``` . . ? . . . @ . . < . . . . . . . . . ``` [Answer] # [Brain-flak](https://github.com/DJMcMayhem/Brain-Flak) ~~102, 98,~~ 96 bytes ``` (({}<>))<>{({}[()])<>(({}[()])){{}(<({}[({})])>)}{}({}({}))<>}{}<>([{}]{}){<>(([()])())}({}{}()) ``` Eww. Gross. I might post an explanation, but I barely understand it myself. This language hurts my brain. [Try it online!](http://brain-flak.tryitonline.net/#code=KCh7fTw-KSk8Pnsoe31bKCldKTw-KCh7fVsoKV0pKXt7fSg8KHt9Wyh7fSldKT4pfXt9KHt9KHt9KSk8Pn17fTw-KFt7fV17fSl7PD4oKFsoKV0pKCkpfSh7fXt9KCkp&input=NAoxMDA) Thanks to github user [@Wheatwizard](https://github.com/Wheatwizard) for coming up with a modulus example. I probably could not have figured that out myself! Also, the shorter answer is [here](https://codegolf.stackexchange.com/a/86570/31716). Possibly incorrect explanation: ``` (({}<>)) #Push this element onto the other stack <> #Move back to stack one. { #While the top element is non-zero: ({}[()]) # Decrement the number on top <> # Move to the other stack (({}[()])) # Push the top element minus one twice { # While the top element is non-zero: {} # Pop the top element (< >) # Push a zero ({}) # Push the second from top element [ ] # Evalue this second from top element as negative ({} ) # And push that negative plus the top element } {} # Pop the top element ({}({})) # Push the top element plus the second from the top, AND push the second from top <> # Switch stacks } {} #Pop the stack <> #Switch to the other stack ([{}]{}) #And push the top element minus the second element. ``` The rest is pretty straightforward. ``` { } #While the top element is non-zero: <> #Move to the other stack (([()]) ) #Push a negative one () #AND push the previously pushed value + 1 (e.g. 0) ( ) #Push: {}{} #The top two elements added together () #Plus one ``` [Answer] # Javascript (ES6) 17 12 11 bytes ``` a=>b=>a%b<1 ``` * **EDIT:** Removed 5 bytes because 'a>0' is expected. * **EDIT2:** Removed 1 byte thanks to **Downgoat**. [Answer] ## Mathematica - 17 13 3 bytes ``` ∣ ``` Thanks to @MartinEnder for saving a ton of bytes! [Answer] # Retina, 12 bytes ``` ^(1+)\1* \1$ ``` Takes space-separated input in unary, like `111111111111 1111` to check if **12** if divisible by **4**. Prints **1** (true) or **0** (false). [Try it online!](http://retina.tryitonline.net/#code=XigxKylcMSogXDEk&input=MTExMTExMTExMTExIDExMTE) ~~FryAmTheEggman saved two bytes.~~ Oops, rewrote my answer to take the arguments in the right order. (Then Fry beat me to it in the comments. I’m slow at regex!) [Answer] ## Batch, 20 bytes ``` @cmd/cset/a!(%1%%%2) ``` Outputs `1` on success, `0` on failure. [Answer] # Vim, 11 keystrokes ``` C<C-r>=<C-r>"<C-Left>%<C-Right><1<cr> ``` Not bad for a language that only handles strings. :D [Answer] ## C#, ~~27~~ ~~13~~ 12 Bytes ``` a=>b=>a%b<1; ``` Thanks to TuukkaX for pointing out anonymous lambdas are acceptable. Thanks to David Conrad for pointing me on to currying which I wasn't even aware was a thing. Short and sweet, since we're only dealing with integers we can use `<1` rather than `==0` and save a whole byte. [Answer] # brainfuck, 53 bytes Takes input as bytes, output is a byte value of `0x00` or `0x01`. It's the [DivMod algorithm](https://esolangs.org/wiki/Brainfuck_algorithms#Divmod_algorithm) followed by [Boolean negation](https://esolangs.org/wiki/Brainfuck_algorithms#x_.3D_not_x_.28boolean.2C_logical.29). ``` ,>,<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>,>[<+>,]+<[>-<-]>. ``` [**Try it online**](http://brainfuck.tryitonline.net/#code=LD4sPFstPi1bPis-Pl0-WytbLTwrPl0-Kz4-XTw8PDw8XT4sPls8Kz4sXSs8Wz4tPC1dPgorKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysu&input=ZDI) - Has a bunch of extra `+` near the end so you can see the output in ASCII. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~88~~ 86 bytes ``` (<({}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}<>(({}<{}>)){{}{}(<(())>)}{} ``` This is a denser version of [the original Brain-Flak divisibility test algorithm](https://codegolf.stackexchange.com/a/86157/31716) written by [~~Dr Green Eggs and Iron Man~~ DJMcMayhem](https://codegolf.stackexchange.com/users/31716/dr-green-eggs-and-iron-man) and myself. Here is a brief(ish) explanation of how it works: ``` ({}<>) #Move the top of the stack to the other stack #Start Mod (< >) #Push zero <> #Switch stacks { #While the top of the stack is not zero ({}[()]) #Subtract one from the top of the stack <> #Switch stacks {}() #Pop the top, add one and ... [({})] #Subtract the second element on the stack (( )) #Push twice { #If the top is not zero {} #Pop the duplicate ({}({})) #Add the second element to the first (< >) #Push zero } #End if {} #Pop the zero <> #Switch back } #End While <> #Switch to the other stack ({}<{}>) #Remove the second value on the stack #End Mod ( ) #Duplicate the result of modulation { #If the top is not zero {}{} #Pop the top two elements (<(())>) #Push a one and a zero } #End if {} #Pop the zero ``` [Try it Online!](http://brain-flak.tryitonline.net/) [Answer] ## LOLCODE, ~~74~~ 64 bytes ``` HOW IZ I f YR a AN YR b BOTH SAEM MOD OF a AN b AN 0 IF U SAY SO ``` [Answer] # Java 8, 11 bytes ``` a->b->a%b<1 ``` What the heck, there are JS and C# versions of this, why not a Java version, too? Usage: ``` import java.util.function.Function; public class Program { public static void main(String[] args) { System.out.printf("%d, %d %b%n", 9, 3, divides(9, 3, a->b->a%b<1)); System.out.printf("%d, %d %b%n", 3, 9, divides(3, 9, a->b->a%b<1)); } public static boolean divides(int a, int b, Function<Integer, Function<Integer, Boolean>> f) { return f.apply(a).apply(b); } } ``` [Answer] # C, 60 Bytes ``` #include <stdio.h> main(){int a,b;scanf("%d %d",&a,&b);a%b==0;} ``` [Answer] ## R, ~~22~~ 20 bytes ``` a=scan();!a[1]%%a[2] ``` As usually, reads two numbers from the input that is terminated by an empty line. Update: thanks to [Jarko Dubbeldam](https://codegolf.stackexchange.com/users/59530/jarko-dubbeldam) for shaving off 2 bytes (despite the fact that his edit was rejected, it was very helpful!). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 bytes ``` 0=| ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///38C25n/ao7YJj3r7HnU1P@pd86h3y6H1xo/aJj7qmxoc5AwkQzw8g/8rGCqkKQAJhUe9cxVKikpLMiq5IGJGqGLGIDEzFDFDc6AYkEBRZwQUMzLCFIPZkZaYUwwzzghFyARTyBIkZIwsZGgGstMUSQgA "APL (Dyalog Unicode) – Try It Online") Is zero equal to the division remainder? [Answer] # Python, 16 bytes ``` lambda D,d:D%d<1 ``` [Answer] # GolfScript, 3 bytes ``` ~%! ``` Explanation: ``` ~ # Evaluate the input % # Take the first modulus the second ! # Boolean not ``` [Try it online!](http://golfscript.tryitonline.net/#code=fiUh&input=) [Answer] ## CJam, ~~6~~ 4 bytes *Saved 2 bytes thanks to Dennis* ``` q~%! ``` [Try it online](http://cjam.aditsu.net/#code=q%20%20%20%20e%23%20Take%20in%20the%20input%0A%20~%20%20%20e%23%20Dump%20the%20individual%20values%20to%20the%20stack%0A%20%20%25%20%20e%23%20Modulus%0A%20%20%20!%20e%23%20Boolean%20NOT&input=16%205) ``` q e# Take in the input ~ e# Dump the individual values to the stack % e# Modulus ! e# Boolean NOT ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` %0 ``` [Try it online!](http://brachylog.tryitonline.net/#code=JTA&input=WzQyOjZd) [Answer] # Julia, 9 bytes ``` D\d=D%d<1 ``` [Try it online!](http://julia.tryitonline.net/#code=RFxkPUQlZDwxCgpmb3IgKEQsZCkgaW4gKFsxLDFdLCBbMiwxXSwgWzEsMl0sIFs2LDNdLCBbMyw2XSkKICAgIEBwcmludGYoIiVzIC0-ICVzXG4iLCBbRCxkXSwgRFxkKQplbmQ&input=) [Answer] ## Fortran 95, 78 bytes ``` function f(i,j)result(k) integer::i,j,k k=merge(1,0,MOD(i,j)<1) end function f ``` [Answer] ## MarioLANG, ~~121~~ ~~109~~ 107 bytes *Saved 14 bytes thanks to Martin Ender* ``` ;>(-)-)+(([!) )"=========#[ ; +(![-)< )<!+ ==#===" "#: >!< >(+ !![(< =#"="===##=:" ! < #======" ``` [Try it online!](http://mariolang.tryitonline.net/#code=Oz4oLSktKSsoKFshKQopIj09PT09PT09PSNbCjsgKyghWy0pPCApPCErCiAgPT0jPT09IiAgIiM6Cj4hPCA-KCsgISFbKDwKPSMiPSI9PT0jIz06IgogICEgICAgICA8CiAgIz09PT09PSI&input=MTIgNA) **Explanation** The algorithm is simply to keep subtracting `d` from `n` to see if you can do it an integer number of times and have no remainder. ``` ; ) ; > =     ``` First, the input is collected. `n` is in the first cell, `d` in the second. ``` >(-)-)+(([! "=========# )< " ! #"="===##=     ``` This is essentially the main loop. It decrements the first and second cells, and increments the third. ``` [!) =#[ !+ #:   (<   :"     ``` This is the final output. If after the incrementing/decrementing, the first cell is 0, then we've eliminated `n`. If after this, the second cell (`d`) is `0`, then `d` went into `n` evenly. We increment and print (`1`). Otherwise, move back to the first cell (which is `0`) and print it. ```       +(![-)< ==#==="  !< >(+ !![  #"="===##= ! < #======" ``` This loop happens if the second cell is `0` after incrementing and decrementing. It copies the third cell to the second cell. The part at the bottom is to bypass the loop if the cell is not `0`. [Answer] # Tcl , 34 bytes ``` ge stdin a ge stdin b exp $a%$b<1 ``` My first /\*successful\*/ attempt in codegolf ! This code must be executed in Tcl shell , otherwise it will not work. One byte thanks to @Lynn . Four bytes thanks to @Lynn and @LeakyNun (now I understand what he meant)! [Answer] # PHP, ~~23~~ 22 bytes ``` <?=$argv[1]%$argv[2]<1 ``` prints 1 for true, empty string (=nothing) for false call from cli with `n` and `d` as arguments --- 10 bytes for ancient PHP: `<?=$n%$d<1` [Answer] # J, 3 bytes ``` 0=| ``` Usage: ``` 2 (0=|) 10 ``` Will return `1`. And is equivalent to pseudocode `10 MOD 2 EQ 0` *Note this is very similar to the [APL answer](https://codegolf.stackexchange.com/questions/86149/divisibility-test/86153#86153), because J is heaviliy inspired by APL* [Answer] ## PowerShell v2+, 20 bytes ``` !($args-join'%'|iex) ``` Takes input as two command-line arguments `$args`, `-join`s them together into a string with `%` as the separator, pipes that to `iex` (short for `Invoke-Expression` and similar to `eval`). The result is either `0` or non-zero, so we take the Boolean not `!` of that result, which means either `$TRUE` or `$FALSE` (non-zero integers in PowerShell are truthy). That Boolean is left on the pipeline and output is implicit. ### Alternative versions, also 20 bytes each ``` param($a,$b)!($a%$b) !($args[0]%$args[1]) ``` Same concept, just slightly different ways of structuring the input. Thanks to @DarthTwon for providing these. ### Examples ``` PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 24 12 True PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 24 13 False PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 12 24 False ``` [Answer] # Haskell, ~~13~~ 11 bytes ``` ((1>).).mod ``` This defines a new function `(!) :: Integral n => n -> n -> Bool`. Since `mod n m` returns only positive numbers if `n` and `m` are positive, we can save a byte by using `1>` instead of `0==`. Usage: ``` ghci> let n!d=1>mod n d ghci> 100 ! 2 True ghci> 100 ! 3 False ``` ]
[Question] [ You are to write a program which generates random integers between \$0\$ and \$99\$ inclusive, outputting each integer in turn, until \$0\$ is generated. You may choose which single-order random distribution (uniform, binomial, Poisson etc.) you use so long as each integer has a non-zero chance of being generated and is chosen independently. The output should always end with `0`. As each integer must be chosen independently, the output cannot be some permutation of the integers \$\{0, 1, 2, ..., 99\}\$ trimmed to end with \$0\$. You may follow another method to accomplish the same task, so long as the result is identical to the described method here (for example: you may generate a number \$K\$ geometrically distributed with parameter \$\frac 1 {99}\$, then output \$K\$ independent numbers with a uniform distribution on the set \$\{1, 2, ..., 99\}\$, then output a \$0\$). The integers may be separated by any non-digit, non-empty separator (e.g. newlines, spaces etc.), and may be output in any consistent base. You may output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) or [format](https://codegolf.meta.stackexchange.com/q/9501/66833). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. [Answer] # [Scratch 3.0](https://scratch.mit.edu), 9 blocks/76 bytes [![beautiful](https://i.stack.imgur.com/6XofW.png)](https://i.stack.imgur.com/6XofW.png) As SB Syntax: ``` define set[N v]to(1 repeat until<(N)=(0 set[N v]to(pick random(0)to(99 say(N ``` [Try it on Scratch](https://scratch.mit.edu/projects/480455636/) It just wouldn't be right if I didn't golf this in scratch. This is a function that achieves the desired result ## Explained ``` define // Create a function with no name (not a lambda) set[N v]to(1 // Initalise the variable we will use to generate random numbers with // If we didn't set it to 1, the next loop wouldn't start, as it would see that N = 0. repeat until<(N)=(0 // Pretty self-explanatory set[N v]to(pick random(0)to(99 // Also pretty self-explanatory. But putting this here means we don't have to include two calls to this block: we've essentially created a post-test loop instead of a pre-test loop say(N // Output the randomly generated number and repeat ``` [Answer] # [Python 3](https://docs.python.org/3/), 58 bytes ``` from random import* print(*iter(lambda:randint(0,99),0),0) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVaGhllqQWaeQk5ialJFqBVIAEDXQsLTV1DEDo/38A "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), 25 bytes ``` c(sample(99,rexp(1),T),0) ``` [Try it online!](https://tio.run/##dcwxCsAgDADA3Ve4mYCDjvqOfiBICoLaoBbs620/0PWG63snGFSlMIRgOy8Bj/ZA63AnmmBUZ2Ga2junZ648olIG1SCR8oCPn9vzbmnmq8HC3w33Cw "R – Try It Online") p(0) at each iteration is (e-1)/e. p(each other number) at each iteration is (1/e)\*(1/99). Obviously this choice of random distribution gives a rather unsatisfying-looking output (since most of the runs are rather short). So [this link](https://tio.run/##fcwxCsAgDADA3Ve4NYFQdNR39AMiKQhqg1qwr7d9Qdcbrq0VoYcimcE5ajwFLO3GIh1IBlcMAzbVWDgMbY3RIxXuXqkNVQ8i@QHrP6fzrnGkq8LE3xHXCw) uses the same approach, but changes p(0) to roughly 0.01 to illustrate some longer runs... **What's going on?** ``` rexp(1) # First determine where the '0' will occur: # We generate a single random number using # an exponential distribution with a # rate parameter equal to 1 # (so the chance of any value x is e^-x). c( ,0) # Now place '0' at the subsequent position, sample(99,rexp(1),T) # and fill all the previous positions with # numbers sampled from 1 to 99, # with replacement (specified by the 'T' for TRUE). ``` [Answer] # [Random Brainfuck](https://github.com/TryItOnline/brainfuck), ~~67~~ ~~66~~ ~~65~~ 49 bytes ``` +[>>-[>++<-----]>--<?[>->+<[>]>[<+>-]<<[<]>-]>>.] ``` [Try it online!](https://tio.run/##FcnBCYBAEAPAgpZYQYiFhH2ciiDiCQfWv@p8Z7S@3ReW0Y6@P@tZFZZgRRC/FMDZgoJWygwhSfOblKasegE "Random Brainfuck – Try It Online") Finally found a use for this silly variant. Assumes wrapping cells and that the tape will never overflow (which would be statistically improbable). Basically, Random Brainfuck is just normal Brainfuck, except it adds the `?` opcode which reads a byte from `/dev/urandom`. All I have to do is modulo 100. I move forward 6 bytes each iteration. Outputs random **bytes** to stdout. ``` + (1) 0 0 0 0 [ do # advance tape two places for sentinel >> 0 (0) 0 0 # set 100 # https://esolangs.org/wiki/Brainfuck_constants#100 -[>++<-----]>-- 0 0 0 (100) 0 # Read random byte <? 0 (rng) 100 0 # mod 100 # https://esolangs.org/wiki/Brainfuck_algorithms#Modulus_algorithm [>->+<[>]>[<+>-]<<[<]>-] 0 (0) * rng % 100 # move left and print >> 0 0 * (rng % 100) . print ] while rng % 100 != zero note: start ``` The equivalent C algorithm: ``` void print_random(void) { uint8_t rng; do { rng = randbyte() % 100; putchar(rng); } while (rng != 0); } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~19~~ 18 bytes -1 byte thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)! ``` loop{1/p(rand~99)} ``` [Try it online!](https://tio.run/##KypNqvz/Pyc/v6DaUL9AoygxL6XO0lKz9v9/AA "Ruby – Try It Online") `rand~99` generates a random integer below `abs(~99)=abs(-100)=100`, `p` prints it to the output and returns the integer as a function and `1/x` fails for `x==0`, stopping the program. [Answer] # [R](https://www.r-project.org/), ~~30~~ 29 bytes ``` while(print(sample(0:99,1)))T ``` [Try it online!](https://tio.run/##K/r/vzwjMydVo6AoM69EozgxtwDIMbCytNQx1NTUDPn/HwA "R – Try It Online") `print` returns its argument invisibly, so this will choose an integer from 0-99 uniformly at random until a `0` is printed, because `0` is falsey in R. Uses the "do-`while`" [tip](https://codegolf.stackexchange.com/a/157131/67312). Thanks to Robin Ryder for saving a byte. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ♀(wo▲ ``` [Try it online.](https://tio.run/##y00syUjPz0n7///RzAaN8vxH0zb9/w8A) **Explanation:** ``` ▲ # Do-while true (!=0) with pop, # using the entire program implicitly as inner code-block: ♀ # Push 100 ( # Decrease it to 99 w # Pop and push a random integer within the range [0,99] o # Print it with trailing newline (without popping) ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~52~~ 50 bytes -2 bytes inspired by [EasyasPi's answer](https://codegolf.stackexchange.com/a/218184/64121). Produces some integers with probability \$\frac 2 {256}\$ and some with probability \$\frac 3 {256}\$ in each iteration. ``` import os while id:print(id:=os.urandom(1)[0]%100) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRCG/mKs8IzMnVSEzxaqgKDOvRAPIsM0v1istSsxLyc/VMNSMNohVNTQw0Pz/HwA "Python 3.8 (pre-release) – Try It Online") Uses the builtin function `id` to avoid assigning a new variable before the loop. [`os.urandom(size)`](https://docs.python.org/3/library/os.html#os.urandom) returns a `bytes` object with `size` random bytes. The `bytes` object behaves quite similar to a list of integers, which means `os.urandom(1)[0]` gives a single random integer from \$[0,255]\$, which we map to an integer from \$[0,99]\$ with a modulo operation. --- # [Python 3.8](https://docs.python.org/3.8/), 53 bytes Generates integers from a uniform distribution over \$[0, 99]\$. ``` from random import* while id:print(id:=randint(0,99)) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P60oP1ehKDEvBUhl5hbkF5VocZVnZOakKmSmWBUUZeaVaAAZtiAVILaBjqWlpub//wA "Python 3.8 (pre-release) – Try It Online") [Answer] # Batch, 48 bytes ``` @set n=%random:~-2% @echo %n% @if %n% gtr 0 %0 ``` Works by taking the random number as a string and extracting the last two digits. (But the comparison is a numeric comparison so 00 still compares equal to 0.) 50 bytes if leading zeros are not allowed: ``` @set/an=%random%%%100 @echo %n% @if %n% gtr 0 %0 ``` [Answer] # [Bash (coreutils)](https://www.gnu.org/software/bash/), 22 bytes ``` shuf -ri0-99|sed /^0/q ``` [Try it online!](https://tio.run/##S0oszvj/vzijNE1BtyjTQNfSsqY4NUVBP85Av/D/fwA "Bash – Try It Online") Bash is amazingly short here. Using the little-known sed `q` (quit) command. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 24 bytes ``` for(;$x=random 100){$x}0 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SMNapcK2KDEvJT9XwdDAQLNapaLW4P9/AA "PowerShell – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` W O100 ``` [Try it online!](https://tio.run/##K6gsyfj/P5zL39DA4P9/AA "Pyth – Try It Online") --- Python 3 translation: ``` from random import randrange def n(b): print(b) return b while n(randrange(100)): pass ``` [Answer] # x86-16 DOS .COM file, ~~15~~ 10 bytes Machine code: ``` 00000000: 0f c7 f0 d4 64 cd 29 75 f7 c3 ....d.)u.. ``` Assembly: ``` // sed -i -e 's#//#;#g' dosrand.asm // nasm -f bin dosrand.asm -o dosrand.com [bits 16] org 100h section .text start: .loop: // don't mind the completely non-suspicious AVX instruction // ax -> rand() rdrand ax // al -> al % 100 // ah -> al / 100 // set flags on al aam 100 // putchar(al) int 29h // Loop if aam didn't return zero jnz .loop .end: // return to dos (jumps to 0000h which is int 20h) ret ``` [Try it online!](https://tio.run/##XU7LDoIwELzzFZt4hiCe5Bv8B7OUAjXbR9qSFD/eysO06h52sjOT2UHnuOxoKUfGYiWU53R3i/IYQGlj@SBCUY2kOwKJQhXbamN1I61NW8BnbG9R9QAYEoUodzzXdeJO4IScCT2H9RM01ylJZnbT8HNtyL8CGRIdmmcT2uzVBv69K5fDHuq541E6d@Y@xhcbCEcXS3lp3g) (`int 29h` simulated with `pushf/popf` and `putchar`) [This binary needs a 2013 processor running a 1981 operating system](https://tvtropes.org/pmwiki/pmwiki.php/Main/AnachronismStew). Nothing weird here. 😛 Specifically, it requires [the `rdrand` instruction](https://www.felixcloutier.com/x86/rdrand) introduced in Ivy Bridge. However, QEMU supports this even on non-x86 hosts with `-cpu max`. Prints raw bytes to stdout. I might make a version for i386 using `printf` later, but I like this meme better. Thanks to 2x-1 for recommending `int 29h` and saving 5 bytes! Note that a solution using `mov al, 100; out 41h, al; in al, 41h` was suggested for a portable alternative, but I was unable to get it to work properly; they either infinite looped or the data wasn't random enough depending on the DOS implementation I used (NTVDMx64, DOSBOX, and QEMU/FreeDOS). [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` {{100.rand+|0}...0} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/utrQwECvKDEvRbvGoFZPT8@g9n9BaYlC2n8A "Perl 6 – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 61 bytes (recursive) ``` Object f(){int r=100;return(r*=Math.random())<1?r:r+" "+f();} ``` [Try it online!](https://tio.run/##JY3BCsIwEETv/YrFU6IY2qtR/ILiwaN4SNOqG9ukbDaClH57DDi3YZj3nPmYvevfGac5EIMrXSXGUT2St4zBq62u7GhihNagh6WKbBhtvnRusAwPIRf0DHRq6lrTwIm8oO2pNfxSZHwfJiHlsTnTgXYb2OzKQa8ZYE7diBb@NPgE7GEqAnFlQv@83cHQM8rig5LrN/IwqZBYzWXm0YvCkbqMa7XmHw "Java (JDK) – Try It Online") ``` Object f(){ // Method returning an Object because it either returns an Integer or a String. int r=100; // Initialize r as an int(eger) to 100. return // The rest can be inlined, so use the return here. ( r*=Math.random() // Multiply 100 by a random double number in range [0,1). // Also, *= is a compound operator that implies a cast, // therefore changing the double to an int at no cost. // So now, r is an integer in range [0,100). )<1? // If the multiplied number is zero (the only possible value below 1) r // Return r as an int, which is automatically boxed to an Integer. // Technically, r is 0, so I could have written 0 instead of r // This is the recursion-closing branch. : // Otherwise r+" "+f(); // Return a String, composed of r, a space and the result of the next call to f() // which may either be another String or 0. } ``` # Java (JDK), 64 bytes (iterative) ``` v->{for(int r=1;r>0;System.out.println(r*=Math.random()))r=100;} ``` [Try it online!](https://tio.run/##HYyxisMwEER7f8WWUiDCqXV2c3WqQJqQYk@2c/JJK7NaGY7gb3eUVMPMPN6MKx7n4W/3cUksMNduivhgpkJOfCJzsI0LmDOc0RM8G4Cl/ATvIAtKjTX5AWL91EXY0@N2B@RH1h8U4DtRLnHkr2vlepi6fT32zymx8iTA3cly39rLf5YxmlTELFUigRQfujPKr2GkIUWlta5w29pttx/xZNC5cRFFJQT93rZm218 "Java (JDK) – Try It Online") ## Credits * -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) on the iterative version [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 25 bytes ``` ./^0/^{L$`^ 99* \L@$` $.` ``` [Try it online!](https://tio.run/##K0otycxLNPz/X08/zkA/rtpHJSGOy9JSiyvGx0ElgUtFL@H/fwA "Retina – Try It Online") Explanation: ``` . ``` Suppress the default output. ``` /^0/^{ ``` Repeat until the value is zero. ``` L$`^ 99* ``` Replace the value with 99 `_`s. ``` \L@$` $.` ``` Take the length of a random prefix and also output it on its own line. [Answer] # [Factor](https://factorcode.org/), 29 bytes -4 bytes thanks to @Bubbler. ``` [ 100 random dup . 0 > ] loop ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFQlJiXkp@rUFCUWlJSWVCUmVeiYP0/WsHQwAAmlVJaoKCnYKBgpxCrkJOfX/D/PwA "Factor – Try It Online") [Answer] # [Phooey](https://github.com/ConorOBrien-Foxx/Phooey), 9 bytes ``` (&~r99$c) ``` [Try it online!](https://tio.run/##K8jIz0@t/P9fQ62uyNJSJVnz/38A "Phooey – Try It Online") Dumps raw bytes to stdout. ``` ( do & set cell to 0 by popping from empty stack ~r99 generate random from cell to 99 $c print as byte ) while cell is nonzero ``` # Phooey, integer output, 12 bytes ``` (&~r99$i" ") ``` [Try it online!](https://tio.run/##K8jIz0@t/P9fQ62uyNJSJVNJQUnz/38A) Does the same thing, only instead of printing as a raw byte, it prints it as an integer and adds a space. [Answer] ## Javascript (V8), 39 bytes -4 bytes thanks to [Redwolf Programs](https://codegolf.stackexchange.com/users/79857/redwolf-programs) and [aaaidan](https://codegolf.stackexchange.com/users/51510/aaaidan). ``` do print(a=Math.random()*99|0);while(a) ``` --- ## Javascript (V8), ~~45~~ 43 bytes -2 bytes thanks to [EasyasPi](https://codegolf.stackexchange.com/users/94093/easyaspi). ``` do{a=~~(Math.random()*99);print(a)}while(a) ``` ``` do { a = ~~ (Math.random()*99); print(a) } while(a) ``` Uses a double bitwise NOT operator (~), as a [substitute for Math.floor](http://rocha.la/JavaScript-bitwise-operators-in-practice). [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/PyW/OtG2rk7DN7EkQ68oMS8lP1dDU8vSUtO6oCgzr0QjUbO2PCMzJ1Uj0c5A8/9/AA "JavaScript (V8) – Try It Online") [Answer] # [Random Brainfuck](https://github.com/TryItOnline/brainfuck), 37 bytes ``` +[>-[>++<-----]>--[->?[<<+>>[-]]<]<.] ``` [Try it online!](https://tio.run/##FcHRCYAwEAPQgY44wREHCfmoiiDSCgXnP/G92cbxdGyzXeN897sqRIgRiZ8JCFyVGaRgp3NxVX0 "Random Brainfuck – Try It Online") This answer is inspired by EasyasPi's solution, but I am avoiding modulo by not even trying to get a uniform distribution. This theoretically should work, but practically will take a long time to finish. If you change the code setting the cell to 100 to a lower number you will see that it indeed terminates at some point. ``` + ; initialise cell[0] with 1 [ > ; make cell[1] the new cell[0] -[>++<-----] ; set cell[1] to 100 >-- [->?[<<+>>[-]]<] ; 100 times increment cell[0] with some probability < . ; print cell[0] ] ; until cell[0] is 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ³X’+ƲƬI; ``` [Try it online!](https://tio.run/##y0rNyan8///Q5ohHDTO1j206tsbT@v9/AA "Jelly – Try It Online") ## Explanation ``` ³X’+ƲƬI; Main niladic link Ƭ Repeat and collect results until there's a duplicate result Ʋ ( ³ 100 X Choose a random number from 1 to 100 ’ Decrement (to get a number from 0 to 99) + Add to the current value Ʋ ) I Increments (deltas) ; Join with the implicit argument, 0 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15 11 10 33~~ 16 bytes ``` 100,∘?⍨⍣{0=⊃⌽⍺}⍬ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@GxoY6DzqmGH/qHfFo97F1Qa2j7qaH/XsfdS7q/ZR75r/QDX/0wA "APL (Dyalog Unicode) – Try It Online") A full program which outputs the numbers separated by spaces. Uses `⎕IO←0` (0-indexing). -4 then -1 byte from Adám. -19 bytes from 1\_am\_Jack. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [99ÝΩ=_# ``` [Try it online.](https://tio.run/##yy9OTMpM/f8/2tLy8NxzK23jlf//BwA) **Explanation:** ``` [ # Start an infinite loop: 99Ý # Push a list in the range [0,99] Ω # Pop and push a random integer from this list = # Print it with trailing newline (without popping) _ # Pop and if this integer is 0: # # Stop the infinite loop ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~10~~ 9 bytes ``` {S100mr}h ``` [**Try it online!**](https://tio.run/##S85KzP3/vzrY0MAgt6g24/9/AA) Prints each number with a space before it. ### How it works ``` { }h e# Do-while loop, withput consuming the condition. Nonzero is truthy S e# Push space 100 e# Push 100 mr e# Random integer with uniform distribution on [0 1 2 ... 99] e# Implicit output ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~59~~ \$\cdots\$ ~~44~~ 42 bytes Saved 2 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! Saved a byte thanks to [Davide](https://codegolf.stackexchange.com/users/100356/davide)!!! ``` f(i){for(;printf("%d ",i=rand()%100),i;);} ``` [Try it online!](https://tio.run/##TY3BCsIwEETv@YolUNilLSTn2D/xEtKkLNRYUkGh5NeNsVZxTjNvZ1jXT86VEpBpC9eEZkkcbwFlM4LseEg2jkiNVoo6NmRyqWe4WI5IYhNQVWeAb8px9A8YQJnDnkBX37Z7IvjU9wmS@YXvx3OUf3SdvV9QHySLXJ4uzHZaS39/AQ "C (gcc) – Try It Online") Keeps on printing random integers in \$[0,99]\$ until \$0\$ is printed. [Answer] # [Python 3](https://docs.python.org/3/), ~~66~~ 56 bytes ``` from random import* x=1 while x:x=randint(0,99);print(x) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocVXYGnKVZ2TmpCpUWFXYgiQz80o0DHQsLTWtC4pA7ArN//8B "Python 3 – Try It Online") Thank you to [xnor](https://codegolf.stackexchange.com/users/20260/xnor), [danis](https://codegolf.stackexchange.com/users/99104/danis) and [mhawke](https://codegolf.stackexchange.com/users/61175/mhawke) for showing new stuff and helping improve the code! [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 10 bytes ``` ⁸‹#£D§D,X‽ ``` [Try it online!](https://tio.run/##y8/INfr//1HjjkcNO5UPLXY5tNxFJ@JRw97//wE "Ohm v2 – Try It Online") **Commented:** ``` ⁸‹# push a list containing the integers in the range [0-99] £ X‽ while the the picked number is not 0 D duplicate the list and §D, pick a random number from the list and display it ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 40 bytes ``` f(r){printf("%3d",r=rand()%100)*r&&f();} ``` [Try it online!](https://tio.run/##HYrLDkAwEADv/YqGkF1BKo4e/yKt0oQlq07i2@sxp8lkdDFpHWJHejnNKNvDG7eVcx8sMF47O/IWoqQ2Uc4dD2QAk0opzDhNLWBzh/eQ6@AIUFxCvnxZ/MajP5mkasQdHg "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~26 23~~ 21 bytes *@KjetilS's comment inspired me to save even more bytes than suggested, and @DomHastings got another 2 bytes off by changing to `$=`* ``` say$==rand 100while$= ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLF1rYoMS9FwdDAoDwjMydVxfb//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Answer] # [Lua](https://www.lua.org/), 43 bytes ``` repeat a=math.random(0,99)print(a)until a<1 ``` [Try it online!](https://tio.run/##yylN/P@/KLUgNbFEIdE2N7EkQ68oMS8lP1fDQMfSUrOgKDOvRCNRszSvJDNHIdHG8P9/AA "Lua – Try It Online") ]
[Question] [ Given a pattern (string or array format) of Bits : `[0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]` The tasks is to replace any number of consecutive 1-Bits with an ascending number sequence starting at 1. **Input** * Pattern (can be received as an string or array) Example: + String: `1001011010110101001` + Array: `[1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1]` **Output** * Ascending number sequence (can be returned as an string or array) Example: + String: `1 0 0 1 0 1 2 0 1 0 1 2 0 1 0 1 0 0 1` + Array: `[1, 0, 0, 1, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 0, 1, 0, 0, 1]` **Rules** * *(only apply for strings)* Input wont contain spaces between `1` and `0` * Assume Input `length > 0` * *(only apply for strings)* Output is separated by space (use any other separator if you need as long as is not a number or a letter from the alphabet) **Example:** ``` Given [0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1] Output [0,1,2,3,0,1,2,0,0,0,1,2,3,4,5,6] -------------------------------------------------------------------------- Given 0110101111101011011111101011111111 Output 0 1 2 0 1 0 1 2 3 4 5 0 1 0 1 2 0 1 2 3 4 5 6 0 1 0 1 2 3 4 5 6 7 8 --------------------------------------------------------------------------- Given 11111111111101 Output 1 2 3 4 5 6 7 8 9 10 11 12 0 1 ``` --- Winning criteria: Codegolf [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` γ€ƶ˜ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OZHTWuObTs95///aAMdQzA0gJIGOjARMIwFAA "05AB1E – Try It Online") or as a [Test Suit](https://tio.run/##MzBNTDJM/V9TVhn8/9zmR01rjm07Ped/pdLh/Qq6dgqH9yvp/DcwNDQEYgMDEAMIuEAcQwgHTEPFYWIgJYZIwMAQAA) **Explanation** ``` γ # split input into groups of consecutive equal elements €ƶ # multiply each number in each sublist by its 1-based index in the sublist ˜ # flatten ``` [Answer] # [Haskell](https://www.haskell.org/), 15 bytes ``` scanl1$(*).succ ``` [Try it online!](https://tio.run/##bVHLboMwELzzFaMoB6g2CEiTtlLopVJvPfdAOFhgEquOQba59ONLlygv2mgl27s7M16P98J9Sa2HBjm2g6uE0ek8fIhi11fVoEzXe4c8AAoUKd2PhNKSEYQiOeeUTPt07dyr38RE6cpLpsgRVQaBla7XtwNmtKRHWtGanuiZXihlFsOzPzNml7vPhGt@W13/wx2FJ0rLCy@ZIk8zHoQybG7dcqoaCFNjjm/VfSq/R7hVsFi8ooFCnsNGOHl@fprfS8NMcMH31iCMOJPayWNRWttazN6F0rKGl867OJ4F3DuI7gNhZ5XxiFk@ZgFRR7xrZSRbttlgJ/1ba7w03g1FGRRsUZGM@2gWr@P59AHlT9VosXPDouq6Xw "Haskell – Try It Online") ### Explanation/Ungolfed `scanl1` iterates from left over a list using a function which takes the last result and the current element generating a new list with the results, leaving empty lists and singletons "unmodified". `(*).succ` is the equivalent of `\x y-> (x+1)*y` Using that function together with `scanl1` only works because the increasing sequences (*1,2,3,..*) start with *1* and either have no preceding element (in which case it's the first element in the list which won't be "modified") or they have a leading *0*. [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` c=0 for i in input():c=c*i+i;print c ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9nWgCstv0ghUyEzD4gKSks0NK2SbZO1MrUzrQuKMvNKFJL//4820DEEQwMoaaADEwHDWAA "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~5 4~~ 3 bytes ``` ṁ∫g ``` [Try it online!](https://tio.run/##yygtzv7//@HOxkcdq9P///8fbaBjCIYGUNJAByYChrEA "Husk – Try It Online") ### Explanation ``` ṁ∫g -- full function, example input: [1,1,1,0,1] g -- group: [[1,1],[0],[1]] ṁ -- map the following and concatenate result (example with [1,1,1]) ∫ -- | cumulative sum: [1,2,3] -- : [1,2,3,0,1] ``` **Edit history** -1 byte by using `scanl1` over `zipWith` -1 byte by porting [Dennis](https://codegolf.stackexchange.com/users/12012/dennis?tab=profile)'s [solution](https://codegolf.stackexchange.com/a/167594/48198) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 bytes ``` ⊥⍨¨,\ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXUsf9a44tEIn5v9/AwVDBSMFEAlhGSuYKJgi8ZFFzTDUmSmYK1g86lyYBhY1hMvDIIKPLIqpDgy50MxVsFQwBCoCyoCdAbbGEAcEygMA "APL (Dyalog Unicode) – Try It Online") ### How it works ``` ⊥⍨¨,\ ,\ ⍝ Convert to lists of first n elements ⊥⍨¨ ⍝ Map "Count trailing ones" to each list ``` [Answer] # JavaScript (ES6), 22 bytes Takes input as an array. ``` a=>a.map(s=n=>s=n*-~s) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKPYNs/WDkho6dYVa/5Pzs8rzs9J1cvJT9dI04g20DEEQwMoaaADEwHDWE29rPzMPA11HXVNTS6seg3gug3R@CgmYagjbL6hDnZogKbvPwA "JavaScript (Node.js) – Try It Online") The shorter `a=>a.map(n=>a=n*-~a)` (20 bytes) would unfortunately fail on `[1]` because of coercion of singleton arrays to the integer they're holding. [Answer] # [J](http://jsoftware.com/), 4 bytes ``` #.~\ ``` A port of Bubbler's APL solution [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F9Zry7mvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkIaUJUhGBpASQO4CBiiKjOAKzRE46NowlAHgTCzDHFAkA6F/wA "J – Try It Online") # [J](http://jsoftware.com/), 8 bytes ``` i.&0@|.\ ``` ## How? It's simply the distance to the preceding `0` ``` \ for each prefix |. reverse it @ and i.&0 find the index of the first 0 ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D9TT83AoUYv5r8ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CGlClIRgaQEkDuAgYoiozgCs0ROOjaMJQB4EwswxxQJAOhf8A "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ 38 bytes -1 byte thanks to Erik the Outgolfer ``` i=1 for x in input():i*=x;print i;i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWkCstv0ihQiEzD4gKSks0NK0ytWwrrAuKMvNKFDKtM7VtDf//jzbQMQRDAyhpoAMTAcNYBQA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ‘×¥\ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4zD0w8tjfn//3@0gY4hGBpASQMdmAgYxgIA "Jelly – Try It Online") ``` ‘×¥\ \ Accumulate the input with: ¥ The dyad ‘ Increment the left element × Multiply by the second element (1 or 0) The result always begins with the first element unchanged ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ŒgÄF ``` [Try it online!](https://tio.run/##y0rNyan8///opPTDLW7/H@7eEvaoaQ0QHW4HEu7//xsYGhoCsYEBiAEEXCCOIYQDpqHiMDGQEkMkYGAIAA "Jelly – Try It Online") ### How it works ``` ŒgÄF Main link. Argument: A (bit array) Œg Group adjacent, identical bits. Ä Accumulate; take the cumulative sum of each chunk. F Flatten. ``` [Answer] # [R](https://www.r-project.org/), ~~46~~ 31 bytes ``` function(a)sequence(rle(a)$l)*a ``` [Try it online!](https://tio.run/##K/qfpmCjq6DwP600L7kkMz9PI1GzOLWwNDUvOVWjKCcVyFXJ0dRK/J@mkaxhoGMIhgZQ0kAHJgKGmpr/AQ "R – Try It Online") `sequence`, which ["mainly exists in reverence to the very early history of R"](https://stat.ethz.ch/R-manual/R-devel/library/base/html/sequence.html), is quite handy here. ``` function(a) # function, taking a vector as argument rle(a)$l # take the lengths of the run-length encoding sequence( ) # and generate the list [1:x for x in lengths] *a # multiply by a to maintain 0s, and return ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~11~~ 8 bytes **Solution:** ``` {y*1+x}\ ``` [Try it online!](https://tio.run/##y9bNz/7/v7pSy1C7ojbGQMEQCA2gGAYRfGRRTHVg@P8/AA "K (oK) – Try It Online") **Explanation:** Iterate over the list. Increment accumulator, multiply by current item (which resets accumulator if item is 0): ``` {y*1+x}\ / the solution { }\ / iterate (\) over lambda function x / accumulator 1+ / add 1 y* / multiply by current item ``` [Answer] # [TIS](https://github.com/Phlarx/tis), 68 + 33 = 101 bytes Code (68 bytes): ``` @0 MOV UP ACC SUB 47 MOV ACC ANY @1 ADD 1 JRO UP SUB ACC MOV ACC ANY ``` Layout (33 bytes): ``` 2 1 CC I0 ASCII - O0 NUMERIC - 32 ``` [Try it online!](https://tio.run/##TcpBCoAgFATQ/T/FXEDwW9A20xYGZhQGHSFoV/f/WStnNzPvOW@RXlNMO/IC6xxteUDb/UupsPNBPZP1HkzTmgr7yUcrI8JVNIu6xIBR3qBhNxcCFJLGnOO4BldKY14 "TIS – Try It Online") Explanation: ``` | Input 0 | Input is given in ASCII (`0` is 48, `1` is 49) +--------+------+ | Node 0 | | This node prepares the input data +--------+ | | MOV UP ACC | Read in a character | SUB 47 | Subtract 47 to map [48, 49] to [1, 2] | MOV ACC ANY | Send the 1 or 2 to the next node | | Implicitly wrap back to top of node +--------+------+ | Node 1 | | This node does the incrementing/printing +--------+ | | ADD 1 | Increment counter (starts at zero) | JRO UP | Get value from above, and jump forward that many lines (skip next line or not) | SUB ACC | Reset counter to zero (if input was zero) | MOV ACC ANY | Send the counter value downward to be printed | | Implicitly wrap back to top of node +---------------+ | Output 0 | Output is space-delimited numeric values ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~45~~ ~~44~~ 38 bytes ``` f(a,i)int*a;{while(--i)*++a*=-~a[-1];} ``` [Try it online!](https://tio.run/##LUxLCoMwFNz3FI@UQmKSYpaSehKbRYhaH9go1tKFpFdPn9IZBgbmE/QjhHzGGMZ32wF7rS1O14HlnnuFAuNaeLt9Bhw7rjWKQkpf1PrrG22cTfnpMXKxnYBAZfCNgxo2o4wqieYQMdmjsr9W4u@nhe8TrEsLeKssSIniiHbMC4U9Z5f2HpmiY3Q0TPkH "C (gcc) – Try It Online") Save one byte thanks to Toby Speight! Save 6 bytes by using \*= and a smarter while condition. [Answer] # RAD, 8 bytes ``` (⊢×1+⊣)⍂ ``` [Try it online!](https://tio.run/##K0pM@f9f41HXosPTDbUfdS3WfNTb9P//f0MFQwUDBUMA) ## How? * `(⊢×1+⊣)`, if the right argument is `0`, return `0`, otherwise increment the left argument * `⍂`, LTR Scan (`(A f B) f C` instead of `A f (B f C)`) , apply this across the array [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ṛȧ+ɗ\ ``` [Try it online!](https://tio.run/##y0rNyan8///hztknlmufnB7z////aAMdQzA0gJIGOjARMIwFAA "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 19 bytes ``` scanl1$((*)=<<).(+) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzvzg5MS/HUEVDQ0vT1sZGU09DW/N/bmJmnoKtQkFRZl6JgopCmkK0gY4hGBpASQMdmAgYxv7/l5yWk5he/F83wjkgAAA "Haskell – Try It Online") **Explanation:** The code is equivalent to `scanl1(\b a->(b+a)*a)`, where `b` is the current bit and `a` is the accumulator. `scanl1` takes a list, instantiates the first list element as accumulator, and folds over the list and collects the intermediate values in a new list. *Edit: [BMO beat me by a few seconds and 4 bytes](https://codegolf.stackexchange.com/a/167588/56433).* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` FoldList[+###2&] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98tPyfFJ7O4JFpbWVnZSC32f0BRZl5JtLKCrp1CWrRybKyCmoK@g0J1taGOggEYGcJIQ7xcqOJaHYVquDyaWgMkLgKh6ECzwBCvxfjVYLPHEJckmjG1tf8B "Wolfram Language (Mathematica) – Try It Online") [Answer] # Japt, ~~7~~ ~~6~~ 5 bytes ``` åÏ*°X ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5c8qsFg=&input=WzAsMSwxLDEsMCwxLDEsMCwwLDAsMSwxLDEsMSwxLDFdCi1R) --- ## Explanation ``` åÏ :Cumulatively reduce °X : Increment the current total (initially 0) * : Multiply by the current element ``` [Answer] # Java 8, ~~55~~ 48 bytes ``` a->{int p=0,i=0;for(int v:a)a[i++]=v<1?p=0:++p;} ``` Modifies the input-array instead of returning a new one to save bytes. -7 bytes thanks to *@TimSeguine*. [Try it online.](https://tio.run/##fVFNb4MwDL3vV/iYChqFaxmb9gPWS49VD16aTqE0oMQwVYjfztwAk7ovOYlkx@8956XEDtfl8TzqCkOAV7SufwCwjow/oTawvaUAXW2PoAXX9wfAVc7FgTevQEhWwxYcFDDi@qnnJmgKldpC5afa30DQbXCFe5skh6J7zJ75epMkTT6M@cTStG8Vs8xkUe3Cs4gdeeveo@Y0CJlAwpkPiKP0Ks1iqPlU6VKJMcRJ/0CpL1z2Lb/j@NH3H3OW/h5qQdy7Fh8aKRZnp1c6qQXOCrtrIHORdUuyYTOocqLkX5Mt2Uq@eI/XIKmejGLQrDKMnw) **Explanation:** ``` a->{ // Method with integer-array parameter and no return-type int p=0, // Previous integer, starting at 0 i=0; // Index-integer, starting at 0 for(int v:a) // Loop over the values of the input-array: a[i++]=v<1? // If the current value is 0: p=0 // Reset the previous integer to 0 : // Else: ++p;} // Increase `p` by 1 first with `++p` // and set the current item to this new value of `p` ``` [Answer] ## Shakespeare, 365 bytes ``` I.Ajax,.Ford,.Act I:.Scene I:.[enter Ajax and Ford]Ajax:Open mind!Scene V:.Ford:Am I nicer than the sum of a big red old cute hard cat a big red old cute joy?Ford:If so,you is the sum of thyself a son!Ford:If not,you is zero!Ford:Open heart!Ajax:you is a big red old cute hard cat.Ajax:Speak mind!Ajax:Open mind!Ford:Am I nicer than zero?Ajax:If so, let us Scene V. ``` [try it here](https://tio.run/##fZA/a8MwEMW/yvNuRLJqCV4KnjoEupQMqnWpndp3RpKhzpd39CcppYRKIJ1OPz29Oz@P29aq5mK@a/Uiztaq6QJarY4dMaXgnTiQQ0Jg2CJRp3TSrzMxpoFtVeA3nSV0M6EFD118FXrDcSH4ZYKcYfAxfMKRhYwW3RIIvXExMuHZ3UXWQ5Zsz/BSr7Jg8L/1Qr96GpOuF64eKEt4sFdyUvLZbU/GhSq7vwP/OMpt0ceZzFcp80/VT4tNHx4yWDxjpIDF494itW27/X4XZxp5L@FPLo4b) ## less golfed version ``` I.Ajax,.Ford,. Act I:. Scene I:. [enter Ajax and Ford] Ajax:Open mind! Scene V:. Ford:Am I nicer than the sum of a big red old cute hard cat a big red old cute joy? <- smallest way to 48 (ascii "0") I could think of Ford:If so,you is the sum of thyself a son! Ford:If not,you is zero! Ford:Open heart! Ajax:you is a big red old cute hard cat. <- get value of 32 or space Ajax:Speak mind! <- then output it Ajax:Open mind! Ford:Am I nicer than zero? Ajax:If so, let us Scene V. <- loop through inputs ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 5 bytes ``` ẋ+⊣¦_ ``` [Try it online!](https://tio.run/##S0/MTPz//@Gubu1HXYsPLYv/n/qobeL/aAMFQzA0gJIGCjARMIwFAA "Gaia – Try It Online") ### Explanation ``` ẋ+⊣¦_ Full program ẋ Split into chunks of equal adjacent values. ¦_ And for each chunk, flattening the result afterwards... +⊣ Reduce it cumulatively on + (addition); aka cumulative sums ``` Ugh, I thought SE code fonts were monospace.... [Answer] # C++, 47 bytes ``` [](int*a,int*b){for(int c=0;a!=b;)c=*a++*=1+c;} ``` A lambda that modifies an array in place, given start and end pointers. --- [Try it online!](https://tio.run/##ZVDbioQwDH3vV2RdWKy64Lx6@4p5m5mHWOtQ0FZqHBjEb3erVVh2EwjNSZpzEjEM308h1pGQlACcyIAweiRooYT19giVpgiTLdZ8bo3dABBlmuNHWedclBHGcVReYpEva84Y@1RadFMjC2VGshL76hdE0iIZWzFGsh86JFnQe5AaewnXih0yXkY1MFjHFHox1y9Aa/HN2czAmdMB4S72hd0ks7MKh43UZJkwE0FR@JbtEUCQs3/l4K4dvDC2Ldaj0uHJsgF0e7hDzGly2T09YpqcyO6Ln@slE/dZG@48tXy6mcQTTyt14xL@98Oy/gA "C++ (gcc) – Try It Online") (requires Javascript) --- Generic version at 55 bytes (this works for any container with elements of arithmetic type): ``` [](auto a,auto b){for(auto c=*a-*a;a!=b;)c=*a++*=1+c;}; ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~12~~ 10 bytes ``` ḅ{a₀ᵇ+ᵐ}ᵐc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO1urER00ND7e2az/cOqEWiJP//4820DHQMcQBDaAkmppYhf9RAA "Brachylog – Try It Online") *(-2 bytes thanks to @Fatalize.)* ``` ḅ % split input into "blocks" of equal value { }ᵐ % map this predicate on each such block: a₀ᵇ % Find all prefixes (initial subsequences) of the block % Returns them in increasing order of length +ᵐ % Sum the values in each subsequence % This results in each block being replaced by its cumulative sum values c % concatenate the results back into a single array ``` `~c{≤₁a₀ᵇ+ᵐ}ᵐc` is temptingly just out of reach at 13 bytes, but I haven't been able to find a shorter way of doing cumulative sum than the 5 byte `a₀ᵇ+ᵐ`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~29 24~~ 18 bytes *-6 bytes thanks to Sean!* ``` *.map:{($+=1)*=$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0svN7HAqlpDRdvWUFPLViW@9r81V3FipUKaRrSBjiEYGkBJAx2YCBjGasJVwlQhyxsg6TTEKo5q1n8A "Perl 6 – Try It Online") The inner function could by `($+=1)*=*`, but then the anonymous variable would persist across function calls. We get by this by wrapping it in an explicit code block. ### Explanation: ``` *.map: # Map the array to {($+=1) } # The anonymous variable incremented *=$_ # Multiplied by the element ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~48~~ ~~40~~ 25 bytes Thanks Mazzy for -8 Thanks AdmBorkBork for -15 ``` $args[0]|%{($i=$_*=++$i)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL042iC2RrVaQyXTViVey1ZbWyVTs/b///8OGgY6hmBoACUNdGAiYKgJAA "PowerShell – Try It Online") Takes input as an array numbers. Uses the self-assigning, multiply trick other answers are using and updates everything with a very gross assignment. It then wraps this whole thing in parens to push it to output. [Answer] # [Pyth](https://pyth.readthedocs.io), 6 bytes ``` m=Z*hZ ``` [Try it here!](https://pyth.herokuapp.com/?code=m%3DZ%2ahZ&input=%5B0%2C1%2C1%2C1%2C0%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%5D+&debug=0) ### How it works ``` m=Z*hZ – Full program. Q = the evaluated input. m – For each integer d in Q. =Z – Assign the variable Z (preinitialised to 0) to... *hZ – (Z + 1) * d; (d is implicit at the end). ``` [Answer] Wanted to get an answer in using regular expressions. There is probably an easier solution which I leave as an exercise for the reader. # [PowerShell Core](https://github.com/PowerShell/PowerShell), 86 bytes ``` Filter F{($_-split"(0)(\B|\b)"|?{$_-ne''}|%{$_-replace'(1+)',(1..$_.Length)})-join' '} ``` [Try it online!](https://tio.run/##lVNdS8MwFH3efsWldCRhS0k6PzeGolAU9MmBDyqjlugqXVubDJG2v70mXde54UMNpL099@Sce8tNmnyJTC5FFNEgyUTlreNAhUkMcyEVJv2837OVDiXM4BKTafs5nMHTw7dUYuXM12kkXiaT60z4SmCLWyO9u3GZ5rKOXP5rsdoEXBjDERzDCZzCGZwDZ8A5cBf0u6sqY1qNtw/WSDOjUW/3j4j9w2GrzluXXbxZ5iccGG362jfedXvIq/vvXk5dBWMH5uPWiu2L18KtdAED0GPRs6W/0sp6MOyFc6ud@NSgfiz1SO1Qt0YzodZZbNDmVAGeSZhcKO99FSxNsqFR8QmNkCE9ZqES9CaRCrDV0imFnJWwOSIB5bxEFn3bOoy2agTKfll5YaR0WV6O7QWVaRQqCzOCn6@K51diFRe5hmOBUFkMTJiJNPIDgTAfEjTC3HF0O3cifldLUhL6kYQxAlRW5ppUPw "PowerShell Core – Try It Online") [Answer] # QBasic, 60 bytes ``` INPUT s$ FOR i=1TO LEN(s$) b=MID$(s$,i)>="1 v=-b*v-b ?v NEXT ``` Takes the input as a string; gives the output as numbers separated by newlines. ### Explanation We read the string `s$` and loop `i` from `1` up to its length. `MID$(s$,i)` gets the substring from character `i` (1-indexed) to the end of the string. If this starts with a `1`, it will be lexicographically `>=` the string `"1"`; if it starts with a `0`, it will not be. So `b` gets `0` if the character at index `i` is `0`, or `-1` if the character is `1`. Next, we update the current value `v`. If we just read a `0`, we want `v` to become `0`; otherwise, we want to increment `v` by one. In other words, `v = (-b) * (v+1)`; simplifying the math gives the shorter expression seen in the code. Finally, we print `v` and loop. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 60 bytes ``` ([]){{}<>(())<>{{}<>({}({}))(<>)}{}([])}{}<>{({}[()]<>)<>}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6utbGTkNDU9PGDsKsrgUiTU0NGzvNWiAbqKQWJF4NFI3W0IwFCtvYAfn//xsoGAKhARTDIIKPLIqpDgwB "Brain-Flak – Try It Online") # Explanation: ``` ([]){ For each element in the input {} <>(())<> Push a one to the other stack { If the element is one, {}<>({}({}))(<>) Add the one to a copy of the previous number in the series }{} Pop the element ([])} End loop {}<> Pop extra zero {({}[()]<>)<>}<> And reverse the output stack, subtracting one from each element ``` ]
[Question] [ Or, "Swap the first and last letters of each word" Your challenge is to, given a string of alphabetical ASCII characters as well as one other character to use as a delimiter (to separate each word), swap the first and last letters of each word. If there is a one-character word, leave it alone. The examples/testcases use the lowercase letters and the space as the delimiter. You do not need to handle punctuation; all of the inputs will only consist of the letters a through z, separated by a delimiter, all of a uniform case. For example, with the string "hello world": ``` Input string: "hello world" Identify each word: "[hello] [world]" Identify the first and last letters of each word: "[[h]ell[o]] [[w]orl[d]]" Swap the first letters of each word: "[[o]ell[h]] [[d]orl[w]]" Final string: "oellh dorlw" ``` NOTE: the delimiter does not need to be inputted separately. The delimiter is just the character used to separate words. It can be anything. I wanted to leave options open for creative golfers, so I did not want to limit it to just spaces or new lines. The delimiter is just a character that separates words in the input string. **Test cases:** ``` "swap the first and last letters of each word" -> "pwas eht tirsf dna tasl setterl fo hace dorw" "hello world" -> "oellh dorlw" "test cases" -> "test sasec" "programming puzzles and code golf" -> "grogramminp suzzlep dna eodc folg" "in a green meadow" -> "ni a nreeg weadom" "yay racecar" -> "yay racecar" ``` [Answer] # TeX, 216 bytes (4 lines, 54 characters each) ***Because it's not about the byte count, it's about the quality of the typeset output :-)*** ``` {\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13% \global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{% I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D% #2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }} ``` [Try it Online! (Overleaf; not sure how it works)](https://www.overleaf.com/read/dkypfbgxmhdw) Full test file: ``` {\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13% \global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{% I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D% #2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }} \S{swap the a first and last letters of each word} pwas eht a tirsf dna tasl setterl fo hace dorw \S{SWAP THE A FIRST AND LAST LETTERS OF EACH WORD} \bye ``` Output: > > [![enter image description here](https://i.stack.imgur.com/846L5.png)](https://i.stack.imgur.com/846L5.png) > > > --- For LaTeX you just need the boilerplate: ``` \documentclass{article} \begin{document} {\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13% \global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{% I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D% #2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }} \S{swap the a first and last letters of each word} pwas eht a tirsf dna tasl setterl fo hace dorw \S{SWAP THE A FIRST AND LAST LETTERS OF EACH WORD} \end{document} ``` --- ## Explanation TeX is a strange beast. Reading normal code and understanding it is a feat by itself. Understanding obfuscated TeX code goes a few steps further. I'll try to make this understandable for people who don't know TeX as well, so before we start here's a few concepts about TeX to make things easier to follow: ### For (not so) absolute TeX beginners * First, and most important item in this list: the code does *not* have to be in rectangle shape, [even though](https://tex.stackexchange.com/q/450795/134574) [pop culture](https://tex.stackexchange.com/a/156937/134574) [might lead you](https://tex.stackexchange.com/a/474872/134574) [to think so](https://tex.stackexchange.com/a/406914/134574). * TeX is a macro expansion language. You can, as an example, define `\def\sayhello#1{Hello, #1!}` and then write `\sayhello{Code Golfists}` to get TeX to print `Hello, Code Golfists!`. This is called an “undelimited macro”, and to feed it the first (and only, in this case) parameter you enclose it in braces. TeX removes those braces when the macro grabs the argument. You can use up to 9 parameters: `\def\say#1#2{#1, #2!}` then `\say{Good news}{everyone}`. * The counterpart of undelimited macros are, unsurprisingly, delimited ones :) You could make the previous definition a tad more *semantical*: `\def\say #1 to #2.{#1, #2!}`. In this case the parameters are followed by so-called *parameter text*. Such parameter text delimits the argument of the macro (`#1` is delimited by `␣to␣`, spaces included, and `#2` is delimited by `.`). After that definition you can write `\say Good news to everyone.`, which will expand to `Good news, everyone!`. Nice, isn't it? :) However a delimited argument is (quoting the *TeXbook*) “the shortest (possibly empty) sequence of tokens with properly nested `{...}` groups that is followed in the input by this particular list of non-parameter tokens”. This means that the expansion of `\say Let's go to the mall to Martin` will produce a weird sentence. In this case you'd need to “hide” the first `␣to␣` with `{...}`: `\say {Let's go to the mall} to Martin`. * So far so good. Now things start to get weird. When TeX reads a character (which is defined by a “character code”), it assigns that character a “category code” (catcode, for friends :) which defines what that character will mean. This combination of character and category code makes a token (more on that [here](https://tex.stackexchange.com/a/104050/134574), for example). The ones which are of interest for us here are basically: + **catcode 11**, which define tokens which can make up a control sequence (a posh name for a macro). By default all letters [a-zA-Z] are catcode 11, so I can write `\hello`, which is one single control sequence, while `\he11o` is the control sequence `\he` followed by two characters `1`, followed by the letter `o`, because `1` is not catcode 11. If I did `\catcode`1=11`, from that point on `\he11o` would be one control sequence. One important thing is that catcodes are set when TeX first sees the character at hand, and such catcode is *frozen*... FOREVER! (terms and conditions may apply) + **catcode 12**, which are most of other characters, such as `0"!@*(?,.-+/` and so forth. They are the *least* special type of catcode as they serve only for writing stuff on the paper. But hey, who uses TeX for writing?!? (again, terms and conditions may apply) + **catcode 13**, which is hell :) Really. Stop reading and go do something out of your life. You don't want to know what catcode 13 is. Ever heard of Friday, 13th? Guess where it got its name from! Continue at your own risk! A catcode 13 character, also called an “active” character, is not just a character anymore, it is a macro itself! You can define it to have parameters and expand to something like we saw above. After you do `\catcode`e=13` you *think* you can do `\def e{I am the letter e!}`, BUT. YOU. CANNOT! `e` is not a letter anymore, so `\def` is not the `\def` you know, it is `\d e f`! Oh, choose another letter you say? Okay! `\catcode`R=13 \def R{I am an ARRR!}`. Very well, Jimmy, try it! I dare you do that and write an `R` in your code! That's what a catcode 13 is. I AM CALM! Let's move on. * Okay, now to grouping. This is fairly straightforward. Whatever assignments (`\def` is an assignment operation, `\let` (we'll get into it) is another) done in a group are restored to what they were before that group started unless that assignment is global. There are several ways to start groups, one of them is with catcode 1 and 2 characters (oh, catcodes again). By default `{` is catcode 1, or begin-group, and `}` is catcode 2, or end-group. An example: `\def\a{1} \a{\def\a{2} \a} \a` This prints `1 2 1`. Outside the group `\a` was `1`, then inside it was redefined to `2`, and when the group ended, it was restored to `1`. * The `\let` operation is another assignment operation like `\def`, but rather different. With `\def` you *define* macros which will expand to stuff, with `\let` you create copies of already existing things. After `\let\blub=\def` (the `=` is optional) you can change the start of the `e` example from the catcode 13 item above to `\blub e{...` and have fun with that one. Or better, instead of breaking stuff you can *fix* (would you look at that!) the `R` example: `\let\newr=R \catcode`R=13 \def R{I am an A\newr\newr\newr!}`. Quick question: could you rename to `\newR`? * Finally, the so-called “spurious spaces”. This is kind of a taboo topic because there are people who claim that reputation earned in the [TeX - LaTeX Stack Exchange](https://tex.stackexchange.com) by answering “spurious spaces” questions should not be considered, while others wholeheartedly disagree. Whom do you agree with? Place your bets! Meanwhile: TeX understands a line break as a space. Try to write several words with a line break (not an *empty line*) between them. Now add a `%` at the end of these lines. It's like you were “commenting out” these end-of-line spaces. That's it :) ### (Sort of) ungolfing the code Let's make that rectangle into something (arguably) easier to follow: ``` { \let~\catcode ~`A13 \defA#1{~`#113\gdef} AGG#1{~`#113\global\let} GFF\else GHH\fi AQQ{Q} AII{\ifxQ} AEE#1#2#3|{I#3#2#1FE{#1#2}#3|H} ADD#1#2#3|{I#2FE{#1}#2#3|H} ACC#1#2|{D{}#2Q|#1 } ABBH#1 {HI#1FC#1|BH} \gdef\S#1{\iftrueBH#1 Q } } ``` ### Explanation of each step each line contains one single instruction. Let's go one by one, dissecting them: **`{`** First we start a group to keep some changes (namely catcode changes) local so that they don't mess up the input text. **`\let~\catcode`** Basically *all* TeX obfuscation codes start with this instruction. By default, both in plain TeX and LaTeX, the `~` character is the one active character which can be made into a macro for further use. And the best tool for weirdifying TeX code are catcode changes, so this is generally the best choice. Now instead of `\catcode`A=13` we can write `~`A13` (the `=` is optional): **`~`A13`** Now the letter `A` is an active character, and we can define it to do something: **`\defA#1{~`#113\gdef}`** `A` is now a macro that takes one argument (which should be another character). First the catcode of the argument is changed to 13 to make it active: `~`#113` (replace the `~` by `\catcode` and add an `=` and you have: `\catcode`#1=13`). Finally it leaves a `\gdef` (global `\def`) in the input stream. In short, `A` makes another character active and start its definition. Let's try it: **`AGG#1{~`#113\global\let}`** `AG` first “activates” `G` and does `\gdef`, which followed by the next `G` starts the definition. The definition of `G` is very similar to that of `A`, except that instead of `\gdef` it does a `\global\let` (there isn't a `\glet` like the `\gdef`). In short, `G` activates a character and makes it be something else. Let's make shortcuts for two commands we'll use later: **`GFF\else`** **`GHH\fi`** Now instead of `\else` and `\fi` we can simply use `F` and `H`. Much shorter :) **`AQQ{Q}`** Now we use `A` again to define another macro, `Q`. The above statement basically does (in a less obfuscated language) `\def\Q{\Q}`. This isn't a terribly interesting definition, but it has an interesting feature. Unless you do want to break some code, the only macro that expands to `Q` is `Q` itself, so it acts like a unique marker (it's called a *quark*). You can use the `\ifx` conditional to test if the argument of a macro is such quark with `\ifx Q#1`: **`AII{\ifxQ}`** so you can be pretty sure that you found such a marker. Notice that in this definition I removed the space between `\ifx` and `Q`. Usually this would lead to an error (note that the syntax highlight thinks that `\ifxQ` is one thing), but since now `Q` is catcode 13 it cannot form a control sequence. Be careful, however, not to expand this quark or you'll get stuck in an infinite loop because `Q` expands to `Q` which expands to `Q` which... Now that the preliminaries are done, we can go to the proper algorithm to pwas eht setterl. Due to TeX's tokenization the algorithm has to be written backwards. This is because at the time you do a definition TeX will tokenize (assign catcodes) to the characters in the definition using the current settings so, for example, if I do: ``` \def\one{E} \catcode`E=13\def E{1} \one E ``` the output is `E1`, whereas if I change the order of the definitions: ``` \catcode`E=13\def E{1} \def\one{E} \one E ``` the output is `11`. This is because in the first example the `E` in the definition was tokenized as a letter (catcode 11) before the catcode change, so it will always be a letter `E`. In the second example, however, `E` was first made active, and only then `\one` was defined, and now the definition contains the catcode 13 `E` which expands to `1`. I will, however, overlook this fact and reorder the definitions to have a logical (but not working) order. In the following paragraphs you can assume that the letters `B`, `C`, `D`, and `E` are active. **`\gdef\S#1{\iftrueBH#1 Q }`** (notice there was a small bug in the previous version, it did not contain the final space in the definition above. I only noticed it while writing this. Read on and you'll see why we need that one to properly terminate the macro.) First we define the user-level macro, `\S`. This one shouldn't be an active character to have a friendly (?) syntax, so the macro for gwappins eht setterl is `\S`. The macro starts with an always-true conditional `\iftrue` (it will soon be clear why), and then calls the `B` macro followed by `H` (which we defined earlier to be `\fi`) to match the `\iftrue`. Then we leave the argument of the macro `#1` followed by a space and by the quark `Q`. Suppose we use `\S{hello world}`, then the *input stream* should look like this: `\iftrue BHhello world Q␣` (I replaced the last space by a `␣` so that the rendering of the site does not eat it, like I did in the previous version of the code). `\iftrue` is true, so it expands and we are left with `BHhello world Q␣`. TeX does *not* remove the `\fi` (`H`) after the conditional is evaluated, instead it leaves it there until the `\fi` is *actually* expanded. Now the `B` macro is expanded: **`ABBH#1 {HI#1FC#1|BH}`** `B` is a *delimited macro* whose parameter text is `H#1␣`, so the argument is whatever is between `H` and a space. Continuing the example above the input stream prior to the expansion of `B` is `BHhello world Q␣`. `B` is followed by `H`, as it should (otherwise TeX would raise an error), then the next space is between `hello` and `world`, so `#1` is the word `hello`. And here we got to split the input text at the spaces. Yay :D The expansion of `B` removes everything up to the first space from the input stream and replaces by `HI#1FC#1|BH` with `#1` being `hello`: `HIhelloFChello|BHworld Q␣`. Notice that there is a new `BH` later in the input stream, to do a tail recursion of `B` and process later words. After this word is processed `B` processes the next word until the word-to-be-processed is the quark `Q`. The last space after `Q` is needed because the delimited macro `B` *requires* one at the end of the argument. With the previous version (see edit history) the code would misbehave if you used `\S{hello world}abc abc` (the space between the `abc`s would vanish). OK, back to the input stream: `HIhelloFChello|BHworld Q␣`. First there's the `H` (`\fi`) that completes the initial `\iftrue`. Now we have this (pseudocoded): ``` I hello F Chello|B H world Q␣ ``` The `I...F...H` think is actually a `\ifx Q...\else...\fi` structure. The `\ifx` test checks if the (first token of the) word grabbed is the `Q` quark. If it is there is nothing else to do and the execution terminates, otherwise what remains is: `Chello|BHworld Q␣`. Now `C` is expanded: **`ACC#1#2|{D#2Q|#1 }`** The first argument of `C` is undelimited, so unless braced it will be a single token, The second argument is delimited by `|`, so after the expansion of `C` (with `#1=h` and `#2=ello`) the input stream is: `DelloQ|h BHworld Q␣`. Notice that another `|` is put there, and the `h` of `hello` is put after that. Half the swapping is done; the first letter is at the end. In TeX it is easy to grab the first token of a token list. A simple macro `\def\first#1#2|{#1}` gets the first letter when you use `\first hello|`. The last one is a problem because TeX always grabs the “smallest, possibly empty” token list as argument, so we need a few work-arounds. Next item in the token list is `D`: **`ADD#1#2|{I#1FE{}#1#2|H}`** This `D` macro is one of the work-arounds and it's useful in the sole case where the word has a single letter. Suppose instead of `hello` we had `x`. In this case the input stream would be `DQ|x`, then `D` would expand (with `#1=Q`, and `#2` empty) to: `IQFE{}Q|Hx`. This is similar to the `I...F...H` (`\ifx Q...\else...\fi`) block in `B`, which will see that the argument is the quark and will interrupt the execution leaving only `x` for typesetting. In other cases (returning to the `hello` example), `D` would expand (with `#1=e` and `#2=lloQ`) to: `IeFE{}elloQ|Hh BHworld Q␣`. Again, the `I...F...H` will check for `Q` but will fail and take the `\else` branch: `E{}elloQ|Hh BHworld Q␣`. Now the last piece of this thing, the `E` macro would expand: **`AEE#1#2#3|{I#3#2#1FE{#1#2}#3|H}`** The parameter text here is quite similar to `C` and `D`; the first and second arguments are undelimited, and the last one is delimited by `|`. The input stream looks like this: `E{}elloQ|Hh BHworld Q␣`, then `E` expands (with `#1` empty, `#2=e`, and `#3=lloQ`): `IlloQeFE{e}lloQ|HHh BHworld Q␣`. Another `I...F...H` block checks for the quark (which sees `l` and returns `false`): `E{e}lloQ|HHh BHworld Q␣`. Now `E` expands again (with `#1=e` empty, `#2=l`, and `#3=loQ`): `IloQleFE{el}loQ|HHHh BHworld Q␣`. And again `I...F...H`. The macro does a few more iterations until the `Q` is finally found and the `true` branch is taken: `E{el}loQ|HHHh BHworld Q␣` -> `IoQlelFE{ell}oQ|HHHHh BHworld Q␣` -> `E{ell}oQ|HHHHh BHworld Q␣`-> `IQoellFE{ello}Q|HHHHHh BHworld Q␣`. Now the quark is found and the conditional expands to: `oellHHHHh BHworld Q␣`. Phew. Oh, wait, what are these? NORMAL LETTERS? Oh, boy! The letters are finally found and TeX writes down `oell`, then a bunch of `H` (`\fi`) are found and expanded (to nothing) leaving the input stream with: `oellh BHworld Q␣`. Now the first word has the first and last letters swapped and what TeX finds next is the other `B` to repeat the whole process for the next word. **`}`** Finally we end the group started back there so that all local assignments are undone. The local assignments are the catcode changes of the letters `A`, `B`, `C`, ... which were made macros so that they return to their normal letter meaning and can be safely used in the text. And that's it. Now the `\S` macro defined back there will trigger the processing of the text as above. One interesting thing about this code is that it is fully expandable. That is, you can safely use it in moving arguments without worrying that it will explode. You can even use the code to check if the last letter of a word is the same as the second (for whatever reason you would need that) in an `\if` test: ``` \if\S{here} true\else false\fi % prints true (plus junk, which you would need to handle) \if\S{test} true\else false\fi % prints false ``` Sorry for the (probably far too) wordy explanation. I tried to make it as clear as possible for non TeXies as well :) ### Summary for the impatient The macro `\S` prepends the input with an active character `B` which grabs lists of tokens delimited by a final space and passes them to `C`. `C` takes the first token in that list and moves it to the end of the token list and expands `D` with what remains. `D` checks if “what remains” is empty, in which case a single-letter word was found, then do nothing; otherwise expands `E`. `E` loops through the token list until it finds the last letter in the word, when it is found it leaves that last letter, followed by the middle of the word, which is then followed by the first letter left at the end of the token stream by `C`. [Answer] # JavaScript (ES6), ~~39~~ 36 bytes *Saved 3 bytes thanks to @FryAmTheEggman* Uses a linefeed as separator. ``` s=>s.replace(/(.)(.*)(.)/g,'$3$2$1') ``` [Try it online!](https://tio.run/##TVDRasQgEHy@@4olHERLm9D2OfclfVnMxuQwKq5tuPv5dA3JcYKgszPjjDf8QzZpivnDh57WoVu5u3KTKDo0pFrVaNW8ydatfa8v35evy2et10ycoQOG7gomeA6OGhesGhQ3HN2UVQ21bm5h8qr@8bXWB1wuOy4MfT4XK1XxghHySDBMSazR9@BQDo5ypsQQBiA0Iywh9ZU@tS1UcUEGGjNkkQzQe4SM7IA3iYMhwCgdoA9pqfZnRnIuFBMnLnAqq1gFgcdCdE/m1tAgE78SN5QFNQcvpmATzvPkLcTfx8MRb@mNfCfY4IZNXrT2yYzAGzNuoSn0RsI6e1hOHhBsIvIwE/ZhkcKwB/CTzLzMLCxlNh@iO94hSV2DSehH3ld0/Qc "JavaScript (Node.js) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~8~~ 5 bytes ``` ,V,,` ``` [Try it online!](https://tio.run/##DcZBCsAgDATA@74ll36m54a6oiAqScDnp53TGKNPvTLlFnky/ehGNKJ284DOgqF/BiNojlVBfRvOsvIB "Retina – Try It Online") Saved 3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! Uses a newline as the separator. We make use of Retina's reverse stage and some limits. The first limit is which matches to apply the reversal to, so we pick all of them with `,`. Then we want the first and last letter of each match to be swapped, so we take each letter in the range `,,` which translates to a range from the beginning to the end with step size zero. [Answer] # [Pepe](https://github.com/Soaku/Pepe), ~~107~~ 105 bytes ``` REEeREeeEeeeeerEEreREEEeREEEEEEeREEEErEEREEEEEEEreererEEEeererEEEerEEeERrEEEeerEEeerereeerEEEEeEEEReEeree ``` [Try it online!](https://soaku.github.io/Pepe/#T!8hE$!pE5!rEE7*$-c$!o!m--c!k$GRyL*) **Explanation:** Notation on comments: `command-explanation -> (stack) // explanation` ``` REEe # input -> (R) REeeEeeeee # push space to last -> (R) // this prevents an infinite loop rEE # create loop labeled 0 and automatically push 0 re # pop 0 -> (r) REEEe # go to last item -> (R) REEEEEEe # ...then copy the char to other stack REEEE # go to first item -> (R) rEE # create loop labeled 32 // detect space REEEEEEE # move item to other stack (R) ree # do this while char != 32 re # pop 32 -> (r) rEEEee # push item (dup to end) -> (r) re # ...then pop -> (r) rEEEe rEEeE # go to 2nd to last item -> (r) RrEEEee # push the item (R flag: dup to first) -> (r) rEEee # go to next -> (r) // re # ...then pop -> (r) reee rEEEEeEEE # out all as char then clear -> (r) ReEe # out 32 as char -> (R) ree # do this while stack != 0 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~72~~ 58 bytes ``` print(*[x[-1]+x[1:-1]+x[:x>x[0]]for x in input().split()]) ``` [Try it online!](https://tio.run/##JcZBCsMgEEbhq/zLpKWhobssehFxIYmiIDqMEzI5vRUKD75Ht8RaPr0TpyLTw6h5rfapZt3@bvpV87Y2VIYilRGdMs1Lo5yGdu69XY4g0SMkbgJXDmQ3JnsRzw01wLs94qp8/AA "Python 3 – Try It Online") [Answer] # [laskelH](https://www.haskell.org/), 71 bytes ``` h=reverse s(x:y:o)=a:h(x:r)where(a:r)=h$y:o s o=o f=unwords.map s.words ``` [Try it online!](https://tio.run/##ZVJBbhsxDLzrFTwEaAI0foCBfYCBopfmA8yattjViguRymb7eZeS10DQnkRR5HA4o4g6UUq3WxwKfVBRCvr8edyO8jLgMXpYXtZIhZ7RoyE@@UtQkEHCZah5lXLWw4wL6KHHt9dXOH2bIYvBKDUb5ytYZAVUWLAYyMXvBDwviWbKhsaSQfkPhRk5wwCcjQqOBk9Qc@JMCgdoMy5@9vvt1@rXBnPhogaYz5DQg0TmvY4AhGOERim89elJpV0nhZUt@rx8TfSo79QdeiLAEE4G3vGOyiOmtMHv2kaAWkG@RoO6/Mve562RxxhOcJEH3ChZWbsAbedVwJ9mKY@p94q@RSQ8h12Y3YYzGHICB/@SfIgnha@cMfXGDkPen//vD@GnGHke7f5Yk6upuN1Tq0Nl3zDihxcJaF0WaR5lgolz56TktqE5d3cWcIYxijT5QBccHe2Nxph3qdi@iBzER5amjFGvbX9g9d/2Hd6r9VpOCawWt8tJb/5PHNbtlx078H0ncn9/uPEt8BKFnneT6BObE1AVrw7v2kb/C8m332lT2oLDzTjRHWlvkGqLc0giEzh5Kn8B "Haskell – Try It Online") Example in/output: ``` Swap the first and last letter in each word This also works with single letter words like a It is basically just a straight up implementation in which I for words consisting of two or more letters cons the head of the reversed tail on the reverse of the original head consed on the reversed tail Note that the rules say that we only have to support one kind of separator - I am choosing spaces Technically it works with other whitespace as well, but it will turn everything into spaces in the end Line endings in this example usage are handled separately to make the example output look nicer ``` ``` pwaS eht tirsf dna tasl rettel ni hace dorw shiT olsa sorkw hitw eingls rettel sordw eikl a tI si yasicallb tusj a ttraighs pu nmplementatioi ni hhicw I rof sordw gonsistinc fo owt ro eorm setterl sonc eht deah fo eht deverser lait no eht eeversr fo eht lriginao deah donsec no eht deverser lait eotN that eht suler yas that ew ynlo eavh ot tuppors eno dink fo reparatos - I ma ghoosinc spaces yechnicallT ti sorkw hitw rtheo ehitespacw sa ,ellw tub ti lilw nurt gverythine onti spaces ni eht dne einL sndinge ni shit example esagu era dandleh yeparatels ot eakm eht example tutpuo kool ricen ``` ``` [Answer] # [J](http://jsoftware.com/), ~~23~~ 17 bytes ``` ({:,1|.}:)&.>&.;: ``` [Try it online!](https://tio.run/##TY1BDoIwFET3nmJWVhLS4LZG7/LT/gKm8ElbQ0A5O6ILcTd5My9zX51A@atWJRZTwVTr6WnK80svpjjq21FfzFoc2DYCD5VGGpAbhm9jyqDeIdAWAufMMUE8mGyDUaJTP6vhEOTDwh/MvHmWEqedDVHqSF3X9jWGxzwHTt8PK45RS/D7tO1BqCNzj47JybhXE02IZNlSVOsb "J – Try It Online") [Answer] # x86-16 machine code, IBM PC DOS, ~~39~~ ~~38~~ 32 bytes ``` $ xxd pwas.com 00000000: d1ee ac8a c8ac 8bd6 8bfe f2ae 574f 4f8a ............WOO. 00000010: 25a4 4e88 245e 41e2 efb8 2409 aacd 21c3 %.N.$^A...$...!. ``` Unassembled: ``` D1 EE SHR SI, 1 ; DOS PSP (80H) for command line input AC LODSB ; get input length, SI at beginning 8A C8 MOV CL, AL ; input length in CX AC LODSB ; load a space (word delimiter) into AL 8B D6 MOV DX, SI ; save pointer for later output WORD_LOOP: 8B FE MOV DI, SI ; start DI at beginning F2 AE REPNZ SCASB ; search for next word delimiter 57 PUSH DI ; save beginning of next word 4F DEC DI ; DI will now point to the byte after the space 4F DEC DI ; so it's necessary to back up two chars 8A 25 MOV AH, BYTE PTR[DI] ; move last letter to AH A4 MOVSB ; move first letter to last position 4E DEC SI ; offset MOVSB incrementing SI 88 24 MOV BYTE PTR[SI], AH ; move last letter to first position 5E POP SI ; SI to beginning of next word 41 INC CX ; offset LOOP decrementing CX E2 EF LOOP WORD_LOOP ; loop if not end of input string B8 0924 MOV AX, 0924H ; AH = 9, AL = '$' AA STOSB ; write DOS string delimiter to end CD 21 INT 21H ; write to console C3 RET ; return to DOS ``` Standalone PC DOS executable. Input via command line, output to console. [![enter image description here](https://i.stack.imgur.com/fxyWa.png)](https://i.stack.imgur.com/fxyWa.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` #vyRćsRćðJ ``` [Try it online!](https://tio.run/##LYrBCYAwEARbWbAbn3ZwmlMPj0RyMWIFtmMP2lcM6GOZgdlg1AuX0uSje06ru6@2FNtpRZoZo0RLIO@gVEU5JY6GMIJpmLGH6CB@0M2Jn0CwCuX/92WVhWsJEQKjnI8X "05AB1E – Try It Online") --- -3 Thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). ``` # | Split into words. vy | For each word... RćsRć | Reverse, split head, swap, reverse, split tail ðJ | Join by spaces. ``` [Answer] ## Haskell, 54 bytes ``` unwords.map f.words f[a]=[a] f(a:b)=last b:init b++[a] ``` [Try it online!](https://tio.run/##LU5LrsIwDNz3FKOuQDx6AKTegLd6S0DIpE4avfyUpKrg8IS0ZWHZM/aMZ6T0z8YU1V/L5GYfh9RZCpDdOjfyQre@ViN3dHrse0Mp43HSTtd2ONRNsaQdelTV7x27MOW/HM8Ondrj0gBtmqtfHhlSxyomN2B1MZwzxwQvwSRGLA/bn0Ux1kR@weZLZK73ghKnDYfoVSRrtVMI0@tlOK2@wg8M5Y3czmougorMDpZp8PNGP@mJSIIFxfbWlLeQhlQqRxHCBw "Haskell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 37 bytes ``` $args-replace'(\w)(\w*)(\w)','$3$2$1' ``` [Try it online!](https://tio.run/##TU/dasMgGL3PUxyCW5ORXmy7GxT2IIMh@sUETHRqcW3XZ88@k65MUDx/fkfvMoU4kLWL6A@XRchg4j6Qt1LRrvnILe@ncrS7bidexYt43i3Xqnpvqq6pY5YeaSD0Y4gJctawki@WUuJ34XqQVAOyC7ruap9lBA0Jie099CyRZLSIq92idxh4LrQLuW7LgNLMlbjlPGrHcCiyvemJeJqSkWKRVxQZqU31wZkgp2mcDfzxfLYU147KaYJxti8hczd5xNXk12bktOJG1mxvjTMkTCCaMZHULpfsPDI5M2mQCzlt3pM8IfBHlAzF9R@2VYsfPOBSgZeIHQR9e1KJNA4QnxsdKB5tYuJR9GxayVo0N36v6Oueat/@7HV1XX4B "PowerShell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) with `-p`, ~~42~~ ~~41~~ 29 bytes ``` gsub /(\w)(\w*)(\w)/,'\3\2\1' ``` [Try it online!](https://tio.run/##HYxBDoMwDATveYVvlKoVavudXExiQqQQR3YQgsc3hR5mNYfVyDrurQVdRxhudutP7tf0w6OzH/u2r6413bBAnQmmKFoBs4eEpySqlUSBJyB0M2ws3syUEl@avKl0vhwqqSnCQXBZYg5Q1uNIpP@QY08QOE0mZkAIQpRhIfS8mR13EHTkUL5cauSs7Vl@ "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 7 bytes ``` ¸®ÎiZÅé ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uK7OaVrF6Q&input=InN3YXAgdGhlIGZpcnN0IGFuZCBsYXN0IGxldHRlcnMgb2YgZWFjaCB3b3JkIg) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ⌈ƛḣǔp;Ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIjGm+G4o8eUcDvhuYQiLCIiLCJTd2FwIHRoZSBmaXJzdCBhbmQgbGFzdCBsZXR0ZXJzIG9mIGVhY2ggd29yZCJd) ``` ⌈ Ṅ # To the words split on spaces... ƛ ; # Over each ḣ # Take the first character and the rest ǔ # Rotate the rest p # Append the first char ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Σq╞♪áZN¢ ``` [Run and debug it](https://staxlang.xyz/#p=e471c60da05a4e9b&i=swap%0Athe%0Afirst%0Aand%0Alast%0Aletters%0Aof%0Aeach%0Aword%0A%0Ahello%0Aworld%0A%0Atest%0Acases%0A%0Aprogramming%0Apuzzles%0Aand%0Acode%0Agolf%0A%0Ain%0Aa%0Agreen%0Ameadow%0A%0Ayay%0Aracecar%0A&a=1&m=1) Uses newlines as word separators. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 179 bytes ``` [N S S S N _Create_Label_OUTER_LOOP][S S S N _Push_n=0][N S S T N _Create_Label_INNER_LOOP][S N S _Duplicate_n][S N S _Duplicate_n][S N S _Duplicate_n][T N T S _Read_STDIN_as_character][T T T _Retrieve_input][S S S T S T T N _Push_11][T S S T _Subtract_t=input-11][N T T S S N _If_t<0_jump_to_Label_PRINT][S S S T N _Push_1][T S S S _Add_n=n+1][N S N T N _Jump_to_Label_INNER_LOOP][N S S S S N _Create_Label_PRINT][S S S T N _Push_1][T S S T _Subtract_n=n-1][S N S _Duplicate_n][S N S _Duplicate_n][N T S N _If_n==0_jump_to_Label_PRINT_TRAILING][T T T _Retrieve][T N S S _Print_as_character][S S S N _Push_s=0][N S S S T N _Create_Label_PRINT_LOOP][S S S T N _Push_1][T S S S _Add_s=s+1][S N S _Duplicate_s][S T S S T S N _Copy_0-based_2nd_n][T S S T _Subtract_i=s-n][N T S N _If_0_Jump_to_Label_PRINT_TRAILING][S N S _Duplicate_s][T T T _Retrieve][T N S S _Print_as_character][N S T S T N _Jump_to_Label_PRINT_LOOP][N S S N _Create_Label_PRINT_TRAILING][S S S N _Push_0][T T T _Retrieve][T N S S _Print_as_character][S S S T S S T N _Push_9_tab][T N S S _Print_as_character][N S N S N _Jump_to_Label_OUTER_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Tab as delimiter. Input should contain a trailing newline (or tab), otherwise the program doesn't know when to stop, since taking input in Whitespace can only be done one character at a time. [Try it online](https://tio.run/##TY7hDoMgDIR/X5@ir9ZonWREDTDNnp61lsQlQK/0u4NrTU3rIZP2Tsx8bztALu8FAgOwgVdr/AaB3q0pgpv@7hBek8aai3kEMx6fM8FGqBt44OSvEY0fPRlBRjhT7/WSA21VLKnUBtlmZDGRtTUtFfsClWnFtZcZaZvyZ07bC4JqJevgYpzTW22yFyRUOc8v/QA) (with raw spaces, tabs, and new-lines only). **Explanation in pseudo-code:** Whitespace only has a stack and a heap, where the heap is a map with a key and value (both integers). Inputs can only be read one integer or character at a time, which are always placed in the heap as integers, and can then be received and pushed to the stack with their defined heap-addresses (map-keys). In my approach I store the entire word at the heap-addresses (map-keys) \$[0, ..., \text{word\_length}]\$, and then retrieve the characters to print one by one in the order we'd want after a tab (or newline) is encountered as delimiter. ``` Start OUTER_LOOP: Integer n = 0 Start INNER_LOOP: Character c = STDIN as character, saved at heap-address n If(c == '\t' OR c == '\n'): Jump to PRINT n = n + 1 Go to next iteration of INNER_LOOP PRINT: n = n - 1 If(n == 0): (this means it was a single-letter word) Jump to PRINT_TRAILING Character c = get character from heap-address n Print c as character Integer s = 0 Start PRINT_LOOP: s = s + 1 If(s - n == 0): Jump to PRINT_TRAILING Character c = get character from heap-address s Print c as character Go to next iteration of PRINT_LOOP PRINT_TRAILING: Character c = get character from heap-address 0 Print c as character Print '\t' Go to next iteration of OUTER_LOOP ``` The program terminates with an error when it tries to read a character when none is given in TIO (or it hangs waiting for an input in some Whitespace compilers like [vii5ard](http://vii5ard.github.io/whitespace/)). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes ``` StringReplace[#,a:u~~w:u..~~b:u:>b<>w<>a/.{u->Except@#2}]& ``` [Try it online!](https://tio.run/##TY89a8MwEIb3/IrDgkyOCx1NKrRkL@0YMlzkk22QLKEP1MTYf91V28Hdjufu4b3XYBzIYBwlbupt@4x@nPoPcholXVmNbVrX3KamWdd7m1p@P/N85vjSzOnEL1@SXBTsdbkdt/dixuvM2HLiSjB2Owoh5sNchYwOSgqo0YcIOHWgsQyaYiQfwCoglANk67uqrqBa6mINpLX9YfofjFQ8iYHCzpy3vUdjyt/g0vOpKfxmSNsR9Far/XScAKH3RBMYws7mffXAB/jSWaL/g4dl@wY "Wolfram Language (Mathematica) – Try It Online") *-22 bytes from @attinat* *-12 bytes from @M.Stern* [Answer] # Ruby, 53 bytes ``` gets.split(" ").map{|z|print z[-1]+z[1..-2]+z[0]," "} ``` I tried it without regex. The output prints each word on a new line. If that's against the rules, let me know and I'll fix it. Ungolfed: ``` gets.split(" ").map {|z| print z[-1] + z[1..-2] + z[0], " " } ``` [Answer] # [Zsh](https://zsh.sourceforge.io/), 36 bytes ``` for x;<<<$x[-1]${x:1:-1}$x[1]||<<<$x ``` [Try it Online!](https://tio.run/##HYyxjoMwEER7f8UUSMkVKWgDiu4/jhR7Zo2RjM2tHUEIfDtnaFb7Zp5miXaPE43Xr89ugmCu6rou5p9b@Sw@872838otY/lc17PYN2Wyq4BRep8MLg9cqmMBxfeaBE3j0aBibYPalDI4u2QZppeYQL6Fo/w4ToklIhgwaYspSJt1y86FA9xBibOpKXLMMErohIah9x3G17I4juecDi2jC85kp/cgdMLsMTC1YcrZm94Q0qxJMtFvPn/7Pw) [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 20 bytes ``` (\w)(\w*)(\w) \3\2\1 ``` Simply make three capturing groups consisting of 1, 0-or-more, and 1 word-characters, then reverses their order. [Try it online!](https://tio.run/##TY/BbsMgEETv@YqRT0mlHpre@yW@rGABS2ugLBFKft5d21XVA4idmQfD94N827brPG623vbtdpk/5/v8sW2TDqroiRGWph2UPYTsINw7N0UJYHIJozQ/4f0LUx2k4NTRjQjwmdBJBXoQglCQyDF8aWO6TIlFyo7LL19MSLsru93ZHnOkrKd7zGqzM7O2Ehut65Ij6uP1EtajoSueEYuEk4l/sQo9YvWoxcU7qyPRrloyCLExZ6xMvowTzYvJ2eSIscurRZ/0RLMfOGpn6L/wAw "QuadR – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 24 bytes ``` s/(\w)(\w*)(\w)/$3$2$1/g ``` [Try it online!](https://tio.run/##K0gtyjH9/79YXyOmXBOItUCEpr6KsYqRiqF@@v//Gak5OfkK5flFOSn/8gtKMvPziv/r@prqGRgZ/dctAAA "Perl 5 – Try It Online") [Answer] ## Batch, 141 bytes ``` @set t= @for %%w in (%*)do @call:c %%w @echo%t% @exit/b :c @set s=%1 @if not %s%==%s:~,1% set s=%s:~-1%%s:~1,-1%%s:~,1% @set t=%t% %s% ``` Takes input as command-line parameters. String manipulation is dire in Batch at best, and having to special-case single-letter words doesn't help. [Answer] # APL+WIN, 50 bytes ``` (∊¯1↑¨s),¨1↓¨(¯1↓¨s),¨↑¨s←((+\s=' ')⊂s←' ',⎕)~¨' ' ``` Prompts for string and uses space as the delimiter. [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rPOroOrTe8FHbxEMrijV1Dq0AMicfWqEBFpsMFYPIAjVpaGjHFNuqK6hrPupqAgkAmTpAEzXrDq0AMv8DjfyfxqVeXJ5YoFCSkaqQlllUXKKQmJeiALS9RCEntaQktahYIT9NITUxOUOhPL8oRR0A "APL (Dyalog Classic) – Try It Online") [Answer] ## sed, 64 bytes ``` sed -E 's/\b([[:alpha:]])([[:alpha:]]*)([[:alpha:]])\b/\3\2\1/g' ``` [Answer] # [sed](https://www.gnu.org/software/sed/), 34 bytes And presumably the pattern idea will work with most RE tools (and I do know there are differences between standard RE and extended RE). ``` s,\b\(\w\)\(\w*\)\(\w\)\b,\3\2\1,g ``` [Try it online!](https://tio.run/##NY89TsUwEIT7nGJKQHnFg1MgISpKN5tkia04Xss/L@T0YeNAM2uNZz@PM0@3OdTjyL0ZzJPZzPOpL9dQHXrzZl7NvZ@P41MKo1gqKoxUPWdk2i9rY0jwOyw9NCTINUZJRU3G4sLUyTcyR0pUJOGGd9CK0YpkF2bkSKPSvni0wY3kFeSUKWnJ2FyxneiTCZt1hVsWpBfsfY@hlpZ13qPUFMAPTnuxJ9aFs0ljdy602hwmfLjQDhrJaL7L4B9ao2fUTLPiE@tXwuR5@q/Nfu8Ut9LCF@lvQWqJ2sGLLNDynLpf "sed – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 75 bytes ``` x->join([(n=length(s);n<2 ? s : s[n]*s[2:n-1]*s[1]) for s in split(x)]," ") ``` [Try it online!](https://tio.run/##VY7LDoIwFET3fsWEVWtkAUvf/0FYVLiFmuaW9FbBr8e6UneTMzmZuT@8M9Wy2tONBsfrUp7vwbFqFJ888ZBGJfrAxxoXCPaQhtutNPWey@oTqlbDhpg7x5DJu6QW3e4KFHol7jdXGcMMqwqZzYQ0EqyLkmC4hzc5eEqJIoIFPSm@MIfYF/rrjeR9@FD/hxNltzNC8ksNbujQI69gyA/e "Julia 1.0 – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 110 bytes ``` |a:&str|{for b in a.split(' '){let l=b.len()-1;if l>0{print!("{}{}",&b[l..],&b[1..l])}print!("{} ",&b[0..1])}} ``` [Try it online!](https://tio.run/##RU@9DoMgEN59iiuDQtISXWvsM3RvHLCiITnBAKaJyLNbdGhv@ZL7/u7s4vw@aJiE0pRByCANSg8Omn0T99x5u4XBWOhAaRDczag8LaBg4ZBh03GUyXqrajUAPsowW6X9hZIQQyTXvHsh5@2BFefYsvjn4aRLzqu0jnt9ljtKntaMVkyT0iPMy7qidCB0D2/TSxgNDoTVZwrqC2U/23EfjFbK9I4UvfkkWRb3Lw "Rust – Try It Online") ### A surprisingly long, but nicer solution that returns instead of printing (126 bytes): ``` |a:&str|->String{a.split(' ').flat_map(|b|{let mut q:Vec<_>=b.chars().collect();q.swap(0,b.len()-1);q.push(' ');q}).collect()} ``` [Try it online!](https://tio.run/##dY@9jsIwEIT7e4q9FGBLYB0tOXiGk5Bo0cZxQqT1T@yNkEjy7MGkuoYpR9/szMYh8dI4sNg5IWH8giwyDAlOy4THTeI47c8Xjp1rR1QpUMdiC1upGkK@WQxiqqbxHbEDQ3@8Gv17O58qpe8Yk5BKeyKjWciyV@mR@Z9dpcjkuv3h7YUh3deLZT//o@elXMeE3MzkvkUxzsUOkij@om8jWpsXQRieTzIJ0NWgfW2g9dQUUn7Kdg4Q2mhMftlg7R8rOy8v "Rust – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 15 bytes ``` aR+XW{@a::a@va} ``` Takes the string as a command-line argument. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a **14-byte** version in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/MUg7Irw62CEx0aEssfb////F5YkFCiUZqQppmUXFJQqJeSkKOYlARk5qSUlqUbFCfppCokJ5flEKAA "Pip – Try It Online") ### Explanation ``` aR+XW{@a::a@va} a In the command-line argument, R replace all matches of +XW the regex `\w+` { } with the following callback function: @a Take the first character of the matched string a@v and its -1th (last) character :: and swap them a Return the modified string ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` wm§:→oṙ1hw ``` [Try it online!](https://tio.run/##yygtzv7/vzz30HKrR22T8h/unGmYUf7////i8sQChZKMVIW0zKLiEoXEvBSFnEQgIye1pCS1qFghP00hNTE5Q6E8vygFAA "Husk – Try It Online") ### Explanation ``` wm§:→oṙ1hw m w map over each word §: concatenate the → last char o h and the rest ṙ1 rotated w join on spaces ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes (10 nibbles) ``` :`(\@:`)\$ ``` Word separator is newline character. ``` :`(\@:`)\$$ # (code with implicitly-added final $) # implicit map over lines of input: : # joined `( # first character of \@ # reversed word # (and save leftover of reversed word in variable $) # with : # joined `) # all but first character of \$ # reversed leftover of reversed word # with $ # first character of leftover of reversed word # (so, first character of the original word) ``` [![enter image description here](https://i.stack.imgur.com/tNC2d.png)](https://i.stack.imgur.com/tNC2d.png) ]
[Question] [ You are to print this exact text: ``` ABABABABABABABABABABABABAB BCBCBCBCBCBCBCBCBCBCBCBCBC CDCDCDCDCDCDCDCDCDCDCDCDCD DEDEDEDEDEDEDEDEDEDEDEDEDE EFEFEFEFEFEFEFEFEFEFEFEFEF FGFGFGFGFGFGFGFGFGFGFGFGFG GHGHGHGHGHGHGHGHGHGHGHGHGH HIHIHIHIHIHIHIHIHIHIHIHIHI IJIJIJIJIJIJIJIJIJIJIJIJIJ JKJKJKJKJKJKJKJKJKJKJKJKJK KLKLKLKLKLKLKLKLKLKLKLKLKL LMLMLMLMLMLMLMLMLMLMLMLMLM MNMNMNMNMNMNMNMNMNMNMNMNMN NONONONONONONONONONONONONO OPOPOPOPOPOPOPOPOPOPOPOPOP PQPQPQPQPQPQPQPQPQPQPQPQPQ QRQRQRQRQRQRQRQRQRQRQRQRQR RSRSRSRSRSRSRSRSRSRSRSRSRS STSTSTSTSTSTSTSTSTSTSTSTST TUTUTUTUTUTUTUTUTUTUTUTUTU UVUVUVUVUVUVUVUVUVUVUVUVUV VWVWVWVWVWVWVWVWVWVWVWVWVW WXWXWXWXWXWXWXWXWXWXWXWXWX XYXYXYXYXYXYXYXYXYXYXYXYXY YZYZYZYZYZYZYZYZYZYZYZYZYZ ZAZAZAZAZAZAZAZAZAZAZAZAZA ``` # Specs * You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output. * You may print one extra trailing linefeed. # Scoring Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins. [Answer] # C, 60 bytes ``` main(i){for(;i<703;)putchar(i++%27?65+(i/27+i%27%2)%26:10);} ``` [Answer] # Brainfuck, 104 bytes ``` >+[+[<]>>+<+]><<+++++[>+++++>>++<<<-]>[-<+++++++++++++[->>.+.-<<]>>>.<+<]<----[>+<----]>++>>+++[-<.<.>>] ``` [Answer] ## Convex, 10 bytes ``` U_(+]D*zN* ``` [Try it online!](http://convex.tryitonline.net/#code=VV8oK11EKnpOKg&input=) ``` U Predefined Variable: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" _(+ Push a copy with the 'A at the end. ] Add both strings to an array. D* Repeat array 13 times. D defaults to 13. z Transpose. N* Join by newlines. N defaults to "\n" ``` [Answer] ## Pyth, ~~11~~ 10 bytes ``` jC*13.<BG1 ``` [Try it here.](https://pyth.herokuapp.com/?code=jC%2a13.%3CBG1&debug=0) ``` G the alphabet B bifurcate over .< 1 left shift by 1 *13 repeat 13 times C transpose j join on newlines ``` [Answer] # Vim, ~~85~~ 83 bytes ``` :h<_<cr><cr><cr>YZZP:s/./\0\r/g<cr><c+v>ggy25Pqqlxj:let @a='xkPjj'<cr>25@akia<esc>25klq11@qh<ctrl+v>25jylpl<c+v>25jdGdd ``` I know this can be golfed more, but my head hurts so I gotta stop for now. `<cr>` is the enter key, `<c+v>` is ctrl+v, and `<esc>` is the escape key. Those were all counted as one byte. I recorded a gif of this, but it got screwed up. The video is fine though: <http://recordit.co/ldLKvho9Gi> [Answer] # Ruby, ~~42~~ ~~39~~ ~~38~~ 37 bytes -3 bytes thanks to @user81655 -1 byte thanks to @manatwork -1 byte thanks to @NotthatCharles ``` ?A.upto(?Z){|a|puts (a+a.next[0])*13} ``` See it on repl.it: <https://repl.it/CmOJ> [Answer] # Cheddar, 48 bytes ``` print(65|>90).map(l->@"[l,l>89?65:l+1]*13).vfuse ``` Cheddar is good with strings :D [Try it online!](http://cheddar.tryitonline.net/#code=cHJpbnQoNjV8PjkwKS5tYXAobC0-QCJbbCxsPjg5PzY1OmwrMV0qMTMpLnZmdXNl&input=) ## Explanation ``` print (65|>90) // Range from 65 (A) to 90 (Z) .map(l-> // Map through range @" // Convert following array of char codes to string [l, // The character l>89?65:l+1] // See below for explanation *13 // Repeat 13 times ).vfuse // Vertically fuse ``` What does `l>89?65:l+1` do? Well `89` is the char code for `Y`. Basically, `l>89` is checking if the letter is `Z`, that means we should be returning `A`. If `l>89` is false. I'll return `l+1`, the next char [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 26ḶḂØAṙZj⁷ ``` [Try it online!](http://jelly.tryitonline.net/#code=MjbhuLbhuILDmEHhuZlaauKBtw&input=) ### How it works ``` 26ḶḂØAṙZj⁷ Main link. No arguments. 26Ḷ Yield [0, ..., 25]. Ḃ Bit; compute the parity of each intger. ØAṙ Rotate the alphabet by these amounts. Z Zip; transpose rows and columns. j⁷ Join, separating by linefeeds. ``` [Answer] ## Haskell, ~~60~~ 58 bytes ``` mapM putStrLn[[0..12]>>[a,b]|a:b:_<-scanr(:)"A"['A'..'Z']] ``` Starting with "A" `scanr(:)` builds the a list from the chars of `['A'..'Z']` from the right. (-> `["ABCDE...A", "BCDEF..A", ..., "XYZA", "YZA", "ZA", "A"]`). `(a:b:_)` matches the first two chars of each sublists (with at least two chars) and makes 13 copies of it. [Answer] ## PowerShell, 49 43 bytes TimmyD's remix: ``` 65..89|%{-join[char[]]($_,++$_)*13};"ZA"*13 ``` was, 49 bytes: ``` 0..25|%{(""+[char]($_+++65)+[char]($_%26+65))*13} ``` [![Example output](https://i.stack.imgur.com/G8lmn.gif)](https://i.stack.imgur.com/G8lmn.gif) [Answer] # Python 2, ~~70~~ ~~68~~ 54 bytes List based solution: ``` L=map(chr,range(65,91)) for i in range(-26,0):print(L[i]+L[i+1])*13 ``` But why create a list? Thanks LeakyNun: ``` for i in range(26):print(chr(i+65)+chr(-~i%26+65))*13 ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 26 bytes ``` P +'A ~ | S +$ r2 ,' r' ``` Note the trailing unprintable characters on the last two lines. [Try it online!](http://jellyfish.tryitonline.net/#code=UAorJ0EKfgp8IFMKKyQgcjIKICwnGgpyJxo&input=) ## Explanation This is basically an arithmetic manipulation approach: make a 26×26 grid with alternating 0-1 pattern, add the index of each row to every element of the row, reduce mod 26, and add the ASCII value of `A`. Characters in Jellyfish are just numbers with a special flag, and all arithmetic works on them as expected. From bottom to top: * The `'`s are character literals; they are followed by unprintables with ASCII code 26, and stand for those characters. * The lower `r` computes the character range from 0 to 25. * The `,` forms a pair from the two unprintable chars. * The higher `r` is given argument `2`, and forms the range `[0 1]`. * The `$` takes that range, and reshapes it into the shape given by its other argument, which is the pair of unprintables. This gives a 26×26 matrix of alternating rows `0 1 0 1 0 1 ...` * The lower `+` adds the char range 0-25 to this matrix. The addition distributes on the rows, so row **i** is incremented by **i**. It's also converted to a char matrix, since the south argument consists of chars. * The `~|` is modulus with flipped arguments: the south argument (the above char matrix) is reduced modulo the east argument (the `S` turns the argument-seeking process south, so this is the unprintable literal 26). * The higher `+` adds the literal `A` to every coordinate of the resulting matrix. * The `P` prints the result in matrix format, that is, each row on its own line without quotes. [Answer] # R, ~~72~~ ~~67~~ ~~60~~ 56 bytes ``` write(matrix(LETTERS[c(1:26,2:26,1)],26,26,T),"",26,,"") ``` Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for the extra 4 bytes off! Old `rep`-based solution at 60 bytes: ``` for(i in 1:26)cat(rep(LETTERS[c(i,i%%26+1)],13),"\n",sep="") ``` See [here](http://www.r-fiddle.org/#/fiddle?id=BG1LX7Mx&version=5) on an online interpreter. Thanks to [@user5957401](https://codegolf.stackexchange.com/users/58162) for the extra 7 bytes off! Old matrix-based solution at 72 bytes: ``` for(i in 1:26)cat(matrix(LETTERS[c(1:26,2:26,1)],26,26)[i,],"\n",sep="") ``` See [here](http://www.r-fiddle.org/#/fiddle?id=BG1LX7Mx&version=1) on an online interpreter. [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` 1Y2tn:!to~!+) ``` [**Try it online!**](http://matl.tryitonline.net/#code=MVkydG46IXRvfiErKQ&input=) ``` 1Y2 % Predefined string literal: 'AB···Z' tn: % Duplicate, number of elements, range: gives [1, 2, ···, 26] ! % Transpose into a column vector to~! % Duplicate and transform into [0, 1, 0, 1, ···, 1] using modulo 2 + % Addition with broadcast. Gives 2D numeric array ) % Index (modularly) into string. Implicitly display. ``` [Answer] # Vim, 31 bytes ``` :h<_↵↵↵YZZPJra0qqy2l13Plr↵25@qD ``` Where `↵` is the Return key. [![enter image description here](https://i.stack.imgur.com/zDguj.gif)](https://i.stack.imgur.com/zDguj.gif) [Answer] ## Perl, 26 bytes *Solution from [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings). (12 bytes shorter than mine!)* *-1 byte thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel)* ``` say+($_++,chop)x13for A..Z ``` Run with `-M5.010` or `-E` : ``` perl -E 'say+($_++,chop)x13for A..Z' ``` [Answer] **T-SQL 133 Bytes** (Golfed by : @t-clausen.dk) ``` SELECT REPLICATE(Char(number+65)+IIF(number=25,'A',Char(number+66)),13)FROM spt_values WHERE number<26and'P'=TYPE ``` **T-SQL , 151 Bytes** Using CTE to generate sequence of number ``` ;WITH n(a,v) AS(SELECT CHAR(65)+CHAR(66), 66 UNION ALL SELECT CHAR(v)+CHAR(v+1), v+1 FROM n WHERE v < 91)SELECT REPLICATE(REPLACE(a,'[','A'),13) FROM n ``` **T-SQL, 155 Bytes** ``` SELECT REPLICATE(Char(number+65)+ CASE WHEN number=25 THEN 'A' ELSE Char(number+66) END, 13) FROM master.dbo.spt_values WHERE name IS NULL AND number < 26 ``` [Answer] # Julia, 46 bytes ``` [println("$c$(c+1-26(c>89))"^13)for c='A':'Z'] ``` [Try it online!](http://julia.tryitonline.net/#code=W3ByaW50bG4oIiRjJChjKzEtMjYoYz44OSkpIl4xMylmb3IgYz0nQSc6J1onXQ&input=) [Answer] # Pyth, 10 bytes ``` jCm.<G~!ZG ``` [Demonstration](https://pyth.herokuapp.com/?code=jCm.%3CG~%21ZG&debug=0) Explanation: ``` jCm.<G~!ZG m G Map over G, predefined to the lowercase alphabet. This will give 26 columns. .<G Left shift (cyclically) G by Z Z elements. Z is initialized to 0. ~! After using its value, logical not Z. (0 -> 1, 1 -> 0) C Transpose j Join on newlines ``` [Answer] ## Brainfuck, ~~88~~ 86 bytes ``` ++[[+>]<+<++]+>-[[->+>+<<]>>-]++++++++[<[++++++++<+<]>[>]<-]<<++<[>+++[->.<<.>]<<++.<] ``` Requires an interpreter with 8-bit cells and a tape not bounded on the left. [Try it online!](http://brainfuck.tryitonline.net/#code=KytbWys-XTwrPCsrXSs-LVtbLT4rPis8PF0-Pi1dKysrKysrKytbPFsrKysrKysrKzwrPF0-Wz5dPC1dPDwrKzxbPisrK1stPi48PC4-XTw8KysuPF0&input=) [Answer] # Lua, 80 65 Bytes. ``` s = string c = s.char for i=1,26 do print(s.rep(c(64+i)..c((65+(i%26))),13)) end ``` With help from Leaky Nun ``` c=("").char for i=1,26 do print((c(64+i)..c(65+i%26)):rep(13))end ``` Lua is a pretty inefficent language in regards to handling of strings and such, so this is the best I can narrow it down. [Answer] ## 05AB1E, 12 bytes ``` ADÀ)øvyJ5Ø×, ``` **Explanation** ``` AD # push 2 copies of the alphabet À # rotate the 2nd one left by 1 )ø # add to list and zip v # for each yJ # join the pair 5Ø× # repeat it 13 times , # print with newline ``` [Try it online](http://05ab1e.tryitonline.net/#code=QUTDgCnDuHZ5SjXDmMOXLA&input=) [Answer] # Mathematica, ~~82~~ ~~75~~ ~~67~~ 66 bytes ``` Print@FromCharacterCode@PadLeft[{},26,{i-1,i}~Mod~26+65]~Do~{i,26} ``` Technically shorter, although it prints in lowercase instead of uppercase: # Mathematica, 64 bytes ``` Print[""<>FromLetterNumber@Table[{i-1,i}~Mod~26+1,13]]~Do~{i,26} ``` [Answer] # TSQL, 111 bytes ``` DECLARE @o varchar(702)='',@ int=1WHILE @<702SELECT @o+=CHAR(IIF(@%27=0,10,65+(@/27+1-@%27%2)%26)),@+=1PRINT @o ``` [Fiddle](https://data.stackexchange.com/stackoverflow/query/523598/print-an-alphabet-wave) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [bytes](https://github.com/abrudz/SBCS) ``` ⍉↑26⍴⌽∘⎕A¨⍳2 ``` [Try it online!](https://tio.run/##XZC7DoJAEEV7voISCgWWh7WfAjEQEwK2JlYWCBvWaIzG1kcisdXCxsZPmR/Bu4EYobjJZufM2Zn1Z/FgMvfjNKppvZ@mlG1MhfJVWJMoKNsyj8STyjflR9THn4rEg9UA6lBRkigBD1BDzZeUqNiC@Fmn8iWvlCCwQGiNBZ068QNUQ@IXsNIIhDWS32u41Sxpw0FH3Zb1/P6PZDumslELA3G6ClOV/RiWL1vAbRztIFcLcNfg9YborYw/uRmMipOBpVWshTDERhzERbwv "APL (Dyalog Unicode) – Try It Online") Requires `⎕IO←0`, so that `⍳2` evaluates to `0 1`. ### How it works ``` ⍳2 ⍝ 0 1 ⌽∘⎕A¨ ⍝ Rotate the uppercase alphabet 0 and 1 times, ⍝ giving ["ABC..Z", "BCD..ZA"] 26⍴ ⍝ Cycle the two strings to the length of 26 ⍉↑ ⍝ Promote to a matrix and transpose ``` --- ## Bunch of 13- and 14-byte solutions ``` ⍉↑26⍴⎕A(1⌽⎕A) ⍉↑26⍴0 1⌽¨⊂⎕A (26⍴⍳2)⊖∘.⊣⍨⎕A ∪⍉↑26⍴↓2 27⍴⎕A ∪26⍴⍤1⍉2 27⍴⎕A ``` These are included in the TIO link above. [Answer] # [Brachylog v1](https://github.com/JCumin/Brachylog/releases), ~~30~~ ~~24~~ 20 bytes ``` ~~@Ab:"a"c:@Arz:{:12jc:@Nc.}a:wa~~ ~~@Ab:"a"c:@Arze:12jcw@Nw\~~ @A$(:@Arze:12jcw@Nw\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=QEEkKDpAQXJ6ZToxMmpjd0BOd1w) [Answer] # J, ~~20~~ 19 bytes **1 byte thanks to miles.** ``` u:65+26|(+/2&|)i.26 ``` [Online interpreter](http://tryj.tk/) This is actually the program I used to generate the text in the challenge. [Answer] # Oracle SQL 11.2, ~~141~~ 138 bytes ``` SELECT LISTAGG(CHR(l+64)||CHR(MOD(l,26)+65))WITHIN GROUP(ORDER BY l)FROM(SELECT CEIL(LEVEL/13)l FROM DUAL CONNECT BY LEVEL<339)GROUP BY l; ``` Un-golfed ``` SELECT LISTAGG(CHR(l+64)||CHR(MOD(l,26)+65))WITHIN GROUP(ORDER BY l) FROM ( SELECT CEIL(LEVEL/13)l FROM DUAL CONNECT BY LEVEL<339 -- 26*13+1 ) GROUP BY l ``` [Answer] # T-SQL 99 90 bytes Saved 9 bytes thanks to @t-clausen.dk `DECLARE @ INT=65z:PRINT REPLICATE(CHAR(@)+CHAR(IIF(@=90,65,@+1)),13)SET @+=1IF @<=90GOTO z` Ungolfed: ``` DECLARE @CurrCharacter INT = 65; --ASCII decimal for 'A' WHILE (@CurrCharacter <=90) --ASCII decimal for 'Z' BEGIN PRINT REPLICATE( REPLACE(CHAR(@CurrCharacter)+CHAR(@CurrCharacter+1),'[','A') ,13); --Replicate the current character and its neighbor 13 times. If the neighbor is '[' (ASCII code 91) then replace it with 'A'. SET @CurrCharacter+=1; --Go to the next letter END ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes ``` AuDÀø13×» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fsdTlcMPhHYbGh6cf2v3/PwA "05AB1E – Try It Online") Posting because it beats the other 05AB1E answer and kinda uses a different method *-2 with vectorisation* ## Explained ``` Au # Push the uppercase alphabet. STACK = [A-Z] D # Duplicate that. STACK = [A-Z, A-Z] À # Rotate the alphabet left. STACK = [A-Z, Rotate_Left(A-Z)] ø # Zip those two alphabets. STACK = ["AB", "BC", "CD", "DE", "EF", "FG", "GH", "HI", "IJ", "JK", "KL", "LM", "MN", "NO", "OP", "PQ", "QR", "RS", "ST", "TU", "UV", "VW", "WX", "XY", "YZ", "ZA"] 13×» # Repeat each 13 times and join with newline ``` ]
[Question] [ Some characters are more holy than others. Using as few unholy letters as possible, display the statement above. **Challenge** Write a full program to print `Holy Hole In A Donut, Batman!` to STDOUT or closest alternative. If you can compress the input to reduce your score, go wild :) **Input** None **Output** ``` Holy Hole In A Donut, Batman! ``` **Rules** 1. This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), and lowest score wins 2. The desired output can be read from a file, but that should then be counted towards your total. 3. Trailing newlines are fine in the output 4. Standard loopholes and T&C's apply **Scoring** Your score is your byte count, plus some modifiers: 1. Using holy characters `0469abdegopqrADOPQR@#` count as 2 points each 2. Using extra holy characters `8B%$&` are 1 point (no penalty) 3. Using unholy characters `12357cfhijklmnstuvwxyzCEFGHIJKLMNSTUVWXYZ!"^*()[]{}-=_+|\/?,.<>:;'~` carries a heavier penalty and count as 10 points per character. 4. Space, tab and newlines are 1 point (no penalty). 5. Any other characters not listed are 10 points. \*On my keyboard the key '$' and '&' are extra holy. Where font variations cause a character to become unholy, defer to the list above The unmodified string `Holy Hole In A Donut, Batman!` scores **172** Ruby: `puts "Holy Hole In A Donut, Batman!"` scores **225** **Score checker** @DeadChex has kindly put together a [scoring script](https://jsfiddle.net/qj5vLesq/1/embedded/result/) Please do let me know if I need to clarify anything. I will update the list of characters if necessary - I've only included the obvious keys at this point. The idea is simple enough though - holes in characters are good. [Answer] # Unary, 109,700,689,123,880,793,751,483,665,383,781,675,730,387,604,429,204,978,112,223,950,724,553,435,005,885,707,908,578,678,850,861,879,910,670,154,149,244,112,969,597,673,955,700,447,838,276,456,862,280,889,656,901,703,351,515,963,083,297,978,322,224,548,248,606,910,210,200,102,145,647,654,537,444,488,063,149,647,173,155,335,488,014,867,140,385,453,547,997,132,573,700,942,612,360 points Calculated through [bc](https://en.wikipedia.org/wiki/Bc_(programming_language)) which is the highest precision calculator that I know of Code: ``` 54850344561940396875741832691890837865193802214602489056111975362276717502942853954289339425430939955335077074622056484798836977850223919138228431140444828450851675757981541648989161112274124303455105100051072823827268722244031574823586577667744007433570192726773998566286850471306180 zeros ``` 4.5x10259 Yottabytes Well this ain't winning [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~154~~ ~~153~~ ~~148~~ 143 points ``` " $& & &$&% % B8B$ $8 %8%8& $& & 8 8 $B$ $&B8$$$B "0$0$&$f#8b90b' f+ ``` [Try it online!](https://tio.run/nexus/cjam#FcqhEcAwDARBrK9C47wUEGL4oSrFwP13oDjwZq@Hg2meSGY4AA@zUhHmlCEUOm5MnEmQs/hniWRhTE4m96X1znX7fro/ "CJam – TIO Nexus") ### How it works ``` " $& & &$&% % B8B$ $8 %8%8& $& & 8 8 $B$ $&B8$$$B " e# Push a string of encoded base 8 digits. 0$0$ e# Push two copies of that string. & e# Intersect the copies to remove duplicates. $ e# Sort the resulting string. e# Pushes "\t\n $%&8Bb". f# e# Replace each char of the original string by its index in "\t\n $%&8Bb". e# Pushes 213502515354211124007673102360146465020351251616237320357633371, e# to be understood as an array of single-digit integers. 8b90b e# Convert from base 8 digits to base 90 digits. ' f+ e# Add each base 90 digit to the code point of the space character. e# Pushes the desired string. ``` [Answer] # BrainF\*\*\*, 3140 points Behold, the language of **unholiness**! ``` -[------->+<]>-.-[--->+<]>++.---.-[--->+<]>.-[---->+<]>++.++++[->++<]>.-[--->+<]>++.---.-------.--[--->+<]>-.++++[->++<]>+.+[--->+<]>.-[->+++++<]>-.[->++<]>+.-[-->+<]>.++[->++<]>.[--->+<]>+++.-.+++++++.-.[++>---<]>--.------------.+[->++<]>.[-->+++<]>--.--[--->+<]>-.-------.------------.+++++++++++++.-[->+++++<]>. ``` [Answer] ## Malbolge, ~~1874~~ 1239 ``` (=<`$9]~6;Y327U5v-Qr*Np-&J$#jFg}Cdd@>`O<t]KZp6Wm3US0QPfe**(:9I^$o"`CkW{>Txv:99'`6oo2m1YXiggAed>P&N^?!\IlY3ExTBARc10/_nJ8IG(X&Dfec@~av<]\r8Zon4UTj0Rmfe+Lha`&HFED!BX]VzZ=Rv9UNrLKo2Hk ``` I'm pretty sure this can be golfed more. Will try running this for longer. I want to get sub 1000... I've found shorter length programs (down to 175 I think it was), but the score was higher... Sad. Currently on a 179 length (180 is current) with 4 points less, not sure if editing for that short little bit. [Answer] # sed, ~~169~~ 166 points ``` s&$&\to#y \to#e I% A Do%u8, Ba8ma%!& y&\t#8%&Hltn& ``` I've counted each `\t` as a single point, since it can be replaced with an actual tabulator. [Try it online!](http://sed.tryitonline.net/#code=cyYkJglvI3kgCW8jZSBJJSBBIERvJXU4LCBCYThtYSUhJgp5JgkjOCUmSGx0biY&input=) ### How it works * Both commands use the extra holy `&` as delimiter. * The first command replace the end of the (empty) pattern space with the string `\to#y \to#e I% A Do%u8, Ba8ma%!`. * The second command replaces `\t`, `#`, `8` and `%` with the unholy `H`, `l`, `t` and `n`, respectively. Because of the penalty for unholy characters, transliteration adds 12 bytes but saves 20 points. [Answer] # PHP, ~~175~~ ~~168~~ ~~163~~ ~~160~~ 159 points I did what I could to reduce the score as much as possible. With the help of [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis), the score was reduced by 5 points. ``` echo BeeABBeeoBodBaBdOdPQBBgDQgDdp^"\n\n\t8b\n\n\t\nb&\nb b \n%%nb%%%\n%\nQ"; ``` Yeah, not exactly short... Replace the `\n` and `\t` with a UNIX-style newline and a tab, respectivelly. To execute it, simply run it with the -r switch ([not counted on the score](https://codegolf.meta.stackexchange.com/questions/2424/running-php-with-r-instead-of-code-tags/2428#2428)) --- Here's a shorter one that is only 256 points: ``` <?=$a=Hol,"y {$a}e In A Donut, Batman!"; ``` [Answer] # HTML, 169 points ``` Holy Hole In A Donut&#44 Batman! ``` That's the only character that had a decimal numeric entity with only holed numbers. (In the HTML specification, entities must be followed by a semicolon but it still works in major browsers without one.) [Answer] # JavaScript, 1337 Points ``` for(B="&$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".split("8"),$="",i=0;i<B.length;i++)$+=toDec(s[i]);alert($.split("P").join(" ").toLowerCase().replace(/\b(\s\w|^\w)/g,function($){return $.toUpperCase()})+"!"); ``` This takes advantage of the face that there are 26 letters in the alphabet, and 26 characters can be represented by three digits of ternary (base-3) numbers 0, 1, and 2, here represented by `%$&` respectively. Split that enormous string up at each '8' (I use it as a delimiter because it's extra-holy, spaces would have worked too), convert to a base-3 integer by replacement (`0` becomes `%`, `1` becomes `$`, `2` becomes `&`), convert that to decimal (`%%&` = `2`), and then put the string back together. Add 65 (the `char` value of the letter `A`) and convert each integer to a character, A-Z. Lastly, convert to title-case, and add in punctuation. An easier-to-read unminified version: ``` B ="&$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".split('8') $='' for (i = 0;i<B.length;i++) { $ += toDec(s[i]) }; alert($.split('P').join(' ').toLowerCase().replace(/\b(\s\w|^\w)/g, function (t) { return t.toUpperCase(); })+ "!"); ``` **Sure it's goofy.** But it was a fun idea to play around with anyhow! [Answer] ## Whitespace, 438 points If you see nothing, then it's because of whitespace! Reading about "*4. Space, tab and newlines are 1 point (no penalty).*" brings me to my choice of language: * S = Space * T = Tab * L = Line feed [Start of code] ``` S S S T S S T S S S L T L S S S S S T T S T T T T L T L S S S S S T T S T T S S L T L S S S S S T T T T S S T L T L S S S S S S T S S S S S L T L S S S S S T S S T S S S L T L S S S S S T T S T T T T L T L S S S S S T T S T T S S L T L S S S S S T T S S T S T L T L S S S S S S T S S S S S L T L S S S S S T S S T S S T L T L S S S S S T T S T T T S L T L S S S S S S T S S S S S L T L S S S S S T S S S S S T L T L S S S S S S T S S S S S L T L S S S S S T S S S T S S L T L S S S S S T T S T T T T L T L S S S S S T T S T T T S L T L S S S S S T T T S T S T L T L S S S S S T T T S T S S L T L S S S S S S T S T T S S L T L S S S S S S T S S S S S L T L S S S S S T S S S S T S L T L S S S S S T T S S S S T L T L S S S S S T T T S T S S L T L S S S S S T T S T T S T L T L S S S S S T T S S S S T L T L S S S S S T T S T T T S L T L S S S S S S T S S S S T L T L S S L L L ``` [End of code] [Answer] # Batch, 197 points ``` echo Holy Hole In A Donut, Batman! ``` `c` and `h` are the only two extra characters that aren't holy - and since batch doesn't require quotes round strings, I miss out the 20 point penalty there. [Answer] # [Headsecks](http://esolangs.org/wiki/Headsecks), ~~333~~ 470 I converted my BF program to Headsecks using as many Extra Holy characters as possible. Much holier than BF. Since vertical tabs apparently cost 10, switched to `#`. Note: Probably still a better score than if I hadn't used loops. ``` #&#######8B o8#$#&###8B o8BB$###$#&###8B o8$#&####8B o8BB$BBBB&#8BB o8$#&###8B o8BB$###$#######$##&###8B o8#$BBBB&#8BB o8B$B&###8B o8$#&#8BBBBB o8#$&#8BB o8B$#&##8B o8$BB&#8BB o8$&###8B o8BBB$#$BBBBBBB$#$&BB8### o8##$############$B&#8BB o8$&##8BBB o8##$##&###8B o8#$#######$############$BBBBBBBBBBBBB$#&#8BBBBB o8$ ``` [Answer] # [Insomnia](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/41868#41868), 168 points ``` doe @opp@e p@ pp @d dr$%p$ opp@ p@rop@@% @oe@@ do@ %@pr$% @ r$ % po @ @dp @@ep@ d @% %@d @@% p@ d @ ``` Only managed to do 1 point better than HTML solution. [Answer] # Z80 assembler, ~~539~~ 523 points ``` ld hl,Q L: ld a,(hl) or a ret z call 0A2h inc hl jr L Q: db "Holy Hole In A Donut, Batman!",0 ``` Note that this is intended to run on [a MSX computer](https://en.wikipedia.org/wiki/MSX), whose BIOS routine CHPUT, located at address 00A2h, prints the character passed in the accumulator without modifying any register. (How could the score be calculated by using the assembled binary, by the way?) :-P [Answer] # Pyth, 182 points ``` "Holy Hole In A Donut, Batman! ``` It's not my strongest language. I'm open to suggestions... [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes, score 141 ``` `¤∞ ∵⁽ In A DoṖ₃, Ṙ↳! ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%C2%A4%E2%88%9E%20%E2%88%B5%E2%81%BD%20In%20A%20Do%E1%B9%96%E2%82%83%2C%20%E1%B9%98%E2%86%B3!&inputs=&header=&footer=) A compressed string. Despite various attempts, I haven't found anything better than this :P The score is 108 if you count the Unicode holy characters (`¤∞ṖṘ`) as holy. [Answer] # Pyth, 352 points ``` jkmCid2c::"B88B888 BB8BBBB BB8BB88 BBBB88B B88888 B88B888 BB8BBBB BB8BB88 BB88B8B B88888 B88B88B BB8BBB8 B88888 B88888B B88888 B888B88 BB8BBBB BB8BBB8 BBB8B8B BBB8B88 B8BB88 B88888 B8888B8 BB8888B BBB8B88 BB8BB8B BB8888B BB8BBB8 B8888B"\8\0\B\1d ``` I tried to be smart and encode the string as extra holy characters. That did not work too well... [Answer] # Jolf, noncompeting ### 84 points [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=wrtIb8KnIEhv4oKsIEluIEEgRMKNwqksIELChc6GbiE) ``` »Ho§ Ho€ In A D©, BΆn! ``` Uncompressing a compressed string. [Answer] # [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 232 points `␀` represents a literal null byte `\x00`, which is unholy. ``` <[.<]␀!namtaB ,tunoD A nI eloH yloH ``` [Answer] # [Golunar](http://esolangs.org/wiki/Golunar), 1713 Sure, it's not that competitive, but it scores better than my BF answer. Code is obtained by taking the length of the code in Unary as a number. ``` 17674921849995820305790270238143323861912297173117627579717678879378201073932744615660131563027031190590108979867232158537472346711601276443457666612884962806277404746795044800422000866416680881699125205492286893675575004572084572619659104159027555358269065090420400745692716750939076 ``` [Answer] # [ferNANDo](http://esolangs.org/wiki/FerNANDo), 467 points ``` 8 B B 8 B B 8 B B B B 8 8 B 8 8 8 8 B 8 8 B 8 8 B B B 8 8 8 8 B B 8 B B 8 B B B B B B 8 B B 8 B B B B 8 8 B 8 8 8 8 B 8 8 B 8 8 B B B 8 8 B B 8 B 8 B B 8 B B B B B B 8 B B 8 B B 8 B 8 8 B 8 8 8 B B B 8 B B B B B B 8 B B B B B 8 B B 8 B B B B B B 8 B B B 8 B B B 8 8 B 8 8 8 8 B 8 8 B 8 8 8 B B 8 8 8 B 8 B 8 B 8 8 8 B 8 B B B B 8 B 8 8 B B B B 8 B B B B B B 8 B B B B 8 B B 8 8 B B B B 8 B 8 8 8 B 8 B B B 8 8 B 8 8 B 8 B 8 8 B B B B 8 B 8 8 B 8 8 8 B B B 8 B B B B 8 ``` [Try it online!](http://fernando.tryitonline.net/#code=OCBCCkIgOCBCIEIgOCBCIEIgQgpCIDggOCBCIDggOCA4IDgKQiA4IDggQiA4IDggQiBCCkIgOCA4IDggOCBCIEIgOApCIEIgOCBCIEIgQiBCIEIKQiA4IEIgQiA4IEIgQiBCCkIgOCA4IEIgOCA4IDggOApCIDggOCBCIDggOCBCIEIKQiA4IDggQiBCIDggQiA4CkIgQiA4IEIgQiBCIEIgQgpCIDggQiBCIDggQiBCIDgKQiA4IDggQiA4IDggOCBCCkIgQiA4IEIgQiBCIEIgQgpCIDggQiBCIEIgQiBCIDgKQiBCIDggQiBCIEIgQiBCCkIgOCBCIEIgQiA4IEIgQgpCIDggOCBCIDggOCA4IDgKQiA4IDggQiA4IDggOCBCCkIgOCA4IDggQiA4IEIgOApCIDggOCA4IEIgOCBCIEIKQiBCIDggQiA4IDggQiBCCkIgQiA4IEIgQiBCIEIgQgpCIDggQiBCIEIgQiA4IEIKQiA4IDggQiBCIEIgQiA4CkIgOCA4IDggQiA4IEIgQgpCIDggOCBCIDggOCBCIDgKQiA4IDggQiBCIEIgQiA4CkIgOCA4IEIgOCA4IDggQgpCIEIgOCBCIEIgQiBCIDg&input=) [Answer] # Forth, 193 points ``` ." Holy Hole In A Donut, Batman! ``` [**Try it online**](https://tio.run/nexus/forth-gforth#@6@npOCRn1MJIlIVPPMUHBVc8vNKS3QUnBJLchPzFP//BwA) This also works with the same score: ``` .( Holy Hole In A Donut, Batman! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes (246 points/182 points) ``` ‘¨®¥Ê€†€…‘" Donut, "‘߃‘'!J™ ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oYcahFYfWHVp6uOtR05pHDQvA5DKgsJKCS35eaYmOghKQc3j@sUlASl3R61HLov//jYy5jAE "05AB1E – TIO Nexus") even worse (base-5 with holy characters) - 256 bytes: ``` "BB8$$&B8&&$B$$$8B&$8B%8%$$$&8%&88$$&8%$BB$8B$B$&B8%&%B&8&$8$8&&88""8B%$&"4ÝJ‡5ö36B2ÝJ… ,!‡™ ``` or (less fun, super trivial): ``` "Holy Hole In A Donut, Batman! ``` for 182 points. [Answer] # [W.Y.A.L.H.E.I.N.](https://github.com/MilkyWay90/whenyouaccidentallylose100endorsementsinnationstates), ~~3103 score, 2784 bytes~~ 2886 score, 2558 bytes ``` 14192091 121 8888888888888888888888888888888888888888888888888888888888888888888888888.%8888888888888888888888888888888888888888888888888888.%888888888888888888888888888888888888888888888888888888888888888888888888.%88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%888888888888888888888888888.%88888888888.%8888888888888888888888888888888888888888888888888888888888888888888888888888888888.%888888888888888888888888888888888888888888888888888888888888888888888888888888888.%88888888888888888.%88.%8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%888888888888888888888888888888888888888888888888888888888888888888888888.%88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%8888888888888888888888888888888888888888.%888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%88888888888888.%8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%8888888888888888888888888888888888.%88888888888888888888888.%8888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%8888888888888888888888.%888888888.%888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.%888888888888888888888888.%88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.% ``` [Try it online!](https://tio.run/##K69MzMlIzcz7/9/YzNTIwNKEy9DIkMsJAix8nGgJaGU8jZ094gGJ4YuhnIL4gWglwwCwliGQMKjpRHLMGnZ5B5uHBrknqZlhhm2skxuvA@bVkVUrjdbBwyMUqe8CSkyE6iWr/v//HwA "W.Y.A.L.H.E.I.N. – Try It Online") Used with a brute forcer. After several days, I have golfed this. [Answer] # [><>](https://esolangs.org/wiki/Fish), 201 Points ``` #o<$g0d"oy Hole In A Donut, Batman!"og0b ``` [Try it online!](https://tio.run/##S8sszvj/XznfRiXdIEUpv1LBIz8nVcEzT8FRwSU/r7RER8EpsSQ3MU9RKT/dIOn/fwA "><> – Try It Online") Slightly better than just printing. I imagine clever modulo stuff might be able to shave off a few more points. [Answer] ## Ook! - 15699 points I'll see your Brainfuck, and I raise you this : ``` 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? 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! 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. 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. 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! 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. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook! Ook. ``` No orangutan were harm in the redaction of this program. ]
[Question] [ The ***[Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number)*** ([OEIS](https://oeis.org/A000108)) are a sequence of natural numbers often appearing in combinatorics. The nth Catalan number is the number of Dyck words (balanced strings of parenthesis or brackets such as `[[][]]`; formally defined as a string using two characters `a` and `b` such that any substring starting from the beginning has number of `a` characters greater than or equal to number of `b` characters, and the entire string has the same number of `a` and `b` characters) with length `2n`. The nth Catalan number (for \$n\ge0\$) is also explicitly defined as: $$C\_n=\frac1{n+1}\binom{2n}n$$ Starting from \$n=0\$, the first 20 Catalan numbers are: ``` 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190... ``` # Challenge Write a full program or function that takes a non-negative integer `n` via STDIN or an acceptable alternative, and outputs the nth Catalan number. Your program must work at minimum for inputs `0-19`. ## I/O ### Input Your program must take input from STDIN, function arguments or any of the acceptable alternatives [per this meta post.](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) You can read the inputted number as its standard decimal represention, unary representation, or bytes. * If (and only if) your language cannot take input from STDIN or any acceptable alternative, it may take input from a hardcoded variable or suitable equivalent in the program. ### Output Your program must output the nth Catalan number to STDOUT, function result or any of the acceptable alternatives [per this meta post.](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) You can output the Catalan number in its standard decimal representation, unary representation or bytes. The output should consist of the approriate Catalan number, optionally followed by one or more newlines. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). --- This is not about finding the language that is the shortest. This is about finding the shortest program in every language. Therefore, I will not accept an answer. In this challenge, languages newer than the challenge are acceptable **as long as they have an implementation.** It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8). Note also that built-ins for calculating the nth Catalan number are allowed. # Catalog The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <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 = 66127; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; 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] ## C, ~~78~~ ~~52~~ ~~39~~ ~~34~~ 33 bytes Even more C magic (thanks xsot): ``` c(n){return!n?:(4+6./~n)*c(n-1);} ``` `?:` [is a GNU extension](https://stackoverflow.com/a/2806311). --- This time by expanding the recurrence below (thanks xnor and Thomas Kwa): $$ \begin{equation} \begin{split} C\_0 & = 1 \\ C\_n & = \frac{2 (2n - 1)}{n + 1} C\_{n - 1} \\ & = \frac{2 (2n+2-3)}{n+1} C\_{n - 1} \\ & = 2 \left(2\frac{n+1}{n+1} - \frac{3}{n+1}\right) C\_{n - 1} \\ & = \left(4 - \frac{6}{n+1}\right) C\_{n - 1} \end{split} \end{equation} $$ ``` c(n){return n?(4+6./~n)*c(n-1):1;} ``` `-(n+1)` is replaced by `~n`, which is equivalent in two's complement and saves 4 bytes. --- Again as a function, but this time exploiting the following recurrence: $$ \begin{equation} \begin{split} C\_0 & = 1 \\ C\_n & = \frac{2 (2n - 1)}{n + 1} \cdot C\_{n - 1} \end{split} \end{equation} $$ ``` c(n){return n?2.*(2*n++-1)/n*c(n-2):1;} ``` `c(n)` enters an infinite recursion for negative `n`, although it's not relevant for this challenge. --- Since calling a function seems an acceptable alternative to console I/O: ``` c(n){double c=1,k=2;while(k<=n)c*=1+n/k++;return c;} ``` `c(n)` takes an `int` and returns an `int`. --- Original entry: ``` main(n){scanf("%d",&n);double c=1,k=2;while(k<=n)c*=1+n/k++;printf("%.0f",c);} ``` Instead of directly calculating the definition, the formula is rewritten as: $$ \begin{equation} \begin{split} \frac{1}{n + 1} {2n \choose n} &= \frac{(2n)!}{(n!)^2 \cdot (n + 1)} \\ & = \frac{2n \cdot \ldots \cdot (n + 1)}{n! \cdot (n + 1)} \\ & = \frac{1}{n + 1} \cdot \frac{\prod\_{k = 1}^n (n + k)}{\prod\_{k = 1}^n k} \\ & = \frac{1}{n + 1} \cdot \prod\_{k = 1}^n \frac{n + k}{k} \\ & = \frac{1}{n + 1} \cdot \prod\_{k = 1}^n \left(1 + \frac{n}{k}\right) \\ & = \frac{1}{n + 1} (n + 1) \prod\_{k = 2}^n \left(1 + \frac{n}{k}\right) \\ & = \prod\_{k = 2}^n \left(1 + \frac{n}{k}\right) \end{split} \end{equation} $$ The formula assumes `n >= 2`, but the code accounts for `n = 0` and `n = 1` too. In the C mess above, `n` and `k` have the same role as in the formula, while `c` accumulates the product. All calculations are performed in floating point using `double`, which is almost always a bad idea, but in this case the results are correct up to `n = 19` at least, so it's ok. `float` would have saved 1 byte, unfortunately it's not precise enough. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ḥc÷‘ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bikY8O34oCY&input=&args=NQ) ### How it works ``` Ḥc÷‘ Left argument: z Ḥ Compute 2z. c Hook; apply combinations to 2z and z. ÷‘ Divide the result by z+1. ``` [Answer] ## TI-BASIC, 11 bytes ``` (2Ans) nCr Ans/(Ans+1 ``` Strangely, nCr has higher precedence than multiplication. [Answer] ## CJam, 12 bytes ``` ri_2,*e!,\)/ ``` [Try it online.](http://cjam.tryitonline.net/#code=cmlfMiwqZSEsXCkv&input=OA) Beyond input 11, you'll need to tell your Java VM to use more memory. And I wouldn't actually recommend going much beyond 11. In theory, it works for any N though, since CJam uses arbitrary-precision integers. ### Explanation CJam doesn't have a built-in for binomial coefficients, and computing them from three factorials takes a lot of bytes... so we'll have to do something better than that. :) ``` ri e# Read input and convert it to integer N. _ e# Duplicate. 2, e# Push [0 1]. * e# Repeat this N times, giving [0 1 0 1 ... 0 1] with N zeros and N ones. e! e# Compute the _distinct_ permutations of this array. , e# Get the number of permutations - the binomial. There happen to be 2n-over-n of e# of them. (Since 2n-over-n is the number of ways to choose n elements out of 2n, and e# and here we're choosing n positions in a 2n-element array to place the zeros in.) \ e# Swap with N. )/ e# Increment and divide the binomial coefficient by N+1. ``` [Answer] ## Python 3, 33 bytes ``` f=lambda n:0**n or(4+6/~n)*f(n-1) ``` Uses the recurrence ``` f(0) = 1 f(n) = (4-6/(n+1)) * f(n-1) ``` The base case of 0 is handled as `0**n or`, which stops as `1` when `n==0` and otherwise evaluates the recursive expression on the right. The bitwise operator `~n==-n-1` shortens the denominator and saves on parens. Python 3 is used for its float division. Python 2 could do the same with one more byte to write `6.`. [Answer] # Mathematica, ~~16~~ 13 bytes ``` CatalanNumber ``` Built-ins, amirite fellas :/ Non-builtin version (21 bytes): ``` Binomial[2#,#]/(#+1)& ``` A binomial-less version (25 bytes): ``` Product[(#+k)/k,{k,2,#}]& ``` [Answer] ## J, 8 bytes ``` >:%~]!+: ``` This is a monadic train; it uses the (2x nCr x)/(x+1) formula. Try it [here](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%3E%3A%25%7E%5D!%2B%3A)5). [Answer] # pl, 4 bytes ``` ☼ç▲÷ ``` [Try it online.](http://pl.tryitonline.net/#code=4pi8w6filrLDtw&input=NQ) ## Explanation In pl, functions take their arguments off the stack and push the result back onto the stack. Normally when there are not enough arguments on the stack, the function simply fails silently. However, something special happens when the amount of arguments on the stack is one off from the arity of the function -- the input variable `_` is added to the argument list: ``` ☼ç▲÷ ☼ double: takes _ as the argument since there is nothing on the stack ç combinations: since there is only one item on the stack (and arity is 2), it adds _ to the argument list (combinations(2_,_)) ▲ increment last used var (_) ÷ divide: adds _ to the argument list again ``` In effect, this is the pseudocode: ``` divide(combinations(double(_),_),_+1); ``` [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), ~~94~~ ~~86~~ 68 bytes 8 bytes by changing the factorial-er from version 1 to version 2. 18 bytes by computing `n!(n+1)!` in one step. **Largely inspired by [Dennis' primality test algorithm](https://codegolf.stackexchange.com/a/86501/48934).** Hexdump: ``` 0000000: 16f8de a59f17 a0ebba 7f4cd3 e05f3f cf0fd0 a0ebde ..........L.._?...... 0000015: b1c1bb 76fe18 8cc1bb 76fe1c e0fbda 390fda bde3d8 ...v.....v.....9..... 000002a: 000fbe af9d1b b47bc7 cfc11c b47bc7 cff1fa e07bda .......{.....{.....{. 000003f: 39e83e cf07 9.>.. ``` [Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMixhZGQgMixyd2QgMyxqbnoKZndkIDEsYWRkIDEKam1wCiAgam1wLHN1YiAxLHJ3ZCAxLGFkZCAxLHJ3ZCAxLGFkZCAxLHJ3ZCAxLGFkZCAxLGZ3ZCAzLGpuegogIHJ3ZCAxLHN1YiAxLHJ3ZCAxLHN1YiAxLHJ3ZCAxCiAgam1wLHN1YiAxLGZ3ZCAzLGFkZCAxLHJ3ZCAzLGpuegogIGZ3ZCAxCmpuegpmd2QgMwpqbXAKICBqbXAKICAgIHN1YiAxLHJ3ZCAxCiAgICBqbXAsc3ViIDEscndkIDEsYWRkIDEscndkIDEsYWRkIDEsZndkIDIsam56CiAgICByd2QgMgogICAgam1wLHN1YiAxLGZ3ZCAyLGFkZCAxLHJ3ZCAyLGpuegogICAgZndkIDMKICBqbnoKICByd2QgMQogIGptcCxzdWIgMSxqbnoKICByd2QgMQogIGptcCxzdWIgMSxmd2QgMixhZGQgMSxyd2QgMixqbnoKICBmd2QgMwpqbnogCmZ3ZCAxCmptcAogIGptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMSxhZGQgMSxyd2QgMixqbnoKICBmd2QgMSxzdWIgMSxmd2QgMQogIGptcCxzdWIgMSxyd2QgMixhZGQgMSxmd2QgMixqbnoKICByd2QgMQpqbnoKcndkIDIKam1wCiAgam1wCiAgICBzdWIgMSxmd2QgMQogICAgam1wLHN1YiAxLGZ3ZCAxLGFkZCAxLGZ3ZCAxLGFkZCAxLHJ3ZCAyLGpuegogICAgZndkIDIKICAgIGptcCxzdWIgMSxyd2QgMixhZGQgMSxmd2QgMixqbnoKICAgIHJ3ZCAzCiAgam56CiAgZndkIDEKICBqbXAsc3ViIDEsam56CiAgZndkIDEKICBqbXAsc3ViIDEscndkIDIsYWRkIDEsZndkIDIsam56CiAgcndkIDMKam56IApmd2QgMQpqbXAKICBmd2QgMSxhZGQgMSxyd2QgMwogIGptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMSxzdWIgMSxyd2QgMixqbnoKICBmd2QgMQogIGptcCxzdWIgMSxyd2QgMSxhZGQgMSxmd2QgMSxqbnoKICBmd2QgMQpqbnoKZndkIDEKcHV0&input=NA&debug=on) Uses the formula `a(n) = (2n)! / (n!(n+1)!)`. * The factorial-er: [version 1](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMSxhZGQgMSxyd2QgMixqbnoKZndkIDMKYWRkIDEKcndkIDIKam1wCiAgc3ViIDEKICBmd2QgMQogIGptcAogICAgc3ViIDEKICAgIGZ3ZCAxCiAgICBqbXAKICAgICAgc3ViIDEsZndkIDEsYWRkIDEsZndkIDEsYWRkIDEscndkIDIKICAgIGpuegogICAgZndkIDEKICAgIGptcAogICAgICBzdWIgMSxyd2QgMSxhZGQgMSxmd2QgMQogICAgam56CiAgICByd2QgMgogIGpuegogIGZ3ZCAxLGptcCxzdWIgMSxqbnoKICByd2QgMgogIGptcCxzdWIgMSxmd2QgMixhZGQgMSxyd2QgMixqbnoKICBmd2QgMgogIGptcCxzdWIgMSxyd2QgMSxhZGQgMSxyd2QgMSxhZGQgMSxmd2QgMixqbnoKICBmd2QgMgogIGptcCxzdWIgMSxyd2QgMixhZGQgMSxmd2QgMixqbnoKICByd2QgNApqbnoKZndkIDIKcHV0&input=NQ&debug=on) (in-place, constant memory), [version 2](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcAogIGptcCxzdWIgMSxmd2QgMixhZGQgMSxyd2QgMixqbnoKICBmd2QgMgogIGptcCxzdWIgMSxyd2QgMSxhZGQgMSxyd2QgMSxhZGQgMSxmd2QgMixqbnoKICByd2QgMQogIHN1YiAxCmpuegpyd2QgMgpqbXAKICBqbXAKICAgIHN1YiAxLGZ3ZCAxCiAgICBqbXAsc3ViIDEsZndkIDEsYWRkIDEsZndkIDEsYWRkIDEscndkIDIsam56CiAgICBmd2QgMQogICAgam1wLHN1YiAxLHJ3ZCAxLGFkZCAxLGZ3ZCAxLGpuegogICAgcndkIDIKICBqbnoKICBmd2QgMSxqbXAsc3ViIDEsam56LGZ3ZCAyCiAgam1wLHN1YiAxLHJ3ZCAzLGFkZCAxLGZ3ZCAzLGpuegogIHJ3ZCA0Cmpuegpmd2QgMQpwdXQ&input=NQ&debug=on) (in-place, linear memory) * The multiplier: [here](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CnJ3ZCAxCmdldApqbXAKICBzdWIgMQogIGZ3ZCAxCiAgam1wLHN1YiAxLGZ3ZCAxLGFkZCAxLGZ3ZCAxLGFkZCAxLHJ3ZCAyLGpuegogIGZ3ZCAxCiAgam1wLHN1YiAxLHJ3ZCAxLGFkZCAxLGZ3ZCAxLGpuegogIHJ3ZCAyCmpuegpmd2QgMwpwdXQ&input=MTIKMTM&debug=on) (in place, constant memory) * The divider: [here](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmZ3ZCAyCmdldApyd2QgMgpqbXAKICBmd2QgMwogIGFkZCAxCiAgcndkIDEKICBqbXAsc3ViIDEscndkIDEsYWRkIDEscndkIDEsc3ViIDEsZndkIDIsam56CiAgcndkIDEKICBqbXAsc3ViIDEsZndkIDEsYWRkIDEscndkIDEsam56CiAgcndkIDEKam56CmZ3ZCAzCnB1dA&input=MTU2CjEy&debug=on) (does not halt if not divisible) ## Assembler ``` set numin set numout get jmp,sub 1,fwd 1,add 1,fwd 2,add 2,rwd 3,jnz fwd 1,add 1 jmp jmp,sub 1,rwd 1,add 1,rwd 1,add 1,rwd 1,add 1,fwd 3,jnz rwd 1,sub 1,rwd 1,sub 1,rwd 1 jmp,sub 1,fwd 3,add 1,rwd 3,jnz fwd 1 jnz fwd 3 jmp jmp sub 1,rwd 1 jmp,sub 1,rwd 1,add 1,rwd 1,add 1,fwd 2,jnz rwd 2 jmp,sub 1,fwd 2,add 1,rwd 2,jnz fwd 3 jnz rwd 1 jmp,sub 1,jnz rwd 1 jmp,sub 1,fwd 2,add 1,rwd 2,jnz fwd 3 jnz fwd 1 jmp jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz fwd 1,sub 1,fwd 1 jmp,sub 1,rwd 2,add 1,fwd 2,jnz rwd 1 jnz rwd 2 jmp jmp sub 1,fwd 1 jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz fwd 2 jmp,sub 1,rwd 2,add 1,fwd 2,jnz rwd 3 jnz fwd 1 jmp,sub 1,jnz fwd 1 jmp,sub 1,rwd 2,add 1,fwd 2,jnz rwd 3 jnz fwd 1 jmp fwd 1,add 1,rwd 3 jmp,sub 1,fwd 1,add 1,fwd 1,sub 1,rwd 2,jnz fwd 1 jmp,sub 1,rwd 1,add 1,fwd 1,jnz fwd 1 jnz fwd 1 put ``` ## Brainfuck equivalent [This Retina script](http://retina.tryitonline.net/#code=TSFgKFtmcl13ZHxhZGR8c3ViKSBcZHxqbnp8am1wfGpuZXxub3AKam1wClsKam56Cl0Kc3ViIChcZCkKJDEkKi0KYWRkIChcZCkKJDEkKisKZndkIChcZCkKJDEkKj4KcndkIChcZCkKJDEkKjwKwrYK&input=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMixhZGQgMixyd2QgMyxqbnoKZndkIDEsYWRkIDEKam1wCiAgam1wLHN1YiAxLHJ3ZCAxLGFkZCAxLHJ3ZCAxLGFkZCAxLHJ3ZCAxLGFkZCAxLGZ3ZCAzLGpuegogIHJ3ZCAxLHN1YiAxLHJ3ZCAxLHN1YiAxLHJ3ZCAxCiAgam1wLHN1YiAxLGZ3ZCAzLGFkZCAxLHJ3ZCAzLGpuegogIGZ3ZCAxCmpuegpmd2QgMwpqbXAKICBqbXAKICAgIHN1YiAxLHJ3ZCAxCiAgICBqbXAsc3ViIDEscndkIDEsYWRkIDEscndkIDEsYWRkIDEsZndkIDIsam56CiAgICByd2QgMgogICAgam1wLHN1YiAxLGZ3ZCAyLGFkZCAxLHJ3ZCAyLGpuegogICAgZndkIDMKICBqbnoKICByd2QgMQogIGptcCxzdWIgMSxqbnoKICByd2QgMQogIGptcCxzdWIgMSxmd2QgMixhZGQgMSxyd2QgMixqbnoKICBmd2QgMwpqbnogCmZ3ZCAxCmptcAogIGptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMSxhZGQgMSxyd2QgMixqbnoKICBmd2QgMSxzdWIgMSxmd2QgMQogIGptcCxzdWIgMSxyd2QgMixhZGQgMSxmd2QgMixqbnoKICByd2QgMQpqbnoKcndkIDIKam1wCiAgam1wCiAgICBzdWIgMSxmd2QgMQogICAgam1wLHN1YiAxLGZ3ZCAxLGFkZCAxLGZ3ZCAxLGFkZCAxLHJ3ZCAyLGpuegogICAgZndkIDIKICAgIGptcCxzdWIgMSxyd2QgMixhZGQgMSxmd2QgMixqbnoKICAgIHJ3ZCAzCiAgam56CiAgZndkIDEKICBqbXAsc3ViIDEsam56CiAgZndkIDEKICBqbXAsc3ViIDEscndkIDIsYWRkIDEsZndkIDIsam56CiAgcndkIDMKam56IApmd2QgMQpqbXAKICBmd2QgMSxhZGQgMSxyd2QgMwogIGptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMSxzdWIgMSxyd2QgMixqbnoKICBmd2QgMQogIGptcCxzdWIgMSxyd2QgMSxhZGQgMSxmd2QgMSxqbnoKICBmd2QgMQpqbnoKZndkIDEKcHV0) is used to generate the brainfuck equivalent. Note that it only accepts one digit as command argument, and does not check if a command is in the comments. ``` [->+>>++<<<]>+ [[-<+<+<+>>>]<-<-<[->>>+<<<]>]>>> [[-<[-<+<+>>]<<[->>+<<]>>>]<[-]<[->>+<<]>>>]> [[->+>+<<]>->[-<<+>>]<]<< [[->[->+>+<<]>>[-<<+>>]<<<]>[-]>[-<<+>>]<<<]> [>+<<<[->+>-<<]>[-<+>]>]> ``` [Answer] # Pyth, 8 ``` /.cyQQhQ ``` [Try it online](http://pyth.herokuapp.com/?code=%2F.cyQQhQ&input=5&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=%2F.cyQQhQ&input=50&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&debug=0) ### Explanation ``` /.cyQQhQ ## implicit: Q = eval(input()) / hQ ## integer division by (Q + 1) .c ## nCr yQ ## use Q * 2 as n Q ## use Q as r ``` [Answer] # Julia, 23 bytes ``` n->binomial(2n,n)/(n+1) ``` This is an anonymous function that accepts an integer and returns a float. It uses the basic binomial formula. To call it, give it a name, e.g. `f=n->...`. [Answer] ## Seriously, 9 bytes ``` ,;;u)τ╣E\ ``` Hex Dump: ``` 2c3b3b7529e7b9455c ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b3b7529e7b9452f&input=5) Explanation: ``` , Read in evaluated input n ;; Duplicate it twice u) Increment n and rotate it to bottom of stack τ╣ Double n, then push 2n-th row of Pascal's triangle E Look-up nth element of the row, and so push 2nCn \ Divide it by the n+1 below it. ``` [Answer] # JavaScript (ES6), 24 bytes Based on the [Python answer](https://codegolf.stackexchange.com/a/66141/42545). ``` c=x=>x?(4+6/~x)*c(x-1):1 ``` ### How it works ``` c=x=>x?(4+6/~x)*c(x-1):1 c=x=> // Define a function c that takes a parameter x and returns: x? :1 // If x == 0, 1. (4+6/~x) // Otherwise, (4 + (6 / (-x - 1))) *c(x-1) // times the previous item in the sequence. ``` I think this is the shortest it can get, but suggestions are welcome! [Answer] ## Matlab, ~~35~~ 25 bytes ``` @(n)nchoosek(2*n,n)/(n+1) ``` ## Octave, 23 bytes ``` @(n)nchoosek(2*n,n++)/n ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 3 chars / 6 bytes ``` Мƅï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=4&code=%D0%9C%C6%85%C3%AF)` Builtins ftw! So glad I implemented math.js early on. # Bonus solution, 12 chars / 19 bytes ``` Мơ 2*ï,ï)/⧺ï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=true&input=19&code=%D0%9C%C6%A1%202*%C3%AF%2C%C3%AF%29%2F%E2%A7%BA%C3%AF)` Ay! 19th byte! Evaluates to pseudo-ES6 as: ``` nchoosek(2*input,input)/(input+1) ``` [Answer] ## Haskell, 27 bytes ``` g 0=1 g n=(4-6/(n+1))*g(n-1) ``` A recursive formula. There's got to be a way to save on parens... Directly taking the product was 2 bytes longer: ``` g n=product[4-6/i|i<-[2..n+1]] ``` [Answer] ## Dyalog APL, 9 bytes ``` +∘1÷⍨⊢!+⍨ ``` This is a monadic train; it uses the (2x nCr x)/(x+1) formula. Try it online [here](http://tryapl.org/?a=%28+%u22181%F7%u2368%u22A2%21+%u2368%29%20%u237315&run). [Answer] # C, ~~122~~ ~~121~~ ~~119~~ 108 bytes ``` main(j,v)char**v;{long long p=1,i,n=atoi(v[1]);for(j=0,i=n+1;i<2*n;p=(p*++i)/++j);p=n?p/n:p;printf("%d",p);} ``` I used gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) to compile in a windows cygwin environment. Input comes in on the command line. It's similar to Sherlock9's Python solution but the loops are combined into one to avoid overflow and get output up to the 20th Catalan number (n=19). [Answer] # [Javagony](http://esolangs.org/wiki/Javagony), 223 bytes ``` public class C{public static int f(int a,int b){try{int z=1/(b-a);}catch(Exception e){return 1;}return a*f(a+1,b);}public static void main(String[]s){int m=Integer.parseInt(s[0])+1;System.out.println(f(m,2*m-1)/f(1,m)/m);}} ``` Fully expanded: ``` public class C { public static int f(int a,int b){ try { int z=1/(b-a); } catch (Exception e){ return 1; } return a*f(a+1,b); } public static void main(String[] s){ int m=Integer.parseInt(s[0])+1; System.out.println(f(m,2*m-1)/f(1,m)/m); } } ``` [Answer] # R, ~~35~~ ~~28~~ 16 bytes ``` numbers::catalan ``` Edit: Use numbers package builtin. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Dxcr>/ ``` **Explanation:** ``` Code: Stack: Explanation: Dxcr>/ D [n, n] # Duplicate of the stack. Since it's empty, input is used. x [n, n, 2n] # Pops a, pushes a, a * 2 c [n, n nCr 2n] # Pops a,b pushes a nCr b r [n nCr 2n, n] # Reverses the stack > [n nCr 2n, n + 1] # Increment on the last item / [(n nCr 2n)/(n + 1)] # Divides the last two items # Implicit, nothing has printed, so we print the last item ``` [Answer] # R, 28 bytes Not using a package, so slightly longer than a previous answer ``` choose(2*(n=scan()),n)/(n+1) ``` [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), 9 bytes ``` nxx«*n>÷1 ``` [Try it online!](http://oasis.tryitonline.net/#code=bnh4wqsqbj7DtzE&input=&args=MTk) Oasis is a language designed by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) which is specialized in sequences. Here, we shall use the following relationship kindly provided by [Stefano Sanfilippo](https://codegolf.stackexchange.com/a/66168/48934): ![](https://i.stack.imgur.com/CW9Zo.png) Currently, this language can do recursion and closed form. To specify that `a(0)=1` is simple: just add the `1` at the end. For example, if a sequence begins with `a(0)=0` and `a(1)=1`, just put `10` at the end. Unfortunately, all sequences must be 0-indexed. ``` nxx«*n>÷1 stack 1 a(0)=1 n push n (input) n x double 2n x double 4n « minus 2 4n-2 * multiply: second (4n-2)*a(n-1) argument is missing, so a(n-1) is used. n push n (input) (4n-2)*a(n-1) n > add 1 (4n-2)*a(n-1) n+1 ÷ integer division (4n-2)*a(n-1)/(n+1) = ((4n-2)/(n+1))*a(n-1) = ((4n+4-6)/(n+1))*a(n-1) = ((4n+4)/(n+1) - 6/(n+1))*a(n-1) = (4-6/(n+1))*a(n-1) ``` --- Closed-form: ## 10 bytes ``` nx!n!n>!*÷ ``` [Try it online!](http://oasis.tryitonline.net/#code=bnghbiFuPiEqw7c&input=&args=MTk) ``` nx!n!n>!*÷ n push n (input) x double ! factorial: stack is now [(2n)!] n push n (input) ! factorial: stack is now [(2n)! n!] n push n (input) > add 1 ! factorial: stack is now [(2n)! n! (n+1)!] * multiply: stack is now [(2n)! (n!(n+1)!)] ÷ divide: stack is now [(2n)!/(n!(n+1)!)] ``` [Answer] # TeX, 231 bytes ``` \newcommand{\f}[1]{\begingroup\count0=1\count1=2\count2=2\count3=0\loop\multiply\count0 by\the\count1\divide\count0 by\the\count2\advance\count1 by4\advance\count2 by1\advance\count3 by1 \ifnum\count3<#1\repeat\the\count0\endgroup} ``` ## Usage ``` \documentclass[12pt,a4paper]{article} \begin{document} \newcommand{\f}[1]{\begingroup\count0=1\count1=2\count2=2\count3=0\loop\multiply\count0 by\the\count1\divide\count0 by\the\count2\advance\count1 by4\advance\count2 by1\advance\count3 by1 \ifnum\count3<#1\repeat\the\count0\endgroup} \newcount \i \i = 0 \loop \f{\the\i} \advance \i by 1 \ifnum \i < 15 \repeat \end{document} ``` [![enter image description here](https://i.stack.imgur.com/Wckg8.png)](https://i.stack.imgur.com/Wckg8.png) [Answer] # Japt, 16 bytes Even Mathematica is shorter. `:-/` ``` U*2ª1 o àU l /°U ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VSoyqjEgbyDgVSBsIC+wVQ==&input=Ng==) ### Ungolfed and explanation ``` U*2ª 1 o àU l /° U U*2||1 o àU l /++U // Implicit: U = input number U*2||1 // Take U*2. If it is zero, take 1. o àU // Generate a range of this length, and calculate all combinations of length U. l /++U // Take the length of the result and divide by (U+1). // Implicit: output result ``` Alternate version, based on the recursive formula: ``` C=_?(4+6/~Z *C$(Z-1):1};$C(U ``` [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 13 Bytes ``` VV2*FVF/V1+F/ V Capture the input as a final global variable. V Push it back. 2* Multiply it by 2 F Factorial. VF Factorial of the input. / Divide the second to top by the first. V1+ 1+input F Factorial. / Divide. ``` This is a function in [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy). How to make it a program that does this, you ask? Concatenate `N`. c: [Try it online!](http://vitsy.tryitonline.net/#code=VlYyKkZWRi9WMStGL04&input=&args=MQ) [Answer] # [Milky Way 1.5.14](https://github.com/zachgates7/Milky-Way), 14 bytes ``` ':2K;*Ny;1+/A! ``` --- ### Explanation ``` ' # read input from the command line : # duplicate the TOS 2 1 # push integer to the stack K # push a Pythonic range(0, TOS) as a list ; ; # swap the TOS and the STOS * # multiply the TOS and STOS N # push a list of the permutations of the TOS (for lists) y # push the length of the TOS + # add the STOS to the TOS / # divide the TOS by the STOS A # push the integer representation of the TOS ! # output the TOS ``` or, alternatively, the *much* more efficient version: --- # [Milky Way 1.5.14](https://github.com/zachgates7/Milky-Way), 22 bytes ``` '1%{;K£1+k1-6;/4+*}A! ``` --- ### Explanation ``` ' # read input from the command line 1 1 1 6 4 # push integer to the stack %{ £ } # for loop ; ; # swap the TOS and the STOS K # push a Pythonic range(0, TOS) as a list + + # add the TOS and STOS k # push the negative absolute value of the TOS - # subtract the STOS from the TOS / # divide the TOS by the STOS * # multiply the TOS and the STOS A # push the integer representation of the TOS ! # output the TOS ``` --- ## Usage ``` python3 milkyway.py <path-to-code> -i <input-integer> ``` [Answer] # Clojure/ClojureScript, 53 bytes ``` (defn c[x](if(= 0 x)1(*(c(dec x))(- 4(/ 6(inc x)))))) ``` Clojure can be pretty frustrating to golf in. It's very pithy while still being very readable, but some of the niftier features are really verbose. `(inc x)` is more idiomatic than `(+ x 1)` and "feels" more concise, but doesn't actually save characters. And writing chains of operations is nicer as `(->> x inc (/ 6) (- 4))`, but it's actually longer than just doing it the ugly way. [Answer] # Ruby, 30 bytes ``` c=->n{n<1?1:c[n-1]*(4+6.0/~n)} ``` Thanks to xsot, saved few bytes by using complement. **Ungolfed:** ``` c = -> n { n < 1 ? 1 : c[n-1]*(4+6.0/~n) } ``` **Usage:** ``` > c=->n{n<1?1:c[n-1]*(4+6.0/~n)} > c[10] => 16796.0 ``` [Answer] # Prolog, 42 bytes Using recursion is almost always the way to go with Prolog. **Code:** ``` 0*1. N*X:-M is N-1,M*Y,X is(4-6/(N+1))*Y. ``` **Example:** ``` 19*X. X = 1767263190.0 ``` Try it online [here](http://swish.swi-prolog.org/p/qICyHIzl.pl) ]
[Question] [ Imagine travelling to a point lying **A** miles away horizontally and **B** miles away vertically from your current position. Or in other words, travelling from `(0, 0)` to point `(a, b)`. How far would you need to end up travelling? This seems like a straightforward question, but the answer depends on who you ask. If you're a crow, and you can travel *as the crow flies*, the distance travelled is just the [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) to `(a, b)`. This is ``` sqrt(a^2 + b^2) ``` But if you're just a boring human, you don't really want to walk that far, so you'll need to take a taxi. Most taxis wont drive in a straight line towards your destination because they generally try to stay on the roads. So the real distance you'll end up travelling is the sum of the vertical distance and the horizontal distance. Or the formula is: ``` abs(a) + abs(b) ``` This is called the [Taxicab Distance](https://en.wikipedia.org/wiki/Taxicab_geometry). This picture nicely demonstrates the difference between the two: [![enter image description here](https://i.stack.imgur.com/PwxcY.jpg)](https://i.stack.imgur.com/PwxcY.jpg) To travel to `(6, 6)`, a crow can just fly on the green line, and this gives a distance of `6 * sqrt(2)` or roughly 8.49. A taxicab can take the red, blue or yellow paths, but they will all take 12. This leads to the real question I'm asking. If a crow and a taxicab both leave from point `(0, 0)`, and travel to point `(a, b)`, how much longer is the taxicab's path? Or, in more math jargon, > > Given a two dimensional vector, determine the difference between the norm2 of the vector, and the norm1 of the vector. > > > You must write the shortest possible program or function to answer this question. You may choose to take 'a' and 'b' as two separate inputs, or as a two item tuple. You can take input and output in any reasonable format. If the difference is a non integer, you must be accurate to at least two decimal places. You can always assume that 'a' and 'b' will be integers, and that they won't both be 0. (Though it is possible that either one of them will be zero) As usual, standard loopholes apply and try to make your program as short as possible, counted in bytes. I will upvote any answer that posts an explanation of how the code works, and demonstrates any cool tricks used to save bytes. Here are some examples for you to test your code on: ``` #input #output 3, 4 2 -3, 4 2 -3, -4 2 6, 6 3.51 42, 0 0 10, 10 5.86 3, 3 1.76 ``` Have fun golfing! :) [Answer] # [Taxi](http://esolangs.org/wiki/Taxi), ~~7394~~ 3773 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:n.[a]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Multiplication Station.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to The Underground.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Go to The Underground:n 2 r 2 r.Switch to plan "b" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:s 2 r 1 l 1 l 2 r.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:e 2 r.Pickup a passenger going to Multiplication Station.Go to The Underground:w 1 r 2 r 1 r 2 l.[b]Go to Multiplication Station:s 1 l 1 r.Go to Tom's Trims:s 1 r 3 r.Switch to plan "c" if no one is waiting.Switch to plan "a".[c]Go to Multiplication Station:s 1 l 3 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 2 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Multiplication Station.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:w 1 r 2 r 1 r 4 l.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r.Go to Cyclone:s 1 l 1 l 1 l 1 r.Pickup a passenger going to Cyclone.[d]Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Cyclone:s 1 r 2 l 2 r.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Cyclone.99 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.Pickup a passenger going to The Underground.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to Trunkers.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.Go to Trunkers:s 1 l.[f]Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Trunkers.Go to Trunkers:s 1 l.Go to Sunny Skies Park:w 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Divide and Conquer.Go to Zoom Zoom:n.Go to Divide and Conquer:w 1 l 2 r 1 r.Pickup a passenger going to Addition Alley.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Divide and Conquer.2 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:w 1 r 2 r 1 r 2 l 3 l.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l.Go to The Underground:s 1 l 1 r 2 l.Switch to plan "g" if no one is waiting.Pickup a passenger going to The Underground.Go to Trunkers:s 2 r 1 l.Switch to plan "f".[g]Go to Rob's Rest:n 3 l 2 l 1 l 2 r 1 r.Pickup a passenger going to What's The Difference.Go to Sunny Skies Park:s 1 l 1 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 3 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r. ``` # [Try it online!](https://tio.run/##vVdNj5swEL33V4xy6alIm@xlc9vuSntqG21SVWrEwcAAVhw7tU1pfn3KZwIEjPOhPRAUY49n3nszHmvyjx4ObwK0gIVQGn6EIfVxnsIDsOyR@dtZUH@T7IDAjiiFPEIJkaA8yletxPazgpWkW2U9r9yvMTLnzpq4xuUxwlfiIQupilHuaxud4bmqHTc687L3meBYGan@zXm1lsF0ZP1zEFBNBYdnxnBvnPotYZruGPVJsWCpi7fzAFRBSjIr2TSi83Hpx5QF8D3ZohRMRHWMfZ@yOKcWfvbHmRbEPo4Q24mxNNEezBCbFhIxe5GT9JMHKCMpEh4MoX4NjCcVNDao3MrBWaZU@3E@Z8cIh4k3ARoCF5Dt3GDADGJMpCcogzdJGau9bw0WdMiWfL7cyjCOsnsRJiXpFV25eJy155ZT@@00Uuk8X1VhZdaDsD@AcHcemThr38aB2Ygyao1fngeqhuKe@W7jzv1Sa0ACN4vvVAptKDAKcYDcth7HitG78DLtvaPSldXTQIPG05kle6hmjceubK4D94qw742UqmvKdSW7X@3ddETLtA2ytEX3BsXW2D49fahEzWcQWp36K5nwDUpzn7NMON/DckNRwYLITR1CZ7hw/1hZK8Ml1c46dK851Mfcf6V/aYBAeAAvgv9J0DLaXh8Hokpvab0u9b408VuIbfEzr/PofGrVz9ro05hD2DjiP6p76gl8erfUmVnIfhD5AZxbXcZoYtrmSwv6hgS7fc6xayko6pav6Ir@r790NPKhav3ONguzWhm5Z@cVr1Bn1pr8FROdt16ZI680DFEi93EIKGXVT5tM9n4rC9b4ddDynoZF82iy1LiOOucXVH48yA@H2afH/w "Taxi – Try It Online") [Engineer Toast](https://codegolf.stackexchange.com/users/38183/engineer-toast), a much more experienced Taxi golfer, decided to take some time (probably a lot less than I did) and golf down my Taxi program by basically rewriting it. You can find my old answer body and links to my old TIOs in the edit history. Engineer Toast's ungolfed square root algorithm: [Try it online!](https://tio.run/##rVbbbhoxEH3nK0ap1CatujRErRTe0kSK@tA0KulLEUVmd2AtjL3xJQtv/ZZ@Wn8knfEutxQCSFkJErye8cyZM2fsxVQ@PnbhW/BF8ODug7AI1hgPZghCg9S83mt0Ife@cO1mE3VSyrEsMJMiMXbU5F/Nr@hzk7m@GfZTMyEbqUf9yl2f3blXn8VgpoyWQvcncTN5bXRvZToOBTifSd1rXBvwBm6N8/BtOJQptks4BUUfy3@TRr1dQCGcQz1CCyNDR7HZXY5Ah6AaSpejnSW1u6frbTf3@by/y1lK8WKyjNIECymtIqQmaI@WcPni3zhIcxQF2ZJVRmfm0tEXoUe/6VU6BhRpDpIshJdGk8WDUAFBOEDCSPFGT2Eq4Tz5vKOqQEr2RqsZkKOMjpR0IMXngAKh7a1fZ6fvT8EZOD9fenZAR7vA2EnUPuk1@K2DUkiuCAgPHS9smkuVwU2YoDXKjBZQbXrX1jVc1ae1Txl@6AztyBJIGcN3FQolU@GxqjPvGvD/xmLGGHQ4rjsb9Jjzo3R5cfohRhu0nkFnLNHBrbBjQkfAaxgA81SoUszcEhkCY@GlJJg95MF6dk8uZSyUMg6hlD6n4F1u6K0WE2TL@H5kiJdDw@kQXfRoTsmaC22sMdhBnXkUz@96mtuiCk/WYwXsgs6174rGDC9BLmPhmZ@OShhLXRgnmRJt2P5wX8Pf339guglr2PUszNcLuO@zMI98P9jD0pwYV3UAFY6Ysw8tIaqP6K2xs8M8KJF6mLkTqSKpH/cSiXWelLs5ciUfZIaRmpdG3wfcm1PbeHAl54lMI4czOsERA6qOyrJIh942kpUHKOJ6snq3Nm9KttG9pmKVUqmoBoEFVE4K6kmhPbBMMK2VMcU85p/GTOJXW0dVRktpTuB4Cu@g05yeNFvMieNm6wR8sJobwtdiI2CIJQxmntKNfc9qzRJ9/Db5eALzE/6Ps55ArTiBduBzUWMMF0rhLNmoHXtp6GZH66sE@15BbYK@9XIz4WwfPdwUw7OA23lujBWf8UJKulaDirbdG1Ny0@fiAeMQ1jj1y4nK96Apy8RlHOR@RWt6KxeMFWlZ3i@qQndo3ND0p42FIsIdDY5ADkEbmu64UoeDp@p3dOira8NKj6zIQmt@a3oagTgi@0Z3wGnVNz92Y9EF5bcKxMLhbs4dfhXb7XPlVphsuCjqRWSPj6ef/gE "Taxi – Try It Online") Ungolfed, with explanations: ``` [ Crow vs. Taxi ] [ GET THE NEGATIVE ABSOLUTE VALUES OF BOTH STDINS ] [Move the stdin values to Tom's Trims b/c:] [1) Stdin doesn't count as a passenger waiting] [2) Checking for no one waiting is shorter that keeping tracker of a count for just 2 iterations OR repeating all the code over again] Go to Post Office:w 1 l 1 r 1 l. Pickup a passenger going to Tom's Trims. Pickup a passenger going to Tom's Trims. Go to Tom's Trims:n. [a] [Clone the first waiting value] [If we've already picked up both, move to the next process] [Switch to plan "c" if no one is waiting.] Pickup a passenger going to The Babelfishery. Go to The Babelfishery:s 1 l 1 r. Pickup a passenger going to Cyclone. Go to Cyclone:n 1 l 1 l 2 r. Pickup a passenger going to Addition Alley. Pickup a passenger going to Multiplication Station. [Add one to the value] 1 is waiting at Starchild Numerology. Go to Starchild Numerology:s 2 l 2 r. Pickup a passenger going to Cyclone. Go to Cyclone:w 1 r 4 l. Pickup a passenger going to Addition Alley. Go to Addition Alley:n 2 r 1 r. Pickup a passenger going to The Underground. [Pick up a clone of that one to feed into Multiplication Station] Go to Cyclone:n 1 l 1 l. Pickup a passenger going to Multiplication Station. [Subtract one and see if that's more than zero] Go to The Underground:n 2 r 2 r. Switch to plan "b" if no one is waiting. [It was more than zero so we make it negative] [First, though, get rid of the pesky result from The Underground] Pickup a passenger going to Charboil Grill. Go to Charboil Grill:s 2 r 1 l 1 l 2 r. -1 is waiting at Starchild Numerology. Go to Starchild Numerology:e 2 r. Pickup a passenger going to Multiplication Station. Go to The Underground:w 1 r 2 r 1 r 2 l. [b] [Make sure it's a negative value and leave it at Multiplication Station] [Either it was already negative OR we now have -1 as a passenger] Go to Multiplication Station:s 1 l 1 r. [Get the next stdin unless we've already gotten them both] Go to Tom's Trims:s 1 r 3 r. Switch to plan "c" if no one is waiting. Switch to plan "a". [ ADD THE TWO NEGATIVES AND INVERT TO GET THE TAXI DISTANCE] [c] [Pickup the two negative absolute values and clone them] Go to Multiplication Station:s 1 l 3 l. Pickup a passenger going to Cyclone. Pickup a passenger going to Cyclone. Go to Cyclone:s 1 r 2 l 2 r. Pickup a passenger going to Addition Alley. Pickup a passenger going to Cyclone. Pickup a passenger going to Addition Alley. [Add the two clones values to get the negative Taxi distance] Go to Addition Alley:n 2 r 1 r. Pickup a passenger going to Multiplication Station. [Invert to get the Taxi distance and store it at Rob's Rest] -1 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 l 1 l 1 l 3 l. Pickup a passenger going to Multiplication Station. Go to Multiplication Station:w 1 r 2 r 1 r 4 l. Pickup a passenger going to Rob's Rest. Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r. [ FIND THE CROW DISTANCE ] [Uses the Babylonian method: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method ] [Square and Sum the cloned values] Go to Cyclone:s 1 l 1 l 1 l 1 r. Pickup a passenger going to Cyclone. [d] Pickup a passenger going to Multiplication Station. Pickup a passenger going to Multiplication Station. Go to Multiplication Station:s 1 l 2 r 4 l. Pickup a passenger going to Addition Alley. Go to Cyclone:s 1 r 2 l 2 r. Switch to plan "e" if no one is waiting. Switch to plan "d". [e] Go to Addition Alley:n 2 r 1 r. Pickup a passenger going to Cyclone. [Pickup our cycle counter] [It's cheaper to do this than to check each iteration's value as equal to the last] [Taxi can only handle integers up to 2^31-1 so 99 iterations is sufficient.] 99 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 l 1 l 1 l 3 l. Pickup a passenger going to The Underground. [Duplicate stdin to be stored as S at Trunkers and as x0 at Sunny Skies Park] [a & b are always integers so Trunkers won't hurt S and it's close with a short name so it's good for golfing] Go to Cyclone:e 1 l 2 r. Pickup a passenger going to Trunkers. Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park:n 1 r. Go to Trunkers:s 1 l. [ This is our starting position for square root: ] [ • x at Sunny Skies Park ] [ • S at Trunkers ] [ • Taxi at Trunkers ] [ • The iterator as a passenger going to The Underground ] [f] [Duplicate S so we don't lose it] Pickup a passenger going to Cyclone. Go to Cyclone:w 2 r. Pickup a passenger going to Divide and Conquer. Pickup a passenger going to Trunkers. Go to Trunkers:s 1 l. [Diplicate x for division and addition] Go to Sunny Skies Park:w 1 r. Pickup a passenger going to Cyclone. Go to Cyclone:n 1 l. Pickup a passenger going to Divide and Conquer. [Gas will be super important in this loop] Go to Zoom Zoom:n. [Perform (x + S/x)/2] [(/2) turns out to be a few bytes shorter than (*.5), mostly due to place names] Go to Divide and Conquer:w 1 l 2 r 1 r. Pickup a passenger going to Addition Alley. Go to Cyclone:e 1 l 1 l 2 l. Pickup a passenger going to Addition Alley. Go to Addition Alley:n 2 r 1 r. Pickup a passenger going to Divide and Conquer. 2 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 l 1 l 3 l 2 r. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer:w 1 r 2 r 1 r 2 l 3 l. Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l. [Now we have the next iteration of x] [Check the iterator] Go to The Underground:s 1 l 1 r 2 l. Switch to plan "g" if no one is waiting. Pickup a passenger going to The Underground. [Reset the loop] Go to Trunkers:s 2 r 1 l. Switch to plan "f". [ ADD THE NEGATIVE SUM TO THE SQUARE ROOT TO GET THE NEGATIVE DIFFERENCE ] [g] Go to Rob's Rest:n 3 l 2 l 1 l 2 r 1 r. Pickup a passenger going to What's The Difference. Go to Sunny Skies Park:s 1 l 1 l. Pickup a passenger going to What's The Difference. Go to What's The Difference:n 1 r 1 l. Pickup a passenger going to The Babelfishery. Go to The Babelfishery:e 3 r. Pickup a passenger going to Post Office. Go to Post Office:n 1 l 1 r. ``` [Answer] # Javascript (ES6), 36 bytes -1 byte thanks to @dtkaias ``` (x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y) ``` **Example code snippet:** ``` f= (x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y) for(i=0;i<7;i++) a=[3,-3,-3,6,42,10,3][i], b=[4,4,-4,6,0,10,3][i], console.log(`f(${a},${b}) = ${f(a,b)}`) ``` [Answer] # Julia, 20 bytes ``` x->norm(x,1)-norm(x) ``` Takes `a` and `b` as a list. Julia's `norm` second argument defaults to 2 - hence this would be equivalent to `norm(x, 1) - norm(x, 2)`. [Answer] # Java 8, 47 bytes Golfed: ``` (a,b)->(a<0?-a:a)+(b<0?-b:b)-Math.sqrt(a*a+b*b) ``` This is about as basic as it gets: subtract the two calculated values to find the difference. This uses ternary logic instead of `Math.abs()` to save one byte each occurrence. Unfortunately, the parentheses are required due to operator precedence. The output is whatever Java's `double` can hold, which is accurate to more than two decimal places and satisfies the accuracy requirement of the question. Ungolfed: ``` public class TheCrowVsTheTaxicab { public static void main(String[] args) { int[][] inputs = new int[][] { { 3, 4 }, { -3, 4 }, { -3, -4 }, { 6, 6, }, { 42, 0 }, { 10, 10 }, { 3, 3 } }; double[] outputs = new double[] { 2, 2, 2, 3.51, 0, 5.85, 1.76 }; for (int i = 0; i < inputs.length; ++i) { double actual = f((a, b) -> (a < 0 ? -a : a) + (b < 0 ? -b : b) - Math.sqrt(a * a + b * b), inputs[i][0], inputs[i][1]); System.out.println("Input: " + inputs[i][0] + ", " + inputs[i][1]); System.out.println("Expected: " + outputs[i]); System.out.println("Actual: " + actual); System.out.println(); } } private static double f(java.util.function.BiFunction<Integer, Integer, Double> f, int a, int b) { return f.apply(a, b); } } ``` Output: ``` Input: 3, 4 Expected: 2.0 Actual: 2.0 Input: -3, 4 Expected: 2.0 Actual: 2.0 Input: -3, -4 Expected: 2.0 Actual: 2.0 Input: 6, 6 Expected: 3.51 Actual: 3.5147186257614305 Input: 42, 0 Expected: 0.0 Actual: 0.0 Input: 10, 10 Expected: 5.85 Actual: 5.857864376269049 Input: 3, 3 Expected: 1.76 Actual: 1.7573593128807152 ``` [Answer] # [R](https://www.r-project.org/), 30 bytes ``` function(v)norm(v)-norm(v,'f') ``` Takes `v` as a 1-column matrix. `norm` computes a particular norm of a matrix, with the default being the L1 norm (taxicab), and `f` the L2 norm (`'f'` for Frobenius/Euclidean). [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTDMvvygXSOlCaB31NHXN/2kauYklRZkVGskahgY6hgaaOkaamv8B "R – Try It Online") [Answer] # Mathematica, 32 bytes ``` N[Tr@Abs[a={##1}]-Sqrt@Tr[a^2]]& ``` or # Mathematica, 31 bytes ``` N[Abs@#+Abs@#2-Sqrt[#^2+#2^2]]& ``` or @Not a tree's suggestion # Mathematica, 26 bytes ``` N[Tr@Abs@{##}-Abs[#+I#2]]& ``` or @alephalpha's suggestion # Mathematica, 19 bytes ``` N[#~Norm~1-Norm@#]& ``` [Answer] # Dyalog APL, 13 bytes ``` +/∘|-.5*⍨+.×⍨ ``` [Try it online!](http://tryapl.org/?a=%28+/%u2218%7C-.5*%u2368+.%D7%u2368%29%20%AF3%20%AF4&run) Explanation (input X): ``` +/∘| - Sum of the element-wise absolute value of X - - Minus .5*⍨+.×⍨ - Euclidean distance = sqrt(X . X) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~40~~ ~~38~~ 36 bytes *-2 bytes thanks to vaultah. -2 bytes thanks to sTertooy.* Fun fact, 11 bytes of this code were just copied from the question and golfed. ``` lambda a,b:abs(a)+abs(b)-abs(a+b*1j) ``` [Try it online!](https://tio.run/##Xc1BDoMgEAXQPaf4S9EhETUuTDyJZQFpSWlaNMKmp6cWowtnM//lZzLLNz5n3yQ73tJbf8xdQ5MZtAmF5tV/GS6yKlPKF0/xEWLAiIlhm6kldIr2LK4Qp3pCf@SuIdQHZE2Qp7abVjHFmJ1XODiP/G7I7bI6H2GL0vH0Aw "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ 9 bytes *-2 bytes thanks to @ETHproductions* ``` Nxa -MhUV ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=TnhhIC1NaFVW&input=NiA2) ## Explained ``` Nxa -MhUV // implicit: U and V are input integers, N = [U,V] N a // get absolute value of both inputs x // sum those values -MhUV // subtract hypot(U, V) -> sqrt(U^2 + V^2) ``` [Answer] # Scheme - 58 bytes. ``` (define (f a b) (-(+(abs a)(abs b))(sqrt(* a a)(* b b)))) ``` [Answer] # Pyth, 8 bytes ``` -s.aMQ.a ``` [Try it online.](https://pyth.herokuapp.com/?code=-s.aMQ.a&input=6%2C+6&test_suite_input=3%2C+4%0A-3%2C+4%0A-3%2C+-4%0A6%2C+6%0A42%2C+0%0A10%2C+10%0A3%2C+3&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=-s.aMQ.a&input=6%2C+6&test_suite=1&test_suite_input=3%2C+4%0A-3%2C+4%0A-3%2C+-4%0A6%2C+6%0A42%2C+0%0A10%2C+10%0A3%2C+3&debug=0) ### Explanation ``` -s.aMQ.aQ Q (input) appended implicitly .aMQ absolute values of input vector s sum - subtract .aQ norm2 of input vector ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes Takes argument in the form `xJy`, e.g. `3J4` ``` ||-2+/∘|9 11○⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@VR24SaGl0jbf1HHTNqLBUMDR9N737UtQgoc2iFcZaJwqH1xl4Q8tB6EwUzLzMFEyMvAwVDAy9DAwVjL2MA "APL (Dyalog Unicode) – Try It Online") `|` the magnitude of[Doc](http://help.dyalog.com/16.0/Content/Language/Primitive%20Functions/Magnitude.htm) `|` the argument's magnitude `-` minus `2+/` the pair-wise sum `∘` of `|` the magnitudes of `9 11.○⊢` the the argument's real and the imaginary parts.[Doc](http://help.dyalog.com/16.0/Content/Language/Primitive%20Functions/Circular.htm) Special trick for golfing was the use of the pairwise reduction (`2+/`) to supply `+/` with a no-op left argument, thereby avoiding parentheses: `||-(+/∘|9 11○⊢)` [Answer] # J, 13 bytes ``` +/@:|-+/&.:*: ``` This is a function that takes the coordinates as an array, e.g.: ``` (+/@:|-+/&.:*:) _3 4 2 ``` Explanation: ``` +/ sum @: of | absolutes - minus +/ sum &.: under *: square ``` [Answer] # [J](http://jsoftware.com/), ~~9~~ 8 bytes -1 thanks to my colleague Marshall. ``` +&|-|@j. ``` [Try it online!](https://tio.run/##y/r/P83WSlutRrfGIUvv/39jhXgwMlMwMVIwNFAwVkhTMAHCeBOgkAFYBAA "J – Try It Online") Takes **A** as left argument and **B** as right argument. `+` the sum `&` of `|` the magnitudes `-` minus `|` the magnitude `@` of `j.` **A** + **B** *i* Golfing trick: combine the values to a single complex number because the diagonal is easy to get like that, while also keeping them separate because the sum is easy to get like that. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ÄO¹nOt- ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cIv/oZ15/iW6//9Hm@mYxQIA "05AB1E – Try It Online") **Explanation** ``` Ä # absolute value of inputs O # sum ¹ # push input again n # square O # sum t # sqrt - # subtract ``` [Answer] # TI-Basic (TI-84 Plus CE), 10 bytes ``` sum(abs(Ans))-√(sum(Ans2 ``` Program that input as a list of two integers in `Ans`, e.g. call with `{3,4}:prgmCROW` (replacing `3,4` with the input and `CROW` with the name of the program). Explanation: ``` sum(abs(Ans))-√(sum(Ans2 Ans # The input list of two integers abs( ) # Absolute value of each item in the list sum( ) # Sum of the list Ans # The input list of two integers 2 # Square of each item in the list sum( # Sum of the list √( # Square root of the sum - # Difference of the two values ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~8~~ 7 bytes ``` |sG2&|- ``` [**Try it online!**](https://tio.run/##y00syfn/v6bY3UitRvf//2hDAwVDg1gA "MATL – Try It Online") ### Explanation ``` | % Implicit input: vector of two numbers. Absolute value, element-wise s % Sum of vector G % Push input again 2 % Push 2 &| % 2-norm of input - % Subtract. Implicit display ``` [Answer] # Common Lisp, 57 bytes ``` (defun g(a b)(+(abs a)(abs b)(-(sqrt(+(* a a)(* b b)))))) ``` [Try it online!](https://tio.run/##HchLCsAgEAPQq2QZLYX2SDP9iCBi1Z7fTg2BkHek2MoYPK/7zQgUqONC0QZxc@yvbE/txh7ys4cazwyWGnMHA/bNavIB) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ²S½ạAS$ ``` [Try it online!](https://tio.run/##y0rNyan8///QpuBDex/uWugYrPL///9oMx0Fs1gA "Jelly – Try It Online") Format is list of two numbers. [Answer] # GNU APL 1.2, 24 bytes ``` ∇f P (+/|P)-(+/P*2)*.5 ∇ ``` `∇f P` declares a function `f` that takes a vector `P` containing the distances as an argument (e.g. `[3, 4]`) APL operates on vectors, so `+/|P` applies the `|` operator (`abs` function) to each element in the vector and then evaluates `+` on each element (so add all the elements). This gives the taxi distance. `P*2` yields a vector that is the same as `P` but with each element squared. `+/P*2` to add those together and then (with parentheses for precedence because APL is right-to-left) `*.5` to get the square root. This gives the crow distance. Add an extra pair of parentheses for the taxi distance for precedence and compute the difference. `∇` to end the function. [Answer] # [Add++](https://github.com/SatansSon/AddPlusPlus), ~~59~~ 57 bytes ``` D,f,@@,|@|+ D,g,@@,d*@d*+ _ $f>G>G V $g>?>? S -G $f>x>0 O ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HwUGnxqFGm8tFJx3ETtFySNHS5ornUkmzc7dz5wrjUkm3s7ez5wrm0nUHCVbYGXD5////3@y/GQA "Add++ – Try It Online") This took me ages to solve. It doesn't round the final answer as that isn't possible in Add++. This is how the program works with the inputs `-3` and `-4` (`ACC` is the accumulator value) ``` D, Define a function f, called f @@, that takes 2 arguments (e.g. -3, -4) | absolute value; STACK = [-3, 4] @ reverse stack; STACK = [4, -3] | absolute value; STACK = [4, 3] + sum; STACK = [7] implicitly return the top of the stack D, Define a function g, called g @@, that takes 2 arguments (e.g. -3, -4) d duplicate; STACK = [-3, -4, -4] * multiply; STACK = [-3, 16] @ reverse; STACK = [16, -3] d duplicate; STACK = [16, -3, -3] * multiply; STACK = [16, 9] + sum; STACK = [25] implicitly return the top of the stack _ store the inputs in the second stack; ACC = 0; STACK = [-3, -4] $f>G>G apply f with -3 and -4 as arguments; ACC = 7; STACK = [] V store ACC in the stack; ACC = 7; STACK = [7] $g>?>? apply g with -3 and -4 as arguments; ACC = 25; STACK = [7] S square root the ACC; ACC = 5; STACK = [7] -G subtract the stack value from the ACC; ACC = -2; STACK = [] $f>x>0 apply f with ACC and 0 as arguments; ACC = 2; STACK = [] O output ACC as a number ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` a.aQsa0 ``` [Try it here](https://pyth.herokuapp.com/?code=a.aQsa0&input=%5B6%2C+6%5D&debug=0) --- **[Pyth](https://github.com/isaacg1/pyth), ~~25~~ 23 bytes** THis is the initial solution, my first not-so-trivial Pyth solution and you can see just how bad I used to be at golfing in Pyth :) ``` K.aswJ.asw-+KJ^+^K2^J2 .5 ``` [Try it online!](https://tio.run/##K6gsyfj/31svsbjcC0Toant7xWnHeRvFeRkp6Jn@/69rzGUCAA "Pyth – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 15 bytes ``` ABa+ABb-RT$+g*g ``` Takes input from command-line arguments. [Try it online!](https://tio.run/##K8gs@P/f0SlR29EpSTcoREU7XSv9////xv91TQA "Pip – Try It Online") ### Explanation In pseudocode, this is `abs(a) + abs(b) - sqrt(fold+(g*g))`. `a` and `b` are the first two cmdline args, and `g` is the list of cmdline args (i.e. argv). The `*` operator vectorizes, like many Pip operators, so `$+g*g` is the same thing as `a*a + b*b`. The rest is pretty straightforward. Unfortunately, I can't save any bytes with `$+ABg`, because the precedence of operators with fold doesn't work like it should yet. `$+` ought to be slightly higher precedence than binary `-`, but at the moment it parses as `$+(ABg-RT$+g*g)`, giving the wrong answer. Doing `($+ABg)-RT$+g*g` doesn't save any bytes over the less-obfuscated version above. [Answer] # PHP>=7.1, 54 bytes ``` [,$x,$y]=$argv;echo abs($x)+abs($y)-sqrt($x**2+$y**2); ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/19a9481c72fc8df777304388d703b02945e9de45) # [PHP](https://php.net/), 55 bytes ``` <?=abs($x=$argv[1])+abs($y=$argv[2])-sqrt($x**2+$y**2); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJReZhutpKuko2QMxrHWXPZ2QFnbxKRiDZUKW7CKaMNYTW2wQCVUwChWU7e4sKgEqERLy0hbpRJIalr//w8A "PHP – Try It Online") # [PHP](https://php.net/), 60 bytes with an function instead of a full program ``` function f($x,$y){return abs($x)+abs($y)-sqrt($x**2+$y**2);} ``` [Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUKnRUKjWri1JLSovyFBKTioEimtpgulJTt7iwqAQooKVlpK1SCSQ1rWv/pyZn5AM1GusYa1r/BwA "PHP – Try It Online") [Answer] # Excel VBA, 34 Bytes Anonymous VBE immediate window function that takes input from range `[A1:B1]` and outputs the difference between the Euclidean and Taxicab distances to the VBE immediate window. ``` ?[ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2)] ``` [Answer] # [,,,](https://github.com/totallyhuman/commata/), 18 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page) Essentially a port of my Python answer. ``` a:↔a:0•2*⇆2*+√↔+↔- ``` [Answer] ## Forth (gforth), 68 bytes ``` abs swap abs 2dup + s>d d>f dup * swap dup * + s>d d>f fsqrt f- f.s ``` [Try it online](https://tio.run/##S8svKsnQTU8DUf/NFMz@JyYVKxSXJxYogBhGKaUFCtoKxXYpCil2aQognhZEFsJESKUVFxaVKCik6Sqk6RX//w8A) ! The coordinates are two numbers on the stack. PS my first code golf... don't hit too hard ;-)! [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes Creates a complex number to calculate the distance with. ``` ->x,y{x.abs+y.abs-(x+y*1i).abs} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euQqeyukIvMalYuxJE6mpUaFdqGWZqgji1/wsU0qK1UssSczTSU0uKNWP/Rxsa6BgaxAIA "Ruby – Try It Online") [Answer] # Ruby (2.0.0 - 2.3.0), 57bytes ``` x,y=$*.map(&:to_i);puts x.abs+y.abs-Math.sqrt(x**2+y**2) ``` This assumes taking input from ARGV e.g. ``` ruby -e 'x,y=$*.map(&:to_i);puts x.abs+y.abs-Math.sqrt(x**2+y**2)' -- -3 4 ``` This feels like a cheat since Ruby comes with a math lib that has abs and sqrt functions (unlike the guy who wrote his own abs and sqrt functions, though I didn't see anything specifically forbidding the use of such functions). The first trick is using `.map` instead of `.each` which saves a byte, then using the `&:symbol` notation to pass map a proc we execute `to_i` on each item in the array, and use multiple assignment to assign values to x and y. A longer version would be: ``` (x, y) = ARGV.map{ |string| string.to_i } ``` (since map returns an array, multiple assignment is probably the way to do it, this does throw away any additional parameters, but we're assuming only two inputs anyway) Then I just removed all of the spaces in the equation. Here's a longer version, 84 bytes ``` $*.map!(&:to_i);puts$*.inject(0){|x,y|x+y.abs}-Math.sqrt($*.inject(0){|x,y|x+y**2}) ``` The goal here was to not repeat myself, e.g. having to write `x` or `abs` twice and my squaring twice `x**2 + y**2` It did not work. But what's interesting is that puts doesn't need a space, I guess the lexer is smart enough to see the special char and know it's a special var. `inject` and `reduce` are synonyms, inject has a signature of ``` inject(initial) {| memo, obj | block } ``` In our case we need to set the initial to 0, then we have our accumulator (i.e.: memo = 0) and the object from each iteration. The down side to this method is that it will take more than two inputs and will either sum or square, add, then sqrt all the values in the array. I *think*--though I don't have a Ruby 2.4.0 to test with--that this will work as well, which comes in at 72 bytes: ``` $*.map!(&:to_i);puts$*.sub{|x,y|x+y.abs}-Math.sqrt($*.sum{|x,y|x+y**2}) ``` Sum defaults to 0 and as far as I can tell, works the same as inject/reduce. [Answer] # Google Sheets, 31 Bytes Worksheet function that takes input from range `[A1:B1]` and outputs the difference between the Euclidean and Taxicab distances ``` =ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2 ``` # Excel, 32 bytes Same as above but formatted for MS Excel ``` =ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2) ``` ]
[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/31506/edit). Closed 2 years ago. [Improve this question](/posts/31506/edit) The goal is to write a simple "99 Bottles of Beer" program .. that is valid in *at least* 2 distinct languages (e.g. not Python 2 and Python 3). It must be a complete file that will run or compile. Interesting answers should be up-voted, but compactness also counts. (Of course, language diversity is the main goal.) EDIT: I would say that to have normal C code that does the same thing with C++ and Objective-C counts as derivative. The code should do clever stuff so that lines have different meanings with different languages. [Answer] ## C, Perl, PHP, Python, Ruby **Update**: I've put together a jsfiddle that helps visualize the path through the code for each of the five languages: <http://jsfiddle.net/wK6bD/4/embedded/result/> An alternative version, that removes all comments, and compresses all insignificant strings, regex and replacement patterns: <http://jsfiddle.net/wK6bD/5/embedded/result/> And I saved a byte while I was at it. Turns out C had an unnecessary semi-colon ;) ``` #/*<?php ob_clean();" s='''*/include<stdio.h> main($y){char*$s,$t[3],$u[3]/*';''' def printf(a,*b):import sys;sys.stdout.write(a%b) for y in range(99,-1,-1): ''' 99.downto(0){|y|$y=y;"/*=;#*/; for($y=100;$y--;){ #/*" $u=(($t=$y)+99)%100;'*/ sprintf($t,"%d",$y);sprintf($u,"%d",($y+99)%100); #//';#''' printf("%s bottle%s of beer on the wall, %s bottle%s of beer.\n%s", #/* -- THIS LINE ENDS WITH CR -- y//1or'No more','s'[:y!=1],y or'no more','''s*/ +$y>0?$t:"No more",$s=$y!=1?"s":"",$y>0?$t:"no more",$s,$y>0? #//'''[:y!=1],y and''' "Take one down and pass it around": #//'''[6:38]or "Go to the store and buy some more"); printf(", %s bottle%s of beer on the wall.\n\n", #/* -- THIS LINE ENDS WITH CR -- y//1-1and~-y%100or'no more','''s*/ +$y!=1?$u:"no more",$y!=2?"s":"");} #/*?><?php " %w;q(*/ }//";#'''[:y!=2]) ``` **Please Note**: This file needs to be saved with *mixed* line endings. All lines should be terminated with `LF` (char *10*, a.k.a. unix-style), except for the two lines marked `-- THIS LINE ENDS WITH CR --`, which should be terminated with `CR` (char *13*, a.k.a. mac-style). I recommend using [notepad++](http://notepad-plus-plus.org/), or other text editor which allows you to manually edit line endings. For PHP, it is assumed that `output_buffering` is enabled. According to [the documentation](http://www.php.net/manual/en/outcontrol.configuration.php), this is hardcoded to be `Off` when using the CLI, regardless of `ini` settings, so it needs to be explicitly (re)enabled: ``` $ php -d output_buffering=4096 bottles.pl.php.py.rb.c ``` This enables a 4kb buffer, which is the 'recommended' value. If you're using one of the supplied `ini`s this will already be set, so it should run as-is from any web server. The total file size is *823* bytes (not counting the comments about the line endings), an average of *164.6* bytes per language. **Versions Tested** **C** - gcc 4.8.1, cl 15.00 **Perl** - 5.16.2 **PHP** - 5.4.16 **Python** - 2.7.6, 3.3.4 **Ruby** - 1.8.7, 1.9.3 Output is identical for all five languages (see below). --- ## Perl, PHP ``` <?php '>#' ;for($i='no more';100>($a="$i bottle".(2^($i+=1)?'s':'').' of beer');$o=" Take one down and pass it around, $b. ".ucfirst($f="$b, $a.$o")){$b="$a on the wall";}print"$f Go to the store and buy some more, $b."; ``` I like this one because of how short it is, so I'm leaving it. It also demonstrates how much of a Perl-wanna-be PHP is ;) Sample Usage: ``` $ perl bottles 99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. ... 2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall. ``` [Answer] # C + Ruby ``` #define do { #define then { #define end } #define def int #define nil { #define print(a,b) printf("%d%s", a, b) def bottle(i) nil print(i, (i==1)?" bottle":" bottles"); end i=0; def main() nil i = 99; while(i>=1) do bottle(i); puts(" of beer on the wall, "); bottle(i); puts(" of beer.\nTake one down and pass it around,"); if(i==1) then break; end bottle(i-1); puts(" of beer on the wall."); puts(""); i-=1; end puts("no more bottles of beer on the wall."); puts(""); puts("No more bottles of beer on the wall,"); puts("no more bottles of beer."); puts("Go to the store and buy some more,"); puts("99 bottles of beer on the wall."); end #if 0 main #endif ``` They're actually pretty similar once you normalize the syntax! :P [Answer] ## JavaScript (SpiderMonkey/NodeJS), Perl, PHP, Ruby **EDIT:** Added and `Ruby` **EDIT 2:** * Prints a title; * Consistent output in all languages; * No warnings. The Code: ``` //#<?php ; $i = 99; $php = ![]; $o = 'of beer'; $ruby = 0x0 != ''; $t = $php ? '' : '//#'; $js = !$ruby && 1 + '0' == '10'; $s = 'Go to the store and buy some more, 99 bottles of beer on the wall.'; $c = 'print($t ." 99 BOTTLES OF BEER #\\\\\\\\\\n"); while($i>=0) { $j = $i; $k = ($i-1); $b = $i!=1 ? " bottles " : " bottle "; print("\\n" .($i > 0 ? $j : "No more") .$b .$o ." on the wall, " .($i > 0 ? $j : "no more") .$b .$o .".\\n" .($i > 0 ? "Take one down and pass it around, " .($i > 1 ? $k : "no more") ." bottle" .($i != 2 ? "s " : " ") .$o ." on the wall." : $s) ."\\n"); $i-=1; }'; $c = $js ? $c.replace('."\\n"','').replace(RegExp(' [.]','g'),'+').replace(RegExp('print','g'), typeof(console) != 'undefined' ? 'console.log' : 'print') : $c; $c = $ruby ? $c.gsub('{',"do\n").gsub('}',"\nend").gsub(' .',' << ').gsub('$i;','$i.to_s;').gsub('1)','1).to_s') : $c; eval($c); ``` The output: ``` D:\>node polyglot //# 99 BOTTLES OF BEER #\\ 99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. * * * 2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall. ``` [Answer] # C++ and PHP I thought I'd give it a go. EDIT: Compacted it a bit. ``` //99 BOTTLES OF BEER\\<br/><br/><?PHP function cat($a,$b){return $a.$b; }/* #include<iostream> #include<string> #define echo(a) std::cout << a #define cat(a,b) a<<b int $bottles; std::string $endline = "\n"; std::string $bottlesname; int isset(std::string){ echo("//99 BOTTLES OF BEER\\\\\n\n"); return true; } int main() /**/ { if(!isset($endline)) $endline = "<br/>"; $bottles = 99; $bottlesname = " bottles"; while( $bottles > 0 ){ echo(cat(cat($bottles, $bottlesname ), " of beer on the wall, ")); echo(cat(cat(cat(cat($bottles, $bottlesname ), " of beer."), $endline), "Take one down and pass it around, ")); $bottlesname = --$bottles==1?" bottle":" bottles"; if( $bottles == 0 ) echo("no more"); else echo($bottles); echo(cat(cat(cat($bottlesname," of beer on the wall."),$endline),$endline)); } echo(cat("No more bottles of beer on the wall, no more bottles of beer.",$endline)); echo(cat(cat("Go to the store and buy some more, 99 bottles of beer on the wall.",$endline),$endline));; } ``` This will compile fine as C++ and it will spit out some nice HTML if run through PHP. Either way, the output is: ``` //99 BOTTLES OF BEER\\ 99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down, pass it around, 97 bottles of beer on the wall. ... 3 bottles of beer on the wall, 3 bottles of beer. Take one down, pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall, 2 bottles of beer. Take one down, pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall. ``` [Answer] # Haskell, PHP Combining a functional and an imperative language! ``` {-0;} function cast($x){ return $x; } function bottle($n){ /*-} import Prelude hiding ((.)){-*///-};(*/) = ($){- /*-} (.) = (++) cast f = show $ f id f :: Int -> [String] f n = id */ return (cast($n) . " bottles of beer on the wall, " . cast($n) . " bottles of beer.\nTake one down and pass it around, " . cast($n-1) . " bottles of beer on the wall.\n\n"); {-0;}};echo"<pre>";for($x=99;$x>1;$x-=1)echo bottle($x);echo/*-} main = (\x->putStr$(concat$[99,98..2]>>=f)++x)*/"1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n\n"; ``` In Haskell, I defined the function `*/` that made working with PHP comments a lot easier! [Answer] # Brainfuck, English Source for BF: <http://www.99-bottles-of-beer.net/language-brainfuck-1718.html> ``` ++>+>++>>+>>>++++++++++[->+>+>++++++++++<<<]>>>>++++++++++[->+++++>++++++++++>++ +++++++++>++++++++>++++++++>+++>++++>+<<<<<<<<]+>--+>+++>++++++>--+>+++++>+++>++ +++>+>+>+>+>++>+>+>++[-<]<<<<<<<[->>[>>>>>>>>[<<<<<<<[->[-]>>>>>>>>>>>.<----.>>> .<<<--.++.+++.+<-.+<<+<<<<<<<<]+>[-<[-]>>>>>[>>>+<<<<+<+<+>>>-]<<<[->>>+<<<]>[>> >>>>+<<<<<<-]>>>>>[[-]>.<]<<<<[>>>>>-<<<<<-]>>[<<+<+<+>>>>-]<<<<[->>>>+<<<<]>[>> >>>>+<<<<<<-]>>>>>>.<<<<<[>>>>>-<<<<<-]>>>[-<<<+<+>>>>]<<<<[->>>>+<<<<]>-[[-]>>> >+<<<<]<<<]+>>>>>>>>>>>>>.<<<<----.>----.+++++..-<++++++++++.-------.<<[[-]>>>.< <<]>>>>>>.<<<----.<+.>>>>.<<<<----.+++..+>+++.+[>]+>+>[->+<<-<-<<<.<<<----.-.>>> .<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..------>---->------------------ -------------->>>++.-->..>>>]>>>[->[-]<<<<<<<[<]<[-]>>[>]>>>>>]+>[-<[-]<<<<[->>[ ->+<<<<-<<<.<<<----.-.>>>.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..----- ->---->++++++++++++++++++++++++++++++++>>>.<.>>>>>>]<<]<[->>>>[-<<+<<<<++.-->.[< ]<<<<<<<<[->[-]<]+>[-<[-]>>>>>>>>>>>>>.<<<-----.++++++++++.------.>>>>.<<<----.- .<.>>>>.<<<<-.>+.++++++++.---------.>>>.<<<<---.>.<+++.>>>>.<<<++.<---.>+++..>>> .<<<<++++++++.>+.>>>.<<<<--------.>--.---.++++++.-------.<+++.++>+++++>>>>.<.[<] <<<<<<<]+>>>>>>-<<<+>>[<<[-]<+<+>>>>-]<<<<[>-<[-]]>[->>>+<<<]>[->->+++++++++<<]> >>>>[>]>>>>]<<<<]>>>>>>]+<<<<<<<[<]<]+<+<<<<<<+<-]>>>>>>>>>>[>]>>>>>[->[-]<]+>[- <[-]<<<<<<<<<-------------.<<----.>>>.<<<+++++.-----.>>>.<<<+++++.<++.---.>>>>.< <<-.+.-----.+++.<.>>>>.<<<<----.>----.<+++.>>>>.<<<<--.>+++++++.++++.>>>.<<<---- --.----.--.<+++.>>>>.<<<.++.+++.+<.+>>>>>.<.>>>>>>>>>]+<[-]+<[-]<[-]<[-]+<<<[<]< [-]<[-]<[-]<[-]++++++++++[->+>+>++++++++++<<<]>->->-<<<<<<[-]+<[-]<+<<] [99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. 97 bottles of beer on the wall, 97 bottles of beer. Take one down and pass it around, 96 bottles of beer on the wall. 96 bottles of beer on the wall, 96 bottles of beer. Take one down and pass it around, 95 bottles of beer on the wall. 95 bottles of beer on the wall, 95 bottles of beer. Take one down and pass it around, 94 bottles of beer on the wall. 94 bottles of beer on the wall, 94 bottles of beer. Take one down and pass it around, 93 bottles of beer on the wall. 93 bottles of beer on the wall, 93 bottles of beer. Take one down and pass it around, 92 bottles of beer on the wall. 92 bottles of beer on the wall, 92 bottles of beer. Take one down and pass it around, 91 bottles of beer on the wall. 91 bottles of beer on the wall, 91 bottles of beer. Take one down and pass it around, 90 bottles of beer on the wall. 90 bottles of beer on the wall, 90 bottles of beer. Take one down and pass it around, 89 bottles of beer on the wall. 89 bottles of beer on the wall, 89 bottles of beer. Take one down and pass it around, 88 bottles of beer on the wall. 88 bottles of beer on the wall, 88 bottles of beer. Take one down and pass it around, 87 bottles of beer on the wall. 87 bottles of beer on the wall, 87 bottles of beer. Take one down and pass it around, 86 bottles of beer on the wall. 86 bottles of beer on the wall, 86 bottles of beer. Take one down and pass it around, 85 bottles of beer on the wall. 85 bottles of beer on the wall, 85 bottles of beer. Take one down and pass it around, 84 bottles of beer on the wall. 84 bottles of beer on the wall, 84 bottles of beer. Take one down and pass it around, 83 bottles of beer on the wall. 83 bottles of beer on the wall, 83 bottles of beer. Take one down and pass it around, 82 bottles of beer on the wall. 82 bottles of beer on the wall, 82 bottles of beer. Take one down and pass it around, 81 bottles of beer on the wall. 81 bottles of beer on the wall, 81 bottles of beer. Take one down and pass it around, 80 bottles of beer on the wall. 80 bottles of beer on the wall, 80 bottles of beer. Take one down and pass it around, 79 bottles of beer on the wall. 79 bottles of beer on the wall, 79 bottles of beer. Take one down and pass it around, 78 bottles of beer on the wall. 78 bottles of beer on the wall, 78 bottles of beer. Take one down and pass it around, 77 bottles of beer on the wall. 77 bottles of beer on the wall, 77 bottles of beer. Take one down and pass it around, 76 bottles of beer on the wall. 76 bottles of beer on the wall, 76 bottles of beer. Take one down and pass it around, 75 bottles of beer on the wall. 75 bottles of beer on the wall, 75 bottles of beer. Take one down and pass it around, 74 bottles of beer on the wall. 74 bottles of beer on the wall, 74 bottles of beer. Take one down and pass it around, 73 bottles of beer on the wall. 73 bottles of beer on the wall, 73 bottles of beer. Take one down and pass it around, 72 bottles of beer on the wall. 72 bottles of beer on the wall, 72 bottles of beer. Take one down and pass it around, 71 bottles of beer on the wall. 71 bottles of beer on the wall, 71 bottles of beer. Take one down and pass it around, 70 bottles of beer on the wall. 70 bottles of beer on the wall, 70 bottles of beer. Take one down and pass it around, 69 bottles of beer on the wall. 69 bottles of beer on the wall, 69 bottles of beer. Take one down and pass it around, 68 bottles of beer on the wall. 68 bottles of beer on the wall, 68 bottles of beer. Take one down and pass it around, 67 bottles of beer on the wall. 67 bottles of beer on the wall, 67 bottles of beer. Take one down and pass it around, 66 bottles of beer on the wall. 66 bottles of beer on the wall, 66 bottles of beer. Take one down and pass it around, 65 bottles of beer on the wall. 65 bottles of beer on the wall, 65 bottles of beer. Take one down and pass it around, 64 bottles of beer on the wall. 64 bottles of beer on the wall, 64 bottles of beer. Take one down and pass it around, 63 bottles of beer on the wall. 63 bottles of beer on the wall, 63 bottles of beer. Take one down and pass it around, 62 bottles of beer on the wall. 62 bottles of beer on the wall, 62 bottles of beer. Take one down and pass it around, 61 bottles of beer on the wall. 61 bottles of beer on the wall, 61 bottles of beer. Take one down and pass it around, 60 bottles of beer on the wall. 60 bottles of beer on the wall, 60 bottles of beer. Take one down and pass it around, 59 bottles of beer on the wall. 59 bottles of beer on the wall, 59 bottles of beer. Take one down and pass it around, 58 bottles of beer on the wall. 58 bottles of beer on the wall, 58 bottles of beer. Take one down and pass it around, 57 bottles of beer on the wall. 57 bottles of beer on the wall, 57 bottles of beer. Take one down and pass it around, 56 bottles of beer on the wall. 56 bottles of beer on the wall, 56 bottles of beer. Take one down and pass it around, 55 bottles of beer on the wall. 55 bottles of beer on the wall, 55 bottles of beer. Take one down and pass it around, 54 bottles of beer on the wall. 54 bottles of beer on the wall, 54 bottles of beer. Take one down and pass it around, 53 bottles of beer on the wall. 53 bottles of beer on the wall, 53 bottles of beer. Take one down and pass it around, 52 bottles of beer on the wall. 52 bottles of beer on the wall, 52 bottles of beer. Take one down and pass it around, 51 bottles of beer on the wall. 51 bottles of beer on the wall, 51 bottles of beer. Take one down and pass it around, 50 bottles of beer on the wall. 50 bottles of beer on the wall, 50 bottles of beer. Take one down and pass it around, 49 bottles of beer on the wall. 49 bottles of beer on the wall, 49 bottles of beer. Take one down and pass it around, 48 bottles of beer on the wall. 48 bottles of beer on the wall, 48 bottles of beer. Take one down and pass it around, 47 bottles of beer on the wall. 47 bottles of beer on the wall, 47 bottles of beer. Take one down and pass it around, 46 bottles of beer on the wall. 46 bottles of beer on the wall, 46 bottles of beer. Take one down and pass it around, 45 bottles of beer on the wall. 45 bottles of beer on the wall, 45 bottles of beer. Take one down and pass it around, 44 bottles of beer on the wall. 44 bottles of beer on the wall, 44 bottles of beer. Take one down and pass it around, 43 bottles of beer on the wall. 43 bottles of beer on the wall, 43 bottles of beer. Take one down and pass it around, 42 bottles of beer on the wall. 42 bottles of beer on the wall, 42 bottles of beer. Take one down and pass it around, 41 bottles of beer on the wall. 41 bottles of beer on the wall, 41 bottles of beer. Take one down and pass it around, 40 bottles of beer on the wall. 40 bottles of beer on the wall, 40 bottles of beer. Take one down and pass it around, 39 bottles of beer on the wall. 39 bottles of beer on the wall, 39 bottles of beer. Take one down and pass it around, 38 bottles of beer on the wall. 38 bottles of beer on the wall, 38 bottles of beer. Take one down and pass it around, 37 bottles of beer on the wall. 37 bottles of beer on the wall, 37 bottles of beer. Take one down and pass it around, 36 bottles of beer on the wall. 36 bottles of beer on the wall, 36 bottles of beer. Take one down and pass it around, 35 bottles of beer on the wall. 35 bottles of beer on the wall, 35 bottles of beer. Take one down and pass it around, 34 bottles of beer on the wall. 34 bottles of beer on the wall, 34 bottles of beer. Take one down and pass it around, 33 bottles of beer on the wall. 33 bottles of beer on the wall, 33 bottles of beer. Take one down and pass it around, 32 bottles of beer on the wall. 32 bottles of beer on the wall, 32 bottles of beer. Take one down and pass it around, 31 bottles of beer on the wall. 31 bottles of beer on the wall, 31 bottles of beer. Take one down and pass it around, 30 bottles of beer on the wall. 30 bottles of beer on the wall, 30 bottles of beer. Take one down and pass it around, 29 bottles of beer on the wall. 29 bottles of beer on the wall, 29 bottles of beer. Take one down and pass it around, 28 bottles of beer on the wall. 28 bottles of beer on the wall, 28 bottles of beer. Take one down and pass it around, 27 bottles of beer on the wall. 27 bottles of beer on the wall, 27 bottles of beer. Take one down and pass it around, 26 bottles of beer on the wall. 26 bottles of beer on the wall, 26 bottles of beer. Take one down and pass it around, 25 bottles of beer on the wall. 25 bottles of beer on the wall, 25 bottles of beer. Take one down and pass it around, 24 bottles of beer on the wall. 24 bottles of beer on the wall, 24 bottles of beer. Take one down and pass it around, 23 bottles of beer on the wall. 23 bottles of beer on the wall, 23 bottles of beer. Take one down and pass it around, 22 bottles of beer on the wall. 22 bottles of beer on the wall, 22 bottles of beer. Take one down and pass it around, 21 bottles of beer on the wall. 21 bottles of beer on the wall, 21 bottles of beer. Take one down and pass it around, 20 bottles of beer on the wall. 20 bottles of beer on the wall, 20 bottles of beer. Take one down and pass it around, 19 bottles of beer on the wall. 19 bottles of beer on the wall, 19 bottles of beer. Take one down and pass it around, 18 bottles of beer on the wall. 18 bottles of beer on the wall, 18 bottles of beer. Take one down and pass it around, 17 bottles of beer on the wall. 17 bottles of beer on the wall, 17 bottles of beer. Take one down and pass it around, 16 bottles of beer on the wall. 16 bottles of beer on the wall, 16 bottles of beer. Take one down and pass it around, 15 bottles of beer on the wall. 15 bottles of beer on the wall, 15 bottles of beer. Take one down and pass it around, 14 bottles of beer on the wall. 14 bottles of beer on the wall, 14 bottles of beer. Take one down and pass it around, 13 bottles of beer on the wall. 13 bottles of beer on the wall, 13 bottles of beer. Take one down and pass it around, 12 bottles of beer on the wall. 12 bottles of beer on the wall, 12 bottles of beer. Take one down and pass it around, 11 bottles of beer on the wall. 11 bottles of beer on the wall, 11 bottles of beer. Take one down and pass it around, 10 bottles of beer on the wall. 10 bottles of beer on the wall, 10 bottles of beer. Take one down and pass it around, 9 bottles of beer on the wall. 9 bottles of beer on the wall, 9 bottles of beer. Take one down and pass it around, 8 bottles of beer on the wall. 8 bottles of beer on the wall, 8 bottles of beer. Take one down and pass it around, 7 bottles of beer on the wall. 7 bottles of beer on the wall, 7 bottles of beer. Take one down and pass it around, 6 bottles of beer on the wall. 6 bottles of beer on the wall, 6 bottles of beer. Take one down and pass it around, 5 bottles of beer on the wall. 5 bottles of beer on the wall, 5 bottles of beer. Take one down and pass it around, 4 bottles of beer on the wall. 4 bottles of beer on the wall, 4 bottles of beer. Take one down and pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall, 3 bottles of beer. Take one down and pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.] ``` [Answer] # PHP and [아희(Aheui)](http://esolangs.org/wiki/Aheui) ``` <?php $b = 99; while(true) { echo ($b==0 ? "No more" : $b)." bottle".($b==1 ? "" : "s")." of beer on the wall, ".($b==0 ? "no more" : $b)." bottle".($b==1 ? "" : "s")." of beer.\n"; if($b == 0) { echo "Go to the store and buy some more"; $b = 99; } else { echo "Take one down and pass it around"; $b--; } echo ", ".($b==0 ? "no more" : $b)." bottle".($b==1 ? "" : "s")." of beer on the wall.\n\n"; if($b == 99) break; } /* 발발따밤따박박나타삭밤밣따산박밦따밞뚜 우어어어어어어어어어어어어어어어어어어 아우 오사뺘뿌처밞밞따받타맣산빠받다맣삭빠맣산빠박박나다맣빠받다맣빠밦다맣빠밝타맣수 오우어명여어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어 오삭빠맣산빠발타발타맣빠받다맣빠밣다빠맣맣빠맣빠밝타맣수 오우어어어어어어어어어어어어어어멓더벍뻐선처우텨너벅벅뻐 오우어어어어어어어어어어어어어어어어어어어어어 오아삭빠맣산빠받다맣빠밦타맣삭빠맣산빠발타발타맣빠밝타빠맣맣빠밦다맣삭빠맣산빠받다맣빠박다뭏 오뭏뻐멓더벖더벖뻐석멓뻐멓뻐멓터벖터벌뻐멓더벖더벌뻐선멓뻐석멓터벍뻐멓터범뻐멓더벓뻐선멓뻐석 오사뺘뿌처산빠박다맣빠받다맣삭빠맣산빠박박나다맣빠받다맣빠밦다맣빠밝타맣수 오우어명여어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어 오삭빠맣산빠발타발타맣빠받다맣빠밣다빠맣맣빠맣빠밝타맣수 오우어어어어어어어어어어어어어어멓더벍뻐선처우텨너벅벅뻐 오우어어어어어어어어어어어어어어어어어어어어어 오삭빠맣산빠받다맣빠밦타맣삭빠맣산빠발타발타맣빠밝타빠맣맣빠밦다맣밦밝따밤다맣발발다뭏 오우어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어 오사뺘우차박밦따밝따맣산빠발타밦타맣빠박박나타맣빠밝타맣삭빠맣산빠받다맣빠박다맣빠밝타뮿 오ㅇㅇ아아밣밣따밝다맣산빠받다맣삭빠맣산빠밣다맣빠받다맣삭빠맣산빠밣다맣빠밤타맣빠밝타뮿 오뮿뻐석멓터벓뻐멓더벅뻐멓터벖터벌뻐선멓뻐석멓더벅뻐멓더벖더벌뻐멓더벋뻐멓터벓뻐선멓뻐석 오유멓터벓뻐멓더벅뻐멓터벖터벌뻐선멓뻐석멓터벍뻐멓더벖뻐멓더벋뻐멓더벓뻐멓더벍뻐선멓뻐석 오삭산빠밤다맣빠발타밦타맣빠밝다빠맣맣삭빠맣산빠받타맣빠밣다맣삭빠뮿 초삭빠맣산빠발타발타맣빠밞다빠맣밤다맣삭빠맣산빠밝다맣빠받다맣빠박박나다맣빠밝타뮿 희유어어어어어멓터벓뻐멓더벅뻐멓더벎뻐멓더벋뻐멓더벖뻐멓터벖터벌뻐선 툐우어어어어어어어어어어어어어어어어어멓터벍뻐멓더벖뻐멓더벅멓뻐더너벅벅뻐선멓뻐석 토삭빠밦다밦다맣빠뭏 노우터너벅벅처불뼈서 복우더터너벅벅뱔뗘따볌 복사뺘뿌처산빠박다맣빠받다맣삭빠맣산빠박박나다맣빠받다맣빠밦다맣빠밝타맣수 또우어명여어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어 봄삭빠맣산빠발타발타맣빠받다맣빠밣다빠맣맣빠맣빠밝타맣수 또우어어어어어어어어어어어어어어멓더벍뻐선처우텨너벅벅뻐 볼우어어어어어어어어어어어어어어어어어어어어어 볼아삭빠맣산빠받다맣빠밦타맣삭빠맣산빠발타발타맣빠밝타빠맣맣빠밦다맣삭빠맣산빠받다맣빠박다뭏 뽀불벌멓더벍더벍뻐석멓뻐멓뻐멓터벖터벌뻐멓더벖더벌뻐선멓뻐석멓터벍뻐멓터범뻐멓더벓뻐선멓뻐석 소댜몋빠몋 ``` Aheui was tested with [naheui](https://github.com/aheui/naheui). I know it's cheating, but it works anyway. [Answer] This will work in Python 3 and in Julia. ``` [[print(b, " bottles of beer on the wall, ", b, " bottles of beer.\nTake one down and pass it around, ", b-1, " bottles of beer on the wall.\n" ) for b in l] for l in [[12 * i + j + 4 for j in [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]] for i in [7, 6, 5, 4, 3, 2, 1, 0]]] print("3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n") print("2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n") print("1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n") print("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n") ``` [Answer] BrainFuck and Python 2 This will compile and run under CPython2.7 (and probably others) as well as a BrainFuck interpreter. These are two distinct languages, with very little overlap, and this answer is totally cheating. ``` # Thanks to Raphael Bois for the code (taken from http://goo(dot)gl/GddKtS) # ++>+>++>>+>>>:++++++++++[->+>+>++++++++++<<<]>>>>++++++++++[->+++++>++++++++++>+++++++++++>++++++++>++++++++>+++>++++>+<<<<<<<<]+>--+>+++>++++++>--+>+++++>+++>+++++>+>+>+>+>++>+>+>++[-<]<<<<<<<[->>[>>>>>>>>[<<<<<<<[->[-]>>>>>>>>>>>.<----.>>>.<<<--.++.+++.+<-.+<<+<<<<<<<<]+>[-<[-]>>>>>[>>>+<<<<+<+<+>>>-]<<<[->>>+<<<]>[>>>>>>+<<<<<<-]>>>>>[[-]>.<]<<<<[>>>>>-<<<<<-]>>[<<+<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>+<<<<<<-]>>>>>>.<<<<<[>>>>>-<<<<<-]>>>[-<<<+<+>>>>]<<<<[->>>>+<<<<]>-[[-]>>>>+<<<<]<<<]+>>>>>>>>>>>>>.<<<<----.>----.+++++..-<++++++++++.-------.<<[[-]>>>.<<<]>>===>>>>.<<<----.<+.>>>>.<<<<----.+++..+>+++.+[>]+>+>[->+<<-<-<<<.<<<----.-.>>>.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..------>---->-------------------------------->>>++.-->..>>>]>>>[->[-]<<<<<<<[<]<[-]>>[>]>>>>>]+>[-<[-]<<<<[->>[->+<<<<-<<<.<<<----.-.>>>.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..------>---->++++++++++++++++++++++++++++++++>>>.<.>>>>>>]<<]<[->>>>[-<<+<<<<++.-->.[<]<<<<<<<<[->[-]<]+>[-<[-]>>>>>>>>>>>>>.<<<-----.++++++++++.------.>>>>.<<<----.-.<.>>>>.<<<<-.>+.++++++++.---------.>>>.<<<<---.>.<+++.>>>>.<<<++.<---.>+++..>>>.<<<<++++++++.>+.>>>.<<<<--------.>--.---.++++++.-------.<+++.++>+++++>>>>.<.[<]<<<<<<<]+>>>>>>-<<<+>>[<<[-]<+<+>>>>-]<<<<[>-<[-]]>[->>>+<<<]>[->->+++++++++<<]>>>>>[>]>>>>]<<<<]>>>>>>]+<<<<<<<[<]<]+<+<<<<<<+<-]>>>>>>>>>>[>]>>>>>[->[-]<]+>[-<[-]<<<<<<<<<-------------.<<----.>>>.<<<+++++.-----.>>>.<<<+++++.<++.---.>>>>.<<<-.+.-----.+++.<.>>>>.<<<<----.>----.<+++.>>>>.<<<<--.>+++++++.++++.>>>.<<<------.----.--.<+++.>>>>.<<<.++.+++.+<.+>>>>>.<.>>>>>>>>>]+<[-]+<[-]<[-]<[-]+<<<[<]<[-]<[-]<[-]<[-]++++++++++[->+>+>++++++++++<<<]>->->-<<<<<<[-]+<[-]<+<<] dot = chr(46) comma = chr(44) for x in range(99, 2, -1): print """%d bottles of beer on the wall%s %d bottles of beer%s Take one down and pass it around%s %d bottles of beer on the wall%s """ % (x, comma, x, dot, comma, x - 1, dot) print """2 bottles of beer on the wall%s 2 bottles of beer%s Take one down and pass it around%s 1 bottle of beer on the wall%s 1 bottle of beer on the wall%s 1 bottle of beer%s Take one down and pass it around%s no more bottles of beer on the wall%s No more bottles of beer on the wall%s no more bottles of beer%s Go to the store and buy some more%s 99 bottles of beer on the wall%s""" % (comma, dot, comma, dot, comma, dot, comma, dot, comma, dot, comma, dot) ``` The second line is the BrainFuck-run code. BrainFuck interpreters should ignore the rest of the code, and [online interpreters](http://brainfuck.tk) will run it. The rest of the code is the Python code. Originally it was just going to print the entire set of lyrics, but that's not as fun. The same was also going to be done for the BrainFuck code, but it blew by the character restrictions in posts (by about 270,000 characters). [Answer] # **Lua and (F)ASM** ``` S=10;--[[ irp x,<display 'The beer song:',13,10>,<rept 101 d:0\{reverse match,\\{j equ 'If one bottle of beer should accidently fall ...',13,10\\}match,\\{p equ 's'\\}match,\\{q equ \`d\\}match=1,d\\{p equ ''\\}match=0,d\\{q equ 'no'\\}match=0,d\\{j equ 'Who drunk all the beer!',13,10\\}match f,q\\{display q,' bottle',p,' of beer on the wall, ',q,' bottle',p,' of beer,',13,10,j\\}\}>{x} S=10;]]-- S=10; beer=99 S=10; repeat S=10; print(beer.." bottles of beer on the wall, "..beer.." bottles") S=10; beer=beer-1 S=10; print("Take one down and pass it around, "..beer.." bottles of beer on the wall.") S=10; print() S=10; until beer==1 S=10; print("1 bottle of beer on the wall, 1 bottle of beer.") S=10; print("Take one down and pass it around, no more bottles of beer on the wall.") S=10; print() S=10; print("No more bottles of beer on the wall, no more bottles of beer.") ``` Credits to [Revolution](http://board.flatassembler.net/topic.php?p=43906) for the Fasm one liner, even though everything in between line 1 and 3 is ignored by Lua so I could have writte an aribitrary long fasm program in there. The trick is that in lua you can use a semicolon to separate instruction, to write multiple instructions on the same line, while in fasm a semicolon is the beginning a comment. S=10; is a valid assignement in both languages, everything else is fairly obvious [Answer] # J, Python 2.x I'm a little late to the party, but oh well. Nothing too fancy here, because it's my first time polyglotting. Python is quite impossible to be properly mixed with J; so I basically commented J out in Python and made Python a string literal in J. I'll probably add more languages later. ``` (''''"_)`(''"_)@.(1) 1 number =: 'No more'"_`('no more'"_)@.([ = 0:)`(":@])@.(] > 0:) bottle =: number , {.&' bottles'@(8: - =&1@]) verse1 =: 1&bottle, ' of beer on the wall, '"_, bottle, ' of beer.'"_ verse2 =: 'Take one down and pass it around, '"_, bottle@<:, ' of beer on the wall.'"_ verse =: verse1 ,: verse2 song =: (<:@[ $: ] , verse@[ , ''"_)`(] , verse1@[)@.([ < 1:) sing =: (] song ''"_) , 'Go to the store and buy some more, '"_ , bottle , ' of beer on the wall.'"_ sing ". 2 {. 0 : 0 99''') print(lambda x:x(x,99,lambda c,w=1,p=0:"%s %s of beer%s"%(c or"nN"[p]+"o more","bottle"+"s"*(c!=1)," on the wall"*w)))(lambda x,c,y:c+1and"%s, %s.\n%s"%(y(c,1,1),y(c,0),"Take one down and pass it around, %s.\n\n"%y(c-1)*(c>0))+x(x,c-1,y)or"Go to the store and buy some more, %s.\n"%y(99) ) ``` [Answer] ## C# + Ruby ``` using System; namespace bottles { class Program { static void Main(string[] args) { for (int i = 99; i >= 0; i--) Console.WriteLine("{0} bottles", i); } } } /* #!/usr/bin/ruby 99.downto(0){|i| print i.to_s+" bottles\n" } __END__ */ ``` to run (Ruby): ruby -x script.cs [Answer] This should work in C, C++ and Objective-C. Objective-C++ has not been tested but will probably work: ``` #include <stdio.h> int main(void) { int b; for (b = 99; b >= 0; b--) { switch (b) { case 0: printf("No more bottles of beer on the wall, no more bottles of beer.\n"); printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n"); break; case 1: printf("1 bottle of beer on the wall, 1 bottle of beer.\n"); printf("Take one down and pass it around, no more bottles of beer on the wall\n"); break; default: printf("%d bottles of beer on the wall, %d bottles of beer.\n", b, b); printf("Take one down and pass it around, %d %s of beer on the wall.\n" ,b - 1,((b - 1) > 1)? "bottles" : "bottle"); break; } } return 0; } ``` [Answer] # Ruby, Golfscript ``` "#{File.write('out.txt', "99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down, pass it around, 97 bottles of beer on the wall. 97 bottles of beer on the wall, 97 bottles of beer. Take one down, pass it around, 96 bottles of beer on the wall. 96 bottles of beer on the wall, 96 bottles of beer. Take one down, pass it around, 95 bottles of beer on the wall. 95 bottles of beer on the wall, 95 bottles of beer. Take one down, pass it around, 94 bottles of beer on the wall. 94 bottles of beer on the wall, 94 bottles of beer. Take one down, pass it around, 93 bottles of beer on the wall. 93 bottles of beer on the wall, 93 bottles of beer. Take one down, pass it around, 92 bottles of beer on the wall. 92 bottles of beer on the wall, 92 bottles of beer. Take one down, pass it around, 91 bottles of beer on the wall. 91 bottles of beer on the wall, 91 bottles of beer. Take one down, pass it around, 90 bottles of beer on the wall. 90 bottles of beer on the wall, 90 bottles of beer. Take one down, pass it around, 89 bottles of beer on the wall. 89 bottles of beer on the wall, 89 bottles of beer. Take one down, pass it around, 88 bottles of beer on the wall. 88 bottles of beer on the wall, 88 bottles of beer. Take one down, pass it around, 87 bottles of beer on the wall. 87 bottles of beer on the wall, 87 bottles of beer. Take one down, pass it around, 86 bottles of beer on the wall. 86 bottles of beer on the wall, 86 bottles of beer. Take one down, pass it around, 85 bottles of beer on the wall. 85 bottles of beer on the wall, 85 bottles of beer. Take one down, pass it around, 84 bottles of beer on the wall. 84 bottles of beer on the wall, 84 bottles of beer. Take one down, pass it around, 83 bottles of beer on the wall. 83 bottles of beer on the wall, 83 bottles of beer. Take one down, pass it around, 82 bottles of beer on the wall. 82 bottles of beer on the wall, 82 bottles of beer. Take one down, pass it around, 81 bottles of beer on the wall. 81 bottles of beer on the wall, 81 bottles of beer. Take one down, pass it around, 80 bottles of beer on the wall. 80 bottles of beer on the wall, 80 bottles of beer. Take one down, pass it around, 79 bottles of beer on the wall. 79 bottles of beer on the wall, 79 bottles of beer. Take one down, pass it around, 78 bottles of beer on the wall. 78 bottles of beer on the wall, 78 bottles of beer. Take one down, pass it around, 77 bottles of beer on the wall. 77 bottles of beer on the wall, 77 bottles of beer. Take one down, pass it around, 76 bottles of beer on the wall. 76 bottles of beer on the wall, 76 bottles of beer. Take one down, pass it around, 75 bottles of beer on the wall. 75 bottles of beer on the wall, 75 bottles of beer. Take one down, pass it around, 74 bottles of beer on the wall. 74 bottles of beer on the wall, 74 bottles of beer. Take one down, pass it around, 73 bottles of beer on the wall. 73 bottles of beer on the wall, 73 bottles of beer. Take one down, pass it around, 72 bottles of beer on the wall. 72 bottles of beer on the wall, 72 bottles of beer. Take one down, pass it around, 71 bottles of beer on the wall. 71 bottles of beer on the wall, 71 bottles of beer. Take one down, pass it around, 70 bottles of beer on the wall. 70 bottles of beer on the wall, 70 bottles of beer. Take one down, pass it around, 69 bottles of beer on the wall. 69 bottles of beer on the wall, 69 bottles of beer. Take one down, pass it around, 68 bottles of beer on the wall. 68 bottles of beer on the wall, 68 bottles of beer. Take one down, pass it around, 67 bottles of beer on the wall. 67 bottles of beer on the wall, 67 bottles of beer. Take one down, pass it around, 66 bottles of beer on the wall. 66 bottles of beer on the wall, 66 bottles of beer. Take one down, pass it around, 65 bottles of beer on the wall. 65 bottles of beer on the wall, 65 bottles of beer. Take one down, pass it around, 64 bottles of beer on the wall. 64 bottles of beer on the wall, 64 bottles of beer. Take one down, pass it around, 63 bottles of beer on the wall. 63 bottles of beer on the wall, 63 bottles of beer. Take one down, pass it around, 62 bottles of beer on the wall. 62 bottles of beer on the wall, 62 bottles of beer. Take one down, pass it around, 61 bottles of beer on the wall. 61 bottles of beer on the wall, 61 bottles of beer. Take one down, pass it around, 60 bottles of beer on the wall. 60 bottles of beer on the wall, 60 bottles of beer. Take one down, pass it around, 59 bottles of beer on the wall. 59 bottles of beer on the wall, 59 bottles of beer. Take one down, pass it around, 58 bottles of beer on the wall. 58 bottles of beer on the wall, 58 bottles of beer. Take one down, pass it around, 57 bottles of beer on the wall. 57 bottles of beer on the wall, 57 bottles of beer. Take one down, pass it around, 56 bottles of beer on the wall. 56 bottles of beer on the wall, 56 bottles of beer. Take one down, pass it around, 55 bottles of beer on the wall. 55 bottles of beer on the wall, 55 bottles of beer. Take one down, pass it around, 54 bottles of beer on the wall. 54 bottles of beer on the wall, 54 bottles of beer. Take one down, pass it around, 53 bottles of beer on the wall. 53 bottles of beer on the wall, 53 bottles of beer. Take one down, pass it around, 52 bottles of beer on the wall. 52 bottles of beer on the wall, 52 bottles of beer. Take one down, pass it around, 51 bottles of beer on the wall. 51 bottles of beer on the wall, 51 bottles of beer. Take one down, pass it around, 50 bottles of beer on the wall. 50 bottles of beer on the wall, 50 bottles of beer. Take one down, pass it around, 49 bottles of beer on the wall. 49 bottles of beer on the wall, 49 bottles of beer. Take one down, pass it around, 48 bottles of beer on the wall. 48 bottles of beer on the wall, 48 bottles of beer. Take one down, pass it around, 47 bottles of beer on the wall. 47 bottles of beer on the wall, 47 bottles of beer. Take one down, pass it around, 46 bottles of beer on the wall. 46 bottles of beer on the wall, 46 bottles of beer. Take one down, pass it around, 45 bottles of beer on the wall. 45 bottles of beer on the wall, 45 bottles of beer. Take one down, pass it around, 44 bottles of beer on the wall. 44 bottles of beer on the wall, 44 bottles of beer. Take one down, pass it around, 43 bottles of beer on the wall. 43 bottles of beer on the wall, 43 bottles of beer. Take one down, pass it around, 42 bottles of beer on the wall. 42 bottles of beer on the wall, 42 bottles of beer. Take one down, pass it around, 41 bottles of beer on the wall. 41 bottles of beer on the wall, 41 bottles of beer. Take one down, pass it around, 40 bottles of beer on the wall. 40 bottles of beer on the wall, 40 bottles of beer. Take one down, pass it around, 39 bottles of beer on the wall. 39 bottles of beer on the wall, 39 bottles of beer. Take one down, pass it around, 38 bottles of beer on the wall. 38 bottles of beer on the wall, 38 bottles of beer. Take one down, pass it around, 37 bottles of beer on the wall. 37 bottles of beer on the wall, 37 bottles of beer. Take one down, pass it around, 36 bottles of beer on the wall. 36 bottles of beer on the wall, 36 bottles of beer. Take one down, pass it around, 35 bottles of beer on the wall. 35 bottles of beer on the wall, 35 bottles of beer. Take one down, pass it around, 34 bottles of beer on the wall. 34 bottles of beer on the wall, 34 bottles of beer. Take one down, pass it around, 33 bottles of beer on the wall. 33 bottles of beer on the wall, 33 bottles of beer. Take one down, pass it around, 32 bottles of beer on the wall. 32 bottles of beer on the wall, 32 bottles of beer. Take one down, pass it around, 31 bottles of beer on the wall. 31 bottles of beer on the wall, 31 bottles of beer. Take one down, pass it around, 30 bottles of beer on the wall. 30 bottles of beer on the wall, 30 bottles of beer. Take one down, pass it around, 29 bottles of beer on the wall. 29 bottles of beer on the wall, 29 bottles of beer. Take one down, pass it around, 28 bottles of beer on the wall. 28 bottles of beer on the wall, 28 bottles of beer. Take one down, pass it around, 27 bottles of beer on the wall. 27 bottles of beer on the wall, 27 bottles of beer. Take one down, pass it around, 26 bottles of beer on the wall. 26 bottles of beer on the wall, 26 bottles of beer. Take one down, pass it around, 25 bottles of beer on the wall. 25 bottles of beer on the wall, 25 bottles of beer. Take one down, pass it around, 24 bottles of beer on the wall. 24 bottles of beer on the wall, 24 bottles of beer. Take one down, pass it around, 23 bottles of beer on the wall. 23 bottles of beer on the wall, 23 bottles of beer. Take one down, pass it around, 22 bottles of beer on the wall. 22 bottles of beer on the wall, 22 bottles of beer. Take one down, pass it around, 21 bottles of beer on the wall. 21 bottles of beer on the wall, 21 bottles of beer. Take one down, pass it around, 20 bottles of beer on the wall. 20 bottles of beer on the wall, 20 bottles of beer. Take one down, pass it around, 19 bottles of beer on the wall. 19 bottles of beer on the wall, 19 bottles of beer. Take one down, pass it around, 18 bottles of beer on the wall. 18 bottles of beer on the wall, 18 bottles of beer. Take one down, pass it around, 17 bottles of beer on the wall. 17 bottles of beer on the wall, 17 bottles of beer. Take one down, pass it around, 16 bottles of beer on the wall. 16 bottles of beer on the wall, 16 bottles of beer. Take one down, pass it around, 15 bottles of beer on the wall. 15 bottles of beer on the wall, 15 bottles of beer. Take one down, pass it around, 14 bottles of beer on the wall. 14 bottles of beer on the wall, 14 bottles of beer. Take one down, pass it around, 13 bottles of beer on the wall. 13 bottles of beer on the wall, 13 bottles of beer. Take one down, pass it around, 12 bottles of beer on the wall. 12 bottles of beer on the wall, 12 bottles of beer. Take one down, pass it around, 11 bottles of beer on the wall. 11 bottles of beer on the wall, 11 bottles of beer. Take one down, pass it around, 10 bottles of beer on the wall. 10 bottles of beer on the wall, 10 bottles of beer. Take one down, pass it around, 9 bottles of beer on the wall. 9 bottles of beer on the wall, 9 bottles of beer. Take one down, pass it around, 8 bottles of beer on the wall. 8 bottles of beer on the wall, 8 bottles of beer. Take one down, pass it around, 7 bottles of beer on the wall. 7 bottles of beer on the wall, 7 bottles of beer. Take one down, pass it around, 6 bottles of beer on the wall. 6 bottles of beer on the wall, 6 bottles of beer. Take one down, pass it around, 5 bottles of beer on the wall. 5 bottles of beer on the wall, 5 bottles of beer. Take one down, pass it around, 4 bottles of beer on the wall. 4 bottles of beer on the wall, 4 bottles of beer. Take one down, pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall, 3 bottles of beer. Take one down, pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall, 2 bottles of beer. Take one down, pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Take one down, pass it around, No bottles of beer on the wall. No bottles of beer on the wall, No bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.")}" ``` ]
[Question] [ Write a function/program that accepts a string of lower/uppercase letters [A-Za-z] as input, that checks whether the occuring letters are unique and in alphabetical order (ignoring lower and uppercase) or not. The output must be truthy if they are unique and in alphabetical order and falsy if not. Here some testcases ``` a true abcdefGHIjklmnopqrSTUVWXyz true aa false puz true puzz false puzZ false puZ true PuZ true pzu false pzU false abcdABCD false dcba false ``` If you want, run your program on all words of a wordlist like [this one](http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt) and and post some interesting ones =). ### Score Lowest number of bytes wins. [Answer] # CJam, 8 bytes ``` lel_$_&= ``` [Here is a test harness](http://cjam.aditsu.net/#code=qN%2F%7B%0A%0Ael_%24_%26%3D%0A%0Ap%7D%2F&input=a%0AabcdefGHIjklmnopqrSTUVWXyz%0Aaa%0Apuz%0Apuzz%0ApuzZ%0ApuZ%0APuZ) for all examples in the challenge. This returns `0` or `1` (which are falsy and truthy, respectively, in CJam). And [here](http://cjam.aditsu.net/#code=qN%2F%7B%0A%0Ael_%24_%26%3D%0A%0A%7D%2C%20N*) is a script to filter the word list in the question (takes a few seconds to run). You'll have to copy the word list into the input field manually, because it's too long for a permalink. ## Explanation ``` l "Read input."; el "Convert to lower case."; _$ "Get a copy and sort it."; _& "Remove duplicates (by computing the set intersection with itself)."; = "Check for equality with original (lower case) word."; ``` [Answer] # Regex (any flavor), 55 bytes Some people don't consider regex to be a programming language, but it's been used before, and it's not close to being the shortest. ``` ^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$ ``` I've added one byte for the `i` (case-insensitive) flag. This is very straightforward and might be shorter to generate on the fly. If regex alone are not allowed, you can use this 56-byte [Retina](https://github.com/mbuettner/retina) program suggested by Martin Büttner: ``` i`^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$ ``` Running this on the wordlist linked above yielded 10 6-letter words in alphabetical order. > > ["abhors", "almost", "begins", "begirt", "bijoux", "biopsy", "chimps", "chinos", "chintz", "ghosty"] > > > [Answer] # Python 3, 44 bytes ``` *s,=input().lower() print(sorted(set(s))==s) ``` A simple approach - check uniqueness, check sortedness. [Answer] # [><>](http://esolangs.org/wiki/Fish), ~~52~~ ~~42~~ 39 bytes ``` 0>i:1+?v1n; ? )'`':/'@'v 0v?){:-<'`'/;n ``` This type of question is one of the few types that ><> is pretty comfortable with, since we only need to deal with one char at a time. ## Explanation Don't get lost! There's a lot of wrapping here. ``` 0 Push 0. We'll be mapping a-z to 1-26, so 0 will be smaller than everything (loop) i Read a char of input :1+? 1n; If there's no more input, print 1 :'`')? If the char is bigger than backtick... '`' Push backtick (which is one before 'a'), else... '@' Push an @ sign (which is one before 'A') - Subtract, mapping a-z to 1-26 :{)? If the new char is bigger than the previous char... Repeat from the beginning of the loop, else... 0n; Print 0 ``` ## Previous solution, 42 bytes ``` 0i:1+?v1n;n0/\! ?)'`':/'@'v ? ){:-<'`'/ vv ``` The interesting thing is that, despite appearing to have the same functionality, the alternative ``` 0i:1+?v1n;n0\/! ?)'`':/'@'v ? ){:-<'`'/ ^^ ``` *(The change is in the arrows and mirrors on the far right)* actually gives *incorrect* results, due to ><>'s interpreter using a Python defaultdict. What happens is that, by traversing through the empty space at the end of the second row, 0s are implicitly placed into the blank spaces when ><> tries to access the cell. This then messes with the `?` conditional trampoline at the beginning of the same row, as the newly placed 0s are skipped rather than the `v` at the end. [Answer] # Haskell, 52 Bytes ``` import Data.Char and.(zipWith(>)=<<tail).map toLower ``` Usage: `(and.(zipWith(>)=<<tail).map toLower) "abcd"` which outputs `True`. [Answer] # C, 67 65 57 54 (52) characters ``` f(char*s){int c,d=0;for(;(c=*s++)&&(c&~32)>(d&~32);d=c);return!c;} ``` a little shorter: ``` f(char*s){int c,d=0;for(;(c=*s++)&&(c&~32)>d;d=c&~32);return!c;} ``` and even shorter: ``` f(char*s){int d=32;for(;(*s|32)>d;d=*s++|32);return!*s;} ``` Here's a little test: <http://ideone.com/ZHd0xl> After the latest suggestions here are still two shorter versions: ``` // 54 bytes f(char*s){int d=1;for(;(*s&=95)>d;d=*s++);return!*s;} // 52, though not sure if valid because of global variable d;f(char*s){d=1;for(;(*s&=95)>d;d=*s++);return!*s;} ``` Also this code relies on the fact, that in ASCII lowercase and uppercase only differ by the 5th bit (32) which I filter out. So this might not work with other encodings obviously. EDIT: The latest version always sets the 5th bit as `|32` is shorter than `&~32`. [Answer] # Ruby, 33 ``` ->s{c=s.upcase.chars c==c.sort|c} ``` Checks to see if the sorted unique characters are the same as all the characters. [Answer] ## Javascript (ES5), 101 ``` function i(s){b=0;l=''.a s.toUpperCase().split('').forEach(function(c){if(c<=l)b=1 l=c}) return!b} ``` ## Improved to 87 by edc95: upvote his comment :) ``` function i(s){return!s.toUpperCase().split(l='').some(function(c){return(u=l,l=c)<=u})} ``` *Btw, the test cases currently in OP are fulfilled if a program is only checking uniqueness, disregarding order.* --- I cant write comments yet, so I'll answer some remarks here: **@edc65:** Thanks! I tried rewriting it using `some()`, but I couldn't get a shorter solution, because even though it looks like it would enable me to get rid of the superflous b variable, you need to type "return" twice (same with `reduce()`), and you can't just return the comparison's result directly, because the last character needs to be saved after the comparison with it. **@edc65:** That's a nice use of the comma operator for 87! I edited it into my answer for more visibility. [Answer] # Haskell, 90 bytes Supplies the function `f :: String -> Bool` ``` import Data.List import Distribution.Simple.Utils f l=g$lowercase l g l=sort l==l&&l==nub l ``` Usage (assuming it is saved as golf.hs). `...` is used to replace `ghci`'s verbose loading messages. ``` $ ghci golf.hs ... *Main> f "as" ... True *Main> f "aa" False ``` If someone has a `lowercase` method shorter than `import Distribution.Simple.Utils` then please comment. [Answer] ## Wolfram Mathematica, 49 37 bytes ``` f[x_]:=(l=Characters[ToLowerCase[x]];Union[l]==l) ``` P.S. Shorter solution by Martin Büttner: ``` Union[l=Characters@ToLowerCase@#]==l& ``` [Answer] # J, 17 bytes Checks if the lowercase sorted `/:~` string equals `-:` the lowercase nub `~.` string. ``` (/:~-:~.)@tolower NB. testing with the example inputs ((/:~-:~.)@tolower) every (1$'a');'abcdefGHIjklmnopqrSTUVWXyz';'aa';'puz';'puzz';'puzZ';'puZ';'PuZ' 1 1 0 1 0 0 1 1 ``` As in J a 1-charater long "string" represented as a regular string (with quotes) is just a character atom not a real string I formatted the input appropriately so all input would be real strings. (In the example above I used `1$'a'`.) [Answer] # MATLAB, ~~29~~ 27 bytes Now for a one-liner which even makes sense outside of code-golf. As an anonymous function (use as `o('yourstring')`) ``` o=@(s)all(diff(lower(s))>0) ``` I guess this function is pretty self-explanatory since it reads like a newspaper ad. Previous version (29 bytes): ``` all(diff(lower(input('')))>0) ``` Input must be presented between `'` marks, e.g. `'Potato'`. [Answer] ## Golang (65 bytes) Go is not a golf friendly language, also, i suck at golf... ``` func a(s[]byte)(bool){return len(s)<2||s[0]|32<s[1]|32&&a(s[1:])} ``` Run it here: <http://play.golang.org/p/xXJX8GjDvr> *edit 106->102* *edit 102->96* *edit 96->91* *edit 91->87* *edit 87->65* I beat the java version, I can stop for today [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ḷ⊆Ạ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/z/csf1RV9vDXQv@/49WSlTSUUpMSk5JTXP38MzKzsnNyy8oLAoOCQ0Lj6isAkmCVBSUVkFIKBUFpkBkAJCMBQA "Brachylog – Try It Online") The predicate succeeds if the input meets the requirements outlined and fails if it does not, printing `true.` or `false.` if run as a program. ``` The input, ḷ lowercased, ⊆ is a not-necessarily-contiguous sub-list of Ạ "abcdefghijklmnopqrstuvwxyz". ``` The first version I came up with, not explicitly referencing the alphabet: # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ḷ≠.o ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/z/csf1R5wK9/P//o5USlXSUEpOSU1LT3D08s7JzcvPyCwqLgkNCw8IjKqtAkiAVBaVVEBJKRYEpEBkAJGMB "Brachylog – Try It Online") ``` The input, ḷ lowercased, ≠ in which every character is distinct, . is the output variable, o which sorted, is still the output variable. ``` [Answer] # Pure Bash 4.x, 37 ``` [[ ${1,,} =~ ^`printf %s? {a..z}`$ ]] ``` [Try it online!](https://tio.run/##VYxLC4JQFIT391ccxCBBpdYh0osKWkRlD6Po6D0XLVPzQWTUXzcVWjTwzWKGGQdTr3x4fkCQEPIe8IhBpZQy0DSQ5OV4Md9L5eEA8qurqm8wPnA6x4kfZgJaqQkv1PXifZbheCzrpS@g3ZZNw@goSg8yj8LmsBa5XgRZklOTUJDSfyXwFwmf8SikEhk6Licxmc4u1@AWRvE9Wa2tzXb3LBgii/OipjG7MpstKuIir7CabX8wHDHuOsi@ "Bash – Try It Online") Input taken as a command-line parameter. As per standard shell semantics, exit code 0 means true (alphabetic) and exit code != 0 means false (not alphabetic). The printf creates the regex as in [@hsl's solution](https://codegolf.stackexchange.com/a/47212/11259). The input string is expanded to lowercase and compared against the regex. --- Previous answer: ### Bash + coreutils, 52 Straightforward solution: ``` a=`fold -1<<<${1,,}` cmp -s <(sort -u<<<"$a")<<<"$a" ``` [Answer] ## J, 21 characters This is too long. The argument must have rank `1`, i.e. it must be a string or vector. ``` */@(<=~.;/:~)@tolower ``` * `tolower y` – `y` in lower case. * `/:~ y` – `y` in lexical order. * `~. y` – the nub of `y`, that is, `y` with duplicates removed. * `x ; y` – `x` and `y` put into boxes and then concatenated. * `< y` – `y` put into a box. * `x = y` – `x` compared element-wise with `y`. * `(< y) = (~. y) ; (/:~ y)` – a vector indicating if `y` is equal to its nub and itself sorted. * `*/ y` – the product of the items of `y`, or its logical and if the items are booleans. * `*/ (< y) = (~. y) ; (/:~ y)` – a boolean indicating the desired property for lowercase `y`. [Answer] # Julia, 44 bytes ``` s->(l=lowercase(s);l==join(sort(unique(l)))) ``` This creates an anonymous function that takes a single argument `s`, converts it to lower case, and compares it to the unique sorted version of the string. It returns a boolean, i.e. `true` or `false`. If you want to test it out, assign it like `f=s->...` and then call `f("PuZ")`, etc. [Answer] # C# 6, 18 + ~~82~~ 76 = 94 bytes Requires (18 bytes): ``` using System.Linq; ``` Code (76 bytes): ``` bool a(string s)=>(s=s.ToLower()).Distinct().OrderBy(x=>x).SequenceEqual(s); ``` C# 6 supports lambdas to define a function, which is useful for golfing. Non-C# 6 version: ``` bool a(string s){return (s=s.ToLower()).Distinct().OrderBy(x=>x).SequenceEqual(s);} ``` Ungolfed code: ``` bool IsInAlphabeticalOrder(string s) { s = s.ToLower(); return s.Distinct() .OrderBy(x => x) .SequenceEqual(s); } ``` [Answer] # JavaScript (ES6) 54 Convert to uppercase, then to array and sort. If during sort two element are in the wrong order or equal, return 0 (falsy) else 1 (truthy) **Edit** Shortened thx to @Optimizer (but still 2 more than the @Tamas solution implemented in ES6: `F=s=>[...s.toUpperCase()].every(c=>(u=l,l=c)>u,l='')`) ``` F=s=>[...s.toUpperCase(x=1)].sort((a,b)=>a<b?1:x=0)&&x ``` **Test** in Firefox / FireBug console ``` ;['a','abcdefGHIjklmnopqrSTUVWXyz','aa','puz','puzz','puzZ','puZ','PuZ'] .map(w=>w+' '+F(w)) ``` > > ["a 1", "abcdefGHIjklmnopqrSTUVWXyz 1", "aa 0", "puz 1", "puzz 0", "puzZ 0", "puZ 1", "PuZ 1"] > > > [Answer] # C (44 bytes) `f(char*s){return(*s&=95)?f(s+1)>*s?*s:0:96;}` Test it here: <http://ideone.com/q1LL3E> Posting this because I can't comment yet, otherwise it would be a suggestion to improve the existing C answer because I completely stole the case-insensitive idea from the existing C answer. Returns 0 if the string is not ordered, and a non-zero value if ordered. [Answer] ## Java 8 - 90 89 87 85 chars The idea here is to use a 'reduce' function that tracks the last char and "gives up" when it detects the sequence is not strictly ascending. **golfed:** ``` int f(String s){return s.toLowerCase().chars().reduce(0,(v,c)->(v<0)?v:(c>v)?c:-1);} ``` **ungolfed:** ``` int f(String s){ return s.toLowerCase() .chars() .reduce(0, (v,c) -> (v<0)? v : (c>v)?c:-1); } ``` **example:** ``` System.out.println(new Quick().f("abc")); System.out.println(new Quick().f("aa")); System.out.println(new Quick().f("abcdefGHIjklmnopqrSTUVWXyz")); System.out.println(new Quick().f("puZ")); System.out.println(new Quick().f("Puz")); System.out.println(new Quick().f("cba")); ``` **output:** ``` 99 -1 122 122 122 -1 ``` [Answer] ## VBA (161 bytes) ``` Function t(s As String) t = 0 For i = 2 To Len(s) a = Left(LCase(s), i) If Asc(Right(a, 1)) <= Asc(Right(a, 2)) Then Exit Function Next t = 1 End Function ``` Compares ascii value with previous letter in lowercase, return 0 (false) when its value is smaller / equal and exit function [Answer] # Perl 6, 35 bytes ``` {my@c=.uc.comb;@c [[email protected]](/cdn-cgi/l/email-protection)} ``` This produces a callable block; if I could just assume that `$_` is already set to the desired word, I could delete the surrounding curly braces and lose two more bytes, but probably the only reasonable way to make that assumption would be to run it with `-n` and feed the word as standard input, which would add the two bytes right back. [Answer] # [R](https://www.r-project.org/), 37 bytes ``` all(diff(utf8ToInt(scan(,''))%%32)>0) ``` [Try it online!](https://tio.run/##K/qfZptWmpdckpmfp1Gho1CcnJiHENDT09Os0Kz@n5iTo5GSmZamUVqSZhGS75lXogFSqKGjrq6pqapqbKRpZ6D5v5YrTUMpMSk5JTXN3cMzKzsnNy@/oLAoOCQ0LDyiskpJEyRfUFoVBWGBVDo6Obsoaf4HAA "R – Try It Online") Posting since this is substantially different and shorter than [Michal's R answer](https://codegolf.stackexchange.com/a/47272/86301). Converts the letters to ASCII codepoints with `utf8ToInt`, then takes modulo 32 so that lower and upper letters are converted to the same numbers 1...26. Computes the pairwise differences, and checks that they are all positive. [Answer] # Perl, 27 @hsl's regexp dynamically build. ``` #!perl -p $"="?";@x=a..z;$_=/^@x?$/i ``` Also we can do a reverse match: convert the input into a regexp: `PuZ` => `.*p.*u.*z.*` and then match this to a string of letters in alphabetical order. Result - also 27 characters. ``` #!perl -lp $_=join(s//.*/g,a..z)=~lc ``` [Answer] ## k (6 bytes) ``` &/>':_ ``` `&` returns true if both args are true `/` modifies `&` to apply "over" a list, like a fold in functional languages `>` greater than `':` modifies `>` to apply "each-prior", so returns a vector of booleans stating which elements are greater than their predecessor `_` makes it argument lower case ``` _"puzZ" "puzz" >':_"puzZ" 1110b &/>':_"puzZ" 0b ``` (`0b` means boolean false) ## q (13 bytes) ``` all(>':)lower ``` q is just syntactic sugar on k. `all` is defined as `&/`, and lower is `_` [Answer] # Python, 50 bytes ``` f=lambda x:sorted(set(x.lower()))==list(x.lower()) ``` Try online here: <http://repl.it/c5Y/2> [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda s:eval('"%s"'%'"<"'.join(s.lower())) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKrUsMUdDXUm1WEldVV3JRkldLys/M0@jWC8nvzy1SENTU/N/QVFmXolGmoZSYlJySmqau4dnVnZObl5@QWFRcEhoWHhEZZWSpiYXQlkikPsfAA "Python 2 – Try It Online") Puts `<` symbols between all the letters (converted to lowercase), and then `eval`s it. Python's chained comparison operators are perfectly happy to evaluate the whole thing as one big boolean expression. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ⇩¨=‡Us ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oepwqg94oChVXMiLCIiLCJhXG5hYmNkZWZHSElqa2xtbm9wcXJTVFVWV1h5eiAgXG5hYVxucHV6XG5wdXp6XG5wdXpaXG5wdVpcblB1WiJd) ## Explained ``` ⇩¨=‡Us ⇩¨= # is the lowercase version of the input invariant under: ‡Us # uniquify and sort? ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 36 bytes ``` \S:-maplist(to_lower,S,L),sort(L,L). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/PybYSjc3sSAns7hEoyQ/Pie/PLVIJ1jHR1OnOL@oRMMHyNIDqkpITNDj4gJSSckpqWnuHp5Z2Tm5efkFhUXBIaFh4RGVVRD5glI4IwrCCIAxgFIIRTCxqlIYIxRhgaOTswuEl5KcBLMYSAMA "Prolog (SWI) – Try It Online") Ungolfed: ``` \S :- maplist(to_lower, S, L), % convert each character code in S to lowercase, putting that in a list called L sort(L, L). % Does L sorted and uniquified equal L? ``` ]
[Question] [ Unfortunately [one of the greatest comic book writers](https://en.wikipedia.org/wiki/Stan_Lee) passed away yesterday afternoon. Lots of Hollywood stars, musicians, actors, and many other people are paying tribute to this awesome writer, so we must do something as well. **Challenge** Print The Avengers Logo Note: You may use any other character in place of # other than a space character; while you must use a space character for the space [![enter image description here](https://i.stack.imgur.com/ldz4s.jpg)](https://i.stack.imgur.com/ldz4s.jpg) In ASCII-art ``` ###### ############### ##### ########## #### ####### #### ### #### ### ### ### #### ### ### ### #### ### ### ### #### ### ### ### #### ### ### ### #### ### ### ### ########### ### ### ########### ### ### #### ### ### ### ### ### ### #### #### #### ######## ###### ################# ### ``` **Optional** Who was (in your opinion) his greatest hero and villain in the entire marvel universe? --- Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~62~~ ~~59~~ 58 bytes ``` “ḢE{ɠs{Ƒ0Ṇṁỵ8ỊṢṂƊeLṫfIWẈḞ'ʠJ£ṗɱ\çoȧ?ƒnØẆƥṂ⁷ɱ’b12ĖŒṙḂa⁶s27Y ``` *Thanks to @JonathanAllan for golfing off 1 byte!* [Try it online!](https://tio.run/##AXcAiP9qZWxsef//4oCc4biiRXvJoHN7xpEw4bmG4bmB4bu1OOG7iuG5ouG5gsaKZUzhuatmSVfhuojhuJ4nyqBKwqPhuZfJsVzDp2/Ipz/Gkm7DmOG6hsal4bmC4oG3ybHigJliMTLElsWS4bmZ4biCYeKBtnMyN1n//w "Jelly – Try It Online") ### How it works ``` “ḢE{ɠs{Ƒ0Ṇṁỵ8ỊṢṂƊeLṫfIWẈḞ'ʠJ£ṗɱ\çoȧ?ƒnØẆƥṂ⁷ɱ’ ``` is a bijective base-250 integer literal, which uses the characters in [Jelly's code page](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) as digits. The literal encodes the integer \$\scriptsize 10250938842396786963034911279002199266186481794751691439873548591280332406943905758890346943197901909163\$, which `b12` converts to duodecimal, yielding \$\scriptsize 30b620b40ba54a64771433841333139413468423468423467433467433466b466b465453465363431424b43896860ba3\_{12}\$. There are some zeroes, because 14 spaces (e.g.) are encoded as 3 spaces, 0 hashes, and 11 spaces. This maintains the base small (the largest run consists of 17 hashes), without adding any additional logic to the decoder. `Ė` (enumerate) prefixes every base-12 digit by its 1-based index, then `Œṙ` performs run-length decoding. Now, for each integer in the resulting array, `Ḃ` extracts the least significant bit, then `a⁶` (AND space) replaces ones with spaces, while leaving zeroes unchanged. Finally, `s27` splits the unformatted character array into chunks of length 27, which `Y` separates by linefeeds. [Answer] # [R](https://www.r-project.org/), ~~198~~, ~~173~~, ~~163~~, ~~157~~, ~~144~~, 142 bytes ``` write(rep(rep(c(' ',4),44),utf8ToInt("NFMOJEDJFDGGADCCHDACCCACIDACDFHDBCDFHDBCDFGDCCDFGDCCDFFKDFFKDFEDECDFECFCDCADBDKDCHIFHQJC")-64),1,27,,'') ``` [Try it online!](https://tio.run/##PY1LCgIxEESvIrNJAu1CGdRtpiudz6AieAOZATcqIeLxY1B08V5R1KJyra98LZPO0@PDRauFot5Q33iWeXe@x1vR3UH2x@SQBN5bMAdYZrYcW0IChr99W3@W8YuDa82xMNhiwAgOUcIpcWeWm/a0ovWWSClT6xs "R – Try It Online") Also `R` honors to the great Stan. **Notes :** * instead of the character `#` we've used the character `4` because saves 2 bytes and : + it's a reference to the Fantastic Four and/or the next Avengers 4 movie + it's like we're repeating the logo inside the logo (since `4` seems a mini "slanted" `A`) * -15 bytes thanks to @Giuseppe **Explanation** : Applying a Run Length Encoding (`rle` function) on the characters of the string (excluding `'\n'`) returns 88 repetitions of the alternating `<space>,<hash>,<space>,<hash>,<space>,<hash>...`. The 88 repetitions are all values in the range `[1,17]` hence, summing `64` we get the code points of the letters `[A...Q]` obtaining the string : `"NFMOJEDJFDGGADCCHDACCCACIDACDFHDBCDFHDBCDFGDCCDFGDCCDFFKDFFKDFEDECDFECFCDCADBDKDCHIFHQJC"` Hence the code basically does the opposite operations : ``` v <- utf8ToInt("NFMOJEDJFDGGADC...")-64 # convert the string back to [1...17] vector e <- rep(rep(c(' ',4),44),v) # perform the inverse of rle function obtaining an # expanded vector of <space>'s and <four>'s write(e,1,27,,'') # write the vector to stdout arranging it # in rows of maximum 27 characters ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~71~~ ~~66~~ ~~65~~ 64 bytes ``` 0000000: 95 91 21 12 00 20 08 c0 3a af 90 ff 7f 52 4e 58 ..!.. ..:....RNX 0000010: 58 93 25 d8 8a 27 47 e4 23 66 01 2c ce b1 3c 12 X.%..'G.#f.,..<. 0000020: 5f 5b 17 7c 81 ed 31 28 4e 6e a4 6d 23 ad 5b c2 _[.|..1(Nn.m#.[. 0000030: ae 25 83 9a 94 1a 2f 6f 05 fc e5 f0 73 13 f9 0b .%..../o....s... ``` *Thanks to @ovs for golfing off 1 byte!* [Try it online!](https://tio.run/##jc@7ToMxDAXgnac4C0zIcm5Owlgx8BYQ54IQhQW1Cw//49JWrJzBzpJPx3pQ3c/Xw8e28SUPqKk6qOMBZs/g0hlZ2kTg6bCWW/ApeoBOsXkktsft7uYsODNKlonhuWK0ntCLs5@VC5yYVmYO8L0sMz7pL1/3dDG8GT2OjCGckJZYBeWO0mqAUzFXY8HUKucezy/fp/VGT3Q1ghnKoui1Mbw06yFdIdVOyytUrD46YlzTjHeiu1@AKtHj1YhmsJ36r9C2/QA "Bubblegum – Try It Online") [Answer] # Python 2, 129 bytes ``` 00000000: 2363 6f64 696e 673a 4c31 0a70 7269 6e74 #coding:L1.print 00000010: 2778 da95 9141 0e5c 3021 0803 ef7d 4593 'x...A.\0!...}E. 00000020: feff 8f9b 5d14 5c6e f1b0 f622 7422 2890 ....].\n..."t"(. 00000030: 2e7d 5a09 dc4b 19cb bc53 84d1 4a6a 5960 .}Z..K...S..JjY` 00000040: 116e 3f42 c290 b3f7 c0bc 76cf 549d 6ed8 .n?B......v.T.n. 00000050: f8fa 5f26 0b0e 8c93 d5cb 35f6 b1e7 a939 .._&......5....9 00000060: 9e98 e769 47b9 87d6 cdf5 5c30 3030 32c0 ...iG.....\0002. 00000070: 4029 272e 6465 636f 6465 2827 7a69 7027 @)'.decode('zip' 00000080: 29 ) ``` [Try it online!](https://tio.run/##jZE7b1RBDIV7fsUhSGxSZDRPzzgNDwkhAV1oQBuFOy@yFDersEILIr998WTv9riw3fjz8XGeft4dDvt9xeUD/mL7e3d3P1tcHg56iStYRw7UyYOYGii6Cb44Az1FjWiJQS164EW5r5v5@9Uno7YPm3n37EgwgxFjQp04gI2XyRYKnLbSJe3QeqzwgR2w2iul3qi1fi718Z1aGFYYvfWO1DkjVOMRiojpJmt0shbRS7KJNSCT6katZylnu7PzE8MNHU02hUkzavEZhktGLsEh@WrgJ5oQmAbj8atSH4VwrdSHH1@@LQwvDGNkseveolhZl12PKDoXRCodwXMVP2oSxvzqrXqKX@qzmk86wrglddnULUFn3ZCK3F6DiHGhE7JpERM7Hrfcvjwywki8MEgY3DihRbHfx8xIsRJK7UGccVrcHcmWox@b90@M9bDypCMKw2vL8hwrb/UUQI76sbPJRsRJ4FFLh9cXK1WbPLidr/5stquFkYanIvO/4uIf) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~71~~ ~~68~~ 67 bytes ``` ←⁸↙P⁵↘←⁴↓P³↙F⁹⟦³⟧→P⁴↘P⁶↘‖OM←←¹⁷↘F⁹«P⁺³›ι³↑P⁴↗¿⁼ι²B⁸±²»↘→UO³¦¹⁴UMKA# ``` [Try it online!](https://tio.run/##bZBNT8MwDIbP3a@IxsWRymHrgH2c@BIXYNUkTohDVtwuwmtKlhYkxG8PS0erRsotsh8/ee1sJ3SmBFmbalkaWD5ibmI256vRk2oQlnfqq3Q1V6jJyKrFLrz@RhY7B3iKmYf440lInyvNYMHZyfKavPVQ5x8YZsEAA@AyCGwwJ8zMukFNooKe@Y/gLTC5Ciq6mD@jaPBdSvUBkpg9aBQGNciYJZwf8ehkeKnat79A3@vckcwZ3H/Wgg7OMOWc3ahvmMfsGYujF6ZO@Rva3DvUekuqLFyeSXsoUd2q/V6U75AiflwTAY/Z@GzMV9ba84b@AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ←⁸↙P⁵↘←⁴↓P³↙F⁹⟦³⟧→P⁴↘P⁶ ``` Output half of the circle. ``` ↘‖OM←←¹⁷↘ ``` Reflect it and draw in the bottom. ``` F⁹«P⁺³›ι³↑P⁴↗¿⁼ι²B⁸±²» ``` Draw the left arm and crossbar of the A. ``` ↘→UO³¦¹⁴ ``` Draw the right arm of the A. ``` UMKA# ``` Change all the characters to `#`s. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~244~~ ~~243~~ 242 bytes ``` #define z <<10|117441415 x[]={8064,2097088,8142832,31473596,58751886,30 z,60 z,60 z,120 z,120 z,255 z,255 z,480 z,448 z,63897630,33423612,2097136,1835008};b(_,i){i&&b(_/2,i-1),putchar(32+_%2*3);}main(_){_<19&&b(x[_-1],27)&puts("")&main(_+1);} ``` [Try it online!](https://tio.run/##Rc3dasJAEIbhc68iWAxZndCdn92dYLwSkUWjtnugFG1BjF57TCroycvH8MA05VfTdN3HdrdPx112zeoa7Q0xiKCgG12Wq0Wr1guQrYJVBUUhZQJGCewqD06DQ1UPbLMr@FeQ3iXnXhUdLiI6QNYqeLbALMQe6f8NsgdUdtbqfb4pIiTTpjzv1ydBKtHAz99v870@FUyzOKEpm/n9sE7HIpo21lgN9rKMJa6Agsl7fS7GY5M/zQx73nUP "C (gcc) – Try It Online") -1 Thanks to Peter Cordes -1 Thanks to ceilingcat Uses bit compression. ### Explanation: The goal is to print a set of numbers in binary using space and # as digits which represent the logo. A bit of bash magic converts the logo to binary masks: ``` echo "ibase=2;$(<code which echoes the logo [see my bash solution for example]> | tr ' #' 01)" | bc ``` This results in the binary 'numbers' being: ``` 8064,2097088,8142832,31473596,58751886,117472135,117502855,117502855,117564295,117564295,117702535,117702535,117932935,117900167,63897630,33423612,2097136,1835008 ``` There is an obvious pattern in the middle where every line contains `### ### ###` We can save some space by compressing that middle section based on saving that pattern and OR-ing against it. In addition, all of those lines merely add some stuff to the left of the middle section, so we make the `z` macro which takes `??????????????` and converts it into `###??????????????### ###`. This involves bitshifting left by 10 and OR-ing with the binary of that pattern, which is 117441415. Now we can more easily understand the code: ``` #define z <<10|117441415 // Define z to be the compression defined above x[]={ // Define x to be an array storing each line's number 8064,2097088,8142832, // The first 5 lines are uncompressed 31473596,58751886, 30 z,60 z,60 z,120 z, // The middle 9 lines are z-compressed 120 z,255 z,255 z,480 z, 448 z, 63897630,33423612, // The last 4 lines are uncompressed 2097136,1835008}; b(_,i){ // we also need a function to print n-bit binary numbers i&& // i is the bit counter, we recurse until its zero b(_/2,i-1), // each recursive call halves the input and decrements i putchar(" #"[_%2]);} // this just prints the correct character main(_){ // this is the main function, called as ./? will have 1 in _ (argc) _<19? // if _ is less than 19 then... b(x[_-1],27), // print the binary expansion of x[_-1] puts(""), // print a new line main(_+1) // recurse with _++ :0;} ``` [Answer] # T-SQL, ~~341~~ 338 bytes ``` DECLARE @ CHAR(2000)=REPLACE(REPLACE(REPLACE( 'PRINT SPACE(14*6&$6*15&$4*5$4*10&$2*4$7*7$1*4&$1*3$8*4$1*3$3*3&*3$9*4$1*3$4 *3&*3$8*4$2*3$4*3&*3$8*4$2*3$4*3&*3$7*4$3*3$4*3&*3$7*4$3*3$4*3&*3$6*11$4*3& *3$6*11$4*3&*3$5*4$5*3$4*3&*3$5*3$6*3$4*3&$1*4$2*4$11*4&$2*8$9*6&$6*17&$6*3)' ,'*',')+REPLICATE(''#'','),'$',')+SPACE('),'&',')+('' ''')EXEC(@) ``` The first 4 line breaks are for readability only, the final line break is part of a string literal. Similar to my [Adam West tribute](https://codegolf.stackexchange.com/a/126472/70172), I've manually encoded a long string, and made the following replacements: * `*7` gets replaced by `+REPLICATE('#',7)` * `$4` gets replaced by `+SPACE(4)` * `&` gets replaced by a line break inside quotes This results in a *massive* SQL command string: ``` PRINT SPACE(14)+REPLICATE('#',6)+(' ')+SPACE(6)+REPLICATE('#',15)+(' ')+SPACE(4)+REPLICATE('#',5)+SPACE(4)+REPLICATE('#',10)+(' ')+SPACE(2)+REPLICATE('#',4)+SPACE(7)+REPLICATE('#',7)+SPACE(1)+REPLICATE('#',4)+(' ')+SPACE(1)+REPLICATE('#',3)+SPACE(8)+REPLICATE('#',4)+SPACE(1)+REPLICATE('#',3)+SPACE(3)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(9)+REPLICATE('#',4)+SPACE(1)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(8)+REPLICATE('#',4)+SPACE(2)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(8)+REPLICATE('#',4)+SPACE(2)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(7)+REPLICATE('#',4)+SPACE(3)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(7)+REPLICATE('#',4)+SPACE(3)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(6)+REPLICATE('#',11)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(6)+REPLICATE('#',11)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(5)+REPLICATE('#',4)+SPACE(5)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+REPLICATE('#',3)+SPACE(5)+REPLICATE('#',3)+SPACE(6)+REPLICATE('#',3)+SPACE(4)+REPLICATE('#',3)+(' ')+SPACE(1)+REPLICATE('#',4)+SPACE(2)+REPLICATE('#',4)+SPACE(11)+REPLICATE('#',4)+(' ')+SPACE(2)+REPLICATE('#',8)+SPACE(9)+REPLICATE('#',6)+(' ')+SPACE(6)+REPLICATE('#',17)+(' ')+SPACE(6)+REPLICATE('#',3) ``` Which, when run, produces the necessary output. Long, but still better than my best set-based solution (**463 bytes**): ``` SELECT SPACE(a)+REPLICATE('#',b)+SPACE(c)+REPLICATE('#',d) +SPACE(e)+REPLICATE('#',f)+SPACE(g)+REPLICATE('#',h) FROM(VALUES(7,0,7,6,0,0,0,0),(6,8,0,7,0,0,0,0),(4,5,4,5,0,5,0,0),(2,4,7,7,1,4,0,0), (1,3,8,4,1,3,3,3),(0,3,9,4,1,3,4,3),(0,3,8,4,2,3,4,3),(0,3,8,4,2,3,4,3), (0,3,7,4,3,3,4,3),(0,3,7,4,3,3,4,3),(0,3,6,6,0,5,4,3),(0,3,6,6,0,5,4,3), (0,3,5,4,5,3,4,3),(0,3,5,3,6,3,4,3),(1,4,2,4,5,0,6,4),(2,8,9,6,0,0,0,0), (6,9,0,8,0,0,0,0),(6,3,0,0,0,0,0,0))t(a,b,c,d,e,f,g,h) ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~74~~ ~~73~~ 71 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` qc2-Az↓n⁴╫m┬ff╷\_↘Tt)%⁵6>Yy7pQ∔I%SIŗ+T^≤?↔↖¶8^`O‾+O│≤n≡j↶82„2┬{ #@]∑‾+n ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjUxJXVGRjQzJXVGRjEyJXVGRjBEJXVGRjIxJXVGRjVBJXUyMTkzbiV1MjA3NCV1MjU2QiV1RkY0RCV1MjUyQyV1RkY0NiV1RkY0NiV1MjU3NyV1RkYzQ18ldTIxOThUJXVGRjU0JTI5JTI1JXUyMDc1NiV1RkYxRSV1RkYzOXk3cCV1RkYzMSV1MjIxNCV1RkYyOSV1RkYwNVNJJXUwMTU3JXVGRjBCVCV1RkYzRSV1MjI2NCUzRiV1MjE5NCV1MjE5NiVCNiV1RkYxOCU1RSU2ME8ldTIwM0UrJXVGRjJGJXUyNTAyJXUyMjY0biV1MjI2MWoldTIxQjY4MiV1MjAxRSV1RkYxMiV1MjUyQyV1RkY1QiUyMCUyMyV1RkYyMCV1RkYzRCV1MjIxMSV1MjAzRSV1RkYwQiV1RkY0RQ__,v=8) [Answer] # JavaScript (ES6), ~~173~~ 170 bytes ``` _=>`tc du 9a9k 58fe38 36h83676 6j83!h85!h85!f87!f87!dm96 6dm96 6b8b!b6d696 3858n8 5gjc dy d6`.split`!`.join`696 6`.replace(/./g,c=>'# '[(k=parseInt(c,36))&1].repeat(k/2)) ``` [Try it online!](https://tio.run/##JYxLDoIwGIT3PYXEREqCEG0oPwvYewZjbOmDpy2BauLpseBiJpNvJtPzD1/E3E3ubKxUqy7XZ1kxJ5B8o4IXA8pAKwKI0BYIzSmiPZCghWyXhnyXfBW@@XsNdVBTSX0mkIEBlDW9//siSVmyTGPnWMCS3naGbSMPZzWNXCicJmkTi7IKj4fwjody4vOibsZhERMaRafLY5sq7vCQXqNoFdYsdlTJaBussQc/ "JavaScript (Node.js) – Try It Online") --- # [Node.js](https://nodejs.org), 163 bytes Provided that an array of strings is a valid output: ``` _=>Buffer(`.&-/*%$*&$''!$##($!###!#)$!#$&($"#$&($"#$&'$##$&'$##$&&+$&&+$&%$%#$&%#&#$#!$"$+$#()&(1*#2`).map(c=>s+='# '[x^=1].repeat(c-32),s=x='')&&s.match(/.{27}/g) ``` [Try it online!](https://tio.run/##PYpBDoIwFESvIvxP@wtSAi5clYXXMCqkFtQgEIqGxHj22sToYt7kZeZWP2urp@s4p/1wNq5R7qTK3aNpzESVZGkWRxgz5DxAAMIAAAIQvpERhn9yv/7Ikm8ijLxFwAAhwBATBBKM8hiKSsh7PZJWpU0UhxXfL0eVH@RkRlPPpNNNIdZWLYpzwZj151lfKJOvYvvOWuH00NuhM7IbWmpICPcB "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~101~~ ~~88~~ 64 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „# •∍ΔÎë,½=bOÅ.âαUΔ'òõƶαÔγλ#xÆ]~”FbćÁ˜Ð”wнQ_wā©•12вεN>yи}˜èJ27ô» ``` -24 bytes by creating a port of [*@Dennis♦*' Jelly answer](https://codegolf.stackexchange.com/a/175891/52210). [Try it online.](https://tio.run/##AXQAi/9vc2FiaWX//@KAniMg4oCi4oiNzpTDjsOrLMK9PWJPw4Uuw6LOsVXOlCfDssO1xrbOscOUzrPOuyN4w4ZdfuKAnUZixIfDgcucw5DigJ130L1RX3fEgcKp4oCiMTLQss61Tj550Lh9y5zDqEoyN8O0wrv//w) **Explanation:** ``` „# # Push string "# " •∍ΔÎë,½=bOÅ.âαUΔ'òõƶαÔγλ#xÆ]~”FbćÁ˜Ð”wнQ_wā©• '# Push compressed integer 10250938842396786963034911279002199266186481794751691439873548591280332406943905758890346943197901909163 12в # Convert to Base-12 as list: [3,0,11,6,2,0,11,4,0,11,10,5,4,10,6,4,7,7,1,4,3,3,8,4,1,3,3,3,1,3,9,4,1,3,4,6,8,4,2,3,4,6,8,4,2,3,4,6,7,4,3,3,4,6,7,4,3,3,4,6,6,11,4,6,6,11,4,6,5,4,5,3,4,6,5,3,6,3,4,3,1,4,2,4,11,4,3,8,9,6,8,6,0,11,10,3] ε } # Map each `y` to: N> # The index+1 yи # Repeated `y` amount of times ˜ # Flatten the list è # Index each in the string "# " (with automatic wraparound) J # Join everything together 27ô # Split into parts of length 27 » # And join by newlines ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression of the integer and list works. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~174~~ ~~168~~ ~~164~~ 160 bytes -6 bytes thanks to Dennis. ``` i,j;main(l){while(i="NFMOJEDJFDGGADCCHDACCCACIDACDFHDBCDFHDBCDFGDCCDFGDCCDFFKDFFKDFEDECDFECFCDCADBDKDCHIFHQJC"[j++]&63)for(;i;)putchar(l++%28?--i,35-j%2*3:10);} ``` [Try it online!](https://tio.run/##PYldC4IwGEb/i2BszUEpRTQi5vtuTqWi6@hCRuXEPpCii@i3LyHq4pzDw2P5yVrvXdSIc@UupKWvZ@3aA3GLYK1Xm0JhoTHLJAIYlAAgIe@L2mD6d9a/P@vyi0LVLwUaECSmWCKYXJttAcGuYWw/mCb0eO2IcILeHndbVx1pGQvj2ZJzFyUT3oTxMJmPR1S8vf8A "C (gcc) – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 170 bytes ``` /+/\/\///*/ +)/'$# +(/"$!+'/" +&/!#+%/"! !+$/*!+"/**+!/###/""('* (!!!' "&#"!!&" $#'$& &* !""& ! $ !"'& !%""&$%""&$%)$%)$%(&#%(&#%'&'!%'!"$"! &$#") $&#"'!!* (!!&#" "$ ``` [Try it online!](https://tio.run/##JU05DsMwDNv1CpFSJMca9KEuGQp06Jb/wzVS8AC5kPf3uj/ve62ufm10z1ats9NNazQdlU2taFgdTQjKe6LYcxbazJocOWUASBWGEQiKW3poTFGQoVBXAXOnY3f/2/lwhD3KSBwJ@r7RcOMpvucSeOZ3FPpaPw "/// – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~192~~ 176 bytes ``` dc<<<"16i2o81C0000 81FFFF0 9FE00FC BCF001E F070387 F078387 F03FF87 F03FF87 F01E387 F01E387 F00F387 F00F387 F007B87 B807B8E 9E03FBC 87C3FF0 81FFFC0 8001F80f"|tr 01 ' #'|cut -c2- ``` [Try it online!](https://tio.run/##Xc2xDsIwDIThV7HK0KnSuZGIK2WKFb8HBCGYkKBsfffgwFRu@abTfz69bq1dakpp4ON9fggrfCRsPtBiBTClrAZwIUNEkNiVn8FsJ5ewE/ZnzG6WbqGl@DErSdTQe9@uul4zwXXY1ieBaaTDuNX3SlOdp9Y@ "Bash – Try It Online") -16 thanks to manatwork This is similar to my C answer, except it just uses a raw base-16 compression and passes it through bc, then uses tr to convert 1 to # and 0 to space. Each row has 1 appended to it and stripped off of it to maintain alignment. Unfortunately `dc` is shorter than `bc`. [Answer] ## Haskell, ~~170~~ 163 bytes Edit: -7 bytes thanks to @Ørjan Johansen ``` m=<<"Mc Ul WeWg YdTgZa ZcSdZcX cRdZcW cSdYcW cSdYcW cTdXcW cTdXcW cUkW cUkW cVdVcW cVcUcW ZdYdPa YhRc Un U " m ' '="###\n" m c=(' '<$['Z','Y'..c])++('#'<$['a'..c]) ``` [Try it online!](https://tio.run/##TYxLDoIwFEXnruKFmhSDsgK6A00MUKAVB80rH0NpiOD2rUVjwuSenDO4vZqHxhjXstqNLEmCCwI3UDZlB0LnnVQgMdMSK8DUowRvYoNcVxvw4T@FLtZQIPeQWuirAtGn/t0Ch2A3AgXKAkJIbVdDFvqQ7G9U0iMVNI7xfoiikJJvVL/gRvWwwGB6LdnyPFto3Rtbo7rZnXCaPg "Haskell – Try It Online") Spaces are encoded as uppercase characters (length: `Z` down to char), hash signs as lowercase characters (length: `a` to char) and the last three `#` of each line plus newline as a space. Function `m` decodes it. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~136~~ 112 bytes ``` :128['?@~p<?x ?aB ~ <|xpqpac`?@~x> q|<!Ca`||?x'.ords].base(2)~~TR/1/ /.comb(27)>>.say ``` [Try it online!](https://tio.run/##K0gtyjH7/9/K0MgiWt2@3qG@joGhvsCGwZ69gkXGPpFPsN5JjrmOx4a9RqKCv6CwQD4xOcGegd2hjoGfscJOjrmwxkbRuT4xgb@GvYaBwb5CXS@/KKU4Vi8psThVw0izri4kSN9QX0FfLzk/N0nDyFzTzk6vOLHy/38A "Perl 6 – Try It Online") Parses a base 128 number from the ordinal values of the compressed string, converts to base 2 and replaces the `1`s with spaces. This uses zeroes as the main character. The string has like 9 null bytes, which was a bitch to type up in TIO. I would have used base 127 for the same amount of bytes, but no nulls, but that has a carriage return, which seems to be impossible to distinguish from a newline `:(` ### Explanation: ``` :128['...'.ords] # Convert the bytes of the string to base 128 .base(2) # Convert to base 2 ~~TR/1/ / # Translate 1s to spaces # Alternatively, this could be .split(1) .comb(27) # Split to strings of length 27 >>.say # Print each on a newline ``` [Answer] # [J](http://jsoftware.com/), 130 128 bytes ``` echo' #'{~18 27$;(_243{.2#.inv 92x#._32+a.i.])&>'!TYPW.ajz i8hIhXl''3lOH8GvV.C2Z{r/=,G';'"a*2ZDxRplkh2tzRakz.?ZwVmeOT6L^lFB^eyT' ``` [Try it online!](https://tio.run/##y/r/PzU5I19dQVm9us7QQsHIXMVaI97IxLhaz0hZLzOvTMHSqEJZL97YSDtRL1MvVlPNTl0xJDIgXC8xq0oh0yLDMyMiR13dOMffw8K9LEzP2SiqukjfVsdd3VpdKVHLKMqlIqggJzvDqKQqKDG7Ss8@qjwsN9U/xMwnLsfNKS61MkT9/38A "J – Try It Online") ## Initial solution # [J](http://jsoftware.com/), 164 bytes ``` echo' #'{~18 27$,#:849239965469633263905532594449192007713271791872263657753301928240007 12380965417202148347902847903517734495157419855048834759608223758433386496x ``` [Try it online!](https://tio.run/##Fcw7CkJBEETRrQw84SUG3VX9dTsiiImpILj1cSappA73Nefj/nyf4zi/P62BvFyPW1mD3eEWHSSCLe6Et5m1NkQylUjN1kosEJ7ppKyzYLLAULBkRzQhUCtatqD20jWTK@bqadrlLlZbeIcUwPQykhXW8ZnzDw "J – Try It Online") [Answer] # [PHP](https://php.net/), ~~286~~ ~~212~~ ~~209~~ 208 bytes ``` <?php foreach(str_split('000680018y4g04uj1s0iql6k0yz98u1xxu2v1xyhs71xyhs71xzt6v1xzt6v1y2ruv1y2ruv1y7pmv1y70cn121jq60jwdto018y5s13bwg',6)as $i)echo str_replace(0,' ',str_pad(base_convert($i,36,2),27,0,0))." "; ``` [Try it online!](https://tio.run/##Pc7dCoIwGMbx865iSOAGI96tmkZBlxJzLqdZzn340c0bQnXyO/gfPDzW2GW5XK2x6N45LZXBPribt20dcAoAIgdg@Xyo4BAb5qHuW/GA@X3KI5umyAc2zcZnP99BDF9n7uLfzD5XQb0YZ00voBnL0K3LR8/2xVilVBDp0bYmWpkOrSectq1UGgNNUUrXYmWJC@n1TXWvQbuAtzXdC8oJ5RkFCoTskk1yXpYP "PHP – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 181 bytes ``` say+(sprintf"%28b",oct"0x$_")=~y/10/# /r for"0003f0003fff800f87fe03c07f78700f71ce00f70ee01e70ee01e70ee03c70ee03c70ee07ff0ee07ff0ee0f070ee0e070e79e003c3fc01f803fffe00380000"=~/.{7}/g ``` [Try it online!](https://tio.run/##Tc1BCsIwFATQq5SooKjNxJgmLnoEzyAa8qUgTUm7sIg9ujHpqpt5/Fn86Vx4qRj7@7jf9l1o2oHY5mQe7ODtwPBe39iunkYuwFcFDwX5wABImoPIAGQ0OUgLTdrodGthXQbOQbgl0i7RRAsIc@ky@pIeSCvJQqSJPJSLNAaweuLlR3/5M8ZKyXMlVaKSKX6@Gxrf9vF4VSUE/g "Perl 5 – Try It Online") [Answer] [**MATLAB**](https://se.mathworks.com/products/matlab.html) **: 144 Bytes** ``` reshape(repelem([repmat(' #',1,44),' '],'NFMOJEDJFDGGADCCHDACCCACIDACDFHDBCDFHDBCDFGDCCDFGDCCDFFKDFFKDFEDECDFECFCDCADBDKDCHIFHQJCR'-64),27,[])' ``` [Try it online!](https://tio.run/##PYnLCsIwFER/peDiJhAXleBzld6bR1NU7LZkUSTgwmJpi78fA6KLOXOGed2X/h1TmuL86MfIpjjGZxxm1mUb@oVBsQJRCim5gAKC6Mrj/nCCizlfvSZvyFpFiI4UIiqsc5NxVP1p8/ujab7RpPPSaJBQUUUNoauNu3lsYb2VgYvNTnSBQ0of) (Technically in Octave) **Explanation:** This uses the same strategy as digEmAll in R, just with MATLAB syntax. The main difference is that MATLAB has automatic conversion from characters to integers. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 199 bytes ``` _=>{var r="";for(int i=0,j,k=0;i<88;i++)for(j=0;j++<"0(/1,'&,(&))#&%%*&#%%%#%+&#%&(*&$%&(*&$%&()&%%&()&%%&((-&((-&('&'%&('%(%&%#&$&-&%*+(*3,%"[i]-34;){r+=i%2<1?' ':'#';if(++k%27<1)r+='\n';}return r;} ``` [Try it online!](https://tio.run/##bU/JasMwFLznK4Sdp8Wy0yyFhspOD4WeWijk0EMaiuoqRllkkJRACf52V4mpe@nAm7fMm8OULitrq9pyL51Dr7aurDwMUMD5yhc4L70u0anWX@hFakOdt9pUqzWStnKs//tzXLD8dl4dRk9HU@adIe3aAn1Kf5AGFe1HsTifpEW2iCKxqS3VxiNdjNNtuivGQufzudCcs4u0DYct53k0pjeTlOCUYsZiDJDgGABi4KFjmuBhzyyov0yzrggmYSNAAUOMhzjDkHCazFKIVnqdzW4FO1teaJjmkweCyD2JidAbyvkOpnf5hAWRvBsiGqv80RpkRdOKwX/RH2vj6r0avVntFe1C02jpQ/RnpSLGRO9qrlPT/gA "C# (.NET Core) – Try It Online") Uses the same approach as my solution to the [tribute to Adam West](https://codegolf.stackexchange.com/a/126301/70347). [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 726 723 bytes *-3 bytes thanks to [@squid](https://codegolf.stackexchange.com/users/85755/squid)* ``` {iii}ii{c}cccciccccccddd{dd}c{ii}iicccccci{c}cccccddd{dd}c{ii}iiccccicccccdcccci{c}ddd{dd}c{ii}iicciccccdcccccccicccccccdciccccddd{dd}c{ii}iicicccdcccccccciccccdcicccdcccicccddd{dd}c{ii}iiicccdccccccccciccccdcicccdccccicccddd{dd}c{ii}iiicccdcccccccciccccdccicccdccccicccddd{dd}c{ii}iiicccdcccccccciccccdccicccdccccicccddd{dd}c{ii}iiicccdccccccciccccdcccicccdccccicccddd{dd}c{ii}iiicccdccccccciccccdcccicccdccccicccddd{dd}c{ii}iiicccdcccccci{c}cdccccicccddd{dd}c{ii}iiicccdcccccci{c}cdccccicccddd{dd}c{ii}iiicccdccccciccccdcccccicccdccccicccddd{dd}c{ii}iiicccdcccccicccdccccccicccdccccicccddd{dd}c{ii}iiciccccdcciccccd{c}ciccccddd{dd}c{ii}iicciccccccccdccccccccciccccccddd{dd}c{ii}iicccccci{c}cccccccddd{dd}c{ii}iicccccciccc ``` [Try it online!](https://tio.run/##tZJBDoAgDARf5KNMV@OePRLejggpAkLwIE040B1oYYttxc7zWJwzJC1pxIoPSggABrBighZzijTESECpGmBSnwp@z8ZlzEg9pzm@8IKu8RGvXU3i06Pn8MGNv7DMoE/V8wJ9vvgxwd1Jy/I0EbWVgzHsyH45dwE "Deadfish~ – Try It Online") --- Having never seen/read anything Marvel and only relying on spoilers, it seems that Thanos is the best. [Answer] ## [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse) - 16913 bytes ``` 0 0 0 1 1 0 0 0 1 0 1 2 0 0 0 2 1 0 3 1 0 0 3 0 1 0 1 0 1 0 1 1 4 1 0 0 4 0 1 5 1 0 0 5 0 0 6 1 0 0 6 0 1 7 1 0 0 7 0 0 8 1 0 0 8 0 1 9 1 0 0 9 0 0 10 1 0 0 10 0 1 11 1 0 0 11 0 0 12 1 0 0 12 0 1 13 1 0 0 13 0 0 14 1 0 0 14 0 1 15 1 0 0 15 0 1 16 0 0 0 16 0 1 17 0 0 0 17 1 1 18 0 0 0 18 1 0 1 1 0 1 1 1 0 19 1 0 0 19 0 0 20 1 0 0 20 0 0 21 1 0 0 21 0 1 22 1 0 0 22 0 0 23 1 0 0 23 0 0 2 0 0 1 2 0 0 24 0 0 0 24 0 1 25 0 0 0 25 0 1 26 0 0 0 26 0 1 27 0 0 0 27 1 1 28 0 0 0 28 0 1 3 0 0 1 3 1 1 4 0 0 1 4 0 0 5 1 0 1 5 0 0 29 0 0 0 29 0 0 6 0 0 1 6 0 0 30 0 0 0 30 0 0 31 0 0 0 31 1 0 32 1 0 0 32 0 1 7 1 0 1 7 1 1 33 1 0 0 33 0 1 34 1 0 0 34 0 0 35 1 0 0 35 0 1 36 1 0 0 36 0 1 37 0 0 0 37 0 1 38 0 0 0 38 1 1 39 0 0 0 39 1 0 8 1 0 1 8 1 0 40 1 0 0 40 0 0 41 1 0 0 41 0 0 42 1 0 0 42 0 1 43 1 0 0 43 0 0 44 1 0 0 44 0 1 45 1 0 0 45 0 0 46 1 0 0 46 0 1 47 1 0 0 47 0 0 48 1 0 0 48 0 1 49 1 0 0 49 0 0 50 1 0 0 50 0 1 51 1 0 0 51 0 0 52 1 0 0 52 0 1 53 1 0 0 53 1 1 54 0 0 0 54 0 1 9 0 0 1 9 1 1 10 0 0 1 10 0 0 11 0 0 1 11 1 0 55 0 0 0 55 0 0 12 0 0 1 12 1 0 56 0 0 0 56 0 0 13 0 0 1 13 0 0 57 1 0 0 57 0 1 58 0 0 0 58 1 0 59 0 0 0 59 0 1 14 0 0 1 14 1 1 60 0 0 0 60 0 1 15 0 0 1 15 0 1 61 0 0 0 61 0 1 16 0 0 1 16 0 0 62 1 0 0 62 0 0 63 1 0 0 63 0 0 64 1 0 0 64 0 1 65 1 0 0 65 0 1 66 0 0 0 66 0 1 67 0 0 0 67 1 1 68 0 0 0 68 1 0 17 1 0 1 17 1 0 69 1 0 0 69 0 0 70 1 0 0 70 0 0 71 1 0 0 71 0 1 72 1 0 0 72 0 1 73 0 0 0 73 0 1 18 0 0 1 18 0 1 19 0 0 1 19 0 0 74 1 0 0 74 0 0 75 1 0 0 75 0 0 76 1 0 0 76 0 0 77 1 0 0 77 0 1 78 0 0 0 78 0 1 79 0 0 0 79 0 1 80 0 0 0 80 1 1 81 0 0 0 81 1 0 20 1 0 1 20 1 0 82 1 0 0 82 0 0 83 1 0 0 83 0 0 84 1 0 0 84 0 1 85 1 0 0 85 0 0 86 1 0 0 86 0 1 87 1 0 0 87 0 0 88 1 0 0 88 0 1 89 1 0 0 89 0 0 90 1 0 0 90 0 0 21 0 0 1 21 0 0 91 0 0 0 91 0 1 92 0 0 0 92 0 1 93 0 0 0 93 0 1 94 0 0 0 94 1 1 95 0 0 0 95 0 1 22 0 0 1 22 1 1 23 0 0 1 23 0 0 24 1 0 1 24 0 0 96 0 0 0 96 0 0 25 0 0 1 25 0 0 97 0 0 0 97 0 0 98 0 0 0 98 1 0 99 1 0 0 99 0 1 26 1 0 1 26 1 1 100 0 0 0 100 0 1 101 0 0 0 101 0 1 102 0 0 0 102 0 1 103 0 0 0 103 1 1 104 0 0 0 104 1 0 27 1 0 1 27 1 0 105 1 0 0 105 0 0 106 1 0 0 106 0 0 107 1 0 0 107 0 1 108 0 0 0 108 0 1 109 0 0 0 109 0 1 28 0 0 1 28 0 1 29 0 0 1 29 0 0 110 1 0 0 110 0 0 111 1 0 0 111 0 0 112 1 0 0 112 0 0 113 1 0 0 113 0 1 114 1 0 0 114 0 0 115 1 0 0 115 0 1 116 1 0 0 116 0 1 117 0 0 0 117 0 1 118 0 0 0 118 1 1 119 0 0 0 119 1 0 30 1 0 1 30 1 0 120 1 0 0 120 0 0 121 1 0 0 121 0 0 122 1 0 0 122 0 1 123 1 0 0 123 0 0 124 1 0 0 124 0 1 125 1 0 0 125 0 1 126 0 0 0 126 0 1 31 0 0 1 31 0 1 32 0 0 1 32 0 0 127 1 0 0 127 1 1 128 0 0 0 128 1 0 33 1 0 1 33 1 0 129 1 0 0 129 0 0 130 1 0 0 130 0 0 131 1 0 0 131 0 0 34 0 0 1 34 0 0 132 0 0 0 132 0 1 133 0 0 0 133 0 1 134 0 0 0 134 0 1 135 0 0 0 135 1 1 136 0 0 0 136 0 1 35 0 0 1 35 1 1 36 0 0 1 36 0 0 37 1 0 1 37 0 0 137 0 0 0 137 0 0 38 0 0 1 38 0 0 138 0 0 0 138 0 0 139 0 0 0 139 1 0 140 1 0 0 140 0 1 39 0 0 1 39 1 1 141 0 0 0 141 0 1 142 0 0 0 142 0 1 143 0 0 0 143 0 1 144 0 0 0 144 1 1 145 0 0 0 145 1 0 40 1 0 1 40 1 0 146 1 0 0 146 0 0 147 1 0 0 147 0 1 148 0 0 0 148 0 1 41 0 0 1 41 0 1 42 0 0 1 42 0 0 149 1 0 0 149 0 0 150 1 0 0 150 0 0 151 1 0 0 151 0 0 152 1 0 0 152 0 1 153 1 0 0 153 0 0 154 1 0 0 154 0 1 155 1 0 0 155 0 0 156 1 0 0 156 0 1 157 0 0 0 157 0 1 158 0 0 0 158 0 1 159 0 0 0 159 1 1 160 0 0 0 160 1 0 43 1 0 1 43 1 0 161 1 0 0 161 0 0 162 1 0 0 162 0 0 163 1 0 0 163 0 1 164 0 0 0 164 0 1 165 0 0 0 165 0 1 44 0 0 1 44 0 1 45 0 0 1 45 0 0 166 1 0 0 166 1 1 167 0 0 0 167 1 0 46 1 0 1 46 1 0 168 1 0 0 168 0 0 169 1 0 0 169 0 1 170 0 0 0 170 0 1 47 0 0 1 47 0 1 48 0 0 1 48 0 0 171 1 0 0 171 0 0 172 1 0 0 172 0 0 173 1 0 0 173 0 1 174 0 0 0 174 0 1 175 0 0 0 175 1 1 176 0 0 0 176 1 0 49 1 0 1 49 1 0 177 1 0 0 177 0 0 178 1 0 0 178 1 1 179 0 0 0 179 0 1 50 0 0 1 50 1 1 51 0 0 1 51 0 0 52 0 0 1 52 1 0 180 0 0 0 180 0 0 53 0 0 1 53 1 0 181 0 0 0 181 0 0 54 0 0 1 54 0 0 182 1 0 0 182 0 1 183 0 0 0 183 1 0 184 0 0 0 184 0 1 55 0 0 1 55 1 1 185 0 0 0 185 0 1 56 0 0 1 56 0 1 186 0 0 0 186 0 1 57 0 0 1 57 1 1 187 0 0 0 187 1 0 58 1 0 1 58 1 0 188 1 0 0 188 0 0 189 1 0 0 189 0 1 190 0 0 0 190 0 1 59 0 0 1 59 0 1 60 0 0 1 60 0 0 191 1 0 0 191 0 0 192 1 0 0 192 0 0 193 1 0 0 193 0 0 194 1 0 0 194 0 1 195 1 0 0 195 0 0 196 1 0 0 196 0 1 197 1 0 0 197 0 0 198 1 0 0 198 0 1 199 1 0 0 199 0 1 200 0 0 0 200 0 1 201 0 0 0 201 1 1 202 0 0 0 202 1 0 61 1 0 1 61 1 0 203 1 0 0 203 0 0 204 1 0 0 204 0 0 205 1 0 0 205 0 1 206 0 0 0 206 0 1 207 0 0 0 207 0 1 62 0 0 1 62 0 1 63 0 0 1 63 0 0 208 1 0 0 208 1 1 209 0 0 0 209 1 0 64 1 0 1 64 1 0 210 1 0 0 210 0 0 211 1 0 0 211 0 1 212 0 0 0 212 0 1 65 0 0 1 65 0 1 66 0 0 1 66 0 0 213 1 0 0 213 0 0 214 1 0 0 214 0 0 215 1 0 0 215 0 0 216 1 0 0 216 0 1 217 0 0 0 217 0 1 218 0 0 0 218 0 1 219 0 0 0 219 1 1 220 0 0 0 220 1 0 67 1 0 1 67 1 0 221 1 0 0 221 0 0 222 1 0 0 222 1 1 223 0 0 0 223 0 1 68 0 0 1 68 1 1 69 0 0 1 69 0 0 70 0 0 1 70 1 0 224 0 0 0 224 0 0 71 0 0 1 71 1 0 225 0 0 0 225 0 0 72 0 0 1 72 0 0 226 1 0 0 226 0 1 227 0 0 0 227 1 0 228 0 0 0 228 0 1 73 0 0 1 73 1 1 229 0 0 0 229 0 1 74 0 0 1 74 0 1 230 0 0 0 230 0 1 75 0 0 1 75 1 1 231 0 0 0 231 1 0 76 1 0 1 76 1 0 232 1 0 0 232 0 0 233 1 0 0 233 0 1 234 0 0 0 234 0 1 77 0 0 1 77 0 1 78 0 0 1 78 0 0 235 1 0 0 235 0 0 236 1 0 0 236 0 0 237 1 0 0 237 0 0 238 1 0 0 238 0 1 239 1 0 0 239 0 0 240 1 0 0 240 0 1 241 1 0 0 241 0 0 242 1 0 0 242 0 1 243 0 0 0 243 0 1 244 0 0 0 244 0 1 245 0 0 0 245 1 1 246 0 0 0 246 1 0 79 1 0 1 79 1 0 247 1 0 0 247 0 0 248 1 0 0 248 0 0 249 1 0 0 249 0 1 250 0 0 0 250 0 1 251 0 0 0 251 0 1 80 0 0 1 80 0 1 81 0 0 1 81 0 0 252 1 0 0 252 0 0 253 1 0 0 253 0 1 254 0 0 0 254 1 1 255 0 0 0 255 1 0 82 1 0 1 82 1 0 256 1 0 0 256 0 0 257 1 0 0 257 0 1 258 0 0 0 258 0 1 83 0 0 1 83 0 1 84 0 0 1 84 0 0 259 1 0 0 259 0 0 260 1 0 0 260 0 0 261 1 0 0 261 0 0 262 1 0 0 262 0 1 263 0 0 0 263 0 1 264 0 0 0 264 0 1 265 0 0 0 265 1 1 266 0 0 0 266 1 0 85 1 0 1 85 1 0 267 1 0 0 267 0 0 268 1 0 0 268 1 1 269 0 0 0 269 0 1 86 0 0 1 86 1 1 87 0 0 1 87 0 0 88 0 0 1 88 1 0 270 0 0 0 270 0 0 89 0 0 1 89 1 0 271 0 0 0 271 0 0 90 0 0 1 90 0 0 272 1 0 0 272 0 1 273 0 0 0 273 1 0 274 0 0 0 274 0 1 91 0 0 1 91 1 1 275 0 0 0 275 0 1 92 0 0 1 92 0 1 276 0 0 0 276 0 1 93 0 0 1 93 1 1 277 0 0 0 277 1 0 94 1 0 1 94 1 0 278 1 0 0 278 0 0 279 1 0 0 279 0 1 280 0 0 0 280 0 1 95 0 0 1 95 0 1 96 0 0 1 96 0 0 281 1 0 0 281 0 0 282 1 0 0 282 0 0 283 1 0 0 283 0 0 284 1 0 0 284 0 1 285 1 0 0 285 0 0 286 1 0 0 286 0 1 287 1 0 0 287 0 0 288 1 0 0 288 0 1 289 0 0 0 289 0 1 290 0 0 0 290 0 1 291 0 0 0 291 1 1 292 0 0 0 292 1 0 97 1 0 1 97 1 0 293 1 0 0 293 0 0 294 1 0 0 294 0 0 295 1 0 0 295 0 1 296 0 0 0 296 0 1 297 0 0 0 297 0 1 98 0 0 1 98 0 1 99 0 0 1 99 0 0 298 1 0 0 298 0 0 299 1 0 0 299 0 1 300 0 0 0 300 1 1 301 0 0 0 301 1 0 100 1 0 1 100 1 0 302 1 0 0 302 0 0 303 1 0 0 303 0 1 304 0 0 0 304 0 1 101 0 0 1 101 0 1 102 0 0 1 102 0 0 305 1 0 0 305 0 0 306 1 0 0 306 0 0 307 1 0 0 307 0 0 308 1 0 0 308 0 1 309 0 0 0 309 0 1 310 0 0 0 310 0 1 311 0 0 0 311 1 1 312 0 0 0 312 1 0 103 1 0 1 103 1 0 313 1 0 0 313 0 0 314 1 0 0 314 1 1 315 0 0 0 315 0 1 104 0 0 1 104 1 1 105 0 0 1 105 0 0 106 0 0 1 106 1 0 316 0 0 0 316 0 0 107 0 0 1 107 1 0 317 0 0 0 317 0 0 108 0 0 1 108 0 0 318 1 0 0 318 0 1 319 0 0 0 319 1 0 320 0 0 0 320 0 1 109 0 0 1 109 1 1 321 0 0 0 321 0 1 110 0 0 1 110 0 1 322 0 0 0 322 0 1 111 0 0 1 111 1 1 323 0 0 0 323 1 0 112 1 0 1 112 1 0 324 1 0 0 324 0 0 325 1 0 0 325 0 1 326 0 0 0 326 0 1 113 0 0 1 113 0 1 114 0 0 1 114 0 0 327 1 0 0 327 0 0 328 1 0 0 328 0 0 329 1 0 0 329 0 0 330 1 0 0 330 0 1 331 1 0 0 331 0 0 332 1 0 0 332 0 1 333 1 0 0 333 0 1 334 0 0 0 334 0 1 335 0 0 0 335 1 1 336 0 0 0 336 1 0 115 1 0 1 115 1 0 337 1 0 0 337 0 0 338 1 0 0 338 0 0 339 1 0 0 339 0 1 340 0 0 0 340 0 1 341 0 0 0 341 0 1 116 0 0 1 116 0 1 117 0 0 1 117 0 0 342 1 0 0 342 0 0 343 1 0 0 343 0 0 344 1 0 0 344 0 1 345 0 0 0 345 0 1 346 0 0 0 346 1 1 347 0 0 0 347 1 0 118 1 0 1 118 1 0 348 1 0 0 348 0 0 349 1 0 0 349 0 1 350 0 0 0 350 0 1 119 0 0 1 119 0 1 120 0 0 1 120 0 0 351 1 0 0 351 0 0 352 1 0 0 352 0 0 353 1 0 0 353 0 0 354 1 0 0 354 0 1 355 0 0 0 355 0 1 356 0 0 0 356 0 1 357 0 0 0 357 1 1 358 0 0 0 358 1 0 121 1 0 1 121 1 0 359 1 0 0 359 0 0 360 1 0 0 360 1 1 361 0 0 0 361 0 1 122 0 0 1 122 1 1 123 0 0 1 123 0 0 124 0 0 1 124 1 0 362 0 0 0 362 0 0 125 0 0 1 125 1 0 363 0 0 0 363 0 0 126 0 0 1 126 0 0 364 1 0 0 364 0 1 365 0 0 0 365 1 0 366 0 0 0 366 0 1 127 0 0 1 127 1 1 367 0 0 0 367 0 1 128 0 0 1 128 0 1 368 0 0 0 368 0 1 129 0 0 1 129 1 1 369 0 0 0 369 1 0 130 1 0 1 130 1 0 370 1 0 0 370 0 0 371 1 0 0 371 0 1 372 0 0 0 372 0 1 131 0 0 1 131 0 1 132 0 0 1 132 0 0 373 1 0 0 373 0 0 374 1 0 0 374 0 0 375 1 0 0 375 0 0 376 1 0 0 376 0 1 377 1 0 0 377 0 0 378 1 0 0 378 0 1 379 1 0 0 379 0 1 380 0 0 0 380 0 1 381 0 0 0 381 1 1 382 0 0 0 382 1 0 133 1 0 1 133 1 0 383 1 0 0 383 0 0 384 1 0 0 384 0 0 385 1 0 0 385 0 1 386 0 0 0 386 0 1 387 0 0 0 387 0 1 134 0 0 1 134 0 1 135 0 0 1 135 0 0 388 1 0 0 388 0 0 389 1 0 0 389 0 0 390 1 0 0 390 0 1 391 0 0 0 391 0 1 392 0 0 0 392 1 1 393 0 0 0 393 1 0 136 1 0 1 136 1 0 394 1 0 0 394 0 0 395 1 0 0 395 0 1 396 0 0 0 396 0 1 137 0 0 1 137 0 1 138 0 0 1 138 0 0 397 1 0 0 397 0 0 398 1 0 0 398 0 0 399 1 0 0 399 0 0 400 1 0 0 400 0 1 401 0 0 0 401 0 1 402 0 0 0 402 0 1 403 0 0 0 403 1 1 404 0 0 0 404 1 0 139 1 0 1 139 1 0 405 1 0 0 405 0 0 406 1 0 0 406 1 1 407 0 0 0 407 0 1 140 0 0 1 140 1 1 141 0 0 1 141 0 0 142 0 0 1 142 1 0 408 0 0 0 408 0 0 143 0 0 1 143 1 0 409 0 0 0 409 0 0 144 0 0 1 144 0 0 410 1 0 0 410 0 1 411 0 0 0 411 1 0 412 0 0 0 412 0 1 145 0 0 1 145 1 1 413 0 0 0 413 0 1 146 0 0 1 146 0 1 414 0 0 0 414 0 1 147 0 0 1 147 1 1 415 0 0 0 415 1 0 148 1 0 1 148 1 0 416 1 0 0 416 0 0 417 1 0 0 417 0 1 418 0 0 0 418 0 1 149 0 0 1 149 0 1 150 0 0 1 150 0 0 419 1 0 0 419 0 0 420 1 0 0 420 0 0 421 1 0 0 421 0 0 422 1 0 0 422 0 1 423 1 0 0 423 0 0 424 1 0 0 424 0 1 425 0 0 0 425 0 1 426 0 0 0 426 0 1 427 0 0 0 427 1 1 428 0 0 0 428 1 0 151 1 0 1 151 1 0 429 1 0 0 429 0 0 430 1 0 0 430 0 0 431 1 0 0 431 0 1 432 1 0 0 432 0 0 433 1 0 0 433 0 1 434 1 0 0 434 0 0 435 1 0 0 435 0 1 436 1 0 0 436 0 0 437 1 0 0 437 0 1 438 1 0 0 438 0 1 439 0 0 0 439 0 1 152 0 0 1 152 0 1 153 0 0 1 153 0 0 440 1 0 0 440 0 0 441 1 0 0 441 0 0 442 1 0 0 442 0 0 443 1 0 0 443 0 1 444 0 0 0 444 0 1 445 0 0 0 445 0 1 446 0 0 0 446 1 1 447 0 0 0 447 1 0 154 1 0 1 154 1 0 448 1 0 0 448 0 0 449 1 0 0 449 1 1 450 0 0 0 450 0 1 155 0 0 1 155 1 1 156 0 0 1 156 0 0 157 0 0 1 157 1 0 451 0 0 0 451 0 0 158 0 0 1 158 1 0 452 0 0 0 452 0 0 159 0 0 1 159 0 0 453 1 0 0 453 0 1 454 0 0 0 454 1 0 455 0 0 0 455 0 1 160 0 0 1 160 1 1 456 0 0 0 456 0 1 161 0 0 1 161 0 1 457 0 0 0 457 0 1 162 0 0 1 162 1 1 458 0 0 0 458 1 0 163 1 0 1 163 1 0 459 1 0 0 459 0 0 460 1 0 0 460 0 1 461 0 0 0 461 0 1 164 0 0 1 164 0 1 165 0 0 1 165 0 0 462 1 0 0 462 0 0 463 1 0 0 463 0 0 464 1 0 0 464 0 0 465 1 0 0 465 0 1 466 1 0 0 466 0 0 467 1 0 0 467 0 1 468 0 0 0 468 0 1 469 0 0 0 469 0 1 470 0 0 0 470 1 1 471 0 0 0 471 1 0 166 1 0 1 166 1 0 472 1 0 0 472 0 0 473 1 0 0 473 0 0 474 1 0 0 474 0 1 475 1 0 0 475 0 0 476 1 0 0 476 0 1 477 1 0 0 477 0 0 478 1 0 0 478 0 1 479 1 0 0 479 0 0 480 1 0 0 480 0 1 481 1 0 0 481 0 1 482 0 0 0 482 0 1 167 0 0 1 167 0 1 168 0 0 1 168 0 0 483 1 0 0 483 0 0 484 1 0 0 484 0 0 485 1 0 0 485 0 0 486 1 0 0 486 0 1 487 0 0 0 487 0 1 488 0 0 0 488 0 1 489 0 0 0 489 1 1 490 0 0 0 490 1 0 169 1 0 1 169 1 0 491 1 0 0 491 0 0 492 1 0 0 492 1 1 493 0 0 0 493 0 1 170 0 0 1 170 1 1 171 0 0 1 171 0 0 172 0 0 1 172 1 0 494 0 0 0 494 0 0 173 0 0 1 173 1 0 495 0 0 0 495 0 0 174 0 0 1 174 0 0 496 1 0 0 496 0 1 497 0 0 0 497 1 0 498 0 0 0 498 0 1 175 0 0 1 175 1 1 499 0 0 0 499 0 1 176 0 0 1 176 0 1 500 0 0 0 500 0 1 177 0 0 1 177 1 1 501 0 0 0 501 1 0 178 1 0 1 178 1 0 502 1 0 0 502 0 0 503 1 0 0 503 0 1 504 0 0 0 504 0 1 179 0 0 1 179 0 1 180 0 0 1 180 0 0 505 1 0 0 505 0 0 506 1 0 0 506 0 0 507 1 0 0 507 0 0 508 1 0 0 508 0 1 509 1 0 0 509 0 1 510 0 0 0 510 0 1 511 0 0 0 511 1 1 512 0 0 0 512 1 0 181 1 0 1 181 1 0 513 1 0 0 513 0 0 514 1 0 0 514 0 0 515 1 0 0 515 0 1 516 0 0 0 516 0 1 517 0 0 0 517 0 1 182 0 0 1 182 0 1 183 0 0 1 183 0 0 518 1 0 0 518 0 0 519 1 0 0 519 0 0 520 1 0 0 520 0 0 521 1 0 0 521 0 1 522 1 0 0 522 0 1 523 0 0 0 523 0 1 524 0 0 0 524 1 1 525 0 0 0 525 1 0 184 1 0 1 184 1 0 526 1 0 0 526 0 0 527 1 0 0 527 0 1 528 0 0 0 528 0 1 185 0 0 1 185 0 1 186 0 0 1 186 0 0 529 1 0 0 529 0 0 530 1 0 0 530 0 0 531 1 0 0 531 0 0 532 1 0 0 532 0 1 533 0 0 0 533 0 1 534 0 0 0 534 0 1 535 0 0 0 535 1 1 536 0 0 0 536 1 0 187 1 0 1 187 1 0 537 1 0 0 537 0 0 538 1 0 0 538 1 1 539 0 0 0 539 0 1 188 0 0 1 188 1 1 189 0 0 1 189 0 0 190 0 0 1 190 1 0 540 0 0 0 540 0 0 191 0 0 1 191 1 0 541 0 0 0 541 0 0 192 0 0 1 192 0 0 542 1 0 0 542 0 1 543 0 0 0 543 1 0 544 0 0 0 544 0 1 193 0 0 1 193 1 1 545 0 0 0 545 0 1 194 0 0 1 194 0 1 546 0 0 0 546 0 1 195 0 0 1 195 1 1 547 0 0 0 547 1 0 196 1 0 1 196 1 0 548 1 0 0 548 0 0 549 1 0 0 549 0 1 550 0 0 0 550 0 1 197 0 0 1 197 0 1 198 0 0 1 198 0 0 551 1 0 0 551 0 0 552 1 0 0 552 0 0 553 1 0 0 553 0 0 554 1 0 0 554 0 1 555 1 0 0 555 0 1 556 0 0 0 556 0 1 557 0 0 0 557 1 1 558 0 0 0 558 1 0 199 1 0 1 199 1 0 559 1 0 0 559 0 0 560 1 0 0 560 0 1 561 0 0 0 561 0 1 200 0 0 1 200 0 1 201 0 0 1 201 0 0 562 1 0 0 562 0 0 563 1 0 0 563 0 0 564 1 0 0 564 0 0 565 1 0 0 565 0 1 566 1 0 0 566 0 0 567 1 0 0 567 0 1 568 0 0 0 568 0 1 569 0 0 0 569 0 1 570 0 0 0 570 1 1 571 0 0 0 571 1 0 202 1 0 1 202 1 0 572 1 0 0 572 0 0 573 1 0 0 573 0 1 574 0 0 0 574 0 1 203 0 0 1 203 0 1 204 0 0 1 204 0 0 575 1 0 0 575 0 0 576 1 0 0 576 0 0 577 1 0 0 577 0 0 578 1 0 0 578 0 1 579 0 0 0 579 0 1 580 0 0 0 580 0 1 581 0 0 0 581 1 1 582 0 0 0 582 1 0 205 1 0 1 205 1 0 583 1 0 0 583 0 0 584 1 0 0 584 1 1 585 0 0 0 585 0 1 206 0 0 1 206 1 1 207 0 0 1 207 0 0 208 0 0 1 208 1 0 586 0 0 0 586 0 0 209 0 0 1 209 1 0 587 0 0 0 587 0 0 210 0 0 1 210 0 0 588 1 0 0 588 0 1 589 0 0 0 589 1 0 590 0 0 0 590 0 1 211 0 0 1 211 1 1 591 0 0 0 591 0 1 212 0 0 1 212 0 1 592 0 0 0 592 0 1 213 0 0 1 213 0 0 593 1 0 0 593 0 1 594 0 0 0 594 1 1 595 0 0 0 595 1 0 214 1 0 1 214 1 0 596 1 0 0 596 0 0 597 1 0 0 597 0 0 598 1 0 0 598 0 1 599 0 0 0 599 0 1 600 0 0 0 600 0 1 215 0 0 1 215 0 1 216 0 0 1 216 0 0 601 1 0 0 601 0 0 602 1 0 0 602 0 1 603 0 0 0 603 1 1 604 0 0 0 604 1 0 217 1 0 1 217 1 0 605 1 0 0 605 0 0 606 1 0 0 606 0 0 607 1 0 0 607 0 1 608 0 0 0 608 0 1 609 0 0 0 609 0 1 218 0 0 1 218 0 1 219 0 0 1 219 0 0 610 1 0 0 610 0 0 611 1 0 0 611 0 0 612 1 0 0 612 0 0 613 1 0 0 613 0 1 614 1 0 0 614 0 0 615 1 0 0 615 0 1 616 1 0 0 616 0 0 617 1 0 0 617 0 1 618 1 0 0 618 0 0 619 1 0 0 619 0 1 620 1 0 0 620 0 1 621 0 0 0 621 0 1 622 0 0 0 622 1 1 623 0 0 0 623 1 0 220 1 0 1 220 1 0 624 1 0 0 624 0 0 625 1 0 0 625 0 0 626 1 0 0 626 0 0 221 0 0 1 221 0 0 627 0 0 0 627 0 1 628 0 0 0 628 0 1 629 0 0 0 629 0 1 630 0 0 0 630 1 1 631 0 0 0 631 0 1 222 0 0 1 222 1 1 223 0 0 1 223 0 0 224 1 0 1 224 0 0 632 0 0 0 632 0 0 225 0 0 1 225 0 0 633 0 0 0 633 0 0 634 0 0 0 634 1 0 635 1 0 0 635 0 1 226 1 0 1 226 1 1 636 0 0 0 636 0 1 637 0 0 0 637 0 1 638 0 0 0 638 0 1 639 0 0 0 639 1 1 640 0 0 0 640 1 0 227 1 0 1 227 1 0 641 1 0 0 641 0 0 642 1 0 0 642 0 0 643 1 0 0 643 0 1 644 1 0 0 644 0 0 645 1 0 0 645 0 1 646 1 0 0 646 0 0 647 1 0 0 647 0 1 648 0 0 0 648 0 1 649 0 0 0 649 0 1 228 0 0 1 228 0 1 229 0 0 1 229 0 0 650 1 0 0 650 0 0 651 1 0 0 651 0 0 652 1 0 0 652 0 0 653 1 0 0 653 0 1 654 1 0 0 654 0 0 655 1 0 0 655 0 1 656 1 0 0 656 0 0 657 1 0 0 657 0 1 658 1 0 0 658 0 1 659 0 0 0 659 0 1 660 0 0 0 660 1 1 661 0 0 0 661 1 0 230 1 0 1 230 1 0 662 1 0 0 662 0 0 663 1 0 0 663 0 0 664 1 0 0 664 0 1 665 1 0 0 665 0 0 666 1 0 0 666 0 0 231 0 0 1 231 0 0 667 0 0 0 667 0 1 668 0 0 0 668 0 1 669 0 0 0 669 0 1 670 0 0 0 670 1 1 671 0 0 0 671 0 1 232 0 0 1 232 1 1 233 0 0 1 233 0 0 234 1 0 1 234 0 0 672 0 0 0 672 0 0 235 0 0 1 235 0 0 673 0 0 0 673 0 0 674 0 0 0 674 1 0 675 1 0 0 675 0 1 236 1 0 1 236 1 1 676 1 0 0 676 0 1 677 1 0 0 677 0 0 678 1 0 0 678 0 1 679 1 0 0 679 0 1 680 0 0 0 680 0 1 681 0 0 0 681 1 1 682 0 0 0 682 1 0 237 1 0 1 237 1 0 683 1 0 0 683 0 0 684 1 0 0 684 0 0 685 1 0 0 685 0 1 686 1 0 0 686 0 0 687 1 0 0 687 0 1 688 1 0 0 688 0 0 689 1 0 0 689 0 1 690 1 0 0 690 0 0 691 1 0 0 691 0 1 692 1 0 0 692 0 0 693 1 0 0 693 0 1 694 1 0 0 694 0 0 695 1 0 0 695 0 1 696 1 0 0 696 0 0 697 1 0 0 697 0 1 698 1 0 0 698 1 1 699 0 0 0 699 0 1 238 0 0 1 238 1 1 239 0 0 1 239 0 0 240 0 0 1 240 1 0 700 0 0 0 700 0 0 241 0 0 1 241 1 0 701 0 0 0 701 0 0 242 0 0 1 242 0 0 702 1 0 0 702 0 1 703 0 0 0 703 1 0 704 0 0 0 704 0 1 243 0 0 1 243 1 1 705 0 0 0 705 0 1 244 0 0 1 244 0 1 706 0 0 0 706 0 1 245 0 0 1 245 0 0 707 1 0 0 707 0 0 708 1 0 0 708 0 0 709 1 0 0 709 0 1 710 1 0 0 710 0 0 711 1 0 0 711 0 1 712 1 0 0 712 0 1 713 0 0 0 713 0 1 714 0 0 0 714 1 1 715 0 0 0 715 1 0 246 1 0 1 246 1 0 716 1 0 0 716 0 0 717 1 1 ``` Made with ASCII\_only's program generator [Answer] # deflate, 79 bytes eJyVkcsJADAIQ++ZIpD9dyxUqrGUgjlpHvglXdqCJymk1yEiaRXEIOXzuBHCiKObReUxUzYaMdt2wmTBg/FmNXndgLRbNvL7ifsLfMw6iQ== [Answer] # Brainf\*\*\*, ~~656~~ ~~652~~ 605 bytes ``` ++[+++[<+>->>+>->-<<<<]>-]>..............>......>+.<<......>...............>.<<....>.....<....>..........>.<<..>....<.......>.......<.>....>.<<.>...<........>....<.>...<...>...>.<...<.........>....<.>...<....>...>.<...<........>....<..>...<....>...>.<...<........>....<..>...<....>...>.<...<.......>....<...>...<....>...>.<...<.......>....<...>...<....>...>.<...<......>...........<....>...>.<...<......>...........<....>...>.<...<.....>....<.....>...<....>...>.<...<.....>...<......>...<....>...>.<<.>....<..>....<...........>....>.<<..>........<.........>......>.<<......>.................>.<<......>... ``` The loop at the start initiates the tape to ``` ... 032 [035] 010 ... ``` Then the rest of the code outputs those characters. (-47 bytes thanks to orthoplex) [Answer] # T-SQL, 244 bytes **Golfed:** ``` DECLARE @ varchar(max)='MfFoDEDjBDGGAcACHDACCc@CIDACDc@CHDBCDc@CHDBCDc@CGDCCDc@CGDCCDc@CFKDc@CFKDc@CEDECDc@CECFCDcADBDKdBHIfFqFC 'WHILE'!'<@ SET @=stuff(@,1,1,'')+replicate(char(35-charindex(' ',@)%2*3),ascii(@)%32)+left(' ',ascii(@)/97)PRINT @ ``` **Ungolfed:** ``` DECLARE @ varchar(max)='MfFoDEDjBDGGAcACHDACCc@CIDACDc@CHDBCDc@CHDBCDc@CGDCCDc@CGDCCDc@CFKDc@CFKDc@CEDECDc@CECFCDcADBDKdBHIfFqFC ' WHILE'!'<@ SET @=stuff(@,1,1,'')+ replicate(char(35-charindex(' ',@)%2*3),ascii(@)%32)+ left(' ',ascii(@)/97) PRINT @ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1020909/tribute-to-stan-lee)** ungolfed version ]
[Question] [ Echo the following in as few bytes as possible: ``` I'm Slim Shady. Yes, I'm the real Shady. All you other Slim Shadys are just imitating. So, won't the real Slim Shady please stand up? Please stand up. Please stand up. ``` The following five words must appear **EXACTLY ONCE** in your code: `I'm` `Slim` `Shady` `real` `stand` [Answer] # Python: 176 ``` print"{0}{1}{2}. Yes, {0}{3}{2}.\nAll you other {1}{2}s are just imitating.\nSo, won't {3}{1}{2} p{4}?\nP{4}. P{4}.".format("I'm ","Slim ","Shady","the real ","lease stand up") ``` Naturally, the same idea as other compression solutions (though independently obtained). [Answer] **Brainfuck 1923 bytes** Enjoy... ``` -[------->+<]>.+[-->+<]>++.---[->+++<]>+. [->+++++<]>-.>-[--->+<]>--.--[--->++++<] >.---.++++.[->+++++<]>-.>-[--->+<]>--.>+ [----->+++<]>+.-------.+++.+[--->+<]>++. -----[++>---<]>.++[--->++<]>.--[->+++<]>-. [->++++<]>+.[--->+<]>----.-[++>---<]>+. ------------.++++[->++<]>+.+[-->+<]>++.--- [->+++<]>+.[->+++++<]>-.---[->++++<] >.------------.---.--[--->+<]>-.---[----->++<] >.-------------.----.+++++++++++.[++>---<] >--.>-[--->+<]>--.>+[----->+++<]>+.-------. +++.+[--->+<]>++.-----[++>---<]>.> ++++++++++.+++[->+++++<]>.[--->+<]>+.. [++>---<]>--.--[->++++<]>+.----------.++++++.- [---->+<]>+++.+++++[->+++<] >.+++++.------------.---.+++++++++++++. [-->+++++<]>+++.>-[--->+<]>--.-- [--->++++<]>.---.++++.[->+++++<]>-.>- [--->+I'm<]>--.>+[----->+++<]>+.-------.+++.+ [--->+<]>++.------.+[---->+<]>+++.[->+++<]>+.-- [--->+<]>---.-------------.--[--->+<]>-.- [--->++<]>.+++++++++++.--.+. [---Slim->+<]>+++.-[--->++<]>-.++++.----. +++++++++++.+[->+++<]>++.--[--->+<] >-.-----------.+++++.-------.--[->+++<]>-. >++++++++++.>-[--->+<]>--.[--->+<]>--. [->+++++<]>+.------------.--[->++++<]>-. --------.-.[++>---<]>++.[->+++<]>-.[---->+ <]>+++.---[->++++<]>.------------.---.--[--- >+<]>-.---[----->Shady++<]>.-------------.- ---.+++++++++++.[++>---<]>--.>-[--->+<] >--.--[--->++++<]>.---.++++.[->+++++<] >-.>-[--->+<]>--.>+[----->+++<]>+.-------. +++.+[--->+<]>++.-[---->+<]>++.[-->+++++++<] >.----.-------.----.--[--->+<]>--.++++[->+++<] >.--[--->+<]>-.---[->++++<]>-.+.+[->+++<] >++.+++++++++++++.----------.-[--->+<] >-.---[->++++<]>+.-----.[--->++++<]>-.> ++++++++++.[->++++++++<]>.+[--->++++<] >.---real----.----.--[--->+<]>--.++++[->+++<] >.--[--->+<]>-.---[->++++<]>-.+.+[->+++<] >++.+++++++++++++.----------.-[--->+<]>-.--- [->++++<]>+.-----.[->+++++<]>--.++[--->++<] >.[-->stand+++++<]>.+[--->++++<]> .-------.----.--[--->+<]>--.++++[->+++<] >.--[--->+<]>-.---[->++++<]>-.+.+[->+++<] >++.+++++++++++++.----------.-[--->+<] >-.---[->++++<]>+.-----.[->+++++<]>--. ``` *Standard Loop Holes* [Answer] # Perl, 155 With improvements by [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) and [Thaylon](/users/29681): ``` $_="01. Yes, 02X. All you other1s are just imitating. So, won't21 p3? P3. P3.";s/\d/("I'm"," SlimX"," the real","lease stand up")[$&]/ge;s/X/ Shady/g;print ``` [Answer] ## Ruby, 154 bytes ``` $><<"012. Yes, 032. All you other12s are just imitating. So, won't312 p4? P4. P4.".gsub(/\d/){%W{I'm \ Slim \ Shady \ the\ real lease\ stand\ up}[$&.hex]} ``` After helping out a few people with how to split up the filler strings I decided to give their replacement callback idea a go. ;) [Answer] # JavaScript (E6) 165 Just the same in another language ``` alert("012. Yes, 05326All you other12s are just imitating6So, won't5312 p4?\nP4. P4." .replace(/\d/g,x=>"I'm1 Slim1 Shady1real1lease stand up1 the 1.\n".split(1)[x])) ``` Explanation: replace each single digit in the first string with the corresponding string in the array `["I'm"," Slim"," Shady","real","lease stand up"," the ",".\n"]` Revised with the new rules here at PPCG (output returned from a function, no constraints about features newer than the challenge), this could be 158. See the snippet ``` F= _=>`012. Yes, 0532. All you other12s are just imitating. So, won't5312 p4? P4. P4.`.replace(/\d/g,x=>"I'm, Slim, Shady,real,lease stand up, the ".split`,`[x]) console.log(F()) ``` [Answer] # CJam - 133 ``` "I'm| Slim| Shady| the real|lease stand up|432. Yes, 412. All you other32s are just imitating. So, won't132 p0? P0. P0."'|/~5,{`/\*}/ ``` Try it at <http://cjam.aditsu.net/> I think it also works in GolfScript if you replace `'|` with `"|"` [Answer] # GolfScript, ~~162~~ ~~154~~ ~~152~~ 144 bytes ``` "I'm ":i"Slim ":|"Shady":y". Yes, "i"the real ":!y". All you other "|y"s are just imitating. So, won't "!|y" p""lease stand up":l"? P"l". P"l"." ``` [Test online](http://golfscript.apphb.com/?c=IkknbSAiOmkiU2xpbSAiOnwiU2hhZHkiOnkiLiBZZXMsICJpInRoZSByZWFsICI6IXkiLgpBbGwgeW91IG90aGVyICJ8eSJzIGFyZSBqdXN0IGltaXRhdGluZy4KU28sIHdvbid0ICIhfHkiIHAiImxlYXNlIHN0YW5kIHVwIjpsIj8KUCJsIi4gUCJsIi4i) [Answer] **VBA 343 bytes** ``` Sub EMINEM() e = "Slim " m = "Shady" i = "I'm " n = "lease stand up" em = "real " MsgBox i & e & m & ". Yes, " & i & "the " & em & m & "." & Chr(10) & "All you other " & e & m & "s are just imitating." & Chr(10) & "So, won't the " & em & e & m & " p" & n & Chr(10) & "P" & n & ". P" & n & "." End Sub ``` [Answer] # VBA 307 Bytes And obfuscated with line separators (just for fun). Based on [this answer](https://codegolf.stackexchange.com/a/35556/20807) ``` Function p() e = "Slim ": m = "Shady": i = "I'm ": n = "lease stand up": s = "real ": a = "." p = i & e & m & ". Yes, " & i & "the " & s & m & a & Chr(10) & "All you other " & e & m & "s are just imitating." & Chr(10) & "So, won't the " & s & e & m & " p" & n & Chr(10) & "P" & n & ". P" & n & a End Function ``` Called from the immediate window with `?p`. The 307 includes the `?p`. [Answer] # PHP - 151 bytes ``` <?="I'm Slim Shady".gzinflate("]Œ1 „0E{Á;üÎFr…ÅÒNHe9à°F&‰d&,Þ~Avmßûï;̬=Æ.ÂVFaø•–ÃµÍ ‚#WäÓx ñR *Œ­ª!Ä`d!½Ï¹Ï=>9uöót7Ø…Ij”ÔýÕ6Ó?qx‚/");@realstand; ``` hexdump: ``` 0000000 3f3c 223d 2749 206d 6c53 6d69 5320 6168 0000010 7964 2e22 7a67 6e69 6c66 7461 2865 5d22 0000020 318c 840a 1030 7b45 3bc1 cefc 7246 c585 0000030 4ed2 6548 e039 46b0 8926 2664 de2c 057e 0000040 7641 df6d effb cc3b 3dac 2ec6 56c2 6146 0000050 f812 9695 b5c3 20cd 2382 e457 14d3 0978 0000060 52f1 2a0a ad8c 21aa 60c4 2164 cfbd cfb9 0000070 3e3d 7539 f3f6 3774 85d8 1949 946a d416 0000080 d5fd d336 713f 8278 222f 3b29 7240 6165 0000090 736c 6174 646e 003b 0000097 ``` # Another answer without using gzinflate (228 bytes): Reads shorts (16 bits), extracts 3 5-bit integers as indices of a lookup table. ``` <?$a=str_split(" .Yes,AlyouthrajimngSw'pP? ")+[27=>"I'm ",'Slim ',@Shady,'the real ','lease stand up'];$b=unpack(@v26,'o… ~:tç (ƒ-4€t£9ê`0BË-SBT $2U`Y{ÿXg |ác');foreach($b as$c)echo$a[$c>>10],$a[$c>>5&31],$a[$c&31]; ``` hexdump: ``` 0000000 3f3c 6124 733d 7274 735f 6c70 7469 2228 0000010 2e20 6559 2c73 6c41 6f79 7475 7268 6a61 0000020 6d69 676e 7753 7027 3f50 220a 2b29 325b 0000030 3d37 223e 2749 206d 2c22 5327 696c 206d 0000040 2c27 5340 6168 7964 272c 6874 2065 6572 0000050 6c61 2720 272c 656c 7361 2065 7473 6e61 0000060 2064 7075 5d27 243b 3d62 6e75 6170 6b63 0000070 4028 3276 2c36 9d27 026f 8504 7e0c 3a03 0000080 e774 0918 0901 8328 1c2d 8034 a374 ea39 0000090 6001 3011 cb42 532d 5442 a007 3224 6055 00000a0 9d59 ff7b 5802 2067 e17c 2763 3b29 6f66 00000b0 6572 6361 2868 6224 6120 2473 2963 6365 00000c0 6f68 6124 245b 3e63 313e 5d30 242c 5b61 00000d0 6324 3e3e 2635 3133 2c5d 6124 245b 2663 00000e0 3133 3b5d 00000e4 ``` [Answer] # C, 374 By moving memory Not the shortest but can it get any faster? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> char *s; void m (int d, int f, int p) { memmove (s+p+f, s+p, strlen(s)-p+1); // Shift a part of the string to make room for our insertion memcpy (s+p, s+d, f); // Copy the desired reference in place } int main () { s = malloc (168); strcpy (s,"I'm Slim Shady. Yes, the real.\nAll you others are just imitating.\nSo, won't the please stand up?\nP. "); m (0, 4, 21); m (8, 6, 33); m (3, 11, 54); m (28, 5, 100); m (3, 11, 105); m (118, 14, 135); m (134, 16, 151); puts (s); } ``` It's 374 chars long after minification. ``` #include<stdio.h> #include<stdlib.h> #include<string.h> char*s;void m(int d,int f,int p){memmove(s+p+f,s+p,strlen(s)-p+1);memcpy(s+p,s+d,f);}int main(){s=malloc(168);strcpy(s,"I'm Slim Shady. Yes, the real.\nAll you others are just imitating.\nSo, won't the please stand up?\nP. ");m(0,4,21);m(8,6,33);m(3,11,54);m(28,5,100);m(3,11,105);m(118,14,135);m(134,16,151);puts(s);} ``` [Answer] # Java, 247 My first code golf, while learning Java. Posted it because it beats the other (fully functional) Java entry and the Haskell entry. ``` class S{public static void main(String[]a){String s="I'm",t=" Slim",u=" Shady",v=" the real",w="lease stand up";System.out.print(s+t+u+". Yes, "+s+v+u+".\nAll you other"+t+u+"s are just imitating.\nSo, won't"+v+t+u+" p"+w+"?\nP"+w+". P"+w+".");}} ``` [Answer] # C# ~~209~~ ~~205~~ ~~201~~ ~~197~~ ~~209~~ ~~212~~ 217 ``` class P{static void Main(){System.Console.Write("{0}{1}{2}. Yes, {0}{3}{2}.\nAll you other {1}{2}s are just imitating.\nSo, won't {3}{1}{2} p{4}?\nP{4}. P{4}.", "I'm ","Slim ","Shady","the real ","lease stand up");}} ``` *Now with Proper Capitalization and New Lines* [Answer] # VB ~~253~~ ~~249~~ ~~245~~ ~~241~~ ~~244~~ ~~285~~ ~~259~~ 223 I hate New Line termination ``` Module M Sub Main Console.Write("{0}{1}{2}. Yes, {0}{3}{2}.{5}All you other {1}{2}s are just imitating.{5}So, won't {3}{1}{2} p{4}?{5}P{4}. P{4}.","I'm ","Slim ","Shady","the real ","lease stand up",vbCr) End Sub End Module ``` *Now with proper Capitalization And Newlines in the output, and no Tabs* \* ***Thank you VB for `vbCrLf`*** [Thank you, @Taylor Scott!](https://tio.run/##JY@9asNAEIR7PcWgxglIInHi2gSTIoXAoCK4XEWLfeZ0a@7Hxhz37MpJavZjdmcZ5q5cIF335NRfbdjXoxiZplaGoBlt0YUeLSlTHMQ40dz8WuX5pYxvKb6nuE0NTuwqzPpj0XGXvrTGUwLEX9hi9TmQZVyD81Cj8uSVOc/eTio8xGw85v/Filv8TPt8O2Y2WGZZlT@bERmdVisvNDwzcwYsk553mskxnCczINzK6t4f7GvxnVXusXAtNk3/) [Answer] # PowerShell ~~194~~ ~~189~~ 164 ``` "{0}{1}{2}. Yes, {0}{3}{2}.`nAll you other {1}{2}s are just imitating.`nSo, won't {3}{1}{2} p{4}?`nP{4}. P{4}."-f"I'm ","Slim ","Shady","the real ","lease stand up" ``` Somehow my answer ened up resembling [@nneonneo's](https://codegolf.stackexchange.com/a/35531/3970) a lot, even though it wasn't my original intent... [Answer] # PHP - 196 171 ``` <?$S="Shady";$P="lease stand up";$R="the real ";$I="I'm ";$s="Slim ";echo"$I$s$S. Yes, $I$R$S All you other $s$S"."s are just imitating. So, won't $R$s$S p$P? P$P. P$P." ``` ; [Answer] # Lua ~~201~~ ~~193~~ ~~188~~ 178 ``` h=" Shady"i="I'm"s=" Slim"..h r=" the real"u="lease stand up"io.write(i,s,". Yes, ",i,r,h,".\nAll you other",s,"s are just imitating.\nSo, won't",r,s," p",u,"?\nP",u,". P",u,".") ``` Ungolfed & expanded some ``` h=" Shady" i="I'm" s=" Slim"..h r=" the real" u="lease stand up" io.write(i,s,". Yes, ",i,r,h,".\nAll you other",s,"s are just imitating.\nSo, won't",r,s," p",u,"?\nP",u,". P",u,".") ``` [Answer] # Common Lisp, 197 ``` (let((a"I'm ")(b"Slim ")(c"Shady")(d"real ")(e"lease stand up"))(format t"~{~A~}"(list a b c". Yes, "a"the "d c". All you other "b c"s are just imitating. So, won't the "d b c" p"e"? P"e". P"e""))) ``` [Answer] # Perl, 161 ~~164~~ bytes Not quite as short as [squeamish ossifrage's answer](https://codegolf.stackexchange.com/questions/35516/the-real-slim-shady#answer-35525), but I wanted to share the CamelCaseCompression, which no one else has used and allows the removal of many spaces and quotation marks. It does need a slightly longer text to become truly beneficial, though. ``` $_="0 1 2. Yes, 03 2. AllYouOther 1 2sAreJustImitating. So, won't3 1 24? 4. 4.";s/\d/qw(I'm Slim Shady TheReal PleaseStandUp)[$&]/ge;s/\B([A-Z])/ \L\2/g;print ``` Edit: Following Thaylon's suggestion, the `s/(\S)([A-Z])/\1 \L\2/g` substitution has been shortened by four characters. That doesn't pick up on comma-capital digraphs, though, so an extra space had to be inserted before "won't". [Answer] **PYTHON: ~~198~~ 193 bytes** ``` i,s,h,r,t="I'm ","Slim ","Shady","real ","lease stand up" print i+s+h+". Yes, "+i+"the "+r+h+".\nAll you other "+s+h+"s are just imitating.\nSo, won't the "+r+s+h+" p"+t+"?\n"+"P"+t+'. P'+t+'.' ``` [Answer] ## Golfscript - 140 (tweetable) ``` "I'm"" Slim"" Shady"". Yes, "3$" the real"3$". All you other"6$2$"s are just imitating. So won't"5$3$3$" p""lease stand up""? P"1$". P"1$"." ``` I'm Slim Shady. Yes, 3 the real 3. All you other 62s are just imitating. So won't 533 please stand up? P1. P1. [Answer] # [///](https://esolangs.org/wiki////), 131 bytes ``` /0/ Shady//1/lease stand up//2/ the real//3/ Slim0//4/I'm/43. Yes, 420. All you other3s are just imitating. So, won't23 p1? P1. P1. ``` [Try it online!](https://tio.run/##DcuxCoMwFIXh3ac4m4vkqHEvHbsVnDpe8FJTohFvRHz61OHfvt@i2KxWCltinGW6yI5RxRSWZZ1wbGRP5Fmxq0TS3zCGpSUHvuqFg3f4qDUY@tZVzxhxpQPpHnZvkF3xOywjLCFLDuvXVWNqcKa1zr3H1j2qd@dwV8of "/// – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/) (full program), ~~183~~ ~~180~~ ~~178~~ ~~173~~ 172 bytes *178 -> 173 bytes, thanks to Sara J* ``` fn main(){print!("{}{}{}. Yes, {0}{}{2}. All you other{1}{2}s are just imitating. So, won't{3}{1}{2} p{}? P{4}. P{4}.","I'm"," Slim"," Shady"," the real","lease stand up")} ``` [Try it online!](https://tio.run/##JYzNCsIwEITvfYoxl1Yoxb@7ePQm9ORxodFG0qQkW6SEPHtMLAuzM8PwucVzSi@DiZRp9mF2yvCuESGW6/CUvkU4lHSKXXXTGqtdYHmULhxL6UFO4pM5UJNiYmXeXdXbFl9rag7nuO0wh3itHuGSqX8VrbjXU1b0Wm1/pGEtJtPhJOnstSQv4ZnMgGUW@5jSDw "Rust – Try It Online") [Answer] # C# 226 ``` class P{static void Main(){System.Console.Write("{0}{1}{2}. Yes, {0} the{3} {2}.All you other{1}{2}s are just imitating.So, won't the{3}{1}{2} please{4}up?Please{4}up. Please{4}up.","I'm"," Slim ","Shady"," real"," stand ");}} ``` [Answer] # Java, ~~308~~ ~~301~~ ~~298~~ ~~292~~ 258 Java is a bit verbose, but here is my try: ``` class P{public static void main(String[]c){String s=" Shady",t=" the real",l="lease stand up",i=" Slim",m="I'm";System.out.format("%s%s%s. Yes, %s%s%s.\nAll you other%s%ss are just imitating.\nSo, won't%s%s%s p%s?\nP%s. P%s.",m,i,s,m,t,s,i,s,t,i,s,l,l,l);}} ``` [Answer] **MySQL: 273 267** ``` set @i="I'm", @s="Slim", @h="Shady", @r="real", @t="stand", @p="lease stand up";select concat(@i," ",@s," ",@h,". Yes, ",@i," the ",@r," ",@h,".\r\nAll you other ",@s," ",@h,"s are just imitating.\r\nSo, won't the ",@r," ",@s," ",@h," p",@p,"?\r\nP",@p,". P",@p,"."); ``` [Answer] # Ruby: 211 This one is impressive since simply printing the text is more efficient, but this is way cooler. ``` puts Zlib.inflate("eJxdjDEKwzAQBHu9Yjs3Rl8ILt0FVKU88GErnCWhO2H8e6sIwUmzxQyz87AjSOyz0XJ6vFhHzB3axqhM8hFuEsGZG3IX9ZYoqDLeTQ1xj0YW0+pdyCOOnAa7/XwTFGFShhqlBa083PMXePyDC15NOP8=".unpack("m0")[0])#I'mSlimShadyrealstand ``` [Answer] # JavaScript ~~259~~ ~~240~~ 238 bytes Not that good but might as well post an answer. ``` b=String.prototype,b.a=b.replace,alert("123. Yes, 16537All you other 23s are just imitating7So, won't 6523 p4?\nP4. P4.".a(/1/g,"I'm ").a(/2/g,"Slim ").a(/3/g,"Shady").a(/4/g,"lease stand up").a(/5/g,"real ").a(/6/g,"the ").a(/7/g,".\n")) ``` More readable version : ``` b=String.prototype b.a=b.replace alert("123. Yes, 16537All you other 23s are just imitating7So, won't 6523 p4?\nP4. P4." .a(/1/g,"I'm ") .a(/2/g,"Slim ") .a(/3/g,"Shady") .a(/4/g,"lease stand up") .a(/5/g,"real ") .a(/6/g,"the ") .a(/7/g,".\n") ) ``` [Answer] # F#, 250 242 ``` [1..21]|>List.iter((function|1|5->"I'm "|2|9|13->"Slim "|4->". Yes, "|6|12->"the real "|8->".\nAll you other "|11->"s are just imitating.\nSo won't "|15->" p"|16|18|20-> "lease stand up"|17->"?\nP"|19->". P"|21->"."|_->"Shady")>>printf "%s") ``` More readable version with line breaks: ``` [1..21]|>List.iter((function |1|5->"I'm " |2|9|13->"Slim " |4->". Yes, " |6|12->"the real " |8->".\nAll you other " |11->"s are just imitating.\nSo won't " |15->" p" |16|18|20-> "lease stand up" |17->"?\nP" |19->". P" |21->"." |_->"Shady")>>printf "%s") ``` [Answer] # JavaScript (ES6), ~~165~~ 163 bytes ``` f= _=>`${a="I'm"}${b=` Slim${c=` Shady`}`}. Yes, ${a+(d=" the real")+c}. All you other${b}s are just imitating. So, won't${d+b} p${e="lease stand up"}? P${e}. P${e}.` console.log(f()); ``` ]
[Question] [ # The Challenge: Print every 2 letter word [acceptable in Scrabble](http://phrontistery.info/scrabble3.html) using as few bytes as possible. I have created a text file list [here](http://pastebin.com/raw.php?i=iYLyuS1N). See also below. There are 101 words. No word starts with C or V. Creative, even if nonoptimal, solutions are encouraged. ``` AA AB AD ... ZA ``` # Rules: * The outputted words must be separated somehow. * Case does not matter, but should be consistent. * Trailing spaces and newlines are allowed. No other characters should be outputted. * The program should not take any input. External resources (dictionaries) cannot be used. * No standard loopholes. Wordlist: ``` AA AB AD AE AG AH AI AL AM AN AR AS AT AW AX AY BA BE BI BO BY DE DO ED EF EH EL EM EN ER ES ET EX FA FE GO HA HE HI HM HO ID IF IN IS IT JO KA KI LA LI LO MA ME MI MM MO MU MY NA NE NO NU OD OE OF OH OI OM ON OP OR OS OW OX OY PA PE PI QI RE SH SI SO TA TI TO UH UM UN UP US UT WE WO XI XU YA YE YO ZA ``` [Answer] # Python 3, ~~194~~ 188 bytes ``` s="BI ODEXIF BAAX ASOHER LOXUMOPAGOR KI US AMY BOITONOSI MMEMINANEHI UPI AYAHOYOWOMUNUHAID PEFARED QIS BEN JOFETAE KAT ABYESHMALI UTI ZADOELAWE " while s:" "in s[:2]or print(s[:2]);s=s[1:] ``` Almost definitely not the shortest method, but I thought this would be a good start. Try to pack each pair into paths by overlapping as much as possible (e.g. `"ODEX..."` = `["OD", "DE", "EX", ...]`). Spaces are used to separate paths, and any pairs with a space in it is removed (the trailing space is to prevent a single `E` from being printed at the end). I also tried regex golfing this but it was longer. [Answer] # CJam, ~~96~~ 94 bytes ``` 0000000: 31 30 31 2c 22 5a 0a d0 fd 64 f6 07 a3 81 30 f2 101,"Z...d....0. 0000010: c2 a5 60 0c 59 0f 14 3c 01 dd d1 69 7d 66 47 6e ..`.Y..<...i}fGn 0000020: db 54 e5 8f 85 97 de b9 79 11 35 34 21 cb 26 c3 .T......y.54!.&. 0000030: f0 36 41 2b b4 51 fb 98 48 fc cb 52 75 1f 1d b1 .6A+.Q..H..Ru... 0000040: 6b c3 0c d9 0f 22 32 36 30 62 33 36 62 66 7b 3c k...."260b36bf{< 0000050: 31 62 32 35 6d 64 2d 35 35 7d 27 41 66 2b 1b25md-55}'Af+ ``` The above is a hexdump, which can be reversed with `xxd -r -c 16 -g 1`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=101%2C%22Z%0A%C3%90%C3%BDd%C3%B6%07%C2%A3%C2%810%C3%B2%C3%82%C2%A5%60%0CY%0F%14%3C%01%C3%9D%C3%91i%7DfGn%C3%9BT%C3%A5%C2%8F%C2%85%C2%97%C3%9E%C2%B9y%1154!%C3%8B%26%C3%83%C3%B06A%2B%C2%B4Q%C3%BB%C2%98H%C3%BC%C3%8BRu%1F%1D%C2%B1k%C3%83%0C%C3%99%0F%22260b36bf%7B%3C1b25md-55%7D'Af%2B). Depending on what exactly counts as *separated somehow*, the byte count could be lowered to **93** or even **92**: * If we replace `-55` with `59`, the words will be separated by non-breaking spaces (0xA0). * If we replace `-55` with `W`, the words will be separated by at-signs (0x40). ### Idea We can encode each pair of letters **xy** as **(ord(x) - 65) × 25 + (ord(y) - 65)**.1 Instead of storing the resulting integers, we'll store the differences of all pairs that correspond to two adjacent words (sorted alphabetically). The highest difference is **35**, so we consider them digits of a base **36** integer and convert that integer into a a byte string. ### Code ``` 101, e# Push [0 ... 100]. "…" e# Push the string that encodes the differences/increments. 260b e# Convert from base 260 to integer. 36b e# Convert from integer to base 36 (array). f{ e# For each I in [0 ... 100]: e# Push the base 36 array. < e# Keep it's first I elements. 1b e# Compute their sum. 25md e# Push quotient and residue of the sum's division by 25. -55 e# Push -55 = '\n' - 'A'. } e# 'Af+ e# Add 'A' to all resulting integers. This casts to Character. ``` 1 Since the second letter is never a **Z**, using **25** instead of **26** is enough. [Answer] ## PHP 224, 218, 210 206 ``` foreach(explode(",","I19SR,9ZY8H,,CNK,5JRU0,H,CN4,G0H,H160,CN4,75,CU9,AMIHD,MTQP,HQOXK,7L,74,G,CXS,CU9,HTOG,,CNK,MHA8,CNL,1")as$a){$b++;for($c=0;$c<26;$c++)echo base_convert($a,36,10)&pow(2,$c)?chr(96+$b).chr(97+$c)." ":"";} ``` ``` aa ab ad ae ag ah ai al am an ar as at aw ax ay ba be bi bo by de do ed ef eh el em en er es et ex fa fe go ha he hi hm ho id if in is it jo ka ki la li lo ma me mi mm mo mu my na ne no nu od oe of oh oi om on op or os ow ox oy pa pe pi qi re sh si so ta ti to uh um un up us ut we wo xi xu ya ye yo za ``` --- Definitely not a great score, but I liked the challenge. I create a table of the options, created a bitwise system to flag which options are valid. [![enter image description here](https://i.stack.imgur.com/p9EJy.png)](https://i.stack.imgur.com/p9EJy.png) Then I base-36 encoded those options to get the string: ``` "I19SR,9ZY8H,,CNK,5JRU0,H,CN4,G0H,H160,CN4,75,CU9,AMIHD,MTQP,HQOXK,7L,74,G,CXS,CU9,HTOG,,CNK,MHA8,CNL,1" ``` Note the 3rd entry in that string array doesn't have a value, because C has no options. To print the values, I just convert the valid options to chars. There might be something I could do to reduce recognising that there are no words ending in C, J, K, Q, V or Z, but I can't think of a method to reduce it atm. --- By transposing the table, there are more empty elements and the data encodes a little more compactly which shaved off a few bytes. The array is now printed in a different order: ``` foreach(explode(",","UB1YB,1,,CUP,CLMEJ,CUO,1,SG0H,5J9MR,,,H,MX01,MTXT,CYO5M,MTQ8,,CNL,MTXT,MHAP,50268,,CN5,CNL,FSZ,,")as$a){$b++;for($c=0;$c<26;$c++)echo base_convert($a,36,10)&pow(2,$c)?chr(97+$c).chr(96+$b)." ":"";} ``` ``` aa ba fa ha ka la ma na pa ta ya za ab ad ed id od ae be de fe he me ne oe pe re we ye ef if of ag ah eh oh sh uh ai bi hi ki li mi oi pi qi si ti xi al el am em hm mm om um an en in on un bo do go ho jo lo mo no so to wo yo op up ar er or as es is os us at et it ut mu nu xu aw ow ax ex ox ay by my oy ``` Thanks to Ismael for the explode and for loop hints. ``` foreach(explode(3,UB1YB3133CUP3CLMEJ3CUO313SG0H35J9MR333H3MX013MTXT3CYO5M3MTQ833CNL3MTXT3MHAP35026833CN53CNL3FSZ)as$d)for($e++,$f=0;$f<26;$f++)echo base_convert($d,36,10)&pow(2,$f)?chr(97+$f).chr(96+$e)." ":""; ``` --- With an update to php5.6, `pow(,)` can be replaced by `**` saving another 4 bytes. ``` foreach(explode(3,UB1YB3133CUP3CLMEJ3CUO313SG0H35J9MR333H3MX013MTXT3CYO5M3MTQ833CNL3MTXT3MHAP35026833CN53CNL3FSZ)as$d)for($e++,$f=0;$f<26;$f++)echo base_convert($d,36,10)&2**$f?chr(97+$f).chr(96+$e)." ":""; ``` [Answer] # Ruby, 166 bytes Borrowing [sp3000's](https://codegolf.stackexchange.com/a/54609/4372) neat method for encoding the words into a compact string. The kicker here is the short method for decoding it back into the two-letter words: Using a lookahead in the regex passed to String's scan method in order to extract overlapping matches, not containg space: ``` puts "BI ODEXIF BAAX ASOHER LOXUMOPAGOR KI US AMY BOITONOSI MMEMINANEHI UPI AYAHOYOWOMUNUHAID PEFARED QIS BEN JOFETAE KAT ABYESHMALI UTI ZADOELAWE".scan /(?=(\w\w))/ ``` # Ruby, 179 bytes My own approach: Generate all two-letter words between `AA` and `ZA`, and select the valid ones using a base 36 encoded bitmask: ``` i=-1 puts ("AA".."ZA").select{|w|"djmsjr5pfw2omzrfgydo01w2cykswsrjaiwj9f2moklc7okcn4u2uxyjenr7o3ub90fk7ipdq16dyttg8qdxajdthd6i0dk8zlmn5cmdkczrg0xxk6lzie1i45mod7".to_i(36)[i+=1]>0} ``` [Answer] # Perl, 167 164 157 bytes ``` "AMAEDOXUHALAXISHENUNUPABEFAHIDEMYESOHOSITAAGOYAYAWOWETOINODOREX KIFEHMMER BYONELI BOEMUS PELOMI UMOFAD BATAR KANAS JOPI UTI ZAI BI QI"=~/$_/&&say for AA..ZZ ``` Wrote a separate script to group the letters together as compact as possible into a string that contained all the valid 2 letter words. This then iterates over all of the two letter words and prints the valid ones, one per line. Run with `perl -M5.10.1 script.pl`. [Answer] # C,155 bytes **Golfed version** ``` i,v;main(){for(;++i-408;" >b  Ùc :oÒ¹ i ;¹ w so@)ia ¥g¨¸ ´k¦ase    Ù{§k {"[i/8]>>i%8&1||printf("%c%c%c ",i/8%2*v,i/16+65,!(i/8%2)*v))v="YUOIEMHA"[i%8];} ``` **Output** ``` YA HA AA BY BO BI BE BA AB DO DE OD ID ED AD YE OE HE AE FE FA OF IF EF GO AG UH OH EH AH OI HI AI JO KI KA LO LI LA EL AL MY MU MO MI ME MM MA UM OM EM HM AM NU NO NE NA UN ON IN EN AN YO HO PI PE PA UP OP QI RE OR ER AR SO SI SH US OS IS ES AS TO TI TA UT IT ET AT WO WE OW AW XU XI OX EX AX OY AY ZA ``` **Ungolfed version** The 51-byte magic string in the golfed version contains many characters beyond ASCII 126, which have almost certainly been mangled into Unicode equivalents. The ungolfed version uses hex instead, and as a constant rather than a literal. Also, the ungolfed version separates the words with a newline, which makes it easier to copy and paste into Excel, order the list and compare with the required one. ``` char a[]= {0xFF,0x3E ,0x62,0x7F ,0xFF,0xFF ,0xEB,0x63 ,0xFF,0x3A ,0x6F,0xE3 ,0xFB,0x7F ,0xFF,0x69 ,0xFF,0x3B ,0xFB,0xFF ,0x77,0xFF ,0x73,0x6F ,0x40,0x29 ,0x69,0x61 ,0xFF,0xBE ,0x67,0xF9 ,0xF7,0xFF ,0xEF,0x6B ,0xB3,0x61 ,0x73,0x65 ,0xFF,0xFF ,0xFF,0xFF ,0xEB,0x7B ,0xF5,0x6B ,0xFF,0x7B ,0x7F}; //iterate through i = 16*letter + 8*order + vowel i,v;main(){for(;i++-408;a[i/8]>>i%8&1||printf("%c%c%c\n",i/8%2*v,i/16+65,!(i/8%2)*v))v="YUOIEMHA"[i%8];} ``` **Explanation** If we expand the definition of vowel to include the 8 letters AHMEIOUY, we observe that all words consist of one vowel and one other letter (which may or may not be a vowel.) Therefore, for all the words ending in a vowel, we need a table of 26 bytes, one for each first letter, with the individual bits corresponding to the vowel. We need a similar table for the words starting with a vowel, except that this time we only need 25 bytes, as there is no word ending in Z. The two tables are riffled together to create the final table. In order to avoid any ASCII codes in the region 0..31, the two least common "vowels" M and H are assigned to the 6th and 7th bit, and the encoding considers 1 for an invalid word and 0 for a valid word. Since there is no consonant which pairs with both M and H it is possible to ensure at least one of these bits is a 1. The 8th bit is assigned to A, which is the most common vowel, to try to limit the non-ASCII characters (still there are rather a lot of them.) The tables used are below. For words containing 2 vowels, I gave priority to the first letter as being considered the "vowel" and the second letter as the "letter." An exception to this is words starting with M, as this avoids a clash between MM and HM. Hex encoding of words starting with a vowel ``` 3E 7F FF 63 3A E3 7F 69 3B FF FF 6F 29 61 BE F9 FF 6B 61 65 FF FF 7B 6B 7B AA AB AD AE AG AH AI AL AM AN AR AS AT AW AX AY HA HE HI HM HO ED EF EH EL EM EN ER ES ET EX ID IF IN IS IT OD OE OF OH OI OM ON OP OR OS OW OX OY UH UM UN UP US UT YA YE YO ``` Hex encoding of words ending with a vowel ``` A H M E I O U Y FF BA BE BI BO BY 62 FF DE DO EB FF FA FE 6F GO FB FF FF JO FB KA KI 77 LA LI LO 73 MA MM ME MI MO MU MY 40 NA NE NO NU 69 FF PA PE PI 67 QI F7 RE EF SH SI SO B3 TA TI TO 73 FF FF WE WO EB XI XU F5 FF ZA 7F ``` [Answer] # Java, 484 448 407 391 389 bytes My first try ``` public static void main(String[]a){int[]x={57569742,35784706,0,2099200,5534148,35651584,2048,35792896,5247168,2048,33685504,33687552,35794978,35653664,7746958,35782656,131072,2097152,395264,33687552,551296,0,2099200,131104,35653632,33554432};for(Integer i=0;i<26;i++){for(int z=0;z<26;z++){if("".format("%26s",i.toString(x[i],2)).charAt(z)=='1'){System.out.format("%c%c ",'A'+i,'A'+z);}}}} ``` Formatted: ``` public static void main(String[] a) { int[] x = { 57569742, 35784706, 0, 2099200, 5534148, 35651584, 2048, 35792896, 5247168, 2048, 33685504, 33687552, 35794978, 35653664, 7746958, 35782656, 131072, 2097152, 395264, 33687552, 551296, 0, 2099200, 131104, 35653632, 33554432 }; for (Integer i = 0; i < 26; i++) { for (int z = 0; z < 26; z++) { if ("".format("%26s", i.toString(x[i], 2)).charAt(z) == '1') { System.out.format("%c%c ", 'A' + i, 'A' + z); } } } } ``` [Try it online](http://ideone.com/e.js/Sj3uEx) [Answer] # [Malbolge](https://github.com/TryItOnline/malbolge), 2118 bytes ``` D'``_#>nI||38h6/vdtO*)_^mI7)"XWfB#z@Q=`<)\xwvuWm32ponmfN+ibJfe^$\[`Y}@VUySXQPUNSLpJINMLEiC+G@EDCB;_?>=}|492765.R210p(-,+*#G'&feB"baw=u]sxq7Xnsrkjoh.fNdchgf_%]\a`Y^W{>=YXWPOsSRQ3OHMLKJIBfF('C<`#"8=<;:3W1w5.R2+q/('&J$)"'~D$#"baw=utsxq7Xnsrkjoh.fNdchgf_%c\D`_X|\>=YXWPOsSRQ3OHMLKJIBfFEDC%$@9]=6|:32V6/.3210)M-m+$)"'&%|Bcb~w|u;yxwvuWm3kpinmfe+ihgfH%cb[ZY}]?UZYRWVOs65KPIHGkKJIH*)?c&BA@?8\6|:32V6/.3210)M-,lk)"F&feBzbxw=uzyrwpon4Ukpi/mfkdc)g`ed]#DZ_^]VzZ<;QPt7MLQPOHlFEJIHAe(>C<;_?>765:981Uv.32+*)Mnm%$)(!Efe{zy?}|{zyxqpo5mrkpoh.fNdihg`ed]#DZ_^]Vz=YRQuUTMqQ32NMLEDhHG@(>C<;_?>76;:3W76v43,+O/.nm+*)"Fgf${z@a}v{zyr8vo5Vrqj0nmfN+Lhg`_%cbDCY}@VUySRWPt76Lp3ONMLEDhHG@(>C<;_"8\6|:32V0v.Rs10/.'&+$H('&feB"!x>|^]srwvun4Ukpi/gfe+Lbaf_%cE[`Y}@?[TxRWPUNMLKo2NGFjD,BAeED&<A:^>=6|:32V6v.R21*/(L,+*#"!E}|{z@xw|{t:[qpotsrk1Rhmlkd*Kgfe^$bDZ_^]VzZ<;QuUTMqKJOHGkEJCBA@dD=<;:^>=6|:32V654t,+O).',+*#G'&feBzbx>|^]yr8vXnsrkjoh.fkdcbg`&^Fba`Y^WVzZ<XWPUTMqQ3INMFjD,BAe?>=B;_9>7<54X8765u-Q10)o'&J$)"!~%${A!x}v<]\xwpun4rTpoh.leMchgf_d]#DZ_^]VzZYR:Pt7SLKPOHlFEJIHAeED&<`@"87<5Y98165.3,P*/(-&+$H(!~}C#c!x}|u;\[wvun4lTjih.fN+Lbgfe^c\"CY}@VUyYXWPOsSRKJIHlLE-IBAeE'&<`@"87<5Y98165.3,Pq/.-,+*#G'&fe#"!x>|{zyr8Yotml2ponPlkdcb(fH%]\[`Y^W{zZ<XWPUTMq4JIHMLEi,BA@d>=B;:9]7};:3W7wv.3,+O)o'&J*)('g%${Ay~}v{zyrq7otmrqpoh.fejiha'eG]\[ZY}@VUy<;WVOsSRQPImM/KJIBAe(>=aA:^>=6|:32V65u-Qr0/.'K+$j"'~De#zy~wv<]yrqpo5srkjohg-kdib(feG]b[Z~^]\UTYRvP8TSRKJIHlLKD,BAe?>=B;_?>7<;:981U54t,+O)o'&Jkj('&}C#"bx>_{tyr8vuWVl2pihgle+ihgfH%cEDZ~XWVUy<XWPUTMqQP2NGLEiCBGF?>b%A@?87[;:zy1U54t210/.'K+$j"'~De#zy~wv<zyxwp6Wmlqpohg-kdib(feG]ba`Y^W{>=YXWPOs65KJIHl/KJIBA@dDCB;:9]=<;:zy1Uvu3,P0)o'&J$#(!~D|#"y?}v{zyr8vXnml2ponPledc)gfH%c\D`_^]VzZ<;QVOTSLpPIHGkKJCBG@dD=<;:^>=6|:32Vw543,+*N.nm+*)"F&feB"y~}|{ts9qvonsl2ponmfN+Lha`e^$\[Z_X|\UTYRQVOsM5KJOHGFjD,BA@d>=B;:9]=};4X81w5.R210)o'&J$j"'~%|{"y?w_u;y[wpun4Ukponmfe+Lha'eGc\[!B^WV[TxXQ9ONrRQ32NMLEDh+AeE'&<`#"8=<;:3W7wv.3,+O/.'m+*)(!EfeBcbx>_{tsxwvun4Ukpi/POkdcha'_d]#DZ_^]VzZ<RQPUNMqQ3ONGkE-IBAeED=BA:9]=<|43870/St,+O/.-ml*)(!Ef|Bcb~w|u;y[Zvun4rTpoh.fN+cKgf_%cE[!BXWV[ZSwWP8TSLpJIHMLEJIBf)d'=aA@">=<5Y98165.3,Pq)('K%*#"!EfeBcyxwvu;yxwvuWm3~ ``` [Try it online!](https://tio.run/##bZXVeupQEEafhaBBi7sHK05xt0BbEpxggVfvmdnBTr/ecPkzWbPm3/yAGy64Kfvzw6j7/Z48ME@JotX16TAJ421eS/e6fMpJU/XaJCI/hYr@vo9uH/bCrsZbLcvFnJ/kdF/D9wnbVbRb/cYlVK0cP@rFQiX3kVm@p3LZTOwrqkuEYkw04u0FA/6LaHNbnA67sWQxvy01Br1OK0@oVRM2Qg0He/@uszmsnPX5Zj37XnwaJ7nx6HM66Sk77UG/0a2dA/5GvVbIbz5KRWs@mc2k31ORSVyjjvr6csrl93k91pp5j@m6lUmjVr0raEp9ZRRyKX37d/qozfR7dbH9dzrMrlSE3B2/Q/RYLVWHyWiF2emsgddhukopRkbD617ceY83MrPlF5BhdV@QnlSOhq1m49IJVpqNUq2a3zjs6UIqmZhBelJLB0eqSDgUdLV/p@u5GU3FkcxpeIDZT8f1HojbKpBu4iez8Yie9tlxR840e91O9dT0eYuFrTObKRbySS4eg/QwqwlEfcgdiHvcLnNFgHSdls7OeaWC1shiE/Z8OgYvIvweVsuFnV/PlhIZmP013d8oFXeVcnZVtFpwq8xnMhF6piN3p0OwWfW6vMk45@E/qPh0ojifQoOLAOlrl7CwV9er7zfiTAbSgfuQid6cKdVgdkdmac3/SqfuZN4EY2ljfjMZ1SqdIqmRnJEdAmK3s1kD9xuZKXDPDAe41RgxMtgqHyC9ArnphSWXiH8z@kiYjTEqX9jTDdy3KqCRWpMmg0ZSshgyCR324nnraQGZLThjLn3y3GysTU/R9@ELd0Im/Z6Hrcbeo7DPMYMuPtPtti2QoY3qp@@wVZwdyTyNhK0Op31VNz4kvmM6GClxh2u6zQ53BNfkDjh9dlvdBbvdGYrgzELyXXZVKs5h2eEi@Dpwq0sgsy7jVjk2S3x/caZR8gD3j0z6xRkk0w9RLkhvgDNwq1Z9AcgYCHfZ9RKVjyAdfG@3CHeu/P2FzgB3JDNqU7et3q8JTecyMUMKuav/SF@ZjM8mkJOtEmcaiy3PYc8UOCSjgWvqYM9AEzzJ2CAde0aP3JGMx91xXoiRe/AduSMZLa1RT5HM8SoZuXJC@npFfGfhCwZqNgHpTWl2nxdvFZqgkOKzJmwCvCb/4NUZ5L5GI9M6xTf2DCs/Ha974H7EXLu01alhNv6C2SEdmuDa7bQr5UZJKLjKdzLpl63CNYE5eKs3Z3D22Tf4DtwpcKZ33qIzu1oVyMCVco@eiTHNa72Gs9@dKYDv2MCRRDwYGCqxZ5wtr@d0JOkW81@zQxPsl44azyGZ19n/b2BoMZxdIgO@Rwl3tB7ThR1s9WakHJxhRDkFPXNrgvr8vlUWWwxnxwa@X1M1X4bX49aRMPvva9rbsWe0uXvPkCaArcKtbtwrYTHfcPe3KfM56JO3qYn9jtwhfZO1k1uVrunhjP/ihWuSXo/7NSEZpXiG2fc96PcWuSbomQXp9wxxZtRuySJwq9Az9aI7n1uXHh2pu/n@eJvuRgJ3nJ00MLweZKubw7PFCnnwHdJfb9VXwncVmyCfg56RronxR8KEu2izupxvpo8tSTfwnJT@fJtaTeHRBEBmlJ5KHSmLgDOt5se@hkbiq43XhC8fPVaD7yEq4P/vVuGO0krSkTg7efMeL9/15@cf "Malbolge – Try It Online") [Answer] ## Matlab, 177 bytes Generate a binary matrix defining all allowed pairs of letters, reshape it and base-64 encode it. The base-64 encoded string (`'CR+ ... % '`) is used as data in the program. The program reverses operations to unpack the matrix, and then reads the allowed pairs: ``` x=de2bi('CR+"'' 1$$ L*\"%$!! ! $!04P@<W( 0$ 1"%$$100@RZP4 $$ 0$ ! 1$$$$1 0 P ( $ 0 0$ ! # % '-32)';[i,j]=find(reshape(x(1:650),26,[])');char([j i]+64) ``` [Answer] *(Warning, this answer is not programmatically interesting)* Since all words are two characters long, we can smash them all together and then rip them apart again using a simple regular expression. Any regex-friendly language can do this, some more efficiently than others: # Grep (via Bash), 215 bytes ``` grep -o ..<<<AAABADAEAGAHAIALAMANARASATAWAXAYBABEBIBOBYDEDOEDEFEHELEMENERESETEXFAFEGOHAHEHIHMHOIDIFINISITJOKAKILALILOMAMEMIMMMOMUMYNANENONUODOEOFOHOIOMONOPOROSOWOXOYPAPEPIQIRESHSISOTATIT ``` # Javascript, 224 bytes ``` alert("AAABADAEAGAHAIALAMANARASATAWAXAYBABEBIBOBYDEDOEDEFEHELEMENERESETEXFAFEGOHAHEHIHMHOIDIFINISITJOKAKILALILOMAMEMIMMMOMUMYNANENONUODOEOFOHOIOMONOPOROSOWOXOYPAPEPIQIRESHSISOTATITOUHUMUNUPUSUTWEWOXIXUYAYEYOZA".match(/../g)) ``` # Perl, 225 bytes ``` $_="AAABADAEAGAHAIALAMANARASATAWAXAYBABEBIBOBYDEDOEDEFEHELEMENERESETEXFAFEGOHAHEHIHMHOIDIFINISITJOKAKILALILOMAMEMIMMMOMUMYNANENONUODOEOFOHOIOMONOPOROSOWOXOYPAPEPIQIRESHSISOTATITOUHUMUNUPUSUTWEWOXIXUYAYEYOZA";s/../$&\n/g;print ``` # Python, 245 bytes ``` import re print re.sub(r'..','\g<0>\n',"AAABADAEAGAHAIALAMANARASATAWAXAYBABEBIBOBYDEDOEDEFEHELEMENERESETEXFAFEGOHAHEHIHMHOIDIFINISITJOKAKILALILOMAMEMIMMMOMUMYNANENONUODOEOFOHOIOMONOPOROSOWOXOYPAPEPIQIRESHSISOTATITOUHUMUNUPUSUTWEWOXIXUYAYEYOZA") ```   --- As a note, some of the answers here are longer than `echo`, which I'd consider a baseline: # POSIX shell, 307 bytes ``` echo AA AB AD AE AG AH AI AL AM AN AR AS AT AW AX AY BA BE BI BO BY DE DO ED EF EH EL EM EN ER ES ET EX FA FE GO HA HE HI HM HO ID IF IN IS IT JO KA KI LA LI LO MA ME MI MM MO MU MY NA NE NO NU OD OE OF OH OI OM ON OP OR OS OW OX OY PA PE PI QI RE SH SI SO TA TI TO UH UM UN UP US UT WE WO XI XU YA YE YO ZA ``` [Answer] # Bash, 179 bytes ``` echo U`sed -r 's/./& &/g'<<<HAABADEDOEFAEHELAGOFEMAHINAISHMENERESITALOHOMMONOPAMUMYAWETOSOWOYOXUNUPEXI`F `grep -o ..<<<ANARASATAXAYBEBIBOBYJOKAKILIMIOIDOIDORPIQITIUSUTYEZA` ``` * Saved 7 bytes thanks to Adam Katz comment It uses `sed` to do regex replacement. First regex input is based on [Sp3000 idea](https://codegolf.stackexchange.com/a/54609/42928) while second regex uses common input without spaces. Explanation: ``` echo print to standard output the following U boundary U character sed -r [etc] the result of replacing regex . select a character & & replace it for: matched char, space, matched char g do it globaly for every character <<<HAAB[etc] string input based on Sp3000 idea => HA AA AB ... F boundary F character sed -r [etc] the result of replacing regex .. every two characters <space>& for space+matched character g do it globally <<<ANAR normal input => AN AR ... ``` [Answer] # CJam, ~~100~~ 98 bytes ``` 'A'@" ©Ô&ñ±ð¨9_AÚá¼thÁätÑû¨HÙH&J3p¼ÛèVçckùá%´}xà41"260bGb{_{+N2$2$}{;;)'@}?}%-3< ``` [(permalink)](http://cjam.aditsu.net/#code=%27A%27%40%22%06%C2%8F%20%04%C2%A9%C3%94%26%12%C2%91%1A%C3%B1%0B%C2%B1%C3%B0%C2%A89_A%C3%9A%C3%A1%C2%BCth%C3%81%C3%A4%C2%8Et%06%C3%91%C3%BB%C2%8A%C2%A8H%C3%99%03H%C2%94%26%C2%95%16J3p%C2%91%C2%BC%C3%9B%C3%A8V%C3%A7c%C2%92k%C3%B9%C3%A1%06%25%C2%B4%1B%7Dx%C3%A041%22260bGb%7B_%7B%2BN2%242%24%7D%7B%3B%3B%29%27%40%7D%3F%7D%25-3%3C) * Saved two bytes via preinitialized variables (thanks Dennis!) This is my first CJam entry, so there is probably the potential for some more golfing. However, I came up with a way to compress the list of characters down to 63 bytes which, hopefully, someone else will find helpful. ## Compression Method So far most methods that I saw encoded both letters of each word. However, when we put the words in alphabetical order, the first letter doesn't change very often, so it seems wasteful to encode it explicitly. I encode only the last character of each word, and include a special item whenever the first character should increment. The characters are encoded as the first character, then a list of differences. Since there are no duplicate words, the differences must all be at least `1`. Thus I can use `0` as a separator item. (Note that I must then store the first letter of each subsequence as one-indexed, otherwise there would be confusion between 'rollover first character `0`' and 'start with A `0`'.) Since the differences in this case are never greater than 15, we can use base-16 and pack two (4-bit) items into each (8-bit) byte. (In the actual code I converted from base-260 instead of base-256 to avoid issues with unprintable characters.) [Answer] # [Python 3](https://docs.python.org/3.8/), 148 bytes ``` a=97 for n in b"!B$E'Hil-Nr3TWx9aEio9eodfHl-Nr3TxaEOaEi-odfN3TOaiaioaEi-ou9aEoudEfHi-N0r3Wx9aEiI%(ioaio(-N03TeoIuaEoa":a+=n%3;print("%c%c"%(a,n|96)) ``` [Try it online!](https://tio.run/##JcvNCsIwEATgu09Rg8EULQgBa5RehEB6aS8Bz2t/cEGyJTRQwXePwR7nm5npM7/IycvkY4RKlZuRfOYydNmTbe87vTf4Lhov7WNRoJHUQP1oVlpAt8mKJI20LSAg/XNIUwq9Hg0WzcnL9VtzkXokkUzageqQVsCucKgcl7fJo5sF4x3vGBdwdF91zvMYfw "Python 3.8 (pre-release) – Try It Online") Prints lowercase. The idea is to encode, for each of the 101 two-letter Scrabble words in order: * Whether the first letter is 0, 1, or 2 positions higher than the previous word's (3 options) * The second letter (26 options) The 78 potential values fit easily in one byte per each entry `n`, and moreover within printable 7-bit ASCII. The second letter is encoded in the last five bits, which lets the expression `96|n` set the first two bits to ones to get its lowercase ASCII value. The first letter delta (0, 1, or 2) could be encoded in the first two bits, but it's golfier to extract it as `n%3` by setting those two bits to whichever of `01`, `10`, or `11` gives the right value. Avoiding `00` let us avoid hitting unprintable characters in the range 0 to 31. This answer uses 101 bytes for the hardcode data string and the other 47 bytes for extraction logic, so it's over 2/3 data. The data can surely be compressed further, but of course at a tradeoff to extraction. Thanks to [mousetail for posting a Python answer](https://codegolf.stackexchange.com/a/252073/20260) whose incremental-delta technique inspired this one. [Answer] # [Zsh](https://zsh.sourceforge.io/) `--braceccl`, 163 bytes ``` s=(ABDEGHILMNRSTWXY AEIOY EO DFHLMNRSTX AE O AEIMO DFNST O AI AIO AEIMOUY AEOU DEFHIMNPRSWXY AEI I E HIO AIO HMNPST EO IU AEO A) for c ({ABD-UW-Z})echo $c{$s[++i]} ``` [Try it Online!](https://tio.run/##LY7PCoJAEMbvPcV38KCIj9DBcG0X0g3XRS061GIYBIbrKfHZt1kSZg7z@/4wXzs428/jZ8ZjupvemLez@zA9ZOzIxakoK1U3bYeUCdmBSWQ5/9OWGKQXCk9LVftL0GxQ@5TUyFjORVGeK7UVQYCBexstJ4Wi1Cy09yONds9xgkG40BeJbpLLGvVmGBGYJbDXOH7dVud@) Previously: ~~[169 bytes](https://#%20%5BZsh%5D(https://www.zsh.org/),%20169%20bytes%20%20%60%60%60bash%20for%20X%20($%7B(s::):-aABDEGHILMNRSTWXYbAEIOYdEOeDFHLMNRSTXfAEgOhAEIMOiDFNSTjOkAIlAIOmAEIMOUYnAEOUoDEFHIMNPRSWXYpAEIqIrEsHIOtAIOuHMNPSTwEOxIUyAEOzA%7D)((#X%3E90))&&W=$X%7C%7C%3C%3C%3C$W$X:l%20%60%60%60%60%20%20%5BAttempt%20This%20Online!%5D(https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3V6blFylEKGioVGsUW1lpWukmOjq5uLp7ePr4-gUFh4RHRCY5unr6R6a4-qe6uHlARCPSHF3T_TOAEr7-mS5ufsEhWf7Zjp45jp7-uWDB0Mg8R1f_0HwXVzcPT1-_gKBgoEEFQKlCzyLXYg9P_xKg0lIPoExwSLmrf4VnaCVQfZVjraaGhnKEnaWBpqaaWritSkRNjY2NjUq4SoRVDsTBUHfD3A8A))~~ , ~~[175 bytes](https://tio.run/##ZYzLCoJAGEb3PcVAIroI2mYWTDg2A@ofjuK4NNK0e2pUXp7dhlrGtzvn8DVVPmh6OziLBK8ssqbMcT2fB5GIt5gwiHcEUsumPyoyTPaQS@FCYdkeDw5wxOyEGZy/MIwvmEB4tYhNmettfC6PblLdWUkqyqCW6YNKw4MngRcL37Jv8Ci7lkig4oKUVqsMQ3f6eatpY7GcTXVdVaOFIrrONE0lUoRx6ocedeiWVHWKJv8bPg)~~ , ~~[182 bytes](https://tio.run/##ZcnRSsMwFIDhe58isFASxkCYN7pUiCy1B9Ke0bQkZQqrrLNRZ6fd0M367FWv5b/7/lPXDIx/DTqsbmKdpHm5VlhHcZJmDXqTb7F4xaI1tqzkXN1CZqx7UIBlrU3uNvIRG0j8PEqf8FnCC@AWkrJVESwyt5MK3qCL93iIFyb/UJ9QHNVJnm3ad8LYzI/Hgo70jHMXUr3090HA2MhdX55zHgQ2pO7q0PdCCGqpWzHmxfTi7/zKHaGO2tXwTXqyq7p9TSb/G34A)~~ [Answer] # C - ~~228~~ 217 Bytes - GCC ``` _;main(){char *z,*i="AABDEGHILMNRSTWXY AEIOY EO DFHLMNRSTX AE O AEIMO DFNST O AI AIO AEIMOUY AEOU DEFHIMNPRSWXY AEI I E HIO AIO HMNPST EOU IEO A A ";for(z=i;_++^26;)for(;*++z^32;putchar(_+64),putchar(*z),puts(""));} ``` Will update if I can get it smaller, just compile with gcc -w, ./a.out outputs perfectly. If there's any interest in an ungolfed, let me know. I can't think of any way to shorten it off the top of my head, (you can technically remove the quotes in puts and you'll still get a correct answer, the output just looks like garbage) so please let me know of anyways to shorten it [Answer] # C#, 348 bytes I had a go: ``` using System;class A{static void Main(){var a=new System.Collections.BitArray(Convert.FromBase64String("tnOciwgCCAAAAAggAFBxHIkAAAAACICIKABQQBgAAAIgIACAgCAAIqIgigCCADfWuIgAAAACAIAAAAAwCICAIAAAYRkAAAAAAggAgAAIIoAACA=="));int c, d;for(var i=0;i<652;i++){if(a[i]){c=Math.DivRem(i,26,out d);Console.Write("{0}{1} ",(char)('A' + c),(char)('@' + d));}}}} ``` Ungolfed: ``` using System; class A { static void Main() { var a = new System.Collections.BitArray(Convert.FromBase64String( "tnOciwgCCAAAAAggAFBxHIkAAAAACICIKABQQBgAAAIgIACAgCAAIqIgigCCADfWuIgAAAACAI" + "AAAAAwCICAIAAAYRkAAAAAAggAgAAIIoAACA==")); int c, d; for(var i = 0; i < 652; i++) { if(a[i]) { c = Math.DivRem(i, 26, out d); Console.Write("{0}{1} ", (char)('A' + c), (char)('@' + d)); } } } } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 140 bytes ``` K"aeiou"=H+-G+K\zKL.[`Z25.Bib32jdSfTs.e.e?nZ`0+@Gk@HY""byMc"ljjns 1u a 6jji0 o 2 100u 60hg0 2 k m 101v r 6hr7c s 4 8 g006 m hpg0 a 5 q g"d ``` [Try it online!](https://tio.run/##DYu9DoIwGEVf5aYrsfmoUl0MxAUSdNJFdOBXSlFAEBN8@drxnnPusHyUMTHLqqaf2T5yVqET33/xkd/SRHj80ORrocvz4zLxild@l6TkBGEbRFfG8uVUsKfW3QR3BjJIrRtCDwGXaIYkVZMdLV4WuF@MkGrcFpiwwQ41kbRGDTayZw9v1Kw05g8 "Pyth – Try It Online") Compression method: Since there's no `Z` in the second position of any word, use the reordered alphabet `bcdfghjklmnpqrstvwxyaeiou` to encode the validity of each of those letters as a second letter for each first letter (first letters are in alphabetical order). This is 25 bits per letter, or exactly 5 Base-32 digits. Since most consonants only take vowels as the second letter, I put vowels at the end to get mostly 1-digit numbers for them. I'm sure it could overall be improved by further analysis and reordering of the alphabet, although then the definition of the reordered alphabet would take up more bytes. ## Explanation ``` K"aeiou"=H+-G+K\zK # Define the reordered alphabet K"aeiou" # K := "aeiou" =H # H := -G # G.removeAll( +K\z # K + "z" + K # ) + K L.[`Z25.Bib32 # Define a lambda function for decompression L # y = lambda b: ib32 # convert b to int using Base 32 .B # convert to binary string .[`Z25 # pad to the left with "0" to the nearest multiple of 25 in length c"..."d # split the compressed string on " " yM # Apply y (above lambda) to each element # Intermediate result: List of binary strings # with 1s for allowed combinations .e # map over ^ lambda b (current element), k (current index): .e b # map over b: lambda Z (cur. elem.), Y (cur. ind.): +@Gk@HY # G[k] + H[Y] (G is the regular alphabet) ?nZ`0 "" # if Z != "0" else "" s # combine into one large list fT # remove all falsy values (empty strings) S # sort (if any order is possible, remove this) jd # join on spaces (if a normal list with the words is # allowed, remove this) ``` [Answer] # [Python](https://www.python.org), ~~174~~ 158 bytes -16 bytes thanks to @xnor ``` a=0 for x in b"BCBCBBDBBEBBDBBDEEGKcKQCCEBBEBBEEEfNEEECQCIFBWNITIGNEEECGEDEKGKBBCBEBCCBEBBDEE\X_BGNIGUFBCDBhKVMHEKN_":print('%c%c'%(a//27+65,a%27+65));a+=x-65 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY35yXaGnCl5RcpVChk5ikkKTk5A6GTi5OTK5h0cXV19072DnR2dgULubq6pvkBCedAZ083p3A_zxBPdzDf3dXF1dvd2wmo29XJ2Rms3dU1JiLeyd3P0z3UzcnZxSnDO8zXw9XbL17JqqAoM69EQ101WTVZXVUjUV_fyFzbzFQnURVMa2paJ2rbVuiamUJcCXUszNEA) String encodes the difference between each successive word. To find the word we need to sum all the letters then divmod 27. I beleive this is the shortest python answer so far. [Answer] # Python 3, 169 bytes ``` p,a="z",96 for i in "abdeghilmnrstwxyaeioy!!eodfhlmnrstxae!oaeimodfnstoaiaioaeimouyaeoudefhimnprswxyaeiie!hioaiohmnpst!!eoiuaeoa":print((chr(a:=a+(i<=p))+i)*(i>"_"));p=i ``` My first code golf. Uses a list of the second letter for each combination alphabetically, and changes the first letter if the next character is smaller than the previous (new set of words). Exclamation points are added to break up sections where the next character would be larger than the previous and to skip C and V. [Answer] # Python 3, 224 bytes ``` s='';i=int("AQHU9HU1X0313T1J9OMYMZZSRFWLCYT3POSE06UGHXDZN6H5SQSZIFCE6VEB",36) for c in range(26): b=i%6;i//=6;k=(1<<b)-1;j=i%(1<<k);i>>=k for d in 'AOIEHMUSTMNDFPYBCGJKLQRVWXZ': if j&1:s+=chr(c+65)+d+' ' j>>=1 print s ``` Uses bit masks of variable length to encode which second letters exist for each possible first letter. The bit masks can be 0,1,3,7,15 or 31 bits long. Bits are mapped to letters with `for d in 'AOIEHMUSTMNDFPYBCGJKLQRVWXZ':`, earlier bits are used for more common letters so that the bit masks can be short in most cases (usually 3 or 7 bits since most consonants are only followed by one of 5 vowels or Y M or H). Unfortunately the code to decode it negates the savings compared to more simple methods (the original list is only 303 bytes). [Answer] **PHP: ~~211~~ ~~209~~ 204** You have to turn warnings off, otherwise one will print in regards to the implicit creation of `$b` ``` for($a=65;$b<strlen($c="ABDEGHILMNRSTWXY!AEIOY!EO!DFHLMNRSTX!AE!O!AEIMO!DFNST!O!AI!AIO!AEIMOUY!AEOU!DEFHIMNPRSWXY!AEI!I!E!HIO!AIO!HMNPST!EO!IU!AEO!A");$b++)if($c[$b]!='!')echo chr($a).$c[$b].' ';else$a++; ``` Very fun. Early attempts were in the 250 range, but this is my slimmest yet. [Answer] ## CJam (99 bytes) This includes a few special characters, so it's safest to give a hexdump. (In particular, the character with value `0xa0`, corresponding to a non-breaking space, caused me quite a bit of trouble in setting up the online demo). ``` 00000000 36 37 36 22 c4 b2 2d 51 3f 04 93 5c 64 6c 8d 6e |676"..-Q?..\dl.n| 00000010 d7 f9 7d 97 29 aa 43 ef 04 41 12 e1 aa ce 12 4d |..}.).C..A.....M| 00000020 05 f3 1c 2b 73 43 a0 f0 41 c0 a7 33 24 06 37 a3 |...+sC..A..3$.7.| 00000030 83 96 57 69 9b 91 c4 09 c3 93 e1 ed 05 3b 84 55 |..Wi.........;.U| 00000040 d9 26 fd 47 68 22 32 35 36 62 33 38 62 7b 31 24 |.&.Gh"256b38b{1$| 00000050 2b 7d 2f 5d 7b 32 36 62 28 3b 36 35 66 2b 3a 63 |+}/]{26b(;65f+:c| 00000060 4e 7d 2f |N}/| 00000063 ``` [Online demo](http://cjam.aditsu.net/#code=676%22%C3%84%C2%B2-Q%3F%04%C2%93%5Cdl%C2%8Dn%C3%97%C3%B9%7D%C2%97)%C2%AAC%C3%AF%04A%12%C3%A1%C2%AA%C3%8E%12M%05%C3%B3%1C%2BsC%C2%A0%C3%B0A%C3%80%C2%A73%24%067%C2%A3%C2%83%C2%96Wi%C2%9B%C2%91%C3%84%09%C3%83%C2%93%C3%A1%C3%AD%05%3B%C2%84U%C3%99%26%C3%BDGh%22256b38b%7B1%24%2B%7D%2F%5D%7B26b(%3B65f%2B%3AcN%7D%2F). The approach is difference-encoding in base-26. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 1371 bytes Quite golfable, but I didn't put too much effort into it. ``` >+[+[<]>>+<+]>[-<<+<+>>>]-[-[-<]>>+<]>-[-<<<<+>>>>]<<<<<<..>>.<<.>+.>.<<.>++.>.< <.>+.>.<<.>++.>.<<.>+.>.<<.>+.>.<<.>+++.>.<<.>+.>.<<.>+.>.<<.>++++.>.<<.>+.>.<<. >+.>.<<.>+++.>.<<.>+.>.<<.>+.>.<------------------------<+.>.>.<<.>++++.>.<<.>++ ++.>.<<.>++++++.>.<<.>++++++++++.>.<--------------------<++.>.>.<<.>++++++++++.> .<-----------<+.>.>.<<.>++.>.<<.>++.>.<<.>++++.>.<<.>+.>.<<.>+.>.<<.>++++.>.<<.> +.>.<<.>+.>.<<.>++++.>.<-----------------------<+.>.>.<<.>++++.>.<<+.>++++++++++ .>.<--------------<+.>.>.<<.>++++.>.<<.>++++.>.<<.>++++.>.<<.>++.>.<-----------< +.>.>.<<.>++.>.<<.>++++++++.>.<<.>+++++.>.<<.>+.>.<-----<+.>.>.<--------------<+ .>.>.<<.>++++++++.>.<--------<+.>.>.<<.>++++++++.>.<<.>+.>.<---------<+.>.>.<<.> ++++.>.<<.>++++.>.<<.>++++.>.<<.>++.>.<<.>++++++.>.<<.>++++.>.<----------------- -------<+.>.>.<<.>++++.>.<<.>++++++++++.>.<<.>++++++.>.<-----------------<+.>.>. <<.>+.>.<<.>+.>.<<.>++.>.<<.>+.>.<<.>++++.>.<<.>+.>.<<.>++.>.<<.>++.>.<<.>+.>.<< .>++++.>.<<.>+.>.<<.>+.>.<------------------------<+.>.>.<<.>++++.>.<<.>++++.>.< <+.>.>.<----<+.>.>.<<+.>+++.>.<<.>+.>.<<.>++++++.>.<--------------<+.>.>.<<.>+++ +++++.>.<<.>++++++.>.<-------<+.>.>.<<.>+++++.>.<<.>+.>.<<.>++.>.<<.>+++.>.<<.>+ .>.<---------------<++.>.>.<<.>++++++++++.>.<------<+.>.>.<<.>++++++++++++.>.<-- ------------------<+.>.>.<<.>++++.>.<<.>++++++++++.>.<--------------<+.>.>. ``` [Try it online!](https://tio.run/##lVNRCsMgDP1/Vwn1BCEXET@2wWAM9lHY@Z3talETa2s/TPOeiS8m9/n2@jy/j3eMQp48BxFiCuIn5mSISJh8@v5AkMVMawEk8LqcE3FpE3LbvhpQntKxAwdI48Lo1NRZvKA6KoHKZM1PdtgB64iZjYpepdXGGeXoYReUUnlH6MO96thmc55hitT1VO@U07aXgapsyWIyYdUBBQ8nVVltYJYaw8IZ7WRG2iLA7oLhQFhtte7o99fVGcmzXLzWTiVzEjty6wQ4rFD7yn3Zu2U0dndMM5EtOBNwpUYD0TH@AA "brainfuck – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 91 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âG→æ£ilæα¿:√▒▓uøD¶[│█æä║¢v┼T↨σªΩ■&*φòb¡CÆ?ì▀┬6ù═╦±qBF!╘π╓╙'♣*ù&↕!£ä3±r⌡W-╓D╬☺╝ï╜²á5Æ÷§═ôφF; ``` [Run and debug it](https://staxlang.xyz/#p=83471a919c696c91e0a83afbb1b2750044145bb3db9184ba9b76c55417e5a6eafe262aed9562ad43923f8ddfc23697cdcbf171424621d4e3d6d327052a972612219c8433f172f5572dd644ce01bc8bbdfda03592f615cd93ed463b&i=) The only neat trick this answer uses is using the "," token to show a change in the first letter, rather than storing it for every word. Thanks to recursive for the idea of using the m operator [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 78 bytes ``` kaf»⌐±ẋ∆ṡẊ⊍¬5=↔ε{→₇-¥Kkṡw¹ǔ„L²Fŀwɖ"≠₌Ǎ›ꜝ%ǐ[Q∑)fĠλ=WτṪṫ¨≤‹r≬|{gǔs⁼∵2»16τ0€v¦øA+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYWbCu+KMkMKx4bqL4oiG4bmh4bqK4oqNwqw1PeKGlM61e+KGkuKChy3CpUtr4bmhd8K5x5TigJ5MwrJGxYB3yZZcIuKJoOKCjMeN4oC66pydJceQW1HiiJEpZsSgzrs9V8+E4bmq4bmrwqjiiaTigLly4omsfHtnx5Rz4oG84oi1MsK7MTbPhDDigqx2wqbDuEErIiwiIiwiIl0=) This uses a strategy similar to the CJam answer of storing differences between the second letters and signalling a new first letter with a 0. ``` »...» # Large integer 16τ # Convert from base 16 0€ # Split on zeroes v¦ # Take the cumulative sums of each list of numbers øA # For each each number, get the nth letter + # Prepend each of corresponding items of... kaf # The lowercase alphabet, as a list of characters ``` [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 148 bytes ``` A[BDGHLMNRSTWXY]|E[DFHLMNRSTX]|I[DFNST]|O[DFHIMNPRSWXY]|U[HMNPST]|[ABFHK-NPTYZ]A|[ABDFHM-PRWY]E|[ABHKLMPQSTX]I|[BDGHJLMNSTWY]O|[BM]Y|[HM]M|[MNX]U|SH ``` [Attempt This Online!](https://staging.ato.pxeger.com/run?1=LY6xEoIwEET_hT69LQxgEC5EAgMxcwVFsLNgsLvPsLOh0cI_8m-8INXNu93Z3edn9ld_8_O4-LeLxBjh-rovkzh8H7FL0qOsQDWm7QeLlLk033lAKpiUaZHq8C5A6cZsts5JhqC4OMllKZRu7QXjgOwEoZveYhZQlhXoc4graGs7cTy3WayZAS1xFgI5UAN2ZOR_2z5x3e8P) Or ``` BY|HM|SH|NU|XU|A[BDGHLMNRSTWXY]|E[DFHLMNRSTX]|I[DFNST]|M[MUY]|O[DFHIMNPRSWXY]|U[HMNPST]|[ABFHK-NPTYZ]A|[ABDFHM-PRWY]E|[ABHKLMPQSTX]I|[BDGHJLMNSTWY]O ``` [Attempt This Online!](https://staging.ato.pxeger.com/run?1=LY4xEoIwEEXvQp_elgxgEDZEQgZiZguKYGfBYLfHsLOh0cIbeRsTpNp589_s_8_P7K_-5udx8W-XsDHB9XVfJnb4PrglAaQFSUODodTx7ChqkK3u-sEi5S4rdh6QykBSd0jgwIS0iWkJUrV6s40TAaLgUl6IiknV2QumEYMJTLW9xTyiqGpQ5_i1pK30FFpCqcXmv22fuO73Bw) I'm under the impression this is close to optimal, but I plan on writing a program to verify / discover the shortest solution which uses only this strategy. What I have here is as far as I could manage by hand. Not a full code breakdown but everything here is basically just ``` XY|X[YZ]|[XY]Z XY // print XY | // then X[YZ] // print XY and XZ | // then [XY]Z // print XZ and YZ ``` [Answer] # [R](https://r-project.org), ~~199~~ 198 bytes *In 2018 six new two-letter words were added to the Official Scrabble Players' Dictionary: **DA, EW, GI, OK, PO, and TE**. This answer would have had 192 bytes in 2015 but I wanted to include the new words!* ``` `/`=strsplit;cat(unlist(Map(paste0,LETTERS[-22][-3],el('ABDEGHILMNRSTWXY,AEIOY,AEO,DFHLMNRSTWX,AE,IO,AEIMO,DFNST,O,AI,AIO,AEIMOUY,AEOU,DEFHIKMNPRSWXY,AEIO,I,E,HIO,AEIO,HMNPST,EOI,U,AEO,A'/',')/''))) ``` This answer is adapted from my answer at [this related challenge about element names](https://codegolf.stackexchange.com/a/264743/86701). First we overload the `/` operator with the `strsplit()` function. Then for the first letters of the words, we use the builtin `LETTERS` to get a vector of uppercase letters, removing elements 3 and 22 (C and V). For the second letters, we split a string by the `,` character to get a list of the second letters going with each first letter. Then we split it again by an empty string to get a list of vectors of individual characters. `Map()` is used to apply `paste0()` to the first elements of the first-letters vector and the second-letters list, then the second elements, etc. `unlist()` flattens and `cat()` prints without any quotes. [Attempt this online!](https://ato.pxeger.com/run?1=NU9RCoJAFDzO7sITw36C6MNwbZdcN1ylQgQlDAQJ0fU0_dhHV-kO3aZVEx4PZubNPOb5aofh3eu7tfl-cjvfdbrtmrrS21uhcf-oq05jUTS4KTpdriCgcUwjlVqOk6XWOoOyxsjde_TAeCDCSMXnyxVcyuW4JXg-W2iDgctREyMfqhgM4mb-ZDJZEvCoz_hRhKdILWHAgQKbDyUwoxk3lRyS6YuLbASI2AgRQuY2_1JLuR8) [Answer] # Haskell, 192 bytes ``` putStr$(\(a:b)->((a:).(:" "))=<<b)=<<words"AABDEGHILMNRSTWXY BAEIOY DEO EDFHLMNRSTX FAE GO HAEIMO IDFNST JO KAI LAIO MAEIMOUY NAEOU ODEFHIMNPRSWXY PAEI QI RE SHIO TAIO UHMNPST WEO XIU YAEO ZA" ``` For every space separated word in the string put the first letter in front of all other letters and add a space, e.g `SHIO` -> `SH SI SO`. [Answer] ## Java, 334 bytes ``` public class C{public static void main(String[]a){for(int i=0;i<26;i++){for(int j=0;j<26;j++){if(java.util.BitSet.valueOf(java.util.Base64.getDecoder().decode("2znORQQBBAAAAAQQAKg4jkQAAAAABEBEFAAoIAwAAAEQEABAQBAAEVEQRQBBgBtrXEQAAAABAEAAAAAYBEBAEACAsAwAAAAAAQQAQAAEEUAABA==")).get(i*26+j)){System.out.format("%c%c\n",'a'+i,'a'+j);}}}}} ``` Formatted: ``` public class Code { public static void main(String[] a) { for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { if (java.util.BitSet.valueOf( java.util.Base64.getDecoder() .decode("2znORQQBBAAAAAQQAKg4jkQAAAAABEBEFAAoIAwAAAEQEABAQBAAEVEQRQBBgBtrXEQAAAABAEAAAAAYBEBAEACAsAwAAAAAAQQAQAAEEUAABA==")) .get(i * 26 + j)) { System.out.format("%c%c\n", 'a' + i, 'a' + j); } } } } } ``` Separately, I encoded the word list into a length 26x26=676 BitSet, converted it to a byte array, and then finally to Base 64. That string is hard-coded in this program, and the reverse procedure is used to reproduce the BitSet, and ultimately print out the list of words [Answer] ## Java, 356 bytes Uses the random number generator to get the words: ``` import java.util.Random;class X{public static void main(String[]a){int j,n,m=9,x;for(String u:"rgzza 2u2hh r2rxs qs5f fwiag 26i33y 2xqmje 5h94v 16ld2a 17buv 4zvdi 1elb3y 2t108q 5wne9 1mrbfe 1ih89 fh9ts r0gh".split(" ")){x=Integer.parseInt(u,36);Random r=new Random(x/2);j=m-=x%2;while(j-->0){n=r.nextInt(676);System.out.format(" %c%c",65+n/26,65+n%26);}}}} ``` Ungolfed: ``` import java.util.Random; class X{ public static void main(String[]a){ int j,n,m=9,x; for(String u:"rgzza 2u2hh r2rxs qs5f fwiag 26i33y 2xqmje 5h94v 16ld2a 17buv 4zvdi 1elb3y 2t108q 5wne9 1mrbfe 1ih89 fh9ts r0gh".split(" ")){ x=Integer.parseInt(u,36); Random r=new Random(x/2); j=m-=x%2; while(j-->0){ n=r.nextInt(676); System.out.format(" %c%c",65+n/26,65+n%26); } } } } ``` You can try it here: <http://ideone.com/Qni32q> ]
[Question] [ # Robbers section The cops section can be found [here](https://codegolf.stackexchange.com/q/88979/34388). ### Challenge Your task is to outgolf the submissions of the cops *in the same language* and *the same version* (for example, **Python 3.5** ≠ **Python 3.4**, so that is not allowed). A submission is outgolfed when the length in bytes is shorter than the original submission. **You only need to golf off at least 1 byte** in order to crack a submission. E.g. if the task was to perform **2 × *n***, and the submission was the following: ``` print(2*input()) ``` You could outgolf the cop by doing the following: ``` print 2*input() ``` Or even this (since lambda's are allowed): ``` lambda x:2*x ``` Post this with the following header: ``` ##{language name}, <s>{prev byte count}</s> {byte count}, {cop's submission + link} ``` For example: > > ## Python 2, ~~16~~ 12 bytes, Adnan (+ link to submission) > > > > ``` > lambda x:2*x > > ``` > > Computes [A005843](https://oeis.org/A005843), (offset = 0). > > > In that case, you have **cracked** the submission. ### Scoring The person with who cracked the most submissions is the winner. ### Rules * The crack submission must be in the same language as the cop submission. * The same input should result into the same output (so a(2) = 4 should remain 4). * For languages such as Python, you can import libraries that are standard included within the language. (So, no numpy/sympy etc.) * Input and output are both in decimal (base 10). --- > > **Note** > > > This challenge is finished. The winner of the *Robbers* section is **feersum**. The final scores for the CnR are shown below: > > > * **feersum**: **16** cracks > * **Dennis**: **12** cracks > * **Leaky Nun**: **6** cracks > * **Lynn**: **4** cracks > * **miles**: **3** cracks > * **Martin Ender**: **2** cracks > * **Emigna**: **2** cracks > * **jimmy23013**: **1** crack > * **Sp3000**: **1** crack > * **randomra**: **1** crack > * **alephalpha**: **1** crack > * **nimi**: **1** crack > * **Destructible Watermelon**: **1** crack > * **Dom Hastings**: **1** crack > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), [George V. Williams](https://codegolf.stackexchange.com/a/89087/25180) ``` RÆḊḞ ``` [Try it here.](http://jelly.tryitonline.net/#code=UsOG4biK4bie&input=&args=MTI) A hidden feature! If I remembered correctly, `ÆḊ`(A) = sqrt(det(AAT)) is n! times the n dimensional [Lebesgue measure](https://en.wikipedia.org/wiki/Lebesgue_measure) of a [simplex](https://en.wikipedia.org/wiki/Simplex) formed by n input point and the origin in m dimensional space. When n=1 it degenerate to the Euclidean distance. Not that weird after all... [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), ~~91~~ 33 bytes, [Blue](https://codegolf.stackexchange.com/a/89090/8478) ``` 1""?{\>{+/</+'+./_'..@'~&/!}'+=($ ``` Unfolded: ``` 1 " " ? { \ > { + / < / + ' + . / _ ' . . @ ' ~ & / ! } ' + = ( $ . . . . ``` [Try it online!](http://hexagony.tryitonline.net/#code=MSIiP3tcPnsrLzwvKycrLi9fJy4uQCd-Ji8hfScrPSgk&input=MTA) Still looks somewhat golfable but I figured I'd post it before FryAmTheEggman beats me to it. ;) ### Explanation Here are some colour-coded execution paths: [![enter image description here](https://i.stack.imgur.com/bEm1o.png)](https://i.stack.imgur.com/bEm1o.png) However, these are unnecessarily convoluted due to golfing. Here is the exact same code with a saner layout: [![enter image description here](https://i.stack.imgur.com/WejUK.png)](https://i.stack.imgur.com/WejUK.png) That's better. And finally, here is a memory diagram, where the red arrow indicates the initial position and orientation of the memory pointer (MP): [![enter image description here](https://i.stack.imgur.com/IEckm.png)](https://i.stack.imgur.com/IEckm.png) The gist is that I'm iteratively computing Fibonacci numbers on the three edges labelled **f(i)**, **f(i+1)** and **f(i+2)** while keeping track of the iterator on the edges **A**, **B** and **C**. While doing so the roles of these edges are swapped out cyclically after each iteration. Let's see how this happens... The code starts on the grey path which does some initial setup. Note that **f(i)** already has its correct initial value of `0`. ``` 1 Set edge f(i+1) to 1. "" Move the MP to edge A. ? Read input n into edge A. ) Increment n. ``` Now the green path is the main loop. `_` and `>` are just mirrors. ``` ( Decrement n. < If the result is zero or less, continue on the red path, otherwise perform another iteration of the main loop. { Move the MP to edge f(i+2). + Add edges f(i) and f(i+1) into this edge, computing the next Fibonacci number. ' Move the MP to the edge opposite A. ~ Multiply by -1 to ensure that it's non-positive (the edge may have a positive value after a few iterations). & Copy the current value of n from A. ' Move back and to the right again. + Copy n by adding it to zero. Since we know that the other adjacent edge is always zero, we no longer need to use ~&. '+'+ Repeat the process twice, moving n all the way from A to B. = Reverse the orientation of the MP so that it points at f(i) which now becomes f(i+2) for the next iteration. ``` This way, the MP moves around the inner triplet of edges, computing successive Fibonacci numbers until `n` reaches zero. Then finally the red path is executed: ``` {} Move the MP to f(i). ! Print it. @ Terminate the program. ``` --- Diagrams generated with Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer) and [EsotericIDE](https://github.com/Timwi/EsotericIDE). [Answer] ## Cheddar, ~~7~~ 6 bytes, [Downgoat](https://codegolf.stackexchange.com/a/89051/30688) ``` (<<)&1 ``` This seems to work, but it's always possible that I don't understand the language correctly. [Answer] # Haskell, ~~5~~ 4 bytes, [xnor](https://codegolf.stackexchange.com/a/89044/48934) ``` (^)1 ``` Simple currying. [Answer] ## Stack Cats, ~~14~~ 13 bytes, [feersum](https://codegolf.stackexchange.com/a/89484/21487) ``` ^]T{_+:}_ ``` with the `-nm` flags for +4 bytes. [Try it online!](http://stackcats.tryitonline.net/#code=Xl1Ue18rOn1f&input=MTAwMA&args=LW5t) Okay, that loop was nuts. I tried several approaches, such as brute forcing over a reduced alphabet and brute forcing `3x+2` or `5x+4` and trying to extend it, but I never expected the solution to *actually* contain a loop. The best way to see how this works is to add a `D` flag for debugging (so run with `-nmD`) and turn debug on for the above TIO link. A `{}` loop remembers the top of stack at the beginning of the loop, and exits when the top of stack is that value again. The interior of the loop does some fun subtracting and cycling of the top three elements of the stack, which is how the loop gets to run for so many iterations. [Answer] # [Sesos, ~~14~~ 11 bytes, Leaky Nun](https://codegolf.stackexchange.com/a/88985/3852) Computes **n2**. [Try it here.](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcAogIGptcCwgc3ViIDEsIGZ3ZCAxLCBhZGQgMSwgZndkIDEsIGFkZCAyLCByd2QgMiwgam56CiAgZndkIDIsIHN1YiAxCiAgcndkIDEsIHN1YiAxCiAgam1wLCBzdWIgMSwgcndkIDEsIGFkZCAxLCBmd2QgMSwgam56CiAgcndkIDEKam56CmZ3ZCAyCnB1dA&input=MTM) Hex dump: ``` 0000000: 16c0f7 959d9b 26e83e ce3d ......&.>.= ``` From assembly: ``` set numin set numout get jmp jmp, sub 1, fwd 1, add 1, fwd 1, add 2, rwd 2, jnz fwd 2, sub 1 rwd 1, sub 1 jmp, sub 1, rwd 1, add 1, fwd 1, jnz rwd 1 jnz fwd 2 put ``` [Answer] ## Woefully, ~~776~~ 759 bytes, [Destructible Watermelon](https://codegolf.stackexchange.com/a/92485/30688) ``` | |||||||| | | || |||||| | ||| |||| | |||| || | ||||| || | |||| |||| | ||| |||||| | || |||||||| | | |||||||||| | || |||||||| | ||| ||||||| | ||||||||||| | ||||||||||| | ||||||||||| | ||||||||||| | |||||||||| | ||||||||| | ||||||||| | ||||||||| | ||||||||| | |||||||||| | ||||||||||| | |||||||||||| | ||||||||||| | |||||||||| | ||||||||| | |||||||| | ||||||| | |||||| | ||||| | |||| | ||| | || | | | | | | | || | || | || | || | || | | | | | | | || | ||| | |||| | ||||| | |||||| | ||||||| | |||||| | ||||||| | |||||||| | ||||||||| | |||||||||| | ||||||||||| | |||||||||||| | ||||||||||| | |||||||||| | ||||||||| | |||||||| | ||||||| | |||||| | ||||| | |||| | ||| | || | | | | | | | | | || | | | || | ||| | ||| | |||| | ||| | || | | | | | | | || | || | || | || | ``` I tried to read the source code for this language but it was too confusing. For one thing, `ip[1]` is a line number while `ip[0]` is the column number, while the `cp` coordinates are used the other way around. Yet, sometimes the value of `cp` is assigned to `ip`. I gave up on trying to understand what the program is doing and found a way to encode the identical sequence of instructions using fewer bars. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~27~~ 21 bytes, [Fatalize](https://codegolf.stackexchange.com/a/89017/48934) ``` yrb:1a:+a:[1]c*. :2/. ``` [Try it online!](http://brachylog.tryitonline.net/#code=eXJiOjFhOithOlsxXWMqLgo6Mi8u&input=MTA&args=Wg) [Answer] # J, ~~17~~ 12 bytes, [miles](https://codegolf.stackexchange.com/a/88999/7311) ``` +/@(]!2*-)i: ``` Pretty much the same as the original just more golfed. :) `i:` having `+1` range compared to `i.` is useful (and weird). If you use `i.` here `n=0` will be incorrect but luckily `i:` solves that. [Try it online here.](http://tryj.tk/) [Answer] # M, ~~10~~ 6 bytes, [Dennis](https://codegolf.stackexchange.com/a/89066/6710) ``` R×\³¡Ṫ ``` Given *n*, it computes the *nth*-level factorial of *n*. This was a fun exercise! The code is capable of running as Jelly so you can [Try it online](http://jelly.tryitonline.net/#code=UsOXXMKzwqHhuao&input=&args=NA). ## Explanation ``` R×\³¡Ṫ Input: n R Create the range [1, 2, ..., n] ³¡ Repeat n times starting with that range ×\ Find the cumulative products Ṫ Get the last value in the list Return implicitly ``` [Answer] # Snowman, ~~50~~ 44 bytes, [Doorknob](https://codegolf.stackexchange.com/a/89008/3852) ``` ((}#2nMNdE0nR1`wRaC2aGaZ::nM;aF;aM:`nS;aF*)) ``` [Try it online!](http://snowman.tryitonline.net/#code=fnZnMTBzQiogLy8gcmVhZCBpbnB1dCBmcm9tIFNURElOIGFuZCBwYXNzIGl0IHRvIHRoZSBzdWJyb3V0aW5lCgooKH0jMm5NTmRFMG5SMWB3UmFDMmFHYVo6Om5NO2FGO2FNOmBuUzthRiopKQoKI3RTc1AgICAgLy8gb3V0cHV0IHRoZSByZXR1cm4gdmFsdWUgdG8gU1RET1VU&input=MTA) [Answer] ## Haskell, ~~15~~ 14 bytes, [xnor](https://codegolf.stackexchange.com/a/92488/30688) ``` until odd succ ``` I spent a fruitless couple of hours learning to decipher "pointless" syntax... `until` I found this instead. Or for a less mellifluous 13 bytes, `until odd(+1)`. [Answer] ## Python 2, ~~43~~ 40, [xsot](https://codegolf.stackexchange.com/a/89011/30688%5D) ``` g=lambda n:n<2or-~sum(map(g,range(n)))/3 ``` [Answer] # [Pyke, ~~11~~ 9 bytes, muddyfish](https://codegolf.stackexchange.com/a/89004/12012) ``` hVoeX*oe+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=hVoeX%2aoe%2B&input=4) ### How it works ``` Implicit input: n (accumulator), n (iterations) h Increment the number of iterations. V Do the following n + 1 times. o Iterator. Pushes its value (initially 0) and increments it. e Perform integer division by 2. This pushes 0 the first time, then 1, then 2, etc. X Square the result. * Multiply the accumulator and the result. oe As before. + Add the result to the accumulator. This sets the accumulator to a(0) = 0 in the first iteration and applies the recursive formula in all subsequent ones. ``` [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 4, [Emigna](https://codegolf.stackexchange.com/a/89134/9288) ``` LnOx ``` > > From the formula for the sum of squares of positive integers 1^2 + 2^2 + 3^2 + ... + n^2 = n(n+1)(2\*n+1)/6, if we multiply both sides by 2 we get Sum\_{k=0..n} 2\*k^2 = n(n+1)(2\*n+1)/3, which is an alternative formula for this sequence. - Mike Warburton (mikewarb(AT)gmail.com), Sep 08 2007 > > > [Answer] ## Jelly, ~~22~~ 21 bytes, [Dennis](https://codegolf.stackexchange.com/a/89836/30688) ``` _²×c×Ḥc¥@÷⁸÷’{S ‘µR+ç ``` I spent several hours reading Jelly source code for the last one, so I might as well put this "skill" to use. I hope @Dennis will share with us his mathematical discoveries allowing a shorter formula (assuming there is something and not only weird Jelly tricks!). [Answer] # J, ~~20~~ 19 bytes, [miles](https://codegolf.stackexchange.com/a/89886/12012) ``` [:+/2^~+/@(!|.)\@i. ``` This computes the product as a sum of squared Fibonacci numbers, which are calculated as a sum of binomial coefficients. Thankfully, @miles himself posted the code to generate Fibonacci numbers [in this comment](https://codegolf.stackexchange.com/questions/86944/fibonacci-orial/86977#comment213743_86977). [Answer] # [*Acc!!*, ~~526~~ 525 bytes, DLosc](https://codegolf.stackexchange.com/a/90448/12012) ``` N Count x while _%60-46 { (_+_%60*5-288)*10+N } _/60 Count i while _/27^i { _+27^i*(_/27^i*26-18) } _*3+93 Count i while _/27^i/27%3 { _-i%2*2+1 Count j while _/3^(3*j+2-i%2)%3 { _+3^(1+i%2) Count k while _/3^(3*k+1+i%2)%3-1 { _+3^(3*k+1+i%2)*26 } } } Count i while _/27^i/3 { _-_/27^i/3%27*27^i*3+_/3^(3*i+1+_%3)%3*3 } _/3 Count i while _/100^i { _*10-(_%100^i)*9 } Count i while _/100^i/10 { _+_/100^i/10%10 Count j while i+1-j { _+(_%10-_/100^(j+1)%10)*(100^(j+1)-1) } } _/100 Count j while _/100^j { Write _/100^j%10+48 } ``` I have no idea how this works, but I was able to spot a tiny improvement. ``` 24c24 < _+_/100^i*100^i*9 --- > _*10-(_%100^i)*9 ``` [Answer] ## Haskell, 10 bytes, [xnor](https://codegolf.stackexchange.com/a/97130/34531) ``` gcd=<<(2^) ``` Usage example: `map ( gcd=<<(2^) ) [1..17]` -> `[1,2,1,4,1,2,1,8,1,2,1,4,1,2,1,16,1]`. How it works: From the [oeis page](https://oeis.org/A006519) we see that `a(n) = gcd(2^n, n)` or written in Haskell syntax: `a n = gcd (2^n) n`. Functions with the pattern `f x = g (h x) x` can be turned to point-free via the function `=<<`: `f = g =<< h`, hence `gcd=<<(2^)` which translates back to `gcd (2^x) x`. [Answer] # [Sesos, ~~14~~ 9 bytes, Leaky Nun](https://codegolf.stackexchange.com/a/88991/3852) Computes **n mod 16**. [Try it here.](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKc2V0IG1hc2sKZ2V0CmptcCwgc3ViIDEsIGZ3ZCAxLCBhZGQgMTYsIHJ3ZCAxLCBqbnoKZndkIDEKam1wLCBzdWIgMTYsIGZ3ZCAxLCBhZGQgMSwgcndkIDEsIGpuegpmd2QgMQpwdXQ&input=MzM) Hex: ``` 0000000: 17f84a 750e4a 7d9d0f ..Ju.J}.. ``` Assembly: ``` set numin set numout set mask get jmp, sub 1, fwd 1, add 16, rwd 1, jnz fwd 1 jmp, sub 16, fwd 1, add 1, rwd 1, jnz fwd 1 put ``` [Answer] # [Python, ~~39~~ 17 bytes, Destructible Watermelon](https://codegolf.stackexchange.com/a/88994/48934) ``` lambda n:n*-~n>>1 ``` [Answer] # [05AB1E, ~~9~~ 4 bytes, Emigna](https://codegolf.stackexchange.com/a/89000/48934) ``` >n4÷ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Pm40w7c&input=MjU) Computes this function instead: [![formula](https://i.stack.imgur.com/lLu9J.gif)](https://i.stack.imgur.com/lLu9J.gif) [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), ~~7~~ 6 bytes, [Adnan](https://codegolf.stackexchange.com/a/89009/8478) ``` ?!/$(@ ``` Unfolded: ``` ? ! / $ ( @ . ``` [Try it online!](http://hexagony.tryitonline.net/#code=ID8gISAKLyAkICgKIEAgLg&input=Nw&debug=on) Same idea, slightly different layout. [Answer] ## MATL, ~~11~~ 10 bytes, [Luis Mendo](https://codegolf.stackexchange.com/a/89024/30688) ``` YftdAwg_p* ``` Instead of doing -1^length(array) it converts the elements to Boolean values (which are always 1), negates them, and takes the product of the elements. [Answer] # Jelly, ~~11~~ 10, [Dennis](https://codegolf.stackexchange.com/a/89061/48934) ``` Ḥ’_Rc’*@RP ``` Vectorized version of same approach. [Try it online!](http://jelly.tryitonline.net/#code=4bik4oCZX1Jj4oCZKkBSUArFvMOH4oKsRw&input=&args=MSwgMiwgMywgNCwgNQ) [Answer] # [05AB1E, ~~10~~ 8 bytes, Adnan](https://codegolf.stackexchange.com/a/89092/3852) ``` µNÂÂQ>i¼ ``` [Try it online](http://05ab1e.tryitonline.net/#code=wrVOw4LDglE-acK8&input=NDU). [Answer] # [Brachylog, ~~11~~ 10 bytes, Fatalize](https://codegolf.stackexchange.com/a/89219/48934) ``` yb:AcLrLc. ``` [Try it online!](http://brachylog.tryitonline.net/#code=eWI6QWNMckxjLg&input=MTE&args=Wg) ## Explanation Brachylog is a Prolog-derived languages, whose greatest ability is to prove things. Here, we prove these statements: ``` yb:AcLrLc. yb:AcL Inclusive range from 1 to input, concatenated with A, gives L LrL L reversed is still L Lc. L concatenated is output ``` [Answer] # Jelly, ~~9~~ 8 bytes, [Dennis](https://codegolf.stackexchange.com/a/89115/6710) ``` œċr0$L€Ḅ ``` Sorry! I wasn't able to find your intended solution. This relies on the fact that `C(n+k-1, k)` is the number of ways to choose `k` values from `n` with replacement. Note: This is inefficient since it generates the possible sets in order to count them, so try to avoid using large values of *n* online. [Try it online](http://jelly.tryitonline.net/#code=xZPEi3IwJEzigqzhuIQ&input=&args=NA) or [Verify up to *n*](http://jelly.tryitonline.net/#code=xZPEi3IwJEzigqzhuIQKMHLFvMOH4oKsJEc&input=&args=MTA). I later found another 8 byte version that is efficient enough to compute *n* = 1000. This computes the values using the binomial coefficient and avoids generating the lists. ``` Ḷ+c’Ṛ;1Ḅ ``` [Try it online](http://jelly.tryitonline.net/#code=4bi2K2PigJnhuZo7MeG4hA&input=&args=NA) or [Verify up to *n*](http://jelly.tryitonline.net/#code=4bi2K2PigJnhuZo7MeG4hAowcsW8w4figqwkRw&input=&args=MTA). ## Explanation ``` œċr0$L€Ḅ Input: n r0$ Create a range [n, n-1, ..., 0] œċ Create all combinations with replacement for (n, n), (n, n-1), ..., (n, 0) L€ Find the length of each Ḅ Convert it from binary to decimal and return Ḷ+c’Ṛ;1Ḅ Input: n Ḷ Creates the range [0, 1, ..., n-1] + Add n to each in that range ’ Get n-1 c Compute the binomial coefficients between each Ṛ Reverse the values ;1 Append 1 to it Ḅ Convert it from binary to decimal and return ``` [Answer] ## M, ~~9~~ 8 bytes, [Dennis](https://codegolf.stackexchange.com/a/89247/30688)​ ``` Ḥrc’ḊḄḤ‘ ``` [Answer] ## QBasic, ~~30~~ 29 bytes, [DLosc](https://codegolf.stackexchange.com/a/89857/30688) ``` INPUT n:?(n MOD 2)*(n+.5)+n/2 ``` ]
[Question] [ **UPDATE** : [isaacg's Pyth submission](https://codegolf.stackexchange.com/a/37863/31414) is the winner! --- Many of you must have heard that there is a cooler version of JavaScript in town (read ES6) which has a method `String.prototype.repeat` so that you can do ``` "Hello, World!".repeat(3) ``` and get ``` "Hello, World!Hello, World!Hello, World!" ``` as the output. Your job is to write a function or a program in a **language of your choice** which detects if a string has been gone under such transformation. i.e. The input string can be represented as an exact `n` times repetition of a smaller string. The output (as function's return statement or STDOUT) should be truthy if the string can be or falsy if the string cannot be represented as a repetition of smaller string. Some sample input: ``` "asdfasdfasdf" // true "asdfasdfa" // false "ĴĴĴĴĴĴĴĴĴ" // true "ĴĴĴ123ĴĴĴ123" // true "abcdefgh" // false ``` Note that the last input is false, thus **`n` should be greater than `1`** **Complete rules** * Write a function/program in any language to input (via function argument/command line args/STDIN) a string * Return/Print truthy value if the given string is formed via an exact repetition of a smaller string, repeating at least twice. * Maximum size of the input string is ideally Infinity * String can have all possible ASCII characters * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so smallest code in characters wins. [Answer] ## Python (24) ``` lambda s:s in(s+s)[1:-1] ``` Checks if the string is a substring of itself concatenated twice, eliminating the first and last characters to avoid trivial matches. If it is, it must be a nontrivial cyclic permutation of itself, and thus the sum of repeated segments. [Answer] ## Regex (ECMAScript flavour), 11 bytes Sounds like a job for regex! ``` ^([^]+)\1+$ ``` [Test it here.](http://refiddle.com/refiddles/5417583975622d4df7be0a00) I've chosen ECMAScript, because it's the only flavour (I know) in which `[^]` matches any character. In all others, I'd either need a flag to change the behaviour of `.` or use `[\s\S]` which is three characters longer. Depending on how we're counting the flag, that *could* of course be a byte shorter. E.g. if we're counting pattern + flags (e.g. ignoring delimiters), the PCRE/Perl equivalent would be ``` /^(.+)\1+$/s ``` Which is 10 bytes, ignoring the delimiters. [Test it here.](http://regex101.com/r/qZ0jP3/1) This matches only strings which consist of at least two repetitions of some substring. Here is a full 26-byte ES6 function, but I maintain that regular expression submissions are generally valid: ``` f=s->/^([^]+)\1+$/.test(s) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 ``` /:+zz1_1z ``` Or ``` }z:+zz1_1 ``` These are both close translations of @xnor's python answer, except that they take input from STDIN and print it. The first is equivalent to: ``` z = input() print((z+z)[1:-1].count(z)) ``` 0 for False, 1 for True. The second line is equivalent to: ``` z = input() print(z in (z+z)[1:-1]) ``` False for False, True for True. Pyth's official compiler had a bug related to the second one, which I just patched, so the first is my official submission. [Answer] # CJam, 9 ``` q__+)@+#) ``` Similar to xnor's idea. ``` q " Read input. "; __+ " Duplicate twice and concatenate them together. "; ) " Remove the last character of the longer string. "; @+ " Insert that character at the beginning of the shorter string. "; #) " Find the shorter string in the longer string, and increase by one. "; ``` [Answer] ## APL, 11 ``` 2<+/x⍷,⍨x←⍞ ``` **Explanation** `⍞` takes string input from screen `x←` assigns to variable `x` `,⍨` concatenates the string with itself `x⍷` searches for `x` in the resulting string. Returns an array consisting of 1's in the starting position of a match and 0's elsewhere. `+/` sums the array `2<` check if the sum is greater than 2 (as there will be 2 trivial matches) [Answer] # CJam, 10 bytes I caught the CJam bug. My first answer, so probably can be golfed some more: ``` q__+(;);\# ``` Outputs -1 for FALSE and a number >=0 for TRUE [Answer] # GolfScript, 10 bytes ``` ..+(;);\?) ``` Yet another implementation of xnor's clever idea. [Answer] # Python - ~~59~~ 57 ``` lambda s:any([s*n==s[:n]*len(s)for n in range(2,len(s))]) ``` [Answer] # Pure bash, 30 bytes Simple port of [@xnor's clever answer](https://codegolf.stackexchange.com/a/37855/11259): ``` [[ ${1:1}${1:0: -1} =~ "$1" ]] ``` Exit code is 0 for TRUE and 1 for FALSE: ``` $ for s in 'Hello, World!Hello, World!Hello, World!' 'asdfasdfasdf' 'asdfasdfa' 'ĴĴĴĴĴĴĴĴĴ' 'ĴĴĴ123ĴĴĴ123' 'abcdefgh'; do echo "./isrepeated.sh "\"$s\"" returns $(./isrepeated.sh "$s"; echo $?)"; done ./isrepeated.sh "Hello, World!Hello, World!Hello, World!" returns 0 ./isrepeated.sh "asdfasdfasdf" returns 0 ./isrepeated.sh "asdfasdfa" returns 1 ./isrepeated.sh "ĴĴĴĴĴĴĴĴĴ" returns 0 ./isrepeated.sh "ĴĴĴ123ĴĴĴ123" returns 0 ./isrepeated.sh "abcdefgh" returns 1 $ ``` Note `=~` within `[[ ... ]]` is [the regex operator in bash](http://www.gnu.org/software/bash/manual/bashref.html#index-_005d_005d). However *"Any part of the pattern may be quoted to force it to be matched as a string"*. So as ai often the case with bash, getting quoting right is very important - here we just want to check for a string submatch and not a regex match. [Answer] ## TI-BASIC - 32 I thought I'd try a tokenized language. Run with the string in Ans, returns 0 if false and the length of the repeated string if true. ``` inString(sub(Ans+Ans,1,2length(Ans)-1),sub(Ans,length(Ans),1)+Ans ``` Amazing how it's a one-liner. [Answer] # ECMAScript 6 (189) ``` (function(){var S=String.prototype,r=S.repeat;S.isRepeated=function(){return!1};S.repeat=function(c){var s=new String(r.call(this,c));if(c>1)s.isRepeated=function(){return!0};return s}}()); ```   ``` < console.log("abc".isRepeated(),"abc".repeat(10).isRepeated()); > false true ``` Surely this is the only valid solution? For example, the word (string) `nana` isn't necessarily created from `"na".repeat(2)` [Answer] # ECMAScript 6 (34 ~~36~~) Another ES6 answer, but without using `repeat` and using [xnor's trick](https://codegolf.stackexchange.com/a/37855/26765): ``` f=i=>(i+i).slice(1,-1).contains(i) ``` Must be run in the console of a ES6-capable browser such as Firefox. [Answer] # C 85 ``` l,d;f(s){return l=strlen(s),strstr(d,strcpy(strcpy(d=alloca(l*2+1),s)+l,s)-1)-d-l+1;} ``` It turned out to be quite long but external functions are always like that. It came to my mind that I could rewrite every string function replacing them by a loop or a recursive one. But in my experience it would turn out longer and frankly I don't want to try that out. After some research I saw solutions on high performance but not as clever (and short) as xnor's one. just to be original... i rewrote the same idea in c. explanation: ``` int length, duplicate; int is_repetition(char *input) { // length = "abc" -> 3 length = strlen(input); // alloca because the function name is as long as "malloc" // but you don't have to call free() because it uses the stack // to allocate memory // duplicate = x x x x x x + x duplicate = alloca(length*2 + 1); // duplicate = a b c 0 x x + x strcpy(duplicate, input); // duplicate = a b c a b c + 0 strcpy(duplicate + length, input); if (strstr(duplicate,duplicate + length - 1) != duplicate + length - 1) // repetition // e.g. abab -> abababab -> aba[babab] // -> first occurence of [babab] is not aba[babab] // but a[babab]ab -> this is a repetition return 1; else // not repetition // e.g. abc -> abcabc -> ab[cabc] // -> first occurence of [cabc] is ab[cabc] // it matches the last "cabc" return 0; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ṙJċ ``` [Try it online!](https://tio.run/nexus/jelly#@/9w50yvI93///9PSUNAAA "Jelly – TIO Nexus") Same as [this answer](https://codegolf.stackexchange.com/a/121546/41024) (maybe the later challenge is a generalization of this one?). [Answer] # ECMAScript 6 (59 ~~62~~ ~~67~~ ~~73~~) Not a winner, but seems like there should at least be one answer actually in ES6 for this question that actually uses the `repeat` function: ``` f=i=>[...i].some((_,j)=>i.slice(0,j).repeat(i.length/j)==i) ``` Must be run in the console of a ES6-capable browser such as Firefox. It does a lot of unnecessary iterations, but why make it longer just to avoid that, right? * *Edit #1:* Saved a few bytes by converting it into a function. Thanks to Optimizer! * *Edit #2:* Thanks to hsl for the spread operator trick to save more bytes! * *Edit #3:* And thanks to Rob W. for another 3 bytes! [Answer] # Java 8, 28 bytes ``` s->s.matches("(?s)(.+)\\1+") ``` [Try it online.](https://tio.run/##jY/BTsMwDIbvewqrp0TTMg1uTMCN23bZbpSDm6ZrRupUdTppQn0rHoH3KmEtHJBgVWwplv/Pv33EEy58beiYv/baITNs0NLbDMBSME2B2sD2qwTIvHcGCbTYhcbSAViuY6OLGYMDBqthCwT30PPigVWFQZeGRSIeWQo1l2m6mieyXw9E3WYuEiN48jaHKnqP059fUA6@yyXsmzaU57tLuTtzMJXybVB1FAZHgpQWCXJefGciL6v9Lf54//0mIqub25/PVQRTGuI/5diJVz6hYzP1yuvmmc5NcSinbjnqulnXfwI) **Explanation:** Checks if the input-String matches the regex, where [`String#matches`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) implicitly adds `^...$` to match the entire String. Explanation of the regex itself: ``` ^(s?)(.+)\1+$ ^ Begin of the string (s?) Enable DOTALL-mode, where `.` also matches new-lines ( Open capture group 1 .+ One or more characters ) Close capture group 1 \1+ Plus the match of the capture group 1, one or more times $ End of the string ``` So it basically checks if a substring is repeated two or more times (supporting new-lines). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` żḢ/v≈a ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwixbzhuKIvduKJiGEiLCIiLCJcImFzZGZhc2RmYXNkZlwiXG5cImFzZGZhc2RmYVwiXG5cIsS0xLTEtMS0xLTEtMS0xLTEtFwiXG5cIsS0xLTEtDEyM8S0xLTEtDEyM1wiXG5cImFiY2RlZmdoXCIiXQ==) ## Explained ``` żḢ/v≈a / # Split the input string into pieces of żḢ # range [2, len(input)] v≈a # do any of those have all the same item ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), ~~51~~ ~~36~~ 25 bytes Based on [my Ruby answer](https://codegolf.stackexchange.com/a/252724/11261). Returns the string for truthy and `nil` for falsy. ``` ~:[]%(~:*&2|~:[]&(1..-2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWO-usomNVNeqstNSMakBsNQ1DPT1dI01NiPzNjAIFt2ilxOKUNBhWiuVCFYMJHNmCDlFlDI2M4Qy4IUnJKalp6RlKsRD7FiyA0AA) This is equivalent to the lambda `->s{ (s*2)[1..-2][s] }`. [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 19 bytes Another port of [xnor's answer](https://codegolf.stackexchange.com/questions/37851/string-prototype-isrepeated/37855#37855). Takes input on stdin; prints the string if it's repeated and `nil` otherwise. ``` p ($_*2)[1..-2][$_] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5ejlLsojTbpaUlaboWmwsUNFTitYw0ow319HSNYqNV4mMhMgug1E3XxOKUNBjmgnO4jmxBh1AhQyNjOIMrMSk5JTUtPQNiGgA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ²é ¤øU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sukgpPhV&input=WwoiYXNkZmFzZGZhc2RmIiAKImFzZGZhc2RmYSIKIlx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNCIKIlx1MDEzNFx1MDEzNFx1MDEzNDEyM1x1MDEzNFx1MDEzNFx1MDEzNDEyMyIKImFiY2RlZmdoIgpdLW1S) Boring copy of the common logic from other answers: ``` ²é ¤øU ² # Duplicate the input é # Move the last character to the front ¤ # Remove the first two characters øU # Return true if it still contains the input ``` # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¬x@¥éY ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rHhApelZ&input=WwoiYXNkZmFzZGZhc2RmIiAKImFzZGZhc2RmYSIKIlx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNFx1MDEzNCIKIlx1MDEzNFx1MDEzNFx1MDEzNDEyM1x1MDEzNFx1MDEzNFx1MDEzNDEyMyIKImFiY2RlZmdoIgpdLW1S) More interesting, but has a weirder output; `1` means `false`, any other output means `true`. Identical to [this](https://codegolf.stackexchange.com/a/121565/71434) answer on a different challenge, but discovered separately. Explanation: ``` ¬x@¥éY ¬ # Convert input to an array of characters x@ # Apply a function to each one, then sum the results: éY # Rotate the input string a number of times equal to the current index ¥ # Return 1 if it's still equal to the input, 0 otherwise ``` ]
[Question] [ Write a program that takes in (via STDIN/command line) a non-negative integer N. When N is 0, your program should print `O` (that's capital Oh, not zero). When N is 1, your program should print ``` \|/ -O- /|\ ``` When N is 2 your program should print ``` \ | / \|/ --O-- /|\ / | \ ``` When N is 3 your program should print ``` \ | / \ | / \|/ ---O--- /|\ / | \ / | \ ``` For larger N, this pattern continues on in the same exact fashion. Each of the eight rays of the "sun" should be made of N of the appropriate `-`, `|`, `/`, or `\` characters. ## Details * Instead of a program, you may write a function that takes an integer. The function should print the sun design normally or return it as a string. * You must either + have no trailing spaces at all, or + only have enough trailing spaces so the pattern is a perfect (2N+1)\*(2N+1) rectangle. * The output for any or all N may optionally have a trailing newline. ## Scoring The shortest code in bytes wins. [Answer] # C: ~~116~~ ~~102~~ ~~99~~ ~~95~~ ~~92~~ 90 ``` s(n){for(int c=-n,r=c;r<=n;c++)putchar(c>n?c=-c,r++,10:c?r?c-r?c+r?32:47:92:45:r?124:79);} ``` I think that I am getting fairly close to a minimal solution using this approach, but I can't stop feeling that there is a much better approach in C. Ungolfed: ``` void s(int n) { for( int c = -n, r = c; r <= n; c++ ) putchar( c > n ? c = -c, r++, '\n' : c ? r ? c - r ? c + r ? ' ' : '/' : '\\' : '-' : r ? '|' : 'O' ); } ``` [Answer] # GNU sed, 252 + 1 Phew - I beat the php answer! Score + 1 for using the `-r` parameter. Because of sed limitations, we have to burn nearly 100 bytes just convert N to a string of N spaces. The rest is the fun stuff. ``` /^0/{y/0/O/;q} s/./<&/g s/9/8 /g s/8/7 /g s/7/6 /g s/6/5 /g s/5/4 /g s/4/3 /g s/3/2 /g s/2/1 /g s/1/ /g s/0//g :t s/ </< /g tt s/<//g : s/ // s^.*^\\&|&/^;ta :a /\\$/q p s^\\\|/^-O-^;tn s^(\\)? (/)?^\2 \1^g;ta :n y/ /-/ p s^-O-^/|\\^ y/-/ / ta ``` ### Explanation * The first line is an early exit for the N=0 case. * The next 15 lines (up to the `:`) convert N to a string of N spaces * `s/ //` removes one space * `s^.*^\\&|&/^;ta` converts N-1 spaces to: `\` + N-1 spaces + `|` + N-1 spaces + `/` * Iterate, printing each iteration, and moving `\` one space to the right and `/` one space to the left... * ...until we match `\|/`, which is replaced with `-O-` and jump to the `n` label * replace with `-` and print * replace `-0-` with `/|\`, and replace with `-` and jump back into the main loop * Iterate, printing each iteration, and moving `\` one space to the right and `/` one space to the left... * ...until we match `\$` which indicates were finished, and quit. ### Output ``` $ for i in {0..3}; do sed -rf asciisun.sed <<< $i ; done O \|/ -O- /|\ \ | / \|/ --O-- /|\ / | \ \ | / \ | / \|/ ---O--- /|\ / | \ / | \ $ ``` [Answer] # J, ~~37~~ ~~34~~ 40 bytes ``` 1:echo('O\/-|'{.@#~0=+&|,-,+,[,])"*/~@i: ``` Usage: ``` (1:echo('O\/-|'{.@#~0=+&|,-,+,[,])"*/~@i:) 2 NB. prints to stdout: \ | / \|/ --O-- /|\ / | \ ``` Explanation (from left to right): * `i:` generates list `-n, -(n-1), ..., n-1, n` * `( )"*/~@i:` creates the Descartes product of i: with itself in a matrix arrangement, e.g. for `n = 1` creates the following `3-by-3` matrix ``` ┌─────┬────┬────┐ │-1 -1│-1 0│-1 1│ ├─────┼────┼────┤ │0 -1 │0 0 │0 1 │ ├─────┼────┼────┤ │1 -1 │1 0 │1 1 │ └─────┴────┴────┘ ``` * for every matrix-element with integers `x y` we do the following * `+&|,-,+,[,]` calculate a list of properties + `+&|` `abs(x)+abs(y)`, equals `0` iff (if and only if) `x=0` and `y=0` + `-` x-y, equals `0` iff `x=y` i.e. we are on the diagonal + `+` x+y, equals `0` iff `x=-y` i.e. we are on the anti-diagonal + `[` x, equals `0` iff `x=0` i.e. we are on the middle row + `]` y, equals `0` iff `y=0` i.e. we are on the middle column * `'O\/-|'#~0=` compare these above property values to `0` and take the `i`th character from the string `'O\/-|'` if the `i`th property is true. * the first character in the resulting string will always be the one we need, if there string is empty we need a space * `{.` takes the first character of a string and if there is no one it returns a space character as padding just as we need * we now have the exact matrix we need so we print it to stdout once with `1:echo` [Try it online here.](http://tryj.tk/) [Answer] # Pyth, ~~39~~ ~~38~~ 36 bytes ``` jbXmXXj\|m*\ Q2d\\_hd\/JhyQQX*\-JQ\O ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=jbXmXXj%5C%7Cm*%5C+Q2d%5C%5C_hd%5C%2FJhyQQX*%5C-JQ%5CO&input=3&debug=0) ### Explanation ``` jbXmXXj\|m*\ Q2d\\_hd\/JhyQQX*\-JQ\O implicit: Q = input JhyQ J = 1 + 2*Q m J map each d of [0,1,...,2*Q] to: *\ Q " "*input m 2 list with twice " "*input j\| join this list by "|" X d\\ replace the value at d to "\" X _hd\/ replace the value at -(d+1) to "/" X Q replace line Q by: *\-J "-"*J X Q\O replace element at Q with "O" jb join by "newlines" ``` Another 36 bytes solution would be: ``` jbmXXj\|m*?\-KqdQ\ Q2d\\_hd?\OK\/hyQ ``` [Answer] # PHP, 182 bytes This seemed like a fun activity for my first answer. Comments on my code are welcome. ``` <?php function s($n){$e=2*$n+1;for($i=0;$i<$e*$e;$i++){$x=$i%$e;$y=floor($i/$e);echo$y==$x?($x==$n?"O":"\\"):($e-1==$x+$y?"/":($y==$n?"-":($x==$n?"|":" ")));echo$x==$e-1?"\n":"";}}?> ``` Here is the un-golfed code with comments: ``` <?php function s($n) { $e=2*$n+1; //edge length for($i=0;$i<$e*$e;$i++) { $x = $i%$e; // current x coordinate $y = floor($i/$e); // current y coordinate if ($y==$n&&$x==$n) { // center of square echo'O'; } else if ($y==$n) { // horizontal line echo'-'; } else if ($x==$n) { // vertical line echo'|'; } else if ($y==$x) { // diagonal line from top-left to bottom right echo'\\'; } else if (($y-$n)==($n-$x)) { // diagonal line from bottom-left to top-right echo'/'; } else { // empty space echo' '; } if ($x==$e-1) { // add new line for the end of the row echo"\n"; } } }?> <pre> <?php s(10); ?> </pre> ``` **Edited with code by royhowie** [Answer] ## Python 2, 99 ``` n=input() R=range(-n,n+1) for i in R:print''.join("O\|/ -"[[R,i,0,-i,j].index(j)^(i==0)]for j in R) ``` Prints line by line, creating each line by checking whether the coordinate `(i,j)` (centered at `(0,0)`) satisfies `j==-i`, `j==0`, `j==i`, or none, with a hack to make the center line work. [Answer] # CJam, ~~48 45 43 41~~ 38 bytes This is still too long and I am still doing some redundant things, but here goes: ``` ri:R{_S*"\|/"@R-~S**1$N}%'-R*'O1$W$sW% ``` [Try it online here](http://cjam.aditsu.net/#code=ri%3AR%7B_S*%22%5C%7C%2F%22%40R-%7ES**1%24N%7D%25%27-R*%27O1%24W%24sW%25&input=6) [Answer] # SpecBAS - 117 bytes ``` 1 INPUT s: LET t=s*2: FOR y=0 TO t: PRINT AT y,y;"\";AT y,t/2;"|";AT t-y,y;"/";AT t/2,y;"-": NEXT y: PRINT AT s,s;"O" ``` This prints the slashes and dashes in one loop, and then plonks the "O" in the middle. Output using 1, 2 and 9 ![enter image description here](https://i.stack.imgur.com/UtwI5.png) [Answer] # OS/2 Classic Rexx, 102... or 14 for "cheater's version" Take out the linefeeds to "golf" it. ``` w='%1' o=center('O',w,'-') m='center(space("\|/",w),%1)' do w w=w-1 interpret "o="m"|o|"m end l say o ``` Cheater's version, name the script whatever source code you want under 255 characters (requires HPFS disk): ``` interpret '%0' ``` --- **EDIT:** Just to be clear, cheater's version isn't intended to count! It's just to be silly and show an old dog can still do tricks. :) *e.g. For real fun and games, an implementation of Java-8/C11 style "lambda" expressions on a list iterator. Not tested, but ought to run on a circa 1979 IBM mainframe. ;)* ``` ForEachInList( 'Months.January.Days', 'Day' -> 'SAY "You have an appointment with" Day.Appointment.Name "on" Day.Appointment.Date' ) EXIT ForEachInList: SIGNAL ON SYNTAX PARSE ARG MyList "," MyVar "->" MyCommand INTERPRET ' MyListCount = ' || MyList || '.Count' DO ListIndex = 1 TO MyListCount INTERPRET MyVar || ' = ' || MyList || '.' || ListIndex INTERPRET MyCommand END RETURN SYNTAX: SAY MyCommand ' is not a valid expression. ' EXIT ``` -- Calling code assumes you already made a stem (array), naturally. [Answer] # JavaScript (ES6) 97 ~~98~~ This seems different enough ... ``` // GOLFED f=n=>(y=>{for(t='';++y<n;t+='\n')for(x=-n;++x<n;)t+='-O /\\|'[y?x?x-y?x+y?2:3:4:5:+!x]})(-++n)||t // Ungolfed F=n=>{ ++n; t = ''; for (y = -n; ++y < n; t += '\n') for (x = -n; ++x < n; ) if (y != 0) if (x != 0) if (x != y) if (x != -y) t += ' ' else t += '/' else t += '\\' else t += '|' else if (x != 0) t += '-' else t += 'O' return t; } // TEST function test(){ OUT.innerHTML = f(N.value|0); } test() ``` ``` input { width: 4em } ``` ``` N: <input id=N value=5><button onclick="test()">Go</button> <pre id="OUT"></pre> ``` [Answer] # Haskell, ~~109~~ ~~98~~ 96 bytes Thanks to nimi and Mauris for their help! ``` 0#0='O' 0#_='-' _#0='|' i#j|i==j='\\'|i== -j='/'|1<2=' ' f n=unlines[map(i#)[-n..n]|i<-[-n..n]] ``` **Explanation:** The operator `#` specifies which character appears at coordinates (i,j), with the sun centered at (0,0). Function `f` builds the result String by mapping `#` over all pairs of coordinates ranging from -n to n. **Usage:** ``` ghci> putStr $ f 2 \ | / \|/ --O-- /|\ / | \ ``` [Answer] # R, ~~177~~ 149 bytes Mickey T. is the man! He helped me fix my originally incorrect solution *and* save 28 bytes. Thanks, Mickey! ``` m=matrix(" ",(w=2*(n=scan()+1)-1),w);m[row(m)==rev(col(m))]="/";diag(m)="\\";m[,n]="|";m[n,]="-";m[n,n]="O";m[,w]=paste0(m[,w],"\n");cat(t(m),sep="") ``` Ungolfed + explanation: ``` # Create a matrix of spaces, read n from stdin, assign w=2n+1 m <- matrix(" ", (w <- 2*(n <- scan() + 1) - 1), w) # Replace the opposite diagonal with forward slashes m[row(m) == rev(col(m))] <- "/" # Replace the diagonal with backslashes diag(m) <- "\\" # Replace the vertical center line with pipes m[, n] <- "|" # Replace the horizontal center line with dashes m[n, ] <- "-" # Put an O in the middle m[n, n] <- "O" # Collapse the columns into single strings m[, w] <- paste0(m[, w], "\n") # Print the transposed matrix cat(t(m), sep = "") ``` Any further suggestions are welcome! [Answer] # C#, ~~230~~ 226 bytes ``` string g(int n){string r="";int s=n*2+1;for(int h=0;h<s;h++){for(int w=0;w<s;w++){if(h==w){if(w==n){r+="O";}else{r+="\\";}}else if(w==s-h-1){r+="/";}else if(w==n){r+="|";}else if(h==n){r+="-";}else{r+=" ";}}r+="\n";}return r;} ``` As requested, the ungolfed version: string ug(int n) { ``` // The sting we'll be returning string ret = ""; // The width and height of the output int s = n * 2 + 1; // for loop for width and height for (int height = 0; height < s; height++) { for (int width = 0; width < s; width++) { // Matches on top-left to bottom-right diagonal line if (height == width) { // If this is the center, write the 'sun' if (width == n) { ret += "O"; } // If this is not the center, add the diagonal line character else { ret += "\\"; } } // Matches on top-right to bottom-left diagonal line else if (width == s - height - 1) { ret += "/"; } // Matches to add the center line else if (width == n) { ret += "|"; } // Matches to add the horizontal line else if (height == n) { ret += "-"; } // Matches all others else { ret += " "; } } // Add a newline to separate each line ret += "\n"; } return ret; } ``` This is my first post so apologies if I've done something wrong. Any comments and corrections are very welcome. [Answer] # Ruby: ~~98~~ 92 characters Proc that returns a string with the Sun. ``` f=->n{x=(0..m=n*2).map{|i|s=?|.center m+1 s[i]=?\\ s[m-i]=?/ s} x[n]=?O.center m+1,?- x*?\n} ``` Sample run: ``` irb(main):001:0> f=->n{x=(0..m=n*2).map{|i|s=?|.center m+1;s[i]=?\\;s[m-i]=?/;s};x[n]=?O.center m+1,?-;x*?\n} => #<Proc:0x000000020dea60@(irb):1 (lambda)> irb(main):002:0> (0..3).each {|i| puts f[i]} O \|/ -O- /|\ \ | / \|/ --O-- /|\ / | \ \ | / \ | / \|/ ---O--- /|\ / | \ / | \ => 0..3 ``` [Answer] # Rust, 215 characters ``` fn a(n:usize){for i in 0..n{println!("{}\\{}|{1}/{0}",s(i),s(n-i-1))}println!("{}O{0}",vec!["-";n].concat());for i in(0..n).rev(){println!("{}/{}|{1}\\{0}",s(i),s(n-i-1))}}fn s(n:usize)->String{vec![" ";n].concat()} ``` I tried to use a string slicing method (by creating a string of `n-1` spaces and slicing to and from an index) like so: ``` fn a(n:usize){let s=vec![" ";n-(n>0)as usize].concat();for i in 0..n{println!("{}\\{}|{1}/{0}",&s[..i],&s[i..])}println!("{}O{0}",vec!["-";n].concat());for i in(0..n).rev(){println!("{}/{}|{1}\\{0}",&s[..i],&s[i..])}} ``` But that's actually 3 chars longer. Ungolfed code: ``` fn asciisun_ungolfed(n: usize) { for i in 0..n { println!("{0}\\{1}|{1}/{0}", spaces(i), spaces(n-i-1)) } println!("{0}O{0}", vec!["-"; n].concat()); for i in (0..n).rev() { println!("{0}/{1}|{1}\\{0}", spaces(i), spaces(n-i-1)) } } fn spaces(n: usize) -> String { vec![" "; n].concat() } ``` The part I like is how I shave a few chars off on the formatting strings. For example, ``` f{0}o{1}o{1}b{0}ar ``` is equivalent to ``` f{}o{}o{1}b{0}ar ``` because the "auto-incrementer" for the format string argument position is not affected by manually specifying the number, and acts completely independently. [Answer] # Octave 85 Bulding matrices as always=) `eye` produces an identity matrix, the rest is self explanatory I think. ``` m=(e=eye(2*(k=input('')+1)-1))*92+rot90(e)*47;m(:,k)='|';m(k,:)=45;m(k,k)='o';[m,''] ``` [Answer] # IDL 8.3, 135 bytes Dunno if this can be golfed more... It's very straightforward. First we create a `m x m` array (`m=2n+1`) of empty strings; then, we draw the characters in lines (`y=x`, `y=-x`, `y=n`, and `x=n`). Then we drop the O in at point `(n, n)`, and print the whole thing, formatted as `m` strings of length 1 on each line so that there's no extra spacing from printing the array natively. ``` pro s,n m=2*n+1 v=strarr(m,m) x=[0:m-1] v[x,x]='\' v[x,m-x-1]='/' v[n,x]='|' v[x,n]='-' v[n,n]='O' print,v,f='('+strtrim(m,2)+'A1)' end ``` Test: ``` IDL> s,4 \ | / \ | / \ | / \|/ ----O---- /|\ / | \ / | \ / | \ ``` [Answer] # Matlab, ~~93~~ 87 bytes Sadly the function header has to be so big... Apart from that I think it is golfed pretty well. I wonder if it could be done better with some of the syntax differences in Octave. ``` N=input('');E=eye(N)*92;D=rot90(E)*.52;H=ones(1,N)*45;V=H'*2.76;[E V D;H 79 H;D V E ''] ``` [Answer] # Javascript (*ES7 Draft*) 115 ``` f=l=>[['O |/\\-'[y^x?z+~x^y?y^l?x^l?1:2:5:3:x^l&&4]for(x in _)].join('')for(y in _=[...Array(z=2*l+1)])].join('\n') // Snippet demo: (Firefox only) for(var X of [0,1,2,3,4,5]) document.write('<pre>' + f(X) + '</pre><br />'); ``` [Answer] # Pyth - 52 bytes The hard part was figuring out how to switch the slashes for each side. I settled for defining a lambda that takes the symbols to use. ``` KdMms[*Kt-QdG*Kd\|*KdH)_UQjbg\\\/p\O*Q\-*\-Qjb_g\/\\ ``` Can likely be golfed more, explanation coming soon. [Try it online here](http://pyth.herokuapp.com/?code=KdMms%5B*Kt-QdG*Kd%5C%7C*KdH)_UQjbg%5C%5C%5C%2Fp%5CO*Q%5C-*%5C-Qjb_g%5C%2F%5C%5C&input=3). [Answer] # Perl, 94 There are a lot of nested ternary operators in here, but I think the code is reasonably straightforward. ``` $n=<>;for$x(-$n..$n){for$y(-$n..$n){print$x^$y?$x+$y?$x?$y?$":'|':'-':'/':$x?'\\':'O'}print$/} ``` **Try it out here:** [ideone.com/E8MC1d](http://ideone.com/E8MC1d) [Answer] **C# - 291 (full program)** ``` using System;using System.Linq;class P{static void Main(string[] a){Func<int,int,int,char>C=(s,x,i)=>x==(2*s+1)?'\n':i==s?x==s?'O':'-':x==s?'|':x==i?'\\':x==2*s-i?'/':' ';int S=int.Parse(a[0])*2;Console.Write(Enumerable.Range(0,(S+1)*(S+1)+S).Select(z=>C(S/2,z%(S+2),z/(S+2))).ToArray());}} ``` [Answer] # [Haskell](https://www.haskell.org/), 80 bytes ``` a#b=2*a+0^b^2 f n|r<-[-n..n]=[[" /\\x-xOx|"!!mod(0#x#y#(x-y)#(x+y))9|x<-r]|y<-r] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5ydZIK1HbIC4pzogrTSGvpshGN1o3T08vL9Y2OlpJQT8mpkK3wr@iRklRMTc/RcNAuUK5UlmjQrdSE0hqV2pqWtZU2OgWxdZUgsj/uYmZeQq2CrmJBb7xCgWlJcElRT55ChppCiaa/wE "Haskell – Try It Online") [Answer] # JavaScript (ES6), 139 135 140 + 1 bytes (+1 is for `-p` flag with node in the console) **fixed:** ``` t=(n,m)=>(m=2*n+1,(A=Array).from(A(m),(d,i)=>A.from(A(m),(e,j)=>i==j?j==n?"O":"\\":m-1==j+i?"/":i==n?"-":j==n?"|":" ").join("")).join("\n")) ``` **usage:** ``` t(3) /* \ | / \ | / \|/ ---O--- /|\ / | \ / | \ */ ``` **ungolfed:** ``` var makeSun = function (n, m) { m = 2 * n + 1; // there are 2*n+1 in each row/column return Array.from(Array(m), function (d, i) { return Array.from(Array(m), function (e, j) { // if i is j, we want to return a \ // unless we're at the middle element // in which case we return the sun ("O") if (i == j) { return j == n ? "O" : "\\"; // the other diagonal is when m-1 is j+i // so return a forward slash, / } else if (m - 1 == j + i) { return "/"; // the middle row is all dashes } else if (i == n) { return "-"; // the middle column is all pipes } else if (j == n) { return "|"; // everything else is a space } else { return " "; } }).join(""); }).join("\n"); } ``` [Answer] # Python 3, ~~193~~ 186 bytes ### Golfed ``` def f(n): s,b,e,d,g=' \\/|-';p,r,i='',int(n),0 while r:print(s*i+b+s*(r-1)+d+s*(r-1)+e);r-=1;i+=1 print(g*n+'O'+g*n);r+=1;i=n-1 while r<n+1:print(s*i+e+s*(r-1)+d+s*(r-1)+b);r+=1;i-=1 ``` ### Output ``` >>> f(3) \ | / \ | / \|/ ---O--- /|\ / | \ / | \ >>> f(5) \ | / \ | / \ | / \ | / \|/ -----O----- /|\ / | \ / | \ / | \ / | \ ``` ### Ungolfed ``` def f(n): s, b, e, d, g = ' \\/|-' p, r, i = '', int(n), 0 while r: print(s*i + b + s*(r-1) + d + s*(r-1) + e) r -= 1 i += 1 print(g*n + 'O' + g*n) r += 1 i = n-1 while r < n+1: print(s*i + e + s*(r-1) + d + s*(r-1) + b) r += 1 i -= 1 ``` [Answer] # CJam, ~~59~~ 55 bytes ``` ri:A,W%{_S*"\|/"\*\A\-(S*_@@++}%_Wf%W%['-A*_'O\++]\++N* ``` This won't win any awards as-is but I was happy enough it worked! Thanks to Sp3000 for golfing tips. [Answer] # Python, ~~175 129 127~~ 125 Bytes ``` s,q,x=' ','',int(input()) for i in range(x):d=(x-i-1);q+=(s*i+'\\'+s*d+'|'+s*d+'/'+s*i+'\n') print(q+'-'*x+'O'+'-'*x+q[::-1]) ``` Try it online [here](http://repl.it/nHv/1). [Answer] # Ruby - 130 bytes ``` def f(n);a=(0...n).map{|i|' '*i+"\\"+' '*(n-1-i)+'|'+' '*(n-1-i)+'/'+' '*i};puts(a+['-'*n+'O'+'-'*n]+a.reverse.map(&:reverse));end ``` usage: ``` irb(main):002:0> f(3) \ | / \ | / \|/ ---O--- /|\ / | \ / | \ ``` [Answer] # Perl ~~85~~ ~~91~~ ~~90~~ ~~89~~ 86B ``` map{$_=$r||O;s/^|$/ /mg;s/ (-*O-*) /-$1-/;$r="\\$s|$s/ $_ /$s|$s\\";$s.=$"}1..<>;say$r ``` Ungolfed: ``` # usage: echo 1|perl sun.pl map { $_ = $r || O; # no strict: o is "o". On the first run $r is not defined s/^|$/ /mg; # overwriting $_ saves characters on these regexes s/ (-*O-*) /-$1-/; $r = "\\$s|$s/ $_ /$s|$s\\"; # Embedded newlines save 1B vs \n. On the first run $s is not defined. $s .= $" } 1..<>; say $r ``` [Answer] # Prolog, 219 bytes No, it's not much of a golfing language. But I think this site needs more Prolog. ``` s(N,N,N,79). s(R,R,_,92). s(R,C,N,47):-R+C=:=2*N. s(N,_,N,45). s(_,N,N,124). s(_,_,_,32). c(_,C,N):-C>2*N,nl. c(R,C,N):-s(R,C,N,S),put(S),X is C+1,c(R,X,N). r(R,N):-R>2*N. r(R,N):-c(R,0,N),X is R+1,r(X,N). g(N):-r(0,N). ``` Tested with `swipl` on Linux. Invoke like so: `swipl -s asciiSun.prolog`; then query for your desired size of sun: ``` ?- g(3). \ | / \ | / \|/ ---O--- /|\ / | \ / | \ true . ``` Ungolfed: ``` % Args to sym/4 are row, column, N and the character code to be output at that location. sym(N,N,N,79). sym(R,R,_,'\\'). sym(R,C,N,'/') :- R+C =:= 2*N. sym(N,_,N,'-'). sym(_,N,N,'|'). sym(_,_,_,' '). % Args to putCols/3 are row, column, and N. % Recursively outputs the characters in row from col onward. putCols(_,C,N) :- C > 2*N, nl. putCols(R,C,N) :- sym(R,C,N,S), put_code(S), NextC is C+1, putCols(R,NextC,N). % Args to putRows/2 are row and N. % Recursively outputs the grid from row downward. putRows(R,N) :- R > 2*N. putRows(R,N) :- putCols(R,0,N), NextR is R+1, putRows(NextR,N). putGrid(N) :- putRows(0,N). ``` ]
[Question] [ A [haiku](https://www.youngwriters.co.uk/types-haiku-poem) is a poem with three lines, with a 5/7/5 *syllable* count, respectively. A **haiku-w** is poem with three lines, with a 5/7/5 **word** count, respectively. ## Challenge Write a program that will return **true** if the input is a haiku-w, and **false** if not. A valid haiku-w input must consist of 3 lines, separated by a newline. * Line 1 must consist of 5 words, each word separated by a space. * Line 2 must consist of 7 words, each word separated by a space. * Line 3 must consist of 5 words, each word separated by a space. ## Examples ``` The man in the suit is the same man from the store. He is a cool guy. ``` **Result:** True ``` Whitecaps on the bay: A broken signboard banging In the April wind. ``` **Result:** False --- ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. * Standard code-golf loopholes apply. Cheating is prohibited. * Other boolean return values, such as `1` and `0`, are acceptable. * A length-3 list of strings as an input is also acceptable. * Valid haiku-w inputs should not have leading or trailing spaces, or multiple spaces separating words. [Answer] # JavaScript (ES6), ~~73~~ ~~72~~ ~~64~~ ~~63~~ ~~54~~ ~~42~~ 39 bytes *Thanks to Neil for saving 13 bytes* ``` a=>a.map(b=>b.split` `.length)=='5,7,5' ``` ## Explanation This is a fat-arrow function that takes an array of strings as argument. It replaces each line by its word count. If it is a haiku-w, `a` now contains an array of a five, a seven and a five again. Since JavaScript doesn't allow us to compare 2 arrays at the same time, the array is converted to a string first, and then compared. This results in a boolean that is returned. [Answer] # AWK (GNU Awk), ~~24~~, ~~30~~, ~~28~~, 20 bytes **Golfed** ``` 517253==$0=q=q NF NR ``` Will output "517253" for *True*, and empty string for *False*. > > In awk, any nonzero numeric value or any nonempty string value is true. Any other value (zero or the null string, "") is false > > > [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/html_node/Truth-Values.html) **How It Works** Each awk statement (rule) consists of a pattern (or expression) with an associated action: ``` pattern {action} ``` Awk will read the input line by line (record by record) and evaluate pattern expression to see if a corresponding action is to be invoked. The code above is a standalone Awk expression (pattern) w/o the action block, which is implied to be `{print $0}` in that case. It should be read right-to-left: `q=q NF NR` Append a **N**umber of **F**ields (words) and **N**umber of **R**ecords (i.e. the current line number), to the variable *q*. This way, when processing a proper Haiku-w, *q* will be set to: * *51* - on line #1 (5 words) * *5172* - on line #2 (5 words + 7 words) * *517253* - on line #3 (5 words + 7 words + 5 words) `$0=q` Assign the newly computed value of *q* to *$0* (which holds the whole current line/record by default). `517253==$0` Compare it with a "signature" for a proper Haiku-w (517253), if there is a match, the whole expression evaluates to "true" and a corresponding action (implicit `print $0`) is run, sending "517253" to stdout (True), otherwise output will be empty (False). Note that this will properly recognize a Haiku-w, even if it is followed by an arbitrary number of garbage lines, but I believe that is ok, as: > > A length-3 list of strings as an input is also acceptable. > > > (i.e. we can assume the input to be 3 lines long) **Test** ``` >awk '517253==$0=q=q NF NR'<<EOF The man in the suit is the same man from the store. He is a cool guy. EOF 517253 ``` [Try It Online !](http://www.tutorialspoint.com/execute_bash_online.php?PID=0Bw_CjBb95KQMYU90TzNtb1FyRnM) [Answer] # [Python](https://docs.python.org/3/), 42 bytes ``` lambda l:[s.count(' ')for s in l]==[4,6,4] ``` [**Try it online!**](https://tio.run/nexus/python3#dYq9CgIxEAZ7n@LrLoFgdVgIeZKY4tRdXIjZIz93vn20Fq4bZobhcRtped@fC9I11PNDe25mwmRZCyokI0Xvw@wubo5jLfLLbILktTdjHf4hWjs0E9quaK9CBNZewLLR6cCjygeVNspHxxc) Takes input as a list of lines, with the words separated by single spaces. As we're guaranteed there'll be no leading or trailing spaces, and only single spaces will seperate each word, we can verify a w-haiku by simply counting the spaces in each line. We do this in a list comprehension, to create a list of the space-counts. If it is a correct haiku, it should look like `[4, 6, 4]`, so we compare it with this and return the result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` ċ€⁶⁼“¥©¥‘ ``` [Try it online!](https://tio.run/nexus/jelly#@3@k@1HTmkeN2x417nnUMOfQ0kMrDy191DDj////0eohGakKuYl5Cpl5CiVAZnFpZom6jnpmMYSXmAuRTSvKz4WIlOQXpeoBVXikKgAVJSok5@fnKKSXVuqpxwIA) ## Explanation ``` ċ€⁶⁼“¥©¥‘ Input: length-3 list of strings € For each string ċ ⁶ Count the number of spaces “¥©¥‘ Convert string to code page indices, makes [4, 6, 4] ⁼ Match ``` [Answer] ## Batch, 102 bytes ``` @echo off call:c&&call:c 2||exit/b :c set/an=%1+5 set/ps= for %%W in (%s%)do set/an-=1 exit/b%n% ``` Exits with non-zero errorlevel as soon as it reads a line with the wrong number of words. [Answer] # Mathematica, 21 bytes ``` {4,6,4}==Count@" "/@#& ``` Unnamed function taking a list of lists of characters as input and returning `True` or `False`. Simply counts how many spaces are in each list of characters, which under the rules of the challenge correlate perfectly with the number of words in each line. Previous submission: # Mathematica, 31 bytes ``` Length/@StringSplit/@#=={5,7,5}& ``` Unnamed function taking a list of strings as input and returning `True` or `False`. [Answer] ## Haskell, ~~34~~ 33 bytes ``` f l=[sum[1|' '<-c]|c<-l]==[4,6,4] ``` [Try it online!](https://tio.run/nexus/haskell#JYq9CsMgGEVf5SKFLCZQCJni3gfoJg4i2gh@WvwZCnl3K7jdc8/pDkHI0kg@7wXLuRp1m3MNSgi584PvqpP2EQLf7GPFAw6SvS8L0hFD1DFL85Vx5sskTdO6nGg@NWW7jeJlMSINk1LAp/02pvof "Haskell – TIO Nexus"). Edit: thanks to @xnor for a byte! [Answer] # [Retina](https://github.com/m-ender/retina), 12 bytes ``` M%` ^4¶6¶4$ ``` (there's a trailing space after the first line) [Try it online!](https://tio.run/nexus/retina#@@@rmqDAFWdyaJvZoW0mKv//h2SkKuQm5ilk5imUAJnFpZklXJnFEHZiLkQurSg/FyJSkl@UqsflkaoAVJKokJyfn6OQXlqpBwA "Retina – TIO Nexus") * `M%`` - Count the number of spaces in each line. + `M` - Match mode - print the number of matches. + `%` - for each line + ``` - separate configuration and regex pattern + - just a space. * `^4¶6¶4$` - There should be 4, 6, and 4 spaces, and exactly three lines. + `¶` matches newlines. The rest is a simple regular expression. Prints `1` for valid input, `0` for invalid. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 43 bytes ``` "$args"-replace'\S'-match'^( ) \1 \1$' ``` [Try it online!](https://tio.run/nexus/powershell#JYrBCoAgGIPvPcWIwDoU9Bbd6xjRj/ypkBpqh57eBHcY@7bltqOgYjsGfm6SLPZVjJaS1OLoUTQ0@wwU60TOedMMSw7GIZUYX5NOZ2IFsnW8gre1ST7wdLqFUT4E6f0N9X7TDw "PowerShell – TIO Nexus") ### Explanation Takes input as a newline separated string. Removes all non-whitespace, then checks to see that it matches "4 spaces, newline, 6 spaces, newline, 4 spaces newline" exactly, using a regex. The capture group matches 4 spaces, the backreference `\1` refers to that. Newlines are embedded in the string. Note the second line of the regex contains two spaces after the backreference. [Answer] # Python, ~~58~~ 44 bytes ``` lambda h:[len(l.split())for l in h]==[5,7,5] ``` -14 by tbodt [Answer] # [Perl](https://www.perl.org/), 26 bytes 24 bytes of code + 2 bytes for `-ap` flags. ``` $m.=@F}{$_=$m==575&$.==3 ``` [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdAtSPyvkqtn6@BWW60Sb6uSa2tram6qpqJna2v8/39IRqpCbmKeQmaeQgmQWVyaWcKVWQxhJ@ZC5NKK8nMhIiX5Ral6XB6pCkAliQrJ@fk5CumllXoA "Perl – TIO Nexus") [Answer] # Pyth, 9 bytes ``` qj464T/R; ``` A program that takes input of a list of `"quoted strings"` and prints `True` or `False` as appropriate. [Test suite](http://pyth.herokuapp.com/?code=qj464T%2FR%3B&test_suite=1&test_suite_input=%5B%22The+man+in+the+suit%22%2C+%22is+the+same+man+from+the+store.%22%2C+%22He+is+a+cool+guy.%22%5D%0A%5B%22Whitecaps+on+the+bay%3A%22%2C+%22A+broken+signboard+banging%22%2C+%22In+the+April+wind.%22%5D&debug=0) **How it works** ``` qj464T/R; Program. Input: Q qj464T/R;Q Implicit variable fill T Are the base-10 j digits 464 of 464 q equal / to the number ; of spaces R in each string Q in the input? Implicitly print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes *Saved lots of bytes thanks to @ETHproductions* This takes an array of three strings as input. ``` ®¸lÃ¥"5,7,5 ``` [Run it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=rrhsw6UiNSw3LDU=&input=WyJUaGUgbWFuIGluIHRoZSBzdWl0IgoiaXMgdGhlIHNhbWUgbWFuIGZyb20gdGhlIHN0b3JlIgoiSGUgaXMgYSBjb29sIGd1eS4iXQ==) [Answer] ## Pyke, ~~11~~ 9 bytes ``` dL/uq ``` [Try it here!](http://pyke.catbus.co.uk/?code=dL%2Fu%03%04%06%04q&input=%5B%22The+man+in+the+suit%22%2C+%22is+the+same+man+from+the+store.%22%2C+%22He+is+a+cool+guy.%22%5D) ``` dL/ - map(i.count(" "), input) q - ^ == V u - [4, 6, 4] ``` After the `u` byte there are the following bytes: `0x03 0x04 0x06 0x04` [Answer] # J, 12 bytes ``` 4 6 4=#@;:@> ``` The input is a boxed list of strings. ## Explanation This is a fork with a constant left tine. This checks the result of the right tine, `#@;:@>`, for equality with `4 6 4`. The right time unboxes each (`>`), then (`@`) converts each string to words (`;:`), then (`@`) takes the length of each (`#`). [Answer] ## R, 48 bytes ``` all(stringr::str_count(scan(,"")," ")==c(4,6,4)) ``` Reads a 3-length character vector from stdin and works by counting the number of spaces. To count the number of spaces we use the `str_count` from the `stringr` package which can count occurrences based on a regex pattern. An alternative approach without using packages could be: ``` all(sapply(scan(,""),function(x)length(el(strsplit(x," "))))==c(5,7,5)) ``` [Answer] ## C 142 bytes ``` void f(){char *c;l=3;s[3]={0};while(l>0){if(*c==' ')s[l-1]++;if((*c=getchar())=='\n'){l--;}}printf("%d",(s[0]==4 && s[1]==6 && s[2]==4)?1:0);} ``` Ungolfed version: ``` void f() { char *c; c = (char *)malloc(sizeof(char)); int l=3; int s[3]= {0}; while(l>0) { if(*c==' ') s[l-1]++; if( (*c=getchar())=='\n') { l--; } } printf("%d",(s[0]==4 && s[1]==6 && s[2]==4)?1:0); } ``` Returns 1 for 5/7/5 sequence else 0. A positive testcase: [![enter image description here](https://i.stack.imgur.com/xmZUX.gif)](https://i.stack.imgur.com/xmZUX.gif) [Answer] # C++, 357 bytes Sort of new to code golf, but this is the best I could do quickly ``` #include <iostream> using namespace std; int n(std::string s) { int b = 0; for(char c: s) if(c == ' ') b++; cout << "C = " << b; return b; } int main() { string a, b, c; getline(cin, a); getline(cin, b); getline(cin, c); if(n(a)==4 && n(b)==6 && n(c)==4) cout<<'1'; else cout << '0'; return 0; } ``` [Answer] # Ruby 1.9.3 Not golfed, but is itself a haiku-w ``` def haiku_w(input) lines = input.split("\n") lengths = lines.map(&:split).map(&:length) lengths.eql?([5,7,5]) end ``` or... ``` lines equals input split (newlines) lengths equals lines map split map length lengths equals five seven five? ``` Unfortunately doesn't work with leading whitespace on any lines, but does cope with trailing. [Answer] # [Python 2](https://docs.python.org/2/), ~~57~~ 64 bytes **Edit** Corrected with the addition of 7 bytes after feedback from @Dada. Thanks! ``` i,j=input,'' for x in i():j+=`len(x.split())`+' ' i(j=='5 7 5 ') ``` [Try it online!](https://tio.run/nexus/python2#JYtLCgMhEET3c4rGTSsj7oZAwH0OkAOMBCdp8TP4gcnpjcFdVb1XnaTTFM9WJeJypAwXUATi4u5WvXsb@aXK6alyIfYVARfiTmvc4AYboOidPT8Wgon/Xx2xNKpMMiqzmTDpkVOYS03ZqmE8LAzJwCslD@/2VewH "Python 2 – TIO Nexus") Not the shortest Python answer by a long way but just wanted to use the new trick I learned recently of using `input()` to display the output and save a `print` statement. Takes a list of lines as input. Requires Ctrl C (or any other key-press for that matter) to terminate the program (with an exception) in a terminal but works fine without on TIO. [Answer] # MATL, 16 bytes ``` "@Y:Ybn&h][ACA]= ``` The input is a cell array of strings and returns a [truthy or falsey array](https://tio.run/nexus/matl#@5@QqQABqgpu@UUKiTk5Cpl5BaUlxVz2CnAZzzSFkqLSVC51EKnOVYuQSc0pTlVISwSSXOpgSp0r1iXk/39DLgOuaEMFIIzlijZQAMJYEN8AyAcA). [**Try it Online**](https://tio.run/nexus/matl#@6/kEGkVmZSnlhEb7ejsGGv7/3@1ekhGqkJuYp5CZp5CCZBZXJpZoq6jnlkM4SXmQmTTivJzISIl@UWpekAVHqkKQEWJCsn5@TkK6aWVeuq1AA) **Explanation** ``` % Implicitly grab input " % For each element in the cell array @Y:Yb % Split it on spaces n % Count the number of elements &h % Horizontally concatenate everything on the stack [ACA] % Create the array [5 7 5] = % Perform an element-wise equality % Implicitly display the truthy/falsey array ``` [Answer] # MATLAB / Octave, 38 bytes ``` @(x)cellfun(@(y)sum(y==32),x)==[4 6 4] ``` This solution accepts a cell array of strings as input, counts the number of spaces in each line and then compares the result to the array `[4 6 4]` and yields a truthy (all values are 1) or falsey (any value is zero) array. [Online demo](http://ideone.com/KK8UDN) [Answer] # [Perl 6](http://perl6.org/), 25 bytes ``` {.lines».words~~(5,7,5)} ``` [Answer] ## Clojure, 44 bytes ``` #(=(for[l %](count(filter #{\ }l)))'(4 6 4)) ``` Input is list of strings. Function finds only spaces and counts them. This explanation is a Haiku. :) [Answer] # Java 7, 154 bytes ``` class M{public static void main(String[]a){System.out.print(a.length==3&&a[0].split(" ").length==5&a[1].split(" ").length==7&a[2].split(" ").length==5);}} ``` The program requirement and potential of having less or more than three lines, not too mention Java's verbosity itself, causes this 'golfed' code to be pretty big.. **Ungolfed:** [Try it here.](https://ideone.com/mW9xaG) ``` class M{ public static void main(String[] a){ System.out.print(a.length == 3 && a[0].split(" ").length == 5 & a[1].split(" ").length == 7 & a[2].split(" ").length == 5); } } ``` [Answer] # SimpleTemplate, 77 bytes Sadly, the regular expression aproach is the shortest. ``` {@if"@^([^\s]+ ?){5}\s([^\s]+ ?){7}\s([^\s]+ ?){5}+$@"is matchesargv}{@echo1} ``` Requires that the text is given as the first argument, with \*NIX-style newlines. This won't work with Windows-style newlines. **Ungolfed:** ``` {@if "@^([^\s]+ ?){5}\s([^\s]+ ?){7}\s([^\s]+ ?){5}+$@"is matches argv} {@echo 1} {@/} ``` --- **Non-regex based, 114 byes** ``` {@setR 1}{@eachargv asL keyK}{@php$DATA[L]=count(explode(' ',$DATA[L]))!=5+2*($DATA[K]&1)}{@set*R R,L}{@/}{@echoR} ``` This requires that each line is given as an argument to the function. **Ungolfed:** ``` {@set result 1} {@each argv as line key k} {@php $DATA['line'] = count(explode(' ', $DATA['line'])) != 5+2*( $DATA['k'] & 1 )} {@set* result result, line} {@/} {@echo result} ``` [Answer] # Stacked, 22 bytes ``` [' 'eq sum]map(4 6 4)= ``` Takes input from the top of the stack as a list of character strings, as such: ``` ($'The man in the suit' $'is the same man from the store.' $'He is a cool guy.') ``` ## Explanation ``` [' 'eq sum]map(4 6 4)= [ ]map map the following function over each item ' 'eq vectorized equality with ' ' sum summed (4 6 4)= is equal to (4 6 4) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` €#€g575SQ ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oaY0yEKebmpsGB/7/H60ekpGqkJuYp5CZp1ACZBaXZpao66hnFkN4ibkQ2bSi/FyISEl@UaoeUIVHqgJQUaJCcn5@jkJ6aaWeeuzXvHzd5MTkjFQA "05AB1E – TIO Nexus") **Explanation** ``` €# # split each line on spaces €g # get length of each line 575 # push the number 575 S # split into list of digits Q # compare for equality ``` [Answer] # [Java (OpenJDK)](http://openjdk.java.net/), 82 bytes -2 bytes thanks to @corvus\_192! ``` s->s[0].split(" ").length==5&s[2].split(" ").length==5&s[1].split(" ").length==7 ``` [Try it online!](https://tio.run/nexus/java-openjdk#dU5BasMwEDzLr1h0CPahIi2UHoL7gvaUo8lhbcuOiCwZ7TqhBL9dlZKSXlrmMOzMMLPz0lrTQWeRCD7ROLgWwjjWYcBOwwdObY9XmO@x1nur0UFYXLnnYNzYHOCI5rRcqh2shfjJESMnOnvTw5RKf8MYRqryhrhXw1BHenqnZntQNFvDpQRZKavdyMe6ft1sqHn533r@03qLQuzSxP6LWE/KL6zmtM/WlYPKv9@@qFJkLdYYJcLkMVx86AEzZJS3o30gSwhZJHiw/AY "Java (OpenJDK) – TIO Nexus") It looks *so golfable* but without a builtin map function, I can't find a good way. Iterating through the array is a few bytes longer, as is writing a map function using streams. Lambda expression takes an array of Strings and returns a Boolean. [Answer] # SmileBASIC, ~~96~~ 94 bytes ``` INPUT A$,B$,C$?C(A$,4)*C(B$,6)*C(C$,4)DEF C(S,E)WHILE""<S INC N,POP(S)<"! WEND RETURN N==E END ``` ]
[Question] [ # Alternating Arrays An *alternating array* is a list of any length in which two (not necessarily different) values are alternating. That is to say, all even-indexed items are equal, and all odd-indexed items are equal. Your task is to write a program or function which, when given a list of positive integers, outputs/returns `truthy` if it is alternating and `falsy` otherwise. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins! **Edge Cases:** ``` [] -> True [1] -> True [1,1] -> True [1,2,1] -> True ``` **Other Test Cases:** ``` [1,2,1,2] -> True [3,4,3] -> True [10,5,10,5,10] -> True [10,11] -> True [9,9,9,9,9] -> True [5,4,3,5,4,3] -> False [3,2,1,2,1,2] -> False [1,2,1,2,1,1,2] -> False [2,2,3,3] -> False [2,3,3,2] -> False ``` # Example Here is an example you can test your solution against, written in Python 3 (not golfed): ``` def is_alternating(array): for i in range(len(array)): if array[i] != array[i%2]: return False return True ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ḣ2ṁ⁼ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx2KjhzsbHzXu@X@4/VHTGiBy//8/moszWiE6Vkch2hBM6EApIySGjhGYaaBjqgMloHxDsBpLHSiMVYjVARtnqmOiY6wDJkEKjCGGwA2Cc6ECRkCOMUQpmAEUVYjligUA "Jelly – TIO Nexus") ### How it works ``` ḣ2ṁ⁼ Main link. Argument: A (array) ḣ2 Head 2; truncate A after its second element. If A has two or less elements, this returns A itself. ṁ Mold; cyclically repeat the elements of the previous result to create an array that has the same shape/length as A. ⁼ Test the result for equality with A. ``` [Answer] ## brainfuck, 34 bytes ``` ,>,>+>, [ [<+<<->>>-] +<[-<<] >[>] , ] <. ``` Takes the array as byte values in a string, and outputs `\x00` for false and `\x01` for true. [Try it online.](http://brainfuck.tryitonline.net/#code=LD4sPis-LFtbPCs8PC0-Pj4tXSs8Wy08PF0-Wz5dLF08Lg&input=MTIxMg&debug=on) This maintains the structure `a b 1 c` on the tape, where `c` is the current character, `b` is the previous character, and `a` is the previous previous character, as long as the array is alternating. If a mismatch is found, the pointer is moved to the left such that `a`, `b`, and the `1` flag all become zero, and this situation will continue until all the input is consumed. [Answer] # R, ~~24~~ 23 bytes ``` all((a=scan())==a[1:2]) ``` Reads a vector into STDIN, takes the first two elements of that vector, and checks equality. If the lengths of `a[1:2]` and a don't match, R will loop through `a[1:2]` to match the length of a. It will give a warning about doing so, but it will work. Surprisingly this even works for empty input, not sure why, but I'll roll with it. Saved 1 byte thanks to @MickyT [Answer] # [MATL](http://github.com/lmendo/MATL), ~~7~~ 6 bytes ``` 2YCs&= ``` For alternating arrays this outputs a non-empty matrix of ones, which is truthy. For non-alternating arrays the matrix contains at least one zero, and is thus falsy (see [here](https://codegolf.stackexchange.com/a/95057/36398)). [Try it online!](https://tio.run/nexus/matl#@28U6VysZvv/f7ShjpEOEMcCAA) Or [verify all test cases](https://tio.run/nexus/matl#S/hvFOlcrGb73yXkf3QsV7QhCOtASCMErWMEYhnomOpACQjXEKTAUgcKgWxTHRMdYx0wCeQZQ7TCtMN5EL4RkG0MVgemgWIA). ### Explanation Let's take `[1 2 1 2]` as example input. ``` 2YC % Implicit input. Build matrix whose columns are overlapping blocks of % length 2. If input has size less than 2 this gives an empty array % STACK: [1 2 1; 2 1 2] s % Sum of each column. For an empty array this gives 0 % STACK: [3 3 3] &= % Matrix of all pairwise equality comparisons. Implicit display % STACK: [1 1 1; 1 1 1; 1 1 1] ``` [Answer] ## JavaScript (ES6), 27 bytes ``` a=>!a.some((v,i)=>a[i&1]-v) ``` ### Test cases ``` let f = a=>!a.some((v,i)=>a[i&1]-v) console.log(f([])); // -> True console.log(f([1])); // -> True console.log(f([1,1])); // -> True console.log(f([1,2,1])); // -> True console.log(f([1,2,1,2])); // -> True console.log(f([10,5,10,5,10])); // -> True console.log(f([10,11])); // -> True console.log(f([9,9,9,9,9])); // -> True console.log(f([5,4,3,5,4,3])); // -> False console.log(f([3,2,1,2,1,2])); // -> False console.log(f([1,2,1,2,1,1,2])); // -> False console.log(f([2,2,3,3])); // -> False console.log(f([2,3,3,2])); // -> False ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 25 bytes ``` M`\b(\d+),\d+,(?!\1\b) ^0 ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/jvmxCTpBGToq2pAyR0NOwVYwxjkjS54gz@/@cy5DLUAWEjGKljxGVooGOqAyVAHENDLksdKOQy1THRMdYBk1zGEA0QTXA2iGcEZBkDVYBJHSMA "Retina – TIO Nexus") Instead of matching an input with alternating values (which leads to some annoying edge effects in a regex), I'm matching inputs that *aren't* valid and then negate the result afterwards. The benefit of matching an invalid input is that this is a property can be checked locally, and it doesn't need to treat empty or short input specially: any input is invalid if it contains two distinct values that are one position apart. So the first stage counts the number of matches of `\b(\d+),\d+,(?!\1\b)` which matches and captures one value, then matches the next value, and then asserts that the third value in sequence is different. This gives zero for valid inputs and something positive for invalid values. The second stage simply counts the number of matches of `^0` which is `1` if the first stage returned `0` and `1` otherwise. [Answer] # Mathematica, 29 bytes ``` #=={}||Equal@@(Most@#+Rest@#)& ``` A port of Luis Mendo's MATL algorithm. Unnamed function taking a list of numbers (or even more general objects) and returning `True` or `False`. Tests whether sums of consecutive elements are all equal. Unfortunately `Most` and `Rest` choke on the empty list, so that has to be tested separately. # Mathematica, 33 bytes ``` Differences[#,1,2]~MatchQ~{0...}& ``` Unnamed function taking a list of numbers (or even more general objects) and returning `True` or `False`. The function `Differences[#,1,2]` takes the differences, not of *consecutive* pairs of integers, but pairs of integers at distance two apart. Then we just check whether the resulting list has nothing other than zeros in it. As a bonus, for one more byte (change the `2` to `#2`), we get a function that inputs a list of integers and another positive integer `#2`, and checks whether the input list is the result of interleaving `#2` constant sequences periodically with one another. For example, ``` Differences[#,1,#2]~MatchQ~{0...}&[{1,2,3,4,5,1,2,3,4,5,1,2},5] ``` evaluates to `True`. [Answer] ## Haskell, ~~27~~ 26 bytes ``` and.(zipWith(==)=<<drop 2) ``` This evaluates to an anonymous function that solves the challenge. The idea is to drop the first two numbers from the list, zip with the original list using equality, and check that the result only contains `True`s. [Try it online!](https://tio.run/nexus/haskell#y03MzLMtKC0JLinSK87IL9dLU4k21DHSMdQxjP2fZpuYl6KnUZVZEJ5ZkqFha6tpa2OTUpRfoGCk@f8/AA "Haskell – TIO Nexus") Thanks to nimi for 1 byte! [Answer] # [Retina](https://github.com/m-ender/retina), ~~39~~ ~~32~~ 28 bytes ``` ^(\d*)((,\d+)(,\1(\3|$))*)?$ ``` [Try it online!](https://tio.run/nexus/retina#PYs7DoAwDEP3nKNISfFAUhiYGLlEhRh6DO5e@gNZfrIle@LzzhfH5IUZMc1SqBzD40S8HC5nUlJU20cY6YINA7Wo0o4h2rAioJFCP/TTn2uzkkJZNMJe "Retina – TIO Nexus") Saved 7 bytes thanks to [Martin](https://codegolf.stackexchange.com/users/8478/martin-ender)! Saved another 3 thanks to [Kobi](https://codegolf.stackexchange.com/users/7762/kobi)! And to [Kritixi](https://codegolf.stackexchange.com/users/41805/kritixi-lithos) for an idea for another 1. We optionally match a number that occupies the entire input, any pair of numbers, or any pair of numbers followed by the same pair any number of times and optionally not including the second number at the very end. Could save 2 bytes if the input was in unary. [Answer] # Pyth, 9 bytes ``` q<*<Q2lQl ``` ### Explanation ``` q<*<Q2lQlQQ Implicitly add enough Qs to make the code run <Q2 Take the first two elements of the input * lQ Repeat those len(input) times < lQ Take the first len(input) elements q Q Check if those are equal to the input ``` [Answer] # Java 8, 63 bytes ``` i->{int r=0,x=1;for(;++x<i.length;)r|=i[x]-i[x-2];return r==0;} ``` This is a lambda expression for a `Predicate< int[ ] >` Explanation: initialize the result to 0. For each element, Biteise OR the result with the difference between the current element and the element 2 indicies earlier. return `true` if the result equals 0. Otherwise return `false` [Answer] # [Perl 6](https://perl6.org), ~~49 43~~ 42 bytes ``` {!grep {![==] @_},roundrobin |.rotor: 2,:partial} ``` [Try it](https://tio.run/nexus/perl6#bZJLa4NAFIX3/ooTGorSW6naFKoYhEK33WQXJFidplKrMjOGButvt76iUToDw3C@@zjzKATD6UkPHaVodjsmpKMo32fchlnE4Nbl6shZjnK1d10f3qEinhVpxLP3OMWvzjOZcRsm2XnAZRwkVd0ke7KpI@BCVYC9j264W2DHC0atZvj/aNSpC81s1WvtBm/yk/HOK14CwYStjKFkTt2mIg@0oWHxl8QYrCxynmmY/oy0aEOPZFG3Dn5fg0T0aVZv4mJkxoyRdXTGzEa3@npY5nVkPNgV05qnypMgxV1/4Y7ykfHL5d9vsT5Ahf3FzqoXp3khNYJ9CpKCqWv2k7NQskiDhrJpEgu0Dz4FjhEE/Ri3v6Kq/wA "Perl 6 – TIO Nexus") ``` {!.grep: ->\a,\b=$_[1] {sum .[0,1]Z!==a,b}} ``` [Try it](https://tio.run/nexus/perl6#bZJLa4NAFIX3/ooTKkXpjURtClWUQKHbbrKqkWDMNJWaRBwNDeJvt@MjGqUzMAznu48zj5wzXF600JZysVszntmSdLziMTzvGZyqmGmHlCUW5u4moM3Okbee7qPg@RGatyDd/5w5TkC7sqxE2ioTFTgcKBLg@WiG4wLrNGdUa7r/j0aNOtGMWr3XHvCRfbO0cYm3gDNuSX0oGUO3ociCltQt/pTonZVJzit10x@RGi3pmUxq1s7vexDzNs1sTdyMjJjes4aOmCF0s62HaV5D@oPdMVU8UhIHJzy1F25LX@f0dvlzF/IWCqwfdlVW0SnJM5VgXYI4Z4rMfhMWZmyvQkUhmkQc9VMPgX0EQTtE9X8oqz8 "Perl 6 – TIO Nexus") ``` {!.grep: ->\a,\b=.[1] {sum .[0,1]Z!==a,b}} ``` [Try it](https://tio.run/nexus/perl6#bZJLa4NAFIX3/ooTGorSG4naFKqMBArddpNVEwkTM02lJhFHQ4P4262vaJTOwDCc7z7OPFIpcHnRfUdJy91KyMRRlOMVj/55L8CKbKIfYhHZmLkbTpsd09eGh0ymR@jrORne54QxTrs8L8qsZVIWkGBQFWDtoR7MBVZxKqjSDO8fjWp1pJmVeq894CP5FnFtEm9cCmkrXSiZfbe@yJwW1C7emBitlVHOK7XTG5AKLeiZLKrX1u87D2WTZjUmbkYGzOhYTQfMLHWrqYdxXk26g90xrXyjKOQnPDUX7ihf5/h2@TMX0y1U2D/iqi6DU5QmGsG@8DAV6lT8RsJPxF6DhqxsEkhUL90HdhEE/RBU3yEv/gA "Perl 6 – TIO Nexus") ## Expanded: ``` { ! # invert .grep: # find any mismatches -> \a, \b = .[1] # optional second parameter with default of second value from input { sum # count up the values that don't match .[ 0, 1 ] # the first two values from the input Z[![==]] # zip not equal a, b # the current two values under test. } } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` :{~c#Tbh#Co}f#= ``` [Try it online!](https://tio.run/nexus/brachylog#@29VXZesHJKUoeycX5umbPv/f7ShgZWpFZSIBQA "Brachylog – TIO Nexus") ### Explanation ``` :{ }f Find all results of the predicate below #= They must all be equal ~c#T Deconcatenate the input into three lists bh#C The middle list has two elements #Co Order that couple of elements as the output ``` [Answer] # APL, 7 bytes ``` ⊢≡⍴⍴2⍴⊢ ``` Explanation: * `2⍴⊢`: reshape the input array by 2 * `⍴⍴`: reshape the result by the original size of the input, repeating elements * `⊢≡`: see if the result of that is equal to the original input Test cases: ``` true←(1 2 1 2)(10 5 10 5 10)(10 11)(9 9 9 9 9) false←(5 4 3 5 4 3)(3 2 1 2 1 2)(1 2 1 2 1 1 2)(2 2 3 3)(2 3 3 2) ( ⊢≡⍴⍴2⍴⊢ ) ¨ true 1 1 1 1 ( ⊢≡⍴⍴2⍴⊢ ) ¨ false 0 0 0 0 0 ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda x:(x[:2]*len(x))[:len(x)]==x ``` [Try it online!](https://tio.run/nexus/python2#TYzLCsMgEEXX8StmqWUWUZtFBb/ESklpBSG1ISTg31tfhDJw594zDwca7mmZP8/XDFHRaJSwl@UdaGTMqGas1jG57wYP8AHoiJwpMhQQC/BhPXZa0LBuPuzg8g2SFpKxCIZXwd7En0FR7YgTdumZ150b9rLETHhFiVXLSLbz88UZOxA5yLZaTaY/ "Python 2 – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), ~~33~~ 32 bytes ``` f(a:x@(_:b:_))=a==b&&f x f a=1<3 ``` [Try it online!](https://tio.run/nexus/haskell#y03MzLMtKC0JLinSK87IL9dLU4k21DHSMYz9n6aRaJVklWxVpGmbaGubrKaWpgHhcqUpJNoa2hj//w8A "Haskell – TIO Nexus") or [Verify the testcases.](https://tio.run/nexus/haskell#y03MzLMtKC0JLinSK87IL1fJTSxQSIuOjtWJNgRhHSMIqWMIoyEiBjqmOlACwjUEKbDUgUIg21THRMdYB0wCecYQrTpIBoIxhG8EZBuD1YFpoFjs/zSNRKskq2SrIk3bRFvbZDW1NA0I1zpNIdHW0Mb4/38A "Haskell – TIO Nexus") -1 byte thanks to Zgarb. [Answer] ## bash, ~~56~~ ~~54~~ 38 bytes ``` [ -z $3 ]||((($1==$3))&&(shift;$0 $*)) ``` Save this as a script, and pass the list of numbers as arguments (for an n-element list, you'll pass n arguments). The output is the exit code: 0 (for true) if the list is alternating, and 1 (for false) otherwise. (Returning output in the exit code is allowed in the PPCG standard I/O methods.) This works recursively: * If the list has fewer than 3 elements, then exit with return code 0; * else if the 1st element != the 3rd element, then exit with return code 1; * else run the program recursively on the list with the first element removed. [Answer] # J, 8 bytes ``` -:$$2&{. ``` ## Explanation ``` -:$$2&{. input: (y) 2&{. the first two elements of y $ shaped like $ the shape of y -: and check if they match ``` ## Test cases ``` f =: -:$$2&{. ]true =: '' ; 1 ; 1 1 ; 1 2 1 ; 1 2 1 2 ; 10 5 10 5 10 ; 10 11 ; 9 9 9 9 9 ++-+---+-----+-------+------------+-----+---------+ ||1|1 1|1 2 1|1 2 1 2|10 5 10 5 10|10 11|9 9 9 9 9| ++-+---+-----+-------+------------+-----+---------+ f each true +-+-+-+-+-+-+-+-+ |1|1|1|1|1|1|1|1| +-+-+-+-+-+-+-+-+ ]false =: 5 4 3 5 4 3 ; 3 2 1 2 1 2 ; 1 2 1 2 1 1 2 ; 2 2 3 3 ; 2 3 3 2 +-----------+-----------+-------------+-------+-------+ |5 4 3 5 4 3|3 2 1 2 1 2|1 2 1 2 1 1 2|2 2 3 3|2 3 3 2| +-----------+-----------+-------------+-------+-------+ f each false +-+-+-+-+-+ |0|0|0|0|0| +-+-+-+-+-+ ``` [Answer] **Python 2.7, 38 bytes** ``` >> i=lambda a:(a[:2]*len(a))[0:len(a)]==a ``` **Test Cases:** ``` >> print i([1,2,1,2]) >> True >> print i([10,5,10,5,10] >> True >> print i([5,4,3,5,4,3]) >> False >> print i([3,2,1,2,1,2]) >> False ``` [Answer] # Jelly, 6 bytes My first Jelly program! I know I'll never beat Dennis, but I'm awfully proud of this regardless. ``` s2ZE€Ạ // Main link: Argument A (array) s2 // Split A into chunks of 2 // [1,2,1,2] -> [[1,2],[1,2]] Z // Transpose A // [[1,2],[1,2]] -> [[1,1],[2,2]] E€ // Map an equality check to each sublist of A // [[1,1],[2,2]] -> [1,1] Ạ // Any: return 0 if A contains any falsy values, else return 1 // [1,1] -> 1 ``` [Try it here!](http://jelly.tryitonline.net/#code=czJaReKCrOG6oA&input=&args=WzEsMiwxLDIsMSwyXQ) [Answer] ## Pyke, 6 bytes, noncompeting ``` 2<Ql{q ``` [Try it here!](http://pyke.catbus.co.uk/?code=2%3CQl%7Bq&input=%5B1%2C2%2C1%2C2%2C1%2C2%5D) ``` 2< - inp[:2] { - reshape(^, v) Ql - len(inp) q - ^ == inp ``` Allow reshape node to take a list as well as a string [Answer] # **Shenzen IO (Assembler) ,~~83~~ 76 bytes, noncompeting** Shenzen io is a puzzle game where you can code you code in a special assembler-ish language. Unfortunately, you can only use integers between -999 and 999 as inputs or outputs, and there is no way to tell if an array has ended. So i assumed that the array was written on a ROM that wraps around after reading the last cell. This means that only even arrays can be used, which is the reason for it being noncompeting. Code: ``` @mov x0 dat @mov x0 acc teq x0 dat +teq x0 acc b: +mov 1 p1 -mov 0 p1 -jmp b ``` Explanation: ``` # calling for x0 will cause rom to move 1 cell forward @ mov x0 dat # Moves value to variable dat (only run once) @ mov x0 acc # Moves rom position forward and moves x0 to acc teq x0 dat # See if dat equals x0 + teq x0 acc # If last expression was true, see x0 equals acc b: # Label for jumps (GOTO) + mov 1 p1 # Set output (p1) to 1 (same case as previous line) - mov 0 p1 # if any expression was false, set output to 0 - jmp b # jump to b: (same case as prev line) ``` Sorry if any of this is confusing, this is my first code-golf answer. EDIT: removed 7 bytes by replacing loops by run-once code [Answer] ## Ruby, 23 bytes ``` ->a{a[2..-1]==a[0..-3]} ``` [Answer] # Ruby, ~~131~~ 119 bytes ``` a=->x{!(x.values_at(*x.each_index.select{|i|i.even?}).uniq)[1]&!(x.values_at(*x.each_index.select{|i|i.odd?}).uniq[1])} ``` Lambda `a` expects an array `x` and returns true if there are 0 or 1 unique values for the odd indexed elements and 0 or 1 unique values for the even indexed elements in the array. **Notable byte-safers** * use of lambda over `def` * `!arr[1]` vs. `arr.length < 2` * `&` vs `&&` Test cases ``` p a[[]] p a[[1]] p a[[1,1]] p a[[1,2,1]] p a[[1,2,1,2]] p a[[3,4,3]] p a[[10,5,10,5,10]] p a[[10,11]] p a[[9,9,9,9,9]] #false p a[[5,4,3,5,4,3]]==false p a[[3,2,1,2,1,2]]==false p a[[1,2,1,2,1,1,2]]==false p a[[2,2,3,3]]==false p a[[2,3,3,2]]==false ``` [Answer] ## Dart, 46 bytes ``` (l){var i=0;return l.every((x)=>x==l[i++%2]);} ``` Run with: ``` void main() { var f = (l){var i=0;return l.every((x)=>x==l[i++%2]);}; print(f([1,2,1,2,1])); } ``` [Answer] # C#, 54 bytes ``` using System.Linq;p=>!p.Where((v,i)=>v!=p[i%2]).Any(); ``` Filter array to show values that do not match the first value for evens and the 2nd value for odds. If there are not any results, return true. [Answer] # Common Lisp, 62 bytes ``` (defun f(l)(or(not #1=(caddr l))(and(=(car l)#1#)(f(cdr l))))) ``` [Try it online!](https://tio.run/##RU7LCsMgEPyVIaF0vNXYHHpI/0VihYDVkKbX/Lpdo1AXd2dmH8wcls@aM93LfyM8g2LaGNOOXk@crXMbglK00bHwwnrdK3rOtSUvM6S0wicRsERcSQXq8lHz8K8YBBncYYpyw4iWKtVl8IEWgscyirEtmHqinRkEmVM/q2gKLoHi5G137OgOi@mJwx6XTrzRn47zDw) [Answer] # Japt, ~~7~~ 6 bytes ``` eUîU¯2 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=ZVXuVa8y&input=WzEsMiwxLDJd) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=ZVXuVa8y&input=WwpbMSwyLDEsMl0gICAgICAgLT4gVHJ1ZQpbMyw0LDNdICAgICAgICAgLT4gVHJ1ZQpbMTAsNSwxMCw1LDEwXSAgLT4gVHJ1ZQpbMTAsMTFdICAgICAgICAgLT4gVHJ1ZQpbOSw5LDksOSw5XSAgICAgLT4gVHJ1ZQpbNSw0LDMsNSw0LDNdICAgLT4gRmFsc2UKWzMsMiwxLDIsMSwyXSAgIC0+IEZhbHNlClsxLDIsMSwyLDEsMSwyXSAtPiBGYWxzZQpbMiwyLDMsM10gICAgICAgLT4gRmFsc2UKWzIsMywzLDJdICAgICAgIC0+IEZhbHNlCl0KLW1S) ``` :Implicit input of array U U¯2 :Get the first 2 elements of U Uî :Repeat that array to the length of U e :Test for equality with the original U ``` [Answer] # C, ~~52~~ ~~50~~ ~~49~~ 47 bytes *Thanks to @ceilingcat for golfing two bytes!* ``` f(i,l)int*i;{return--l<2?1:*i-i[2]?0:f(++i,l);} ``` Outputs 1 if the array alternates, 0 otherwise. [Try it online!](https://tio.run/##S9ZNT07@/z9NI1MnRzMzr0Qr07q6KLWktChPVzfHxsje0EorUzcz2ijW3sAqTUNbG6TMuvY/UKVCbmJmnoYmVzWXAhCABDKjzWNtqw11jHTguNYaLFtQBJRP01BSTVHSUQDZZa6pac1V@x8A) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` 2∍s∍Q ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f6FFHbzEQB/7/H21ooGOqAyViAQ "05AB1E – Try It Online") Explanation: ``` 2∍s∍Q //Full Program 2∍ //extend/shorten input to length 2 e.g. [1,2,1,2,2] -> [1,2] s∍ //extend/shorten to length of input e.g. [1,2] -> [1,2,1,2,1] Q //is equal to input e.g. [1,2,1,2,1] != [1,2,1,2,2] ``` ]
[Question] [ Given a nonempty finite list of integers, output a *truthy* value if there are exactly two equal entries and all other entries are distinct, and a *falsey* value otherwise. ### Examples ``` truthy: [1,1] [1,2,1] [1,6,3,4,4,7,9] falsey: [0] [1,1,1] [1,1,1,2] [1,1,2,2] [2,1,2,1,2] [1,2,3,4,5] ``` [Answer] # Python 3, ~~30~~ 28 bytes ``` lambda m:len({*m})+1==len(m) ``` [Try it online!](https://tio.run/##NYvNCsMgEITveYo9uq2ExvSHBvIkbQ4WDRXUiEohlD67VUkY2P1mZtet8b3YPs0wwjNpbl6Cgxm0tOR7MD88duNYjMGkjFt8hLCGZl48aGUlKFt8G6JQtvWSC4JtcFrF0gaCQwMAzisbyUzkh2tSCkRMj452U5Mn2/aV9vScdaP37E8122@K2EasEqu0p6z@XqY/ "Python 3 – Try It Online") `{*m}` casts the list to a `set` object, an unordered list of items without duplicates. Doing this will always decrease the length of the list by the number of duplicates in it. By computing how much the length has changed, we can easily tell if the list had a single duplicate and return the result of the test. -2 bytes thanks to ovs. [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` εṠ-u ``` [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/57Y@3LlAt/T////RhjqGsVxA0ghKm@kY65gAobmOJZBvABaDqQFBIyjLCMwyArNgokZgvaaxAA "Husk – Try It Online") ## Explanation ``` εṠ-u Implicit input. u Unique elements. Ṡ- Delete them from input, counting multiplicities. ε Is the result a singleton list? ``` [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f x=[1|a<-x,b<-x,a==b]==1:1:(1<$x) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjbasCbRRrdCJwlEJNraJsXa2hpaGVppGNqoVGj@z03MzFOwVUjJ51IAgoKizLwSBRWFNIVoQx3DWEwxI6yiZjrGOiZAaK5jiSFrgEU9drNB0AiruBEWcSOwOHYdRmD3mMZy/QcA "Haskell – Try It Online") Based on [H.PWiz' answer](https://codegolf.stackexchange.com/a/145064/56433). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 5 bytes ``` QL‘=L ``` [Try it online!](https://tio.run/##y0rNyan8/z/Q51HDDFuf/4fbHzWt@f8/2lDHTMdYxwQIzXUsY3UUgAJAGAsA "Jelly – Try It Online") # Explanation ``` QL‘=L - Main link, argument L (a list) e.g [1,6,3,4,4,7,9] Q - Deduplicated elements [1,6,3,4,7,9] L - Length 6 ‘ - Increment 7 L - Length of the input 7 ([1,6,3,4,4,7,9]) = - Are they equal? 1 ``` If the output values can be any consistent values, then `QL_L` works, which outputs `-1` for truthy and any other non-positive number for falsey (thanks @JonathanAllan) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~7~~, 6 bytes ``` &=sp4= ``` [Try it online!](https://tio.run/##y00syfn/X822uMDE9v//aEMdMx1jHRMgNNexjAUA "MATL – Try It Online") One byte saved thanks to @Guiseppe! Explanation: ``` &= % Table of pair-wise equality comparisons % % [1 0 0 0 0 0 0 % 0 1 0 0 0 0 0 % 0 0 1 0 0 0 0 % 0 0 0 1 1 0 0 % 0 0 0 1 1 0 0 % 0 0 0 0 0 1 0 % 0 0 0 0 0 0 1] % s % Sum each Column. Stack: % % [1 1 1 2 2 1 1] % p % Product of the array. Stack: % % [4] % 4= % Compare the stack to '4' ``` [Answer] # JavaScript (ES6), 30 bytes ``` a=>new Set(a).size==a.length-1 ``` [Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrqHxP9HWLi@1XCE4tUQjUVOvOLMq1dY2US8nNS@9JEPX8L@mRrShjpmOsY4JEJrrWMZqav4HAA) [Answer] # [Pushy](https://github.com/FTcode/Pushy), 8 bytes Simple implementation of checking whether `len(set(list)) == len(list)-1`: ``` LtvuL^=# ``` Explanation: ``` \ Implicit: Put all input on stack Ltv \ Get the stack length - 1, save in auxiliary stack u \ Remove non-unique elements L \ Get the new length ^= \ Compare with the previously saved length # \ Print result ``` This works as the length will only decrease by 1 if there was only exactly 1 non-distinct integer in the initial list. [Try it online!](https://tio.run/##Kygtzqj8/9@npKzUJ85W@f///9GGOmY6xjomQGiuYxkLAA "Pushy – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 25 bytes This is not using a `group` or `unique` approach as many of the other answers, but rather the "cartesian product" of all possible comparisions. ``` @(x)nnz(triu(x==x',1))==1 ``` ### Explanation ``` x==x' %create a matrix where the entry at (i,j) compares whether x(i) == x(ju) triu(x==x',1) %only consider the strict upper triangular matrix nnz(triu(x==x',1)) %count the number of nonzero entries @(x)nnz(triu(x==x',1))==1 %check whether this number is actually 1 ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCMy@vSqOkKLNUo8LWtkJdx1BT09bW8H9iXrFGtKGOoY6xjomOaazmfwA "Octave – Try It Online") And because no program would be complete without a convolution (thanks @LuisMendo for fixing a mistake): # [Octave](https://www.gnu.org/software/octave/), 40 bytes ``` @(x)nnz(~conv(sort(x),-1:2:1,'same'))==1 ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCMy@vSqMuOT@vTKM4v6gEKKCja2hlZGWoo16cmJuqrqlpa2v4PzGvWCPaUMdQx1jHRMc0VvM/AA "Octave – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~7~~ 6 bytes ``` =&#0,= ``` `=` check every element for equality with every unique element, creates a matrix with **m** rows for **m** unique elements. `0,` add an empty row on top. `=&#` does the number of rows equal the length of input? [Try it online!](https://tio.run/##y/r/P81WT8FWTdlAx/Z/anJGvkOag52CoYKhtaGCEZg0UzBWMAFCcwVLawMgHyIHgkZg2ghIG4FpiIgRWL3pfwA) [Answer] ## [Retina](https://github.com/m-ender/retina), ~~15~~ ~~12~~ 11 bytes *Thanks to Neil for saving 1 byte.* ``` D` Mm2`^$ 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg898lgcs31yghToXL8P9/Qx1DLkMdIzBppmOsYwKE5jqWXAZAPkQOBI3AtBGQNgLTEBEjsHpTAA "Retina – Try It Online") Input is linefeed-separated. (The test suite uses comma-separation for convenience.) ### Explanation ``` D` ``` Deduplicate the lines in the input, which removes any integer that has appeared before (but leaves the surrounding linefeed(s)). ``` Mm2`^$ ``` Count the number of empty lines, which is equal to the number of duplicates we removed, but only consider the first two matches. So the output will only be `0` (no duplicates), `1` (one duplicate), `2` (two or more duplicates). ``` 1 ``` Make sure that exactly one duplicate was removed. [Answer] # [R](https://www.r-project.org/), ~~32~~ 31 bytes *-1 byte thanks to @JarkoDubbeldam* ``` cat(sum(duplicated(scan()))==1) ``` [Try it online!](https://tio.run/##K/r/PzmxRKO4NFcjpbQgJxPISU3RKE5OzNPQ1NS0tTXU/G@oYPgfAA) Reads from stdin, writes to stdout. `duplicated` iterates through the list, replacing the values of `l` with `TRUE` if that value occurs earlier in the list, and `FALSE` otherwise. If there's a unique pair of soulmates, there should be exactly one `TRUE` value, so the sum should be `1`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes ``` 1=-/#'1?:\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxNj+FqwyAUhf/7FMIG20Cr3iQtVcYeJAtUMm1C07hFAwlje/YZ25BxQL9z77kXtVK8UvbwJN7kO0JBfj+W8+8gLcZ4Uid3Uc8nq9tOTWpWw0v1EzOlwEKJKgFsuMcZzqMO+HgrEa74rbUMbIhhM7AaSOZfD9K6YrGIoSaETy8Zq92HObvO7nzQ9cVMdaP7s9nV7sq+RuND63rPRF7wjLO2p97ooW6os1RT78buqoOJPxjG0MwSlYLEh8YT7veeZCSPOpBjhTCyuvNmyfHUXdOL4E6QCBKtVUhbigr9AUhbWkw=) A tacit version of `{1=(#x)-#?x}`. * `1?:\` run a distinct-do-scan for one iteration, returning a two-item list containing the original input and the distinct items of the input * `#'` take the count/length of each item in that list * `1=-/` is the difference between the counts one? [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes ``` 2=*/#'=: ``` [Try it online!](https://ngn.codeberg.page/k#eJxNj/1qwyAUxf/3KYQN9oGpepO0VOmThEDFaROaxi0aSBjbs8/YhowD+jv3nntRK+D0Tp9eTgKhIL6fq/l3EBZjPMmzu8rXs1VtJyc5y+Gt/omZimMueZ0ANtzjHBdRB3y8lwiT7N5aBjbEsBlYDSTzrwdpXblYRFETwqcXlGr3YS6uszsflL6aSTeqv5iddjf6NRofWtd7youS5Yy2feaNGnSTOZupzLuxu6lg4g+GMTSzQBUn8aHxhMe9Jzkpog7kWCOMrOq8WXIsddf0IngQJIJEaxXSlrJGf4TrWbs=) Checks if the product of the counts of unique elements is 2. This works because the only way to get the product of 2 is (1, 1, 1, ..., 1, 2) in some order. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` {¥_O ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/@tDSeP///6MNdcx0jHVMgNBcxzIWAA "05AB1E – Try It Online") Outputs `1` as truthy, any other non-negative integer as falsy. In 05AB1E, `1` is the only truthy number (thanks @Emigna for the insight!). ### Explanation ``` { Implicit input. Sort ¥ Consecutive differences _ Boolean negate O Sum. Implicit display ``` [Answer] # Ruby, 32 bytes ``` ->(s){s.uniq.length==s.length-1} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` qtlQl{ ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=qtlQl%7B&test_suite=1&test_suite_input=%5B1%2C1%5D%0A%5B1%2C2%2C1%5D%0A%5B1%2C6%2C3%2C4%2C4%2C7%2C9%5D%0A%5B0%5D%0A%5B1%2C1%2C1%5D%0A%5B1%2C1%2C1%2C2%5D%0A%5B1%2C1%2C2%2C2%5D%0A%5B2%2C1%2C2%2C1%2C2%5D%0A%5B1%2C2%2C3%2C4%2C5%5D&debug=0)** * `l{` - Gets the number of unique elements. * `tlQ` - Gets the length of the input list, decremented. * `q` - Checks equality. # 7 bytes ``` q1l.-Q{ ``` **[Verify all the test cases](https://pyth.herokuapp.com/?code=O&test_suite=1&test_suite_input=%5B1%2C1%5D%0A%5B1%2C2%2C1%5D%0A%5B1%2C6%2C3%2C4%2C4%2C7%2C9%5D%0A%5B0%5D%0A%5B1%2C1%2C1%5D%0A%5B1%2C1%2C1%2C2%5D%0A%5B1%2C1%2C2%2C2%5D%0A%5B2%2C1%2C2%2C1%2C2%5D%0A%5B1%2C2%2C3%2C4%2C5%5D&debug=0)** [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 35 + 18 bytes +18 for using `System.Linq`. ``` n=>n.Distinct().Count()==n.Length-1 ``` [Try it online!](https://tio.run/##LY6xDoJAEERr@IotIYFLsEVoNFaamFhYEIrzPHET3Iu3i8YQvv2EhGammXkzhnPjvA0DI3Vw@bHYlzoivcvY9JoZzt51Xr9gjCMWLWjg4/AOJ42UsPi51bSgfcfpEolWwmEgs0WSps3g5lxfwwOqQFVNao8sSEaSVO3cQLNXFamjpU6eeRHKeEXsHLHrrbp6FDs/sskjIfud10YoMthkixZTmpbxNIU/ "C# (.NET Core) – Try It Online") **67 byte alternative without Linq:** ``` n=>new System.Collections.Generic.HashSet<int>(n).Count==n.Length-1 ``` [Try it online!](https://tio.run/##Pc6xCsJAEEXR2nzFlAnEhdhq0ghqoSCksBCLdR2Tgc0s7IyKhHx7jCD25z6ek7kLEUfnrQgcY2ii7aBPZqJWycEz0A0OljgVjcTN@QI2NpJ9yax@i2JnNg92K2I9X3K4huAruEM5clkxvuBn1sF7dEqBxWyRMZIzOyttjQrftko5m9CDtSzZ7JEbbefFuEz@PUvwaE6RFPfEmN7TaX6600ORwyKHYsiyZTIM4wc "C# (.NET Core) – Try It Online") [Answer] ## Excel, 42 bytes **Danish language version** ``` =TÆLV(A:A)=SUM(--(FREKVENS(A:A,A:A)>0))+1 ``` Assumes each integer from the list in separate cell in column `A`. If we were allowed for inconsistent *falsey* values, we could save 3 bytes: ``` =TÆLV(A:A)+SUM(-(FREKVENS(A:A,A:A)>0)) ``` **English language version (44 bytes)** ``` =COUNTA(A:A)=SUM(--(FREQUENCY(A:A,A:A)>0))+1 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~40~~ 37 bytes ``` ($args|sort -u).count-eq$args.count-1 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9uKY4v6hEQbdUUy85vzSvRDe1ECwM5Rn@///f8L/Rf0MA "PowerShell – Try It Online") The `Sort-Object` command (alias `sort`) with the `-u`nique flag pulls out only the unique components of the input. For example, for input `@(1,3,3,2)`, this will result in `@(1,2,3)`. Thus, we just need to make sure that the `.count` of this object (i.e., how many elements it has) is `-eq`ual to the `.count` of our input array `-1` (i.e., we have exactly one duplicate entry). *Saved 3 bytes thanks to Sinusoid.* *Fixed bug thanks to TessellatingHeckler.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ċ@€`QṢ⁼1,2 ``` [Try it online!](https://tio.run/##y0rNyan8//9It8OjpjUJgQ93LnrUuMdQx@j///@GOmY6xjomQGipYw4A "Jelly – Try It Online") a longer but different approach [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` f x=sum[1|0<-(-)<$>x<*>x]==2+length x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwra4NDfasMbARldDV9NGxa7CRsuuItbW1kg7JzUvvSRDoeJ/bmJmnoKtQkFRZl6JgopCmkK0oY6hjrGOSex/AA "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 36 + 1 (`-a`) = 37 bytes ``` map$k{$_}++,@F;@a=keys%k;say@a+1==@F ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUAlu1olvlZbW8fBzdoh0TY7tbJYNdu6OLHSIVHb0NbWwe3/f0MFQwVjBRMF03/5BSWZ@XnF/3V9TfUMDA3@6yYCAA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` gIÙg- ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/3fPwzHTd//@jDXWMdIx1THRMYgE "05AB1E – Try It Online") ``` g # Get number of elements in input IÙg # Get number of unique elements in input - # Subtract ``` In 05AB1E 1 is the only truthy value, so for a truthy result there must be exactly 1 duplicate element removed by the uniquify. [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` f x=sum[1|a<-x,b<-x,a==b]==2+length x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwra4NDfasCbRRrdCJwlEJNraJsXa2hpp56TmpZdkKFT8z03MzFOwVUjJ51IAgoKizLwSBRWFNIVoQx3DWEwxI6yiZjrGOiZAaK5jiSFrgEU9drNB0AiruBEWcSOwOHYdRmD3mMZy/QcA "Haskell – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB (with Statistics package / toolbox), 21 bytes ``` @(x)nnz(~pdist(x))==1 ``` Anonymous function. Input is a column vector. Output is `true` (displayed as `1`) or `false` (displayed as`0`). [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzL69Ko64gJbO4BMjRtLU1/J@mEW1orWAYq8kFYRkhc8ysFYytFUzAyNxawRIiYQCXR9EJQUbIfCM43wjGR1FiBDPfNFbzPwA "Octave – Try It Online") ### Explanation `pdist(x)` computes a vector of Euclidean distances between all pairs of rows from `x`. It considers each pair only once (order of the two rows doesn't matter), and doesn't consider pairs formed by the same row twice. In our case `x` is a column vector, so Euclidean distance between two rows is just absolute difference between the two numbers. `~` is logical (Boolean) negation, `nnz` is number of nonzeros, and `==1` compares to `1`. So the result is `true` if and only if there is only one pair that gives zero distance. [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), ~~53~~ 25 bytes ``` length-(unique|length)==1 ``` Inspired by [Riley's answer](https://codegolf.stackexchange.com/questions/145030/in-search-of-a-soulmate/145061#145061) and much shorter then my original solution. [Try it online!](https://tio.run/##yyr8Hx1tqGMYqwMkjaC0mY6xjgkQmutYAvkGYDGYGhA0grKMwCwjMAsmagTWaxobGx1b8z8nNS@9JENXozQvs7A0tQbC1bS1Nfz//19@QUlmfl7xf13dvNKcHN3MvILSEiCnKLFcN7@0BMgBAA "jq – Try It Online") [Answer] # Julia, ~~39~~ 26 bytes ``` !a=sum(a.==a')==endof(a)+2 ``` ## Explanation The code generates a 2-dimensional table of booleans, which is then collected using the sum function, counting the number of same-element pairs in the cartesian square of A. Then this is compared to the length of the string plus two, and the quantities are equal only when there is exactly one repeat character. This code redefines the NOT operator. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~23~~ 26 bytes ``` @(x)prod(sum(x==x'))==4 ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzoCg/RaO4NFejwta2Ql1T09bW5H9aflFuYolCcn5uQWJyCZdqSVFpSUalFVeaRrShjmGsJoRhhGCa6RjrmAChuY4lUIhLNS0xpzgVosEApgZJJwgaIXOQZIxgMkZgDpJCI7AlprGa/wE "Octave – Try It Online") The `x==x'` part was inspired by [flawr's answer](https://codegolf.stackexchange.com/a/145046/31516). This is longer than Luis' answer, but it doesn't use any toolboxes. ### Explanation: This is an anonymous function that takes a vector `x` as input, and compares it to itself transposed. This will give a matrix where all diagonal elements are `1`, and any off diagonal elements signals that there are duplicates elements. The sum along any given column shows how many duplicates there are of that number. We want two of the numbers to have a duplicate, so we two values equal to two, and the rest unequal to two. If we take the product of this matrix, we'll get `4` if there are only two equal elements (`2*2*1*1*1*1*...`), and something other than `4` if there are no duplicates, or more than two. [Answer] # PHP, 46 bytes ``` <?=count(array_unique($argv))==count($argv)-1; ``` Counts the number of entries in [`$argv`](http://php.net/manual/en/reserved.variables.argv.php) and compares it to the number of unique entries. If the former is higher than the latter by 1 then truthy, else falsey. [Try it on eval.in!](https://eval.in/878751) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes ``` {¥>ΘO ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/@tBSu3Mz/P//jzbUUTDTUTDWUTABI3MdBctYAA "05AB1E – Try It Online") ``` {¥>ΘO # example input: [1, 6, 3, 4, 4, 7, 9] { # sort -> [1, 3, 4, 4, 6, 7, 9] ¥ # get deltas -> [ 2, 1, 0, 2, 1, 2 ] > # increment -> [ 3, 2, 1, 3, 2, 3 ] Θ # truthify (only 1 gives 1) -> [ 0, 0, 1, 0, 0, 0 ] O # sum -> 1 ``` `1` being the only truthy value in 05AB1E, we can stop here. (Thanks @Emigna for pointing that out.) To get only two distinct values, we can optionally add: ``` Θ # equals 1? -> 1 ``` ]