text
stringlengths
26
126k
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[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] # Clojure, ~~114~~ ~~105~~ ~~63~~ 41 bytes ## V4: 41 bytes -22 bytes thanks to @cliffroot. Since `digit` is a character, it can be converted to it's code via `int`, then have 48 subtracted from it to get the actual number. The map was also factored out. I don't know why it seemed necessary. ``` #(reduce(fn[a d](+(* a 2)(-(int d)48)))%) ``` ## V3: 63 bytes ``` (fn[s](reduce #(+(* %1 2)%2)(map #(Integer/parseInt(str %))s))) ``` -42 bytes (!) by peeking at other answers. My "zipping" was evidently very naïve. Instead of raising 2 to the current place's power, then multiplying it by the current digit and adding the result to the accumulator, it just multiplies the accumulator by 2, adds on the current digit, then adds it to the accumulator. Also converted the reducing function to a macro to shave off a bit. Thanks to @nimi, and @Adnan! Ungolfed: ``` (defn to-dec [binary-str] (reduce (fn [acc digit] (+ (* acc 2) digit)) (map #(Integer/parseInt (str %)) binary-str))) ``` ## V2: 105 bytes ``` #(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range)(reverse %))) ``` -9 bytes by reversing the string so I don't need to create an awkward descending range. ## V1: 114 bytes Well, I'm certainly not winning! In my defense, this is the first program I've ever written that converts between bases, so I had to learn how to do it. It also doesn't help that `Math/pow` returns a double that requires converting from, and `Integer/parseInt` doesn't accept a character, so the digit needs to be wrapped prior to passing. ``` #(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range(dec(count %))-1 -1)%)) ``` Zips the string with a descending index representing the place number. Reduces over the resulting list. Ungolfed: ``` (defn to-dec [binary-str] (reduce (fn [acc [place digit]] (let [parsed-digit (Integer/parseInt (str digit)) place-value (long (Math/pow 2 place))] (+ acc (* parsed-digit place-value)))) 0 (map vector (range (dec (count binary-str)) -1 -1) binary-str))) ``` [Answer] # Perl, ~~21~~ ~~19~~ 16 + 4 = 20 bytes -4 bytes thanks to @Dada Run with `-F -p` (including the extra space after the `F`). Pipe values to the function using `echo -n` ``` $\+=$_+$\for@F}{ ``` Run as `echo -n "101010" | perl -F -pE '$\+=$_+$\for@F}{'` I feel this is sufficiently different from @Dada's answer that it merits its own entry. Explanation: ``` -F #Splits the input character by character into the @F array -p #Wraps the entire program in while(<>){ ... print} turning it into while(<>){$\+=$_+$\for@F}{print} for@F #Loops through the @F array in order ($_ as alias), and... $\+=$_+$\ #...doubles $\, and then adds $_ to it (0 or 1)... while(<>){ } #...as long as there is input. {print}#Prints the contents of $_ (empty outside of its scope), followed by the output record separator $\ ``` This uses my personal algorithm of choice for binary-to-decimal conversion. Given a binary number, start your accumulator at 0, and go through its bits one by one. Double the accumulator each bit, then add the bit itself to your accumulator, and you end up with the decimal value. It works because each bit ends up being doubled the appropriate number of times for its position based on how many more bits are left in the original binary number. [Answer] # Haskell, 31 bytes ``` f=foldl(\a b->2*a+(read$b:[]))0 ``` Takes input in string format (e.g. `"1111"`). Produces output in integer format (e.g. `15`). `:[]` Converts from an element to an array -- in this chase from `Char` to `[Char]` (`String`). `read` Converts from string to whatever context it's in (in this case the context is addition, so converts to `Num`) so `(read$b:[])` converts `b` from `Char` to `Num`. `a` is the accumulator, so multiply that by two and add the `Num` version of `b`. If input in the format `[1,1,1,1]` was allowed, the 18 byte ``` f=foldl((+).(2*))0 ``` would work, but since it's not, it doesn't. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` (++⊢)/⌽⍎¨⍞ ``` `⍞` get string input `⍎¨` convert each character to number `⌽` reverse `(`...`)/` insert the following function between the numbers  `++⊢` the sum of the arguments plus the right argument --- ngn shaved 2 bytes. [Answer] # [7](https://esolangs.org/wiki/7), 25 bytes (65 characters) ``` 07717134200446170134271600446170001755630036117700136161177546635 ``` [Try it online!](https://tio.run/##NcjBDcBADALBlpbYhv4rc@4iRXyGzS6JouoHuq1wHfm/oMy4oCzlBB18nLZrdsXdCw) ## Explanation ``` 0**77** Initialize counter to 0 (an empty section) 17134200..77546635 Push the main loop onto the frame ``` Once the original code has finished executing, the frame is ``` ||**6**||**7**13420044**7**013427160044**7**000175563003**77**7001361**77**7546**35** ``` The last section of this is the main loop, which will run repeatedly until it gets deleted. All of it except the last two commands is data and section separators, which push commands onto the frame to leave it as: ``` ||**6**|| (main loop) |**73426644**|**67342**1**6644**|**6667**55**3663**||0013**7**||54 ``` **`3`** outputs the last section (`54`) and discards the last two bars. On the first iteration, `5` is interpreted as a switch to output format 5 ("US-TTY"), which converts each pair of commands to a character. The `4` following it does not form a group, so it is ignored. On future iterations, we are already in output format 5, so `54` is interpreted as a group meaning "input character". To do this, the character from STDIN is converted into its character code (or, on EOF, `-1`), and 1 is added. Then, the last section (which is now the `00137`) is repeated that many times. In summary: * If the character is `0`, `00137` is repeated 49 times. * If the character is `1`, `00137` is repeated 50 times. * If there are no more characters, `00137` is repeated 0 times (i.e. deleted). * If this was the first iteration, `00137` is left alone (i.e. repeated 1 time). **`5`** removes the last section (`00137` repeated some number of times) from the frame and executes it, resulting in this many sections containing **`6673`**. The main loop has now finished executing, so the last section (which is **`6673`** unless we reached EOF) runs. **`66`** concatenates the last three sections into one (and has some other effects that don't affect the number of sections), which **`73`** deletes. Thus, the last three sections are deleted, and this repeats until the last section is no longer **`6673`**. * If we reached EOF, nothing happens. * If this is the first iteration or the character was `0`, after removing the last three sections 0 or 16 times, there is just one copy left on the frame. This copy deletes itself and the two sections before it, leaving everything up to the main loop and the section after it. * If the character was `1`, after removing the last three sections 17 times, all 50 copies and the third section after the main loop (the EOF handler) have been deleted. Now, the last section left on the frame runs. This could, depending on the inputted character, be any of the three sections after the main loop. If this is the first iteration or the character was `0`, the section just after the main loop, **`73426644`**, runs. **`73`** deletes this section, and **`4`** swaps the main loop with the counter behind it. This counter keeps track of the number we want to output, stored as the number of `7`s and `1`s minus the number of `6`s and `0`s. This metric has the property that it is not changed by pacification (which changes some `6`s into `0`s, some `7`s into `1`s, and sometimes inserts `7...6` around code). **`2`** duplicates the counter and **`6`** concatenates the two copies (after pacifying the second, which, as we saw, does not change the value it represents), so the value is doubled. If this was the first iteration, the counter was previously empty, and doubling it still results in an empty section. Then, **`6`** gets rid of the empty section inserted by **`4`** (and pacifies the counter again, leaving the value unchanged), and **`44`** swaps the counter back to its original position. This leaves two empty sections on the end of the frame, which are removed automatically, and the main loop runs again. If the character was `1`, the second section after the main loop (`**67342**1**6644**`) runs. This is just like the section before it (explained in the last paragraph), except for two extra commands: a **`6`** at the start, which joins the section with the previous one before **`73`** deletes it, and a `1` in the middle, which adds a `7` to the counter (increasing its value by 1) after it gets doubled. If we reached EOF, the third section after the main loop (`**6667**55**3663**`) runs. **`666`** joins the last four sections (everything after the counter) into one section, to be deleted by **`3`**. `**7**55**3**` exits output format 5 by outputting `55` and deletes the section before it, leaving only `||**6**| (counter)` on the frame. **`66`** pacifies the two sections and combines them, turning the **`6`** back into a `0` (and not changing the value of the counter). Finally, the last **`3`** outputs everything. The `0` at the start enters output format 0 ("Numerical output"), and the rest of the section (i.e. the counter) is converted to a number by taking the number of `7`s and `1`s minus the number of `6`s and `0`s. This value, which is the input converted from binary, is output in decimal and the program terminates. [Answer] # Excel, ~~74 70~~ 55 Trailing parens already discounted. Tested in Excel Online. ## Formulae: * `A1`: Input * `B1`: `=LEN(A1)` (7) ### Main Code (48): A pretty simple "add all the powers of 2" formula: ``` =SUM(MID(A1,1+B1-SEQUENCE(B1),1)/2*2^SEQUENCE(B1)) ``` Verify with: ``` =DECIMAL(A1,2) ``` [Answer] # [R](https://www.r-project.org/), ~~48~~ 37 bytes *-11 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126)* ``` sum(utf8ToInt(scan(,""))%%2*2^(31:0)) ``` Takes input as a string, left-padded with 0s to 32 bits. [Try it online!](https://tio.run/##K/r/v7g0V6O0JM0iJN8zr0SjODkxT0NHSUlTU1XVSMsoTsPY0MpAU/O/kgFOYAiGSv8B "R – Try It Online") I copied some good ideas from [djhurio](https://codegolf.stackexchange.com/users/13849)'s [much earlier R answer](https://codegolf.stackexchange.com/a/102320/16766), so go give that an upvote too. As with the first solution there, this solution won't work for the last test case because it's too large to fit into R's default size of integer. ### Explanation To get a vector of the bits as integers 0 and 1, we use `uft8ToInt` to convert to a vector of character codes. This gives us a list of 48s and 49s, which we take mod 2 to get 0s and 1s. Then, to get the appropriate powers of 2 in descending order, we construct a range from 31 down to 0. Then we convert each of those numbers to the corresponding power of two (`2^`). Finally, we multiply the two vectors together and return their `sum`. [Answer] # x86-16 machine code, 10 bytes **Binary:** ``` 00000000: 31d2 acd0 e811 d2e2 f9c3 1......... ``` **Listing:** ``` 31 D2 XOR DX, DX ; clear output value CHRLOOP: AC LODSB ; load next char into AL D0 E8 SHR AL, 1 ; CF = LSb of ASCII char 11 D2 ADC DX, DX ; shift CF left into result E2 F9 LOOP CHRLOOP ; loop until end of string C3 RET ; return to caller ``` Callable function, input string in `[SI]` length in `CX`. Result in `DX`. **Example test program I/O:** [![enter image description here](https://i.stack.imgur.com/4rM2x.png)](https://i.stack.imgur.com/4rM2x.png) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 10 bytes ``` (+/2 1*,)/ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9LQ1jdSMNTS0dTn4tLnMuQyNABBLkMgCQFgPpACkxAMIQzAGCRrgBAD01wxXFyeVnrq6sbxGjUxlka2WlbqmvEGVgmJRellCoZcaeqeXABdSRgX) [Answer] ## C, 48 bytes ``` i;f(char *s){for(i=0;*++s;i+=i+*s-48);return i;} ``` Heavily inspired by @edc45 's answer but I made some significant changes. I made 'i' a global variable to save having to typecast. I also used a for loop to save a few bytes. It does now require a single leading 0 in the binary representation. **More readable version** ``` f(char *s){ int i = 0; // Total decimal counter for(;;*++s;i+=i+*s-48); // Shift left and add 0 or 1 depending on charecter return i; } ``` [Answer] # k, 8 bytes Same method as the Haskell answer above. ``` {y+2*x}/ ``` Example: ``` {y+2*x}/1101111111010101100101110111001110001000110100110011100000111b 2016120520371234567 ``` [Answer] # JavaScript (ES7), ~~56~~ 47 bytes Reverses a binary string, then adds each digit's value to the sum. ``` n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0) ``` **Demo** ``` f=n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0) document.write( f('101010') ) // 42 ``` [Answer] # Java 7, 87 bytes ``` long c(String b){int a=b.length()-1;return a<0?0:b.charAt(a)-48+2*c(b.substring(0,a));} ``` For some reason I always go straight to recursion. Looks like an [iterative solution](https://codegolf.stackexchange.com/a/102233/51785) works a bit nicer in this case... [Answer] # JavaScript (ES6), 38 Simple is better ``` s=>eval("for(i=v=0;c=s[i++];)v+=+c+v") ``` **Test** ``` f=s=>eval("for(i=v=0;c=s[i++];)v+=+c+v") console.log("Test 0 to 99999") for(e=n=0;n<100000;n++) { b=n.toString(2) r=f(b) if(r!=n)console.log(++e,n,b,r) } console.log(e+" errors") ``` [Answer] # Turing Machine Code, 272 bytes (Using, as usual, the morphett.info rule table syntax) ``` 0 * * l B B * * l C C * 0 r D D * * r E E * * r A A _ * l 1 A * * r * 1 0 1 l 1 1 1 0 l 2 1 _ * r Y Y * * * X X * _ r X X _ _ * halt 2 * * l 2 2 _ _ l 3 3 * 1 r 4 3 1 2 r 4 3 2 3 r 4 3 3 4 r 4 3 4 5 r 4 3 5 6 r 4 3 6 7 r 4 3 7 8 r 4 3 8 9 r 4 3 9 0 l 3 4 * * r 4 4 _ _ r A ``` AKA "Yet another trivial modification of my earlier base converter programs." [Try it online](http://morphett.info/turing/turing.html?a283209e440e64106cd35d1bc3f181e1), or you can also use test it using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine) [Answer] ## JavaScript, ~~18~~ 83 bytes ~~`f=n=>parseInt(n,2)`~~ `f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)` **Demo** ``` f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0) document.write(f('1011')) // 11 ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~8~~, 7 bytes ``` "@oovsE ``` [Try it online!](http://matl.tryitonline.net/#code=IkBvb3ZzRQ&input=JzEwMTAxJw) One byte saved thanks to @LuisMendo! [Alternate approach: (9 bytes)](http://matl.tryitonline.net/#code=b290bjpQVypz&input=JzEwMTAxJw) ``` ootn:PW*s ``` [Answer] # Befunge, ~~20~~ 18 bytes Input must be terminated with EOF rather than EOL (this lets us save a couple of bytes) ``` >+~:0`v ^*2\%2_$.@ ``` [Try it online!](http://befunge.tryitonline.net/#code=Pit-OjBgdgpeKjJcJTJfJC5A&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) **Explanation** ``` > The stack is initially empty, the equivalent of all zeros. + So the first pass add just leaves zero as the current total. ~ Read a character from stdin to the top of the stack. :0` Test if greater than 0 (i.e. not EOF) _ If true (i.e > 0) go left. %2 Modulo 2 is a shortcut for converting the character to a numeric value. \ Swap to bring the current total to the top of the stack. *2 Multiply the total by 2. ^ Return to the beginning of the loop, + This time around add the new digit to the total. ...on EOF we go right... $ Drop the EOF character from the stack. . Output the calculated total. @ Exit. ``` [Answer] # Ruby, 37 bytes ``` ruby -e 'o=0;gets.each_byte{|i|o+=o+i%2};p o/2' 1234567890123456789012345678901234567 ``` This depends on the terminating `\n` (ASCII decimal 10) being zero modulo 2 (and on ASCII 0 and 1 being 0 and 1 mod two, respectively, which thankfully they are). [Answer] # [아희(Aheui)](http://esolangs.org/wiki/Aheui), 40 bytes ``` 아빟뱐썩러숙 뎌반뗘희멍파퍄 ``` Accepts a string composed of 1s and 0s. **To try online** Since the online Aheui interpreter does not allow arbitrary-length strings as inputs, this alternative code must be used (identical code with slight modifications): Add the character `벟` at the end of the first line (after `우`) length(n)-times. ``` 어우 우어 뱐썩러숙 번댜펴퍼망희땨 ``` If the input is `10110`, the first line would be `어우벟벟벟벟벟`. When prompted for an input, do NOT type quotation marks. (i.e. type `10110`, not `"10110"`) [Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html) [Answer] # ClojureScript, 36 bytes ``` (fn[x](reduce #(+(* 2 %)(int %2))x)) ``` or ``` #(reduce(fn[a n](+(* 2 a)(int n)))%) ``` The straightforward reduction. Takes a string as input. [Answer] # Minkolang v0.15, ~~23~~ 19 bytes ``` n6ZrI[2%2i;*1R]$+N. ``` [Try it online!](http://play.starmaninnovations.com/minkolang/?code=n6ZrI%5B2%252i%3B*1R%5D%24%2BN%2E&input=1101) ### Explanation ``` n gets input in the form of a number 6Z converts to string (so that it is split into an array) r reverses it I gets the stack length [ ] for loop with the stack's length as the number of iterations 2% gets the modulo of the ascii value 1 =(string conversion)> 49 =(after modulo)> 1 0 =(string conversion)> 48 =(after modulo)> 0 2i; raises 2 to the power of the loop counter * multiplies it by the modulo 1R rotates stack 1 time $+ sums everything N. outputs as number and exit ``` [Answer] # Common Lisp, ~~99~~ ~~88~~ 72 bytes Takes a string as input ``` (defun f(s)(reduce(lambda(a d)(+ d(* a 2)))(map'list #'digit-char-p s))) ``` Ungolfed: ``` (defun bin-to-dec (bin-str) (reduce (lambda (acc digit) (+ digit (* acc 2))) (map 'list #'digit-char-p bin-str))) ``` [Answer] # ><> (Fish) ~~36~~ 28 bytes ``` /i:1+?!v$2*$2%+!| ! /0| ;n~< ``` Edit 1: Forgot to put the output in the original. Added output and used MOD 2 instead of minus 48 to convert ascii to decimal to save the extra bytes lost. (no change in bytes) Edit 2: Changed the algorithm completely. Each loop now does this; times current value by 2, then add the mod of the input. (saving of 8 bytes) [Online version](https://fishlanguage.com/playground/BPT5uHb6PgvsRyvrP) [Try it Online!](http://fish.tryitonline.net/#code=L2k6MSs_IXYkMiokMiUrIXwgIQovMHwgO25-PA&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) - This works with bigger numbers than the above link. [Answer] # **C, 44 bytes** ``` d(s,v)char*s;{return*s?d(s,v+=v+*s++-48):v;} ``` Use as follows : ``` int main(){ printf("%i\n", d("101010",0)); } ``` Remove two bytes and an unused parameter thanks to Steadybox [Answer] # **MATLAB, 49 bytes** ``` @(a)dot(int2str(a)-'0',2.^(floor(log10(a)):-1:0)) ``` Anonymous function that splits the input into an array with `int2str(a)-'0'`, then does a dot product with powers of 2. Has rounding error for the last test case, will update the solution when I figure out a fix. [Answer] # Forth (gforth 0.7.3), 47 bytes ``` : x 2 base ! bl parse s>number drop decimal . ; ``` `: x` - define new word with name 'x' `2 base !` - set base to binary `bl parse` - read line until a space (bl) or EOL `s>number` - try to convert the string to number `drop` - we only want the converted number and not the success flag `decimal` - set base to decimal `.` - print value on top of stack `;` - end of definition Test cases: ``` x 1 1 ok x 10 2 ok x 101010 42 ok x 1101111111010101100101110111001110001000110100110011100000111 2016120520371234567 ok ``` [Answer] # C, ~~41~~ 37 bytes ``` i;b(char*s){i+=i+*s++%2;i=*s?b(s):i;} ``` [Wandbox](http://melpon.org/wandbox/permlink/HSeSFhE9lswSnFlj) [Answer] # SmileBASIC, ~~47~~ 44 bytes ``` INPUT B$WHILE""<B$N=N*2+VAL(SHIFT(B$))WEND?N ``` Another program of the same size: ``` INPUT B$WHILE""<B$N=N*2OR"0"<SHIFT(B$)WEND?N ``` [Answer] # APL(NARS), 26 chars, 52 bytes ``` {+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵} ``` test: ``` f←{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵} ⎕fmt f"0" 0 ~ f"1" 1 ⎕fmt f"101010" 42 ~~ f"10" 2 (≢,f)"11011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 152 4995366924470859583704000893073232977339613183 ``` 152 bits... It should be limited from memory for store string and numbers. ]
[Question] [ A brace string is defined as a string consisting of the characters `*()[]` in which braces match correctly: ``` [brace-string] ::= [unit] || [unit] [brace-string] [unit] ::= "" || "*" || "(" [brace-string] ")" || "[" [brace-string] "]" ``` This is a valid brace-string: ``` ((())***[]**)****[(())*]* ``` But these are not: ``` )( **(**[*](**) **([*)]** ``` Your task is to write a program (or function) that, given a positive integer `n`, takes a number as input and outputs (or returns) all valid brace strings of length `n`. ## Specifications * You may output the strings in any order. * You may output as a list or a string separated by a different character. * Your program must handle 0 correctly. There is 1 possible brace-string of length 0, which is the empty string `""`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases ``` 0. 1. * 2. ** () [] 3. *** ()* []* (*) [*] *() *[] 4. **** ()** []** (*)* [*]* (**) **() **[] *(*) *[*] (()) ()() ()[] ([]) [**] [()] [[]] []() [][] *()* *[]* ``` [Answer] # Prolog, 69 bytes ``` s-->[];e,s. e-->"*";"(",s,")";"[",s,"]". b(N,A):-length(A,N),s(A,[]). ``` One of the most interesting properties of Prolog is that in many cases it's capable of running a program backwards; for example, instead of testing to see if something's true, you can generate all solutions for which it's true, and instead of checking the length of a string, you can generate all strings with a given length. (Another nice property of Prolog is that it requires whitespace after the end of each predicate definition, and a newline can be inserted as cheaply as a space; thus even golfed programs are often fairly readable.) The above defines a predicate (the equivalent of a function) `b` which tests to see if a string has a given length and is a "brace string" as defined in the question. Specifically, it does this via Prolog's grammar/regex/pattern-match support that gives some nice, short sugar for defining this sort of expression (apparently this is standard/portable, but I was unaware of this while originally writing the answer, and thus assumed the answer would work on only one Prolog implementation; it seems it works on every implementation that complies with the standards, though). The program can be translated into English fairly directly; the first two lines say "an *s* is an empty string, or an *e* followed by an *s*; an *e* is an asterisk, or an *s* in parentheses, or an *s* in square brackets". The third line can be interpreted as "The *b* of *N* can be *A* if *A* is a list with length *N* and *A* is an *s* followed by a null string." I took some care to write `s` (and thus `b`) so that they match each "brace string" in exactly one way (which is the reason that both `s` and `e` have to exist, rather than grouping them into one predicate). This makes them both entirely reversible; thus `b` can be used to generate all "brace strings" of a given length, in addition to testing if a string is a brace string of a given length (it can also be used a third way round, to figure out the length of a brace string, but that is almost certainly its least useful mode of operation). The implementation is recursive, e.g. to generate an *s*, the code will generate all possible *e*s that are no longer than the required length of the output, and append all possible *s*s that fit in the remaining space to them; because I specified the length of the argument in advance (within *b*), the Prolog engine knows that it can't generate output that's longer than the given length, which allows the recursion to terminate. Here's an example of the program in operation: ``` | ?- b(4,A),format("~s ",[A]),fail. **** **() **[] *()* *(*) *[]* *[*] ()** ()() ()[] (*)* (**) (()) ([]) []** []() [][] [*]* [**] [()] [[]] ``` [Answer] ## Haskell, ~~101~~ 94 bytes 7 bytes saved by Zgarb! ``` b 0=[""] b n=[x++y|k<-[1..n],x<-u k,y<-b$n-k] u 1=["*"] u n=[a:s++b|s<-b$n-2,a:b<-["()","[]"]] ``` Almost straightforward, following the definition, but with the `""` case moved. Use: ``` *Main> map b [0..3] [[""],["*"],["**","()","[]"],["***","*()","*[]","()*","[]*","(*)","[*]"]] *Main> length $ b 10 21595 ``` (The second computation takes less than a second on a slow machine.) I'd also like to share the result of another approach I came up with while thinking about generating functions. It defines a *list* `b` of lists of strings such that `b!!n` contains all brace-strings of length `n`. Similarly, `u!!n` contains all atoms of size `n-1`. One nice thing is that the code is not using any numbers. It is not completely golfed: `u` and `i` could be inlined, and it certainly misses a few other golfing opportunities. Unfortunately, it doesn't look like it can be made shorter than the first version, but it computes `length $ b !! 10` even faster. ``` b=[""]:b%u u=["*"]:map i b i=concatMap(\s->['(':s++")",'[':s++"]"]) (b:c)%f=zipWith(++)[[x++y|x<-b,y<-e]|e<-f]([]:c%f) ``` [Answer] # Mathematica, 116 bytes ``` #<>""&/@Select[Characters@"*([)]"~Tuples~#,(#/."*"->Nothing//.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b})=={}&]& ``` # Explanation ``` Characters@"*([)]" ``` Find the characters of the string `"*([)]"`, giving the `List` `{"*", "(", "[", ")", "]"}`. ``` ... ~Tuples~# ``` Find the tuples of the above list with length `n`. ``` (#/."*"->Nothing//.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b})=={}& ``` Unnamed Boolean function to find whether the tuple is balanced: ``` #/."*"->Nothing ``` Delete all `"*"` in the input. ``` ... //.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b} ``` Repeatedly delete all consecutive occurrences of `"("` and `")"` or `"["` and `"]"` until the input does not change. ``` ... =={} ``` Check whether the result is an empty `List`. ``` Select[ ... , ... ] ``` Find the tuples that give `True` when the Boolean function is applied. ``` #<>""&/@ ``` Convert each `List` of characters into `String`s. [Answer] # Python 2, 128 bytes ``` n=input() for i in range(5**n): try:s=','.join(' "00([*])00" '[i/5**j%5::5]for j in range(n));eval(s);print s[1::4] except:1 ``` Screw recursive regexes – we’re using Python’s parser! In order to verify that, for example, `*(**[])*` is a brace-string, we do the following: 1. Make a string like `"*", (0,"*","*", [0,0] ,0) ,"*"`, where every second character of four is a character from the brace-strings, and the remaining characters are *glue* to make this a potential Python expression. 2. `eval` it. 3. If that doesn’t throw an error, print `s[1::4]` (the brace-string characters). The *glue* characters are picked so that the string I make is a valid Python expression if and only if taking every second character out of four yields a valid brace-string. [Answer] # Jelly, 29 bytes -3 bytes thanks to @JonathanAllan *Please*, alert me if there are any problems/bugs/errors or bytes I can knock off! ``` “[(*)]”ṗµḟ”*œṣ⁾()Fœṣ⁾[]FµÐLÐḟ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xoDS3N2EcNcx/unH5o68Md84FMraOTH@5c/Khxn4amG4wZHet2aOvhCT6HJwDVcB1ud////78xAA) The previous solution(s) I had: ``` “[(*)]”ṗµḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€Tị “[(*)]”ṗµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€Tị “[(*)]”ṗµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị “[(*)]”x⁸ṗ⁸Qµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị “[(*)]”x⁸ṗ⁸Qµ¹µḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị “[(*)]”x⁸ṗ⁸Qµ¹µḟ”*œṣ⁾()Fœṣ⁾[]FµÐLµ€Ṇ€×Jḟ0ị ``` Explanation (My best attempt at a description): ``` Input n “[(*)]”ṗ-All strings composed of "[(*)]" of length n µḟ”* -Filter out all occurences of "*" œṣ⁾() -Split at all occurences of "()" F -Flatten œṣ⁾[] -Split at all occurences of "[]" F -Flatten µÐL -Repeat that operation until it gives a duplicate result Ðḟ -Filter ``` [Answer] # PHP, 149 bytes ``` for(;$argv[1]--;$l=$c,$c=[])foreach($l?:['']as$s)for($n=5;$n--;)$c[]=$s.'*()[]'[$n];echo join(' ',preg_grep('/^((\*|\[(?1)]|\((?1)\))(?1)?|)$/',$l)); ``` Uses the good old generate all possible and then filter method. Use like: ``` php -r "for(;$argv[1]--;$l=$c,$c=[])foreach($l?:['']as$s)for($n=5;$n--;)$c[]=$s.'*()[]'[$n];echo join(' ',preg_grep('/^((\*|\[(?1)]|\((?1)\))(?1)?|)$/',$l));" 4 ``` [Answer] # Python, 134 bytes ``` from itertools import* lambda n:[x for x in map(''.join,product('*()[]',repeat=n))if''==eval("x"+".replace('%s','')"*3%('*',(),[])*n)] ``` **[repl.it](https://repl.it/Eb1x)** Unnamed function that returns a list of valid strings of length `n`. Forms all length `n` tuples of the characters `*()[]`, joins them into strings using `map(''.join,...)` and filters for those that have balanced brackets by removing the "pairs" `"*"`, `"()"`, and `"[]"` in turn `n` times and checking that the result is an empty string (`n` times is overkill, especially for `"*"` but is golfier). [Answer] ## [Retina](http://github.com/mbuettner/retina), 78 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $* +%1`1 *$'¶$`($'¶$`)$'¶$`[$'¶$`] %(`^ $'; )+`(\[]|\(\)|\*)(?=.*;)|^; A`; ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoKKyUxYDEKKiQnwrYkYCgkJ8K2JGApJCfCtiRgWyQnwrYkYF0KJShgXgokJzsKKStgKFxbXXxcKFwpfFwqKSg_PS4qOyl8XjsKCkFgOw&input=NQ) ### Explanation I'm generating all possible strings of length 5 and then I filter out the invalid ones. ``` .+ $* ``` This converts the input to unary, using `1` as the digit. ``` +%1`1 *$'¶$`($'¶$`)$'¶$`[$'¶$`] ``` This repeatedly (`+`) replaces the first (`1`) one in each line (`%`) in such a way that it makes five copies of the line, one for each possible character. This is done by using the prefix and suffix substitutions, `$`` and `$'` to construct the remainder of each line. This loop stops when there are no more 1s to replace. At this point we've got all possible strings of length `N`, one on each line. ``` %(`^ $'; )+`(\[]|\(\)|\*)(?=.*;)|^; ``` These two stages are executed for each line separately (`%`). The first stage simply duplicates the line, with a `;` to separate the two copies. The second stage is another loop (`+`), which repeatedly removes `[]`, `()` or `*` from the first copy of the string, *or* removes a semicolon at the beginning of the line (which is only possible after the string has vanished completely). ``` A`; ``` Valid strings are those that no longer have a semicolon in front of them, so we simply discard all lines (`A`) which contain a semicolon. [Answer] # Python 3.5, 146 bytes ``` import re;from itertools import*;lambda f:{i for i in map(''.join,permutations("[()]*"*f,f))if re.fullmatch("(\**\[\**\]\**|\**\(\**\)\**)*|\**",i)} ``` Very long compared to other answers, but the shortest one I could currently find. It is in the form of an anonymous lambda function and therefore must be called in the format `print(<Function Name>(<Integer>))` Outputs a Python *set* of *unordered* strings representing all possible brace-strings of the input length. For example, assuming the above function is named `G`, invoking `G(3)` would result in the following output: ``` {'[*]', '*()', '*[]', '(*)', '***', '[]*', '()*'} ``` [Try It Online! (Ideone)](http://ideone.com/6QBiBM) --- However, if, like me, you aren't really a fan of simplifying things using built-ins, then here is my own *original* answer *not* using *any* external libraries to find permutations, and currently standing at a whopping **~~288~~ 237 bytes**: ``` import re;D=lambda f:f and"for %s in range(%d)"%(chr(64+f),5)+D(f-1)or'';lambda g:[i for i in eval('["".join(('+''.join('"[()]*"['+chr(o)+'],'for o in range(65,65+g))+'))'+D(g)+']')if re.fullmatch("(\**\[\**\]\**|\**\(\**\)\**)*|\**",i)] ``` Again, like the competing answer, this one is in the form of a lambda function and therefore must also be called in the format `print(<Function Name>(<Integer>))` And outputs a Python *list* of *unsorted* strings representing all brace-strings of the input length. For example, if the lambda were to be invoked as `G(3)`, this time the output would be the following: ``` ['*()', '(*)', '*[]', '[*]', '()*', '[]*', '***'] ``` Also, this one is also a lot faster than my other answer, being able to find all brace-strings of length `11` in about **115 seconds**, those of length `10` in about **19 seconds**, those of length `9` in about **4 seconds**, and those of length `8` in about **0.73 seconds** on my machine, whereas my competing answer takes *much* longer than 115 seconds for an input of `6`. [Try It Online! (Ideone)](http://ideone.com/BgBlfl) [Answer] # 05AB1E, 23 bytes ``` …[(*.∞sãʒ'*м„()„[]‚õ:õQ ``` Some of these features might have been implemented after the question was posted. Any suggestions are welcome! [Try it online!](https://tio.run/##MzBNTDJM/f//UcOyaA0tvUcd84oPLz41SV3rwp5HDfM0NIFEdOyjhlmHt1od3hr4/78JAA) # How? ``` …[(* - the string '[(*' .∞ - intersected mirror, '[(*'=>'[(*)]' s - swap the top two items, which moves the input to the top ã - cartesian power ʒ ... - filter by this code: '*м - remove all occurrences of '*' „()„[]‚ - the array ["()","[]"] õ - the empty string "" : - infinite replacement (this repeatedly removes "()", "[]", and "*" from the string õQ - test equality with the empty string ``` ]
[Question] [ Many old [**Game Boy**](https://en.wikipedia.org/wiki/Game_Boy_line) games often required string input from the user. However, there was no keyboard. This was handled by presenting the user with a "keyboard screen" like so: [![Pokemon Ruby Keyboard](https://i.stack.imgur.com/glQuY.png)](https://i.stack.imgur.com/glQuY.png) The 'character pointer' would begin on letter A. The user would navigate to each desired character with the [D-Pad](https://en.wikipedia.org/wiki/D-pad)'s four buttons (`UP`, `DOWN`, `LEFT` and `RIGHT`), then press `BUTTON A` to append it to the final string. *Please note:* * ***The grid wraps around***, so pressing `UP` whilst on letter A would take you to T. * The 'character pointer' stays put after appending a letter # The Challenge The above keyboard has options to change case and is an irregular shape. So, for simplicity, in this challenge we will use the following keyboard (the bottom right is ASCII char 32, a space): ``` 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 . ``` Typing on keyboards like this is extremely slow - so, to make this easier, your task is to write a program which tells the user the ***fastest possible way*** to type a given string. If there are multiple fastest ways, you only need to show one. The output key should be: * `>` for `RIGHT` * `<` for `LEFT` * `^` for `UP` * `v` for `DOWN` * `.` for `BUTTON A` (append current letter to string) For example, when given the string `DENNIS`, the solution would look like this: ``` >>>.>.>>v..>>.>>>v. ``` # Rules / Details * Please remember, the grid wraps around! * You may submit a full program or a function, as long as it takes the initial string and produces a solution string. Whitespace / trailing newlines are irrelevant as long as the output is correct. * You can assume input will only consist of characters typable on the specified keyboard, but it may be empty. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. Standard code-golf loopholes apply. # Test Cases *There are usually multiple solutions of the same length. For each test case, I've included the optimum length, and an example. You don't need to print the length in your answer, just the solution.* ``` FLP.TKC -> 25 steps: <<.<v.<<<v.<<<v.^.<<^.<^. MOYLEX -> 23 steps: <<v.>>v.>>>v.>^^.^.<<^. FEERSUM -> 18 steps: <<.<..<vv.>.>>.<^. MEGO -> 14 steps: <<v.<^.>>.>vv. A CAT -> 17 steps: .<^.>>>v.<<.<<vv. BOB -> 10 steps: >.<vv.>^^. (space) -> 3 steps: <^. (empty) -> 0 steps: (empty) ``` You can view my testcase generator [on repl.it](https://repl.it/E304) - please notify me if there are any bugs. Thank you everyone for the submissions! User ngn is currently the winner with 61 bytes, but if anyone can find a shorter solution, the little green tick can be moved ;) [Answer] ## JavaScript (ES6), 147 bytes ``` s=>s.replace(/./g,c=>(q=p,p="AHOVBIPWCJQXDKRYELSZFMY.GNU ".indexOf(c),"<<<>>>".substring(3,((p>>2)+10-(q>>2))%7)+["","v","vv","^"][p-q&3]+"."),p=0) ``` An interesting behaviour of `substring` is that it exchanges the arguments if the second is less than the first. This means that if I calculate the optimal number of left/right presses as a number between -3 and 3, I can add 3, and take the substring of `<<<>>>` starting at 3 and I will get the correct number of arrows. Meanwhile the down/up presses are simply handled by looking up an array using a bitwise and of the difference in rows with 3; this way is slightly shorter as there are fewer array elements. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 61 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) [`4 7∘{∊'.',⍨⍉↑b⍴¨¨'^v' '<>'⌷¨⍨⊂¨a>b←a⌊⍺-a←⍺|↓2-/0,⍺⊤⍵⍳⍨⎕a,'.'}`](http://tryapl.org/?a=%u2395io%u21900%20%u22C4%204%207%u2218%7B%u220A%27.%27%2C%u2368%u2349%u2191b%u2374%A8%A8%27%5Ev%27%20%27%3C%3E%27%u2337%A8%u2368%u2282%A8a%3Eb%u2190a%u230A%u237A-a%u2190%u237A%7C%u21932-/0%2C%u237A%u22A4%u2375%u2373%u2368%u2395a%2C%27.%27%7D%20%A8%20%27FLP.TKC%27%20%27MOYLEX%27%20%27FEERSUM%27%20%27MEGO%27%20%27A%20CAT%27%20%27BOB%27%20%27%27&run) assumes `⎕IO←0` `⎕a,'.'` the alphabet followed by a full stop `⍵⍳⍨` find the argument's chars there as indices 0..26 (`' '` and all others will be 27) `⍺⊤` encode in base 7 (note the left arg `⍺` is bound to `4 7`), get a 2×n matrix `0,` prepend zeros to the left `2-/` differences between adjacent columns `↓` split the matrix into a pair of vectors `a←⍺|` take them modulo 4 and 7 respectively, assign to `a` `b←a⌊⍺-a` make `b` the smaller of `a` and its modular inverse `'^v' '<>'⌷¨⍨⊂¨a>b` choose `^` or `v` for the first vector and `<` or `>` for the second, based on where `a` differs from `b` `b⍴¨¨` repeat each of those `b` times `⍉↑` mix the two vectors into a single matrix and transpose it, get an n×2 matrix `'.',⍨` append `.`-s on the right `∊` flatten [Answer] # Ruby, 107 bytes ``` ->s{c=0 s.tr(". ","[\\").bytes{|b|b-=65 print ["","^","^^","v"][c/7-b/7],(d=(c-c=b)%7)>3??>*(7-d):?<*d,?.}} ``` **Ungolfed in test program** ``` f=->s{ #Input in s. c=0 #Set current position of pointer to 0. s.tr(". ","[\\"). #Change . and space to the characters after Z [\ bytes{|b| #For each byte b, b-=65 #subtract 65 so A->0 B->1 etc. print ["","^","^^","v"][c/7-b/7], #Print the necessary string to move vertically. (d=(c-c=b)%7)>3? #Calculate the horizontal difference c-b (mod 7) and set c to b ready for next byte. ?>*(7-d):?<*d, #If d>3 print an appropriate number of >, else an appropriate number of <. ?. #Print . to finish the processing of this byte. } } #call like this and print a newline after each testcase f["FLP.TKC"];puts f["MOYLEX"];puts f["FEERSUM"];puts f["MEGO"];puts f["A CAT"];puts f["BOB"];puts ``` [Answer] **Mathematica, 193 bytes** **Golf** ``` StringJoin@@(StringTake[">>><<<",Mod[#〚2〛,7,-3]]<>StringTake["vv^",Mod[#〚1〛,4,-1]]<>"."&/@Differences[FirstPosition[Partition[ToUpperCase@Alphabet[]~Join~{"."," "},7],#]&/@Characters["A"<>#]])& ``` **Readable** ``` In[1]:= characters = ToUpperCase@Alphabet[]~Join~{".", " "} Out[1]= {"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", ".", " "} In[2]:= keyboard = Partition[characters, 7] Out[2]= {{"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", ".", " "}} In[3]:= characterPosition[char_] := FirstPosition[keyboard, char] In[4]:= xToString[x_] := StringTake[">>><<<", Mod[x, 7, -3]] In[5]:= yToString[y_] := StringTake["vv^", Mod[y, 4, -1]] In[6]:= xyToString[{y_, x_}] := xToString[x] <> yToString[y] <> "." In[7]:= instructionsList[input_] := xyToString /@ Differences[characterPosition /@ Characters["A" <> input]] In[8]:= instructions[input_] := StringJoin @@ instructionsList[input] In[9]:= instructions["DENNIS"] Out[9]= ">>>.>.>>v..>>.>>>v." ``` [Answer] ## Python 2, 298 bytes This is longer than it should be, but... ``` def l(c):i="ABCDEFGHIJKLMNOPQRSTUVWXYZ. ".index(c);return[i%7,i/7] def d(f,t,a=abs): v,h=l(t)[1]-l(f)[1],l(t)[0]-l(f)[0] if a(h)>3:h=h-7*h/a(h) if a(v)>2:v=v-4*v/a(v) return'^v'[v>0]*a(v)+'<>'[h>0]*a(h) s="A"+input() print''.join([d(p[0],p[1])+'.'for p in[s[n:n+2]for n in range(len(s))][:-1]]) ``` Any help would be greatly appreciated! Takes input in quotation marks. `l` returns the location of a character in the keyboard. The two `if` statements in the middle of `d` are for checking if it would be optimal to 'wrap' around the keyboard. The input, `s` has `"A"` prepended to it because the initial position of the cursor is `A`. We loop through the string in pairs, discarding the last one (which is not a pair: `[:-1]`), finding the minimum distance between the two halves of the pair. Thanks to Flp.Tkc for telling me that I can do `a=abs` instead of saying `abs` every time! [Answer] # Java 8, 1045 bytes ## Golf ``` staticchar[][]a={{'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','.',''}};staticintm=Integer.MAX_VALUE;staticStringn="";staticboolean[][]c(boolean[][]a){boolean[][]r=newboolean[4][];for(inti=0;i<4;i)r[i]=a[i].clone();returnr;}staticvoidg(inti,intj,boolean[][]v,chard,Stringp){v[i][j]=true;if(a[i][j]==d&&p.length()<m){m=p.length();n=p;}if(i-1<0){if(!v[3][j])g(3,j,c(v),d,p"^");}elseif(!v[i-1][j])g(i-1,j,c(v),d,p"^");if(i1>3){if(!v[0][j])g(0,j,c(v),d,p"v");}elseif(!v[i1][j])g(i1,j,c(v),d,p"v");if(j-1<0){if(!v[i][6])g(i,6,c(v),d,p"<");}elseif(!v[i][j-1])g(i,j-1,c(v),d,p"<");if(j1>6){if(!v[i][0])g(i,0,c(v),d,p">");}elseif(!v[i][j1])g(i,j1,c(v),d,p">");}publicstaticvoidmain(String[]args){boolean[][]v=newboolean[4][7];Scannerx=newScanner(System.in);Strings=x.next();Stringpath="";intp=0;intq=0;for(inti=0;i<s.length();i){chart=s.charAt(i);g(p,q,c(v),t,"");path=n".";n="";m=Integer.MAX_VALUE;for(intj=0;j<4;j){for(intk=0;k<7;k){if(a[j][k]==t){p=j;q=k;}}}}System.out.println(path);} ``` ## Readable ``` static char[][] a = { {'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','.',' '} }; static int m = Integer.MAX_VALUE; static String n=""; static boolean[][] c(boolean[][] a){ boolean [][] r = new boolean[4][]; for(int i = 0; i < 4; i++) r[i] = a[i].clone(); return r; } static void g(int i, int j,boolean[][] v,char d,String p) { v[i][j] = true; if (a[i][j]==d && p.length()<m){ m=p.length(); n=p; } if (i-1<0) { if(!v[3][j]) g(3, j, c(v), d, p + "^"); } else if (!v[i-1][j]) g(i-1, j, c(v), d, p + "^"); if (i+1>3) { if(!v[0][j]) g(0, j, c(v), d, p + "v"); } else if(!v[i+1][j]) g(i+1, j, c(v), d, p + "v"); if (j-1<0) { if(!v[i][6]) g(i, 6, c(v), d, p + "<"); } else if (!v[i][j-1]) g(i, j-1, c(v), d, p + "<"); if (j+1>6) { if (!v[i][0]) g(i, 0, c(v), d, p + ">"); } else if (!v[i][j+1]) g(i, j+1, c(v), d, p + ">"); } public static void main(String[] args) { boolean[][] v = new boolean[4][7]; Scanner x = new Scanner(System.in); String s = x.next(); String path=""; int p=0; int q=0; for(int i=0;i<s.length();i++){ char t=s.charAt(i); g(p,q,c(v),t,""); path+=n+"."; n=""; m=Integer.MAX_VALUE; for(int j=0;j<4;j++){ for(int k=0;k<7;k++){ if(a[j][k]==t) { p=j; q=k; } } } } System.out.println(path); } ``` ## Explanation The solution is a direct approach: poorly optimized brute force. The method `g(...)` is a basic depth first search going through each permutation (up, down, left, right). With some slight modifications in ordering for the test cases I get the output: ``` <<.v<.v<<<.v<<<.^.^<<.^<. v<<.v>>.v>>>.^^>.^.^<<. <<.<..^^<.>.>>.^<. v<<.^<.>>.^^>. .^<.v>>>.<<.^^<<. >.^^<.^^>. ^<. // new line for the last ``` ]
[Question] [ ## Problem The goal is as the title says to find the \$n\$th prime such that \$\text{the prime}-1\$ is divisible by \$n\$. ## Explanation Here is an example so you understand the question, *this is not necessarily the way it ought to be solved. It merely as a way to explain the question* given \$3\$ as an input we would first look at all the primes ``` 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 ... ``` Then we select the primes such that \$\text{the prime}-1\$ is divisible by \$n\$ (3 in this case) ``` 7 13 19 31 37 43 61 67 73 79 97 103 107 109 127 ... ``` We then select the \$n\$th term in this sequence We would output \$19\$ for an input of \$3\$ ## Note We can also think of this as the \$n\$th prime in the sequence \$\{1, n + 1, 2n + 1, 3n + 1 ...kn + 1\}\$ where \$k\$ is any natural number ## Test Cases ``` 1 --> 2 2 --> 5 3 --> 19 4 --> 29 100 --> 39301 123 --> 102337 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes 05AB1E uses [CP-1252](http://www.cp1252.com) encoding. Saved a byte thanks to *Osable* ``` µN¹*>Dp½ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOwrkqPkRwwr0&input=MTIz) **Explanation** ``` µ # for N in [1 ...] loop until counter == input N¹*> # N*input+1 (generate multiples of input and increment) D # duplicate p½ # if prime, increase counter # implicitly output last prime ``` [Answer] # Python 2, 58 bytes ``` n=N=input();m=k=1 while N:m*=k*k;k+=1;N-=m%k>~-k%n print k ``` [Answer] # Mathematica, 48 bytes ``` Select[Array[Prime,(n=#)^3],Mod[#-1,n]==0&][[n]]& ``` Unnamed function taking a single argument, which it names `n`. Generates a list of the first `n^3` primes, selects the ones that are congruent to 1 modulo `n`, then takes the `n`th element of the result. It runs in several seconds on the input 123. It's not currently known if there's always even a single prime, among the first `n^3` primes, that is congruent to 1 modulo `n`, much less `n` of them. However, the algorithm can be proved correct (at least for large `n`) under the assumption of the [generalized Riemann hypothesis](https://en.wikipedia.org/wiki/Generalized_Riemann_hypothesis)! [Answer] ## Haskell, ~~59~~ 47 bytes ``` f n=[p|p<-[1,n+1..],all((<2).gcd p)[2..p-1]]!!n ``` Usage example: `f 4` -> `29`. How it works: ``` [p|p<-[1,n+1..] ] -- make a list of all multiples of n+1 -- (including 1, as indexing is 0-based) ,all((<2).gcd p)[2..p-1] -- and keep the primes !!n -- take the nth element ``` Edit: Thanks @Damien for 12 bytes by removing the divisibility test and only looking at multiples in the first place. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘ÆP>%ð#Ṫ‘ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCYw4ZQPiXDsCPhuarigJg&input=&args=MTIz) ### How it works ``` ‘ÆP>%ð#Ṫ‘ Main link. Argument: n ð# Call the dyadic chain to the left with right argument n and left argument k = n, n+1, n+2, ... until n of them return 1. ‘ Increment; yield k+1. ÆP Test k+1 for primality, yielding 1 or 0. % Compute k%n. > Compare the results to both sides, yielding 1 if and only if k+1 is prime and k is divisible by n. Ṫ Tail; extract the last k. ‘ Increment; yield k+1. ``` [Answer] # Java 7, 106 bytes ``` int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}} ``` **Ungolfed:** ``` int c(int n){ for(int z = 1, i = 2, j, x; ; i++){ x = i; for(j = 2; j < x; x = x % j++ < 1 ? 0 : x); if(x > 1 & (i-1) % n < 1 && z++ == n){ return i; } } } ``` **Test code:** [Try it here](https://ideone.com/m4ilQc) (last test case results in a *Time limit exceeded* on ideone) ``` class M{ static int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}} public static void main(String[] a){ System.out.println(c(1)); System.out.println(c(2)); System.out.println(c(3)); System.out.println(c(4)); System.out.println(c(100)); System.out.println(c(123)); } } ``` **Output:** ``` 2 5 19 29 39301 102337 ``` [Answer] **Nasm 679 bytes (Instruction Intel 386 cpu 120 bytes)** ``` isPrime1: push ebp mov ebp,dword[esp+ 8] mov ecx,2 mov eax,ebp cmp ebp,1 ja .1 .n: xor eax,eax jmp short .z .1: xor edx,edx cmp ecx,eax jae .3 div ecx or edx,edx jz .n mov ecx,3 mov eax,ebp .2: xor edx,edx cmp ecx,eax jae .3 mov eax,ebp div ecx or edx,edx jz .n inc ecx inc ecx jmp short .2 .3: xor eax,eax inc eax .z: pop ebp ret 4 Np: push esi push edi mov esi,dword[esp+ 12] xor edi,edi or esi,esi ja .0 .e: xor eax,eax jmp short .z .0: inc esi jz .e push esi call isPrime1 add edi,eax dec esi cmp edi,dword[esp+ 12] jae .1 add esi,dword[esp+ 12] jc .e jmp short .0 .1: mov eax,esi inc eax .z: pop edi pop esi ret 4 ``` this is ungolfed one and the results ``` ;0k,4ra,8Pp isPrime1: push ebp mov ebp, dword[esp+ 8] mov ecx, 2 mov eax, ebp cmp ebp, 1 ja .1 .n: xor eax, eax jmp short .z .1: xor edx, edx cmp ecx, eax jae .3 div ecx or edx, edx jz .n mov ecx, 3 mov eax, ebp .2: xor edx, edx cmp ecx, eax jae .3 mov eax, ebp div ecx or edx, edx jz .n inc ecx inc ecx jmp short .2 .3: xor eax, eax inc eax .z: pop ebp ret 4 ; {1, n+1, 2n+1, 3n+1 } ; argomento w, return il w-esimo primo nella successione di sopra ;0j,4i,8ra,12P Np: push esi push edi mov esi, dword[esp+ 12] xor edi, edi or esi, esi ja .0 .e: xor eax, eax jmp short .z .0: inc esi jz .e push esi call isPrime1 add edi, eax dec esi cmp edi, dword[esp+ 12] jae .1 add esi, dword[esp+ 12] jc .e jmp short .0 .1: mov eax, esi inc eax .z: pop edi pop esi ret 4 00000975 55 push ebp 00000976 8B6C2408 mov ebp,[esp+0x8] 0000097A B902000000 mov ecx,0x2 0000097F 89E8 mov eax,ebp 00000981 81FD01000000 cmp ebp,0x1 00000987 7704 ja 0x98d 00000989 31C0 xor eax,eax 0000098B EB28 jmp short 0x9b5 0000098D 31D2 xor edx,edx 0000098F 39C1 cmp ecx,eax 00000991 731F jnc 0x9b2 00000993 F7F1 div ecx 00000995 09D2 or edx,edx 00000997 74F0 jz 0x989 00000999 B903000000 mov ecx,0x3 0000099E 89E8 mov eax,ebp 000009A0 31D2 xor edx,edx 000009A2 39C1 cmp ecx,eax 000009A4 730C jnc 0x9b2 000009A6 89E8 mov eax,ebp 000009A8 F7F1 div ecx 000009AA 09D2 or edx,edx 000009AC 74DB jz 0x989 000009AE 41 inc ecx 000009AF 41 inc ecx 000009B0 EBEE jmp short 0x9a0 000009B2 31C0 xor eax,eax 000009B4 40 inc eax 000009B5 5D pop ebp 000009B6 C20400 ret 0x4 68 000009B9 56 push esi 000009BA 57 push edi 000009BB 8B74240C mov esi,[esp+0xc] 000009BF 31FF xor edi,edi 000009C1 09F6 or esi,esi 000009C3 7704 ja 0x9c9 000009C5 31C0 xor eax,eax 000009C7 EB1D jmp short 0x9e6 000009C9 46 inc esi 000009CA 74F9 jz 0x9c5 000009CC 56 push esi 000009CD E8A3FFFFFF call 0x975 000009D2 01C7 add edi,eax 000009D4 4E dec esi 000009D5 3B7C240C cmp edi,[esp+0xc] 000009D9 7308 jnc 0x9e3 000009DB 0374240C add esi,[esp+0xc] 000009DF 72E4 jc 0x9c5 000009E1 EBE6 jmp short 0x9c9 000009E3 89F0 mov eax,esi 000009E5 40 inc eax 000009E6 5F pop edi 000009E7 5E pop esi 000009E8 C20400 ret 0x4 000009EB 90 nop 120 [0, 0] [1, 2] [2, 5] [3, 19] [4, 29] [5, 71] [6, 43] [7, 211] [8, 193] [9, 271] [1 0, 191] [11, 661] [12, 277] [13, 937] [14, 463] [15, 691] [16, 769] [17, 1531] [18 , 613] [19, 2357] [20, 1021] [21, 1723] [22, 1409] [23, 3313] [24, 1609] [25, 3701 ] [26, 2029] [27, 3187] [28, 2437] [29, 6961] [30, 1741] [31, 7193] [32, 3617] [33 , 4951] [34, 3877] [35, 7001] [36, 3169] [37, 10657] [38, 6271] [39, 7879] [40, 55 21] [41, 13613] [42, 3823] [43, 15137] [44, 7349] [45, 9091] [46, 7499] [47, 18049 ] [48, 6529] [49, 18229] [50, 7151] [51, 13159] [52, 10141] [53, 26501] [54, 7669] [55, 19801] [56, 11593] [57, 18127] [58, 13109] [59, 32569] [60, 8221] [61, 34649 ] [62, 17981] [63, 21799] [64, 16001] [65, 28081] [66, 10429] [67, 39799] [68, 193 81] [69, 29947] [70, 14771] [71, 47713] [72, 16417] [73, 51539] [74, 25013] [75, 2 9101] [76, 26449] [77, 50051] [78, 16927] [79, 54037] [80, 23761] [81, 41149] [82, 31489] [83, 68891] [84, 19237] [85, 51341] [86, 33713] [87, 45589] [88, 34057] [8 9, 84551] [90, 19531] [91, 64793] [92, 42689] [93, 54499] [94, 41737] [95, 76001] [96, 27457] [97, 97583] [98, 40867] [99, 66529] [100, 39301] [101, 110899] [102, 2 9989] [103, 116803] [104, 49297] [105, 51871] [106, 56711] [107, 126047] [108, 385 57] [109, 133853] [110, 42901] [111, 76369] [112, 53089] [113, 142607] [114, 40129 ] [115, 109481] [116, 63337] [117, 83071] [118, 67733] [119, 112337] [120, 41281] [121, 152219] [122, 70639] [123, 102337] ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 13 bytes Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=O-KVl2BQROKVnEAlWWDilZNOUA&input=MTIz) ``` ;╗`PD╜@%Y`╓NP ``` **Ungolfing** ``` Implicit input n. ;╗ Save a copy of n to register 0. `...`╓ Push first n values where f(x) is truthy, starting with f(0). PD Get the x-th prime - 1. ╜@% Push (x_p - 1) % n. Y If x_p-1 is divisible by n, return 1. Else, return 0. NP Get the n-th prime where n_p-1 is divisible by n. Implicit return. ``` [Answer] # Common Lisp, 162 bytes ``` (defun s(n)(do((b 2(loop for a from(1+ b)when(loop for f from 2 to(1- a)never(=(mod a f)0))return a))(a 0)(d))((= a n)d)(when(=(mod(1- b)n)0)(incf a)(setf d b)))) ``` Usage: ``` * (s 100) 39301 ``` Ungolfed: ``` (defun prime-search (n) (do ((prime 2 (loop for next from (1+ prime) when (loop for factor from 2 to (1- next) never (= (mod next factor) 0)) return next)) (count 0) (works)) ((= count n) works) (when (= (mod (1- prime) n) 0) (incf count) (setf works prime)))) ``` Some of those `loop` constructs can probably be shortened into `do` loops, but this is what I've got for now. [Answer] # [MATL](http://github.com/lmendo/MATL), 12 bytes ``` 1i:"`_YqtqG\ ``` [Try it online!](http://matl.tryitonline.net/#code=MWk6ImBfWXF0cUdc&input=NA) (For input `123` it times out in the online compiler, but it works offline.) ### Explanation ``` 1 % Push 1 i: % Input n and push [1 2 ... n] " % For each (that is, do the following n times) ` % Do...while _Yq % Next prime tq % Duplicate, subtract 1 G % Push n again \ % Modulo % End (implicit). Exit loop if top of stack is 0; else next iteration % End (implicit) % Display (implicit) ``` [Answer] # Perl, ~~77~~ 76 + 1 = 77 bytes ``` for($p=2;@a<$_;$p++){push@a,$p if(1 x$p)!~/^(11+?)\1+$/&&($p%$_<2)}say$a[-1] ``` Uses the prime-testing regex to determine if `$p` is prime, and makes sure that it's congruent to 1 mod the input (the only nonnegative integers below 2 are 0 and 1, but it can't be 0 if it's prime, so it has to be 1. saves 1 byte over `==1`). [Answer] **Mathematica 44 Bytes** ``` Pick[x=Table[i #+1,{i,# #}],PrimeQ/@x][[#]]& ``` Very fast. Uses the idea from the "Note" ``` % /@ {1, 2, 3, 4, 100, 123} // Timing ``` Output ``` {0.0156001, {2, 5, 19, 29, 39301, 102337}} ``` [Answer] # [Perl 6](https://perl6.org), ~~46 39~~ 37 bytes ``` ->\n{(2..*).grep({.is-prime&&($_-1)%%n})[n-1]} ``` ``` ->\n{(1,n+1...*).grep(*.is-prime)[n-1]} ``` ``` {(1,$_+1...*).grep(*.is-prime)[$_-1]} ``` [Answer] # Java 8, 84 bytes ### Golfed ``` (n)->{for(int s=n,i=1;;i+=n)for(int j=2;i%j>0&j<i;)if(++j==i&&--s<1)return n>1?i:2;} ``` ### Ungolfed ``` (n) -> { for (int s = n, // Counting down to find our nth prime. i = 1; // Counting up for each multiple of n, plus 1. ; // No end condition specified for outer for loop. i += n) // Add n to i every iteration. for (int j = 2; // Inner for loop for naive primality check. i % j > 0) // Keep looping while i is not divisible by j // (and implicitly while j is less than i). if(++j==i // Increment j. If j has reached i, we've found a prime && // Short-circutting logical AND, so that we only decrement s if a prime is found --s < 1) // If we've found our nth prime... return n>1?i:2; // Return it. Or 2 if n=1, because otherwise it returns 3. } ``` ## Explanation Solution inspired by several other answers. Function is a lambda that expects a single int. The `n>1?i:2` is a cheap hack because I couldn't figure out a better way to consider the case of n=1. Also, this solution times out on Ideone, but has been tested for all test cases. It times out because in order to shave a couple bytes off, I took out the explicit `j<i` check in the inner loop. It's mostly implied by `i%j>0`... except in the case of `i=1` and `j=2` (the very first iteration), in which case the loop runs until j overflows (I'm assuming). Then it works fine for all iterations afterwards. For a version that doesn't time out that's a couple bytes longer, [see here!](http://ideone.com/whXnHl) [Answer] ## Racket 109 bytes ``` (let p((j 2)(k 0))(cond[(= 0(modulo(- j 1)n))(if(= k(- n 1))j(p(next-prime j)(+ 1 k)))][(p(next-prime j)k)])) ``` Ungolfed: ``` (define (f n) (let loop ((j 2) (k 0)) (cond [(= 0 (modulo (sub1 j) n)) (if (= k (sub1 n)) j (loop (next-prime j) (add1 k)))] [else (loop (next-prime j) k)] ))) ``` Testing: ``` (f 1) (f 2) (f 3) (f 4) (f 100) (f 123) ``` Output: ``` 2 5 19 29 39301 102337 ``` [Answer] ## Ruby 64 bytes ``` require'prime';f=->(n){t=n;Prime.find{|x|(x-1)%n==0&&(t-=1)==0}} ``` Called like this: ``` f.call(100) # 39301 ``` Also, this command-line app works: ``` n=t=ARGV[0].to_i;p Prime.find{|x|(x-1)%n==0&&(t-=1)==0} ``` called like this ``` ruby -rprime find_golf_prime.rb 100 ``` but I am not so sure how to count the characters. I think I can ignore the language name, but have to include the `-rprime` and space before the script name, so that is slightly shorter, at 63 . . . [Answer] ## R, 72 bytes ``` n=scan();q=j=0;while(q<n){j=j+1;q=q+1*(numbers::isPrime(j)&!(j-1)%%n)};j ``` Terribly inefficient and slow but it works. It reads input from stdin and then uses the `isPrime` function from the `numbers` package to find the primes. The rest is just checking whether `prime - 1` is divisible by `n`. [Answer] ## JavaScript (ES6), 65 bytes ``` f=(n,i=n,j=1)=>i?f(n,i-!/^(..+?)\1+$/.test('.'.repeat(j+=n)),j):j ``` Uses the regexp primality tester, since it's a) 8 bytes shorter and b) less recursive than my pure recursive approach. [Answer] **Axiom 64 bytes** ``` f(n)==(n<0 or n>150=>0;[i*n+1 for i in 0..2000|prime?(i*n+1)].n) ``` does someone know how to write above using Axiom streams?... some example ``` -> f(i) for i in 1..150 Compiling function f with type PositiveInteger -> NonNegativeInteger [2, 5, 19, 29, 71, 43, 211, 193, 271, 191, 661, 277, 937, 463, 691, 769, 1531, 613, 2357, 1021, 1723, 1409, 3313, 1609, 3701, 2029, 3187, 2437, 6961, 1741, 7193, 3617, 4951, 3877, 7001, 3169, 10657, 6271, 7879, 5521, 13613, 3823, 15137, 7349, 9091, 7499, 18049, 6529, 18229, 7151, 13159, 10141, 26501, 7669, 19801, 11593, 18127, 13109, 32569, 8221, 34649, 17981, 21799, 16001, 28081, 10429, 39799, 19381, 29947, 14771, 47713, 16417, 51539, 25013, 29101, 26449, 50051, 16927, 54037, 23761, 41149, 31489, 68891, 19237, 51341, 33713, 45589, 34057, 84551, 19531, 64793, 42689, 54499, 41737, 76001, 27457, 97583, 40867, 66529, 39301, 110899, 29989, 116803, 49297, 51871, 56711, 126047, 38557, 133853, 42901, 76369, 53089, 142607, 40129, 109481, 63337, 83071, 67733, 112337, 41281, 152219, 70639, 102337, 75641, 126001, 42589, 176531, 85121, 107071, 62791, 187069, 55837, 152419, 94873, 104761, 92753, 203857, 62929, 226571, 72661, 144103, 99401, 193051, 69697, 168781, 112859, 133183, 111149, 250619, 60601] ``` ## Type: Tuple NonNegativeInteger [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes ``` !⁰fṗ¡+⁰1 ``` [Try it online!](https://tio.run/##yygtzv7/X/FR44a0hzunH1qoDWQZ/v//39DAAAA "Husk – Try It Online") ``` !⁰ # get the input-th element of fṗ # the elements that are primes among ¡ # the list formed by repeatedly +⁰ # adding the input to the last result 1 # starting with 1. ``` ]
[Question] [ Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order. ## Examples ``` "Hello," "world!" --> "Hollo!" "werld," "code" "golf" --> "codf" "gole" "happy" "angry" --> "hnpry" "aagpy" "qwerty" "dvorak" --> "qvertk" "dworay" "1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c" "3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559" "DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham" "Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab" "Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee" ``` ## Rules * The strings will only contain ASCII chars (32-126). * The strings will always be the same length, and will never be empty. * You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. `a1\nb2\nc3` for `"abc", "123"` is invalid). * The output may be **in either order** (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes for each language wins.** [Answer] # Java, 68 bytes ``` (a,b)->{for(int i=a.length;--i>0;){char t=a[--i];a[i]=b[i];b[i]=t;}} ``` ## Ungolfed and testing ``` import java.util.Arrays; import java.util.Collection; import java.util.function.BiConsumer; public class Main { static BiConsumer<char[], char[]> func = (left, right) -> { for (int i = left.length; --i > 0;) { char temp = left[--i]; left[i] = right[i]; right[i] = temp; } }; public static void main(String[] args) { test("Hello,","world!", "Hollo!", "werld,"); test("code", "golf", "codf", "gole"); test("happy", "angry", "hnpry", "aagpy"); } private static void test(String left, String right, String x, String y) { char[] leftChars = left.toCharArray(); char[] rightChars = right.toCharArray(); func.accept(leftChars, rightChars); Collection mixed = Arrays.asList(new String(leftChars), new String(rightChars)); if (mixed.containsAll(Arrays.asList(x, y))) { System.out.println("OK"); } else { System.out.printf("NOK: %s, %s -> %s%n", left, right, mixed); } } } ``` [Answer] ## APL, 12 ``` {↓(⍳⍴⊃⍵)⊖↑⍵} ``` Explanation: {...} defines a function, ⍵ is the right argument. The take (↑) creates a matrix out of the two strings, then rotates each column (⊖) n times, where n is the part in parenthesis (⍳⍴⊃⍵). That's defined as the iota of the length of the first argument. (Ex: length=5 ==> 1 2 3 4 5). So first column is rotated once, second twice (getting back to original positions), third column three times, etc... Try it at [tryapl.org](http://tryapl.org/?a=%7B%u2193%28%u2373%u2374%u2283%u2375%29%u2296%u2191%u2375%7D%20%27happy%27%20%27angry%27&run) [Answer] # Scala, 85 bytes ``` (_:String)zip(_:String)zip(Stream from 0)map{case(t,z)=>if(z%2==0)t else t.swap}unzip ``` take an anonymous string parameter, zip it with another string parameter, zip it with an stream of natural numbers, swap every second tuple of chars and unzip to get a tuple of sequences of chars [Answer] # Swift 3, ~~129~~ 107 bytes ``` func c(n:inout[String],b:inout[String]){ for(j,c)in n.enumerated(){ if j&1<1{n[j]=b[j];b[j]=c}} print(n,b)} ``` **Original** The function receives two arrays of strings as parameters assuming both have same length, as follows: ``` c(n:["c", "o", "d", "e"],b:["g", "o", "l", "f"]) ``` Produces following output ``` codf gole ``` **Edit 1:** Get rid of the internal tuple and change the parameters of the function to be `inout`. Instead of string concatenation manipulate the parameters directly. Example input: ``` var a:Array<String> = ["c", "o", "d", "e"] var b:Array<String> = ["g", "o", "l", "f"] c(n:&a,b:&b) ``` Ouput changed to be array of strings as in: `["g", "o", "l", "e"] ["c", "o", "d", "f"]` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` Tz*İ_ze ``` [Try it online!](https://tio.run/##yygtzv7/P6RK68iG@KrU////e6Tm5OTr/A/PL8pJUQQA "Husk – Try It Online") Outputs are reversed. [Answer] # [Ly](https://github.com/LyricLy/Ly), 11 bytes ``` ir>ir[<o>o] ``` [Try it online!](https://tio.run/##y6n8/z@zyC6zKNom3y4/9v//5PyUVK70/Jw0AA "Ly – Try It Online") This takes the two strings on separate input lines, and outputs the interlaced strings concatenated together. At a high level... It reads the two strings onto separate stacks, then just loops printing the top the each stack. ``` ir - read first string onto the stack, reverse it >ir - switch to new stack, read second string and reverse it [ ] - loop until the stack is empty <o - switch to first stack and print a char >o - switch to the second stack and print a char ``` ]
[Question] [ ### Background When I was in elementary school, we used to play a game in math class that goes as follows. All kids sit in a big circle and take turns counting, starting from **1**. However, the following numbers must be skipped while counting: * Numbers that are multiples of **3**. * Numbers that have a **3** in its decimal representation. The first 15 numbers the kids should say are ``` 1 2 4 5 7 8 10 11 14 16 17 19 20 22 25 ``` Whenever somebody gets a number wrong – says a number that isn't in the sequence or skips a number that is – he's removed from the circle. This goes on until there's only one kid left. ### Task You're bad at this game, so you decide to cheat. Write a program or a function that, given a number of the sequence, calculates the next number of the sequence. You don't have to handle numbers that cannot be represented using your language's native numeric type, provided that your program works correctly up to input **251** and that your algorithm works for arbitrarily large inputs. Input and output can use any convenient base. Since you have to conceal your code, it must be as short as possible. In fact, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ### Test cases ``` 1 -> 2 2 -> 4 11 -> 14 22 -> 25 29 -> 40 251 -> 254 ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 10 bytes ``` <.='e3:I'* ``` [Try it online!](http://brachylog.tryitonline.net/#code=PC49J2UzOkknKg&input=Mjk&args=Wg) ### Explanation ``` (?)<. Output > Input .= Assign a value to the Output . 'e3 3 cannot be an element of the Output (i.e. one of its digits) 3:I'*(.) There is no I such that 3*I = Output ``` [Answer] # JavaScript (ES6), 30 bytes ``` f=n=>++n%3*!/3/.test(n)?n:f(n) ``` [Answer] # J, 24 bytes ``` 3(]0&({$:)~e.&":+.0=|)>: ``` Straight-forward approach that just iterates forward from input *n* until it finds the next number that is valid by the rules. Forms five smileys, `$:`, `:)`, `0=`, `=|`, and `>:`. ## Usage ``` f =: 3(]0&({$:)~e.&":+.0=|)>: (,.f"0) 1 2 11 22 29 251 1 2 2 4 11 14 22 25 29 40 251 254 ``` ## Explanation ``` 3(]0&({$:)~e.&":+.0=|)>: Input: integer n >: Increment n 3 The constant 3 ( ) Operate dyadically with 3 (LHS) and n+1 (RHS) | Take (n+1) mod 3 0= Test if equal to 0 &": Format both 3 and n+1 as a string e. Test if it contains '3' in str(n+1) +. Logical OR the results from those two tests ] Right identity, gets n+1 0&( )~ If the result from logical OR is true $: Call recursively on n+1 { Return that as the result Else act as identity function and return n+1 ``` [Answer] ## Python 2, 73 66 43 bytes Thanks to xnor for telling me I was being silly by using 2 variables, and thanks to Mitch Schwartz too. ``` x=~input() while'3'[:x%3]in`x`:x-=1 print-x ``` [Answer] ## Perl, 19 bytes **18 bytes code + 1 for `-p`.** ``` ++$_%3&&!/3/||redo ``` ### Usage ``` perl -pe '++$_%3&&!/3/||redo' <<< 8 10 perl -pe '++$_%3&&!/3/||redo' <<< 11 14 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes ``` [>Ð3ås3Ö~_# ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Wz7DkDPDpXMzw5Z-XyM&input=Mjk) **Explanation** ``` # implicit input [ # start loop > # increase current number Ð # triplicate # # break loop IF _ # logical negation of 3å # number has one or more 3's in it ~ # OR s3Ö # number % 3 == 0 ``` [Answer] # Java 8, ~~57~~ ~~56~~ ~~55~~ 50 bytes *Thanks to @Numberknot for 1 byte* *Thanks to @Kevin Cruijssen for 5 bytes* ``` i->{for(;++i%3<1|(i+"").contains("3"););return i;} ``` This is a `Function<Integer, Integer>` **Explanation** Naive implementation that simply increments until it reaches an acceptable number. **Test Class** ``` public class CodeGolf { public static void main(String[] args) { Function<Integer, Integer> countingGame = i->{for(;++i%3<1|(i+"").contains("3"););return i;}; int val = 1; for (int i = 0; i < 10; i++) { System.out.print(val + " "); val = countingGame.apply(val); } } } ``` Output of Test Class: ``` 1 2 4 5 7 8 10 11 14 16 ``` [Answer] # Python 2, ~~49~~ ~~44~~ 42 bytes ``` f=lambda x:'3'[:~x%3]in`~x`and f(x+1)or-~x ``` The other Python entry beats this (edit: not any more :-D), but I posted it because I rather like its recursive approach. Thanks to Mitch Schwarz and Erik the Golfer for helping me make this shorter. [Answer] # Japt, 18 bytes ``` °U%3*!Us f'3 ?U:ßU ``` [**Test it online**](http://ethproductions.github.io/japt/?v=master&code=sFUlMyohVXMgZiczID9VOt9V&input=MTE=) I finally have a chance to use `ß` :-) ### How it works ``` // Implicit: U = input integer °U%3 // Increment U, and take its modulo by 3. !Us f'3 // Take all matches of /3/ in the number, then take logical NOT. // This returns true if the number does not contain a 3. * // Multiply. Returns 0 if U%3 === 0 or the number contains a 3. ?U // If this is truthy (non-zero), return U. :ßU // Otherwise, return the result of running the program again on U. // Implicit: output last expression ``` [Answer] ## PowerShell v2+, 46 bytes ``` for($a=$args[0]+1;$a-match3-or!($a%3)){$a++}$a ``` Takes input `$args[0]`, adds `1`, saves into `$a`, starts a `for` loop. The conditional keeps the loop going while either `$a-match3` (regex match) `-or` `$a%3` is zero (the `!` of which is `1`). The loop simply increments `$a++`. At the end of the loop, we simply place `$a` on the pipeline, and output via implicit `Write-Output` happens at program completion. ### Examples ``` PS C:\Tools\Scripts\golfing> 1,2,11,22,29,33,102,251,254|%{"$_ --> "+(.\count-without-three.ps1 $_)} 1 --> 2 2 --> 4 11 --> 14 22 --> 25 29 --> 40 33 --> 40 102 --> 104 251 --> 254 254 --> 256 ``` [Answer] # R, 46 bytes ``` n=scan()+1;while(!n%%3|grepl(3,n))n=n+1;cat(n) ``` [Answer] # Haskell, ~~50~~ 48 bytes ``` f n=[x|x<-[n..],mod x 3>0,notElem '3'$show x]!!1 ``` [Try it on Ideone.](http://ideone.com/0NRlOh) Saved 2 bytes thanks to [@Charlie Harding](https://codegolf.stackexchange.com/users/15516/charlie-harding). Alternative: (50 bytes) ``` g=f.(+1) f n|mod n 3<1||(elem '3'.show)n=g n|1<3=n ``` [Answer] # [Labyrinth](http://github.com/mbuettner/labyrinth), 117 102 bytes ``` ? """""""""""_ ):_3 ( 0/{!@ ; %;:}_';:_3-_10 1 " 1 %;_ """"_""""""""{;;' ``` [Try it online!](http://labyrinth.tryitonline.net/#code=PyAgICAgICAiIiIiIiIiIiIiIl8KKTpfMyAgICAoICAgICAgICAgMC97IUAKOyAgJTs6fV8nOzpfMy1fMTAgMQoiICAxICAgICAgICAgICAgJTtfCiIiIiJfIiIiIiIiIiJ7Ozsn&input=Mjk5) Labyrinth is a two-dimensional, stack-based programming language and at junctions, direction is determined by the top of the stack (positive goes right, negative goes left, zero goes straight). There are two main loops in this programs. The first mods the integer input by 3 and increments if 0. The second repeatedly checks if the last digit is 3 (by subtracting 3 and modding by 10) and then dividing by 10 to get a new last digit. [Answer] # Lua, 58 Bytes ``` i=...+1while(i%3==0or(i..""):find"3")do i=i+1 end print(i) ``` [Answer] ## Pyke, 13 bytes ``` Whii3%!3`i`{| ``` [Try it here!](http://pyke.catbus.co.uk/?code=Whii3%25%213%60i%60%7B%7C&input=299&warnings=0) ``` - i = input W - do: hi - i += 1 i3%! - not (i % 3) | - ^ or V 3`i`{ - "3" in str(i) - while ^ ``` [Answer] # C#, ~~56~~, 51 bytes. This is surprisingly short for a C# answer! ``` x=>{while(++x%3<1|(x+"").Contains("3"));return x;}; ``` [Answer] # Pyth, 11 bytes ``` f&-I`T3%T3h ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=f%26-I%60T3%25T3h&input=29&test_suite_input=1%0A2%0A11%0A22%0A29%0A251&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=f%26-I%60T3%25T3h&input=29&test_suite=1&test_suite_input=1%0A2%0A11%0A22%0A29%0A251&debug=0) ### Explanation: ``` f&-I`T3%T3hQ implicit Q at the end f hQ find the smallest integer T >= input + 1 which fulfills: -I`T3 T is invariant under removing the digit 3 & and %T3 T mod 3 leaves a positive remainder ``` [Answer] # Excel, ~~79~~ 66 bytes It [Taylor Rained](https://codegolf.stackexchange.com/questions/98366/count-without-3/246608?noredirect=1#comment552856_246608) 13 bytes ``` =MIN(LET(r,ROW(A:A),FILTER(r,ISERR(FIND(3,r))*MOD(r,3)*(r>A1)>0))) ``` Input is in the cell `A1`. Output is wherever the formula is. The `LET()` function allows you to define variables for later reference so ti works in pairs of `variable,value`. The last argument is unpaired as it is the output. * `r,ROW(A:A)` creates an array of 1 to whatever the last row is. In the latest version of Excel, that's 1,048,576. * `g,FILTER(r,~*~*~>0)` takes that array and filters just for the values that aren't multiples of 3 and don't have a 3 in them. This done is by multiplying: + `ISERR(FIND(3,r))` which returns TRUE if if a 3 is *not* in the number and FALSE if it *is* + `MOD(r,3)` which returns 0 if it's a multiple of 3 and some positive integer if it isn't + `(r>A1)` creates an array of TRUE / FALSE where the first TRUE value will be the first term that's larger than the input. + When you do math on booleans, Excel uses TRUE=1 and FALSE=0 so the formula `~*~*~>0` only returns TRUE when the three pieces are TRUE (no 3 in number), some positive integer (not a multiple of 3), and TRUE (larger than the input). * `MIN(LET(~))` finds the smallest value in the filtered array which only includes the "without 3" numbers larger than the input so the first value in the array is the next value in the sequence. [![Screenshot](https://i.stack.imgur.com/Quvq3.png)](https://i.stack.imgur.com/Quvq3.png) [Answer] # [Python 3](https://docs.python.org/3/), 49 48 bytes -3 bytes thx to The Thonnu, I missed some spaces and swapping else x+1 and else-~x allowed another space to be taken out, not +2 bytes bc I didn't know I need to count f= on a recursive function, thx xnor :) seems clunky but i cant see more golfs, please lmk if you see something! ``` f=lambda x:f(x+1)if x%3>1or'3'in str(x+1)else-~x ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRocIqTaNC21AzM02hQtXYzjC/SN1YPTNPobikCCyemlOcqltX8b@gKDOvRCNNw1BTkwvGNkJiG6JIIMsYWSJzTIHq/gMA "Python 3 – Try It Online") [Answer] ## [GolfSharp](https://github.com/timopomer/GolfSharp), 43 bytes ``` m=>r(m,m).w(n=>n%3>0&!n.t().I("3")).a()[1]; ``` [Answer] # Ruby, 47 bytes ``` i=gets.to_i;i while(i+=1)%3==0||"#{i}"=~/3/;p i ``` I really feel like this can be golfed further. [Answer] # [MATL](http://github.com/lmendo/MATL), 14 bytes ``` `Qtt3\wV51-hA~ ``` [Try it online!](http://matl.tryitonline.net/#code=YFF0dDNcd1Y1MS1oQX4&input=Mjk) ### Explanation ``` ` % Do...while Q % Add 1. Takes input implicitly in the first iteration tt % Duplicate twice 3\ % Modulo 3 wV % Swap, string representation 51- % Subtract 51, which is ASCII for '3' h % Concatenate A~ % True if any result was 0. That indicates that the number % was a multiple of 3 or had some '3' digit; and thus a % new iteration is needed ``` [Answer] # PHP, ~~60~~ ~~55~~ ~~54~~ 46 bytes Thanks to @user59178 for shaving off a few bytes, @AlexHowansky for a byte, @Titus for another few bytes ``` for(;strstr($i=++$argv[1],51)|$i%3<1;);echo$i; ``` Called from command line with `-r`. Naive method that loops while the number is a multiple of 3, or has 3 in its digits. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` D;Æf3ḟµ‘#2ị ``` [Try it online!](https://tio.run/nexus/jelly#@@9ifbgtzfjhjvmHtj5qmKFs9HB39////40sAQ "Jelly – TIO Nexus") ### How it works ``` D;Æf3ḟµ‘#2ị Main link. Argument: n µ Combine the links to the left into a chain. ‘# Execute the chain for k = n, n + 1, n + 2, ... until n + 1 matches were found. Yield the array of all n + 1 matches. D Decimal; yield the array of k's decimal digits. Æf Yield the array of k's prime factors. ; Concatenate both. 3ḟ Filter false; remove digits and factors from [3]. This yields [3] (truthy) if neither digits nor factors contain 3, [] (falsy) if they do. 2ị Extract the second match. (The first match is n.) ``` [Answer] # PHP, ~~47~~ 41 bytes inspired by [Xanderhall](https://codegolf.stackexchange.com/a/98462#98462), but the latest idea finally justifies an own answer. ``` while(strstr($n+=$n=&$argn%3,51));echo$n; ``` or ``` while(strpbrk($n+=$n=&$argn%3,3));echo$n; ``` This takes advantage from the fact that the input is also from the sequence: For `$n%3==1`, the new modulo is `2`. For `$n%3==2`, the new modulo is `4-3=1`. `$n%3==0` never happens. Run as pipe with `-R` or [try them online](http://sandbox.onlinephpfunctions.com/code/c94a70661b4b1a7f28d583f01ce72ecc287cafe4). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ ~~28~~ ~~27~~ 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` 1∘+⍣{('3'∊⍕⍺)<×3|⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BRxwztR72LqzXUjdUfdXQ96p36qHeXps3h6cY1QEbt/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NwZArTcEIiA3BDBDLyBJEmBoCAA "APL (Dyalog Unicode) – Try It Online") -6 thanks to Adám. -8 thanks to ngn. Old Explanation: ``` 1-⍨g⍣((×3|⊢)>'3'∊⍕)∘(g←+∘1) +∘1 ⍝ curry + with 1, gives the increment function ⍝ increments the left argument so we do not return the number itself (g← ) ⍝ assign to "g" ∘ ⍝ compose g with the repeat ⍕ ⍝ does parsing the argument to a string... '3'∊ ⍝ ...contain '3'? 3|⊢ ⍝ residue of a division by 3 (× ) ⍝ direction (0 if 0, 1 if greater, ¯1 is lower) ( > ) ⍝ and not (we want the left side to be 1, the right side 0) g⍣ ⍝ repeat "g" (increment) until this function is true ^ 1-⍨ ⍝ afterwards, decrement: inversed - ``` # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~23~~ 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` 1∘+⍣(3(×⍤|>∊⍥⍕)⊣) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3/BRxwztR72LNYw1Dk9/1Lukxu5RR9ej3qWPeqdqPuparPk/7VHbhEe9fY/6pnr6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/T1Mw5EpTMAJiQzADxDKyBBGmhgA "APL (Dyalog Extended) – Try It Online") Thanks to Adám. -6 thanks to ngn. Old Explanation: ``` 0+⍣(3(×⍤|>∊⍥⍕)⊢)⍢(1+⊢)⊢ 0 ⍝ the left argument (⍺) +⍣(3(×⍤|>∊⍥⍕)⊢) ⍝ the left function (⍺⍺) (1+⊢) ⍝ the right function (⍵⍵) ⍝ (increments its argument) ⊢ ⍝ the right argument (⍵) ⍝ (just returns the input) ⍢ ⍝ under: ⍝ calls (⍵⍵ ⍵) first, which increments the input ⍝ also (⍵⍵ ⍺) which gives 1 ⍝ then calls (⍺incremented ⍺⍺ ⍵incremented) ⍝ afterwards, does the opposite of ⍵⍵, and decrements the result ⍣ ⍝ ⍣ fixpoint: repeats the left operation until the right side is truthy + ⍝ calls + with ⍺incremented and the input (so, 1+input) (3(×⍤|>∊⍥⍕)⊢) ⍝ right operation 3 ⍝ on its left, "3" ⊢ ⍝ on its right, the current iteration ×⍤| ⍝ divisibility check: × atop | | ⍝ starts with 3|⊢ (residue of ⊢/3) × ⍝ then returns the direction (0 if 0, 1 if greater, ¯1 is lower) ∊⍥⍕ ⍝ contains 3: ⍕ ⍝ stringifies both its arguments (3 and ⊢) ∊⍥ ⍝ checks for membership > ⍝ divisibility "and not" contains 3 ``` [Answer] # Turing Machine Code, 390 bytes ``` 0 * * r 0 0 _ _ l 1 1 1 2 l 2 1 2 3 r 0 1 3 4 l 2 1 4 5 l 2 1 5 6 l 2 1 6 7 l 2 1 7 8 l 2 1 8 9 l 2 1 9 0 l 1 1 * 1 l 2 2 * * l 2 2 _ _ r 3 3 1 1 r 4 3 4 4 r 4 3 7 7 r 4 3 2 2 r 5 3 5 5 r 5 3 8 8 r 5 3 _ _ l 1 4 1 1 r 5 4 4 4 r 5 4 7 7 r 5 4 2 2 r 3 4 5 5 r 3 4 8 8 r 3 5 1 1 r 3 5 4 4 r 3 5 7 7 r 3 5 2 2 r 4 5 5 5 r 4 5 8 8 r 4 * 0 0 r * * 6 6 r * * 9 9 r * * 3 3 r 0 * _ _ * halt ``` [Try it online.](http://morphett.info/turing/turing.html?9e662757c6f814b3ceb0464e715ec3ab) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~27 25~~ 24 bytes ``` {max $_+1...{!/3/&$_%3}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplqZg@786N7FCQSVe21BPT69aUd9YX00lXtW4tvZ/Wn6RgkZOZl5qsaZCNRdncWKlQpqGdq5@TIq2viZX7X8FBUMFXTsFBQUjLiCGME24FAwhooZAphFE1MgUyLQEM00MuIxMwQqMTE0A "Perl 6 – Try It Online") Finds the first number larger than the input that doesn't have a three and has a remainder when moduloed by 3. I was hoping to do something fancy with the condition, like `!/3/&*%3` but it doesn't work with the `!`. `:(` ### Explanation: ``` { } # Anonymous code block $_+1 # From the input+1 ... # Get the series { } # That ends when !/3/ # The number does not contain a 3 & # and $_%3 # The number is not divisible by 3 max # And get the last element of the series ``` [Answer] # APOL, 51 bytes `v(0 +(⧣ 1));w(|(!(%(⁰ 3)) c(t(⁰) '3')) ∆(0));-(⁰ 1)` [Answer] # Swift, 84 bytes ``` func f(_ n:Int)->Int{var n=n+1;while String(n).contains("3")||n%3==0{n+=1};return n} ``` ]
[Question] [ Since Halloween is coming up I thought I might start a fun little code golf challenge! The challenge is quite simple. You have to write a program that outputs either `trick` or `treat`. "The twist?" you may ask. Well let me explain: Your program has to do the following: * Be compilable/runnable in two different languages. Different versions of the same language don't count. * When you run the program in one language it should output `trick` and the other should output `treat`. The case is irrelevant and padding the string with whitespace characters are allowed (see examples). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the fewest bytes wins. A few explanations: **Valid outputs** (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!): ``` "trick" "Treat" " TReAt" " tRICk " ``` **Invalid outputs**: ``` "tri ck" "tr eat" "trck" ``` I'm interested to see what you can come up with! Happy Golfing! I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=97472,OVERRIDE_USER=23417;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=o.replace(TAGS_REG,"")),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,TAGS_REG = /(<([^>]+)>)/ig; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # VBScript, JScript, 41 bytes `x="treat" rem=x="trick" WScript.echo(x)` The VBScript "rem" hides the JScript code. [Answer] # Python 3 / JavaScript, 46 bytes There weren't any "true" Python/JavaScript polyglot answers yet, so I figured I'd try my hand at writing one: ``` a=1//2;alert=print alert(["trick","treat"][a]) ``` ### Python 3 This is how Python sees the code: ``` a=1//2;alert=print alert(["trick","treat"][a]) ``` `//` is integer division in Python 3, so `a=1//2;` sets variable `a` to `0`. Then `alert=print` sets the variable `alert` to the function `print` so that we can use `alert` to output. In the next line, `alert` is called on the item at index `a` in the array `["trick","treat"]`. Since `a` is `0` and `alert` is `print`, this prints `"trick"`. ### JavaScript This is how JS sees the code: ``` a=1//2;alert=print alert(["trick","treat"][a]) ``` The first line is parsed as `a=1`; the rest is simply a comment. This sets variable `a` to `1`. The second line, much like in Python, `alert`s the item at index `a` in `["trick","treat"]`. Since `a` is `1`, this alerts `"treat"`. [Answer] ## Perl / Ruby : 41 bytes ``` #line 9 print __LINE__==2?"treat":"trick" ``` Lines beginning with `#` are comments in both Ruby and Perl. Except that lines following (roughly) the regex `#\s*line\s+\d+` are executed by Perl's compiler and change the line number as the compiler sees it (see the doc : [Plain Old Comments (Not!)](http://perldoc.perl.org/perlsyn.html#Plain-Old-Comments-(Not!))). So when arriving to the second line, Perl thinks it the 9th while Ruby thinks it's the second. Hence Ruby will print `treat` while Perl will print `trick`. [Answer] # PHP, Lua 41 Bytes PHP print trick an Lua treat ``` --$a;echo"trick";/* print("treat") --*/ ``` [Answer] # JavaScript (ES6) / [Japt](https://github.com/ETHproductions/japt), ~~47~~ ~~33~~ 22 bytes ``` 1 alert`trick`;"treat" ``` ### JavaScript This should be fairly obvious: `1` and `"treat"` do nothing, and `alert`trick`` alerts `trick`. ### [Japt](http://ethproductions.github.io/japt/?v=master&code=MQphbGVydGB0cmlja2A7InRyZWF0Ig==&input=) In Japt, lowercase letters (except those in strings) transpile to method calls, e.g. `.a(`. However, if it comes after another lowercase letter, it is instead transpiled to `"a"`. All open parentheses are cut off at semicolons `;`. This means that the code roughly transpiles to: ``` 1 .a("l".e("r".t("trick")));"treat" ``` This is then evaluated as JavaScript. `"r".t("trick")` is `"r`", `"l".e("r")` is `"l"`, and `1.a("l")` is `1`. However, the poor JS engine's work is pointless: only the result of the last expression is sent to STDOUT, so the `1` is discarded and `treat` is printed. [Answer] # CJam / HTML, ~~17~~ 14 bytes Edit: * ***-3*** bytes off. Thanks to @ETHProductions Code: ``` TREAT<"trick" ``` # HTML: ``` TREAT<;"trick" TREAT print TREAT < tag open: ignore rest since there is no closing bracket ``` # CJam: ``` TREAT<;"trick" TREAT< e#random stuff / push vars ; e#discard stack "trick" e#literal trick e#implictly print ``` [Answer] # [///](https://esolangs.org/wiki////)/[D1ffe7e45e](https://esolangs.org/wiki/D1ffe7e45e), 59 bytes See what I did there? ``` /@//TREAT /37333120813633633333333363333336222222226// /$/__/ ``` Basically, in D1ffe7e45e / begins and ends comments. So, `TREAT` is in a comment but the source that prints `TRICK` isn't. The `__` is two no-ops to stop the D1ffe7e45e program from repeating. The source that /// interprets should be self-explanatory. [Answer] # [Emoji](https://esolangs.org/wiki/Emoji)/[Emojicode](http://www.emojicode.org/), 50 bytes ``` 👴💬trick💬➡ 🏁🍇😀🔤treat🔤🍉 ``` [Try Emoji online!](https://tio.run/##S83Nz8r8///D/IlbPsyftKakKDM5G8R4NG8h14f5/Y0f5ve2f5g/o@HD/ClLSopSE0tADKBg5///AA "Emoji – Try It Online") [Try Emojicode online!](https://tio.run/##S83Nz8pMzk9J/f//w/yJWz7Mn7SmpCgzORvEeDRvIdeH@f2NH@b3tn@YP6Phw/wpS0qKUhNLQAygYOf//wA "Emojicode – Try It Online") [Answer] # Julia/Python, 31 Bytes Nothing special, just taking advantage of the similarities between the languages. Julia uses 1 as the first index, while Python uses 0. ``` l=["trick","treat"] print(l[1]) ``` [Try it online - Julia!](https://tio.run/##yyrNyUw0/f8/xzZaqaQoMzlbSQdIpyaWKMVyFRRl5pVo5EQbxmr@/w8A "Julia 0.5 – Try It Online") [Try it online - Python!](https://tio.run/##K6gsycjPM/7/P8c2WqmkKDM5W0kHSKcmlijFchUUZeaVaOREG8Zq/v8PAA "Python 3 – Try It Online") [Answer] # Shakespeare Programming Language / Befunge-98, 467 ``` "kcirt"4k,@.Puck,.Page,.Act I:.Scene I:.[Enter Page and Puck]Page:You is the sum of a big big big big big big cat and the sum of a big big big big cat and a big big cat.Speak thy mind!You is the sum of you and a big pig.Speak thy mind!Puck:You is the sum of me and the sum of a big big big pig and the sum of a big big pig and a pig.Speak thy mind!You is the sum of you and a big big pig.Speak thy mind!Page:You is the sum of you and a big cat.Speak thy mind![Exeunt] ``` Try it online: [Shakespeare Programming Language](https://tio.run/##hZA9D4MgEIb/ytXZMHVysoNDNxOnxjhc8WoJBY1CUn89hSamX2gHErh7H@7JTcPNuURyMZpkL9OclZbLlJXYUcoO3MAxYxUnTeFSF9rQCKEJqFsI2Sa8slNvQUxgrgSTVdBfAOEsuujhaJ70ZngJ4XuFVQOh9OAMSuh29zt19pUXNojuGwnKEVtF20r@p/XA0sTYwH@Oa57xrX6ykZXUxZ2sNo1zDw "Shakespeare Programming Language – Try It Online") / [Befunge-98](https://tio.run/##hZA9D4IwEIb/ysmMnRyUSQcGNxMmQxiOctSmoRBoE/n1lZoQvwoOTdq79@k9uZJqqwVtD3vnIsVlb6Kdio/sYrmK2QUFxezEDZwTlnHS5C95qg314JuAugKfLfwrubYW5ADmRjDYBtoaEEopgoejedKr4TmE7xWWdYRqAkdopK42v1PHqfLCOim@Ea8csG1oXWn6aTkwNzE08J/jkmd4q59sYCV5eierTeHcAw "Befunge-98 – Try It Online") Befunge-98 prints `trick`, Shakespeare prints `TREAT`. **Explaination** Befunge executes until the `@`, so the SPL program is ignored. In SPL, everything until the first dot is ignored because it's the title. **Edit:** port the answer to the official SPL interpreter - I couldn't get it to work before. [Answer] # Scala / Javascript, 33 bytes ``` if(0==false)"trick"; else "treat" ``` `0==false` returns true in javascript, but false in scala [Answer] # Befunge-98/DOS .COM file, 27 bytes ``` 00000000 22 20 b4 09 ba 0b 01 cd 21 c3 20 74 72 65 61 74 |" ......!. treat| 00000010 24 6b 63 69 72 74 22 34 6b 2c 40 |$kcirt"4k,@| 0000001b ``` The Befunge-98 part pushes the characters of a string to the stack, and then outputs the top 5 characters in the stack and ends. The DOS part is: ``` 00000000 2220 and ah,[bx+si] 00000002 B409 mov ah,0x9 00000004 BA0B01 mov dx,0x10b 00000007 CD21 int 0x21 00000009 C3 ret ``` Where the first instruction is just some dummy non important instruction, and the rest calls INT 21h function 09h, which prints a $-terminated string pointed to by DS:DX. [Answer] ## [Charcoal](http://github.com/somebody1234/Charcoal) and [Pip](http://github.com/dloscutoff/pip), 13 bytes ``` trick©"treat" ``` ### Charcoal Charcoal's [code page](https://github.com/somebody1234/Charcoal/wiki/Code-page) reads this as `trick»"treat"`. `trick` prints the string to the canvas. `»` closes a block; apparently, if it is unmatched, it ends the program. The canvas is then printed to the screen. [Try it online](http://charcoal.tryitonline.net/#code=dHJpY2vCuyJ0cmVhdCI&input=) ### Pip ``` t Variable (no-op) r Generate random number (and do nothing with it) i Variable (no-op) c Variable (no-op) k Variable (no-op) © Unrecognized character, ignored "treat" String, output implicitly ``` [Try it online](http://pip.tryitonline.net/#code=dHJpY2vCqSJ0cmVhdCI&input=) [Answer] # C/Lua, 65 bytes ``` #include<stdio.h>/* print"trick"--[[*/ main(){puts("treat");}//]] ``` [Answer] # Ruby / ECMA6 27 bytes ``` {'t':'trick'}['t']||'treat' ``` Turns out you don't need to assign a JSON object in oredr to use it in ecma6 Original, with plain Javascript: # Ruby/Javscript ~~32~~ 31 bytes ``` a={'t':'trick'};a['t']||'treat' ``` Because ruby treats the key as as symbol (:t), does not match with 't' so goes to the or. Whereas JavaScript is not as fussy. [Answer] # Python/Brainf\*\*k (87 Bytes) ``` print("treat")#+++++++++[>+++++++++<-]>+++.--.<+++[>---<-]>.<++[>---<-]>.<++++[>++<-]>. ``` Python ignores everything after the `#` because its a comment and brainf\*\*k ignores `print("treat")#` because they are unrecognized characters. [Answer] # Forth/Perl, 53 bytes ``` 1 ?dup : print"trick" ." treat" ; print"trick" or bye ``` Needs a case-insensitive Forth (e.g: GNU Forth). When run in Forth, it defines a `print"trick"` word that outputs "treat", then calls it. When run in Perl, it uses the colon of Forth's word definition as part of a conditional statement. In `?dup`, the question mark forms part of the aforementioned conditional statement, and `dup` gets treated as a bareword (a string without quotes). The dot in Forth's `."` primitive gets interpreted as Perl's concatenation operator, and `bye` gets treated as another bareword. [Answer] # C / C++, 72 bytes ``` #include<stdio.h> main(){char*a[]={"trick","treat"};puts(a[1//**/2 ]);} ``` Compile with `gcc/g++ -ansi` and don't regard warnings. A C90-conforming C compiler does not recognize `//` as a comment but it skips `/**/`, leaving `puts(a[1/2]);`. C++ will see `puts(a[1]);`. [Answer] # Bash / Wolfram Language (a.k.a. Mathematica), 19 bytes ``` echo trick;#&@treat ``` For Bash, `#` is a comment indicator so it just outputs `trick`. Mathematica multiplies two undefined symbols `echo` and `trick` but ignores the result and proceeds to the second command, which fully expanded goes ``` (Function[Slot[1]])[treat] ``` and evaluates to `treat`. [Answer] # C / Javascript, ~~70~~ 47 bytes **(excluding comments C=22 + Javascript=14 ~= 36 )** ``` /**\ /main(){puts("trick");} //*/alert("treat") ``` What C sees: ``` main(){puts("trick");} ``` What javascript sees: ``` alert("treat") ``` Explanation: ``` /* C comment ends with '/' on next line but js comment remains open *\ / //BEGIN C Block #define function int //*/alert("this whole line is commented in C, but // is in the js comment") //for additional tricks... /*Most compilers can build K&R style C with parameters like this:*/ function volume(x,y,z)/**\ /int x,y,z;/**/ { return x*y*z; } /**\ / #undef function #define var const char** #define new (const char*[]) #define Array(...) {__VA_ARGS__} /**/ var cars = new Array("Ford", "Chevy", "Dodge"); /* Or a more readable version *\ /// BEGIN C Block #undef var #undef new /* END C Block */ ``` [Answer] # Windows Batch, JScript, 35 bytes `trick="treat";WScript. echo (trick)` The batch version displays the parentheses as delimiters. [Answer] # Ruby / Crystal, 31 bytes `puts 'a'=="a"&&"trick"||"treat"` `'a'` is a string literal in Ruby and a character literal in Crystal. `"a"` is a string literal in both. This abuses that difference to detect the language the script is ran in. [Answer] # Pyth and SMBF, 28 bytes ``` "trick"<.q<.q<.q<.q<.q"taert ``` "trick" explanation: > > Pyth has a `quit`-type operation with `.q`, which I use at `<.q` to end the program. Everything afterwards is uninterpreted, but in order for me to fix arity I need to add arity 0 data after each arity-2 `<`. Otherwise, the program requires user input (although what Python datum the input wouldn't matter, since it's not used). Pyth will implicitly print the "trick" at the beginning of the program. > > > "treat" explanation: > > The only characters that SMBF uses are as follows (the others are no-ops or not examined in memory): `"<.<.<.<.<.taert`. The `<.` sets print out the last five characters of the program in reverse order (hence `treat` is reversed into `taert` to have it print as `treat`). > > > [Answer] # [Actually](http://github.com/Mego/Seriously) and Python 2, 21 bytes *thanks to quartata for this solution* ``` print"trick"#X"treat" ``` Try it online: [Actually](http://actually.tryitonline.net/#code=cHJpbnQidHJpY2siI1gidHJlYXQi&input=), [Python 2](http://ideone.com/Wb145I) ## Explanations Actually: ``` print"trick"#X"treat" print 5 NOPs (they only do things if the stack isn't empty) "trick" push "trick" # listify X discard (stack is now empty) "treat" push "treat" (implicitly print) ``` Python 2: ``` print"trick"#X"treat" print"trick" # print "trick" #X"treat" # a comment ``` [Answer] # Windows Batch, VBScript, 34 bytes ``` trick="treat":WScript._ echo trick ``` The Batch `echo` will display the immediate text. The VBScript uses the "\_" line-continuation to run the "echo" command, which displays the contents of the variable "trick", which contains the string "treat". VBScript does not require parenthesis for functions which do not return a value. [Answer] # HTML / JavaScript (ES6), 28 bytes ``` trick<alert`treat`;var trick ``` [**Test HTML**](https://jsfiddle.net/d6nqg24c/) | [**Test JS**](https://jsfiddle.net/d6nqg24c/1/) ## Explanation HTML is a lot like ///: it writes out any plain text, ignoring anything after a `<` until it gets to a `>`. Since there are no `>`s, it just writes "trick". JS is simple: `alert`treat``. However, to avoid a ReferenceError for `trick` not being defined, we have to add a `var trick` to tell JS that `trick` is really supposed to be there. I wanted to add CSS that "prints" `or`, but it seems to be impossible: * If the CSS is before the `<`, it gets written to the HTML document. * If the CSS is after the `<`, it finds a syntax error and stops before running. [Answer] **Haskell / Ruby, 74 bytes** ``` --0;True=false main=if True then print "trick" else print "treat";--0;end ``` ***Haskell*** Anything starting with `--` is treated as a comment. Actual program in Haskell is now just ``` main=if True then print "trick" else print "treat"; ``` which prints "trick". ***Ruby*** --0 is just -(-0). So the first line declares a constant **True** with a value false. Next line does the actual printing and since **True** is false, it prints "treat". main is just treated as a variable in ruby and is assigned the value 0. [Answer] # sh / csh, 32 bytes ``` echo trick #treat|sed 's/.*#//' ``` For csh, the command must be executed interactively. Explanation: In interactive mode, sh treats anything starting with `#` as a comment. csh does so only in batch mode. ksh and bash behave the same way as sh. tcsh behaves like csh. Some of these shells have options to alter this behavior. zsh behaves like csh for this particular command. [Answer] # C / C++, 73 bytes ``` #include<stdio.h> int main(){puts("treat\0trick"+sizeof'1'/sizeof 1*6);} ``` This could fail (printing `trick` in both C and C++) on an implementation with `sizeof (int) == 1`, which implies `CHAR_BIT >= 16`. As far as I know there are no such implementations in the real world. Changing `int main()` to `int main(void)` would make it theoretically more conforming in C, but in practice all C and C++ compilers accept `int main()`. [Answer] # Labyrinth/Perl, 38 bytes As `cat -v`: ``` $_=116.114.105.99.107.$@^"^@^@^L^B^_";print ``` Where `^@` represents ASCII 0 (␀), `^B` represents ASCII 2 (␂), `^L` represents ASCII 12 (␌), and `^_` represents ASCII 31 (␟). Or, as a `hexdump -C`: ``` 00000000 24 5f 3d 31 31 36 2e 31 31 34 2e 31 30 35 2e 39 |$_=116.114.105.9| 00000010 39 2e 31 30 37 2e 24 40 5e 22 00 00 0c 02 1f 22 |9.107.$@^"....."| 00000020 3b 70 72 69 6e 74 |;print| 00000026 ``` I have wanted to post a Labyrinth/Perl answer since reading [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)'s [Labyrinth/><> answer](https://codegolf.stackexchange.com/a/97513/267). In that answer, Labyrinth code looks very much like it starts with a Perl [version string](http://perldoc.perl.org/perldata.html#Version-Strings). So, in this answer, Labyrinth just does the following: ``` $_= → dummy operations 116.114.105.99.107. → print string $ → dummy op @ → end ``` while Perl does: ``` $_= → set the $_ variable to: 116.114.105.99.107 → a version string for the other language .$@ → concatenated with $EVAL_ERROR (null when no eval error) ^"^@^@^L^B^_"; → XORed with "\0\0\x0c\2\x1F", to get "treat" from "trick" print → and finally print the string ``` --- # Labyrinth/Perl alternate version, 105 bytes Here is another version, modifying the string in Labyrinth code, instead of in Perl code: ``` ; $_=116.114.105.99.107.$@ ; ;print; 1+ 7+ 16 ; ;;;;;;;;;;;;; 1 ; ;; ;;;;;9^_9^10^00 ^a ``` Labyrinth code follows the path. The last line modifies the code, rotating columns using `^`. After the last line has been interpreted, the field looks like: ``` ; $_=116.114.101.97.116.$@ ; ; ; + + ; ;;;;;;;;;;;;;;1 ; ; ;;;;;9^_9^10^005^ 9 07 ``` After finishing interpreting the last line, Labyrinth follows the path upwards. Then, the 1 makes it attempt to turn rightwards, but hitting the wall makes it turn leftwards instead. Afterwards, Labyrinth just follows the path, eventually reaching code already explained for the first approach (where Perl modifies the string). As you'll notice, (in `9^_9^10^00 ^ 1`) numbers in Perl can have `_` in them, to make them more readable. --- # Labyrinth/Perl, linear labyrinth version, 76 bytes Not as fun as the previous one, but does the trick (or treat, as it may be): ``` 25^25^25^23^0;$;=116.114.105.99.107.$@ ; print$ ; ; 1+ 7+ 16 ; ``` --- # Labyrinth/Perl, boring version, 49 bytes Separate code paths for Labyrinth and Perl: ``` ;print 116.114.105.99.107 ; 116.114.101.97.116.$@ ``` ]
[Question] [ **This question already has answers here**: [Palindromic palindrome generator](/questions/47827/palindromic-palindrome-generator) (39 answers) Closed 7 years ago. Your task is to palindromize a string as follows: Take the string. ``` abcde ``` Reverse it. ``` edcba ``` Remove the first letter. ``` dcba ``` Glue it onto the original string. ``` abcdedcba ``` But here's the catch: since this challenge is about palindromes, **your code itself also has to be a palindrome.** Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # Python 3, 41 bytes ``` lambda t:t+t[-2::-1]#]1-::2-[t+t:t adbmal ``` [Try it here](https://goo.gl/6W6SZX). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 1 byte ``` û ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w7s&input=YWJjZGU) [Answer] # Dip, 1 byte ``` B ``` Body must be at least 30 characters; you entered 13. [Answer] # Pyth - 13 bytes It kinda looks like its crying. ``` +Qt_Q " Q_tQ+ ``` [Try it online here](http://pyth.herokuapp.com/?code=%2BQt_Q+%22+Q_tQ%2B&input=%22abcde%22&debug=0). [Answer] # [아희(Aheui)](http://esolangs.org/wiki/Aheui), ~~149~~ 137 bytes (47 chars + 2 newlines) ``` 붛뱐쎤붇쎡뻐처순의이멓희 빠본땨벌다따토먀의썩속썩의먀토따다벌땨본빠 희멓이의순처뻐쎡붇쎤뱐붛 ``` Due to the nature of the Aheui language, the input must end in a double quotation mark (") (gets ignored). [Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html) **Bonus (each line is palindromic)**, 131 bytes (42 chars + 5 newlines) ``` 밯빪반분반빪밯 쏜발뚝볃뚝발쏜 쏙툼닿뗘닿툼쏙 뽓첡순괆순첡뽓 숙쌱멈긕멈쌱숙 몋희익욥익희몋 ``` [Answer] # APL -- 13 bytes. ``` ⊣,¯1↓⌽⍝⌽↓1¯,⊣ ``` Explanation: ``` ⊣,¯1↓⌽ ⌽ Reverse the argument. ¯1↓ Drop the last character. ⊣, Concatenate the original to the result. ``` [Answer] ## JavaScript (ES6), ~~86~~ bytes ``` s=>s+[...s].reverse().slice(1).join("")//)""(nioj.)1(ecils.)(esrever.]s...[+s>=s ``` I tried a smarter solution but it's still longer :/ even abusing `[,...a]=s` didn't seem to save bytes [Answer] # J, 17 bytes ``` }:,|.NB. .BN.|,:} ``` Takes the easy way out by using a comment to mirror the code. In J, `NB.` starts a line comment. I do hope to find a method that doesn't involve a comment but the digrams in J probably do make it harder. Also forms two smileys, `}:` and `:}`. ## Usage ``` f =: }:,|.NB. .BN.|,:} f 'abcde' abcdedcba ``` ## Explanation Comment part removed since it is just filler. ``` }:,|. Input: string S |. Reverse S }: Curtail, get S with its last char removed , Join them and return ``` [Answer] # C#, (~~51~~ 50 + 1)\*2 = ~~104~~ 102 bytes saved 2 bytes to the use of `.Aggregate()` ``` s=>s+s.Aggregate("",(a,b)=>b+a,s=>s.Substring(1));//;))1(gnirtsbuS.s>=s,a+b>=)b,a(,""(etagerggA.s+s>=s ``` You can capture this lambda with ``` Func<string,string> f = <lambda here> ``` and call it like this ``` f("abcde") ``` [Answer] ## Ruby, 47 bytes ``` ->s{s+s.reverse[1..-1]}#}[1-..1]esrever.s+s{s>- ``` [Answer] # Mathematica, 67 bytes ``` f=#~Join~Rest@Reverse@#//Function;noitcnuF//#@esreveR@tseR~nioJ~#=f ``` Defines a named function `f` that takes a list of characters as input and returns the appropriate palindromized list as output. The bit after the semicolon (is fortunately syntactically valid and) gives a second, way more complicated name to this same function. It was fun trying to make Mathematica make sense without any brackets! [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 11 bytes ``` :Lc.r r.cL: ``` [Try it online!](http://brachylog.tryitonline.net/#code=OkxjLnIKci5jTDo&input=InRlc3Qi&args=Wg) ### Explanation ``` :Lc. Input concatenated with a string L results in the Output .r(.) The Output reversed is still the Output ``` The second line is a new predicate declaration that never gets called in that code. [Answer] # [Actually](http://github.com/Mego/Seriously), ~~14~~ 13 bytes ``` RiXßRkΣkRßXiR ``` [Try it online!](http://actually.tryitonline.net/#code=UmlYw59Sa86ja1LDn1hpUg&input=ImFiY2RlIg) **Explanation** ``` R # reverse input i # flatten X # discard top of stack ßR # push reversed input kΣ # concatenate each k # wrap in list R # reverse ß # push input X # discard it i # flatten list to string R # reverse string ``` [Answer] ## Pyke, 1 bytes ``` s ``` [Try it here!](http://pyke.catbus.co.uk/?code=s&input=test) Yes, this is the same builtin as the digital root one. This time it takes a sting and turns it into a palindrome. Added with [this commit](https://github.com/muddyfish/PYKE/commit/7e79dc95866b451ded61a07cb1da79cf1b1009fb) (actually on the same day as the digital root question) [Answer] # Java 7, 146 bytes (Enter is added for readibility and not part of the code.) ``` String c(String s){return s+new StringBuffer(s).reverse().substring(1);}/ /};)1(gnirtsbus.)(esrever.)s(reffuBgnirtS wen+s nruter{)s gnirtS(c gnirtS ``` [Answer] # Java 7, 152 bytes ``` String c(char[]s,int i){return s.length==i+1?s[i]+"":s[i]+c(s,++i)+s[i-1];}//};]1-i[s+)i++,s(c+]i[s:""+]i[s?1+i==htgnel.s nruter{)i tni,s][rahc(c gnirtS ``` [Answer] # PHP, 38+39=77 bytes ``` <?=($s=$argv[1]).substr(strrev($s),1);#;)1,)s$(verrts(rtsbus.)]1[vgra$=s$(=?< ``` stupid restriction ... for non-eso languages :) [Answer] # Haskell, ~~46~~ 44 bytes ``` p s=init s++reverse s--s esrever++s tini=s p ``` [Try it on Ideone.](http://ideone.com/VOY2MY) Saved 2 bytes thanks to Damien. Straight forward solution. `init` takes everything but the last character of a string (or last element of a list). `--` enables a single line comment. [Answer] # R, 107 bytes This is the boring solution which just uses comments to make it a palindrome. ``` cat(x<-scan(,""),rev(strsplit(x,"")[[1]])[-1],sep="")#)""=pes,]1-[)]]1[[)"",x(tilpsrts(ver,)"",(nacs-<x(tac ``` # R with few comments, 271 bytes While this code is longer, only 89 of the bytes (33%) are comments, rather than the 50% in the above code. R relies extensively on parentheses for function application, so this was rather difficult. ``` `%q%`=function (x,y)cat(x,y,sep=e)# `%p%`=function (x,y)`if`(length(y),rev(y)[-1],x)# x=strsplit(scan(,e<-""),e)[[1]]# n=NULL e%q%x%p%n n%p%x%q%e LLUN=n #]]1[[)e,)""-<e,(nacs(tilpsrts=x #)x,]1-[)y(ver,)y(htgnel(`fi`)y,x( noitcnuf=`%p%` #)e=pes,y,x(tac)y,x( noitcnuf=`%q%` ``` [Answer] # WinDbg, ~~142~~ 287 bytes ``` db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};r$t3=@$t1-1;.for(r$t1=@$t1-3;@$t1>=@$t0;r$t1=@$t1-1;r$t3=@$t3+1){m$t1 L1 $t3};eb$t3 0;da$t0;*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd ``` *+145 bytes to make it a palindrome, nearly missed that requirement...* Input is passed in via an address in psuedo-register `$t0`. For example: ``` eza 2000000 "abcde" * Write string "abcde" into memory at 0x02000000 r $t0 = 33554432 * Set $t0 = 0x02000000 * Edit: Something got messed up in my WinDB session, of course r $t0 = 2000000 should work * not that crazy 33554432. ``` This may be more golfable, for example I feel like there should be an easier way to convert a memory address in a register to the value at that address. It works by concatenating the chars from the second-to-last to the first to the end of the string. ``` db $t0 L1; * Set $p = memory-at($t0) .for (r $t1 = @$t0; @$p; r $t1 = @$t1 + 1) * Set $t1 = $t0 and increment until $p == 0 { db $t1 L1 * Set $p = memory-at($t1) }; r $t3 = @$t1 - 1; * Point $t3 at end of string * From the second-to-last char, reverse through the string with $t1 back to the start ($t0) * and continue to increment $t3 as chars are appended to the string. .for (r $t1 = @$t1 - 3; @$t1 >= @$t0; r $t1 = @$t1 - 1; r $t3 = @$t3 + 1) { m $t1 L1 $t3 * Copy char at $t1 to end of string ($t3) }; eb $t3 0; * Null terminate the new string da $t0; * Print the palindrome string * Comment of the previous code in reverse, making the whole thing a palindrome *;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd ``` Output: ``` 0:000> eza 2000000 "abcde" 0:000> r $t0 = 33554432 0:000> db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};r$t3=@$t1-1;.for(r$t1=@$t1-3;@$t1>=@$t0;r$t1=@$t1-1;r$t3=@$t3+1){m$t1 L1 $t3};eb$t3 0;da$t0;*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd 02000000 61 a 02000000 61 a 02000001 62 b 02000002 63 c 02000003 64 d 02000004 65 e 02000005 00 . 02000000 "abcdedcba" ``` [Answer] # C, 162 bytes ``` f(char*c,char*d){char*e=c;while(*d++=*c++);c-=2;d-=2;do{*d++=*c--;}while(e<=c);}//};)c=<e(elihw};--c*=++d*{od;2=-d;2=-c;)++c*=++d*(elihw;c=e*rahc{)d*rahc,c*rahc(f ``` Ungolfed, unpalindromized: ``` f(char* c,char* d){ char*e=c; while(*d++=*c++); c-=2;d-=2; do{*d++=*c--;}while(e<=c); } ``` `c` is is input string, assumes output string `d` has sufficient length. Usage: ``` int main() { char a[] = "abcde"; char* b=malloc(strlen(a)*2); f(a,b); printf("%s\n",b); } ``` [Answer] # Perl 5, 44 bytes 43 bytes, plus 1 for `-pe` instead of `-e` ``` s#(.*).#$&.reverse$1#e#1$esrever.&$#.)*.(#s ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 16 chars / 20 bytes ``` ï+ïĦ⬮Đ1//1Đ⬮Ħï+ï ``` `[Try it here (ES6 browsers only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=asdf&code=%C3%AF%2B%C3%AF%C4%A6%E2%AC%AE%C4%901%2F%2F1%C4%90%E2%AC%AE%C4%A6%C3%AF%2B%C3%AF)` Generated from the interpreter console using this: ``` c.value=`ï+ï${alias(String.prototype,'reverse')}⬮${alias(String.prototype,'slice')}1//1${alias(String.prototype,'slice')}⬮${alias(String.prototype,'reverse')}ï+ï` ``` ]
[Question] [ A string is *pairable* if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, `aabaaababbbaba` is pairable as: ``` aaba aaba b b ba ba ``` Given a non-empty string of `a`'s and `b`'s, output a Truthy value if it's pairable and a Falsey value if it isn't. **Pairable:** ``` aa abaaba bbababbb aabaaababbbaba babababa bbbbbbbbbbbb aaababbabbabbbababbaabaabaababaaba aaaabaab ``` **Not pairable:** ``` a ba baab abaabaaba bbbbbbbbbbbbbbb baababbabaaaab aaaaabbaaaaa ``` I encourage you to come up with non-regex-based solutions even when there's already a shorter regex answer in your language. You can mark them as "no regex". By regex, I mean a built-in string pattern matching subsystem. --- **Leaderboard:** ``` var QUESTION_ID=98252,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/98252/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] # Python 2, ~~68~~ 63 bytes ``` f=lambda s,n=1:s==2*s[:n]or''<s[n:]>-f(s,n+1)<f(s[n:])*f(s[:n]) ``` Returns *True* or *False*. Test it on [Ideone](http://ideone.com/WIiCZx). [Answer] # [Retina](http://github.com/mbuettner/retina), 11 bytes ``` ^((.+)\2)+$ ``` [Try all the test cases.](http://retina.tryitonline.net/#code=JWBeKCguKylcMikrJA&input=YWEKYWJhYWJhCmJiYWJhYmJiCmFhYmFhYWJhYmJiYWJhCmJhYmFiYWJhCmJiYmJiYmJiYmJiYgphYWFiYWJiYWJiYWJiYmFiYWJiYWFiYWFiYWFiYWJhYWJhCmEKYmEKYmFhYgphYmFhYmFhYmEKYmJiYmJiYmJiYmJiYmJiCmJhYWJhYmJhYmFhYWFiCmFhYWFhYmJhYWFhYQ) The first two bytes make it multi-line. Pretty literal interpretation of the rules, obviously uses regex, like all Retina programs will. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẆŒPẋ€€2F€ċ ``` Not exactly efficient... [Try it online!](http://jelly.tryitonline.net/#code=4bqGxZJQ4bqL4oKs4oKsMkbigqzEiwrhu7TDh-KCrMW84bu0S-KCrFk&input=&args=YWEKYWFiYgphYmFiCmEKYmEKYmFhYgpiYmJiYg) ### How it works ``` ẆŒPẋ€€2F€ċ Main link. Argument: s (string) Ẇ Window, generate the array of all substrings of s. ŒP Powerset; generate all subarrays of substrings of s. ẋ€€2 Repeat each substring in each subarray twice. For example, ["ab", "a", "b"] becomes ["abab", "aa", "bb"]. F€ Flatten the subarrays by concatenating their strings. ċ Count how many times s appears in the generated strings. ``` [Answer] ## Haskell, ~~72~~ 69 bytes (no regex) ``` g(a:b:c)|a==b=g c g x=x==[] any(g.words.concat).mapM(\c->[[c],c:" "]) ``` A brute-force approach. [Try it on Ideone](http://ideone.com/VqybtA). Thanks to BlackCap for -3 bytes. ## Explanation The helper function `g` takes a list of strings, and checks that it consists of pairs of identical strings, like `["aa","aa","bba","bba","ab","ab"]`. The (anonymous) main function splits a string in all possible ways, and checks that at least one splitting results in a list that `g` accepts. ``` g(a:b:c) g on list with elements a, b and tail c, |a==b in the case that a==b, =g c recurses to the tail c. g x= g on any other list x x==[] checks that x is empty. This includes the case where a is not equal to b, resulting in False. any(g.words.concat).mapM(\c->[[c],c:" "]) The main function: mapM(\c->[[c],c:" "]) Replace each letter c with either "c" or "c " in all possible ways, return list of results. any( ). Check that at least one result satisfies this: concat Concatenate the 1- or 2-letter strings, words. split again at each space, g. apply g. ``` [Answer] # Python 2, 60 bytes ``` f=lambda s,t='':''<s>f(s[1:],t+s[0])|f(t and s)*f(t)>-(s==t) ``` I hope this is correct. It runs pretty slowly and the `and` doesn't look optimal. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖµœs€2ZEµ€S ``` Two bytes longer than [my other answer](https://codegolf.stackexchange.com/a/98259/12012), but this approach is a lot more efficient and handles all but one of the test cases. [Try it online!](http://jelly.tryitonline.net/#code=xZLhuZbCtcWTc-KCrDJaRcK14oKsUwrhu7ThuaPigJzigJ3Dh-KCrOKCrEc&input=&args=YWEKYWJhYWJhCmJiYWJhYmJiCmFhYmFhYWJhYmJiYWJhCmJhYmFiYWJhCmJiYmJiYmJiYmJiYgoKYQpiYQpiYWFiCmFiYWFiYWFiYQpiYmJiYmJiYmJiYmJiYmIKYmFhYmFiYmFiYWFhYWIKYWFhYWFiYmFhYWFh&debug=on) ### How it works ``` ŒṖµœs€2ZEµ€S Main link. Argument: s (string) ŒṖ Generate all partitions of s. µ µ€ Map the monadic chain between the µ's over the partitions. œs€2 Split each string in the partition into two chunks of equal length. Z Zip/transpose, collecting the first halves in one array and the second halves in another. E Test the arrays of halves for equality. S Return the sum of the results, counting the number of different ways s can be paired. ``` [Answer] # Pyth - No Regex - ~~13~~ 12 bytes Checks if any of the partitions are made up of all string that are equals to each other when chopped in two. ``` sm.AqMcL2d./ ``` [Test Suite](http://pyth.herokuapp.com/?code=sm.AqMcL2d.%2F&test_suite=1&test_suite_input=%27aa%27%0A%27abaaba%27%0A%27bbababbb%27%0A%27aabaaababbbaba%27%0A%27babababa%27%0A%27bbbbbbbbbbbb%27%0A%27a%27%0A%27ba%27%0A%27baab%27%0A%27abaabaaba%27%0A%27bbbbbbbbbbbbbbb%27%0A%27baababbabaaaab%27%0A%27aaaaabbaaaaa%27&debug=0). [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 14 bytes (no regex) ``` lye~l:1j@2zcc? ``` [Try it online!](http://brachylog.tryitonline.net/#code=bHllfmw6MWpAMnpjYz8&input=ImFhYmFhYWJhYmJiYWJhIg) This is too slow for some of the test cases ### Explanation ``` ly The list [0, …, length(Input)] e~l A list whose length is an element of the previous list :1j Append itself to this list @2zc Split in half, zip and concatenate so that the list contains pairs of consecutive identical elements c? The concatenation of that list must result in the Input ``` [Answer] ## JavaScript (ES6), no regexp, ~~75~~ 74 bytes ``` f=s=>!s|[...s].some((_,i)=>i&&s[e='slice'](0,i)==s[e](i,i+=i)&&f(s[e](i))) ``` Returns `1` for pairable otherwise `0`. Edit: Saved 1 byte thanks to @edc65. [Answer] ## Python, 58 bytes ``` f=lambda s,p='':s>''and(f(p)>-(s==p)<f(s))|f(s[1:],p+s[0]) ``` This is based on the [Dennis's recursive method](https://codegolf.stackexchange.com/a/98260/20260). The Boolean negation trick is taken from there as well. The new idea is to recurse over partitions `(p,s)` of the original string by starting with `('',s)` and repeatedly moving the first character of `s` to be the last character of `p`. This allows for the parts to be referred to directly without string slicing. But, because the partition starts with `p` empty, we must be careful to avoid infinite loops of `f(s)` calling `f(s)`. [Answer] # JavaScript (ES6), 24 bytes ``` x=>/^((.+)\2)+$/.test(x) ``` Probably doesn't get shorter than this. [Answer] # PHP, 40 Bytes prints 0 for false and 1 for true ``` <?=preg_match("#^((.+)\\2)+$#",$argv[1]); ``` [Answer] # Python, ~~66~~ 64 bytes Thanks @Zgarb for -1 byte! ``` f=lambda x,s=1:x>x[:s]and(x==2*x[:s])|f(x[:s])&f(x[s:])|f(x,s+1) ``` Returns `True` or `False`. [Try it online!](https://repl.it/EQHk/3) Any help golfing this would be appreciated. [Answer] ## Racket 230 bytes ``` (let((sl string-length)(ss substring))(if(odd?(sl s))(printf ".~n")(begin(let p((s s))(if(equal? s "")(printf "!") (for((i(range 1(add1(/(sl s)2)))))(when(equal?(ss s 0 i)(ss s i(* 2 i)))(p(ss s(* 2 i)(sl s)))))))(printf ".~n")))) ``` Prints a '!' for each way in which the string is pairable. Prints a '.' at the end. Ungolfed: ``` (define (f s) (let ((sl string-length) ; create short names of built-in fns (ss substring)) (if (odd? (sl s)) (printf ".~n") ; odd length strings cannot be pairable; end here. (begin (let loop ((s s)) ; start testing here (if (equal? s "") (printf "!") ; if no remaining string, it must be pairable (for ((i (range 1 (add1 (/(sl s)2))))) ; ch lengths varying from 1 to half of string length (when (equal? (ss s 0 i) ; ch if substrings are same (ss s i (* 2 i))) (loop (ss s (* 2 i) (sl s) )))))) ; if yes, loop to check remaining string. (printf ".~n"))))) ; End of testing. ``` Testing: ``` (println "Following should be pairable") (f "bbaabbaa") ; should produce 2 '!' since 2 ways are possible. (f "aa") (f "abaaba") (f "bbababbb") (f "aabaaababbbaba") (f "babababa") ; should be pairable in 2 ways. (f "bbbbbbbbbbbb") ; should be pairable in many ways. (f "aaababbabbabbbababbaabaabaababaaba") (f "aaaabaab") (println "Following should be unpairable") ; (f "a") (f "ba") (f "baab") (f "abaabaaba") (f "bbbbbbbbbbbbbbb") (f "baababbabaaaab") (f "aaaaabbaaaaa") ``` Output: ``` "Following should be pairable" !!. !. !. !. !. !!. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. !. !. "Following should be unpairable" . . . . . . ``` [Answer] # Perl, 16 +2 = 18 bytes (with regex) Run with the `-nl` flags. `-E` is free. ``` say/^((.+)\2)+$/ ``` Run as: ``` perl -nlE 'say/^((.+)\2)+$/' ``` Returns a list of the capture groups (a truthy) if pairable, null string if not pairable. Explanation The `-nl` flags will run the code in a loop (`-n`), putting the input (with trailing newline removed because of `-l`) into the variable `$_` each time, then evaluating the code each time input is entered, until the program is manually terminated. The `-E` flag lets you evaluate code on the command line, and enables the `say` command. ``` say/^((.+)\2)+$/ /^((.+)\2)+$/ #The regex engine (.+)\2 #Find any set of at least one character, followed by itself ( )+ #Do this at least one time /^ $/ #Make sure that this matches the entire string from start to end say #Output the result of the regex ``` If a match is found (e.g. if the string is pairable), then the regex returns a list of the capture groups, which evaluates to a truthy, which is then passed to `say`, and output. If no match is found, then the regex returns the empty string, which evaluates to falsy, which is then passed to `say`, and output. Sample: ``` $ perl -nlE 'say/^((.+)\2)+$/' aaababbabbabbbababbaabaabaababaaba baababaababaaba #Truthy baababbabaaaab #Falsy bbababbb bbb #Truthy aabaaababbbaba bababa #Truthy abaabaaba #Falsy ``` [Answer] # GNU Prolog, ~~49~~ 46 bytes Probably works in other variants too, although they don't all represent strings the same way; GNU Prolog's representation is a useful one for this problem. It's unclear whether this counts as using regex or not. It's not using any regex-like feature, but the entire semantics of the language are similar to those of regex. New version (uses the recursion trick seen in some other answers): ``` s(X):-append(A,B,X),(A=B;A\=X,B\=X,s(A),s(B)). ``` Older version: ``` s(X):-X=[];append(A,B,X),B\=X,append(C,C,A),s(B). ``` This is a predicate (Prolog's equivalent of a function) called `s`, not a complete program. Use it like this: ``` | ?- s("aa"). true ? yes | ?- s("aaababbabbabbbababbaabaabaababaaba"). true ? yes | ?- s("baababbabaaaab"). no | ?- s("bbbbbbbbbbbbbbb"). no ``` An interesting feature of the older solution is that if you ask the interpreter "are there more solutions?" via use of `;` at the `true ?` prompt (rather than asking "is there any solution" via pressing return at the prompt, like I did above), it returns "true" a number of times equal to the number of different ways the string can be expressed in the given form (e.g. it returns "true" twice with `s("aaaa").`, as this can be parsed as `(a a)(a a)` or as `(aa aa)`). Prolog programs are often reversible (allowing `s` to *generate* a list of strings with the given property). The older one isn't (it goes into an infinite loop), but that's because of the golfed method I used to ensure that C is nonempty; if you rewrite the program to specify C as nonempty explicitly, it generates strings of the form "aa", "aabb", "aabbcc", and so on (Prolog being Prolog, it doesn't specify identities for the characters that make them up, just a specification of which characters are the same). The newer one generates strings of the form "aa", "abab", "abcabc", and so on; this is an infinite loop in its own right, and thus never hits the point at which it'd get stuck due to failing to detect a zero-length string. [Answer] ## Brainfuck, 177 bytes ``` +[<<<<,]>>>>[>+[>+[[>>]<+<[<<]>+>-]<[>+<-]>>>,>>[>>]+<<[<+>>-<-]<[>+<-]>>[,>[-<< <<]<[<<<<]>]<[[<<]>]>>]>>[[>+>>>]>>>[>]<<<<[>+[-<<<,<]<[<<<[[<<<<]>>]<]>]>>]<[[- >>>>]>>[<]<]<<]<. ``` Formatted: ``` +[<<<<,] >>>> [ >+ [ >+ [ [>>] <+<[<<] >+>- ] <[>+<-]> >>,>>[>>] +<<[<+> >-<-] <[>+<-]> > [ not equal ,>[-<<<<] <[<<<<] > ] < [ equal [<<] > ] >> ] >> [ mismatch [>+>>>] >>>[>] <<<< [ backtrack >+[-<<<,<] < [ not done yet <<< [ [<<<<] >> ] < ] > ] >> ] < [ match [->>>>] >>[<] < ] << ] <. ``` Expects input without a trailing newline. Prints `\x00` for false and `\x01` for true. [Try it online.](http://brainfuck.tryitonline.net/#code=K1s8PDw8LF0-Pj4-Wz4rWz4rW1s-Pl08KzxbPDxdPis-LV08Wz4rPC1dPj4-LD4-Wz4-XSs8PFs8Kz4-LTwtXTxbPis8LV0-PlssPlstPDw8PF08Wzw8PDxdPl08W1s8PF0-XT4-XT4-W1s-Kz4-Pl0-Pj5bPl08PDw8Wz4rWy08PDwsPF08Wzw8PFtbPDw8PF0-Pl08XT5dPj5dPFtbLT4-Pj5dPj5bPF08XTw8XTwu&input=YmFhYmFhYWE) This implements depth-first search. In particular: check for repeated prefixes of increasing length starting from the current suffix, then move to the next suffix if a match is found, otherwise backtrack. At the beginning, the string is reversed and a sentinel `\x01` is placed at the end. The tape is divided into 4-cell nodes. The memory layout of a node is: `c h x 0` where `c` is the character, `h` is a flag for whether the character is in the first half of a repeated prefix, and `x` is a flag to keep track of the current pair of characters being compared. The `h` flags stay in place while the `x` flags form a moving window. If the string is pairable, the pointer lands next to the sentinel at the end of the main loop; otherwise, the pointer falls off the left side of the string while backtracking. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ~c~jᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy65Luvh1gn//yslJiYlgnBSEhAnKgEA "Brachylog – Try It Online") Note that this algorithm can take a *very* long time, especially on falsey cases, since it checks every possible partition of the input string. ### Explanation ``` ~c Reversed concatenate: find a list that, when concatenated, results in the input string This examines all partitions of the input ~jᵐ Map reversed juxtapose: for each string in that list, is it the result of concatenating a string to itself? ``` For an input string like `"ababcc"`, `~c` tries different partitions until it comes to `["abab", "cc"]`, at which point `~j` succeeds for both items of the list, `ᵐ` outputs `["ab", "c"]`, and the predicate succeeds. [Answer] # [R](https://www.r-project.org/), 31 bytes ``` grepl("^((.+)\\2)+$",scan(,"")) ``` [Try it online!](https://tio.run/##VUzLCoAwDLv3M4qHjQ0Pfs8QUhEvIjL/n7muTrENfSbJpWx5PXfHs3Nj8ClNPgwcrwWHi8zeF4AgqCCRWkWEdIPN7Q7LSviCHobBlECHGaqUdKT38fNQG@k2QCO21haUGw "R – Try It Online") Based on Retina answer. # [R](https://www.r-project.org/), 129 bytes And here’s an original, non-regex answer: ``` o=(y=utf8ToInt(scan(,"")))<0;for(i in 2*1:(sum(y>0)/2))for(j in 1:(i/2)){w=i:(i-j+1);v=w-j;if(all(y[w]==y[v]))o[c(v,w)]=T};all(o) ``` [Try it online!](https://tio.run/##bYnLCsMgFER/JWR1b5vQJKtSe7vvPjtxoQFBSSPkoUjpt1ul2w4MM5yzpuQIIh27vo7uueywTXKBpq4R8d4x7VYwlVmq4dTfYDteEB8dXgbEYmwxmZsC3oFMvq0998g8hdYyo0HOM0QeBFHkXiA6PoFvAgoaP6xIh0kqJUt@o8rk/oPpCw "R – Try It Online") [Answer] # [Lithp](https://github.com/andrakis/node-lithp), 57 characters ``` #S::((? (!= (null) (match S "^((.+)\\2)+$")) true false)) ``` Sample usage: ``` % pairable_strings.lithp ( (def f #S::((? (!= (null) (match S "^((.+)\\2)+$")) true false))) (print (f "aa")) (print (f "aabaaababbbaba")) (print (f "aaababbabbabbbababbaabaabaababaaba")) (print (f "ba")) ) # ./run.js pairable_strings.lithp AtomValue { value: 2, type: 'Atom', name: 'true' } AtomValue { value: 2, type: 'Atom', name: 'true' } AtomValue { value: 2, type: 'Atom', name: 'true' } AtomValue { value: 3, type: 'Atom', name: 'false' } ``` ]
[Question] [ Using your language of choice, golf a [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29). > > A **quine** is a non-empty computer program which takes no input and produces a copy of its own source code as its only output. > > > No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either. No error quines -- there is already a [separate challenge](https://codegolf.stackexchange.com/questions/36260/make-an-error-quine) for error quines. Points for: * Smallest code (in bytes) * Most obfuscated/obscure solution * Using esoteric/obscure languages * Successfully using languages that are difficult to golf in The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat: ``` var QUESTION_ID=69; var OVERRIDE_USER=98; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,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:!0,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=!1;comment_page=1;getComments()}})} function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,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=(function(){var headerTag=String.raw `h\d` var score=String.raw `\-?\d+\.?\d*` var normalText=String.raw `[^\n<>]*` var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>` var noDigitText=String.raw `[^\n\d<>]*` var htmlTag=String.raw `<[^\n<>]+>` return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();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,})});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('<i>'+a.language+'</i>').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages) if(languages.hasOwnProperty(lang)) langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)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;float:left}#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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] ## Python 3, 34 Bytes ``` print((s:='print((s:=%r)%%s)')%s) ``` As far as I'm aware this is shorter than any other published Python 3 quine, mainly by virtue of having been written in the future with respect to most of them, so it can use `:=`. [Answer] # Befunge 98 - ~~17~~ 11 characters ``` <@,+1!',k9" ``` Or if using `g` is allowed: # Befunge 98 - ~~12~~ 10 ``` <@,g09,k8" ``` [Answer] # TECO, 20 bytes ``` <Tab>V27:^TJDV<Esc>V27:^TJDV ``` The `<Esc>` should be replaced with ASCII 0x1B, and the `<Tab>` with 0x09. * `<Tab>V27:^TJDV<Esc>` inserts the text `<Tab>V27:^TJDV`. This is *not* because there is a text insertion mode which TECO starts in by default. Instead, `<Tab>` *text* `<Esc>` is a special insertion command which inserts a tab, and then the text. A string whose own initial delimiter is part of the text -- very handy. * `V` prints the current line. * `27:^T` prints the character with ASCII code 27 without the usual conversion to a printable representation. * `J` jumps to the beginning of the text. * `D` deletes the first character (the tab). * `V` prints the line again. [Answer] # Python 2, 31 bytes ``` s="print's=%r;exec s'%s";exec s ``` It's 2 bytes longer than the [shortest Python quine on this question](https://codegolf.stackexchange.com/a/115/21487), but it's much more useful, since you don't need to write everything twice. For example, to print a program's own source code in sorted order, we can just do: ``` s="print''.join(sorted('s=%r;exec s'%s))";exec s ``` Another example by @feersum can be found [here](https://codegolf.stackexchange.com/a/47198/21487). ## Notes The reason the quine works is because of `%r`'s behaviour. With normal strings, `%r` puts single quotes around the string, e.g. ``` >>> print "%r"%"abc" 'abc' ``` But if you have a single quotes inside the string, it uses double quotes instead: ``` >>> print "%r"%"'abc'" "'abc'" ``` This does, however, mean that the quine has a bit of a problem if you want to use both types of quotes in the string. [Answer] # [RETURN](https://github.com/molarmanful/RETURN), 18 bytes ``` "34¤¤,,,,"34¤¤,,,, ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` First RETURN program on PPCG ever! RETURN is a language that tries to improve DUP by using nested stacks. # Explanation ``` "34¤¤,,,," Push this string to the stack 34 Push charcode of " to the stack ¤¤ Duplicate top 2 items ,,,, Output all 4 stack items from top to bottom ``` [Answer] # [Factor](http://factorcode.org) - ~~74~~ ~~69~~ 65 bytes Works on the listener (REPL): ``` USE: formatting [ "USE: formatting %u dup call" printf ] dup call ``` This is my first ever quine, ~~I'm sure there must be a shorter one!~~ Already shorter. Now I'm no longer sure... (bad pun attempt) What it does is: * `USE: formatting` import the `formatting` vocabulary to use `printf` * `[ "U... printf ]` create a quotation (or lambda, or block) on the top of the stack * `dup call` duplicate it, and call it The quotation takes the top of the stack and embeds it into the string as a literal. Thanks, cat! -> shaved ~~2~~ 4 more bytes :D [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), ~~2642~~ 2593 bytes **Credits to Rohan Jhunjhunwala for the algorithm.** ``` A = 99 set A 112 A + 1 set A 114 A + 1 set A 105 A + 1 set A 110 A + 1 set A 116 A + 1 set A 76 A + 1 set A 105 A + 1 set A 110 A + 1 set A 101 A + 1 set A 32 A + 1 set A 65 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 57 A + 1 set A 57 A + 1 set A 10 A + 1 set A 67 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 57 A + 1 set A 57 A + 1 set A 10 A + 1 set A 66 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 103 A + 1 set A 101 A + 1 set A 116 A + 1 set A 32 A + 1 set A 67 A + 1 set A 10 A + 1 set A 108 A + 1 set A 98 A + 1 set A 108 A + 1 set A 68 A + 1 set A 10 A + 1 set A 67 A + 1 set A 32 A + 1 set A 43 A + 1 set A 32 A + 1 set A 49 A + 1 set A 10 A + 1 set A 112 A + 1 set A 114 A + 1 set A 105 A + 1 set A 110 A + 1 set A 116 A + 1 set A 32 A + 1 set A 115 A + 1 set A 101 A + 1 set A 116 A + 1 set A 32 A + 1 set A 65 A + 1 set A 32 A + 1 set A 10 A + 1 set A 112 A + 1 set A 114 A + 1 set A 105 A + 1 set A 110 A + 1 set A 116 A + 1 set A 73 A + 1 set A 110 A + 1 set A 116 A + 1 set A 32 A + 1 set A 66 A + 1 set A 10 A + 1 set A 112 A + 1 set A 114 A + 1 set A 105 A + 1 set A 110 A + 1 set A 116 A + 1 set A 76 A + 1 set A 105 A + 1 set A 110 A + 1 set A 101 A + 1 set A 32 A + 1 set A 65 A + 1 set A 32 A + 1 set A 43 A + 1 set A 32 A + 1 set A 49 A + 1 set A 10 A + 1 set A 66 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 103 A + 1 set A 101 A + 1 set A 116 A + 1 set A 32 A + 1 set A 67 A + 1 set A 10 A + 1 set A 105 A + 1 set A 102 A + 1 set A 32 A + 1 set A 66 A + 1 set A 32 A + 1 set A 68 A + 1 set A 10 A + 1 set A 70 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 57 A + 1 set A 57 A + 1 set A 10 A + 1 set A 69 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 103 A + 1 set A 101 A + 1 set A 116 A + 1 set A 32 A + 1 set A 70 A + 1 set A 10 A + 1 set A 108 A + 1 set A 98 A + 1 set A 108 A + 1 set A 71 A + 1 set A 10 A + 1 set A 70 A + 1 set A 32 A + 1 set A 43 A + 1 set A 32 A + 1 set A 49 A + 1 set A 10 A + 1 set A 112 A + 1 set A 114 A + 1 set A 105 A + 1 set A 110 A + 1 set A 116 A + 1 set A 67 A + 1 set A 104 A + 1 set A 97 A + 1 set A 114 A + 1 set A 32 A + 1 set A 69 A + 1 set A 10 A + 1 set A 69 A + 1 set A 32 A + 1 set A 61 A + 1 set A 32 A + 1 set A 103 A + 1 set A 101 A + 1 set A 116 A + 1 set A 32 A + 1 set A 70 A + 1 set A 10 A + 1 set A 105 A + 1 set A 102 A + 1 set A 32 A + 1 set A 69 A + 1 set A 32 A + 1 set A 71 A + 1 printLine A = 99 C = 99 B = get C lblD C + 1 print set A printInt B printLine A + 1 B = get C if B D F = 99 E = get F lblG F + 1 printChar E E = get F if E G ``` [Try it online!](http://silos.tryitonline.net/#code=QSA9IDk5CnNldCBBIDExMgpBICsgMQpzZXQgQSAxMTQKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDExMApBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgNzYKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDExMApBICsgMQpzZXQgQSAxMDEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjUKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjcKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgMTAzCkEgKyAxCnNldCBBIDEwMQpBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgMTA4CkEgKyAxCnNldCBBIDk4CkEgKyAxCnNldCBBIDEwOApBICsgMQpzZXQgQSA2OApBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSA2NwpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0MwpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0OQpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSAxMTIKQSArIDEKc2V0IEEgMTE0CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDExNQpBICsgMQpzZXQgQSAxMDEKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDY1CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDEwCkEgKyAxCnNldCBBIDExMgpBICsgMQpzZXQgQSAxMTQKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDExMApBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgNzMKQSArIDEKc2V0IEEgMTEwCkEgKyAxCnNldCBBIDExNgpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA2NgpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSAxMTIKQSArIDEKc2V0IEEgMTE0CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDc2CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTAxCkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDY1CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDQzCkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDQ5CkEgKyAxCnNldCBBIDEwCkEgKyAxCnNldCBBIDY2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDYxCkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDEwMwpBICsgMQpzZXQgQSAxMDEKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDY3CkEgKyAxCnNldCBBIDEwCkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMDIKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjgKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNzAKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjkKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgMTAzCkEgKyAxCnNldCBBIDEwMQpBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNzAKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgMTA4CkEgKyAxCnNldCBBIDk4CkEgKyAxCnNldCBBIDEwOApBICsgMQpzZXQgQSA3MQpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSA3MApBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0MwpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0OQpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSAxMTIKQSArIDEKc2V0IEEgMTE0CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDY3CkEgKyAxCnNldCBBIDEwNApBICsgMQpzZXQgQSA5NwpBICsgMQpzZXQgQSAxMTQKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjkKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjkKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgMTAzCkEgKyAxCnNldCBBIDEwMQpBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNzAKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDEwMgpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA2OQpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA3MQpBICsgMQpwcmludExpbmUgQSA9IDk5CkMgPSA5OQpCID0gZ2V0IEMKbGJsRApDICsgMQpwcmludCBzZXQgQSAKcHJpbnRJbnQgQgpwcmludExpbmUgQSArIDEKQiA9IGdldCBDCmlmIEIgRApGID0gOTkKRSA9IGdldCBGCmxibEcKRiArIDEKcHJpbnRDaGFyIEUKRSA9IGdldCBGCmlmIEUgRw&input=) [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 3057 bytes ``` A = 99 def S set S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 76 A + 1 S A 105 A + 1 S A 110 A + 1 S A 101 A + 1 S A 32 A + 1 S A 65 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 57 A + 1 S A 57 A + 1 S A 10 A + 1 S A 72 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 56 A + 1 S A 51 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 32 A + 1 S A 100 A + 1 S A 101 A + 1 S A 102 A + 1 S A 32 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 67 A + 1 S A 104 A + 1 S A 97 A + 1 S A 114 A + 1 S A 32 A + 1 S A 72 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 76 A + 1 S A 105 A + 1 S A 110 A + 1 S A 101 A + 1 S A 32 A + 1 S A 32 A + 1 S A 83 A + 1 S A 32 A + 1 S A 10 A + 1 S A 67 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 57 A + 1 S A 57 A + 1 S A 10 A + 1 S A 66 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 103 A + 1 S A 101 A + 1 S A 116 A + 1 S A 32 A + 1 S A 67 A + 1 S A 10 A + 1 S A 108 A + 1 S A 98 A + 1 S A 108 A + 1 S A 68 A + 1 S A 10 A + 1 S A 67 A + 1 S A 32 A + 1 S A 43 A + 1 S A 32 A + 1 S A 49 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 67 A + 1 S A 104 A + 1 S A 97 A + 1 S A 114 A + 1 S A 32 A + 1 S A 72 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 32 A + 1 S A 32 A + 1 S A 65 A + 1 S A 32 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 73 A + 1 S A 110 A + 1 S A 116 A + 1 S A 32 A + 1 S A 66 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 76 A + 1 S A 105 A + 1 S A 110 A + 1 S A 101 A + 1 S A 32 A + 1 S A 65 A + 1 S A 32 A + 1 S A 43 A + 1 S A 32 A + 1 S A 49 A + 1 S A 10 A + 1 S A 66 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 103 A + 1 S A 101 A + 1 S A 116 A + 1 S A 32 A + 1 S A 67 A + 1 S A 10 A + 1 S A 105 A + 1 S A 102 A + 1 S A 32 A + 1 S A 66 A + 1 S A 32 A + 1 S A 68 A + 1 S A 10 A + 1 S A 70 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 57 A + 1 S A 57 A + 1 S A 10 A + 1 S A 69 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 103 A + 1 S A 101 A + 1 S A 116 A + 1 S A 32 A + 1 S A 70 A + 1 S A 10 A + 1 S A 108 A + 1 S A 98 A + 1 S A 108 A + 1 S A 71 A + 1 S A 10 A + 1 S A 70 A + 1 S A 32 A + 1 S A 43 A + 1 S A 32 A + 1 S A 49 A + 1 S A 10 A + 1 S A 112 A + 1 S A 114 A + 1 S A 105 A + 1 S A 110 A + 1 S A 116 A + 1 S A 67 A + 1 S A 104 A + 1 S A 97 A + 1 S A 114 A + 1 S A 32 A + 1 S A 69 A + 1 S A 10 A + 1 S A 69 A + 1 S A 32 A + 1 S A 61 A + 1 S A 32 A + 1 S A 103 A + 1 S A 101 A + 1 S A 116 A + 1 S A 32 A + 1 S A 70 A + 1 S A 10 A + 1 S A 105 A + 1 S A 102 A + 1 S A 32 A + 1 S A 69 A + 1 S A 32 A + 1 S A 71 A + 1 printLine A = 99 H = 83 print def printChar H printLine S C = 99 B = get C lblD C + 1 printChar H print A printInt B printLine A + 1 B = get C if B D F = 99 E = get F lblG F + 1 printChar E E = get F if E G ``` [Try it online!](http://silos.tryitonline.net/#code=QSA9IDk5CmRlZiBTIHNldCAKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3NgpBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA1NwpBICsgMQpTIEEgNTcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDYxCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNTYKQSArIDEKUyBBIDUxCkEgKyAxClMgQSAxMApBICsgMQpTIEEgMTEyCkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTAyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA2NwpBICsgMQpTIEEgMTA0CkEgKyAxClMgQSA5NwpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNzIKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMTIKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDExNgpBICsgMQpTIEEgNzYKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMDEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgODMKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjcKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDU3CkEgKyAxClMgQSA1NwpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDMKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMDgKQSArIDEKUyBBIDk4CkEgKyAxClMgQSAxMDgKQSArIDEKUyBBIDY4CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjcKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA0MwpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDQ5CkEgKyAxClMgQSAxMApBICsgMQpTIEEgMTEyCkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDY3CkEgKyAxClMgQSAxMDQKQSArIDEKUyBBIDk3CkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3MwpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2NgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3NgpBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNDMKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA0OQpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDMKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDEwMgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjgKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDYxCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNTcKQSArIDEKUyBBIDU3CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDEwMwpBICsgMQpTIEEgMTAxCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMTAKQSArIDEKUyBBIDEwOApBICsgMQpTIEEgOTgKQSArIDEKUyBBIDEwOApBICsgMQpTIEEgNzEKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDQzCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNDkKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMTIKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDExNgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwNApBICsgMQpTIEEgOTcKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY5CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDEwMwpBICsgMQpTIEEgMTAxCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMTAKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTAyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MQpBICsgMQpwcmludExpbmUgQSA9IDk5CkggPSA4MwpwcmludCBkZWYgCnByaW50Q2hhciBICnByaW50TGluZSAgUyAKQyA9IDk5CkIgPSBnZXQgQwpsYmxECkMgKyAxCnByaW50Q2hhciBICnByaW50ICBBIApwcmludEludCBCCnByaW50TGluZSBBICsgMQpCID0gZ2V0IEMKaWYgQiBECkYgPSA5OQpFID0gZ2V0IEYKbGJsRwpGICsgMQpwcmludENoYXIgRQpFID0gZ2V0IEYKaWYgRSBH&input=) I am ashamed to say this took me a while to write even though most of it was generated by another java program. Thanks to @MartinEnder for helping me out. This is the first quine I have ever written. **Credits go to Leaky Nun** for most of the code. I "borrowed his code" which was originally inspired by mine. My answer is similar to his, except it shows the "power" of the preprocessor. Hopefully this approach can be used to golf of bytes if done correctly. The goal was to prevent rewriting the word "set" 100's of times. **Please check out his [much shorter answer!](https://codegolf.stackexchange.com/a/91283/46918)** [Answer] # [ಠ\_ಠ](https://codegolf.meta.stackexchange.com/a/7390/41247), 6 bytes ``` ಠಠ ``` This used to work back when the interpreter was still buggy but that's fixed now. However, you can try it in the [legacy version of the interpreter](http://codepen.io/molarmanful/debug/rxJmqx)! [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` S+s"S+s" ``` [Try it online!](https://tio.run/##yygtzv7/P1i7WAmE//8HAA "Husk – Try It Online") Husk is a new golfing functional language created by me and [Zgarb](https://chat.stackexchange.com/users/136121). It is based on Haskell, but has an intelligent inferencer that can "guess" the intended meaning of functions used in a program based on their possible types. ### Explanation This is a quite simple program, composed by just three functions: `S` is the S combinator from [SKI (typed) combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus): it takes two functions and a third value as arguments and applies the first function to the value and to the second function applied to that value (in code: `S f g x = f x (g x)`). This gives us `+"S+s"(s"S+s")`. `s` stands for `show`, the Haskell function to convert something to a string: if show is applied to a string, special characters in the string are escaped and the whole string is wrapped in quotes. We get then `+"S+s""\"S+s\""`. Here, `+` is string concatenation; it could also be numeric addition, but types wouldn't match so the other meaning is chosen by the inferencer. Our result is then `"S+s\"S+s\""`, which is a string that gets printed simply as `S+s"S+s"`. [Answer] ## [Bash](https://www.gnu.org/software/bash/), 48 bytes ``` Q=\';q='echo "Q=\\$Q;q=$Q$q$Q;eval \$q"';eval $q ``` [Try it online!](https://tio.run/##S0oszvj/P9A2Rt260FY9NTkjX0EJyItRCQTyVQJVCoGM1LLEHIUYlUIldQhTpfD/fwA "Bash – Try It Online") [Answer] # [Reflections](https://thewastl.github.io/Reflections/), 1.81x10375 bytes Or to be more accurate, `1807915590203341844429305353197790696509566500122529684898152779329215808774024592945687846574319976372141486620602238832625691964826524660034959965005782214063519831844201877682465421716887160572269094496883424760144353885803319534697097696032244637060648462957246689017512125938853808231760363803562240582599050626092031434403199296384297989898483105306069435021718135129945` bytes. The relevant section of code is: ``` +#::(1 \/ \ /: 5;;\ >v\>:\/:4#+ +\ /+# / 2 /4):_ ~/ \ _ 2:#_/ \ _(5#\ v#_\ *(2 \;1^ ;;4) :54/ \/ \ 1^X \_/ ``` Where each line is preceeded by `451978897550835461107326338299447674127391625030632421224538194832303952193506148236421961643579994093035371655150559708156422991206631165008739991251445553515879957961050469420616355429221790143067273624220856190036088471450829883674274424008061159265162115739311672254378031484713452057940090950890560145649762656523007858600799824096074497474620776326517358755429533782443` spaces. The amount of spaces is a base 128 encoded version of the second part, with 0 printing all the spaces again. Edit: H.PWiz points out that the interpreter probably doesn't support this large an integer, so this is all theoretical ### How It Works: ``` +#::(1 Pushes the addition of the x,y coordinates (this is the extremely large number) Dupe the number a couple of times and push one of the copies to stack 1 \ > Pushes a space to stack 2 *(2 \/ / \ >v >:\ /+# / 2 Print space number times \ _ 2:#_/ # Pop the extra 0 \;1^ Switch to stack 1 and start the loop /:4#+ +\ /4):_ ~/ Divide the current number by 128 \ _(5#\ v Mod a copy by 128 ^ 4) : \_/ v#_\ If the number is not 0: ^ ;;4) :54/ Print the number and re-enter the loop /: 5;;\ v\ 4 If the number is 0: 4 Pop the excess 0 : \ And terminate if the divided number is 0 Otherwise return to the space printing loop \ 1^X ``` Conclusion: Can be golfed pretty easily, but maybe looking for a better encoding algorithm would be best. Unfortunately, there's basically no way to push an arbitrarily large number without going to that coordinate. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 1805 bytes ``` (())(()()()())(())(())(()()())(())(())(()()()())(())(())(()()()())(())(()()())(()())(()()())(())(()()()())(())(())(())(())(())(()())(()()()())(()())(()()())(())(()()()())(())(())(()()()())(())(()()())(()())(())(()()())(()()())(())(())(()()())(())(())(())(())(())(()()()())(())(())(()()())(())(())(())(()()())(()()())(()()()())(())(()()())(()())(())(()()())(())(())(())(())(())(()()())(()()()())(())(()())(())(()()())(()())(()()())(()()()())(())(()()())(())(())(())(())(()()())(()()()())(()())(())(()())(()()())(())(()())(()())(())(())(())(())(())(())(())(()())(())(()()())(())(())(()())(())(())(())(())(()()()())(()())(())(()()())(())(())(()()())(()())(())(()()())(()())(())(())(())(()())(())(())(()()())(()())(()())(()()()()())(()())(()())(()())(()()()())(())(())(()()())(())(())(()()())(()())(())(())(()()())(()())(()())(())(())(()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()()()())(())(()())(())(()()())(()())(()())(()()()())(()())(())(())(()())(()()()()())(()()())(())(()())(()())(())(())(())(()()())(())(())(()()()())(())(())(()()()())(())(()()())(()())(()()())(())(()()()())(())(())(()()()())(())(())(())(())(()())(()()()()())(())(())(()())(())(()()())(()())(()())(()())(())(()()()())(())(())(()())(())(()()())(()())(()()())(()()()())(())(()())(())(())(())(()()())(()()()()())(()())(()())(())(()()()())(())(())(())(()())(()()()()())(())(())(()())(())(()()())(())(())(()()())(())(())(()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()()())(()()()){<>(((((()()()()()){}){}){}())[()])<>(([{}])()<{({}())<>((({}())[()]))<>}<>{({}<>)<>}{}>)((){[()](<(({}()<(((()()()()()){})(({})({}){})<((([(({})())]({}({}){}(<>)))()){}())>)>))((){()(<{}>)}{}<{({}()<{}>)}>{}({}<{{}}>{})<>)>)}{}){{}({}<>)<>{(<()>)}}<>{({}<>)<>}{}}<> ``` [Try it online!](https://tio.run/##tVNJDsIwDLzzkvjQH0SReEfVQzkgIRAHrlbeHuwYVDWL4wrRhTrjZcYmubzW23O6PtZ7Ss4B0Cs3uO1trTXka9fZdea@yj7Gkq8x7xG9p3F/rajya1HSY2zV0CfaZhzXbk28RHpK@9pqT3um@r7S@u6zlPPZGFu4fZfbmMaTsFgjjZZuW5rqWYz/7X@eeG2nllqtvWtsx86QfnqsrEe7sa9/3VE95fmLPrh8bbIxykPm7GABjpgxLuTz6DKek7YIWkcf2OcD2xgDEyA7nZdIX5EwDk7Y2DsLAJRDCSKB6oGE00@gO9elCp45iOijSJYh53nEyCYpgRwDKDhrQ9LDaKGXjFNKaTq/AQ "Brain-Flak – Try It Online") *-188 bytes by avoiding code duplication* Like Wheat Wizard's answer, I encode every closing bracket as 1. The assignment of numbers to the four opening brackets is chosen to minimize the total length of the quine: ``` 2: ( - 63 instances 3: { - 41 instances 4: < - 24 instances 5: [ - 5 instances ``` The other major improvement over the old version is a shorter way to create the code points for the various bracket types. The decoder builds the entire quine on the second stack, from the middle outward. Closing brackets that have yet to be used are stored below a 0 on the second stack. Here is a full explanation of an earlier version of the decoder: ``` # For each number n from the encoder: { # Push () on second stack (with the opening bracket on top) <>(((((()()()()()){}){}){}())[()])<> # Store -n for later (([{}]) # n times {<({}()) # Replace ( with (() <>((({}())[()]))<> >}{} # Add 1 to -n ()) # If n was not 1: ((){[()]< # Add 1 to 1-n (({}())< # Using existing 40, push 0, 91, 60, 123, and 40 in that order on first stack <>(({})<(([(({})())]((()()()()()){})({}{}({})(<>)))({})()()())>) # Push 2-n again >) # Pop n-2 entries from stack {({}()<{}>)}{} # Get opening bracket and clear remaining generated brackets (({}<{{}}>{}) (< # Add 1 if n was 2; add 2 otherwise # This gives us the closing bracket ({}(){()(<{}>)} # Move second stack (down to the 0) to first stack temporarily and remove the zero <<>{({}<>)<>}{}> # Push closing bracket ) # Push 0 >) # Push opening bracket ) # Move values back to second stack <>{({}<>)<>} # Else (i.e., if n = 1): >}{}) { # Create temporary zero on first stack (<{}>) # Move second stack over <>{({}<>)<>} # Move 0 down one spot # If this would put 0 at the very bottom, just remove it {}({}{(<()>)}) # Move second stack values back <>{({}<>)<>}}{} } # Move to second stack for output <> ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") [@ngn's updated version](https://chat.stackexchange.com/transcript/message/48380903#48380903 "The APL Orchard") of the [classic APL quine](https://codegolf.stackexchange.com/a/70520/43319 "APL, 22 bytes – Alex A."), using a modern operator to save four bytes. ``` 1⌽,⍨9⍴'''1⌽,⍨9⍴''' ``` [Try APL!](https://tryapl.org/?a=1%u233D%2C%u23689%u2374%27%27%271%u233D%2C%u23689%u2374%27%27%27&run "tryapl.org/?a=1⌽,⍨9⍴'''1⌽,⍨9⍴'''") `'''1⌽,⍨9⍴'''` the characters `'1⌽,⍨9⍴'` `9⍴` cyclically **r**eshape to shape 9; `'1⌽,⍨9⍴''` `,⍨` concatenation selfie; `'1⌽,⍨9⍴'''1⌽,⍨9⍴''` `1⌽` cyclically rotate one character to the left; `1⌽,⍨9⍴'''1⌽,⍨9⍴'''` [Answer] # [Alchemist](https://github.com/bforte/Alchemist), ~~720 657 637~~ 589 bytes *-68 bytes thanks to Nitrodon!* ``` 0n0n->1032277495984410008473317482709082716834303381684254553200866249636990941488983666019900274253616457803823281618684411320510311142825913359041514338427283749993903272329405501755383456706244811330910671378512874952277131061822871205085764018650085866697830216n4+Out_"0n0n->"+Out_n4+nn+n0n 4n0+4n0+n->Out_"n" n+n+4n0+n0+n0+n0->Out_"+" n+n+n+4n0+n0+n0->Out_n 4n+4n0+n0->Out_"4" 4n+n+4n0->Out_"\"" 4n+n+n+n0+n0+n0->Out_"->" 4n+n+n+n+n0+n0->Out_"\n" 4n+4n+n0->Out_"Out_" 4n+4n+n->Out_"\\" nn->4n0+4n0+nnn n0+n4->n nnn+4n+4n+n4->nn+n00 nnn+0n4->n+n40 n40+0n00+n4->n4+nn n40+0n+n00->n4+n40 ``` [Try it online!](https://tio.run/##XZBZagMxEET/fYz5HQy9q/WTK@QChhCSQAyJHLBz/UxKM7KzwCzqV6Xukh7fnl5f3o/ny7JQo7a/Y1KRUqx6TTMmorSiysVSClXClyPVlFQTKxM3dxX4IsRqaNRK1dgya2pEEAOQFDg1OMxLkqaoYDtn9CmM/Y7JzGyS4pVVvZKxs2GMSZFUZKpVK/IVbK5G7sQFs5HGoxCmW6KVUmWKwlrSWbIfpZ@IFZRTQBjTKL2EEQI4ojvCRy2pJBzN5vvPy8O0Xci0FmCtzQA7azT3F9LqatMOwobGM5R5U35pm9B7DDacNnW0wkEO00Dtf1ckuil/hEObtsY/aP1c4dV2QCwUt3O0tus/299h0VZvt/e6t6IV0lqDojRCSWNLv5eBunkjRsvydfq4HE/tvOyfvwE "Alchemist – Try It Online") Warning, takes far longer than the lifetime of the universe to execute, mostly cause we have to transfer that rather large number on the first line back and forth between multiple atoms repeatedly. [Here's a version](https://tio.run/##tZBbbsMgEEX/vQz/WpYGDLb5yRa6gUhV1VZqpJZUSrr9umBIGj/APMZSHjDD3Ln3vHy@frx/nS7XYQAJsj5QThkF3vWE8o42HaMtFS0XXADrW9J0hHNBiGgBeN8z4K0ggjdENE3fENXnAJQy0lDJqqef63NpdMvxompSVqpQMAmV/qrW@EqWhWqYkv3YTmU6Dz3T0Bq2Zl@yUpfGoq0cS1uSc1Xl6N6ZNI6yNML/pfHnVrw9Oypb6nLPIWWh/1h9UAc5vtXP9V1LwViE8a6q6spAXcGOaC62pB@bCoNBDwkwY@pIQI8UcDvpN/VBn5kRNc8nA48j06Hl2GxwOjofXhtfCMwlliLrMitCS6k1MZfcquCa5LqoW9YhvC7tEvfJOxe4VriX@Nd4FrlX@ZZtrfMu9K30L91eu7HYv3precj6TQNbFrZNhNkIMLJtJcRMqJ0gQyGWwkyF2wo0FmYt1FyMvWCDoRbDTcbZjDAabjXGbKzdKMMxluNMx9uONB5nPdZ8iv3oALER4kOkxUgIEh8lJUxqnKRAKZHSQqXHSgyWFi01XE685ICpEdND5sXMCJoeNSdsbtyswDmR80Lnx84Mnhc9NzxG/GwAuQjyIeBgQACRjwIDBhYOFCAYSHCg4GFBAoODBgsOJh40QFiI8CDhYkIEhYcKExY2LlRgmMhwoeFjQwaHiw4b3h740AFiI8SHuA/GHUDio9wD5h3n8Hv@vp7O8jLUb38) that outputs the first few lines in a reasonable amount of time. [Here is the encoder](https://tio.run/##ZZHtboIwFIb/cxWkIwukgv3RLJlmhDvYBagxbrLEDQoBNSxEb52957SizgROe57z9ny0dd4UL8NQ/vpBWxya2n/zeZ17HljWwV8IIya@kGQUGU1mKcjGKe9Z8H7Yr9lbihWOP/HhrEvaqtmHfWzzJ59V@REG6@gUQdNuqEZSowl7Ik2T515oI0UXBlL6293R19FZjKCstgy0UYTCrIulDKKr8B5f5MbEKfXXh2fU5oIncUI1dECVqZHbBqdZN42S72pn3EUUmOVRUG7qsMcAX7um3WOqyewHgyVNfsybNp/bvBlmo3X2usiK1XwYjJZ8V8ootCXYATNGAng0Gf2uY1y@h4BF7nMRaSM3MRugHI45pRaEGDqC57PI/M@KjsbIXQCvbBNfEZsLvMiWaAvOOIcxHi06TrExrCU5@ZRKMVTsg8LVCq5yR@heHCKxJVr9AQ) that turns the program into the data section Everything but the large number on the first line is encoded using these ~~8~~ 9 tokens: ``` 0 n + -> " \n Out_ \ 4 ``` That's why all the atom names are composed of just `n`,`0` and `4`. As a bonus, this is now fully deterministic in what order the rules are executed. ### Explanation: ``` Initialise the program 0n0n-> If no n0n atom (note we can't use _-> since _ isn't a token) n4+Out_"0n0n->"+Out_n4+nn4+n0n NUMn4 Create a really large number of n4 atoms +Out_"0n0n->" Print the leading "0n0n->" +Out_n4 Print the really large number +nn Set the nn flag to start getting the next character +n0n And prevent this rule from being called again Divmod the number by 9 (nn and nnn flag) nn->4n0+4n0+nnn Convert the nn flag to 8 n0 atoms and the nnn flag n0+n4->n Convert n4+n0 atoms to an n atom nnn+4n+4n+n4->nn+n00 When we're out of n0 atoms, move back to the nn flag And increment the number of n00 atoms nnn+0n4->n+n40 When we're out of n4 atoms, add another n atom and set the n40 flag Convert the 9 possible states of the n0 and n atoms to a token and output it (nn flag) n+4n0+4n0->Out_"n" 1n+8n0 -> 'n' n+n+4n0+n0+n0+n0->Out_"+" 2n+7n0 -> '+' n+n+n+4n0+n0+n0->Out_n 3n+6n0 -> '0' 4n+4n0+n0->Out_"4" 4n+5n0 -> '4' 4n+n+4n0->Out_"\"" 5n+4n0 -> '"' 4n+n+n+n0+n0+n0->Out_"->" 6n+3n0 -> '->' 4n+n+n+n+n0+n0->Out_"\n" 7n+2n0 -> '\n' 4n+4n+n0->Out_"Out_" 8n+1n0 -> 'Out_' 4n+4n+n->Out_"\\" 9n+0n0 -> '\' Reset (n40 flag) n40+0nn+n00->n4+n40 Convert all the n00 atoms back to n4 atoms n40+0n00+n4->n4+nn Once we're out of n00 atoms set the nn flag to start the divmod ``` [Answer] # [Brian & Chuck](https://github.com/m-ender/brian-chuck), ~~211 143 138 133 129 98 86~~ 84 bytes ``` ?.21@@/BC1@c/@/C1112BC1BB/@c22B2%C@!{<? !.>.._{<+>>-?>.---?+<+_{<-?>+<<-.+?ÿ ``` [Try it online!](https://tio.run/##SyrKTMzTTc4oTc7@/9@ekVHPyNDBQd/J2dChPlnfQd/Z0NDQCMhzctIHChgZORmp8jk71CsyV9vYcynq2enpxVfbaNvZ6drb6enq6tpr22gDBYA8bRsbXT1t@8P7//8HAA "Brian & Chuck – Try It Online") old version: ``` ?{<^?_>{_;?_,<_-+_;._;}_^-_;{_^?_z<_>>_->_->_*}_-<_^._=+_->_->_->_-!_ ?_;}_^_}<? !.>.>.>.+>._<.}+>.>.>?<{?_{<-_}<.<+.<-?<{??`?= ``` [Try it online!](https://tio.run/##LYuxDsJADEPVEf6iKyH5gXOTPzkDXUBIDEgsRPftR3tC9uJn@/Z@XF@63j/rs/dI1KAnS/AMqrAYS2NVluRWfUF36vCpUcFqXORPds88xLhMExviOJsPiRthTUYKZDCh28IgBt1BXGLp/Qc "Brian & Chuck – Try It Online") New code. Now the data isn't split into nul separated chunks, but the nul will be pulled through the data. ``` Brian: ? start Chuck .21@@/BC1@c/@/C1112BC1BB/@c22B2%C@! data. This is basically the end of the Brian code and the Chuck code reversed and incremented by four. This must be done because the interpreter tries to run the data, so it must not contain runnable characters ASCII 3 for marking the end of the code section {<? loop the current code portion of Chuck Chuck: code 1 (print start of Brian code) .>.. print the first 3 characters of Brian code 2 (print the data section) {<+>>- increment char left to null and decrement symbol right to null for the first char, this increments the question mark and decrements the ASCII 1. So the question mark can be reused in the end of the Chuck code ?>. if it became nul then print the next character ---?+<+ if the character is ASCII 3, then the data section is printed. set it 1, and set the next char to the left 1, too code 3 (extract code from data) {<- decrement the symbol left to the nul ?>+<<-. if it became nul then it is the new code section marker, so set the old one 1 and print the next character to the left +? if all data was processed, then the pointer can't go further to the left so the char 255 is printed. If you add 1, it will be null and the code ends. ÿ ASCII 255 that is printed when the end of the data is reached ``` [Answer] # [Klein](https://github.com/Wheatwizard/Klein), 330 bytes ``` "![ .; =90*/[ .9(#; =[>[. >1# 98='9[ '7[.>; [*; ) =#0,*[ =.>9(. =*(#(#([ .0#8;#(#; [*9>[; => [*? [9(;;"\ / < >:1+0\ /:)$< >\?\ / ?2 $ :9>(:\ (8\/?< \+ < * >$1-+\ >/?:) / >+)$)$)\ /1$9<$)$< \+:?\< >?!\+@ \:)<< ``` [Try it online!](https://tio.run/##vc5NbgMhDAXgtX0JSEAKAw0w3XT4GdOew952UbXK/XeEXKJ@qyc9ffLv3/fPY87rhSE2OEv2iUHF4sxqTKwi0K4MlOO8FYbbB0dqwF41UBuo0@Q3z3BGKm5N1emdWVlYNkczL4V9IV4YafYDuLjWroIJ/vU6Ut1DFtSpbnY1GaITjndtsRZyVdAdkkZHCbqj9qjJ7vcgSGnUbU01hc2urNd3W7p9KRLqkIWNi4RPlLr1jnPOPed5/3oC "Klein – Try It Online") This works in all topologies, mostly by completely avoiding wrapping. The first list encodes the rest of the program offset by one, so newlines are the unprintable (11). [Answer] # [ed(1)](https://kidneybone.com/c2/wiki/EdIsTheStandardTextEditor), 45 bytes We have quines for `TECO`, `Vim`, and `sed`, but not the almighty `ed`?! This travesty shall not stand. (NB: See also, this [error quine](https://codegolf.stackexchange.com/a/36286/15940) for `ed`) [Try it Online!](https://tio.run/##S035/z@RK5FLh0unxJBLRdekWF9HX0@fS6eAK5BLD4vg//8A) ``` a a , ,t1 $-4s/,/./ ,p Q . ,t1 $-4s/,/./ ,p Q ``` Stolen from [here](https://github.com/tpenguinltg/ed1-quine/blob/master/quine.ed). It should be saved as a file `quine.ed` then run as follows: (TIO seems to work a bit differently) ``` $ ed < quine.ed ``` [Answer] # [Grok](https://github.com/AMiller42/Grok-Language), 42 bytes ``` iIilWY!}I96PWwI10WwwwIkWwwwIhWq`` k h ``` [Try it Online!](http://grok.pythonanywhere.com?flags=&code=iIilWY!%7DI96PWwI10WwwwIkWwwwIhWq%60%60%0A%20%20%20k%20%20%20h&inputs=) It is very costly to output anything in Grok it seems. [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), ~~1128~~ ~~1116~~ ~~1069~~ ~~960~~ ~~877~~ ~~844~~ ~~540~~ ~~477~~ ~~407~~ ~~383~~ 33 bytes **Edit**: Woah... -304 B with space **Edit 2**: Bruh. **Edit 3**: Thanks Jo King for the idea! I outgolfed ya! A stack-based language(The first on TIO's list!) It's a big pile of unprintables though ``` N0N (!&+$*)^(!&@^)! ``` (Spaces are `NUL` bytes) [Try it online!](https://tio.run/##S03OSylITkzMKcop@P9f0s9ATFDCT1JKRJoByGAQ0FBUE9BW0dKMAzIc4jQV//8HAA) Here's the code, but in Control Pictures form: ``` ␙N0␖␑␘N␙␚␔␛␀␖␑␘␀␐(!&␐+$*)^(!&@^)! ``` ## Explanation ``` ␙N0␖␑␘N␙␚␔␛␀␖␑␘␀␐ Data (!&␐+$*) Push the stack, reversed and +16 back on top ^(!&@^)! Print everything reversed, including the length (Hence the final `!`) ``` It does error on overflow though... [Answer] # Commodore Basic, ~~54~~ 41 characters ``` 1R─A$:?A$C|(34)A$:D♠"1R─A$:?A$C|(34)A$:D♠ ``` Based on DLosc's QBasic quine, but modified to take advantage of Commodore Basic's shortcut forms. In particular, the shorter version of `CHR$(34)` makes using it directly for quotation marks more efficient than defining it as a variable. As usual, I've made substitutions for PETSCII characters that don't appear in Unicode: `♠` = `SHIFT+A`, `─` = `SHIFT+E`, `|` = `SHIFT+H`. **Edit:** You know what? If a string literal ends at the end of a line, the Commodore Basic interpreter will let you leave out the trailing quotation mark. Golfed off 13 characters. Alternatively, if you want to skirt the spirit of the rules, ``` 1 LIST ``` `LIST` is an instruction that prints the current program's code. It is intended for use in immediate mode, but like all immediate-mode commands, it can be used in a program (eg. `1 NEW` is a self-deleting program). Nothing shorter is possible: dropped spaces or abbreviated forms get expanded by the interpreter and displayed at full length. [Answer] # Jolf, 4 bytes ``` Q«Q« Q double (string) « begin matched string Q« capture that ``` This transpiles to `square(`Q«`)` (I accidentally did string doubling in the `square` function), which evaluates to `Q«Q«`. Note that `q` is the quining function in Jolf, *not* `Q` ;). [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), ~~11~~ ~~9~~ ~~8~~ 6 Bytes This programming language was obviously made past the date of release for this question, but I thought I'd post an answer so I can a) get more used to it and b) figure out what else needed to be implemented. ``` 'rd3*Z ``` The explanation is as follows: ``` 'rd3*Z ' Start recording as a string. (wraps around once, capturing all the items) ' Stop recording as a string. We now have everything recorded but the original ". r Reverse the stack b3* This equates the number 39 = 13*3 (in ASCII, ') Z Output the entire stack. ``` [Answer] # Fuzzy Octo Guacamole, 4 bytes ``` _UNK ``` I am not kidding. Due to a suggestion by @ConorO'Brien, `K` prints `_UNK`. The `_UN` does nothing really, but actually sets the temp var to `0`, pushes `0`, and pushes `None`. The `K` prints "\_UNK", and that is our quine. [Answer] # C++, ~~286~~ ~~284~~ 236 bytes Now with extra golf! ``` #include<iostream> int main(){char a[]="#include<iostream>%sint main(){char a[]=%s%s%s,b[]=%s%s%s%s,c[]=%s%sn%s,d[]=%s%s%s%s;printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}",b[]="\"",c[]="\n",d[]="\\";printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);} ``` I'm currently learning C++, and thought "Hey, I should make a quine in it to see how much I know!" 40 minutes later, I have this, a full ~~64~~ **114** bytes shorter than [the current one](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/2431#2431). I compiled it as: ``` g++ quine.cpp ``` Output and running: ``` C:\Users\Conor O'Brien\Documents\Programming\cpp λ g++ quine.cpp & a #include<iostream> int main(){char a[]="#include<iostream>%sint main(){char a[]=%s%s%s,b[]=%s%s%s%s,c[]=%s%sn%s,d[]=%s%s%s%s;printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}",b[]="\"",c[]="\n",d[]="\\";printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);} ``` [Answer] # [Cheddar](https://github.com/cheddar-lang/Cheddar), 56 bytes ``` var a='var a=%s;print a%@"39+a+@"39';print a%@"39+a+@"39 ``` [**Try it online!**](http://cheddar.tryitonline.net/#code=dmFyIGE9J3ZhciBhPSVzO3ByaW50IGElQCIzOSthK0AiMzknO3ByaW50IGElQCIzOSthK0AiMzk&input=) I felt like trying to make something in Cheddar today, and this is what appeared... [Answer] # 05AB1E, ~~16~~ 17 bytes ``` "34çs«DJ"34çs«DJ ``` With trailing newline. [Try it online!](http://05ab1e.tryitonline.net/#code=IjM0w6dzwqtESiIzNMOnc8KrREoK&input=) **Explanation:** ``` "34çs«DJ" # push string 34ç # push " s« # swap and concatenate DJ # duplicate and concatenate ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes *Thanks to @Oliver for a correction (trailing newline)* ``` "D34ç.øsJ"D34ç.øsJ ``` There is a trailing newline. [Try it online!](http://05ab1e.tryitonline.net/#code=IkQzNMOnLsO4c0oiRDM0w6cuw7hzSgo&input=) ``` "D34ç.øsJ" Push this string D Duplicate 34 Push 34 (ASCII for double quote mark) ç Convert to char .ø Surround the string with quotes s Swap J Join. Implicitly display ``` [Answer] # Clojure, 91 bytes ``` ((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x))))) ``` [Answer] # Mathematica, 68 bytes ``` Print[#<>ToString[#,InputForm]]&@"Print[#<>ToString[#,InputForm]]&@" ``` ]
[Question] []
[Question] [ Given an array of any depth, draw its contents with borders of `+-|` around each subarray. Those are the ASCII characters for plus, minus, and vertical pipe. For example, if the array is `[1, 2, 3]`, draw ``` +-----+ |1 2 3| +-----+ ``` For a nested array such as `[[1, 2, 3], [4, 5], [6, 7, 8]]`, draw ``` +-----------------+ |+-----+---+-----+| ||1 2 3|4 5|6 7 8|| |+-----+---+-----+| +-----------------+ ``` For a ragged array such as `[[[1, 2, 3], [4, 5]], [6, 7, 8]]`, draw ``` +-------------------+ |+-----------+-----+| ||+-----+---+|6 7 8|| |||1 2 3|4 5|| || ||+-----+---+| || |+-----------+-----+| +-------------------+ ``` Notice that there is more space after drawing `[6, 7, 8]`. You may either draw the contents on the top-most, center, or bottom-most line, but whichever you choose, you must remain consistent. This challenge was inspired by the [box](http://www.jsoftware.com/help/dictionary/d010.htm) verb `<` from J. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. * Builtins that solve this are not allowed. * The input array will contain only nonnegative integer values or arrays. Each array will be homogenous, meaning that its elements will either by only arrays or only integers, but never a mix of both. * Each subarray may be nested to any depth. * The output may either by as a string or as an array of strings where each string is a line of output. ## Test Cases ``` [] ++ || ++ [[], []] +---+ |+++| ||||| |+++| +---+ [[], [1], [], [2], [], [3], []] +-----------+ |++-++-++-++| |||1||2||3||| |++-++-++-++| +-----------+ [[[[[0]]]]] +---------+ |+-------+| ||+-----+|| |||+---+||| ||||+-+|||| |||||0||||| ||||+-+|||| |||+---+||| ||+-----+|| |+-------+| +---------+ [[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]] +---------------------------------+ |+-------------+---------+-----+-+| ||+-----------+|+-------+|+---+|1|| |||+---------+|||+-----+|||2 1|| || ||||+-------+|||||3 2 1|||+---+| || |||||4 3 2 1|||||+-----+|| | || ||||+-------+|||+-------+| | || |||+---------+|| | | || ||+-----------+| | | || |+-------------+---------+-----+-+| +---------------------------------+ ``` [Answer] ## JavaScript (ES6), ~~223~~ 203 bytes ``` f=(a,g=a=>a[0].map?`<${a.map(g).join`|`}>`:a.join` `,s=g([a]),r=[s],t=s.replace(/<[ -9|]*>|[ -9]/g,s=>s[1]?s.replace(/./g,c=>c>`9`?`+`:`-`):` `))=>t<`+`?r.join`\n`.replace(/<|>/g,`|`):f(a,g,t,[t,...r,t]) ``` Port of @MitchSchwartz's Ruby solution. Previous version which worked by recursively wrapping the arrays (and therefore worked for arbitrary content, not just integers): ``` f=(...a)=>a[0]&&a[0].map?[s=`+${(a=a.map(a=>f(...a))).map(a=>a[0].replace(/./g,`-`)).join`+`}+`,...[...Array(Math.max(...a.map(a=>a.length)))].map((_,i)=>`|${a.map(a=>a[i]||a[0].replace(/./g,` `)).join`|`}|`),s]:[a.join` `] ``` Note: Although I'm using the spread operator in my argument list, to obtain the desired output, provide a single parameter of the original array rather then trying to spread the array; this has the effect of wrapping the output in the desired outer box. Sadly the outer box costs me 18 bytes, and space-separating the integers costs me 8 bytes, otherwise the following alternative visualisation would suffice for 197 bytes: ``` f=a=>a.map?[s=`+${(a=a.map(f)).map(a=>a[0].replace(/./g,`-`)).join`+`}+`,...[...Array(Math.max(0,...a.map(a=>a.length)))].map((_,i)=>`|${a.map(a=>a[i]||a[0].replace(/./g,` `)).join`|`}|`),s]:[``+a] ``` [Answer] # [Dyalog APL](http://dyalog.com/download-zone.htm), 56 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Thanks to ngn for helping removing about a third of the bytes. ``` {⍵≡∊⍵:⍉⍪⍉⍕⍵⋄(⊢,⊣/)⊃,/(1⊖('++','|'⍴⍨≢),'-'⍪⍣2↑)¨↓↑↓¨∇¨⍵}⊂ ``` ### TryAPL [Define the function](http://tryapl.org/?a=f%u2190%7B%u2375%u2261%u220A%u2375%3A%u2349%u236A%u2349%u2355%u2375%u22C4%28%u22A2%2C%u22A3/%29%u2283%2C/%281%u2296%28%27++%27%2C%27%7C%27%u2374%u2368%u2262%29%2C%27-%27%u236A%u23632%u2191%29%A8%u2193%u2191%u2193%A8%u2207%A8%u2375%7D%u2282&run), then run each test case and compare to the built-in `]Display` utility. [`[1, 2, 3]`](http://tryapl.org/?a=%5Ddisplay%20a%u21901%202%203%20%u22C4%20f%20a&run) [`[[1, 2, 3], [4, 5], [6, 7, 8]]`](http://tryapl.org/?a=%5Ddisplay%20a%u2190%281%202%203%29%284%205%29%286%207%208%29%20%u22C4%20f%20a&run) [`[[[1, 2, 3], [4, 5]], [6, 7, 8]]`](http://tryapl.org/?a=%5Ddisplay%20a%u2190%28%281%202%203%29%284%205%29%29%286%207%208%29%20%u22C4%20f%20a&run) [`[]`](http://tryapl.org/?a=%5Ddisplay%20%u236C%20%u22C4%20f%u236C&run) [`[[], []]`](http://tryapl.org/?a=%5Ddisplay%20%u236C%u236C%20%u22C4%20f%u236C%u236C&run) [`[[], [1], [], [2], [], [3], []]`](http://tryapl.org/?a=%5Ddisplay%20a%u2190%u236C%28%2C1%29%u236C%28%2C2%29%u236C%28%2C3%29%u236C%20%u22C4%20f%20a&run) [`[[[[[0]]]]]`](http://tryapl.org/?a=%5DDisplay%20a%u2190%u2282%u2282%u2282%u2282%2C0%20%u22C4%20f%20a&run) [`[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]]`](http://tryapl.org/?a=%5DDisplay%20a%u2190%28%u2282%u2282%u22824%203%202%201%29%28%u2282%u22823%202%201%29%28%u22822%201%29%28%2C1%29%20%u22C4%20f%20a&run) # Explanation Overall, this is an anonymous function `{...}` atop an enclose `⊂`. The latter just adds another level of nesting prompting the former to add an outer frame. The anonymous function with white-space (`⋄` is the statement separator): ``` { ⍵ ≡ ∊⍵: ⍉ ⍪ ⍉ ⍕ ⍵ (⊢ , ⊣/) ⊃ ,/ (1 ⊖ ('++' , '|' ⍴⍨ ≢) , '-' ⍪⍣2 ↑)¨ ↓ ↑ ↓¨ ∇¨ ⍵ } ``` Here it is again, but with separated utility functions: ``` CloseBox ← ⊢ , ⊣/ CreateVertical ← '++' , '|' ⍴⍨ ≢ AddHorizontals ← 1 ⊖ CreateVertical , '-' ⍪⍣2 ↑ { ⍵ ≡ ∊⍵: ⍉ ⍪ ⍉ ⍕ ⍵ CloseBox ⊃ ,/ AddHorizontals¨ ↓ ↑ ↓¨ ∇¨ ⍵ } ``` Now let me explain each function: `CloseBox` takes a table and returns the same table, but with the table's first column appended on the right of the table. Thus, given the 1-by-3 table `XYZ`, this function returns the 1-by-4 table `XYZX`, as follows:  `⊢` the argument (lit. what is on the right)  `,` prepended to  `⊣/` the leftmost column (lit. the left-reduction of each row) `CreateVertical` takes a table and returns the a string consisting of the characters which would fit `|`s on the sides of the table, but with two `+`s prepended to match two rows of `-`. Eventually the table will be cyclically rotated one row to get a single `+---...` row above and below. Thus, given any three row table, this function returns `++|||`, as follows:  `'++' ,` two pluses prepended to  `'|' ⍴⍨` a stile reshaped by  `≢` the (rows') tally of the argument `AddHorizontals` takes a list-of-lists, makes it into a table, adds two rows of `-`s on top, adds the corresponding left edge characters on the left, then rotates one row to the bottom, so that the table has a border on the top, left, and bottom. As follows:  `1 ⊖` rotate one row (the top row goes to the bottom) of  `CreateVertical ,` the string `++|||...` prepended (as a column) to  `'-' ⍪⍣2` minus added twice to the top of  `↑` the argument transformed from list-of-lists to table `{`The anonymous function`}`: If the argument is a simple (not nested) list, make it into a character table (thus, given the 3-element list `1 2 3`, this function returns the visually identical 1-by-five character table `1 2 3`). If the argument is not a simple list, ensure the elements are simple character tables; pad them to equal height; frame each on their top, bottom, and left; combine them; and finally take the very first column and add it on the right. As follows:  `{` begin the definition of an anonymous function   `⍵ ≡ ∊⍵:` if the argument is identical to the flattened argument (i.e. it is a simple list), then:    `⍉` transpose the    `⍪` columnized    `⍉` transposed    `⍕ ⍵` stringified argument; else:   `CloseBox` Add the leftmost column to the right of   `⊃ ,/` the disclosed (because reduction encloses) concatenated-across   `AddHorizontals¨` add `-`s on top and bottom of each of   `↓ ↑ ↓¨` the padded-to-equal-height\* of   `∇¨ ⍵`  this anonymous function applied to each of the arguments  `}` end the definition of the anonymous function \* Lit. make each table into a list-of-lists, combine the lists-of-lists (padding with empty strings to fill short rows) into a table, then split the table into a list of lists-of-lists [Answer] ## Brainfuck, 423 bytes ``` ->>+>>,[[>+>+<<-]+++++[>--------<-]>[<+>-[[-]<-]]>[[-]<<[>>>>+<<<<<<-<[>-<-]>>>- ]<<<[-<<<<<<-<]>+>>>]<<<[>>+>>>>>+<<<<<<<-]>>>>>>>>>,]<<+[<<,++>[-[>++<,<+[--<<< <<<<+]>]]<[-<+]->>>>[<++<<[>>>>>>>+<<<<<<<-]>>>-[<++>-[>>>>+<<<<<++<]<[<<]>]<[>> +<<<<]>>>+>+>[<<<-<]<[<<]>>>>->+>[-[<-<-[-[<]<[<++<<]>]<[<++++<<]>]<[>+<-[.<<<,< ]<[<<]]>]<[-<<<<<]>>[-[<+>---[<<++>>+[--[-[<+++++++<++>>,]]]]]<+++[<+++++++++++> -]<-.,>>]>>>>+>>>>]<<-] ``` Formatted with some comments: ``` ->>+>>, [ [>+>+<<-] +++++[>--------<-] > [ not open paren <+>- [ not paren [-]<- ] ] > [ paren [-] << [ close paren >>>>+<<<< <<-<[>-<-]>>> - ] <<< [ open paren directly after close paren -<<<<<<-< ] >+>>> ] <<<[>>+>>>>>+<<<<<<<-]>>> >>>>>>, ] <<+ [ <<,++> [ - [ >++< ,<+[--<<<<<<<+] > ] ] <[-<+] ->>>> [ <++<<[>>>>>>>+<<<<<<<-]>>>- [ at or before border <++>- [ before border >>>>+<<<< <++< ] <[<<] > ] < [ after border >>+<< << ] >>>+>+> [ column with digit or space <<<-< ] <[<<] >>>>->+> [ middle or bottom - [ bottom <-<- [ at or before border - [ before border < ] < [ at border <++<< ] > ] < [ after border <++++<< ] > ] < [ middle >+< -[.<<<,<] <[<<] ] > ] <[-<<<<<] >> [ border char or space - [ not space <+>--- [ not plus <<++>> + [ -- [ - [ pipe <+++++++<++>>, ] ] ] ] ] <+++[<+++++++++++>-]<-.,>> ] > >>>+>>>> ] <<- ] ``` [Try it online.](http://brainfuck.tryitonline.net/#code=LT4-Kz4-LFtbPis-Kzw8LV0rKysrK1s-LS0tLS0tLS08LV0-WzwrPi1bWy1dPC1dXT5bWy1dPDxbPj4-Pis8PDw8PDwtPFs-LTwtXT4-Pi1dPDw8Wy08PDw8PDwtPF0-Kz4-Pl08PDxbPj4rPj4-Pj4rPDw8PDw8PC1dPj4-Pj4-Pj4-LF08PCtbPDwsKys-Wy1bPisrPCw8K1stLTw8PDw8PDwrXT5dXTxbLTwrXS0-Pj4-WzwrKzw8Wz4-Pj4-Pj4rPDw8PDw8PC1dPj4-LVs8Kys-LVs-Pj4-Kzw8PDw8Kys8XTxbPDxdPl08Wz4-Kzw8PDxdPj4-Kz4rPls8PDwtPF08Wzw8XT4-Pj4tPis-Wy1bPC08LVstWzxdPFs8Kys8PF0-XTxbPCsrKys8PF0-XTxbPis8LVsuPDw8LDxdPFs8PF1dPl08Wy08PDw8PF0-PlstWzwrPi0tLVs8PCsrPj4rWy0tWy1bPCsrKysrKys8Kys-PixdXV1dXTwrKytbPCsrKysrKysrKysrPi1dPC0uLD4-XT4-Pj4rPj4-Pl08PC1d&input=KCgoKCg0IDMgMiAxKSkpKSgoKDMgMiAxKSkpKCgyIDEpKSgxKSkK) Expects input formatted like `(((((4 3 2 1))))(((3 2 1)))((2 1))(1))` with a trailing newline, and produces output of the form: ``` +---------------------------------+ |+-------------+---------+-----+-+| ||+-----------+|+-------+|+---+| || |||+---------+|||+-----+||| || || ||||+-------+||||| |||| || || |||||4 3 2 1||||||3 2 1||||2 1||1|| ||||+-------+||||| |||| || || |||+---------+|||+-----+||| || || ||+-----------+|+-------+|+---+| || |+-------------+---------+-----+-+| +---------------------------------+ ``` The basic idea is to calculate which character to print based on the depth of nesting. The output format is such that the row index of a box's top border is equal to the corresponding array's depth, with symmetry across the middle row. The tape is divided into 7-cell nodes, with each node representing a column in the output. The first loop consumes the input and initializes the nodes, keeping track of depth and whether the column corresponds to a parenthesis (i.e., whether the column contains a vertical border), and collapsing occurrences of `)(` into single nodes. The next loop outputs one row per iteration. Within this loop, another loop traverses the nodes and prints one character per iteration; this is where most of the work takes place. During the initialization loop, the memory layout of a node at the beginning of an iteration is `x d 0 c 0 0 0` where `x` is a boolean flag for whether the previous char was a closing parenthesis, `d` is depth (plus one), and `c` is the current character. During the character printing loop, the memory layout of a node at the beginning of an iteration is `0 0 d1 d2 c p y` where `d1` indicates depth compared with row index for top half; `d2` is similar to `d1` but for bottom half; `c` is the input character for that column if digit or space, otherwise zero; `p` indicates phase, i.e. top half, middle, or bottom half; and `y` is a flag that gets propagated from left to right, keeping track of whether we have reached the middle row yet. Note that since `y` becomes zero after processing a node, we can use the `y` cell of the previous node to gain more working space. This setup allows us to avoid explicitly calculating the max depth during the initialization phase; the `y` flag is back-propagated to update the `p` cells accordingly. There is a `-1` cell to the left of the nodes to facilitate navigation, and there is a cell to the right of the nodes that keeps track of whether we have printed the last row yet. [Answer] # Ruby, 104 bytes ``` ->s{r=s=s.gsub'}{',?| r=[s,r,s]*$/while s=s.tr('!-9',' ').gsub!(/{[ |]*}/){$&.tr' -}','-+'} r.tr'{}',?|} ``` Anonymous function that expects a string. For example, `{{{{{4 3 2 1}}}}{{{3 2 1}}}{{2 1}}{1}}` produces ``` +---------------------------------+ |+-------------+---------+-----+-+| ||+-----------+| | | || |||+---------+||+-------+| | || ||||+-------+||||+-----+||+---+| || |||||4 3 2 1||||||3 2 1||||2 1||1|| ||||+-------+||||+-----+||+---+| || |||+---------+||+-------+| | || ||+-----------+| | | || |+-------------+---------+-----+-+| +---------------------------------+ ``` You can use this code for testing: ``` f=->s{r=s=s.gsub'}{',?| r=[s,r,s]*$/while s=s.tr('!-9',' ').gsub!(/{[ |]*}/){$&.tr' -}','-+'} r.tr'{}',?|} a=[] a<<'[1, 2, 3]' a<<'[[1, 2, 3], [4, 5], [6, 7, 8]]' a<<'[[[1, 2, 3], [4, 5]], [6, 7, 8]]' a<<'[]' a<<'[[], []]' a<<'[[], [1], [], [2], [], [3], []]' a<<'[[[[[0]]]]]' a<<'[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]]' a.map{|s|s.gsub! '], [','}{' s.tr! '[]','{}' s.gsub! ',','' puts s puts f[s],''} ``` This starts from the middle row and works outwards. First, instances of `}{` are replaced with `|`. Then, while there are still braces, all innermost `{...}` strings are transformed into the appropriate `+-` sequences while characters other than `|{}` are turned into spaces. At the end, the intermediate braces are turned into pipes. [Answer] # PHP+HTML, not competing (~~170~~ ~~141~~ ~~135~~ 130 bytes) saved 29 bytes inspired by SteeveDroz ``` <?function p($a){foreach($a as$e)$r.=(is_array($e)?p($e):" $e");return"<b style='border:1px solid;float:left;margin:1px'>$r</b>";} ``` not competing because it´s no ascii output and because I let the browser do all the interesting work [Answer] # JavaScript (ES6), 221 A non recursive function returning an array of strings (still using a recursive subfunction inside) ``` a=>[...(R=(a,l)=>a[r[l]='',0]&&a[0].map?'O'+a.map(v=>R(v,l+1))+'C':a.join` `)([a],l=-1,r=[],m='')].map(c=>r=r.map(x=>x+v[(k<0)*2+!k--],k=l,1/c?v='-- ':(v='-+|',c>'C'?k=++l:c>','&&--l,c='|'),m+=c))&&[...r,m,...r.reverse()] ``` This works in 2 steps. Step 1: recursively build a string representation of the nested input array. Example: `[[[1, 2, 3], [],[4, 5]], [6, 7, 8]]` -> `"OOO1 2 3,,4 5C,6 7 8CC"` `O` and `C` mark open and close subarray. Simple numeric subarrays are rendered with the elements separated by space, while if array members are subarrays they are separated by commas. This string keeps track of the multilevel structure of the input array, while I can get the middle row of the output just replacing `OC,` with `|`. While recursively building this temp string, I also find the max depth level and initialize an array of empty strings that will contain the half top part of the output. Note: the outer box is tricky, I nest the input inside another outer array, then I have drop the first row of output that is not needed Step 2: scan the temp string and build the output Now I have an array of empty strings, one for each level. I scan the temp string, keeping track of the current level, that increases for each `O` and decreases for each `C`. I visualize this like that: ``` [[[1, 2, 3], [],[4, 5]], [6, 7, 8]] OOO1 2 3,,4 5C,6 7 8CC + + + + + + ++ + |||1 2 3||4 5||6 7 8|| ``` The plus the goes up and down follow the current level For each char, I add a character to every row of output, following the rules: - if digit or space, put a '-' at the current level and below, put a space above - else, put a '+' at the current level, put a '-' if below and put a '|' if above ``` OOO1 2 3,,4 5C,6 7 8CC +--------------------+ |+------------+-----+| ||+-----++---+| || |||1 2 3||4 5||6 7 8|| ``` During the temp scan, I also build the middle row replacing `OC,` with `|` At the end of this step, I have the top half and the middle row, I only have to mirror the top to get the bottom half and I'm done *Less golfed, commented code* ``` a=>{ r = []; // output array R = ( // recursive scan function a, // current subarray l // current level ) => ( r[l] = '', // element of r at level r, init to "" a[0] && a[0].map // check if it is a flat (maybe empty) array or an array of arrays ? 'O'+a.map(v=>R(v,l+1))+'C' // mark Open and Close, recurse : a.join` ` // just put the elements space separated ); T = R([a],-1)]; // build temp string // pass the input nested in another array // and start with level -1 , so that the first row of r will not be visible to .map // prepare the final output m = '' // middle row, built upon the chars in T l = -1 // starting level [...T].map(c => // scan the temp string { k = l; // current level 1/c // check if numeric or space ? v = '-- ' // use '-','-',' ' : ( v = '-+|', // use '-','+','|' c > 'C' ? k=++l // if c=='O', increment level and assign to k : c>'A'&&--l, // if c=='C', decrement level (but k is not changed) c='|' // any of O,C,comma must be mapped to '|' ); m += c; // add to middle row r = r.map( (x,i) => // update each output row // based on comparation between row index and level // but in golfed code I don't use the i index // and decrement l at each step x + v[(k<i)*2+!(k-i)] ) }) // almost done! return [...r,m,...r.reverse()] ``` ) **Test** ``` F= a=>[...(R=(a,l)=>a[r[l]='',0]&&a[0].map?'O'+a.map(v=>R(v,l+1))+'C':a.join` `)([a],l=-1,r=[],m='')].map(c=>r=r.map(x=>x+v[(k<0)*2+!k--],k=l,1/c?v='-- ':(v='-+|',c>'C'?k=++l:c>','&&--l,c='|'),m+=c))&&[...r,m,...r.reverse()] out=x=>O.textContent = x+'\n'+O.textContent ;[[1,2,3] ,[[[1, 2, 3], [4, 5]], [6, 7, 8]] ,[] ,[[], []] ,[[], [1], [], [2], [], [3], []] ,[[[[[0]]]]] ,[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]] ].forEach(t=> out(JSON.stringify(t)+'\n'+F(t).join`\n`+'\n') ) function update() { var i=eval(I.value) out(JSON.stringify(i)+'\n'+F(i).join`\n`+'\n') } update() ``` ``` #I { width:90%} ``` ``` <input id=I value='[[[1, 2, 3], [],[4, 5]], [6, 7, 8]]' oninput='update()'> <pre id=O></pre> ``` [Answer] # Ruby, ~~245~~ 241 bytes The overhead needed to wrap everything in boxes as well as align everything is pretty heavy... Outputs arrays of strings, with one string per line, as per the spec. Bottom-aligned instead of the top-aligned sample test cases because it saves 1 byte. [Try it online!](https://repl.it/EKQz/3) ``` V=->a{a==[*a]?(k=a.map(&V);k[0]==[*k[0]]?[h=?++?-*((k.map!{|z|z[1,0]=[' '*~-z[0].size+?|]*(k.map(&:size).max-z.size);z};f=k.shift.zip(*k).map{|b|?|+b.reduce{|r,e|r+e[1..-1]}+?|})[0].size-2)+?+,*f,h]:[h="+#{?-*(f=k*' ').size}+",?|+f+?|,h]):a} ``` [Answer] # PHP, 404 Bytes All solutions works with maximum depth of the array lesser then 10. for greater values the depth must store in an array and not in a string. ``` <?foreach(str_split(json_encode($_GET[a]))as$j){$j!="]"?:$c--;$r=($j==",")?($l=="]"?"":" "):$j;$r=$r=="]"?"|":$r;$r=$r=="["?($v=="]"?"":"|"):$r;if($r!=""){$n.=$r;$d.=+$c;}$v=$l;$l=$j;$j!="["?:$c++;$m>=$c?:$m=$c;}for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++)$z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" "));echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` Expanded ``` foreach(str_split(json_encode($_GET[a]))as$j){ # split JSON representation of the array $j!="]"?:$c--; $r=($j==",")?($l=="]"?"":" "):$j; $r=$r=="]"?"|":$r; $r=$r=="["?($v=="]"?"":"|"):$r; if($r!=""){ $n.=$r; # concanate middle string $d.=+$c; # concanate depth position } $v=$l; $l=$j; $j!="["?:$c++; $m>=$c?:$m=$c; # maximum depth of the array } for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++) $z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" ")); # Build the strings before the middle string dependent of value middle string and depth echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); #Output ``` ## for 425 Bytes we can make this with REGEX ``` <?$n=($p=preg_filter)("#\]|\[#","|",$r=$p("#\],\[#","|",$p("#,(\d)#"," $1",json_encode($_GET[a]))));preg_match_all("#.#",$r,$e,256);foreach($e[0] as$f){$f[0]!="]"&&$f[0]!="|"?:$c--;$d.=+$c;$f[0]!="|"&&$f[0]!="["?:$c++;$m>=$c?:$m=$c;}for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++)$z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" "));echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` Expanded ``` $r=preg_filter("#\],\[#","|",preg_filter("#,(\d)#"," $1",json_encode($_GET[a]))); preg_match_all("#.#",$r,$e,256); $n=preg_filter("#\]|\[#","|",$r); # concanate middle string foreach($e[0] as$f){ $f[0]!="]"&&$f[0]!="|"?:$c--; $d.=+$c; concanate depth position $f[0]!="|"&&$f[0]!="["?:$c++; $m>=$c?:$m=$c; # maximum depth of the array } # similar to the other ways for($x=0;$x<strlen($n);$x++) for($y=0;$y<$m;$y++) $z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" ")); echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` ## 455 Bytes for a recursive solution ``` <?function v($x,$t=0,$l=1){global$d;$d.=$t;$s="|";$c=count($x);foreach($x as$k=>$v){if(is_array($v))$e=v($v,$t+1,$k+1==$c);else{$e=$v." "[$k+1==$c];$d.=str_pad("",strlen($e),$t+1);}$s.=$e;}$d.=$l?$t:"";$s.=$l?"|":"";return$s;}$n=v($_GET[a]);$m=max(str_split($d));for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++)$z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" "));echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` Expanded ``` function v($x,$t=0,$l=1){ global$d; # concanate depth position $d.=$t; $s="|"; $c=count($x); foreach($x as$k=>$v){ if(is_array($v)){$e=v($v,$t+1,$k+1==$c);} else{$e=$v." "[$k+1==$c];$d.=str_pad("",strlen($e),$t+1);} $s.=$e; } $d.=$l?$t:""; $s.=$l?"|":""; return$s; } $n=v($_GET[a]); # concanate middle string $m=max(str_split($d)); # maximum depth of the array # similar to the other ways for($x=0;$x<strlen($n);$x++) for($y=0;$y<$m;$y++) $z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" ")); echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` ]
[Question] [ # ...counted! You will pass your program a variable which represents a quantity of money in dollars and/or cents and an array of coin values. Your challenge is to output the number of possible combinations of the given array of coin values that would add up to the amount passed to the code. If it is not possible with the coins named, the program should return `0`. Note on American numismatic terminology: * 1-cent coin: penny * 5-cent coin: nickel * 10-cent coin: dime * 25-cent coin: quarter (quarter dollar) **Example 1:** Program is passed: ``` 12, [1, 5, 10] ``` (12 cents) Output: ``` 4 ``` There are 4 possible ways of combining the coins named to produce 12 cents: 1. 12 pennies 2. 1 nickel and 7 pennies 3. 2 nickels and 2 pennies 4. 1 dime and 2 pennies **Example 2:** Program is passed: ``` 26, [1, 5, 10, 25] ``` (26 cents) Output: ``` 13 ``` There are 13 possible ways of combining the coins named to produce 26 cents: 1. 26 pennies 2. 21 pennies and 1 nickel 3. 16 pennies and 2 nickels 4. 11 pennies and 3 nickels 5. 6 pennies and 4 nickels 6. 1 penny and 5 nickels 7. 16 pennies and 1 dime 8. 6 pennies and 2 dimes 9. 11 pennies, 1 dime, and 1 nickel 10. 6 pennies, 1 dime, and 2 nickels 11. 1 penny, 1 dime, and 3 nickels 12. 1 penny, 2 dimes, and 1 nickel 13. 1 quarter and 1 penny **Example 3:** Program is passed: ``` 19, [2, 7, 12] ``` Output: ``` 2 ``` There are 2 possible ways of combining the coins named to produce 19 cents: 1. 1 12-cent coin and 1 7-cent coin 2. 1 7-cent coin and 6 2-cent coins **Example 4:** Program is passed: ``` 13, [2, 8, 25] ``` Output: ``` 0 ``` There are no possible ways of combining the coins named to produce 13 cents. --- This has been through the Sandbox. Standard loopholes apply. This is code golf, so the answer with the fewest bytes wins. [Answer] ## Haskell, ~~37~~ 34 bytes ``` s#l@(c:d)|s>=c=(s-c)#l+s#d s#_=0^s ``` Usage example: `26 # [1,5,10,25]` -> `13`. Simple recursive approach: try both the next number in the list (as long as it is less or equal to the amount) and skip it. If subtracting the number leads to an amount of zero, take a `1` else (or if the list runs out of elements) take a `0`. Sum those `1`s and `0`s. Edit: @Damien: saved 3 bytes by pointing to a shorter base case for the recursion (which also can be found in [@xnors answer](https://codegolf.stackexchange.com/a/96900/34531)). [Answer] ## Mathematica, ~~35~~ 22 bytes *Thanks to miles for suggesting `FrobeniusSolve` and saving 13 bytes.* ``` Length@*FrobeniusSolve ``` Evaluates to an unnamed function, which takes the list of coins as the first argument and the target value as the second. `FrobeniusSolve` is a shorthand for solving Diophantine equations of the form ``` a1x1 + a2x2 + ... + anxn = b ``` for the `xi` over the non-negative integers and gives us all the solutions. [Answer] # Jelly ([fork](https://github.com/miles-cg/jelly/tree/frobenius)), 2 bytes ``` æf ``` This relies on a [branch](https://github.com/miles-cg/jelly/tree/frobenius) of Jelly where I was working on implementing Frobenius solve atoms so unfortunately you cannot try it online. ## Usage ``` $ ./jelly eun 'æf' '12' '[1,5,10]' 4 $ ./jelly eun 'æf' '26' '[1,5,10,25]' 13 $ ./jelly eun 'æf' '19' '[2,7,12]' 2 $ ./jelly eun 'æf' '13' '[2,8,25]' 0 ``` ## Explanation ``` æf Input: total T, denominations D æf Frobenius count, determines the number of solutions of nonnegative X such that X dot-product D = T ``` [Answer] # Pyth, 8 bytes ``` /sM{yS*E ``` Raw brute force, too memory intensive for actual testing. This is O(2*mn*), where *n* is the number of coins and *m* is the target sum. Takes input as `target\n[c,o,i,n,s]`. ``` /sM{yS*EQQ (implicit Q's) *EQ multiply coin list by target S sort y powerset (all subsequences) { remove duplicates sM sum all results / Q count correct sums ``` [Answer] ## Haskell, 37 bytes ``` s%(h:t)=sum$map(%t)[s,s-h..0] s%_=0^s ``` Using some multiple of the first coin `h` decreases the required sum `s` to a non-negative value in the decreasing progression `[s,s-h..0]`, which then must be made with the remaining coins. Once there's no coins left, check that the sum is zero arithmetically as `0^s`. [Answer] ## JavaScript (ES6), ~~51~~ 48 bytes ``` f=(n,a,[c,...b]=a)=>n?n>0&&c?f(n-c,a)+f(n,b):0:1 ``` Accepts coins in any order. Tries both using and not using the first coin, recursively calculating the number of combinations either way. `n==0` means a matching combination, `n<0` means that the coins exceed the quantity while `c==undefined` means that there are no coins left. Note that the function is very slow and if you have a penny coin then the following function is faster (don't pass the penny coin in the array of coins): ``` f=(n,a,[c,...b]=a)=>c?(c<=n&&f(n-c,a))+f(n,b):1 ``` [Answer] ## Perl, 45 bytes Byte count includes 44 bytes of code and `-p` flag. ``` s%\S+%(1{$&})*%g,(1x<>)=~/^$_$(?{$\++})^/x}{ ``` Takes the coin values on the first line, and the targeted amount on the second line : ``` $ perl -pE 's%\S+%(1{$&})*%g,(1x<>)=~/^$_$(?{$\++})^/x}{' <<< "1 5 10 25 26" 13 ``` **Short explanations:** ``` -p # Set $_ to the value of the input, # and adds a print at the end of the code. s%\S+%(1{$&})*%g, # Converts each number n to (1{$&})* (to prepare the regex) # This pattern does half the job. (1x<>) # Converts the target to unary representation. =~ # Match against.. (regex) /^ $_ $ # $_ contains the pattern we prepared with the first line. (?{$\++}) # Count the number of successful matches ^ # Forces a fail in the regex since the begining can't be matched here. /x # Ignore white-spaces in the regex # (needed since the available coins are space-separated) }{ # End the code block to avoid the input being printed (because of -p flag) # The print will still be executed, but $_ will be empty, # and only $\ will be printed (this variable is added after every print) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` œċЀS€€Fċ ``` **[Try it online!](http://jelly.tryitonline.net/#code=xZPEi8OQ4oKsU-KCrOKCrEbEiw&input=U3VtX3tqPTAuLmt9ICgtMSleaiAqIChrLWopXm4gKiBiaW5vbWlhbChuKzEsIGopLg&args=WzEsNSwxMCwyNV0+MjY)** ### How? ``` œċЀS€€Fċ - Main link: coins, target Ѐ - map over right argument, or for each n in [1,2,...,target] œċ - combinations with replacement, possible choices of each of n coins S€€ - sum for each for each (values of those selections) F - flatten into one list ċ - count occurrences of right argument ``` [Answer] # JavaScript (ES6), 59 bytes ``` f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),0):1 ``` Coins are input from highest to lowest, e.g. `f(26,[100,25,10,5,1])`. If you have a penny, remove it and use this much faster version instead: ``` f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),1):1 ``` This uses a recursive formula much like @nimi's. I originally wrote this a few days ago when the challenge was still in the sandbox; it looked like this: ``` f=(n,c=[100,25,10,5])=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),1):1 ``` The only differences being the default value of `c` (it had a set value in the original challenge), and changing the `0` in the `.reduce` function to `1` (this was two bytes shorter and a bazillion times faster than `c=[100,25,10,5,1]`). --- Here's a modified version which outputs all combinations, rather than the number of combinations: ``` f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:[...x,...f(n-y,c.slice(i)).map(c=>[...c,y])],[]):[[]] ``` [Answer] # PHP, 327 Bytes ``` function c($f,$z=0){global$p,$d;if($z){foreach($p as$m){for($j=0;$j<=$f/$d[$z];){$n=$m;$n[$d[$z]]=$j++;$p[]=$n;}}}else for($p=[],$j=0;$j<=$f/$d[$z];$j++)$p[]=[$d[$z]=>$j];if($d[++$z])c($f,$z);}$d=$_GET[a];c($e=$_GET[b]);foreach($p as$u){$s=0;foreach($u as$k=>$v)$s+=$v*$k;if($s==$e&count($u)==count($d))$t[]=$u;}echo count($t); ``` [Try it](http://sandbox.onlinephpfunctions.com/code/9f0d8ad9a8c645219cb9ec9cd6685b7a55e4ebda) [Answer] ## Axiom, ~~63~~ 62 bytes 1 byte saved by @JonathanAllan ``` f(n,l)==coefficient(series(reduce(*,[1/(1-x^i)for i in l])),n) ``` This approach uses generating functions. Probably that didn't help bring down the code size. I think this is the first time that in my playing with Axiom I went as far as defining my own function. The first time the function is called it gives a horrendous warning, but still produces the correct result. After that, everything is fine as long as the list isn't empty. [Answer] # R, ~~81~~ ~~76~~ 63 bytes Thanks to @rturnbull for golfing away 13 bytes! ``` function(u,v)sum(t(t(expand.grid(lapply(u/v,seq,f=0))))%*%v==u) ``` Example (note that `c(...)` is how you pass vectors of values to R): ``` f(12,c(1,5,10)) [1] 4 ``` Explanation: `u` is the desired value, `v` is the vector of coin values. ``` expand.grid(lapply(u/v,seq,from=0)) ``` creates a data frame with every possible combination of 0 to k coins (k depends on the denomination), where k is the lowest such that k times the value of that coin is at least u (the value to achieve). Normally we would use `as.matrix` to turns that into a matrix, but that is many characters. Instead we take the transpose of the transpose (!) which automatically coerces it, but takes fewer characters. `%*% v` then calculates the monetary value of each row. The last step is to count how many of those values are equal to the desired value `u`. Note that the computational complexity and memory requirements of this are horrific but hey, it's code golf. [Answer] # J, 27 bytes ``` 1#.[=](+/ .*~]#:,@i.)1+<.@% ``` ## Usage ``` f =: 1#.[=](+/ .*~]#:,@i.)1+<.@% 12 f 1 5 10 4 26 f 1 5 10 25 13 19 f 2 7 12 2 13 f 2 8 25 0 ``` ## Explanation ``` 1#.[=](+/ .*~]#:,@i.)1+<.@% Input: target T (LHS), denominations D (RHS) % Divide T by each in D <.@ Floor each These are the maximum number of each denomination 1+ Add 1 to each, call these B ,@i. Forms the range 0 the the product of B ] Get B #: Convert each in the range to mixed radix B ] Get D +/ .*~ Dot product between D and each mixed radix number These are all combinations of denominations up to T [ Get T = Test if each sum is equal to T 1#. Convert as base 1 digits to decimal (takes the sum) This is the number of times each sum was true ``` [Answer] # TSQL, 105 bytes This can only handle up to one dollar with these 4 coin types. The ungolfed version can handle up to around 4 dollars, but very slow - on my box this takes 27 seconds. Result is 10045 combinations b.t.w. Golfed: ``` DECLARE @ INT = 100 DECLARE @t table(z int) INSERT @t values(1),(5),(10),(25) ;WITH c as(SELECT 0l,0s UNION ALL SELECT z,s+z FROM c,@t WHERE l<=z and s<@)SELECT SUM(1)FROM c WHERE s=@ ``` Ungolfed: ``` -- input variables DECLARE @ INT = 100 DECLARE @t table(z int) INSERT @t values(1),(5),(10),(25) -- query ;WITH c as ( SELECT 0l,0s UNION ALL SELECT z,s+z FROM c,@t WHERE l<=z and s<@ ) SELECT SUM(1) FROM c WHERE s=@ -- to allow more than 100 recursions(amounts higher than 1 dollar in this example) OPTION(MAXRECURSION 0) ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/560877/a-penny-saved-is-a-penny)** [Answer] ## [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) repl, 66 bytes ``` (d C(q((Q V)(i Q(i(l Q 0)0(i V(s(C(s Q(h V))V)(s 0(C Q(t V))))0))1 ``` Recursive solution: tries using the first coin and not using the first coin, then adds the results from each. Exponential time complexity and no tail-recursion, but it computes the test cases just fine. Ungolfed (key to builtins: `d` = define, `q` = quote, `i` = if, `l` = less-than, `s` = subtract, `h` = head, `t` = tail): ``` (d combos (q ((amount coin-values) (i amount (i (l amount 0) 0 (i coin-values (s (combos (s amount (h coin-values)) coin-values) (s 0 (combos amount (t coin-values)))) 0)) 1)))) ``` Example usage: ``` tl> (d C(q((Q V)(i Q(i(l Q 0)0(i V(s(C(s Q(h V))V)(s 0(C Q(t V))))0))1 C tl> (C 12 (q (1 5 10))) 4 tl> (C 26 (q (1 5 10 25))) 13 tl> (C 19 (q (2 7 12))) 2 tl> (C 13 (q (2 8 25))) 0 tl> (C 400 (q (1 5 10 25))) Error: recursion depth exceeded. How could you forget to use tail calls?! ``` [Answer] # PHP, 130 bytes ``` function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2)); ``` 99 byte recursive function (and 31 bytes of calling it) that repeatedly removes the value of the current coin from the target and calls itself with the new value and the other coins. Counts the number of times the target reaches 0 exactly. Run like: ``` php -r "function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));" 12 1 5 10 ``` [Answer] ## Racket 275 bytes ``` (set! l(flatten(for/list((i l))(for/list((j(floor(/ s i))))i))))(define oll'())(for((i(range 1(add1(floor(/ s(apply min l))))))) (define ol(combinations l i))(for((j ol))(set! j(sort j >))(when(and(= s(apply + j))(not(ormap(λ(x)(equal? x j))oll)))(set! oll(cons j oll)))))oll ``` Ungolfed: ``` (define(f s l) (set! l ; have list contain all possible coins that can be used (flatten (for/list ((i l)) (for/list ((j (floor (/ s i)))) i)))) (define oll '()) ; final list of all solutions initialized (for ((i (range 1 (add1 (floor ; for different sizes of coin-set (/ s (apply min l))))))) (define ol (combinations l i)) ; get a list of all combinations (for ((j ol)) ; test each combination (set! j (sort j >)) (when (and (= s (apply + j)) ; sum is correct (not(ormap ; solution is not already in list (lambda(x) (equal? x j)) oll))) (set! oll (cons j oll)) ; add found solution to final list ))) (reverse oll)) ``` Testing: ``` (f 4 '[1 2]) (println "-------------") (f 12 '[1 5 10]) (println "-------------") (f 19 '[2 7 12]) (println "-------------") (f 8 '(1 2 3)) ``` Output: ``` '((2 2) (2 1 1) (1 1 1 1)) "-------------" '((10 1 1) (5 5 1 1) (5 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1 1 1 1 1)) "-------------" '((12 7) (7 2 2 2 2 2 2)) "-------------" '((3 3 2) (2 2 2 2) (3 2 2 1) (3 3 1 1) (2 2 2 1 1) (3 2 1 1 1) (2 2 1 1 1 1) (3 1 1 1 1 1) (2 1 1 1 1 1 1) (1 1 1 1 1 1 1 1)) ``` Following recursive solution has some error: ``` (define (f s l) ; s is sum needed; l is list of coin-types (set! l (sort l >)) (define oll '()) ; list of all solution lists (let loop ((l l) (ol '())) ; a solution list initialized (when (not (null? l)) (set! ol (cons (first l) ol))) (define ols (apply + ol)) ; current sum in solution list (cond [(null? l) (remove-duplicates oll)] [(= ols s) (set! oll (cons ol oll)) (loop (rest l) '()) ] [(> ols s) (loop (rest l) (rest ol)) (loop (rest l) '()) ] [(< ols s) (loop l ol) (loop (rest l) ol) ]))) ``` Does not work properly for: ``` (f 8 '[1 2 3]) ``` Output: ``` '((1 1 1 2 3) (1 2 2 3) (1 1 1 1 1 1 1 1) (2 3 3) (1 1 1 1 1 1 2) (1 1 1 1 2 2) (1 1 2 2 2) (2 2 2 2)) ``` (1 1 3 3) is possible but does not come in solution list. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 15 bytes ``` s+\Fṁḷ 2*BW;ç/Ṫ ``` [Try it online!](http://jelly.tryitonline.net/#code=cytcRuG5geG4twoyKkJXO8OnL-G5qg&input=&args=MjY+MSw1LDEwLDI1&debug=on) or [Verify all test cases.](http://jelly.tryitonline.net/#code=cytcRuG5geG4twoyKkJXO8OnL-G5qgrDpyI&input=&args=MTIsMjYsMTksMTM+WzEsNSwxMF0sWzEsNSwxMCwyNV0sWzIsNywxMl0sWzIsOCwyNV0&debug=on) This was more of an exercise in writing an efficient version in Jelly without using builtins. This is based on the typical dynamic programming approach used to calculate the number of ways for making change ## Explanation ``` s+\Fṁḷ Helper link. Input: solutions S, coin C s Slice the solutions into non-overlapping sublists of length C +\ Cumulative sum F Flatten ḷ Left, get S ṁ Mold the sums to the shape of S 2*BW;ç/Ṫ Main link. Input: target T, denominations D 2* Compute 2^T B Convert to binary, creates a list with 1 followed by T-1 0's These are the number of solutions for each value from 0 to T starting with no coins used W Wrap it inside another array ; Concatenate with D ç/ Reduce using the helper link Ṫ Tail, return the last value which is the solution ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 15 bytes Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWXO1Jg4pWc4oiZ4pmCU-KVlOKZgs6jaWBNYw&input=MTAKWzEsNSwxMF0) ``` ╗;R`╜∙♂S╔♂Σi`Mc ``` **Ungolfing** ``` Implicit input n, then the list of coins a. ╗ Save a to register 0. ;R Duplicate n and create a range [1..n] from that duplicate. `...`M Map the following function over that range. Variable i. ╜ Push a from register 0. ∙ Push the i-th Cartesian power of a. ♂S Sort each member of car_pow. ╔ Uniquify car_pow so we don't count too any duplicate coin arrangements. ♂Σ Take the sum of each coin arrangement. i Flatten the list. c Using the result of the map and the remaining n, push map.count(n). Implicit return. ``` [Answer] # Python, 120 bytes ``` from itertools import* lambda t,L:[sum(map(lambda x,y:x*y,C,L))-t for C in product(range(t+1),repeat=len(L))].count(0) ``` Bruteforces through all combinations of coins up to target value (even if the smallest is not 1). ]
[Question] [ One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a ["cat program"](http://esolangs.org/wiki/Cat): read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility `cat` it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc. ### Task You should write a **full program** which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's `prompt` and `alert`). These are the *only* admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable. The output should contain exactly the input and *nothing else*. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. **This also applies to trailing newlines.** If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.) Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. *If you do this, I encourage you to add an error-free version to your answer as well (for reference).* As this is intended as a challenge within each language and not between languages, there are a few language specific rules: * If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well). * If it is at all possible in your language to support an *arbitrary* infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example `yes | tr -d \\n | ./my_cat` should print an infinite stream of `y`s. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing). Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output. ### Additional rules * This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in *every* language. Therefore, no answer will be marked as accepted. * Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/). * Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting. 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. Also note that languages *do* have to fulfil [our usual criteria for programming languages](http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. * Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, including the <http://meta.codegolf.stackexchange.com/q/1061>. As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code. ### 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: ``` ## [><>](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 = 62230; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//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 "//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(42), 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] # sed, 0 ``` ``` The empty `sed` program does exactly what is required here: ``` $ printf "abc\ndef" | sed '' abc def$ ``` [Answer] # [Ziim](http://esolangs.org/wiki/Ziim), ~~222~~ ~~201~~ ~~196~~ ~~185~~ 182 bytes ``` ↓ ↓ ↓ ↓ ↓ ↗ ↗↙↔↘↖ ↖ ↓↓⤡⤢ ⤢↙ ↘ ↖⤡ ↖ ↙ ↕↘ ↑ ↙ →↘↖↑ ↙ ↑ →↖ ↑ →↖↘ ↙ ↑↓↑ ⤡ ``` This will probably not display correctly in your browser, so here is a diagram of the code: [![enter image description here](https://i.stack.imgur.com/K0S8k.png)](https://i.stack.imgur.com/K0S8k.png) I can't think of a simpler *structure* to solve the problem in Ziim, but I'm sure the actual code is still quite golfable. Ziim cannot possibly handle infinite streams because it is only possible to print anything at the end of the program. ## Explanation Since Ziim has a rather unique, declarative control flow model an imperative pseudocode algorithm won't cut it here. Instead, I'll explain the basics of Ziim and the present the tidied up structure of the above code (in a similar graphical manner) as ASCII art. Control flow in Ziim happens all over the place: each arrow which isn't pointed at by another arrow initialises a "thread" which is processed independently of the others (not really in parallel, but there are no guarantees which order they are processed in, unless you sync them up via concatenation). Each such thread holds a list of binary digits, starting as `{0}`. Now each arrow in the code is some sort of command which has one or two inputs and one or two outputs. The exact command depends on how many arrows are pointing at it from which orientations. Here is the list of the commands, where `m -> n` indicates that the command takes `m` inputs and produces `n` outputs. * `1 -> 1`, **no-op**: simply redirects the thread. * `1 -> 1`, **invert**: negates each bit in the thread (and also redirects it). * `1 -> 1`, **read**: replaces the thread's value by the next *bit* from STDIN, or by the empty list if we've hit EOF. * `2 -> 1`, **concatenate**: this is the only way to sync threads. When a thread hits one side of the arrow, it will be suspended until another thread hits the other side. At that point they will be concatenated into a single thread and continue execution. * `2 -> 1`, **label**: this is the only way to join different execution paths. This is simply a no-op which has two possible inputs. So threads entering the "label" via either route will simply be redirected into the same direction. * `1 -> 2`, **split**: takes a single thread, and sends two copies off in different directions. * `1 -> 1`, **isZero?**: consumes the first bit of the thread, and sends the thread in one of two directions depending on whether the bit was 0 or 1. * `1 -> 1`, **isEmpty?**: consumes the entire list (i.e. replaces it with an empty list), and sends the thread in one of two direction depending on whether the list was already empty or not. So with that in mind, we can figure out a general strategy. Using *concatenate* we want to repeatedly append new bits to a string which represents the entire input. We can simply do this by looping the output of the *concatenate* back into one of its inputs (and we initialise this to an empty list, by clearing a `{0}` with *isEmpty?*). The question is how we can terminate this process. In addition to appending the current bit we will also *prepend* a 0 or 1 indicating whether we've reached EOF. If we send our string through *isZero?*, it will get rid of that bit again, but let us distinguish the end of the stream, in which case we simply let the thread leave the edge of the grid (which causes Ziim to print the thread's contents to STDOUT and terminate the program). Whether we've reached EOF or not can be determined by using *isEmpty?* on a copy of the input. Here is the diagram I promised: ``` +----------------------------+ {0} --> isEmpty --> label <--+ | | n | | v | v | {0} --> label --> read --> split --> split ------------------> concat | | | | n v y | | inv --> label --> concat <-- isEmpty --> concat <-- label <-- {0} | | ^ ^ | | ^ | | | | v v | | | {0} +------- split ---> label <--- split -------+ | | | | | +-------------> concat <------------+ | | | y v | print and terminate <-- isZero --------------------+ ``` Some notes about where to start reading: * The `{0}` in the top left corner is the initial trigger which starts the input loop. * The `{0}` towards the top right corner is immediately cleared to an empty list an represents the initial string which we'll gradually fill with the input. * The other two `{0}`s are fed into a "producer" loop (one inverted, one not), to give us an unlimited supply of `0`s and `1`s which we need to prepend to the string. [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes This used to be 3 bytes (see below), but that version no long works since the latest update of the language. As I never intentionally introduced the error that version made use of, I decided not to count it. --- An error-free solution (i.e. one which works with the fixed interpreter) turns out to be much trickier. I've had some trouble squeezing it into a 2x2 grid, but I found one solution now, although I need the full **7 bytes**: ``` <)@,;.( ``` After unfolding, we get: [![enter image description here](https://i.stack.imgur.com/HsRLD.png)](https://i.stack.imgur.com/HsRLD.png) Since the initial memory edge is 0, the `<` unconditionally deflects the instruction pointer into the North-East diagonal, where it wraps to the the grey path. The `.` is a no-op. Now `,` reads a byte, `)` increments it such that valid bytes (including null bytes) are positive and EOF is 0. So on EOF, the IP wraps to red path, where `@` terminates the program. But if we still read a byte, then the IP wraps to the green path is instead where `(` decrements the edge to the original value, before `;` prints it to STDOUT. The IP now wraps unconditionally back to the grey path, repeating the process. --- After writing [a brute force script](https://codegolf.stackexchange.com/a/62812/8478) for my Truth Machine answer, I set it to find an error-free **6-byte** solution for the cat program as well. Astonishingly, it did find one - yes, exactly one solution in all possible 6-byte Hexagony programs. After the 50 solutions from the truth machine, that was quite surprising. Here is the code: ``` ~/;,@~ ``` Unfolding: [![enter image description here](https://i.stack.imgur.com/pjs2D.png)](https://i.stack.imgur.com/pjs2D.png) The use of `~` (unary negation) instead of `()` is interesting, because a) it's a no-op on zero, b) it swaps the sides of the branch, c) in some codes a single `~` might be used twice to undo the operation with itself. So here is what's going on: The first time (purple path) we pass through `~` it's a no-op. The `/` reflects the IP into the North-West diagonal. The grey path now reads a character and multiplies its character code by `-1`. This turns the EOF (`-1`) into a truthy (positive) value and all valid characters into falsy (non-positive) values. In the case of EOF, the IP takes the red path and the code terminates. In the case of a valid character, the IP takes the green path, where `~` undoes negation and `;` prints the character. Repeat. --- Finally, here is the 3-byte version which used to work in the original version Hexagony interpreter. ``` ,;& ``` Like the Labyrinth answer, this terminates with an error if the input stream is finite. After unfolding the code, it corresponds to the following hex grid: [![enter image description here](https://i.stack.imgur.com/xNuWk.png)](https://i.stack.imgur.com/xNuWk.png) The `.` are no-ops. Execution starts on the purple path. `,` reads a byte, `;` writes a byte. Then execution continues on the salmon(ish?) path. We need the `&` to reset the current memory edge to zero, such that the IP jumps back to the purple row when hitting the corner at the end of the second row. Once `,` hits EOF it will return `-1`, which causes an error when `;` is trying to print it. --- Diagrams generated with [Timwi](https://codegolf.stackexchange.com/users/668/timwi)'s amazing [HexagonyColorer](https://github.com/Timwi/HexagonyColorer). [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 0 bytes TeaScript is a concise golfing language compiled to JavaScript ``` ``` In a recent update the input is implicitly added as the first property. [Try it online](http://vihanserver.tk/p/TeaScript/?code=x&input=foobar%0Appcg%0Ahello%20world) --- ### Alternatively, 1 byte ``` x ``` `x` contains the input in TeaScript. Output is implicit [Answer] ## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 44 bytes ``` #{<{,+?+}_+{-?>}<? _}>?>+<<<{>?_}>>.<+<+{<{? ``` I originally created this language for [Create a programming language that only appears to be unusable](https://codegolf.stackexchange.com/a/63121/8478). It turns out to be a very nice exercise to golf simple problems in it though. **The Basics:** Each of the two lines defines a Brainfuck-like program which operates on the other program's source code - the first program is called Brian and the second is called Chuck. Only Brian can read and only Chuck can write. Instead of Brainfuck's loops you have `?` which passes control to the other program (and the roles of instruction pointer and tape head change as well). An addition to Brainfuck is `{` and `}` which scan the tape for the first non-zero cell (or the left end). Also, `_` are replaced with null bytes. While I don't think this is optimal yet, I'm quite happy with this solution. My first attempt was 84 bytes, and after several golfing sessions with Sp3000 (and taking some inspiration from his attempts), I managed to get it slowly down to 44, a few bytes at a time. Especially the brilliant `+}+` trick was his idea (see below). ### Explanation Input is read into the first cell on Chuck's tape, then painstakingly copied to the end of Brian's tape, where it's printed. By copying it to the end, we can save bytes on setting the previous character to zero. The `#` is just a placeholder, because switching control does not execute the cell we switched on. `{<{` ensures that the tape head is on Chuck's first cell. `,` reads a byte from STDIN or `-1` if we hit EOF. So we increment that with `+` to make it zero for EOF and non-zero otherwise. Let's assume for now we're not at EOF yet. So the cell is positive and `?` will switch control to Chuck. `}>` moves the tape head (on Brian) to the `+` the `_` and `?` passes control back to Brian. `{-` now decrements the first cell on Chuck. If it's not zero yet, we pass control to Chuck again with `?`. This time `}>` moves the tape head on Brian two cells of the right of the last non-zero cell. Initially that's here: ``` #{<{,+?+}_+{-?>}<?__ ^ ``` But later on, we'll already have some characters there. For instance, if we've already read and printed `abc`, then it would look like this: ``` #{<{,+?+}_+{-?>}<?11a11b11c__ ^ ``` Where the `1`s are actually 1-bytes (we'll see what that's about later). This cell will always be zero, so this time `?` *won't* change control. `>` moves yet another cell to the right and `+` increments that cell. This is why the first character in the input ends up three cells to the right of the `?` (and each subsequent one three cells further right). `<<<` moves back to the last character in that list (or the `?` if it's the first character), and `{>` goes back to the `+` on Brian's tape to repeat the loop, which slowly transfers the input cell onto the end of Brian's tape. Once that input cell is empty the `?` after `{-` will not switch control any more. Then `>}<` moves the tape head on Chuck to the `_` and switches control such that Chuck's second half is executed instead. `}>>` moves to the cell we've now written past the end of Brian's tape, which is the byte we've read from STDIN, so we print it back with `.`. In order for `}` to run past this new character on the tape we need to close the gap of two null bytes, so we increment them to `1` with `<+<+` (so that's why there are the 1-bytes between the actual characters on the final tape). Finally `{<{` moves back to the beginning of Brian's tape and `?` starts everything from the beginning. You might wonder what happens if the character we read was a null-byte. In that case the newly written cell would itself be zero, but since it's at the end of Brian's tape and we don't care *where* that end is, we can simply ignore that. That means if the input was `ab\0de`, then Brian's tape would actually end up looking like: ``` #{<{,+?+}_+{-?>}<?11a11b1111d11e ``` Finally, once we hit EOF that first `?` on Brian's tape will be a no-op. At this point we terminate the program. The naive solution would be to move to the end of Chuck's tape and switch control, such that the program termiantes: `>}>}<?`. This is where Sp3000's really clever idea saves three bytes: `+` turns Chuck's first cell into `1`. That means `}` has a starting point and finds the `_` in the middle of Chuck's tape. Instead of skipping past it, we simply close the gap by turning it into a `1` with `+` as well. Now let's see what the rest of Brian's code happens to do with this modified Chuck... `{` goes back to Chuck's first cell as usual, and `-` turns it back into a null-byte. That means that `?` is a no-op. But now `>}<`, which usually moved the tape head to the middle of Chuck's tape, moves right past it to the end of Chuck's tape and `?` then passes control to Chuck, terminating the code. It's nice when things just work out... :) [Answer] # Haskell, 16 bytes ``` main=interact id ``` `interact` reads the input, passes it to the function given as its argument and prints the result it receives. `id` is the identity function, i.e. it returns its input unchanged. Thanks to Haskell's laziness `interact` can work with infinite input. [Answer] ## sh + binutils, ~~3~~ 2 bytes ``` dd ``` Well, not quite as obvious. From @Random832 ## Original: ``` cat ``` The painfully obvious... :D [Answer] # [Motorola MC14500B Machine Code](https://en.wikipedia.org/wiki/Motorola_MC14500B), 1.5 bytes Written in hexadecimal: ``` 18F ``` Written in binary: ``` 0001 1000 1111 ``` --- ### Explanation ``` 1 Read from I/O pin 8 Output to I/O pin F Loop back to start ``` The opcodes are 4 bits each. [Answer] # [Funciton](http://esolangs.org/wiki/Funciton), 16 bytes ``` ╔═╗ ╚╤╝ ``` (Encoded as UTF-16 with a BOM) ## Explanation The box returns the contents of STDIN. The loose end outputs it. [Answer] # [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 41 bytes ``` Take Northern Line to Mornington Crescent ``` I have no idea whether Mornington Crescent can handle null bytes, and all input is read before the program starts, as that is the nature of the language. [Answer] # Brainfuck, 5 bytes ``` ,[.,] ``` Equivalent to the pseudocode: ``` x = getchar() while x != EOF: putchar(x) x = getchar() ``` This handles infinite streams, but treats null bytes as EOF. Whether or not BF *can* handle null bytes correctly varies from implementation to implementation, but this assumes the most common approach. [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), 2 bytes ``` ,. ``` If the stream is finite, this will terminate with an error, but all the output produce by the error goes to STDERR, so the standard output stream is correct. As in Brainfuck `,` reads a byte (pushing it onto Labyrinth's main stack) and `.` writes a byte (popping it from Labyrinth's main stack). The reason this loops is that both `,` and `.` are "dead ends" in the (very trivial) maze represented by the source code, such that the instruction pointer simply turns around on the spot and moves back to the other command. When we hit EOF `,` pushes `-1` instead and `.` throws an error because `-1` is not a valid character code. This might actually change in the future, but I haven't decided on this yet. --- For reference, we can solve this without an error in **6 bytes** as follows ``` ,)@ .( ``` Here, the `)` increments the byte we read, which gives `0` at EOF and something positive otherwise. If the value is `0`, the IP moves straight on, hitting the `@` which terminates the program. If the value was positive, the IP will instead take a right-turn towards the `(` which decrements the top of the stack back to its original value. The IP is now in a corner and will simply keep making right turns, printing with `.`, reading a new byte with `.`, before it hits the fork at `)` once again. [Answer] # X86 assembly, 70 bytes Disassembly with `objdump`: ``` 00000000 <.data>: 0: 66 83 ec 01 sub sp,0x1 4: 66 b8 03 00 mov ax,0x3 8: 00 00 add BYTE PTR [eax],al a: 66 31 db xor bx,bx d: 66 67 8d 4c 24 lea cx,[si+0x24] 12: ff 66 ba jmp DWORD PTR [esi-0x46] 15: 01 00 add DWORD PTR [eax],eax 17: 00 00 add BYTE PTR [eax],al 19: cd 80 int 0x80 1b: 66 48 dec ax 1d: 78 1c js 0x3b 1f: 66 b8 04 00 mov ax,0x4 23: 00 00 add BYTE PTR [eax],al 25: 66 bb 01 00 mov bx,0x1 29: 00 00 add BYTE PTR [eax],al 2b: 66 67 8d 4c 24 lea cx,[si+0x24] 30: ff 66 ba jmp DWORD PTR [esi-0x46] 33: 01 00 add DWORD PTR [eax],eax 35: 00 00 add BYTE PTR [eax],al 37: cd 80 int 0x80 39: eb c9 jmp 0x4 3b: 66 b8 01 00 mov ax,0x1 3f: 00 00 add BYTE PTR [eax],al 41: 66 31 db xor bx,bx 44: cd 80 int 0x80 ``` The source: ``` sub esp, 1 t: mov eax,3 xor ebx,ebx lea ecx,[esp-1] mov edx,1 int 0x80 dec eax js e mov eax,4 mov ebx,1 lea ecx,[esp-1] mov edx,1 int 0x80 jmp t e: mov eax,1 xor ebx,ebx int 0x80 ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 7 bytes ``` i:0(?;o ``` Try it [here](http://fishlanguage.com/playground/u7ttRxRqTCymDDNe6). Explanation: ``` i:0(?;o i Take a character from input, pushing -1 if the input is empty :0( Check if the input is less than 0, pushing 1 if true, 0 if false ?; Pop a value of the top of the stack, ending the program if the value is non-zero o Otherwise, output then loop around to the left and repeat ``` If you want it to keep going until you give it more input, replace the `;` with `!`. [Answer] # [Universal Lambda](https://esolangs.org/wiki/Universal_Lambda), 1 byte ``` ! ``` A Universal Lambda program is an encoding of a lambda term in binary, chopped into chunks of 8 bits, padding incomplete chunks with *any* bits, converted to a byte stream. The bits are translated into a lambda term as follows: * `00` introduces a lambda abstraction. * `01` represents an application of two subsequent terms. * `111..10`, with *n* repetitions of the bit `1`, refers to the variable of the *n*th parent lambda; i.e. it is a [De Bruijn index](https://en.wikipedia.org/wiki/De_Bruijn_index) in unary. By this conversion, `0010` is the identity function `λa.a`, which means any single-byte program of the form `0010xxxx` is a `cat` program. [Answer] # C, 40 bytes ``` main(i){while(i=~getchar())putchar(~i);} ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~6~~ 5 bytes *Now handles null bytes!* ``` @_i?o ``` Cubix is a 2-dimensional, stack-based esolang. Cubix is different from other 2D langs in that the source code is wrapped around the outside of a cube. [Test it online!](https://ethproductions.github.io/cubix) Note: there's a 50 ms delay between iterations. ## Explanation The first thing the interpreter does is figure out the smallest cube that the code will fit onto. In this case, the edge-length is 1. Then the code is padded with no-ops `.` until all six sides are filled. Whitespace is removed before processing, so this code is identical to the above: ``` @ _ i ? o . ``` Now the code is run. The IP (instruction pointer) starts out on the far left face, pointing east. The first char the IP encounters is `_`, which is a mirror that turns the IP around if it's facing north or south; it's currently facing east, so this does nothing. Next is `i`, which inputs a byte from STDIN. `?` turns the IP left if the top item is negative, or right if it's positive. There are three possible paths here: * If the inputted byte is -1 (EOF), the IP turns left and hits `@`, which terminates the program. * If the inputted byte is 0 (null byte), the IP simply continues straight, outputting the byte with `o`. * Otherwise, the IP turns right, travels across the bottom face and hits the mirror `_`. This turns it around, sending it back to the `?`, which turns it right again and outputs the byte. I think this program is optimal. Before Cubix could handle null bytes (EOF was 0, not -1), this program worked for everything but null bytes: ``` .i!@o ``` --- I've written a [brute-forcer](https://jsfiddle.net/09z5sr3o/3/) to find all 5-byte cat programs. Though it takes ~5 minutes to finish, the latest version has found 5 programs: ``` @_i?o (works as expected) @i?o_ (works in exactly the same way as the above) iW?@o (works as expected) ?i^o@ (false positive; prints U+FFFF forever on empty input) ?iWo@ (works as expected) ``` [Answer] ## PowerShell, ~~88~~ ~~41~~ 30 Bytes ``` $input;write-host(read-host)-n ``` EDIT -- forgot that I can use the `$input` automatic variable for pipeline input ... EDIT2 -- don't need to test for existence of `$input` Yeah, so ... STDIN in PowerShell is ... weird, shall we say. With the assumption that we need to accept input from *all* types of STDIN, this is one possible answer to this catalogue, and I'm sure there are others.1 Pipeline input in PowerShell doesn't work as you'd think, though. Since piping in PowerShell is a function of the language, and not a function of the environment/shell (and PowerShell isn't really *solely* a language anyway), there are some quirks to behavior. For starters, and most relevant to this entry, the pipe isn't evaluated instantaneously (most of the time). Meaning, if we have `command1 | command2 | command3` in our shell, `command2` will not take input or start processing until `command1` completes ... *unless* you encapsulate your `command1` with a `ForEach-Object` ... which is *different* than `ForEach`. (even though `ForEach` is an alias for `ForEach-Object`, but that's a separate issue, since I'm talking `ForEach` as the statement, not alias) This would mean that something like `yes | .\simple-cat-program.ps1` (even though `yes` doesn't really exist, but whatever) wouldn't work because `yes` would never complete. If we could do `ForEach-Object -InputObject(yes) | .\simple-cat-program.ps1` that should (in theory) work. [Getting to Know ForEach and ForEach-Object](http://blogs.technet.com/b/heyscriptingguy/archive/2014/07/08/getting-to-know-foreach-and-foreach-object.aspx) on the Microsoft "Hey, Scripting Guy!" blog. So, all those paragraphs are explaining why `if($input){$input}` exists. We take an input parameter that's specially created automatically if pipeline input is present, test if it exists, and if so, output it. Then, we take input from the user `(read-host)` via what's essentially a separate STDIN stream, and `write-host` it back out, with the `-n` flag (short for `-NoNewLine`). Note that this does not support arbitrary length input, as `read-host` will only complete when a linefeed is entered (technically when the user presses "Enter", but functionally equivalent). Phew. 1But there are other options: For example, if we were concerned with *only* pipeline input, and we didn't require a full program, you could do something like `| $_` which would just output whatever was input. (In general, that's somewhat redundant, since PowerShell has an implicit output of things "left behind" after calculations, but that's an aside.) If we're concerned with only interactive user input, we could use just `write-host(read-host)-n`. ~~Additionally, this function has the ~~quirk~~ feature of accepting command-line input, for example `.\simple-cat-program.ps1 "test"` would populate (and then output) the `$a` variable.~~ [Answer] # [MarioLANG](http://esolangs.org/wiki/MarioLANG#Examples), 11 bytes ``` ,< ." >! =# ``` I'm not entirely sure this is optimal, but it's the shortest I found. This supports infinite streams and will terminate with an error upon reaching EOF (at least the Ruby reference implementation does). There's another version of this which turns Mario into a ninja who can double jump: ``` ,< .^ >^ == ``` In either case, Mario starts falling down the left column, where `,` reads a byte and `.` writes a byte (which throws an error at EOF because `,` doesn't return a valid character). `>` ensures that Mario walks to the right (`=` is just a ground for him to walk on). Then he moves up, either via a double jump with `^` or via an elevator (the `"` and `#` pair) before the `<` tells him to move back to the left column. [Answer] ## [INTERCALL](https://github.com/theksp25/INTERCALL), 133 bytes wat ``` INTERCALL IS A ANTIGOLFING LANGUAGE SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL THE PROGRAM STARTS HERE: READ PRINT GOTO I ``` [Answer] # [rs](https://github.com/kirbyfan64/rs), 0 bytes ``` ``` Seriously. rs just prints whatever it gets if the given script is completely empty. [Answer] # Vitsy, 2 bytes ``` zZ ``` `z` gets all of the input stack and pushes it to the active program stack. `Z` prints out all of the active stack to STDOUT. Alternate method: ``` I\il\O I\ Repeat the next character for input stack's length. i Grab an item from the input. l\ Repeat the next character for the currently active program stack's length. O Output the top item of the stack as a character. ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 0 bytes [Try it online!](http://v.tryitonline.net/#code=&input=VGhlIGVtcHR5IHByb2dyYW0gcHJpbnRzIGl0cyBpbnB1dC4g) V's idea of "memory" is just a gigantic 2D array of characters. Before any program is ran, all input it loaded into this array (known as "The Buffer"). Then, at the end of any program, all text in the buffer is printed. In other words, the empty program *is* a cat program. [Answer] ## [Half-Broken Car in Heavy Traffic](http://esolangs.org/wiki/Half-Broken_Car_in_Heavy_Traffic), 9 + 3 = 12 bytes ``` #< o^< v ``` Half-Broken Car in Heavy Traffic (HBCHT) takes input as command line args, so run like ``` py -3 hbcht cat.hbc -s "candy corn" ``` Note that the +3 is for the `-s` flag, which outputs as chars. Also, HBCHT doesn't seem handle NULs, as all zeroes are dropped from the output (e.g. `97 0 98` is output as two chars `ab`). ### Explanation In HBCHT, your car starts at the `o` and your goal is the exit `#`. `^>v<` direct the car's movement, while simultaneously modifying a BF-like tape (`^>v<` translate to `+>-<`). However, as the language name suggests, your car can only turn right – any attempts to turn left are ignored completely (including their memory effects). Note that this is only for turning – your car is perfectly capable of driving forward/reversing direction. Other interesting parts about HBCHT are that your car's initial direction is randomised, and the grid is toroidal. Thus we just need the car to make it to the exit without modifying the tape for all four initial directions: * Up and down are straightforward, heading directly to the exit. * For left, we wrap and execute `<` and increment with `^`. We can't turn left at the next `<` so we wrap and decrement with `v`, negating out previous increment. Since we're heading downwards now we can turn right at the `<` and exit, having moved the pointer twice and modifying no cell values. * For right, we do the same thing as left but skip the first `^` since we can't turn left. --- **Edit**: It turns out that the HBCHT interpreter does let you execute just a single path via a command line flag, e.g. ``` py -3 hbcht -d left cat.hbc ``` However, not only is the flag too expensive for this particular question (at least 5 bytes for `" -d u"`), it seems that all paths still need to be able to make it to the exit for the code to execute. [Answer] # [Seed](https://github.com/TryItOnline/seed), ~~3883~~ ~~3864~~ 10 bytes ``` 4 35578594 ``` [Try it online!](https://tio.run/##K05NTfn/30TB2NTU3MLU0uT//8SkZAA "Seed – Try It Online") This is one of the stupidest things I have ever done. [Answer] # GolfScript, 3 bytes ``` :n; ``` The empty program echoes standard input. The language cannot possibly handle infinite streams. However, it appends a newline, as @Dennis mentioned. It does so by wrapping the whole stack in an array and calling `puts`, which is defined as `print n print`, where `n` is a newline. However, we can redefine `n` to be STDIN, and then empty the stack, which is precisely what `:n;` does. [Answer] ## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 15 chars ``` (:vGsP10wRsp;bD ``` Taken [directly from Snowman's `examples` directory](https://github.com/KeyboardFire/snowman-lang/blob/master/examples/cat.snowman). Reads a line, prints a line, reads a line, prints a line... Note that due to an implementation detail, when STDIN is empty, `vg` will return the same thing as it would for an empty line. Therefore, this will repeatedly print newlines in an infinite loop once STDIN is closed. This may be fixed in a future version. Explanation of the code: ``` ( // set two variables (a and f) to active—this is all we need :...;bD // a "do-loop" which continues looping as long as its "return value" // is truthy vGsP // read a line, print the line 10wRsp // print a newline—"print" is called in nonconsuming mode; therefore, // that same newline will actually end up being the "return value" from // the do-loop, causing it to loop infinitely ``` [Answer] ## [Minkolang](https://github.com/elendiastarman/Minkolang), 5 bytes ``` od?.O ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=od%3F%2EO&input=Hello%20world!) ### Explanation `o` reads in a character from input and pushes its ASCII code onto the stack (`0` if the input is empty). `d` then duplicates the top of stack (the character that was just read in). `?` is a conditional trampoline, which jumps the next instruction of the top of stack is not `0`. If the input was empty, then the `.` is not jumped and the program halts. Otherwise, `O` outputs the top of stack as a character. The toroidal nature of Minkolang means that this loops around to the beginning. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 0 bytes ``` ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIiLCIiLCIxIl0=) Implicitly inputs then implicitly outputs. Stretching the rules a *teeny* bit. Specifically the following rule: > > The only exception being if your language absolutely always prints a trailing newline after execution. > > > In Vyxal, "printing after execution" (implicit, not explicit printing) always prints with a newline. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~50~~ 38 bytes ``` [“€¬((a=IO.‚Ø 9)!=:eof)€· IO.‡í€…„–“.E ``` [Try it online](https://tio.run/##yy9OTMpM/f8/@lHDnEdNaw6t0dBItPX013vUMOvwDAVLTUVbq9T8NE2Q1HYFsPjCw2uBvEcNyx41zHvUMBmoT8/1/3@P1JycfB2F8PyinBRFLiCoU3RQVlGNU9PS0IzX5kowNDI2MTUzt7A00LXlio6NsVbX0dPnqq6tsVKysbPn4goMdw0KiQz19A9wDHZxc/fw8vaJinAOc/Lz5XJ0cnZxBQp5AsV8/fwDAoOCQ0LDwiMio7i4CstTi0oqSzPzCxKLU9LSM7Kyc6oqksuS8nK5EpOSU1KBQplAsdy8/ILCouKS0rLyisoqAA "05AB1E – Try It Online") or [test an infinite stream](https://tio.run/##S0oszvifnFhiY@Pq72YXb12ZWlxTUqSgm6IQE5NXo59fUKKfX5yYlJkKpRTi/0c/apjzqGnNoTUaGom2nv56jxpmHZ6hYKmpaGuVmp@mCZLargAWX3h4LZD3qGHZo4Z5jxomA/Xpuf4H2vMfAA "Bash – Try It Online"). # Explanation This is probably the first *real* 05AB1E cat posted here. While my previous answer (`?`) mostly worked... > > If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. > > > And while there seems to be no way of doing this in 05AB1E, making `?` the shortest possible answer, there is one not very commonly used command that does the trick. `.E` pops a string and runs it as an Elixir program. In this case, we use the following Elixir code: ``` a = IO.read(x) if a != :eof do IO.write(a) end ``` …where `x` is the number of bytes to read each time — the greater it is, the faster the program runs. It can be anything but `:all`, as that would be equivalent to my previous submission, invalidating it. We can golf this down to: ``` if((a=IO.read x)!=:eof)do IO.write a end ``` By now, you might've realized that this program only ever outputs the first `x` bytes of input. But running the Elixir code isn't the only thing the program does. It runs it over and over in an infinite loop (`[`)! The weird symbols you see in the 05AB1E program are dictionary compression – compressing English words or other common letter combinations into just two bytes each. By substituting in `9` for `x` in the Elixir program (making the program as fast as it can be while not raising the bytecount), we get the final program! ]
[Question] [ An 'Even string' is any string where the [parity](https://en.wikipedia.org/wiki/Parity_(mathematics)) of the ASCII values of the characters is always alternating. For example, the string `EvenSt-ring$!` is an even-string because the ASCII values of the characters are: ``` 69 118 101 110 83 116 45 114 105 110 103 36 33 ``` And the parities of these numbers are: ``` Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd ``` Which is alternating the whole way. However, a string like `Hello world!` is *not* an even string because the ASCII values are: ``` 72 101 108 108 111 32 87 111 114 108 100 33 ``` And the parities are: ``` Even Odd Even Even Odd Even Odd Odd Even Even Even Odd ``` Which is clearly not always alternating. # The challenge You must write either a full program or a function that accepts a string for input and outputs a [truthy](http://meta.codegolf.stackexchange.com/q/2190/31716) value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (the 32-127 range). You do *not* have to handle empty input. # Examples Here are some examples of even strings: ``` #define EvenSt-ring$! long abcdABCD 3.141 ~ 0123456789 C ode - g ol!f HatchingLobstersVexinglyPopulateJuvenileFoxglove ``` And all of these examples are not even strings: ``` Hello World PPCG 3.1415 babbage Code-golf Standard loopholes apply Shortest answer in bytes wins Happy golfing! ``` You may also use [this ungolfed solution](http://julia.tryitonline.net/#code=c3RyID0gcmVhZGxpbmUoU1RESU4pCmV2ZW4gPSB0cnVlCnBhcml0eSA9IEludChzdHJbMV0pICUgMgpmb3IgYyBpbiBzdHJbMjplbmRdCiAgbmV3UGFyaXR5ID0gSW50KGMpICUgMgogIGlmIG5ld1Bhcml0eSA9PSBwYXJpdHkKICAgIGV2ZW4gPSBmYWxzZQogIGVuZAogIHBhcml0eSA9IG5ld1Bhcml0eQplbmQKcHJpbnQoZXZlbik&input=MDEyMzQ1Njc4OQ) to test any strings if you're curious about a certain test-case. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~4~~ 3 bytes Thanks to *Emigna* for saving a byte and thanks to *Luis Mendo* for fixing some bugs. Code: ``` doA ``` Explanation: ``` d # Difference between the characters o # Mod 2 A # Matlab style all ``` [Try it online!](http://matl.tryitonline.net/#code=ZG9B&input=J0hhdGNoaW5nTG9ic3RlcnNWZXhpbmdseVBvcHVsYXRlSnV2ZW5pbGVGb3hnbG92ZSc) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes Saved 1 byte thanks to *Adnan*. ``` Ç¥ÉP ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4fCpcOJUA&input=QyBvZGUgLSBnIG9sIWY) **Explanation** ``` Ç # convert to ascii values ¥ # compute delta's É # mod by 2 P # product ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~7~~ ~~5~~ 4 bytes ``` OIḂẠ ``` Saved 2 bytes using the deltas idea from @[Steven H.](https://codegolf.stackexchange.com/a/96063/6710) Saved 1 byte thanks to @[Lynn](https://codegolf.stackexchange.com/users/3852/lynn). [Try it online!](http://jelly.tryitonline.net/#code=T0nhuILhuqA&input=&args=RXZlblN0LXJpbmckIQ) or [Verify all test cases.](http://jelly.tryitonline.net/#code=T0nhuILhuqAKw4figqw&input=&args=JyNkZWZpbmUnLCdFdmVuU3QtcmluZyQhJywnbG9uZycsJ2FiY2RBQkNEJywnMy4xNDEnLCd-JywnMDEyMzQ1Njc4OScsJ0Mgb2RlIC0gZyBvbCFmJywnSGVsbG8gV29ybGQnLCdQUENHJywnMy4xNDE1JywnYmFiYmFnZScsJ0NvZGUtZ29sZicsJ1N0YW5kYXJkIGxvb3Bob2xlcyBhcHBseScsJ1Nob3J0ZXN0IGFuc3dlciBpbiBieXRlcyB3aW5zJywnSGFwcHkgZ29sZmluZyEn) ## Explanation ``` OIḂẠ Input: string S O Ordinal I Increments Ḃ Mod 2 Ạ All, 0 if it contains a falsey value, else 1 ``` [Answer] # Python 2, 54 Bytes ``` lambda s:all((ord(x)-ord(y))%2for x,y in zip(s,s[1:])) ``` [Answer] # Mathematica, ~~50~~ 44 bytes *The current version is basically all Martin Ender's virtuosity.* ``` Differences@ToCharacterCode@#~Mod~2~FreeQ~0& ``` Returns `True` or `False`. Nothing too clever: takes the mod-2 sum of each pair of consecutive ASCII codes, and checks that 0 is never obtained. Old version: ``` Union@Mod[Most[a=ToCharacterCode@#]+Rest@a,2]=={1}& ``` [Answer] # JavaScript (ES6), ~~60~~ ~~50~~ 46 bytes ``` s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2) ``` I tried recursion, but at 51 bytes, it doesn't seem to be quite worth it: ``` f=([c,...s],p=2)=>c?p-(p=c.charCodeAt()%2)&f(s,p):1 ``` ### Test snippet ``` f=s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2) ``` ``` <input id=I value="Evenst-ring"><button onclick="console.log(f(I.value))">Run</button> ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~138~~ ~~114~~ ~~112~~ 84 + 3 = 87 bytes Thanks to [@Riley](https://codegolf.stackexchange.com/users/57100/riley) for help golfing. This program treats empty input as a noneven string. ``` {({}(())){({}[()]<(()[{}])>)}{}(({})<>[[]{}]()){{}(<>)}{}({}<>)<>}<>(([])[()]){<>}{} ``` [Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fSgoKSkpeyh7fVsoKV08KCgpW3t9XSk-KX17fSgoe30pPD5bW117fV0oKSl7e30oPD4pfXt9KHt9PD4pPD59PD4oKFtdKVsoKV0pezw-fXt9&input=RXZlblN0LXJpbmcgQyBvZGUgLSBnIG9sIWY&args=LWE) ## Explanation (outdated) Shifts the input from the left stack to the right while modding by 2. Finds the difference between each adjacent character until all have been checked or one of the differences is equal to zero (which would only occur in a noneven string). If the loop terminated due to a noneven string then switch back to the left stack and pop the value remaining on it. Otherwise, stay on the right stack and pop the zero above the 1 remaining on the stack. [Answer] ## R, 41 35 bytes EDIT: Saved a few bytes thanks to @JDL by using `diff` instead of `rle`. ``` all(diff(utf8ToInt(readline())%%2)) ``` --- ``` all(rle(utf8ToInt(readline())%%2)[[1]]<2) ``` **Explanation** 1. `readline()` read input. 2. `utf8ToInt()%%2` convert to ascii values and mod 2 (store as R-vector) 3. `all(rle()==1)` run length encoding of to find runs. All runs should be equal to one or smaller than 2 since no runs cant be negative or 0 (saves one byte instead of `==`). [Answer] # Pyth ([fork](https://github.com/Steven-Hewitt/pyth)), 9 bytes ``` .A%R2.+CM ``` No Try It Online link because the fork does not have its own version in the online interpreters. Explanation: ``` CM Map characters to their ASCII codes. .+ Get deltas (differences between consecutive character codes) %R2 Take the modulo of each base 2 .A all are truthy (all deltas are odd) ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 17 bytes ``` @c:{:2%}a@b:{l1}a ``` [Try it online!](http://brachylog.tryitonline.net/#code=QGM6ezoyJX1hQGI6e2wxfWE&input=IkV2ZW5TdC1yaW5nJCEi) ### Explanation ``` @c Input to a list of char codes :{:2%}a Apply X mod 2 for each X in the list of char codes @b Split the list into a list of lists where each sublist elements are the same, e.g. turn [1,0,1,1,0,0] into [[1],[0],[1,1],[0,0]] :{l1}a The length of each sublist must be 1 ``` [Answer] # Java 8, ~~77~~ ~~76~~ ~~72~~ 57 bytes ``` a->{int i=2,b=1;for(int c:a)b=i==(i=c%2)?0:b;return b>0;} ``` -4 bytes thanks to *@Geobits*. **Explanation:** [Try it online.](https://tio.run/##nZTfb9MwEMff@1dcC0iJWLK22/jRKEMjY1SITZWK4AHxcHacxMPzRbbTLZrKv16cbm8DJPxi6ez7fO9O95WvcYMJtUJflz93XKG1cIlS348ApHbCVMgFXA0hACNSAjXwiDdovv8AjDP/sB35wzp0ksMVaMhhh8npvcdB5vMDls@yikw0xHyBMctlnkcy5y/m8bvpgmVGuM5oYKfTbLvLBrG2Y8qLPWpuSJZw45uK1s5IXe8LP3R0eAhfTOeafrEP17114ialzqWtz3SRTnk0eVaKSmoxSR0Vvu8zY7CP4hhewuRgsp/gb@SHjdBrlwxFn48DeEW6DsCQ8fLsfXEegB6ls@NZAPcrgJnO5kfHJ69ev3kbABdApYAEaiA1rv5LQOkHiSU63vjVfCbmE4z9Ku58pPoVtZ1CJz51fn1SiQu6qxVtnhjgUd576AKVFf/00FIoRfCNjCoDhl2tio@hyzwJABkyhnWI4wu/laQmVQWwa4e6RFOCImob/1VYwLZVfYhUQ8YJ6wC1vRXGf0XAen8Bt1LbAL2lb6SHYS7vkPEfjbAdbXe/AQ) ``` a->{ // Method with character-array parameter and boolean return-type int i=2, // Integer `i`, starting at any integer not 0 or 1 b=1; // Flag-integer `b`, starting at 1 for(int c:a) // Loop over the input-array b=i==(i=c%2)? // If two adjacent characters were both odd or even: 0 // Set the flag-integer `b` to 0 : // Else: b; // The flag-integer `b` remains the same return b>0;} // Return if the flag-integer `b` is still 1 ``` [Answer] # Brain-Flak 155 151 141 121 Includes +3 for -a Saved 30 bytes thanks to [1000000000](https://codegolf.stackexchange.com/a/96107/57100) ``` {({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>{({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<>{{}}([]<(())>){((<{}{}>))}{} ``` Output: **truthy**: 1 **falsy**: 0 on top of the stack [Try it online! (truthy)](http://brain-flak.tryitonline.net/#code=eyh7fSgoKSkpeyh7fVsoKV08KCgpW3t9XSk-KX17fSh7fSgpPD4pPD59PD57KHt9Wyh7fSldPCgoKSk-KXsoKDx7fXt9PikpfXt9KHt9WygpXTw-KTw-fTw-e3t9fShbXTwoKCkpPil7KCg8e317fT4pKX17fQ&input=QyBvZGUgLSBnIG9sIWY&args=LWE) [Try it online! (falsy)](http://brain-flak.tryitonline.net/#code=eyh7fSgoKSkpeyh7fVsoKV08KCgpW3t9XSk-KX17fSh7fSgpPD4pPD59PD57KHt9Wyh7fSldPCgoKSk-KXsoKDx7fXt9PikpfXt9KHt9WygpXTw-KTw-fTw-e3t9fShbXTwoKCkpPil7KCg8e317fT4pKX17fQ&input=Q29kZS1nb2xm&args=LWE) --- Better explanation coming later (if I can remember how it works after a few hours...) ``` #compute ((mod 2) + 1) and put on other stack {({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<> #compare top two (remove top 1) push on other stack (-1 for different 0 for same) {({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<> #remove all of the top -1s {{}} #take the logical not of the stack height ([]<(())>){((<{}{}>))}{} ``` [Answer] # [Starry](https://esolangs.org/wiki/Starry), 85 bytes ``` , + * ` , + + * ' + ' ` + * + + * ' + `. ``` [Try it online!](http://starry.tryitonline.net/#code=ICwgICAgICAgKyAgICAqICAgYCAsICsgICAgICAgICAgICAgICArICogJyArICAnIGAgICAgICAgKyAgICAqICsgICArICogICAnICAgICArICBgLg&input=RXZlblN0LXJpbmcgQyBvZGUgLSBnIG9sIWYK) Note that since a Starry program has no way of telling when an input of arbitrary length ends, this program uses a trailing newline in the input to mark the end of the string. If you get a cryptic error message about and undefined method `ord` for `nil:NilClass` then the input is missing a trailing newline. ## Explanation The basic strategy that the program employs is it reads the characters one by one from input and if they are not a newline (character 10) it mods they ASCII value of the character by 2 and finds the difference between it and the previously read character. If the difference is zero the program terminates and prints `0` (falsey). Otherwise the program loops back and does the process over again. If the program reads a newline it terminates and prints `10` (truthy). ### Annotated Program ``` , Push the first character + Push 2 * Replace the first character and 2 with the first character mod 2 ` Label 3 <--------------------------------------------------------\ , Push the next the character | + Push a duplicate of it | + Push 10 | * Replace the 10 and the duplicate with their difference | ' Pop and if not zero (the read char is not 10) goto label 1 >-\ | + Push a duplicate of the character which must be newline (10) | | ' Pop and goto label 2 >---------------------------------------+-\ | ` Label 1 <----------------------------------------------------/ | | + Push 2 | | * Replace the character and 2 with the character mod 2 | | + Duplicate it ^ | | + Roll the top three items on the stack. The top goes to | | the bottom. The top three items are now | | (from top to bottom) the current character, the previous | | character, the current character (all modded by 2). | | * Replace the current character and previous character | | with their difference | | ' Pop if nonzero goto label 3 >----------------------------------+-/ + Push zero | ` Label 2 <------------------------------------------------------/ . Print out the number on top of the stack 0 if we came by not following the goto label 3 10 if we came by going to label 2 ``` [Answer] ## Perl, 24 + 1 (`-p`) = 25 bytes *-4 bytes thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) !* ``` s/./$&&v1/eg;$_=!/(.)\1/ ``` Needs `-p` flag. Outputs 1 is the string is even, nothing otherwise. For instance : ``` perl -pe 's/./$&&v1/eg;$_=!/(.)\1/' <<< "#define Hello World" ``` *Explanations* : replaces each character by its value mod 2 (so the string contains only 0s and 1s after that). Then search for two following 1 or 0 : if it finds some, then the string isn't even, otherwise it is. [Answer] # J, 15 bytes ``` 0=1#.2=/\2|3&u: ``` ## Usage ``` f =: 0=1#.2=/\2|3&u: f 'C ode - g ol!f' 1 f 'Code-golf' 0 ``` ## Explanation ``` 0=1#.2=/\2|3&u: Input: string S 3&u: Get ordinals of each char 2| Take each modulo 2 2 \ For each pair of values =/ Test if they are equal, 1 if true else 0 1#. Treat the list of integers as base 1 digits and convert to decimal This is equivalent to taking the sum 0= Is it equal to 0, 1 if true else 0, and return ``` [Answer] # Vim, 38 bytes `qqs<C-R>=char2nr(@")%2<CR><Esc>l@qq@q:g/00\|11/d<CR>` Assumes input string in buffer, and empty `"q`. Outputs binary nonsense if true, nothing if false. * `s<C-R>=char2nr(@")%2<CR>`: Replaces a character with 1 if odd, 0 if even. The macro this is in just does this to every character in the line (no matter how long it is). * `:g/00\|11/d<CR>`: Deletes the line if 2 consecutive "bits" have the same value. Faster than a back-reference. Normally, in vimgolf, when you use an expression function inside a macro, you're supposed to do the macro itself on the expression register and use some trickery to tab-complete. That's more difficult this time. I may find a way to shorten that later. [Answer] ## [Retina](http://github.com/mbuettner/retina), 39 bytes Byte count assumes ISO 8859-1 encoding. ``` S_` %{2` $` }T01`p`_p .. Mm`.¶.|^¶$ ^0 ``` Outputs `1` for truthy and `0` for falsy. [Try it online!](http://retina.tryitonline.net/#code=JShHYApTX2AKJXsyYAokYAp9VDAxYHBgX3AKLi4KCk1tYC7Cti58XsK2JApeMA&input=I2RlZmluZQpFdmVuU3QtcmluZyQhCmxvbmcKYWJjZEFCQ0QKMy4xNDEKfgowMTIzNDU2Nzg5CkMgb2RlIC0gZyBvbCFmCkhhdGNoaW5nTG9ic3RlcnNWZXhpbmdseVBvcHVsYXRlSnV2ZW5pbGVGb3hnbG92ZQpIZWxsbyBXb3JsZApQUENHCjMuMTQxNQpiYWJiYWdlCkNvZGUtZ29sZgpTdGFuZGFyZCBsb29waG9sZXMgYXBwbHkKU2hvcnRlc3QgYW5zd2VyIGluIGJ5dGVzIHdpbnMKSGFwcHkgZ29sZmluZyE) (The first line enables a linefeed-separated test suite.) ### Explanation Inspired by a answer of mbomb007's [I recently developed a reasonably short `ord()` implementation](http://chat.stackexchange.com/transcript/message/32786271#32786271) in Retina. This is largely based on that, although I was able to make a few simplifications since I don't need a decimal result in since I only need to support printable ASCII (and I only care about the parity of the result, so ending up with an arbitrary offset is fine, too). **Stage 1: Split** ``` S_` ``` This simply splits the input into its individual characters by splitting it around the empty match and dropping the empty results at the beginning and end with `_`. **Stage 2: Replace** ``` %{2` $` ``` The `%{` tells Retina a) that this stage and the next should be run in a loop until the string stops changing through a full iteration, and that these two stages should be applied to each line (i.e each character) of the input separately. The stage itself is the standard technique for duplicating the first character of the input. We match the empty string (but only look at the first two matches) and insert the prefix of that match. The prefix of the first match (at the beginning of the string) is empty, so this doesn't do anything, and the prefix of the second match is the first character, which is therefore duplicated. **Stage 3: Transliterate** ``` }T01`p`_o ``` `}` indicates the end of the loop. The stage itself is a transliteration. `01` indicates that it should only be applied to the first character of the string. `p` is shorthand for all printable ASCII characters and `_` means "delete". So if we expand this, the transliteration does the following transformation: ``` from: !"#$%... to: _ !"#$... ``` So spaces are deleted and all other characters are decremented. That means, these two stages together will create a character range from space to the given character (because they'll repeatedly duplicate and decrement the first character until it becomes a space at which point the duplication and deletion cancel). The length of this range can be used to determine the parity of the character. **Stage 4: Replace** ``` .. ``` We simply drop all pairs of characters. This clears even-length lines and reduces odd-length lines to a single character (the input character, in fact, but that doesn't really matter). **Stage 5: Match** ``` Mm`.¶.|^¶$ ``` It's easier to find inputs which *aren't* even, so we count the number of matches of either two successive empty lines or two successive non-empty lines. We should get `0` for even inputs and something non-zero otherwise. **Stage 6: Match** ``` ^0 ``` All that's left is to invert the result, which we do by counting the number of matches of this regex, which checks that the input starts with a `0`. This is only possible if the result of the first stage was `0`. [Answer] # Clojure, 59 bytes ``` #(every?(fn[p](odd?(apply + p)))(partition 2 1(map int %))) ``` Generates all sequential pairs from string `n` and checks if every pair sum is odd. If a sequence of ints is considered a reasonable format then it's 50 bytes. ``` #(every?(fn[p](odd?(apply + p)))(partition 2 1 %)) ``` See it online : <https://ideone.com/USeSnk> [Answer] ## Julia, ~~55~~ 53 Bytes ``` f(s)=!ismatch(r"00|11",join(map(x->Int(x)%2,[s...]))) ``` **Explained** Map chars to 0|1 and check if the resulting string contains "00" or "11", which makes the string not alternating. [Answer] ## Python, 52 bytes ``` f=lambda s:s==s[0]or(ord(s[0])-ord(s[1]))%2*f(s[1:]) ``` A recursive function. Produces 1 (or True) for even strings, 0 for odd ones. Multiplies the parity of the difference of the first two characters by the recursive value on the remainder. A single-character string gives True, as checked by it equaling its first character. This assumes the input is non-empty; else, one more byte is needed for `s==s[:1]` or `len(s)<2`. --- **Python 2, 52 bytes** ``` p=r=2 for c in input():x=ord(c)%2;r*=p-x;p=x print r ``` Alternatively, an iterative solution. Iterates over the input characters, storing the current and previous character values mod 2. Multiplies the running product by the difference, which because 0 (Falsey) only when two consecutive parities are equal. The "previous" value is initialized to 2 (or any value not 0 or 1) so that the first character never matches parity with the fictional previous character. --- **Python, 42 bytes, outputs via exit code** ``` p=2 for c in input():x=ord(c)%2;p=x/(p!=x) ``` Outputs via exit code. Terminates with a ZeroDivisionError when two consecutive characters have the same parities, otherwise terminates cleanly. [Answer] ## Haskell, ~~42~~ 40 bytes ``` all odd.(zipWith(-)=<<tail).map fromEnum ``` Usage example: `all odd.(zipWith(-)=<<tail).map fromEnum $ "long"` -> `True`. How it works: ``` map fromEnum -- turn into a list of ascii values (zipWith(/=)=<<tail) -- build a list of neighbor differences all odd -- check if all differences are odd ``` Edit: @xnor saved two bytes. Thanks! [Answer] # Mathematica, ~~41~~ 40 Bytes ``` And@@OddQ@Differences@ToCharacterCode@#& ``` -1 character, thanks to Martin Ender [Answer] ## C, 52 bytes ``` int f(char*s){return s[1]?(s[0]-s[1])%2?f(s+1):0:1;} ``` Compares the parity of first 2 characters, recursively moving through the string until it finds 2 characters with the same parity or the string with the length of 1 (`s[1] == 0`). [Code with some of the test cases](https://ideone.com/eZpLvL) [Answer] # Ruby, ~~41~~ 30 (+1) bytes ``` p gsub(/./){$&.ord%2}!~/(.)\1/ ``` Call this from the command line with the `-n` flag, like so: ``` ruby -ne 'p gsub(/./){$&.ord%2}!~/(.)\1/' ``` Replaces each character with the parity of its ASCII value and then compares to a regex. If even, the `=~` comparison will return the index of the first match (i.e. 0), which is a truthy value in Ruby; if not even, the comparison will return `nil`. Thanks to Jordan for the improvements! [Answer] ## Pyke, 8 bytes ``` m.o$2m%B ``` [Try it here!](http://pyke.catbus.co.uk/?code=m.o%242m%25B&input=Hello+World) ``` m.o - map(ord, input) $ - delta(^) 2m% - map(> % 2, ^) B - product(^) ``` [Answer] # C#, 69 bytes ``` s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;}; ``` Full program with test cases: ``` using System; namespace EvenStrings { class Program { static void Main(string[] args) { Func<string,bool>f= s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;}; Console.WriteLine(f("lno")); //false //true: Console.WriteLine(f("#define")); Console.WriteLine(f("EvenSt-ring$!")); Console.WriteLine(f("long")); Console.WriteLine(f("abcdABCD")); Console.WriteLine(f("3.141")); Console.WriteLine(f("~")); Console.WriteLine(f("0123456789")); Console.WriteLine(f("C ode - g ol!f")); Console.WriteLine(f("HatchingLobstersVexinglyPopulateJuvenileFoxglove")); //false: Console.WriteLine(f("Hello World")); Console.WriteLine(f("PPCG")); Console.WriteLine(f("3.1415")); Console.WriteLine(f("babbage")); Console.WriteLine(f("Code-golf")); Console.WriteLine(f("Standard loopholes apply")); Console.WriteLine(f("Shortest answer in bytes wins")); Console.WriteLine(f("Happy golfing!")); } } } ``` [Answer] # PHP, 69 Bytes ``` for(;$i<strlen($s=$argv[1])-1;)$d+=1-ord($s[$i++]^$s[$i])%2;echo$d<1; ``` solution with Regex 81 Bytes ``` for(;$i<strlen($s=$argv[1]);)$t.=ord($s[$i++])%2;echo 1-preg_match("#00|11#",$t); ``` [Answer] ## PowerShell v2+, 47 bytes ``` -join([char[]]$args[0]|%{$_%2})-notmatch'00|11' ``` (Can't *quite* catch PowerShell's usual competitors ...) Takes input `$args[0]` as a string, casts it as a `char`-array, loops through it `|%{...}`, each iteration placing the modulo on the pipeline (with implicit `[char]` to `[int]` conversion). Those are encapsulated in parens and `-join`ed into a string, which is fed into the left-hand of the `-notmatch` operator, checking against `00` or `11` (i.e., returns `True` iff the `0`s and `1`s alternate). That Boolean result is left on the pipeline and output is implicit. ### Test Cases ``` PS C:\Tools\Scripts\golfing> '#define','EvenSt-ring$!','long','abcdABCD','3.141','~','0123456789','C ode - g ol!f','HatchingLobstersVexinglyPopulateJuvenileFoxglove'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)} #define --> True EvenSt-ring$! --> True long --> True abcdABCD --> True 3.141 --> True ~ --> True 0123456789 --> True C ode - g ol!f --> True HatchingLobstersVexinglyPopulateJuvenileFoxglove --> True PS C:\Tools\Scripts\golfing> 'Hello World','PPCG','3.1415','babbage','Code-golf','Standard loopholes apply','Shortest answer in bytes wins','Happy golfing!'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)} Hello World --> False PPCG --> False 3.1415 --> False babbage --> False Code-golf --> False Standard loopholes apply --> False Shortest answer in bytes wins --> False Happy golfing! --> False ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~29~~ 27 bytes ``` i2%\0 n;n 1< 0:i/!?-}:%2^?( ``` Outputs 1 if the word is even, 0 if the word is odd. You can [try it online](https://fishlanguage.com/playground). Edit : saved two bytes thanks to Martin Ender [Answer] # [Perl 6](https://perl6.org), ~~47~~ 26 bytes ``` {?all .ords.rotor(2=>-1).map({(.[0]+^.[1])%2})} ``` ``` {[~](.ords X%2)!~~/(.)$0/} ``` ## Expanded: ``` # bare block lambda with implicit parameter $_ { [~]( # reduce using concatenation operator ( no space chars ) .ords X[%] 2 # the ordinals cross modulus with 2 ( 1 or 0 ) # ^-- implicit method call on $_ ) ![~~] # negating meta operator combined with smartmatch operator / ( . ) $0 / # is there a character followed by itself? } ``` ]
[Question] [ Inspired by a task for Programming 101, here's a challenge that hopefully isn't too easy (or a duplicate). ## Input: * A positive integer `n >= 1`. ## Output: * `n` lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line. ## Test case (n=5): ``` * ** *** **** ***** ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 84 bytes ``` (load library (d Q(q((A)(join(map string(map* repeat-val(repeat-val 42 A)(1to A)))nl ``` [Try it online!](https://tio.run/##RcuxCYAwEEbh3imu/E@wUFzAERzhxCAnZxJjEDJ91Mrqfc3L6ovpFWuFBVnJdEmSSoOVZpzAxNiDehwS6cpJ/faxpeSik9zdYvhJ40Dv0OfwhtlbxUw91wc "tinylisp – Try It Online") # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 89 bytes ``` (d P(q((A N)(i(s N 1)(i(disp(string A))A(P(c 42 A)(s N 1)))(string A (d Q(q((N)(P(q(42))N ``` [Try it online!](https://tio.run/##PcxBCoAgFIThfad4y5ll5gW8gOgZCuJBSKWbTv9SiHYD//A1Lc@h9TTDJgkXECQSiipR5jG2XlHbrWWXQAYkrOJd39@H/PPUkTyQTgzMOzIasiy0Fw "tinylisp – Try It Online") the length of the library functions makes this surprisingly close to the library based one. [Answer] ## Pyke, 6 bytes ``` Voh\** ``` [Try it here!](http://pyke.catbus.co.uk/?code=Voh%5C%2a%2a&input=5) [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 81 bytes 78 bytes but three for the `-A` flag, which enables ASCII output. ``` {(({}[()])<>()){({}[()]<(((((()()()){}())){}{}){})>)}{}((()()()()()){})<>}<>{} ``` [Try it online!](http://brain-flak.tryitonline.net/#code=eygoe31bKCldKTw-KCkpeyh7fVsoKV08KCgoKCgoKSgpKCkpe30oKSkpe317fSl7fSk-KX17fSgoKCkoKSgpKCkoKSl7fSk8Pn08Pnt9&input=NQ&args=LUE) Brain-flak isn't the greatest language for ASCII-art, but it still managed to be somewhat short. Ish. Kinda. Explanation: ``` While True: { ( Decrement counter ({}[()]) And move copy to other stack <>()) Push N '*'s {({}[()]<(((((()()()){}())){}{}){})>)} Pop 0 {} Push newline ((()()()()()){}) Move back to counter <> Endwhile } Move to other stack <> Pop an extra newline {} ``` [Answer] # Jolf, 7 bytes This time, the builtin didn't let me win. Oh well. ``` ―t0jj'* ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=4oCVdDBqaicq&input=NQ) ## Explanation ``` ―t0jj'* ―t0 pattern: left-corner-base triangle j with <input> height j and <input> width. '* comprised of asterisks ``` [Answer] ## Racket 47 bytes ``` (for((i(+ 1 n)))(displayln(make-string i #\*))) ``` Ungolfed: ``` (define (f n) (for ((i (+ 1 n))) ; (i 5) in 'for' produces 0,1,2,3,4 (displayln (make-string i #\*)))) ; #\* means character '*' ``` Testing: ``` (f 5) ``` Output: ``` * ** *** **** ***** ``` [Answer] # Java 7,~~72~~ 70 bytes *Thanks to @kevin for shave it off by 2 bytes.* ``` String f(int n,String s,String c){return n<1?c:f(--n,s+"*",c+s+"\n");} ``` ### Output ``` * ** *** **** ***** ****** ``` [Answer] # Ruby, 27 (or 24) bytes (Thanks to m-chrzan for pointing out the miscounting.) Returns a string. ``` ->n{(1..n).map{|i|?**i}*$/} ``` the `map` makes an array of strings of `*` of increasing length. The `*$/` takes the array and joins the elements to make a newline-separated string. If an array of strings is acceptable, these three bytes can be saved, scoring 24. In test program ``` f=->n{(1..n).map{|i|?**i}*$/} puts f[5] ``` [Answer] # C++, 78 bytes I don't know how there are 2 C++ answers that don't just do it with for loops. Very short and sweet this way: ``` void T(int n){for(int i=1;i<=n;i++){for(int j=0;j<i;j++)cout<<'*';cout<<'\n';}} ``` ## Full program ``` #include <iostream> using namespace std; void T(int n) { for(int i = 1; i <= n; i++) { for(int j = 0; j < i; j++) cout << '*'; cout << '\n'; } } int main() { T(5); } ``` Edit: it is unclear to me whether to count the `#include<iostream>`, `using namespace std`, and/or `std::whatever` in calls. C/C++ answers all over this site seem to use both, and for the most part no one seems to care except for the occasional comment. If I need the `std::`, then +10. If I need the `#include<iostream>`, +18 ([although GCC allows me to do without the basic includes, so maybe not that one](https://codegolf.stackexchange.com/a/2204/56586)) [Answer] # Java, 110 bytes Not that short, but I really like having empty for loops. ``` String f(int n){String s="";for(int i=0;i<n;i++,s+=new String(new char[i]).replace("\0","*")+"\n"){}return s;} ``` [Answer] # GameMaker Language, 68 bytes ``` a="*"for(i=2;i<=argument0;i++){a+="#"for(j=0;j<i;j++)a+="*"}return a ``` [Answer] # Prolog, ~~60 58~~ 56 bytes ``` g(N):-N<=0,put(*),g(N-1);!. f(N):-N<=0,f(N-1),g(N),nl;!. ``` I'm not that familiar with Prolog, but I just gave it a shot. I'm sure it can be a lot shorter. Put the code into a file, then load that file into swipl and run `f(25).` (or some other number). *EDIT:* quotes can be left out in put statement *EDIT 2:* changing `=:=` to `<=` saves 2 bytes. I tried inverting it, but that'd make it wait for a return for some reason. [Answer] # [Elixir](http://elixir-lang.org/), 81 bytes ``` &Enum.reduce(Enum.to_list(1..&1),"",fn(x,r)->r<>String.duplicate("*",x)<>"\n"end) ``` Anonymous function using the capture operator. `Enum.reduce` will iterate a list (the list is obtained by calling `Enum.to_list` on the range 1..n) and concatenate the return string `r` (which has been initialized with "") with a string made of `x` asterisks and a newline. Full program with test case: ``` s=&Enum.reduce(Enum.to_list(1..&1),"",fn(x,r)->r<>String.duplicate("*",x)<>"\n"end) IO.write s.(5) ``` **Try it online on [ElixirPlayground](http://elixirplayground.com/) !** [Answer] # Pyth, ~~10~~ 8 Bytes thanks to Jakube for helping me shave off the extra 2 bytes! ``` VQ*Np"*" ``` [Try it](https://pyth.herokuapp.com/?code=VQ%2aNp%22%2a%22&input=5&debug=0) [Answer] **Brainfuck, 129 bytes** I know there's already a shorter answer in brainfuck, however I wanted to create a program which could handle a multi-digit number input rather than either a single-digit input or a single ascii character input unlike the previous one posted. ``` ,[>+++[->++++[-<<---->>]<]+>,]<-<<[<<]>>[<[->>++++++++++<<]>>>]+>>++++++++++>>++++++[-<+++++++>]<<<<<[>[->+>>.<<<]>>.<[-<+>]<+<-] ``` This is my first ever brainfuck program and it will work for any input between 0 and the maximum size of a single cell (traditionally 8 bits or 255) entered using the characters '0' to '9' (corresponding to ascii-values 048-057) **Explanation** The first part of this program, `,[>+++[->++++[-<<---->>]<]+>,]`, takes the input numbers as char values and removes 48 from each to make them equal to the numbers 0 to 9 rather than the char values of the numbers 0 to 9. It stores these in separate cells with a 1 in between each of them so that the start and end points can be found again. The second part, `<-<<[<<]>>[<[->>++++++++++<<]>>>]`, consolidates the separate values into one cell. This is why the maximum size of a cell controls how high a number can be. The third section, `+>>++++++++++>>++++++[-<+++++++>]<<<<<`, is used to set up the other cells needed: one with the number of asterisks per line, one with the code for a linefeed and one with the code for an asterisk. There is also a blank cell left for working with later. The remainder of the code, `[>[->+>>.<<<]>>.<[-<+>]<+<-]`, is used to: 1. Output as many asterisks as necessary 2. Output a linefeed 3. Reset the value of the cell controlling the asterisks 4. Increment the control cell 5. Decrement the cell with the number until it equals 0 [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes ``` '*×.pD¦`r`» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=JyrDly5wRMKmYHJgwrs&input=NQ) **Explanation:** (Prints hourglass) ``` Implicit input - 5 '* Asterisk character - stack = '*' × Repeat input times - stack = '*****' .p Get prefixes - stack = ['*', '**', '***', '****', '*****'] D Duplicate last element STACK = ['*', '**', '***', '****', '*****'] , ['*', '**', '***', '****', '*****'] ¦ Remove first element from final list STACK = ['*', '**', '***', '****', '*****'] , ['**', '***', '****', '*****'] `r` Reverse 1 list and flatten both STACK = '*****','****','***','**','*','**','***','****','*****' » Join by newlines and implicitly print ``` For input 5, prints: ``` ***** **** *** ** * ** *** **** ***** ``` [Answer] # C++ 11, 65 bytes Not including the `include` in the byte count. ``` #include<string> using S=std::string;S g(int n){return n?g(n-1)+S(n,'*')+'\n':"";} ``` Usage: ``` std::cout << g(n) << std::endl; ``` [Answer] # SQL, 153 Bytes Golfed: ``` CREATE PROCEDURE P @n INT AS BEGIN DECLARE @a INT;SET @a=0;DECLARE @o VARCHAR(1000);SET @o='*'WHILE @a<@n BEGIN PRINT @o;SET @o=@o+'*'SET @a=@a+1;END;END ``` Ungolfed: ``` CREATE PROCEDURE P @n INT AS BEGIN DECLARE @a INT; SET @a=0; DECLARE @o VARCHAR(1000); SET @o='*' WHILE @a<@n BEGIN PRINT @o; SET @o=@o+'*' SET @a=@a+1; END; END ``` Testing: ``` EXEC P '6' ``` Output: ``` * ** *** **** ***** ****** ``` [Answer] # Crystal, 31 bytes `n=5;(1..n).each{|x|puts "*"*x}` Output: ``` * ** *** **** ***** ``` Really demonstrates the beauty of Crystal/Ruby. `n` is the integer input, `(1..n)` is an inclusive range from `1` to `n` (`[1, n]`). `.each` is a method on Range that runs the provided block for every integer in the range. [Answer] # [Dip](https://github.com/mcparadip/Dip), ~~6~~ 5 bytes ``` `**En ``` *-1 byte thanks to [Oliver](https://codegolf.stackexchange.com/users/12537/oliver)* **Explanation:** ``` `** Push "*" repeated input times E Prefixes n Join by newlines ``` [Answer] # C, 88 bytes / 53 bytes Using C89. `g(a){a&&g(a-1);a<2||puts("");while(a--)putchar('*');}main(int a,char**v){g(atoi(v[1]));}` With whitespace for clarity: ``` g(a) { a && g(a-1); a<2 || puts(""); while (a--) putchar('*'); } main(int a, char** v) { g(atoi(v[1])); } ``` Without main, this function is 53 bytes: `g(a){a&&g(a-1);a<2||puts("");while(a--)putchar('*');}` [Answer] # python3, ~~58~~ 57 bytes ``` print('\n'.join(['*'*(p+1)for p in range(int(input()))])) ``` Ungolfed: ``` rownums = int(input()) output = [] for i in range(rownums): currrow = "*" * (i+1) # 'i' * 5 == 'iiiii' output.append(currrow) print('\n'.join(output)) ``` [Answer] # SmileBASIC, 30 bytes ``` INPUT N FOR I=1TO N?"*"*I NEXT ``` [Answer] **Haskell 36 Bytes** Here is a version using map. ``` f="*":map('*':)f;g=unlines.(`take`f) ``` Input `g 10` Output `"*\n**\n***\n****\n*****\n******\n*******\n********\n*********\n**********\n"` Alternatives of interest might be: 38 Bytes ``` g n=id=<<scanl(\x y->'*':x)"*\n"[2..n] ``` 38 Bytes ``` f="*\n":map('*':)f;g n=id=<<(n`take`f) ``` 36 ``` g n=id=<<(take n$iterate('*':)"*\n") ``` [Answer] # k, 18 bytes ``` {-1@(1+!x)#\:"*";} ``` Explanation: ``` -1@ // prints to console 1+!x //returns list from 1 to x (implicit input) #\: //for each item in the prefixed list, "take" this many "*" //asterisk string ``` [Answer] # [Perl 6](http://perl6.org/), 17 bytes ``` put(\*x++$)xx get ``` Full program that prints to stdout. How it works: ``` \* # a Capture object that stringifies to the asterisk, x # string-repeated by ++$ # a counter that starts at 1, put( ) # and printed followed by a newline. xx get # Do all of that n times. ``` Invokes the `put` statement *n* times, each time printing the asterisk repeated by the counter variable `++$`. --- # [Perl 6](http://perl6.org/), 21 bytes ``` {.put for \*Xx 1..$_} ``` A lambda that prints to stdout. How it works: ``` { } # A lambda. \* # A Capture object that stringifies to the asterisk. 1..$_ # Range from 1 to n. X # Cartesian product of the two, x # with the string repetition operator applied to each result. .put for # Iterate over the strings, and print each followed by a newline. ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 26 bytes ``` seq -f10^%f-1 $1|bc|tr 9 * ``` **Output to stderr should be ignored.** [Try it online!](https://tio.run/nexus/bash#@1@cWqigm2ZoEKeql6ZrqKBiWJOUXFNSpGCpoPX//39TAA "Bash – TIO Nexus") The code above works on TIO since the working directory there has no visible files. If this needs to run in a directory that contains a visible file, change `*` to `\*` at the cost of one byte (27 bytes): ``` seq -f10^%f-1 $1|bc|tr 9 \* ``` [Answer] # Terrapin logo, 67 bytes ``` to a :a make "b 1 repeat :a[repeat :b[type "*]make "b b+1 pr "] end ``` [Answer] # PHP, ~~43~~ ~~34~~ ~~31~~ 28 bytes Note: uses IBM 850 encoding (old favorite reinvented recently) ``` for(;$argn--;)echo$o.=~ı,~§; ``` Run like this: ``` echo 5 | php -nR 'for(;$argn--;)echo$o.=~ı,~§;';echo > * > ** > *** > **** > ***** ``` # Explanation Iterates from `N` down to 0. Add an asterisk to `$o` for each iteration, then outputs `$o` and a newline. # Tweaks * Add an asterisk to `$o` for each iteration, and then output `$o`. Saves 9 bytes * Combined adding an asterisk to `$o` with outputting, saves 3 bytes * Saved 3 bytes by using `$argn` [Answer] ## K, 16 Bytes ``` {-1(1+!x)#'"*"}; {-1(1+!x)#'"*"}10; * ** *** **** ***** ****** ******* ******** ********* ********** ``` EDIT BELOW - adding explanation) ``` /Code ---> explanation (pretend x is 3) 1+!x ---> Numbers from 1 to 3 1 2 3#"*" ---> Take left many items of right ==> ("*";"**";"***") -1x ---> Print x to the console, if x is a list, each item is printed to a new line example(notice the -1 printed at the bottom). -1("*";"**";"***") * ** *** -1 To silence the output(-1), put a semicolon after the expression e.g. -1("Hello"); Hello ``` [Answer] # [Röda 0.12](https://github.com/fergusq/roda), ~~30~~ 29 bytes, non-competing ``` h i{seq 1,i|{|j|print"*"*j}_} ``` This is my first try in this scripting language created by [fergusq](https://codegolf.stackexchange.com/users/66323/fergusq) :D This is a function. To run, use this: ``` h i{seq 1,i|{|j|print"*"*j}_} main { h(5) } ``` ### Ungolfed ``` h i{ /* Define a function h with parameter i */ seq 1,i /* Generate a sequence of numbers from 1 to i */ |{ }_ /* and pipe it to a for-loop */ |j| /* where j is the number in the sequence*/ print"*"*j /* and print an asterisk duplicated j times*/ } ``` ]
[Question] [ Inspired by a task for Programming 101, here's a challenge that hopefully isn't too easy (or a duplicate). ## Input: * A positive integer `n >= 1`. ## Output: * `n` lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line. ## Test case (n=5): ``` * ** *** **** ***** ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 22 bytes ``` ?(.;I:^;/-.@o;(!\>'*oN ``` [**Test it online!**](http://ethproductions.github.io/cubix/?code=PyguO0k6XjsvLS5AbzsoIVw+JypvTg==&input=NQ==) Outputs a trailing newline. At first I wasn't sure I could get this to fit on a 2-cube, but in the end it worked out fine: ``` ? ( . ; I : ^ ; / - . @ o ; ( ! \ > ' * o N . . ``` I'll add an explanation when I have time, hopefully later today. [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~13~~ ~~11~~ 10 bytes *Thanks to @MartinEnder for removing two bytes, and @Linus for removing one more!* ``` ri{)'**N}% ``` [Try it online!](http://cjam.tryitonline.net/#code=cml7KScqKk59JQ&input=NQ) ### Explanation ``` ri e# Read input as an integer n { }% e# Run this block for each k in [0 1 ... n-1] ) e# Add 1 to the implicitly pushed k '* e# Push asterisk character * e# Repeat the character k+1 times N e# Push newline e# Implicitly display ``` [Answer] # [Pushy](https://github.com/FTcode/Pushy), 4 bytes ``` :42" ``` [**Try it online!**](https://tio.run/nexus/pushy#@29lYqT0//9/UwA) This method takes advantages of Pushy's automatic int/char conversion: ``` \ Implicit: Input on stack : \ Input times do: (this consumes input) 42 \ Push 42 (char '*') " \ Print whole stack ``` Because each iteration adds a new `*` char, this outputs a triangle. For example, with `n=4`: ``` * \ Stack: [42] ** \ Stack: [42, 42] *** \ Stack: [42, 42, 42] **** \ Stack: [42, 42, 42, 42] ``` [Answer] # LaTeX, 171 bytes I had to use LaTeX instead of plain TeX for the `\typein` macro... Here it is, as golfed as I could: ``` \documentclass{book}\begin{document}\typein[\n]{}\newcount\i\newcount\a\i=0\loop{\a=0\loop*\advance\a by1\ifnum\i>\a\repeat} \advance\i by1 \ifnum\n>\i\repeat\enddocument ``` Explanation: ``` \documentclass{book}% Book because it is shorter than article ;) \begin{document}% Mandatory... \typein[\n]{}% User inputs \n \newcount\i% Create a line counter \newcount\a% And an asterisk counter \i=0% Initializes the line number to zero \loop{% Line number loop \a=0% Sets the number of asterisks to zero \loop% Asterisk loop *% Prints the asterisk \advance \a by 1% Adds one to \a \ifnum\i>\a% If the line number is smaller than the number of asterisks \repeat% Then repeat }% Otherwise prints a new line \advance\i by 1% And add 1 to the line counter \ifnum\n>\i% If input number is less than the number of lines then \repeat% Repeat \enddocument% And finish LaTeX ``` [Answer] # Java ~~7~~ 11, ~~88~~ ~~73~~ 58 bytes ``` String c(int n){return(n<2?"":c(n-1)+"\n")+"*".repeat(n);} ``` -15 bytes by converting to Java 11. [Try it online](https://tio.run/##VZBBTwIxEIXv/IqXerCVBcSDBzHxrInxgDfgULqjW9xtSTsLIYTfvnbdJoZL0/bN@2bm7fRBT3blT2dqHSPetXXnERBZszXolhys@4aR1jGcOgfiNjjpnh9ehHgy0k3maizWTqhxoD1pluJOFE4tLh2wb7d1gmTWwdsSTeLLAbraQKu@F7A8RaZm6lue7pPE0shHpRZJu4zSMZvh8/UDpafobhmVPhDe0tyYz3EiLhA9uLIRDXHlSxwtV6CmrTUThmY3eboEV9AR@TmIxd/vlw@JQoi6IWxPTBPjW8f/YeQsrqxJC70duumL8z5DSnB0zCbZX02lw2qo26hpwtTakBTre1EkSl730v0C). (NOTE: `String#repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because TIO doesn't contain Java 11 yet.) **Explanation:** ``` String c(int n){ // Recursive method with integer parameter and String return-type return(n<2? // If `n` is 1: "" // Start with an empty String : // Else: c(n-1) // Start with a recursive call with `n-1` +"\n") // and a trailing new-line +"*".repeat(n);} // And append `n` amount of '*' ``` [Answer] # [R](https://www.r-project.org/), 33 bytes ``` cat(strrep("*",1:scan()),sep=" ") ``` [Try it online!](https://tio.run/##K/r/PzmxRKO4pKgotUBDSUtJx9CqODkxT0NTU6c4tcBWiUtJ87@h0X8A "R – Try It Online") I hope it's not a dupe - I was able to find only one other R answer. Leverages `strrep` and vectorization to build the vector `"*","**",...,"******"` and prints with `cat` using `newline` as a separator. [Answer] # [Dyalog APL](https://dyalog.com/), 8 [bytes](https://github.com/abrudz/SBCS) ``` '*'/⍤0⍨⍳ ``` Explanation: 1. `'*'`: Literal character `*`. 2. `/⍤0⍨`: Select each 0-ranked vector (scalar) according to. * `/`: Select from the right argument according to the left. * `⍤0`: Apply the preceding function to each scalar in the left and right arguments. * `⍨`: Apply the preceding function, but with the left and right arguments switched (so we select now from the left argument according to the right). 3. `⍳`: Generate integers from 1 to the argument (inclusive) [Answer] # [Rockstar](https://codewithrockstar.com/), 47 bytes ``` listen to N X's0 while N-X let X be+1 say "*"*X ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in) [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 3 bytes ``` \*+ ``` You need to pass the input using `-l` flag. Example run: ``` wasif@wasif:~/Downloads/Regenerate$ python3 regenerate.py -l 5 '\*+' * ** *** **** ***** wasif@wasif:~/Downloads/Regenerate$ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes ``` L'*×» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fR13r8PRDu///NwUA "05AB1E – Try It Online") [Answer] ## Batch, 69 bytes ``` @set s= @for /l %%i in (1,1,%1)do @call set s=*%%s%%&call echo %%s%% ``` [Answer] # Ruby, 26 bytes ``` ->n{s='';n.times{p s+=?*}} ``` [Answer] # Brainfuck, 70 bytes ``` ,>++++++[<-------->>>+++++++<<-]<[>+[->+>.<<]>[-<+>]++++++++++.[-]<<-] ``` I'm sure this could be golfed a little bit. This version only works for single-digit numbers; feel free to modify it to work on larger numbers too. Edit: If it's allowed to use a single character's ASCII value as the input, the resulting code is below. Only 60 bytes. ``` ,>++++++[>>+++++++<<-]>[>+[->+>.<<]>[-<+>]++++++++++.[-]<<-] ``` Explanation: ``` ,>++++++[<-------->>>+++++++<<-] [this gets a single character from input into the first cell, subtracts 48 to convert it to an integer representation, and puts 42 in the 3rd cell (ASCII '*').] <[ while the first cell is not zero do >+ add 1 to 2nd cell (empty when we start) [->+>.<<] [while 2nd cell is not empty subtract 1 and print an *. Make a copy in 3rd cell.] >[-<+>] copy 3rd cell value back to 2nd cell ++++++++++.[-] [put '\n' in 3rd cell, print, clear] <<- ] loop ``` Edit: Here is a version that works for numbers up to 255, reading the *text* representation of the number followed by EOF. If your favorite interpreter has unbounded cells it will work up to 999. ``` >>,[---------- [ >++++++[<------>-]<-- >],] [ Pointer is one past the end of a run of digits containing input. Assumption: input < 256. Add ten times most significant digit to second and ten times the second to the third to get it in one cell. ] <<<[>++++++++++<-]>[>++++++++++<-]> Store 42 '*' in the cell 3 to the right >>++++++[>+++++++<-]<< [ While first cell is not empty >+ Add 1 to 2nd cell [->+>.<<] [make a copy in 3rd cell, print '*'] >[<+>-] copy 3rd back to 2nd ++++++++++.[-] print newline and clear 3rd <<- subtract 1 from 1st and continue ] ``` [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 41 Bytes. 24 of these bytes are just assigning R and s, so that we can use a spaceless segment. ``` 'rep' º 'R' = '*' 's' = ►]¿]s\R\1-]}[ ``` ## Explination ``` 'rep' º 'R' = # Get the function for 'rep' (Replace), associate 'R' with it. '*' 's' = # Associate 's' with the string literal '*' ► # Begin spaceless segment. ] # Push a copy of the top of the stack (The input) ¿ # While truthy, popping the top of the stack. ] # Push a copy... s \ R # Push an *, swap the two top values giving "i, *, i", Repeat the *, i times, giving "i, ****", or whatever. \ 1 - # Swap the top values, giving "****, i", decrement the top value by 1. ] # Push a copy of the top value. }[ # End the while, after processing, pop the top value (Which would be 0). Implcititly print. ``` ## Try it! ``` <style> #frame{ width:60em; height:60em; border:none; } </style> <iframe id='frame' src="https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%27rep%27%20%C2%BA%20%27R%27%20%3D%20%27*%27%20%27s%27%20%3D%20%E2%96%BA%5D%C2%BF%5Ds%5CR%5C1-%5D%7D%5B&input=5">Sorry, You need to support IFrame. Why don't you..?</iframe> ``` [Answer] # Groovy, 27 characters ``` {1.upto(it){println"*"*it}} ``` Sample run: ``` groovy:000> ({1.upto(it){println"*"*it}})(5) * ** *** **** ***** ===> null ``` [Answer] # jq, 19 characters (18 characters code + 1 character command line option.) ``` range(1;.+1)|"*"*. ``` Sample run: ``` bash-4.3$ jq -r 'range(1;.+1)|"*"*.' <<< 5 * ** *** **** ***** ``` [On-line test](https://jqplay.org/jq?q=range(1%3b.%2b1)|"*"*.&j=5) (Passing `-r` through URL is not supported – check Raw Output yourself.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes ``` G↓→N* ``` It's the same length as Jelly, which is really bad for an ASCII-art oriented language. At least it's readable, I guess ### Explanation ``` G Polygon ↓→ Down, then right N Input number * Fill with '*' ``` [Answer] # Lua, 36 bytes ``` for i=1,...do print(("*"):rep(i))end ``` Takes input from the command line. [Answer] ## Haskell, 32 bytes ``` unlines.(`take`iterate('*':)"*") ``` The expression `iterate('*':)"*"` generates the infinite list `["*","**","***","****","*****",...]`. The function then takes the first `n` elements and joins them with newlines. The more direct ``` concat.(`take`iterate('*':)"*\n") ``` is one byte longer. [Answer] # RProgN, 42 Bytes, Competing only for the Bounty ``` Q L c 's' = ►3'rep'º'R'=]¿]s\R\1-]} [ ``` > > The length of the script is used as the character code for \*. > > > [Try it Online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=Q%20L%20c%20%27s%27%20%3D%20%0A%E2%96%BA3%27rep%27%C2%BA%27R%27%3D%5D%C2%BF%5Ds%5CR%5C1-%5D%7D%20%5B&input=) [Answer] # Perl, ~~83~~ 76 bytes (no asterisk) ``` print substr((split("\n",`perldoc perlre`))[55],48,1)x$_."\n"foreach(1..<>); ``` (Faster version for large input, 83 characters): ``` $r=`perldoc perlre`;print substr((split("\n",$r))[425],11,1)x$_."\n"foreach(1..<>); ``` Explanation: The statement `perldoc perlre` executes the shell command to display the Perl documentation on regular expressions, which contains an asterisk as the 11th character on line 425. Split the resulting output by line, then extract that character and print in triangular format. Edited to save 6 characters by not saving the output of the shell command, and instead just running it every time. It increases the runtime, though, but we only care about bytes, not runtime :) Another byte was saved (for a total of -7) by finding an earlier asterisk in the perldoc output. [Answer] # ForceLang, 146 bytes ``` def S set def G goto S a io.readnum() S b 0 label 0 if a=b G 1 if b io.writeln() S b 1+b S c 0 label b io.write "*" S c 1+c if b=c G 0 G b label 1 ``` [Answer] # Python 2, ~~38~~ 37 bytes There are only 36 characters shown, but a trailing newline is needed to avoid an EOF-related error raised by the interpreter. 1 byte knocked off for Flp.Tkc's observation. ``` for n in range(input()+1):print'*'*n ``` ### Output for n=5 ``` # leading newline here * ** *** **** ***** ``` # Python 3, 45 bytes The actual list comprehension is never assigned or printed, but if it were, it would be full of `None`s, as `None` is the default return value of `print()`. ``` [print('*'*n)for n in range(int(input())+1)] ``` [Answer] # TI-Basic, ~~28~~ 22 bytes ``` Prompt A "* For(B,1,A Disp Ans Ans+"* End ``` [Answer] ## [Underload](https://esolangs.org/wiki/Underload), ~~15~~ 13 bytes -2 or -3 bytes thanks to @ØrjanJohansen ``` ( )((*)~*:S)^ ``` Input is a Church numeral [inserted](https://codegolf.meta.stackexchange.com/a/10553/61384) between the `)` and `^` on the second line. For example: ``` ( )((*)~*:S)::*:**^ ``` If printing a leading newline is allowed, the following solution works by ommiting the `~`, for 12 bytes: ``` ( )((*)*:S)^ ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes[SBCS](https://github.com/abrudz/SBCS) ``` (,⍕⊢)⌸⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgmG/9OApIbOo96pj7oWaT7q2fGod/P//2kKpgA "APL (Dyalog Unicode) – Try It Online") [Answer] ## [W](https://github.com/A-ee/w) `n`, ~~6~~ 4 bytes ``` '**M ``` ## Explanation ``` M % Map every item in the implicit input with... % (There's an implicit range from 1) '** % asterisks input times n % Join the result with a (n)ewline ``` # How do I use the `n` flag? `... W.py filename.w [input-list] n` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 11 bytes ``` ~,{)"*"*n}% ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v06nWlNJS0krr1b1/39TAA "GolfScript – Try It Online") ### Explanation: ``` ~, Create list [0...input-1] { }% Map over list: )"*"*n Increment, push that many "*"s, push newline ``` [Answer] # [Flurry](https://github.com/Reconcyl/flurry), 88 bytes ``` {}{()[<><<>()>({})]({}{(){}(((<><<>()>){})[{}{<({}){}>}])}{<(<({})(<({}){}>){}>){}>})}{} ``` Can be run with the interpreter as follows: ``` $ ./Flurry -bnn -c "$pgm" 5 * ** *** **** ***** ``` This is heavily based on [my answer to "Print a 10 by 10 grid of asterisks"](https://codegolf.stackexchange.com/a/211556/61384). In particular, I'm reusing my derivations of `succ`, and `push_star`, and the number `10`. `push_star` is a function that pushes 42 to the stack and returns its argument unchanged: ``` push_star := {(){}(((<><<>()>){})[{}{<({}){}>}])} ``` A function that takes a number `n` and pushes 42 to the stack `n` times, then pushes 10, and returns `n+1`: ``` push_row = λn. (n push_star (); push 10; succ n) = λn. (push (n push_star 10); succ n) = λn. K (succ n) (push (n push_star 10)) = λn. K (succ (push n)) (push (pop push_star 10)) := { () [succ ( {})] ( {} push_star 10)} := { () [succ ( {})] ( {} push_star {<(<({})(<({}){}>){}>){}>})} := { () [succ ( {})] ( {} {(){}(((<><<>()>){})[{}{<({}){}>}])}{<(<({})(<({}){}>){}>){}>})} := {()[<><<>()>({})]({}{(){}(((<><<>()>){})[{}{<({}){}>}])}{<(<({})(<({}){}>){}>){}>})} ``` The number 1: ``` 1 = λf n. f n = λf. f := { {} } ``` Pop a number from the stack and apply `push_row` that many times to 1: ``` main = pop push_row 1 := {}{()[<><<>()>({})]({}{(){}(((<><<>()>){})[{}{<({}){}>}])}{<(<({})(<({}){}>){}>){}>})}{{}} ``` Since popping from an empty stack returns 1, we can replace the final `{{}}` with `{}`, yielding: ``` {}{()[<><<>()>({})]({}{(){}(((<><<>()>){})[{}{<({}){}>}])}{<(<({})(<({}){}>){}>){}>})}{} ``` [Answer] ## Actually, 8 bytes ``` R`'**`Mi ``` [Try it online!](http://actually.tryitonline.net/#code=UmAnKipgTWk&input=NQ) Explanation: ``` R`'**`Mi R range(1, n+1) ([1, 2, ..., n]) `'**`M for each element: that many asterisks i flatten and implicitly print ``` --- ## 5 bytes ``` R'**i ``` [Try it online!](http://actually.tryitonline.net/#code=UicqKmk&input=NQ) ]
[Question] [ ### Introduction The [Atari ST](https://en.wikipedia.org/wiki/Atari_ST) was a rather popular personal computer from the mid 80's to early 90's era, powered by a Motorola 68000 microprocessor. On this machine, the default behavior of the operating system for uncaught CPU exceptions was to display a row of bombs on the screen, as shown in the following picture: [![row of bombs](https://i.stack.imgur.com/CwMSk.png)](https://i.stack.imgur.com/CwMSk.png) *Source: <https://commons.wikimedia.org/wiki/File:Row_of_bombs.png>* *NB: Depending on the OS version, the bomb graphics may vary slightly. But let's take this one as reference.* The number of bombs depends on the exception vector, the most common ones being: * ($008) Bus Error : 2 bombs * ($00c) Address Error : 3 bombs * ($010) Illegal Instruction : 4 bombs ### Goal Your goal is to write a program or function that prints or outputs an ASCII art of such Atari ST bombs. ### Input An integer representing the number of bombs to display. Your code must support the most common values: 2, 3 and 4. Supporting less and/or more bombs is fine, but it is neither required nor subject to a bonus. ### Output The original bomb consists of a 16x16 pixel tile, represented here in both ASCII and binary: ``` ....##.......... 0000110000000000 .#.#..#......... 0101001000000000 .......#........ 0000000100000000 #..#....#....... 1001000010000000 ..#...#####..... 0010001111100000 ......#####..... 0000001111100000 ....#########... 0000111111111000 ...###########.. 0001111111111100 ...###########.. 0001111111111100 ..#############. 0011111111111110 ..########.####. 0011111111011110 ...#######.###.. 0001111111011100 ...######.####.. 0001111110111100 ....#########... 0000111111111000 .....#######.... 0000011111110000 .......###...... 0000000111000000 ``` In this challenge, each ASCII bomb must be stretched to twice its original width for a better rendering. Therefore, it will consist of 16 rows of 32 characters, using `##` for 'ON' pixels and two spaces for 'OFF' pixels. All bomb tiles must be put side by side. Leading spaces are forbidden. Trailing spaces are also forbidden, except the ones that are actually part of the bomb tile (i.e. the 31st and 32nd columns) which *must* be present. You may include no more than one leading line-break and no more than one trailing line-break. ### Example Below is the reference output for two bombs, where mandatory line-breaks are marked as `\n` and tolerated extra line-breaks are marked as `(\n)`: ``` (\n) #### #### \n ## ## ## ## ## ## \n ## ## \n ## ## ## ## ## ## \n ## ########## ## ########## \n ########## ########## \n ################## ################## \n ###################### ###################### \n ###################### ###################### \n ########################## ########################## \n ################ ######## ################ ######## \n ############## ###### ############## ###### \n ############ ######## ############ ######## \n ################## ################## \n ############## ############## \n ###### ###### (\n) ``` (Of course, other line-break formats such as `\r` or `\r\n` may be used just as well.) ### Rules This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~43~~ 44 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +1 byte - forgot to double the characters (not that anyone noticed!) ``` “¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4oCcwqV24bqPKVg7bmTEismTwqHhurkzxItpfeG7ismywqFQIsKm4biKxqXhub7igJli4oG04oCYxJbFkuG5meG7i-KBviAj4bikc-KBtOG6i-KCrMKzWQ&input=&args=Mw)** ### How? Preparation was to compress the data as a run-length encoding of the original image: * Count the length of each run of `1`s (space) or `0`s (hash) in the image, ignoring new lines - yields a list: `[4,2,11,1,1,...]`; * Subtract one from each number - this gives a range of `[0,15]`; * Treat this as a base-16 number (enumerate the values, `v`, with index `i` in reverse and sum up `16**i*v` = `19468823747267181273462257760938030726282593096816512166437`); * Convert this to base-250: `[5,119,249,42,...]`; * Map into Jelly's code page as indexes: `¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P` Now the code evaluates this number, maps the `1`s and `0`s to space and hash characters\*, doubles each, splits into lines and repeats each the appropriate number of times. \* actually the implementation is performed modulo 2 to save bytes, so spaces are odd and hashes are even: ``` “¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y - Main link: n “¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’ - base 250 number, as above b⁴ - convert to base 16 (the run length - 1 list) ‘ - increment (vectorises) (the run length list) Ė - enumerate (pairs each with 1,2,3...) Œṙ - run length decode ([1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,4,5,...]) ⁾ # - string " #" ị - index into (1 based and modular) (makes a bomb without line feeds) Ḥ - double (each char becomes a list of 2 chars) s⁴ - split into slices of length 16 ẋ€³ - repeat each input, n, times Y - join with line feeds ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~57~~ ~~55~~ ~~53~~ 50 bytes Uses [CP-1252](http://www.cp1252.com/) encoding. ``` •ø6ŒY2l½î€ÈS`L<eÆô‚˜3ª½¨ºE»D2Âô3•b15ôvy1J€D„# è¹×, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiw7g2xZJZMmzCvcOu4oKsw4hTYEw8ZcOGw7TigJrLnDPCqsK9wqjCukXCu0Qyw4LDtDPigKJiMTXDtDHCq3Z54oKsROKAniMgw6jCucOXLA&input=NA) **Explanation** As the output image only consists of 2 characters we can represent it as a binary number. We can ignore newlines as every line has the same length. We can ignore the last char of each row as it the same for all rows. We use the thinner image as it takes up less space and we can easily duplicate each character later. Using **1** to represent **space** and **0** to represent **#** we get the binary number: `111100111111111101011011111111111111101111111011011110111111110111000001111111111000001111111100000000011111000000000001111000000000001110000000000000110000000010000111000000010001111000000100001111100000000011111110000000111111111100011111` We then convert this to base-10 and then compress it to base 214, the maximum base in 05AB1E. The result of this is: ``` •ø6ŒY2l½î€ÈS`L<eÆô‚˜3ª½¨ºE»D2Âô3• ``` The meat of the program then consist of the following: ``` <base encoded string> b # convert to binary 15ô # slice into pieces of 15 v # for each slice 1J # append a 1 €D # duplicate each character „# # push the string "# " è # use the list of binary digits to index into the string ¹× # repeat string input number of times , # and print with newline ``` [Answer] # Pyth, ~~57~~ ~~56~~ ~~54~~ ~~53~~ ~~51~~ 50 bytes The code contains unprintable characters, so here's a reversible `xxd` hexdump. ``` 00000000: 6a2a 4c51 6331 3673 2e65 2a79 6240 2220 j*LQc16s.e*yb@" 00000010: 2322 6b6a 4322 4c49 c142 3c60 0cca 9437 #"kjC"LI.B<`...7 00000020: b383 76bb c246 c86d 4c04 99bd 3614 7022 ..v..F.mL...6.p" 00000030: 3137 17 ``` [Try it online.](http://pyth.herokuapp.com/?code=j%2aLQc16s.e%2ayb%40%22+%23%22kjC%22LI%C3%81B%3C%60%0C%C3%8A%C2%947%C2%B3%C2%83v%C2%BB%C3%82F%C3%88mL%04%C2%99%C2%BD6%14p%2217&input=2&debug=0) [Answer] # JavaScript (ES6), ~~159~~ ~~154~~ ~~140~~ 136 bytes *Saved lots of bytes thanks to @Hedi and @Arnauld* ``` n=>[..."ᅬᄉソﻶ쀇쀇考萃쐇숇ﱿ"].map(x=>(f=q=>q?(q&1?" ":"##")+f(q>>1):"")(x.charCodeAt()).repeat(n)).join` ` ``` That's 104 chars, but (sadly) 136 UTF-8 bytes. The string was generated with this snippet: ``` console.log([ 0b1111111111001111, 0b1111111110110101, 0b1111111101111111, 0b1111111011110110, 0b1111100000111011, 0b1111100000111111, 0b1110000000001111, 0b1100000000000111, 0b1100000000000111, 0b1000000000000011, 0b1000010000000011, 0b1100010000000111, 0b1100001000000111, 0b1110000000001111, 0b1111000000011111, 0b1111110001111111 ].map(x=>(65535-x).toString(16)).join(",")) ``` Using `.replace` instead of `[...string].map` is equally long: ``` n=>"ᅬᄉソﻶ쀇쀇考萃쐇숇ﱿ".replace(/./g,x=>(f=q=>q?(q&1?" ":"##")+f(q>>1):"")(x.charCodeAt()).repeat(n)+` `) ``` ### How it works Since each row of the raw data can be represented as a 16-bit number, we can store the entire file in a 16-char string. The compression algorithm takes each binary row, flips it and reverses it (since every row in the original ends in a **0**, every row in the modified version now *starts* with a **1**), then turns it into a char, and concatenates the resulting characters. To decompress it, we need to extract the charcode and turn its binary representation into a string of hashes and spaces. This can be done with a recursive function, like so: ``` (f=q=>q?(q&1?" ":"##")+f(q>>1):"")(x.charCodeAt()) ``` `f` repeatedly takes the last bit of `q`, selecting two spaces if it's 1 or two hashes if it's 0, then concatenates that with the result of running `f` in the rest of `q`. This is run on `x.charCodeAt()`, turning the char-code into the correct string of spaces and hashes. (There was a lot more drama here before, but the 4-byte-saving technique erased all of that.) After that, we can just repeat the string `n` times and add a newline. This is the shortest decompression method I have found, but feel free to suggest any possibly shorter methods. Other attempts at compressing the string: ``` n=>[48,74,128,265,1988,1984,8176,16376,16376,32764,31740,15352,15864,8176,4064,896].map(x=>(f=q=>q?(q&1?" ":"##")+f(q>>1):"")(65535-x).repeat(n)).join` ` n=>"1c,22,3k,7d,1j8,1j4,6b4,cmw,cmw,pa4,oho,bug,c8o,6b4,34w,ow".split`,`.map(x=>(f=q=>q?(q&1?" ":"##")+f(q>>1):"")(65535-parseInt(x,36)).repeat(n)).join` ` n=>"30,4a,80,109,7c4,7c0,1ff0,3ff8,3ff8,7ffc,7bfc,3bf8,3df8,1ff0,fe0,380".split`,`.map(x=>(f=q=>q?(q&1?" ":"##")+f(q>>1):"")('0x'+x^65535)).repeat(n)).join` ` ``` The first of these is 153 bytes, so none of them come anywhere near 136... [Answer] ## MS-DOS .COM file, 84 bytes OK. Just for fun because I cannot beat the 50 bytes... Tried under DOSbox as well as under MS-DOS 6.22 in a virtual machine. Under DOSbox the program works fine however under real MS-DOS the output will not be displayed correctly because DOS requires CR-LF instead of LF at the end of the line. (However the output is correct.) A 88 byte variant would use CR-LF at the end of the line. Here is the file: ``` 0000 be 32 01 fc ad 89 c3 8a 36 82 00 80 ee 30 b9 10 0010 00 d1 c3 18 d2 80 ca 20 80 e2 23 b4 02 cd 21 cd 0020 21 e2 ee fe ce 75 e7 b2 0a cd 21 ad 85 c0 75 d5 0030 cd 20 00 0c 00 52 00 01 80 90 e0 23 e0 03 f8 0f 0040 fc 1f fc 1f fe 3f de 3f dc 1f bc 1f f8 0f f0 07 0050 c0 01 00 00 ``` The assembler code (in AT&T syntax) looks like this: ``` start: # Read data from "image:" mov $image,%si cld # Read the first 16 bytes lodsw nextLine: # Use bx as shift register mov %ax, %bx # Read the number of bombs mov 0x82,%dh sub $'0',%dh nextBombInThisLine: # Number of characters mov $16, %cx nextCharacter: # Rotate the data# get the next bit to CY rol $1, %bx # This results in 0x23 ('#') if CY is set, to 0x20 (' ') otherwise sbb %dl, %dl or $0x20, %dl and $0x23, %dl # Print result character twice mov $2, %ah int $0x21 int $0x21 # more Characters in this line? loop nextCharacter # More bombs to draw? dec %dh jnz nextBombInThisLine # Print a newline # mov $13, %dl # <- Additional 4 bytes needed for "\r\n" # int $0x21 # at the end of the line! mov $10, %dl int $0x21 # Read the next 16 bytes# 0x0000 means: EOF lodsw test %ax,%ax jnz nextLine # End of program int $0x20 image: # Here 34 bytes follow: # 16 16-bit-words "bitmap" for the bombs followed # by 0x0000 indicating the end of the bitmap ``` --- Edit --- I forgot to mention: The program must be started with the following command line: Name of the COM file + **exactly one** space character + Number of bombs (1-9) [Answer] # Python, ~~223~~ 179 bytes ### Second approach: ``` f=lambda n:'\n'.join(''.join(2*' #'[int(d)]for d in bin(int('0c0052000100908023e003e00ff81ffc1ffc3ffe3fde1fdc1fbc0ff807f001c0'[i:i+4],16))[2:].zfill(16))*n for i in range(0,64,4)) ``` [Try it on repl.it!](https://repl.it/Dn1M) Rather than creating a list of strings on-the-fly, there is a hard-coded hexadecimal string which is indexed and converted to binary; then each binary digit is turned into either `' '` or `'#'`, which is duplicated and joined together ... etc. ### First approach: ``` s=' ';b='##';f=lambda n:'\n'.join(n*l.ljust(32)for l in[s*4+b*2,(s+b)*2+s*2+b,s*7+b,b+s*2+b+s*4+b,s*2+b+s*3+b*5,s*6+b*5,s*4+b*9,s*3+b*11,s*3+b*11,s*2+b*13,s*2+b*8+s+b*4,s*3+b*7+s+b*3,s*3+b*6+s+b*4,s*4+b*9,s*5+b*7,s*7+b*3]) ``` [Try it on repl.it!](https://repl.it/DnYi/2) This contains a hard-coded list of the strings of each line (not including trailing spaces) created by duplicating either `' '` or `'##'` a number of times. For each of these strings, they are padded with spaces until 32 characters in length, duplicated `n` times, then joined with newlines. [Answer] # C, ~~250~~ ~~240~~ ~~208~~ 188 bytes ``` d[]={3072,20992,256,36992,9184,992,4088,8188,8188,16382,16350,8156,8124,4088,2032,448,0},m,c,*i=d;f(k){for(;*i;i++,puts(""))for(c=k;c--;)for(m=32768;m;write(1,&"## "[m&*i?0:2],2),m>>=1);} ``` Switch to using a function. ``` m,d[]={3072,20992,256,36992,9184,992,4088,8188,8188,16382,16350,8156,8124,4088,2032,448,0},*i=d;main(c,v)char**v;{for(;*i;puts(""),i++)for(c=atoi(v[1]);c--;)for(m=32768;m;write(1,&"## "[m&*i?0:2],2),m>>=1);} ``` Test like this. `main(c,v)char**v; { f(atoi(v[1])); }` ``` a.exe 2 #### #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ########## ## ########## ########## ########## ################## ################## ###################### ###################### ###################### ###################### ########################## ########################## ################ ######## ################ ######## ############## ###### ############## ###### ############ ######## ############ ######## ################## ################## ############## ############## ###### ###### ``` [Answer] # [///](https://esolangs.org/wiki////), ~~539~~ 532 + no. of bombs bytes The first /// answer, displaying 4 bombs. The end four 1's can be replaced with any unary representation of the number of bombs you want to print (11 for 2, 111 for 3) ``` /-/?|X//y/\/X//xy|//|/\/\///+/%@!|$/bcd|%/efg|@/hij|!/klm|?/nop|b/Bxc/Cxd/Dxe/Exf/Fxg/Gxh/Hxi/Ixj/Jxk/Kxl/Lxm/Mxn/Nxo/Oxp/Pxq/ss|r/tt|s/SS|t/TT|S/ |T/##|1/AX$+-$+?AXyAX$+-cd+?by$+-d+?cycd+-+?dyd+-fg@!?ey+-g@!?fyfg@!-@!?gyg@!-ij!?hy@!-j!?iyij!-!?jyj!-lm?ky!-m?lylm-?mym-opny-poyop|AXA/AA|bB/BB|cC/CC|dD/DD|eE/EE|fF/FF|gG/GG|hH/HH|iI/II|jJ/JJ|kK/KK|lL/LL|mM/MM|nN/NN|oO/OO|pP/PP|A/qtqqs|B/STSTsTqqS|C/qsSTqq|D/TsTqTqsS|E/sTsSrTqS|F/qsrTqS|G/qrrTsS|H/sSrrtTs|I/sSrrtTs|J/srrrTS|K/srrSrS|L/sSrtTStTs|M/sSrtSrs|N/qrrTsS|O/qSrtTq|P/qsStTqs|X/ /1111 ``` [Try it online!](http://slashes.tryitonline.net/#code=Ly0vP3xYLy95L1wvWC8veHl8Ly98L1wvXC8vL14vdFR8Ji9ycnwqL3NTfCsvJUAhfCQvYmNkfCUvZWZnfEAvaGlqfCEva2xtfD8vbm9wfGIvQnhjL0N4ZC9EeGUvRXhmL0Z4Zy9HeGgvSHhpL0l4ai9KeGsvS3hsL0x4bS9NeG4vTnhvL094cC9QeHEvc3N8ci90dHxzL1NTfHQvVFR8Uy8gIHxULyMjfDEvQVgkKy0kKz9BWHlBWCQrLWNkKz9ieSQrLWQrP2N5Y2QrLSs_ZHlkKy1mZ0AhP2V5Ky1nQCE_ZnlmZ0AhLUAhP2d5Z0AhLWlqIT9oeUAhLWohP2l5aWohLSE_anlqIS1sbT9reSEtbT9seWxtLT9teW0tb3BueS1wb3lvcHxBWEEvQUF8YkIvQkJ8Y0MvQ0N8ZEQvRER8ZUUvRUV8ZkYvRkZ8Z0cvR0d8aEgvSEh8aUkvSUl8akovSkp8a0svS0t8bEwvTEx8bU0vTU18bk4vTk58b08vT098cFAvUFB8QS9xdHFxc3xCL1NUU1RzVHFxU3xDL3EqVHFxfEQvVHNUcVRxKnxFL3NUKnJUcVN8Ri9xc3JUcVN8Ry9xJlQqfEgvKiZec3xJLyomXnN8Si9zJnJUU3xLL3MmU3JTfEwvKnJeU15zfE0vKnJ0U3JzfE4vcSZUKnxPL3FTcl5xfFAvcSpecXN8WC8KLzExMTE&input=) If the input must be decimal, the following has ~~555~~ 548 bytes (where the last digit can be changed to 1, 2, 3 or 4): ``` /-/?|X//y/\/X//xy|//|/\/\///4/13|3/12|2/11|^/tT|&/rr|*/sS|+/%@!|$/bcd|%/efg|@/hij|!/klm|?/nop|b/Bxc/Cxd/Dxe/Exf/Fxg/Gxh/Hxi/Ixj/Jxk/Kxl/Lxm/Mxn/Nxo/Oxp/Pxq/ss|r/tt|s/SS|t/TT|S/ |T/##|1/AX$+-$+?AXyAX$+-cd+?by$+-d+?cycd+-+?dyd+-fg@!?ey+-g@!?fyfg@!-@!?gyg@!-ij!?hy@!-j!?iyij!-!?jyj!-lm?ky!-m?lylm-?mym-opny-poyop|AXA/AA|bB/BB|cC/CC|dD/DD|eE/EE|fF/FF|gG/GG|hH/HH|iI/II|jJ/JJ|kK/KK|lL/LL|mM/MM|nN/NN|oO/OO|pP/PP|A/qtqqs|B/STSTsTqqS|C/q*Tqq|D/TsTqTq*|E/sT*rTqS|F/qsrTqS|G/q&T*|H/*&^s|I/*&^s|J/s&rTS|K/s&SrS|L/*r^S^s|M/*rtSrs|N/q&T*|O/qSr^q|P/q*^qs|X/ /4 ``` [Try it online!](http://slashes.tryitonline.net/#code=Ly0vP3xYLy95L1wvWC8veHl8Ly98L1wvXC8vLzQvMTN8My8xMnwyLzExfF4vdFR8Ji9ycnwqL3NTfCsvJUAhfCQvYmNkfCUvZWZnfEAvaGlqfCEva2xtfD8vbm9wfGIvQnhjL0N4ZC9EeGUvRXhmL0Z4Zy9HeGgvSHhpL0l4ai9KeGsvS3hsL0x4bS9NeG4vTnhvL094cC9QeHEvc3N8ci90dHxzL1NTfHQvVFR8Uy8gIHxULyMjfDEvQVgkKy0kKz9BWHlBWCQrLWNkKz9ieSQrLWQrP2N5Y2QrLSs_ZHlkKy1mZ0AhP2V5Ky1nQCE_ZnlmZ0AhLUAhP2d5Z0AhLWlqIT9oeUAhLWohP2l5aWohLSE_anlqIS1sbT9reSEtbT9seWxtLT9teW0tb3BueS1wb3lvcHxBWEEvQUF8YkIvQkJ8Y0MvQ0N8ZEQvRER8ZUUvRUV8ZkYvRkZ8Z0cvR0d8aEgvSEh8aUkvSUl8akovSkp8a0svS0t8bEwvTEx8bU0vTU18bk4vTk58b08vT098cFAvUFB8QS9xdHFxc3xCL1NUU1RzVHFxU3xDL3EqVHFxfEQvVHNUcVRxKnxFL3NUKnJUcVN8Ri9xc3JUcVN8Ry9xJlQqfEgvKiZec3xJLyomXnN8Si9zJnJUU3xLL3MmU3JTfEwvKnJeU15zfE0vKnJ0U3JzfE4vcSZUKnxPL3FTcl5xfFAvcSpecXN8WC8KLzQ&input=) The most important parts of the code are that: | means // ABCDEFGHIJKLMNOP mean each line of the bomb respectively S means 2 spaces s means 4 spaces \* means 6 spaces q means 8 spaces T means ## (2) t means #### (4) ^ means ###### (6) r means ######## (8) & means ################ (16) Most of the code is making sure that the bombs are printed side-by-side, not on top of each other. [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 66 bytes ``` "^a1{9\b aZ5w7qQAwndIUffO"136b2b1Ser0'#erG/ri*z{:_N}% ``` [Try it online!](http://cjam.tryitonline.net/#code=IgFeBB9hMXsLOVweGmIEIGFaNXc3fw9xUUF3bmQQSVUTBRhmZk8iMTM2YjJiMVNlcjAnI2VyRy9yaSp6ezpfTn0l&input=Mg) *(note that there are some unprintable characters in the code.)* --- The bomb in encoded in as a number in binary using 1 for spaces (the leading space as 1 ensures we don't have to pad the binary representations), transposed, and then converted to string in base-136 (which produced the shortest string without wide-characters). These steps can be played with [here](http://cjam.tryitonline.net/#code=IgouLi4uIyMuLi4uLi4uLi4uCi4jLiMuLiMuLi4uLi4uLi4KLi4uLi4uLiMuLi4uLi4uLgojLi4jLi4uLiMuLi4uLi4uCi4uIy4uLiMjIyMjLi4uLi4KLi4uLi4uIyMjIyMuLi4uLgouLi4uIyMjIyMjIyMjLi4uCi4uLiMjIyMjIyMjIyMjLi4KLi4uIyMjIyMjIyMjIyMuLgouLiMjIyMjIyMjIyMjIyMuCi4uIyMjIyMjIyMuIyMjIy4KLi4uIyMjIyMjIy4jIyMuLgouLi4jIyMjIyMuIyMjIy4uCi4uLi4jIyMjIyMjIyMuLi4KLi4uLi4jIyMjIyMjLi4uLgouLi4uLi4uIyMjLi4uLi4uCiIgICAgICAgICAgICAgICAgIGUjIFRIRSBCT01CIQoiLiMiIjEwImVyTiUgICAgICBlIyBlbmNvZGUgdG8gYmluYXJ5IGxpbmVzCnogICAgICAgICAgICAgICAgIGUjIHRyYW5zcG9zZSAoc2F2ZXMgYSBieXRlIHRvLCBidXQgY291bGQgYmUgaW4gY29kZSkKZV97JzAtfSUyYiAgICAgICAgZSMgY29udmVydCBib21iIHRvIG51bWJlcgoxMzZiOmNlX2VkTm8gICAgICBlIyBlbmNvZGluZyAoc3RhY2sgZGlzcGxheSkKICAgICAgICAgICAgICAgICAgZSMgQUNUVUFMIENPREUgQkVMT1cgSEVSRQoxMzZiMmIwJyNlcjFTZXJHLyBlIyBkZWNvZGUgdmlhIGJpbmFyeQpyaSp6ezpfTn0lICAgICAgICBlIyBjb21iaW5lIHZpYSB0cmFuc3Bvc2U&input=Mg&debug=on). This answer then reverses the encoding, the main trick being to repeat the bomb before transposing, effectively concatenating each line of the bomb at once. The characters in each line can be then be doubled up with newlines inserted for the final output. [Answer] # PHP, ~~138~~ 104+32=136 bytes I had never thought that `file` was binary safe. I only wish I would have found a more interesting way to store the data; but nothing I tried beat raw binary. ``` foreach(unpack("v*",file(b)[0])as$v)echo" ",str_repeat(strtr(sprintf("%016b",$v),[" ","##"]),$argv[1]); ``` * read binary data from file, unpack from little endian 16bit to array of int * loop through array: print 16 digit binary to string, replace `0` with 2 spaces, `1` with `##`, repeat `$argv[1]` times, print result + newline run with `-r` --- binary data in file `b`: ``` 0000000 0c00 5200 0100 9080 23e0 03e0 0ff8 1ffc 0000010 1ffc 3ffe 3fde 1fdc 1fbc 0ff8 07f0 01c0 ``` code to generate the file: ``` $f=fopen(b,wb);foreach(array_map(bindec,explode(" ", "0000110000000000 0101001000000000 0000000100000000 1001000010000000 0010001111100000 0000001111100000 0000111111111000 0001111111111100 0001111111111100 0011111111111110 0011111111011110 0001111111011100 0001111110111100 0000111111111000 0000011111110000 0000000111000000"))as$c)fputs($f,pack("v*",$c));fclose($f); ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~64~~ ~~63~~ ~~60~~ ~~59~~ 58 bytes ``` 49:',cxJr(v9hW&waHB`U=NL%)C9[$aoAN'F16ZaQEY"32e!' #'w)liX" ``` [**Try it online!**](http://matl.tryitonline.net/#code=NDk6JyxjeEpyKHY5aFcmd2FIQmBVPU5MJSlDOVskYW9BTidGMTZaYVFFWSIzMmUhJyAjJ3cpbGlYIg&input=Mw) ### Explanation The code uses a pre-compressed version of the 16×16 binary matrix. The pre-compressing (not part of the program) used two steps: 1. Run-length encoding of the matrix read in row-major order (first across, then down). 2. The resulting run-lengths range from 1 to 16, so the vector of run-lengths minus 1 was converted from base 16 to base 94 (to use all printable ASCII codes except single quote, which is not used because it would need escaping). The compressed string, ``` ',cxJr(v9hW&waHB`U=NL%)C9[$aoAN' ``` is decompressed from base 94 to base 16: ``` F16Za ``` The obtained vector of run-lenghts plus 1 is multipled by 2: ``` QE ``` to perform the horizontal stretching. The vector of run-lenghts contains 49 values. The original numbers to be repeated with those lengths should be `[0 1 0 1 ... 0]` (49 entries). But instead of that, it's shorter to use the vector `[1 2 ... 49]`, which will be equally valid thanks to modular indexing. So the run-length decoding is ``` 49: Y" ``` The generated vector containis the runs of `1`, `2`, ...`49`, for a total of 512 entries. This is reshaped into a 16×32 matrix: ``` 32e! ``` and used as modular indices into the string `' #'` to produce a single bomb: ``` ' #'w) ``` Finally, horizontal repetition by a factor given by the input produces the desired result: ``` liX" ``` [Answer] # Python 2: 143 bytes ``` n=input() j=2 while j<258:print''.join(2*'# '[b>'0']for b in bin(int('62XI2JG3U2Q0COCDFCZAMC8A9LAP6W1ZMM4A59GC43M49ENF3Z',36))[j:j+16])*n;j+=16 ``` It's at **[ideone](http://ideone.com/d9IYc7)** (I realised that direct encoding of the original bomb in base 36 made for shorter code in Python.) The string was formed by treating spaces as 1s and hashes as 0s, and then converting to base 36. The program then converts back to binary and slices into lengths of 16 (with an offset of 2 for the '0b' at the front of Python's binary string) , converts to double spaces and double hashes, joins them up, repeats the string `n` times and prints. --- **Previous: Python 2, ~~169 166~~ 163 bytes** ``` n=input() j=0 while j<512:print''.join(' #'[i%2]*2*(v+1)for i,v in enumerate(int(c,16)for c in'31A00010F07010308024A4885A4A3C2703360245035876A25'))[j:j+32]*n;j+=32 ``` It's at **[ideone](http://ideone.com/ZodxuL)** Almost a port of [my Jelly answer](https://codegolf.stackexchange.com/a/95309/53748). [Answer] # Python 2.7, ~~144~~ 141 bytes ``` x=input() for i in range(16):print"".join(" #"[b<"1"]*2for b in bin(int("5ZCAZKAVTP6J04W4VZJ2BQDH5DASIKRS524V8SWRSIVWZEWC8V",36))[2+i::16]*x) ``` The bomb is written in binary with 1 for space, the leading 1 removes the need to pad binary representations. The bomb is transposed (much like in [my CJam answer](https://codegolf.stackexchange.com/a/95297/46756)) and stored in base 36. The program decodes the bomb to binary and iterates bits by a step of 16 effectively following the transposition (which is saves bytes over slicing a given line). The resultant line is concatenated, bits are replaced with doubled or `#`, and joined into a singe string. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~216 204 183 165~~ 134 bytes ``` b(n,i){for(n*=16,i=--n*16;i--;i%n||puts(""))printf(L"àϸ\x7fc\xfde\xfee`\x1fff\xffe\xffe\x7fcǰᇰ䡀\x80⤀\x600"[i/n]&1<<i%n%16?"##":" ");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9JI08nU7M6Lb9II0/L1tBMJ9NWVzdPy9DMOlNX1zpTNa@mpqC0pFhDSUlTs6AoM68kTcNH6fCC8ztiKszTkmMq0lJSgURq6sP962MqDNPS0oC8tFQoAVRxfMPD9g1PFjbEVFgYPFoCpMwMDJSiM/XzYtUMbWyA5qsamtkrKSsrWSkpKChpWtf@B9qhkJuYmaehWZ2kYQQSAQA "C (gcc) – Try It Online") Written as a standalone program (~~201 183~~ 151 bytes) ``` i=16;main(j,l)char**l;{for(;i--;puts(""))for(j=*l[1]*16-769;j--;printf(L"àϸ\x7fc\xfde\xfee`\x1fff\xffe\xffe\x7fcǰᇰ䡀\x80⤀\x600"[i]&1<<j%16?"##":" "));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/T1tDMOjcxM08jSydHMzkjsUhLK8e6Oi2/SMM6U1fXuqC0pFhDSUlTEySSZauVE20Yq2VopmtuZmmdBZIvyswrSdPwUTq84PyOmArztOSYirSUVCCRmvpw//qYCsO0tDQgLy0VSgBVHN/wsH3Dk4UNMRUWBo@WACkzAwOl6MxYNUMbmyxVQzN7JWVlJSslBQWgtda1////NwIA "C (gcc) – Try It Online") This segfaults if a command line parameter is not supplied. [Answer] ## Batch, 415 bytes ``` @echo off set h=##### set s= for %%a in (" ##%s%%s%" " # # #%s% " "%s% #%s% " "# # #%s% " " #%h%%s%" "%s% %h%%s%" " %h%#### " " %h%%h%# " " %h%%h%# " " %h%%h%### " " %h%### #### " " %h%## ### " " %h%# #### " " %h%#### " "%s%%h%## " "%s% ###%s% ")do call:l %1 %%a exit/b :l set r= for /l %%i in (1,1,%1) do call set r=%%r%%%~2 set r=%r: = % echo %r:#=##% ``` Note: the line `set s=` ends in 5 spaces. Accepts the count as a command-line parameter. Simply loops through each line of the bomb (compressed very slightly by removing runs of 5 identical characters) then repeats the bomb as many times as desired before finally duplicating each character. [Answer] # Python 2, ~~206~~ ~~205~~ ~~203~~ ~~199~~ ~~191~~ ~~188~~ ~~186~~ ~~184~~ 160 bytes ``` z=input() for y in 3072,20992,256,36992,9184,992,4088,8188,8188,16382,16350,8156,8124,4088,2032,448:print"".join(" #"[e>0]*2for e in map(int,bin(y+8**6)[5:]))*z ``` Looked at Hex for the number list but it didn't seem to save enough to make it worth the effort. Was hoping to be able to golf the code down but seem to have got as far as I can with this approach. Any additional hints gratefully received. **EDIT** -1 by changing `e==1` to `e>0`. I always forget that one. -2 by ignoring the length of the binary string, prepending 7 0's and taking only the last 16 elements. Works as there are never more than 7 leading 0's. -4 because now that I have lost the second reference to the variable b I can use `bin(y)[2:]` directly in the map function taking it below the magic 200 :-) -8 by using slice assignment on the second list. Learned something new this evening. -3 with thanks to @Jonathan -2 by using `c=d=([0]*7+map(int,bin(y)[2:]))[-16:]` instead of having `c=d;` -2 again thanks to @Jonathan -24 with thanks to @Linus **Output** ``` python bombs.py 2 #### #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ########## ## ########## ########## ########## ################## ################## ###################### ###################### ###################### ###################### ########################## ########################## ################ ######## ################ ######## ############## ###### ############## ###### ############ ######## ############ ######## ################## ################## ############## ############## ###### ###### ``` [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), ~~210~~ 193 Bytes Saved some bytes by switching 0=' ' 1='##' to 1=' ' 0=' ', this means i don't need to add the extra zeros back. Also, this means that now the B64 string that used to say "MAFIA" does not, This is sad. ``` 'n' = => 64 -B 2 B ] 1 16 sub n rep \ 17 32 sub n rep ' ' \ . . '1' ' ' replace '0' '##' replace } a'' = D4D/4/'' a DgQ/AH'' a DAIeAj'' a DgA8AB'' a DwB+AD'' a DcH/wf'' a D+/29/'' a Dz/63/'' a ``` ## Explanation ``` 'n' = # Associate the input with "n" => # Push a new function to the stack. 64 -B # Take the value from the top of the stack, convert it to an integer from Base64 2 B # Take the value from the top of the stack, convert it from an integer to binary ] # Duplicate the top of the stack. 1 16 sub # Push the substring from the top of the stack between 1 and 16, 1 indexed. n # Push the input. rep # Repeat, this gives us 'n' bombs, essentially. \ # Flip the values such that REPEATEDBOMB_ROW TEXT 17 32 sub # Push the substring between 17 and 32. n # Push the input rep # Repeat ' # Push a new line ' # RProgN doesn't actually have escapes, so the raw newline is represented as a newline between qoutes. \ . . # Flip the values so we have LINE1 NEWLINE LINE2, then concatenate them all into one string. '1' ' ' replace # Replace all the 1's in the binary string with two spaces. '0' '##' replace # Replace all the 1's with two '#'s } a'' = # Associate the function with 'a' D4D/4/'' a # Bottom two lines, DgQ/AH'' a # Next two up, DAIeAj'' a # Etc... DgA8AB'' a # Once This is done, the memory stack is implicitly printed from top to bottom. DwB+AD'' a # As such, the bomb is upside down. DcH/wf'' a # Each of these numbers represents two lines, which is why we do the substringing to split it. D+/29/'' a # This works out saving a few bytes. Dz/63/'' a # Implicitly printed output. Yay. ``` Pretty long, The expanding, printing and such of the compressed string is 105 of the bytes. Might be a bit more golfable, but atleast it works. Input is implicitly on the stack, stack is implicitly printed. ## Output ``` #### #### #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ########## ## ########## ## ########## ########## ########## ########## ################## ################## ################## ###################### ###################### ###################### ###################### ###################### ###################### ########################## ########################## ########################## ################ ######## ################ ######## ################ ######## ############## ###### ############## ###### ############## ###### ############ ######## ############ ######## ############ ######## ################## ################## ################## ############## ############## ############## ###### ###### ###### ``` ## Try it! ``` <style> #frame{ width:60em; height:60em; border:none; } </style> <iframe id='frame' src="https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%27n%27%20%3D%20%3D%3E%2064%20-B%202%20B%20%5D%201%2016%20sub%20n%20rep%20%5C%2017%2032%20sub%20n%20rep%20%27%0A%27%20%5C%20.%20.%20%271%27%20%27%20%20%27%20replace%20%270%27%20%27%23%23%27%20replace%20%7D%20a%27%27%20%3D%20D4D%2F4%2F%27%27%20a%20DgQ%2FAH%27%27%20a%20DAIeAj%27%27%20a%20DgA8AB%27%27%20a%20DwB%2BAD%27%27%20a%20DcH%2Fwf%27%27%20a%20D%2B%2F29%2F%27%27%20a%20Dz%2F63%2F%27%27%20a&input=1">Sorry, You need to support IFrame. Why don't you..?</iframe> ``` [Answer] # PHP, ~~144~~ ~~140~~ ~~139~~ ~~138~~ 136 bytes Note: uses Windows-1252 encoding ``` for(;$j%=32*$argn or$r=intval(substr("01c02203k07d1j81j46b4cmwcmwpa4ohobugc8o6b434w0ow",$i++*3,3),36)*print~õ;)echo~ßÜ[$r>>$j++/2%16&1]; ``` Run like this: ``` echo 2 | php -nR 'for(;$j%=32*$argn or$r=intval(substr("01c02203k07d1j81j46b4cmwcmwpa4ohobugc8o6b434w0ow",$i++*3,3),36)*print~õ;)echo~ßÜ[$r>>$j++/2%16&1];' ``` Or using IBM-850 encoding (135 bytes and prettier result): ``` echo 2 | php -nR 'for(;$j%=32*$argn or$r=intval(substr(~¤╬£¤══¤╠ö¤╚ø╬òÃ╬ò╦╔Ø╦£Æê£ÆêÅ×╦ÉùÉØèÿ£ÃÉ╔Ø╦╠╦ê¤Éê,$i++*3,3),36)*print~§;)echo~▀M[$r>>$j++/2%16&1];' ▓▓▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓ ``` # Explanation This doesn't do any binary stuff and doesn't require an external file. Every 16 bit number is reversed, then encoded as a base-36 number, padded with a leading `0` if necessary, so every 16 bits result in 3 bytes. Concatenating those results in `01c02203k07d1j81j46b4cmwcmwpa4ohobugc8o6b434w0ow`. The code reverses the process so the bombs are printed correctly `N` times. # Tweaks * Saved 4 bytes by using only a single for-loop * Saved a byte by printing a single char for each iteration and using string index instead of ternary * Saved a byte by getting resetting `$j` to zero on line boundaries with `%=`. This gets rid of parentheses * Saved 2 bytes by using `$argn` [Answer] # GCC C 129 bytes ### ISO8859/ASCII ``` f(r,i,d){ for(;i<32;i+=2,puts("")) for(d=15*r;--d;) printf((*(int*)&("ÿóÿ­ÿþoÜüðààÀ!ÀCÀCàðø?þ"[i]))&(1<<d%15)?" ":"##"); } ``` In one line: ``` f(r,i,d){for(;i<32;i+=2,puts(""))for(d=15*r;--d;)printf((*(int*)&("ÿóÿ­ÿþoÜüðààÀ!ÀCÀCàðø?þ"[i]))&(1<<d%15)?" ":"##");} ``` Run with: ``` main(c,v)char**v;{f(atoi(v[1]),0)} ``` Compile source as ISO8859-x (ASCII). NB óÿ­ÿþÿoÜüðààÀÀ!ÀCàCðøþ? should contain the invisible ASCII Codes but it has been broken due to the way StackExchange presents its content. Please see the ideaone link for proper test encoding Alternatively the original ASCII String is at : <https://github.com/claydonkey/AtariBombs/blob/master/ISO8859_REPR2.txt> ## Explanation First a conversion of the hex representation of bombs [f3 ff ad ff fe ff 6f 7f dc 1f fc 1f f0 07 e0 03 e0 03 c0 01 c0 21 c0 43 e0 43 f0 07 f8 0f fe 3f] to UTF-8 (in the UTF-8 version the compiler stores the string as Wide Char Array - 2 or 4 bytes for each character at runtime but this is academic). Whereas UTF-8 characters would be stored as 2-4 bytes, these values are all within ISO-8859-1 (ASCII) and thus only require 1 byte. Also it is safe to be stored as ISO-8859-x (there are no 0x8\_ or 0x9\_ values). Therefore the text consumes 32 bytes in ISO-8859 and the routine consumes 135 bytes in total. (NB wide chars are stored as a 16 bit integer in windows and 32bit in linux but again this is irrelevant to the task at hand) Caveat: Not all the characters are displayable (the control characters below 0x20) .They are, however still present . Most web pages are utf-8/ 8859/1253 (<https://w3techs.com/technologies/overview/character_encoding/all>) so I reckon this is legit~~(shifting all values below 0x20 to printable ASCII should fix that).~~ ### UTF-8 Here is the version closer to the original posting with UTF-8 encoded source. This consumes 173 bytes. The string itself being 50 bytes of the source. The routine is also longer as the ASCII bytes are now stored with padding 0's for the 16bit/32bit Wide Chars and have to be shifted instead of casted to uint16\_t as above. I have kept this up as it can be verified with ideone which uses UTF-8 encoding. ``` *w=L"óÿ­ÿþÿoÜüðààÀÀ!ÀCàCðøþ?"; f(r,i,j,m){ for(i;i<32;i+=2,puts("")) for(j=r;j--;) for(m=65536;m>1;(m\=2,printf(((w[i]<<8)+w[i+1]&m)?" ":"##")));} ``` Run with: ``` main(c,v)char**v;{f(atoi(v[1]),0)} ``` If you can set the implicit value to a 16bit integer in your complier you can omit the wchar\_t type declaration of the Wide Char. Ideone doesn't complain so I reckon it's good to go. **Try it out** on [ideone](http://ideone.com/jcR3qG) [Answer] ## Haskell, 155 bytes As a function with type `Int -> String`: ``` b z=concat$do y<-[0..15];"\n":[if odd$div 0x3800FE01FF03DF83BF87BFC7FFC3FF83FF81FF007C007C401090080004A0030(2^(16*y+x))then"##"else" "|x<-[1..z]>>[0..15]] ``` Printing to IO directly will cost 5 bytes (or 6 if we prefer to return `IO ()` rather than `IO [()]`): ``` b z=mapM putStr$do y<-[0..15];"\n":[if odd$div 0x3800FE01FF03DF83BF87BFC7FFC3FF83FF81FF007C007C401090080004A0030(2^(16*y+x))then"##"else" "|x<-[1..z]>>[0..15]] ``` [Answer] ### C, 175 bytes ``` x[]={48,74,128,265,1988,1984,8176,16376,16376,32764,31740,15352,15864,8176,4064,896};f(z,p){while(z++<16){p=1;while(p<<=1){printf("%s",p&(x[z]<<16|x[z])?"##":" ");}puts("");}} ``` concatenates each x to itself and makes p overflow to end each line. [Answer] ## Java, 228 bytes ``` import static java.lang.System.out; public class Bombs { public static void main(String[] args) { new Bombs().d(2); new Bombs().d(3); new Bombs().d(4); } void d(int n){String s="";for(int x=16,r=0;r<16*n;x=16,s+=(++r%n==0?"\n":""))while(--x>=0)s+=((new int[]{1536,10496,128,18496,4592,496,2044,4094,4094,8191,8175,4078,4062,2044,1016,224}[r/n])&(1<<x))==0?" ":"##";out.println(s);} } ``` [Answer] # J, 89 bytes ``` |:@;@#&(<' #'{~2#|:16 16$}.2#.inv 95#.32x-~3 u:'u,:C>%}UwPXHn_C9wF.|U ap<{jH%O9 9wRThGs') ``` Encodes the string as a base-95 number, increments each digit by `32`, then represents it by an ascii string. ## Explanation This is composed of two main parts. There is the constructing of the bomb, and the actual repetition. Let's for the moment refer to the bomb as `b`. Then, the code looks like: ``` |:@;@#&(b) ``` When called with input `k`, this is equivalent to: ``` |: ; (k#b) ``` `b` is a boxed bomb, so `k#b` makes `k` repetitions of `b`, `;` flattens it vertically, and `|:` transposes the result. (The bomb `b` is itself constructed transposed.) Now, here is the bomb: ``` <' #'{~2#|:16 16$}.2#.inv 95#.32x-~3 u:'u,:C>%}UwPXHn_C9wF.|U ap<{jH%O9 9wRThGs' ``` The string following is a base-95 encoded string with an offset of `32`, so that all the characters fall into the ASCII range, and thankfully there are no `'`s that need to be escaped. `3 u:` gets the char codes of the string, `32x-~` makes each number an e`x`tended number and subtracts `32` from it; `95#.` converts to a base-95 number an `2#.inv` converts it to a binary digit array. I added a leading `1` to the binary in order to make it a solid number, so I take it off with `}.`. I shape the array into a 16x16 table with `16 16$` then transpose it using `|:`. (Possible golf for later: transpose the literal encoded string.) `2#` duplicates each character width-wise. We are left with a table of `0`s and `1`s. `' #'{~` maps `0`s to `' '` and `1` to `'#'`. As thus, we are left with our bomb. ## Test case ``` |:@;@#&(<' #'{~2#|:16 16$}.2#.inv 95#.32x-~3 u:'u,:C>%}UwPXHn_C9wF.|U ap<{jH%O9 9wRThGs') 3 #### #### #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ########## ## ########## ## ########## ########## ########## ########## ################## ################## ################## ###################### ###################### ###################### ###################### ###################### ###################### ########################## ########################## ########################## ################ ######## ################ ######## ################ ######## ############## ###### ############## ###### ############## ###### ############ ######## ############ ######## ############ ######## ################## ################## ################## ############## ############## ############## ###### ###### ###### ``` [Answer] # **[BaCon](http://www.basic-converter.org), ~~229~~ ~~227~~ 195 bytes** A contribution in BASIC for sake of nostalgia. The variable 'a' determines the amount of bombs. ``` a=2:FOR x=0 TO 15:FOR y=1 TO a:FOR i=15 DOWNTO 0:?IIF$(v[x]&INT(POW(2,i)),"##"," ");:NEXT:NEXT:?:NEXT:LOCAL v[]={3072,20992,256,36992,9184,992,4088,8188,8188,16382,16350,8156,8124,4088,2032,448} ``` **Output**: ``` #### #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ########## ## ########## ########## ########## ################## ################## ###################### ###################### ###################### ###################### ########################## ########################## ################ ######## ################ ######## ############## ###### ############## ###### ############ ######## ############ ######## ################## ################## ############## ############## ###### ###### ``` [Answer] ## Haskell, ~~191~~ 181 bytes ``` f n=h n:f(div n 2) h n|odd n=' ' h _='#' g b=mapM_ putStrLn[[f 0xfc7ff01fe00fc207c40784038003c007c007e00ff83ff83bfef6ff7fffb5ffcf!!(x`mod`32`div`2+y*16)|x<-[0..32*b-1]]|y<-[0..15]] ``` [Answer] # C (Atari TOS 2.06 US), ~~129 124 117~~ 113 bytes ``` short*a=0xe013b0;main(j,l)char**l;{for(;*a++-224;puts(""))for(j=*l[1]*16-768;j--;printf(*a&1<<j%16?"##":" "));} ``` This uses the bomb bitmap from the TOS ROM, which is slightly different from the one in the question. For other versions of TOS, you'll have to adjust the address pointed to by `*a`. Note that some emulator roms don't include the bomb bitmap! If you don't provide a command line argument, several high resolution bitmapped bombs may be displayed :-) [Answer] # Excel VBA, 204 Bytes Anonymous VBE Immediate window function that takes input from the range `[A1]` and outputs to the ActiveSheet Object ``` Cells.RowHeight=48:For i=0To[A1-1]:[A4,B2,C5,D4,D2,E1:F1,G2,H3,I4,G5:K6,E7:M7,D8:N9,C10:J11,K10:O10,O11,L11:N13,K13:K15,L14:L15,M14,D12:I13,J12,E14:G14,F15:G15,H14:J16].Offset(,16*i).Interior.Color=0:Next ``` ### Output [![Babomb](https://i.stack.imgur.com/tzY5M.png)](https://i.stack.imgur.com/tzY5M.png) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 49 bytes ``` »ƛ¢y⇧↲⁽¹ŀuḂHŻḊ`I5□‡+vġ¯=<↓ d→YCnȧr»‛# τ16ẇƛ⁰*ƛd;ṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%C6%9B%C2%A2y%E2%87%A7%E2%86%B2%E2%81%BD%C2%B9%C5%80u%E1%B8%82H%C5%BB%E1%B8%8A%60I5%E2%96%A1%E2%80%A1%2Bv%C4%A1%C2%AF%3D%3C%E2%86%93%20d%E2%86%92YCn%C8%A7r%C2%BB%E2%80%9B%23%20%CF%8416%E1%BA%87%C6%9B%E2%81%B0*%C6%9Bd%3B%E1%B9%85&inputs=3&header=&footer=) [Answer] ### C++11, 252 bytes ``` #include <iostream> using namespace std;string d("01c02203k07d1j81j46b4cmwcmwpa4ohobugc8o6b434w0ow");int main(){for(int i=0;i!=45;i+=3){int z=stoi(d.substr(i,3),NULL,36);for(unsigned long p=1;p!=1<<31;p<<=1){cout<<(((z<<16|z)&p)?"##":" ");}puts("");}} ``` [Answer] # SmileBASIC, 127 bytes ``` INPUT N FOR J=0TO 15FOR K=1TO N FOR I=0TO 14?" #"[1AND ASC("xxxxxxxxxxxxxxx"[I])>>J]*2; NEXT NEXT?NEXT ``` [![screenshot](https://i.stack.imgur.com/OUfXA.jpg)](https://i.stack.imgur.com/OUfXA.jpg) (Screenshot of version without doubled characters) SB has a square font, so doubling the characters looks bad (and doesn't fit on the screen) Non-ASCII characters have been replaced by `x`'s. Hex values: `0008,0002,0610,1F8A,3FC1,7FC1,7FF2,FFF4,FFF8,EFF0,73F0,7FC0,3FC0,1F80,0600` Since SB saves files in UTF-8, some of these count as 2 or 3 bytes. ]
[Question] [ PPCG user and elected mod, [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) just became the second ever user to earn over 100k rep! [![enter image description here](https://i.stack.imgur.com/5ME5N.png)](https://i.stack.imgur.com/5ME5N.png) This is a totally original idea, that I [did not get from anybody else](https://codegolf.stackexchange.com/questions/57719/generate-dennis-numbers), but let's make a challenge based off of his user ID, `12012` as a tribute! Looking at it, you'll notice that there are two distinct "sections" to his ID. > > 12 > > > and > > 012 > > > Both of these sections add up to a 3. That's a pretty interesting property. Let's define a "Dennis 2.0 number" as any positive integer where every maximal subsequence of strictly increasing digits sums to the same number. For example, ``` 123 ``` is a Dennis 2.0 number because there is only one maximal sublist of strictly increasing digits, and it sums to 6. Additionally, 2,846,145 is also a Dennis 2.0 number because the three maximal sublists of increasing digits, namely ``` 28 46 145 ``` All sum to `10`. Additionally, numbers that just repeat the same digit *must* be Dennis 2.0 numbers because, for example, `777` can be broken down into ``` 7 7 7 ``` which *clearly* all sum to seven. A number such as `42` is *not* a Dennis 2.0 number, since it is broken down into ``` 4 2 ``` which clearly do not sum to the same number. # The challenge You must write a program or function to determine if a given number is a Dennis 2.0 number or not. You can take input and output in any reasonable input format, e.g. as a string, as a number, from a file, funtion arguments/return, from STDIN/STDOUT, etc. and then return a [truthy value](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) if this number is a Dennis 2.0 number, and a falsy value if it is not. For reference, here is every Dennis 2.0 number up to 1,000: ``` 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 22 23 24 25 26 27 28 29 33 34 35 36 37 38 39 44 45 46 47 48 49 55 56 57 58 59 66 67 68 69 77 78 79 88 89 99 101 111 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 202 222 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 303 312 333 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 404 413 444 456 457 458 459 467 468 469 478 479 489 505 514 523 555 567 568 569 578 579 589 606 615 624 666 678 679 689 707 716 725 734 777 789 808 817 826 835 888 909 918 927 936 945 999 ``` Standard loopholes apply, and the shortest answer measured in bytes wins! [Answer] ## JavaScript (ES6), ~~72~~ 70 bytes Takes a string as input. Returns either false or a truthy value (which can be a number). It's using a regular expression to transform an input string such as `"2846145"` into: ``` "(a=2+8)&&(a==4+6)&&(a==1+4+5)" ``` Then calls `eval()` on this expression. ``` let f = n=>eval(n.replace(/./g,(v,i)=>(v>n[i-1]?'+':i?')&&(a==':'(a=')+v)+')') console.log(f("101")); console.log(f("102")); console.log(f("777")); console.log(f("2846145")); ``` [Answer] # Jelly, ~~13~~ 12 bytes *1 byte thanks to @Dennis.* ``` DIṠ’0;œṗDS€E ``` [Try it online!](http://jelly.tryitonline.net/#code=REnhuaDigJkwO8WT4bmXRFPigqxF&input=&args=Mjg0NjE0NQ) ### Explanation ``` DIṠ’0;œṗDS€E Main link. Argument: N D Convert N to its digits. I Find the differences between the elements. Ṡ Find the sign of each difference. This yields 1 for locations where the list is strictly increasing and 0 or -1 elsewhere. ’ Decrement. This yields 0 for locations where the list is strictly increasing and -1 or -2 elsewhere. 0; Prepend a 0. D Get another list of digits. œṗ Split the list of digits at truthy positions, i.e. the -1s and -2s. S€ Sum each sublist. E Check if all values are equal. ``` [Answer] # Python, 50 bytes ``` r='0' for d in input():r=d+'=+'[r<d]*2+r 1/eval(r) ``` Expects `input()` to evaluate to a string, so the input needs surrounding quotes in Python 2. Output is via [exit code](https://codegolf.meta.stackexchange.com/a/5330/12012), where **0** indicates success (truthy) and **1** indicates failure (falsy). Test it on [Ideone](http://ideone.com/pmwd1X). ### How it works We initialize **r** to the string **0** and iterate over all digits **d** in the input. * If **d** is larger than the first digit of **r** (initially **0**, then equal to the previous value of **d**), `r<d` evaluates to *True* and `'=+'[r<d]*2` yields `++`. * If **d** is smaller than the first digit of **r**, `'=+'[r<d]*2` yields `==`. * If **d** is equal to the first digit of **r**, **r** will be longer than the singleton string **d**, so `'=+'[r<d]*2` yields once again `==`. In all cases, the digit **d** and the two generated characters get prepended to **r**. Once all input digits have been processed, `eval(r)` evaluates the generated expression. * If the input consists of a single strictly increasing sequence of (positive) digits, the expression evaluates to their sum. For example, the integer **12345** results in the expression `5++4++3++2++1++0`, which yields **15** when evaluated. Note that each second **+** is a *unary* plus, so it doesn't affect the result. Dividing **1** by **15** is valid (the result is not important); the program exits normally. * If the input consists of two strictly increasing sequences of digits, the expression consists of a simple comparison. For example, the integer **12012** results in the expression `2++1++0==2++1++0`, which yields *True* when evaluated since both terms have sum **3**. Dividing **1** by *True* (**1**) is valid (the result is not important); the program exits normally. On the other hand, the integer **12366** results in the expression `6==6++3++2++1++0`, which yields *False* when evaluated since the terms have sums **6** and **12**. Dividing **1** by *False* (**0**) raises a *ZeroDivisionError*; the program exits with an error. * If the input consists of three or more strictly increasing sequences of digits, the expression consists of a [chained comparison](https://docs.python.org/3/reference/expressions.html#comparisons), which returns *True* if and only if all involved comparisons return *True*. For example, the integer **94536** results in the expression `6++3==5++4==9++0`, which yields *True* when evaluated since all terms have sum **9**. As before, the program exits normally. On the other hand, the integer **17263** results in the expression `3==6++2==7++1++0`, which yields *False* when evaluated since the terms have sums **3**, **8**, and **8**. As before, the program exits with an error. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 13 bytes ``` ~c@e:{<+}a!#= ``` [Try it online!](http://brachylog.tryitonline.net/#code=fmNAZTp7PCt9YSEjPQ&input=NTc1) ### Explanation ``` ~c Find a list of integers which when concatenated result in the Input @e Split the integers into lists of digits :{<+}a Each list of digit is stricly increasing, and compute its sum ! Discard all other choice points (prevents backtracking for smaller sublists) #= All sums must be equal ``` `~c` will unify with the biggest sublists first. [Answer] ## Pyke, 18 bytes ``` mb$1m>0R+fMbms}lt! ``` [Try it here!](http://pyke.catbus.co.uk/?code=mb%241m%3E0R%2BfMbms%7Dlt%21&input=%22835%22) ``` mb - map(int, input) $ - delta(^) 1m> - map(^, 1>i) 0R+ - [0]+^ f - input.split_at(^) Mb - deep_map(int, ^) ms - map(sum, ^) } - uniquify(^) lt! - len(^) == 1 ``` [Answer] ## PowerShell v2+, ~~100~~ ~~64~~ 61 bytes ``` -join([char[]]$args[0]|%{("+$_","-eq$_")[$_-le$i];$i=$_})|iex ``` A literal one-liner, as this is all one pipeline. Takes input as a string `$args[0]`. Loops through it as a `char`-array, each iteration placing either the current element with a `+` or `-eq` in front of it onto the pipeline based on whether the current value is `-l`ess-than-or-`e`qual to the previous value `$i`. Those strings are `-join`ed together and piped to `iex` (short for `Invoke-Expression` and similar to `eval`. For example, for input `2846145` this will be evaluated as `+2+8-eq4+6-eq1+4+5`, which is `True`. That Boolean is left on the pipeline, and `True`/`False` is implicitly written at program completion. *NB - for single-digit input, the resulting digit is left on the pipeline, which is a truthy value in PowerShell.* ### Examples ``` PS C:\Tools\Scripts\golfing> 2846145,681,777,12366,2|%{"$_ -> "+(.\dennis-number-20.ps1 "$_")} 2846145 -> True 681 -> False 777 -> True 12366 -> False 2 -> 2 ``` [Answer] # GNU sed 217 or 115 Both include +1 for -r **217:** ``` s/./&,/g;s/^/,/g;:;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*)\1,/\1\2X\1,/;t;s/,//g s,1X1(1*),X\1a,;t;/^1.*X/c0 /Xa*$/s,a*$,,;y,a,1,;/1X1/b;/1X|X1/c0 c1 ``` Takes input in normal decimal [Try it online!](http://sed.tryitonline.net/#code=cy8uLyYsL2c7cy9eLywvZzs6O3MsMCwsO3MsMiwxMSw7cywzLDIxLDtzLDQsMzEsO3MsNSw0MSw7cyw2LDUxLApzLDcsNjEsO3MsOCw3MSw7cyw5LDgxLDt0O3MvKCwxKikoMSopXDEsL1wxXDJYXDEsLzt0O3MvLC8vZwpzLDFYMSgxKiksWFwxYSw7dDsvXjEuKlgvYzAKL1hhKiQvcyxhKiQsLDt5LGEsMSw7LzFYMS9iOy8xWHxYMS9jMApjMQ&input=MTIzCjI4NDYxNDUKNzc3CjQy&args=LXI) --- **115:** ``` s/^|$/,/g;:;s/(,1*)(1*)\1,/\1\2X\1,/;t;s/,//g s,1X1(1*),X\1a,;t;/^1.*X/c0 /Xa*$/s,a*$,,;y,a,1,;/1X1/b;/1X|X1/c0 c1 ``` Takes input as a comma separated list of the numbers digits in unary. e.g. `123` would be `1,11,111` [Try it online!](http://sed.tryitonline.net/#code=cy9efCQvLC9nOzo7cy8oLDEqKSgxKilcMSwvXDFcMlhcMSwvO3Q7cy8sLy9nCnMsMVgxKDEqKSxYXDFhLDt0Oy9eMS4qWC9jMAovWGEqJC9zLGEqJCwsO3ksYSwxLDsvMVgxL2I7LzFYfFgxL2MwCmMx&input=MSwxMSwxMTEKMTEsMTExMTExMTEsMTExMSwxMTExMTEsMSwxMTExLDExMTExCjExMTExMTEsMTExMTExMSwxMTExMTExCjExMTEsMTE&args=LXI) [Answer] ## Perl, 38 + 3 (`-p`) = 41 bytes *-9 bytes thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) !* ``` s%.%2x$&.(~$&le~$')%eg;$_=/^(2+1)\1*$/ ``` Since there is a `$'`, the code needs to be in a file to run. So `-p` counts for 3 bytes. Outputs 1 if the number is a Dennis 2.0 number, or an empty string otherwise : ``` $ cat dennis_numbers.pl s%.%2x$&.(~$&le~$')%eg;$_=/^(2+1)\1*$/ $ perl -p dennis_numbers.pl <<< "1 10 12315 12314" ``` [Answer] # JavaScript (ES6), ~~66~~ ~~65~~ 63 bytes *Saved 2 bytes thanks to @edc65* ``` x=>[...x,p=t=z=0].every(c=>p>=(t+=+p,p=c)?(z?z==t:z=t)+(t=0):1) ``` Takes input as a string. Old version (only works in Firefox 30+): ``` x=>[for(c of(p=t=0,x))if(p>=(t+=+p,p=c))t+(t=0)].every(q=>q==+p+t) ``` [Answer] # Mathematica, 38 bytes ``` Equal@@Tr/@IntegerDigits@#~Split~Less& ``` Anonymous function. Takes a number as input, and returns `True` or `False` as output. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) 2, 10 bytes, language postdates challenge ``` ẹ~c<₁ᵐ!+ᵐ= ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9w1866ZJtHTY0Pt05Q1AYStv//G5mYmQEA "Brachylog – TIO Nexus") This is basically the same algorithm as @Fatalize's answer (which I didn't see until after I'd written this), but rearranged somewhat to make it golfier under Brachylog 2's syntax. It's a full program, returning `false.` if it isn't a Dennis 2.0 number, or `true` if it is. ## Explanation ``` ẹ~c<₁ᵐ!+ᵐ= ẹ Interpret the input number as a list of digits ! Find the first (in default order) ~c partition of the digits <₁ᵐ such that each is in strictly increasing order = Assert that the following are all equal: +ᵐ the sums of each partition ``` As usual for a Brachylog full program, if all the assertions can be met simultaneously, we get a truthy return, otherwise falsey. The default order for `~c` is to sort partitions with fewer, longer elements first, and in Prolog (thus Brachylog), the default order's defined by the first predicate in the program (using the second as a tiebreak, and so on; here, `~c` dominates, because `ẹ` is deterministic and thus has nothing to order). [Answer] # MATL, ~~24~~ ~~23~~ ~~20~~ ~~18~~ 16 bytes ``` Tjdl<vYsG!UlXQ&= ``` Returns a [truthy of falsey](http://matl.tryitonline.net/#code=YAppdEQKPwonVFJVRSdECn0KJ0ZBTFNFJ0QKXVQKCg&input=WzEgMSAxOyAxIDEgMTsgMSAxIDFdClsxXQpbMSAwIDA7IDAgMSAwOyAwIDAgMV0KWzEgMSAxOyAxIDAgMTsgMSAxIDFd) matrix [**Try it Online!**](http://matl.tryitonline.net/#code=VGpkbDx2WXNHIVVsWFEmPQ&input=Mjg0NjE0NQ) Also, congrats @Dennis! **Explanation** ``` T % Push a literal TRUE to the stack % STACK: {1} j % Explicitly grab the input as a string % STACK: {1, '2846145'} d % Compute the difference between successive ASCII codes % STACK: {1, [6 -4 2 -5 3 1]} l< % Find where that difference is less than 1 % STACK: {1, [0 1 0 1 0 0]} v % Prepend the TRUE value we pushed previously % STACK: {[1 0 1 0 1 0 0]} Ys % Compute the cumulative sum. This assigns a unique integer label to % each set of increasing numbers % STACK: {[1 1 2 2 3 3 3]} G!U % Grab the input as numeric digits % STACK: {[1 1 2 2 3 3 3], [2 8 4 6 1 4 5]} lXQ % Compute the sum of each group of increasing digits % STACK: {[10 10 10]} &= % Computes element-wise equality (automatically broadcasts). A % truthy value in MATL is a matrix of all ones which is only the case % when all elements are equal: % STACK: {[1 1 1 % 1 1 1 % 1 1 1]} % Implicitly display the result ``` [Answer] ## PHP, ~~108~~ ~~105~~ 92 bytes ``` $p=-1;foreach(str_split("$argv[1].")as$d)$p>=$d?$r&&$s-$r?die(1):($r=$s)&$s=$p=$d:$s+=$p=$d; ``` takes input from argument, exits with `0` for Dennis-2.0 number, with `1` else. **breakdown** ``` $p=-1; // init $p(revious digit) to -1 foreach(str_split("$argv[1].")as$d) // loop $d(igit) through input characters // (plus a dot, to catch the final sum) $p>=$d // if not ascending: ?$r // do we have a sum remembered &&$s-$r // and does it differ from the current sum? ?die(1) // then exit with failure :($r=$s)&$s=$p=$d // remember sum, set sum to digit, remember digit :$s+=$p=$d // ascending: increase sum, remember digit ; // ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 18 bytes ``` SD¥X‹X¸«DgL*ꥣOÙg ``` **Explanation** `N = 12012` used as example. ``` # implicit input N = 12012 S # split input number to list of digits # STACK: [1,2,0,1,2] D # duplicate # STACK: [1,2,0,1,2], [1,2,0,1,2] ¥ # reduce by subtraction # STACK: [1,2,0,1,2], [1,-2,1,1] X‹ # is less than 1 # STACK: [1,2,0,1,2], [0,1,0,0] X¸« # append 1 # STACK: [1,2,0,1,2], [0,1,0,0,1] DgL* # multiply by index (1-indexed) # STACK: [1,2,0,1,2], [0,2,0,0,5] ê # sorted unique # STACK: [1,2,0,1,2], [0,2,5] ¥ # reduce by subtraction # STACK: [1,2,0,1,2], [2,3] £ # split into chunks # STACK: [[1,2],[0,1,2]] O # sum each # STACK: [3,3] Ù # unique # STACK: [3] g # length, 1 is true in 05AB1E # STACK: 1 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=U0TCpVjigLlYwrjCq0RnTCrDqsKlwqNPw5ln&input=MjQ1MTI4MDI5) [Answer] # Ruby 2.3, 56 bytes ``` p !gets.chars.chunk_while(&:<).map{|a|eval a*?+}.uniq[1] ``` Almost certainly not the golfiest way to do this, but it shows off some nice language features. (Not newline-tolerant, so run like `ruby dennis2.rb <<< '12012'`) [Answer] # PHP, 144 bytes ``` <?php preg_match_all("/0?1?2?3?4?5?6?7?8?9?/",$argv[1],$n);foreach($n[0]as$i)if(strlen($i)&&($a=array_sum(str_split($i)))!=$s=$s??$a)die;echo 1; ``` I'm sure there's a much cleverer (and shorter) way to do this but it will do for now. [Answer] ## Python 2, 69 bytes Takes input as a string. ``` lambda I:len(set(eval(reduce(lambda x,y:x+',+'[y>x[-1]]+y,I+' '))))<2 ``` Explanation: ex `1201212012` Converts to list of sums: `1+2,0+1+2,1+2,0+1+2,` Evals and converts to set. `set([3])` If the length of the set is 1, all sums are the same. [Answer] # JavaScript (ES6), 58 ``` s=>![...s,z=x=p=0].some(c=>[c>p?0:z-=(x=x||z),z-=p=c][0]) ``` Applying my rarely useful tip <https://codegolf.stackexchange.com/a/49967/21348> It scans the string char by char identifying run of ascending chars, at the end of each rum it checks if the sum is always the same * c : current char * p : previous char * z : running sum, at the end of a run will be compared to ... * x : sum to compare against, at first run is simply made equal to z **Test** ``` f= s=>![...s,z=x=p=0].some(c=>[c>p?0:z-=(x=x||z),z-=p=c][0]) function run() { var i=I.value O.textContent = i + ' -> ' + f(i) } run() test=`1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 22 23 24 25 26 27 28 29 33 34 35 36 37 38 39 44 45 46 47 48 49 55 56 57 58 59 66 67 68 69 77 78 79 88 89 99 101 111 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 202 222 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 303 312 333 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 404 413 444 456 457 458 459 467 468 469 478 479 489 505 514 523 555 567 568 569 578 579 589 606 615 624 666 678 679 689 707 716 725 734 777 789 808 817 826 835 888 909 918 927 936 945 999`.split` ` numerr=0 for(i=1; i<1000; i++) { v = i + ''; r = f(v); ok = r == (test.indexOf(v) >= 0) if (!ok) console.log('Error',++numerr, v) } if(!numerr) console.log('All test 1..999 ok') ``` ``` <input id=I value=612324 type=number oninput='run()'> <pre id=O> ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes Two versions ``` !t{sMcJjQThMx1<R0.+J LS{b!t{sMhyI#I#./jQT ``` [Try the first one online!](http://pyth.herokuapp.com/?code=%21t%7BsMcJjQThMx1%3CR0.%2BJ&test_suite=1&test_suite_input=101%0A102%0A777%0A2846145&debug=0) [Try the second one online!](http://pyth.herokuapp.com/?code=LS%7Bb%21t%7BsMhyI%23I%23.%2FjQT&test_suite=1&test_suite_input=101%0A102%0A777%0A2846145&debug=0) [Answer] # Ruby, ~~117~~ ~~105~~ 85 bytes ``` # original (117): j,k=0,?0;"#{i}".chars.group_by{|n|n>k||j=j+1;k=n;j}.values.map{|a|a.map(&:to_i).reduce(&:+)}.reduce{|m,n|n==m ?m:nil} # inspired by PHP regexp approach (105): "#{i}".scan(/0?1?2?3?4?5?6?7?8?9?/).map{|a|a.chars.map(&:to_i).reduce(&:+)}.reduce{|m,n|!n||n==m ?m:nil} # some number comparison simplification (85): !"#{i}".scan(/0?1?2?3?4?5?6?7?8?9?/).map{|a|a.chars.map(&:to_i).reduce(&:+)}.uniq[1] ``` This would return the integer of this dennis number or `nil` if not a dennis number. All integers will be considered true in ruby as well `nil` is considered false. `i` is the integer that is being check. Third version actually returns `true` and `false`. P.S. tested to return 172 integers from 1 to 1000 as in the answer. [Answer] # APL, 23 bytes ``` {1=≢∪+/↑N⊂⍨1,2>/N←⍎¨⍕⍵} ``` Explanation: * `N←⍎¨⍕⍵`: get the individual digits in the input, store in `N` * `N⊂⍨1,2>/N`: find the sublists of strictly increasing numbers in `N` * `+/↑`: sum each sublist * `1=≢∪`: see if the resulting list has only one unique element [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 109 bytes ``` D,g,@@#,BF1_B D,k,@@#,bR$d@$!Q@BFB D,f,@,BDdVÑ_€?1€_0b]$+€?dbLRBcB*BZB]GbL1+b]+qG€gd€bLÑ_0b]$+BcB]£k€¦+Ñ=1$ª= ``` [Try it online!](https://tio.run/##TY7fasIwGMWvm6fousDAhtHUP9sKupAVZSDIvPBiWDqzVKnOrGurFJw3ewOfYbCLsaeob7IXcV@KDG9OzvfL@XIykTJJDgefzAhj54R3aciRTxbVJIZYMnz2wHhXwylhhPtytN@Fvx8/txQkdESAbT1J0R/yZ17jjzzoiT61RWC/9eBmJkFEH5aqLGSC8nMBrPyy97s2xeV3G/qzPIXnkWFdWJLN1wj6lpNYEeYBlJvpFhl4A6HtUQGOsC6i4XvdvavNEcJ6oUPdeuvfOtQ9eve60aKN5kmodeqbV/UbhArPGis/UirOTPfSMdVqKaI0M1eJmb@a1HEcb6wsNCgQeomXce5phLqVh2/GSkaFF4N7SiMN8LRTMbD3msBpDCpy@AM "Add++ – Try It Online") ## How it works We define our 3 functions, \$f\$, \$g\$ and \$k\$. \$f\$ is the main function, which transforms the input to the correct output. ### \$f(x)\$ First, we convert the input \$x\$ into a list of digits, then take the forward increments. Next, we take the sign of each increment. For increasing subsequences, this yields a subsequence of \$1\$, for equal subsequences, such as \$[4, 4, 4]\$, this yields \$0\$s and for decreasing sections, \$-1\$ is returned. We then take the complement of each of these signs, to turn \$1\$ into a falsey value, and everything else into a truthy value. Next, \$0\$ is prepended to this array, and we take the sign of each element again. This yields an array, \$A\$, of \$0\$ and \$1\$, with the first element always being \$0\$. We then yield the range \$[1, 2, ... length(A)]\$ and remove the elements that correspond to \$0\$ in \$A\$. This leaves us with a second array, \$A'\$. We then push the number of digits in the input, add one and append this number to \$A'\$. We then deduplicate \$A'\$, to yield a new array, \$A''\$. Next, we use the \$g\$ helper function. As \$g\$ is dyadic (takes 2 arguments), it behaves slightly differently when paired with the *each* operator, `€`. Dyadic functions pop a value from the stack and bind that value as their right argument to create a partial monadic function. This partial function is then mapped over each element in the argument. Here, the bound right argument is the digits of the input and the partial function is mapped over \$A''\$. ### \$g(x, y)\$ Let's take a look at just one iteration of \$g(x, y)\$ where \$x := [1, 2, 0, 1, 2]\$ and \$y = 3\$. Note that \$3\$ is the first index in \$A''\$ where the signs from \$A\$ corresponded with \$1\$, rather than \$0\$. In fact, for \$x = 12012\$, we can see that \$A'' = [3, 6]\$. \$3\$ is the only non-zero index in \$A\$, and \$6\$ is the length of \$x\$ plus one. So, for \$g([1, 2, 0, 1, 2], 3)\$ the following happens: First, we swap the two arguments so that the stack has the digits below the index. We then flatten the array and decrement the index. So far, the stack looks like `[1 2 0 1 2 2]`. We then perform the *head* command. We pop the index from the top f the stack and take that many characters from the stack, starting at the bottom. This yields \$[1, 2]\$, which is then returned by \$g\$. So, \$g(x, y)\$ is mapped over each element \$y \in A''\$, which returns a series of prefixes of the input of various increasing lengths. This part could get slightly confusing, so we'll work through it with the example input of \$x := 12012\$. After the mapping of \$g\$, the stack currently looks like ``` [[[1 2] [1 2 0 1 2]]] ``` We then push an array containing the length of each array in the top element, or in this instance, the array \$[2, 5]\$. This is the same as \$A'' - 1\$, if the \$-\$ operator maps, but it takes more bytes to use this relationship. Next, the forward differences of the lengths is taken, and \$0\$ is prepended, yielding, in this example, \$[0, 3]\$. This new array is then zipped with the results from \$g\$ to create \$B\$ and the *starmap* operator is run over each pair. ### \$k(x, n)\$ The *starmap* operator uses the function \$k\$ as its argument, and works by taking a dyadic function and a nested array. The array must consist of pairs, such as \$[[1, 2], [3, 4], [5, 6]]\$, and the dyadic function is mapped over each pair, with each element of the pairs being the left and right arguments respectively. Here, our example nested array is \$[[[1, 2], 0], [[1, 2, 0, 1, 2], 3]]\$ and our function is \$k\$. We'll focus simply on \$k([1, 2, 0, 1, 2], 3)\$ for now. \$k(x, n)\$ starts, similar to \$g\$, by swapping the two arguments, so that the array is the top of the stack. We then reverse the array and swap the arguments back. Now, \$n = 0\$, we want to leave the array unchanged, so we duplicate the integer and rotate the top three arguments, so that the stack has the format of \$[n, x, n]\$. Next, we return the array if \$n = 0\$. Otherwise, the top element is discarded, and we arrange the stack back to how it was i.e. with the reversed array at the bottom and the integer at the top, or in our example: \$[[2, 1, 0, 1, 2], 3]\$. We then flatten the stack, and take the first \$n\$ elements of \$x\$. These elements are then returned and replace \$x\$ in \$B\$. For our input, this returns \$[0, 1, 2]\$. (Strictly speaking, it returns\$[2, 1, 0]\$, but order doesn't matter for the rest of the program). After \$k(x, n)\$ is mapped over each pair \$(x, n) \in B\$, we take the sum of each pair, then check that each element is equal, by asserting that each neighbouring pair are equal, and then asserting that each of those equality tests result in \$1\$ (a truthy value). Finally, this result is returned. ]
[Question] [ Notice the pattern in the below sequence: ``` 0.1, 0.01, 0.001, 0.0001, 0.00001 and so on, until reaching 0.{one hundred zeros}1 ``` Then, continued: ``` 0.2, 0.02, 0.002, 0.0002, 0.00002 and so on, until reaching 0.{two hundred zeros}2 ``` Continued: ``` 0.3, 0.03, etc, until 0.{three hundred zeros}3 ``` Continued: ``` 0.4, 0.04, etc, until 0.{four hundred zeros}4 ``` Sped up a bit: ``` 0.10, 0.010, etc. until 0.{one thousand zeros}10 ``` Sped up some more: `0.100, 0.0100...` You get the idea. The input your code will receive is an integer, the number of terms, and the output is that many number of terms of the sequence. Input and output formats are unrestricted, and separators are not required. Trailing zeros are necessary. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48934) apply. --- The outputs of some nth terms are given below: ``` nth term -> number ------------------- 1 -> 0.1 102 -> 0.2 303 -> 0.3 604 -> 0.4 1005 -> 0.5 1506 -> 0.6 2107 -> 0.7 2808 -> 0.8 3609 -> 0.9 4510 -> 0.10 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 23 bytes Online compiler can't show all terms for high N but it works fine offline. ``` Lvy2°*>F„0.0N×yJ,¼¾¹Qiq ``` **Explanation** ``` # implicit input X Lv # for each y in range [1 .. X] y2°*>F # for each N in range [0 .. y*100+1) „0. # push the string "0." 0N× # push 0 repeated N times y # push current y J, # join and print ¼¾¹Qiq # quit the program after X terms printed ``` [Try it online!](http://05ab1e.tryitonline.net/#code=THZ5MsKwKj5G4oCeMC4wTsOXeUoswrzCvsK5UWlx&input=MzAz) [Answer] # Python 2, ~~73~~ 64 bytes I think this is pretty short. I'm not sure that I can get it any shorter now that I golfed the `if-else` away. ``` s=z=1 exec'print"0.%0*d"%(z,s);q=z>s*100;z+=1-z*q;s+=q;'*input() ``` [**Try it online**](https://repl.it/Dklg/2) Less golfed: ``` n=input() s=z=1 for i in range(n): print"0.%0*d"%(z,s) if z>s*100:z=1;s+=1 else:z+=1 ``` [Answer] # Haskell, ~~53~~ 63 bytes This does the same thing as the 05AB1E answer now ``` f=(`take`["0."++('0'<$[1..y])++show x|x<-[1..],y<-[0..x*100]]) ``` [Answer] # Perl 5, 57 52 bytes (needs `-E` for `say`) ``` for(1..<>){say"0."."0"x$i++.$.;$.++,$i=0if$i>100*$.} ``` Or readably: ``` # $. is the input line number, use it to count the # number at the end. # $i counts zeroes in the middle, starts at 0 implicitly for(1..<>){ # get the number of terms from stdin and loop # <> implicitly increases $. (to 1) say "0." . "0" x $i++ . $.; # print the number, add one zero $.++, $i=0 if $i > 100 * $.; # increment the number, reset number # of zeroes if we've printed enough } ``` Trailing zeroes are printed since the number after the row of zeroes is just an integer concatenated as a string. Test run: ``` $ perl -E 'for(1..<>){say"0."."0"x$i++.$.;$.++,$i=0if$i>100*$.}' | tail -3 4511 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009 0.10 0.010 ``` [Answer] ## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), ~~73~~ 64 bytes ``` :#0|{C=!q$D=@0.|[0,q*100|d=d+1?D+$LTRIM$|(C) D=D+A~d=a|_X]]q=q+1 ``` Saved 9 bytes by removing `x` as upper bound in the `FOR` loop. Upper bound is now set as `q*100`. Shame that QBasic automatically adds a space in front of a printed number, that's a costly `LTRIM$`... Some explanation: `q` is used as the current number in the loop. This starts as 1 and gets incremented every 100N turns. This number gets converted to a string and is then appended to the string `0.` and the correct number of `0`'s. In detail: ``` We use q as our 'base number', this is 1 implicitly : Get the max number of terms from a numeric CMD line param #0| Define string A$ as "0" { DO C=!q$ our base number is cast to the string C$ D=@0.| define D$ as "0." [0,q*100| FOR each of the terms we need to do for our base number (i.e. 101 for 1, 201 for 2 ...) d=d+1 Keep track of the total # of terms (i.e. 101 after the 1 cycle, 302 after the 2...) ?D+$LTRIM$|(C) Print to screen D$ + C$, where D$ = "0.[000]" and C$ is our base number (1, or 2, or - much later - 100) LTRIM is in there to prevent "0.00 1" D=D+A Add A$ to the end of D$ ("0.00" becomes "0.000") ~d=a|_X] Stop if we've reached the max. # of terms ] NEXT q=q+1 If we've done all the terms necessary with this base number then raise base number. The DO loop gets closed implicitly by QBIC. ``` --- Edit: QBIC has seen quite some development over time, and the above can now be solved in 49 bytes, 15 bytes shorter: ``` {D=@0.`[0,q*100|d=d+1?D+!q$┘D=D+@0`~d=a|_X]]q=q+1 ``` [Answer] ## PowerShell v2+, 89 bytes ``` param($n)for($j=1;;$j++){for($i=0;$i-le100*$j;$i++){"0.$('0'*$i)$j";if(++$k-ge$n){exit}}} ``` Straight-up double-`for` loop. The first, for `$j` is infinite. The inner, for `$i`, loops from `0` up to `100*$j`, using string concatenation and string multiplication to print out the appropriate item. It also checks total loop counter `$k` against input `$n`, and `exit`s the program after we hit that point. [Answer] # PHP, 83 Bytes ``` for($s=1;$i++<$argv[1];){if($r>100*$s){$s++;$r=0;}echo" 0.".str_repeat(0,$r++).$s;} ``` [Answer] # GNU sed 163 157 +2 included for -rn ``` s,^,0.1\n,;:;P;s,\.,.0,;s,.$,,;/0{101}/{s,0\.0*(09)?,\1, s,.9*\n,x&,;h;s,.*x(.*)\n.*,\1,;y,0123456789,1234567890, G;s,(.*\n)(.*)x.*\n(.*),0.\2\1\3,};/\n./b ``` Takes input in unary [based in this consensus](http://meta.codegolf.stackexchange.com/a/5349/57100). [Try it online!](http://sed.tryitonline.net/#code=cyxeLDAuMVxuLDs6O1A7cyxcLiwuMCw7cywuJCwsOy8wezEwMX0ve3MsMFwuMCooMDkpPyxcMSwKcywuOSpcbix4Jiw7aDtzLC4qeCguKilcbi4qLFwxLDt5LDAxMjM0NTY3ODksMTIzNDU2Nzg5MCwKRztzLCguKlxuKSguKil4LipcbiguKiksMC5cMlwxXDMsfTsvXG4uL2IKCiNleGFtcGxlIGlucHV0IGlzIDEwMg&input=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx&args=LXJu) --- An easy way to run this is: ``` yes 1 | head -{input} | tr -d '\n' | sed -rnf zeroOne.sed ``` --- **Explanation** ``` s,^,0.1\n, #add 0.1 as the first line of the pattern space : P #print everything up to the first newline s,\.,.0, #add a 0 after the . s,.$,, #reduce the number left to print by one /0{100}/{ #if there is a string of 100 zero do the following s,0\.0*(09)?,\1, #get rid of all the 0s (except one if the we are adding another digit) s,.9*\n,x&, #put an x before the left most number that will change h #store in hold space s,.*x(.*)\n.*,\1, #remove everything except the numbers that change y,0123456789,1234567890, #replace numbers with the next one up G #bring the rest of the string back s,(.*\n)(.*)x.*\n(.*),0.\2\1\3, #replace the x and numbers that changed with the new ones } /\n./b #branch back unless there isn't anything on the last line ``` [Answer] # Mathematica, 70 bytes ``` Take[Join@@Table["0."<>Array["0"&,k]<>ToString@m,{m,#},{k,0,100m}],#]& ``` Unnamed function that takes the desired length as its argument and returns a list of strings (using strings instead of numbers makes the trailing zeros easy to include). This version is slow as hell! because if you want, for example, the first 10 terms, it actually computes the sequence all the way through the 10th segment (101 + 201 + ... + 1001 = 5510 terms) and then retains only the first 10. So already at input 303, it's computing nearly five million terms and discarding almost all of them. The **81**-byte version ``` Take[Join@@Table["0."<>Array["0"&,k]<>ToString@m,{m,Sqrt[#/50]+1},{k,0,100m}],#]& ``` doesn't have this flaw, and in fact calculates nearly the fewest segments possible. [Answer] # JavaScript (ES6), 69 ``` n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0) ``` Unnamed function with desired length in input and returning an array of strings. **Test** ``` f= n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0) var tid=0 function exec() { var n=+I.value; O.textContent=f(n).map((r,i)=>i+1+' '+r).join`\n`; } function update() { clearTimeout(tid); tid=setTimeout(exec, 1000); } exec() ``` ``` <input id=I value=305 type=number oninput='update()'><pre id=O></pre> ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 71 bytes ``` sn1sj1si1[lj1+dddsjZ1-dkAr^/li1+si]sJ[0nK1+kA/pljA0*K=Jlnlid1+si<M]dsMx ``` [Try it online!](https://tio.run/##FckxDoAgDADA/0gMNKw6sEL4gAQXu7Q0xNjF39d46@FlMUTTCcqgBE0YHCIqH7DiSM/phcApdc0tzAJuJH8Lp7CUPcsUwn@32lHra/YB "dc – Try It Online") Honestly, I thought taking advantage of dc's arbitrary precision would make this easy, but I'm pretty sure just printing a ton of zeroes will be golfier. It feels really suboptimal, but I still think the use of arbitrary precision is interesting. `sn1sj1si1` We're taking top-of-stack as our nth-term target, so we store it in `n`, initialize `i` and `j` at 1, and leave a 1 on the stack. `[lj1+dddsjZ1-dkAr^/li1+si]sJ` Macro `J` handles what to do when we've hit the 100, 200, &c. mark. Counter `j` keeps track of this, so we increment it, we set our precision to the number of digits it has less one, and then we leave the first digit of it (`Z1-Ar^/`; divide by 10^(number of digits less one)) on the stack since this is our starting point for the next big long chain. `[0nK1+kA/pljA0*K=Jlnlid1+si<M]dsMx` Our main macro. First we print a leading 0 with `0n`. Then `K1+k` increments our precision by one place. `A/` divides by ten, pushing us a place over to the right.`p` prints, and then the rest is housekeeping. We can test our current precision to determine whether or not we need to jump into macro `J`, so we multiply counter `j` by a hundred (note: `A0` here may need to be replaced with `100` on some implementations (cygwin)) and do the comparison. We load `n`, our target nth term, increment our main counter, `i`, and then compare the two. If we haven't yet hit the target, we keep running `M`. [Answer] # Excel VBA, 63 Bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window ``` n=[A1]:While n>i*100:n=n-1-i*100:i=i+1:Wend:?"0."String(n,48)&i ``` [Answer] # Java 8, 120 bytes ``` n->{String r="";a:for(int i=1,j,k,c=n;;i++)for(j=0;j<=i*100;r+=i+"\n"){for(r+="0.",k=j++;k-->0;r+=0);if(c--<1)break a;}} ``` Explanation and TIO uses the one below however. The difference: the one above creates one big String and then returns it; the one below prints every line separately (which is much better for performance). **130 bytes:** ``` n->{String r;a:for(int i=1,j,k,c=n;;i++)for(j=0;j<=i*100;System.out.println(r+i)){for(r="0.",k=j++;k-->0;r+=0);if(c--<1)break a;}} ``` **Explanation:** [Try it here.](https://tio.run/##LY/BbsIwEETvfMWKk13HkSNVPXQxf1AuHFEPxjjV2sGJHINURfn24ADS7mFndqQ33tyN7AcX/SUstjPjCD@G4rQBoJhdao11cFhPgHtPF7Cs6BA5FmkuW2bMJpOFA0TQsES5n445UfyDhOa77dMzQbqpfBUqqyMiCcFXw2uFfqfpo1EKj/9jdte6v@V6KPHcRZYEcT6tn0lvVb2tgvZCYJByrzAJrThSy6yUu4afkzMBDM7zgptCNdzOXaF6wz3Zr6UZe7GdfsHwV61YW/alPt@N5uUB) (Will time out or exceed output limit for test cases above `604`, but locally test case `4510` works in below 2 seconds.) ``` n->{ // Method with integer parameter and no return-type String r; // Row String a:for(int i=1, // Index integer `i` starting at 1 j,k, // Some other index integers c=n // Counter integer starting at the input ;;i++) // Loop (1) indefinitely for(j=0; // Reset `j` to 0 j<=i*100; // Loop (2) from 0 to `i*100` (inclusive) System.out.println(r+i)){ // After every iteration: print `r+i` + new-line for(r="0.", // Reset row-String to "0." k=j++; // Reset `k` to `j` k-->0; // Loop (3) from `j` down to `0` r+=0 // And append the row-String with "0" ); // End of loop (3) if(c--<1) // As soon as we've outputted `n` items break a; // Break loop `a` (1) } // End of loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) } // End of method ``` ]
[Question] [ Write a program or function that prints or outputs this exact text (consisting of 142 characters): ``` ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` Your program must take no input (except in languages where this is impossible, such as `sed`), and produce the above text (and *only* the above text) as output. A trailing newline is acceptable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~70~~ ~~68~~ 67 bytes ``` '()'12:)l10:&<toYP43Y$51hb(!10Xy'\::\'FFhZ++'|'3$Yc'||\'3:(95'Zd'o( ``` [Try it online!](http://matl.tryitonline.net/#code=JygpJzEyOilsMTA6Jjx0b1lQNDNZJDUxaGIoITEwWHknXDo6XCdGRmhaKysnfCczJFljJ3x8XCczOig5NSdaZCdvKA&input=) ### Explanation What a mess. But hey, there's a convolution! The explanation will be clearer if you can *inspect the stack contents after a given statement*. To do it, just insert `X#0$%` at that point. (This means: `X#` show stack contents, `0$` don't implicitly display anything else, `%` comment out rest of the code). For example, [see the stack right after the convolution](http://matl.tryitonline.net/#code=JygpJzEyOilsMTA6Jjx0b1lQNDNZJDUxaGIoITEwWHknXDo6XCdGRmhaK1gjMCQlKyd8JzMkWWMnfHxcJzM6KDk1J1pkJ28o&input=). ``` '()' % Push this string 12: % Range [1 2 ... 12] ) % Index into string (modular, 1-based): gives '()()()()()()' l % Push 1 (will be used later) 10: % Range [1 2 ... 10] &< % All pairwise "less than" comparisons. Gives matrix with "true" % below the main diagonal, and the remining entries equal to "false" to % Duplicate. Convert to numbers (true becomes 1, false becomes 0) YP43Y$ % Compute pi with 43 significant digits (42 decimals). Gives a string 51h % Append last decimal, '3' (ASCII 51). This is needed to avoid rounding b % Bubble up the true-false matrix, to be used as logical index ( % Fill the chars from the pi string into the 0-1 matrix, at the positions % indicated by the true-false matrix. Thus each 1 is replaced by a char % from the pi string. Entries that were 0 remain as 0. This is done in % columm-major order... ! % ...so transpose to make it row-major 10Xy % Identity matrix of size 10 '\::\' % Push this string... FFh % ...and append two zeros Z+ % 2D convolution keeping size. The identity matrix convolved with the % above string gives the diagonal bands with chars '\' and ':' + % Add to the matrix containing the digits of pi. At each entry, only one % of the two matrices is nonzero '|' % Push this string 3$Yc % Three-input string concatenation. This prepends the 1 (which was pushed % a while ago) and appends '|' to each row of the matrix. This converts % the matrix to char. Note that char 1 will be displayed as a space. We % used char 1 and not char 0 (which would be displayed as a space too) % because function `Yc` (`strcat`) strips off trailing space from the % inputs, counting char 0 as space, but not char 1 '||\' % Push this string 3:( % Assign it to the first 3 entries of the matrix (column-major), that is, % to the top of the first column 95 % Push ASCII for '_' 'Zd'o % Push string 'Zd' and convert to numbers: gives [90 100]. These are the % (column-major) indices where the '_' char should appear in the last row ( % Fill those chars % Implicitly display. (Chars 0 and 1 are displayed as space) ``` [Answer] # Perl, 93 bytes ``` $_=bpi$=;printf'()'x6x!$`.' %12s',F.ee x!$\--^substr"\32::\\$&|",-12while/.{$\}/g ``` Requires the command line option `-l71Mbignum=bpi`, counted as 14. The `\32` should be replaced by a literal character 26. **Sample Usage** ``` $ perl -l71Mbignum=bpi pi-slice.pl ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` --- ### Perl, 111 bytes ``` $_=bpi$_*($l=($.=$_)-3);printf'()'x($./2)x!$`." %$.s",F.ee x!$l--^substr"\32::\\$&|",-$.while/.{$l}/g ``` Parameterized version. Requires the command line option `-nMbignum=bpi`, counted as 12. **Sample Usage** ``` $ echo 10 | perl -nMbignum=bpi pi-slice.pl ()()()()() |\3.14159| |:\265358| \::\97932| \::\3846| \::\264| \::\33| \::\8| \__\| $ echo 20 | perl -nMbignum=bpi pi-slice.pl ()()()()()()()()()() |\3.141592653589793| |:\2384626433832795| \::\028841971693993| \::\75105820974944| \::\5923078164062| \::\862089986280| \::\34825342117| \::\0679821480| \::\865132823| \::\06647093| \::\8446095| \::\505822| \::\31725| \::\3594| \::\081| \::\28| \::\4| \__\| ``` [Answer] ## JavaScript (ES6), ~~187~~ 174 bytes This is *1 byte shorter* than just displaying the plain text. ``` for(y=n=0,s=`()()()()()() `;y<10;y++,s+=`| `)for(x=-2;x++<9;)s+=x>y?(Math.PI+'2384626433832795028841971693')[n++]:`\\${y>8?'__':x+1|y>2?'::':'||'}\\`[y-x]||' ';console.log(s) ``` [Answer] # [///](http://esolangs.org/wiki////), ~~129~~ 127 bytes ``` /-/\\\\//&/--::--//%/ //#/| %//!/()()/!!! |-3.1415926| |:-53589793| &2384626| &433832#&79502# &8841#%&971#% &69#%%&3#%% -__-| ``` [Try it online!](http://slashes.tryitonline.net/#code=Ly0vXFxcXC8vJi8tLTo6LS0vLyUvICAvLyMvfAolJS8vIS8oKSgpLyEhIQp8LTMuMTQxNTkyNnwKfDotNTM1ODk3OTN8CiYyMzg0NjI2fAogJjQzMzgzMnwKJSY3OTUwMnwKJSAmODg0MSMmOTcxIyAmNjkjJSYzIyUgLV9fLXw) [Answer] # Python 2, 131 bytes ``` print'()'*6+'\n|\\3.1415926|\n|:\\53589793|' for n in 2384626,433832,79502,8841,971,69,3,'':print'%11s|'%('\%s'*2%('_:'[n<'']*2,n)) ``` Joint effort between Sp3000 and Lynn. Copper saved a byte, too! [Ideone link.](https://ideone.com/JrC2Nl) [Answer] # Bash, 153 bytes ``` cat << _ ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| _ ``` [Answer] ## Batch, 195 bytes ``` @echo ()()()()()() @echo ^|\3.1415926^| @echo ^|:\53589793^| @set i=\ @for %%d in (2384626 433832 79502 8841 971 69 3)do @call:l %%d @echo %i%__\^| @exit/b :l @set i= %i% @echo%i%::\%1^| ``` [Answer] # Fourier, ~~196~~ 190 bytes ***New feature alert!*** ## Code ``` |SaCaaSa|f|~Y0~jY(32aj^~j)|w6(40a41ai^~i)10a~N124a~W92a~S3o46a1415926oWaNaWa58a~CSa53589793oWaNaf2384626oWaNa1wf433832oWaNa2wf79502oWaNa3wf8841oWaNa4wf971oWaNa5wf69oWaNa6wf3oWaNa7wSa95aaSaWa ``` ## Explanation This program is my first demonstration of functions in Fourier: Functions are defined like so: ``` |code goes here|f ``` The first pipe starts the function declaration. You then put the code in between the pipes. The last pipe ends the function declaration. Finally, the `f` is the variable in which the function is stored. This can be any character, as long as it isn't a reserved function. For example, in my code, one of the function s is: ``` |SaCaaSa|f ``` Where the variable `S` stores the number 92 and `C` stores the number 58. When called, the function outputs the following: ``` \::\ ``` Since it is the most repeated thing in the pie. Similarly, to golf down the output, I have used a loop: ``` 6(40a41ai^~i) ``` Which repeats the code `40a41a` 6 times. `40a41a` on its own outputs: ``` () ``` So repeating the code six times outputs: ``` ()()()()()() ``` Thereby outputting the crust of the pie. [**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=fFNhQ2FhU2F8Znx-WTB-alkoMzJhal5-ail8dzYoNDBhNDFhaV5-aSkxMGF-TjEyNGF-VzkyYX5TM280NmExNDE1OTI2b1dhTmFXYTU4YX5DU2E1MzU4OTc5M29XYU5hZjIzODQ2MjZvV2FOYTF3ZjQzMzgzMm9XYU5hMndmNzk1MDJvV2FOYTN3Zjg4NDFvV2FOYTR3Zjk3MW9XYU5hNXdmNjlvV2FOYTZ3ZjNvV2FOYTd3U2E5NWFhU2FXYQ) Because I haven't implemented functions in the Python interpreter, this program will not work on <http://tryitonline.net> [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), ~~135~~ 129 bytes (the interpreter isn't really ~~slightly~~ buggèd (anymore :])~~, but it does not affect this program~~) By restructuring and rewriting my program, I golfed... six bytes And now I have to make new explanation... Still could be shorter probs though --- At least the best solution in this lang isn't just writing in the raw data ¯\*(ツ)*/¯ --- [Answer] # Pyth, 89 bytes ``` J_2K+.n0."09\07´\C2\84J\01£\07Nl:?í"*"()"6Vr9Zp*dJp?!Z\|?qZ9"|:""\::"p\\p:KZ+ZN\|=+ZN=hJ)p*dJ"\__\|" ``` [Try it online!](http://pyth.herokuapp.com/?code=J_2K%2B.n0.%2209%07%C2%B4%C2%84J%01%C2%A3%07Nl%3A%3F%C3%AD%22%2a%22%28%29%226Vr9Zp%2adJp%3F%21Z%5C%7C%3FqZ9%22%7C%3A%22%22%5C%3A%3A%22p%5C%5Cp%3AKZ%2BZN%5C%7C%3D%2BZN%3DhJ%29p%2adJ%22%5C__%5C%7C%22&debug=0) Replace `\xx` (hexadecimal) with the corresponding ASCII character if you copy/paste the code from this answer; it contains unprintable characters in the packed string which SE filters out. ### Explanation ``` J_2 Sets J to -2 .n0 Pi; returns 3.141592653589793 ."(...)" Packed string; returns "2384626433832795028841971693" + Concatenation; returns "3.1415926535897932384626433832795028841971693" K Sets K to that string *"()"6 Repetition; returns "()()()()()()", which is implicitly printed with a newline r9Z Range; returns [9, 8, 7, 6, 5, 4, 3, 2, 1] (Z is initialized to 0) V Loop through r9Z, using N as the loop variable *dJ Repetition; d is initialized to " " (returns an empty string if J <= 0) p Print without a newline ?!Z Ternary; if not Z \| then return "|" ?qZ9 else, ternary; if Z == 9 "|:" then return "|:" "\::" else, return "\::" p Print without a newline \\ One-character string; returns "\" p Print without a newline :KZ+ZN Slice; returns K[Z:Z+N], not including K[Z+N] p Print without a newline \| One-character string; returns "|", which is implicitly printed with a newline. =+ZN Adds N to Z =hJ Increments J by 1 ) Ends loop *dJ Repetition; d is initialized to " " p Print without a newline "\__\|" Returns "\__\|", which is implicitly printed with a newline ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 83 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) surely still quite golfabale ``` 7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7 ⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|” ``` **[TryItOnline](http://jelly.tryitonline.net/#code=N-G4tuKBtuG6izvigqzigJxcOjpc4oCd4oCcfDpc4oCd4bmt4bmZNwrigb4oKeG6izbigbfigb58XDjDmFDDpnDigJ184oG3OFJVUuKCrMK14oCc4oG-4biFfFphIn7huYXhu7XDvsi3XuG5h-KBt8SK4oCZROG5gTvigqzigJ18xbxAwqJZ4oG3w7jigbbhuos34oCcXF9fXHzigJ0&input=&args=)** How? ``` 7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7 - Link 1, left side padding and filling 7Ḷ - lowered range of 7 ([0,1,2,3,4,5,6]) “\::\” - filling ("\::\") ⁶ẋ;€ - space character repeated that many times and concatenate for each “|:\” - top crust edge filling ("|:\") ṭ - tack (append to the end) ṙ7 - rotate to the left by 7 (move top crust filling to the top) ⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ - Main Link (divided into two for formatting) ⁾()ẋ6⁷ - "()" repeated 6 times and a line feed ⁾|\ - "|\" ØP - pi 8 æp - round to 8 significant figures (top edge of the glaze) ”|⁷ - "|" and a line feed 8R - range of 8 ([1,2,3,4,5,6,7,8]) U - reverse ([8,7,6,5,4,3,2,1]) R€ - range for each ([[1,2,..8],[1,2,..7],...,[1,2],[1]]) µ - monadic chain separation “⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|” - Main link (continued) “⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’ - base 250 representation of the rest of the digits D - decimalise (makes it a list) ṁ - mould (into the shape of the array formed above) ”| - "|" ;€ - concatenate for each ¢ - call last link (1) as a nilad ż@ - zip (with reversed operands) Y⁷ - join with line feeds, and another line feed ø - niladic chain separation ⁶ẋ7 - space character repeated 7 times “\__\|” - "\__\|" the very bottom of the pie wedge ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 105 bytes ``` '()'*6 '|\3.1415926| |:\53589793|' 2384626,433832,79502,8841,971,69,3|%{" "*$i+++"\::\$_|"} ' '*7+'\__\|' ``` [Try it online!](https://tio.run/nexus/powershell#BcHBDcMgDADAP1NEKJEbsKKCwdjMYol3Z6g7O73b8LohcQA3ekorXSt78GmduuhQcgiVpHFlbERCFYf2d0WRVlBHQVYkv77xiOn85JyjzWnn8vgLcEAaGWwtc9j7Dw "PowerShell – TIO Nexus") *Not sure how I never answered this challenge ... I upvoted it and several of the other answers. Oh well, better late than never?* This puts six balanced parens as a string on the pipeline, then a literal string (saves two bytes) of the next two rows. Then, we loop through the rest of the numbers, each iteration incrementing the number of prepended spaces (`$i`) concatenated with `\::<number>|`. Finally, we create a string of the tip of the pie. Those strings are all left on the pipeline, and an implicit `Write-Output` sticks a newline between. This is 39 bytes shorter than [just printing the pie.](https://tio.run/nexus/powershell#RcnBDYAgDEDRO1NwQy9GaAstszRhke6O0mDMP738mY7zL5jClTGTlGrBuhIQSxOwoL1rAca6TlxCAIbywtWEboeLGbPDJW3DVWXDBR@ijqGW5nwA "PowerShell – TIO Nexus") [Answer] # Python 2, ~~193~~ 176 bytes ``` P="3.1415926 53589793 2384626 433832 79502 8841 971 69 3".split() f="()"*6+"\n|\%s|\n|:\%s|\n"%(P[0],P[1]) for s in range(7):f+=" "*s+"\::\\"+P[s+2]+"|\n" print f+" "*7+"\__\|" ``` Or a shorter, more boring answer: ``` print r"""()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\|""" ``` [Answer] # C# 220 213 209 208 202 201 (171\*) Bytes \*I find this to be unoriginal and cheating ``` void F()=>Console.Write(@"()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\|"); ``` 201 Bytes: ``` void f(){var s="()()()()()()\n";for(int i=0;i<9;)s+=(i<1?"|":i<2?"|:":"\\::".PadLeft(i+1))+$"\\{new[]{3.1415926,53589793,2384626,433832,79502,8841,971,69,3}[i++]}|\n";Console.Write(s+@" \__\|");} ``` 220 bytes: I'm sure that there is something to be golfed here ``` void f(){string s="()()()()()()\n",x=" ";for(int i=9,j=0;i>0;j+=i--)s+=(i>7?"|"+(i<9?":":"")+"\\":x.Substring(i)+@"\::\")+$"{Math.PI}32384626433832795028841971693".Substring(j,i)+"|\n";Console.Write(s+x+@"\__\|");} ``` [Answer] # Ruby, ~~140~~ ~~138~~ 137 bytes My solution to this problem in ruby, this is my first code golf answer :D ``` [0,2384626,433832,79502,8841,971,69,3,1].map{|n|puts n<1?"()"*6+"\n|\\3.1415926|\n|:\\53589793|":"\\#{n>1?"::\\#{n}":"__\\"}|".rjust(12)} ``` **Readable version and explanation:** ``` for n in [-1,2384626,433832,79502,8841,971,69,3,0] if n < 0 # n == -1 puts "()"*6+"\n|\\3.1415926|\n|:\\53589793|" else if n > 0 # digits of pi puts "\\::\\#{n}|".rjust(12) else # edge of pie puts "\\__\\|".rjust(12) end end end ``` Nothing really clever, just using some simple loops :) **Output:** ``` ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸M↑__↖←¤:↗¤UGPi ``` [Try it online!](https://tio.run/nexus/charcoal#@394@qPGbRqaj9pmPmqbfGjno8YNj9qmARGUORkkuulR24xHjTve71n7qG1ifDxYwYRDS6wetU0/tOT9nq3v9ywPyPz/HwA) You may be wondering: what is this sorcery? How can you fill with `UGPi`? Well, Charcoal is starting to get Wolfram Language support, in the hope that one day it can be competitive in more challenges! ## Previous, 71 bytes ``` ×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸M↑__↖←¤:↗¤3.141592653589793238462643383279502884197169 ``` [Try it online!](https://tio.run/nexus/charcoal#@394@qPGbRqaj9pmPmqbfGjno8YNj9qmARGUORkkuulR24xHjTve71n7qG1ifDxYwYRDS6wetU0/tMRYz9DE0NTSyMzU2NTC0tzS2MjYwsTMyMzE2NjC2Mjc0tTAyMLCxNDS3NDM8v9/AA "Charcoal – TIO Nexus") ## Verbose ``` Print(Multiply(6, "()")); Move(:DownLeft) Print(:Down, 10) Move(:UpLeft) Print(:UpLeft, 10) Move(:Down) Print(:Down, 2) Print(:DownRight, 8) Move(:Up) Print("__") Move(:UpLeft) Move(:Left) Fill(":") Move(:UpRight) Fill("3.141592653589793238462643383279502884197169") ``` Note that this is different as the deverbosifier automatically compresses strings and does not remove redundant commands. ## With compressed strings, 52 bytes ``` ×⁶¦()↙↓¹⁰↖↖¹⁰↓↓²↘⁸↑__↖←¤:M↗¤”i¶∧²uτ¶R› §Q´⌈#_⮌POÞ” ``` ## xxd output ``` 0000000: aab6 ba28 291f 14b1 b01c 1cb1 b014 14b2 ...()........... 0000010: 1eb8 125f 5f1c 11ef 3acd 1def 0469 0a01 ...__...:....i.. 0000020: b275 f40a 52be 0999 9fa4 d1e0 1a23 5f86 .u..R........#_. 0000030: d04f de04 .O.. ``` [Try it online!](https://tio.run/nexus/charcoal#XY3NDoIwEITvPAXpqU3Q0G5/8Wo8SWJMPHNCadIAMRXj01elEoHbzs43M@F0t63H5cN527sXllmKMEGE7JKyG2pc7Ltne6yvniSRHB9ZSnPyAy79wo5yDnwDqzRb6LO9NZ@E/jdONqoqtN6JKt4H6xxGxYwZuyYDtpRTYZgUILRRBhhoLpnkABqYMiJnWnNqFJUGkRDCZngD "Charcoal – TIO Nexus") [Answer] # PHP, 170 bytes no arbritrary precision Pi in PHP? Calculating takes much more space than Copy&Paste. Doesn´t matter that the last digit here is cut, not rounded; but in 64 bit Pi the last digit gets rounded up. ``` for(;$i<11;)echo str_pad($i?["\\__\\","|\\","|:\\","\\::\\"][$i>9?0:min(3,$i)].[3.1415926,53589793,2384626,433832,79502,8841,971,69,3][$i-1]."| ":" ",13,$i++?" ":"()",0); ``` Run with `php -r '<code>'` **uncommented breakdown** ``` for(;$i<11;) echo str_pad($i? ["\\__\\","|\\","|:\\","\\::\\"][$i>9?0:min(3,$i)] .[3.1415926,53589793,2384626,433832,79502,8841,971,69,3][$i-1] ."|\n" :"\n" ,13,$i++?" ":"()",0); ``` [Answer] # Python 2, ~~183~~ 171 bytes ``` p,d=[2384626,433832,79502,8841,971,69,3],"|\n" c=("()"*6)+d[1]+"|\\"+`3.1415926`+d+"|:\\"+`53589793`+d for x in range(7):c+=" "*x+"\\::\\"+`p[x]`+d print c+" "*7+"\\__\\|" ``` Does't really do anything clever. Just builds up a big string then prints it out. **EDIT** Reduced to 171 after reading @Lynn's answer and learning. Sorry if it is wrong to (shamelessly) steal some bytes from you without you suggesting it. Please tell me if so and I will roll back the change. **Output** ``` python pi.pie.py ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 63 bytes ``` ü?½Pi<Θ*q}ü¿▒5Ç>cdƒ±<Gw►,─ô╟▒g•iâÑ♠514Φ⌂!Ñεùáèè♂ÑD╔«dÿ47¡ô#UV•╧ ``` [Run and debug online!](https://staxlang.xyz/#p=813fab50693ce92a717d81a8b135803e63649ff13c4777102cc493c7b167076983a506353134e87f21a5ee97a08a8a0ba544c9ae64983437ad9323555607cf&a=1) Shorter than the accepted MATL answer. It would definitely be shorter if more digits were stored as the constant pi in Stax. (What is that `Pi<0` in the code?) ## Explanation Uses the ASCII equivalent to explain, which is ``` .()6*PVP$2ME.|\a+"|:\"a+"!RNyb2L$-!mV=223w+&O-"!{"\::\"s$+mELr"\__\"]+|>m'|+ ``` Expalantion: ``` .()6*PVP$2ME.|\a+"|:\"a+ .() "()" 6*P Print 6 times VP$ First two lines of pi in the output 2ME Push the two lines separately on the stack .|\a+ Prepend the first line with "|\" "|:\"a+ Prepend the second line with "|:\" "..."!{"\::\"s$+mELr"\__\"]+|>m'|+ "..."! [2384626,433832,79502,8841,971,69,3] {"\::\"s$+m Convert each element to a string and prepend "\::\" ELr Prepend the first two lines to array "\__\"]+ Append "\__\" to the converted array |> Right align text m'|+ Append "|" to each array element and print ``` [Answer] # Java 7, ~~260~~ ~~236~~ 191 bytes ``` String d(){return"()()()()()()\n|\\3.1415926|\n|:\\53589793|\n\\::\\2384626|\n \\::\\433832|\n \\::\\79502|\n \\::\\8841|\n \\::\\971|\n \\::\\69|\n \\::\\3|\n \\__\\|";} ``` Sigh, simply outputting the pie is shorter, even with all the escaped backslashes.. >.> Here is previous answer with a tiny bit of afford, although still not very generic or fancy (**236 bytes**): ``` String c(){String n="\n",p="|",q=p+n,x="\\::\\",s=" ",z=s;return"()()()()()()"+n+p+"\\"+3.1415926+q+p+":\\53589793"+q+x+2384626+q+s+x+433832+q+(z+=s)+x+79502+q+(z+=s)+x+8841+q+(z+=s)+x+971+q+(z+=s)+x+69+q+(z+=s)+x+3+q+(z+=s)+"\\__\\|";} ``` A pretty boring answer, since simply outputting the result without too much fancy things is shorter in Java than a generic approach. **Ungolfed & test code:** [Try it here.](https://ideone.com/FW4KmJ) ``` class M{ static String c(){ String n = "\n", p = "|", q = p + n, x = "\\::\\", s = " ", z = s; return "()()()()()()" + n + p + "\\" + 3.1415926 + q + p + ":\\53589793" + q + x + 2384626 + q + s + x + 433832 + q + (z += s) + x + 79502 + q + (z += s) + x + 8841 + q + (z += s) + x + 971 + q + (z += s) + x + 69 + q + (z += s) + x + 3 + q + (z += s) + "\\__\\|"; } public static void main(String[] a){ System.out.println(c()); } } ``` **Output:** ``` ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` [Answer] # Qbasic, 175 bytes ``` ?"()()()()()()":?"|\3.1415926|":?"|:\53589793|":?"\::\2384626|":?" \::\433832|":?" \::\79502|":?" \::\8841|":?" \::\971|":?" \::\69|":?" \::\3|":?" \__\|" ``` [Answer] # Lua, 152 Bytes ``` print[[()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\|]] ``` Try as I might I could not compress this pi. Lua is just too verbose to do it, maybe a pi of greater size, but not this one. Another solution, 186 Bytes. ``` s="()()()()()()\n|\\3.1415926|\n|:\\53589793|\n"i=0 for z in('2384626|433832|79502|8841|971|69|3|'):gmatch'.-|'do s=s..(' '):rep(i)..'\\::\\'..z.."\n"i=i+1 end print(s..' \\__\\|') ``` Annoyingly Lua's pi isn't accurate enough to even fill the pi. :( [Answer] # Javascript, 172 bytes Paste into your console to run. ``` for(y=n=0,s=`()()()()()() `;y<10;y++,s+=`| `)for(x=-2;x++<9;)s+=x>y(Math.PI+'2384626433832795028841971693'[n++]:`\\${y>8?'__':x+1|y>1?'::':'||'}\\`[y-x]||' ';console.log(s) ``` [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 871 bytes ``` {iiii}cicdcicdcicdcicdcicdcic{ddd}dc{{i}}{i}iiiic{ddd}ddc{dddd}dcdddddciiiciiicdddciiiiciiiic{d}iiiciiiic{{i}ddd}c{{d}}{d}ddddc{{i}}{i}iiiic{dddddd}ddddddc{iii}iiiic{dddd}icddciiciiicicddciicddddddc{{i}ddd}iiic{{d}}{d}ddddc{{i}dd}iic{ddd}ddddcc{iii}iiiic{dddd}ddciciiiiicddddciicddddciiiic{{i}ddd}c{{d}}{d}ddddc{ii}iic{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}cdcciiiiicdddddcdc{{i}ddd}iiiic{{d}}{d}ddddc{ii}iicc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}iiiciicddddcdddddciic{{i}ddd}iiiic{{d}}{d}ddddc{ii}iiccc{iiiiii}c{ddd}ddddcc{iii}iiiic{ddd}ddddddccddddcdddc{{i}ddd}iiiiic{{d}}{d}ddddc{ii}iicccc{iiiiii}c{ddd}ddddcc{iii}iiiic{ddd}dddddcddcddddddc{{i}ddd}iiiiic{{d}}{d}ddddc{ii}iiccccc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}iiciiic{{i}ddd}dddc{{d}}{d}ddddc{ii}iicccccc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}dc{{i}ddd}iiic{{d}}{d}ddddc{ii}iiccccccc{iiiiii}ciiiccdddc{iii}iic{{d}}{d}ddddc ``` [Try it online!](https://tio.run/##jdJdDsMgCADgE@1QC2wZz3s0nN3xO@lmG5oYieInweLjjk96v25zDpKPgQA3YyAiI4xBzDI0NdbQZt3USXJlR0fEBJHLKxZAT0iAoqmBG9p139PK1garDnFPxpkauF/049t61i1rf7BSVqR7sObzuk0wyfp3oUsnCy4Nq9XSlm253lmvNB@hQTfsfICvfWDP3DYMWXDTbXYD6ms5vuda3tU/VahlaRqU3/Z4Zs4P "Deadfish~ – Try It Online") Just because. [Answer] **JavaScript (ES6), ~~170 bytes~~ 165 bytes** is a bit "cheated", since if run on the console, the return value would be displayed ``` v=0;("()()()()()()\n|9|:87654321".replace(/\d/g,(o)=>"\\"+(Math.PI+'2384626433832795028841971693').substr(v,o,v-=-o)+"|\n"+(o<9?" ".repeat(8-o)+(o>1?"\\::":"\\__\\|"):"")) ``` After some teaking, the function looks like this(function must be called with parameter with the value 0): ``` v=>`()()()()()() |9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}| ${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`) ``` If you want to call the function 167 bytes: ``` z=v=>`()()()()()() |9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}| ${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`) /*could be run like this or directly in the console*/ console.info("\n"+z(0)); ``` [Answer] # PHP, 142 bytes Sneaky-sneaky :) `php` just prints everything out without trying to interpret them as PHP code if it does not see any `<?php ?>` pairs. ``` ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\8841| \::\971| \::\69| \::\3| \__\| ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 76 bytes ``` `:+R' 7"¦__¦|":*"()"6§+(mo:'|t↑2)↓2m↓3z+zR¢" "Nmo`:'|+"¦::¦"Cṫ9Γ·::'.ṁs↑54İπ ``` [Try it online!](https://tio.run/##yygtzv7/P8FKO0hdwVzp0LL4@EPLapSstJQ0NJXMDi3X1sjNt1KvKXnUNtFI81HbZKNcIGFcpV0VdGiRkoKSX25@AlBaG6jRyurQMiXnhztXW56bfGi7lZW63sOdjcVAfaYmRzacb/j/HwA "Husk – Try It Online") There's probably some interesing way to shorten this further. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 64 bytes ``` ‛()6*15∆Iṅ\.1Ṁ½÷$‛|\p$`|:\\`p"43∆I16ȯ7ɾṘẇvṅ‛\:mvp‛\_mJJ\|vJJ12↳⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJsoKTYqMTXiiIZJ4bmFXFwuMeG5gMK9w7ck4oCbfFxccCRgfDpcXFxcYHBcIjQz4oiGSTE2yK83yb7huZjhuod24bmF4oCbXFw6bXZw4oCbXFxfbUpKXFx8dkpKMTLihrPigYsiLCIiLCIiXQ==) ]
[Question] [ # Challenge Given an input of an all-lowercase string `[a-z]`, output the total distance between the letters. ## Example ``` Input: golf Distance from g to o : 8 Distance from o to l : 3 Distance from l to f : 6 Output: 17 ``` ## Rules * Standard loopholes forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - shortest answer in bytes wins. * The alphabet can be traversed from either direction. **You must always use the shortest path.** (i.e the distance between `x` and `c` is 5). ![1](https://i.stack.imgur.com/RyIZy.jpg) # Test cases ``` Input: aa Output: 0 Input: stack Output: 18 Input: zaza Output: 3 Input: valleys Output: 35 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~11~~ 8 bytes ``` OIæ%13AS ``` Saved 3 bytes thanks to @[Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender). [Try it online!](http://jelly.tryitonline.net/#code=T0nDpiUxM0FT&input=&args=J2dvbGYn) or [Verify all test cases.](http://jelly.tryitonline.net/#code=T0nDpiUxM0FTCsOH4oKs&input=&args=Wydnb2xmJywgJ2FhJywgJ3N0YWNrJywgJ3phemEnLCAndmFsbGV5cydd) ## Explanation ``` OIæ%13AS Input: string Z O Ordinal. Convert each char in Z to its ASCII value I Increments. Find the difference between each pair of values æ%13 Symmetric mod. Maps each to the interval (-13, 13] A Absolute value of each S Sum Return implicitly ``` [Answer] ## Haskell, ~~57~~ 56 bytes ``` q=map$(-)13.abs sum.q.q.(zipWith(-)=<<tail).map fromEnum ``` Usage example: `sum.q.q.(zipWith(-)=<<tail).map fromEnum $ "valleys"` -> `35`. How it works: ``` q=map$(-)13.abs -- helper function. -- Non-pointfree: q l = map (\e -> 13 - abs e) l -- foreach element e in list l: subtract the -- absolute value of e from 13 map fromEnum -- convert to ascii values zipWith(-)=<<tail -- build differences of neighbor elements q.q -- apply q twice on every element sum -- sum it up ``` Edit: @Damien saved one byte. Thanks! [Answer] # [MATL](http://github.com/lmendo/MATL), ~~14~~, 10 bytes ``` dt_v26\X<s ``` [Try it online!](http://matl.tryitonline.net/#code=ZHRfdjI2XFg8cw&input=J3ZhbGxleXMn) *Thanks [@Suever](https://codegolf.stackexchange.com/users/51939/suever) for saving 4 bytes!* Explanation: ``` d % Take the difference between consecutive characters t_ % Make a copy of this array, and take the negative of each element v % Join these two arrays together into a matrix with height 2 26\ % Mod 26 of each element X< % Grab the minimum of each column s % Sum these. Implicitly print ``` Previous version: ``` d26\t13>26*-|s ``` [Answer] ## Python 3, ~~69~~ 68 bytes ``` lambda s:sum([13-abs(13-abs(ord(a)-ord(b)))for a,b in zip(s,s[1:])]) ``` Breakdown: ``` lambda s: sum( ) [ for a,b in zip(s,s[1:])] 13-abs(13-abs(ord(a)-ord(b))) ``` [Answer] # Java, ~~126~~ ~~120~~ 117 bytes ``` int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=(26+z[i]-z[i-1])%26)<14?e:26-e);return r;} ``` Thanks to @KevinCruijssen for pointing out a bug in the original version and suggesting to make the for-loop empty. The use of `(26 + z[i] - z[i - 1]) % 26)` is inspired from a comment by @Neil on another answer. `(26 + ...)%26` serves the same purpose as `Math.abs(...)` because of `...? e : 26 - e`. **Ungolfed**: ``` int f(String s) { byte[]z = s.getBytes(); int r = 0, i = 0, e; for (; ++i < z.length; r += (e = (26 + z[i] - z[i - 1]) % 26) < 14 ? e : 26 - e); return r; } ``` [Answer] ## JavaScript (ES6), ~~84~~ ~~82~~ 79 bytes Saved 3 bytes thanks to Cyoce: ``` f=([d,...s],p=parseInt,v=(26+p(s[0],36)-p(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0 ``` **Explanation:** ``` f=( [d,...s], //Destructured input, separates first char from the rest p=parseInt, //p used as parseInt v=(26+p(s[0],36)-p(d,36))%26 //v is the absolute value of the difference using base 36 to get number from char ) )=> s[0]? //If there is at least two char in the input f(s) //sum recursive call + //added to (v>13?26-v:v) //the current shortest path : //else 0 //ends the recursion, returns 0 ``` **Example:** Call: `f('golf')` Output: `17` --- Previous solutions : 82 bytes thanks to Neil: ``` f=([d,...s],v=(26+parseInt(s[0],36)-parseInt(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0 ``` 84 bytes: ``` f=([d,...s],v=Math.abs(parseInt(s[0],36)-parseInt(d,36)))=>s[0]?f(s)+(v>13?26-v:v):0 ``` [Answer] ## Ruby, 73 bytes ``` ->x{eval x.chars.each_cons(2).map{|a,b|13-(13-(a.ord-b.ord).abs).abs}*?+} ``` [Answer] # PHP, 93 Bytes ``` for(;++$i<strlen($s=$argv[1]);)$r+=13<($a=abs(ord($s[$i-1])-ord($s[$i])))?$a=26-$a:$a;echo$r; ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes ``` SÇ¥YFÄ5Ø-}(O ``` **Explanation** ``` SÇ # convert to list of ascii values ¥ # take delta's YF } # 2 times do Ä5Ø- # for x in list: abs(x) - 13 (O # negate and sum ``` [Try it online!](http://05ab1e.tryitonline.net/#code=U8OHwqVZRsOENcOYLX0oTw&input=dmFsbGV5cw) [Answer] # Perl, 46 bytes Includes +3 for `-p` (code contains `'`) Give input on STDIN without final newline: ``` echo -n zaza | stringd.pl ``` `stringd.pl`: ``` #!/usr/bin/perl -p s%.%$\+=13-abs 13-abs ord($&)-ord$'.$&%eg}{ ``` [Answer] ## Racket 119 bytes ``` (λ(s)(for/sum((i(sub1(string-length s))))(abs(-(char->integer (string-ref s i))(char->integer(string-ref s(+ 1 i))))))) ``` Testing: ``` (f "golf") ``` Output: ``` 17 ``` Detailed version: ``` (define(f s) (for/sum((i(sub1(string-length s)))) (abs(-(char->integer(string-ref s i)) (char->integer(string-ref s(+ 1 i))))))) ``` [Answer] # C#, 87 85 bytes **Improved** solution - *replaced Math.Abs() with the add & modulo trick to save 2 bytes:* ``` s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;}; ``` **Initial** solution: ``` s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;}; ``` **[Try it online!](https://ideone.com/4KtV7g)** Full source, including test cases: ``` using System; namespace StringDistance { class Program { static void Main(string[] args) { Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;}; Console.WriteLine(f("golf")); //17 Console.WriteLine(f("aa")); //0 Console.WriteLine(f("stack")); //18 Console.WriteLine(f("zaza")); //3 Console.WriteLine(f("valleys"));//35 } } } ``` [Answer] # Actually, 21 bytes Based partially on [cia\_rana's Ruby answer](https://codegolf.stackexchange.com/a/93654/47581). There was a bug with `O` (in this case, map ord() over a string) where it would not work with `d` (dequeue bottom element) and `p` (pop first element) without first converting the map to a list with `#`. This bug has been fixed, but as that fix is newer than this challenge, so I've kept `#` in. **Edit:** And the byte count has been wrong since September. Whoops. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=TyM7ZFhAcFjimYAtYEE7w7psLWttYE3Oow&input=InZhbGxleXMi) ``` O#;dX@pX♀-`A;úl-km`MΣ ``` **Ungolfing** ``` Implicit input string. The string should already be enclosed in quotation marks. O# Map ord() over the string and convert the map to a list. Call it ords. ; Duplicate ords. dX Dequeue the last element and discard it. @ Swap the with the duplicate ords. pX Pop the last element and discard it. Stack: ords[:-1], ords[1:] ♀- Subtract each element of the second list from each element of the first list. This subtraction is equivalent to getting the first differences of ords. `...`M Map the following function over the first differences. Variable i. A; abs(i) and duplicate. úl Push the lowercase alphabet and get its length. A golfy way to push 26. - 26-i k Pop all elements from stack and convert to list. Stack: [i, 26-i] m min([i, 26-i]) Σ Sum the result of the map. Implicit return. ``` [Answer] # Java 7,128 bytes ``` int f(String s){char[]c=s.toCharArray();int t=0;for(int i=1,a;i<c.length;a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);return t;} ``` # Ungolfed ``` int f(String s){ char[]c=s.toCharArray(); int t=0; for(int i=1,a; i<c.length; a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a); return t; } ``` [Answer] # Pyth, 20 bytes ``` Lm-13.adbsyy-M.:CMQ2 ``` A program that takes input of a quoted string on STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=Lm-13.adbsyy-M.%3ACMQ2&test_suite=1&test_suite_input=%22aa%22%0A%22stack%22%0A%22zaza%22%0A%22valleys%22&debug=0) **How it works** ``` Lm-13.adbsyy-M.:CMQ2 Program. Input: Q L def y(b) -> m b Map over b with variable d: -13 13- .ad abs(d) CMQ Map code-point over Q .: 2 All length 2 sublists of that -M Map subtraction over that yy y(y(that)) s Sum of that Implicitly print ``` [Answer] ## dc + od, 65 bytes ``` od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp' ``` **Explanation:** Because in *dc* you can't access a string's characters, I used *od* to get the ASCII values. These will be processed in reverse order from the stack (LIFO container) like so: ``` dsN0sT # initialize N (neighbor) = top ASCII value, and T (total) = 0 [lNrdsNr- # loop 'R': calculate difference between current value and N, #updating N (on the first iteration the difference is 0) d*vdD[26-]sS<S # get absolute value (d*v), push 13 (D) and call 'S' to subtract #26 if the difference is greater than 13 d*vlT+sT # get absolute value again and add it to T d0<R]dsR # repeat loop for the rest of the ASCII values xlTp # the main: call 'R' and print T at the end ``` **Run:** ``` echo -n "golf" | ./string_distance.sh ``` **Output:** ``` 17 ``` [Answer] # C, ~~82 86 83~~ 76 bytes ``` t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;} ``` Assumes input string is at least one character long. This doesn't require `#include<stdlib.h>` Edit: Argh, sequence points! [Try it on Ideone](https://ideone.com/mLjkOm) [Answer] # C, 70 bytes ~~76 bytes~~ ``` k,i;f(char *s){for(i=0;*++s;i+=(k=abs(*s-s[-1]))>13?26-k:k);return i;} ``` [Answer] # Scala, 68 bytes ``` def f(s:String)=(for(i<-0 to s.length-2)yield (s(i)-s(i+1)).abs).sum ``` Criticism is welcome. [Answer] # C#, 217 bytes Golfed: ``` IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}} ``` Ungolfed: ``` IEnumerable<int> g(string k) { Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97; for (int i = 0; i < k.Length - 1; i++) { var f = x(k[i]); var s = x(k[i + 1]); var d = Math.Abs(f - s); yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d; } } ``` Output: ``` aa: 0 stack: 18 zaza: 3 valleys: 35 ``` 'a' is 97 when converted to bytes, so 97 is subtracted from each one. If the difference is greater than 13 (ie, half of the alphabet), then subtract the differences between each character (byte value) from 26. A last minute addition of "yield return" saved me a few bytes! [Answer] # Python 3, 126 bytes With list *in*comprehension. ``` d=input() print(sum([min(abs(x-y),x+26-y)for x,y in[map(lambda x:(ord(x)-97),sorted(d[i:i+2]))for i in range(len(d))][:-1]])) ``` [Answer] # PHP, 79 bytes ``` for($w=$argv[1];$w[++$i];)$s+=13-abs(13-abs(ord($w[$i-1])-ord($w[$i])));echo$s; ``` [Answer] # Java, 109 bytes ``` int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x; ``` ]
[Question] [ I remember people saying that code size should be measured in bytes, and not in characters, because it's possible to store information with weird Unicode characters, which have no visual meaning. How bad can it be? In this challenge, you should output the following Lorem Ipsum text, taken from [Wikipedia](https://en.wikipedia.org/wiki/Lorem_ipsum#Example_text): ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ``` Please specify the number of *characters* (not bytes) in your code. Code with the minimal number of characters wins. Your code should only contain valid Unicode characters, as described [here](https://en.wikipedia.org/wiki/Valid_characters_in_XML#XML_1.1), that is: * Code points up to U+10FFFF * No surrogates (the range D800–DBFF is forbidden) * No characters FFFE and FFFF * No null characters (code 0) If your code cannot be displayed, provide a version with offending characters redacted, and a hexdump. Some notes: * The output must be one long line (445 characters). If your system cannot do that (e.g. you're printing it on paper), output a closest approximation. Trailing linebreaks don't matter. * Built-in functions that generate Lorem Ipsum text are not allowed * Please specify a valid text encoding for your code, if relevant [Answer] # JavaScript (ES7), ~~326~~ ~~283~~ ~~273~~ ~~249~~ ~~243~~ 242 chars ``` _=>"򾍮󂙙󱤭󕜛񟉝񚫎󸦘󏇌󻮾󪕍򦙜񴫰𭙝𧇍񛜃򧮖󓔽򅬸󪙗񴦲񿫽񟮩򺥸󫡽񛜕󖷉󂨗񢕕򦯊񗮣󌫉񣔶򥹖񟷗򢫂󧩜񝼜󾿍񙇛񴮪󼬗񟪵񥦘񝕋󖹜񝹜򢟝񚪲󧩙񙁪񛌖󆆸񛌗󳭞񧔍􄮉񧮮񜭾󫤭󕜛񜫩󫬻򄗗񻭲󺙗񟼕􆞪󻤿򅙝𯎎񛉕򹤭󕜛򀿉򏨒񧔷􅚪񞕛򢮾󪂌򆞮􆴼򥾩󓆊򃅝񛏙򣕝񧔷󕴹󮉍򅾢󷫽񜫩񷪹񢝞򢜏򌦒񢖮󳭾󏔶󕚲󺕗򥤲񸾝񝕋󖿇"[r='replace'](/./gu,c=>(c.codePointAt()-4**8).toString(32))[r](/\d/g,d=>" , exum. ".substr(d,2))[r](/^.|\. ./g,x=>x.toUpperCase()) ``` ### How it works The first step in my compression technique is to convert the whole string to lowercase (not mandatory, but looks better), and replace each pair of chars in `, exum.` (as well as the trailing space by itself) with its index in the string plus 2. This makes the text a valid base-32 number: ``` lorem9ips69dolor9sit9amet2consectetur9adipiscing3lit2sed9do3iusmod9tempor9incididunt9ut9labore3t9dolore9magna9aliqua8ut3nim9ad9minim9veniam2quis9nostrud94ercitation9ullamco9laboris9nisi9ut9aliquip943a9commodo9consequat8duis9aute9irure9dolor9in9reprehenderit9in9voluptate9velit3sse9cill69dolore3u9fugiat9nulla9pariatur84cepteur9sint9occaecat9cupidatat9non9proident2sunt9in9culpa9qui9officia9deserunt9mollit9anim9id3st9laboru7 ``` The next step is to convert each 4-char run to decimal, then get the character at that code point. This can be done with the following function: ``` f=s=>s.replace(/..../g,x=>(n=parseInt(x,32),String.fromCharCode(0xD800+(n>>10),0xDC00+(n&0x03FF)))) ``` (**Note:** Since all digits are 2 or greater, the minimum possible value of four digits is 2222₃₂. This is equal to 95978₁₀, or 176EA₁₆; therefore, code points will never be in the restricted range.) And now we have our compressed string: ``` 򾍮󂙙󱤭󕜛񟉝񚫎󸦘󏇌󻮾󪕍򦙜񴫰𭙝𧇍񛜃򧮖󓔽򅬸󪙗񴦲񿫽񟮩򺥸󫡽񛜕󖷉󂨗񢕕򦯊񗮣󌫉񣔶򥹖񟷗򢫂󧩜񝼜󾿍񙇛񴮪󼬗񟪵񥦘񝕋󖹜񝹜򢟝񚪲󧩙񙁪񛌖󆆸񛌗󳭞񧔍􄮉񧮮񜭾󫤭󕜛񜫩󫬻򄗗񻭲󺙗񟼕􆞪󻤿򅙝𯎎񛉕򹤭󕜛򀿉򏨒񧔷􅚪񞕛򢮾󪂌򆞮􆴼򥾩󓆊򃅝񛏙򣕝񧔷󕴹󮉍򅾢󷫽񜫩񷪹񢝞򢜏򌦒񢖮󳭾󏔶󕚲󺕗򥤲񸾝񝕋󖿇 ``` That's 445 chars compressed into 106 chars. The decompression simply reverses this process: 1. Convert each char to its code-point in base-32, minus 65536. 2. Replace each digit `n` with `" , exum. ".substr(n,2)`. 3. Convert each letter after a period or at the beginning of the string to uppercase. The only ES7 feature used is `**`. Replace `4**8` with `65536` to run in a browser that doesn't yet support ES7. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 123 characters All but the final period are packed into 111 32-bit characters (UTF-32). ``` '.',⍨80⎕DR'𦽌򒁭󗕳󆽤𲁲𒁴󇑥󦽣񆍥𧕴򖑡𷍩􆝮񆥬񗌠󶐠񖥥񆽭󖕴􇉯򖍮񖑩񒁴𖰠񗉯􇑥󶱯󒁥𖹧򖱡󦅵􇑕󖥮􆑡򖹩񗘠󖅩񗄠󢁳𧑳񒁤𷉥񆅴􆹯𖱬􆽣󶉡􇍩򗍩􇑵𖥬􇁩񒁸󶌠񆽭󶌠𖕳󧑡򗕄񖄠򒁥񗉵󆽤򒁲񗈠򆕲񖑮􇑩񢁮􇕬񗑡󆕶񒁴􆕳󆱩񂁭𦽬񖔠񷕦􇑡󆱵𗀠񆅩􂹲񖍸񖕴򗌠󲁴񖅣􇑡򗁵𗑡󶸠𧀠񖑩􂱴񆹵􆹩􆱵񗄠񦼠򖍩񖐠񗉥󒁴򖱬󦄠򒁭𶔠𖰠񗉯' ``` `'.',⍨` period appended to `80⎕DR` the 8-bit (`8`) character (`0`) **D**ata **R**epresentation of `'`...`'` the 111 Unicode characters U+**26F4C 9206D D7573 C6F64 32072 12074 C7465 E6F63 46365 27574 96461 37369 10676E 4696C 57320 F6420 56965 46F6D D6574 10726F 9636E 56469 52074 16C20 5726F 107465 F6C6F D2065 16E67 96C61 E6175 107455 D696E 106461 96E69 57620 D6169 57120 E2073 27473 52064 37265 46174 106E6F 16C6C 106F63 F6261 107369 97369 107475 1696C 107069 52078 F6320 46F6D F6320 16573 E7461 97544 56120 92065 57275 C6F64 92072 57220 86572 5646E 107469 6206E 10756C 57461 C6576 52074 106573 C6C69 4206D 26F6C 56520 77566 107461 C6C75 17020 46169 102E72 56378 56574 97320 F2074 56163 107461 97075 17461 F6E20 27020 56469 102C74 46E75 106E69 106C75 57120 66F20 96369 56420 57265 D2074 96C6C E6120 9206D 36520 16C20 5726F**, which all fall in the range 12074–10756C and thus inside the OP's all-permitted range 10000–10FFFF. [Answer] # bash + coreutils + gzip + recode, 191 characters ``` echo -ne "ᾋࠀ㰟퍗\03㖐셱䌱ࡄ戋⪒宮⦀⃬〣ख़ʏ쬏湂삲מּ浊莎ᔍ얪䴬畐Ꮏ肭⽡តप㩴뇶ᮤ樶鞔岀梬昅⹭盖ꈥ먣Ვ빓ỢꞴꃑ괓꣪㷨삗䎺뛔䛓ﵸ摉篨䊷૤⦓헉픺ꉖ橬ꟲỒꗻ퉋則ใ⢍럴摧耼񸺷⒅୴䘺㦳櫇鐱窑駁愵䚞鎴鍉Ⅻक़毽➔脂ힸ⤹喝葁㎋頇㺞ⳃ┶왤惌⒜猜䌋吏젔掚ᛩ鯢⚕䜹鴛皽⨫ꇈ銹믍䄛逦軵융󌒣杻龇븁\0"|recode u8..utf16be|tr -d ٣ܣ|gunzip ``` The string is the gzip of the text interpreted as UTF-16BE, plus a few extra bytes to pair with the unpaired surrogate halves. The tr strips off the extra surrogate halves. This script file (or the shell into which this command is typed) should interpret text as UTF-8, which is why the recode is needed. [Answer] ## Javascript (ES6), ~~261~~ ~~255~~ 254 characters *Saved 1 byte, thanks to ETHproductions* ``` _=>'L'+"⫒㠰拳␰䨒堵̎⨦W䙨ⅶ嵷˘㥆姳䗨⠬巯堡Ŋɩ懪䨶尩个˒≎㥎䜩怷㰷䤆ŵ̊㹩⫒ᨠᩌ㳠抮f̅㩊ᠰ䀩㩎搰㩊ئ抠ˮ婱拗⠩啺巨㬆ɒ㸘∦㰲䤆姵㩀Ƕ̘㨆㬴⠳⠺…䈲䥒䤠⫱᬴w㬣ᠶ⬘嗠⫘䥀噯䗠⫀⫓䕭啩̎Ɏ㹹庘⬆⭀巯奠Ŷ㷨䌯䥀噯⠪ⰸ㦸̆㼱ï哳峮૘梠䵨慷堵幎≠⣨峨愠◳ᬆ䐷ɒ䫓⥎ܑ拠̑Ɏ㼨ó㬴⹠⇫î奩拊̑㹰巯䓠ȮŎ廪ᨀ噧ਸ".replace(/./g,c=>(s=" ,.DEUabcdefghilmnopqrstuvx")[(c=c.charCodeAt()-32)&31]+s[c>>5&31]+s[c>>10]) ``` ### Breakdown Payload: 148 Unicode characters Code: 107 bytes ### How it works We first remove the leading `'L'` from the original message so that we're left with 444 = 148 \* 3 characters. Without the leading `'L'`, the character set is made of the 27 following characters: ``` " ,.DEUabcdefghilmnopqrstuvx" ``` Each group of 3 characters is encoded as: ``` n = 32 + a + b * 32 + c * 32^2 ``` where a, b and c are the indices of the characters in the above character set. This leads to a Unicode code point in the range U+0020 to U+801F, ending somewhere in the "CJK Unified Ideographs". ``` let f = _=>'L'+"⫒㠰拳␰䨒堵̎⨦W䙨ⅶ嵷˘㥆姳䗨⠬巯堡Ŋɩ懪䨶尩个˒≎㥎䜩怷㰷䤆ŵ̊㹩⫒ᨠᩌ㳠抮f̅㩊ᠰ䀩㩎搰㩊ئ抠ˮ婱拗⠩啺巨㬆ɒ㸘∦㰲䤆姵㩀Ƕ̘㨆㬴⠳⠺…䈲䥒䤠⫱᬴w㬣ᠶ⬘嗠⫘䥀噯䗠⫀⫓䕭啩̎Ɏ㹹庘⬆⭀巯奠Ŷ㷨䌯䥀噯⠪ⰸ㦸̆㼱ï哳峮૘梠䵨慷堵幎≠⣨峨愠◳ᬆ䐷ɒ䫓⥎ܑ拠̑Ɏ㼨ó㬴⹠⇫î奩拊̑㹰巯䓠ȮŎ廪ᨀ噧ਸ".replace(/./g,c=>(s=" ,.DEUabcdefghilmnopqrstuvx")[(c=c.charCodeAt()-32)&31]+s[c>>5&31]+s[c>>10]) console.log(f()) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 319 [bytes](http://www.cp1252.com/) Uses CP-1252 encoding. ``` •9y†QHÚSe²ŒÓdéÓ#ǧÖN›Íˆž4GÏóREØån‡·JîÁØ£ÎÁ¥evÑRZ¶—¥1RËÒÆzçå"UNé¨v¯ÊcŒÔÝjðtrœÛeã&“SÁxÌ4Þá1N$ù?T(çÛbŸœfó˜lUž}Þß-©ÃMšBÈÑPàê#jÇÐ+n¼BDFý>–¸äFT×›qÜY³ö9ªòËùˆA‡¾p=‘¤ÚÞ{I¶Œ±Ål#¨5´Aq˜Àž,s<*Ï;‡õã¾»ðŽL´ÅuØö+Xi+S>»/8Kã~WΔƒß”¤µðWluØa'cUÐeà¥ä…ž+œ6*0RU£›aÝQ_ñœoþÏð””Þã7ã¨sŒV`_É-´éÄèÆd¦úE5Í^Aá,‘‡™™¢äTHä0¥3±.}Søg•36B0„. :™J'yð:'z',:'.« ``` **Interpret the following string as a base 36 number and encode into base 214** ``` LOREMYIPSUMYDOLORYSITYAMETZYCONSECTETURYADIPISCINGYELITZYSEDYDOYEIUSMODYTEMPORYINCIDIDUNTYUTYLABOREYETYDOLOREYMAGNAYALIQUA0UTYENIMYADYMINIMYVENIAMZYQUISYNOSTRUDYEXERCITATIONYULLAMCOYLABORISYNISIYUTYALIQUIPYEXYEAYCOMMODOYCONSEQUAT0DUISYAUTEYIRUREYDOLORYINYREPREHENDERITYINYVOLUPTATEYVELITYESSEYCILLUMYDOLOREYEUYFUGIATYNULLAYPARIATUR0EXCEPTEURYSINTYOCCAECATYCUPIDATATYNONYPROIDENTZYSUNTYINYCULPAYQUIYOFFICIAYDESERUNTYMOLLITYANIMYIDYESTYLABORUM ``` **After that we** ``` 36B # encode back into base 36 0„. : # replace 0 with ". " ™J # convert to titlecase and join 'yð: # replace "y" with <space> 'z',: # replace "z" with "," '.« # add a "." at the end ``` For some reason the encoding didn't work with a 0 at the end which is why need a special case for the final ".". [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiOXnigKBRSMOaU2XCssWSw5Nkw6nDkyPDh8Knw5ZO4oC6w43LhsW-NEfDj8OzUkXDmMOlbuKAocK3SsOuw4HDmMKjw47DgcKlZXbDkVJawrbigJTCpTFSw4vDksOGesOnw6UiVU7DqcKodsKvw4pjxZLDlMOdasOwdHLFk8ObZcOjJuKAnFPDgXjDjDTDnsOhMU4kw7k_VCjDp8ObYsW4xZNmw7PLnGxVxb59w57Dny3CqcODTcWhQsOIw5FQw6DDqiNqw4fDkCtuwrxCREbDvT7igJPCuMOkRlTDl-KAunHDnFnCs8O2OcKqw7LDi8O5y4ZB4oChwr5wPeKAmMKkw5rDnntJwrbFksKxw4VsI8KoNcK0QXHLnMOAxb4sczwqw4874oChw7XDo8K-wrvDsMW9TMK0w4V1w5jDtitYaStTPsK7LzhLw6N-V8OO4oCdxpLDn-KAncKkwrXDsFdsdcOYYSdjVcOQZcOgwqXDpOKApsW-K8WTNiowUlXCo-KAumHDnVFfw7HFk2_DvsOPw7DigJ3igJ3DnsOjN8OjwqhzxZJWYF_DiS3CtMOpw4TDqMOGZMKmw7pFNcONXkHDoSzigJjigKHihKLihKLCosOkVEjDpDDCpTPCsS59U8O4Z-KAojM2QjDigJ4uIDrihKJKJ3nDsDoneicsOicuwqs&input=) [Answer] # PHP ,247 Characters combination of the 2 previous versions ``` echo gzuncompress(base64_decode(mb_convert_encoding("敊眱歍䙸兺䕉剆癚䅪礯極南慷潧楏㡷䥷汚䅯⽌䐸灐扫䱁獶猫扅煄橨啎硡灎䱈噑䔷⭂牓㥨䘴㡊䭪瀰獦夷灇漲氵剣杇楳婧啵扥卹摴慩䩢潪䡊圫啨㝩氷卧ぢご煏潪㙍䍮儷焲ㅅ扔⽘桭卥㉇别桃琫啺䍵公欹塊ㅔ煩噭灳氯䥥ぱ堷ぱ⭫橨祇啂灶㙣浵䅈湋䐷硴卑潘㙉砰捭塖橩汪祲昰䥪佄㔸晔慯眸䨲歮欰䱗䕲䑗⭫㡯䅷塏畃猵⭪慅兔佌流晥塹穄䩔扇婇䑍䩊硺䡅䵌⭤㝉䙇佡䙵浢㑩慖剺湱潊ぢ摰㝋卩楹婏㕵猷灴ぁ慫楗倹捙ㄲ⽁䍧塋啊","UTF-16"))); ``` PHP, 261 Characters ``` echo mb_convert_encoding("䱯牥洠楰獵洠摯汯爠獩琠慭整Ⱐ捯湳散瑥瑵爠慤楰楳捩湧⁥汩琬⁳敤⁤漠敩畳浯搠瑥浰潲⁩湣楤楤畮琠畴慢潲攠整⁤潬潲攠浡杮愠慬楱畡⸠啴⁥湩洠慤楮業⁶敮楡洬ⁱ畩猠湯獴牵搠數敲捩瑡瑩潮⁵汬慭捯慢潲楳楳椠畴⁡汩煵楰⁥砠敡⁣潭浯摯⁣潮獥煵慴⸠䑵楳⁡畴攠楲畲攠摯汯爠楮⁲数牥桥湤敲楴⁩渠癯汵灴慴攠癥汩琠敳獥⁣楬汵洠摯汯牥⁥甠晵杩慴畬污⁰慲楡瑵爮⁅硣数瑥畲⁳楮琠潣捡散慴⁣異楤慴慴潮⁰牯楤敮琬⁳畮琠楮⁣畬灡ⁱ畩晦楣楡⁤敳敲畮琠浯汬楴⁡湩洠楤⁥獴慢潲畭.","UTF-16"); ``` Encoding $s contains the string ``` foreach(str_split(bin2hex($s),4)as $c)eval('echo"\u{'.$c.'}";'); ``` Old Version PHP , 386 Bytes|Characters ``` echo gzinflate(base64_decode("NZDBcUMxCERb2QI8v4rklmsKIIjvMCMJWQKPyw/KT25CwLL7PmxKg44VDcWqTSx1UBO/ga0vYRePCSo6dLH2O6RqNpeUXIBorGYFLm3ksnbWoiW6IxyVvlIe4pe0oNG9E6jqI+jAp0O6ttRG0/14ZknthkfoQrflMwrkJZPVydU6olZqbJfyHtKl+9KvpI4chlAab+nJrgB5yg+8bUkKF+iMdHJl1Y4pY8q39CIzg+fH02qMPCdpJ5NC1hKw1vpPKAMFzrgrOfo2hEEzi5gH3l8swyU2xmRgzCSccxxDC/neyBRjmhbpm+ImlUc56qCdG3aeykoosmTubrO6bdAGpIlj/XGNdvwA")); ``` [Answer] # C#, ~~337~~ ~~333~~ 331 characters ``` _=>{var q="";foreach(var c in"潌敲彭灩畳彭潤潬彲楳彴浡瑥弬潣獮捥整畴彲摡灩獩楣杮敟楬ⱴ獟摥摟彯楥獵潭彤整灭牯楟据摩摩湵彴瑵江扡牯彥瑥摟汯牯彥慭湧彡污煩慵弮瑕敟楮彭摡浟湩浩癟湥慩Ɑ煟極彳潮瑳畲彤硥牥楣慴楴湯畟汬浡潣江扡牯獩湟獩彩瑵慟楬畱灩敟彸慥损浯潭潤损湯敳畱瑡弮畄獩慟瑵彥物牵彥潤潬彲湩牟灥敲敨摮牥瑩楟彮潶畬瑰瑡彥敶楬彴獥敳损汩畬彭潤潬敲敟彵畦楧瑡湟汵慬灟牡慩畴ⅲ䕟捸灥整牵獟湩彴捯慣捥瑡损灵摩瑡瑡湟湯灟潲摩湥ⱴ獟湵彴湩损汵慰煟極潟晦捩慩摟獥牥湵彴潭汬瑩慟楮彭摩敟瑳江扡牯浵ਡ")q=q+(char)(c&255)+(char)(c>>8);return q.Replace("!",".").Replace("_"," ");}; ``` *-4 characters by replacing the `.`s after "pariatur" and "laborum" with `!` before combining the chars to wide chars and adding a trailing new line.* *-2 characters by re-assigning the output var rather than appending with `+=`.* How it works: The lorem ipsum string was converted to that mess by replacing `.` with `!`, with `_` so when the ascii chars are placed next to each other to make a wide char each wide char is a single character. ``` /*Func<object, string> Lorem = */ _=> // unused parameter { // Output var var q = ""; // Enumerate each wide char foreach (var c in "潌敲彭灩畳彭潤潬彲楳彴浡瑥弬潣獮捥整畴彲摡灩獩楣杮敟楬ⱴ獟摥摟彯楥獵潭彤整灭牯楟据摩摩湵彴瑵江扡牯彥瑥摟汯牯彥慭湧彡污煩慵弮瑕敟楮彭摡浟湩浩癟湥慩Ɑ煟極彳潮瑳畲彤硥牥楣慴楴湯畟汬浡潣江扡牯獩湟獩彩瑵慟楬畱灩敟彸慥损浯潭潤损湯敳畱瑡弮畄獩慟瑵彥物牵彥潤潬彲湩牟灥敲敨摮牥瑩楟彮潶畬瑰瑡彥敶楬彴獥敳损汩畬彭潤潬敲敟彵畦楧瑡湟汵慬灟牡慩畴ⅲ䕟捸灥整牵獟湩彴捯慣捥瑡损灵摩瑡瑡湟湯灟潲摩湥ⱴ獟湵彴湩损汵慰煟極潟晦捩慩摟獥牥湵彴潭汬瑩慟楮彭摩敟瑳江扡牯浵ਡ") // Split each wide char into two ascii chars q = q + (char)(c&255) + (char)(c>>8); // Restore the replaced periods and spaces return q.Replace("!",".").Replace("_"," "); }; ``` [Answer] # ISOLADOS, 44016 bytes <http://pastebin.com/raw/Y2aAhdpi> Push the ASCII code for every character in the Lorem Ipsum string, concatenate everything, and output. [Answer] # [MATL](http://github.com/lmendo/MATL), 354 characters ``` '8 sxAI($ltZ>2<xa`vYf:s2e9]c&^KtD%e{C*XEpQ]]>dwmi>2;{sUCIZ{V(}Yj 7K&)|,%JD/Pz^:3$*@vVJw)4pgvz4s_$,%pVGu~|PS/Qr7pz5Z2[VV{Lyq}{l!yGiKNg.zFJxL75 sT1]eL2f3iVe~11!|6c+O9.kMWFQYvEp^w0p oH,?Ey"nbV>0g`#)kqTq""" z_AYmyJutvg:o9&AT{#(<42wu.b7" QoOn\#])]ISdH$yc{eM> .[~/`"#2:7C4Mk@eRW8L*_!xjo\cO)!LHK=g:P?&Uc];KdnE(%K7J-z9:7&rhxHl/KZ8\t_C|rT#%28[%+#u.?'F2Y2' ,.DEL'hZa ``` This decodes from base-94 (using the printable ASCII chars except single quote; so only Unicode characters up to 126 are used) to the alphabet of required characters, formed by most lowercase letters, some uppercase letters, space, comma, and period. It takes a few seconds in the online compiler. [Try it online!](http://matl.tryitonline.net/#code=JyU5PmQiX300c1BzZEIrZU1uI3F5bzElS1ExZDc3VkhGeTY0JEUoPXhOYiRXTHZvTWlcbnNyVHcjKyJrR0tkYE51XD1VZWlefXJaU3EiYS1LLnZ7T3YwNG84bTw5fD5wUiIzeHMsVFkldk5bYGAgSCh8IE8heFxlMFoydnMzYm86dSgwNmRrJiR6JSA_JCVVPW0sPTpXJWp8KEVAKCVhNk0qP30xU2pCMz1VYmZHLjQ0c2orLmcmbjYiSEg7RUcxZFI6d11pQ31WYEZAKnFwNnR3RVJgVyJ6al86LjMuTkxGLUVGSVBsUjxIcjBYZ2slV1tiTigqeyAkOT5OYCg4IztMeildK0ZNdkB1flIrQGlaN119SDVMOm1EOHBPWU4qYVIhZC41UVJ-OUhSIyJjLy8tfTs0e15ENTRiWXd-IWB1dHlNXWBNbCdGMlkyJ2prd3l6J1gtJyAsLkRFTFUnaFph&input=) [Answer] ## JavaScript (ES5), 342 characters ``` c="remo ipsudlta,cngbq.UvxDhfE";"L"+"Qq©Úu[Qsx7Ķz`¾ƅ&Øxø§Ëƴ%ţ¾÷öm¿Zw¥ſøûƠtĭĚǎmĭöđnŔơxēǮŗĭ*x÷;ƚ:ȸƚņţǮ{XĩámɓŏƙâĚDUĚǎÁƚÂtĭŎݦ1mňŽ8ZUŽƜ-äļÝÁŌĪqu[Qqƙ¢3*ôĭ[ÞĵĪ%mÄſĘÚu[Q#èĭƝĘň®ŏØȅ˔Ż­#ÂƠoƈŅƆĭƂ§ÿĵĭƘƙ¢VôƠţÅƠqƙƂĔňǮjʨſňô¾Ơn[ēĭœq÷\"ĭĚǎI".split('').map(function(x){y=x.charCodeAt(0);return c[~~(y/27)]+c[y%27]}).join('') ``` Pretty straightforward, so I'm sure there's room for improvement. I encoded every pair of output characters as a single Unicode character. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 279 bytes ``` «;Jq×L↑yVx₅QȯZ3ẎhȦ¼_ø€ẋ°Q±3₀₈∑hṁ₃ø∧≤∆⌐>ʀ↵₌X⇧ƒ₀₆ḃ₅Ḣ~^9\6↓¾<₆≈Q‡‟ṄBḞUß¼ƈv→⟇ʀ7ė⟑∞~*Ṅ∩ꜝtW₴h⟨p&¥z%₇Jɖ⁋¥(₂⌐⌊mṖ⅛ɾṙ3±żð→Ṙq↳'ḭguIH?TLŻrhNɾwl꘍×ByÞkĿMτI□ǑΠȧ½Ḃ≬jȦ₂ṡ⇧j…0Ȧ₂wyẆ₈≠₂d„⟨>∵↔C7⟇≠∑¤ƈƛiḃṁ₍Q]*꘍ṡḂcu%İ∑lL5∧∴!qÞLOτxÞ≥€ṅQh₅Ṫ°₄B*ṫṘ:NḊεβ⋏ṫẎFpƈc⁰ŀqẏy↓{'Ǒ£ẏŻ@kżoƛg)K1cV⌈»ΠC¼⟩F^ȯ₌«\z‛. V‛ ‛, V¡ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%3BJq%C3%97L%E2%86%91yVx%E2%82%85Q%C8%AFZ3%E1%BA%8Eh%C8%A6%C2%BC_%C3%B8%E2%82%AC%E1%BA%8B%C2%B0Q%C2%B13%E2%82%80%E2%82%88%E2%88%91h%E1%B9%81%E2%82%83%C3%B8%E2%88%A7%E2%89%A4%E2%88%86%E2%8C%90%3E%CA%80%E2%86%B5%E2%82%8CX%E2%87%A7%C6%92%E2%82%80%E2%82%86%E1%B8%83%E2%82%85%E1%B8%A2%7E%5E9%5C6%E2%86%93%C2%BE%3C%E2%82%86%E2%89%88Q%E2%80%A1%E2%80%9F%E1%B9%84B%E1%B8%9EU%C3%9F%C2%BC%C6%88v%E2%86%92%E2%9F%87%CA%807%C4%97%E2%9F%91%E2%88%9E%7E*%E1%B9%84%E2%88%A9%EA%9C%9DtW%E2%82%B4h%E2%9F%A8p%26%C2%A5z%25%E2%82%87J%C9%96%E2%81%8B%C2%A5%28%E2%82%82%E2%8C%90%E2%8C%8Am%E1%B9%96%E2%85%9B%C9%BE%E1%B9%993%C2%B1%C5%BC%C3%B0%E2%86%92%E1%B9%98q%E2%86%B3%27%E1%B8%ADguIH%3FTL%C5%BBrhN%C9%BEwl%EA%98%8D%C3%97By%C3%9Ek%C4%BFM%CF%84I%E2%96%A1%C7%91%CE%A0%C8%A7%C2%BD%E1%B8%82%E2%89%ACj%C8%A6%E2%82%82%E1%B9%A1%E2%87%A7j%E2%80%A60%C8%A6%E2%82%82wy%E1%BA%86%E2%82%88%E2%89%A0%E2%82%82d%E2%80%9E%E2%9F%A8%3E%E2%88%B5%E2%86%94C7%E2%9F%87%E2%89%A0%E2%88%91%C2%A4%C6%88%C6%9Bi%E1%B8%83%E1%B9%81%E2%82%8DQ%5D*%EA%98%8D%E1%B9%A1%E1%B8%82cu%25%C4%B0%E2%88%91lL5%E2%88%A7%E2%88%B4!q%C3%9ELO%CF%84x%C3%9E%E2%89%A5%E2%82%AC%E1%B9%85Qh%E2%82%85%E1%B9%AA%C2%B0%E2%82%84B*%E1%B9%AB%E1%B9%98%3AN%E1%B8%8A%CE%B5%CE%B2%E2%8B%8F%E1%B9%AB%E1%BA%8EFp%C6%88c%E2%81%B0%C5%80q%E1%BA%8Fy%E2%86%93%7B%27%C7%91%C2%A3%E1%BA%8F%C5%BB%40k%C5%BCo%C6%9Bg%29K1cV%E2%8C%88%C2%BB%CE%A0C%C2%BC%E2%9F%A9F%5E%C8%AF%E2%82%8C%C2%AB%5Cz%E2%80%9B.%20V%E2%80%9B%20%20%E2%80%9B%2C%20V%C2%A1&inputs=&header=&footer=) Uses Vyxal base-255 encoding, since it can only do lowercase and space, I convert ". " to z and "," to " ", so when I decompress I can easily add back in the punctuation. Finally, it reintroduces uppercase through the sentence-case operator. [Answer] # [Pip](https://github.com/dloscutoff/pip), 139 UTF-8 characters ``` "EDUL ,.".z@:^A*"𝜋򙇶󎹤񕙕󁌯󑃳񞢤񍚙񚝋󖼄𺧶񾔯򣒋򓽅𦕪𢪤񛽹򝕄󒹶򮂏򢗪񺭴󑍺𤣨򮅤񞢊򬪸񙉧񭃤𼧷󙳄𖢋򣹤𺢓񽇳𧅴񹹥𥽯󉊕󎬛񑅾񞄯󑽏򭂛򔣳񍒒𺊸񾒔񾗤󞢇򓻻񽢋󱅧𢚳򝕕𢚴󊻻𾣄𡽺񙇸󞅤񕙕󁇴𦅶󂷋򢥸񾢏򡎕򖻚𾥤󢹏󑅹󊲉񼩛򙅕򕜋𢽤񦶯𾢔󜩇𥣸񹽛󁢀󲕶󒽸𦗴󑊩񉵩𾢉󝧪𾣺𥊴𥬕񺥴󑒙󝍄񽂉󜫇𥽯𥖌񺗧𢥹񞍴󑉵򔧺𡺏򙇪𢼺𤣨򮍳"TB32FB:32 ``` [Try it online!](https://tio.run/##LZG9bttAEIS7PEegMghc2J2rxEhSpUza9Olcp4plEgRJU4QonQTqh4COpBgxkoWYNKU76vhIwe7tAygXwNUWOxjMN3P7/fZ87n388PXz67cXvYsf766/vX/Tg@XC17HT0EBkyGJGdw97Gt5XmPAMg1mMs6VPk5MFsmiwG@91Gvl6pGxYsxJ4meFcCb1kFkWi0Y/9UPNpiXJX0zCQkKW/9KOdGS9Pb8sjxm6Bu/sMTsWB4sqCCfd1KjKQfITKqaCwaxQih1ztyfUYDbZzHNodJpbJpEK968/1OK0wiCKQ3hG7aIzdNKOEO3rUtqi4T3/sAvisMpmYuTV5bQtdav09CFgpibFzpMR@QXVqWNsN9Q@@5rmx46FeDZietDPo8oy4CGloC/KeXDxt5jq2mWYLH7jKcN3soeNjWmwcyNMjCjWnO/6TnlhDkTrCemoq8DboPm@MzqVlUZoYEnKvhnzLUObmH8W0DCxUfZcWv53/2JBPHlBODUIuMAmMxn3W40LCSoZmJlP56aXWoHrV@3Jzdfnp5vrq8nz@Bw "Pip – Try It Online") ### Explanation Observe that there are 28 distinct characters in the string. We can use characters up to character code U+10FFFF = \$1,114,111\$, and since \$\sqrt[4]{1,114,111} \approx 32 > 28\$, we can pack four Lorem Ipsum characters into one Unicode character. (In theory, we might run into some forbidden characters within that range. In practice, that didn't happen.) The decoder is a little longer than it should be because Pip's builtin base conversion generates strings (e.g. `"1RFP"`) rather than lists of numbers (e.g. `[1;27;15;25]`). ``` "EDUL ,.".z@:^A*"𝜋..."TB32FB:32 "𝜋..." String of 112 Unicode characters A* Codepoint of each TB32 Convert each to a (4-digit) base 32 number ^ Split each base 32 number into a list of its digits FB:32 Convert each digit from base 32 to an integer @: Use those numbers to index into "EDUL ,.".z Character lookup table: "EDUL ,." plus lowercase letters ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 126 characters A large integer is encoded in base 1114111, which is converted to custom base `" .,a..z"` and the resulting string is converted to sentence case. ``` "􏿿૵򡏚򈣸󑰙𴿧𦛭񆛤𝌱񊷈􊢗􋄇򟰕򋴜𓏃󠝲򸵫򒕎𯑇񜥷𷇞󛷪􆥮񹳞򵪦󾔁𵇫񽅨功򜡸񄟎𗼵󾌢񂰹󌲏񱲼񺪓񑷯򈽧𘟅󬕲񦗷剗񁛍󛋢􎔊󼱃儮򹔊򤬲򈏉􏢮𝔐󪸉󘝙񍺻􀺿􏶺򑑩򤺶򈳚󸙆񆸏􃜘񁹂򚽊󊫸򺙵򔗲𖁙񕅱𨸞򢟊򏷔󐥓򈞰򺽆񲋧񯺼򭋕񺦶􈫭󤜘𵓈𽂿𷟮򢒽󾫺𢠑򓁌򾟍𞍿􍵻󮘻򸷒񳗩񫄪󈆁񐶢򺍮􀕛񑖑󆷰𣽖񚮾󌞴򃋏󽷤"ÇćβA… .,ìÅвJ‡.ª ``` [Try it online!](https://tio.run/##BcHLjppQGADgV2lm3cw7dNu36CRddNVFX0C8AIKICIiKwsh4mQFFRfEgiiS166aP0Ezitjn/f87eft/3H1@evn293x@4XpZ/oxQn@hDll4wZmwHdlws6d1cgulM6bm1BITJXAoerdQn9jY3qfkRNvcaexwlmaYRdu/3PG9K1IcFoRiiRPOaSkIuzGI47D9Nwzi6WQFMpgqLxelN8HE0yqPtt6pxTdmkFUN0cWSvRYZucIQ9NMMga5WJB@36DLe0E5g65NR0QXI25asDblsLO29qtHuPRUnC6TFDWm1wPYjq2OizMmqw/HoCWn3glL7l@yNEw3nCaH1DeDVk2EEHMdF4b9UE4VnFYKEyJMswHKVpOQnvCAOzGlr5mHga@gjqxWGdmouxtMC9ESNQFrPMzrlQb8vmBy9GKTUd9mpoyLaolJX6MQbdglyinwbOBptDCi69RTyu5lp5Y3D9hRrqwc94gqodMFgXoHALMtZhXbBeMnsFEsqEvRQ@G8YW1vD3WVJ0VZPpwlX5Jv5NP75X5h8eP1@W18Sf5/F6ZPP4M7/f/ "05AB1E – Try It Online") Or, with byte scoring: # [05AB1E](https://github.com/Adriandmen/05AB1E), 277 bytes ``` .•Jã‘éLõÝåʒ?ÿU ¤Ú¹αšt\Žαæ™4c\’ÑÑ[Ï!îèιáܶ§:ºÃbxxQΩù2ú²º„¶₄êy³Ôá‚ιüá‚ÖÆjηatÜÿ˜≠²Ÿ‹»BˆAÇλ—W?üÿ¾TP׸˷]Δ…È¶ª¢X9ât稒ƶövY∞ʒE¯Š¿[¹|εÔgƵΣCõ÷yʒĆ7hZ`ĀÀAFнúO¡]îγĬ-Ðu†₂≠т,ÜÞör,™¨}м!s±ÑH—‘DθwO³¦&‚ÚøγF∊6∊7p×Ì"₄ôʒÛ₅,ÿɽOϦÃ9-p¦»:nÒƶÙØ¶∊[₁?θsÑK„³½ζp÷‰oæB¤|λ·(θŒ¨”∍∊₄=Ýá¾ÉĆΓΓŒ*›αβ™•„wy„.,‡.ª ``` [Try it online!](https://tio.run/##HZFdTxNBFIbv/Rd4YYwpvTBGAglpQCVGTaqJxo9CIhjjx4U0tgpNMBmXWlvUYJdGoJamW3ApjUHbtbvblrLJebtclGQCf@H8kTrlYiZzcc6c53nPfGx27tXzfj/IonwL2yw2sHcHDWzhV08PwXtwjnaQp6as@UZ82u/IGkxOlq88m2axiSyyEawOYR8V2YSBAtm0O0YtLM8tLt6Te2heRovq1GJRJJu1JKoJspCDwSKvOg7OHviB1GvpzMZRgHdc4EyJ6r7LokntyePUBD7LNovcw5Aq9@jw/l2sk4sv5MzIHAsTaTW0SuVHoyjHsUsVBXZkw37/mNPFnn6D/vgl8iLUXJIN5F4cNeT2NSXoJHp6NzXy8snTroCYmDrpoBUmYwb70kKSfg/j@zsWJdY0xXOqBRRbEfbbgJKnyoeTg6EY1ZC9qcBUZteluxAmi8wLA508XGlNcXrlqjojUazj6/mB@7@ejp@sfQrAQ4Y6YaySieXR4SiZ1B57A11hb2JDBZVeibD2MSTdGLK3B9lZ1JF2FA6Lv/MwJ2lnSbbJuShdXx8Ib3H6m2pSQ8bV5gw6RKabkmtyzdcvsWjJmqwrbrVi9ddCQl3BAAsjSNV@/z8 "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 300 chars ``` “ḊḄr⁷ƤⱮx#y&Ọ¬½ẇṾƤẋRṠỊ/IṗIÞƝỊż,CA~ñ;ßɦ4ṿḷNVẸẆ`°ṄjJ⁽Ɱ!Æḋ"uƒ⁽ƙfƈÇœƓ®ḶẓƭƊȮ⁻w}Ġṙ(1€CÐ-ɼ#ȯjėȮoZœ°ȥạ_ẊƊaʠiẸṂṪẒ$ċⱮiẹOṠBṇḲ^*GƓŒA>żıWṭƤe&ėẠF6³ṂḲzlçÇṪġṂŻỵḢ⁴WJC⁽Ỵihıỵṃ¥ẏƬEỴ⁽#ḍʠḢ*^O[4)ỵZ5VoPĠƘṙḅß]<œ/ṅẸ% ḍ"Ɱ+¢¦ß÷⁵Ḍ³Ṅ¶2X|©dċÆṁḢƭṗM°`KǦɗỤɱṆȯƘkṅbṙ⁻l<t,ḟȮạżæ€ṠṣIȥCṘƥṁ©53ẒþØŻṁ£æƥ?¬ṿFæṘ⁴nụ’ṃ“Lrem ipsudlta,cngbq.UvxDhfEo ``` [Try it online!](https://tio.run/##FVJdTxNBFP0rSJUoVokIvkg0WMEUVIyJYDAiIEVaK1UEBaOGxdKaLUbTfWibqF2guwbSli4indktkMzsTrb8i7t/pN59vGfO3PMxE4vE4yutlrf6E4gMJLngSXVR8ozqcmClA6wNVmZHYKaBHosSmJmHQFWw5K4w0FyY/xa/cHAawVD/Z25c58Wm3gP0BEj9/iiYBMzUJKsBTcaGPOkId57hKSCZ9iWRxVkUZsVXnnYUobAqkEMwFVERslv1JOv9J1sFWjh/xVsrh/iPS81GwN2L2Tm3mhh3FFZzNTA3n4EpC3nqVI36WnQN6C6Y2bN2BpUQoiPo9RbQNJD9ic47QnGy/Techm2MAa2IUqTDzoGpDl5jf/27ZP9DnP/hGHTX3kTAscD6B2TLkw7GhkJoF6yD6Jxt@Cj9wlD/uygPIIhHASDfTlUkd06MPOm5gJTx3tHEA1sVeQwBZJ0Xn/Y5ShfQdXR6rg3p7ejxIttiOi/yuieh0obvI8kOux9/ZDszdgarohLuFBWs@h6rTQ7zNNObObBKTQNoyt0T@Ze4cRolsLF432IQSNGtYjFOg@tYnP9UdDvsaiGgeaHhOrbTexUr4sc8j/lw3ua60G4ypJ4Mch1pGHceLM1bLWBK/BR3FyKv2qKv3y7NxBengs/nX0y/ufzo3fLtudmBRKv1Hw "Jelly – Try It Online") The encoding is [Jelly](//github.com/DennisMitchell/jelly/wiki/Code-page). Thanks to compressed strings, I was able to compress it by 3 bytes. [Answer] # Deadfish~, 3209 bytes ``` {{i}ddd}iiiiiic{iii}iiiiiciiic{d}dddc{i}ddc{{d}ii}iiic{{i}ddd}iiic{i}dddciiiciic{d}iic{{d}ii}iiic{{i}ddd}ddc{i}icdddciiiciiic{{d}ii}ddc{{i}dd}iiic{d}c{i}ic{{d}ii}ddddc{iiiiii}iiiiic{i}iic{d}iic{i}iiiiic{{d}iii}ddc{d}ddc{{i}ddd}dddc{i}iicdciiiiic{d}ddddcddc{ii}dddc{d}dddddc{i}iiiiicicdddc{{d}ii}ddc{iiiiii}iiiiiciiiciiiiic{i}dddc{d}iiic{i}c{d}ddddddciiiiiiciiiiic{d}iiic{{d}iii}dc{{i}ddd}dc{i}dddcdddc{i}ic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}ddddcdc{{d}iii}iic{{i}ddd}ddc{i}ic{{d}ii}ic{{i}ddd}dciiiic{i}iicddcddddddciic{d}dc{{d}iii}iic{{i}dd}iiiic{d}dddddc{i}ddciiicdciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{d}dciiiiiicdddddciiiiicdddddc{ii}dddc{d}iiiciiiiiic{{d}ii}ddddc{{i}dd}iiiiicdc{{d}ii}ddddc{{i}ddd}iiiiiic{d}dcic{i}iiiciiic{d}dddc{{d}iii}ic{{i}ddd}dc{i}iiiiic{{d}ii}ddddc{{i}ddd}ddc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiiiiic{i}dddc{d}dddc{dddddd}dddddc{iiiiii}iiiiic{i}icdddc{i}ddciiiic{dd}c{ddddd}dc{d}ddddc{iiiii}iiic{iii}ic{{d}ii}ddddc{{i}ddd}dc{i}dcdddddciiiic{{d}ii}iiic{iiiiii}iiiiiciiic{{d}iii}iic{{i}dd}dddcddddciiiiicdddddciiiic{{d}ii}iiic{{i}dd}iiiiiic{dd}iiic{i}dcdddddc{d}iic{i}iic{dddddd}dddddc{d}ddc{{i}dd}iciiiic{d}ddc{i}c{{d}ii}dddc{{i}dd}ddciciiiicicddciiic{dd}iiic{{d}iii}iic{{i}ddd}dc{ii}dc{dd}ic{i}iiic{d}dddddciiiiiic{i}ic{dd}ic{ii}dc{d}dciiiiiicdc{{d}ii}iic{{i}dd}iiiiic{d}icc{d}dc{i}iic{d}c{i}iic{{d}ii}ic{{i}ddd}iiiiiic{d}dcic{i}iiiciiic{d}ic{i}c{{d}ii}dddc{{i}dd}ddcdddddc{i}c{d}c{{d}iii}dddc{{i}dd}iiiiicdc{{d}ii}ddddc{iiiiii}iiiiic{i}icdddc{i}ddciiiic{d}ddc{i}dddc{{d}ii}c{{i}ddd}dc{ii}dc{{d}i}iic{{i}ddd}dcddddc{dddddd}dddddc{{i}ddd}dddc{i}iicddcciic{d}dc{i}ic{{d}ii}ic{{i}ddd}dddc{i}iicdciiiiic{d}ddddc{i}iiciiiic{dd}c{ii}dc{{d}iii}c{d}ddddc{iii}iiiiiic{iiiii}dc{d}ddc{i}c{{d}ii}dddc{iiiiii}iiiiic{ii}cdc{d}dddddc{{d}iii}ic{{i}ddd}iiic{i}dciiicdddc{d}dddc{{d}iii}ic{{i}ddd}ddc{i}icdddciiiciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{d}dddc{i}iciic{d}dddciiicdddc{i}dc{d}cic{i}iiic{d}ic{i}ic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiiiic{d}iiicdddc{i}dcdddddciiiic{dd}ic{ii}dc{d}dddddc{{d}iii}ic{{i}dd}iiiiiic{dd}iiic{i}dddcdddc{i}ic{{d}ii}ddddc{{i}ddd}dc{i}iiiicc{d}ddddc{{d}iii}ic{{i}ddd}dddciiiiiiciiicc{i}dc{d}iic{{d}ii}iiic{{i}ddd}ddc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}ddd}dc{i}iiiiiic{{d}ii}dddddc{{i}ddd}c{i}iiiiic{d}ddddciic{d}iic{ii}dc{{d}ii}ddddc{{i}dd}ddc{i}dddc{d}icc{d}dc{dddddd}dddddc{{i}dd}c{d}dddddc{ii}dddc{d}ic{d}iic{ii}dcicdddc{{d}iii}iic{d}ddddc{iiii}dddc{iiiii}ic{dd}dciic{i}iciiiic{d}dddddc{i}iiiiiicdddc{{d}ii}ddc{{i}dd}iiic{d}ciiiiiciiiiiic{{d}ii}ddddc{{i}dd}dc{d}ddccddciiiicddcddc{ii}dc{{d}ii}ddddc{{i}ddd}dddc{ii}ddcdddddc{d}iiicdddddcdddc{ii}dc{dd}ic{ii}dc{{d}ii}ddddc{{i}dd}ddcicdc{{d}ii}iic{{i}dd}ciicdddcddddddcdddddcic{i}dciiiiiic{{d}iii}ddc{d}ddc{{i}dd}iiiciic{d}iiiciiiiiic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddd}dddc{ii}ddc{d}iciiiic{d}dddddc{dddddd}dddddc{{i}dd}iciiiic{d}ddc{{d}iii}dddc{{i}dd}dc{d}icciiicddddddciiiiiic{d}iic{dddddd}dddddc{{i}ddd}ddcic{i}iiiic{d}ddddc{i}iiiciiic{d}iiiciiiiiic{{d}ii}ddddc{{i}dd}dddciicdddccdddc{i}ic{{d}ii}ddddc{iiiiii}iiiiic{i}iiicdddddciiiic{{d}ii}iiic{{i}ddd}iiicdddddc{{d}iii}iic{{i}ddd}dc{i}iiiicic{{d}ii}ddddc{{i}ddd}iiiiiic{d}dcic{i}iiiciiiciiic{d}iic{dddddd}dddc ``` [Try it online!](https://deadfish.surge.sh/#LGvd9WS0pbqf/4v3/5+KdQt0JT9/iW6n+LdR+eKfiU/f4lup0LeVH5+JT90Jbp/imLeJT91Qv/3/4t+Kfi3/4lP90KdCW6nULfkf+KdUUL3UKdVC3/5lQlP3Qv/3/5+f+LdQp/i2KdVR/+f+Kf4lP9wlupwt1FQt4lP90KdCW6f4p1RCU/34lup0LeJT94lupx/i35RVUeKcJT/fiW6f+KdVC3R+R+JT90Jbqf5/4px/+VUf+VUL3UKf5/+JT91Qlun/5CU/dUJbqf/4pxi3+finUJT/eJbqcLf/iU/dUJbqdC3lR+finUJT/eJbp1CnR/+LdQp1CqqdVC//f/i3lQt0f4qYqqcKdUL/3+L94lP3VCW6nC3FVH+JT9/i//f/n4lP9+Jbp1FUf+VUf4lP3+Jbp//ip/i3FVCn4t+Kqp1UKdCW6ef4p0LYlP3UJbp0Z/mUfip/iU/34lupwvcKni3+KdVH/4t4qeL3CnH/5CU/fiW6f/ingpwt+KYt+JT94lup//inGLf5+KeLYlP3UJbp0VULYpiU/3UJbp/+QlP3VC//f/i3lQt0f4p0LdQlP2JbqcL3CU9+JbqcVQqqnVQlup1C35QeKcLeJT94lup1C35H/inVC35/ipi9wlP9inVC/f/4v/cKdC2JT91C//f/i9kKdVCU/3iW6n+LcflQp1CU/3iW6nQt5Ufn4lP3Qlup/n/iU/fiW6finULeeKdR+VC3CmYt/ini3iU/dUJbqf5/4lP34lun/+Kf5ULcVUf4qeL3CnVQlP94lun/+Kn+LdRULeJT91Qlupwt/4KdUJT/eJbqdR/+fgtwp+JT9/iW6nQt5Ufn4p1CU/3iW6nC3/+JT91UJbqYt/+KdUeKfi9wlP3VCW6dC3UKeCnCqqdVCW6Yp1UL3UKeKfi9xlQlP9+KdUL/dQv/eKnHi3n+KdVC3/+VCU/dCW6f4pn/n/4lP3VCW6cKdBR/lFC9wlP3VCW6nUL3RVQp/lVFQvcKni9wlP3VCW6dGQlP34lumeVFVRVRi3H/4lP90KdCW6f54p/n/4lP3VCW6n+f+JT9+JbqdQvdCnn+KdVCqqdVCW6ef4p0JT/dQlunCnh+VVH/4p+Kqp1UJbqdGLf+KdULf5+Kf5/+JT91QlunUeVBULeJT91Qv/3/4t/lVH+JT9/iW6n+VUJT/fiW6nC3/mJT91Qlup//inGLf5+fin4qqnUA) Who cares about all that compression nonsense... [Answer] # Deadfish~, 3061 characters ``` {i}dsdddddc{{iii}d}iciiic{d}dddc{i}ddc{{ii}dd}dc{{i}ddd}iiic{i}dddciiiciic{d}iic{{ii}dd}dc{dd}ddsc{i}icdddciiiciiic{{d}ii}ddc{{i}dd}iiic{d}c{i}ic{{ii}ddd}iic{{iii}ii}ic{i}iic{d}iic{i}iiiiic{{d}iii}ddc{d}ddc{dd}ddsdc{i}iicdciiiiic{d}ddddcddc{ii}dddc{d}dddddc{i}iiiiicicdddc{{d}ii}ddc{{iii}ii}iciiiciiiiic{i}dddc{d}iiic{i}c{dd}iiiiciiiiiiciiiiic{d}iiic{{d}iii}dc{dd}ddsic{i}dddcdddc{i}ic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}ddddcdc{{ii}d}ddc{dd}ddsc{i}ic{{d}ii}ic{dd}ddsiciiiic{i}iicddcddddddciic{d}dc{{ii}d}ddc{{i}dd}iiiic{d}dddddc{i}ddciiicdciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{d}dciiiiiicdddddciiiiicdddddc{ii}dddc{d}iiiciiiiiic{{ii}ddd}iic{dd}dsddddcdc{{ii}ddd}iic{{i}dd}ddddc{d}dcic{i}iiiciiic{d}dddc{{d}iii}ic{dd}ddsic{i}iiiiic{{ii}ddd}iic{dd}ddsc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiiiiic{i}dddc{d}dddc{{ii}d}ic{{iii}ii}ic{i}icdddc{i}ddciiiic{dd}c{ddddd}dc{d}ddddc{{iii}i}dc{iii}ic{{ii}ddd}iic{dd}ddsic{i}dcdddddciiiic{{ii}dd}dc{{iii}ii}iciiic{{ii}d}ddc{{i}dd}dddcddddciiiiicdddddciiiic{{ii}dd}dc{dd}dsdddc{dd}iiic{i}dcdddddc{d}iic{i}iic{{ii}d}ic{d}ddc{{i}dd}iciiiic{d}ddc{i}c{{d}ii}dddc{{i}dd}ddciciiiicicddciiic{dd}iiic{{ii}d}ddc{dd}ddsic{ii}dc{dd}ic{i}iiic{d}dddddciiiiiic{i}ic{dd}ic{ii}dc{d}dciiiiiicdc{{d}ii}iic{dd}dsddddc{d}icc{d}dc{i}iic{d}c{i}iic{{d}ii}ic{{i}dd}ddddc{d}dcic{i}iiiciiic{d}ic{i}c{{d}ii}dddc{{i}dd}ddcdddddc{i}c{d}c{{ii}dd}iiic{dd}dsddddcdc{{ii}ddd}iic{{iii}ii}ic{i}icdddc{i}ddciiiic{d}ddc{i}dddc{{d}ii}c{dd}ddsic{ii}dc{{d}i}iic{dd}ddsicddddc{{ii}d}ic{dd}ddsdc{i}iicddcciic{d}dc{i}ic{{d}ii}ic{dd}ddsdc{i}iicdciiiiic{d}ddddc{i}iiciiiic{dd}c{ii}dc{{d}iii}c{d}ddddc{{iii}d}iic{iiiii}dc{d}ddc{i}c{{d}ii}dddc{{iii}ii}ic{ii}cdc{d}dddddc{{d}iii}ic{{i}ddd}iiic{i}dciiicdddc{d}dddc{{d}iii}ic{dd}ddsc{i}icdddciiiciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{d}dddc{i}iciic{d}dddciiicdddc{i}dc{d}cic{i}iiic{d}ic{i}ic{{ii}ddd}iic{{i}ddd}iiiciiiiic{{d}ii}iic{dd}dsdddc{d}iiicdddc{i}dcdddddciiiic{dd}ic{ii}dc{d}dddddc{{d}iii}ic{dd}dsdddc{dd}iiic{i}dddcdddc{i}ic{{ii}ddd}iic{dd}ddsic{i}iiiicc{d}ddddc{{d}iii}ic{dd}ddsdciiiiiiciiicc{i}dc{d}iic{{ii}dd}dc{dd}ddsc{i}icdddciiiciiic{d}dddc{{d}iii}ic{dd}ddsic{ii}ddddc{{ii}ddd}ddc{{i}ddd}c{i}iiiiic{d}ddddciic{d}iic{ii}dc{{ii}ddd}iic{{i}dd}ddc{i}dddc{d}icc{d}dc{{ii}d}ic{{i}dd}c{d}dddddc{ii}dddc{d}ic{d}iic{ii}dcicdddc{{ii}d}ddc{d}ddddc{iiii}dddc{iiiii}ic{dd}dciic{i}iciiiic{d}dddddc{ii}ddddcdddc{{d}ii}ddc{{i}dd}iiic{d}ciiiiiciiiiiic{{ii}ddd}iic{{i}dd}dc{d}ddccddciiiicddcddc{ii}dc{{ii}ddd}iic{dd}ddsdc{ii}ddcdddddc{d}iiicdddddcdddc{ii}dc{dd}ic{ii}dc{{ii}ddd}iic{{i}dd}ddcicdc{{d}ii}iic{{i}dd}ciicdddcddddddcdddddcic{i}dciiiiiic{{d}iii}ddc{d}ddc{{i}dd}iiiciic{d}iiiciiiiiic{{ii}ddd}iic{{i}ddd}iiiciiiiic{{d}ii}iic{dd}ddsdc{ii}ddc{d}iciiiic{d}dddddc{{ii}d}ic{{i}dd}iciiiic{d}ddc{{ii}dd}iiic{{i}dd}dc{d}icciiicddddddciiiiiic{d}iic{{ii}d}ic{dd}ddscic{i}iiiic{d}ddddc{i}iiiciiic{d}iiiciiiiiic{{ii}ddd}iic{{i}dd}dddciicdddccdddc{i}ic{{ii}ddd}iic{{iii}ii}ic{i}iiicdddddciiiic{{ii}dd}dc{{i}ddd}iiicdddddc{{ii}d}ddc{dd}ddsic{i}iiiicic{{ii}ddd}iic{{i}dd}ddddc{d}dcic{i}iiiciiiciiic{d}iic{{ii}d}iiic ``` The code is too long for the recursive Python [implementation on tio.run](https://tio.run/#deadfish-). So here is another link which works (I took it from [this other answer](https://codegolf.stackexchange.com/a/226172/25315)). [Try it online](https://deadfish.surge.sh/#LGvq53tZLS+pqqHf9Sz8eVQ+qHf1Sh31Uvx9VH548vHf1Sh6VMPrKj8/HeXqh31S/HkPrHf1UvHf9esfXjy8fX/jvL9UPKh6VND68j/x5VRQ/qoeVVD6/8yod5eqHf9es/P/H1UPL8fQ9L/P/z/x5fjvL9Q9Kmx9VFQ+sd5fqh5UO+qX48qoh39SoelTD6x3l6x6VNn+Pryiqo8eUO/qVDvql/jyqofVH5H47y9UO+ql+f+PKP/yqj/yqh/VQ8vz/8d/VS8elNVEO/qpeO+qVUPKMfX5+PKod5frHpU2Pr/x39VLx6VMPrKj8/HlUO8v1jvqlUPKj/8fVQ8qh39Sx3/XrH1lQ+qP8ekPVSh5VQ7/rUP+sd/VS8elTY+oqo/x39Uod/16z8d/UqHfVKoqj/yqj/Hf1Sh6U1Q9L8fUVUPLx9eO/qWPKh31Sz/HlQ+h3l6qHfVKjP8yj8el+O/qVD0qbH9Q9LH1+PKqj/8fWPSx/UPKP/yHeXrx6U1UPLB5Q+vHkPrx3l6x31Sqh5Rj6/Px5Y+h3l6qHfVKiqh9DyHf1S/HpTVRDv6qXjv+vWPrKh9Uf48qH1UO8vQ9Kmx/UO8tePSpsqh39Sx6VND68oPHlD6x3l6x6VND68j/x5VQ+vP8ekP6h3l+h5VQ7/qXj/+oeVD6HeXqod/16x/RDyqod5frHfVS/H1H5UPKod5frHpUw+sqPz8d5eqHfVS/P/HeXrx31S8eVQ+s8eVR+VD6h5GPr8eWPrHf1UvHfVS/P/HeXrx6U1Q8vyofUVUf49LH9Q8qqHeX6x6U1Q9L8fVRUPrHf1UvHpU2Pr/B5VQ7y/WPSpo//PwfUPLx39UoelTD6yo/Px5VDvL9Y9Kmx/VUO/qpUO+qkPr/x5VR48vH9Q7+ql476pUPqoeWDyh39Sx31SHlVQ/qoeWPLx/UZUO/qVDyqh/9VD/+selHj6z/HlVQ/qqKh3l6od9Uvx5H/n/47+ql476pQ8qCj/KKH9Q7+ql49Kmh/VFVDy/KqKh/UPSx/UO/qpeO+qVGQ7y9eO+qR5UVVFVGPqP/x3l+qHlQ76pfnjy/P/x39VLx31Uvz/x3l68elTQ/qh5Z/jyqod/Usd9Us/x5UO/ql+O+qUPLD8qqP/x5eO/qWPSpjH1/jyqh9fn48vz/8d/VS8d9UqjyoKh9Y7+ql47/r1j6/KqP8d/VKHfVS/KqHf1Kh6VNj6/zHf1UvHfVKqHlGPr8/Px5eO/qX4A=) Not sure it's optimal, but should be pretty close. It uses the `s` command. It also takes advantage of the overflow feature when it's useful - when the accumulator is equal to 256, it wraps around to 0. ]
[Question] [ # Description Subtract the next P numbers from a N number. The next number of N is N + 1. Look at the examples to get what I mean. # Examples: ``` Input: N=2,P=3 Calculate: n - (n+1) - (n+2) - (n+3) //Ending with 3, because P=3 Calculate: 2 - 2+1 - 2+2 - 2+3 //Replacing N with 2 from Input Calculate: 2 - 3 - 4 - 5 Output: -10 Input: N=100,P=5 Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5) Calculate: 100- 101 - 102 - 103 - 104 - 105 Output: -415 Input: N=42,P=0 Calculate: n Calculate: 42 Output: 42 Input: N=0,P=3 Calculate: n - (n+1) - (n+2) - (n+3) Calculate: 0 - 1 - 2 - 3 Output: -6 Input: N=0,P=0 Calulate: n Calculate: 0 Output: 0 ``` # Input: **N**: Integer, positive, negative or 0 **P**: Integer, positive or 0, not negative # Output: Integer or String, leading 0 allowed, trailing newline allowed # Rules: * No loopholes * This is code-golf, so shortest code in bytes wins * Input and Output must be as described [Answer] # C89, ~~38~~, ~~35~~, 33 bytes ``` h(n,p,r)int*r;{*r=n-p++*(n+p/2);} ``` Test it on [Coliru](http://coliru.stacked-crooked.com/a/d79b4c81eab66666). [Answer] # Maple, 19 bytes ``` n-sum(i,i=n+1..n+p) ``` Usage: ``` > f:=(n,p)->n-sum(i,i=n+1..n+p); > f(2, 3); -10 > f(100,5); -415 > f(42,0); 42 ``` [Answer] # [Perl 6](http://perl6.org), 21 bytes ``` {$^n-[+] $n^..$n+$^p} ``` ## Explanation: ``` # bare block lambda with two placeholder parameters 「$n」 and 「$p」 { $^n - # reduce using 「&infix:<+>」 [+] # a Range that excludes 「$n」 and has 「$p」 values after it $n ^.. ($n + $^p) } ``` [Answer] # Java 8, 25 bytes ``` (n,p)->n-(p*n+p*(p+1)/2); ``` # Ungolfed test program ``` public static void main(String[] args) { BiFunction<Integer, Integer, Integer> f = (n, p) -> n - (p * n + p * (p + 1) / 2); System.out.println(f.apply(100, 5)); } ``` [Answer] # Scala, 41 bytes ``` def?(n:Int,p:Int)=n-(1 to p).map{n+_}.sum ``` Testing code: ``` println(?(2,3)) println(?(100,5)) println(?(42,0)) println(?(0,3)) println(?(0,0)) // Output -10 -415 42 -6 0 ``` [Answer] # Clojure/Clojurescript, 30 bytes ``` #(reduce -(range %(+ 1 % %2))) ``` The straightforward approach is shorter than the mathematically clever ones. [Answer] # [Julia](http://julialang.org): 17-18 bytes (13 as program with terminal inputs) As per suggestion in comments that "function or program" form is needed: * as function: 17 characters, 18 bytes if you count ∘ as multibyte ``` n∘r=2n-sum(n:n+r) ``` usage: `5∘3` outputs `-16` * as program, passed initial parameters from terminal: 13 bytes: ``` 2n-sum(n:n+r) ``` usage: `julia -E 'n,r=5,3;include("codegolf.jl")'` [Answer] # Excel, 20 bytes Subtract the next `B1` integers from `A1`: ``` =A1-B1*(A1+(B1+1)/2) ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 11 bytes Formula stolen elsewhere... ``` ~1$1$)2/+*- ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v85QxVBF00hfW0v3/39DAwMFUwA "GolfScript – Try It Online") ## Explanation This just boils down to ``` A-B*(A+(B+1)/2) ``` Converted to postfix. # [GolfScript](http://www.golfscript.com/golfscript/), 15 bytes ``` ~),{1$+}%{-}*\; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v05Tp9pQRbtWtVq3VivG@v9/QwMDBVMA "GolfScript – Try It Online") ## Explanation ``` ~ # Evaluate the input ), # Generate inclusive range {1$+}% # Add each item by the other input {-}* # Reduce by difference \; # Discard the extra other input ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-hr`, ~~8~~ 6 bytes ``` +ɧ^∑$- ``` [Try it online!](https://tio.run/##y05N//9f@9D@k8vjHnVMVNH9/9/QwIDLlAtI/tfNKAIA "Keg – Try It Online") No formula, just a for loop! [Answer] ## [W](https://github.com/a-ee/w) `d`, ~~6~~ 4 bytes Surprised to see that it's not short at all. (Although it at least ties with Jelly...) ``` 7▄i← ``` ## Explanation Uncompressed: ``` +.@-R + % Generate b+a . % Generate range(a,b+a) @-R % Reduce via subtraction ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ôV r- ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9FYgci0&input=MiAz) ``` ôV r- :Implicit input of integers U=N & V=P ôV :Range [U,U+V] r- :Reduce by subtraction ``` [Answer] # [Demsos](https://desmos.com), 20 bytes ``` f(n,p)=n-p(p/2+.5+n) ``` Other 20-byters: ``` f(n,p)=n-pn-p(p+1)/2 f(n,p)=n-pp/2-.5p-np f(n,p)=n-.5p(2n+p+1) f(n,p)=n-pn-.5pp-.5p ``` [Try it on Desmos!](https://www.desmos.com/calculator/ok09b870nw) With the sum function, it's 27 bytes: ``` f(n,p)=n-∑_{x=n+1}^{n+p}x ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes ``` {-/x+!y+1} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rW1a/QVqzUNqzl4kqLNrI2jgVShgYG1qYghomRtQGINoCIGwB5AFkZDQs=) Quick. [Answer] # [Python 3](https://en.wikipedia.org/wiki/Python_(programming_language)), 43 bytes ``` lambda n,p:n-sum([n+i+1 for i in range(p)]) ``` [Try it online!](https://tio.run/##LY3BCoMwEETP9iv2uIsR1tpCya@EHFLaaqCuS9RDvz51wdubGXijv21aZHhoqZ@lgDhQyAIhXB0M0UHomR3cjW5HxQZ8Tmw5@kujJcuGWL9pfr7SIVEv3brPGKTNbQ9mzqYtScY3KkWqhPZFVP8 "Python 3.8 (pre-release) – Try It Online") Explanation: ``` lambda n,p: # Lambda header [n+i+1 for i in range(p)] # Next P numbers sum( ) # Sum each number n- # Subtract from N for final result ``` [Answer] # [Ly](https://github.com/LyricLy/Ly), 14 bytes ``` n0ns-0Rl0I*-&+ ``` [Try it online!](https://tio.run/##y6n8/z/PIK9Y1yAox8BTS1dN@/9/QwMDLlMA "Ly – Try It Online") This relies on the fact that for X=starting number and Y=iterator, the answer is: `X - (X*Y) - sum([1..Y])` It uses the `R` command to generate the range of negative numbers. ``` n - read starting number onto the stack 0n - push "0", read iteration count onto the stack s - save iteration count - - convert to negative number 0 - push "0" to set ending number R - generate a range of negative numbers l - load the iterator count 0I - copy the starting number * - multiple to get base number common to all decrements - - convert to negative (relies on "0" from range) &+ - sum the stack, answer prints automatically ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes ``` ⊣-(+/(⍳⊢)+⊣) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYt1NbT1NR71bn7UtUhTG8jX/P@obypQytDAQCFNwZQLwjMCso25/gMA "APL (Dyalog Unicode) – Try It Online") ]
[Question] []
[Question] [ Write a program or function that takes in a single-line string. You can assume it only contains [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters). Print or return a string of an ASCII art rocket such as ``` | /_\ |E| |a| |r| |t| |h| |_| /___\ VvV ``` with the input string written from top to bottom on the fuselage. In this case the input was `Earth`. The height of the rocket (including flames) is always the length of the string plus five. Each line in the output may have up to two trailing spaces and there may be a single optional trailing newline. **The shortest code in bytes wins.** ## More Examples: ``` [empty string] | /_\ |_| /___\ VvV a | /_\ |a| |_| /___\ VvV |0 | /_\ ||| |0| |_| /___\ VvV \/\ | /_\ |\| |/| |\| |_| /___\ VvV _ _ [note trailing space] | /_\ | | |_| | | |_| | | |_| /___\ VvV [4 spaces] | /_\ | | | | | | | | |_| /___\ VvV SPACEY | /_\ |S| |P| |A| |C| |E| |Y| |_| /___\ VvV ``` # Leaderboard ``` var QUESTION_ID=91182,OVERRIDE_USER=26997;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] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ↷¦|_θ__←v↖V→/↑_↑⊕Lθ/‖B ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R2/ZDy2riz@2Ij3/UNqHsUdu0sEdtk/QftU0E8ic@6pr6fs@aczv0HzVMe79n0f//CiDABQA "Charcoal – Try It Online") Needs trailing newline in input, due to how Charcoal input works. [Answer] # [V](https://github.com/DJMcMayhem/V), 47 46 39 37 35 bytes ``` A_Ó./ |&|\r a/___\ VvVHO | /_\ ``` [Try it online!](https://tio.run/##K/v/3zFe@vBkPX2FGrWamCKuRP34@PgYLoWwsjBpD38FhRouBf34mP//M1JzcvIVyvOLclIA "V – Try It Online") This is my first time trying to golf something. There is probably room for improvement since I don't know V, only vim. Hexdump: ``` 00000000: 415f 1bf3 2e2f 207c 267c 5c72 2f67 0a61 A_.../ |&|\r/g.a 00000010: 2f5f 5f5f 5c0a 2056 7656 1b48 4f20 207c /___\. VvV.HO | 00000020: 0a20 2f5f 5c . /_\ ``` [Answer] # Java 10, ~~102~~ ~~99~~ 81 bytes ``` a->{var r=" |\n /_\\\n |";for(var c:a)r+=c+"|\n |";return r+"_|\n/___\\\n VvV";} ``` 3 bytes saved thanks to *@Jules*. [Try it online.](https://tio.run/##bZBPa4NAEMXv@RTDnlYk2nPFQgg5NhSEQOkWmW5Ms6lZZRyFEP3sdv3Tg213YZf3Zob3Yy7Y4Ppy/Op1jlUFz2jsfQVgLGd0Qp3BfpAACZOxn6ClPiO9vQN6kfO7lXsqRjYa9mAhhh7XT/cGCSgWAK2yEKZKua8V0akgOZT0I3rkx9oX7VSgjGuyQL5InROm6TRyaA4i6vpoCCnrj9yFzFlNYY5wdaxy4hqBJlDOKpZCjHg/CpeyfVhqpUKllhak7v6y3Fk6yctmu3tdejskPos/yxmBx455kcaWNc/Iya3i7BoUNQelK3JupQ20HFsCLrZu4xsivEnPm7P@mZgju/4b) **Explanation:** ``` a->{ // Method with character-array parameter and String return-type var r=" |\n /_\\\n |"; // Result-String, starting with the top part: // | // /_\ // | for(var c:a) // Loop over each character in the input-array: r+=c // Append the character to the result-String, +"|\n |"; // with trailing: // | // | return r // Return the result-String, +"_|\n/___\\\n VvV";} // appended with bottom part: // _| // /___\ // VvV ``` [Answer] # Excel 2016+, 73 bytes An anonymous worksheet function that takes input from cell `A1` and outputs to the calling cell ``` =" | /_\ |"&Concat(Mid(A1,Sequence(Len(A1)),1)&"| |")&"_| /___\ VvV" ``` [Answer] # C, ~~128~~ ~~97~~ 94 bytes ``` #define P printf( r(char*s){for(P" |\n /_\\\n");*s;P" |%c|\n",*s++));P" |_|\n/___\\\n VvV");} ``` Un-golfed: ``` #define P printf( /* Knock off a few bytes by abusing the preprocessor */ r(char*s) { /* Function r (for rocket) accepting a string */ for( /* For loop */ P " |\n /_\\\n"); /* BEFORE entering loop, print the top part */ *s; /* Loop until the null at the end of the string is encountered */ P " |%c|\n",*s++) /* Print a middle section for each char */ ); P " |_|\n/___\\\n VvV"); /* Print the bottom part */ } ``` After realizing that I have completely forgotten about `puts()` due to its usual uselessness (I always use `printf()`), I finally got it under 90 bytes, only to realize that someone else had beaten me to it: ``` r(char*s){for(puts(" |\n /_\\");*s;printf(" |%c|\n",*s++));puts(" |_|\n/___\\\n VvV");} ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, ~~30~~ 24 bytes ``` `|/__`:ḣṫ⁰p\|vp÷„Ḣ‛VvWøM ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiYHwvX19gOuG4o+G5q+KBsHBcXHx2cMO34oCe4bii4oCbVnZXw7hNIiwiIiwiRWFydGgiXQ==) *-5 bytes thanks to allxy* ## How? ``` `|/__`:ḣṫ⁰p\|vp÷„Ḣ‛VvWøM `|/__` # Push string "|/__" : # Duplicate ḣ # Head extract, push a[0] and a[1:] ṫ # Tail extract, push a[:-1] and a[-1] (stack: a[0], a[1:-1], a[-1]) ⁰p # Prepend the input to this a[-1] \|vp # For each character, prepend "|" ÷ # Dump, push all contents to the stack „ # Rotate stack left once Ḣ # Remove head ‛Vv # Push string "Vv" W # Wrap stack into a list øM # Flip brackets and palindromise each # C flag centers and joins on newlines ``` [Answer] # Pyth, 38 bytes ``` j++" | /_\\"jR_B" |"+Q\_"/___\\ VvV ``` [Try it online.](http://pyth.herokuapp.com/?code=j%2B%2B%22++%7C%0A+%2F_%5C%5C%22jR_B%22+%7C%22%2BQ%5C_%22%2F___%5C%5C%0A+VvV&input=%22Earth%22&test_suite_input=%22Earth%22%0A%22%22%0A%22a%22%0A%22%7C0%22%0A%22%5C%2F%5C%5C%22%0A%22_+_+%22%0A%22SPACEY%22&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=j%2B%2B%22++%7C%0A+%2F_%5C%5C%22jR_B%22+%7C%22%2BQ%5C_%22%2F___%5C%5C%0A+VvV&input=%22Earth%22&test_suite=1&test_suite_input=%22Earth%22%0A%22%22%0A%22a%22%0A%22%7C0%22%0A%22%5C%2F%5C%5C%22%0A%22_+_+%22%0A%22SPACEY%22&debug=0) [Answer] # Scala, 97 94 77 bytes ``` print(" |\n /_\\\n"+args(0).map{" |"+_+"|\n"}.mkString+" |_|\n/___\\\n VvV") ``` [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), ~~157 154~~ 143 bytes ``` pL | def p print : lbl L Line pL /_\ loadL : a = 256 :a x = get a if x c GOTO e :c p | pChar x pL | a + 1 if x a :e pL |_| pL /___\ p VvV ``` It should be fairly readable. Feel free to [try it online!](http://silos.tryitonline.net/#code=cEwgICB8CmRlZiBwIHByaW50IDogbGJsIEwgTGluZQpwTCAgL19cCmxvYWRMIDoKYSA9IDI1Ngo6YQp4ID0gZ2V0IGEKaWYgeCBjCkdPVE8gZQo6YwpwICB8CnBDaGFyIHgKcEwgfAphICsgMQppZiB4IGEKOmUKcEwgIHxffApwTCAvX19fXApwICBWdlY&input=&args=Uy5JLkwuTy5T) [Answer] # R, 116 bytes **Golfed** ``` write(c(" |"," /_\\",sapply(strsplit(scan(,""),"")[[1]],function(y)paste0(" |",y,"|"))," |_|","/___\\"," VvV"),1,1) ``` **Ungolfed** ``` write( # Write to console x = c(" |"," /_\\", # Add in stock rocket part sapply(X = strsplit(scan(,""),"")[[1]], # Take in rocket part specification, split string, loop over all specs FUN = function(y) { paste0(" |",y,"|")) # Custom build rocket body }, " |_|","/___\\"," VvV"), # Add stock parts file = 1, # Print to console ncolumns = 1) | /_\ |s| |t| |r| |s| |p| |l| |i| |t| |!| |_| /___\ VvV ``` [Answer] **Python 3, ~~78~~ 75 Bytes** ``` w=" |\n /_\\" for i in input(): w+="\n |"+i+"|" w+="\n |_| \n/___\\ \n VvV" print(w) ``` Thanks @ValueInk for spotting that I could lose 3 bytes by clearing the `input` function of arguments. [Answer] # Lua, 69 68 bytes ``` print([[ | /_\ ]]..(...):gsub('.',' |%0|\n')..[[ |_| /___\ VvV]]) ``` Should work with Lua 5.1 - 5.3 (tested with 5.3). I don't have enough rep to comment on nolan's answer, but this is quite similar. I'm using `[[long string]]` syntax to save a few bytes by avoiding needing to escape newlines and backslashes. `gsub` doesn't need to specify a capture because `%0` can be used. (Actually, `%1` still works without a capture as well, but this isn't strictly documented.) I also trimmed away the input validation; not sure why it was there -- an empty string input (as opposed to empty input) will work fine. Handling a missing `arg[1]` can be done more briefly just by `(arg[1]or''):gsub(...)` anyway, although at this point it is briefer just to switch to `io.read()` and get the input from stdin. Anyway, `...` is a shorter way to get command-line input (even if parens are needed). [Answer] # [Perl 6](http://perl6.org/), 51 bytes ``` {" | /_\\ {("|$_| "for |.comb,'_')}/___\\ VvV"} ``` A lambda that takes a string as argument, and returns a string. [try it online](https://glot.io/snippets/ehvqs6hxl2) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 50 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ↑'/___\' ' VvV',⍨' |' ' /_\',↓' ','|',⍨'|',⍪⍞,'_' ``` OK, so it may not be the shortest submission, but it *is* the only one that carries the name of [a real rocket manufacturer](https://en.wikipedia.org/wiki/Applied_Physics_Laboratory): ``` | /_\ |A| |P| |L| |_| /___\ VvV ``` [TryAPL online!](http://tryapl.org/?a=%7B%u2191%27/___%5C%27%20%27%20VvV%27%2C%u2368%27%20%20%7C%27%20%27%20/_%5C%27%2C%u2193%27%20%27%2C%27%7C%27%2C%u2368%27%7C%27%2C%u236A%u2375%2C%27_%27%7D%A8%27%27%20%27a%27%20%27%7C0%27%20%27%5C/%5C%27%20%27%20_%20_%20%27%20%27%20%20%20%20%27%20%27SPACEY%27&run) [Answer] ## [><>](http://esolangs.org/wiki/Fish), 60 bytes ``` ' |'a' /_\'av a$v?(0:i'|| '< 'r\~'_'$a'/___\'a' VvV o>l?!; ``` Pretty simple really. lots of strings, the newlines are annoying. [Try it online](https://fishlanguage.com/playground/Zh3YMSH3Ba2vWGvWo) ``` | /_\ |>| |<| |>| |_| /___\ VvV ``` [Answer] # Swift, 99 byte ``` let f:(String)->String={$0.characters.reduce(" |\n /_\\\n"){$0+" |\($1)|\n"}+" |_|\n/___\\\n VvV"} ``` Use like this: ``` print(f("Some String")) ``` Result: ``` | /_\ |S| |o| |m| |e| | | |S| |t| |r| |i| |n| |g| |_| /___\ VvV ``` [Answer] # R, 101 bytes This is an improvement on [Frédéric's answer](https://codegolf.stackexchange.com/a/91275/59052). I eliminated the variable definition, the for-loop, and the need for the `sep=""` argument. ``` cat(" |\n /_\\\n",sapply(strsplit(scan(,""),""),function(x)paste0("|",x,"|\n")),"|_|\n/___\\\n VvV") ``` Ungolfed: ``` cat(" |\n /_\\\n", # Print top of rocket sapply( strsplit(scan(,""),""), # Take stdin and convert to list of chars function(x)paste0("|",x,"|\n")), # Print letters ,"|_|\n/___\\\n VvV") # Print bottom and FLAMES ``` I'm sure that there is still some improvement possible. [Answer] ## Perl, 51 bytes **50 bytes code + 1 for `-p`.** ``` s/./$&| |/g;s~^~ | /_\\ |~;s~$~_| /___\\ VvV~ ``` ### Usage ``` perl -pe 's/./$&| |/g;s~^~ | /_\\ |~;s~$~_| /___\\ VvV~' <<< earth | /_\ |e| |a| |r| |t| |h| |_| /___\ VvV ``` ``` perl -pe 's/./$&| |/g;s~^~ | /_\\ |~;s~$~_| /___\\ VvV~' <<< '' | /_\ |_| /___\ VvV ``` ``` perl -pe 's/./$&| |/g;s~^~ | /_\\ |~;s~$~_| /___\\ VvV~' <<< '0|' | /_\ |0| ||| |_| /___\ VvV ``` [Answer] # Dart, 80 bytes ``` g(s)=>' |\n /_\\\n${s.split('').map((s)=>' |$s|\n').join()} |_|\n/___\\\n VvV'; ``` Running it through ``` main()=>print(g("Jasper")); ``` Gives: ``` | /_\ |J| |a| |s| |p| |e| |r| |_| /___\ VvV ``` [Answer] ## [GNU sed](https://www.gnu.org/software/sed/), ~~54~~ ~~49~~ 48 bytes This was my first answer to a challenge on this site. The solution is simple, mainly printing, so I spent some time making sure that it can't be golfed anymore. ``` s:.:\n |&|:g s:: |& /_\\&: a\ |_|\n/___\\\n VvV ``` **[Try it online!](https://tio.run/nexus/sed#@19spWcVk6dQo1Zjlc5VbGWlAGQq6MfHxKhZcSXGKNTE18Tk6cfHAwWAqsLKwv7/93MMdgQA)** Fast forward half a year later, I rewrote the script, used a trick for good measure and golfed it down to 1 byte shorter. Now that's progress! **Explanation:** the pattern space at each step is mentioned for clarity, given the input example "GO" ``` s:.:\n |&|:g # turn each input char into a section of the rocket (\n |G|\n |O|) s:: |& /_\\&: # 's::' is a trick; the search part is actually the one from the previous 's' #command, i.e. a char. Only the first char, '\n', the modifier 'g' is not #inherited. The replace part is the head of the rocket. ( |\n /_\\n |G|\n |O|) a\ |_|\n/___\\\n VvV # append the tail of the rocket, plus implicit printing at the end | /_\ |G| |O| |_| /___\ VvV ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 38 bytes ``` " | /_\ |"q'_+"| |"*"| /___\ VvV" ``` [Try it online!](https://tio.run/nexus/cjam#@6@koFDDpaAfH8OlUKNUqB6vrVQDYmkBKf34eJBwWFmY0v//NQYA "CJam – TIO Nexus") **Explanation** Nothing fancy, pretty straightforward. ``` " |\n /_\\n |" Push the top of the rocket q'_+ Push the input and append an underscore "|\n |"* Join the characters of the input with the sides "|\n/___\\n VvV" Push the bottom of the rocket ``` [Answer] # Common Lisp, ~~85~~ 74 bytes ``` (lambda(s)(format t" | /_\\ ~{ |~a| ~} |_| /___\\ VvV"(coerce s'list))) ``` [Try it online!](https://tio.run/##FcwxDoAgDADAnVc0XWwnX@EXmEhIRY0mGgwQFytfR11vuLBv@WyNaJdjnIQy0xLTIQUKAqiB3jtn6g1aRU19QL2a3vtfwV4WKcQ5hRly902FmXGQVFbk1l4 "Common Lisp – Try It Online")(I added some bytes to call this anonymous function) For changing part we take input as string. ``` ~{ |~a| ;we loop through all characters of string ~} ;printing characters from list (coerce s'list) ;string is converted into list of characters later used by above loop ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 52 characters ``` ?(\|'\| \ )\\\_\/ \ \| ^\ \|\_\|\ \/\_\_\_\\\ VvV ``` Only tricky point is that Keg has no strings, the input is pushed to stack character by character. So the processing order is: read input (`?`) and turn it into middle section, append top section reversed, reverse them all (`^`), append bottom section. (Note that the interpreter (TIO implementation?) does not support absolutely no input. Empty input is specified as single newline, which will not be processed anyway.) [Try it online!](https://tio.run./##y05N///fXiOmRj2mRiGGSzMmJiY@Rh/IAnIV4mK4FGJqgAI1QL4@kAbBGKBgWFnY//@uiUUlGQA "Keg – Try It Online") [Answer] # C - 84 Bytes ``` f(char*s){puts(" |\n /_\\");while(*s)printf(" |%c|\n", *s++);puts(" |_|\n/___\\\n VvV");} ``` **Ungolfed** ``` f(char* s) { puts(" |\n /_\\"); while(*s) printf(" |%c|\n", *s++); puts(" |_|\n/___\\\n VvV"); } ``` **Explanation** Function that receives a string prints it into the ascii-rocket. Tested on GCC, generates some warnings if not compiled with -std=c89. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 36 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ù |ÿ /_\è'_▐û |\+mñn'/ÿ___\+ÿ VvV]n ``` Input as a list of characters. [Try it online.](https://tio.run/##y00syUjPz0n7///wTgWFmsP7FfTjYw6vUI9/NG3C4d0KNTHauYc35qnrH94fHx8fow2UDysLi837/1/dVV1HPRGIi4C4BIgz1Lm4gAJc6jVAjgGQjokBMvSBGMjgUlcAMuKBGEFDxBCYSz0YSAcAsSMQOwMxyIpIdQA) **Explanation:** ``` ù | # Push string " |" ÿ /_\ # Push string " /_\" è # Push the inputs as string-array '_▐ '# Append a trailing "_" û |\+ # Prepend " |" in front of each string mñ # Palindromize each string in the list n # Join it with newline delimiter '/ '# Push string "/" ÿ___\ # Append string "___\": "/___\" ÿ VvV # Push string " VvV" ] # Wrap the entire stack into a list n # Join it with newline delimiter # (after which the entire stack is output implicitly) ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~65~~ 60 bytes ``` `0:" |\n /_\\";{`0:" |",x,"|"}'$1:0;`0:" |_|\n/___\\\n VvV" ``` [Try it online!](https://ngn.bitbucket.io/k#eJwrtjKwMrBOMLBSUlCoiclT0I+PiVGyrgYL1CjpVOgo1SjVqqtoFUPU1MQDFenHxwNVARWHlYUpAQBBrRJs) -5 bytes thanks to Razetime! First ever K answer! May not be perfect, but it's pretty good! Explaination: ``` `0:" |\n /_\\" / Print the top of the rocket {`0:" |",x,"|"} / Print " |$x|" '$1:0; / For each character in the user input / Note: ';' is important because without it / the console will also output `(:: :: ...)` `0:" |_|\n/___\\\n VvV" / Print the end of the rocket ``` [Answer] ## Batch, 128 bytes ``` @echo off set s=%1_ echo ^| echo /_\ :l echo ^|%s:~0,1%^| set s=%s:~1% if not "%s%"=="" goto l echo /___\ echo VvV ``` [Answer] ## C#, ~~130~~ ~~111~~ 95 bytes ``` s=>{var a=" |\n /_\\\n";foreach(var c in s)a+=" |"+c+"|\n";a+=" |_|\n/___\\\n VvV";return a;}; ``` *Saved 16 bytes thanks to Kevin Cruijssen* [Answer] # Javascript (using external lib - Enumerable) (84 bytes) ``` n=>" |\n /_\\\n"+_.From(n).WriteLine(x=>" |"+x+"|")+(n?"\n":'')+" |_|\n/___\\\n VvV" ``` Link to lib: <https://github.com/mvegh1/Enumerable> Code explanation: Pretty straight forward. Just boilerplates the rocketship template (top and bottom), and concats the fuselage string in the middle. Whats eating up a lot of bytes is the check if the input is truthy, because for an empty string it's wrong to add a newline to the beginning of the bottom template I love how the native JS answer blows this away... [![enter image description here](https://i.stack.imgur.com/Q1sAl.png)](https://i.stack.imgur.com/Q1sAl.png) [Answer] # Haskell, ~~67 63~~ 59 bytes ``` (++"_|\n/___\\\n VvV").(" |\n /_\\\n |"++).(>>=(:"|\n |")) ``` Thanks to Damien it's now essentially the same as xnor's answer, just in point-free notation. [Ideone it!](http://ideone.com/MYt2Mh) ]
[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] ## Ruby, 35 bytes ``` ->s{(?!..?~).map{|x|s.scan x}-[[]]} ``` Tried to turn the problem upside down to save some bytes. Instead of starting with the string, start with the possible character set. [Answer] ## Perl6, ~~48~~ ~~47~~ 45 ``` slurp.comb.Bag.kv.map:{$^a.trim&&say $a x$^b} ``` Thanks to manatwork for the improvements. [Answer] # MATL, 7 bytes ``` Xz!t7XQ ``` [**MATL Online Demo**](https://matl.io/?code=Xz%21t7XQ&inputs=%27Ah%2C+abracadabra%21%27&version=19.0.0) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¸¬ü ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=uKz8&input=IkEgbWFuLCBhIHBsYW4sIGEgY2FuYWw6IFBhbmFtYSEi) ``` ¸¬ü :Implicit input of string ¸ :Split on spaces ¬ :Join ü :Group & sort :Implicit output joined with newlines ``` [Answer] # [Arturo](https://arturo-lang.io), 26 bytes ``` $=>[sort&--` `|chunk=>[&]] ``` [Try it!](http://arturo-lang.io/playground?KjLKeY) Takes input as a list of characters. ``` $=>[ ; a function where input is assigned to & sort ; sort &--` ` ; input with spaces removed | ; then chunk=>[&] ; split into groups of equal contiguous characters ] ; end function ``` [Answer] # [Zsh](https://www.zsh.org/), 35 bytes [Try it online!](https://tio.run/##qyrO@P8/Lb9IoUJBQ6Vao7TYykrTUF9foVbTxsZGpRrIjI5TqYit/f//v2OGjkJiUlFicmIKiFIEAA) ``` for x (${(us::)1// })<<<${1//[^$x]} ``` Input via argument `$1`. Expression `${(us::)1// }` splits `$1` to array of unique chars, and removes spaces. Iterate over the unique array. For each `x`, print `$1`, removing non-`x` chars. ~~[45 bytes](https://tio.run/##qyrO@P/f0VZDpVqj2MpK07BW0zotv0ihQgEkUqrpWKtpY2MDZPpmAWUdlVUqav8D1WfoKCQmFSUmJ6aAKEUA "Zsh – Try It Online")~~: `A=(${(s::)1});for x (${(u)A})<<<${(Mj::)A#$x}` [Answer] # Ruby, 46 bytes [Try it online!](https://repl.it/Cr3J) ``` ->s{(s.chars-[' ']).uniq.map{|c|c*s.count(c)}} ``` My original full program version, 48 bytes after adding the `n` flag: ``` p gsub(/\s/){}.chars.uniq.map{|c|c*$_.count(c)} ``` [Answer] # Python, 107 Could be shortened by lambda, but later ``` x=sorted(input()) i=0 while i<len(x):x[i:]=[' '*(x[i]!=x[i-1])]+x[i:];i-=~(x[i]!=x[i-1]) print("".join(x)) ``` [Answer] ## CJam, 10 bytes ``` {S-$e`::*} ``` An unnamed block that expects the string on top of the stack and replaces it with a list of strings. [Try it online!](http://cjam.tryitonline.net/#code=IlwiU2hvdyBtZSBob3cgeW91IGRvIHRoYXQgdHJpY2ssIHRoZSBvbmUgdGhhdCBtYWtlcyBtZSBzY3JlYW1cIiBzaGUgc2FpZCIKCntTLSRlYDo6Kn0KCn5w&input=) ### Explanation ``` S- Remove spaces. $ Sort. e` Run-length encode, gives pairs [R C], where R is the run-length and C is the character. ::* Repeat the C in each pair R times. ``` [Answer] # Common Lisp, 123 ``` (lambda(s &aux(w(string-trim" "(sort s'char<))))(princ(elt w 0))(reduce(lambda(x y)(unless(char= x y)(terpri))(princ y))w)) ``` Ungolfed: ``` (lambda (s &aux (w (string-trim " " (sort s 'char<)))) (princ (elt w 0)) (reduce (lambda (x y) (unless (char= x y) (terpri)) (princ y)) w)) ``` Not the most golf friendly language. This could probably be modified to return list of lists instead of printing string. [Answer] # Emacs, 36 keystrokes `C-SPACE` `C-E``M-x``sort-r``TAB``RETURN``.``RETURN``.``RETURN``C-A``C-M-S-%``\(\(.\)\2*\)``RETURN``\1``C-Q``C-J``RETURN``!` ### Result `A man, a plan, a canal: Panama!` --> ``` ! ,, : A P aaaaaaaaa c ll mm nnnn p ``` ### Explanation 1. `C-SPACE` `C-E` 2. `M-x` `sort-r``TAB` `RETURN` `.``RETURN` `.``RETURN` 3. `C-A` 4. `C-M-S-%` `\(\(.\)\2*\)``RETURN``\1` `C-Q` `C-J``RETURN` `!` 1. Select the input line; 2. Call `sort-regexp-fields` with arguments `.` and `.`; * Argument #1: *Regexp scpecifying records to sort* * Argument #2: *Regexp scpecifying key within records* 3. Return at line start; 4. Apply regexp substitution `\(\(.\)\2*\)` -> `\1\n` on all matches. [Answer] ## Pyke, ~~16~~ 9 bytes ``` d-}F/i*d+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=d-%7DF%2Fi%2ad%2B&input=Ah%2C+abracadabra%21%21&warnings=0) [Answer] # PHP, 67 bytes Space as separator PHP5 using deprecated `ereg_replace` function. ``` for(;++$i<128;)echo ereg_replace("[^".chr($i)."]","",$argv[1])." "; ``` PHP7, 73 bytes ``` for(;++$i<128;)echo str_repeat($j=chr($i),substr_count($argv[1],$j))." "; ``` Using built in is worse :( ``` foreach(array_count_values(str_split($argv[1]))as$a=>$b)echo str_repeat($a,$b)." "; ``` [Answer] # Perl, 31 bytes Includes +1 for `-p` Run with input on STDIN: ``` explode.pl <<< "ab.ceaba.d" ``` `explode.pl`: ``` #!/usr/bin/perl -p s%.%$&x s/\Q$&//g.$/%eg;y/ //s ``` If you don't care about spurious newlines inbetween the lines the following 24 bytes version works too: ``` #!/usr/bin/perl -p s%.%$&x s/\Q$&//g.$/%eg ``` [Answer] # Oracle SQL 11.2, 123 bytes ``` SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))GROUP BY c; ``` Un-golfed ``` SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) FROM (SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)) GROUP BY c ``` [Answer] # [S.I.L.O.S](https://esolangs.org/wiki/S.I.L.O.S) 265 The (non competing) code better input format is at the bottom, feel free to [try it online!](http://silos.tryitonline.net/#code=CmRlZiA6IGxibApsb2FkTGluZSA6CmEgPSAyNTYKOmEKOnMKeCA9IGdldCBhCnogPSB4CnogLSAzMgp6IHwKaWYgeiB1CmEgKyAxCkdPVE8gcwo6dQppZiB4IGMKR09UTyBlCjpjCmIgPSB4CmIgKyA1MTIKYyA9IGdldCBiCmMgKyAxCnNldCBiIGMKYSArIDEKaWYgeCBhCjplCmEgPSA1MTIKYiA9IDc2OApsID0gMTAKOloKaiA9IGEKaiAtIGIKaWYgaiB6CnogPSBnZXQgYQpjID0gYQpjIC0gNTEyCjozCmlmIHogQwpwcmludENoYXIgbAphICsgMQpHT1RPIFoKOkMKcHJpbnRDaGFyIGMKeiAtIDEKR09UTyAzCjp6&input=&args=VGhpcyBpcyB0ZXN0IGlucHV0IHdpdGhvdXQgYW55IG5ld2xpbmVzLiBBQUFBQUEgQkJCQkIgVGhlIHF1aWNrIEJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgMTIzNDU2Nzg5MCE) ``` def : lbl loadLine : a = 256 :a :s x = get a z = x z - 32 z | if z u a + 1 GOTO s :u if x c GOTO e :c b = x b + 512 c = get b c + 1 set b c a + 1 if x a :e a = 512 b = 768 l = 10 :Z j = a j - b if j z z = get a c = a c - 512 :3 if z C printChar l a + 1 GOTO Z :C printChar c z - 1 GOTO 3 :z ``` Input for the above is a series of command line arguments representing ascii values, terminated with a zero.[Try it online!](http://silos.tryitonline.net/#code=CmRlZiA6IGxibAo6YQo6cwpyZWFkSU8gOgp4ID0gaQp6ID0geAp6IC0gMzIKeiB8CmlmIHogdQpHT1RPIHMKOnUKaWYgeCBjCkdPVE8gZQo6YwpiID0geApiICsgNTEyCmMgPSBnZXQgYgpjICsgMQpzZXQgYiBjCmlmIHggYQo6ZQphID0gNTEyCmIgPSA3NjgKbCA9IDEwCjpaCmogPSBhCmogLSBiCmlmIGogegp6ID0gZ2V0IGEKYyA9IGEKYyAtIDUxMgo6MwppZiB6IEMKcHJpbnRDaGFyIGwKYSArIDEKR09UTyBaCjpDCnByaW50Q2hhciBjCnogLSAxCkdPVE8gMwo6eg&input=NjQ&args=NjU+MTIz+NjU+NjU+NjU+NjY+NjY+MA). --- For a more reasonable method of input we must up the byte count (and use features that were nonexistent before the writing of this challenge). For 291 bytes we get the following code. ``` \ def : lbl loadLine : a = 256 :a :s x = get a z = x z - 32 z | if z u a + 1 GOTO s :u if x c GOTO e :c b = x b + 512 c = get b c + 1 set b c a + 1 if x a :e a = 512 b = 768 l = 10 :Z j = a j - b if j z z = get a c = a c - 512 :3 if z C printChar l a + 1 GOTO Z :C printChar c z - 1 GOTO 3 :z ``` Feel free to [test this version online!](http://silos.tryitonline.net/#code=CmRlZiA6IGxibApsb2FkTGluZSA6CmEgPSAyNTYKOmEKOnMKeCA9IGdldCBhCnogPSB4CnogLSAzMgp6IHwKaWYgeiB1CmEgKyAxCkdPVE8gcwo6dQppZiB4IGMKR09UTyBlCjpjCmIgPSB4CmIgKyA1MTIKYyA9IGdldCBiCmMgKyAxCnNldCBiIGMKYSArIDEKaWYgeCBhCjplCmEgPSA1MTIKYiA9IDc2OApsID0gMTAKOloKaiA9IGEKaiAtIGIKaWYgaiB6CnogPSBnZXQgYQpjID0gYQpjIC0gNTEyCjozCmlmIHogQwpwcmludENoYXIgbAphICsgMQpHT1RPIFoKOkMKcHJpbnRDaGFyIGMKeiAtIDEKR09UTyAzCjp6&input=&args=VGhpcyBpcyB0ZXN0IGlucHV0IHdpdGhvdXQgYW55IG5ld2xpbmVzLiBBQUFBQUEgQkJCQkIgVGhlIHF1aWNrIEJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgMTIzNDU2Nzg5MCE). The backslash is unnecessary but is there to show the important leading line feed. [Answer] ## ARM machine code on Linux, 60 bytes Hex Dump: ``` b590 4c0d f810 2b01 b11a 58a3 3301 50a3 e7f8 6222 2704 2001 f1ad 0101 2201 237f 5ce5 b135 700b df00 3d01 d8fc 250a 700d df00 3b01 d8f4 bd90 000200bc ``` This function basically creates an array of size 128, and whenever it reads a character from the input string it increment's the value at that characters position. Then it goes back through the array and prints each character array[character] times. Ungolfed Assembly (GNU syntax): ``` .syntax unified .bss @bss is zero-initialized data (doesn't impact code size) countArray: .skip 128 @countArray[x] is the number of occurances of x .text .global expStr .thumb_func expstr: @Input: r0 - a NUL-terminated string. @Output: Groups of characters to STDOUT push {r4,r7,lr} ldr r4,=countArray @Load countArray into r4 readLoop: ldrb r2,[r0],#1 @r2=*r0++ cbz r2,endReadLoop @If r2==NUL, break ldr r3,[r4,r2] @r3=r4[r2] adds r3,r3,#1 @r3+=1 str r3,[r4,r2] @r4[r2]=r3 b readLoop @while (true) endReadLoop: @Now countArray[x] is the number of occurances of x. @Also, r2 is zero str r2,[r4,#' ] @'<character> means the value of <character> @What that just did was set the number of spaces found to zero. movs r7,#4 @4 is the system call for write movs r0,#1 @1 is stdout sub r1,sp,#1 @Allocate 1 byte on the stack @Also r1 is the char* used for write movs r2,#1 @We will print 1 character at a time movs r3,#127 @Loop through all the characters writeLoop: ldrb r5,[r4,r3] @r5=countArray[r3] cbz r5,endCharacterLoop @If we're not printing anything, go past the loop strb r3,[r1] @We're going to print byte r3, so we store it at *r0 characterLoop: swi #0 @Make system call @Return value of write is number of characters printed in r0 @Since we're printing one character, it should just return 1, which @means r0 didn't change. subs r5,r5,#1 bhi characterLoop @If we're here then we're done printing our group of characters @Thus we just need to print a newline. movs r5,#10 @r5='\n' (reusing r5 since we're done using it as a loop counter strb r5,[r1] swi #0 @Print the character endCharacterLoop: subs r3,r3,#1 bhi writeLoop @while (--r3) pop {r4,r7,pc} .ltorg @Store constants here ``` Testing script (also assembly): ``` .global _start _start: ldr r0,[sp,#8] @Read argv[1] bl expstr @Call function movs r7,#1 @1 is the system call for exit swi #0 @Make system call ``` [Answer] # Scala, 53 bytes ``` def?(s:String)=s.filter(_!=' ').groupBy(identity).map{_._2.mkString} ``` When run with REPL: ``` scala> ?("Ah, abracadabra!") res2: scala.collection.immutable.Iterable[String] = List(!, A, aaaaa, ,, bb, c, h, rr, d) scala> print(res2.mkString("\n")) ! A aaaaa , bb c h rr d ``` EDIT: Forgot to filter spaces [Answer] ## Clojure, 46 ``` #(partition-by identity(sort(re-seq #"\S" %))) ``` Long and descriptive function names for simplest of things, yeah. [Answer] # PowerShell, 65 @TimmyD has the shorter answer but I don't have enough rep to comment. Here's my answer in 65 bytes. I didn't think to use `group` and I didn't know that you could stick `-join` in front of something instead of `-join""` on the end and save two characters (using that would make my method 63). ``` ([char[]]$args[0]-ne32|sort|%{if($l-ne$_){"`n"};$_;$l=$_})-join"" ``` My method sorts the array, then loops through it and concatenates characters if they match the preceding entry, inserting a newline if they do not. [Answer] # Clojure (55 bytes) ``` (defn f[s](map(fn[[a b]](repeat b a))(frequencies s))) ``` Test Cases: ``` (f "Ah, abracadabra!") ;;=> ((\space) (\!) (\A) (\a \a \a \a \a) (\b \b) (\c) (\d) (\h) (\,) (\r \r)) (f "\\o/\\o/\\o/") ;;=> ((\\ \\ \\) (\o \o \o) (\/ \/ \/)) (f "A man, a plan, a canal: Panama!") ;;=> ((\space \space \space \space \space \space) (\!) (\A) (\a \a \a \a \a \a \a \a \a) (\c) (\, \,) (\l \l) (\m \m) (\n \n \n \n) (\P) (\p) (\:)) (f "\"Show me how you do that trick, the one that makes me scream\" she said") ;;=> ((\space \space \space \space \space \space \space \space \space \space \space \space \space \space) (\a \a \a \a \a) (\" \") (\c \c) (\d \d) (\e \e \e \e \e \e \e) (\h \h \h \h \h \h) (\i \i) (\k \k) (\,) (\m \m \m \m) (\n) (\o \o \o \o \o) (\r \r) (\S) (\s \s \s \s) (\t \t \t \t \t \t) (\u) (\w \w) (\y)) ``` [Answer] # Java 8, ~~121~~ ~~120~~ ~~110~~ 103 Bytes ``` s->s.chars().distinct().filter(c->c!=32) .forEach(c->out.println(s.replaceAll("[^\\Q"+(char)c+"\\E]",""))) ``` Above lambda can be consumed with Java-8 `Consumer`. It fetches distinct characters and replaces other characters of the String to disassemble each character occurrence. [Answer] # [Elixir](http://elixir-lang.org), 70 bytes ``` def f(s), do: '#{s}'|>Enum.group_by(&(&1))|>Map.delete(32)|>Map.values ``` [Answer] ## R, 67 bytes Even though there's already an R-answer by @Frédéric I thought my solution deserves it's own answer because it's conceptually different. ``` for(i in unique(x<-strsplit(readline(),"")[[1]]))cat(x[x%in%i]," ") ``` The program prints the ascii characters in order of appearence in the string where groups are separated by two white spaces and chars within groups by one white space. A special case is if the string has whitespaces in itself, then at one specific place in the output there will be `4+number of white spaces in string` white spaces separating two groups E.g: `Ah, abracadabra!` => `A h , a a a a a b b r r c d !` ### Ungolfed Split up the code for clarity even though assignment is done within the unique functions and changed to order of evaluation: ``` x<-strsplit(readline(),"")[[1]]) # Read string from command line and convert into vector for(i in unique(x){ # For each unique character of the string, create vector cat(x[x%in%i]," ") # of TRUE/FALSE and return the elements in x for which } # these are matched ``` [Answer] **C, 178** ``` #define F for #define i8 char #define R return z(i8*r,i8*e,i8*a){i8*b,c;F(;*a;++a)if(!isspace(c=*a)){F(b=a;*b;++b)if(r>=e)R-1;else if(*b==c)*b=' ',*r++=c;*r++='\n';}*r=0;R 0;} ``` z(outputArray,LastPointerOkinOutputarray,inputArray) return -1 on error 0 ok Note:Modify its input array too... ``` #define P printf main(){char a[]="A, 12aa99dd333aA,,<<", b[256]; z(b,b+255,a);P("r=%s\n", b);} /* 178 r=AA ,,, 1 2 aaa 99 dd 333 << */ ``` [Answer] ## Racket 243 bytes ``` (let*((l(sort(string->list s)char<?))(g(λ(k i)(list-ref k i))))(let loop((i 1)(ol(list(g l 0))))(cond((= i(length l)) (reverse ol))((equal?(g l(- i 1))(g l i))(loop(+ 1 i)(cons(g l i)ol)))(else(loop(+ 1 i)(cons(g l i)(cons #\newline ol))))))) ``` Ungolfed: ``` (define (f s) (let*((l (sort (string->list s) char<?)) (g (λ (k i)(list-ref k i))) ) (let loop ((i 1) (ol (list (g l 0)))) (cond ((= i (length l)) (reverse ol)) ((equal? (g l (- i 1)) (g l i)) (loop (+ 1 i) (cons (g l i) ol))) (else (loop (+ 1 i) (cons (g l i) (cons #\newline ol)))) )))) ``` Testing: ``` (display (f "Ah, abracadabra!")) ``` Output: ``` ( ! , A a a a a a b b c d h r r) ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 1.5 bytes (3 nibbles) ``` =~| ``` ``` =~| # full program =~|$$$ # with implicit args added; | # filter $ # the input $ # by itself (=remove spaces), =~ # now group the remaining characters by $ # themselves ``` [![enter image description here](https://i.stack.imgur.com/wTtS1.png)](https://i.stack.imgur.com/wTtS1.png) [Answer] # [Factor](https://factorcode.org), 37 bytes ``` [ " " without [ ] collect-by values ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JcwxCsJAEIXhPqd4BuxML7GyEhFEEKuQYhw2JDjZjdlZxbPYpNELeJrcxoVliq-Yn_f-NsTqxmk-XM77464Eee_Ywxv16Fz0Hoxl43EzozWCTZblW_RkVyAMkmSyJCVOkZ4W-SdoU6znZYU83rPT1gVFhRrsRAxrcX3hQRLibJ3iH5NITIaxsxpDQ9ymzzQl_w) * `" " without` remove spaces * `[ ] collect-by` group letters by letter * `values` discard the keys [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ðK{γ ``` Outputs as a list. [Try it online](https://tio.run/##yy9OTMpM/f//8Abv6nOb//93zNBRSEwqSkxOTAFRigA) or [verify all test cases](https://tio.run/##NYsxCgIxEEWv8p06YG@zbG0jWBqL2SSQsJuNJKsS7D2AJxE8gr2H8CIxy2IxvPl/3oTEnTPlkhvC9/4ANbm8n9vb51VEOVBrBbiLrFjPWJEgKcP6PzW28DxWCadhoeKRhw12FX55oL0NV3iDGTmcoQMmyxOm6FQv6m4QRrN0nnuTZjmpaNhLQqrnxE7T8Qc). `ðK` could alternatively be `ðм` or `#J` for the same byte-count. **Explanation:** ``` ðK # Remove all spaces from the (implicit) input-string { # Sort the remaining characters γ # Group adjacent equal characters together in substrings # (after which the resulting list is output implicitly) ðм # (Vectorized) remove all spaces from the (implicit) input-string # # Split the (implicit) input-string by spaces (no-op if the input doesn't contain # any spaces) J # Join this list back together to a string (or no-op, by joining the stack # consisting of just the single string if the input didn't contained any spaces) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) +coreutils, 55 bytes ``` for x in `fold -1|tee a|sort|uniq`;{ grep $x a|rs -g0;} ``` [Try it online!](https://tio.run/##S0oszvj/Py2/SKFCITNPISEtPydFQdewpiQ1VSGxpji/qKSmNC@zMMG6WiG9KLVAQaUCKFxUrKCbbmBd@/@/Y4aOQmJSUWJyYgqIUvwPAA "Bash – Try It Online") ]
[Question] [ Tired of always wondering how many more Pokémon you need to catch to get those high-tier evolutions? Wonder no more! Now you will write a complete program or function to calculate it for you! ## The Challenge: As input, your program will receive a list of the costs in candy to evolve a Pokémon to the next tier. (This list may be separated by any delimiter of your choosing, or as function arguments). Your program will then return or print the number of Pokémon that must be caught, including the one that will be evolved, to evolve through all the tiers given. How do you calculate this? Like so: 1. Add up all the candy costs: `12 + 50 = 62` 2. Subtract 3 candies from the total, this being from the one Pokémon you keep for evolving: `62 - 3 = 59` 3. Divide this number by 4 (3 for catching, 1 for giving it to the Professor), always taking the `ceil()` of the result: `ceil(59/4) = 15` 4. Finally, add 1 to this total to get the total number of Pokémon you must catch, 16! Example `Input -> Output`: ``` [4] -> 2 [50] -> 13 [12, 50] -> 16 [25, 100] -> 32 [19, 35, 5, 200] -> 65 ``` ## Winning: The app has already taken up most of the space on your phone, so your program needs to be as short as possible. The complete program or function with the smallest byte count will be accepted in two weeks! (with any ties being settled by the earliest submitted entry!) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` O4÷> ``` **Explanation** ``` O # sum 4÷ # integer division by 4 > # increment ``` [Try it online](http://05ab1e.tryitonline.net/#code=TzTDtz4&input=WzE5LCAzNSwgNSwgMjAwXQ) [Answer] # Jelly, ~~5~~ 4 bytes ``` S:4‘ ``` [Try it online!](http://jelly.tryitonline.net/#code=Uzo04oCY&input=&args=WzE5LCAzNSwgNSwgMjAwXQ) `S`um, integer divide `:` by `4` and increment `‘`. [Answer] # C# REPL, 15 bytes ``` n=>n.Sum()/4+1; ``` Casts to `Func<IEnumerable<int>, int>`. [Answer] ## Actually, 4 bytes ``` Σ¼≈u ``` [Try it online!](http://actually.tryitonline.net/#code=zqPCvOKJiHU&input=WzE5LCAzNSwgNSwgMjAwXQ) Explanation: ``` Σ¼≈u Σ sum ¼ divide by 4 ≈ floor u add 1 ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes ``` +:4/+ ``` [Try it online!](http://brachylog.tryitonline.net/#code=Kzo0Lys&input=WzE5OjM1OjU6MjAwXQ&args=Wg) ### Explanation A very original answer… ``` + Sum :4/ Integer division by 4 + Increment ``` [Answer] # BASH (sed + bc) 19 ``` sed 's~)~+4)/4~'|bc ``` Input is a `+` separate list on stdin E.g.: `echo '(19+35+5+200)'| sed 's~)~+4)/4~'|bc` [Answer] # Haskell, 17 bytes ``` (+1).(`div`4).sum ``` [Answer] ## Pyke, 4 bytes ``` seeh ``` [Try it here!](http://pyke.catbus.co.uk/?code=seeh&input=%5B19%2C+35%2C+5%2C+200%5D&warnings=0) ``` ((sum(input)/2)/2)+1 ``` [Answer] # Pyth, 5 bytes ``` h/sQ4 ``` [Try it here!](http://pyth.herokuapp.com/?code=h%2FsQ4&input=%5B19%2C35%2C5%2C200%5D&debug=0) Sum input with `sQ`, divide by 4 with `/4` and finally increment `h`. [Answer] # CJam, 7 bytes ``` {:+4/)} ``` [Try it here!](http://cjam.tryitonline.net/#code=WzE5IDM1IDUgMjAwXQp7Ois0Lyl9Cgp-cA&input=) Defines an unnamed block that expects the input on the stack and leaves the result there. `:+` sums the list, `4/` divides the result by 4 and `)` increments that. [Answer] ## [Retina](https://github.com/m-ender/retina/), ~~18~~ 17 bytes Byte count assumes ISO 8859-1 encoding. ``` $ ¶4 .+|¶ $* 1111 ``` Input is linefeed-separated. [Try it online!](http://retina.tryitonline.net/#code=JArCtjQKLit8wrYKJCoKMTExMQ&input=MTkKMzUKNQoyMDA) [Answer] # R, 22 bytes ``` floor(sum(scan())/4+1) ``` [Answer] # **JavaScript, 29 Bytes** ``` x=>x.reduce((a,b)=>a+b)/4+1|0 ``` [Answer] # S.I.L.O.S ~~100 99~~ 103 characters + 22 for sample input Code with testing harness. ``` set 512 52 set 513 10 GOSUB e GOTO f funce a = 0 i = 511 lblE i + 1 b = get i a + b if b E a / 4 a + 1 return lblf printInt a ``` input as a series of set commands to modify the spots of the heap starting at spot 512. [Try it Online!](http://silos.tryitonline.net/#code=c2V0IDUxMiA1MgpzZXQgNTEzIDEwCkdPU1VCIGUKR09UTyBmCmZ1bmNlCmEgPSAwCmkgPSA1MTEKbGJsRQppICsgMQpiID0gZ2V0IGkKYSArIGIKaWYgYiBFCmEgLyA0CmEgKyAxCnJldHVybgpsYmxmCnByaW50SW50IGE&input=) ]
[Question] [ Consider the standard equilateral triangle, with nodes labeled using [barycentric coordinates](https://en.wikipedia.org/wiki/Barycentric_coordinate_system): ![](https://i.stack.imgur.com/URM7b.png) We can turn this 3 node triangle into a 6 node triangle by adding a new line of 3 vertices (one more than was present on a side of the original 3 node triangle), remove any internal edges (but **not** internal nodes) and re-normalize the coordinates: [![enter image description here](https://i.stack.imgur.com/cbF99.png)](https://i.stack.imgur.com/cbF99.png) Repeating the process to go from a 6 node triangle to a 10 node triangle, add a line of 4 vertices (again, one more than was present on a side of the original 6 node triangle), remove any internal edges (but **not** internal nodes) and re-normalize the coordinates: [![enter image description here](https://i.stack.imgur.com/Ff1Zt.png)](https://i.stack.imgur.com/Ff1Zt.png) This process can be repeated indefinitely. The goal of this challenge is given an integer `N` representing how many times this process has been performed, output all the nodes for the associated triangle in barycentric coordinates. # Input Your program/function should take as input a single non-negative integer `N` representing how many times this process has been applied. Note that for `N=0`, you should output the original triangle with 3 nodes. The input may come from any source (function parameter, stdio, etc.). # Output Your program/function should output all the nodes in normalized barycentric coordinates. The order of the nodes does not matter. A number can be specified as a fraction (fraction reduction not required) or a floating point number. You may also output "scaled" vectors to specify a node. For example, all 3 of the following outputs are equivalent and allowed: ``` 0.5,0.5,0 1/2,2/4,0 [1,1,0]/2 ``` If using floating point output, your output should be accurate to within 1%. The output may be to any sink desired (stdio, return value, return parameter, etc.). Note that even though the barycentric coordinates are uniquely determined by only 2 numbers per node, you should output all 3 numbers per node. # Examples Example cases are formatted as: ``` N x0,y0,z0 x1,y1,z1 x2,y2,z2 ... ``` where the first line is the input `N`, and all following lines form a node `x,y,z` which should be in the output exactly once. All numbers are given as approximate floating point numbers. ``` 0 1,0,0 0,1,0 0,0,1 1 1,0,0 0,1,0 0,0,1 0.5,0,0.5 0.5,0.5,0 0,0.5,0.5 2 1,0,0 0,1,0 0,0,1 0.667,0,0.333 0.667,0.333,0 0.333,0,0.667 0.333,0.333,0.333 0.333,0.667,0 0,0.333,0.667 0,0.667,0.333 3 1,0,0 0.75,0,0.25 0.75,0.25,0 0.5,0,0.5 0.5,0.25,0.25 0.5,0.5,0 0.25,0,0.75 0.25,0.25,0.5 0.25,0.5,0.25 0.25,0.75,0 0,0,1 0,0.25,0.75 0,0.5,0.5 0,0.75,0.25 0,1,0 ``` # Scoring This is code golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired. [Answer] ## CJam (22 bytes) ``` {):X),3m*{:+X=},Xdff/} ``` This is an anonymous block (function) which takes `N` on the stack and leaves an array of arrays of doubles on the stack. [Online demo](http://cjam.aditsu.net/#code=2%0A%0A%7B)%3AX)%2C3m*%7B%3A%2BX%3D%7D%2CXdff%2F%7D%0A%0A~%60) ### Dissection ``` { e# Define a block ):X e# Let X=N+1 be the number of segments per edge ),3m* e# Generate all triplets of integers in [0, X] (inclusive) {:+X=}, e# Filter to those triplets which sum to X Xdff/ e# Normalise } ``` [Answer] # Haskell, 53 bytes ``` f n|m<-n+1=[map(/m)[x,y,m-x-y]|x<-[0..m],y<-[0..m-x]] ``` [Answer] # Python 3, 87 bytes This is actually supposed to be a comment to [the solution by TheBikingViking](https://codegolf.stackexchange.com/a/90801/58861) but I don't have enough reputation for comments. One can save a few bytes by only iterating over the variables `i,j` and using the fact that with the third one they add up to `n+1`. ``` def f(n):d=n+1;r=range(n+2);print([[i/d,j/d,(d-i-j)/d]for i in r for j in r if d>=i+j]) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), 10 bytes ``` ÌL<¤/3ãDOÏ ``` **Explanation** ``` ÌL< # range(1,n+2)-1 ¤/ # divide all by last element (n+1) 3ã # cartesian product repeat (generate all possible triples) DO # make a copy and sum the triples Ï # keep triples with sum 1 ``` [Try it online](http://05ab1e.tryitonline.net/#code=w4xMPMKkLzPDo0RPw48&input=Mw) [Answer] ## Mathematica, ~~44~~ 43 bytes ``` Select[Range[0,x=#+1]~Tuples~3/x,Tr@#==1&]& ``` This is an unnamed function taking a single integer argument. Output is a list of lists of exact (reduced) fractions. Generates all 3-tuples of multiples of `1/(N+1)` between 0 and 1, inclusive, and then selects those whose sum is 1 (as required by barycentric coordinates). [Answer] # [MATL](http://github.com/lmendo/MATL), 17 bytes ``` 2+:qGQ/3Z^t!s1=Y) ``` [Try it online!](http://matl.tryitonline.net/#code=Mis6cUdRLzNaXnQhczE9WSk&input=Mw) ### Explanation The approach is the same as in other answers: 1. Generate the array `[0, 1/(n+1), 2/(n+1), ..., 1]`, where `n` is the input; 2. Generate all 3-tuples with those values; 3. Keep only those whose sum is `1`. More specifically: ``` 2+ % Take input and add 2: produces n+2 :q % Range [0 1 ... n+1] GQ/ % Divide by n+1 element-wise: gives [0, 1/(n+1), 2/(n+1)..., 1] 3Z^ % Cartesian power with exponent 3. Gives (n+1)^3 × 3 array. Each row is a 3-tuple t % Duplicate !s % Sum of each row 1= % Logical index of entries that equal 1 Y) % Use that index to select rows of the 2D array of 3-tuples ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish/blob/master/doc.md), ~~37~~ 33 bytes *Thanks to Zgarb for saving 4 bytes.* ``` p *% # S ` =E S `/ 1+r#>>i 3 ``` [Try it online!](http://jellyfish.tryitonline.net/#code=cAoqJQojIFMKYAo9RSAgIFMKYC8KMStyIz4-aQogICAz&input=Mg) Like my Mathematica and Peter's CJam answers, this generates a set of candidate tuples and then selects only those that sum to 1. I'm not entirely happy with the layout yet, and I wonder whether I can save some bytes with hooks or forks, but I'll have to look into that later. [Answer] # Perl 6: ~~50~~ 40 bytes ``` {grep *.sum==1,[X] (0,1/($_+1)...1)xx 3} ``` Returns a sequence of 3-element lists of (exact) rational numbers. Explanation: * `$_` Implicitly declared parameter of the lambda. * `0, 1/($_ + 1) ... 1` Uses the sequence operator `...` to construct the arithmetic sequence that corresponds to the possible coordinate values. * `[X] EXPR xx 3` Takes the Cartesian product of three copies of EXPR, i.e. generates all possible 3-tuples. * `grep *.sum == 1, EXPR` Filter tuples with a sum of 1. [Answer] # Ruby, 62 I'd be surprised if this can't be improved on: ``` ->x{0.step(1,i=1.0/(x+1)){|a|0.step(1-a,i){|b|p [a,b,1-a-b]}}} ``` Taking the advice latent in the puzzle, this calculates the second node options based on the first, and the third node by subtracting the first two. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 24 bytes ``` +:1f yg:2j:eaL+?/g:Lz:*a ``` [Try it online!](http://brachylog.tryitonline.net/#code=KzoxZgp5ZzoyajplYUwrPy9nOkx6Oiph&input=MQ&args=Wg&debug=on) [Answer] # Python 3, 106 bytes ``` def f(n):r=range(n+2);print([x for x in[[i/-~n,j/-~n,k/-~n]for i in r for j in r for k in r]if sum(x)==1]) ``` A function they takes input via argument and prints a list of lists of floats to STDOUT. Python is not good at Cartesian products... **How it works** ``` def f(n): Function with input iteration number n r=range(n+2) Define r as the range [0, n+1] for i in r for j in r for k in r Length 3 Cartesian product of r [i/-~n,j/-~n,k/-~n] Divide each element of each list in the product by n+1 [x for x in ... if sum(x)==1] Filter by summation to 1 print(...) Print to STDOUT ``` [Try it on Ideone](http://ideone.com/yuki0R) [Answer] # [Actually](https://github.com/Mego/Seriously), 15 bytes This uses an algorithm similar to the one in [TheBikingViking's Python answer](https://codegolf.stackexchange.com/a/90801/47581). Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=dTt1cuKZgC8zQOKImWDOozE9YOKWkQ&input=Mw) ``` u;ur♀/3@∙`Σ1=`░ ``` **Ungolfed:** ``` u; Increment implicit input and duplicate. ur Range [0..n+1] ♀/ Divide everything in range by (input+1). 3@∙ Take the Cartesian product of 3 copies of [range divided by input+1] `Σ1=` Create function that takes a list checks if sum(list) == 1. ░ Push values of the Cartesian product where f returns a truthy value. ``` [Answer] # Ruby, ~~77~~ 74 bytes Another answer using the algorithm in [TheBikingViking's Python answer](https://codegolf.stackexchange.com/a/90801/47581). Golfing suggestions welcome. ``` ->n{a=[*0.step(1,i=1.0/(n+1))];a.product(a,a).reject{|j|j.reduce(&:+)!=1}} ``` Another 74-byte algorithm based on [Not that Charles's Ruby answer](https://codegolf.stackexchange.com/a/90828/47581). ``` ->x{y=x+1;z=1.0/y;[*0..y].map{|a|[*0..y-a].map{|b|p [a*z,b*z,(y-a-b)*z]}}} ``` [Answer] ## JavaScript (Firefox 30-57), ~~88~~ 81 bytes ``` n=>[for(x of a=[...Array(++n+1).keys()])for(y of a)if(x+y<=n)[x/n,y/n,(n-x-y)/n]] ``` Returns an array of arrays of floating-point numbers. Edit: Saved 7 bytes by computing the third coordinate directly. I tried eliminating the `if` by calculating the range of `y` directly but it cost an extra byte: ``` n=>[for(x of a=[...Array(++n+1).keys()])for(y of a.slice(x))[x/n,(y-x)/n,(n-y)/n]] ``` ]
[Question] [ Here's a nice easy challenge: > > Given a string that represents a number in an unknown base, determine the lowest possible base that number might be in. The string will only contain `0-9, a-z`. If you like, you may choose to take uppercase letters instead of lowercase, but please specify this. You must output this lowest possible base in decimal. > > > Here is a more concrete example. If the input string was "01234", it is impossible for this number to be in binary, since 2, 3, and 4 are all undefined in binary. Similarly, this number cannot be in base 3, or base 4. Therefore, this number *must* be in base-5, or a higher base, so you should output '5'. Your code must work for any base between base 1 (unary, all '0's) and base 36 ('0-9' and 'a-z'). You may take input and provide output in any reasonable format. Base-conversion builtins are allowed. As usual, standard loopholes apply, and the shortest answer in bytes is the winner! # Test IO: ``` #Input #Output 00000 --> 1 123456 --> 7 ff --> 16 4815162342 --> 9 42 --> 5 codegolf --> 25 0123456789abcdefghijklmnopqrstuvwxyz --> 36 ``` [Answer] # Perl, ~~30~~ 27 bytes Includes +1 for `-p` Run with the input on STDIN, e.g. ``` base.pl <<< codegolf ``` `base.pl`: ``` #!/usr/bin/perl -p \@F[unpack"W*"];$_=@F%39-9 ``` [Answer] ## LiveScript, 32 bytes ``` ->1+parseInt (it/'')sort!pop!,36 ``` A port of [this answer](https://codegolf.stackexchange.com/a/90745) in my favorite language that compile to JavaScript. If `base~number` operator worked with variables I could write `->1+36~(it/'')sort!pop!` (23 bytes), but it conflicts with the function bind operator :/ [Answer] # PowerShell full program, 56 62 bytes lowercase letters required. ``` ([int]((read-host).ToCharArray()|sort|select -l 1)-8)%39 ``` [Answer] # R, 59 57 bytes Thanks to @Andreï-Kostyrka for two bytes. ``` max(which(c(0:9,letters)%in%strsplit(scan(,""),"")[[1]])) ``` `scan(,'')` takes the input and coerces it to a string. Then `strsplit` divides it into its individual characters. `[[1]]` is because that returns a list. `%in%` then checks which of the vector `0,1,2,...,8,9,a,b,c,...,x,y,z` is in the input. which tells us the place in that vector of items in the input -- and `max` finds the biggest place -- which corresponds to the base. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` Hà> ``` [Try it online](https://tio.run/##yy9OTMpM/f/f4/ACu///o5WSlXQUlPJBRAqISAUR6XCxHBCRphQLAA "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##bc5JDoJAEIXhvacgvYYEcEA3sDHGeAXCAhAUJ1ScT@NdPFjrD0kRo5svL13VVVVWcVJk2puMZ4EyLMs3VKCnr6evTR0qW5nGL1EnVA7RhS70oA@DupwT8zrWpSE40uQ0nb8j3PZLE1NiCXPIYCFvm3aNLXP/X/XBk0tGEEMC6ff8XJYsoYAVrGXnFnZyxx4OcIQKTnCGC1zhBnd4qOgN). Explanation: ``` # implicit input H # convert each digit to decimal à # maximum > # add 1 # implicit output ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `G`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` 36b⁺ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPVJkJmNvZGU9MzZiJUUyJTgxJUJBJmZvb3Rlcj0maW5wdXQ9JTIyMDAwMDAlMjIlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwMSUwQSUyMjEyMzQ1NiUyMiUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjA3JTBBJTIyZmYlMjIlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwMTYlMEElMjI0ODE1MTYyMzQyJTIyJTIwJTIwLSUzRSUyMDklMEElMjI0MiUyMiUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjA1JTBBJTIyY29kZWdvbGYlMjIlMjAlMjAlMjAlMjAtJTNFJTIwMjUlMEElMjIwMTIzNDU2Nzg5YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXolMjIlMjAlMjAlMjAlMjAtJTNFJTIwMzYmZmxhZ3M9Q0c=) Takes input in uppercase. #### Explanation ``` 36b⁺ # Implicit input 36b # Convert each character from base-36 ⁺ # Increment each integer # Implicit output of maximum ``` ]
[Question] [ # Enterprise Quality Code! ### TL;DR * Answers will consist of a full program (**of length < 30k**) prints the the first N Prime numbers (as a base 10 representation without leading zeros unless the chosen language only supports unary or other based output) separated by newlines (optional trailing linefeed). * You may post cracks at any time, but you must wait one hour after posting each initial bowled submission * Leading or trailing whitespace is not acceptable (except for the trailing newline) * An answer's score is the number of bytes in the answer. A user's score is the total number of bytes of all uncracked answers. * An answer gets cracked when another user posts an answer (in the same language) which is a permutation of any subset of the characters used in the original answer. * The user with the highest score will receive an accepted tick mark on his /her highest scoring post (although it doesnt really matter which specific post gets the tick) --- [The Inspiration for this challenge](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition) --- At Pretty Good consultants there is a focus on writing "quality" verbose code that is sufficiently engineered. Your boss has decided to test you on your skills. --- Consider the set of all [programming languages](http://meta.codegolf.stackexchange.com/a/2073/46918) in existence before the posting of this challenge. For this challenge there will technically be one individual "winner" in each language, however the boss will give a ~~promotion~~ accepted tick mark to only one answer based on your score. --- # Detailed Spec The goal of this challenge is to [receive](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) an integer N strictly smaller than 2^8-1 and print the first N prime numbers (in less than 24 hours) separated by your platforms choice of new line (a trailing newline is optional). [OEIS sequence A000040](https://oeis.org/A000040) in as **many bytes** as possible in as many languages as possible. However, note that others vying for the promotion will try to "help" you by **golfing** down your score. (Please note that your prime generation function should *theoretically* work for integer N inputs strictly smaller than 2^16-1 given enough time, the bounds for N have been reduced after realizing how slow some interpreters are (namely mine) hardcoding the list of primes is strictly forbidden) Sample output for an input 11 ``` 2 3 5 7 11 13 17 19 23 29 31 ``` --- ## How to participate Pick any language X, but please avoid selecting a language which is just another version or derivative of another answer. If there is no existing answer in language X than you will write a program (which must fit into a single post **I.E it must be less than 30k characters**) that solves this challenge. The length in bytes of the source (in any reasonable preexisting textual encoding) will be **added** to your score. You must avoid using any unnecessary characters for reasons that will soon become apparent. If language X already has been used to answer this question, then you must answer using any permutation of any proper subset of the characters used in the shortest answer (I.E take the shortest X answer and remove some (>=1) characters and optionally rearrange the resulting code). The previous holder of the shortest X answer will lose **all** of the bytes provided by his answer from his score, and the number of bytes of your submission will now be added to your score. The number of bytes golfed off gets "lost" forever. --- ### Rules for Languages You may only crack a submission by posting an answer in the same language (and version), but you are barred from posting an answer in language X if there exists a submission in a sufficiently similar language Y. Please do not abuse this rule posting an answer in a sufficiently similar language will receive disqualification. --- Below is a leader board which removes answers with "cracked" (with any case) in their header. ``` var QUESTION_ID=90593,OVERRIDE_USER=46918;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 a-r});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<>]+>)^(?:(?!cracked)\i.)*[^\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), 15410 bytes ``` 0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘b⁹‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ḤỌ;”€vj⁷ ``` Crack of [@Dennis's entry](https://codegolf.stackexchange.com/a/90668/53748) His was: taking `0`; incrementing to 25383 using `‘`; doubling to 50766 using `Ḥ`; converting to base 256 with `b⁹` to get [198, 78]; then casting to characters with `Ọ` to yield ÆN Mine is: taking `0`; incrementing to 15360 using `‘`; converting to base 256 with `b⁹` to get [60, 0]; incrementing to [99, 39] using `‘`; doubling to [198, 78] using `Ḥ`; then casting to characters with `Ọ` to yield ÆN [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25,394 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ([cracked](https://codegolf.stackexchange.com/a/90693/12012)) ``` 0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ḥb⁹Ọ;”€vj⁷ ``` Let's hope I didn't miss something obvious... [Try it online!](http://jelly.tryitonline.net/) You have to copy-paste the code yourself; the URI cannot hold. [Answer] # [MATL](http://github.com/lmendo/MATL), 5 bytes Note sure I get how this challenge works, but here it goes. ``` :Yq"@ ``` [Try it online!](http://matl.tryitonline.net/#code=OllxIkA&input=MTA) [Answer] # Ruby, 25209 bytes ``` require"_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________".size.*(1331).to_s 35 puts Prime.take gets.to_i ``` [Demo at ideone](https://ideone.com/smXDN0). That's a string consisting of 25153 underscores and nothing else (25153\*1331 base 35 is "mathn"), the site formatting might mess with it a bit. [Answer] # Mathematica, 32 bytes ``` Map[Print,Prime[Range[Input[]]]] ``` I mean, there's not much secretive bowling that can be done in this language. [Answer] # C#, 27573 bytes - [cracked!](https://codegolf.stackexchange.com/a/184936/84206) Cracks [Jonathan Allan's answer](https://codegolf.stackexchange.com/questions/90593/enterprise-quality-code-prime-sieve/91005#91005) by 18 characters, namely: `00ijjfff++==;;;;()`. ``` static void Main(){int n=int.Parse(System.Console.ReadLine()),v=30*" ... 27387 '[' characters ... ".Length,c=0,p=0,f,j;while(c<n){j=f=0;while(++j<v)if(p%j==0)f++;f--;if(--f==0){System.Console.WriteLine(p);c++;}p++;}} ``` Test it on [**ideone**](https://ideone.com/FxnIIZ)! The characters are saved as follows: 1. `j=0;j++;f=0;` is rearranged to `j=f=0;j++`, giving `0;` (2 saved) 2. `j++;while(j<v){if(p%j==0)f++;j++;}` is rearranged to `while(++j<v)if(p%j==0)f++;`, taking both the `j++`s into the `while` statement, making it one statement, which allow me to remove the `{}`. This step gives me `j;j++;` (6 + 2 = 8 saved), leaving the `{}` for later use. 3. The two sequential `if(f==0)` statements are merged with the remaining `{}`, giving a full `if(f==0)` (8 + 8 = 16 saved). 4. `f--;if(f==0)` is changed to `if(--f==0)`, giving the last `f;` (2 + 16 = 18 saved). [Answer] # R, 87 bytes ``` f=function(n){u=t=1;while(t<n+1){u=u+1;if(which(!u%%1:u)[1+1]==u){cat(u,"\n");t=t+1}}} ``` Loops through numbers until it has found n primes. [Answer] # Python 3, 117 bytes ``` def p(i): r=[] d=2 while i: if all(d%e for e in r): r+=[d] i-=1 d+=1 print('\n'.join(str(e)for e in r)) ``` A shorter version of [@JonathonAllan's answer](https://codegolf.stackexchange.com/a/90672/55526). `all` evaluates to `True` for empty generator expressions, so `r` can initially be defined as the empty list and `d` as `2`, rather than `r=[2]` and `d=3` in the original. However, this leads to one too few primes being printed, so `i>1` can be changed to just `i`. [Try it on Ideone](http://ideone.com/mWDqQG) [Answer] # Octave, 65 bytes ``` for k=primes((true+true)^(z=input('')))(1:z),disp(num2str(k)),end ``` Here's an example run. The first `10` is the input, the numbers after that are the output. [![enter image description here](https://i.stack.imgur.com/4VIJb.png)](https://i.stack.imgur.com/4VIJb.png) [Answer] # Java, ~~204 205 204~~ 203 bytes [**cracked!**](https://codegolf.stackexchange.com/a/91222/53748) Crack of one of [Rohan Jhunjhunwala's submission](https://codegolf.stackexchange.com/a/90702/53748)s. ``` class y{public static void main(String[]b){int n=2,l=870119,i,f,j;i=new java.util.Scanner(System.in).nextInt();while(i>0){f=0;for(j=1;j<l;j++){if(n%j==0){f++;}}if(f==2){System.out.println(n);i--;}n++;}}} ``` The spec said it only needs to work up to the 2^16-1 = 65535th prime (821603). We can remove the `string x="z...z"` and the loop to increment this value and set `l` to be a working value greater than or equal to 821603. In removing that we can also remove the initialisation of `i`, so we get ne numeric characters `0791819` to use. The smallest valid, working value for `l` is now 870119. Test it on [**ideone**](http://ideone.com/dCNntx) [Answer] # C#, 27569 bytes ``` static void Main(){int n=int.Parse(System.Console.ReadLine()),c=0,p=0,f,j;while(c<n){j=f=0;while(++j<30*"27387 '[' characters".Length)if(p%j==0)f++;f--;if(--f==0){System.Console.WriteLine(p);c++;}p++;}} ``` Cracks [Scepheo's answer](https://codegolf.stackexchange.com/a/91135/84206). Bytes shaved off: `vv=,` [Try it online!](https://tio.run/##7d2xSsNgFAXgVykFIbFNiDq2mVxbEB0cnEL8YxNqEpqgSOmzx1acnHyA74N7hsN9h1MOSdkdwlTui2GYbY/TMBZjXc4@uvp1ti3qNoqPdTvO2vyc6UNxGEL09DWM4T2979qh24f0MRSvm7oNURwvyzxb9uerls3qc1fvQ1Su2/jY5FWe/RaLRbO@y67nLwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8D/zdBPat3EX11XUXzV5nsXVYrGqkmR1bpKkujTHPzNbz4d6DD87W328Ks/vp/4Sp@k03dx@Aw "C# (.NET Core) – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 3794 bytes I either missed something on my first run through or the specs changed while I was working on this, but it Turns out this is an invalid submission. I will be following up with a working one. (Hopefully) [Try It Online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgpKCkpKCkpKCkoKSkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSl7KHt9PD4pPD59PD4-KXsoe31bKCldPCh7fTw-KTw-Pil9e317e319PD57KHt9PD4pPD59PD4&input=MjU1) ``` ({}<(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()())())()())()())()()()())()())()()()())()())()()()())()()()()()())()())()()()()()())()()()())()())()()()())()()()()()())()()()()()())()())()()()()()())()()()())()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()())()()()())()())()()()())()()()()()()()()()()()()()())()()()())()()()()()())()())()()()()()()()()()())()())()()()()()())()()()()()())()()()())()()()()()())()()()()()())()())()()()()()()()()()())()())()()()())()())()()()()()()()()()()()())()()()()()()()()()()()())()()()())()())()()()())()()()()()())()())()()()()()()()()()())()()()()()())()()()()()())()()()()()())()())()()()()()())()()()())()())()()()()()()()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()()()()()()()()()())()()()()()())()()()()()()()()()())()())()()()())()()()()()())()()()()()()()())()()()()()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()()()()()()()())()()()()()()()()()())()())()()()()()()()()()())()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()())()()()())()()()()()()()()()()()())()()()()()()()())()()()())()()()()()()()())()()()())()()()()()())()()()()()()()()()()()())()())()()()()()()()()()()()()()()()()()())()()()()()())()()()()()()()()()())()()()()()())()()()()()())()())()()()()()())()()()()()()()()()())()()()()()())()()()()()())()())()()()()()())()()()()()())()()()())()())()()()()()()()()()()()())()()()()()()()()()())()())()()()())()()()()()())()()()()()())()())()()()()()()()()()()()())()()()())()()()()()())()()()()()()()())()()()()()()()()()())()()()()()()()())()()()()()()()()()())()()()()()()()())()()()()()())()()()()()())()()()())()()()()()()()())()()()()()())()()()())()()()()()()()())()()()())()()()()()()()()()()()()()())()()()()()()()()()())()()()()()()()()()()()())()())()()()()()()()()()())()())()()()())()())()()()()()()()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()()()()()()()()()()()()()()()())()()()())()()()()()()()())()()()()()()()()()())()()()()()()()())()()()())()()()()()())()()()()()())()()()()()()()()()()()()()())()()()())()()()()()())()()()()()())()()()()()()()())()()()()()())()()()()()()()()()()()())()()()())()()()()()())()())()()()()()()()()()())()())()()()()()())()()()()()()()()()())()())()()()()()()()()()())()())()()()()()())()()()()()()()()()()()()()()()()()())()()()())()())()()()())()()()()()())()()()()()())()()()()()()()())()()()()()())()()()()()())()()()()()()()()()()()()()()()()()()()()()())()())()()()()()()()()()())()()()()()()()())()()()()()()()()()())()()()()()())()()()()()())()()()()()()()())()()()()()()()()()()()())()()()())()()()()()())()()()()()())()())()()()()()())()()()()()()()()()()()())()()()()()()()()()())()()()()()()()()()()()()()()()()()())()())()()()())()()()()()())()())()()()()()())()()()())()())()()()())()()()()()()()()()()()())()())()()()()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())()()()()()())()()()()()())()()()()()()()())()()()()()()()()()()()()()()()()()())()()()()()()()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()())()()()()()()()())()()()())()())()()()()()())()()()()()()()()()()()())()()()()()()()()()())()())()()()())()())()()()())()()()()()())()()()()()()()()()()()())()()()()()()()()()()()())()()()()()()()())()()()()()()()()()()()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()()()()()()()())()()()())()()()()()()()()()()()()()())()()()())()()()()()())()())()()()()){({}<>)<>}<>>){({}[()]<({}<>)<>>)}{}{{}}<>{({}<>)<>}<> ``` Here's a breakdown of the characters for you: * `[]`: 1 * `<>`: 11 * `{}`: 11 * `()`: 1874 Good luck. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` j.fP_ ``` [Try it online!](http://pyth.herokuapp.com/?code=j.fP_&input=255&debug=0) I still don't understand this challenge. How come in this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") it is not that we must have a crack ourselves? Like, I would expect that we are to post a longer version that does the task, and then the robber would golf the code. [Answer] # SQLite, 170 bytes ``` WITH c(i)AS(SELECT 2 UNION SELECT i+1 FROM c LIMIT 1609),p AS(SELECT i FROM c WHERE(SELECT COUNT()FROM c d WHERE i<c.i AND c.i%i=0)=0)SELECT*FROM p LIMIT(SELECT n FROM i) ``` The input N is taken from a table; create it with, e.g., `CREATE TABLE i AS SELECT 42 AS n;`. [SQLFiddle](http://www.sqlfiddle.com/#!5/651e0/2) [Answer] ## Haskell, 238 bytes ``` p n m 2=compare n m==LT p n m d=if compare n m==LT then False else if mod n m==0then p n(m+1)(d+1)else p n(m+1)d d z y x=if z==x then return()else if p y 1 0then do putStrLn(show y) d(z+1)(y+1)x else d z(y+1)x main=do n<-readLn d 0 1n ``` This is a shorter version of [@Laikoni's answer](https://codegolf.stackexchange.com/a/90631/34531). I've just replaced `getLine` and `(read n)` by `readLn` and `n`. [Answer] # Haskell, 246 bytes, [cracked](https://codegolf.stackexchange.com/a/90661/56433) ``` p n m 2=compare n m==LT p n m d=if compare n m==LT then False else if mod n m==0then p n(m+1)(d+1)else p n(m+1)d d z y x=if z==x then return()else if p y 1 0then do putStrLn(show y) d(z+1)(y+1)x else d z(y+1)x main=do n<-getLine d 0 1(read n) ``` [Try it on Ideone.](http://ideone.com/vHSlhc) I tried to provide as few operators as possible to prevent more sophisticated shorter solutions. Hopefully I didn't overlook some unnecessary white space. [Answer] ## Pyke, 19 bytes ``` 821603S#_P)FoQ<I))K ``` [Try it here!](http://pyke.catbus.co.uk/?code=821603S%23_P%29FoQ%3CI%29%29K&input=5) The timeout on the website is too small to run in under 5 seconds so you can decrease the first number to get it to work online [Answer] # [S.I.L.O.S](https://esolangs.org/wiki/S.I.L.O.S), 163 bytes ``` readIO : a = 2 lblM b = i b - y if b c GOTO E lblc d = 2 lblI c = a c - d c - 1 if c d y + 1 printInt a GOTO i lbld z = a z % d d + 1 if z I lbli a + 1 GOTO M lblE ``` Nothing in particular was done to arbitrarily lengthen this code, but it should remain safe. (Emphasis on "should") Feel free to [try this code online!](http://silos.tryitonline.net/#code=cmVhZElPIDoKYSA9IDIKbGJsTQpiID0gaQpiIC0geQppZiBiIGMKR09UTyBFCmxibGMKZCA9IDIKbGJsSQpjID0gYQpjIC0gZApjIC0gMQppZiBjIGQKeSArIDEKcHJpbnRJbnQgYQpHT1RPIGkKbGJsZAp6ID0gYQp6ICUgZApkICsgMQppZiB6IEkKbGJsaQphICsgMQpHT1RPIE0KbGJsRQ&input=MTAyMw) [Answer] # Python 3, ~~119~~ 120 bytes [cracked!](https://codegolf.stackexchange.com/a/90677/53748) ``` def p(i): r=[2] d=3 while i>1: if all(d%e for e in r): r+=[d] i-=1 d+=1 print('\n'.join(str(e)for e in r)) ``` For all those struggling robbers... ``` % * 1 ' * 2 ( * 5 ) * 5 + * 2 - * 1 . * 1 1 * 3 2 * 1 3 * 1 : * 3 = * 5 > * 1 [ * 2 \ * 1 ] * 2 a * 1 d * 5 e * 6 f * 4 h * 1 i * 9 j * 1 l * 3 n * 5 o * 3 p * 2 r * 8 s * 1 t * 2 w * 1 <newline> * 8 <space> * 24 ``` [Answer] # C#, 27591 bytes [**cracked!**](https://codegolf.stackexchange.com/a/91135/53748) ``` static void Main(){int n=int.Parse(System.Console.ReadLine()),v=30*" ...between the quotes is a total of 27387 '[' characters... ".Length,c=0,p=0,f,j;while(c<n){j=0;j++;f=0;while(j<v){if(p%j==0)f++;j++;}f--;f--;if(f==0)System.Console.WriteLine(p);if(f==0)c++;p++;}} ``` 30 \* 27387 = 821610. The 2^16-1th prime (the specified limit) is 821603, this code checks to see if there are exactly 2 factors in the range [1, 821609] until n primes have been written to the console. Test it on [**ideone**](https://ideone.com/Bq6CBq) Character set: ``` ' ' :3 '"' :2 '%' :1 '(' :9 ')' :9 '*' :1 '+' :10 ',' :5 '-' :4 '.' :6 '0' :8 '3' :1 ';' :11 '<' :2 '=' :12 'C' :2 'L' :3 'M' :1 'P' :1 'R' :1 'S' :2 'W' :1 '[' :27387 'a' :4 'c' :4 'd' :2 'e' :12 'f' :10 'g' :1 'h' :3 'i' :13 'j' :6 'l' :4 'm' :2 'n' :10 'o' :5 'p' :4 'r' :2 's' :6 't' :8 'v' :3 'w' :2 'y' :2 '{' :3 '}' :3 ``` [Answer] # Java, 197 bytes Another crack of one of [Jonathan Allan's answers](https://codegolf.stackexchange.com/a/90703/54142) ``` class y{public static void main(String[]b){int n=2,l=870119,i=new java.util.Scanner(System.in).nextInt(),f,j;while(i>0){f=0;for(j=1;j<l;j++)if(n%j==0)f++;if(f==2){System.out.println(n);i--;}n++;}}} ``` Saves 6 characters (namely `{{}}i;`) by removing extraneous curly brackets around the `for` loop and following `if`, and by moving the assignment to `i` into its declaration. Test on [**ideone**](http://ideone.com/d0BRne). [Answer] # Bash, ~~166~~ 133 bytes ``` a=2 while((l<$1));do if((b[a])) then((c=b[a]));else((c=a,l++));echo $a;fi;((d=a+c)) while((b[d]));do((d+=c));done ((b[d]=c,a++));done ``` (no trailing newline) Pass primes count as `$1` [Answer] # Prolog (SWI), 109 bytes ``` p(N):-q(N,2). q(N,X):-N=0;Y is X+1,(A is X-1,\+ (between(2,A,B),0is X mod B),writeln(X),M is N-1;M=N),q(M,Y). ``` [Online interpreter](http://swish.swi-prolog.org/p/OSwiIzrk.pl) [Answer] # Java (Cracked) ``` class y{public static void main(String[]b){int i=0,n=2,f,j,l;String x="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";l=x.length();for(;i<791819;i++){l++;}i=new java.util.Scanner(System.in).nextInt();while(i>0){f=0;for(j=1;j<=l;j++){if(n%j==0){f++;}}if(f==2){System.out.println(n);i--;}n++;}}} ``` Add 58 Z's to get this to run properly [Answer] # [Tcl](http://tcl.tk/), 111 bytes ``` set i 2 while \$i<$n {set p 1 set j 2 while \$j<$i {if $i%$j==0 {set p 0 break} incr j} if $p {puts $i} incr i} ``` [Try it online!](https://tio.run/##TYoxDoAgEAR7XrHF2YM1/sRGCcZDQ4hgLIhvRzSaWM1mdpJZS7QJHkrKZzFaccy8WvTEmjzybQOUuOl@r9PEyDyBuCHXdfJLpRg3OyynYG82uMraBOSwp1jj1/NZygU "Tcl – Try It Online") --- # tcl, 116 ``` set i 2 while \$i<$n {set p 1 set j 2 while \$j<$i {if ![expr $i%$j] {set p 0 break} incr j} if $p {puts $i} incr i} ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMNXdVUFVlcWx3UHM) --- # tcl, 195 before it was golfed: ``` for {set i 2} {$i<$n} {incr i} { set p 1 for {set j 2} {$j<$i} {incr j} { if {[expr $i%$j] == 0} { set p 0 break } } if $p {puts $i} } ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMZ242b1BGTUpfVjg) — You can set the value of `n` on the first line [Answer] # [JavaScript (Node.js)](https://nodejs.org), 116 bytes ``` i=>{r=[] d=2 while(i){if(r.map(e=>d%e).filter(x=>x).length==r.length){r.push(d);i--}d+=1} console.log(r.join('\n'))} ``` [Try it online!](https://tio.run/##LcyxDoIwEADQnf8w3GHaBCYTc/yIOjT0So/UlhRUEsK3Vwe3N73JvM0yZJlXFZPl4qgI9Xum26Oy1FUfL4FBcBcHWT/NDEy9PTFqJ2HlDBv1G@rAcVw9Uf4L96zn1@LB4lWUOuyZ2qMaUlxSYB3S@MumJBHqe6wRj@Kga5qLarF8AQ "JavaScript (Node.js) – Try It Online") ## Charset: ``` "1": 1, "2": 1, "i": 7, "=": 8, ">": 3, "{": 3, "r": 6, "[": 1, "]": 1, "\n":4, "d": 4, "w": 1, "h": 4, "l": 6, "e": 7, " ": 7, ")": 7, "f": 2, ".": 7, "m": 1, "a": 1, "p": 2, "%": 1, "t": 3, "x": 2, "n": 4, "g": 3, "u": 1, "s": 2, ";": 1, "-": 2, "}": 3, "+": 1, "c": 1, "o": 4, "j": 1, "'": 2 ``` [Answer] # APL ([NARS2000](http://www.nars2000.org/download/Download.html)), 72 UCS-2 [chars](http://meta.codegolf.stackexchange.com/a/9429/43319) = 144 bytes ``` {⍵(⍵=⍵)⍴((⍵=⍵)=+/[⍵=⍵](⍵|⍵)=((⍵=⍵)+⍳+/⍵⍴⍵)∘.|(⍵=⍵)+⍳+/⍵⍴⍵)/(⍵=⍵)+⍳+/⍵⍴⍵} ``` [TryAPL online!](http://tryapl.org/?a=%7B%u2375%28%u2375%3D%u2375%29%u2374%28%28%u2375%3D%u2375%29%3D+/%5B%u2375%3D%u2375%5D%28%u2375%7C%u2375%29%3D%28%28%u2375%3D%u2375%29+%u2373+/%u2375%u2374%u2375%29%u2218.%7C%28%u2375%3D%u2375%29+%u2373+/%u2375%u2374%u2375%29/%28%u2375%3D%u2375%29+%u2373+/%u2375%u2374%u2375%7D11&run) ]
[Question] [ The goal here is to simply reverse a string, with one twist: Keep the capitalization in the same places. Example Input 1: `Hello, Midnightas` Example Output 1: `SathginDim ,olleh` Example Input 2: `.Q` Exmaple Output 2: `q.` **Rules**: * Output to STDOUT, input from STDIN * The winner will be picked 13th of July on GMT+3 12:00 (One week) * The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters. * Any punctuation ending up in a position where there was an upper-case letter must be ignored. [Answer] # VIM, 46 bytes It'd be three bytes `g~G` if we didn't need to read from stdin or write to stdout, but oh well... ``` vim -es '+normal! g~G' '+%print|q!' /dev/stdin ``` To test this, run ``` echo "testString" | vim -es '+normal! g~G' '+%print|q!' /dev/stdin ``` This is my first submission on here, not sure if this kind of submission is acceptable. [Answer] ## Javascript (using external library) (224 bytes) ``` (s)=>{t=_.From(s);var cnt=t.Count();var caps=t.Select(x=>{return x.toUpperCase()===x&&x.toLowerCase()!==x}).ToArray(),i=-1;return t.AggregateRight((a,b)=>{i++;var c=caps[i];return c?a+b.toUpperCase():a+b.toLowerCase()},"");} ``` Disclaimer: Using a library I wrote to bring C#'s LINQ to Javascript [![Image 1](https://i.stack.imgur.com/2dMRM.png)](https://i.stack.imgur.com/2dMRM.png) [Answer] # Sed, 113 + 1 = 114 bytes Why? Because it's fun to use the *wrong* tool to do things :P Usage: Run `sed -rf file`, enter text and press `Ctrl` + `D` (send EOF). Golfed: ``` s/[A-Z]/\a\l&/g;s/^.*$/\f&\v/;:x;s/\f\a/\a\f/;s/\a\v/\v\a/;s/\f(.)(.*)(.)\v/\3\f\2\v\1/;tx;s/\f|\v//g;s/\a./\U&/g ``` Ungolfed: ``` s/[A-Z]/\a\l&/g #Prepend all upper-case letters with a #BEL ASCII character and make them lowercase s/^.*$/\f&\v/ #Wrap text between a from feed (\f) and a vertical tab (\v) #These are used as markers :x #Define a label named x s/\f\a/\a\f/;s/\a\v/\v\a/ #Move BEL characters outside of the boundary, so they're not moved later s/\f(.)(.*)(.)\v/\3\2\1/ #This part does the switching itself #It grabs a character preceded by a form feed and another #one followed by a vertical tab and swaps them, while keeping the text in-between #and replaces the marker \f and \v tx #Conditional jump (t) to label x #Jumps to the label x if the last substitution (s command) was successful s/\f|\v//g #Delete markers s/\a(.)/\u\1/g #Make letters preceded by a BEL upper-case ``` [Answer] # Java 7, ~~221~~ ~~217~~ 180 bytes ``` void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);} ``` Loads of bytes saved thanks to *@LeakuNun*'s approach. **Ungolfed & test cases:** [Try it here.](https://ideone.com/oqyLIU) ``` class Main{ void c(char[] s){ int x = 0, y = s.length-1; for(char t; x < y; s[x] = s(t, s[y]), s[y] = s(s[y], t), x++, y--){ t = s[x]; } } char s(char a, char b){ return (char)(64 < a & a < 91 ? 96 < b & b < 123 ? b-32 : b : 64 < b & b < 91 ? b+32 : b); } public static void main(String[] a){ print("Hello, Midnightas"); print("TEST"); print("test"); print("Test"); print(".,..,,!@"); print("ABCDefgHijklMNOPqrsTuVWxyz"); print("AbCdEfGHIJKlmnop123"); } static void print(String s){ char[] t = s.toCharArray(); c(t); System.out.println(t); } } ``` **Output:** ``` SathginDim ,olleh q. TSET tset Tset @!,,..,. ZYXWvutSrqpoNMLKjihGfEDcba 321pOnMLKJIhgfedcba ``` [Answer] # Lua, 132 Bytes ``` function(s)o=""i=0 for m in s:gmatch(".")do n=s:sub(#s-i,#s-i)l=m:lower()o=o..(m==l and n:lower()or n:upper())i=i+1 end print(o)end ``` There might be a better way to do this in lua, but I think this works. [Answer] # Ruby, 64 bytes [Try it online!](https://repl.it/Coos) ``` ->s{i=0;s.gsub(/./){c=s[i-=1];$&=~/[A-Z]/?c.upcase: c.downcase}} ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 24 bytes ``` {b?UCaa}MZLCRVa(_NAZ Ma) ``` Gets a binary array for the uppercase indices and uppercases those places in the reversed lowercase string. [Try it online!](https://tio.run/##K8gs@P@/Osk@1DkxsdY3ysc5KCxRI97PMUrBN1Hz////Hqk5Ofk6Cr6ZKXmZ6RklicUA "Pip – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` Âls€.uÅÏu ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cFNO8aOmNXqlh1sP95f@/@@RmpOTr6Pgm5mSl5meUZJYDAA "05AB1E – Try It Online") **Commented:** ``` Â # Push input and input reversed l # lowercase reversed input s # swap to normal input €.u # map is_upper ÅÏ # where this is true, # apply to the reversed input: u # uppercase ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` £ÔgY mvc-X¦v ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o9RnWSBtdmMtWKZ2&input=IkhlbGxvLCBNaWRuaWdodGFzIg) ``` £ÔgY mvc-X¦v :Implicit input of string U £ :Map each character X at 0-based index Y Ô : Reverse U gY : Get the character at index Y m : Map v : Literal "v" c- : Reduce charcode by X¦ : X does not equal v : Its lowercase :(This results in mapping the character by either "v", : which is Japt's lowercase method or "u", : which is Japt's uppercase method) ``` [Answer] # [Arturo](https://arturo-lang.io), 62 bytes ``` $->s[i:0map reverse lower s'c[if<=>s\[i]`A``Z`->upper'c'i+1c]] ``` [Try it](http://arturo-lang.io/playground?Ye1pKi) Takes a string, returns a list of characters. [Answer] # Commodore C64 (just for fun/non-competing), 194 Tokenised BASIC Bytes To enter this on a real C64, you must use [BASIC keyword abbreviations](https://www.c64-wiki.com/wiki/BASIC_keyword_abbreviation), as you are not able to enter more than 80 characters onto a C64 BASIC line though once entered the interpreter will show the keywords in full. The listing is shown as abbreviations with switched character modes to upper/lower case. You may do this by pressing SHIFT + C=. The program will switch modes anyway on line 0 with the control character N (achieved by pressing `CTRL+N` after the opening quote). ``` 0input"{CTRL+N}";a$:ifa$=""tHeN 1l=len(a$):dIp(l),b(l):fOx=1tol:p(x)=aS(mI(a$,x,1))>127:nE:i=1:fOx=lto1stE-1 2b(i)=aS(mI(a$,x,1))aN127:i=i+1:nE:fOx=1tol 3ifb(x)>64tH?cH(b(x)-128*p(x)); 4ifb(x)<65tH?cH(b(x)); 5nE ``` **Note** I've marked this as non-competing because whilst the character encoding on the Commodore C64 (PETSCII) is compatible with ASCII, it is not ASCII. As this question is six years old at the time of writing, and the questioner has left, I'm sure no one will mind. Some caveats, string handling with the `INPUT` command has some limitations. For instance, if you wanted to enter `Hello, World!` as a test, you would need to enter it starting with a double quotation mark, so `"Hello, World!"`. A quick explanation: * Line 0 switches the character set to upper/lower case, rather than PETSCII graphics mode, and waits for a user input; if there is an empty string entered then the program terminates. I added this otherwise it will error, as the `FOR/NEXT` loops are expecting at least one character to iterate over. * Line 1 will set l to the length of the string, and set up two numeric arrays, called `p(l)` and `b(l)`. `p(l)` is used for determines whether the positional character is upper case or not, by checking if the character code is 128 or more. If so, a `-1` is added to the array at position `x`, otherwise it is `0`. When that loop ends, we set variable `i` to `1`, and start a new loop counting down from the string length to 1. * Line 2 sets the array `b(l)` at position `i` to the PETSCII character code; this value is `AND`ed with 127 so that each position will be the lower-case character code. `i` is then incremented by `1` and the loop ends. We then set up a final `FOR/NEXT` loop, again counting up from 1 to `l`. * Line 3 checks if array position `b(x)` is 65 or greater (this is for characters `a` - `z` inclusive). If so, it prints the character -128 multiplied by the contents of `p(x)`, which is `-1` for upper-case at that position, or `0` if not. `-128*-1` will add `128` so converting the character at that position to upper case. * Line 4 checks if array position `b(x)` has a value below 64; if so, we don't want to convert this to upper case or we will get some odd results for numbers and punctuation etc. * Line 5 iterates the loop again until it is done. When the loop is finished, the program will end gracefully. The screen shot below shows the BASIC program as the interpreter lists it. This was a fun challenge and took a little while to get the logic right, so it's quite likely that there are some further optimisations to save some BASIC bytes. [![Reverse a string while maintaining the capitalization in the same places, Commodore C64](https://i.stack.imgur.com/AvrPI.png)](https://i.stack.imgur.com/AvrPI.png) [Answer] # Excel VBA, 256 bytes ``` Function z(d) r = Len(d) ReDim E(1 To r) For i = 1 To r b = Mid(d, i, 1) If Asc(b) > 64 And Asc(b) < 91 Then E(i) = 1 Next i i = 1 For p = r To 1 Step -1 v = Mid(d, p, 1) If E(i) = 1 Then z = z & UCase(v) Else z = z & LCase(v) i = i + 1 Next p End Function ``` [Answer] # Google Sheets, 133 Closing parens already discounted. Input: `A1` * `A2`: `=LEN(A1)` * `B1`: `=ArrayFormula(MID(A1,1+A2-SEQUENCE(A2),1))` + Reverse string * `C1`: `=JOIN(,ArrayFormula(if(REGEXMATCH(MID(A1,SEQUENCE(A2),1),"[A-Z]"),UPPER(B:B),LOWER(B:B))))` + Compare capital positions, capitalize if originally upper, lower if not. Then join. `EXACT(UPPER(...),...)` is worse because we're dealing with a range here. + It's a little sluggish because we don't chop off the `B:B` at the blanks. [Answer] C ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *a,*b,*c; a=c=strdup(argv[1]); b=&argv[1][strlen(a)-1]; for(;*a;a++,b--){ *a=(*a>='A'&&*a<='Z')?((*b>='a'&&*b<='z')?*b-32:*b):((*b>='A'&&*b<='Z')?*b+32:*b); } puts(c); free(c); return 0; } ``` ]
[Question] [ Given two positive integers, 'a' and 'b', output an ascii-art "box" that is *a* characters wide and *b* characters tall. For example, with '4' and '6': ``` **** * * * * * * * * **** ``` Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be ``` 4646 6 4 4 6 6 4 4 6 6464 ``` A and B *may* be two-digit numbers. For example, the inputs "10" and "3" should output this: ``` 1031031031 1 0 3013013013 ``` In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to *positive* integers, '0' is an invalid input, which you do not have to handle. Here are some more test cases: ``` Input: (3, 5) Output: 353 5 5 3 3 5 5 353 Input: (1, 1) Output: 1 Input: (4, 4) Output: 4444 4 4 4 4 4444 Input: (27, 1) Output: 271271271271271271271271271 Input: (1, 17) Output: 1 1 7 1 1 7 1 1 7 1 1 7 1 1 7 1 1 Input: (12, 34): Output: 123412341234 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 4 1 3 2 2 3 1 4 432143214321 ``` You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins! [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~65~~ 51 bytes ``` ~~juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ\_UhQ+R]0\_UeQ)m\*;hQeQ~~ AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH ``` [Try it online!](http://pyth.herokuapp.com/?code=AQjuXGhHX%40GhHeH%40jkQ~hZ%7Bs%5B%2CL0G%2CRtGH_%2CLtHG_%2CR0H%29m%2a%3BGH&input=10%2C3&debug=0) [Answer] ## C#, 301 bytes I'm sure there is a lot more golfing that can be done here but I'm just happy I got a solution that worked. I found a bug where the bottom line was in the wrong order, damnit! ``` a=>b=>{var s=new string[b];int i=4,c=b-2,k=a;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");for(;--k>=0;)s[b-1]+=t.Substring(a+c,a)[k];}return s;}; ``` Old version: 280 bytes ``` a=>b=>{var s=new string[b];int i=4,c=b-2;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");s[b-1]=t.Substring(a+c,a);}return s;}; ``` [Answer] # Python 2, 199 bytes ``` w,h=input() s=(`w`+`h`)*w*h r=[s[:w]]+[[" "for i in[0]*w]for j in[0]*(h-2)]+[s[w+h-2:2*w+h-2][::-1]]*(h>1) for y in range(1,h-1):r[y][w-1],r[y][0]=s[w+y-1],s[w+h+w-2-y] print"\n".join(map("".join,r)) ``` [Answer] # Ruby, 128 bytes ``` ->w,h{s="%d%d"%[w,h]*q=w+h;a=[s[0,w]];(h-2).times{|i|a<<(s[2*q-5-i].ljust(w-1)+s[w+i,1])[-w,w]};puts a,h>1?(s[q-2,w].reverse):p} ``` Outputs trailing newline if height is 1. Ideone link: <https://ideone.com/96WYHt> [Answer] # JavaScript, ~~213~~ ~~212~~ 202 ``` c=>a=>{for(a=$=a,c=_=c,l=c*a*2,b=0,s=Array(l+1).join(c+""+a),O=W=s.substr(0,a),W=W.substr(0,a-2).replace(/./g," ");--_;)O+="\n"+s[l-c+_]+W+s[$++];return O+"\n"+[...s.substr(l-a-c+1,a)].reverse().join``} ``` Surely has room for improvement. **Edit:** Saved a byte thanks to TheLethalCoder [Answer] # C, 311 bytes ``` char s[5];sprintf(s,"%d%d",a, b);int z=strlen(s);int i=0;while(i<a){printf("%c",s[i++%z]);}if(b>2){i=1;while(i<b-1){char r=s[(a+i-1)%z];char l=s[(2*a+2*b-i-4)%z];if(a>1){printf("\n%c%*c",l,a-1,r);}else{printf("\n%c",l);}i++;}}printf("\n");if(b>1){i=0;while(i<a){printf("%c",s[(2*a+b-i-3)%z]);i++;}printf("\n");} ``` Uses automatically included libraries `stdio.h` and `string.h`. [Answer] ## JavaScript (ES6), 171 bytes ``` (w,h)=>[...Array(h)].map((_,i)=>i?++i<h?(w>1?s[p+p+1-i]+` `.repeat(w-2):``)+s[w+i-2]:[...s.substr(p,w)].reverse().join``:s.slice(0,w),s=`${w}${h}`.repeat(p=w+h-2)).join`\n` ``` Where `\n` represents the literal newline character. Creates a repeated digit string, then decides what to concatenate based on which row we're on; top row is just the initial slice of the repeated digit string, bottom row (if any) is a reversed slice from the middle of the string, while intervening rows are built up using characters taken from other parts of the string. [Answer] # TSQL, 291 bytes **Golfed:** ``` DECLARE @ INT=5,@2 INT=4 ,@t INT,@z varchar(max)SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)v:PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)+isnull(space(@-2)+left(@z,1),''),reverse(@z)))SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))IF @<=len(@z)goto v ``` **Ungolfed:** ``` DECLARE @ INT=5,@2 INT=4 ,@t INT,@z varchar(max) SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t) v: PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1) +isnull(space(@-2)+left(@z,1),''),reverse(@z))) SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2))) IF @<=len(@z)goto v ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/526524/code-golf-abcs-the-ascii-box-challenge)** [Answer] # Python 3, ~~155~~ 148 bytes Golfed off 7 more bytes: ``` p=print def f(w,h): s=((str(w)+str(h))*w*h)[:2*w+2*h-4or 1];p(s[:w]) for i in range(h-2):p(['',s[-i-1]][w>1]+' '*(w-2)+s[w+i]) p(s[1-h:1-h-w:-1]) ``` Substituted `2*w+2*h-4or 1` for `max(1,2*w+2*h-4)` and `['',s[-i-1]][w>1]` for `(s[-i-1]if w>1else'')`. Prior version: ``` p=print def f(w,h): s=((str(w)+str(h))*w*h)[:max(1,2*w+2*h-4)];p(s[:w]) for i in range(h-2):p((s[-i-1]if w>1else'')+' '*(w-2)+s[w+i]) p(s[1-h:1-h-w:-1]) ``` ]
[Question] [ The purpose of this challenge is to produce an ASCII version of the cover of [this great album](https://en.wikipedia.org/wiki/The_Wall) by the rock band Pink Floyd. The brick junctions are made of characters `_` and `|`. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is: ``` _________ | | | | _________ ``` Each row of bricks is **offset by half a brick width** (4 chars) with respect to the previous row: ``` ________________________________________ | | | | | | | | | | ________________________________________ | | | | | | | | | | ________________________________________ | | | | | | | | | | ``` The wall is **parameterized** as follows. All parameters are measured in chars including junctions: 1. **Horizontal offset** of first row, `F`. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are `0`, `1`, ..., `7`. 2. Total **width**, `W`. This includes junctions. Its value is a positive integer. 3. Total **height**, `H`. This includes junctions. Its value is a positive integer. The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of `3`). For example, here's the output for `6`, `44`, `11`: ``` ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | ``` and a visual explanation of parameters: ``` F=6 ...... . ____________________________________________ . | | | | | . | | | | | . ____________________________________________ . | | | | | | H=11 . | | | | | | . ____________________________________________ . | | | | | . | | | | | . ____________________________________________ . | | | | | | ............................................ W=44 ``` ## Additional rules You may provide a program or a function. Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings. Trailing spaces or newlines are allowed. Shortest code in bytes wins. ## Test cases Inputs are in the order given above, that is: horizontal offset of first row, total width, total height. ``` 6, 44, 11: ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | 2, 20, 10: ____________________ | | | | | | ____________________ | | | | ____________________ | | | | | | ____________________ 1, 1, 1: _ 1, 2, 3: __ | | 3, 80, 21: ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ``` [Answer] # C, 86 85 83 82 bytes 3 bytes saved thanks to Lynn. 1 byte saved thanks to charlie. ``` i;f(o,w,h){++w;for(i=0;++i<w*h;)putchar(i%w?i/w%3?i%w+i/w/3*4+~o&7?32:124:95:10);} ``` [Answer] # C, 92 bytes ``` b(f,w,h,y,x){for(y=0;y<h;y++,puts(""))for(x=0;x<w;x++)putchar(y%3?(x+y/3*4-f)%8?32:124:95);} ``` Invoke as `b(F, W, H)`. [Answer] # Pyth, ~~43~~ 27 bytes I ***need*** to golf it heavily... the score is too shameful. ``` AQVE<*H?%N3X*8d+G*4/N3\|\_H ``` [Try it online already.](http://pyth.herokuapp.com/?code=AQVE%3C%2aH%3F%25N3X%2a8d%2BG%2a4%2FN3%5C%7C%5C_H&input=6%2C44%0A11&debug=0) ### Input format ``` 6,44 11 ``` ### Output format ``` ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | ``` ## Explanation ``` AQVE<*H?%N3X*8d+G*4/N3\|\_H First two inputs as list in Q, third input as E. AQ Assign G to the first item in Q and H to the second item in Q. VE For N from 0 to E-1: /N3 N floor-div 3. if N gives a remainder of 3 or 4 or 5 when divided by 6, this will be odd; otherwise, this will be even. *4 Multiply by 4. if the above is odd, this will leave a remainder of 4 when divided by 8; otherwise, the remainder would be 0. +G Add G (as an offset). X*8d \| In the string " " (*8d), replace (X) the character with the index above with "|" (modular indexing, hence the manipulation above). ?%N3 \_ If N%3 is non-zero, use the above; otherwise, use "_". *H The above repeated H times. < H Take the first H characters of above. Implicitly print with newline. ``` [Answer] # Perl, 63 bytes ``` #!perl -nl $y+=print+map$y%3?$_++-$`&7?$":'|':_,($y%6&4)x$&for/ \d+/..$' ``` Counting the shebang as 2, input is taken from stdin, whitespace separated. **Sample Usage** ``` $ echo 2 20 10 | perl bricks.pl ____________________ | | | | | | ____________________ | | | | ____________________ | | | | | | ____________________ ``` [Answer] ## Haskell, 83 bytes ``` q s="_":[s,s] (f!w)h=take h$cycle$take w.drop(7-f).cycle<$>q" |"++q" | " ``` This defines a ternary infix function `!` which returns a list of strings. Usage example: ``` *Main> putStrLn $ unlines $ (3!14) 7 ______________ | | | | ______________ | | ______________ ``` How it works: ``` q" |"++q" | " -- build a list of 6 strings -- 1: "_" -- 2: " |" -- 3: " |" -- 4: "_" -- 5: " | " -- 6: " | " <$> -- for each of the strings take w.drop(7-f).cycle -- repeat infinitely, drop the first 7-f chars -- and take the next w chars cycle -- infinitely repeat the resulting list take h -- and take the first h elements ``` [Answer] ## JavaScript (ES6), ~~96~~ 95 bytes ``` g= (f,w,h)=>[...Array(h)].map((_,i)=>(i%3?` |`:`_`).repeat(w+7).substr(f^7^i%6&4,w)).join` ` ; ``` ``` <div onchange=o.textContent=g(f.value,w.value,+h.value)><input id=f type=number min=0 max=7 placeholder=Offset><input id=w type=number min=0 placeholder=Width><input id=h type=number min=0 placeholder=Height></div><pre id=o> ``` Explanation: Creates a string of either the repeating 7 spaces plus `|` pattern or just repeated `_`s, but at least long enough to be able to extract the `w` characters required for each row. The first three rows start at position `f^7` and then the next three rows start at position `f^3`, so I achieve this by ~~toggling bit 2 of `f` on every third row~~ using the opposite bit 2 on the last two rows of each block of 6 for a saving of 1 byte. [Answer] # Python 2, ~~93~~ 88 bytes ~~2nd indentation level is tab~~ Saving some bytes thanks to Leaky Nun and some own modifications, also now correct offset: ``` def f(F,W,H): for h in range(H):print["_"*W,((("|"+7*" ")*W)[8-F+h%6/3*4:])[:W]][h%3>0] ``` previous code: ``` def f(F,W,H,x="|"+7*" "): for h in range(H): print ["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0] ``` Same length as unnamed lambda: ``` lambda F,W,H,x="|"+7*" ":"\n".join(["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0]for h in range(H)) ``` [Answer] # MATL, ~~42~~ ~~36~~ 33 bytes ``` :-Q'_ | |'[DClCl]Y"8et4YShwi:3$)! ``` Input format is: `nCols`, `offset`, `nRows` [**Try it Online**](http://matl.tryitonline.net/#code=Oi1RJ18gfCB8J1tEQ2xDbF1ZIjhldDRZU2h3aTozJCkh&input=NDQKNgoxMQ) The approach here is that we setup a "template" which we then index into by using the row indices (`[1 2 ... nRows]`) and column indices shifted by the first input (`[1 2 ... nCols] - shift`). Thanks to MATL's modular indexing, it will automatically result in a tiled output. As a side-note, to save some space, technically I work with a transposed version of the template and then just take a transpose (`!`) at the end. The template is this: ``` ________ | | ________ | | ``` [Answer] # QBasic, ~~121~~ 109 bytes ## (Tested on QB64) Thanks to @DLosc for golfing my `IF` statement with a mathematical equivalent. That was worth 12 bytes. ## General Method: Loop through each cell one at a time and determine whether it should be a `_`, , or `|` depending on its location. `MOD` statements and boolean logic are used to determine brick boundaries and how much to stagger the bricks. ## Code: ``` INPUT F,W,H FOR y=0TO H-1:FOR x=0TO W-1 ?CHR$((y MOD 3>0)*(((x-(y MOD 6>3)*4)MOD 8=F)*92+63)+95); NEXT:?:NEXT ``` ## Usage Note: QBasic expects input to be numbers separated by commas. [Answer] # Java, ~~149~~, ~~147~~, ~~146~~, 143 bytes Golfed: ``` String f(int o,int w,int h){String s="";for(int y=0,x;y<h;++y){for(x=0;x<w;++x){s+=y%3>0?(x-o+(y-1)/3%2*4)%8==0?'|':' ':'_';}s+='\n';}return s;} ``` Ungolfed: ``` public class AllInAllItsJustUhAnotherTrickInCodeGolf { public static void main(String[] args) { int offset = 6; int width = 44; int height = 11; System.out.println(new AllInAllItsJustUhAnotherTrickInCodeGolf() .f(offset, width, height)); } // Begin golf String f(int o, int w, int h) { String s = ""; for (int y = 0, x; y < h; ++y) { for (x = 0; x < w; ++x) { s += y % 3 > 0 ? (x - o + (y - 1) / 3 % 2 * 4) % 8 == 0 ? '|' : ' ' : '_'; } s += '\n'; } return s; } // End golf } ``` [Answer] # Ruby, ~~72~~ 66 bytes ``` ->f,w,h{h.times{|i|puts i%3<1??_*w:((?|+' '*7)*w)[8-f+i%6/4*4,w]}} ``` Thanks @Value Ink for 6 bytes! Simple string multiplication and slicing. Works in Ruby 2.3.0 (Ideone's version 2.1 threw syntax error). [Answer] # Julia: ~~150~~ ~~128~~ ~~116~~ ~~108~~ 107 bytes ``` # in codegolf.jl r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...) ``` to run with arguments: `julia -e 'o=2;h=18;w=40;include("codegolf.jl")'` If you feel calling from bash is cheating and you want a function inside the interpreter, then the function version is 117 bytes :) ``` f(o,h,w)=(r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...)) ``` [demo](http://julia.tryitonline.net/#code=ZihvLGgsdyk9KGI9MzIqb25lcyhJbnQzMiw2LDgpO2JbWzEsNF0sOl09OTU7YltbMiwzLDIzLDI0XV09MTI0O2I9cmVwbWF0KGIsaCx3KVsxOmgsbysxOm8rdysxXTtiWzosZW5kXT0xMDtwcmludChyZWludGVycHJldChDaGFyLGInKS4uLikpCmYoMiwgMTgsNDAp&input=) (Thanks, @glen-o for the extra byte-saving tip!) [Answer] ## JavaScript, ~~172~~ ~~168~~ ~~165~~ ~~157~~ ~~147~~ ~~142~~ 137 bytes ``` (O,W,H)=>{t='_'.repeat(W),x='| '.repeat(W),f=t+` `;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+` `;return f} ``` ``` N = (O,W,H)=>{t='_'.repeat(W),x='| '.repeat(W),f=t+` `;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+` `;return f} let test_data = [[6,44,11], [2,20,10], [1,1,1], [1,2,3], [3,80,21]]; for (test of test_data) console.log(N(...test)); ``` [Answer] # Dyalog APL, 29 bytes `↑⎕⍴⎕⍴¨a,4⌽¨a←'_',2⍴⊂⌽⎕⌽¯8↑'|'` tests: [`6 44 11`](http://tryapl.org/?a=F%20W%20H%u21906%2044%2011%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`2 20 10`](http://tryapl.org/?a=F%20W%20H%u21902%2020%2010%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`1 1 1`](http://tryapl.org/?a=F%20W%20H%u21901%201%201%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`1 2 3`](http://tryapl.org/?a=F%20W%20H%u21901%202%203%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`3 80 21`](http://tryapl.org/?a=F%20W%20H%u21903%2080%2021%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run) `⎕` is evaluated input; as the expression executes from right to left, it prompts for `F`, `W`, and `H` in that order `¯8↑'|'` is `' |'` `⎕⌽` is rotate, it chops F chars from the front and puts them at the end of the string the other `⌽` means reverse `'_',2⍴⊂` creates a 3-tuple of '\_' followed by two separate copies of the string so far `a,4⌽¨a←` append the 4-rotation of everything so far, we end up with a 6-tuple `⎕⍴¨` reshape each element to the width `⎕⍴` reshape to the height `↑` mix vector of vectors into a matrix [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '_'|7úD)³∍ε73N3÷è¹-._²∍ ``` -1 byte thanks to *@Grimmy*. Inputs in the order \$\text{offset}, \text{width}, \text{height}\$. Output as a list of string-lines. [Try it online](https://tio.run/##yy9OTMpM/f9fPV69xvzwLhfNQ5sfdfSe22pu7Gd8ePvhFYd26urFH9oEFPtfe2j3fzMuExMuQ0MA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJh1bGhIX@V49XrzE/vMtF89C6Rx2957aaG/sZH95@eEWErl58JFDkf@2h3TqaMYe22f@PjjbTMTHRMTSM1Yk20jEy0DE0ALIMdYAQTBvpGANpYx0LAx0jkIiBjqWOSWwsAA). **Explanation:** ``` '_ '# Push "_" '| '# Push "|" 7ú # Pad 7 leading spaces: " |" D # Duplicate it ) # Wrap all three values on the stack into a list ³∍ # Extend this list to the (third) input-height amount of lines # i.e. height=7 → ["_"," |"," |","_"," |"," |","_"] ε # Map over each line: N # Push the (0-based) map-index 3÷ # Integer-divide it by 3 73 è # Index it into 73 (0-based and with wraparound) # i.e. indices=[0,1,2,3,4,5,6,7,...] → [7,7,7,3,3,3,7,7,...] ¹+ # Subtract the (first) input-offset # i.e. offset=6 → [-3,-3,-3,1,1,1,-3,-3,...] ._ # Rotate the string that many times towards the left # i.e. ["_"," |"," |","_"," |"," |","_"] and # [-3,-3,-3,1,1,1,-3] → ["_"," | "," | ","_"," | "," | ","_"] ²∍ # After this inner loop: push the (second) input-width # Extend/shorten the line to a size equal to the (second) input-width # i.e. width=5 and line=" | " → " | " # i.e. width=20 and line=" | " → " | | |" # i.e. width=5 and line="_" → "_____" # i.e. width=20 and line="_" → "____________________" # (after which the list of string-lines is output implicitly as result) ``` `73N3÷è` could alternatively be `₃€ÐÍNè` for the same byte-count: [Try it online](https://tio.run/##ATsAxP9vc2FiaWX//ydfJ3w3w7pEKcKz4oiNzrXigoPigqzDkMONTsOowrktLl/CsuKIjf99wrv/Ngo0NAoxMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJh1bGhIX@V49XrzE/vMtF89C6Rx2957Y@amp@1LTm8ITDvX6HV0To6sVHAoX/1x7araMZc2ib/f/oaDMdExMdQ8NYnWgjHSMDHUMDIMtQBwjBtJGOMZA21rEw0DECiRjoWOqYxMYCAA). ``` ₃ # Push builtin 95 €Ð # Triplicate each digit: [9,9,9,5,5,5] Í # Decrease each by 2: [7,7,7,3,3,3] Nè # Index the (0-based) map-index into this (0-based and with wraparound) ``` [Answer] # [Actually](https://github.com/Mego/Seriously), ~~44~~ ~~43~~ 40 bytes This is an Actually port of the algorithm in [Neil's JS answer](https://codegolf.stackexchange.com/a/90076/47581). Golfing suggestions welcome. [Try it online!](https://tio.run/##S0wuKU3Myan8///R1OmPps4tetSzwNpMQ9VE7dHUOeZxcY@mzlavMVdSUNLS1ioBchw8QCLxWsYaqpGej3oW@mb@/29oyGViwmUGAA "Actually – Try It Online") ``` ╗╝r⌠;6(%4&╜7^^╛'|7" "*+*t╛@H╛'_*3(%YI⌡Mi ``` **Ungolfing:** ``` Takes implicit input in the order h, w, f. ╗╝ Save f to register 0. Save w to register 1. r⌠...⌡M Map over range [0..h-1]. Call this variable i. ; Duplicate i 6(% i%6... 4& ...&4 ╜7^^ ...^i^7. Call it c. ╛ Push w. '|7" "*+ The string " |" *t╛@H ((" |" * w)[c:])[:w] ╛'_* Push "_" * w 3(% Push 3, move duplicate i to TOS, mod. YI If not i%3, take "_"*w, else ((" |" * w)[c:])[:w] Function ends here. i Flatten the resulting list and print the bricks implicitly. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~101~~ 88 bytes ``` param($n,$w,$h)0..--$h|%{(('| '*$w|% S*g(8-$n+4*($_%6-gt3))$w),('_'*$w))[!($_%3)]} ``` [Try it online!](https://tio.run/##LY3RCoJAEEXf9ys2GdsZG2NXJSLoK@otRCQsH8xEhX1Iv31zrWG4nDt34HZvW/VDXTWNg8f547qyL18ILYNlqEnv93EM9RR@ENUkf6MisFMoL9ETjzG0uyxCKMJD/BxTIrDEqAr/Q3Tb@CSlfHazEIgHzjI2hlhgwolmoz0aln7/mLBMPaYsj3qxhmipF744uFbDKO/lUJ0kFMF6k1t4LOamc69m1SRfI6XE7L4 "PowerShell – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 30 bytes ``` (n₃[¹\_*,|7\|꘍¹*⁰ǔǔn3ḭ∷[4ǔ]¹Ẏ, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%28n%E2%82%83%5B%C2%B9%5C_*%2C%7C7%5C%7C%EA%98%8D%C2%B9*%E2%81%B0%C7%94%C7%94n3%E1%B8%AD%E2%88%B7%5B4%C7%94%5D%C2%B9%E1%BA%8E%2C&inputs=10%0A44%0A1&header=&footer=) A big mess. ``` ( # (height) times (to make each row) n₃[ # If the iteration is divisible by 3 (flat row) then... ¹\_*, # (width) underscores | # Else (part of a brick)... 7\|꘍ # Prepend seven spaces to an underscore ¹* # Repeat (width) times ⁰ǔǔ # Cycle by (offset), then cycle once more n3ḭ∷[ ] # If it's an offset row 4ǔ # Cycle once more ¹Ẏ, # Trim to the correct length and print. ``` [Answer] # Octave ~~80~~ 76 bytes ``` % in file codegolf.m c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;char(repmat(c+32,h,w)(1:h,o+1:o+w)) ``` to run from terminal: `octave --eval "o=2;h=18;w=44; codegolf"` (alternatively, if you think the terminal call is cheating :p then an anonymous function implementation takes 86 bytes :) ``` c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;f=@(o,h,w)char(repmat(c+32,h,w)(1:h,o+1:o+w)) ``` Call `f(2,18,44)` at the octave interpreter. [Answer] # Bash + Sed, ~~411~~ ~~395~~ ~~381~~ 370 bytes: ``` F=`printf '_%.s' $(eval echo {1..$2})`;V=" |";(($[($2-$1)/8]>0))&&L=`printf "$V%.s" $(eval echo {1..$[($2-$1)/8]})`||L=;Z=`printf "%$1.s|%s\n" e "$L"`;I=$[($2-(${#Z}-4))/8];(($I>0))&&W=`printf "$V%.s" $(eval echo {1..$I})`||W=;J=${Z:4}$W;for i in `eval echo {1..$[$3/3+1]}`;{ (($[$i%2]<1))&&O+="$F\n$J\n$J\n"||O+="$F\n$Z\n$Z\n";};echo "`echo -e "$O"|sed -n 1,$3p`" ``` Well, here is my very first answer in Bash, or any shell scripting language for that matter. This is also by far the longest answer here. Takes in a sequence of space-separated command line arguments in the format `Offset Width Height`. This can probably be a lot shorter than it currently is, so any tips and/or tricks for golfing this down more are appreciated. [Answer] ## Delphi/Object Pascal, 305, 302, 292 bytes Full console program that reads 3 parameters. ``` uses SySutils,Math;var i,q,o,w,h:byte;begin o:=StrToInt(paramstr(1));w:=StrToInt(paramstr(2));h:=StrToInt(paramstr(3));for q:=0to h-1do begin for i:=1to w do if q mod 3=0then Write('_')else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8))=1then Write('|')else Write(' ');Writeln('');end end. ``` ### ungolfed ``` uses SySutils, Math; var i,q,o,w,h:byte; begin o:=StrToInt(paramstr(1)); w:=StrToInt(paramstr(2)); h:=StrToInt(paramstr(3)); for q := 0 to h-1 do begin for i := 1 to w do if q mod 3 = 0 then Write('_') else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8)) = 1 then Write('|') else Write(' '); Writeln(''); end end. ``` Sadly, Delphi does not have a ternary operator and it is quite a verbose language. ### test case ``` D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 2 20 10 ____________________ | | | | | | ____________________ | | | | ____________________ | | | | | | ____________________ D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 6 44 11 ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | ``` Edit: Could shave of 3 bytes by using byte as type for all variables. Edit 2: And console applications do not *need* the program declaration, -10 [Answer] # JavaScript (ES6), ~~81 78~~ 77 bytes *Saved 3 bytes thanks to @mypronounismonicareinstate* Takes input as `(F, W)(H)`. ``` (F,W,x=y=0)=>g=H=>y<H?` |_ `[x++<W?y%3?(x+~F^y/3<<2)&7?3:1:2:x=+!++y]+g(H):'' ``` [Try it online!](https://tio.run/##bczBCsIgAIDhe09hh5qi1dRRITpvY2@wQ1QbaxvFmNEiFKJXN6@xzh//f6te1Vg/rvfnajCXxrfKw4wUxCqnYqTSTuUqdTLX5ex9BuXBYiwL7RZcQ4s/2cltuJQMLXeaCyqYsArPMXZH3MEciSjytRlG0zfr3nSwhVsCkgRBShGa/QojgMVB4olQAgBFENC/woLwiXAC9uHGQuO/ "JavaScript (Node.js) – Try It Online") ]
[Question] []
[Question] []
[Question] []
[Question] [ ## Background I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week. When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet. My strategy is to pull one random sock from the pile at a time and put it on a drawer. Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet. Your task is to simulate this random process and return the number of draws required to find the first matching pair. ## Input Your input is an integer **N ≥ 1**. It represents the "number of days in a week": there are **N** pairs of socks in the pile, and each pair has a distinct label. If necessary, you may also take a PRNG seed as input. ## Output Your output is the number of socks I have to draw before the first matching pair is found. For example, if the first two socks already form a matching pair, the output is `2`. Of course, the output is random, and depends on the drawing order. We assume that *all drawing orders are equally likely*, so that each time a sock is drawn, the choice is uniform and independent from all other choices. ## Example Let **N = 3**, so that we have 6 socks in total, labeled **A A B B C C**. One possible run of the "sock-drawing protocol" is as follows: ``` | Pile | Drawer | Pairs Begin | AABBCC | - | - Draw B | AABCC | B | - Draw C | AABC | BC | - Draw B | AAC | C | BB Draw A | AC | AC | BB Draw A | C | C | AA BB Draw C | - | - | AA BB CC ``` The first matching pair was found after drawing the second **B**, which was the third sock to be drawn, so the correct output is `3`. ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Input and output can be in any reasonable format, including unary (string of `1`s). You may assume that your language's built-in RNG is perfect. You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution. ## "Test cases" Here are the approximate probabilities of all outputs for the input **N = 7**: ``` Output 2 3 4 5 6 7 8 Probability 0.077 0.154 0.210 0.224 0.186 0.112 0.037 ``` To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḤX€Ṛ<RTḢ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bikWOKCrOG5mjxSVOG4og&input=&args=MTAw) or [verify the distribution for **N = 7**](http://jelly.tryitonline.net/#code=4bikWOKCrOG5mjxSVOG4ogrigJjCteKAmXg0yLc0w4figqzEi8OQ4oKsUsO3NMi3NMW8QFJH&input=&args=Nw). ### Background Let **n** be the number of pairs; there are **2n** individual socks. For the first draw, there are **2n** socks and **0** of them would result in a matching pair. Therefore, the probability of success is **0 / 2n = 0**. Since the first draw wasn't successful, there are **2n - 1** socks on the pile and **1** of them would result in a matching pair. Therefore, the probability of success is **1 / (2n - 1)**. *If* the second draw wasn't successful, there are **2n - 2** socks on the pile and **2** of them would result in a matching pair. Therefore, the probability of success is **2 / (2n - 2)**. In general, if the first **k** draws were unsuccessful, there are **2n - k** socks on the pile and **2** of them would result in a matching pair. Therefore, the probability of success is **k / (2n - k)**. Finally, if none of the first **n** draws was successful, there are **2n - k** socks on the pile and all of them would result in a matching pair. Therefore, the probability of success is **n / (2n - n) = 1**. ### How it works ``` ḤX€Ṛ<RTḢ Main link. Argument: n Ḥ Unhalve; yield 2n. X€ Map `random draw' over [1, ..., 2n], pseudo-randomly choosing an integer from [1, ..., k] for each k in [1, ..., 2n]. Ṛ Reverse the resulting array. R Range; yield [1, ..., n]. < Perform vectorized comparison. Comparing k with the integer chosen from [1, ..., 2n - (k - 1)] yields 1 with probability (k - 1) / (2n - (k - 1)), as desired. The latter half of elements of the left argument do not have a counter- part in the right argument, so they are left untouched and thus truthy. T Truth; yield all indices of non-zero integers. Ḣ Head; extract the first one. ``` [Answer] ## Jelly, 8 bytes ``` Rx2ẊĠṪ€Ṃ ``` [Try it online!](http://jelly.tryitonline.net/#code=Ungy4bqKxKDhuarigqzhuYI&input=&args=NQ) ``` R generate [1, 2, ..., n] x2 duplicate every element (two socks of each pair) Ẋ shuffle the list, to represent the order in which socks are drawn Ġ group indices by value. this will produce a list of pairs of indices; each pair represents the point in time at which each of the corresponding socks were drawn Ṫ€ take the last element of each pair. this returns an array of n integers which represent the points in time at which a matching sock was drawn Ṃ minimum, find the first point at which a matching sock was drawn ``` To verify, [here is a version](http://jelly.tryitonline.net/#code=Ungy4bqKwqnEoOG5quKCrOG5gizCrg&input=&args=NQ) that displays both the desired output and the result of the "shuffle list" operation (to see what order socks were drawn in). [Answer] # Python, 66 bytes ``` from random import* f=lambda n,k=1:k>randint(1,n*2)or-~f(n-.5,k+1) ``` Dennis thought up a clever way to rearrange things, saving 5 bytes. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` Q:"r@qGEy-/<?@. ``` [Try it online!](http://matl.tryitonline.net/#code=UToickBxR0V5LS88P0Au&input=Mw) Or [observe the empirical distribution](http://matl.tryitonline.net/#code=MWUzOiJHClE6InJAcUdFeS0vPD9ALgpdXV0Kdkc6UT1ZbTVNd3Y&input=Nw) for 1000 samples in the *N*=7 case (it takes a while). This **directly generates the random variable** representing the result, based on its probability distribution. Let *N* be the number of sock pairs, and let *p*(*k*) denote the probability that the *k*-th draw is successful, conditioned on the fact that the *k*-1-th draw was not succesful. Then (see also [here](http://gondolin.blogspot.com.es/2009/04/socks-problem.html)): * *p*(1) is obviously 0. You can't have a pair with a single sock. * *p*(2) is 1/(2\**N*−1). At the second draw there is one winning sock that may be chosen out of 2\**N*−1 remaining socks. * *p*(3) is 2/(2\**N*−2). At the third draw there are 2 winning socks out of 2\**N*−2. The number of winning socks is 2 because the two socks you got after the second draw were different. * In general, by the same reasoning, *p*(*k*) is (*k*−1)/(2\**N*−*k*+1) * By the above formula, *p*(*N*+1) is 1. If you get to the *N*+1-th draw you are guaranteed to succeed then. So the code iterates for a maximum of *N*+1 draws. At the *k*-th draw a random variable is generated that equals 1 with probability (*k*-1)/(2\**N*-*k*), or 0 otherwise. Whenever the random variable equals 1 (the draw has been succesful) the process stops and the current *k* is output. ``` Q: % Input N implicitly. Generate [1 2 ... N+1] (values of draw index, k) " % For each r % Random variable uniformly distributed on the interval (0,1) @q % Push iteration index, k-1 GE % Push 2*N y % Duplicate: push k-1 again - % Subtract: gives 2*N-k+1 / % Divide: gives (k-1)/(2*N-k+1) < % Push 1 if random value is less than (k-1)/(2*N-k+1), 0 otherwise ? % If we got a 1 @ % Push k . % Break loop % End if implicitly % End loop implicitly % Display implicitly ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes ``` EZ@G\&=XRafX< ``` [Try it online!](http://matl.tryitonline.net/#code=RVpAR1wmPVhSYWZYPA&input=Mw) Or [observe the empirical distribution](http://matl.tryitonline.net/#code=NGUzOiJHCkVaQEdcJj1YUmFmWDwKXQp2RzpRPVltNU13dg&input=Nw) for 4000 samples in the *N*=7 case (it takes a while). ``` E % Input N implicitly. Multiply by 2 Z@ % Random permutation of [1 2 ... 2*N] G\ % Modulo N: random permutation of [0 0 1 1 ... N-1 N-1] &= % Compare all pairs for equality. Gives an N×N matrix XR % Upper triangular part excluding the diagonal a % True for each column if it contains at least one true entry f % Get indices of true values X< % Take minimum. Implicitly display ``` [Answer] # JavaScript, ~~77~~ 73 bytes ``` n=>{p={};for(i=n;i--;p[i]=2);while(--p[n*Math.random()|0])i++;return i+2} ``` **Explanation** ``` var f = (n) => { var index; // used first to initialize pile, then as counter var pile = {}; // sock pile // start with index = n // check that index > 0, then decrement // put 2 socks in pile at index for(index = n; index--; pile[index] = 2); // index is now -1, reuse for counter // pick random sock out of pile and decrement its count // continue loop if removed sock was not the last while(--pile[n * Math.random() | 0]) { index++; // increment counter } // loop finishes before incrementing counter when first matching pair is removed // add 1 to counter to account for initial value of -1 // add 1 to counter to account for drawing of first matching pair return index + 2; }; ``` [Answer] ## CJam, 17 bytes ``` ri,2*mr{L+:L(&}#) ``` [Test it here.](http://cjam.aditsu.net/#code=ri%2C2*mr%7BL%2B%3AL(%26%7D%23)p&input=7) [Answer] # Python 3, ~~142~~ ~~105~~ 104 bytes Thanks to *Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ* for saving one byte! My first answer: ``` import random i=[x/2 for x in range(int(2*input()))] d=[] a=0 random.shuffle(i) while 1: b=i.pop() if b in d: print(a) s d=d+[b] a+=1 ``` My new answer: ``` from random import* i=range(int(input()))*2 shuffle(i) j=0 for x in i: if x in i[:j]:print(1+j)+s j+=1 ``` Both exit with a `NameError` on `s`. [Answer] # R, 49 ``` N=scan();which(duplicated(sample(rep(1:N,2))))[1] ``` I'm sure there must be a better way of doing this in R! I tried doing something cleverer but it didn't work. Edit: Improved by @bouncyball since it doesn't have to be a function. [Answer] # Python 2, 101 bytes ``` from random import* d=[] p=range(input())*2 shuffle(p) while list(set(d))==d:d+=p.pop(), print len(d) ``` [Answer] ## VBA, 61 bytes ``` Function K(D):While 2*D-K>K/Rnd:K=K+1:Wend:K=K+1:End Function ``` - models the shifting probability of sock match given previous failure to match. At the point of evaluation, K is "socks in hand", so draw number is one more. [Answer] # Pyth, 14 bytes ``` lhfnT{T._.S*2S ``` Explanation: ``` ._ #Start with a list of all prefixes of .S #a randomly shuffled *2S #range from 1 to input (implicit), times 2. f #filter this to only include elements where nT{T #element is not equal to deduplicated self (i.e. it has duplicates) lh #print the length of the first element of that filtered list ``` ]
[Question] [ If you don't know what the [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) is, I'll explain it briefly: There are three rods and some discs each of which has a different size. In the beginning all discs are on the first tower, in sorted order: The biggest one is at the bottom, the smallest at the top. The goal is to bring all the discs over to the third rod. Sounds easy? Here's the catch: You can't place a disc on top of a disc that is smaller than the other disc; you can only hold one disc in your hand at a time to move them to another rod and you can only place the disc on rods, not on the table, you sneaky bastard. ### ascii example solution: ``` A B C | | | _|_ | | __|__ | | A B C | | | | | | __|__ _|_ | A B C | | | | | | | _|_ __|__ A B C | | | | | _|_ | | __|__ ``` # Challenge There are three rods called A,B and C. (You can also call them 1,2 and 3 respectivly if that helps) In the beginning all n discs are on rod A(1). Your challenge is to verify a solution for the tower of hanoi. You'll need to make sure that: 1. In the end all n discs are on rod C(3). 2. For any given disc at any given state there is no smaller disc below it. 3. No obvious errors like trying to take discs from an empty rod or moving discs to nonexistant rods. (the solution does not have to be optimal.) # Input Your program will receive two inputs: 1. The number of discs n (an integer) 2. The moves which are taken, which will consist of a set of tuples of: (tower to take the currently uppermost disc from),(tower to take this disc to) where each tuple refers to a move. You can choose how they are represented. For example something like the following ways of representing the solution for n=2 which I've drawn in ascii above. (I'll use the first one in the test cases, because it's easy on the eyes): "A->B ; A->C ; B->C" [("A","B"),("A","C"),("B","C")] [(1,2),(1,3),(2,3)] "ABACBC" [1,2,1,3,2,3] # Output * Truthy, if the conditions that can be found under "challenge" hold. * Falsy, if they don't. # Test cases: ### True: ``` n=1, "A->C" n=1, "A->B ; B->C" n=2, "A->B ; A->C ; B->C" n=2, "A->C ; C->B ; A->C ; B->C" n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C" ``` ### False: *3rd one suggested by @MartinEnder, 7th by @Joffan* ``` n=1, "A->B" n=1, "C->A" n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=2, "A->B ; A->C ; C->B" n=2, "A->C ; A->B ; C->B ; B->A" n=2, "A->C ; A->C" n=3, "A->B ; A->D; A->C ; D->C ; A->C" n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C" n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C" ``` This is [code-golf](https://codegolf.stackexchange.com/questions/tagged/code-golf), shortest solution wins. Standard rules and loopholes apply. No batteries included. [Answer] ## [Retina](https://github.com/m-ender/retina), ~~167~~ ~~165~~ ~~157~~ ~~150~~ 123 bytes This totally looks like a challenge that should be solved with a single regex... (despite the header saying "Retina", this is just a vanilla .NET regex, matching valid inputs). ``` ^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?!\3|\4)1 ``` Input format is the list of instructions of the form `AB`, followed by `n` in unary using the digit `1`. There are no separators. Output is `1` for valid and `0` for invalid. [Try it online!](http://retina.tryitonline.net/#code=JWBeKD89XEQqKCg_PSg_PDM-MSspKTEpKykoKD89QSg_PDEtMz4uKyl8Qig_PDEtND4uKyl8Qyg_PDEtNT4uKykpLig_PUEuKig_IVwzKShcMSl8Qi4qKD8hXDQpKFwxKXxDLiooPyFcNSkoXDEpKS4pKyg_IVwzfFw0KTE&input=QUMxCkFCQkMxCkFCQUNCQzExCkFDQ0JBQ0JDMTEKQUNBQkNCQkFCQ0FDMTEKQUNBQkNCQUNCQUJDQUMxMTEKQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDMTExMQpBQjEKQ0ExCkFCQUNDQjExCkFDQUJDQkJBMTEKQUNBQzExCkFDQUNBQkNCQUNCQUJDQUMxMTEKQUNBQkNCQUJCQ0JBQkNBQzExMQpBQ0FCQ0JBQ0JBQkNDQjExMQpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDMTExMQpBQkFCQUJBQ0JDQkNCQzExMTE) (The first two characters enable a linefeed-separated test suite.) Alternative solution, same byte count: ``` ^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?<-5>1)+$ ``` This can possibly be shortened by using `1`, `11` and `111` instead of `A`, `B` and `C` but I'll have to look into that later. It might also be shorter to split the program into several stages, but where's the challenge in that? ;) ### Explanation This solution makes heavy use of .NET's balancing groups. For a full explanation [see my post on Stack Overflow](https://stackoverflow.com/a/17004406/1633117), but the gist is that capturing groups in .NET are stacks, where each new capture pushes another substring and where it's also possible to pop from such a stack again. This lets you count various quantities in a string. In this case it lets us implement the three rods directly as three different capturing groups where each disc is represented by a capture. To move discs around between rods we make use of a weird quirk of the `(?<A-B>...)` syntax. Normally, this pops a capture from stack `B` and pushes onto stack `A` the string between that popped capture and the beginning of this group. So `(?<A>a).(?<B-A>c)` matched against `abc` would leave `A` empty and `B` with `b` (as opposed to `c`). However, due to .NET variable-length lookbehinds it's possible for the captures of `(?<A>...)` and `(?<B-A>...)` to overlap. For whatever reason, if that's the case, the *intersection* of the two groups is pushed onto `B`. I've detailed this behaviour in the "advanced section" on balancing groups [in this answer](https://stackoverflow.com/a/36047989/1633117). On to the regex. Rods `A`, `B` and `C` correspond to groups `3`, `4` and `5` in the regex. Let's start by initialising rod `A`: ``` ^ # Ensure that we start at the beginning of the input. (?= # Lookahead so that we don't actually move the cursor. \D* # Skip all the instructions by matching non-digit characters. ( # For each 1 at the end of the input... (?=(?<3>1+)) # ...push the remainder of the string (including that 1) # onto stack 3. 1)+ ) ``` So e.g. if the input ends with `111`, then group 3/rod `A` will now hold the list of captures `[111, 11, 1]` (the top being on the right). The next bit of the code has the following structure: ``` ( (?=A...|B...|C...). (?=A...|B...|C...). )+ ``` Each iteration of this loop processes one instruction. The first alternation pulls a disc from the given rod (onto a temporary group), the second alternation puts that that disc onto the other given rod. We'll see in a moment how this works and how we ensure that the move is valid. First, taking a disc off the source rod: ``` (?= A(?<1-3>.+) | B(?<1-4>.+) | C(?<1-5>.+) ) ``` This uses the weird group-intersection behaviour I've described above. Note that group `3`, `4` and `5` will always hold substrings of `1`s at the end of the string whose length corresponds to the disc's size. We now use `(?<1-N>.+)` to pop the top disc off stack `N` and push the intersection of this substring with the match `.+` onto stack `1`. Since `.+` always necessarily covers the entire capture popped off `N`, we know that this simply moves the capture. Next, we put this disc from stack `1` onto the stack corresponding to the second rod: ``` (?= A.*(?!\3)(\1) | B.*(?!\4)(\1) | C.*(?!\5)(\1) ) ``` Note that we don't have to clean up stack `1`, we can just leave the disc there, since we'll put a new one on top before using the stack again. That means we can avoid the `(?<A-B>...)` syntax and simply copy the string over with `(\1)`. To ensure that the move is valid we use the negative lookahead `(?!\N)`. This ensures that, from the position where we want to match the current disc, it's impossible to match the disc already on stack `N`. This can only happen if either a) `\N` will never match because the stack is completely empty or b)`the disc on top of stack`N`is larger than the one we're trying to match with`\1`. Finally, all that's left is ensuring that a) we've matched all instructions and b) rods `A` and `B` are empty, so that all discs have been moved onto `C`. ``` (?!\3|\4)1 ``` We simply check that neither `\3` nor `\4` can match (which is only the case if both are empty, because any actual disc *would* match) and that we can then match a `1` so that we haven't omitted any instructions. [Answer] # Java "only" ~~311 272 263 261 260 259~~ 256 bytes Saved ~~39~~ countless bytes due to @Frozn noticing an older debug feature as well as some clever golfing tricks. Golfed version ``` int i(int n,int[]m){int j=0,k=0,i=n;Stack<Integer>t,s[]=new Stack[3];for(;j<3;)s[j++]=new Stack();for(;i-->0;)s[0].push(i);for(;k<m.length;k+=2)if((t=s[m[k+1]]).size()>0&&s[m[k]].peek()>t.peek())return 0;else t.push(s[m[k]].pop());return s[2].size()<n?0:1;} ``` ungolfed with explanation and pretty printed stacks at each step ``` /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package codegolf; /** * * @author rohan */ import java.util.Arrays; import java.util.Stack; public class CodeGolf { //golfed version int i(int n,int[]m){int j=0,k=0,i=n;Stack<Integer>[] s=new Stack[3];for(;j<3;j++)s[j]=new Stack();for(;i-->0;)s[0].push(i);for(;k<m.length;System.out.println(Arrays.toString(s)),k+=2)if(!s[m[k+1]].isEmpty()&&s[m[k]].peek()>s[m[k+1]].peek())return 0;else s[m[k+1]].push(s[m[k]].pop());return s[2].size()==n?1:0;} /** Ungolfed * 0 as falsy 1 as truthy * @param n the number of disks * @param m represents the zero indexed stacks in the form of [from,to,from,to] * @return 0 or 1 if the puzzle got solved, bad moves result in an exception */ int h(int n, int[] m) { //declarations int j = 0, k = 0, i = n; //create the poles Stack<Integer>[] s = new Stack[3]; for (; j < 3; j++) { s[j] = new Stack(); } //set up the first tower using the "downto operator for (; i-- > 0;) { s[0].push(i); } //go through and perform all the moves for (; k < m.length; System.out.println(Arrays.toString(s)), k += 2) { if (!s[m[k + 1]].isEmpty() && s[m[k]].peek() > s[m[k + 1]].peek()) { return 0;//bad move } else { s[m[k + 1]].push(s[m[k]].pop()); } } return s[2].size() == n ? 1 : 0;// check if all the disks are done } /** * @param args the command line arguments */ public static void main(String[] args) { //test case System.out.println( new CodeGolf().h(3,new int[]{0,2,0,1,2,1,0,2,1,0,1,2,0,2})==1?"Good!":"Bad!"); } } ``` The ungolfed version has a feature where it will print out what the stacks look like at each step like so... ``` [[2, 1], [], [0]] [[2], [1], [0]] [[2], [1, 0], []] [[], [1, 0], [2]] [[0], [1], [2]] [[0], [], [2, 1]] [[], [], [2, 1, 0]] Good! ``` [Answer] # Python 2, ~~186~~ ~~167~~ ~~158~~ ~~135~~ ~~127~~ ~~115~~ ~~110~~ 102 bytes ``` n,m=input() x=[range(n),[],[]] for a,b in m:p=x[a].pop();e=x[b];e and 1/(p>e[-1]);e+=p, if x[0]+x[1]:_ ``` Takes input on STDIN in the following format: ``` (1,[(0,1),(1,2)]) ``` That is, a Python tuple of the number of discs and a Python list of tuples of `(from_rod,to_rod)`. As in Python, the surrounding parentheses are optional. Rods are zero-indexed. For example, this test case: ``` n=2; "A->B ; A->C ; B->C" ``` would be given as: ``` (2,[(0,1),(0,2),(1,2)]) ``` If the solution is valid, outputs nothing and exits with an exit code of 0. If it is invalid, throws an exception and exits with an exit code of 1. Throws an `IndexError` if moving to a nonexistant rod or trying to take a disc off a rod that has no discs on it, a `ZeroDivisionError` if a disc is placed on top of a smaller disc, or a `NameError` if there are discs left on the first or second rods at the end. *Saved 13 bytes thanks to @KarlKastor!* *Saved 8 bytes thanks to @xnor!* [Answer] # [Retina](https://github.com/m-ender/retina), ~~84~~ 80 Bytes -5 bytes thanks to Martin Ender ``` ~ ~$' $ ABC {`^(.)(.*)( ~+)\1 $3$2$1 }`^(\W+)(\w)(.*)(?<=\1~+|\w)\2 $3$1$2 ^AB ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAp-CiB-JCcKJApBQkMKe2BeKC4pKC4qKSggfispXDEKJDMkMiQxCn1gXihcVyspKFx3KSguKikoPzw9XDF-K3xcdylcMgokMyQxJDIKXkFCIA&input=QUN-CkFCQkN-CkFCQUNCQ35-CkFDQ0JBQ0JDfn4KQUNBQkNCQkFCQ0FDfn4KQUNBQkNCQUNCQUJDQUN-fn4KQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDfn5-fgpBQn4KQUNBQ34KQUNCQ34KQ0F-CkFCQUNDQn5-CkFDQUJDQkJBfn4KQUNBQ35-CkFDQUNBQkNCQUNCQUJDQUN-fn4KQUNBQkNCQUJCQ0JBQkNBQ35-fgpBQ0FCQ0JBQ0JBQkNDQn5-fgpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDfn5-fgpBQkFCQUJBQ0JDQkNCQ35-fn4KQUJBQn4KQUNBQkNCQUNCQUJDQUNDQUNBfn5-) (plus 5 bytes for line-by-line tests) The code simulates a full game. * Input is given as `ACABCBACBABCAC~~~`. `~~~` means three discs. * First four lines convert the input to the game format: `ACABCBACBABCAC ~~~ ~~ ~ABC`. In the beginning the A rod has all 3 discs, and B and C rods are empty. * Next we have a loop of two steps: + Take the first letter in the line, which indicates the next source rod. Find this rod, and take the last disc on in. Remove the letter and move the disc to the stark (pick it up). In out example, after the first step, the text will look like: `~CABCBACBABCAC ~~~ ~~ABC`. + In the second stage we find the target rod, and move the disc there. We validate the rod is empty, or has a bigger disc at the top: `ABCBACBABCAC ~~~ ~~AB ~C`. * Finally we confirm the A and B rods are empty - this means all discs are in C (there's an extra space at the last line). [Answer] # Python 2.7, ~~173~~ ~~158~~ ~~138~~ ~~130~~ ~~127~~ 123 bytes: ``` r=range;a,b=input();U=[r(a,0,-1),[],[]] for K,J in b:U[J]+=[U[K].pop()]if U[J]<[1]or U[K]<U[J]else Y print U[-1]==r(a,0,-1) ``` Takes input through the stdin in the format `(<Number of Discs>,<Moves>)` where `<Moves>` is given as an array containing tuples corresponding to each move, which each contain a pair of comma separated integers. For instance, the test case: ``` n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" ``` given in the post would be given as: ``` (3,[(0,2),(0,1),(2,1),(0,2),(1,0),(1,2),(0,2)]) ``` to my program. Outputs an `IndexError` if the 3rd condition isn't met, a `NameError` if the 2nd condition isn't met, and `False` if the 1st condition isn't met. Otherwise outputs `True`. [Answer] # VBA, ~~234~~ ~~217~~ ~~213~~ 196 bytes ``` Function H(N,S) ReDim A(N) While P<Len(S) P=P+2:F=1*Mid(S,P-1,1):T=1*Mid(S,P,1) E=E+(T>2):L=L+T-F For i=1 To N If A(i)=F Then A(i)=T:Exit For E=E+(A(i)=T)+(i=N) Next Wend H=L+9*E=2*N End Function ``` Input format for moves is a string with an even number of digits (012). Invocation is in spreadsheet, =H([number of discs], [move string]) The array A holds the rod position of the various discs. A move is simply updating the first occurrence of the "From" rod number into the "To" rod number. If you encounter a "To" rod disc first, or no "From" rod disc, it's an invalid move. The total "rod value" of A is held in L, which needs to end at 2N. Errors are accumulated as a negative count in E. In common with other solutions, "moving" a disc from a tower to the same tower is not forbidden. I could forbid it for another 6 bytes. ## Results Function result in first column (the last n=3 case is my addition using an extra rod). ``` TRUE 1 02 TRUE 1 0112 TRUE 2 010212 TRUE 2 02210212 TRUE 2 020121101202 TRUE 3 02012102101202 TRUE 4 010212012021010212102012010212 FALSE 1 01 FALSE 1 20 FALSE 2 02012102101202 FALSE 2 010221 FALSE 2 02012110 FALSE 2 0202 FALSE 3 0202012102101202 FALSE 3 0201210112101202 FALSE 3 02012102101221 FALSE 3 0103023212 FALSE 4 0102120120210102121020120102 FALSE 4 01010102121212 ``` [Answer] # php, 141 bytes ``` <?php $a=$argv;for($t=[$f=range($a[++$i],1),[],[]];($r=array_pop($t[$a[++$i]]))&&$r<(end($t[$a[++$i]])?:$r+1);)$t[$a[$i]][]=$r;echo$t[2]==$f; ``` Command line script, takes input as the height then a series of array indexes (0 indexed) e.g. 1 0 2 or 2 0 1 0 2 1 2 for the 1 or 2 height shortest test cases. Echos 1 on true cases and nothing on false ones. Gives 2 notices and 1 warning so needs to be run in an environment that silences those. [Answer] # JavaScript (ES6), 108 ``` n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1] ``` **Input format:** function with 2 arguments * arg 1, numeric, number of rings * arg 2, array of strings, each string 2 characters '0','1','2' **Output:** return 1 if ok, 0 if invalid, exception if nonexisting rod **Less golfed** and explained ``` n=>a=>( // rods status, rod 0 full with an array n..1, rod 1 & 2 empty arrays s = [ [...Array(t=n)].map(_=>t--), [], [] ], // for each step in solution, evaluate function and stop if returns true err = a.some( ([x,y]) => { v = s[x].pop(); // pull disc from source rod // exception is s[x] is not defined if (!v) return 1; // error source rod is empty l = s[y].push(v); // push disc on dest rod, get number of discs in l // exception is s[y] is not defined if(s[y][l-2] < v) return 1; // error if undelying disc is smaller }), err ? 0 // return 0 if invalid move : s[2][n-1]; // il all moves valid, ok if the rod 2 has all the discs ) ``` **Test** Note: the first row of the Test function is needed to convert the input format given in the question to the input expected by my function ``` F= n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1] Out=x=>O.textContent+=x+'\n' Test=s=>s.split`\n`.map(r=>[+(r=r.match(/\d+|.->./g)).shift(),r.map(x=>(parseInt(x[0],36)-10)+''+(parseInt(x[3],36)-10))]) .forEach(([n,s],i)=>{ var r try { r = F(+n)(s); } catch (e) { r = 'Error invalid rod'; } Out(++i+' n:'+n+' '+s+' -> '+r) }) Out('OK') Test(`n=1, "A->C" n=1, "A->B ; B->C" n=2, "A->B ; A->C ; B->C" n=2, "A->C ; C->B ; A->C ; B->C" n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"`) Out('\nFail') Test( `n=1, "A->B" n=1, "C->A" n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=2, "A->B ; A->C ; C->B" n=2, "A->C ; A->B ; C->B ; B->A" n=2, "A->C ; A->C" n=3, "A->B ; A->D; A->C ; D->C ; A->C" n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C" n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"`) ``` ``` <pre id=O></pre> ``` ]
[Question] [ Write a program or function that outputs an `L` if run on a little endian architecture or a `B` if run on a big endian architecture. Lower case output `l` or `b` is also acceptable. There is no input. Scoring is code golf, so the code with the fewest bytes wins. **Edit:** *As per the comments below, I am clarifying that the entry must be able to run on either architecture.* *I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.* [Answer] # Python, 33 bytes ``` import sys exit(sys.byteorder[0]) ``` `sys.byteorder` is either `'little'` or `'big'` (and for those of you who will read this sentence without looking at the code, `[0]` means take the first character). [Answer] # C, 26 bytes ``` a=66<<24|76;f(){puts(&a);} ``` Assumes 32-bit `int` and ASCII characters. Tested on amd64 (little-endian) and mips (big-endian). # GCC, 23 bytes ``` 00000000: 613d 2742 0000 4c27 3b66 2829 7b70 7574 a='B..L';f(){put 00000010: 7328 2661 293b 7d s(&a);} ``` Suggested by feersum. The value of multi-character constants is implementation-dependent, but this seems to work in GCC. Tested on the same architectures. [Answer] # MATLAB / Octave, 24 bytes ``` [~,~,e]=computer;disp(e) ``` The [`computer`](http://es.mathworks.com/help/matlab/ref/computer.html) function gives information about, well, the computer it's running on. The third output is endianness: `L` or `B` for little- or big-endian respectively. [Try it on Ideone](http://ideone.com/FpfrEb). [Answer] # JavaScript ES6, 50 bytes ``` _=>"BL"[new Int8Array(Int16Array.of(1).buffer)[0]] ``` I don’t know who decided it was a good idea for [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) objects to expose the native endianness of the interpreter, but here we are. [Answer] # C, ~~36~~ 35 bytes **1 byte thanks to @algmyr and @owacoder.** ``` ~~main(a){printf(\*(char\*)&a?"L":"B");}~~ main(a){putchar(66+10**(char*)&a);} main(a){putchar("BL"[*(char*)&a]);} ``` * Version 1: [Ideone it!](http://ideone.com/uWicng) * Version 2: [Ideone it!](http://ideone.com/OjpPrP) * Version 3: [Ideone it!](http://ideone.com/DzmxIa) Credits [here](https://stackoverflow.com/a/4181991/6211883). Untested since I don't have a big-endian machine. [Answer] ### Mathematica, 22 ``` {B,L}[[$ByteOrdering]] ``` This probably breaks some rule about not using a built-in function but I'm not really interested in rube goldberging an alternative. [Answer] # C, 27 One byte longer, but here it is anyway: ``` f(){putchar(htons(19522));} ``` [Answer] # PowerPC machine code - 20 bytes PowerPC is bi-endian (the endianness can be set up at startup), so this code should conform to the challenge request of being able to run both on BE and LE machines. This is a function that *returns*1 `'L'` or `'B'` depending on the endianness currently set. As a function, AFAICT it conforms the SVR4 PowerPC ABI (used by Linux on ppc32), the PowerOpen ABI (used e.g. by AIX) and the OS X ABI. In particular, it relies just on the fact that GPR 0 is a volatile scratch register, and GPR 3 is used to return "small" values. ``` 00000000 <get_endian>: 0: 7c 00 00 a6 mfmsr r0 4: 54 03 0f fe rlwinm r3,r0,1,31,31 8: 1c 63 00 0a mulli r3,r3,10 c: 38 63 00 42 addi r3,r3,66 10: 4e 80 00 20 blr ``` Now, it goes like this: * the [MSR](https://en.wikipedia.org/wiki/Machine_state_register) is read into GP register 0; the MSR contains at bit 31 the endianness settings (0 = big endian; 1 = little endian); * `rlwinm` extracts just that bit: it takes the value in GPR0, **r**otates **l**eft by 1 place (so that now is in position 0) and **m**asks it with 1 (the mask generated by those 31,312); the result is put into GP register 3; * multiply the result by 10 and sum 66 (`'B'`) (10 is the difference between `'L'` and `'B'`) * finally, return to the caller --- ### Notes 1. yep, the question does ask to *print*, but it's not clear how I should print stuff in assembly expected to run unmodified on different operating systems. =) 2. for those interested, see the [rlwinm](https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/com.ibm.aix.alangref/idalangref_rlwinm_rlinm_rtlwrdimm_instrs.htm) documentation; knowing next to nothing about PowerPC, I found this kind of instructions extremely interesting. **2018 update**: Raymond Chen is publishing a series about the PowerPC architecture, you can find [here](https://blogs.msdn.microsoft.com/oldnewthing/20180810-00/?p=99465) his great post about `rlwinm` & friends. [Answer] # Java 8, ~~96, 64~~ 52 bytes ``` ()->(""+java.nio.ByteOrder.nativeOrder()).charAt(0); ``` A golf based on [this SO answer](https://stackoverflow.com/a/9431652). All credit goes to @LeakyNun and @AlanTuning. Java keeps the loosing streak. 96 bytes: ``` char e(){return java.nio.ByteOrder.nativeOrder().equals(java.nio.ByteOrder.BIG_ENDIAN)?'b':'l';} ``` 64 bytes: ``` char e(){return(""+java.nio.ByteOrder.nativeOrder()).charAt(0);} ``` Untested b/c I don't have access to a big-endian machine. [Answer] # Perl, ~~38~~ 36 bytes ``` say+(pack"L",1 eq pack"V",1)?"L":"B" ``` Works by packing a number in the system's default byte order and comparing it to a number packed in little-endian byte order. [Answer] # (G)Forth, 24 bytes ``` here $4200004C , c@ emit ``` Assumes that cells are 32 bits (and that your Forth interpreter supports Gforth's [base prefixes](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Number-Conversion.html#fnd-2)). It simply stores the number 0x4200004C in memory and then displays the byte at the low end. [Answer] # C, 34 bytes This assumes ASCII character encoding ``` main(a){putchar(66+10**(char*)a);} ``` Call without argument. Explanation: On call, `a` will be 1. `*(char*)a` accesses the first byte of `a`, which on little-endian platforms will be 1, on big-endian platforms will be 0. On big-endian platforms, this code will therefore pass 66 + 10\*0 = 66 to `putchar`. 66 is the ASCII code for `B`. On little-endian platforms, it will pass 66 + 10\*1 = 76, which is the ASCII code for `L`. [Answer] # C#, 60 52 bytes C# is surprisingly competitive in this one. ``` char e=>System.BitConverter.IsLittleEndian?'L':'B'; ``` Credits to Groo for the C#6 syntax. 60 bytes: ``` char e(){return System.BitConverter.IsLittleEndian?'L':'B';} ``` [Answer] # Julia, ~~24~~ 19 bytes ``` ()->ntoh(5)>>55+'B' ``` This is an anonymous function that takes no input and returns a `Char`. To call it, assign it to a variable. It assumes that integers are 64-bit. The `ntoh` function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, `ntoh` is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so `ntoh(5) == 360287970189639680`. Which is also, perhaps more readably, equal to: `0000010100000000000000000000000000000000000000000000000000000000` in binary. If we right bit shift the result of `ntoh(5)` by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant `'B'`, we'll get `'B'` or `'L'` for big or little endian machines, respectively. Saved 5 bytes thanks to FryAmTheEggman and Dennis! [Answer] # PHP 5.6, ~~41~~ 31 bytes (thx to isertusernamehere) `<?=unpack(S,"\x01\x00")[1]-1?B:L;` # PHP 7, 41 bytes `echo unpack('S',"\x01\x00")[1]-1?'B':'L';` Idea stolen from: <https://stackoverflow.com/a/24785578/2496717> [Answer] ## Common Lisp, 27 bytes *Tested on SBCL and ECL. For a portable approach, one should use [trivial-features](https://github.com/trivial-features/trivial-features/blob/master/SPEC.md).* ``` (lambda()'L #+big-endian'B) ``` The `#+` notation is a [read-time condition](http://clhs.lisp.se/Body/01_ebaa.htm), that *reads* the next form only if the conditional expression evaluates to true. Here the condition is the whole `#+big-endian` text which means that the test is satisfied if the `:big-endian` keyword belongs to the [`*FEATURES*`](http://clhs.lisp.se/Body/v_featur.htm) list (a list which contains among other things platform-specific information). The following expression is `'B`, which is either read or skipped according to the outcome of the test. If your platform is big-endian and you write the above form in the REPL, it is exactly as if you wrote the following: ``` CL-USER>(lambda()'L 'B) ``` (NB.`CL-USER>` is the prompt) A function's body is an implicit [`PROGN`](http://clhs.lisp.se/Body/s_progn.htm), meaning that only the evaluation of the last expression is returned. So the above actually returns symbol ̀`B`. If however the read-time condition evaluates to false, the form reads as if you wrote: ``` CL-USER>(lambda()'L) ``` ... which simply returns symbol `L`. [Answer] ## ARMv6 and later: 20 bytes machine code ``` 0xE10F1000 : MRS r0,CPSR ; read current status register 0xE3110C02 : TST r0,#1<<9 ; set Z flag if bit 9 set 0x03A0004C : MOVEQ r0,#'L' ; return 'L' if Z clear 0x13A00042 : MOVNE r0,#'B' ; return 'B' if Z set 0xEBxxxxxx : BL putchar ; print it (relative branch) ``` Untested, as I don't have a suitable machine to hand. Bit 9 of the CPSR gives the current load/store endianness. [Answer] # Perl 5, 21 + 1 = 22 bytes Run with `perl -E`. ``` say ord pack(S,1)?L:B ``` Tested on amd64 (little-endian) and mips (big-endian). [Answer] # R, ~~28~~ 23 bytes ``` substr(.Platform$endian,1,1) ``` `.Platform$endian` returns `big` if run on big endian and `little` if on little. Here, using `substr`, it returns the first letter of the output, so either `b` or `l`. As `endian` is the only object starting with an `e` contained in object `.Platform` we can reduce it thanks to partial matching to the following 23 bytes code: ``` substr(.Platform$e,1,1) ``` [Answer] # Clojure, ~~46~~ 44 bytes ``` #(nth(str(java.nio.ByteOrder/nativeOrder))0) ``` This is a function that uses the Java builtin to get the endianness of the machine. Then get the string representation of it which will be either `"LITTLE_ENDIAN"` or `"BIG_ENDIAN"` and take the first character of whichever string is chosen and return that. Saved 2 bytes thanks to @[cliffroot](https://codegolf.stackexchange.com/users/53197/cliffroot). [Answer] # Ruby, ~~31~~30 chars. ``` puts [1].pack("s")>"\01"??L:?B ``` Hmm, must be a better way. Count 5 characters less if the char need not to be output as I think other solutions omit printing. i.e. remove the "puts " part if you don't want anything printed. [Answer] # Bash (and other unix shells), 32 (33) bytes First and second attempt: ``` case `echo|od` in *5*)echo B;;*)echo L;;esac # portable [[ `echo|od` =~ 5 ]]&&echo B||echo L # non-portable ``` Thanks to Dennis, shorter version: ``` od<<<a|grep -q 5&&echo L||echo B # non-portable echo|od|grep -q 5&&echo B||echo L # portable ``` The `echo` utility outputs a newline, with hex value `0A`, and no other output. For `<<<a` it is `61 0A`. The `od` utility, by default, interprets the input as two-byte words, zero-padded if the number of bytes is odd, and converts to octal. This results in the output of echo being interpred as `0A 00`, which is converted to `005000` as big-endian or `000012` in little-endian. `61 0A` becomes `005141` in little-endian and `060412` in big-endian. The full output of od also includes address and size data meaning we cannot use `0`, `1`, or `2` for the test. The command is well-defined to expose the system's endianness. From [the standard](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/od.html): > > The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system. > > > ## Compatibility notes I am not certain if putting `echo|od` in backquotes with no double quotes around them [which results in a three-word argument to `case`] is supported on all systems. I am not certain if all systems support shell scripts with no terminating newline. I am mostly certain but not 100% of the behavior of od with adding the padding byte on big-endian systems. If needed, `echo a` can be used for the portable versions. All of the scripts work in bash, ksh, and zsh, and the portable ones work in dash. [Answer] ## PHP, 16 bytes ``` <?=pack(S,14)^B; ``` This uses two tricks not used in the two existing PHP answers: 1. The value passed to pack() or unpack() can be anything, not just 0 or 1. 2. The bitwise XOR operator (`^`) works on strings, and the result is only as long as the shorter string, avoiding the need for a string indexing or ternary operator. [Answer] # Node, 42 bytes ``` n=>require('os').endianness()[0] ``` Pro: there's a builtin. Con: property names are very long [Answer] # PowerShell, 44 bytes ``` [char](66+10*[BitConverter]::IsLittleEndian) ``` Character 66 is `B`, and 10 characters later is number 76, `L`. A Boolean value of "true" becomes `1` when cast to a number. `BitConverter` is a standard .NET class. [Answer] ## Bash, 27 bytes ``` iconv -tucs2<<<䉌|head -c1 ``` `䉌` ([U+424C](http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=424C)) is encoded as three UTF-8 bytes: `E4 89 8C`. It is assumed that `iconv` uses the function from glibc and that a UTF-8 locale is used. [Answer] # Racket, ~~35~~ 28 bytes ``` (if(system-big-endian?)'B'L) ``` `'B` or `'L` respectively. Let me know if this is not specific enough :) [Answer] # PHP, 22 bytes ``` <?=ord(pack(S,1))?L:B; ``` [Answer] ## Haskell (using GHC-only size-restricted numeric types), 75 bytes ``` import Unsafe.Coerce import GHC.Int f="BL"!!fromEnum(unsafeCoerce 1::Int8) ``` (not tested on a big-endian architecture, but it seems like it *ought* to work!) [Answer] ## K, 15 bytes ``` ("bl")@*6h$-8!` ,"l" ``` Explanation; ``` From right to left; -8!` /serialises the back tick and returns (0x010000000a000000f500) 6h$-8!` /This casts the result to `int which is type 6h(could have used `int$-8!`) - the result is (1 0 0 0 10 0 0 0 245 0i) *6h$-8!` /* means first, we take the first item which is 1. Since it will be either 1 or 0, we can use it to index (@) into the two element list on the left i.e. ("bl")1 returns "l" and ("bl")0 returns b ``` ]
[Question] [ In the popular (and essential) computer science book, *An Introduction to Formal Languages and Automata* by Peter Linz, the following formal language is frequently stated: $$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$ mainly because this language can not be processed with finite-state automata. This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero". # Challenge Write a working program/function which gets a string, **containing "a"s and "b"s only**, as input and **returns/outputs a truth value**, saying if this string **is valid the formal language L.** * Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities. * Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. [More info here.](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) * Standard code golf rules apply. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Good luck! ### Truthy test cases ``` "ab" "aabb" "aaabbb" "aaaabbbb" "aaaaabbbbb" "aaaaaabbbbbb" ``` ### Falsy test cases ``` "" "a" "b" "aa" "ba" "bb" "aaa" "aab" "aba" "abb" "baa" "bab" "bba" "bbb" "aaaa" "aaab" "aaba" "abaa" "abab" "abba" "abbb" "baaa" "baab" "baba" "babb" "bbaa" "bbab" "bbba" "bbbb" ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 85994; // 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 = 48934; // 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,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); 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; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="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] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÇÂs{αß ``` Only `1` is truthy in 05AB1E, and it'll output `0` (or `""` for the empty string) as falsey. [Try it online](https://tio.run/##yy9OTMpM/f//cPvhpuLqcxsPz///PxEEkkAAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@2Hm4qrz208PP@/zv9opcQkJR2lxMQkCAWkoQwQC8YEs@EcCA/EBYkAMUQGxAATUIUQY0EkWBhiQxJUHZgNVQ4zGOoAiD6IlkQoBTEGZg7UIIhJEKMgGpKglkBtgVkDsydJKRYA). **Explanation:** ``` Ç # Convert the (implicit) input-string to a list of integer codepoints # i.e. "aaabbb" → [97,97,97,98,98,98] # i.e. "baba" → [98,97,98,97] # i.e. "aab" → [97,97,98] # i.e. "" → [] Â # Bifurcate this list (short for Duplicate & Reverse copy) # STACK: [[97,97,97,98,98,98], [98,98,98,97,97,97]] # STACK: [[98,97,98,97], [97,98,97,98]] # STACK: [[97,97,98], [98,97,97]] # STACK: [[], []] s # Swap to get the duplicated list # STACK: [[98,98,98,97,97,97], [97,97,97,98,98,98]] # STACK: [[97,98,97,98], [98,97,98,97]] # STACK: [[98,97,97], [97,97,98]] # STACK: [[], []] { # Sort it # STACK: [[98,98,98,97,97,97], [97,97,97,98,98,98]] # STACK: [[97,98,97,98], [97,97,98,98]] # STACK: [[98,97,97], [97,97,98]] # STACK: [[], []] α # Take the absolute difference at the same positions # STACK: [[1,1,1,1,1,1]] # STACK: [[0,1,1,0]] # STACK: [[1,0,1]] # STACK: [[], []] ß # And take the minimum, which will be 1 if all were truthy; # 0 if any were falsey; or an empty string if the list is empty # STACK: [1] # STACK: [0] # STACK: [0] # STACK: [""] # (after which it is output implicitly as result) ``` [Answer] # Java 8, ~~69~~ 37 bytes ``` s->s.matches("(a(?=a*(\\2?+b)))+\\2") ``` Regex shamelessly 'borrowed' from [here](https://stackoverflow.com/a/3644267/1682559). -6 bytes thanks to *@Deadcode*, plus a bit more by converting Java 7 to 8 [Try it online.](https://tio.run/##PZBNb8IwDIbv/Aorp2RNI227gRiHnceF49jBCQHK2rRqTKVp4rd3cQKTIn/o9fNazgUnrC@H79m1GCN8YBN@FwBNID8e0XnYcgtg@771GMDJHY1NOEFUqyTcFilEQmocbCHAeo71WzQdkjv7KIVEuVnjk9zvXzaVVUpVqRJqXjE3XG2buDs@9c0BurT/vuHzC1CV5cd@lBOOQD7SO0YPSxBoNaLlkGJOnEuRK6s1au61TS8LTGhMLYM2KylnuYDZjad4BHNgoBAZYYYhHrHZJvsUo@JkhYlD25AUWiiVDwDY/UTynemvZIZ0HbVBPq6pxFJUAoQZ/eCR5PNr/ZBM68OJzjL9WzDun1D3v7/Nfw) **Explanation:** ``` s-> // Method with String parameters and boolean return-type s.matches("...") // Check if the String matches the regex explained below ``` *Regex explanation:* ``` ^ $ # (implicit by String#matches: match entire String) + # Repeat one or more times: ( ) # Capture group 1, which does: a # Match an 'a' (?= ) # With a positive look-ahead to: a* # 0 or more 'a's ( ) # Followed by, in capture group 2: \2 # The value of capture group 2, ?+ # zero or one times, giving prio to one, without backtracking b # Following by a 'b' \2 # Followed by the value of capture group 2 (the 'b's) ``` [Answer] # C (Ansi), ~~65~~ 75 Bytes ## Golfed: ``` l(b,i,j,k)char*b;{for(i=j=0;(k=b[i++])>0&k<=b[i];)j+=2*(k>97)-1;return !j;} ``` ## Explanation: Sets a value j and increments j on each b and decrements j on anything else. Checked if the letter before is less than or equal the next letter so prevent abab from working ## Edits Added checks for abab cases. [Answer] ## Batch, 133 bytes ``` @if ""=="%1" exit/b1 Fail if the input is empty @set a=%1 Grab the input into a variable for processing @set b=%a:ab=% Remove all `ab` substrings @if "%a%"=="%b%" exit/b1 Fail if we didn't remove anything @if not %a%==a%b%b exit/b1 Fail if we removed more than one `ab` @if ""=="%b%" exit/b0 Success if there's nothing left to check @%0 %b% Rinse and repeat ``` Returns an `ERRORLEVEL` of 0 on success, 1 on failure. Batch doesn't like to do substring replacement on empty strings, so we have to check that up front; if an empty parameter was legal, line 6 wouldn't be necessary. [Answer] ## PowerShell v2+, ~~61~~ 52 bytes ``` param($n)$x=$n.length/2;$n-and$n-match"^a{$x}b{$x}$" ``` Takes input `$n` as a string, creates `$x` as `half the length`. Constructions an `-and` Boolean comparison between `$n` and a `-match` regex operator against the regex of an equal number of `a`'s and `b`'s. Outputs Boolean `$TRUE` or `$FALSE`. The `$n-and` is there to account for `""`=`$FALSE`. ## Alternate, 35 bytes ``` $args-match'^(a)+(?<-1>b)+(?(1)c)$' ``` This uses the regex from [Leaky's answer](https://codegolf.stackexchange.com/a/86002/42963), based on .NET balancing groups, just encapsulated in the PowerShell `-match` operator. Returns the string for truthy, or empty string for falsey. [Answer] # Pyth - 13 bytes ``` &zqzS*/lz2"ab ``` Explained: ``` qz #is input equal to "ab #the string "ab" * #multiplied by /lz2 #length of input / 2 S #and sorted? &z #(implicitly) print if the above is true and z is not empty ``` [Answer] ## Haskell, 39 bytes ``` p x=elem x$scanl(\s _->'a':s++"b")"ab"x ``` Usage example: `p "aabb"` -> `True`. `scanl(\s _->'a':s++"b")"ab"x` build a list of all `["ab", "aabb", "aaabbb", ...]` with a total of `(length x)` elements. `elem` checks if `x` is in this list. [Answer] # Octave, 28 bytes ``` @(m)diff(+m)>=0&~sum(m-97.5) ``` This defines an anonymous function. It works also for empty input. Falsy and truthy are as described in [my MATL answer](https://codegolf.stackexchange.com/a/86018/36398). [**Try it at ideone**](http://ideone.com/yPySIn). ### Explanation `diff(+m)>0` checks if the input string (consisting of `'a'` and `'b'`) is sorted, that is, all characters `'a'` come before all `'b'`. The other condition that needs to be checked is whether the numbers of characters `'a'` and `'b'` are the same. Since their ASCII codes are `97` ansd `98`, this is done subtracting `97.5` and chacking if the the sum is zero. For empty input the result is empty, which is falsy. [Answer] # Mathematica ~~83~~ ~~80~~ ~~68~~ 54 bytes ``` #&@@@#<>""=="ab"&&Equal@@Length/@#&@*Split@*Characters ``` Thanks @MartinEnder for shortening it by 26 bytes :) If input can be a list of characters instead of a string, **39 bytes** is possible: ``` #&@@@#=={a,b}&&Equal@@Length/@#&@*Split ``` eg: ``` #&@@@#=={a,b}&&Equal@@Length/@#&@*Split@{a,b,a,b,a,b} (*False*) ``` [Answer] # Racket, 91 bytes ``` (λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr x)))(/(length x)2))) ``` Expects input in the form of a list of characters. If you really need to put it in as a raw string, that adds 21 extra characters (for **112** bytes): ``` (λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr(string->list x))))(/(string-length x)2))) ``` An even longer (102 bytes with list input) way, but I think it's creative so I'm leaving it here: ``` (λ(x)(and(eqv?(/(length x)2)(length(member #\b x)))(eqv?(length(remove-duplicates(member #\b x)))1))) ``` Explanation to follow. [Answer] ## JavaScript, 34 bytes ``` s=>(s=s.match`^a(.*)b$`[1])?f(s):1 ``` In true automata fashion, this function returns 1 if it's true, and fails if it's not. ``` f=s=>(s=s.match`^a(.*)b$`[1])?f(s):1 let test_strings = ["ab", "aabb", "", "a", "abb", "abc", "abab", "abba"]; test_strings.map(s => { try {console.log("f(\"" + s + "\") returned " + f(s));} catch(e) {console.log("f(\"" + s + "\") threw " + e);} }); ``` [Answer] # Excel, 55 bytes ``` =AND(A1<>"",A1=REPT("a",LEN(A1)/2)&REPT("b",LEN(A1)/2)) ``` Test string in cell A1, formula above in any other cell. Generates a comparison string of the appropriate length and checks for a match. Shows TRUE or FALSE as appropriate. [Answer] # PHP, ~~61~~ 40 bytes new approach inspired by [Didz´ answer](https://codegolf.stackexchange.com/questions/85994/count-of-as-and-bs-must-be-equal-did-you-get-it-computer/86300#86300): regexp with a recursive pattern ``` <?=preg_match('#^(a(?1)?b)$#',$argv[1]); ``` P.S.: I see now that I am not the first one with this pattern. You never stop learning. --- Josh´s [C solution](https://codegolf.stackexchange.com/questions/85994/count-of-as-and-bs-must-be-equal-did-you-get-it-computer/86014#86014) translated to PHP comes at the same size (with one byte lost in translation, one byte golfed for PHP with bitwise `and`, one byte golfed for C and PHP): `<?=strlen($s=$argv[1])==2*strspn($s,a)&$s[strrpos($s,a)+1]>a;` (61 bytes) --- My second own approach, a little longer: build a string with (input length / 2) of `a`, one of `b` and compare the concatenation to input: `<?=str_repeat(a,$n=strlen($s=$argv[1])/2).str_repeat(b,$n)==$s;` (63 bytes) Could save 3 bytes on that if I could use `($r=str_repeat)` for a function call directly ... if. --- all versions: * take the string as argument from cli * print `1` for true, nothing for false --- **testing** * replace `<?=` with `<?function f($s){return` * remove `=$argv[1]` (or replace `$argv[1]` with `$s`) * append `}` and my test suite (below) * call in a web browser ``` function out($a){if(is_object($a)){foreach($a as$v)$r[]=$v;return'{'.implode(',',$r).'}';}if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';} function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',$e==$y?'Y':'N',"</td></tr>";$h='';} $cases=[ 1=>[ab,aabb,aaabbb,aaaabbbb,aaaaabbbbb,aaaaaabbbbbb], 0=>['',a,b,aa,ba,bb,aaa,aab,aba,abb,baa,bab,bba,bbb,aaaa,aaab,aaba, abaa,abab,abba,abbb,baaa,baab,baba,babb,bbaa,bbab,bbba,bbbb] ]; foreach($cases as$e=>$a)foreach($a as$x)test($x,$e,f($x)|0); ``` [Answer] # Pyth, 7 bytes ``` .AanV_S ``` [Try it online](https://pyth.herokuapp.com/?code=.AanV_S&test_suite=1&test_suite_input=%22ab%22%0A%22aabb%22%0A%22aaabbb%22%0A%22aaaabbbb%22%0A%22aaaaabbbbb%22%0A%22aaaaaabbbbbb%22%0A%22%22%0A%22a%22%0A%22b%22%0A%22aa%22%0A%22ba%22%0A%22bb%22%0A%22aaa%22%0A%22aab%22%0A%22aba%22%0A%22abb%22%0A%22baa%22%0A%22bab%22%0A%22bba%22%0A%22bbb%22%0A%22aaaa%22%0A%22aaab%22%0A%22aaba%22%0A%22abaa%22%0A%22abab%22%0A%22abba%22%0A%22abbb%22%0A%22baaa%22%0A%22baab%22%0A%22baba%22%0A%22babb%22%0A%22bbaa%22%0A%22bbab%22%0A%22bbba%22%0A%22bbbb%22) ### How it works ``` SQ sorted input _ reverse nV Q vectorized not-equal with input a Q append input .A test whether all elements are truthy ``` [Answer] ## C, 65 bytes ``` m,t;C(char*c){for(m=1,t=0;*c;)m>0&*c++-97&&(m-=2),t+=m;return!t;} ``` [Answer] ## Brainfuck, 77 bytes ``` , [ [ >+[>+<-]<< ,[>->+<<-] >[<<] > ] >+[<<] > [ >-[>+<-]<< , [ [>->+<<-] >[<<] < ] >> ] +>[<] ] <. ``` Expects input without a trailing newline. Outputs `\x00` for false and `\x01` for true. [Try it online.](http://brainfuck.tryitonline.net/#code=LFtbPitbPis8LV08PCxbPi0-Kzw8LV0-Wzw8XT5dPitbPDxdPls-LVs-KzwtXTw8LFtbPi0-Kzw8LV0-Wzw8XTxdPj5dKz5bPF1dPC4&input=YWFhYWFhYmJiYmJi) The idea is to increment `n` for initial `a` characters and decrement `n` for subsequent `b` characters and then check whether `n` is zero at the end, short-circuiting to print false if the input does not match `/^a+b+$/`. Since the input is guaranteed to match `/^[ab]*$/`, we can ignore the fact that `ord('a') = 97` and just use `ord('b') = ord('a') + 1` to check for `/^a+b/`. [Answer] # [Cubically](https://github.com/aaronryank/cubically), ~~109~~ ~~98~~ ~~70~~ 60 bytes ``` +52/1+55~=7!6&(:7UR'UF'D2~=7)6>7?6&(:7D2FU'RU'~=7)6>7!6&!8%6 ``` -11 bytes thanks to TehPers -10 bytes thanks to new language feature [Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f29RI31Db1LTO1lzRTE3DyjzI0MnQx9DNECigaWZnbg8WdDP2MXYyDjKGCgJVKlqomv3/nwgCSSAAAA "Cubically – Try It Online") Prints `1` if the string matches L, otherwise prints nothing. Explanation: ``` +52/1+55 Sets the notepad to 97 ('a') ~ takes input =7!6& exits if input is not 'a' ( )6 While the notepad is truthy :7 Save the current character value UR'UF'D2 Perform a cube operation ~=7 Set notepad to true if next character is the same >7?6& Exit if next character is end of input (-1) ( )6 While the notepad is truthy :7 Save the current character D2FU'RU' Reverse one iteration of the previous operation ~=7 Set notepad to true if next character is the same >7!6& Exit if next character is NOT end of input !8%6 Print 1 if the cube is solved ``` The looping operation has been replaced with a new sequence with a period of 1260, which will still never give a false negative but now is guaranteed to work for inputs of less than 1260 characters. I've replaced the previous check for solved cube with `!8%6`. `8` is a recently added pseudo-face which is always equal to "Is the cube solved?" so I can just branch on that directly. [Answer] # [Ruby](https://www.ruby-lang.org/), 17 bytes (16 + '-n' flag) ``` p~/^(a\g<1>?b)$/ ``` [Try it online!](https://tio.run/##KypNqvz/v6BOP04jMSbdxtDOPklTRf///8TEJC4wSuICkkAaxAGCJCD4l19QkpmfV/xfNw8A "Ruby – Try It Online") The recursive regex solution ported to ruby. [Answer] > > Nearly 5 months later, decided to come back to my first answer here to see if I could golf it more. Here's the results! > > > # [Zsh](https://www.zsh.org/), 28 bytes ``` eval ${${${1:?}//a/( }//b/)} ``` Just as I posted my 29 byte answer, I thought "what about if we handle the empty case specially?" Turns out, it's one byte shorter! [Try it online!](https://tio.run/##XY3BCoMwEETv@YqBClqohF5bwW9JzIqBYEoSW2vx29No1UNnWZZ5u8NOvouvThuCI6FgdE93KMvoKQw8BZQlsoWyYnVjXDfZZ6nrrZ45F7xAGpKf53hmVVVlNXCCHcJjCKBRBzRWEVrr0pOWHPUNXTCRs9AewQ2hezNle4oiSSaleMLEhMRPm5fi8K0wfjnYTg6wR3aQ5/@R9GHpA3wB "Zsh – Try It Online") Successful cases: `( ( ( ... ( ( ))...)))`. Unsuccessful cases: * Unmatched/uneven parens: obviously fails * `/ba/` case: `( )( )` is a "parse error" in the eval, but gives `unknown file attribute:` if run directly. * Empty case: `${1:?}` handles exactly this. --- # [Zsh](https://www.zsh.org/), 29 bytes ``` eval \(${${1//a/(+}//b/+i)}\) ``` [Try it online!](https://tio.run/##XY1BCoMwFET3OcVABRUroesKvYibaL4YCKbE2FrFs6fRqosO/MW8P8NMfevfrdIES0JCq47ukIbRS2j05JDniFbKks2NfvuUSTRH841zwZNs4bzimUqXMvUpK4oiegAXmME9BwcalUNtJKExNqw0ZKmr6YqJrIHq4ezg2g@TpiMvgqqgUA@YmKjw0@4rcfpG6H4N7JETHJUDxPF/JSysd4Iv "Zsh – Try It Online") Same "eval matching delimiters" principle, but this time using math mode instead of parameter expansions: ``` eval \(${${1//a/(+}//b/+i)}\) \( \) # literal ( ) ${1//a/(+} # replace 'a' with '(+' ${ //b/+i)} # replace 'b' with '+i)' ``` A successful result looks like: `((+(+(...+(++i)+...i)+i)+i))`, incrementing `i` to `1` and adding it repeatedly. This will result in a positive integer, which `(( ))` evaluates truthy. An unsuccessful result looks like one of the following: * Uneven/unmatched parens (obviously fails) * `/^b(a{n}b{n})?a$/` case: `(+i)(...)(+)` fails with "missing identifier after `+`" * Any other `/ba/` case: `(...)(...)` errors in math mode * Empty case: `()` is an anonymous function with no body, and errors --- > > *Original answer:* > > > # [Zsh](https://www.zsh.org/), 35 bytes ``` eval '${'${${1//a/'${'}//b/'}'}'#}' ``` [Try it online!](https://tio.run/##qyrO@P8/tSwxR0FdpRqIVKoN9fUT9UGcWn39JH31WiBUrlX///9/YlJiEgA "Zsh – Try It Online") ([More examples](https://tio.run/##XVDLboMwELzzFauARCMlQr22UZsee8wnmDAJqMamfiSFiG@nuyFJpa6x8c6Md8cefD2l9GlorzyotzF3oLM1FVxjjqRKGwOFuvFUQzH4kqT0NCyJyHe6CZ45kG4MSM37wde01w3XiLoS8U7EFb6jDfiTC7MV5gvoPCnnVE8H61omFtllXBCMj@wFbRd68kHsiA7UOXi4E6T6hw5wRgXofkUOrT3h2mI2u@KK3JX/ylTUmI7vIrvoZ9Xetq3ks393jC0MX4ltzOIkOdeNBhdWs@iVKpt4BFqvxeXTdrfkdVgKN46LCSelKc8u/GWX56JQhSRjUZRFPvJIx3zabDbZO1FK/LJiCD9NYCcVrn0dDnAwe6xogLPEDx9cDHWfVNZgUhwlB70JjESVNMctL9UjPyjtRXCTPID7kTuQ5/@PcAeZD@AX "Zsh – Try It Online")) Inspired by [xnor's post](https://codegolf.stackexchange.com/a/86032/86147), this outputs via exit code. Zsh will happlily handle nested `${}`s, but will err on `${${...}${...}}` or unmatched braces. There are two caveats which makes this longer: * We need the outer `${...}`, since `${}${}` is valid zsh. * We need a `#` at then end, which causes an error when the input is the empty string: + `${${}#}` is prefix removal, which is fine. + `${#}` evaluates to the number of parameters, which will be an integer and not a valid command. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 24 bytes ``` f('a':s++"b")=s==""||f s ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NQz1R3apYW1spSUnTttjWVkmppiZNofh/bmJmnoKtQpqCUiIYJIGB0n8A "Curry (PAKCS) – Try It Online") Returns `True` for truth, and nothing otherwise. [Answer] # Python 2, ~~43~~ 40 Bytes ``` lambda s:''<s==len(s)/2*"a"+len(s)/2*"b" ``` [Try it online!](https://tio.run/##bY7LbsQgDEX3/gqLTUKrmSazpKHLfkF3aRZGSVQkhkTAqJqvTzH0samE7OvHPXi/p4/NXw573beQMN7jM6za0dXMhFFFrRsyzRYwDnE89Wp66Ya1jWOvTv0kweoO1jx1aD2bzzHN1itAu6JVuAfrUy50Xzpu8a2TSH5Gl2FThr/7RqHTbuwYCD@M7ZbOn8GmpRVv4bYoRMGA9vi9rGmGfBwTo3y6PAgSj3@FEQdK/mpxcUHxSjkpFPIfvpMHGSAyHHIsiXMVRX3Lqg0AAXfA5FdGbAfKJVNMmeRcxtVa0LzFK1QCG6qjWNjDJl4xBVM4FVRJ5gs "Python 2 – Try It Online") - considered the obvious solution thanks to *Leaky Nun* other idea, 45 bytes: ``` lambda s:s and list(s)==sorted(len(s)/2*"ab") ``` [Try it online!](https://tio.run/##bY6xbsQgDIZ3nsJiCVS6a3IjPTr2CbqlGYxCVCSORDGn6p4@xdCqSyVk/8b@P3t75M81XY5w29Y9Az3oRSw24s3NCGTI2g5dt@5AVxpPg5le@@uiaBzMaZi0CLYXS@lGCInNZ8pzSEZAWCAY2PaQcinsUH@iTypqwDRDLLCpwD9SZyDaOPYMFL@M9Z7PX3vIXsn3/e4NgGSAOv4ua5hAWZG2lsr1fla8gfTz5Umik/oAzft8JA/yDUsyIPU/S6I@0AlEx6HEmjg3UdWPbNoJgYJ/hCuvttgusJRMcbVTcm03a0XzFI9gDWxojmphD5t4xFVM5TRQI7lv "Python 2 – Try It Online") *-4 bytes by using len/2 (i get an error when the half comes last)* *now gives false for the empty string* *-3 bytes thanks to xnor* [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Ṡ=s`abdcạ& ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboW6x7uXGBbnJCYlJL8cNdCtSXFScnFUKkFaxLBIAkMIGIA) #### Explanation ``` Ṡ=s`abdcạ& # Implicit input Ṡ= # Is the input sorted? s # Swap so the input is back on top `ab # Push the string "ab" dc # Count the occurrences of "a" and "b" ạ # Are they equal to each other? & # Logical AND # Implicit output ``` [Answer] ## Pyke, 10 bytes ``` le"ab"*Sq& ``` [Try it here!](http://pyke.catbus.co.uk/?code=le%22ab%22%2aSq%26&input=ab) Or 9 bytes if null input isn't valid ``` le"ab"*Sq ``` [Answer] # Ruby, 33 bytes [Try it online](https://repl.it/CeXK) ``` ->s{s==?a*(l=s.size/2)+?b*l&&l>0} ``` [Answer] ## Actually, 14 bytes ``` "[]""ab"(t≡#ÆY ``` This uses the same strategy as [xnor's solution](https://codegolf.stackexchange.com/a/86032/4372) for the first part: transform the input into a nested iterable. [Try it online!](http://actually.tryitonline.net/#code=IltdIiJhYiIodOKJoSPDhlk&input=ImFhYmIi) Explanation: ``` "[]""ab"(t≡#ÆY "[]""ab"(t translate "a" -> "[", "b" -> "]" ≡ eval (since this is evaluating a literal, it still works in the online interpreter) - leaves a list if the string is valid, else a string # listify (does nothing to a list, makes a list of characters for a string) Æ filter strings (take all string elements in the list - so an empty list if there are none) Y boolean negate (an empty list is falsey and a non-empty list is truthy, so negation gets the correct value) ``` [Answer] # Ruby, 31 bytes Aw, that poor syntax highlighter :) ``` ->s{s=~/^a+/&&$&.tr(?a,?b)==$'} ``` Does `s` begin with one or more `a`? Is also that bunch of `a`s (`$&`) the same as the rest of the string (`$'`) if we replace all those `a`s with `b`s? [test here](https://repl.it/Ce9w) [Answer] # C#, 78 67 bytes ``` bool f(string s)=>Regex.IsMatch(s,"^(?'o'a)+(?'-o'b)+(?(o)(?!))$"); ``` This implementation uses .NET Regex's ["Balancing Group Definitions"](https://msdn.microsoft.com/en-us/library/bs2twtah(v=vs.110).aspx#balancing_group_definition) to match the same number of 'a' and 'b' characters while ensuring that the input isn't an empty string by using the `+` quantifier. [Answer] # Python, 101 bytes ``` def q(s): a=len(s)/2 for x in range(a): if s[x]!='a' or s[a+x]!='b' or a*2!=len(s):a=0 return a ``` Not the most efficient, had some trouble with 0 being even. Could probably get it lower with python tricks. Returns 0 if false, a positive integer if true. (which will be half len(s)) [Answer] # k (21 bytes) Can probably be shorter ``` {|/0,(=).(#:'=x)"ab"} ``` Example ``` k){|/0,(=).(#:'=x)"ab"}"" 0b k){|/0,(=).(#:'=x)"ab"}"ab" 1b k){|/0,(=).(#:'=x)"ab"}"aab" 0b ``` [Answer] # PHP bounty version, 31 bytes for PHP 4.1, call `php-cgi -f <scriptname> s=<argument>` (or in browser with `?s=<argument>`) for current PHP, use `$_GET[s]` instead of `$s` --- **31 bytes** ``` <?eval(strtr("do$s;",ab,'{}')); ``` `unexpected ';'` for valid, `unexpected end of file` or `unexpected '}'` for invalid ``` <?eval(strtr("1|$s;",ab,'[]')); ``` ok for valid, `unexpected ';'` or `unexpected ']'` for invalid # 26 bytes if empty input was undefined or valid: ``` <?eval(strtr($s,ab,'{}')); ``` **29 bytes**, if empty input was undefined or valid: ``` <?eval(strtr("$s;",ab,'[]')); ``` Abusing other control structures: **32 bytes** ``` <?eval(strtr("$c=$s;",ab,'[]')); ``` ok for valid, Parse error for invalid: `unexpected ';'`, `unexpected ']'` or `Cannot use [] for reading` (for `abab`) **33 bytes** ``` <?eval(strtr("1 or$s;",ab,'[]')); ``` same as `1|` ``` <?eval(strtr("if(0)$s",ab,'{}')); ``` ok for valid, `unexpected end of file` or `unexpected '}'` for invalid input **35 bytes**: ``` <?eval(strtr("for(;;)$s",ab,'{}')); ``` infinite loop for valid (use `for(;0;)` to make finite), same as `if` for invalid **36 bytes** ``` <?eval(strtr("while(0)$s",ab,'{}')); ``` same as `if` **39 bytes** ``` <?eval(strtr("function()$s;",ab,'{}')); ``` `unexpected ';'` for empty, same as `if` for other input ]
[Question] [ A binary recurrence sequence is a recursively-defined sequence of the following form: $$F(1) = a\_1 \\ \vdots \\ F(y) = a\_y \\ F(n) = \alpha F(n-x) + \beta F(n-y), n > y$$ This is a generalization of the Fibonacci (\$x = 1, y = 2, a = [1, 1], \alpha = 1, \beta = 1\$) sequence and the Lucas (\$x = 1, y = 2, a = [2, 1], \alpha = 1, \beta = 1\$) sequence. ## The Challenge Given \$n, x, y, a, \alpha\$, and \$\beta\$, in any reasonable format, output the \$n\$th term of the corresponding binary recurrence sequence. ## Rules * You may choose for the sequence to be either 1-indexed or 0-indexed, but your choice must be consistent across all inputs, and you must make note of your choice in your answer. * You may assume that no invalid inputs would be given (such as a sequence that terminates prior to \$n\$, or a sequence that references undefined terms, like \$F(-1)\$ or \$F(k)\$ where \$k > n\$). As a result of this, \$x\$ and \$y\$ will always be positive. * The inputs and outputs will always be integers, within the boundaries of your language's natural integer type. If your language has unbounded integers, the inputs and outputs will be within the range \$[-2^{31}, 2^{31}-1]\$ (i.e. the range for a 32-bit signed two's complement integer). * \$a\$ will always contain exactly \$y\$ values (as per the definition). ## Test Cases Note: all test cases are 0-indexed. ``` x = 1, y = 2, a = [1, 1], alpha = 1, beta = 1, n = 6 => 13 x = 1, y = 2, a = [2, 1], alpha = 1, beta = 1, n = 8 => 47 x = 3, y = 5, a = [2, 3, 5, 7, 11], alpha = 2, beta = 3, n = 8 => 53 x = 1, y = 3, a = [-5, 2, 3], alpha = 1, beta = 2, n = 10 => -67 x = 5, y = 7, a = [-5, 2, 3, -7, -8, 1, -9], alpha = -10, beta = -7, n = 10 => 39 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁴Cịæ.⁵ṭµ¡⁶ị ``` **Try it online!** [1](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzEsIDFd+WzEsIDJd+WzEsIDFd+Nw) | [2](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzIsIDFd+WzEsIDJd+WzEsIDFd+OQ) | [3](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzIsIDMsIDUsIDcsIDExXQ+WzMsIDVd+WzIsIDNd+OQ) | [4](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=Wy01LCAyLCAzXQ+WzEsIDNd+WzEsIDJd+MTE) | [5](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=Wy01LCAyLCAzLCAtNywgLTgsIDEsIC05XQ+WzUsIDdd+Wy0xMCwgLTdd+MTE) ### How it works ``` ⁴Cịæ.⁵ṭµ¡⁶ị Main link. Arguments: a; [x, y]; [α, β]; n (1-based) µ Combine the links to the left into a chain. ¡ Execute that chain n times, updating a after each execution. ⁴ Yield [x, y]. C Complement; yield [1 - x, 1 - y]. ị Retrieve the elements of a at those indices. Indexing is 1-based and modular in Jelly, so this retrieves [a[-x], a[-y]] (Python syntax). ⁵ Yield [α, β]. æ. Take the dot product of [a[-x], a[-y]] and [α, β]. ⁶ Yield n. ị Retrieve the element of a at index n. ``` [Answer] ## Python 2, 62 bytes ``` x,y,l,a,b=input();f=lambda n:l[n]if n<y else a*f(n-x)+b*f(n-y) ``` A direct recursive solution. All inputs are taken from STDIN except for `n` as a function argument, a split that's is [allowed by default](http://meta.codegolf.stackexchange.com/a/5415/20260) (though contentiously). There doesn't seem to be a way to save bytes with `and/or` in place of `if/else` because `l[n]` could be falsey as 0. [Answer] ## JavaScript (ES6), ~~51~~ 44 bytes ``` (x,y,z,a,b)=>g=n=>n<y?z[n]:a*g(n-x)+b*g(n-y) ``` Note that the function is partially curried, e.g. `f(1,2,[1,1],1,1)(8)` returns 34. It would cost 2 bytes to make the intermediate functions independent of each other (currently only the last generated function works correctly). Edit: Saved 7 bytes thanks to @Mego pointing out that I'd overlooked that the the passed-in array always contains the first `y` elements of the result. [Answer] ## Haskell, ~~54~~ 48 bytes ``` l@(x,y,a,p,q)%n|n<y=a!!n|k<-(n-)=p*l%k x+q*l%k y ``` [Answer] # Python 2, 59 bytes ``` x,y,A,a,b,n=input() exec'A+=a*A[-x]+b*A[-y],;'*n print A[n] ``` Test it on [Ideone](http://ideone.com/4Qun1t). [Answer] # J, 43 bytes ``` {:{](],(2>@{[)+/ .*]{~1-@>@{[)^:(3>@{[)>@{. ``` Given an initial sequence of terms *A*, computes the next term *n* times using the parameters of *x*, *y*, *α*, and *β*. Afterwards, it selects the *nth* term in the extended sequence and outputs it as the result. ## Usage Since J only supports 1 or 2 arguments, I group up all the parameters as a list of boxed lists. The initial seed values *A* are first, followed by the parameters of *x* and *y* as a list, followed by the parameters of *α* and *β* as a list, and ending with the value *n*. ``` f =: {:{](],(2>@{[)+/ .*]{~1-@>@{[)^:(3>@{[)>@{. 2 3 5 7 11;3 5;2 3;8 ┌──────────┬───┬───┬─┐ │2 3 5 7 11│3 5│2 3│8│ └──────────┴───┴───┴─┘ f 2 3 5 7 11;3 5;2 3;8 53 f _5 2 3 _7 _8 1 _9;5 7;_10 _7;10 39 ``` ]